/* voltergeist.h: the voltergeist wire format (SPEC.md, draft v1) in C99, one header.
 *
 * Declarations always; the code under `#define VOLTERGEIST_IMPLEMENTATION` in exactly one .c file.
 * No allocation (the caller passes every buffer), no global state, no libc beyond memcpy, memmove and memset.
 * Every multi-byte number is read and written byte by byte, so the code is endian independent.
 * Assumes float is IEEE 754 binary32 and double binary64 (true on ARM, x86, RISC-V; not on AVR).
 * MIT licence, as the rest of the repository. */
#ifndef VOLTERGEIST_H
#define VOLTERGEIST_H

#include <stddef.h>
#include <stdint.h>

#ifndef VG_API
#define VG_API
#endif

#ifdef __cplusplus
extern "C" {
#endif

/* VG_FRAME_MAX: no frame is longer (SPEC.md 1.2), so every frame fits the byte stream's u16 prefix. */
enum { VG_VERSION = 1, VG_HEAD = 16, VG_STREAM_PREFIX = 2, VG_STREAM_MAX = 65535, VG_FRAME_MAX = 65535, VG_EVENT_SIZE = 12 };
/* A MIDI frame's record head (i32 offset, u16 length) and the longest SysEx message, F0 and F7 included (SPEC.md 4.4). */
enum { VG_MIDI_RECORD = 6, VG_SYSEX_MAX = 1024 };

/* Flags, byte 0 low nibble. */
enum { VG_FLAG_EXT = 1, VG_FLAG_IRREGULAR = 2, VG_FLAG_REDUNDANT = 4, VG_FLAG_RESERVED = 8 };

/* Frame types (SPEC.md 3). */
enum { VG_SAMPLES = 1, VG_EVENTS = 2, VG_MAP = 3, VG_MIDI = 4, VG_HELLO = 16, VG_PING = 17, VG_PONG = 18, VG_CLOCK = 19, VG_REPORT = 20 };

/* Sample formats, event kinds, HELLO roles, map kinds. */
enum { VG_F32 = 1, VG_I16 = 2, VG_I24 = 3 };
enum { VG_GATE = 1, VG_TRIGGER = 2, VG_NOTE_ON = 3, VG_NOTE_OFF = 4 };
enum { VG_ROLE_SENDER = 1, VG_ROLE_RECEIVER = 2, VG_ROLE_BOTH = 3 };
enum { VG_KIND_SAMPLES = 1, VG_KIND_EVENTS = 2 };

/* Status. VG_OK and VG_SKIP are not rejects; every negative one is, named as the JS reader names it
 * (vg_status_name gives the string, which matches the `error` field of vectors/reject.json). */
enum {
  VG_OK = 0, VG_SKIP = 1,
  VG_E_SHORT = -1, VG_E_VERSION = -2, VG_E_FLAGS = -3, VG_E_CLOCK = -4, VG_E_CHANNELS = -5, VG_E_FORMAT = -6,
  VG_E_COUNT = -7, VG_E_REDUNDANT = -8, VG_E_LENGTH = -9, VG_E_OFFSETS = -10, VG_E_VALUE = -11, VG_E_KIND = -12,
  VG_E_JSON = -13, VG_E_MAP_ID = -14, VG_E_MAP = -15, VG_E_ROLE = -16, VG_E_UTF8 = -17, VG_E_STATUS = -18, VG_E_MIDI = -19,
  VG_E_SYSEX = -20
};
/* The most negative status, for a caller that checks a status is one of these. */
enum { VG_E_LAST = VG_E_SYSEX };

typedef struct { uint16_t type; uint16_t words; const uint8_t *data; } vg_ext; /* data is 4 x words bytes */

typedef struct { int32_t offset; uint8_t channel; uint8_t kind; uint16_t note; float value; } vg_event;

/* Decoded bodies. Pointers point INTO the decoded buffer (zero copy); read them with the accessors below. */
typedef struct {
  uint8_t channels, format, count, redundant; /* n, format, k, r */
  uint16_t map;
  const uint8_t *offsets; /* k x i32 on the wire, NULL unless the I flag is set */
  const uint8_t *values;  /* k x n values on the wire, sample major */
} vg_samples;
typedef struct { uint8_t count, redundant; uint16_t map; const uint8_t *events; } vg_events;
typedef struct { uint8_t count, redundant; const uint8_t *records; } vg_midi; /* m records: i32 offset, u16 L, L bytes */
typedef struct { uint16_t map; uint16_t len; const uint8_t *json; } vg_map;  /* JSON checked, not parsed */
typedef struct { uint8_t role; size_t len; const uint8_t *name; } vg_hello;  /* UTF-8; a leading BOM is part of the name */
typedef struct { double t0, t1; } vg_pong;
typedef struct { double offset, rtt; } vg_clock;
typedef struct { uint8_t fraction; uint16_t late_fired; int32_t lost; uint32_t highest, jitter, late, recovered; } vg_report;
typedef struct { size_t len; const uint8_t *data; } vg_body; /* an unknown type's body, after any extension */

typedef struct {
  uint8_t type, flags; /* flags: the low nibble of byte 0 */
  uint16_t stream;
  uint32_t seq;
  double clock;
  int has_ext;
  vg_ext ext;
  union { vg_samples samples; vg_events events; vg_midi midi; vg_map map; vg_hello hello; vg_pong pong; vg_clock clock;
          vg_report report; vg_body unknown; } u;
} vg_frame;

/* Decode one frame (one datagram, one message, or one frame from vg_reader_feed).
 * VG_OK, VG_SKIP (version 1, a type this reader does not know: ignore it, keep the connection), or a reject < 0. */
VG_API int vg_decode(const uint8_t *buf, size_t len, vg_frame *f);
VG_API const char *vg_status_name(int status);

/* Accessors for a decoded SAMPLES or EVENTS frame; i < count, c < channels. */
VG_API int32_t vg_offset(const vg_frame *f, unsigned i);
VG_API float vg_sample_f32(const vg_frame *f, unsigned i, unsigned c);  /* format VG_F32 */
VG_API int32_t vg_sample_int(const vg_frame *f, unsigned i, unsigned c); /* format VG_I16 or VG_I24, raw */
VG_API double vg_sample(const vg_frame *f, unsigned i, unsigned c);     /* any format, raw, as a double */
VG_API void vg_event_at(const vg_frame *f, unsigned i, vg_event *e);

/* A MIDI frame's message i (i < count): bytes point into the frame. Walks from the first record, so O(i). */
typedef struct { int32_t offset; uint16_t len; const uint8_t *bytes; } vg_midi_msg;
VG_API void vg_midi_at(const vg_frame *f, unsigned i, vg_midi_msg *m);
/* One MIDI message against SPEC.md 4.4: VG_OK, VG_E_STATUS (no status byte, so running status, or an undefined one),
 * VG_E_MIDI (length not the status's, a data byte over 7F) or VG_E_SYSEX (no F7, over VG_SYSEX_MAX, a status inside).
 * A receiver drops a valid SysEx message (bytes[0] == 0xF0) unless its owner allowed SysEx. */
VG_API int vg_midi_check(const uint8_t *bytes, size_t len);

/* Integer raw values to the channel's unit (SPEC.md 4.1 Values): raw / full scale, clamped at -1, then onto
 * min..max when has_range. f32 passes through. vg_from_unit is the inverse, rounded and clamped. */
VG_API double vg_to_unit(double raw, int format, int has_range, double min, double max);
VG_API int32_t vg_from_unit(double value, int format, int has_range, double min, double max);

/* Encoding. Every encoder returns the frame's length in bytes, or 0 when it refuses: bad arguments, a frame over VG_FRAME_MAX, or cap too small.
 * With out NULL it only checks and returns the length needed. An encoder never writes a frame a reader rejects. */
typedef struct { uint16_t stream; uint32_t seq; double clock; const vg_ext *ext; /* NULL: no extension */ } vg_head;

typedef struct {
  uint16_t map; uint8_t channels, format, count, redundant;
  const int32_t *offsets; /* k offsets, sets I; NULL for a regular frame */
  const float *f32;       /* k x n, for VG_F32 */
  const int32_t *ints;    /* k x n raw, for VG_I16 and VG_I24, clamped to the format's range */
} vg_samples_in;

VG_API size_t vg_encode_samples(uint8_t *out, size_t cap, const vg_head *h, const vg_samples_in *s);
VG_API size_t vg_encode_events(uint8_t *out, size_t cap, const vg_head *h, uint16_t map, uint8_t redundant,
                               const vg_event *events, size_t count);
VG_API size_t vg_encode_map(uint8_t *out, size_t cap, const vg_head *h, uint16_t map, const uint8_t *json, size_t len);
VG_API size_t vg_encode_midi(uint8_t *out, size_t cap, const vg_head *h, uint8_t redundant, const vg_midi_msg *msgs, size_t count);
VG_API size_t vg_encode_hello(uint8_t *out, size_t cap, const vg_head *h, uint8_t role, const uint8_t *name, size_t len);
VG_API size_t vg_encode_ping(uint8_t *out, size_t cap, const vg_head *h);
VG_API size_t vg_encode_pong(uint8_t *out, size_t cap, const vg_head *h, double t0, double t1);
VG_API size_t vg_encode_clock(uint8_t *out, size_t cap, const vg_head *h, double offset, double rtt);
VG_API size_t vg_encode_report(uint8_t *out, size_t cap, const vg_head *h, const vg_report *r);
/* A type this library does not know (0, 5 to 15, 21 to 255) with an opaque body, for v1.x types. */
VG_API size_t vg_encode_raw(uint8_t *out, size_t cap, const vg_head *h, uint8_t type, const uint8_t *body, size_t len);

/* The MAP's JSON (SPEC.md 4.3), checked without allocation and without a parse tree. vg_map_info returns VG_OK,
 * VG_E_JSON (not UTF-8, not JSON, not an object) or VG_E_MAP (breaks the key table); info may be NULL. */
typedef struct { int kind; double rate; int format; unsigned channels; } vg_map_info_t;
typedef struct {
  const uint8_t *name; size_t name_len; /* the JSON string's raw bytes between the quotes, escapes as written */
  int has_min, has_max, has_voct; double min, max, voct;
  int has_clamp, has_slew; double clamp_lo, clamp_hi, slew; /* safety limits, SPEC.md 6.1 */
} vg_map_channel_t;
VG_API int vg_map_info(const uint8_t *json, size_t len, vg_map_info_t *info);
VG_API int vg_map_channel(const uint8_t *json, size_t len, unsigned index, vg_map_channel_t *ch);
VG_API int vg_utf8_valid(const uint8_t *s, size_t len);

/* Byte streams (SPEC.md 1.1): each frame behind a u16 length. The reader takes chunks of any size. */
typedef struct {
  uint8_t *buf; size_t cap;   /* holds a frame split across chunks; frames longer than cap are skipped */
  size_t have; uint16_t need; uint8_t prefix[2], got, skipping;
  int error;                  /* VG_E_LENGTH once a length under 16 arrived; the reader then stops */
  uint32_t oversize;          /* frames skipped because they did not fit buf */
} vg_reader;
VG_API void vg_reader_init(vg_reader *r, uint8_t *buf, size_t cap);
/* Consumes bytes until one whole frame is ready or data runs out; returns how many it consumed. On a frame,
 * *frame and *frame_len are set (else NULL and 0); the frame is valid until the next call (it may point into data).
 * Call again with the rest of the chunk. */
VG_API size_t vg_reader_feed(vg_reader *r, const uint8_t *data, size_t len, const uint8_t **frame, size_t *frame_len);
/* Puts the length in front of a frame: out gets len + 2 bytes. out and frame may overlap. 0 when refused. */
VG_API size_t vg_stream_wrap(uint8_t *out, size_t cap, const uint8_t *frame, size_t len);

/* The clock estimator (SPEC.md 5.3): the last `keep` pongs, the fastest third by round trip, the median of their
 * offsets. offset is the answerer's clock minus this end's. */
#ifndef VG_CLOCK_KEEP
#define VG_CLOCK_KEEP 120
#endif
typedef struct { double rtt[VG_CLOCK_KEEP], offset[VG_CLOCK_KEEP]; unsigned keep, head, n; } vg_clock_est;
typedef struct { double offset, rtt; unsigned n, used; } vg_clock_best;
VG_API void vg_clock_init(vg_clock_est *e, unsigned keep); /* keep 0 or above VG_CLOCK_KEEP means VG_CLOCK_KEEP */
VG_API void vg_clock_add(vg_clock_est *e, double t0, double t1, double t2, double t3);
VG_API void vg_clock_pong(vg_clock_est *e, const vg_frame *pong, double t3);
VG_API int vg_clock_get(const vg_clock_est *e, vg_clock_best *out); /* 0 until a pong arrived */

/* Sample playout (SPEC.md 6), on fixed storage: read(T) takes T on the SENDER's clock. */
enum { VG_PLAY_EMPTY = 0, VG_PLAY_OK = 1, VG_PLAY_HOLD = 2, VG_PLAY_GAP = 3 };
enum { VG_MODE_HOLD = 0, VG_MODE_INTERPOLATE = 1 };
typedef struct { int64_t seq; double t; } vg_slot;
typedef struct {
  vg_slot *slot; float *values; size_t cap, size; unsigned channels; int mode;
  int started; double playhead; uint32_t overflow;
} vg_playout;
VG_API void vg_playout_init(vg_playout *p, vg_slot *slots, float *values, size_t cap, unsigned channels, int mode);
VG_API int vg_playout_push(vg_playout *p, int64_t seq, double t, const float *values); /* 0: late, a repeat, or full */
VG_API int vg_playout_read(vg_playout *p, double T, float *out); /* VG_PLAY_*; out untouched when EMPTY */

/* Safety limits on one channel (SPEC.md 6.1), no allocation: move at most `slew` units a second toward x (slew 0:
 * none), then clamp to [lo, hi] when has_clamp. now_us is the receiver's clock. Fill it from the map's channel, or
 * from the receiver's own setting, which replaces the map's; vg_limit_set keeps the last output across a change. */
typedef struct { int has_clamp; double lo, hi, slew; int started; double y, t; } vg_limit;
VG_API void vg_limit_init(vg_limit *l, int has_clamp, double lo, double hi, double slew);
VG_API void vg_limit_set(vg_limit *l, int has_clamp, double lo, double hi, double slew);
VG_API double vg_limit_apply(vg_limit *l, double x, double now_us);

/* Event playout: due(T) hands back events with t <= T in clock order, then seq. */
#ifndef VG_EVENT_SEEN
#define VG_EVENT_SEEN 256
#endif
typedef struct { int64_t seq; double t; vg_event ev; } vg_timed_event;
typedef struct {
  vg_timed_event *buf; size_t cap, size; int64_t seen[VG_EVENT_SEEN]; unsigned seen_n, seen_head; uint32_t overflow;
} vg_event_playout;
VG_API void vg_events_init(vg_event_playout *p, vg_timed_event *buf, size_t cap);
VG_API int vg_events_push(vg_event_playout *p, int64_t seq, double t, const vg_event *ev); /* 0: a repeat, or full */
VG_API size_t vg_events_due(vg_event_playout *p, double T, vg_timed_event *out, size_t max);

#ifdef __cplusplus
}
#endif
#endif /* VOLTERGEIST_H */

#ifdef VOLTERGEIST_IMPLEMENTATION
#ifndef VOLTERGEIST_IMPLEMENTED
#define VOLTERGEIST_IMPLEMENTED

#include <string.h>

typedef char vg__float_is_32[sizeof(float) == 4 ? 1 : -1];
typedef char vg__double_is_64[sizeof(double) == 8 ? 1 : -1];

#ifndef VG_JSON_DEPTH
#define VG_JSON_DEPTH 32 /* nesting a MAP may use; deeper is a reject here and accepted by JS */
#endif

static uint16_t vg__rd16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); }
static uint32_t vg__rd32(const uint8_t *p) {
  return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static uint64_t vg__rd64(const uint8_t *p) { return (uint64_t)vg__rd32(p) | ((uint64_t)vg__rd32(p + 4) << 32); }
static void vg__wr16(uint8_t *p, uint16_t x) { p[0] = (uint8_t)x; p[1] = (uint8_t)(x >> 8); }
static void vg__wr32(uint8_t *p, uint32_t x) {
  p[0] = (uint8_t)x; p[1] = (uint8_t)(x >> 8); p[2] = (uint8_t)(x >> 16); p[3] = (uint8_t)(x >> 24);
}
static void vg__wr64(uint8_t *p, uint64_t x) { vg__wr32(p, (uint32_t)x); vg__wr32(p + 4, (uint32_t)(x >> 32)); }

static float vg__bits_f32(uint32_t b) { float x; memcpy(&x, &b, 4); return x; }
static double vg__bits_f64(uint64_t b) { double x; memcpy(&x, &b, 8); return x; }
static uint32_t vg__f32_bits(float x) { uint32_t b; memcpy(&b, &x, 4); return b; }
static uint64_t vg__f64_bits(double x) { uint64_t b; memcpy(&b, &x, 8); return b; }
/* Finite means the exponent is not all ones; read from the bits, so -ffast-math cannot fold it away. */
static int vg__fin32(uint32_t b) { return ((b >> 23) & 0xffu) != 0xffu; }
static int vg__fin64(uint64_t b) { return ((b >> 52) & 0x7ffu) != 0x7ffu; }
static int vg__finite(double x) { return vg__fin64(vg__f64_bits(x)); }

static int32_t vg__rdi24(const uint8_t *p) {
  uint32_t u = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16);
  return (u & 0x800000u) ? (int32_t)u - 0x1000000 : (int32_t)u;
}
static unsigned vg__fmt_size(unsigned fmt) { return fmt == VG_F32 ? 4u : fmt == VG_I16 ? 2u : fmt == VG_I24 ? 3u : 0u; }

VG_API const char *vg_status_name(int s) {
  switch (s) {
    case VG_OK: return "ok"; case VG_SKIP: return "skip";
    case VG_E_SHORT: return "short"; case VG_E_VERSION: return "version"; case VG_E_FLAGS: return "flags";
    case VG_E_CLOCK: return "clock"; case VG_E_CHANNELS: return "channels"; case VG_E_FORMAT: return "format";
    case VG_E_COUNT: return "count"; case VG_E_REDUNDANT: return "redundant"; case VG_E_LENGTH: return "length";
    case VG_E_OFFSETS: return "offsets"; case VG_E_VALUE: return "value"; case VG_E_KIND: return "kind";
    case VG_E_JSON: return "json"; case VG_E_MAP_ID: return "map-id"; case VG_E_MAP: return "map";
    case VG_E_ROLE: return "role"; case VG_E_UTF8: return "utf8"; case VG_E_STATUS: return "status";
    case VG_E_MIDI: return "midi"; case VG_E_SYSEX: return "sysex";
    default: return "unknown";
  }
}

/* ---- UTF-8, as the WHATWG decoder with fatal set: no overlongs, no surrogates, nothing above U+10FFFF ---- */

VG_API int vg_utf8_valid(const uint8_t *s, size_t len) {
  size_t i = 0;
  while (i < len) {
    unsigned c = s[i], need, lo = 0x80, hi = 0xbf;
    if (c < 0x80) { i++; continue; }
    if (c >= 0xc2 && c <= 0xdf) need = 1;
    else if (c >= 0xe0 && c <= 0xef) { need = 2; if (c == 0xe0) lo = 0xa0; if (c == 0xed) hi = 0x9f; }
    else if (c >= 0xf0 && c <= 0xf4) { need = 3; if (c == 0xf0) lo = 0x90; if (c == 0xf4) hi = 0x8f; }
    else return 0;
    if (len - i - 1 < need) return 0;
    if (s[i + 1] < lo || s[i + 1] > hi) return 0;
    if (need > 1 && (s[i + 2] < 0x80 || s[i + 2] > 0xbf)) return 0;
    if (need > 2 && (s[i + 3] < 0x80 || s[i + 3] > 0xbf)) return 0;
    i += need + 1;
  }
  return 1;
}

/* ---- JSON: a scanner that validates as JSON.parse does and remembers where values start ---- */

typedef struct { const uint8_t *p, *end; } vg__js;
enum { VG__J_BAD = 0, VG__J_STR, VG__J_NUM, VG__J_OBJ, VG__J_ARR, VG__J_LIT };

static void vg__ws(vg__js *s) {
  while (s->p < s->end && (*s->p == ' ' || *s->p == '\t' || *s->p == '\n' || *s->p == '\r')) s->p++;
}
static int vg__hex(uint8_t c) {
  return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
}
/* At the opening quote; leaves p after the closing one. */
static int vg__str(vg__js *s) {
  s->p++;
  while (s->p < s->end) {
    uint8_t c = *s->p++;
    if (c == '"') return 1;
    if (c < 0x20) return 0;
    if (c == '\\') {
      if (s->p >= s->end) return 0;
      c = *s->p++;
      if (c == 'u') {
        int k;
        if (s->end - s->p < 4) return 0;
        for (k = 0; k < 4; k++) if (vg__hex(s->p[k]) < 0) return 0;
        s->p += 4;
      } else if (!strchr("\"\\/bfnrt", c) || c == 0) return 0;
    }
  }
  return 0;
}
/* Decimal to double without libc. Exact for the usual rates; not correctly rounded in every case. */
static int vg__num(vg__js *s, double *out) {
  int neg = 0, digits = 0, e10 = 0, ex = 0, exneg = 0;
  uint64_t m = 0;
  double v, scale = 1, ten = 10;
  unsigned n;
  if (s->p < s->end && *s->p == '-') { neg = 1; s->p++; }
  if (s->p >= s->end) return 0;
  if (*s->p == '0') s->p++;
  else if (*s->p >= '1' && *s->p <= '9') {
    while (s->p < s->end && *s->p >= '0' && *s->p <= '9') {
      if (digits < 19) { m = m * 10 + (uint64_t)(*s->p - '0'); digits++; } else e10++;
      s->p++;
    }
  } else return 0;
  if (s->p < s->end && *s->p == '.') {
    s->p++;
    if (s->p >= s->end || *s->p < '0' || *s->p > '9') return 0;
    while (s->p < s->end && *s->p >= '0' && *s->p <= '9') {
      if (digits < 19 && (m || *s->p != '0')) { m = m * 10 + (uint64_t)(*s->p - '0'); digits++; e10--; }
      else if (!m) e10--;
      s->p++;
    }
  }
  if (s->p < s->end && (*s->p == 'e' || *s->p == 'E')) {
    s->p++;
    if (s->p < s->end && (*s->p == '+' || *s->p == '-')) { exneg = *s->p == '-'; s->p++; }
    if (s->p >= s->end || *s->p < '0' || *s->p > '9') return 0;
    while (s->p < s->end && *s->p >= '0' && *s->p <= '9') { if (ex < 100000) ex = ex * 10 + (*s->p - '0'); s->p++; }
  }
  e10 += exneg ? -ex : ex;
  v = (double)m;
  if (m) {
    n = (unsigned)(e10 < 0 ? -e10 : e10);
    if (n > 800) n = 800;
    if (e10 < 0 && n > 300) { v /= 1e300; n -= 300; }
    while (n) { if (n & 1) scale *= ten; ten *= ten; n >>= 1; }
    v = e10 < 0 ? v / scale : v * scale;
  }
  *out = neg ? -v : v;
  return 1;
}
static int vg__lit(vg__js *s, const char *w) {
  size_t n = strlen(w);
  if ((size_t)(s->end - s->p) < n || memcmp(s->p, w, n)) return 0;
  s->p += n;
  return 1;
}
/* Skips one value; returns its kind (VG__J_BAD when it is not JSON). */
static int vg__value(vg__js *s, int depth) {
  double d;
  if (s->p >= s->end) return VG__J_BAD;
  switch (*s->p) {
    case '"': return vg__str(s) ? VG__J_STR : VG__J_BAD;
    case 't': return vg__lit(s, "true") ? VG__J_LIT : VG__J_BAD;
    case 'f': return vg__lit(s, "false") ? VG__J_LIT : VG__J_BAD;
    case 'n': return vg__lit(s, "null") ? VG__J_LIT : VG__J_BAD;
    case '{': case '[': {
      int obj = *s->p == '{';
      uint8_t close = obj ? '}' : ']';
      if (depth >= VG_JSON_DEPTH) return VG__J_BAD;
      s->p++; vg__ws(s);
      if (s->p < s->end && *s->p == close) { s->p++; return obj ? VG__J_OBJ : VG__J_ARR; }
      for (;;) {
        if (obj) {
          if (s->p >= s->end || *s->p != '"' || !vg__str(s)) return VG__J_BAD;
          vg__ws(s);
          if (s->p >= s->end || *s->p != ':') return VG__J_BAD;
          s->p++; vg__ws(s);
        }
        if (!vg__value(s, depth + 1)) return VG__J_BAD;
        vg__ws(s);
        if (s->p >= s->end) return VG__J_BAD;
        if (*s->p == close) { s->p++; return obj ? VG__J_OBJ : VG__J_ARR; }
        if (*s->p != ',') return VG__J_BAD;
        s->p++; vg__ws(s);
      }
    }
    default: return vg__num(s, &d) ? VG__J_NUM : VG__J_BAD;
  }
}
/* A JSON string (at its quote, already validated) against an ASCII word, escapes decoded. */
static int vg__str_is(const uint8_t *p, const char *w) {
  p++;
  for (;;) {
    unsigned c = *p++;
    if (c == '"') return *w == 0;
    if (c == '\\') {
      c = *p++;
      switch (c) {
        case 'b': c = 8; break; case 'f': c = 12; break; case 'n': c = 10; break; case 'r': c = 13; break;
        case 't': c = 9; break;
        case 'u': c = (unsigned)(vg__hex(p[0]) << 12 | vg__hex(p[1]) << 8 | vg__hex(p[2]) << 4 | vg__hex(p[3])); p += 4; break;
        default: break;
      }
    }
    if (*w == 0 || c != (unsigned char)*w) return 0;
    w++;
  }
}

/* The keys a map's rules care about; the last occurrence wins (SPEC.md 4.3), as in JSON.parse. */
typedef struct { const char *key; const uint8_t *at; int kind; } vg__slot;

/* Scans an object at s->p and records the last value of each listed key. */
static int vg__object(vg__js *s, vg__slot *keys, unsigned nkeys) {
  unsigned i;
  if (s->p >= s->end || *s->p != '{') return 0;
  s->p++; vg__ws(s);
  if (s->p < s->end && *s->p == '}') { s->p++; return 1; }
  for (;;) {
    const uint8_t *k = s->p, *v;
    int kind;
    if (s->p >= s->end || *s->p != '"' || !vg__str(s)) return 0;
    vg__ws(s);
    if (s->p >= s->end || *s->p != ':') return 0;
    s->p++; vg__ws(s);
    v = s->p;
    if (!(kind = vg__value(s, 1))) return 0;
    for (i = 0; i < nkeys; i++) if (vg__str_is(k, keys[i].key)) { keys[i].at = v; keys[i].kind = kind; }
    vg__ws(s);
    if (s->p >= s->end) return 0;
    if (*s->p == '}') { s->p++; return 1; }
    if (*s->p != ',') return 0;
    s->p++; vg__ws(s);
  }
}
static double vg__num_at(const uint8_t *p, const uint8_t *end) {
  vg__js s; double d = 0;
  s.p = p; s.end = end;
  vg__num(&s, &d);
  return d;
}

/* clamp: an array (already validated JSON) of exactly two finite numbers, lo <= hi. */
static int vg__pair(const uint8_t *p, const uint8_t *end, double *lo, double *hi) {
  vg__js s; double v[2]; unsigned n = 0;
  s.p = p + 1; s.end = end; vg__ws(&s);
  while (*s.p != ']') {
    const uint8_t *at = s.p;
    if (n == 2 || vg__value(&s, 1) != VG__J_NUM) return 0;
    v[n] = vg__num_at(at, end);
    if (!vg__finite(v[n++])) return 0;
    vg__ws(&s);
    if (*s.p == ',') { s.p++; vg__ws(&s); }
  }
  if (n != 2 || !(v[0] <= v[1])) return 0;
  *lo = v[0]; *hi = v[1];
  return 1;
}

/* One channel object of the map: name a non empty string, min max voct numbers, node port unit strings, clamp a
 * pair lo <= hi, slew a number above 0. */
static int vg__channel(const uint8_t *p, const uint8_t *end, vg_map_channel_t *ch) {
  vg__slot k[9] = { { "name", 0, 0 }, { "min", 0, 0 }, { "max", 0, 0 }, { "voct", 0, 0 },
                    { "node", 0, 0 }, { "port", 0, 0 }, { "unit", 0, 0 }, { "clamp", 0, 0 }, { "slew", 0, 0 } };
  vg__js s; unsigned i; double lo = 0, hi = 0, slew = 0;
  s.p = p; s.end = end;
  if (!vg__object(&s, k, 9)) return 0;
  if (k[0].kind != VG__J_STR || k[0].at[1] == '"') return 0;
  for (i = 1; i < 4; i++)
    if (k[i].at && (k[i].kind != VG__J_NUM || !vg__finite(vg__num_at(k[i].at, end)))) return 0;
  for (i = 4; i < 7; i++) if (k[i].at && k[i].kind != VG__J_STR) return 0;
  if (k[7].at && (k[7].kind != VG__J_ARR || !vg__pair(k[7].at, end, &lo, &hi))) return 0;
  if (k[8].at) {
    if (k[8].kind != VG__J_NUM) return 0;
    slew = vg__num_at(k[8].at, end);
    if (!vg__finite(slew) || !(slew > 0)) return 0;
  }
  if (ch) {
    vg__js n; n.p = k[0].at; n.end = end; vg__str(&n);
    ch->name = k[0].at + 1; ch->name_len = (size_t)(n.p - k[0].at) - 2;
    ch->has_min = k[1].at != 0; ch->min = ch->has_min ? vg__num_at(k[1].at, end) : 0;
    ch->has_max = k[2].at != 0; ch->max = ch->has_max ? vg__num_at(k[2].at, end) : 0;
    ch->has_voct = k[3].at != 0; ch->voct = ch->has_voct ? vg__num_at(k[3].at, end) : 0;
    ch->has_clamp = k[7].at != 0; ch->clamp_lo = lo; ch->clamp_hi = hi;
    ch->has_slew = k[8].at != 0; ch->slew = slew;
  }
  return 1;
}

/* Walks the map; want >= 0 also fills *ch for that channel index. */
static int vg__map(const uint8_t *json, size_t len, vg_map_info_t *info, int want, vg_map_channel_t *ch) {
  vg__slot k[5] = { { "name", 0, 0 }, { "kind", 0, 0 }, { "channels", 0, 0 }, { "rate", 0, 0 }, { "format", 0, 0 } };
  vg__js s; unsigned n = 0; int kind, format = 0, found = 0; double rate = 0;
  if (!json || !len) return VG_E_JSON;
  if (!vg_utf8_valid(json, len)) return VG_E_JSON;
  s.p = json; s.end = json + len;
  vg__ws(&s);
  if (s.p >= s.end || *s.p != '{') {
    /* Valid JSON that is not an object is a json reject too; anything else is not JSON. */
    return VG_E_JSON;
  }
  if (!vg__object(&s, k, 5)) return VG_E_JSON;
  vg__ws(&s);
  if (s.p != s.end) return VG_E_JSON;
  if (k[0].kind != VG__J_STR || k[0].at[1] == '"') return VG_E_MAP;
  if (k[1].kind != VG__J_STR) return VG_E_MAP;
  kind = vg__str_is(k[1].at, "samples") ? VG_KIND_SAMPLES : vg__str_is(k[1].at, "events") ? VG_KIND_EVENTS : 0;
  if (!kind) return VG_E_MAP;
  if (k[2].kind != VG__J_ARR) return VG_E_MAP;
  {
    vg__js a; a.p = k[2].at + 1; a.end = s.end; vg__ws(&a);
    while (*a.p != ']') {
      const uint8_t *el = a.p;
      if (vg__value(&a, 1) != VG__J_OBJ) return VG_E_MAP;
      if (!vg__channel(el, s.end, want == (int)n ? ch : 0)) return VG_E_MAP;
      if (want == (int)n) found = 1;
      n++;
      vg__ws(&a);
      if (*a.p == ',') { a.p++; vg__ws(&a); }
    }
  }
  if (n < 1 || n > 255) return VG_E_MAP;
  if (kind == VG_KIND_SAMPLES) {
    if (k[3].kind != VG__J_NUM) return VG_E_MAP;
    rate = vg__num_at(k[3].at, s.end);
    if (!vg__finite(rate) || !(rate > 0)) return VG_E_MAP;
    if (k[4].kind != VG__J_STR) return VG_E_MAP;
    format = vg__str_is(k[4].at, "f32") ? VG_F32 : vg__str_is(k[4].at, "i16") ? VG_I16 : vg__str_is(k[4].at, "i24") ? VG_I24 : 0;
    if (!format) return VG_E_MAP;
  }
  if (want >= 0 && !found) return VG_E_MAP;
  if (info) { info->kind = kind; info->rate = rate; info->format = format; info->channels = n; }
  return VG_OK;
}
VG_API int vg_map_info(const uint8_t *json, size_t len, vg_map_info_t *info) { return vg__map(json, len, info, -1, 0); }
VG_API int vg_map_channel(const uint8_t *json, size_t len, unsigned index, vg_map_channel_t *ch) {
  return vg__map(json, len, 0, index > 254 ? 255 : (int)index, ch);
}

/* ---- decode ---- */

static int vg__offsets_ok(const uint8_t *p, unsigned n, size_t stride, int first0) {
  unsigned i; int32_t prev = 0;
  for (i = 0; i < n; i++, p += stride) {
    int32_t x = (int32_t)vg__rd32(p);
    if (x < 0 || (i && x < prev) || (first0 && i == 0 && x != 0)) return 0;
    prev = x;
  }
  return 1;
}

VG_API int vg_decode(const uint8_t *b, size_t len, vg_frame *f) {
  size_t o = VG_HEAD;
  unsigned flags, irr, red;
  uint64_t cb;
  memset(f, 0, sizeof *f);
  if (len < VG_HEAD || !b) return VG_E_SHORT;
  if (len > VG_FRAME_MAX) return VG_E_LENGTH;
  if ((b[0] >> 4) != VG_VERSION) return VG_E_VERSION;
  flags = b[0] & 15u;
  if (flags & VG_FLAG_RESERVED) return VG_E_FLAGS;
  f->flags = (uint8_t)flags; f->type = b[1]; f->stream = vg__rd16(b + 2); f->seq = vg__rd32(b + 4);
  cb = vg__rd64(b + 8);
  if (!vg__fin64(cb)) return VG_E_CLOCK;
  f->clock = vg__bits_f64(cb);
  if (flags & VG_FLAG_EXT) {
    unsigned words;
    if (len < o + 4) return VG_E_SHORT;
    words = vg__rd16(b + o + 2);
    if (len < o + 4 + 4 * (size_t)words) return VG_E_SHORT;
    f->has_ext = 1; f->ext.type = vg__rd16(b + o); f->ext.words = (uint16_t)words; f->ext.data = b + o + 4;
    o += 4 + 4 * (size_t)words;
  }
  irr = flags & VG_FLAG_IRREGULAR; red = flags & VG_FLAG_REDUNDANT;
  switch (f->type) {
    case VG_SAMPLES: {
      vg_samples *s = &f->u.samples;
      unsigned n, fmt, k, r, size, i;
      if (len < o + 8) return VG_E_SHORT;
      n = b[o]; fmt = b[o + 1]; k = b[o + 4]; r = b[o + 5];
      if (n == 0) return VG_E_CHANNELS;
      if (!(size = vg__fmt_size(fmt))) return VG_E_FORMAT;
      if (k == 0) return VG_E_COUNT;
      if (red ? (r == 0 || 2 * r > k) : r != 0) return VG_E_REDUNDANT;
      if (len != o + 8 + (irr ? 4 * (size_t)k : 0) + (size_t)k * n * size) return VG_E_LENGTH;
      s->channels = (uint8_t)n; s->format = (uint8_t)fmt; s->map = vg__rd16(b + o + 2); s->count = (uint8_t)k; s->redundant = (uint8_t)r;
      o += 8;
      if (irr) {
        s->offsets = b + o;
        if (!vg__offsets_ok(b + o, k, 4, 1)) return VG_E_OFFSETS;
        o += 4 * (size_t)k;
      }
      s->values = b + o;
      if (fmt == VG_F32) for (i = 0; i < k * n; i++) if (!vg__fin32(vg__rd32(b + o + 4 * (size_t)i))) return VG_E_VALUE;
      return VG_OK;
    }
    case VG_EVENTS: {
      vg_events *e = &f->u.events;
      unsigned m, r, i;
      if (irr) return VG_E_FLAGS;
      if (len < o + 4) return VG_E_SHORT;
      m = b[o]; r = b[o + 1];
      if (m == 0) return VG_E_COUNT;
      if (red ? (r == 0 || 2 * r > m) : r != 0) return VG_E_REDUNDANT;
      if (len != o + 4 + VG_EVENT_SIZE * (size_t)m) return VG_E_LENGTH;
      e->count = (uint8_t)m; e->redundant = (uint8_t)r; e->map = vg__rd16(b + o + 2); e->events = b + o + 4;
      for (i = 0; i < m; i++) {
        const uint8_t *p = e->events + VG_EVENT_SIZE * (size_t)i;
        if (p[5] == 0) return VG_E_KIND;
        if (!vg__fin32(vg__rd32(p + 8))) return VG_E_VALUE;
      }
      if (!vg__offsets_ok(e->events, m, VG_EVENT_SIZE, 0)) return VG_E_OFFSETS;
      return VG_OK;
    }
    case VG_MIDI: {
      vg_midi *mi = &f->u.midi;
      unsigned m, r, i, L; int st;
      int32_t prev = 0;
      if (irr) return VG_E_FLAGS;
      if (len < o + 4) return VG_E_SHORT;
      m = b[o]; r = b[o + 1];
      if (m == 0) return VG_E_COUNT;
      if (red ? (r == 0 || 2 * r > m) : r != 0) return VG_E_REDUNDANT;
      mi->count = (uint8_t)m; mi->redundant = (uint8_t)r; mi->records = b + o + 4;
      o += 4;
      for (i = 0; i < m; i++) {
        if (len < o + VG_MIDI_RECORD) return VG_E_LENGTH;
        L = vg__rd16(b + o + 4);
        if (len - o - VG_MIDI_RECORD < L) return VG_E_LENGTH;
        if ((st = vg_midi_check(b + o + VG_MIDI_RECORD, L)) != VG_OK) return st;
        o += VG_MIDI_RECORD + L;
      }
      if (o != len) return VG_E_LENGTH;
      for (o = (size_t)(mi->records - b), i = 0; i < m; i++) { /* offsets last, as the JS reader checks them */
        int32_t x = (int32_t)vg__rd32(b + o);
        if (x < 0 || (i && x < prev)) return VG_E_OFFSETS;
        prev = x; o += VG_MIDI_RECORD + vg__rd16(b + o + 4);
      }
      return VG_OK;
    }
    case VG_MAP: {
      unsigned id, L; int st;
      if (irr || red) return VG_E_FLAGS;
      if (len < o + 4) return VG_E_SHORT;
      id = vg__rd16(b + o); L = vg__rd16(b + o + 2);
      if (id == 0) return VG_E_MAP_ID;
      if (len != o + 4 + L) return VG_E_LENGTH;
      if ((st = vg_map_info(b + o + 4, L, 0)) != VG_OK) return st;
      f->u.map.map = (uint16_t)id; f->u.map.len = (uint16_t)L; f->u.map.json = b + o + 4;
      return VG_OK;
    }
    case VG_HELLO: {
      vg_hello *h = &f->u.hello;
      if (irr || red) return VG_E_FLAGS;
      if (len < o + 4) return VG_E_SHORT;
      h->role = b[o];
      if (h->role == 0) return VG_E_ROLE;
      h->name = b + o + 4; h->len = len - o - 4;
      if (!vg_utf8_valid(h->name, h->len)) return VG_E_UTF8;
      return VG_OK;
    }
    case VG_PING:
      if (irr || red) return VG_E_FLAGS;
      return len == o ? VG_OK : VG_E_LENGTH;
    case VG_PONG: case VG_CLOCK: {
      uint64_t a, c;
      if (irr || red) return VG_E_FLAGS;
      if (len != o + 16) return VG_E_LENGTH;
      a = vg__rd64(b + o); c = vg__rd64(b + o + 8);
      if (!vg__fin64(a) || !vg__fin64(c)) return VG_E_VALUE;
      if (f->type == VG_PONG) { f->u.pong.t0 = vg__bits_f64(a); f->u.pong.t1 = vg__bits_f64(c); }
      else { f->u.clock.offset = vg__bits_f64(a); f->u.clock.rtt = vg__bits_f64(c); }
      return VG_OK;
    }
    case VG_REPORT: {
      vg_report *r = &f->u.report;
      if (irr || red) return VG_E_FLAGS;
      if (len != o + 24) return VG_E_LENGTH;
      r->fraction = b[o]; r->late_fired = vg__rd16(b + o + 2); r->lost = (int32_t)vg__rd32(b + o + 4);
      r->highest = vg__rd32(b + o + 8); r->jitter = vg__rd32(b + o + 12); r->late = vg__rd32(b + o + 16);
      r->recovered = vg__rd32(b + o + 20);
      return VG_OK;
    }
    default:
      f->u.unknown.data = b + o; f->u.unknown.len = len - o;
      return VG_SKIP;
  }
}

VG_API int32_t vg_offset(const vg_frame *f, unsigned i) {
  return f->u.samples.offsets ? (int32_t)vg__rd32(f->u.samples.offsets + 4 * (size_t)i) : 0;
}
VG_API float vg_sample_f32(const vg_frame *f, unsigned i, unsigned c) {
  return vg__bits_f32(vg__rd32(f->u.samples.values + 4 * ((size_t)i * f->u.samples.channels + c)));
}
VG_API int32_t vg_sample_int(const vg_frame *f, unsigned i, unsigned c) {
  size_t at = (size_t)i * f->u.samples.channels + c;
  if (f->u.samples.format == VG_I16) return (int16_t)vg__rd16(f->u.samples.values + 2 * at);
  return vg__rdi24(f->u.samples.values + 3 * at);
}
VG_API double vg_sample(const vg_frame *f, unsigned i, unsigned c) {
  return f->u.samples.format == VG_F32 ? (double)vg_sample_f32(f, i, c) : (double)vg_sample_int(f, i, c);
}
VG_API void vg_event_at(const vg_frame *f, unsigned i, vg_event *e) {
  const uint8_t *p = f->u.events.events + VG_EVENT_SIZE * (size_t)i;
  e->offset = (int32_t)vg__rd32(p); e->channel = p[4]; e->kind = p[5]; e->note = vg__rd16(p + 6);
  e->value = vg__bits_f32(vg__rd32(p + 8));
}

VG_API void vg_midi_at(const vg_frame *f, unsigned i, vg_midi_msg *m) {
  const uint8_t *p = f->u.midi.records;
  while (i--) p += VG_MIDI_RECORD + vg__rd16(p + 4);
  m->offset = (int32_t)vg__rd32(p); m->len = vg__rd16(p + 4); m->bytes = p + VG_MIDI_RECORD;
}

/* The length of a message from its status: 0 for SysEx, -1 for a data byte or an undefined status. */
static int vg__status_len(unsigned s) {
  static const signed char sys[16] = { 0, 2, 3, 2, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1 };
  if (s < 0x80) return -1;
  if (s < 0xf0) return (s & 0xe0) == 0xc0 ? 2 : 3;
  return sys[s & 15];
}
VG_API int vg_midi_check(const uint8_t *p, size_t len) {
  size_t i; int want;
  if (!len || !p) return VG_E_MIDI;
  want = vg__status_len(p[0]);
  if (want < 0) return VG_E_STATUS;
  if (want == 0) {
    if (len < 2 || len > VG_SYSEX_MAX || p[len - 1] != 0xf7) return VG_E_SYSEX;
    for (i = 1; i + 1 < len; i++) if (p[i] > 0x7f) return VG_E_SYSEX;
    return VG_OK;
  }
  if (len != (size_t)want) return VG_E_MIDI;
  for (i = 1; i < len; i++) if (p[i] > 0x7f) return VG_E_MIDI;
  return VG_OK;
}

VG_API double vg_to_unit(double raw, int format, int has_range, double min, double max) {
  double x;
  if (format == VG_F32) return raw;
  x = raw / (format == VG_I16 ? 32767.0 : 8388607.0);
  if (x < -1) x = -1;
  return has_range ? min + (x + 1) / 2 * (max - min) : x;
}
VG_API int32_t vg_from_unit(double v, int format, int has_range, double min, double max) {
  double full = format == VG_I16 ? 32767.0 : 8388607.0, x = v, y;
  int32_t t;
  if (has_range && max != min) x = 2 * (v - min) / (max - min) - 1;
  if (!(x >= -1)) x = -1; /* NaN lands at -1 */
  if (x > 1) x = 1;
  y = x * full + 0.5; /* Math.round: half up */
  t = (int32_t)y;
  if ((double)t > y) t--;
  return t;
}

/* ---- encode ---- */

static size_t vg__head(uint8_t *out, size_t cap, const vg_head *h, unsigned type, unsigned flags, size_t body) {
  size_t B, total;
  if (!h || !vg__finite(h->clock)) return 0;
  if (h->ext && h->ext->words && !h->ext->data) return 0;
  B = VG_HEAD + (h->ext ? 4 + 4 * (size_t)h->ext->words : 0);
  total = B + body;
  if (total > VG_FRAME_MAX) return 0;
  if (!out) return total;
  if (cap < total) return 0;
  out[0] = (uint8_t)((VG_VERSION << 4) | flags | (h->ext ? VG_FLAG_EXT : 0)); out[1] = (uint8_t)type;
  vg__wr16(out + 2, h->stream); vg__wr32(out + 4, h->seq); vg__wr64(out + 8, vg__f64_bits(h->clock));
  if (h->ext) {
    vg__wr16(out + VG_HEAD, h->ext->type); vg__wr16(out + VG_HEAD + 2, h->ext->words);
    if (h->ext->words) memcpy(out + VG_HEAD + 4, h->ext->data, 4 * (size_t)h->ext->words);
  }
  return total;
}
static size_t vg__body_at(const vg_head *h) { return VG_HEAD + (h->ext ? 4 + 4 * (size_t)h->ext->words : 0); }

VG_API size_t vg_encode_samples(uint8_t *out, size_t cap, const vg_head *h, const vg_samples_in *s) {
  unsigned n, k, r, size, i;
  size_t total, o;
  if (!s) return 0;
  n = s->channels; k = s->count; r = s->redundant; size = vg__fmt_size(s->format);
  if (!n || !k || !size || 2 * r > k) return 0;
  if (s->format == VG_F32 ? !s->f32 : !s->ints) return 0;
  if (s->offsets) {
    if (s->offsets[0] != 0) return 0;
    for (i = 1; i < k; i++) if (s->offsets[i] < s->offsets[i - 1]) return 0;
  }
  if (s->format == VG_F32) for (i = 0; i < k * n; i++) if (!vg__fin32(vg__f32_bits(s->f32[i]))) return 0;
  total = vg__head(out, cap, h, VG_SAMPLES, (s->offsets ? VG_FLAG_IRREGULAR : 0) | (r ? VG_FLAG_REDUNDANT : 0),
                   8 + (s->offsets ? 4 * (size_t)k : 0) + (size_t)k * n * size);
  if (!total || !out) return total;
  o = vg__body_at(h);
  out[o] = (uint8_t)n; out[o + 1] = s->format; vg__wr16(out + o + 2, s->map); out[o + 4] = (uint8_t)k; out[o + 5] = (uint8_t)r;
  vg__wr16(out + o + 6, 0);
  o += 8;
  if (s->offsets) for (i = 0; i < k; i++, o += 4) vg__wr32(out + o, (uint32_t)s->offsets[i]);
  for (i = 0; i < k * n; i++) {
    if (s->format == VG_F32) { vg__wr32(out + o, vg__f32_bits(s->f32[i])); o += 4; continue; }
    {
      int32_t x = s->ints[i], lo = s->format == VG_I16 ? -32768 : -8388608, hi = s->format == VG_I16 ? 32767 : 8388607;
      uint32_t u = (uint32_t)(x < lo ? lo : x > hi ? hi : x);
      out[o] = (uint8_t)u; out[o + 1] = (uint8_t)(u >> 8);
      if (s->format == VG_I24) out[o + 2] = (uint8_t)(u >> 16);
      o += size;
    }
  }
  return total;
}

VG_API size_t vg_encode_events(uint8_t *out, size_t cap, const vg_head *h, uint16_t map, uint8_t redundant,
                               const vg_event *ev, size_t count) {
  size_t total, o, i;
  if (!ev || count < 1 || count > 255 || 2 * (size_t)redundant > count) return 0;
  for (i = 0; i < count; i++) {
    if (ev[i].kind == 0 || ev[i].offset < 0 || (i && ev[i].offset < ev[i - 1].offset)) return 0;
    if (!vg__fin32(vg__f32_bits(ev[i].value))) return 0;
  }
  total = vg__head(out, cap, h, VG_EVENTS, redundant ? VG_FLAG_REDUNDANT : 0, 4 + VG_EVENT_SIZE * count);
  if (!total || !out) return total;
  o = vg__body_at(h);
  out[o] = (uint8_t)count; out[o + 1] = redundant; vg__wr16(out + o + 2, map);
  for (o += 4, i = 0; i < count; i++, o += VG_EVENT_SIZE) {
    vg__wr32(out + o, (uint32_t)ev[i].offset); out[o + 4] = ev[i].channel; out[o + 5] = ev[i].kind;
    vg__wr16(out + o + 6, ev[i].note); vg__wr32(out + o + 8, vg__f32_bits(ev[i].value));
  }
  return total;
}

VG_API size_t vg_encode_map(uint8_t *out, size_t cap, const vg_head *h, uint16_t map, const uint8_t *json, size_t len) {
  size_t total, o;
  if (map == 0 || len > 65535 || vg_map_info(json, len, 0) != VG_OK) return 0;
  total = vg__head(out, cap, h, VG_MAP, 0, 4 + len);
  if (!total || !out) return total;
  o = vg__body_at(h);
  vg__wr16(out + o, map); vg__wr16(out + o + 2, (uint16_t)len);
  memcpy(out + o + 4, json, len);
  return total;
}

VG_API size_t vg_encode_midi(uint8_t *out, size_t cap, const vg_head *h, uint8_t redundant, const vg_midi_msg *msgs, size_t count) {
  size_t total, o, i, body = 4;
  if (!msgs || count < 1 || count > 255 || 2 * (size_t)redundant > count) return 0;
  for (i = 0; i < count; i++) {
    if (msgs[i].offset < 0 || (i && msgs[i].offset < msgs[i - 1].offset)) return 0;
    if (vg_midi_check(msgs[i].bytes, msgs[i].len) != VG_OK) return 0;
    body += VG_MIDI_RECORD + msgs[i].len;
    if (body > VG_FRAME_MAX) return 0;
  }
  total = vg__head(out, cap, h, VG_MIDI, redundant ? VG_FLAG_REDUNDANT : 0, body);
  if (!total || !out) return total;
  o = vg__body_at(h);
  out[o] = (uint8_t)count; out[o + 1] = redundant; vg__wr16(out + o + 2, 0);
  for (o += 4, i = 0; i < count; i++) {
    vg__wr32(out + o, (uint32_t)msgs[i].offset); vg__wr16(out + o + 4, msgs[i].len);
    memcpy(out + o + VG_MIDI_RECORD, msgs[i].bytes, msgs[i].len);
    o += VG_MIDI_RECORD + msgs[i].len;
  }
  return total;
}

VG_API size_t vg_encode_hello(uint8_t *out, size_t cap, const vg_head *h, uint8_t role, const uint8_t *name, size_t len) {
  size_t total, o;
  if (role == 0 || (len && !name) || !vg_utf8_valid(name, len)) return 0;
  total = vg__head(out, cap, h, VG_HELLO, 0, 4 + len);
  if (!total || !out) return total;
  o = vg__body_at(h);
  out[o] = role; out[o + 1] = out[o + 2] = out[o + 3] = 0;
  if (len) memcpy(out + o + 4, name, len);
  return total;
}

VG_API size_t vg_encode_ping(uint8_t *out, size_t cap, const vg_head *h) { return vg__head(out, cap, h, VG_PING, 0, 0); }

static size_t vg__two(uint8_t *out, size_t cap, const vg_head *h, unsigned type, double a, double b) {
  size_t total, o;
  if (!vg__finite(a) || !vg__finite(b)) return 0;
  total = vg__head(out, cap, h, type, 0, 16);
  if (!total || !out) return total;
  o = vg__body_at(h);
  vg__wr64(out + o, vg__f64_bits(a)); vg__wr64(out + o + 8, vg__f64_bits(b));
  return total;
}
VG_API size_t vg_encode_pong(uint8_t *out, size_t cap, const vg_head *h, double t0, double t1) { return vg__two(out, cap, h, VG_PONG, t0, t1); }
VG_API size_t vg_encode_clock(uint8_t *out, size_t cap, const vg_head *h, double offset, double rtt) { return vg__two(out, cap, h, VG_CLOCK, offset, rtt); }

VG_API size_t vg_encode_report(uint8_t *out, size_t cap, const vg_head *h, const vg_report *r) {
  size_t total, o;
  if (!r) return 0;
  total = vg__head(out, cap, h, VG_REPORT, 0, 24);
  if (!total || !out) return total;
  o = vg__body_at(h);
  out[o] = r->fraction; out[o + 1] = 0; vg__wr16(out + o + 2, r->late_fired); vg__wr32(out + o + 4, (uint32_t)r->lost);
  vg__wr32(out + o + 8, r->highest); vg__wr32(out + o + 12, r->jitter); vg__wr32(out + o + 16, r->late);
  vg__wr32(out + o + 20, r->recovered);
  return total;
}

VG_API size_t vg_encode_raw(uint8_t *out, size_t cap, const vg_head *h, uint8_t type, const uint8_t *body, size_t len) {
  size_t total;
  if ((type >= 1 && type <= 4) || (type >= 16 && type <= 20) || (len && !body)) return 0;
  total = vg__head(out, cap, h, type, 0, len);
  if (!total || !out) return total;
  if (len) memcpy(out + vg__body_at(h), body, len);
  return total;
}

/* ---- byte streams ---- */

VG_API void vg_reader_init(vg_reader *r, uint8_t *buf, size_t cap) {
  memset(r, 0, sizeof *r);
  r->buf = buf; r->cap = buf ? cap : 0;
}

VG_API size_t vg_reader_feed(vg_reader *r, const uint8_t *data, size_t len, const uint8_t **frame, size_t *frame_len) {
  size_t used = 0;
  *frame = 0; *frame_len = 0;
  if (r->error) return 0;
  while (used < len) {
    size_t want, take;
    if (r->got < 2) {
      r->prefix[r->got++] = data[used++];
      if (r->got == 2) {
        r->need = vg__rd16(r->prefix);
        if (r->need < VG_HEAD) { r->error = VG_E_LENGTH; return used; }
        r->have = 0;
        r->skipping = r->need > r->cap;
        if (r->skipping) r->oversize++;
      }
      continue;
    }
    want = r->need - r->have;
    take = len - used < want ? len - used : want;
    if (!r->skipping && r->have == 0 && take == want) { /* whole in this chunk: no copy */
      *frame = data + used; *frame_len = want; r->got = 0;
      return used + want;
    }
    if (!r->skipping) memcpy(r->buf + r->have, data + used, take);
    r->have += take; used += take;
    if (r->have == r->need) {
      r->got = 0;
      if (!r->skipping) { *frame = r->buf; *frame_len = r->need; return used; }
    }
  }
  return used;
}

VG_API size_t vg_stream_wrap(uint8_t *out, size_t cap, const uint8_t *frame, size_t len) {
  if (len < VG_HEAD || len > VG_STREAM_MAX || cap < len + 2 || !out || !frame) return 0;
  memmove(out + 2, frame, len);
  vg__wr16(out, (uint16_t)len);
  return len + 2;
}

/* ---- clock estimator ---- */

VG_API void vg_clock_init(vg_clock_est *e, unsigned keep) {
  memset(e, 0, sizeof *e);
  e->keep = keep == 0 || keep > VG_CLOCK_KEEP ? VG_CLOCK_KEEP : keep;
}
VG_API void vg_clock_add(vg_clock_est *e, double t0, double t1, double t2, double t3) {
  e->rtt[e->head] = (t3 - t0) - (t2 - t1);
  e->offset[e->head] = ((t1 - t0) + (t2 - t3)) / 2;
  e->head = (e->head + 1) % e->keep;
  if (e->n < e->keep) e->n++;
}
VG_API void vg_clock_pong(vg_clock_est *e, const vg_frame *f, double t3) {
  vg_clock_add(e, f->u.pong.t0, f->u.pong.t1, f->clock, t3);
}
VG_API int vg_clock_get(const vg_clock_est *e, vg_clock_best *out) {
  unsigned short idx[VG_CLOCK_KEEP];
  double off[(VG_CLOCK_KEEP + 2) / 3];
  unsigned i, j, n = e->n, used;
  if (!n) return 0;
  for (i = 0; i < n; i++) idx[i] = (unsigned short)((e->head + e->keep - n + i) % e->keep); /* oldest first */
  for (i = 1; i < n; i++) { /* insertion sort: stable, as JS's sort */
    unsigned short x = idx[i];
    for (j = i; j > 0 && e->rtt[idx[j - 1]] > e->rtt[x]; j--) idx[j] = idx[j - 1];
    idx[j] = x;
  }
  used = (n + 2) / 3;
  for (i = 0; i < used; i++) {
    double x = e->offset[idx[i]];
    for (j = i; j > 0 && off[j - 1] > x; j--) off[j] = off[j - 1];
    off[j] = x;
  }
  out->offset = used % 2 ? off[used / 2] : (off[used / 2 - 1] + off[used / 2]) / 2;
  out->rtt = e->rtt[idx[0]]; out->n = n; out->used = used;
  return 1;
}

/* ---- sample playout ---- */

VG_API void vg_playout_init(vg_playout *p, vg_slot *slots, float *values, size_t cap, unsigned channels, int mode) {
  memset(p, 0, sizeof *p);
  p->slot = slots; p->values = values; p->cap = cap; p->channels = channels; p->mode = mode;
}
static void vg__pl_move(vg_playout *p, size_t to, size_t from, size_t count) {
  memmove(p->slot + to, p->slot + from, count * sizeof *p->slot);
  memmove(p->values + to * p->channels, p->values + from * p->channels, count * p->channels * sizeof *p->values);
}
VG_API int vg_playout_push(vg_playout *p, int64_t seq, double t, const float *v) {
  size_t lo = 0, hi = p->size;
  if (p->started && t < p->playhead) return 0;
  while (lo < hi) { size_t m = (lo + hi) / 2; if (p->slot[m].seq < seq) lo = m + 1; else hi = m; }
  if (lo < p->size && p->slot[lo].seq == seq) return 0;
  if (p->size == p->cap) { /* full: drop the oldest, unless the newcomer would be it */
    if (lo == 0 || p->cap == 0) { p->overflow++; return 0; }
    vg__pl_move(p, 0, 1, --p->size); lo--; p->overflow++;
  }
  vg__pl_move(p, lo + 1, lo, p->size - lo);
  p->slot[lo].seq = seq; p->slot[lo].t = t;
  memcpy(p->values + lo * p->channels, v, p->channels * sizeof *v);
  p->size++;
  return 1;
}
VG_API int vg_playout_read(vg_playout *p, double T, float *out) {
  size_t j, i = 0; int any = 0; unsigned c;
  const float *a, *b; double w;
  if (!p->started || T > p->playhead) p->playhead = T;
  p->started = 1;
  for (j = 0; j < p->size && p->slot[j].t <= T; j++) { i = j; any = 1; }
  if (!any) return VG_PLAY_EMPTY;
  if (i > 0) { vg__pl_move(p, 0, i, p->size - i); p->size -= i; }
  a = p->values;
  if (p->size < 2) { memcpy(out, a, p->channels * sizeof *out); return p->slot[0].t == T ? VG_PLAY_OK : VG_PLAY_HOLD; }
  b = p->values + p->channels;
  {
    int gap = p->slot[1].seq != p->slot[0].seq + 1;
    if (gap && p->mode == VG_MODE_HOLD) { memcpy(out, a, p->channels * sizeof *out); return VG_PLAY_GAP; }
    w = (T - p->slot[0].t) / (p->slot[1].t - p->slot[0].t);
    for (c = 0; c < p->channels; c++) out[c] = (float)(a[c] + ((double)b[c] - a[c]) * w);
    return gap ? VG_PLAY_GAP : VG_PLAY_OK;
  }
}

/* ---- safety limits ---- */

VG_API void vg_limit_init(vg_limit *l, int has_clamp, double lo, double hi, double slew) {
  memset(l, 0, sizeof *l);
  vg_limit_set(l, has_clamp, lo, hi, slew);
}
VG_API void vg_limit_set(vg_limit *l, int has_clamp, double lo, double hi, double slew) {
  l->has_clamp = has_clamp; l->lo = lo; l->hi = hi; l->slew = slew > 0 ? slew : 0;
}
VG_API double vg_limit_apply(vg_limit *l, double x, double now) {
  if (l->slew > 0 && l->started) {
    double dt = now > l->t ? now - l->t : 0, step = l->slew * dt / 1e6;
    if (x > l->y + step) x = l->y + step; else if (x < l->y - step) x = l->y - step;
  }
  if (l->has_clamp) x = x < l->lo ? l->lo : x > l->hi ? l->hi : x;
  l->y = x; l->t = now; l->started = 1;
  return x;
}

/* ---- event playout ---- */

VG_API void vg_events_init(vg_event_playout *p, vg_timed_event *buf, size_t cap) {
  memset(p, 0, sizeof *p);
  p->buf = buf; p->cap = cap;
}
VG_API int vg_events_push(vg_event_playout *p, int64_t seq, double t, const vg_event *ev) {
  unsigned k; size_t i;
  for (k = 0; k < p->seen_n; k++) if (p->seen[k] == seq) return 0;
  if (p->size == p->cap) { p->overflow++; return 0; }
  p->seen[p->seen_head] = seq; p->seen_head = (p->seen_head + 1) % VG_EVENT_SEEN;
  if (p->seen_n < VG_EVENT_SEEN) p->seen_n++;
  for (i = p->size; i > 0 && (p->buf[i - 1].t > t || (p->buf[i - 1].t == t && p->buf[i - 1].seq > seq)); i--) {}
  memmove(p->buf + i + 1, p->buf + i, (p->size - i) * sizeof *p->buf);
  p->buf[i].seq = seq; p->buf[i].t = t; p->buf[i].ev = *ev;
  p->size++;
  return 1;
}
VG_API size_t vg_events_due(vg_event_playout *p, double T, vg_timed_event *out, size_t max) {
  size_t n = 0;
  while (n < p->size && n < max && p->buf[n].t <= T) { out[n] = p->buf[n]; n++; }
  if (n) { memmove(p->buf, p->buf + n, (p->size - n) * sizeof *p->buf); p->size -= n; }
  return n;
}

#endif /* VOLTERGEIST_IMPLEMENTED */
#endif /* VOLTERGEIST_IMPLEMENTATION */
