diff --git a/CHANGELOG.md b/CHANGELOG.md index 63f6231..a1ab5c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ from one version to the next. ## [Unreleased] +### Added + +- **Table > Latency Check** (`Ctrl+Shift+L`, or `Cmd+Shift+L` on a Mac), for + working out where lag on a real table comes from. A ruler ahead of each + moving puck and finger shows the whole delay, end to end, and a readout + splits it into frame rate, tracker rate, Planchette's own delay, updates + while moving, and pucks lost and found. `docs/TABLE.md` has a 20 minute test + to run with it. + ### Fixed - On Windows, editing an interface did not reload it when the workspace path diff --git a/docs/TABLE.md b/docs/TABLE.md index 1dba959..43fc048 100644 --- a/docs/TABLE.md +++ b/docs/TABLE.md @@ -208,6 +208,83 @@ typo is copied to `table.json.broken` before anything overwrites it. Turn on table input in Settings first. Present mode can be tried on a laptop too (it will show the not-1:1 banner). +## Measuring lag + +If what the table shows trails the hand, **Table > Latency Check** +(`Ctrl+Shift+L`) says where the time goes. It draws over whatever interface is +running, in present mode too, and the same command closes it. Counts start when +it opens, so close and reopen it between tests. + +Lag is four delays added together, and each has its own fix: + + tracker -> Planchette -> the interface -> the display + +**The ruler** is the whole delay, end to end. Every puck and finger gets a +yellow ring exactly where the tracker last reported it. While it moves, a ruler +runs ahead of the ring along the direction of travel, ticked at 50, 100, 150 and +200 ms at the current speed. Slide a puck steadily and look at where the +physical puck's centre sits on the ruler: at the 100 tick, everything between +the puck and the screen adds up to about 100 ms. With no lag at all, the puck +would sit in its ring. Software cannot measure this on its own because it cannot +see the puck; an eye, or a slow-motion phone video paused mid-slide, can. + +**The readout** splits it up: + +| Line | What it is | Healthy | +| ---- | ---------- | ------- | +| Frame rate | How often the screen is redrawn. An interface shares this, so a heavy one pulls it down. *Long* counts frames over 25 ms, each one a visible stutter. | The display's refresh rate, usually 60, with long frames rare | +| Tracker | Packets per second from the tracker | Steady while things move (the rate for any given tracker is *unconfirmed*) | +| Planchette | From a packet arriving to it reaching the interface, median and worst | A few ms. More means the computer is busy, usually with the interface | +| While moving | How often a moving puck or finger gets a new position, and the longest wait | Close to the tracker's rate; gaps under 50 ms | +| Lost and found | A puck that vanished and came back within a second, and the longest absence | 0, or very rare | + +### The test + +About 20 minutes, in present mode, with table input on. Bring one puck and a +phone that films slow motion. Write the numbers down as you go (there is a +table below). + +1. **Idle.** Nothing on the table. Note the frame rate and long frames. +2. **Tracker rate.** Slide a puck in slow circles for ten seconds. Note + packets/s and updates/s while moving. +3. **End to end.** Slide the puck in a straight line at a steady, medium + speed, about a metre in two seconds. Note the tick the real puck sits at. + Do it five times, both directions. If it is too quick to read, film it in + slow motion and pause mid-slide. Then do the same with one finger. +4. **Fast.** Slide the puck back and forth hard, ten times. Note *Lost and + found* and the longest gap. +5. **The display.** Find the display's picture settings (its remote or on-screen + menu) and look for a *Game*, *PC* or low-latency mode. Note what it was on, + switch, and repeat step 3. +6. **The tracker.** Open the tracker's own software and look for smoothing, + filtering or prediction settings. Note what they are, turn smoothing to its + lowest, and repeat steps 3 and 4. Change one setting at a time, and put back + anything that does not help. +7. **The interface.** Open the interface people noticed lag in, with the check + still open, and use it for a minute. Note the frame rate and long frames. + Watch whether the interface's own graphics trail the yellow ring. + +| Test | Result | +| ---- | ------ | +| Idle: frame rate, long frames | | +| Tracker: packets/s, updates/s while moving | | +| End to end, puck: tick (five tries) | | +| End to end, finger: tick | | +| Fast: lost and found, longest gap | | +| Display mode before, after; tick after | | +| Tracker settings changed; tick and lost and found after | | +| The interface: frame rate, long frames, trails the ring? | | + +### Reading the results + +| Seen | Where the time goes | What helps | +| ---- | ------------------- | ---------- | +| The ruler says 100 ms or more, Planchette says a few ms, frame rate is steady | The tracker or the display | Steps 5 and 6. A display's image processing alone can add 50 ms or more | +| Frame rate drops, or long frames climb, only with one interface open | That interface is too heavy for this computer | Make the interface draw less: smaller or fewer canvases, no large blurs or shadows redrawn every frame | +| The interface's graphics trail the yellow ring | The interface itself: easing, smoothing, or a slow loop | Fix it in the interface. Its graphics should be where the ring is | +| Updates/s while moving well below packets/s, long gaps, lost and found climbing with speed | The tracker loses the puck's tag in motion | Tracker settings, lighting on the table, clean and flat tags, a slower game | +| Planchette above about 5 ms | The computer is busy | Usually the interface; check the frame rate with it open | + ## Troubleshooting | Symptom | Likely cause | @@ -218,6 +295,7 @@ too (it will show the not-1:1 banner). | Every puck vanishes every couple of seconds while sitting still | The tracker sends nothing while nothing moves (*unconfirmed* for any given tracker). Set `tuio.staleMs` to `0`. | | After starting Planchette, pucks already on the table do not appear until moved | The tracker only sends positions for things that move. Nudge them. | | Everything is mirrored, or turns the wrong way | **Table > Calibrate…** | +| What the table shows trails the hand | [Measuring lag](#measuring-lag) | | Orange *Not 1:1* banner | `surface` does not match the display, or present mode is on the wrong display (`display`). | ## On-site checklist @@ -241,3 +319,4 @@ found in this document, replacing the *unconfirmed* notes above. `staleMs`, and recovers when it comes back. 8. Reboot: the computer comes back into present mode, on the right display, with the last interface. +9. Run [the lag test](#the-test) and keep its table of results. diff --git a/electron/main.js b/electron/main.js index 5b226bb..ddb5aff 100644 --- a/electron/main.js +++ b/electron/main.js @@ -135,7 +135,10 @@ let tuio = null function startTuio() { tuio = createTuioListener({ - frame: (f) => send('tuio:frame', f), + // Stamped on arrival, so Table > Latency Check can say how long the frame + // took to reach the interface. The tracker emits synchronously while the + // packet is being handled, so this is the packet's arrival time. + frame: (f) => send('tuio:frame', { ...f, t: Date.now() }), control: (e) => send('tuio:control', e), status: (s) => send('tuio:status', s), }) @@ -841,6 +844,7 @@ function buildMenu() { { type: 'separator' }, { label: 'Assign Pucks…', click: () => send('app:enroll') }, { label: 'Calibrate…', click: () => send('app:calibrate') }, + { label: 'Latency Check', accelerator: 'CmdOrCtrl+Shift+L', click: () => send('app:latency') }, { label: 'Show table.json', click: () => { diff --git a/electron/preload.cjs b/electron/preload.cjs index bd0c3d2..d9f53e2 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -29,6 +29,7 @@ contextBridge.exposeInMainWorld('planchette', { onPicker: (cb) => ipcRenderer.on('app:picker', () => cb()), onEnroll: (cb) => ipcRenderer.on('app:enroll', () => cb()), onCalibrate: (cb) => ipcRenderer.on('app:calibrate', () => cb()), + onLatency: (cb) => ipcRenderer.on('app:latency', () => cb()), onAppsChanged: (cb) => ipcRenderer.on('apps:changed', (_e, appId) => cb(appId)), onReloadApp: (cb) => ipcRenderer.on('app:reload', () => cb()), diff --git a/index.html b/index.html index 67c4158..05795a4 100644 --- a/index.html +++ b/index.html @@ -204,6 +204,18 @@ /* Calibration is judged against the overlay, so it shows even on the table. */ body.present.calibrating #overlay { display: block; pointer-events: none; } + /* ---- Table > Latency Check ---- */ + #latency-ruler { position: absolute; inset: 0; pointer-events: none; z-index: 5; } + #latency-ruler[hidden], #latency-hud[hidden] { display: none; } + #latency-hud { + position: fixed; top: 16px; right: 16px; z-index: 30; pointer-events: none; + padding: 10px 14px; border-radius: 8px; background: #000c; color: #ffd400; + font: 12px/1.6 var(--mono); white-space: pre; + } + #latency-hud .latency-hint { color: #fff; font-family: system-ui, sans-serif; white-space: normal; max-width: 46ch; margin-bottom: 6px; } + /* As the setup dialogs: at one table pixel per screen pixel, 12px is about 4mm. */ + body.present #latency-hud { zoom: 2; } + /* ---- settings ---- */ #settings { border: 1px solid var(--line); border-radius: 10px; padding: 0; diff --git a/scripts/smoke-desktop.mjs b/scripts/smoke-desktop.mjs index 68f253f..b67826e 100644 --- a/scripts/smoke-desktop.mjs +++ b/scripts/smoke-desktop.mjs @@ -670,6 +670,46 @@ try { "document.getElementById('enroll').close(); document.getElementById('calibrate').close(); return 1", ) + // Table > Latency Check: a puck slides, is lost for one frame and comes back + // under a new session. The readout must see the tracker, Planchette's own + // delay, the moving update rate, and the dropout. + await inMain("BrowserWindow.getAllWindows()[0].webContents.send('app:latency'); return 1") + for (let i = 0; i < 12; i++) { + objs[0].x += 0.01 + await sender.frame(objs, curs) + await sleep(40) + } + await sender.frame(objs.slice(1), curs) + await sleep(40) + objs[0].sid = 15 + await pump(3) + await sleep(1100) // one status poll, so packets/s is filled in + const latency = await evaluate(` + const hud = document.getElementById('latency-hud'); + const ruler = document.getElementById('latency-ruler'); + return { text: hud?.innerText ?? '', shown: hud ? !hud.hidden : false, ruler: ruler ? !ruler.hidden : false }; + `) + check( + 'latency: the check opens over the interface', + latency?.shown && latency.ruler && latency.text.includes('Latency check'), + JSON.stringify(latency), + ) + check( + 'latency: tracker rate, Planchette delay and moving updates are measured', + /\d+ packets\/s/.test(latency?.text ?? '') && + /Planchette\s+\d+ ms, max \d+ ms/.test(latency?.text ?? '') && + /While moving\s+\d+ updates\/s/.test(latency?.text ?? ''), + latency?.text, + ) + check( + 'latency: a puck lost and found again is counted', + /Lost and found\s+1, longest \d+ ms/.test(latency?.text ?? ''), + latency?.text, + ) + await inMain("BrowserWindow.getAllWindows()[0].webContents.send('app:latency'); return 1") + const closed = await evaluate("return document.getElementById('latency-hud').hidden") + check('latency: the same command closes it', closed === true) + // The tracker goes silent: everything must leave rather than haunt the table. await sleep(3000) const silent = await tableState() diff --git a/src/host/appsource.ts b/src/host/appsource.ts index 530fd72..fa86c6b 100644 --- a/src/host/appsource.ts +++ b/src/host/appsource.ts @@ -43,6 +43,7 @@ export interface DesktopBridge { onPicker(cb: () => void): void onEnroll(cb: () => void): void onCalibrate(cb: () => void): void + onLatency(cb: () => void): void onAppsChanged(cb: (appId: string | null) => void): void onReloadApp(cb: () => void): void onChooseWorkspace(cb: () => void): void diff --git a/src/host/latency.ts b/src/host/latency.ts new file mode 100644 index 0000000..f2f0202 --- /dev/null +++ b/src/host/latency.ts @@ -0,0 +1,348 @@ +import type { Puck, Touch } from '../sdk/types' +import type { TableModel } from './model' +import type { TuioFrame, TuioStatus } from './tuio' + +/** + * Table > Latency Check: what it takes to say where lag on a real table comes from. + * + * Lag between a hand and what the table shows is the sum of four delays, and + * only one of them is Planchette's: + * + * tracker -> Planchette -> the interface -> the display + * + * Two things are shown, over whatever interface is running: + * + * - A ring exactly where each puck and finger is reported, with a ruler ahead + * of it along the direction of travel, ticked at 50, 100, 150 and 200 ms at + * the current speed. Slide a puck steadily and the physical puck sits at + * the tick that is the whole delay, end to end. Software alone cannot + * measure that, because it cannot see the puck; a person, or a slow-motion + * video, can. + * - Numbers that split it up: the host's frame rate (an interface shares the + * renderer's thread, so a heavy one shows up here), how often the tracker + * sends, how long Planchette holds a frame, how often a moving puck is + * updated, and how often a puck is lost and found again. + * + * Counts start when the check is opened. Close and reopen it to start over. + */ + +/** Below this a contact is resting, and its update rate says nothing about motion. */ +const MOVING_MM_S = 60 +const TICKS_MS = [50, 100, 150, 200] +/** A puck back within this long of leaving, with the same marker, was lost rather than lifted. */ +const DROPOUT_MS = 1000 +/** Rolling window for rates and medians. */ +const WINDOW_MS = 2000 +/** A frame this long means at least one missed refresh at 60 Hz. */ +const LONG_FRAME_MS = 25 +const VELOCITY_SMOOTHING = 0.5 + +/** The main process stamps each tracker frame as it arrives (electron/main.js). */ +type StampedFrame = TuioFrame & { t?: number } + +export interface LatencyBridge { + onTuioFrame(cb: (frame: StampedFrame) => void): void + tuioStatus(): Promise +} + +interface Motion { + mmX: number + mmY: number + at: number + /** mm per ms. */ + vx: number + vy: number +} + +interface Sample { + at: number + value: number +} + +export interface LatencyCheck { + readonly isOpen: boolean + open(): void + close(): void + toggle(): void + /** The readout as text, for the smoke test and for anyone copying it out. */ + readout(): string +} + +export function installLatencyCheck(opts: { + surfaceEl: HTMLElement + model: TableModel + bridge: LatencyBridge | null +}): LatencyCheck { + const { surfaceEl, model, bridge } = opts + + const canvas = document.createElement('canvas') + canvas.id = 'latency-ruler' + canvas.hidden = true + surfaceEl.appendChild(canvas) + const ctx = canvas.getContext('2d')! + + const hud = document.createElement('div') + hud.id = 'latency-hud' + hud.hidden = true + document.body.appendChild(hud) + + let open = false + let raf = 0 + let poll = 0 + + // Everything below is reset by open(). + const motion = new Map() + let frameTimes: Sample[] = [] + let delays: Sample[] = [] + let updateGaps: Sample[] = [] + let longFrames = 0 + let longestGap = 0 + let dropouts = 0 + let longestDropout = 0 + let packetsPerSec: number | null = null + let lastFrameAt = 0 + /** markerId -> when its last puck left, for telling a dropout from a lift. */ + const leftAt = new Map() + + const key = (kind: 'p' | 't', id: number) => `${kind}${id}` + + function track(k: string, mmX: number, mmY: number): void { + const now = performance.now() + const m = motion.get(k) + if (!m) { + motion.set(k, { mmX, mmY, at: now, vx: 0, vy: 0 }) + return + } + const dt = now - m.at + if (dt <= 0) return + const vx = (mmX - m.mmX) / dt + const vy = (mmY - m.mmY) / dt + m.vx += (vx - m.vx) * VELOCITY_SMOOTHING + m.vy += (vy - m.vy) * VELOCITY_SMOOTHING + // Only gaps while moving say anything about the tracker: a resting puck is + // allowed to go quiet. + if (Math.hypot(m.vx, m.vy) * 1000 > MOVING_MM_S) { + updateGaps.push({ at: now, value: dt }) + if (dt > longestGap) longestGap = dt + } + m.mmX = mmX + m.mmY = mmY + m.at = now + } + + model.subscribe((name, data) => { + if (!open) return + const now = performance.now() + switch (name) { + case 'puckadd': { + const p = data as Puck + const left = leftAt.get(p.markerId) + if (left !== undefined && now - left < DROPOUT_MS) { + dropouts++ + longestDropout = Math.max(longestDropout, now - left) + leftAt.delete(p.markerId) + } + track(key('p', p.id), p.mmX, p.mmY) + break + } + case 'puckmove': { + const p = data as Puck + track(key('p', p.id), p.mmX, p.mmY) + break + } + case 'puckremove': { + const p = data as Puck + motion.delete(key('p', p.id)) + leftAt.set(p.markerId, now) + break + } + case 'touchstart': + case 'touchmove': { + const t = data as Touch + track(key('t', t.id), t.mmX, t.mmY) + break + } + case 'touchend': + motion.delete(key('t', (data as Touch).id)) + break + } + }) + + bridge?.onTuioFrame((f) => { + if (!open || typeof f.t !== 'number') return + delays.push({ at: performance.now(), value: Math.max(0, Date.now() - f.t) }) + }) + + /* ---------------- drawing ---------------- */ + + function draw(now: number): void { + const s = model.getSurface() + if (canvas.width !== s.widthPx || canvas.height !== s.heightPx) { + canvas.width = s.widthPx + canvas.height = s.heightPx + } + const k = s.pxPerMm + ctx.clearRect(0, 0, canvas.width, canvas.height) + ctx.lineCap = 'round' + ctx.font = `600 ${Math.round(5 * k)}px system-ui, sans-serif` + ctx.textAlign = 'center' + ctx.textBaseline = 'middle' + + const contacts: Array<{ k: string; x: number; y: number; r: number }> = [] + for (const [id, p] of model.rawPucks()) { + contacts.push({ k: key('p', id), x: p.x * s.widthMm, y: p.y * s.heightMm, r: s.puckDiameterMm / 2 }) + } + for (const [id, t] of model.rawTouches()) { + contacts.push({ k: key('t', id), x: t.x * s.widthMm, y: t.y * s.heightMm, r: t.radiusMm }) + } + + for (const c of contacts) { + ctx.strokeStyle = '#ffd400' + ctx.lineWidth = 1.2 * k + ctx.beginPath() + ctx.arc(c.x * k, c.y * k, c.r * k, 0, Math.PI * 2) + ctx.stroke() + // A dot at the reported centre, to line up with the middle of the puck. + ctx.fillStyle = '#ffd400' + ctx.beginPath() + ctx.arc(c.x * k, c.y * k, 1.5 * k, 0, Math.PI * 2) + ctx.fill() + + const m = motion.get(c.k) + // A contact that has not been updated lately has stopped, whatever its last velocity said. + if (!m || now - m.at > 150) continue + const speed = Math.hypot(m.vx, m.vy) + if (speed * 1000 < MOVING_MM_S) continue + const ux = m.vx / speed + const uy = m.vy / speed + // Ticks are perpendicular to the direction of travel, ahead of the ring. + const far = speed * TICKS_MS[TICKS_MS.length - 1]! + ctx.strokeStyle = 'rgba(255, 212, 0, .55)' + ctx.lineWidth = 0.8 * k + ctx.beginPath() + ctx.moveTo(c.x * k, c.y * k) + ctx.lineTo((c.x + ux * far) * k, (c.y + uy * far) * k) + ctx.stroke() + for (const ms of TICKS_MS) { + const d = speed * ms + const tx = c.x + ux * d + const ty = c.y + uy * d + ctx.strokeStyle = '#ffd400' + ctx.lineWidth = 1 * k + ctx.beginPath() + ctx.moveTo((tx - uy * 6) * k, (ty + ux * 6) * k) + ctx.lineTo((tx + uy * 6) * k, (ty - ux * 6) * k) + ctx.stroke() + ctx.fillStyle = '#ffd400' + ctx.fillText(String(ms), (tx - uy * 11) * k, (ty + ux * 11) * k) + } + } + } + + /* ---------------- numbers ---------------- */ + + function trim(list: Sample[], now: number): Sample[] { + const from = now - WINDOW_MS + let i = 0 + while (i < list.length && list[i]!.at < from) i++ + return i ? list.slice(i) : list + } + + const median = (xs: number[]) => { + if (!xs.length) return null + const s = [...xs].sort((a, b) => a - b) + return s[Math.floor(s.length / 2)]! + } + const ms = (v: number | null) => (v === null ? 'n/a' : `${Math.round(v)} ms`) + + function lines(): string[] { + const now = performance.now() + frameTimes = trim(frameTimes, now) + delays = trim(delays, now) + updateGaps = trim(updateGaps, now) + + const frames = frameTimes.map((f) => f.value) + const fps = frames.length ? Math.round(1000 / (frames.reduce((a, b) => a + b, 0) / frames.length)) : null + const worst = frames.length ? Math.max(...frames) : null + const gap = median(updateGaps.map((g) => g.value)) + const delay = median(delays.map((d) => d.value)) + const maxDelay = delays.length ? Math.max(...delays.map((d) => d.value)) : null + + return [ + `Frame rate ${fps ?? 'n/a'} fps, worst frame ${ms(worst)}, ${longFrames} long since opened`, + `Tracker ${packetsPerSec === null ? 'not connected' : `${packetsPerSec} packets/s`}`, + `Planchette ${delay === null ? 'n/a' : `${ms(delay)}, max ${ms(maxDelay)}`}`, + `While moving ${gap === null ? 'n/a' : `${Math.round(1000 / gap)} updates/s`}, longest gap ${ms(longestGap || null)}`, + `Lost and found ${dropouts}${dropouts ? `, longest ${ms(longestDropout)}` : ''}`, + ] + } + + function render(): void { + const text = lines() + hud.replaceChildren( + ...[ + 'Latency check. Slide a puck steadily: where the real puck sits on the ruler is the whole delay.', + ...text, + ].map((t, i) => { + const row = document.createElement('div') + row.textContent = t + if (i === 0) row.className = 'latency-hint' + return row + }), + ) + } + + function loop(now: number): void { + if (!open) return + if (lastFrameAt) { + const dt = now - lastFrameAt + frameTimes.push({ at: now, value: dt }) + if (dt > LONG_FRAME_MS) longFrames++ + } + lastFrameAt = now + draw(now) + raf = requestAnimationFrame(loop) + } + + async function refreshStatus(): Promise { + const s = bridge ? await bridge.tuioStatus().catch(() => null) : null + packetsPerSec = s && s.state === 'listening' ? s.packetsPerSec : null + if (open) render() + } + + const api: LatencyCheck = { + get isOpen() { + return open + }, + open() { + if (open) return + open = true + motion.clear() + leftAt.clear() + frameTimes = [] + delays = [] + updateGaps = [] + longFrames = longestGap = dropouts = longestDropout = 0 + lastFrameAt = 0 + canvas.hidden = hud.hidden = false + document.body.classList.add('latency') + void refreshStatus() + poll = window.setInterval(() => void refreshStatus(), 500) + raf = requestAnimationFrame(loop) + }, + close() { + if (!open) return + open = false + cancelAnimationFrame(raf) + clearInterval(poll) + canvas.hidden = hud.hidden = true + document.body.classList.remove('latency') + }, + toggle() { + if (open) api.close() + else api.open() + }, + readout: () => lines().join('\n'), + } + return api +} diff --git a/src/host/main.ts b/src/host/main.ts index 3071e0a..ccaa717 100644 --- a/src/host/main.ts +++ b/src/host/main.ts @@ -9,6 +9,7 @@ import { TableModel } from './model' import { showUpgradeNotice } from './notice' import { setupTableSettings } from './table-ui' import { installPresent } from './present' +import { installLatencyCheck } from './latency' import { installTuio } from './tuio' import { Overlay } from './overlay' import { installSimApi } from './simapi' @@ -213,6 +214,13 @@ model.subscribe((name, data) => frame.sendEvent(name, data)) const tuioInput = window.planchette && !EMBED ? installTuio(model, window.planchette) : null if (inspector && tuioInput) inspector.tagFor = tuioInput.tagFor +// Table > Latency Check. Desktop only: the menu is how it opens, and the numbers +// worth having come from a tracker. +if (window.planchette && !EMBED) { + const latency = installLatencyCheck({ surfaceEl, model, bridge: window.planchette }) + window.planchette.onLatency(() => latency.toggle()) +} + // On the table, every puck and finger comes from the tracker. A mouse there is // an operator's, for the settings and setup dialogs, not a simulated hand. if (!PRESENT) {