/*
 * The glasses' motion sensors: XREAL's IMU stream, fused here into which
 * way the head points (3DoF).
 *
 * The glasses are a USB network device too; the glasses end is
 * 169.254.2.1 and port 52998 streams without being asked (no handshake).
 * Frames are 134 bytes, little endian:
 *   0   28 36 00 00 00 80      header
 *   14  u64                    the glasses' clock, ns
 *   30  u8                     kind: 11 motion (1000 Hz), 4 other (400 Hz)
 *   34  f32 x3                 gyro, rad/s       (kind 11; NaN in kind 4)
 *   46  f32 x3                 accelerometer, m/s^2
 *   58  f32 x3                 kind 4: the magnetometer, it seems
 *   70  f32                    temperature, C
 * Read from an XREAL 1 Pro+ (3318:0444); the One series' drivers agree on
 * the header and the gyro/accel offsets.
 *
 * Tailscale (an exit node without LAN access, or someone's subnet
 * routes) can claim 169.254.0.0/16, so the socket is bound to the
 * interface that has the glasses' link address (SO_BINDTODEVICE, allowed
 * unprivileged for a connect since Linux 5.7).
 *
 * Fusion is a Mahony filter: the gyro turns the estimate, the gravity the
 * accelerometer feels pulls its tilt back; heading drifts only by the
 * gyro's bias, which is measured while the head is still. Samples carry
 * the glasses' timestamps; their offset from our clock is the smallest
 * seen (the least delayed sample), so poses can be predicted to the
 * moment a frame lights up.
 *
 * It doesn't know the compositor: what it needs comes through imu.h's
 * host (an event loop, the settings, a callback) and imu-host.h (the
 * log, the clock, where state is kept), so the Monado driver in c8-xr
 * builds this same file with its own imu-host.h.
 */
#define _GNU_SOURCE // memmem, SO_BINDTODEVICE
#include <arpa/inet.h>
#include <errno.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "imu.h"
/* <>: the program's own (its -I first), not always this folder's */
#include <imu-host.h>

#define IMU_HOST "169.254.2.1"
#define IMU_PORT 52998
#define IMU_NET "169.254.2." // the glasses' link, our end of it
#define FRAME 134
#define KIND_MOTION 11
#define GRAVITY 9.80665

#define CHECK_MS 1000 // watchdog: connect, give up, notice silence
#define READ_MS 100 // the stream is read this often when no frame asks
#define CONNECT_MS 2000
#define SILENT_MS 1000
#define NOTIFY_MS 10000 // wanted this long with no data: say why
#define SETTLE_NS 1000000000LL // fast tilt pull and bias first, then recentre

#define KP_SETTLE 5.0
#define KP 0.4
/* Still is the gyro barely wavering, whatever it reads: its noise is
 * about 0.002 rad/s, a head held still sways more. A still stretch's
 * average is then the bias; a moving head never counts, so putting the
 * glasses on can't teach it a drift */
#define STILL_SAMPLES 250 // a quarter of a second
#define STILL_SPREAD 0.005 // rad/s, standard deviation per axis
#define BIAS_MAX 0.02 // rad/s: more than that is turning, not bias
#define BIAS_TAKE 0.3 // how much of a still stretch's average to take
/* Worn, the head is never that still, and the bias moves as the glasses
 * warm up: what was learnt on the desk went stale and the world turned
 * steadily one way. But a head held about still sways to and fro, so
 * over a second it turns by next to nothing, and its average is the
 * bias too, only less exactly: taken a little at a time, and only when
 * near what's known (a slow, steady turn isn't learnt as drift) */
#define WORN_SAMPLES 1000 // a second
#define WORN_SPREAD 0.03 // rad/s: a head looking at something
#define WORN_NEAR 0.006 // rad/s from the bias known
#define WORN_TAKE 0.05
/* Prediction turns on by the gyro for up to 100 ms, so one sample's
 * wobble would shake the picture: it turns by the last few ms' average.
 * That lags only how fast the head turns, not where it points */
#define GYRO_TAU 0.006 // s
/* [glasses] steady: the shown orientation follows the fused one through
 * a 1€ filter (Casiez et al.): a low cutoff while the head is all but
 * still, so text at 1:1 pixels doesn't shimmer, rising with the turning
 * speed so a real turn is never behind. The most it trails by is
 * 1/(2π BETA) rad, a twentieth of a degree */
#define STEADY_FC 1.0 // Hz, held still
#define STEADY_BETA 100.0 // Hz more per rad/s
/* What gravity reads isn't 9.81 on every sensor, nor once it has warmed
 * up: "only gravity pushing" is judged against what it has read lately.
 * Against the constant, a sensor reading half a m/s^2 off would never be
 * pulled level again, nor learn its bias, and the world would tip */
#define G_TAU 5.0 // s
#define G_SANE 2.0 // m/s^2 from 9.81: beyond it isn't gravity alone
#define G_LEVEL 0.5 // m/s^2 from what it reads: only gravity pushing
#define HEALTH_NS 10000000000LL // how tracking is doing, to the log
/* The bias moves with the sensor's temperature, some 15 C from plugged
 * in to warm, and one bias kept from a session's (warm) end was wrong
 * for the next one's (cold) start, always the same way: the world turned
 * right until it was learnt again, and worn that is slow. So it's kept
 * by temperature too, a value every TEMP_STEP degrees: a session starts
 * from the one for the temperature it starts at, warming follows the
 * curve as it was learnt (THERMAL_SAMPLES apart), and where the glasses
 * were measured at rest, which is exact, the bias in use is drawn a
 * little towards that */
#define TEMP_STEP 2.0 // C
#define TEMP_BINS 40 // from 0 C
#define TEMP_TAU 5.0 // s: the temperature read is smoothed
#define THERMAL_SAMPLES 1000 // a second
#define TABLE_TAKE_REST 0.2 // of the bias in use, a second at rest
#define TABLE_TAKE_WORN 0.005 // and worn
#define TABLE_TRUSTED 5.0 // seconds at rest make a value one to lean on
#define TABLE_PULL 0.01 // towards a trusted value, a second

struct c8_imu {
	struct c8_imu_host host;
	bool wanted;
	int64_t wanted_since;
	bool told; // the no-IMU toast, once per wanting

	int fd;
	/* io: only while connecting. The stream itself isn't watched: a
	 * thousand samples a second would wake the loop as often, and the
	 * pose is only wanted once a frame. c8_imu_read takes what's come,
	 * before each glasses frame and from `reader` when none are drawn. */
	struct wl_event_source *io, *watchdog, *reader;
	bool connecting;
	int64_t connect_started, last_data;
	uint8_t buf[FRAME * 64];
	size_t len;

	/* Sensor axes to the head's (+x right, +y up, -z ahead): which one
	 * and its sign, per head axis */
	int axis[3], sign[3];

	/* The filter; orientation turns head axes into the world's */
	bool live, settled;
	struct quat q;
	struct vec3 bias, gyro; // gyro: averaged (GYRO_TAU), bias taken off
	struct quat shown; // q steadied, see STEADY_FC
	int64_t first_ts, last_ts, offset; // offset: our clock - theirs
	bool have_offset;
	struct vec3 still_sum, still_sq; // the stretch so far, raw gyro
	int still_n;
	struct vec3 worn_sum, worn_sq; // the same over WORN_SAMPLES
	int worn_n;
	bool bias_known;
	int64_t bias_saved; // ms, see save_bias
	double g; // what gravity reads, see G_TAU
	/* The bias by temperature, see TEMP_STEP: rest counts the seconds
	 * measured at rest, 0 with worn > 0 is learnt worn only */
	struct {
		struct vec3 bias;
		float rest, worn;
	} table[TEMP_BINS];
	double temp, temp_last; // smoothed; as of the last thermal()
	bool have_temp, started; // started: this connection took its first bias
	int thermal_n;
	int learnt; // since the last thermal(): 1 worn, 2 at rest

	/* Since the last health line */
	struct {
		int64_t since, offset0; // their clock; the first offset
		int samples, level, asked, clamped;
		double gap_max, g_sum, ahead_sum, ahead_max, asked_gap_max;
		int64_t asked_last;
		float temperature;
	} health;
};

/* "-x,-z,-y": per head axis x, y, z, the sensor's axis and sign */
static bool parse_axes(struct c8_imu *imu, const char *s) {
	int axis[3], sign[3];
	for (int i = 0; i < 3; i++) {
		sign[i] = 1;
		if (*s == '-' || *s == '+') {
			sign[i] = *s++ == '-' ? -1 : 1;
		}
		if (*s < 'x' || *s > 'z') {
			return false;
		}
		axis[i] = *s++ - 'x';
		if (i < 2 && *s++ != ',') {
			return false;
		}
	}
	if (*s || axis[0] == axis[1] || axis[1] == axis[2] ||
			axis[0] == axis[2]) {
		return false;
	}
	memcpy(imu->axis, axis, sizeof(axis));
	memcpy(imu->sign, sign, sizeof(sign));
	return true;
}

static struct vec3 to_head(struct c8_imu *imu, const float v[3]) {
	return (struct vec3){
		imu->sign[0] * v[imu->axis[0]],
		imu->sign[1] * v[imu->axis[1]],
		imu->sign[2] * v[imu->axis[2]],
	};
}

static void set_live(struct c8_imu *imu, bool live, bool settled) {
	if (live == imu->live && settled == imu->settled) {
		return;
	}
	bool was = imu->settled;
	imu->live = live;
	imu->settled = settled;
	if (imu->host.changed) {
		imu->host.changed(imu->host.data, settled && !was);
	}
}

static void reset_filter(struct c8_imu *imu) {
	imu->q = imu->shown = quat_identity();
	imu->gyro = (struct vec3){ 0 };
	imu->have_offset = false;
	imu->first_ts = imu->last_ts = 0;
	imu->still_sum = imu->still_sq = (struct vec3){ 0 };
	imu->still_n = 0;
	imu->worn_sum = imu->worn_sq = (struct vec3){ 0 };
	imu->worn_n = 0;
	imu->g = GRAVITY;
	imu->have_temp = imu->started = false;
	imu->thermal_n = THERMAL_SAMPLES - 1; // the first sample starts it
	imu->learnt = 0;
	memset(&imu->health, 0, sizeof(imu->health));
}

static void save_bias(struct c8_imu *imu);

static void disconnect(struct c8_imu *imu) {
	if (imu->io) {
		wl_event_source_remove(imu->io);
		imu->io = NULL;
	}
	if (imu->fd >= 0) {
		close(imu->fd);
		imu->fd = -1;
	}
	imu->connecting = false;
	imu->len = 0;
	if (imu->live && imu->bias_known) {
		/* What was learnt since the last minute's save, too */
		imu->bias_saved = 0;
		save_bias(imu);
	}
	set_live(imu, false, false);
}

/* The sensor sits tilted in the frame: its ahead is [glasses] tilt
 * degrees above where the eyes look (the 1 Pro+'s about 40, measured as
 * the axis a head tilts about, which is the line of sight). The filter
 * works in the sensor's axes; what's drawn turns down by that much */
static struct quat to_eyes(struct c8_imu *imu, struct quat q) {
	double tilt_deg = 0;
	bool steady = true;
	imu->host.settings(imu->host.data, &tilt_deg, &steady);
	double tilt = tilt_deg * M_PI / 180;
	return quat_mul(q, quat_axis_angle((struct vec3){ 1, 0, 0 }, -tilt));
}

/* Turning by the gyro over dt: q * exp(w dt / 2) */
static struct quat turn(struct quat q, struct vec3 w, double dt) {
	double angle = vec3_length(w) * dt;
	if (angle < 1e-12) {
		return q;
	}
	return quat_normalize(quat_mul(q,
		quat_axis_angle(vec3_scale(w, 1 / vec3_length(w)), angle)));
}

/* The bias is learnt only while the glasses rest (a head on them sways
 * more than it), so it's kept for the next session:
 * ~/.local/state/cont8nuum/glasses-bias, "x y z" rad/s in head axes */
static bool bias_path(char *path, size_t size, bool make) {
	return c8_state_path("glasses-bias", path, size, make);
}

/* The file: the bias last in use, then a line "t BIN x y z rest worn"
 * for each temperature known */
static void load_bias(struct c8_imu *imu) {
	char path[4200];
	FILE *f = bias_path(path, sizeof(path), false) ? fopen(path, "r") : NULL;
	if (f == NULL) {
		return;
	}
	struct vec3 b;
	if (fscanf(f, "%lf %lf %lf", &b.x, &b.y, &b.z) == 3 &&
			vec3_length(b) < BIAS_MAX) {
		imu->bias = b;
		imu->bias_known = true;
	}
	int bin;
	float rest, worn;
	while (fscanf(f, " t %d %lf %lf %lf %f %f", &bin, &b.x, &b.y, &b.z,
			&rest, &worn) == 6) {
		if (bin >= 0 && bin < TEMP_BINS && vec3_length(b) < BIAS_MAX &&
				rest >= 0 && worn >= 0 && rest + worn > 0) {
			imu->table[bin].bias = b;
			imu->table[bin].rest = rest;
			imu->table[bin].worn = worn;
		}
	}
	fclose(f);
}

static void save_bias(struct c8_imu *imu) {
	int64_t now = c8_now_ms();
	if (imu->bias_saved && now - imu->bias_saved < 60000) {
		return; // resting, it's learnt four times a second
	}
	imu->bias_saved = now;
	char path[4200], tmp[4210];
	if (!bias_path(path, sizeof(path), true)) {
		return;
	}
	snprintf(tmp, sizeof(tmp), "%s.new", path);
	FILE *f = fopen(tmp, "w");
	if (f == NULL) {
		return;
	}
	fprintf(f, "%.6f %.6f %.6f\n", imu->bias.x, imu->bias.y, imu->bias.z);
	for (int i = 0; i < TEMP_BINS; i++) {
		if (imu->table[i].rest + imu->table[i].worn > 0) {
			fprintf(f, "t %d %.6f %.6f %.6f %.1f %.1f\n", i,
				imu->table[i].bias.x, imu->table[i].bias.y,
				imu->table[i].bias.z, imu->table[i].rest, imu->table[i].worn);
		}
	}
	if (fclose(f) == 0) {
		rename(tmp, path);
	}
}

static bool bin_known(struct c8_imu *imu, int bin) {
	return imu->table[bin].rest + imu->table[bin].worn > 0;
}

/* The bias the table has for a temperature: between the known values
 * either side of it, or the nearest one's. trusted: both were measured
 * at rest */
static bool table_bias(struct c8_imu *imu, double temp, struct vec3 *out,
		bool *trusted) {
	double at = temp / TEMP_STEP - 0.5; // bins are known at their middles
	int lo = -1, hi = -1;
	for (int i = (int)floor(at); i >= 0; i--) {
		if (i < TEMP_BINS && bin_known(imu, i)) {
			lo = i;
			break;
		}
	}
	for (int i = (int)floor(at) + 1; i < TEMP_BINS; i++) {
		if (i >= 0 && bin_known(imu, i)) {
			hi = i;
			break;
		}
	}
	if (lo < 0 && hi < 0) {
		return false;
	}
	if (lo < 0 || hi < 0) {
		int one = lo < 0 ? hi : lo;
		*out = imu->table[one].bias;
		*trusted = imu->table[one].rest >= TABLE_TRUSTED;
		return true;
	}
	double f = (at - lo) / (hi - lo);
	*out = vec3_add(vec3_scale(imu->table[lo].bias, 1 - f),
		vec3_scale(imu->table[hi].bias, f));
	*trusted = imu->table[lo].rest >= TABLE_TRUSTED &&
		imu->table[hi].rest >= TABLE_TRUSTED;
	return true;
}

/* Once a second: the bias follows the temperature along the table, and
 * the table takes what was learnt at this one */
static void thermal(struct c8_imu *imu) {
	if (!imu->have_temp) {
		return;
	}
	struct vec3 now, before;
	bool trusted = false, unused = false;
	if (!imu->started) {
		/* A connection's first: the bias for the temperature it starts
		 * at, over the one the last session ended with */
		imu->started = true;
		if (table_bias(imu, imu->temp, &now, &trusted)) {
			imu->bias = now;
			imu->bias_known = true;
			IMU_LOG(IMU_INFO, "Glasses: gyro bias %.4f %.4f %.4f rad/s "
				"for %.1f C", now.x, now.y, now.z, imu->temp);
		}
	} else if (table_bias(imu, imu->temp, &now, &trusted) && trusted &&
			table_bias(imu, imu->temp_last, &before, &unused) && unused) {
		/* Only along values measured at rest: what was learnt worn
		 * wavers from one temperature to the next by more than the
		 * bias moves */
		imu->bias = vec3_add(imu->bias, vec3_sub(now, before));
		if (imu->learnt != 2) {
			imu->bias = vec3_add(imu->bias,
				vec3_scale(vec3_sub(now, imu->bias), TABLE_PULL));
		}
	}
	imu->temp_last = imu->temp;
	int bin = (int)floor(imu->temp / TEMP_STEP);
	if (imu->learnt && imu->bias_known && bin >= 0 && bin < TEMP_BINS) {
		bool rest = imu->learnt == 2;
		if (!bin_known(imu, bin) || (rest && imu->table[bin].rest <= 0)) {
			/* The first for this temperature, or the first at rest,
			 * which is worth more than all that was learnt worn */
			imu->table[bin].bias = imu->bias;
		} else if (rest || imu->table[bin].rest < TABLE_TRUSTED) {
			double take = rest ? TABLE_TAKE_REST : TABLE_TAKE_WORN;
			imu->table[bin].bias = vec3_add(
				vec3_scale(imu->table[bin].bias, 1 - take),
				vec3_scale(imu->bias, take));
		}
		float *seconds = rest ? &imu->table[bin].rest : &imu->table[bin].worn;
		*seconds = fminf(*seconds + 1, 100000);
		save_bias(imu);
	}
	imu->learnt = 0;
}

/* Adds a sample to a stretch; once it has n, its mean and spread (the
 * largest standard deviation of an axis), and it starts again */
static bool stretch(struct vec3 *sum, struct vec3 *sq, int *count, int n,
		struct vec3 gyro, struct vec3 *mean, double *spread) {
	*sum = vec3_add(*sum, gyro);
	*sq = vec3_add(*sq, (struct vec3){
		gyro.x * gyro.x, gyro.y * gyro.y, gyro.z * gyro.z });
	if (++*count < n) {
		return false;
	}
	*mean = vec3_scale(*sum, 1.0 / n);
	double v[3] = { sq->x / n - mean->x * mean->x,
		sq->y / n - mean->y * mean->y, sq->z / n - mean->z * mean->z };
	*spread = 0;
	for (int i = 0; i < 3; i++) {
		*spread = fmax(*spread, sqrt(fmax(0, v[i])));
	}
	*sum = *sq = (struct vec3){ 0 };
	*count = 0;
	return true;
}

/* Stretches of stillness: the bias from them */
static void still(struct c8_imu *imu, struct vec3 gyro, bool level_g) {
	if (!level_g) {
		/* being pushed about: start again */
		imu->still_n = imu->worn_n = 0;
		imu->still_sum = imu->still_sq = (struct vec3){ 0 };
		imu->worn_sum = imu->worn_sq = (struct vec3){ 0 };
		return;
	}
	struct vec3 mean;
	double spread;
	if (stretch(&imu->worn_sum, &imu->worn_sq, &imu->worn_n,
			WORN_SAMPLES, gyro, &mean, &spread) &&
			spread < WORN_SPREAD &&
			vec3_length(vec3_sub(mean, imu->bias)) < WORN_NEAR) {
		imu->bias = vec3_add(vec3_scale(imu->bias, 1 - WORN_TAKE),
			vec3_scale(mean, WORN_TAKE));
		if (imu->learnt < 1) {
			imu->learnt = 1;
		}
		save_bias(imu);
	}
	if (!stretch(&imu->still_sum, &imu->still_sq, &imu->still_n,
			STILL_SAMPLES, gyro, &mean, &spread) ||
			spread > STILL_SPREAD || vec3_length(mean) > BIAS_MAX) {
		return;
	}
	if (!imu->bias_known) {
		imu->bias = mean;
		imu->bias_known = true;
		imu->bias_saved = 0; // the first: saved at once
		IMU_LOG(IMU_INFO, "Glasses: gyro bias %.4f %.4f %.4f rad/s",
			mean.x, mean.y, mean.z);
	} else {
		imu->bias = vec3_add(vec3_scale(imu->bias, 1 - BIAS_TAKE),
			vec3_scale(mean, BIAS_TAKE));
	}
	imu->learnt = 2;
	save_bias(imu);
}

/* Every HEALTH_NS a line saying how tracking is doing, so a session
 * that went wrong can be read afterwards: samples and the longest gap
 * between two, how far our clock has moved against theirs, how far ahead
 * poses were predicted (and how often that hit its limit), the longest
 * wait between two frames asking, what gravity reads and how much of the
 * time it counted as gravity alone, the bias and the temperature */
static void health(struct c8_imu *imu, int64_t ts, double dt, double acc_len,
		bool level_g) {
	if (imu->health.since == 0) {
		imu->health.since = ts;
		if (imu->health.offset0 == 0) {
			imu->health.offset0 = imu->offset;
		}
	}
	imu->health.samples++;
	imu->health.level += level_g;
	imu->health.g_sum += acc_len;
	imu->health.gap_max = fmax(imu->health.gap_max, dt);
	if (ts - imu->health.since < HEALTH_NS) {
		return;
	}
	int n = imu->health.samples, asked = imu->health.asked;
	IMU_LOG(IMU_INFO, "Glasses: tracking: %d samples, gap %.1f ms, "
		"clock %+.2f ms, ahead %.1f/%.1f ms (%d of %d at the limit), "
		"frames %.1f ms apart at most, g %.2f (%.2f, level %d%%), "
		"bias %.4f %.4f %.4f, %.1f C", n, imu->health.gap_max * 1e3,
		(imu->offset - imu->health.offset0) / 1e6,
		asked ? imu->health.ahead_sum / asked * 1e3 : 0,
		imu->health.ahead_max * 1e3, imu->health.clamped, asked,
		imu->health.asked_gap_max * 1e3, imu->health.g_sum / n, imu->g,
		imu->health.level * 100 / n, imu->bias.x, imu->bias.y, imu->bias.z,
		imu->health.temperature);
	int64_t offset0 = imu->health.offset0, last = imu->health.asked_last;
	float temperature = imu->health.temperature;
	memset(&imu->health, 0, sizeof(imu->health));
	imu->health.offset0 = offset0;
	imu->health.asked_last = last;
	imu->health.temperature = temperature;
}

static void sample(struct c8_imu *imu, int64_t ts, struct vec3 gyro,
		struct vec3 acc) {
	int64_t now = c8_now_ns();
	/* Their clock to ours: the least delayed sample so far, let creep
	 * up a little each time so drift between the clocks is followed */
	int64_t offset = now - ts;
	if (!imu->have_offset || offset < imu->offset) {
		imu->offset = offset;
		imu->have_offset = true;
	} else {
		imu->offset += 200; // 0.2 ms a second at 1 kHz
	}

	double dt = (ts - imu->last_ts) / 1e9;
	bool first = imu->last_ts == 0;
	imu->last_ts = ts;
	if (first) {
		imu->first_ts = ts;
	}
	bool settling = ts - imu->first_ts < SETTLE_NS;

	double acc_len = vec3_length(acc);
	if (fabs(acc_len - GRAVITY) < G_SANE && !first && dt > 0 && dt < 0.05) {
		/* Pushes this way and that average out over a few seconds */
		double tau = settling ? 0.2 : G_TAU;
		imu->g += (acc_len - imu->g) * dt / (tau + dt);
	}
	bool level_g = fabs(acc_len - imu->g) < G_LEVEL;
	float t = imu->health.temperature;
	if (isfinite(t) && t > 0 && t < TEMP_BINS * TEMP_STEP) {
		if (!imu->have_temp) {
			imu->temp = imu->temp_last = t;
			imu->have_temp = true;
		} else if (!first && dt > 0 && dt < 0.05) {
			imu->temp += (t - imu->temp) * dt / (TEMP_TAU + dt);
		}
	}
	if (++imu->thermal_n >= THERMAL_SAMPLES) {
		imu->thermal_n = 0;
		thermal(imu);
	}
	still(imu, gyro, level_g);
	health(imu, ts, first ? 0 : dt, acc_len, level_g);
	struct vec3 w = vec3_sub(gyro, imu->bias);

	if (first || dt <= 0 || dt > 0.05) {
		imu->gyro = w;
		imu->shown = imu->q;
		return; // a gap: nothing to integrate over
	}
	/* Gravity's pull: up as felt against up as the estimate has it,
	 * only when nothing but gravity is pushing */
	if (acc_len > 1e-3 && (settling || level_g)) {
		struct vec3 felt = vec3_scale(acc, 1 / acc_len);
		struct vec3 up = quat_rotate(quat_conjugate(imu->q),
			(struct vec3){ 0, 1, 0 });
		struct vec3 e = vec3_cross(felt, up);
		w = vec3_add(w, vec3_scale(e, settling ? KP_SETTLE : KP));
	}
	imu->q = turn(imu->q, w, dt);
	struct vec3 now_w = vec3_sub(gyro, imu->bias);
	imu->gyro = vec3_add(imu->gyro, vec3_scale(vec3_sub(now_w, imu->gyro),
		dt / (GYRO_TAU + dt)));
	double tilt_deg = 0;
	bool steady = true;
	imu->host.settings(imu->host.data, &tilt_deg, &steady);
	if (settling || !steady) {
		imu->shown = imu->q;
	} else {
		double fc = STEADY_FC + STEADY_BETA * vec3_length(imu->gyro);
		double a = 1 / (1 + 1 / (2 * M_PI * fc * dt));
		imu->shown = quat_normalize(quat_slerp(imu->shown, imu->q, a));
	}
	set_live(imu, true, !settling);
	if (ts / 1000000000 != (ts - (int64_t)(dt * 1e9)) / 1000000000) {
		/* Once a second, for checking the axes: where ahead points */
		struct quat eyes = to_eyes(imu, imu->q);
		struct vec3 f = quat_rotate(eyes, (struct vec3){ 0, 0, -1 });
		struct vec3 r = quat_rotate(eyes, (struct vec3){ 1, 0, 0 });
		IMU_LOG(IMU_DEBUG, "Glasses: yaw %.0f pitch %.0f roll %.0f "
			"(acc %.1f %.1f %.1f)", atan2(-f.x, -f.z) * 180 / M_PI,
			asin(fmax(-1, fmin(1, f.y))) * 180 / M_PI,
			asin(fmax(-1, fmin(1, r.y))) * -180 / M_PI, acc.x, acc.y, acc.z);
	}
}

static void parse(struct c8_imu *imu) {
	static const uint8_t header[] = { 0x28, 0x36, 0x00, 0x00, 0x00, 0x80 };
	size_t at = 0;
	while (imu->len - at >= FRAME) {
		uint8_t *f = imu->buf + at;
		if (memcmp(f, header, sizeof(header)) != 0) {
			/* Lost step: find the next header */
			uint8_t *next = memmem(f + 1, imu->len - at - 1, header,
				sizeof(header));
			at = next ? (size_t)(next - imu->buf) : imu->len;
			continue;
		}
		at += FRAME;
		if (f[30] != KIND_MOTION) {
			continue;
		}
		uint64_t ts;
		float g[3], a[3];
		memcpy(&ts, f + 14, 8);
		memcpy(g, f + 34, sizeof(g));
		memcpy(a, f + 46, sizeof(a));
		bool ok = ts > 0;
		for (int i = 0; i < 3; i++) {
			ok = ok && isfinite(g[i]) && isfinite(a[i]) &&
				fabsf(g[i]) < 35 && fabsf(a[i]) < 160;
		}
		if (ok) {
			memcpy(&imu->health.temperature, f + 70, 4);
			sample(imu, (int64_t)ts, to_head(imu, g), to_head(imu, a));
		}
	}
	memmove(imu->buf, imu->buf + at, imu->len - at);
	imu->len -= at;
}

/* The connection came up, or didn't */
static int on_io(int fd, uint32_t mask, void *data) {
	struct c8_imu *imu = data;
	int err = 0;
	socklen_t len = sizeof(err);
	getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
	if (err != 0 || (mask & (WL_EVENT_ERROR | WL_EVENT_HANGUP))) {
		IMU_LOG(IMU_DEBUG, "Glasses: IMU: %s", strerror(err));
		disconnect(imu);
		return 0;
	}
	imu->connecting = false;
	imu->last_data = c8_now_ms();
	reset_filter(imu);
	wl_event_source_remove(imu->io);
	imu->io = NULL;
	wl_event_source_timer_update(imu->reader, READ_MS);
	IMU_LOG(IMU_INFO, "Glasses: IMU connected");
	return 0;
}

/* Everything the glasses have sent since the last time, through the
 * filter in the order it came. May find the stream ended, or get the
 * first fix: `changed` then runs from here. */
void c8_imu_read(struct c8_imu *imu) {
	if (imu == NULL || imu->fd < 0 || imu->connecting) {
		return;
	}
	for (;;) {
		ssize_t n = read(imu->fd, imu->buf + imu->len,
			sizeof(imu->buf) - imu->len);
		if (n > 0) {
			imu->len += n;
			imu->last_data = c8_now_ms();
			parse(imu);
			continue;
		}
		if (n < 0 && (errno == EAGAIN || errno == EINTR)) {
			return;
		}
		IMU_LOG(IMU_INFO, "Glasses: IMU stream ended");
		disconnect(imu);
		return;
	}
}

static int reader(void *data) {
	struct c8_imu *imu = data;
	c8_imu_read(imu);
	if (imu->fd >= 0 && !imu->connecting) {
		wl_event_source_timer_update(imu->reader, READ_MS);
	}
	return 0;
}

/* The interface with our end of the glasses' link */
bool c8_imu_glasses_link(char name[IF_NAMESIZE]) {
	struct ifaddrs *list;
	if (getifaddrs(&list) < 0) {
		return false;
	}
	bool found = false;
	for (struct ifaddrs *i = list; i && !found; i = i->ifa_next) {
		if (i->ifa_addr == NULL || i->ifa_addr->sa_family != AF_INET) {
			continue;
		}
		char addr[INET_ADDRSTRLEN];
		inet_ntop(AF_INET, &((struct sockaddr_in *)i->ifa_addr)->sin_addr,
			addr, sizeof(addr));
		if (strncmp(addr, IMU_NET, strlen(IMU_NET)) == 0 &&
				strcmp(addr, IMU_HOST) != 0) {
			snprintf(name, IF_NAMESIZE, "%s", i->ifa_name);
			found = true;
		}
	}
	freeifaddrs(list);
	return found;
}

static void try_connect(struct c8_imu *imu) {
	struct sockaddr_in sa = { .sin_family = AF_INET,
		.sin_port = htons(IMU_PORT) };
	inet_pton(AF_INET, IMU_HOST, &sa.sin_addr);
	char dev[IF_NAMESIZE] = "";
	/* C8_XR_IMU=HOST:PORT: a stream from elsewhere (a test's) */
	const char *override = getenv("C8_XR_IMU");
	if (override && *override) {
		char host[64];
		int port;
		if (sscanf(override, "%63[^:]:%d", host, &port) != 2 ||
				inet_pton(AF_INET, host, &sa.sin_addr) != 1) {
			return;
		}
		sa.sin_port = htons(port);
	} else if (!c8_imu_glasses_link(dev)) {
		return; // the link isn't up (yet)
	}
	int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
	if (fd < 0) {
		return;
	}
	if (dev[0] && setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, dev,
			strlen(dev)) < 0) {
		IMU_LOG_ERRNO(IMU_DEBUG, "Glasses: binding to %s", dev);
	}
	int one = 1;
	setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
	if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0 &&
			errno != EINPROGRESS) {
		close(fd);
		return;
	}
	imu->fd = fd;
	imu->connecting = true;
	imu->connect_started = c8_now_ms();
	imu->io = wl_event_loop_add_fd(imu->host.loop, fd,
		WL_EVENT_WRITABLE, on_io, imu);
}

static int watchdog(void *data) {
	struct c8_imu *imu = data;
	int64_t now = c8_now_ms();
	if (!imu->wanted) {
		return 0;
	}
	c8_imu_read(imu); // before judging it silent
	if (imu->fd < 0) {
		try_connect(imu);
	} else if (imu->connecting && now - imu->connect_started > CONNECT_MS) {
		disconnect(imu);
	} else if (!imu->connecting && now - imu->last_data > SILENT_MS) {
		IMU_LOG(IMU_INFO, "Glasses: IMU went quiet");
		disconnect(imu);
	}
	if (!imu->told && !imu->live && now - imu->wanted_since > NOTIFY_MS) {
		imu->told = true;
		if (imu->host.silent) {
			imu->host.silent(imu->host.data);
		}
	}
	wl_event_source_timer_update(imu->watchdog, CHECK_MS);
	return 0;
}

struct c8_imu *c8_imu_create(const struct c8_imu_host *host) {
	struct c8_imu *imu = calloc(1, sizeof(*imu));
	imu->host = *host;
	imu->fd = -1;
	/* The 1 Pro+ as worn: right is the sensor's +x, up -y, back -z.
	 * Up is gravity and the turn; right/back could as well be the other
	 * way round as far as a recording goes (a half turn about up), and
	 * wearing them settled it: with -x,-y,z looking up moved the slate
	 * up. C8_XR_AXES tries others */
	const char *axes = getenv("C8_XR_AXES");
	if (!(axes && parse_axes(imu, axes)) && !parse_axes(imu, "x,-y,-z")) {
		abort();
	}
	reset_filter(imu);
	load_bias(imu);
	imu->watchdog = wl_event_loop_add_timer(host->loop, watchdog, imu);
	imu->reader = wl_event_loop_add_timer(host->loop, reader, imu);
	return imu;
}

void c8_imu_destroy(struct c8_imu *imu) {
	if (imu == NULL) {
		return;
	}
	imu->host.changed = NULL;
	disconnect(imu);
	wl_event_source_remove(imu->watchdog);
	wl_event_source_remove(imu->reader);
	free(imu);
}

void c8_imu_set_wanted(struct c8_imu *imu, bool wanted) {
	if (wanted == imu->wanted) {
		return;
	}
	imu->wanted = wanted;
	if (wanted) {
		imu->wanted_since = c8_now_ms();
		imu->told = false;
		watchdog(imu); // at once, then every second
	} else {
		disconnect(imu);
		wl_event_source_timer_update(imu->watchdog, 0);
	}
}

bool c8_imu_orientation(struct c8_imu *imu, int64_t when_ns,
		struct quat *out) {
	if (!imu || !imu->live) {
		return false;
	}
	/* Ahead of the last sample by as long as it takes to be seen,
	 * turning on as the gyro last said */
	double ahead = (when_ns - (imu->last_ts + imu->offset)) / 1e9;
	int64_t now = c8_now_ns();
	if (imu->health.asked_last) {
		imu->health.asked_gap_max = fmax(imu->health.asked_gap_max,
			(now - imu->health.asked_last) / 1e9);
	}
	imu->health.asked_last = now;
	imu->health.asked++;
	imu->health.clamped += ahead >= 0.1;
	imu->health.ahead_sum += fmax(0, fmin(ahead, 0.1));
	imu->health.ahead_max = fmax(imu->health.ahead_max, ahead);
	ahead = fmax(0, fmin(ahead, 0.1));
	*out = to_eyes(imu, turn(imu->shown, imu->gyro, ahead));
	return true;
}
