# Take Stamp protocol

Frames are **LSTN v2** exactly as in `/workspace/listento/RELAY_STAMP_SPEC.md` (section 2), so a
Take Stamp dump is also a valid Listen stream:

- 56-byte header, little-endian except magic `"LSTN"`.
- Take Stamp always sends **type 3 (PCM f32le)**, 20 ms frames (960 @ 48 kHz), flags `PLAYING|BITPERFECT`
  (`DISCONT` on the first frame after play/locate/loop), `marker_off=0xFFFF` (no chirp: placement is
  by stamp, not by chirp), `tier=0`.
- `song_pos_ns` = Marcus's Logic playhead (host `timeInSamples`) at the frame's first sample, in ns.
  `samples = round(ns*rate/1e9)`; this round trip is exact (tested 44.1-192 kHz, 0-2.3 h).
- `stamp_us` = sender wall clock (UNIX us) at the first sample. Receivers use it as **take recency**:
  when two passes cover the same song position, the newer pass wins, regardless of arrival order.
- `crc32` of the payload; receivers count mismatches (should be 0 = bit-perfect transport).
- `payload_len` (offset 52) = payload bytes, per the Listen spec. (Builds before 2026-11-18 23:00 CT wrote 0 here.)
- **Session frames** (producer-started takes): flag **b4 `SESSION` (0x10)** and `hdr_len = 60`, with a
  **u32 `take_id` at offset 56**. Readers that follow the spec (skip `hdr_len`) are unaffected. Session
  frames are 2 channels: **ch0 = performer's mic (vocal), ch1 = the beat/click exactly as the performer
  hears it**, both stamped with the same song position.

## Relay (https://marcusx.fun/takestamp, supernode 127.0.0.1:19360)

RAM-only. A bounded in-memory ring (128 MB, ~5.5 min of stereo f32 @ 48 k) so a receiver can
reconnect without loss. Restart = empty. No files, no recordings, no logs of audio.

| call | what |
|---|---|
| `POST /api/push` | body = one or more frames back to back |
| `GET /api/pull?after=N&epoch=E&wait=10` | long-poll; body = frames back to back. Headers `X-TakeStamp-Epoch`, `X-TakeStamp-Head`, `X-TakeStamp-Last` (pass Last as next `after`; if the epoch changed the relay restarted and replays from 0) |
| `GET /api/status` | open; JSON, no audio |
| `POST /api/clear` | drop the ring |

Auth: `X-TakeStamp-Key: [redacted]` (or `X-Listen-Password`, or `?key=`), or the page cookie. Password
`[redacted]` is the only gate.

## Placement rule (receiver)

`out[Lou_pos] = take[Lou_pos + lead]` where `take` is the song timeline built from stamps. If
Marcus's and Lou's sample rates differ, positions are mapped through seconds with linear
interpolation. Through-the-preamps Print: input arriving at Lou position `u` is filed at
`u - loop + lead`, where `loop` is the measured ping round trip.

## Session channel (producer-controlled record)

Marcus never presses play. The producer's Record starts both sides; during the take the producer's
local playback is muted and replaced by Marcus's stamped feed (vocal + the beat as he hears it), so
both share one monitor. Lag doesn't matter: every sample carries its song position and is placed by
it. RAM-only, same key as the audio (`[redacted]`), no other gate.

| call | what |
|---|---|
| `POST /api/session` | JSON event (below). The relay adds `seq`, `relay_us`, and for `record_start` a `take_id` if none was given; replies `{"ok":true,"event":{...}}` |
| `GET /api/session?after=N&epoch=E&wait=S` | long-poll (S <= 25). `{"epoch","head","events":[...],"state":{...},"now_us"}`. `after=-1` (or omitted) = just learn `head`/`state`. If `epoch` changed the relay restarted; resume from 0 |
| `GET /api/status` | now also includes `session` (current state) and `session_head` |

Events (`type`):

| type | sender | fields |
|---|---|---|
| `record_start` | producer | `tempo` (BPM), `start_song_pos_ns`, `rate`, `count_in_beats`, `producer_press_us` -> relay assigns `take_id` |
| `record_stop` | producer | `take_id`, `stop_song_pos_ns`, `producer_stop_us` |
| `performer_started` | performer | `take_id`, `performer_start_us`, `song_start_samples`, `rate`, `auto: true`, `button_pressed: false` |
| `performer_stopped` | performer | `take_id`, `end_song_samples` (exclusive, after the tail was shipped), `performer_stop_us` |
| `producer_mode`, `hello` | either | free-form status (optional) |

Sequence:

```
producer  Record ─ record_start{tempo,pos,rate} ─▶ relay ─▶ performer (long-poll)
                     mute local playback                    starts its own transport at `pos`
                                                            plays click/beat, streams SESSION frames
          monitor ◀── frames (take_id, song pos) ◀── relay ◀─┘   ch0 vocal, ch1 beat-as-heard
          = Marcus's feed through a fixed buffer
          capture = ch0 written at its song position (arrival time ignored)
producer  Stop ─── record_stop ──────────────────▶ relay ─▶ performer stops, ships tail,
          DRAIN: play out tail  ◀── performer_stopped{end_song_samples}
          -> back to TALK automatically (plugin also exports the take as a BWF at its song position)
```

Producer rules: monitor playout starts `buffer` ms after the first frame of the take lands, at that
frame's song position, then advances one block at a time **only if the whole block is present**;
otherwise it holds (silence, "stall") and resumes, so vocal and beat can never come apart (they ride in
the same frames). The monitor therefore runs behind the producer's own playhead by about
`control delay + uplink delay + buffer`; that lag never touches placement.
Performer rules: stamp the mic at `song pos - I/O comp` together with the beat from `I/O comp` samples
ago (both lanes then agree with what Marcus actually heard). A record_stop for another `take_id` is ignored.
