summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md237
-rw-r--r--build.zig117
-rw-r--r--examples/micscope/README.md11
-rw-r--r--examples/micscope/src/main.zig252
-rw-r--r--examples/micscope/test/record.script10
-rw-r--r--examples/micscope/test/transport.script22
-rw-r--r--examples/spheres/README.md10
-rw-r--r--examples/spheres/src/main.zig31
-rw-r--r--examples/spheres/test/play.script2
-rw-r--r--src/abi.zig53
-rw-r--r--src/gpu/Executor.zig26
-rw-r--r--src/host/Console.zig9
-rw-r--r--src/host/Host.zig313
-rw-r--r--src/host/Sessions.zig631
-rw-r--r--src/host/audio.zig89
-rw-r--r--src/host/memory.zig558
-rw-r--r--src/host/probe.zig86
-rw-r--r--src/host/root.zig67
-rw-r--r--src/host/timeline.zig22
-rw-r--r--src/layout.zig36
-rw-r--r--src/sketch/request.zig2
-rw-r--r--src/sketch/root.zig40
-rw-r--r--src/sketch/web.zig18
-rw-r--r--test/killed.script4
-rw-r--r--web/host.js22
25 files changed, 1531 insertions, 1137 deletions
diff --git a/README.md b/README.md
index bf2aacb..58dae6c 100644
--- a/README.md
+++ b/README.md
@@ -45,24 +45,23 @@ An app is an ordinary module. Every declaration is optional:
| Declaration | Meaning |
| --- | --- |
| `name`, `width`, `height` | Window title and initial canvas |
-| `State` | Saved to a file, kept in every session's keyframes and marks, replayed: what `update` changes. No pointers and no host handles (compile errors). |
+| `State` | The one thing a sketch keeps: what `update` changes, saved in one file with its history, replayed. No pointers, no host handles, and at most 32 MiB, half of a save (compile errors). |
| `Session` | This process: survives reloads, never saved. Caches, image and buffer handles, playback cursors. |
-| `Store` | On disk, at the same address in every run: survives reloads and restarts. Big data that is not replayed (a recording, a document). May point into itself; no host handles. |
| `init(state, host)` | Seed brand-new state, after the declared defaults |
| `setup(session, init) !void` | Initialize resources once per fresh Session, including startup with restored State |
| `update(state, input)` | **Deterministic**: the host replays recorded input through it |
-| `draw(state, session, store, frame)` | Pictures and sound, as commands; may change Session and Store |
-| `command(state, session, store, console, line) !bool` | Console lines the host does not know |
+| `draw(state, session, frame)` | Pictures and sound, as commands; may change Session |
+| `command(state, session, console, line) !bool` | Console lines the host does not know |
| `commands` | Console completions |
Functions take the parameters they name, matched by type and in any order:
-`draw(s: *const State, f: *sk.Frame)` and `draw(s: *const State, store:
-*Store, ss: *Session, f: *sk.Frame)` both work. `update` can only ask for
+`draw(s: *const State, f: *sk.Frame)` and `draw(f: *sk.Frame, ss: *Session,
+s: *const State)` both work. `update` can only ask for
`State` and `Input`; asking for more is a compile error, since a replay could
not reproduce it.
-`setup` receives `*sk.Init` with `host`, `session`, and `store` allocators;
-it may also request Session, Store, or Host directly. It gets no State, Input,
+`setup` receives `*sk.Init` with `host` and the `session` allocator; it may
+also request Session or Host directly. It gets no State, Input,
or Frame. Load assets and create/upload GPU buffers there, then use those
resources in `draw`. `try init.host.writeBuffer(buffer, offset, bytes)` submits
a copy immediately; the source bytes may be released when it returns. WebGPU
@@ -83,14 +82,11 @@ Memory comes by lifetime, one allocator each:
| --- | --- | --- |
| `f.scratch` | this frame | all at once, after the frame is drawn |
| `f.session` | this process | one allocation at a time; the rest when Session's layout changes, along with the images and buffers the session made |
-| `f.store` | on disk, `<state>.store` | one allocation at a time; `--fresh` empties it |
-A Store layout change migrates field by field like State: unchanged fields,
-pointers included, keep their values, since the store never moves.
-`command` gets the session and store allocators on its `Console`.
+`command` gets the session allocator on its `Console`.
-`update` sees only State, so when a key should do something to Session or
-Store, State carries a request: `seek: sk.Request(f32)`, sent with
+`update` sees only State, so when a key should do something to Session,
+State carries a request: `seek: sk.Request(f32)`, sent with
`s.seek.send(0.5)`. Session keeps an `sk.Handled`, and `draw` runs
`if (ss.seek.take(s.seek)) |to| ...` once per request. A fresh Session
counts earlier requests as handled, so nothing re-fires after a restart.
@@ -126,13 +122,13 @@ Session (a trail in an offscreen image) is stale then; repaint it from
State.
`draw` gets a `Frame`: `clear`, `fill`, `shape`, `shapeColors`, `image`,
-`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `gain`, `audio`, `microphone`, `pixels`, `gpu`,
+`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `gain`, `audio`, `audioBuffer`, `microphone`, `pixels`, `gpu`,
`compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and
`f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`,
-`decodeSound`, `newSound`, `samples`, `readFile`, `env`, `log`, `textSize`). Commands may be built
+`decodeSound`, `newSound`, `samples`, `readFile`, `appendFile`, `writeFile`, `env`, `log`, `textSize`). Commands may be built
from locals: the methods copy what they keep (text, GPU descriptions,
uniforms) into scratch. Bulk data (vertices, samples, pixels, uploads) is
-not copied and must outlive the frame: scratch, session or store memory.
+not copied and must outlive the frame: scratch or session memory.
`f.text(x, y, scale, bytes, color)` draws one line from its top left
corner; scale 1 is a 13 px monospace face (8 px a character on a 16 px
@@ -169,13 +165,24 @@ move. The web host ignores `raster`.
dialog; the answer comes back as the console line `open <path>`, so it
reaches the sketch's `command` like anything typed there. `f.run(line)`
does the same with any line, after the frame: `draw` cannot write State,
-so this is how it tells State something only it learns (how many takes a
-Store holds, say).
+so this is how it tells State something only it learns (which of its
+files are already written, say).
+
+`f.host.appendFile(name, bytes)` appends to a file of the sketch's own,
+`<stem>.<name>` beside its save `<stem>.xitdb` (in `.sketchbook/` under
+`zig build run`), creating it, and returns its path for `readFile` ("" when nothing
+was written, and always on the web). Only `draw` and `command` can call it,
+and a write is not replayed, like sound. `readFile` maps a file once, so
+what is appended afterwards is not in what it returned.
+`f.host.writeFile(name, bytes)` does the same to a new, empty file of that
+name. micscope starts each take's `take-<id>.f32` so, and appends to it as
+it records.
`f.download(buffer, .{ .size = n, .key = k })` reads a GPU buffer back
without stalling: the bytes arrive in a later frame's `in.downloads`, a
frame or two behind. For measurements a shader made (a pitch, a level),
-not for pixels.
+not for pixels; sound a shader made goes to the speakers with
+`f.audioBuffer` (see sound, below), which does not wait a frame.
Geometry and colors are duck-typed. Anything with `x`/`y` is a point, anything
that also has `w`/`h` (or `width`/`height`) is a rect, in any number type, and
@@ -368,9 +375,8 @@ after a reload that shrinks it. The default buffer is the element's own
defaults, never `std.mem.zeroes` (an enum may have no 0).
**Data that grows.** State is kept in keyframes, replayed and migrated, so
-it holds what `update` changes, at a size fixed in its type. Store is not
-kept in keyframes or replayed, so what is in it does not follow a seek. Three
-cases, by who needs the data:
+it holds what `update` changes, at a size fixed in its type, 32 MiB at most.
+Three cases, by who needs the data:
- `update` needs it: a `List` in State, sized for the worst case (the
quadtree's 4096 points, 32 KiB; flocking's 2048 boids).
@@ -384,7 +390,8 @@ cases, by who needs the data:
may derive it differently. A cheap derivation needs no cache at all:
the quadtree builds its tree in `f.scratch` every frame.
- It is the user's work, not a function of State (a recording, a
- document): Store.
+ document): a `List` in State, or, bigger than a save, files of the
+ sketch's own (`appendFile`), named from State, as micscope's takes are.
The timeline then needs nothing more: a seek changes the key like an
update does (`examples/noc`: `koch`, `lsystem`, `quadtree`).
@@ -450,8 +457,31 @@ topping its queue up to 2048 samples (about 43 ms) ahead of the device,
so what `draw` declares is heard up to that much later.
`f.audio(key, samples, .{})` streams PCM, and `input.stream(key)` reports
-what the host has queued and played: the sketch chooses how far ahead it
-keeps a stream. `f.microphone()` keeps the default recording device open
+what the host has queued and played, and its `underruns` (pushes that found
+it empty though the frame before had pushed to it: each a gap). The sketch
+chooses how far ahead it keeps a stream; `input.lead` is how far the host
+would: the slowest of the last 64 frames' worth of samples (a stream is fed
+once a frame), plus the device's pull (what it takes from a stream at once,
+1024 samples by SDL's default), plus half a pull for each recent underrun.
+A sketch that makes its sound as it goes pushes `in.lead -|
+in.stream(key).queued` a frame, and a change it makes is heard after what
+is queued ahead of it, about a pull: 19 to 27 ms after `draw` on this
+machine at 60 Hz. `SDL_AUDIO_DEVICE_SAMPLE_FRAMES=256` in the environment
+asks SDL for 5 ms pulls instead, and a change leaves in about 6.5 ms (on
+PipeWire every client then runs at that size). `f.audioBuffer(key, buffer, .{ .count
+= n })` streams `n` samples a compute shader wrote (f32 from `.offset`
+bytes): the host reads them back within the frame, waiting for the GPU's
+work so far (about 0.2 ms), and queues them. A GPU synth is then:
+
+```zig
+const n: u32 = @min(f.in.lead -| f.in.stream(1).queued, max_block);
+if (n > 0) {
+ f.compute(.{ .kernel = synth, .readwrite = &.{ss.block}, .uniforms = ..., .groups = .{ (n + 63) / 64, 1, 1 } });
+ f.audioBuffer(1, ss.block, .{ .count = n });
+}
+```
+
+(`examples/spheres` is one.) `f.microphone()` keeps the default recording device open
while declared, and the next frame's `input.microphone` holds what it heard
(to `draw` only: it is a device, not an event, so it does not replay).
`host.samples(audio)` gives a loaded sound's samples, mono at
@@ -810,37 +840,40 @@ a talk with a slider, a loop, a choice, two slides and `beside`.
and shaders), and a save that touches several files may build more than
once. The cache grows with each start of the watch (65 MB for a game),
not with edits.
-- **State file.** `<name>.state` holds the live State, shared via
- `MAP_SHARED`, so the file is up to date as it changes. Its header carries
- the reflected layout, so a layout change migrates it field by field, with
- enums matched by tag name, and `sketchbook-probe` can print any sketch's
- state. Arrays and vectors migrate element by element: the elements both
- layouts have, each field by field, so an element type can gain a field
- and a capacity can grow (new elements take their defaults) or shrink (the
- rest is dropped; a count field such as `sk.List`'s `len` is kept, and
- `List` clamps it where it is read). An array whose type is unchanged is
- copied whole. Files from before element leaves (`SKETCH01`) are read and
- rewritten, and the snapshot slots of files from before sessions become
- marks `1` to `7` in a run that records; a file that is not a state file
- is refused, never truncated.
-- **Store file.** `<name>.state.store` is a heap mapped at a fixed address
- (`0x2000_0000_0000`, 64 GiB reserved), grown in place, locked to one
- process. Power-of-two size classes with free lists in the file.
- Keyframes, marks and replays do not cover it (only `draw` and `command`
- change it).
-- **Where files go.** `zig build run`, `probe` and `export` keep a sketch's
- files in `.sketchbook/`: `<name>.state`, `<name>.state.store` and
- `<name>.xitdb`. The host makes the directory with a `.gitignore` of `*`,
- so neither git nor jj takes in a database that grows (the jj snapshot a
- build makes would commit one while it is under a megabyte), and moves in,
- once, the state and store an older build kept in the project's root;
- when both exist, nothing moves and the host says which is used. Without
- `--state`, a run keeps them in `$XDG_DATA_HOME/<name>/`
- (`~/.local/share/<name>/` without it), which is where a shipped game's
- go; a script or an export uses `sketch.state` in the working directory.
-- **Sessions.** Every run of a build that records is a session in
- `<name>.xitdb`, one xitdb database per sketch beside its state file: an
- append-only log of the events live `update` was fed, in whole frames, and
+- **The save.** A sketch keeps one thing, State, in one file, its save:
+ `<name>.xitdb`, an xitdb database. Live State is process memory; the save
+ holds the present, its newest keyframe and the frames logged after it,
+ which a run restores and replays through `update` (played by another
+ build, the keyframe alone, and the run says how many frames it left),
+ so a run starts where the last stopped; and the history before it
+ (Sessions, below). `--fresh` starts from defaults and leaves the save as
+ it is. A keyframe is State in 4 KiB pages and writes only the pages that
+ changed since the keyframe before it, an all-zero page nothing: about 5
+ KB a keyframe for drat-meout's 20 KiB State, 10 KB for a 4 MiB State
+ edited once a minute. Each stretch carries the reflected layout, so a
+ keyframe from an older layout migrates field by field, with enums
+ matched by tag name, and so does live State at a reload. Arrays and
+ vectors migrate element by element: the elements both layouts have, each
+ field by field, so an element type can gain a field and a capacity can
+ grow (new elements take their defaults) or shrink (the rest is dropped; a
+ count field such as `sk.List`'s `len` is kept, and `List` clamps it where
+ it is read). An array whose type is unchanged is copied whole. A state
+ file from before (`<name>.state` beside the save, any of its formats) is
+ imported into a new save once: its State the present, its snapshot slots
+ marks `1` to `7`; the file is left as it was and not read again, and one
+ that is not a state file is said and left.
+- **Where files go.** `zig build run` and `export` keep a sketch's files in
+ `.sketchbook/`: `<name>.xitdb` and the `<name>.<file>` it appends to. The
+ host makes the directory with a `.gitignore` of `*`, so neither git nor
+ jj takes in a save that grows (the jj snapshot a build makes would commit
+ one while it is under a megabyte), and moves in, once, the `<name>.state`
+ an older build kept in the project's root; when both exist, nothing moves
+ and the host says which is used. Without `--state`, a run keeps them in
+ `$XDG_DATA_HOME/<name>/` (`~/.local/share/<name>/` without it), which is
+ where a shipped game's go; a script or an export uses `sketch.xitdb` in
+ the working directory. `--state x.xitdb` and `--state x.state` both name
+ the save `x.xitdb`.
+- **Sessions.** Every run is a session in the save: an append-only log of the events live `update` was fed, in whole frames, and
keyframes, the State at the start, every minute while it changes, at
every jump (`load`, `set`, `reset`, a seek, a sketch command), before and
after a reload, at every mark and at exit. Each stretch of a session
@@ -848,34 +881,53 @@ a talk with a slider, a loop, a choice, two slides and `beside`.
was built from: the repository's revision (`jj:<commit> <change>`, else
`git:<sha>`, `+dirty` with uncommitted changes, read once per `zig
build`), Zig's version, the backend and the mode. Nothing in it is ever
- overwritten; marks and clips are names pointing into it.
+ overwritten, only dropped, oldest first, at the cap (below); marks and
+ clips are names pointing into it.
- `App.Options.record` decides who records, at build time: null, the
- default, means Debug builds. A playtest build of a release opts in with
- one line, `.record = b.option(bool, "record", "collect sessions in a
- release build")`. A script from `--fresh` state records in memory (time
- travel works, nothing touches the disk; it stops at 256 MiB, ten hours or
- more of play, keeping what it has), a script without `--fresh` to the
- file, an export nothing. A build that does not record has no marks or
- clips, and the console says so. The console's status line ends with
- `rec file`, `rec memory` or `rec off`, and `sessions` says where.
+ `App.Options.record` decides how much of it the save keeps, at build
+ time: null, the default, means Debug builds keep all of it, up to the
+ cap below. A build that does not record keeps the present and the marks
+ (and clips) only: at every keyframe it drops the frames and keyframes
+ before it, and at exit it compacts the file, so while it runs the disk
+ holds at most the last minute of input, and after, none. A playtest
+ build of a release opts in with one line, `.record = b.option(bool,
+ "record", "collect sessions in a release build")`. A script from
+ `--fresh` state records in memory (time travel works, nothing touches
+ the disk; it stops at 256 MiB, ten hours or more of play, keeping what
+ it has), a script without `--fresh` to the file, an export nothing, and
+ an export has no marks or clips, as the console says. The console's
+ status line ends with `rec file`, `rec memory` or `rec off`, and
+ `sessions` says where.
A commit is a second of play (of event time, so a script commits on the
same frames every run), and is made at once for a reload, a mark, a
clip's start or end, an export and exit; only a mark and exit are synced
to disk. A crash (a panic, `kill -9`) loses the frames not yet committed,
- under a second: the session lists as `(crashed)`, and a clip it left
- open ends where the session does. A power loss loses what the kernel had
+ under a second (15 of 255 in the kill test): the next run starts from the
+ last committed frame's State, the session lists as `(crashed)`, and a
+ clip it left open ends where the session does. A power loss loses what the kernel had
not written back (30 s past the last sync, by default); the torn end is
mended at the next start, the file opened at its last whole commit, and
a file still unreadable is renamed to `<path>.broken.<seconds>`, never
- deleted, and a new one begun. Live State is in the state file either way.
+ deleted, and a new one begun.
+
+ A minute of drat-meout's play was 268 KB with the pointer moving every
+ frame (16 MB an hour), 164 KB idle (86 KB of ticks, the rest keyframes,
+ then whole States; a keyframe is about 5 KB now).
- A minute of drat-meout's play is 268 KB with the pointer moving every
- frame (16 MB an hour), 164 KB idle (86 KB of ticks, the rest keyframes).
- Every commit leaves the nodes it copied behind, about a kilobyte; a clean
- exit compacts the file once it is past twice what its sessions hold plus
- 64 MiB. Nothing is compressed or forgotten yet.
+ **The cap.** A save is at most 64 MiB, and State half of that, so
+ history has room. A commit that leaves the file past it drops history
+ oldest first, keyframes' pages and the frames logged with them, and
+ compacts the file to three quarters of the cap: a hitch of about 170 ms
+ for a 48 MiB file in a Debug build, once every 16 MiB of history. The
+ present is never dropped, nor the keyframe of the newest mark of each
+ name, nor the newest clip of each name and its frames. What was dropped
+ says so when it is asked for (`load #K`, `play session N`). A mark of a
+ new name needs room for a whole State: when marks fill the save it is
+ refused, saying how to make room, by saving over a mark's name (the
+ older one then goes with history) or starting another save (`--state`).
+ Every commit leaves the nodes it copied behind, about a kilobyte, which
+ the compaction removes too.
Playtests: `export-session [S] FILE` writes session S (this run's when
none is given) with its marks and clips to a database of its own, for a
@@ -942,9 +994,9 @@ a talk with a slider, a loop, a choice, two slides and `beside`.
`expect`, or a console line that errors (a sketch command returning an
error included), fails the script. Headless always means offscreen, even
with `SDL_VIDEO_DRIVER` set, and GPU work still runs, into a texture. A
- scripted `--fresh` run works on files of its own (`<state>.<pid>`),
- renamed to the given `--state` at exit, so two builds running the same
- script at once do not share them; its sessions are in memory.
+ scripted `--fresh` run saves nothing: its sessions are in memory, and the
+ files it appends to are `<stem>.<pid>.<name>`, removed at exit, so two
+ builds running the same script at once do not share them.
- **Export.** `--export DIR` plays the sketch headless, from fresh state,
and saves every frame as `DIR/000000.png`, `000001.png`, ...;
`--export -` writes them to stdout instead, as raw RGBA:
@@ -964,8 +1016,8 @@ a talk with a slider, a loop, a choice, two slides and `beside`.
hides its controls, plays through and quits. `--size WxH` is the room
for the canvas (`in.window_width`/`height`, and the first canvas): a
sketch that sets its canvas to the room exports at any size. An export
- keeps state files of its own and removes them, so it can run beside a
- player. `--export` plays no script. In a release build on an RTX 3050,
+ saves nothing, and the files it appends to are its own, removed at exit,
+ so it can run beside a player. `--export` plays no script. In a release build on an RTX 3050,
an `anim` scene takes 6 ms a frame as raw RGBA and 21 as PNG at
1920x1080, 19 and 73 at 3840x2160; with ffmpeg encoding x264 from the
pipe, 11 and 41. The PNG encoder is the slow part: pipe, when the frames
@@ -1028,7 +1080,7 @@ pub fn build(b: *std.Build) void {
}
```
-`addSteps` installs the executable and adds `run`, `lib`, `probe`,
+`addSteps` installs the executable and adds `run`, `lib`,
`export` (`zig build export -- frames --size 1920x1080`: what follows `--`
is `--export`'s directory, or `-`, then its options), `e2e` and
`test`, and with `.web = .{}` also `web` (the page into `zig-out/web`) and
@@ -1047,7 +1099,6 @@ and returns plain `std.Build` objects:
| `app.addRun(lib, .{})` | the generic host running the installed library, its files in `.sketchbook/` |
| `app.addScript(exe_or_lib, file, .{})` | a headless, fresh-state scripted run, of the executable or of the library through the host (so the script can `reload` it) |
| `app.addExport(exe, .{ .fps, .frames, .size })` | a headless export of the executable's frames, as PNGs in `.frames`, a directory of the cache |
-| `app.addProbe(state)` | the probe on a state file |
| `app.addTest(.{})` | tests with the app importable as `app` |
| `app.addReloadCheck(.{ .script, .edits })` | a check that the app hot-reloads with State kept (below) |
@@ -1057,8 +1108,8 @@ for sketches whose per-pixel loops crawl in Debug; null (the default) is
`optimize`. Only Zig code changes mode (the host's and the app's), so it
costs one more compile, not SDL's. A `b.option` makes it a `-D` flag.
-`sb.app(.{ ..., .record = true })` records sessions in every mode (see
-The host); null, the default, records in Debug builds only.
+`sb.app(.{ ..., .record = true })` keeps history in every mode (see
+The host); null, the default, in Debug builds only.
**Hot reload, checked.** `addReloadCheck` builds the app's library as
written, and again from a copy of its sources with textual edits applied,
@@ -1135,7 +1186,7 @@ and Pillow (the renderers against resvg), `ffmpeg` if there is one, and,
for `zig build test-web`, Chrome.
`sb.modules` (`abi`, `sketch`, `host`, `vector`, `scope`, `anim`),
-`sb.host_exe` and `sb.probe_exe` are exposed for anything else.
+`sb.host_exe` is exposed for anything else.
Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`.
## Known limits
@@ -1144,23 +1195,25 @@ Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`.
`f.openFile` answers with a line of any length.
- Every upload, compute dispatch and GPU pass is its own command buffer and
submit. Fine at a handful per frame; batch them per frame if that grows.
-- The store is not crash-safe: a crash in the middle of an allocation can
- leave it inconsistent, and `--fresh` starts it over.
-- Handles inside Store containers (`std.ArrayList(sk.Image)`) are not caught
- at compile time: the check does not follow pointers.
- Native antialiasing resolves coverage per sample within a run of
shapes, the canvas per shape, so where two shapes' edges meet the web
can show a faint seam native does not. `fill` rects and images are
antialiased natively only inside a target. Without a GPU renderer,
native draws aliased. A stroke that overlaps itself blends twice
natively where it overlaps, once on the web.
-- On the web: nothing persists (Store lasts as long as the page) and no
+- A keyframe hashes all of State to find the pages that changed: about 70
+ ms for 32 MiB in a Debug build, 3 ms in ReleaseFast, once a minute while
+ State changes and at every jump.
+- On the web: nothing persists and no
sessions are recorded, and multisampling is 4× at most. Every voice is
silent there, whatever its sound (loaded, decoded or made with
`newSound`), and so are groups' gains; `decodeSound` gives `.none`, and
`loadSound` knows only sounds the page decoded (opened or dropped
- files). What does sound: streams (`f.audio`) and the microphone, mixed
- on the main thread (a ScriptProcessor), so a busy page can crackle.
+ files). What does sound: streams (`f.audio`, `f.audioBuffer`) and the
+ microphone, mixed on the main thread (a ScriptProcessor), so a busy page
+ can crackle. A GPU buffer streamed there arrives a frame or two later
+ (WebGPU reads back only asynchronously), counted as queued meanwhile, and
+ `in.lead` is a fixed 100 ms.
The reusable GPU executor and the pardes integration are described in
[docs/pardes-rendering.md](docs/pardes-rendering.md), including the remaining
diff --git a/build.zig b/build.zig
index 08db674..aac8d16 100644
--- a/build.zig
+++ b/build.zig
@@ -6,7 +6,7 @@
//!
//! const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
//! const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") });
-//! _ = app.addSteps(.{}); // run, lib, probe, e2e, test, install;
+//! _ = app.addSteps(.{}); // run, lib, e2e, test, install;
//! // web and serve with `.web = .{}`
//!
//! or pick the pieces: `app.addLibrary()`, `app.addExecutable()`,
@@ -110,18 +110,7 @@ pub fn build(b: *Build) void {
});
b.installArtifact(host_exe);
- const probe = b.addExecutable(.{
- .name = "sketchbook-probe",
- .root_module = b.createModule(.{
- .root_source_file = b.path("src/host/probe.zig"),
- .target = target,
- .optimize = optimize,
- .imports = &.{.{ .name = "abi", .module = abi }},
- }),
- });
- b.installArtifact(probe);
-
- var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf }, .host_exe = host_exe, .probe_exe = probe, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) };
+ var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf }, .host_exe = host_exe, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) };
// Vector graphics: built with the same shader step apps use. Both forms
// of its shaders are exported, so apps' web builds can swap them too.
@@ -183,6 +172,15 @@ pub fn build(b: *Build) void {
b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }),
b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 }, .{ .name = "xitdb", .module = xitdb } } }),
}) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step);
+ // A State bigger than a save holds is a compile error that says what to do.
+ const too_big = b.addObject(.{ .name = "too_big", .root_module = b.createModule(.{
+ .root_source_file = b.addWriteFiles().add("too_big.zig", "comptime { _ = @import(\"abi\").layout.of(struct { bytes: [(32 << 20) + 1]u8 }, .state); }"),
+ .target = target,
+ .optimize = optimize,
+ .imports = &.{.{ .name = "abi", .module = abi }},
+ }) });
+ too_big.expect_errors = .{ .contains = "may be 32 MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session." };
+ test_step.dependOn(&too_big.step);
// The anim module alone: its unit tests, and below the player's scenes.
const test_anim = b.step("test-anim", "Test the anim module: its unit tests and the player on its test scenes");
const anim_tests = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/anim/root.zig"), .target = target, .optimize = optimize, .imports = anim_imports }) }));
@@ -407,17 +405,22 @@ pub fn build(b: *Build) void {
test_step.dependOn(&reload.step);
// A session survives a kill -9 up to its last commit: 255 frames
- // played, four commits of 60 made, the fifth lost with the process.
- // Its sketch records in every mode, so the test does in release builds too.
+ // played, four commits of 60 made, the fifth lost with the process; the
+ // next run starts from frame 240's State, replayed. Its sketch records
+ // in every mode, so the test does in release builds too; and a sketch
+ // that does not record keeps its present all the same.
const recorded = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = true }).addLibrary();
+ const unrecorded = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = false }).addLibrary();
const killed = b.addSystemCommand(&.{ "sh", "-c",
\\set -e
\\db="${3%.state}.xitdb"
- \\rm -f "$3" "$3.store" "$db"
- \\if "$0" --headless --script "$1" --state "$3" "$4"; then echo "killed run exited"; exit 1; else test $? = 137; fi
- \\"$0" --headless --script "$2" --state "$3" "$4"
+ \\for lib in "$4" "$5"; do
+ \\rm -f "$db"
+ \\if "$0" --headless --script "$1" --state "$3" "$lib"; then echo "killed run exited"; exit 1; else test $? = 137; fi
+ \\"$0" --headless --script "$2" --state "$3" "$lib"
\\test "$(stat -c %s "$db")" -lt 1048576
- \\rm -f "$3" "$3.store" "$db"
+ \\rm -f "$db"
+ \\done
});
killed.setName("a session survives kill -9");
killed.addArtifactArg(host_exe);
@@ -425,6 +428,7 @@ pub fn build(b: *Build) void {
killed.addFileArg(b.path("test/killed.script"));
_ = killed.addOutputFileArg("kill.state");
killed.addArtifactArg(recorded);
+ killed.addArtifactArg(unrecorded);
killed.has_side_effects = true;
killed.expectExitCode(0);
test_step.dependOn(&killed.step);
@@ -441,12 +445,12 @@ pub fn build(b: *Build) void {
const past = b.addSystemCommand(&.{ "sh", "-c",
\\set -e
\\db="${4%.state}.xitdb"
- \\rm -f "$4" "$4.store" "$db"
+ \\rm -f "$4" "$db"
\\"$0" --headless --script "$1" --state "$4" "$5"
\\"$0" --headless --script "$2" --state "$4" "$5"
\\"$0" --headless --script "$3" --state "$4" "$6"
\\test "$(stat -c %s "$db")" -lt 1048576
- \\rm -f "$4" "$4.store" "$db"
+ \\rm -f "$4" "$db"
});
past.setName("past sessions replay");
past.addArtifactArg(host_exe);
@@ -486,7 +490,7 @@ pub fn build(b: *Build) void {
// A script run twice records the same database but for the wall clock's
// times: the log and the keyframes follow from the script alone. From
- // fresh state it records in memory: no database at all.
+ // fresh state it records in memory: no file at all.
const same_sessions = b.addExecutable(.{ .name = "same_sessions", .root_module = b.createModule(.{
.root_source_file = b.path("test/same_sessions.zig"),
.target = target,
@@ -500,7 +504,7 @@ pub fn build(b: *Build) void {
\\"$0" --headless --script "$1" --state "$d/b.state" "$4"
\\"$2" "$d/a.xitdb" "$d/b.xitdb"
\\"$0" --headless --fresh --script "$1" --state "$d/c.state" "$4"
- \\test -e "$d/c.state"; test ! -e "$d/c.xitdb"
+ \\test ! -e "$d/c.state"; test ! -e "$d/c.xitdb"
\\rm -f "$d"/*
});
twice.setName("a script recorded twice");
@@ -514,34 +518,36 @@ pub fn build(b: *Build) void {
test_step.dependOn(&twice.step);
b.step("test-same", "A script run twice records the same database but for times").dependOn(&twice.step);
- // Where files go. Without --state: the XDG data directory, state and
- // sessions. In .sketchbook/ (`zig build run`'s): a .gitignore, and an
- // older build's state moved in, once, never over a file there.
+ // Where files go. Without --state: the XDG data directory, one file. In
+ // .sketchbook/ (`zig build run`'s): a .gitignore and the save, whose
+ // present the next run starts from; an older build's state file beside
+ // it is moved in, once, never over a file there, and never deleted.
const paths = b.addSystemCommand(&.{ "sh", "-c",
\\set -e
\\exe=$(realpath "$0"); lib=$(realpath "$1"); mkdir -p "$2"; d=$(realpath "$2")
\\rm -rf "$d"/* "$d"/.sketchbook; cd "$d"
\\XDG_DATA_HOME="$d/data" "$exe" --headless --console quit "$lib"
- \\test -s data/replay/replay.state; test -s data/replay/replay.xitdb
- \\"$exe" --headless --state replay.state --console "set updates 7" --console quit "$lib"
- \\"$exe" --headless --state .sketchbook/replay.state --console quit "$lib" 2>err
- \\grep -q moved err; test ! -e replay.state; test ! -e replay.state.store; grep -qx '*' .sketchbook/.gitignore
+ \\test "$(ls -A data/replay)" = replay.xitdb
+ \\"$exe" --headless --state .sketchbook/replay.xitdb --console "set updates 7" --console quit "$lib"
+ \\test "$(ls -A .sketchbook | tr '\n' ' ')" = ".gitignore replay.xitdb "; grep -qx '*' .sketchbook/.gitignore
\\printf 'expect updates 7\n' >check.script
- \\"$exe" --headless --state .sketchbook/replay.state --script check.script "$lib"
- \\"$exe" --headless --state replay.state --console quit "$lib"
- \\"$exe" --headless --state .sketchbook/replay.state --console quit "$lib" 2>err
- \\grep -q 'both exist' err; test -e replay.state
- \\"$exe" --headless --state .sketchbook/replay.state --script check.script "$lib"
+ \\"$exe" --headless --state .sketchbook/replay.xitdb --script check.script "$lib"
+ \\printf 'not a state file' >old.state
+ \\"$exe" --headless --state .sketchbook/old.xitdb --console quit "$lib" 2>err
+ \\grep -q moved err; test ! -e old.state; test "$(cat .sketchbook/old.state)" = 'not a state file'
+ \\printf 'not a state file' >old.state
+ \\"$exe" --headless --state .sketchbook/old.xitdb --console quit "$lib" 2>err
+ \\grep -q 'both exist' err; test -e old.state
\\rm -rf "$d"/* "$d"/.sketchbook
});
- paths.setName("state and sessions paths");
+ paths.setName("where the save goes");
paths.addArtifactArg(host_exe);
paths.addArtifactArg(recorded);
_ = paths.addOutputDirectoryArg("paths");
paths.has_side_effects = true;
paths.expectExitCode(0);
test_step.dependOn(&paths.step);
- b.step("test-paths", "Check where state and sessions files go").dependOn(&paths.step);
+ b.step("test-paths", "Check where the save goes").dependOn(&paths.step);
// Recorded input replays to the same state: played, seeked, stepped,
// and after a live pointer move (core host behaviour, not an API).
@@ -737,7 +743,6 @@ pub fn init(b: *Build, options: Options) Sketchbook {
.optimize = options.optimize,
.modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim"), .gltf = dep.module("gltf") },
.host_exe = dep.artifact("sketchbook"),
- .probe_exe = dep.artifact("sketchbook-probe"),
.gltf_generator = dep.artifact("gltf-bindings"),
.web = dep.path("web"),
.glsl = dep.path("src/glsl.zig"),
@@ -789,8 +794,6 @@ pub const Sketchbook = struct {
modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module, gltf: *Build.Module },
/// The generic host: loads and hot-reloads a sketch library.
host_exe: *Build.Step.Compile,
- /// Prints any sketch's state file.
- probe_exe: *Build.Step.Compile,
/// `host.js` and the `index.html` template.
web: Build.LazyPath,
/// The GLSL declaration generator (see `addGlslLayouts`).
@@ -1250,8 +1253,9 @@ pub const App = struct {
/// Imports for the app's root module, besides `sketch`: for example
/// `sb.modules.vector`, or shaders from `addSpirvModule`.
imports: []const Build.Module.Import = &.{},
- /// Record every interactive run's sessions to a file beside its
- /// state (src/host/Sessions.zig). Null: in Debug builds only. A
+ /// Keep every run's history in the save, the newest 64 MiB of it
+ /// (src/host/Sessions.zig); without, the save keeps the present and
+ /// the marks only. Null: in Debug builds only. A
/// playtest build of a release opts in with one line,
/// `.record = b.option(bool, "record", "collect sessions in a release build")`.
record: ?bool = null,
@@ -1450,9 +1454,8 @@ pub const App = struct {
}
pub const RunOptions = struct {
- /// State file, relative to the working directory;
- /// `.sketchbook/<name>.state` by default, where the host keeps the
- /// sessions database beside it, all ignored by git and jj.
+ /// The save, relative to the working directory;
+ /// `.sketchbook/<name>.xitdb` by default, ignored by git and jj.
state: ?[]const u8 = null,
/// Where relative asset paths resolve; the project root by default.
cwd: ?Build.LazyPath = null,
@@ -1465,7 +1468,7 @@ pub const App = struct {
const install = b.addInstallArtifact(library, .{});
const run = b.addRunArtifact(app.sb.host_exe);
run.step.dependOn(&install.step);
- run.addArgs(&.{ "--state", options.state orelse b.fmt(".sketchbook/{s}.state", .{app.name}) });
+ run.addArgs(&.{ "--state", options.state orelse b.fmt(".sketchbook/{s}.xitdb", .{app.name}) });
run.addFileArg(b.graph.path(.install_lib, library.out_filename));
run.setCwd(options.cwd orelse b.path("."));
run.stdio = .inherit;
@@ -1479,7 +1482,7 @@ pub const App = struct {
cwd: ?Build.LazyPath = null,
};
- /// Plays a script headless, with a throwaway state file, against
+ /// Plays a script headless, from fresh state and saving nothing, against
/// `artifact`: the executable (`addExecutable`), or the hot-reloadable
/// library (`addLibrary`) through the generic host, which scripts can
/// `reload`. Fails when an expectation or a console line does.
@@ -1491,7 +1494,7 @@ pub const App = struct {
run.addFileArg(script);
run.addArg("--state");
// Named per script: runs of one app may share an output directory.
- _ = run.addOutputFileArg(b.fmt("{s}-{s}.state", .{ app.name, std.fs.path.stem(script.getDisplayName()) }));
+ _ = run.addOutputFileArg(b.fmt("{s}-{s}.xitdb", .{ app.name, std.fs.path.stem(script.getDisplayName()) }));
for (options.defines) |pair| run.addArgs(&.{ "--define", b.fmt("{s}={s}", .{ pair[0], pair[1] }) });
if (library) run.addArtifactArg(artifact);
run.setCwd(options.cwd orelse b.path("."));
@@ -1521,7 +1524,7 @@ pub const App = struct {
const b = app.sb.b;
const run = b.addRunArtifact(exe);
run.addArg("--state");
- _ = run.addOutputFileArg(b.fmt("{s}-export.state", .{app.name}));
+ _ = run.addOutputFileArg(b.fmt("{s}-export.xitdb", .{app.name}));
run.addArg("--export");
const frames = run.addOutputDirectoryArg("frames");
run.addArgs(&.{ "--fps", b.fmt("{d}", .{options.fps}) });
@@ -1532,17 +1535,6 @@ pub const App = struct {
return .{ .run = run, .frames = frames };
}
- /// Prints the app's live state; `zig build probe -- --watch` follows it.
- pub fn addProbe(app: App, state: ?[]const u8) *Build.Step.Run {
- const b = app.sb.b;
- const run = b.addRunArtifact(app.sb.probe_exe);
- run.addArg(state orelse b.fmt(".sketchbook/{s}.state", .{app.name}));
- run.setCwd(b.path("."));
- run.stdio = .inherit;
- run.addPassthruArgs();
- return run;
- }
-
/// Tests in `root_source_file` (the app's root by default), with the
/// app's imports and the app itself importable as `app`.
pub fn addTest(app: App, options: struct { root_source_file: ?Build.LazyPath = null }) *Build.Step.Compile {
@@ -1787,7 +1779,7 @@ pub const App = struct {
/// The conventional wiring. Installs the executable, and adds:
/// `run` (host + hot reload), `lib` (rebuild the library; use `--watch`),
- /// `web` and `serve` (with `web` options), `probe`, `export` (frames
+ /// `web` and `serve` (with `web` options), `export` (frames
/// for ffmpeg), `e2e` (scripts) and `test`.
pub fn addSteps(app: App, options: StepsOptions) Steps {
const b = app.sb.b;
@@ -1798,7 +1790,6 @@ pub const App = struct {
const run = app.addRun(library, .{});
b.step("run", "Run with hot reload (rebuild with `zig build lib --watch`)").dependOn(&run.step);
b.step("lib", "Build and install the hot-reloadable library").dependOn(&b.addInstallArtifact(library, .{}).step);
- b.step("probe", "Print the live state (-- --watch to follow)").dependOn(&app.addProbe(null).step);
const web = if (options.web) |web_options| blk: {
const web = app.addWeb(web_options);
@@ -1810,7 +1801,7 @@ pub const App = struct {
// `--export` takes the first argument after `--`.
const exporting = b.addRunArtifact(exe);
- exporting.addArgs(&.{ "--state", b.fmt(".sketchbook/{s}.state", .{app.name}), "--export" });
+ exporting.addArgs(&.{ "--state", b.fmt(".sketchbook/{s}.xitdb", .{app.name}), "--export" });
exporting.addPassthruArgs();
exporting.setCwd(b.path("."));
exporting.stdio = .inherit;
diff --git a/examples/micscope/README.md b/examples/micscope/README.md
index bd55ee0..875ebdf 100644
--- a/examples/micscope/README.md
+++ b/examples/micscope/README.md
@@ -148,6 +148,11 @@ with WebGPU (Chrome, Edge, Safari 26; Firefox on Linux with
browser has accepted its self-signed certificate (miniserve prints the
addresses as QR codes, for phones).
-The takes are the sketch's `Store`: they live in `micscope.state.store` and
-are still there after a restart. Takes stop at ten minutes; the strip holds
-64. A store from before the strip has its one tape as the first take.
+Each take is a file of its samples (mono 32-bit floats at the host's
+rate), `micscope.take-<id>.f32` beside the save (in `.sketchbook/`
+under `zig build run`), written as it records (`Host.appendFile`). State
+lists the takes, so they are still there after a restart. A take starts
+its file empty (`Host.writeFile`). A deleted take's file stays: a seek
+back, or any mark from before the delete, finds it again. Takes stop at ten minutes; the
+strip holds 64. A `micscope.state.store` from before is not read: its takes
+stay in it.
diff --git a/examples/micscope/src/main.zig b/examples/micscope/src/main.zig
index 3b44ba0..99aac76 100644
--- a/examples/micscope/src/main.zig
+++ b/examples/micscope/src/main.zig
@@ -9,11 +9,13 @@
//! speakers.
//!
//! Memory by lifetime: State is the transport, the selection and the views,
-//! changed by `update` from keys and the mouse, and replayable. Store holds
-//! the takes, on disk: they are still there after a restart. Session is
-//! this process's playback cursor, the microphone's recent past and GPU
-//! objects. Transport changes, seeks and deletions are `sk.Request`s, which
-//! `draw` carries out once each.
+//! the takes (their ids and names), changed by `update` from keys and the
+//! mouse, and replayable. A take's samples are a file of its own, written
+//! by `draw` as it records and by `open` (see `Host.appendFile`): they are
+//! still there after a restart. Session is this process's copy of the
+//! takes' samples, the playback cursor, the microphone's recent past and
+//! GPU objects. Transport changes and seeks are `sk.Request`s, which `draw`
+//! carries out once each.
const std = @import("std");
const sk = @import("sketch");
const gpu = sk.abi.gpu;
@@ -27,7 +29,7 @@ const tuner = @import("tuner.zig");
pub const name = "micscope";
pub const width = 1280;
pub const height = 900;
-pub const commands = .{ "open", "takes" };
+pub const commands = .{ "open", "next-id" };
/// The longest take: ten minutes at the host's rate.
const max_seconds = 600;
@@ -55,11 +57,12 @@ pub const State = struct {
seek: sk.Request(f32) = .{},
scrubbing: bool = false,
dialog: sk.Request(void) = .{},
- /// Deletes the take at this index.
- remove: sk.Request(u32) = .{},
- /// How many takes the Store holds. `update` keeps count as it records
- /// and deletes; `draw` corrects it with the `takes` command if not.
- takes: u32 = 0,
+ /// Oldest first.
+ takes: sk.List(Take, max_takes) = .{},
+ /// The next take's id. `draw` moves it past take files already there
+ /// with the `next-id` command: other runs' (`--fresh` keeps the files),
+ /// or the future a seek went back from.
+ next_id: u32 = 1,
/// The take the transport and the keys work on, by index (oldest 0).
selected: u32 = 0,
views: [max_takes]View = @splat(.{}),
@@ -76,37 +79,36 @@ pub const State = struct {
};
pub const Take = struct {
- /// Its samples: `Store.tape[start..][0..len]`.
- start: usize = 0,
- len: usize = 0,
- /// Stays the same when earlier takes are deleted: GPU caches go by it.
+ /// Names its file, `take-<id>.f32`: its mono samples at
+ /// `Input.sample_rate`. Stays the same when earlier takes are deleted:
+ /// Session and the GPU caches go by it.
id: u32 = 0,
- /// Where the listener is, in samples into the take.
- heard: f64 = 0,
/// A file's name, or empty for the microphone.
source: [64]u8 = @splat(0),
source_len: u32 = 0,
};
-pub const Store = struct {
- /// Every take's mono samples at `Input.sample_rate`, one after another,
- /// oldest first. A recording grows the last one.
- tape: std.ArrayList(f32) = .empty,
- takes: std.ArrayList(Take) = .empty,
- next_id: u32 = 1,
+/// A take's samples in `Session.tape`.
+const Clip = struct {
+ id: u32 = 0,
+ start: usize = 0,
+ len: usize = 0,
+ /// Where the listener is, in samples into the take.
+ heard: f64 = 0,
};
pub const Session = struct {
transport: sk.Handled = .{},
seek: sk.Handled = .{},
dialog: sk.Handled = .{},
- remove: sk.Handled = .{},
+ /// State's takes' samples, read from their files once a process, one
+ /// after another in the order read. A recording grows the last one.
+ tape: std.ArrayList(f32) = .empty,
+ clips: sk.List(Clip, max_takes) = .{},
/// The take playback follows, by id, and the next of its samples to
/// queue.
playing: u32 = 0,
cursor: usize = 0,
- /// The take being recorded, by id.
- recording: u32 = 0,
/// The microphone's recent past and the live view.
live: scope.Scope = .{},
/// Pitch, by tuner.comp: of the microphone (live, or recording), and
@@ -123,7 +125,7 @@ const Tuned = enum(u32) { input, take };
/// GPU objects, made on first use.
const Gpu = struct {
ready: bool = false,
- /// `Store.tape`, and how many of its samples are in it.
+ /// `Session.tape`, and how many of its samples are in it.
tape: sk.Buffer = .none,
capacity: usize = 0,
uploaded: usize = 0,
@@ -281,7 +283,7 @@ const World = struct {
live: bool,
fn of(s: *const State) World {
- return .{ .takes = s.takes, .live = s.transport.value != .recording };
+ return .{ .takes = s.takes.count(), .live = s.transport.value != .recording };
}
fn slots(w: World) u32 {
return w.takes + @intFromBool(w.live);
@@ -341,10 +343,10 @@ pub fn update(s: *State, in: *const sk.Input) void {
if (in.pressed(sk.Key.equals)) s.gain = @min(s.gain * 1.25, 64);
if (in.pressed(sk.Key.minus)) s.gain = @max(s.gain / 1.25, 0.25);
if (in.pressed(sk.Key.z) and s.selected < max_takes) s.views[s.selected] = .{};
- if (!recording and s.takes > 0) {
+ if (!recording and s.takes.count() > 0) {
// Up the strip is older.
if (in.pressed(sk.Key.up)) select(s, s.selected -| 1, in);
- if (in.pressed(sk.Key.down)) select(s, @min(s.selected + 1, s.takes - 1), in);
+ if (in.pressed(sk.Key.down)) select(s, @min(s.selected + 1, s.takes.count() - 1), in);
}
const l = Layout.of(in.width, in.height);
const page = l.view.h - l.panel_height / 2;
@@ -429,7 +431,7 @@ fn act(s: *State, a: Action, in: *const sk.Input) void {
.start => seekTo(s, 0),
.end => seekTo(s, 1),
.open => s.dialog.send({}),
- .delete => if (now != .recording and s.takes > 0) remove(s, in),
+ .delete => if (now != .recording and s.takes.count() > 0) remove(s, in),
.overview => {
// The whole strip, or back to full size.
const l = Layout.of(in.width, in.height);
@@ -446,9 +448,9 @@ fn act(s: *State, a: Action, in: *const sk.Input) void {
/// Starts a new take, unless the strip is full. It takes the live view's
/// place, which the camera follows.
fn record(s: *State) void {
- if (s.takes >= max_takes) return;
- s.selected = s.takes;
- s.takes += 1;
+ s.takes.appendBounded(.{ .id = s.next_id }) catch return;
+ s.next_id += 1;
+ s.selected = s.takes.count() - 1;
s.views[s.selected] = .{};
s.follow = true;
change(s, .recording);
@@ -483,12 +485,14 @@ fn panBy(s: *State, pixels: f32, in: *const sk.Input) void {
moveCamera(s, cam, in);
}
-/// Deletes the selected take and selects the one above it.
+/// Deletes the selected take and selects the one above it. Its file stays:
+/// any keyframe or mark from before the delete brings the take back, and
+/// neither the sketch nor the host can tell when none is left.
fn remove(s: *State, in: *const sk.Input) void {
- const index = @min(s.selected, s.takes - 1);
- s.remove.send(index);
- std.mem.copyForwards(View, s.views[index .. s.takes - 1], s.views[index + 1 .. s.takes]);
- s.takes -= 1;
+ const n = s.takes.count();
+ const index = @min(s.selected, n - 1);
+ _ = s.takes.orderedRemove(index);
+ std.mem.copyForwards(View, s.views[index .. n - 1], s.views[index + 1 .. n]);
s.selected = index -| 1;
moveCamera(s, cameraOf(s, Layout.of(in.width, in.height)), in);
}
@@ -506,15 +510,14 @@ fn zoom(v: *View, at: f32, factor: f32) void {
v.hi = lo + span;
}
-/// `open PATH` adds a file as a take; `open` alone shows the dialog.
-/// `takes N` tells State how many takes the Store holds (`draw` sends it).
-pub fn command(s: *State, store: *Store, c: *sk.Console, line: []const u8) !bool {
+/// `open PATH` adds a file as a take, writing its samples to the take's
+/// file; `open` alone shows the dialog. `next-id N` moves the counter
+/// (`draw` sends it).
+pub fn command(s: *State, ss: *Session, c: *sk.Console, line: []const u8) !bool {
var words = std.mem.tokenizeAny(u8, line, " \t");
const verb = words.next() orelse return false;
- if (std.mem.eql(u8, verb, "takes")) {
- const n = try std.fmt.parseInt(u32, words.next() orelse return error.ExpectedCount, 10);
- s.takes = @min(n, max_takes);
- s.selected = @min(s.selected, s.takes -| 1);
+ if (std.mem.eql(u8, verb, "next-id")) {
+ s.next_id = try std.fmt.parseInt(u32, words.next() orelse return error.ExpectedId, 10);
return true;
}
if (!std.mem.eql(u8, verb, "open")) return false;
@@ -523,22 +526,24 @@ pub fn command(s: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
s.dialog.send({});
return true;
}
- if (store.takes.items.len >= max_takes) return error.TooManyTakes;
+ if (s.takes.count() >= max_takes) return error.TooManyTakes;
const samples = c.host.samples(c.host.loadSound(path));
if (samples.len == 0) return error.CannotOpen;
// Recording grows the last take: stop before this one goes after it.
if (s.transport.value == .recording) change(s, .stopped);
const kept = samples[0..@min(samples.len, max_seconds * c.in.sample_rate)];
- var take: Take = .{ .start = store.tape.items.len, .len = kept.len, .id = store.next_id };
+ var take: Take = .{ .id = s.next_id };
const base = std.fs.path.basename(path);
take.source_len = @intCast(@min(base.len, take.source.len));
@memcpy(take.source[0..take.source_len], base[0..take.source_len]);
- try store.takes.ensureUnusedCapacity(c.store, 1);
- try store.tape.appendSlice(c.store, kept);
- store.takes.appendAssumeCapacity(take);
- store.next_id += 1;
- s.takes = @intCast(store.takes.items.len);
- s.selected = s.takes - 1;
+ // Into Session now, so the web, which keeps no files, has it too.
+ try ss.tape.appendSlice(c.session, kept);
+ try ss.clips.appendBounded(.{ .id = take.id, .start = ss.tape.items.len - kept.len, .len = kept.len });
+ var file: [32]u8 = undefined;
+ _ = c.host.writeFile(try std.fmt.bufPrint(&file, "take-{d}.f32", .{take.id}), std.mem.sliceAsBytes(kept));
+ try s.takes.appendBounded(take);
+ s.next_id += 1;
+ s.selected = s.takes.count() - 1;
s.views[s.selected] = .{};
s.follow = true;
change(s, .stopped);
@@ -549,7 +554,7 @@ pub fn command(s: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
// ---------------------------------------------------------------------------
// Draw: the takes, the microphone, the speakers and the GPU.
-pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
+pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
const in = f.in;
const rate: f64 = @floatFromInt(in.sample_rate);
const dt: f64 = @min(@as(f64, @floatFromInt(in.dt)) / std.time.ns_per_s, 0.1);
@@ -557,24 +562,26 @@ pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
f.canvas(@intFromFloat(@max(in.window_width, min_width)), @intFromFloat(@max(in.window_height, min_height)));
f.clear(0x0b0c0f);
- adoptTape(store, f.store);
if (ss.dialog.take(s.dialog) != null) f.openFile("open", .{ .pattern = "wav;flac;ogg" });
- if (ss.remove.take(s.remove)) |index| removeTake(ss, store, index);
-
+ // Files are written live, never while a recording of the session plays
+ // back: like sound, a write is not replayed.
+ const writing = in.mode == .live or in.mode == .recording;
+ if (in.jumped and writing) {
+ // State came from elsewhere: the next id's file may hold samples.
+ var id = s.next_id;
+ while (f.host.readFile(f.host.appendFile(f.format("take-{d}.f32", .{id}), &.{})).len > 0) id += 1;
+ if (id != s.next_id) f.run(f.format("next-id {d}", .{id}));
+ }
// Requests from State. Any of them, or another take selected, flushes
// what is queued, so the cursor restarts from what was heard.
const transport = ss.transport.take(s.transport);
const seek = ss.seek.take(s.seek);
- // Recording goes by the transport's value rather than the request, so a
- // fresh session that only caught up with the request still records.
- if (s.transport.value != .recording) {
- ss.recording = 0;
- } else if (store.takes.items.len == 0 or store.takes.items[store.takes.items.len - 1].id != ss.recording) {
- startTake(ss, store, f.store);
- }
- const takes = store.takes.items;
- if (s.takes != takes.len) f.run(f.format("takes {d}", .{takes.len}));
- const selected: ?*Take = if (takes.len > 0) &takes[@min(s.selected, takes.len - 1)] else null;
+ const takes = s.takes.constSlice();
+ // A take that begins here (not one a jump brought) starts its file
+ // empty, whatever a file of its id held.
+ if (transport == .recording and writing and !in.jumped and takes.len > 0) _ = f.host.writeFile(f.format("take-{d}.f32", .{takes[takes.len - 1].id}), &.{});
+ readTakes(s, ss, f);
+ const selected: ?*Clip = if (takes.len > 0) clipOf(ss, takes[@min(s.selected, takes.len - 1)].id) else null;
var queued: usize = in.stream(stream).queued;
if (selected) |t| {
if (transport != null or seek != null or t.id != ss.playing) {
@@ -606,15 +613,16 @@ pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
f.microphone();
ss.live.push(in.microphone);
switch (s.transport.value) {
- .recording => if (takes.len > 0 and takes[takes.len - 1].id == ss.recording) {
- const t = &takes[takes.len - 1];
+ // Into the last take, at the tape's end.
+ .recording => if (takes.len > 0 and writing) if (clipOf(ss, takes[takes.len - 1].id)) |t| if (t.start + t.len == ss.tape.items.len) {
const room = max_seconds * in.sample_rate -| t.len;
const heard = in.microphone[0..@min(in.microphone.len, room)];
- store.tape.appendSlice(f.store, heard) catch f.host.log("the store is full: recording stopped");
- t.len = store.tape.items.len - t.start;
+ ss.tape.appendSlice(f.session, heard) catch f.host.log("out of memory: recording stopped");
+ _ = f.host.appendFile(f.format("take-{d}.f32", .{t.id}), std.mem.sliceAsBytes(heard));
+ t.len = ss.tape.items.len - t.start;
t.heard = @floatFromInt(t.len);
},
- .forward, .backward => if (selected) |t| play(ss, t, store.tape.items[t.start..][0..t.len], f, s.transport.value == .forward, queued, rate, dt),
+ .forward, .backward => if (selected) |t| play(ss, t, ss.tape.items[t.start..][0..t.len], f, s.transport.value == .forward, queued, rate, dt),
.stopped => {},
}
@@ -632,41 +640,48 @@ pub fn draw(s: *const State, ss: *Session, store: *Store, f: *sk.Frame) void {
f.text(16, Layout.header, 2, "micscope needs a GPU: the host has none.", 0xff8080);
return;
}
- render(s, ss, store, f, rate, dt);
+ render(s, ss, f, rate, dt);
}
-/// Stores from before the strip held one tape: it becomes the first take.
-fn adoptTape(store: *Store, a: std.mem.Allocator) void {
- if (store.takes.items.len > 0 or store.tape.items.len == 0) return;
- store.takes.append(a, .{ .len = store.tape.items.len, .id = store.next_id }) catch return;
- store.next_id += 1;
-}
-
-fn startTake(ss: *Session, store: *Store, a: std.mem.Allocator) void {
- store.takes.append(a, .{ .start = store.tape.items.len, .id = store.next_id }) catch {
- return;
+/// Session's tape follows State's takes: a take State no longer has leaves
+/// it, and one it lacks is read from its file (a new one's is empty).
+fn readTakes(s: *const State, ss: *Session, f: *sk.Frame) void {
+ var i: u32 = 0;
+ while (i < ss.clips.count()) {
+ const t = ss.clips.buffer[i];
+ if (for (s.takes.constSlice()) |take| {
+ if (take.id == t.id) break true;
+ } else false) {
+ i += 1;
+ continue;
+ }
+ _ = ss.clips.orderedRemove(i);
+ const tape = ss.tape.items;
+ std.mem.copyForwards(f32, tape[t.start .. tape.len - t.len], tape[t.start + t.len ..]);
+ ss.tape.shrinkRetainingCapacity(tape.len - t.len);
+ for (ss.clips.slice()[i..]) |*later| later.start -= t.len;
+ ss.gpu.uploaded = @min(ss.gpu.uploaded, t.start);
+ for (&ss.gpu.panels) |*p| if (p.id == t.id) {
+ p.id = 0;
+ p.forget();
+ };
+ }
+ for (s.takes.constSlice()) |take| if (clipOf(ss, take.id) == null) {
+ const bytes = f.host.readFile(f.host.appendFile(f.format("take-{d}.f32", .{take.id}), &.{}));
+ const samples = std.mem.bytesAsSlice(f32, @as([]align(4) const u8, @alignCast(bytes[0 .. bytes.len / 4 * 4])));
+ ss.tape.appendSlice(f.session, samples) catch return f.host.log("out of memory: takes not read");
+ ss.clips.appendBounded(.{ .id = take.id, .start = ss.tape.items.len - samples.len, .len = samples.len }) catch return;
};
- ss.recording = store.next_id;
- store.next_id += 1;
}
-fn removeTake(ss: *Session, store: *Store, index: u32) void {
- if (index >= store.takes.items.len) return;
- const t = store.takes.orderedRemove(index);
- const tape = store.tape.items;
- std.mem.copyForwards(f32, tape[t.start .. tape.len - t.len], tape[t.start + t.len ..]);
- store.tape.shrinkRetainingCapacity(tape.len - t.len);
- for (store.takes.items[index..]) |*later| later.start -= t.len;
- ss.gpu.uploaded = @min(ss.gpu.uploaded, t.start);
- for (&ss.gpu.panels) |*p| if (p.id == t.id) {
- p.id = 0;
- p.forget();
- };
+fn clipOf(ss: *Session, id: u32) ?*Clip {
+ for (ss.clips.slice()) |*t| if (t.id == id) return t;
+ return null;
}
/// Keeps the stream `lead_seconds` ahead, reading the take either way, and
/// follows the listener.
-fn play(ss: *Session, t: *Take, tape: []const f32, f: *sk.Frame, forward: bool, queued: usize, rate: f64, dt: f64) void {
+fn play(ss: *Session, t: *Clip, tape: []const f32, f: *sk.Frame, forward: bool, queued: usize, rate: f64, dt: f64) void {
const lead: usize = @intFromFloat(rate * lead_seconds);
const want = lead -| queued;
// What is heard now: the cursor, less what is queued in front of it.
@@ -768,17 +783,17 @@ fn sync(g: *Gpu, f: *sk.Frame, tape: []const f32) void {
}
}
-fn render(s: *const State, ss: *Session, store: *Store, f: *sk.Frame, rate: f64, dt: f64) void {
+fn render(s: *const State, ss: *Session, f: *sk.Frame, rate: f64, dt: f64) void {
const g = &ss.gpu;
setup(g, f);
- sync(g, f, store.tape.items);
+ sync(g, f, ss.tape.items);
// New code may mean new shaders: make everything again (the live view
// sees to its own).
if (f.in.reloaded) for (&g.panels) |*p| p.forget();
- const takes = store.takes.items;
+ const takes = s.takes.constSlice();
const selected = if (takes.len > 0) @min(s.selected, takes.len - 1) else 0;
const recording = s.transport.value == .recording;
- const world: World = .{ .takes = @intCast(takes.len), .live = !recording };
+ const world: World = .of(s);
const l = Layout.of(f.in.width, f.in.height);
const cam = cameraOf(s, l);
const view = l.view;
@@ -795,24 +810,23 @@ fn render(s: *const State, ss: *Session, store: *Store, f: *sk.Frame, rate: f64,
// The tuner: on the microphone's newest sound, and on the selected take
// around its playhead.
const reach = tuner_layouts.tuner_window + tuner_layouts.tuner_lags;
- if (recording and takes.len > 0) {
- const t = takes[takes.len - 1];
+ const last = if (recording and takes.len > 0) clipOf(ss, takes[takes.len - 1].id) else null;
+ if (last) |t| {
tune(g, f, .input, g.tape, t.start, t.len, t.len, rate);
} else tune(g, f, .input, ss.live.gpu.tape, 0, scope.history, scope.history, rate);
- if (!recording and takes.len > 0) {
- const t = takes[selected];
+ if (!recording and takes.len > 0) if (clipOf(ss, takes[selected].id)) |t| {
const end: usize = @intFromFloat(@max(t.heard, 0));
tune(g, f, .take, g.tape, t.start, t.len, end + reach / 2, rate);
- }
+ };
for (0..world.takes) |slot| {
const k: u32 = @intCast(slot);
const b = l.box(k).toScreen(cam);
if (b.whole.y + b.whole.h <= view.y or b.whole.y >= view.y + view.h) continue;
const tint: layouts.Tint = if (recording and k + 1 == world.takes) .recording else .take;
- drawTake(s, g, f, size, b, &takes[k], s.views[k], k == selected, tint, rate, dt);
+ drawTake(s, g, f, size, b, clipOf(ss, takes[k].id) orelse continue, s.views[k], k == selected, tint, rate, dt);
}
f.clip(null);
- labels(s, ss, store, f, world, cam, rate);
+ labels(s, ss, f, world, cam, rate);
}
/// Finds the pitch of the `tuner_window` samples before `end` (of the
@@ -884,7 +898,7 @@ fn spectrum(g: *Gpu, f: *sk.Frame, tape: sk.Buffer, p: *Panel, size: [2]u32, par
});
}
-fn drawTake(s: *const State, g: *Gpu, f: *sk.Frame, size: Box, b: Box, t: *const Take, view: View, selected: bool, tint: layouts.Tint, rate: f64, dt: f64) void {
+fn drawTake(s: *const State, g: *Gpu, f: *sk.Frame, size: Box, b: Box, t: *const Clip, view: View, selected: bool, tint: layouts.Tint, rate: f64, dt: f64) void {
const p = panelFor(g, f, t.id);
// Waveform columns, when what they show changed.
@@ -1041,8 +1055,8 @@ const red = 0xff5a5a;
const green = 0x6fdc8c;
const yellow = 0xffd84d;
-fn labels(s: *const State, ss: *const Session, store: *const Store, f: *sk.Frame, world: World, cam: sk.Camera, rate: f64) void {
- const takes = store.takes.items;
+fn labels(s: *const State, ss: *Session, f: *sk.Frame, world: World, cam: sk.Camera, rate: f64) void {
+ const takes = s.takes.constSlice();
const recording = s.transport.value == .recording;
const selected = if (takes.len > 0) @min(s.selected, takes.len - 1) else 0;
@@ -1055,14 +1069,13 @@ fn labels(s: *const State, ss: *const Session, store: *const Store, f: *sk.Frame
};
const l = Layout.of(f.in.width, f.in.height);
f.text(16, 10, 2, status[0], status[1]);
- if (takes.len > 0) {
- const t = takes[selected];
+ if (if (takes.len > 0) clipOf(ss, takes[selected].id) else null) |t| {
const times = .{ Time{ .seconds = t.heard / rate }, Time{ .seconds = @as(f64, @floatFromInt(t.len)) / rate } };
// As much as fits beside the buttons (or, narrow, the corner).
const room = if (l.narrow) l.w - 16 * 7 else l.button(buttons.len - 1).x - 16;
if (room >= 480) {
f.print(140, 10, 2, bright, "{f} / {f}", times);
- if (room >= 740) f.print(500, 14, 1, dim, "take {d} of {d}: {s}", .{ selected + 1, takes.len, source(&t) });
+ if (room >= 740) f.print(500, 14, 1, dim, "take {d} of {d}: {s}", .{ selected + 1, takes.len, source(&takes[selected]) });
} else f.print(16 + 16 * 7, 14, 1, bright, "{f} / {f}", times);
}
for (buttons, 0..) |a, i| button(s, f, a, l.button(i));
@@ -1087,14 +1100,14 @@ fn labels(s: *const State, ss: *const Session, store: *const Store, f: *sk.Frame
tunerOverlay(f, b.spectrum, ss.tuners[@intFromEnum(Tuned.input)].reading, s.a4, rate, cam.zoom >= 0.8);
continue;
}
- const t = &takes[k];
+ const t = clipOf(ss, takes[k].id) orelse continue;
const seconds = Time{ .seconds = @as(f64, @floatFromInt(t.len)) / rate };
if (recording and k + 1 == world.takes) {
f.print(b.whole.x, title_y, 1, red, "RECORDING take {d} {f}", .{ k + 1, seconds });
} else {
const chosen = k == selected;
if (chosen) f.fill(.{ .x = b.whole.x - if (l.narrow) @as(f32, 6) else 12, .y = b.wave.y, .w = 3, .h = b.timeline.h }, yellow);
- f.print(b.whole.x, title_y, 1, @as(u24, if (chosen) bright else dim), "#{d} {s} {f}", .{ k + 1, source(t), seconds });
+ f.print(b.whole.x, title_y, 1, @as(u24, if (chosen) bright else dim), "#{d} {s} {f}", .{ k + 1, source(&takes[k]), seconds });
}
if (cam.zoom >= 0.8) {
const span = visible(s.views[k], t.len, @intFromFloat(@min(l.box(0).wave.w, layouts.max_columns)));
@@ -1254,7 +1267,8 @@ test "the world stacks takes in order with the live view last" {
test "the camera follows the bottom and stays inside the world, wide or narrow" {
for ([_]Layout{ .of(width, height), .of(390, 844) }) |l| {
- var s: State = .{ .takes = 5 };
+ var s: State = .{};
+ s.takes.len = 5;
const cam = cameraOf(&s, l);
// Following: the live view's bottom sits at the viewport's bottom.
try std.testing.expectApproxEqAbs(l.view.y + l.view.h - 4, cam.toScreen(l.box(5).whole).y + l.panel_height, 1);
diff --git a/examples/micscope/test/record.script b/examples/micscope/test/record.script
index 2750a18..843d802 100644
--- a/examples/micscope/test/record.script
+++ b/examples/micscope/test/record.script
@@ -1,9 +1,9 @@
# Records (from whatever microphone the host gives a headless run) into a
# new take, stops, and plays it back.
-expect takes 0
+expect takes.len 0
key r
expect transport.value recording
-expect takes 1
+expect takes.len 1
frames 60
screenshot .zig-cache/micscope/recording.png
key r
@@ -13,11 +13,11 @@ expect transport.value forward
frames 10
# Each recording is another take; opening a file while recording ends it.
key r
-expect takes 2
+expect takes.len 2
expect selected 1
console open test/sweep.wav
expect transport.value stopped
-expect takes 3
+expect takes.len 3
frames 2
-expect takes 3
+expect takes.len 3
screenshot .zig-cache/micscope/strip.png
diff --git a/examples/micscope/test/transport.script b/examples/micscope/test/transport.script
index f821a03..2015682 100644
--- a/examples/micscope/test/transport.script
+++ b/examples/micscope/test/transport.script
@@ -2,7 +2,7 @@
# 16 kHz) over a quiet 440 Hz tone.
console open test/sweep.wav
frames 2
-expect takes 1
+expect takes.len 1
expect selected 0
expect transport.value stopped
key right
@@ -36,7 +36,7 @@ frames 30
screenshot .zig-cache/micscope/played.png
# A second take goes under the first and is selected; up is older.
console open test/sweep.wav
-expect takes 2
+expect takes.len 2
expect selected 1
key up
expect selected 0
@@ -47,14 +47,22 @@ click 400 150
expect selected 0
frames 2
screenshot .zig-cache/micscope/two-takes.png
-# Deleting it leaves the second.
+# Deleting it leaves the second. Its file stays: going back to before the
+# deletion reads it again.
+console save two
key delete
-expect takes 1
+expect takes.len 1
expect selected 0
-# State that miscounts the takes is told by draw.
-console set takes 0
+console load two
frames 2
-expect takes 1
+expect takes.len 2
+key delete
+expect takes.len 1
+# A counter that names a take file already written (--fresh keeps the
+# files; a seek back finds the future's) is moved past it by draw.
+console set next_id 1
+frames 2
+expect next_id 3
# More takes than fit: the camera follows the bottom until the wheel pans
# it, then 0 shows the whole strip.
console open test/sweep.wav
diff --git a/examples/spheres/README.md b/examples/spheres/README.md
index 3c65666..30023de 100644
--- a/examples/spheres/README.md
+++ b/examples/spheres/README.md
@@ -17,10 +17,12 @@ Everything moves on the GPU:
| `sprite.*`, `trail.*`, `fade.frag` | The sky: the cloud as layered dust on a long exposure, system 0's bodies as glows, and their trails as ribbons tapering with age. |
| `link.*` | The coupling: a ribbon from modulator to carrier, as bright as the coupling, with pulses flowing along it. |
-The sound reaches the speakers by a readback (`f.download`) about two
-frames later; the CPU only queues it, and hands it to sketchbook's `scope`
-module (the views micscope uses) for the oscilloscope, spectrum and
-spectrogram.
+The sound goes from the GPU's block straight to the speakers
+(`f.audioBuffer`): the host reads it back in the same frame and keeps the
+lead it measures queued (`in.lead`), so a change is heard in about two
+device pulls rather than 100 ms. A second readback (`f.download`), a frame
+later, hands it to sketchbook's `scope` module (the views micscope uses)
+for the oscilloscope, spectrum and spectrogram.
## From motion to sound
diff --git a/examples/spheres/src/main.zig b/examples/spheres/src/main.zig
index 60b498f..062aebd 100644
--- a/examples/spheres/src/main.zig
+++ b/examples/spheres/src/main.zig
@@ -27,8 +27,6 @@ pub const height = 800;
/// The audio stream's key.
const stream = 1;
-/// How much sound is kept queued ahead: synthesised, read back, queued.
-const lead_seconds = 0.1;
/// Systems integrated: system 0 and its cloud.
const systems = layouts.max_systems;
/// How far apart the copies start.
@@ -87,8 +85,6 @@ const Travel = struct { to: chords.Pick, speed: f64 };
pub const Session = struct {
reset: sk.Handled = .{},
started: bool = false,
- /// Synthesised samples not back from the GPU yet.
- in_flight: usize = 0,
/// System 0 as last read back, and whether it has been.
lead: layouts.Lead = std.mem.zeroes(layouts.Lead),
have_lead: bool = false,
@@ -113,8 +109,6 @@ pub const Session = struct {
travel: ?Travel = null,
/// The snapshot whose chord is held.
held: ?chords.Pick = null,
- /// Samples still to come back from before a chord was chosen, dropped.
- discard: usize = 0,
gpu: Gpu = .{},
};
@@ -418,18 +412,13 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
const g = &ss.gpu;
setup(g, f);
- // What came back: sound for the speakers and the scope, and system 0.
+ // What came back: the sound, for the scope, and system 0.
for (in.downloads) |d| switch (@as(Readback, @enumFromInt(d.key))) {
.audio => {
const samples = std.mem.bytesAsSlice(f32, d.bytes[0 .. d.bytes.len / 4 * 4]);
const aligned = f.scratch.alloc(f32, samples.len) catch continue;
for (aligned, samples) |*to, from| to.* = from;
- ss.in_flight -|= aligned.len;
- // Sound made before a chord was chosen is not played.
- const dropped = @min(ss.discard, aligned.len);
- ss.discard -= dropped;
- f.audio(stream, aligned[dropped..], .{});
- ss.scope.push(aligned[dropped..]);
+ ss.scope.push(aligned);
},
.lead => if (d.bytes.len >= @sizeOf(layouts.Lead)) {
ss.lead = std.mem.bytesToValue(layouts.Lead, d.bytes[0..@sizeOf(layouts.Lead)]);
@@ -456,7 +445,6 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
ss.held = pick;
ss.travel = .{ .to = pick, .speed = @max(@abs(pick.time() - ss.time) / 1.2, 2) };
f.audio(stream, &.{}, .{ .clear = true });
- ss.discard = ss.in_flight;
}
};
@@ -517,13 +505,12 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
ss.trail_filled = @min(ss.trail_filled + trail.points, layouts.trail);
f.download(g.lead, .{ .size = @sizeOf(layouts.Lead), .key = @intFromEnum(Readback.lead) });
- // The sound: enough to keep `lead_seconds` queued, counting what is
- // still on its way back from the GPU.
- const queued = in.stream(stream).queued + ss.in_flight;
- const want: usize = @min(@as(usize, @intFromFloat(lead_seconds * rate)) -| queued, layouts.max_block);
+ // The sound: as much as keeps the host's lead queued, streamed straight
+ // from the GPU's block; and read back for the scope.
+ const want: u32 = @min(in.lead -| in.stream(stream).queued, layouts.max_block);
if (want > 0) {
const params = gpu.uniform(f.scratch, layouts.SynthParams{
- .count = @intCast(want),
+ .count = want,
.mode = @intFromEnum(s.mode),
.rate = @floatCast(rate),
// Loud enough for a phone's speaker; tanh rounds the peaks off.
@@ -535,11 +522,11 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
.readonly = &.{ g.voices, g.phases },
.readwrite = &.{g.block},
.uniforms = params,
- .groups = .{ @intCast((want + 63) / 64), 1, 1 },
+ .groups = .{ (want + 63) / 64, 1, 1 },
});
f.compute(.{ .label = "advance.comp", .kernel = advance_kernel, .readwrite = &.{ g.voices, g.phases }, .uniforms = params });
- f.download(g.block, .{ .size = @intCast(want * @sizeOf(f32)), .key = @intFromEnum(Readback.audio) });
- ss.in_flight += want;
+ f.audioBuffer(stream, g.block, .{ .count = want });
+ f.download(g.block, .{ .size = want * @sizeOf(f32), .key = @intFromEnum(Readback.audio) });
}
const l = Layout.of(in.width, in.height, s.instrument);
diff --git a/examples/spheres/test/play.script b/examples/spheres/test/play.script
index 1b06372..8dbe978 100644
--- a/examples/spheres/test/play.script
+++ b/examples/spheres/test/play.script
@@ -1,6 +1,8 @@
# Plays each preset and synthesis mode headless; screenshots land in
# .zig-cache/spheres/ for review.
frames 120
+# The GPU's blocks reach the speakers' stream.
+expect-audio 1
expect running true
expect preset figure_eight
screenshot .zig-cache/spheres/figure-eight.png
diff --git a/src/abi.zig b/src/abi.zig
index 35c399b..2e80a35 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -165,6 +165,9 @@ pub const Stream = struct {
queued: u32 = 0,
/// Samples pushed since the stream was last cleared.
pushed: u64 = 0,
+ /// Pushes that found it empty though the frame before had pushed to
+ /// it: each a gap in its sound.
+ underruns: u32 = 0,
};
/// Everything a sketch learns about the world for one call.
@@ -218,6 +221,11 @@ pub const Input = struct {
keys: std.StaticBitSet(256) = .empty,
streams: []const Stream = &.{},
sample_rate: u32 = 48_000,
+ /// How many samples a stream should hold after this frame's push, as
+ /// the host measures it: enough to outlast the slowest recent frame and
+ /// the device's next pull, and more after an underrun. A sketch that
+ /// makes its sound as it goes pushes `lead -| stream(key).queued`.
+ lead: u32 = 4800,
/// Mono samples at `sample_rate` recorded since the previous frame, while
/// `draw` declares `Command.microphone`. Only `draw` sees them: they come
/// from a device, not from events, so they do not replay.
@@ -313,8 +321,8 @@ pub const Voice = struct {
/// Slices must stay alive until the host consumes the frame, right after
/// `draw` returns. `sketch.Frame` copies the small ones (text, GPU
/// descriptions, uniforms) into scratch memory itself; bulk data (vertices,
-/// samples, pixels, uploads) must already live in scratch, session or store
-/// memory, or be a literal.
+/// samples, pixels, uploads) must already live in scratch or session memory,
+/// or be a literal.
pub const Command = union(enum) {
clear: Color,
rect: struct { dst: Rect, color: Color },
@@ -377,6 +385,12 @@ pub const Command = union(enum) {
voice: Voice,
/// Mono samples at `Input.sample_rate` for stream `key`.
audio: struct { key: u32, samples: []const f32, clear: bool = false },
+ /// `count` mono samples (f32) that a compute shader left in `buffer`
+ /// at `offset`, for stream `key`: queued like `audio`'s once the GPU
+ /// has made them. Natively that is within this frame (the host waits
+ /// for the GPU's work so far); on the web they arrive a frame or two
+ /// later and count as queued meanwhile.
+ audio_buffer: struct { key: u32, buffer: Buffer, offset: u32 = 0, count: u32 },
/// The gain of a group of voices (`Voice.group`) this frame; a group
/// not given one plays at 1. Declared like a voice, so it replays.
gain: struct { group: u3, gain: f32 },
@@ -647,7 +661,9 @@ pub const Host = struct {
samples: *const fn (*anyopaque, Audio) []const f32,
/// The whole file, mapped for the life of the host; empty if missing.
readFile: *const fn (*anyopaque, []const u8) []const u8,
- env: *const fn (*anyopaque, []const u8) ?[]const u8,
+ /// See `Host.appendFile`: name, then bytes; `replace` for `writeFile`.
+ appendFile: *const fn (*anyopaque, [*]const u8, usize, [*]const u8, usize, bool) callconv(.c) [*:0]const u8,
+ env:*const fn (*anyopaque, []const u8) ?[]const u8,
/// A monotonic clock in nanoseconds, for measuring, not for state:
/// `update` must use `Input` time to stay replayable.
clock: *const fn (*anyopaque) u64,
@@ -720,6 +736,21 @@ pub const Host = struct {
pub fn readFile(h: Host, path: []const u8) []const u8 {
return h.vtable.readFile(h.ctx, path);
}
+ /// Appends `bytes` to the sketch's file `name` (no `/` in it),
+ /// creating it: `<stem>.<name>`, beside the save `<stem>.xitdb` (in
+ /// `.sketchbook/` under `zig build run`). Returns the file's path, for
+ /// `readFile`, or "" when nothing was written, which on the web is
+ /// always. Only `draw` and `command` can write, and a write is not
+ /// replayed, like sound. `readFile` maps a file once: what is appended
+ /// to it afterwards is not in what it returned.
+ pub fn appendFile(h: Host, name: []const u8, bytes: []const u8) []const u8 {
+ return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, false));
+ }
+ /// `appendFile` to a new, empty file of that name: what the old one
+ /// held is gone (a `readFile` of it keeps its bytes).
+ pub fn writeFile(h: Host, name: []const u8, bytes: []const u8) []const u8 {
+ return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, true));
+ }
pub fn env(h: Host, name: []const u8) ?[]const u8 {
return h.vtable.env(h.ctx, name);
}
@@ -739,12 +770,8 @@ pub const Context = struct {
/// This process: survives reloads; frees one allocation at a time, and
/// releases the rest when Session's layout changes.
session: std.mem.Allocator,
- /// On disk, next to the state file: survives reloads and restarts, at
- /// the same addresses, so Store may point into it.
- store: std.mem.Allocator,
- /// The sketch's `Session` and `Store` values.
+ /// The sketch's `Session` value.
session_root: [*]u8,
- store_root: [*]u8,
/// Filled by `draw`, using `scratch`.
commands: *std.ArrayList(Command),
};
@@ -793,20 +820,19 @@ pub const Info = struct {
height: u32,
state: Layout,
session: Layout,
- store: Layout,
/// Console completions offered by the sketch.
commands: []const []const u8 = &.{},
/// What the sketch was built from: its repository's revision ("jj:<commit>
/// <change>", "git:<sha>[+dirty]", or nothing), then `build`. Each
/// stretch of a recorded session keeps it.
source: []const u8 = "",
- /// Whether the host records sessions to a file (`App.Options.record`;
- /// Debug builds do unless told otherwise).
+ /// Whether the save keeps history, or only the present and the marks
+ /// (`App.Options.record`; Debug builds keep it unless told otherwise).
record: bool = false,
};
/// Which memory `sketch_defaults` fills.
-pub const Memory = enum(u8) { state, session, store };
+pub const Memory = enum(u8) { state, session };
/// The entry points of a sketch, exported from libraries under these names.
/// What became of a console line offered to a sketch.
@@ -828,8 +854,7 @@ pub const Sketch = struct {
setup: *const fn (*const Context) callconv(.c) bool,
/// Deterministic: new state from state and input, nothing else.
update: *const fn (*const Context, [*]u8) callconv(.c) void,
- /// Presentation: reads state, may change session and store, appends
- /// commands.
+ /// Presentation: reads state, may change session, appends commands.
draw: *const fn (*const Context, [*]const u8) callconv(.c) void,
/// A console line the host did not understand.
command: *const fn (*const Context, [*]u8, *const []const u8) callconv(.c) Outcome,
diff --git a/src/gpu/Executor.zig b/src/gpu/Executor.zig
index 460b2d5..797dcbf 100644
--- a/src/gpu/Executor.zig
+++ b/src/gpu/Executor.zig
@@ -503,6 +503,32 @@ pub fn download(g: *Gpu, d: @FieldType(abi.Command, "download")) !void {
};
}
+/// Copies `out.len` bytes of a buffer from `offset` back now, waiting for
+/// the GPU to finish the work submitted before (sound that must be queued
+/// this frame).
+pub fn read(g: *Gpu, buffer: abi.Buffer, offset: u32, out: []u8) !void {
+ const source = g.storage(buffer) orelse return error.UnknownBuffer;
+ const size: u32 = @intCast(out.len);
+ if (size == 0 or @as(u64, offset) + size > source.size) return error.DownloadOutOfBounds;
+ const transfer = for (g.spare.items, 0..) |t, i| {
+ if (t.size >= size) break g.spare.swapRemove(i);
+ } else Transfer{
+ .buffer = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }) orelse return error.GpuBuffer,
+ .size = size,
+ };
+ defer g.spare.append(g.gpa, transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, transfer.buffer);
+ const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer;
+ const copy = c.SDL_BeginGPUCopyPass(cmd);
+ c.SDL_DownloadFromGPUBuffer(copy, &.{ .buffer = source.buffer, .offset = offset, .size = size }, &.{ .transfer_buffer = transfer.buffer, .offset = 0 });
+ c.SDL_EndGPUCopyPass(copy);
+ const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
+ defer c.SDL_ReleaseGPUFence(g.device, fence);
+ if (!c.SDL_WaitForGPUFences(g.device, true, &fence, 1)) return error.GpuFence;
+ const mapped: [*]const u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer.buffer, false) orelse return error.GpuMap);
+ defer c.SDL_UnmapGPUTransferBuffer(g.device, transfer.buffer);
+ @memcpy(out, mapped[0..size]);
+}
+
/// The downloads the GPU has finished, copied into `arena`, in the order
/// they were asked for.
pub fn collect(g: *Gpu, arena: std.mem.Allocator) ![]const abi.Download {
diff --git a/src/host/Console.zig b/src/host/Console.zig
index 75da732..0d4cda0 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -350,7 +350,7 @@ fn listSessions(self: *Console, host: *Host) !void {
switch (s.mode()) {
.file => self.print("recording to {s}", .{s.path}),
.memory => self.log("recording in memory (scripted run)"),
- .off => return self.log("not recording (release build: .record = true collects)"),
+ .off => return self.log("not recording (an export)"),
}
const n = try s.count(.sessions);
var i = n -| 4;
@@ -457,10 +457,13 @@ fn listNamed(self: *Console, host: *Host, marks: bool) !void {
var i = n -| 5;
while (i < n) : (i += 1) {
const e = if (marks) try s.markAt(i) else try s.clipAt(i);
- const key = try s.load(e.session, e.key);
- defer key.free(host.gpa);
const label = e.name();
if (marks) {
+ // An older mark of a name may have gone with history.
+ const key = s.keyAt(e.session, e.key) catch {
+ self.print("#{d} {s}: session {d}, dropped", .{ i, label, e.session });
+ continue;
+ };
self.print("#{d} {s}: session {d} frame {d}", .{ i, label, e.session, key.frame });
} else self.print("#{d} {s}: session {d} frames {d}..{d}", .{ i, label, e.session, e.start, e.end });
}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 4f1214a..002c704 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -27,15 +27,17 @@ pub const Options = struct {
library: ?[]const u8 = null,
/// Local 9P control socket, opt-in.
ninep: ?[]const u8 = null,
- /// State file; the sessions database goes next to it, `<name>.xitdb`
- /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.state`
+ /// The save, a sessions database: `<stem>.xitdb`, for a path
+ /// `<stem>.xitdb`, `<stem>.state` (where a state file from before is
+ /// imported from) or `<stem>`. Empty: `$XDG_DATA_HOME/<name>/<name>.xitdb`
/// (`~/.local/share` without it), for a shipped game.
state: []const u8 = "",
/// Playing a script: from fresh state, sessions go to memory only.
script: bool = false,
/// Offscreen video, silent audio, no vsync: for scripts and CI.
headless: bool = false,
- /// Forget the state file's contents: scripts start from a known place.
+ /// Start from State's defaults, not the save's present: scripts start
+ /// from a known place.
fresh: bool = false,
/// Time every GPU command alone and print the times at exit.
profile_gpu: bool = false,
@@ -70,11 +72,10 @@ images: gfx.Images,
/// Plays the 2D commands: targets, blend, antialiased shapes.
painter: gfx.Painter,
audio: sound.Audio,
-state: memory.StateFile,
+state: memory.State,
session: memory.Session,
/// A failed resource setup disables app callbacks while keeping host controls alive.
session_ready: bool = false,
-store: memory.StoreFile,
/// Images and buffers the sketch made (`newImage`, `decodeImage`,
/// `newBuffer`): Session holds their handles, so they go when it resets.
made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList(abi.Buffer) = .empty } = .{},
@@ -92,8 +93,11 @@ reloads: usize = 0,
/// file's inode, size and modification time): sessions' stretches carry it,
/// and `play` warns on a mismatch.
build: u64 = 0,
-/// The state file's path when the host chose it (`Options.state`), `gpa`'s.
+/// The save's path when the host chose it (`Options.state`), `gpa`'s.
state_path: []const u8 = "",
+/// `Options.state` without `.xitdb` or `.state`: the save is
+/// `<stem>.xitdb`, the sketch's own files `<stem>.<name>`.
+stem: []const u8 = "",
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
@@ -107,6 +111,11 @@ commands: std.ArrayList(abi.Command) = .empty,
pending: std.ArrayList(abi.Event) = .empty,
input: abi.Input = .{},
files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty,
+/// Mappings of files `writeFile` replaced: the sketch may still hold them.
+retired: std.ArrayList([]align(memory.page) const u8) = .empty,
+/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps
+/// them.
+written: std.StringHashMapUnmanaged(void) = .empty,
canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
@@ -172,21 +181,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
var data_buf: [std.fs.max_path_bytes]u8 = undefined;
const state_path = if (given.state.len > 0) "" else blk: {
const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."});
- const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.state", .{ data, info.name, info.name });
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.xitdb", .{ data, info.name, info.name });
errdefer gpa.free(path);
try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?);
break :blk path;
};
errdefer gpa.free(state_path);
if (state_path.len > 0) options.state = state_path;
- var state = try memory.StateFile.open(gpa, options.state);
- errdefer state.close();
- var store_buf: [std.fs.max_path_bytes]u8 = undefined;
- var store = memory.StoreFile.open(gpa, try std.mem.print(&store_buf, "{s}.store", .{options.state}), options.fresh) catch |err| {
- if (err == error.StoreInUse) std.log.err("{s}.store is open in another process", .{options.state});
- return err;
- };
- errdefer store.close();
self.* = .{
.gpa = gpa,
@@ -199,14 +200,14 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.images = .{ .gpa = gpa, .renderer = renderer.? },
.painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null },
.audio = .{ .gpa = gpa },
- .state = state,
+ .state = .init(gpa),
.session = .init(gpa),
- .store = store,
.timeline = undefined,
.sessions = .{ .gpa = gpa, .io = io },
.sketch = sketch,
.library = library,
.state_path = state_path,
+ .stem = stemOf(options.state),
.info_arena = .init(gpa),
.frame_arena = .init(gpa),
.input = .{ .exporting = options.export_to != null },
@@ -227,10 +228,8 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
self.build = fileId(io, options.library orelse "/proc/self/exe");
try self.adopt(sketch);
self.openSessions(info.record);
- // Before --fresh: it never touches the history.
- if (importSnapshots(&self.state, &self.sessions)) |n| {
- if (n > 0) self.print("{d} snapshots of {s} are marks now", .{ n, options.state });
- } else |err| self.print("snapshots of {s} kept in it: {t}", .{ options.state, err });
+ // Before --fresh, which never touches the save.
+ self.openPresent();
if (options.fresh) self.resetState();
if (!options.headless and options.export_to == null) {
self.presentation = Presentation.init(gpa, self.window) catch null;
@@ -259,12 +258,21 @@ pub fn deinit(self: *Host) void {
std.posix.munmap(entry.value_ptr.*);
}
self.files.deinit(self.gpa);
+ for (self.retired.items) |bytes| std.posix.munmap(bytes);
+ self.retired.deinit(self.gpa);
+ // A scripted run from fresh state, or an export, leaves no files.
+ const private = (self.options.script or self.options.export_to != null) and self.options.fresh;
+ var written = self.written.keyIterator();
+ while (written.next()) |path| {
+ if (private) std.Io.Dir.cwd().deleteFile(self.io, path.*) catch {};
+ self.gpa.free(path.ptr[0 .. path.len + 1]);
+ }
+ self.written.deinit(self.gpa);
self.timeline.deinit();
self.session.deinit(self.gpa);
- self.store.close();
self.made.images.deinit(self.gpa);
self.made.buffers.deinit(self.gpa);
- self.state.close();
+ self.state.deinit(self.gpa);
self.pending.deinit(self.gpa);
self.frame_arena.deinit();
self.info_arena.deinit();
@@ -329,7 +337,7 @@ test "timing clock drives ordinary ticks without moving input or replay time" {
}
pub fn live(self: *Host) []u8 {
- return self.state.slot(0);
+ return self.state.live();
}
/// One frame: reload if a build replaced the library, feed input through
@@ -478,6 +486,7 @@ fn draw(self: *Host, now: u64, started: u64) !u64 {
}
}
self.input.streams = self.audio.streamStatus();
+ self.input.lead = self.audio.lead;
self.input.sample_rate = sound.sample_rate;
self.input.microphone = self.audio.record(arena);
self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{};
@@ -505,6 +514,10 @@ fn draw(self: *Host, now: u64, started: u64) !u64 {
.voice => |voice| self.audio.declare(voice),
.gain => |g| self.audio.gains[g.group] = g.gain,
.audio => |a| self.audio.push(a.key, a.samples, a.clear),
+ .audio_buffer => |a| if (self.passes) |*g| if (a.count > 0) {
+ const samples = try arena.alloc(f32, a.count);
+ if (g.read(a.buffer, a.offset, std.mem.sliceAsBytes(samples))) self.audio.push(a.key, samples, false) else |err| self.print("gpu audio: {t} ({s})", .{ err, c.SDL_GetError() });
+ },
.quit => self.quit = true,
.gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }),
.post_process => |p| if (self.passes) |*g| self.runPostProcess(g, p.source, p.target, p.effect) catch |err| self.print("gpu postprocess: {t} ({s})", .{ err, c.SDL_GetError() }),
@@ -652,9 +665,7 @@ fn context(self: *Host) abi.Context {
.input = &self.input,
.scratch = self.frame_arena.allocator(),
.session = self.session.heap.allocator(),
- .store = self.store.allocator(),
.session_root = self.session.bytes.ptr,
- .store_root = self.store.root(),
.commands = &self.commands,
};
}
@@ -697,7 +708,11 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
const replay = self.console.execute(self, line, now) catch |err| {
// The sketch has printed its own error already.
if (err == error.NotRecording) {
- self.console.log("Not recording (a release build: .record = true collects): no marks or clips.");
+ self.console.log("Not recording (an export): no marks or clips.");
+ } else if (err == error.HistoryDropped) {
+ self.console.log("That part of the history is gone: a save keeps 64 MiB, the newest.");
+ } else if (err == error.SaveFull) {
+ self.console.log("No room for a new mark: marks and the present fill the save. Save over a mark's name (its older one goes with history), or start another save (--state).");
} else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
if (self.timeline.restored) self.jumped = true;
try self.restoredInput(now);
@@ -739,7 +754,6 @@ pub fn resetState(self: *Host) void {
self.sketch.defaults(.state, bytes.ptr);
const ctx = self.context();
self.sketch.init(&ctx, bytes.ptr);
- self.state.markUsed(0, true);
}
/// Loads the watched library again.
@@ -758,17 +772,16 @@ pub fn load(self: *Host, path: []const u8) !void {
self.library = library;
self.reloads += 1;
self.build = fileId(self.io, path);
- self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() }) catch |err| self.print("session: {t}", .{err});
+ self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.header }) catch |err| self.print("session: {t}", .{err});
self.print("reload {d}: {s}", .{ self.reloads, path });
}
fn adopt(self: *Host, sketch: abi.Sketch) !void {
const info = sketch.info();
if (info.abi != abi.hash) return error.AbiMismatch;
- const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults);
+ const migrated = try self.state.adopt(self.gpa, info.state, sketch.defaults);
const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults);
if (session_reset) self.releaseMade();
- const stored = try self.store.adopt(self.gpa, info.store, sketch.defaults);
_ = self.info_arena.reset(.retain_capacity);
const arena = self.info_arena.allocator();
self.name = try arena.dupe(u8, info.name);
@@ -779,22 +792,13 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void {
self.sketch = sketch;
self.timeline.defaults = sketch.defaults;
self.reloaded = true;
- switch (adoption) {
- .unchanged => {},
- .created => {},
- .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
- }
- if (!self.state.used(0)) self.resetState();
+ if (migrated) |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset });
if (session_reset) {
const ctx = self.context();
self.session_ready = self.sketch.setup(&ctx);
if (!self.session_ready) self.console.visible = true;
}
if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{});
- switch (stored) {
- .unchanged, .created => {},
- .migrated => |m| self.print("store layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
- }
}
/// Frees what the old Session made: its handles are gone with it.
@@ -938,42 +942,88 @@ fn consoleKey(e: abi.Event) ?Console.Key {
};
}
-/// Starts this run's session (Sessions.zig): in a file beside the state
-/// file when the build records, in memory for a script from fresh state,
-/// nowhere for an export. A database that cannot be opened is said, and
-/// the run goes on unrecorded.
+/// Opens the save (Sessions.zig) and starts this run's session in it: a
+/// file, `<stem>.xitdb`; in memory for a script from fresh state; nowhere
+/// for an export. A save that cannot be opened is said, and the run goes
+/// on unsaved.
fn openSessions(self: *Host, record: bool) void {
const o = self.options;
- const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else if (record) .file else .off;
+ const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else .file;
var buf: [std.fs.max_path_bytes]u8 = undefined;
- const stem = if (std.mem.endsWith(u8, o.state, ".state")) o.state[0 .. o.state.len - ".state".len] else o.state;
- const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{stem}) catch "sketch.xitdb";
- const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() };
+ const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{self.stem}) catch "sketch.xitdb";
+ const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.header };
self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: {
- self.print("not recording: {s}: {t}", .{ path, err });
+ self.print("not saved: {s}: {t}", .{ path, err });
break :blk .{ .gpa = self.gpa, .io = self.io };
};
- if (o.headless) return;
- switch (self.sessions.mode()) {
- .file => self.print("recording to {s}", .{path}),
- .memory => {},
- .off => if (o.export_to == null) self.print("not recording (release build: .record = true collects)", .{}),
- }
+ // Without `.record`, history is trimmed to the present and the marks.
+ self.sessions.history = record;
+ if (o.headless or self.sessions.mode() != .file) return;
+ self.print("{s} to {s}", .{ if (record) "recording" else "saving", path });
}
-/// Snapshots of a state file from before sessions become marks "1".."7",
-/// then the file holds live state only. While nothing records, they stay.
-fn importSnapshots(state: *memory.StateFile, sessions: *Sessions) !usize {
- if (state.slots == 1 or sessions.mode() == .off) return 0;
+/// The State this run starts from: the save's present, its newest keyframe
+/// and the frames logged after it, replayed; in a new save, a state file
+/// from before (`<stem>.state`), imported once and left as it was; else
+/// `init`'s.
+fn openPresent(self: *Host) void {
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(self.gpa);
+ const found = self.sessions.present(&events) catch |err| blk: {
+ self.print("the save's present did not read ({t}): starting from defaults", .{err});
+ break :blk null;
+ };
+ const key = found orelse {
+ if (self.sessions.session != 0 or self.sessions.mode() != .file) return self.resetState();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const old = std.fmt.bufPrint(&buf, "{s}.state", .{self.stem}) catch return self.resetState();
+ const n = importOld(self.gpa, old, &self.state, &self.sessions, self.sketch.defaults) catch |err| {
+ if (err != error.FileNotFound) self.print("{s} not imported ({t}): kept as it was", .{ old, err });
+ return self.resetState();
+ };
+ return self.print("{s} imported: its State, and {d} snapshots as marks; the file is kept as it was", .{ old, n });
+ };
+ defer key.free(self.gpa);
+ self.timeline.restore(key) catch |err| {
+ self.print("the save's present did not restore ({t}): starting from defaults", .{err});
+ return self.resetState();
+ };
+ self.timeline.restored = false;
+ var frames: usize = 0;
+ for (events.items) |e| frames += @intFromBool(e.kind == .tick);
+ if (frames == 0) return;
+ if (key.build != self.build) return self.print("{d} frames played after the save's last keyframe not replayed: another build", .{frames});
+ // As they were fed: `started` only for a run's first frame.
+ self.started = key.frame == 0;
+ self.update(events.items);
+ self.started = true;
+}
+
+/// A state file from before (`path`) into a new save: its live State into
+/// `state`, its snapshots (slots 1..7) marks "1".."7", in `state`'s layout;
+/// the file is left as it was. Returns the number of marks.
+fn importOld(gpa: std.mem.Allocator, path: []const u8, state: *memory.State, sessions: *Sessions, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !usize {
+ const old = try memory.OldState.open(path);
+ defer old.close();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const scratch = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), state.layout.size);
var n: usize = 0;
- for (1..state.slots) |i| if (state.used(i)) {
- _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, state.slot(i));
+ for (1..old.slots) |i| if (old.slot(i)) |image| {
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), image, state.layout, scratch, defaults);
+ _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, scratch);
n += 1;
};
- try state.dropSnapshots();
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), old.slot(0) orelse return error.CorruptStateFile, state.layout, state.live(), defaults);
return n;
}
+/// `path` without `.xitdb` or `.state`.
+pub fn stemOf(path: []const u8) []const u8 {
+ for ([_][]const u8{ ".xitdb", ".state" }) |suffix| if (std.mem.endsWith(u8, path, suffix)) return path[0 .. path.len - suffix.len];
+ return path;
+}
+
fn wallClock(io: std.Io) u64 {
return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds));
}
@@ -1014,6 +1064,7 @@ const api: abi.Host.VTable = .{
.newSound = apiNewSound,
.samples = apiSamples,
.readFile = apiReadFile,
+ .appendFile = apiAppendFile,
.env = apiEnv,
.clock = apiClock,
};
@@ -1090,6 +1141,47 @@ fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
self.files.put(self.gpa, key, bytes) catch self.gpa.free(key);
return bytes;
}
+fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize, replace: bool) callconv(.c) [*:0]const u8 {
+ const self = hostOf(ctx);
+ const name = name_ptr[0..name_len];
+ if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) {
+ self.print("appendFile: {s}: a name, not a path", .{name});
+ return "";
+ }
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const o = self.options;
+ const private = (o.script or o.export_to != null) and o.fresh;
+ // A scripted run from fresh state, or an export, writes files of its own
+ // (two runs of one build step may share a directory), gone at exit.
+ const path = (if (private) std.mem.print(&buf, "{s}.{d}.{s}", .{ self.stem, std.os.linux.getpid(), name }) else std.mem.print(&buf, "{s}.{s}", .{ self.stem, name })) catch return "";
+ if (replace) {
+ // A new file: a mapping of the old one stays valid.
+ std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
+ if (self.files.fetchRemove(path)) |old| {
+ self.gpa.free(old.key);
+ self.retired.append(self.gpa, old.value) catch {};
+ }
+ }
+ const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ defer file.close(self.io);
+ const end = file.length(self.io) catch return "";
+ file.writePositionalAll(self.io, bytes[0..len], end) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ const kept = self.written.getOrPut(self.gpa, path) catch return "";
+ if (!kept.found_existing) {
+ const copy = self.gpa.dupeSentinel(u8, path, 0) catch {
+ self.written.removeByPtr(kept.key_ptr);
+ return "";
+ };
+ kept.key_ptr.* = copy;
+ }
+ return @ptrCast(kept.key_ptr.*.ptr);
+}
fn apiClock(_: *anyopaque) u64 {
return c.SDL_GetTicksNS();
}
@@ -1119,11 +1211,10 @@ test "session setup runs for restored state and layout reset, not same-layout re
const State = extern struct { value: u32 = 1 };
const Session1 = extern struct { ready: u32 = 0 };
const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 };
- const Store = struct {};
var setup_calls: usize = 0;
var init_calls: usize = 0;
var fail_setup = false;
- const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) };
+ const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session) };
const changed: abi.Info = blk: {
var value = description;
value.session = abi.layout.of(Session2, .session);
@@ -1139,7 +1230,6 @@ test "session setup runs for restored state and layout reset, not same-layout re
switch (kind) {
.state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
.session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{},
- .store => {},
}
}
fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void {
@@ -1164,26 +1254,11 @@ test "session setup runs for restored state and layout reset, not same-layout re
Fixture.init_calls = 0;
Fixture.fail_setup = false;
const a = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var state_buf: [std.fs.max_path_bytes]u8 = undefined;
- var store_buf: [std.fs.max_path_bytes]u8 = undefined;
- const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path});
- const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&tmp.sub_path});
- {
- var state = try memory.StateFile.open(a, state_path);
- defer state.close();
- _ = try state.adopt(a, Fixture.description.state, Fixture.defaults);
- @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77;
- state.markUsed(0, true);
- }
- // Exercise adoption with real persisted memory, without opening SDL devices.
+ // Exercise adoption without opening SDL devices.
var host: Host = undefined;
host.gpa = a;
- host.state = try memory.StateFile.open(a, state_path);
- defer host.state.close();
- host.store = try memory.StoreFile.open(a, store_path, false);
- defer host.store.close();
+ host.state = .init(a);
+ defer host.state.deinit(a);
host.session = .init(a);
defer host.session.deinit(a);
host.info_arena = .init(a);
@@ -1198,7 +1273,8 @@ test "session setup runs for restored state and layout reset, not same-layout re
host.input = .{};
host.commands = .empty;
try host.adopt(Fixture.sketch);
- try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
+ // Defaults: the present or `init` comes after (openPresent).
+ try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls);
try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
const session_ptr = host.session.bytes.ptr;
@@ -1239,7 +1315,7 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload
try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data"));
}
-test "a state file's snapshots from before sessions become marks, and the file one slot" {
+test "a state file from before imports into a new save: its State live, its snapshots marks, the file as it was" {
const State = extern struct { v: u32 = 0 };
const D = struct {
fn f(_: abi.Memory, p: [*]u8) callconv(.c) void {
@@ -1252,32 +1328,24 @@ test "a state file's snapshots from before sessions become marks, and the file o
defer tmp.cleanup();
var buf: [std.fs.max_path_bytes]u8 = undefined;
const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path});
- // An eight-slot SKETCH02 file, slots 0, 1 and 3 used: built from a new
- // one-slot file's header.
- {
- var file = try memory.StateFile.open(gpa, path);
- defer file.close();
- _ = try file.adopt(gpa, abi.layout.of(State, .state), D.f);
- }
- const one = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
- defer gpa.free(one);
+ var state: memory.State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, abi.layout.of(State, .state), D.f);
+ // An eight-slot SKETCH02 file, slots 0, 1 and 3 used, its header State's.
const stride = memory.page;
const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride);
defer gpa.free(old);
@memset(old, 0);
- @memcpy(old[0..memory.header_len], one[0..memory.header_len]);
+ @memcpy(old[0..state.header.len], state.header);
const h: *memory.Header = @ptrCast(@alignCast(old.ptr));
h.magic = memory.file_magic_v2;
h.used = 0b1011;
for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little);
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old });
- var state = try memory.StateFile.open(gpa, path);
- defer state.close();
- try std.testing.expectEqual(memory.old_slot_count, state.slots);
- var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.layoutBytes() }, 0);
+ var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.header }, 0);
defer sessions.deinit();
- try std.testing.expectEqual(@as(usize, 2), try importSnapshots(&state, &sessions));
+ try std.testing.expectEqual(@as(usize, 2), try importOld(gpa, path, &state, &sessions, D.f));
for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| {
const m = (try sessions.findMark(&.{@intCast(want[0])})).?;
const key = try sessions.load(m.session, m.key);
@@ -1286,12 +1354,39 @@ test "a state file's snapshots from before sessions become marks, and the file o
try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little));
}
try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2"));
- // One slot now, live state kept, and it reopens so.
- try std.testing.expectEqual(@as(usize, 1), state.slots);
- try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.slot(0)[0..4], .little));
- var again = try memory.StateFile.open(gpa, path);
- defer again.close();
- try std.testing.expectEqualStrings(&memory.file_magic, &again.header().magic);
- try std.testing.expectEqual(@as(usize, 1), again.slots);
- try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, again.slot(0)[0..4], .little));
+ try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.live()[0..4], .little));
+ const after = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, old, after);
+}
+
+test "appendFile appends to a file beside the save and names it for readFile" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ var host: Host = undefined;
+ host.gpa = std.testing.allocator;
+ host.io = io;
+ host.written = .empty;
+ host.files = .empty;
+ host.options = .{};
+ host.stem = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t", .{&tmp.sub_path});
+ defer {
+ var written = host.written.keyIterator();
+ while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]);
+ host.written.deinit(host.gpa);
+ }
+ const name = "take-1.f32";
+ const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false));
+ try std.testing.expect(std.mem.endsWith(u8, path, "/t.take-1.f32"));
+ try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false));
+ const bytes = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(bytes);
+ try std.testing.expectEqualStrings("abcd", bytes);
+ // writeFile: a new file, its old bytes gone.
+ _ = apiAppendFile(&host, name, name.len, "e", 1, true);
+ const again = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(again);
+ try std.testing.expectEqualStrings("e", again);
}
diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig
index 751961d..cf0ab24 100644
--- a/src/host/Sessions.zig
+++ b/src/host/Sessions.zig
@@ -1,7 +1,8 @@
-//! Every run of a sketch, recorded: one xitdb database per sketch, beside
-//! its state file, holding an append-only log of the frames live `update`
-//! was fed, and the State at the moments that matter (keyframes). Nothing
-//! in it is ever overwritten: marks and clips are names pointing into it.
+//! A sketch's save: one xitdb database holding every run of it, an
+//! append-only log of the frames live `update` was fed, and the State at
+//! the moments that matter (keyframes). The newest keyframe and the frames
+//! after it are the present a run starts from (`present`). Nothing in it
+//! is ever overwritten: marks and clips are names pointing into it.
//!
//! root = map {
//! version 1
@@ -14,20 +15,33 @@
//! started wall-clock ns at open ended ns at a clean exit, else 0
//! from "" or where it came from ("import <file>")
//! stretches list of { frame, build, source, layout }: one a load (start, reloads);
-//! `layout` is the state file's header (memory.readLayout reads it)
+//! `layout` is State's header (memory.State.header, read by memory.layoutOf)
//! batches list of bytes: a little-endian u64, the first frame's index, then
//! whole frames of raw `abi.Event`s, each frame ending with its tick
-//! keys list of { frame, batch, stretch, why, time, state, line }: the
-//! State before frame `frame` is fed, in stretch `stretch`'s layout;
-//! `batch` is where reading frames from it starts
+//! keys list of { frame, batch, stretch, why, time, size, pages, written, line }:
+//! the State before frame `frame` is fed, in stretch `stretch`'s
+//! layout; `batch` is where reading frames from it starts
//! frames frames committed
//! }
//!
+//! A keyframe's State is `size` bytes in `pages`, a list of `page`-byte
+//! blobs (the last one shorter), an all-zero page an empty slot. A keyframe
+//! starts from the list of the one before it and writes only the pages
+//! whose hash changed (`written` bytes), so every page another keyframe
+//! holds unchanged is shared, never written twice. (Keyframes from before
+//! pages hold their State whole, as `state` bytes; `load` reads both.)
+//!
//! One transaction (`commit`) a second of session time, and at once for a
//! reload, a mark, a clip's start or end, and exit: a crash loses less than
//! a second of play; fsync only at exit and for a mark. A file a crash or
-//! power loss tore opens at its last whole commit (`mend`); a clean exit
-//! compacts one that commits left past twice its contents (`close`).
+//! power loss tore opens at its last whole commit (`mend`).
+//!
+//! A save is at most `max_save`: a commit that leaves the file past it
+//! drops history oldest first and compacts the file to three quarters of
+//! it (`trim`); the present, the newest mark of each name and the newest
+//! clip of each name are never dropped. A build that does not record
+//! (`history` false) drops all it may at every keyframe, and compacts at
+//! exit: what it keeps is the present and the marks.
const Sessions = @This();
const std = @import("std");
const xitdb = @import("xitdb");
@@ -36,9 +50,8 @@ const abi = @import("abi");
pub const Disk = xitdb.Database(.buffered_file, u64);
pub const Memory = xitdb.Database(.memory, u64);
-/// `file` for interactive runs of a build that records, `memory` for a
-/// scripted run from fresh state (time travel, nothing on disk), `off`
-/// otherwise (an export, a release build).
+/// `file` for every run but two: `memory` for a scripted run from fresh
+/// state (time travel, nothing on disk), `off` for an export.
pub const Mode = enum { off, memory, file };
pub const Why = enum(u64) { start, periodic, jump, before_reload, after_reload, mark, exit, import };
@@ -52,15 +65,27 @@ pub const max_name = 32;
/// A memory database (a scripted run's) stops recording at this size: ten
/// hours or more of play at 60 Hz. What it holds stays readable.
pub const memory_max: u64 = 256 << 20;
+/// The most a save's file holds (State is at most half of it,
+/// `abi.layout.max_state`, so history has room).
+pub const max_save: u64 = 64 << 20;
-pub const K = enum(u64) { version = 1, sessions, marks, clips, started, ended, from, stretches, batches, keys, frames, frame, build, source, layout, batch, stretch, why, time, state, line, name, session, key, start, end };
+pub const K = enum(u64) { version = 1, sessions, marks, clips, started, ended, from, stretches, batches, keys, frames, frame, build, source, layout, batch, stretch, why, time, state, line, name, session, key, start, end, pages, size, written };
fn key(k: K) u64 {
return @intFromEnum(k);
}
pub const Stretch = struct { frame: u64 = 0, build: u64, source: []const u8, layout: []const u8 };
-const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, state: []u8, line: []u8 };
+/// A keyframe's page: the OS page, the grain of sharing.
+pub const page = 4096;
+
+/// A keyframe: `session`'s keyframe `key`.
+const At = struct { session: u64, key: u64 };
+
+/// A keyframe queued: the pages of its State that differ from keyframe
+/// `from`'s (`indices`, ascending; their bytes one after the other in
+/// `pages`, `page` apart).
+const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, size: u64, from: ?At, indices: []u64, pages: []u8, line: []u8 };
gpa: std.mem.Allocator,
/// Files and the wall clock; a memory database runs on `std.Io.failing`.
@@ -89,10 +114,13 @@ batch_time: u64 = 0,
/// The first and latest event time logged: times never go back.
first_time: u64 = 0,
last_time: u64 = 0,
-/// The last keyframe's time, stretch and bytes' hash.
+/// The last keyframe's time and stretch.
key_time: u64 = 0,
key_stretch: u64 = 0,
-key_hash: u64 = 0,
+/// The keyframe the next one starts from (the last one, or the one a run
+/// started from), and the hashes of its pages.
+last: ?At = null,
+hashes: []u64 = &.{},
queued: std.ArrayList(Keyframe) = .empty,
/// The clip being recorded, an index into `clips`.
recording: ?u64 = null,
@@ -104,6 +132,8 @@ full: bool = false,
/// The console line that last changed State, for the next keyframe.
line: [256]u8 = undefined,
line_len: usize = 0,
+/// Keep history, up to `max_save`; else only the present and the marks.
+history: bool = true,
/// Opens the database at `path` (file mode: created with its directory when
/// missing; one a crash or power loss tore is opened at its last whole
@@ -165,6 +195,7 @@ pub fn deinit(s: *Sessions) void {
s.dropQueued();
s.queued.deinit(s.gpa);
s.batch.deinit(s.gpa);
+ s.gpa.free(s.hashes);
if (s.file) |f| f.close(s.io);
if (s.buffer) |b| {
b.deinit();
@@ -175,43 +206,212 @@ pub fn deinit(s: *Sessions) void {
}
/// The last frames, an exit keyframe of `state`, and the session's end, in
-/// one transaction synced to disk; then closed.
+/// one transaction synced to disk; then closed. Without history the file is
+/// compacted, so the frames it dropped are gone from the disk too.
pub fn close(s: *Sessions, state: []const u8, ended: u64) void {
defer s.deinit();
if (s.db == .off) return;
s.stopClip() catch {};
_ = s.keyframe(.exit, state) catch {};
s.commitSynced(.{ .end = ended }) catch |err| std.log.warn("sessions: last commit failed: {t}", .{err});
- if (s.db != .file) return;
- const size = s.file.?.length(s.io) catch return;
- if (size < compact_floor) return;
- const live = liveSize(&s.db.file) catch return;
- if (size > 2 * live + compact_floor) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
+ if (s.db == .file and !s.history) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
}
-/// The database's file compacted at a clean exit, once it is past twice what
-/// its batches and keyframes hold plus this: every commit leaves the
-/// nodes it copied behind.
-const compact_floor: u64 = 64 << 20;
-
/// Writes what the database holds now, without the nodes commits left
-/// behind, to `<path>.new`, synced, and renames it over the file.
+/// behind, to `<path>.new`, synced, renames it over the file, and goes on
+/// in it.
fn compact(s: *Sessions) !void {
const cwd = std.Io.Dir.cwd();
var buf: [std.fs.max_path_bytes + 8]u8 = undefined;
const new = try std.fmt.bufPrint(&buf, "{s}.new", .{s.path});
const file = try cwd.createFile(s.io, new, .{ .read = true, .truncate = true });
- errdefer cwd.deleteFile(s.io, new) catch {};
- defer file.close(s.io);
- var buffer: std.Io.Writer.Allocating = .init(s.gpa);
- defer buffer.deinit();
+ errdefer {
+ file.close(s.io);
+ cwd.deleteFile(s.io, new) catch {};
+ }
+ const buffer = try s.gpa.create(std.Io.Writer.Allocating);
+ buffer.* = .init(s.gpa);
+ errdefer {
+ buffer.deinit();
+ s.gpa.destroy(buffer);
+ }
var offsets: std.AutoHashMap(u64, u64) = .init(s.gpa);
defer offsets.deinit();
- _ = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = &buffer, .fsync = true }, &offsets);
+ var db = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = buffer, .fsync = true }, &offsets);
+ db.core.file.fsync = false;
try cwd.rename(new, cwd, s.path, s.io);
+ s.file.?.close(s.io);
+ s.buffer.?.deinit();
+ s.gpa.destroy(s.buffer.?);
+ s.file = file;
+ s.buffer = buffer;
+ s.db = .{ .file = db };
+}
+
+/// Drops history oldest first, then compacts the file: until its keyframes'
+/// pages and frames are under three quarters of `max_save`, or, without
+/// history, all it may (compacted only past `max_save`; `close` does it
+/// at exit). A few rounds at most: what a dropped keyframe wrote may still
+/// be shared by one kept, so a round can free less than it counted.
+fn trim(s: *Sessions) !void {
+ const goal = max_save / 4 * 3;
+ var keep: u64 = if (s.history) goal else 0;
+ for (0..4) |_| {
+ var dropped: u64 = 0;
+ var left: u64 = 0;
+ try s.db.file.runContext(Trim(Disk){ .s = s, .keep = keep, .dropped = &dropped, .left = &left });
+ var size = try s.file.?.length(s.io);
+ if (!s.history and size <= max_save) return;
+ try s.compact();
+ size = try s.file.?.length(s.io);
+ if (size <= goal or dropped == 0) return;
+ // What the count leaves out (lists, maps, stretches) is the rest.
+ keep = left -| (size - goal);
+ }
+}
+
+/// A keyframe's pages or a batch of frames, for `trim`.
+const Item = struct { session: u64, index: u64, frame: u64, bytes: u64, batch: bool, keep: bool };
+
+/// The transaction of `trim`: drops a keyframe by removing its pages (its
+/// fields stay, so keyframe numbers and searches by frame still work) and
+/// a batch by emptying its slot, oldest first, until what is left counts at
+/// most `keep` bytes; a session left with nothing loses its keyframes,
+/// batches and stretches. Never the present (the newest keyframe and the
+/// batches from its own on), the keyframe of the newest mark or clip of a
+/// name, or a batch holding a frame of such a clip.
+fn Trim(comptime DB: type) type {
+ return struct {
+ s: *Sessions,
+ keep: u64,
+ /// Bytes dropped, and counted after.
+ dropped: *u64,
+ left: *u64,
+
+ const R = Read(DB);
+ const Map = DB.HashMap(.read_write);
+ const List = DB.ArrayList(.read_write);
+
+ pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void {
+ var arena: std.heap.ArenaAllocator = .init(ctx.s.gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const root = try Map.init(cursor.*);
+ const all = try R.list(root.readOnly(), .sessions) orelse return;
+ const n = try all.count();
+ var pinned: std.AutoHashMapUnmanaged(At, void) = .empty;
+ const Clip = struct { session: u64, start: u64, end: u64 };
+ var clips: std.ArrayList(Clip) = .empty;
+ for ([_]K{ .marks, .clips }) |which| {
+ const list = try R.list(root.readOnly(), which) orelse continue;
+ var names: std.StringHashMapUnmanaged(void) = .empty;
+ var i = try list.count();
+ while (i > 0) {
+ i -= 1;
+ const e = try R.at(list, i);
+ var buf: [max_name]u8 = undefined;
+ const name = (try R.field(e, .name)).readBytes(&buf) catch return error.CorruptSession;
+ if ((try names.getOrPut(a, try a.dupe(u8, name))).found_existing) continue;
+ const at: At = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) };
+ try pinned.put(a, at, {});
+ const end = if (which == .clips) try R.uint(e, .end) else continue;
+ try clips.append(a, .{ .session = at.session, .start = try R.uint(e, .start), .end = if (end == 0) std.math.maxInt(u64) else end });
+ }
+ }
+ // The present: the newest keyframe, and the batches from its own on.
+ var now: At = undefined;
+ var now_batch: u64 = 0;
+ var i = n;
+ while (true) {
+ if (i == 0) return;
+ i -= 1;
+ const keys = try R.list(try R.at(all, i), .keys) orelse continue;
+ const n_keys = try keys.count();
+ if (n_keys == 0) continue;
+ now = .{ .session = i, .key = n_keys - 1 };
+ now_batch = try R.uint(try R.at(keys, n_keys - 1), .batch);
+ break;
+ }
+ try pinned.put(a, now, {});
+ // What is not dropped yet, each session's in frame order.
+ var items: std.ArrayList(Item) = .empty;
+ var total: u64 = 0;
+ for (0..n) |si| {
+ const ses = try R.at(all, si);
+ const start = items.items.len;
+ if (try R.list(ses, .keys)) |keys| for (0..try keys.count()) |k| {
+ const e = try R.at(keys, k);
+ if (try e.getCursor(key(.pages)) == null) continue;
+ const written = if (try e.getCursor(key(.written))) |w| try w.readUint() else 0;
+ try items.append(a, .{ .session = si, .index = k, .frame = try R.uint(e, .frame), .bytes = written, .batch = false, .keep = pinned.contains(.{ .session = si, .key = k }) });
+ };
+ if (try R.list(ses, .batches)) |batches| for (0..try batches.count()) |b| {
+ var c = try batches.getCursor(@intCast(b)) orelse continue;
+ if ((try c.slot()).tag == .none) continue;
+ var buf: [8]u8 = undefined;
+ var reader = try c.reader(&buf);
+ var head: [8]u8 = undefined;
+ try reader.interface.readSliceAll(&head);
+ try items.append(a, .{ .session = si, .index = b, .frame = std.mem.readInt(u64, &head, .little), .bytes = reader.size, .batch = true, .keep = si == now.session and b >= now_batch });
+ };
+ const mine = items.items[start..];
+ std.mem.sort(Item, mine, {}, struct {
+ fn lessThan(_: void, x: Item, y: Item) bool {
+ return x.frame < y.frame or (x.frame == y.frame and !x.batch and y.batch);
+ }
+ }.lessThan);
+ // A batch holds frames up to the next batch's first.
+ const frames = try R.uint(ses, .frames);
+ var end: u64 = std.math.maxInt(u64);
+ var j = mine.len;
+ while (j > 0) {
+ j -= 1;
+ const it = &mine[j];
+ if (!it.batch) continue;
+ const last = @min(end, frames);
+ for (clips.items) |clip| if (clip.session == si and clip.start < last and it.frame < clip.end) {
+ it.keep = true;
+ };
+ end = it.frame;
+ }
+ for (mine) |it| total += it.bytes;
+ }
+ // Dropped oldest first.
+ const sessions = try List.init(try root.putCursor(key(.sessions)));
+ var left: std.ArrayList(u64) = .empty;
+ try left.appendNTimes(a, 0, n);
+ for (items.items) |it| {
+ if (it.keep or total <= ctx.keep) {
+ left.items[it.session] += 1;
+ continue;
+ }
+ const ses = try Map.init(try sessions.putCursor(@intCast(it.session)));
+ if (it.batch) {
+ try (try List.init(try ses.putCursor(key(.batches)))).put(@intCast(it.index), .{ .slot = null });
+ } else {
+ const k = try Map.init(try (try List.init(try ses.putCursor(key(.keys)))).putCursor(@intCast(it.index)));
+ _ = try k.remove(key(.pages));
+ try k.put(key(.written), .{ .uint = 0 });
+ }
+ total -= it.bytes;
+ ctx.dropped.* += it.bytes;
+ }
+ ctx.left.* = total;
+ for (left.items, 0..) |kept, si| {
+ if (kept > 0 or si >= now.session) continue;
+ var any = false;
+ var it = pinned.keyIterator();
+ while (it.next()) |at| any = any or at.session == si;
+ if (any) continue;
+ const ses = try Map.init(try sessions.putCursor(@intCast(si)));
+ for ([_]K{ .keys, .batches, .stretches }) |k| _ = try ses.remove(key(k));
+ }
+ }
+ };
}
-/// The bytes of every session's batches and keyframes: what compaction keeps.
+/// The bytes of every session's batches and keyframes' pages (each written
+/// once): what compaction keeps.
/// Reading them all is also what proves a mended file whole.
fn liveSize(db: *Disk) !u64 {
const R = Read(Disk);
@@ -222,11 +422,14 @@ fn liveSize(db: *Disk) !u64 {
const session = try R.Map.init(c);
if (try R.list(session, .batches)) |batches| {
var b = try batches.iterator();
- while (try b.next()) |blob| live += try blob.count();
+ while (try b.next()) |blob| live += if ((try blob.slot()).tag == .none) 0 else try blob.count();
}
if (try R.list(session, .keys)) |keys| {
var k = try keys.iterator();
- while (try k.next()) |key_cursor| live += try (try R.field(try R.Map.init(key_cursor), .state)).count();
+ while (try k.next()) |key_cursor| {
+ const e = try R.Map.init(key_cursor);
+ live += if (try e.getCursor(key(.written))) |w| try w.readUint() else try (try R.field(e, .state)).count();
+ }
}
}
return live;
@@ -320,19 +523,38 @@ pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void
/// Queues a keyframe of `state` before the next frame, and returns its
/// index; an unchanged State is the last keyframe again (but for a
-/// `before_reload` one: the last word in the old layout).
+/// `before_reload` one: the last word in the old layout). Only the pages
+/// whose hash differs from the last keyframe's are copied, and written.
pub fn keyframe(s: *Sessions, why: Why, state: []const u8) !u64 {
if (s.db == .off) return error.NotRecording;
- const hash = std.hash.Wyhash.hash(0, state);
defer s.line_len = 0;
- if (s.keys > 0 and why != .before_reload and hash == s.key_hash and s.key_stretch == s.stretches - 1) return s.keys - 1;
- const state_copy = try s.gpa.dupe(u8, state);
- errdefer s.gpa.free(state_copy);
+ const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, state.len, page) catch unreachable);
+ errdefer s.gpa.free(hashes);
+ var changed: std.ArrayList(u64) = .empty;
+ defer changed.deinit(s.gpa);
+ for (hashes, 0..) |*h, i| {
+ h.* = std.hash.Wyhash.hash(0, state[i * page .. @min(state.len, (i + 1) * page)]);
+ if (i >= s.hashes.len or s.hashes[i] != h.*) try changed.append(s.gpa, i);
+ }
+ if (s.keys > 0 and why != .before_reload and changed.items.len == 0 and hashes.len == s.hashes.len and s.key_stretch == s.stretches - 1) {
+ s.gpa.free(hashes);
+ return s.keys - 1;
+ }
+ const pages = try s.gpa.alloc(u8, changed.items.len * page);
+ errdefer s.gpa.free(pages);
+ for (changed.items, 0..) |i, k| {
+ const bytes = state[i * page .. @min(state.len, (i + 1) * page)];
+ @memcpy(pages[k * page ..][0..bytes.len], bytes);
+ }
+ const indices = try changed.toOwnedSlice(s.gpa);
+ errdefer s.gpa.free(indices);
const line_copy = try s.gpa.dupe(u8, s.line[0..s.line_len]);
errdefer s.gpa.free(line_copy);
- try s.queued.append(s.gpa, .{ .frame = s.frames, .batch = s.batches, .stretch = s.stretches - 1, .why = why, .time = s.last_time, .state = state_copy, .line = line_copy });
+ try s.queued.append(s.gpa, .{ .frame = s.frames, .batch = s.batches, .stretch = s.stretches - 1, .why = why, .time = s.last_time, .size = state.len, .from = s.last, .indices = indices, .pages = pages, .line = line_copy });
+ s.gpa.free(s.hashes);
+ s.hashes = hashes;
+ s.last = .{ .session = s.session, .key = s.keys };
s.key_time = s.last_time;
- s.key_hash = hash;
s.key_stretch = s.stretches - 1;
s.keys += 1;
return s.keys - 1;
@@ -348,8 +570,15 @@ pub fn stretch(s: *Sessions, st: Stretch) !void {
}
/// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`),
-/// synced to disk. Returns the keyframe's index.
+/// synced to disk. Returns the keyframe's index. A mark of a new name needs
+/// room for a whole State under `max_save`, history dropped to make it
+/// (`trim`): without, it is refused (`error.SaveFull`). A mark over an
+/// existing name lets the older one go with history.
pub fn mark(s: *Sessions, name: []const u8, why: Why, state: []const u8) !u64 {
+ if (s.db == .file and try s.file.?.length(s.io) + state.len > max_save and try s.findMark(name) == null) {
+ try s.trim();
+ if (try s.file.?.length(s.io) + state.len > max_save) return error.SaveFull;
+ }
const k = try s.keyframe(why, state);
try s.commitSynced(.{ .mark = .{ .name = name, .key = k } });
return k;
@@ -371,7 +600,8 @@ pub fn stopClip(s: *Sessions) !void {
fn dropQueued(s: *Sessions) void {
for (s.queued.items) |k| {
- s.gpa.free(k.state);
+ s.gpa.free(k.indices);
+ s.gpa.free(k.pages);
s.gpa.free(k.line);
}
s.queued.clearRetainingCapacity();
@@ -416,7 +646,10 @@ pub fn commit(s: *Sessions, extra: Extra) !void {
s.committed = s.frames;
s.batch.clearRetainingCapacity();
}
+ const keyed = s.queued.items.len > 0;
s.dropQueued();
+ if (s.db != .file) return;
+ if ((try s.file.?.length(s.io)) > max_save or (!s.history and keyed)) s.trim() catch |err| std.log.warn("sessions: history not trimmed: {t}", .{err});
}
fn Commit(comptime DB: type) type {
@@ -456,8 +689,28 @@ fn Commit(comptime DB: type) type {
try k.put(key(.stretch), .{ .uint = q.stretch });
try k.put(key(.why), .{ .uint = @intFromEnum(q.why) });
try k.put(key(.time), .{ .uint = q.time });
- try k.put(key(.state), .{ .bytes = q.state });
+ try k.put(key(.size), .{ .uint = q.size });
try k.put(key(.line), .{ .bytes = q.line });
+ // From the keyframe before's pages, copied as the
+ // transaction writes on (it may be in it too).
+ var from = try k.putCursor(key(.pages));
+ if (q.from) |at| if (try pagesSlot(root, at)) |slot| {
+ try from.write(.{ .slot = slot });
+ try from.freeze();
+ };
+ const pages = try List.init(from);
+ const had = try pages.count();
+ var written: u64 = 0;
+ for (q.indices, 0..) |i, j| {
+ const bytes = q.pages[j * page ..][0..@min(page, q.size - i * page)];
+ const zero = std.mem.allEqual(u8, bytes, 0);
+ if (!zero) written += bytes.len;
+ const data: DB.WriteableData = if (zero) .{ .slot = null } else .{ .bytes = bytes };
+ if (i < had) try pages.put(@intCast(i), data) else try pages.append(data);
+ }
+ const n = std.math.divCeil(u64, q.size, page) catch unreachable;
+ if (had > n) try pages.slice(n);
+ try k.put(key(.written), .{ .uint = written });
}
}
switch (ctx.extra) {
@@ -485,6 +738,13 @@ fn Commit(comptime DB: type) type {
}
}
+ /// The slot of keyframe `at`'s pages; null for one from before pages.
+ fn pagesSlot(root: Map, at: At) !?xitdb.Slot {
+ const R = Read(DB);
+ const ses = try R.at(try R.list(root.readOnly(), .sessions) orelse return null, at.session);
+ return (try R.at(try R.list(ses, .keys) orelse return null, at.key)).getSlot(key(.pages));
+ }
+
fn putStretch(list: List, st: Stretch) !void {
const item = try Map.init(try list.appendCursor());
try item.put(key(.frame), .{ .uint = st.frame });
@@ -513,6 +773,8 @@ pub const Entry = struct {
};
/// A keyframe, its bytes `gpa`'s (`free`).
pub const Loaded = struct {
+ /// Stored in pages (not whole, from before them).
+ paged: bool = true,
frame: u64,
batch: u64,
why: Why,
@@ -594,13 +856,15 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
const st = try R.uint(e, .stretch);
const stretch_entry = try R.at(try R.list(ses, .stretches) orelse return error.CorruptSession, st);
const why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession;
- const state = try R.bytes(e, .state, s.gpa);
+ const pages = try R.list(e, .pages);
+ const state = if (pages) |list| try R.pages(list, try R.uint(e, .size), s.gpa) else if (try e.getCursor(key(.state))) |whole| try whole.readBytesAlloc(s.gpa, null) else return error.HistoryDropped;
errdefer s.gpa.free(state);
const line = try R.bytes(e, .line, s.gpa);
errdefer s.gpa.free(line);
const source = try R.bytes(stretch_entry, .source, s.gpa);
errdefer s.gpa.free(source);
return .{
+ .paged = pages != null,
.frame = try R.uint(e, .frame),
.batch = try R.uint(e, .batch),
.why = why,
@@ -616,6 +880,32 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
}
}
+/// The State a run starts from, the present: the newest keyframe of the
+/// sessions before this one, with the frames logged after it appended to
+/// `out` (replayed, they bring it to where that run stopped). Null in a
+/// new database. This run's first keyframe starts from its pages.
+pub fn present(s: *Sessions, out: *std.ArrayList(abi.Event)) !?Loaded {
+ if (s.db == .off) return null;
+ var i = s.session;
+ while (i > 0) {
+ i -= 1;
+ const sum = try s.summary(i);
+ if (sum.keys == 0) continue;
+ const newest = try s.load(i, sum.keys - 1);
+ errdefer newest.free(s.gpa);
+ try s.events(i, newest.batch, newest.frame, sum.frames, out);
+ if (newest.paged) {
+ const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, newest.state.len, page) catch unreachable);
+ for (hashes, 0..) |*h, j| h.* = std.hash.Wyhash.hash(0, newest.state[j * page .. @min(newest.state.len, (j + 1) * page)]);
+ s.gpa.free(s.hashes);
+ s.hashes = hashes;
+ s.last = .{ .session = i, .key = sum.keys - 1 };
+ }
+ return newest;
+ }
+ return null;
+}
+
/// Keyframe `k`'s frame, time and why, without its bytes.
pub fn keyAt(s: *Sessions, session: u64, k: u64) !struct { frame: u64, time: u64, why: Why } {
switch (s.db) {
@@ -658,7 +948,9 @@ pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out:
const n = try batches.count();
var i = from;
while (i < n) : (i += 1) {
- const blob = try (try batches.getCursor(@intCast(i)) orelse return error.CorruptSession).readBytesAlloc(s.gpa, null);
+ const cursor = try batches.getCursor(@intCast(i)) orelse return error.CorruptSession;
+ if ((try cursor.slot()).tag == .none) return error.HistoryDropped;
+ const blob = try cursor.readBytesAlloc(s.gpa, null);
defer s.gpa.free(blob);
if (blob.len < 8 or (blob.len - 8) % @sizeOf(abi.Event) != 0) return error.CorruptSession;
var f = std.mem.readInt(u64, blob[0..8], .little);
@@ -775,6 +1067,8 @@ fn Transfer(comptime From: type, comptime To: type) type {
const List = To.ArrayList(.read_write);
pub fn run(ctx: @This(), cursor: *To.Cursor(.read_write)) !void {
+ var copied: std.AutoHashMap(u64, xitdb.Slot) = .init(ctx.gpa);
+ defer copied.deinit();
const src = try R.root(ctx.from);
if (try R.uint(src, .version) != 1) return error.NotASessionsDatabase;
const all = try R.list(src, .sessions) orelse return error.NotASessionsDatabase;
@@ -786,7 +1080,7 @@ fn Transfer(comptime From: type, comptime To: type) type {
for (0..try all.count()) |i| {
if (ctx.only) |o| if (o != i) continue;
var to = try sessions.appendCursor();
- try copy(From, To, ctx.gpa, try all.getCursor(@intCast(i)) orelse return error.CorruptSession, &to);
+ try copy(From, To, ctx.gpa, try all.getCursor(@intCast(i)) orelse return error.CorruptSession, &to, &copied);
if (ctx.label) |l| try (try Map.init(to)).put(key(.from), .{ .bytes = try std.fmt.bufPrint(&buf, "import {s}", .{l}) });
}
for ([_]K{ .marks, .clips }) |which| {
@@ -797,7 +1091,7 @@ fn Transfer(comptime From: type, comptime To: type) type {
const session = try R.uint(try R.Map.init(e), .session);
if (ctx.only) |o| if (o != session) continue;
var to = try list.appendCursor();
- try copy(From, To, ctx.gpa, e, &to);
+ try copy(From, To, ctx.gpa, e, &to, &copied);
const item = try Map.init(to);
try item.put(key(.session), .{ .uint = base + if (ctx.only == null) session else 0 });
const l = ctx.label orelse continue;
@@ -811,21 +1105,27 @@ fn Transfer(comptime From: type, comptime To: type) type {
};
}
-/// Copies the value at `from` (a uint, bytes, or a list or map of them) to `to`.
-fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write)) anyerror!void {
- switch ((try from.slot()).tag) {
+/// Copies the value at `from` (a uint, bytes, or a list or map of them) to
+/// `to`. Bytes `copied` already (a page keyframes share) are written once:
+/// it maps their place in `from` to their slot in `to`.
+fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write), copied: *std.AutoHashMap(u64, xitdb.Slot)) anyerror!void {
+ const slot = try from.slot();
+ switch (slot.tag) {
+ .none => try to.write(.{ .slot = null }),
.uint => try to.write(.{ .uint = try from.readUint() }),
.bytes, .short_bytes => {
+ if (slot.tag == .bytes) if (copied.get(slot.value)) |done| return to.write(.{ .slot = done });
const bytes = try from.readBytesAlloc(gpa, null);
defer gpa.free(bytes);
try to.write(.{ .bytes = bytes });
+ if (slot.tag == .bytes) try copied.put(slot.value, try to.slot());
},
.array_list => {
const list = try To.ArrayList(.read_write).init(to.*);
var it = try from.iterator();
while (try it.next()) |c| {
var next = try list.appendCursor();
- try copy(From, To, gpa, c, &next);
+ try copy(From, To, gpa, c, &next, copied);
}
},
.hash_map => {
@@ -834,7 +1134,7 @@ fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: Fr
while (try it.next()) |c| {
const kv = try c.readKeyValuePair();
var next = try map.putCursor(kv.hash);
- try copy(From, To, gpa, kv.value_cursor, &next);
+ try copy(From, To, gpa, kv.value_cursor, &next, copied);
}
},
else => return error.CorruptSession,
@@ -861,6 +1161,19 @@ fn Read(comptime DB: type) type {
fn bytes(map: Map, k: K, gpa: std.mem.Allocator) ![]const u8 {
return (try field(map, k)).readBytesAlloc(gpa, null);
}
+ /// `size` bytes from a keyframe's pages, `gpa`'s.
+ fn pages(l: List, size: u64, gpa: std.mem.Allocator) ![]u8 {
+ const out = try gpa.alloc(u8, size);
+ errdefer gpa.free(out);
+ @memset(out, 0);
+ for (0..try l.count()) |i| {
+ const c = try l.getCursor(@intCast(i)) orelse continue;
+ if ((try c.slot()).tag == .none) continue;
+ const into = out[@min(size, i * page)..@min(size, (i + 1) * page)];
+ if ((c.readBytes(into) catch return error.CorruptSession).len != into.len) return error.CorruptSession;
+ }
+ return out;
+ }
fn list(map: Map, k: K) !?List {
return try List.init(try map.getCursor(key(k)) orelse return null);
}
@@ -1025,7 +1338,8 @@ test "a compacted session database is smaller and holds every session and frame"
try s.commit(.none);
const size = try s.file.?.length(io);
const live_size = try liveSize(&s.db.file);
- try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 6 * 8), live_size);
+ // Six keyframes of 8 bytes, the first all zeros: an empty page.
+ try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 5 * 8), live_size);
try s.compact();
s.deinit();
const compacted = (try tmp.dir.statFile(io, "t.xitdb", .{})).size;
@@ -1067,3 +1381,206 @@ test "a memory session stops recording at its bound, and what it holds still rea
try s.events(s.session, 0, 0, n, &back);
try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..n]), std.mem.sliceAsBytes(back.items));
}
+
+test "a session's keyframes write only the pages that changed: a State of megabytes edited each minute, and one never changed" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 4 MiB, every page holding something, one u64 edited a minute.
+ const state = try gpa.alloc(u8, 4 << 20);
+ defer gpa.free(state);
+ for (state, 0..) |*b, i| b.* = @truncate(i *% 7 + 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ const minutes = 10;
+ var sizes: [minutes + 1]u64 = undefined;
+ for (0..minutes * 60 * 60) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ if (f % 3600 == 1800) std.mem.writeInt(u64, state[(f / 3600) * 300_000 ..][0..8], f, .little);
+ try s.frame(&one, state, if (f == 0) .start else null);
+ if (f % 3600 == 0) {
+ try s.commit(.none);
+ sizes[f / 3600] = try s.file.?.length(io);
+ }
+ }
+ try s.commit(.none);
+ sizes[minutes] = try s.file.?.length(io);
+ // One keyframe a minute: at 0 s, 60 s, ...
+ try std.testing.expectEqual(@as(u64, minutes), s.keys);
+ // A minute is 216,000 bytes of ticks and a keyframe of one page with
+ // its copied path: under 230 KB a minute, where a whole State a
+ // keyframe was 4 MiB.
+ for (1..minutes) |m| try std.testing.expect(sizes[m + 1] - sizes[m] < 230_000);
+ // Every keyframe reads back whole: the edits made before it, and none after.
+ const want = try gpa.alloc(u8, state.len);
+ defer gpa.free(want);
+ for (0..minutes) |k| {
+ for (want, 0..) |*b, i| b.* = @truncate(i *% 7 + 1);
+ for (0..k) |m| std.mem.writeInt(u64, want[m * 300_000 ..][0..8], m * 3600 + 1800, .little);
+ const loaded = try s.load(s.session, k);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(@as(u64, k * 3600), loaded.frame);
+ try std.testing.expectEqualSlices(u8, want, loaded.state);
+ }
+ // A keyframe alone, in a commit of its own: one changed page is that
+ // page, its copied path and the keyframe's fields; no changed page (one
+ // kept before a reload) is the fields alone.
+ for ([_]bool{ true, false }) |edit| {
+ if (edit) state[123] +%= 1;
+ const before = try s.file.?.length(io);
+ _ = try s.keyframe(if (edit) .jump else .before_reload, state);
+ try s.commit(.none);
+ try std.testing.expect(try s.file.?.length(io) - before < @as(u64, if (edit) 12 << 10 else 8 << 10));
+ }
+ const last = try s.load(s.session, s.keys - 1);
+ defer last.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, last.state);
+}
+
+test "an exported session keeps its keyframes' shared pages shared" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ var out_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const out = try std.fmt.bufPrint(&out_buf, ".zig-cache/tmp/{s}/one.xitdb", .{&tmp.sub_path});
+ const state = try gpa.alloc(u8, 1 << 20);
+ defer gpa.free(state);
+ for (state, 0..) |*b, i| b.* = @truncate(i *% 13 + 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ // Ten keyframes a byte apart.
+ for (0..600) |f| {
+ const t = f * std.time.ns_per_s / 60;
+ var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)};
+ if (f % 60 == 0) state[f * 100] +%= 1;
+ try s.frame(&one, state, if (f == 0) .start else if (f % 60 == 0) .jump else null);
+ }
+ try s.exportSession(0, out);
+ const size = (try std.Io.Dir.cwd().statFile(io, out, .{})).size;
+ // One State and nine pages, not ten States.
+ try std.testing.expect(size < state.len + state.len / 8);
+ var again = try open(gpa, io, .file, out, .{ .build = 7, .source = "", .layout = "a layout" }, 2000);
+ defer again.deinit();
+ const loaded = try again.load(0, 9);
+ defer loaded.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, loaded.state);
+}
+
+test "a session database past max_save drops its oldest history: the present and the marks stay, the file under it" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 2 MiB of State, its first half rewritten each second: a keyframe
+ // writes 1 MiB, so the cap is reached at about the 60th.
+ const state = try gpa.alloc(u8, 2 << 20);
+ defer gpa.free(state);
+ @memset(state, 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ for (0..100) |k| {
+ @memset(state[0 .. 1 << 20], @truncate(k + 2));
+ var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)};
+ try s.frame(&one, state, if (k == 0) .start else .jump);
+ if (k == 5) _ = try s.mark("a", .mark, state);
+ if (k == 20) _ = try s.mark("b", .mark, state);
+ try std.testing.expect(try s.file.?.length(io) <= max_save);
+ }
+ try s.commit(.none);
+ // The oldest keyframes and frames are gone; the marks and the newest
+ // keyframe read back whole.
+ try std.testing.expectError(error.HistoryDropped, s.load(0, 1));
+ var log: std.ArrayList(abi.Event) = .empty;
+ defer log.deinit(gpa);
+ try std.testing.expectError(error.HistoryDropped, s.events(0, 0, 0, 2, &log));
+ for ([_]struct { []const u8, u8 }{ .{ "a", 7 }, .{ "b", 22 } }) |want| {
+ const m = (try s.findMark(want[0])).?;
+ const loaded = try s.load(m.session, m.key);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(want[1], loaded.state[0]);
+ try std.testing.expectEqual(@as(u8, 1), loaded.state[1 << 20]);
+ }
+ const newest = try s.load(0, s.keys - 1);
+ defer newest.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, newest.state);
+ try s.events(0, newest.batch, newest.frame, s.frames, &log);
+}
+
+test "a session database without history keeps the present and the marks, and leaves nothing else at exit" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ var state: [64 << 10]u8 = @splat(1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ s.history = false;
+ for (0..20) |k| {
+ @memset(state[0 .. 32 << 10], @truncate(k + 2));
+ var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)};
+ try s.frame(&one, &state, if (k == 0) .start else .jump);
+ if (k == 3) _ = try s.mark("a", .mark, &state);
+ }
+ try s.commit(.none);
+ try std.testing.expectError(error.HistoryDropped, s.load(0, 1));
+ const m = (try s.findMark("a")).?;
+ const loaded = try s.load(m.session, m.key);
+ loaded.free(gpa);
+ s.close(&state, 2000);
+ // At exit: compacted to the present, the mark and the session's fields.
+ try std.testing.expect((try tmp.dir.statFile(io, "t.xitdb", .{})).size < 3 * state.len);
+ var again = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 3000);
+ defer again.deinit();
+ var log: std.ArrayList(abi.Event) = .empty;
+ defer log.deinit(gpa);
+ const now = (try again.present(&log)).?;
+ defer now.free(gpa);
+ try std.testing.expectEqualSlices(u8, &state, now.state);
+}
+
+test "a session database full of marks refuses a mark of a new name, and takes one over an old name" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 2 MiB of State, all of it changed for each mark.
+ const state = try gpa.alloc(u8, 2 << 20);
+ defer gpa.free(state);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ var name: [8]u8 = undefined;
+ var k: u8 = 0;
+ while (true) : (k += 1) {
+ @memset(state, k + 1);
+ _ = s.mark(try std.fmt.bufPrint(&name, "m{d}", .{k}), .mark, state) catch |err| {
+ try std.testing.expectEqual(error.SaveFull, err);
+ break;
+ };
+ try std.testing.expect(k < 40 and try s.file.?.length(io) <= max_save);
+ }
+ try std.testing.expect(k > 20);
+ @memset(state, 99);
+ try std.testing.expectError(error.SaveFull, s.mark("new", .mark, state));
+ _ = try s.mark("m3", .mark, state);
+ try s.commit(.none);
+ try std.testing.expect(try s.file.?.length(io) <= max_save);
+ // Every mark's newest keyframe is whole.
+ for (0..k) |i| {
+ const m = (try s.findMark(try std.fmt.bufPrint(&name, "m{d}", .{i}))).?;
+ const loaded = try s.load(m.session, m.key);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(@as(u8, if (i == 3) 99 else @intCast(i + 1)), loaded.state[state.len - 1]);
+ }
+}
diff --git a/src/host/audio.zig b/src/host/audio.zig
index bf5fdc4..e95e38e 100644
--- a/src/host/audio.zig
+++ b/src/host/audio.zig
@@ -28,6 +28,19 @@ pub const Audio = struct {
heard_gains: [8]f32 = @splat(1),
streams: std.ArrayList(Stream) = .empty,
status: std.ArrayList(abi.Stream) = .empty,
+ /// Samples the device takes from each stream at once.
+ pull: u32 = 1024,
+ /// The wall-clock time (ns) between the ends of the last frames'
+ /// commands, where pushes are done; and when the last ended.
+ intervals: [64]u64 = @splat(0),
+ frame: u64 = 0,
+ last_frame: u64 = 0,
+ /// Grown by underruns, shrinking back while there are none.
+ margin: u32 = 0,
+ /// A stream ran dry since the lead was last worked out.
+ dry: bool = false,
+ /// `Input.lead`: see `lead`.
+ lead: u32 = 4800,
scope: Scope = .{},
/// The default recording device, bound to this stream while declared.
microphone: ?*c.SDL_AudioStream = null,
@@ -44,12 +57,25 @@ pub const Audio = struct {
/// Mixed since a script last asked (`expect-audio`).
sounded: bool = false,
};
- const Stream = struct { key: u32, out: *c.SDL_AudioStream, pushed: u64 = 0 };
+ const Stream = struct {
+ key: u32,
+ out: *c.SDL_AudioStream,
+ pushed: u64 = 0,
+ /// Pushed to this frame, and the last.
+ fed: bool = false,
+ was_fed: bool = false,
+ underruns: u32 = 0,
+ };
pub fn open(self: *Audio) !void {
const device = c.SDL_OpenAudioDevice(c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec);
if (device == 0) return error.OpenAudio;
self.device = device;
+ var format: c.SDL_AudioSpec = undefined;
+ var frames: c_int = 0;
+ if (c.SDL_GetAudioDeviceFormat(device, &format, &frames) and frames > 0 and format.freq > 0) {
+ self.pull = @intCast(@divFloor(@as(i64, frames) * sample_rate + format.freq - 1, format.freq));
+ }
self.voices_out = try self.bind();
self.scope.attach(device) catch {};
}
@@ -176,9 +202,18 @@ pub const Audio = struct {
if (clear) {
_ = c.SDL_ClearAudioStream(s.out);
s.pushed = 0;
+ s.was_fed = false;
}
if (samples.len == 0) return;
+ // Fed last frame and empty now: the device came up short since
+ // (counted at the push, as a pull before it would hide it by the
+ // next frame).
+ if (s.was_fed and !s.fed and c.SDL_GetAudioStreamQueued(s.out) == 0) {
+ s.underruns += 1;
+ self.dry = true;
+ }
if (c.SDL_PutAudioStreamData(s.out, samples.ptr, @intCast(samples.len * @sizeOf(f32)))) s.pushed += samples.len;
+ s.fed = true;
}
fn streamFor(self: *Audio, key: u32) ?*Stream {
@@ -192,14 +227,22 @@ pub const Audio = struct {
return &self.streams.items[self.streams.items.len - 1];
}
- /// Drops undeclared voices, keeps the voice mix queued ahead, and opens
- /// or closes the microphone.
+ /// Drops undeclared voices, works out the lead for the next frame, keeps
+ /// the voice mix queued ahead, and opens or closes the microphone.
pub fn endFrame(self: *Audio) void {
self.reconcileMicrophone();
var i: usize = 0;
while (i < self.voices.items.len) {
if (self.voices.items[i].seen) i += 1 else _ = self.voices.swapRemove(i);
}
+ const now = c.SDL_GetTicksNS();
+ if (self.last_frame != 0) {
+ self.intervals[self.frame % self.intervals.len] = now -| self.last_frame;
+ self.frame += 1;
+ }
+ self.last_frame = now;
+ self.lead = lead(self.intervals, self.pull, &self.margin, self.dry);
+ self.dry = false;
const out = self.voices_out orelse return;
const queued = c.SDL_GetAudioStreamQueued(out);
if (queued < 0) return;
@@ -257,16 +300,33 @@ pub const Audio = struct {
return false;
}
+ /// The streams as a frame starts.
pub fn streamStatus(self: *Audio) []const abi.Stream {
self.status.clearRetainingCapacity();
- for (self.streams.items) |s| {
- const queued = c.SDL_GetAudioStreamQueued(s.out);
- self.status.append(self.gpa, .{ .key = s.key, .queued = @intCast(@divFloor(@max(queued, 0), @sizeOf(f32))), .pushed = s.pushed }) catch {};
+ for (self.streams.items) |*s| {
+ const queued: u32 = @intCast(@divFloor(@max(c.SDL_GetAudioStreamQueued(s.out), 0), @sizeOf(f32)));
+ s.was_fed = s.fed;
+ s.fed = false;
+ self.status.append(self.gpa, .{ .key = s.key, .queued = queued, .pushed = s.pushed, .underruns = s.underruns }) catch {};
}
return self.status.items;
}
};
+/// How many samples to keep queued: the slowest of the last frames' worth
+/// (pushes come once a frame, `intervals` apart), plus the device's pull
+/// (it takes that much at once), plus `margin`: half a pull more at each
+/// underrun (`dry`), back down by a sample a frame.
+fn lead(intervals: [64]u64, pull: u32, margin: *u32, dry: bool) u32 {
+ var slowest: u64 = 0;
+ for (intervals) |ns| slowest = @max(slowest, ns);
+ margin.* = if (dry) @min(margin.* + pull / 2, max_lead) else margin.* -| 1;
+ const frame: u32 = @intCast(@min(slowest * sample_rate / std.time.ns_per_s, 1 << 20));
+ return @min(frame + pull + margin.*, max_lead);
+}
+/// 170 ms: a frame slower than that is a stall, not a pace.
+const max_lead = 8192;
+
/// Where the voice mix stops being passed through: -2.5 dBFS. Quieter
/// mixes keep their true volume to the bit; a clip normalised to full scale
/// only has its peaks bent (1 comes out at 0.875).
@@ -462,3 +522,20 @@ test "voices at another rate are resampled linearly, and a group's gain scales i
try std.testing.expect(out[0] > 0.375 and out[0] < 0.38);
try std.testing.expectEqual(@as(f32, 0.5), out[1023]);
}
+
+test "the lead the mixer gives streams outlasts the slowest recent frame and the device's pull, more after an underrun" {
+ const expectEqual = std.testing.expectEqual;
+ var intervals: [64]u64 = @splat(20 * std.time.ns_per_ms);
+ var margin: u32 = 0;
+ // 50 Hz and a pull of 1024: a frame's 960 samples and the pull.
+ try expectEqual(@as(u32, 960 + 1024), lead(intervals, 1024, &margin, false));
+ // One 50 ms frame in the window sets it.
+ intervals[5] = 50 * std.time.ns_per_ms;
+ try expectEqual(@as(u32, 2400 + 1024), lead(intervals, 1024, &margin, false));
+ // An underrun adds half a pull, which goes a sample a frame.
+ try expectEqual(@as(u32, 2400 + 1024 + 512), lead(intervals, 1024, &margin, true));
+ try expectEqual(@as(u32, 2400 + 1024 + 511), lead(intervals, 1024, &margin, false));
+ // A stall is not a pace: the lead stops at 170 ms.
+ intervals[6] = std.time.ns_per_s;
+ try expectEqual(@as(u32, max_lead), lead(intervals, 1024, &margin, false));
+}
diff --git a/src/host/memory.zig b/src/host/memory.zig
index 044fc3b..2749ea1 100644
--- a/src/host/memory.zig
+++ b/src/host/memory.zig
@@ -1,13 +1,12 @@
//! Sketch memory by lifetime.
//!
-//! `StateFile`: one `MAP_SHARED` file holding the live state, plus a header
-//! describing the layout, so the state outlives restarts,
-//! a probe can read it from another process, and a reload with a changed
-//! layout can carry the old values over field by field.
+//! `State`: process memory in the layout the sketch declares; a reload
+//! with a changed layout carries the old values over field by field. It
+//! outlives the process in the sessions database (Sessions.zig), whose
+//! stretches keep its layout in the header format below.
//!
-//! `StoreFile`: a heap in a file, mapped at the same address in every run,
-//! so what it holds may point into it: the sketch's `Store` and everything
-//! allocated for it outlive restarts.
+//! `OldState`: a state file from before the database held the present,
+//! read once to import it.
//!
//! `Session`: this process's memory, kept across reloads.
const std = @import("std");
@@ -18,7 +17,7 @@ const field_value = @import("fields.zig");
pub const page = std.heap.page_size_min;
pub const header_len = 64 * 1024;
-/// One slot, the live state: snapshots are marks in the sessions database.
+/// A layout header, and an old file's one slot, the live state.
pub const file_magic = "SKETCH03".*;
/// Before sessions: slot 0 live and 1..7 snapshots (`old_slot_count`), which
/// the host imports as marks and then drops (`dropSnapshots`).
@@ -291,167 +290,93 @@ fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) boo
return true;
}
-pub const StateFile = struct {
- fd: posix.fd_t,
- map: []align(page) u8,
- /// 1, or `old_slot_count` in a file from before sessions.
- slots: usize = 1,
- /// Layout of the bytes in the file, owned by `arena`.
- layout: Layout,
+/// Live State: page aligned, in the running sketch's layout; `header` is
+/// that layout as `layoutOf` reads it back, for the sessions' stretches.
+pub const State = struct {
+ bytes: []align(page) u8 = &.{},
+ layout: Layout = .{},
+ header: []const u8 = "",
+ /// Owns `layout` and `header`.
arena: std.heap.ArenaAllocator,
- /// Opens or creates `path`. A new (empty) file has no layout and no used
- /// slots: the first `adopt` fills it. A file that is not a state file
- /// this host can read is refused, never truncated: it may be someone's
- /// work, written by another build.
- pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- errdefer _ = posix.system.close(fd);
- var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) };
- errdefer self.arena.deinit();
- const len = try fileSize(fd);
- if (len > 0) {
- if (len < header_len) return error.NotAStateFile;
- self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true });
- errdefer posix.munmap(self.map);
- try self.check();
- self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{};
- return self;
- }
- try self.resize(0);
- self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
- return self;
+ pub fn init(gpa: std.mem.Allocator) State {
+ return .{ .arena = .init(gpa) };
}
- pub fn close(self: *StateFile) void {
- if (self.map.len != 0) posix.munmap(self.map);
- _ = posix.system.close(self.fd);
+ pub fn deinit(self: *State, gpa: std.mem.Allocator) void {
+ gpa.free(self.bytes);
self.arena.deinit();
}
- pub fn header(self: *StateFile) *Header {
- return @ptrCast(self.map.ptr);
- }
-
- /// The header and the layout after it, as `readLayout` reads them back.
- pub fn layoutBytes(self: *StateFile) []const u8 {
- const h = self.header();
- return self.map[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len];
+ pub fn live(self: *State) []align(page) u8 {
+ return self.bytes[0..self.layout.size];
}
- pub fn slot(self: *StateFile, index: usize) []align(page) u8 {
- std.debug.assert(index < self.slots);
- const h = self.header();
- const start = header_len + index * h.stride;
- return @alignCast(self.map[start..][0..h.size]);
+ /// Makes State hold `new`'s layout: a new allocation of its defaults
+ /// (`defaults`), then every leaf `migrate` keeps of the old State. Null
+ /// when the layout is unchanged, or there was none.
+ pub fn adopt(self: *State, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !?Migration {
+ const first = self.bytes.len == 0;
+ if (!first and self.layout.hash == new.hash and self.layout.size == new.size) return null;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ errdefer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), new);
+ const region = try arena.allocator().alignedAlloc(u8, .of(Header), header_len);
+ @memset(region, 0);
+ const h: *Header = @ptrCast(region.ptr);
+ h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = std.mem.alignForward(usize, @max(new.size, 1), page), .used = 1, .field_count = 0, .strings_len = 0 };
+ try writeLayout(region, layout);
+ const bytes = try gpa.alignedAlloc(u8, .fromByteUnits(page), @max(new.size, 1));
+ @memset(bytes, 0);
+ defaults(.state, bytes.ptr);
+ const m = if (first) null else migrate(self.layout, self.live(), layout, bytes);
+ self.deinit(gpa);
+ self.* = .{ .bytes = bytes, .layout = layout, .header = region[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len], .arena = arena };
+ return m;
}
+};
- pub fn used(self: *StateFile, index: usize) bool {
- return self.header().used & (@as(u32, 1) << @intCast(index)) != 0;
- }
-
- pub fn markUsed(self: *StateFile, index: usize, value: bool) void {
- const bit = @as(u32, 1) << @intCast(index);
- if (value) self.header().used |= bit else self.header().used &= ~bit;
- }
-
- pub const Adoption = union(enum) {
- unchanged,
- created,
- migrated: Migration,
- };
-
- /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults`
- /// writes the new default values, then unchanged fields are copied over.
- pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) {
- // Same type, older header: describe it again, bytes untouched.
- if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) {
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
- self.layout = try Layout.copy(self.arena.allocator(), new);
- try writeLayout(self.map[0..header_len], self.layout);
- self.header().magic = file_magic_v2;
- }
- return .unchanged;
- }
- const had_state = self.header().used & 1 != 0;
-
- // Keep the old bytes and layout while the file is rebuilt.
- var old_arena: std.heap.ArenaAllocator = .init(gpa);
- defer old_arena.deinit();
- const old_layout = self.layout;
- var old_slots: [old_slot_count]?[]u8 = @splat(null);
- for (old_slots[0..self.slots], 0..) |*copy, i| {
- if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i));
- }
- const old_used = self.header().used;
- // `old_layout` points into `self.arena`: move it aside before resetting.
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
-
- self.layout = try Layout.copy(self.arena.allocator(), new);
- const stride = std.mem.alignForward(usize, @max(new.size, 1), page);
- try self.resize(stride);
- const h = self.header();
- h.* = .{ .magic = if (self.slots == 1) file_magic else file_magic_v2, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 };
- try writeLayout(self.map[0..header_len], self.layout);
+/// A state file from before the sessions database held the present: a
+/// layout header, then one slot (`file_magic`), or eight (`file_magic_v2`,
+/// `file_magic_v1`), the first live State and the others snapshots. Mapped
+/// read-only: imported once, never changed.
+pub const OldState = struct {
+ map: []align(page) const u8,
+ slots: usize,
- var total: Migration = .{};
- for (old_slots, 0..) |maybe_old, i| {
- const old = maybe_old orelse continue;
- const bytes = self.slot(i);
- @memset(bytes, 0);
- defaults(.state, bytes.ptr);
- const m = migrate(old_layout, old, self.layout, bytes);
- total.kept += m.kept;
- if (i == 0) total.reset = m.reset;
- }
- if (!had_state) {
- self.markUsed(0, false);
- return .created;
- }
- return .{ .migrated = total };
+ /// error.FileNotFound when `path` is missing or empty; a file that is
+ /// no state file this host reads is refused.
+ pub fn open(path: []const u8) !OldState {
+ const map = mapReadOnly(path);
+ if (map.len == 0) return error.FileNotFound;
+ errdefer posix.munmap(map);
+ if (map.len < header_len) return error.NotAStateFile;
+ const h: *const Header = @ptrCast(map.ptr);
+ const slots: usize = if (std.mem.eql(u8, &h.magic, &file_magic)) 1 else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) old_slot_count else return error.NotAStateFile;
+ if (map.len < header_len + slots * h.stride or h.size > h.stride) return error.CorruptStateFile;
+ return .{ .map = map, .slots = slots };
}
- /// Makes a file from before sessions one of a single slot, its
- /// snapshots (imported as marks by now) dropped.
- pub fn dropSnapshots(self: *StateFile) !void {
- if (self.slots == 1) return;
- const stride = self.header().stride;
- self.slots = 1;
- try self.resize(stride);
- self.header().magic = file_magic;
- self.header().used &= 1;
+ pub fn close(self: OldState) void {
+ posix.munmap(self.map);
}
- fn check(self: *StateFile) !void {
- const h = self.header();
- if (std.mem.eql(u8, &h.magic, &file_magic)) {
- self.slots = 1;
- } else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) {
- self.slots = old_slot_count;
- } else return error.NotAStateFile;
- if (self.map.len < header_len + self.slots * h.stride or h.size > h.stride) return error.CorruptStateFile;
+ /// The header and layout, as `restore` and `layoutOf` take them.
+ pub fn layoutBytes(self: OldState) []const u8 {
+ return self.map[0..header_len];
}
- fn resize(self: *StateFile, stride: usize) !void {
- const len = header_len + self.slots * stride;
- if (self.map.len != 0) posix.munmap(self.map);
- self.map = &.{};
- switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
- }
- self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true });
+ /// Slot `i`'s State, null when the slot is unused.
+ pub fn slot(self: OldState, i: usize) ?[]const u8 {
+ const h: *const Header = @ptrCast(self.map.ptr);
+ if (h.used & (@as(u32, 1) << @intCast(i)) == 0) return null;
+ return self.map[header_len + i * h.stride ..][0..h.size];
}
};
/// Fills `live` (laid out as `to`) from `image`, state kept in another
-/// layout, described by `layout_bytes` (a header as `StateFile.layoutBytes`
-/// gives it): `defaults`, then every leaf `migrate` keeps. Returns the
+/// layout, described by `layout_bytes` (a header as `State.header` holds
+/// it): `defaults`, then every leaf `migrate` keeps. Returns the
/// image's layout, `arena`'s.
pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []const u8, to: Layout, live: []u8, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Layout {
const from = try layoutOf(arena, layout_bytes);
@@ -462,7 +387,7 @@ pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []cons
return from;
}
-/// The layout in a header as `StateFile.layoutBytes` gives it, `arena`'s.
+/// The layout in a header as `State.header` holds it, `arena`'s.
pub fn layoutOf(arena: std.mem.Allocator, layout_bytes: []const u8) !Layout {
if (layout_bytes.len < @sizeOf(Header) or layout_bytes.len > header_len) return error.CorruptKeyframe;
const region = try arena.alignedAlloc(u8, .of(Header), header_len);
@@ -515,14 +440,14 @@ fn writeLayout(region: []u8, layout: Layout) !void {
h.strings_len = @intCast(strings);
}
-/// The layout stored in a state or store file's header, or null if it has
-/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`,
-/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole
-/// leaves only, which migrate while their type is unchanged.
+/// The layout stored in a state file's header, or null if it has none.
+/// Reads both formats, by magic: a v1 header (`file_magic_v1`) has no
+/// element leaves, so its arrays are whole leaves only, which migrate while
+/// their type is unchanged.
pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
const h: *const Header = @ptrCast(@alignCast(map.ptr));
if (h.hash == 0 and h.field_count == 0) return null;
- const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1);
+ const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1);
const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField);
const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride;
if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader;
@@ -560,10 +485,6 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves };
}
-pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 {
- return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0);
-}
-
pub fn fileSize(fd: posix.fd_t) !u64 {
var stat: linux.Statx = undefined;
switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) {
@@ -582,208 +503,6 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 {
return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{};
}
-/// Where every store is mapped, in every process: far from where Linux puts
-/// executables (0x55...) and mappings (0x7f...).
-pub const store_base: usize = 0x2000_0000_0000;
-/// The most a store can grow to. Only reserved: pages exist as they are used.
-pub const store_reserve: usize = 64 << 30;
-/// The allocator's record (`Meta`); unchanged by the layout format.
-pub const store_magic = "SKSTORE1".*;
-/// The store's layout header, like `file_magic` and `file_magic_v1`.
-pub const store_layout_magic = "SKSTORE2".*;
-pub const store_layout_magic_v1 = "SKSTORE1".*;
-/// The layout region is a state file header; the allocator's own record
-/// follows, then the heap.
-const meta_offset = header_len;
-const heap_offset = 2 * header_len;
-
-/// A heap in a file, with the sketch's `Store` at its root. Mapped at
-/// `store_base` in every run, so pointers it holds into itself stay valid
-/// across restarts. Not crash-safe: a crash in the middle of an allocation
-/// can leave it inconsistent (`--fresh` starts over).
-///
-/// Blocks come in power-of-two sizes, each class with a free list threaded
-/// through the free blocks, so growing a list by doubling reuses what it
-/// frees. The file grows by mapping more of it in place: nothing moves.
-pub const StoreFile = struct {
- fd: posix.fd_t,
- /// Bytes of the file mapped at `store_base`.
- len: usize,
- /// The root's layout, owned by `arena`.
- layout: Layout,
- arena: std.heap.ArenaAllocator,
-
- const Meta = extern struct {
- magic: [8]u8 = store_magic,
- base: u64 = store_base,
- /// Offset of the first byte never handed out.
- top: u64 = heap_offset,
- /// Offset of the sketch's Store, or 0 before the first adopt.
- root: u64 = 0,
- /// Offsets of the first free block of each size class (2^i bytes), 0
- /// when none; a free block's first 8 bytes hold the next one's.
- free: [64]u64 = @splat(0),
- };
-
- pub fn open(gpa: std.mem.Allocator, path: []const u8, fresh: bool) !StoreFile {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- errdefer _ = posix.system.close(fd);
- // The same file mapped by two processes would be two heaps writing
- // over each other.
- if (linux.errno(linux.flock(fd, posix.LOCK.EX | posix.LOCK.NB)) != .SUCCESS) return error.StoreInUse;
- const reserved = posix.mmap(@ptrFromInt(store_base), store_reserve, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED_NOREPLACE = true }, -1, 0) catch return error.StoreAddressTaken;
- // Old kernels treat FIXED_NOREPLACE as a hint.
- if (@intFromPtr(reserved.ptr) != store_base) {
- posix.munmap(reserved);
- return error.StoreAddressTaken;
- }
- errdefer posix.munmap(reserved);
- var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) };
- errdefer self.arena.deinit();
- const size: usize = @intCast(try fileSize(fd));
- if (!fresh and size > 0) {
- // Checked before mapping, which may lengthen the file: a file
- // that is not a store is refused untouched, never wiped.
- var m: Meta = undefined;
- const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset);
- if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile;
- try self.grow(size);
- self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{};
- return self;
- }
- try self.wipe();
- return self;
- }
-
- pub fn close(self: *StoreFile) void {
- posix.munmap(@as([*]align(page) u8, @ptrFromInt(store_base))[0..store_reserve]);
- _ = posix.system.close(self.fd);
- self.arena.deinit();
- }
-
- /// Empties the store: no root, nothing allocated.
- fn wipe(self: *StoreFile) !void {
- // Mapped pages past the new end would fault: map the reserve back.
- if (self.len > heap_offset) {
- _ = try posix.mmap(@ptrFromInt(store_base + heap_offset), self.len - heap_offset, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED = true }, -1, 0);
- self.len = heap_offset;
- }
- try truncate(self.fd, heap_offset);
- try self.grow(heap_offset);
- @memset(self.region(), 0);
- self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
- self.meta().* = .{};
- self.layout = .{};
- }
-
- /// Maps the file up to `need` bytes, growing it when it is shorter.
- fn grow(self: *StoreFile, need: usize) !void {
- if (need <= self.len) return;
- const len = std.mem.alignForward(usize, @max(need, self.len * 2, 1 << 20), page);
- if (len > store_reserve) return error.StoreFull;
- if (try fileSize(self.fd) < len) try truncate(self.fd, len);
- _ = try posix.mmap(@ptrFromInt(store_base + self.len), len - self.len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .SHARED, .FIXED = true }, self.fd, self.len);
- self.len = len;
- }
-
- fn region(_: *StoreFile) []u8 {
- return @as([*]u8, @ptrFromInt(store_base))[0..header_len];
- }
- fn header(_: *StoreFile) *Header {
- return @ptrFromInt(store_base);
- }
- fn meta(_: *StoreFile) *Meta {
- return @ptrFromInt(store_base + meta_offset);
- }
-
- /// The sketch's Store.
- pub fn root(self: *StoreFile) [*]u8 {
- const offset = self.meta().root;
- return @ptrFromInt(store_base + if (offset == 0) heap_offset else offset);
- }
-
- pub const Adoption = StateFile.Adoption;
-
- /// Makes the root hold `new`'s layout: the new defaults, then every field
- /// whose path and type are unchanged, copied over. Pointer fields keep
- /// pointing where they did, since the store never moves.
- pub fn adopt(self: *StoreFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- const m = self.meta();
- if (m.root != 0 and self.layout.hash == new.hash and self.layout.size == new.size) return .unchanged;
- const a = self.allocator();
- const alignment: std.mem.Alignment = .fromByteUnits(@max(new.alignment, 1));
- const fresh = a.rawAlloc(@max(new.size, 1), alignment, @returnAddress()) orelse return error.StoreFull;
- @memset(fresh[0..@max(new.size, 1)], 0);
- defaults(.store, fresh);
-
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
- const old_layout = self.layout;
- self.layout = try Layout.copy(self.arena.allocator(), new);
- var result: Adoption = .created;
- if (m.root != 0) {
- const old: [*]u8 = @ptrFromInt(store_base + m.root);
- result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) };
- a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress());
- }
- self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 };
- try writeLayout(self.region(), self.layout);
- m.root = @intFromPtr(fresh) - store_base;
- return result;
- }
-
- pub fn allocator(self: *StoreFile) std.mem.Allocator {
- return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
- }
-
- fn class(len: usize, alignment: std.mem.Alignment) u6 {
- return @intCast(std.math.log2_int_ceil(usize, @max(len, alignment.toByteUnits(), 16)));
- }
-
- fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 {
- const self: *StoreFile = @ptrCast(@alignCast(ctx));
- const m = self.meta();
- const c = class(len, alignment);
- const size = @as(usize, 1) << c;
- if (m.free[c] != 0) {
- const block: [*]u8 = @ptrFromInt(store_base + m.free[c]);
- if (alignment.check(@intFromPtr(block))) {
- m.free[c] = @as(*const u64, @ptrCast(@alignCast(block))).*;
- return block;
- }
- }
- const offset = std.mem.alignForward(usize, m.top, @max(@min(size, page), alignment.toByteUnits()));
- self.grow(offset + size) catch return null;
- m.top = offset + size;
- return @ptrFromInt(store_base + offset);
- }
-
- /// In place within the block's size class.
- fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool {
- return class(memory.len, alignment) == class(new_len, alignment);
- }
-
- fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret: usize) ?[*]u8 {
- return if (resize(ctx, memory, alignment, new_len, ret)) memory.ptr else null;
- }
-
- fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, _: usize) void {
- const self: *StoreFile = @ptrCast(@alignCast(ctx));
- const m = self.meta();
- const c = class(memory.len, alignment);
- @as(*u64, @ptrCast(@alignCast(memory.ptr))).* = m.free[c];
- m.free[c] = @intFromPtr(memory.ptr) - store_base;
- }
-};
-
-fn truncate(fd: posix.fd_t, len: usize) !void {
- switch (posix.errno(posix.system.ftruncate(fd, @intCast(len)))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
- }
-}
-
/// Session memory: survives reloads while its layout hash is unchanged.
/// Everything allocated from `heap` is released with it.
pub const Session = struct {
@@ -921,7 +640,7 @@ test "migration keeps unchanged fields and defaults the rest" {
try std.testing.expectEqual(@as(usize, 1), m.reset);
}
-test "state file migrates live state, and a reopen reads the layout back" {
+test "State migrates to a changed layout, and keeps itself when it is unchanged" {
const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* };
const V2 = extern struct { level: u16 = 1, score: u32 = 0 };
const D = struct {
@@ -932,65 +651,20 @@ test "state file migrates live state, and a reopen reads the layout back" {
@as(*V2, @ptrCast(@alignCast(p))).* = .{};
}
};
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.state", .{&tmp.sub_path});
const gpa = std.testing.allocator;
- {
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .state), D.v1));
- file.markUsed(0, true);
- @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99;
- }
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash);
- const adoption = try file.adopt(gpa, abi.layout.of(V2, .state), D.v2);
- try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset);
- try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(file.slot(0).ptr)).*);
-}
-
-test "a store keeps its root and what it points to across a reopen, and migrates by field" {
- const V1 = struct { list: std.ArrayList(u32) = .empty, count: u32 = 0 };
- const V2 = struct { added: u8 = 7, list: std.ArrayList(u32) = .empty };
- const D = struct {
- fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void {
- @as(*V1, @ptrCast(@alignCast(p))).* = .{};
- }
- fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void {
- @as(*V2, @ptrCast(@alignCast(p))).* = .{};
- }
- };
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.store", .{&tmp.sub_path});
- const gpa = std.testing.allocator;
- {
- var store = try StoreFile.open(gpa, path, false);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1));
- const v: *V1 = @ptrCast(@alignCast(store.root()));
- for (0..10_000) |i| try v.list.append(store.allocator(), @intCast(i));
- v.count = 3;
- try std.testing.expectError(error.StoreInUse, StoreFile.open(gpa, path, false));
- }
- {
- var store = try StoreFile.open(gpa, path, false);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.unchanged, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1));
- const adoption = try store.adopt(gpa, abi.layout.of(V2, .store), D.v2);
- try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset);
- const v: *V2 = @ptrCast(@alignCast(store.root()));
- try std.testing.expectEqual(@as(u8, 7), v.added);
- try std.testing.expectEqual(@as(u32, 9999), v.list.items[9999]);
- v.list.deinit(store.allocator());
- }
- var store = try StoreFile.open(gpa, path, true);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2));
+ var state: State = .init(gpa);
+ defer state.deinit(gpa);
+ try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1));
+ @as(*V1, @ptrCast(state.live().ptr)).score = 99;
+ try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1));
+ try std.testing.expectEqual(@as(u32, 99), @as(*V1, @ptrCast(state.live().ptr)).score);
+ const m = (try state.adopt(gpa, abi.layout.of(V2, .state), D.v2)).?;
+ try std.testing.expectEqual(@as(usize, 1), m.reset);
+ try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(@alignCast(state.live().ptr))).*);
+ // The header reads back as the layout.
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ try std.testing.expectEqual(abi.layout.hash(V2), (try layoutOf(arena.allocator(), state.header)).hash);
}
test "arrays migrate element by element: fields, enums by name, shrink and growth" {
@@ -1105,14 +779,15 @@ test "a file that is not a state file is refused, untouched" {
defer std.testing.allocator.free(text);
@memset(text, 'x');
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text });
- try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path));
+ try std.testing.expectError(error.NotAStateFile, OldState.open(path));
const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited);
defer std.testing.allocator.free(after);
try std.testing.expectEqualSlices(u8, text, after);
}
+ try std.testing.expectError(error.FileNotFound, OldState.open(try testPath(&buf, tmp, "none.state")));
}
-test "a state file from before element leaves (drat-meout's) keeps every value" {
+test "a state file from before element leaves (drat-meout's) imports with every value" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
@@ -1132,30 +807,29 @@ test "a state file from before element leaves (drat-meout's) keeps every value"
const h: *const Header = @ptrCast(@alignCast(original.ptr));
const live = original[header_len..][0..h.size];
- // The layout the game had when it wrote the file, as a sketch would
- // describe it: unchanged, so nothing migrates and the header is
- // rewritten in the new format.
- const same = try asSketchLayout(a, old, &.{});
- {
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f));
- try std.testing.expectEqualStrings(&file_magic_v2, &file.header().magic);
- }
- var file = try StateFile.open(gpa, path);
+ const file = try OldState.open(path);
defer file.close();
- try std.testing.expectEqual(old.fields.len, file.layout.fields.len);
- try std.testing.expectEqualSlices(u8, live, file.slot(0));
-
- // A changed layout (one field gone, one new): every other leaf keeps
- // its value, the songs included (an unchanged array type, so whole).
- const changed = try asSketchLayout(a, old, "scene");
- _ = try file.adopt(gpa, changed, NoDefaults.f);
- for (old.fields) |leaf| {
- if (std.mem.eql(u8, leaf.path, "scene")) continue;
- try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0)));
+ try std.testing.expectEqual(@as(usize, old_slot_count), file.slots);
+ // Into the layout the game had when it wrote the file, as a sketch would
+ // describe it: every byte; then into a changed one (one field gone, one
+ // new): every other leaf keeps its value, the songs included (an
+ // unchanged array type, so whole).
+ for ([_][]const u8{ "", "scene" }) |drop| {
+ var state: State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, try asSketchLayout(a, old, drop), NoDefaults.f);
+ @memset(state.live(), 0);
+ _ = try restore(a, file.layoutBytes(), file.slot(0).?, state.layout, state.live(), NoDefaults.f);
+ if (drop.len == 0) try std.testing.expectEqualSlices(u8, live, state.live());
+ for (old.fields) |leaf| {
+ if (drop.len > 0 and std.mem.eql(u8, leaf.path, drop)) continue;
+ try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(state.live()));
+ }
}
- try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]);
+ // The file is as it was.
+ const after = try tmp.dir.readFileAlloc(io, "game.state", gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, original, after);
}
const NoDefaults = struct {
diff --git a/src/host/probe.zig b/src/host/probe.zig
deleted file mode 100644
index 4b61153..0000000
--- a/src/host/probe.zig
+++ /dev/null
@@ -1,86 +0,0 @@
-//! sketchbook-probe: prints the live state of any running sketch, from its
-//! state file alone. The file header carries the layout, so the probe needs
-//! no knowledge of the sketch: it maps the same pages read-only.
-const std = @import("std");
-const memory = @import("memory.zig");
-const fields = @import("fields.zig");
-
-const usage =
- \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE
- \\Prints every field of the live state; --watch prints again on change.
- \\
-;
-
-pub fn main(init: std.process.Init) !void {
- var path: ?[]const u8 = null;
- var watch = false;
- var interval_ms: i64 = 100;
- var args = init.minimal.args.iterate();
- _ = args.skip();
- while (args.next()) |arg| {
- if (std.mem.eql(u8, arg, "--watch")) {
- watch = true;
- } else if (std.mem.eql(u8, arg, "--interval")) {
- interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds");
- } else if (std.mem.startsWith(u8, arg, "-")) {
- std.debug.print("{s}", .{usage});
- return;
- } else path = arg;
- }
- const file = path orelse fatal("no state file given");
- const map = memory.mapReadOnly(file);
- if (map.len < memory.header_len) fatal("not a sketchbook state file");
- const magic = map[0..8];
- if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v2) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file");
- defer std.posix.munmap(map);
- var arena: std.heap.ArenaAllocator = .init(init.gpa);
- defer arena.deinit();
- const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet");
- const header: *const memory.Header = @ptrCast(@alignCast(map.ptr));
- const live = map[memory.header_len..][0..header.size];
-
- const shown = try arena.allocator().dupe(u8, live);
- show(file, layout, live);
- while (watch) {
- try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake);
- if (std.mem.eql(u8, shown, live)) continue;
- @memcpy(shown, live);
- show(file, layout, live);
- }
-}
-
-fn show(path: []const u8, layout: memory.Layout, live: []const u8) void {
- var buf: [4096]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash });
- for (layout.fields) |leaf| {
- // Whole arrays are shown by their elements' leaves.
- if (leaf.whole()) continue;
- w.end = 0;
- if (leaf.dims.len == 0) {
- fields.format(leaf, live, &w) catch {};
- } else {
- // Elements in index order, the first few.
- var it = leaf.elements();
- var n: usize = 0;
- while (it.next()) |offset| : (n += 1) {
- if (n == 8) {
- w.writeAll(" ...") catch {};
- break;
- }
- if (n > 0) w.writeAll(" ") catch {};
- fields.format(leaf.at(offset), live, &w) catch {};
- }
- }
- var name: [128]u8 = undefined;
- var nw: std.Io.Writer = .fixed(&name);
- nw.writeAll(leaf.path) catch {};
- for (leaf.dims) |d| nw.print(" [{d}]", .{d.count}) catch {};
- std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, nw.buffered(), w.buffered() });
- }
-}
-
-fn fatal(message: []const u8) noreturn {
- std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage });
- std.process.exit(2);
-}
diff --git a/src/host/root.zig b/src/host/root.zig
index 5889b42..9c7ad77 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -2,11 +2,11 @@
//! that it hot-reloads whenever a build replaces it.
//!
//! sketchbook [options] [LIBRARY]
-//! --state FILE persistent state (default: $XDG_DATA_HOME/<name>/<name>.state;
-//! sketch.state for a script or an export)
+//! --state FILE the save (default: $XDG_DATA_HOME/<name>/<name>.xitdb;
+//! sketch.xitdb for a script or an export)
//! --headless offscreen video, silent audio
//! --script FILE play a script instead of reading devices
-//! --fresh start from default state (sessions, marks and clips are kept)
+//! --fresh start from default state (the save's history is kept)
//! --timing-marker encode frame ID and draw sample time for video analysis
//! --profile-gpu time each GPU command alone, print the times at exit
//! --console LINE run a console line once the sketch is loaded (repeatable)
@@ -93,25 +93,9 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
} else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg");
}
- // A scripted run from fresh state works on files of its own, moved to
- // the given path at exit: two runs of one build step (two `zig build`s
- // at once share its output path) never share a state or store file,
- // nor fail on the store's lock (its sessions are in memory). An export's are
- // removed instead: nothing reads them, and a player may have the given
- // ones open.
- var private_buf: [std.fs.max_path_bytes]u8 = undefined;
- if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.state";
- const given = options.state;
- const private = (script_path != null or options.export_to != null) and options.fresh;
- if (!private) sketchbookDir(init.io, given);
- if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long");
- defer if (private) for ([_][]const u8{ "", ".store" }) |suffix| {
- var from: [std.fs.max_path_bytes + 16]u8 = undefined;
- var to: [std.fs.max_path_bytes + 16]u8 = undefined;
- const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue;
- const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue;
- _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr);
- };
+ if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb";
+ // A scripted run from fresh state, or an export, touches no save.
+ if (!((script_path != null or options.export_to != null) and options.fresh)) sketchbookDir(init.io, options.state);
sdl_heap.install();
{
@@ -131,11 +115,12 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
const usage =
\\usage: sketchbook [options] [LIBRARY]
\\ --9p SOCKET local 9P controls: ctl, status, log, screen.png
- \\ --state FILE persistent state; sessions are kept beside it (default:
- \\ $XDG_DATA_HOME/<name>/<name>.state, sketch.state for --script, --export)
+ \\ --state FILE the save, one file: FILE, or FILE.xitdb for a FILE.state (where a
+ \\ state file from before is imported from, once); default:
+ \\ $XDG_DATA_HOME/<name>/<name>.xitdb, sketch.xitdb for --script, --export
\\ --headless offscreen video, silent audio, no vsync
\\ --script FILE play a script instead of reading devices
- \\ --fresh start from default state (sessions, marks and clips are kept)
+ \\ --fresh start from default state (the save's history is kept)
\\ --timing-marker encode frame ID and draw sample time for video analysis
\\ --profile-gpu time each GPU command alone, print the times at exit
\\ --console LINE run a console line once the sketch is loaded (repeatable)
@@ -148,10 +133,10 @@ const usage =
\\
;
-/// A state file in a directory named `.sketchbook` (`zig build run`'s):
-/// the directory is made, with a `.gitignore` of `*` (its sessions database
-/// grows, and a jj snapshot would commit it), and the state and store files
-/// an older build kept beside it are moved in, once. A file is never
+/// A save in a directory named `.sketchbook` (`zig build run`'s): the
+/// directory is made, with a `.gitignore` of `*` (the save grows, and a jj
+/// snapshot would commit it), and the state file an older build kept beside
+/// it (`<stem>.state`) is moved in, once, to be imported. A file is never
/// replaced: when both exist, nothing moves.
fn sketchbookDir(io: std.Io, state: []const u8) void {
const dir = std.fs.path.dirname(state) orelse return;
@@ -161,20 +146,16 @@ fn sketchbookDir(io: std.Io, state: []const u8) void {
var buf: [std.fs.max_path_bytes]u8 = undefined;
const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return;
cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {};
- for ([_][]const u8{ "", ".store" }) |suffix| {
- var from_buf: [std.fs.max_path_bytes]u8 = undefined;
- var to_buf: [std.fs.max_path_bytes]u8 = undefined;
- const parent = std.fs.path.dirname(dir) orelse ".";
- const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}{s}", .{ parent, std.fs.path.basename(state), suffix }, 0) catch return;
- const to = std.fmt.bufPrintSentinel(&to_buf, "{s}{s}", .{ state, suffix }, 0) catch return;
- switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) {
- .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }),
- .EXIST => {
- std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to });
- return;
- },
- else => {},
- }
+ var from_buf: [std.fs.max_path_bytes]u8 = undefined;
+ var to_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const parent = std.fs.path.dirname(dir) orelse ".";
+ const stem = Host.stemOf(std.fs.path.basename(state));
+ const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}.state", .{ parent, stem }, 0) catch return;
+ const to = std.fmt.bufPrintSentinel(&to_buf, "{s}/{s}.state", .{ dir, stem }, 0) catch return;
+ switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) {
+ .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }),
+ .EXIST => std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to }),
+ else => {},
}
}
diff --git a/src/host/timeline.zig b/src/host/timeline.zig
index c2eeff3..e755433 100644
--- a/src/host/timeline.zig
+++ b/src/host/timeline.zig
@@ -45,8 +45,8 @@ pub const Frames = struct {
pub const Timeline = struct {
gpa: std.mem.Allocator,
- /// Live state is its slot 0.
- state: *memory.StateFile,
+ /// Live State.
+ state: *memory.State,
/// The running sketch's: a restore starts from its defaults.
defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void,
mode: abi.Mode = .live,
@@ -90,7 +90,7 @@ pub const Timeline = struct {
pub fn restore(self: *Timeline, key: Sessions.Loaded) !void {
var arena: std.heap.ArenaAllocator = .init(self.gpa);
defer arena.deinit();
- _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.slot(0), self.defaults);
+ _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.live(), self.defaults);
self.restored = true;
self.fed = 0;
self.next_check = 0;
@@ -202,18 +202,14 @@ pub const Timeline = struct {
test "frames are whole: input waits for its tick, in playback, seek and step" {
const gpa = std.testing.allocator;
- // Live state on plain memory: 8 bytes, no fields.
- var file: memory.StateFile = undefined;
- file.map = try gpa.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.page);
- defer gpa.free(file.map);
- @memset(file.map, 0);
- file.slots = 1;
- file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 1, .field_count = 0, .strings_len = 0 };
- file.layout = .{ .size = 8, .hash = 1 };
+ // Live State: 8 bytes, no fields.
const D = struct {
fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {}
};
- var t: Timeline = .{ .gpa = gpa, .state = &file, .defaults = D.f };
+ var state: memory.State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, .{ .size = 8, .alignment = 1, .hash = 1, .fields = &.{} }, D.f);
+ var t: Timeline = .{ .gpa = gpa, .state = &state, .defaults = D.f };
defer t.deinit();
// Frame k: a move at 10k ms, its tick 5 ms later; then a move with no
// tick (a frame cut off).
@@ -223,7 +219,7 @@ test "frames are whole: input waits for its tick, in playback, seek and step" {
try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667));
}
try events.append(gpa, .{ .kind = .mouse_move, .time = 40_000_000 });
- const key: Sessions.Loaded = .{ .frame = 0, .batch = 0, .why = .mark, .time = 0, .stretch = 0, .build = 7, .state = try gpa.dupe(u8, &@as([8]u8, @splat(0))), .line = try gpa.dupe(u8, ""), .source = try gpa.dupe(u8, ""), .layout = try gpa.dupe(u8, file.layoutBytes()) };
+ const key: Sessions.Loaded = .{ .frame = 0, .batch = 0, .why = .mark, .time = 0, .stretch = 0, .build = 7, .state = try gpa.dupe(u8, &@as([8]u8, @splat(0))), .line = try gpa.dupe(u8, ""), .source = try gpa.dupe(u8, ""), .layout = try gpa.dupe(u8, state.header) };
t.load(key, events);
try t.play(0);
diff --git a/src/layout.zig b/src/layout.zig
index 5e60e22..c585d71 100644
--- a/src/layout.zig
+++ b/src/layout.zig
@@ -13,23 +13,28 @@
//! against a leaf's pattern at lookup time.
//!
//! What each kind of sketch memory may hold:
-//! - State is saved to disk and snapshotted: no pointers, and no host
-//! handles (images, sounds, buffers), which only mean something in the
-//! process that made them.
+//! - State is saved, the one thing a sketch keeps, in keyframes of its
+//! save: no pointers, and no host handles (images, sounds, buffers),
+//! which only mean something in the process that made them; at most
+//! `max_state` bytes.
//! - Session lives in this process: anything, as long as pointers go into
//! memory the host owns (its heaps, mapped files), never into the sketch
//! library, which a reload unmaps.
-//! - Store is a file mapped at the same address in every run: pointers into
-//! the store itself, but no host handles.
const std = @import("std");
const abi = @import("abi.zig");
+/// The most a State may be, in bytes: half of the 64 MiB a save holds, so
+/// history has room (Sessions.max_save).
+pub const max_state = 32 << 20;
+
pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout {
return comptime blk: {
@setEvalBranchQuota(1_000_000);
switch (memory) {
- .state => check(T, "State", @typeName(T), false),
- .store => check(T, "Store", @typeName(T), true),
+ .state => {
+ check(T, @typeName(T));
+ if (@sizeOf(T) > max_state) @compileError(std.fmt.comptimePrint("State is {d} bytes, and may be {d} MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session.", .{ @sizeOf(T), max_state >> 20 }));
+ },
.session => {},
}
const Leaves = struct {
@@ -155,17 +160,16 @@ pub fn resolve(fields: []const abi.Field, path: []const u8) ?Resolved {
return null;
}
-fn check(comptime T: type, comptime memory: []const u8, comptime path: []const u8, comptime pointers: bool) void {
+fn check(comptime T: type, comptime path: []const u8) void {
comptime {
- if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError(memory ++ " cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session.");
+ if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError("State cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session.");
switch (@typeInfo(T)) {
- // Not followed: types can point to themselves.
- .pointer => if (!pointers) @compileError(memory ++ " cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Store or Session."),
- .array => |a| check(a.child, memory, path ++ "[]", pointers),
- .vector => |v| check(v.child, memory, path ++ "[]", pointers),
- .optional => |o| check(o.child, memory, path, pointers),
- .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers),
- .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers),
+ .pointer => @compileError("State cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Session."),
+ .array => |a| check(a.child, path ++ "[]"),
+ .vector => |v| check(v.child, path ++ "[]"),
+ .optional => |o| check(o.child, path),
+ .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, path ++ "." ++ name),
+ .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, path ++ "." ++ name),
else => {},
}
}
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 d15046d..2a7c64a 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");
@@ -67,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
@@ -82,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 {
@@ -219,6 +215,13 @@ pub const Frame = struct {
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 } });
}
@@ -291,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);
@@ -311,7 +313,7 @@ pub const Console = struct {
pub const Build = struct {
/// The repository revision the sketch was built from, "" when unknown.
source: []const u8 = "",
- /// Record sessions to a file (`abi.Info.record`).
+ /// Keep history in the save (`abi.Info.record`).
record: bool = false,
};
@@ -339,7 +341,6 @@ 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.*;
@@ -350,7 +351,6 @@ pub fn Glue(comptime App: type, comptime made: Build) 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,
@@ -377,10 +377,10 @@ pub fn Glue(comptime App: type, comptime made: Build) 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");
@@ -389,8 +389,6 @@ pub fn Glue(comptime App: type, comptime made: Build) 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)
@@ -416,7 +414,6 @@ pub fn Glue(comptime App: type, comptime made: Build) 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 {
@@ -424,7 +421,7 @@ pub fn Glue(comptime App: type, comptime made: Build) 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});
@@ -442,7 +439,7 @@ pub fn Glue(comptime App: type, comptime made: Build) 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;
@@ -488,7 +485,6 @@ 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, .{});
try std.testing.expect(!app.setup(&ctx));
defer std.testing.allocator.free(session.bytes);
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 62a173a..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;
@@ -82,8 +84,6 @@ fn Driver(comptime App: type) type {
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| {
@@ -414,6 +415,7 @@ fn Driver(comptime App: type) type {
.newSound = newSound,
.samples = samples,
.readFile = readFile,
+ .appendFile = appendFile,
.env = env,
.clock = clock,
};
@@ -478,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;
}
diff --git a/test/killed.script b/test/killed.script
index cceeb48..7d0899c 100644
--- a/test/killed.script
+++ b/test/killed.script
@@ -1,4 +1,6 @@
# After test/kill.script: its session kept the four commits of 60 frames it
-# made before it was killed, and says it crashed.
+# made before it was killed, and says it crashed; this run starts from them,
+# replayed.
+expect updates 240
console sessions
expect-log frames 240 (crashed)
diff --git a/web/host.js b/web/host.js
index efc335d..32bdbfb 100644
--- a/web/host.js
+++ b/web/host.js
@@ -314,13 +314,16 @@ const gpu = {
// Reads a buffer back; it reaches the sketch before a later frame.
arrived: [],
download(id, offset, size, key) {
+ gpu.read(id, offset, size, bytes => gpu.arrived.push({key, bytes}));
+ },
+ read(id, offset, size, then) {
const staging = gpu.spare.find(b => b.size >= size) ?? gpu.device.createBuffer({size: Math.max(size, 256), usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST});
gpu.spare = gpu.spare.filter(b => b !== staging);
const commands = gpu.device.createCommandEncoder();
commands.copyBufferToBuffer(gpu.buffers[id], offset, staging, 0, size);
gpu.device.queue.submit([commands.finish()]);
staging.mapAsync(GPUMapMode.READ, 0, size).then(() => {
- gpu.arrived.push({key, bytes: new Uint8Array(staging.getMappedRange(0, size)).slice()});
+ then(new Uint8Array(staging.getMappedRange(0, size)).slice());
staging.unmap();
gpu.spare.push(staging);
}, () => {});
@@ -392,7 +395,8 @@ const sound = {
}
},
queue(key) {
- if (!sound.queues.has(key)) sound.queues.set(key, {chunks: [], at: 0, queued: 0});
+ // `waiting`: GPU buffers on their way, in order (counted as queued).
+ if (!sound.queues.has(key)) sound.queues.set(key, {chunks: [], waiting: [], at: 0, queued: 0});
return sound.queues.get(key);
},
listen() {
@@ -660,9 +664,21 @@ const imports = {
push(key, ptr, len, clear) {
if (len) sound.hint();
const q = sound.queue(key);
- if (clear) { q.chunks = []; q.at = 0; q.queued = 0; }
+ if (clear) { q.chunks = []; q.waiting = []; q.at = 0; q.queued = 0; }
if (len) { q.chunks.push(new Float32Array(wasm.memory.buffer.slice(ptr, ptr + len * 4))); q.queued += len; }
},
+ buffer(key, id, offset, count) {
+ if (!gpu.buffers[id]) return;
+ sound.hint();
+ const q = sound.queue(key);
+ const chunk = {samples: null};
+ q.waiting.push(chunk);
+ q.queued += count;
+ gpu.read(id, offset, count * 4, bytes => {
+ chunk.samples = new Float32Array(bytes.buffer);
+ while (q.waiting.length && q.waiting[0].samples) q.chunks.push(q.waiting.shift().samples);
+ });
+ },
queued: key => sound.queues.get(key)?.queued ?? 0,
listen: () => sound.listen(),
},