From 525b9f9a41687d0bb21da5e35e6f08ee56302ff8 Mon Sep 17 00:00:00 2001 From: Collin Pendleton Date: Tue, 10 Nov 2026 13:42:37 -0600 Subject: [PATCH 1/2] fix: keep the beat in step with the music, and make tapping it reliable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The beat maps were right (checked on a real song against librosa: same tempo, beats on the onsets, the one on the kick), but every screen placed them late, by a varying amount: - The speaker's position reports were stamped when they reached the server, so everyone lagged by the report's trip, more when it queued behind the last one. Reports now say when they were read (`at`), and the server moves the position on by up to 2 s. - Clock sync was one sample from the socket's hello, with anything under 250 ms taken as zero. A new GET /time lets each client time a few round trips and keep the quickest. Tap tempo in the beat lab: - Taps are timed on performance.now(). The room's position jumps as the server corrects it, which reset taps part way or skewed them. - A skipped beat is counted and a double tap dropped, instead of either wrecking the fit. Four taps before it applies, as the lab says. - At the analysed tempo, taps (and the ±20 ms / Move 1 buttons) shift the song's own beats into place rather than replacing them with a fixed grid, so a live band's drift is still followed. --- api/openapi.yaml | 36 ++++++ server/internal/httpapi/api.gen.go | 77 +++++++++++++ server/internal/httpapi/playback.go | 3 + server/internal/httpapi/server.go | 6 + server/internal/playback/playback.go | 12 ++ server/internal/playback/playback_test.go | 21 ++++ web/src/api/schema.gen.ts | 58 ++++++++++ web/src/components/shell/beat-lab.tsx | 2 +- web/src/lib/beat.ts | 128 ++++++++++++++-------- web/src/lib/clock.test.ts | 15 ++- web/src/lib/clock.ts | 51 ++++++++- web/src/lib/room-socket.ts | 3 +- web/src/lib/speaker.ts | 3 +- web/src/lib/tap-tempo.test.ts | 88 +++++++++++++++ web/src/lib/tap-tempo.ts | 92 ++++++++++++++++ 15 files changed, 542 insertions(+), 53 deletions(-) create mode 100644 web/src/lib/tap-tempo.test.ts create mode 100644 web/src/lib/tap-tempo.ts diff --git a/api/openapi.yaml b/api/openapi.yaml index c267190..b1330d1 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -28,6 +28,25 @@ paths: schema: $ref: "#/components/schemas/Health" + /time: + get: + operationId: getServerTime + summary: The server's clock + description: | + For clients to measure how far their clock is from the server's: a + few requests, keeping the quickest round trip. Playback positions + are stamped with server time, so every screen in a room keeps the + same beat only if they agree on it. + tags: [system] + security: [] + responses: + "200": + description: The time as the server answered + content: + application/json: + schema: + $ref: "#/components/schemas/ServerTime" + # --- Signup and sign-in --------------------------------------------------- /invites/{code}: @@ -5108,6 +5127,15 @@ components: type: string example: 0.1.0 + ServerTime: + type: object + required: [ms] + properties: + ms: + type: integer + format: int64 + description: The server's clock, in ms since the epoch. + Error: type: object required: [code, message] @@ -8900,6 +8928,14 @@ components: type: integer format: int64 minimum: 0 + at: + type: integer + format: int64 + description: | + When `positionMs` was read, in ms since the epoch on the server's + clock (see `/time`). The server moves the position on by the time + the report took to arrive; without it, the report counts as read + on arrival. error: type: string maxLength: 500 diff --git a/server/internal/httpapi/api.gen.go b/server/internal/httpapi/api.gen.go index 609692a..cf2913f 100644 --- a/server/internal/httpapi/api.gen.go +++ b/server/internal/httpapi/api.gen.go @@ -3925,6 +3925,11 @@ type Player struct { // PlayerReport defines model for PlayerReport. type PlayerReport struct { + // At When `positionMs` was read, in ms since the epoch on the server's + // clock (see `/time`). The server moves the position on by the time + // the report took to arrive; without it, the report counts as read + // on arrival. + At *int64 `json:"at,omitempty"` DeviceId string `json:"deviceId"` // Error What went wrong, for `error`. @@ -5035,6 +5040,12 @@ type ServerSettingsUpdate struct { InviteExpiryHours *int `json:"inviteExpiryHours,omitempty"` } +// ServerTime defines model for ServerTime. +type ServerTime struct { + // Ms The server's clock, in ms since the epoch. + Ms int64 `json:"ms"` +} + // ServiceLink defines model for ServiceLink. type ServiceLink struct { // AccountLabel Example: alice on music.example.com @@ -6555,6 +6566,9 @@ type ServerInterface interface { // UpdateServerSettings Change the server's settings (admin) // (PATCH /server-settings) UpdateServerSettings(w http.ResponseWriter, r *http.Request) + // GetServerTime The server's clock + // (GET /time) + GetServerTime(w http.ResponseWriter, r *http.Request) // ListUserAudit Who changed whose account, and when (admin) // (GET /user-audit) ListUserAudit(w http.ResponseWriter, r *http.Request) @@ -12340,6 +12354,20 @@ func (siw *ServerInterfaceWrapper) UpdateServerSettings(w http.ResponseWriter, r handler.ServeHTTP(w, r) } +// GetServerTime operation middleware +func (siw *ServerInterfaceWrapper) GetServerTime(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetServerTime(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + // ListUserAudit operation middleware func (siw *ServerInterfaceWrapper) ListUserAudit(w http.ResponseWriter, r *http.Request) { @@ -12619,6 +12647,7 @@ func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.H } m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/healthz", wrapper.GetHealth) + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/time", wrapper.GetServerTime) m.HandleFunc(http.MethodDelete+" "+options.BaseURL+"/invites/{code}", wrapper.DeleteInvite) m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/invites/{code}", wrapper.GetInvite) m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/auth/signup", wrapper.Signup) @@ -20679,6 +20708,27 @@ func (response UpdateServerSettingsdefaultJSONResponse) VisitUpdateServerSetting return err } +type GetServerTimeRequestObject struct { +} + +type GetServerTimeResponseObject interface { + VisitGetServerTimeResponse(w http.ResponseWriter) error +} + +type GetServerTime200JSONResponse ServerTime + +func (response GetServerTime200JSONResponse) VisitGetServerTimeResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + type ListUserAuditRequestObject struct { } @@ -21549,6 +21599,9 @@ type StrictServerInterface interface { // UpdateServerSettings Change the server's settings (admin) // (PATCH /server-settings) UpdateServerSettings(ctx context.Context, request UpdateServerSettingsRequestObject) (UpdateServerSettingsResponseObject, error) + // GetServerTime The server's clock + // (GET /time) + GetServerTime(ctx context.Context, request GetServerTimeRequestObject) (GetServerTimeResponseObject, error) // ListUserAudit Who changed whose account, and when (admin) // (GET /user-audit) ListUserAudit(ctx context.Context, request ListUserAuditRequestObject) (ListUserAuditResponseObject, error) @@ -27172,6 +27225,30 @@ func (sh *strictHandler) UpdateServerSettings(w http.ResponseWriter, r *http.Req } } +// GetServerTime operation middleware +func (sh *strictHandler) GetServerTime(w http.ResponseWriter, r *http.Request) { + var request GetServerTimeRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetServerTime(ctx, request.(GetServerTimeRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetServerTime") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetServerTimeResponseObject); ok { + if err := validResponse.VisitGetServerTimeResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + // ListUserAudit operation middleware func (sh *strictHandler) ListUserAudit(w http.ResponseWriter, r *http.Request) { var request ListUserAuditRequestObject diff --git a/server/internal/httpapi/playback.go b/server/internal/httpapi/playback.go index fc7fa84..0180f69 100644 --- a/server/internal/httpapi/playback.go +++ b/server/internal/httpapi/playback.go @@ -104,6 +104,9 @@ func (s *Server) ReportPlayback(ctx context.Context, req ReportPlaybackRequestOb if req.Body.Error != nil { rep.Error = *req.Body.Error } + if req.Body.At != nil { + rep.At = time.UnixMilli(*req.Body.At) + } np, err := s.Playback.Report(ctx, req.RoomId, userID, rep) if err != nil { return nil, err diff --git a/server/internal/httpapi/server.go b/server/internal/httpapi/server.go index b6108a7..f4ac94e 100644 --- a/server/internal/httpapi/server.go +++ b/server/internal/httpapi/server.go @@ -164,6 +164,11 @@ func (s *Server) GetHealth(context.Context, GetHealthRequestObject) (GetHealthRe return GetHealth200JSONResponse{Status: HealthStatusOk, Version: s.Version}, nil } +// GetServerTime tells a client the server's clock, to set its own by. +func (s *Server) GetServerTime(context.Context, GetServerTimeRequestObject) (GetServerTimeResponseObject, error) { + return GetServerTime200JSONResponse{Ms: time.Now().UnixMilli()}, nil +} + // --- Request context ---------------------------------------------------------- // publicOps can be called without a session. Everything else requires one. @@ -171,6 +176,7 @@ func (s *Server) GetHealth(context.Context, GetHealthRequestObject) (GetHealthRe // TestPublicOpsMatchSpec keeps this in sync with `security: []` in the spec. var publicOps = map[string]bool{ "GetHealth": true, + "GetServerTime": true, "GetInvite": true, "Signup": true, "BeginPasskeySignup": true, diff --git a/server/internal/playback/playback.go b/server/internal/playback/playback.go index 3c53450..53ff708 100644 --- a/server/internal/playback/playback.go +++ b/server/internal/playback/playback.go @@ -67,6 +67,9 @@ const ( StatePaused = "paused" ) +// maxReportAge bounds how far a speaker's report is moved on for its trip. +const maxReportAge = 2 * time.Second + // Sessions opens provider sessions for links. It's links.Service in // production. Songs play through the link of whoever queued them. type Sessions interface { @@ -985,6 +988,9 @@ type Report struct { ItemID string Event string Position time.Duration + // At is when Position was read, on the server's clock; zero if the + // speaker didn't say. The position is moved on by the report's trip. + At time.Time // Error describes an EventError, for the notice. Error string } @@ -1004,6 +1010,12 @@ func (e *Engine) Report(ctx context.Context, roomID, userID string, rep Report) } now := e.cfg.Now() p.LastSeen = now + // A report takes a moment to arrive, longer when the one before it is + // slow: left as it is, everyone's beat would lag the speaker's by that. + // Bounded, in case the speaker's clock is off after all. + if !rep.At.IsZero() && rep.Event != EventPaused { + rep.Position += min(max(now.Sub(rep.At), 0), maxReportAge) + } stale := r.np.Item == nil || r.np.Item.ID != rep.ItemID || r.np.Driver != string(provider.PlaybackStream) // Progress is every few seconds; only a stale one says something's off // (the speaker is on another song than the room). diff --git a/server/internal/playback/playback_test.go b/server/internal/playback/playback_test.go index 23c6a2f..fcd32c7 100644 --- a/server/internal/playback/playback_test.go +++ b/server/internal/playback/playback_test.go @@ -268,6 +268,27 @@ func TestStreamPlayback(t *testing.T) { if np = e.report(e.alice, "phone", playback.EventProgress, 3500*time.Millisecond); np.Position != 3500*time.Millisecond { t.Errorf("after progress report: %v", np.Position) } + // A report read 80 ms before it arrived counts from when it was read… + read := func(pos, ago time.Duration) rooms.NowPlaying { + t.Helper() + np, err := e.p.Report(ctx, e.room.ID, e.alice.ID, playback.Report{ + DeviceID: "phone", ItemID: e.np().Item.ID, Event: playback.EventProgress, Position: pos, At: e.clock().Add(-ago), + }) + if err != nil { + t.Fatal(err) + } + return np + } + if np = read(3500*time.Millisecond, 80*time.Millisecond); np.Position != 3580*time.Millisecond { + t.Errorf("report read 80ms ago: %v", np.Position) + } + // …but a speaker clock that's way off moves it by 2 s at most, and never back. + if np = read(3500*time.Millisecond, time.Minute); np.Position != 5500*time.Millisecond { + t.Errorf("report read a minute ago: %v", np.Position) + } + if np = read(3500*time.Millisecond, -time.Second); np.Position != 3500*time.Millisecond { + t.Errorf("report from the future: %v", np.Position) + } // Pause, seek and play each bump the revision for the speaker. if np, _ = e.command(e.bob, playback.Command{Action: playback.ActionPause}); np.State != playback.StatePaused || np.Revision != rev+1 { diff --git a/web/src/api/schema.gen.ts b/web/src/api/schema.gen.ts index 01598e3..f651204 100644 --- a/web/src/api/schema.gen.ts +++ b/web/src/api/schema.gen.ts @@ -21,6 +21,29 @@ export interface paths { patch?: never; trace?: never; }; + "/time": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The server's clock + * @description For clients to measure how far their clock is from the server's: a + * few requests, keeping the quickest round trip. Playback positions + * are stamped with server time, so every screen in a room keeps the + * same beat only if they agree on it. + */ + get: operations["getServerTime"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/invites/{code}": { parameters: { query?: never; @@ -3824,6 +3847,13 @@ export interface components { /** @example 0.1.0 */ version: string; }; + ServerTime: { + /** + * Format: int64 + * @description The server's clock, in ms since the epoch. + */ + ms: number; + }; Error: { /** * @description Stable, machine-readable error code. @@ -6062,6 +6092,14 @@ export interface components { event: "playing" | "progress" | "paused" | "ended" | "error"; /** Format: int64 */ positionMs: number; + /** + * Format: int64 + * @description When `positionMs` was read, in ms since the epoch on the server's + * clock (see `/time`). The server moves the position on by the time + * the report took to arrive; without it, the report counts as read + * on arrival. + */ + at?: number; /** @description What went wrong, for `error`. */ error?: string; }; @@ -6714,6 +6752,26 @@ export interface operations { }; }; }; + getServerTime: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The time as the server answered */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ServerTime"]; + }; + }; + }; + }; getInvite: { parameters: { query?: never; diff --git a/web/src/components/shell/beat-lab.tsx b/web/src/components/shell/beat-lab.tsx index 76a5489..230fc67 100644 --- a/web/src/components/shell/beat-lab.tsx +++ b/web/src/components/shell/beat-lab.tsx @@ -279,7 +279,7 @@ function Beat() { setTaps(tap() ?? 0) }} > - Tap on the beat {taps > 0 && taps < 3 ? `(${taps})` : ''} + Tap on the beat {taps > 0 && taps < 4 ? `(${taps})` : ''}

Start on a “one” and tap at least 4 times. Fixes this song on this device. diff --git a/web/src/lib/beat.ts b/web/src/lib/beat.ts index bb68531..b710ec2 100644 --- a/web/src/lib/beat.ts +++ b/web/src/lib/beat.ts @@ -3,7 +3,8 @@ // the song without re-rendering anything. // // Where the beat comes from, first match wins: -// 1. a grid tapped in the beat lab, for a song the analysis got wrong; +// 1. a fix from the beat lab: the song's beats moved into place, or a +// grid of its own for a song whose tempo the analysis got wrong; // 2. the song's beat map from the server (lib/beat-map.ts); // 3. the default tempo, while the map loads or for songs without one: // in time, but not in phase. @@ -24,6 +25,7 @@ import { beatAt, loudnessAt, sectionEnergy, spectrumAt, type BeatMap } from './beat-map' import { positionAt, type NowPlaying } from './now-playing' import { createStore } from './store' +import { alignToMap, fitTaps, mod4 } from './tap-tempo' export type BeatLevel = 'off' | 'subtle' @@ -135,8 +137,13 @@ export const beatSource = createStore<{ np: NowPlaying | null; map: BeatMap | nu /** A song's beat grid: its tempo and the position of one downbeat, in ms. */ export type Grid = { bpm: number; anchorMs: number } -/** Grids tapped in the beat lab, by song. They beat the song's map. */ -const tapped = new Map() +/** + * Fixes made in the beat lab, by song. A shift keeps the song's analysed + * beats and moves them (later by offsetMs, the bar starting barShift beats + * on); a grid replaces them. + */ +type Fix = { kind: 'shift'; offsetMs: number; barShift: number } | { kind: 'grid'; grid: Grid } +const fixes = new Map() export const gridVersion = createStore(0) function keyOf(np: NowPlaying) { @@ -168,54 +175,66 @@ export type BeatOrigin = 'tapped' | 'analysed' | 'steady' | 'default' export function currentBeat(): Grid & { origin: BeatOrigin } { const c = clock() - const own = c && tapped.get(c.key) - if (own) return { ...own, origin: 'tapped' } + const fix = c && fixes.get(c.key) + if (fix?.kind === 'grid') return { ...fix.grid, origin: 'tapped' } const map = c && mapFor(c.key) - if (map && map.bpm > 0) return { bpm: map.bpm, anchorMs: map.beats[map.downbeat] ?? 0, origin: 'analysed' } + if (map && map.bpm > 0) { + const anchorMs = map.beats[map.downbeat] ?? 0 + if (!fix) return { bpm: map.bpm, anchorMs, origin: 'analysed' } + return { bpm: map.bpm, anchorMs: anchorMs + fix.offsetMs + (fix.barShift * 60000) / map.bpm, origin: 'tapped' } + } if (map) return { bpm: 0, anchorMs: 0, origin: 'steady' } return { bpm: DEFAULT_BPM, anchorMs: 0, origin: 'default' } } -function setGrid(g: Grid) { +function setFix(fix: Fix) { const c = clock() if (!c) return - tapped.set(c.key, { bpm: Math.min(220, Math.max(50, g.bpm)), anchorMs: g.anchorMs }) + fixes.set( + c.key, + fix.kind === 'grid' ? { kind: 'grid', grid: { bpm: Math.min(220, Math.max(50, fix.grid.bpm)), anchorMs: fix.grid.anchorMs } } : fix, + ) gridVersion.set((v) => v + 1) wake() } +/** The current song's fix, and whether its map can take a shift instead of a grid. */ +function fixable() { + const c = clock() + const fix = c ? fixes.get(c.key) : undefined + const map = c ? mapFor(c.key) : null + return { fix, shiftable: fix?.kind !== 'grid' && !!map && map.bpm > 0 } +} + // --- Tap tempo --------------------------------------------------------------- -let taps: number[] = [] +/** Taps by performance.now(): a steady clock, unlike the room's position, which jumps as the server corrects it. */ +let taps: { key: string; at: number }[] = [] /** - * A tap on the beat. Start on a "one": a straight line through the taps - * gives the tempo, and the first tap becomes a downbeat. + * A tap on the beat. Start on a "one". From the fourth tap, the taps fix + * the song's beat: at the analysed tempo they just move its beats into + * place; at another tempo they make a grid of their own. Returns how many + * taps so far. */ export function tap() { const c = clock() - if (!c) return + if (!c?.playing) return + const now = performance.now() const last = taps.at(-1) - if (last === undefined || c.pos - last > 2000 || c.pos < last) taps = [] - taps.push(c.pos) - taps = taps.slice(-12) - if (taps.length < 3) return taps.length - // Least squares: tap i lands at anchor + i·period. - const n = taps.length - const mi = (n - 1) / 2 - const mt = taps.reduce((a, b) => a + b, 0) / n - let num = 0 - let den = 0 - taps.forEach((t, i) => { - num += (i - mi) * (t - mt) - den += (i - mi) ** 2 - }) - const period = num / den - // The first tap is beat 0; move the anchor to the bar of the last one. - const first = mt - mi * period - const bars = Math.floor((n - 1) / 4) - setGrid({ bpm: 60000 / period, anchorMs: first + bars * 4 * period }) - return n + if (!last || last.key !== c.key || now - last.at > 2500) taps = [] + taps.push({ key: c.key, at: now }) + taps = taps.slice(-16) + if (taps.length < 4) return taps.length + // Every tap's song position from this one reading of the clock. + const times = taps.map((t) => c.pos - (now - t.at)) + const fit = fitTaps(times) + if (!fit) return taps.length + const map = mapFor(c.key) + const shift = map ? alignToMap(map, times, fit.period) : null + if (shift) setFix({ kind: 'shift', ...shift }) + else setFix({ kind: 'grid', grid: { bpm: 60000 / fit.period, anchorMs: fit.firstMs } }) + return taps.length } /** The current beat as a grid to adjust: tapped, analysed, or the default. */ @@ -225,33 +244,45 @@ function adjustable(): Grid { } export function nudge(ms: number) { + const { fix, shiftable } = fixable() + if (shiftable) { + const s = fix?.kind === 'shift' ? fix : { offsetMs: 0, barShift: 0 } + setFix({ kind: 'shift', offsetMs: s.offsetMs + ms, barShift: s.barShift }) + return + } const g = adjustable() - setGrid({ ...g, anchorMs: g.anchorMs + ms }) + setFix({ kind: 'grid', grid: { ...g, anchorMs: g.anchorMs + ms } }) } export function scaleTempo(factor: number) { const g = adjustable() - setGrid({ ...g, bpm: g.bpm * factor }) + setFix({ kind: 'grid', grid: { ...g, bpm: g.bpm * factor } }) } /** Moves the "one" along by a beat, for a grid that starts its bars in the wrong place. */ export function shiftDownbeat() { + const { fix, shiftable } = fixable() + if (shiftable) { + const s = fix?.kind === 'shift' ? fix : { offsetMs: 0, barShift: 0 } + setFix({ kind: 'shift', offsetMs: s.offsetMs, barShift: mod4(s.barShift + 1) }) + return + } const g = adjustable() - setGrid({ ...g, anchorMs: g.anchorMs + 60000 / g.bpm }) + setFix({ kind: 'grid', grid: { ...g, anchorMs: g.anchorMs + 60000 / g.bpm } }) } -/** Forgets the song's tapped grid, back to its beat map. */ +/** Forgets the song's fix, back to its beat map. */ export function resetGrid() { const c = clock() if (!c) return - tapped.delete(c.key) + fixes.delete(c.key) taps = [] gridVersion.set((v) => v + 1) } // --- Delay calibration ------------------------------------------------------- -let heard: number[] = [] +let heard: { key: string; at: number }[] = [] /** * A tap on the beat as it's heard here, to work out how late this @@ -265,12 +296,14 @@ export function calibrateTap(): number | null { const map = np && !np.paused ? mapFor(keyOf(np)) : null if (!np || !map || map.bpm <= 0) return null const pos = positionAt(np, Date.now()) + const now = performance.now() + const key = keyOf(np) const last = heard.at(-1) - if (last === undefined || pos - last > 2000 || pos < last) heard = [] - heard.push(pos) + if (!last || last.key !== key || now - last.at > 2500) heard = [] + heard.push({ key, at: now }) heard = heard.slice(-16) const lags = heard - .map((t) => beatAt(map, t)) + .map((t) => beatAt(map, pos - (now - t.at))) .filter((p) => p !== null) .map((p) => (p.into > p.period / 2 ? p.into - p.period : p.into)) .sort((a, b) => a - b) @@ -374,12 +407,17 @@ function wake() { /** Where pos falls in the song's beat, from whichever source applies. */ function place(key: string, pos: number): { index: number; into: number; period: number; bar: number } | null { - const own = tapped.get(key) + const fix = fixes.get(key) const map = mapFor(key) - if (!own && map) return map.bpm > 0 ? beatAt(map, pos) : null + if (fix?.kind !== 'grid' && map) { + if (map.bpm <= 0) return null + if (!fix) return beatAt(map, pos) + const p = beatAt(map, pos - fix.offsetMs) + return p && { ...p, bar: mod4(p.bar - fix.barShift) } + } // No guessing while the map is on its way: the guess would jump when it lands. - if (!own && mapPending(key)) return null - const { bpm, anchorMs } = own ?? { bpm: DEFAULT_BPM, anchorMs: 0 } + if (!fix && mapPending(key)) return null + const { bpm, anchorMs } = fix?.kind === 'grid' ? fix.grid : { bpm: DEFAULT_BPM, anchorMs: 0 } const period = 60000 / bpm const since = pos - anchorMs const n = Math.floor(since / period) diff --git a/web/src/lib/clock.test.ts b/web/src/lib/clock.test.ts index 622ac85..126b9c4 100644 --- a/web/src/lib/clock.test.ts +++ b/web/src/lib/clock.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it } from 'vitest' -import { serverNow, serverOffset, syncServerClock, toLocalTime } from './clock' +import { offsetFrom, serverNow, serverOffset, syncServerClock, toLocalTime } from './clock' describe('server clock', () => { afterEach(() => syncServerClock(new Date(1000).toISOString(), 1000)) @@ -16,6 +16,19 @@ describe('server clock', () => { expect(serverOffset()).toBe(0) }) + it('measures the offset from the quickest round trip', () => { + expect( + offsetFrom([ + // Slow, and the answer came early in it: misleading. + { sent: 1000, received: 1400, server: 1100 }, + // Quick: the server's 2120 was about our 2020. + { sent: 2000, received: 2040, server: 2120 }, + { sent: 3000, received: 3200, server: 3300 }, + ]), + ).toBe(100) + expect(offsetFrom([])).toBeNull() + }) + it('ignores garbage', () => { syncServerClock(new Date(10_000).toISOString(), 4_000) syncServerClock('not a time') diff --git a/web/src/lib/clock.ts b/web/src/lib/clock.ts index 5d24f5e..c3ab7c5 100644 --- a/web/src/lib/clock.ts +++ b/web/src/lib/clock.ts @@ -1,21 +1,64 @@ // The server's clock, as seen from here. Playback positions are stamped // with server time; a phone or TV whose clock is a few seconds off would -// otherwise show a different lyric line from everyone else. The room -// socket's hello carries the server's time, and this keeps the offset. +// otherwise show a different lyric line from everyone else, and a clock +// that's a tenth of a second off puts its beat visibly out of step. The +// room socket's hello gives a rough offset at once; measureServerClock +// then times a few round trips to /time for a close one. -/** Offsets smaller than this are network latency, not a wrong clock. */ +import { api } from '@/api/client' + +/** Offsets from the hello smaller than this are network latency, not a wrong clock. */ const NOISE_MS = 250 let offset = 0 +// Whether offset came from measured round trips, which the hello's rough one mustn't overwrite. +let measured = false /** Records the server's time, as a hello received at `receivedAt` gave it. */ export function syncServerClock(serverTime: string, receivedAt = Date.now()) { const t = Date.parse(serverTime) - if (!Number.isFinite(t)) return + if (!Number.isFinite(t) || measured) return const d = t - receivedAt offset = Math.abs(d) < NOISE_MS ? 0 : d } +/** One round trip: when it was sent and came back (our clock), and the server's time in between. */ +export type ClockSample = { sent: number; received: number; server: number } + +/** + * The offset the samples give: the quickest round trip's, which has the + * least room for the server's answer to sit anywhere but its middle. + */ +export function offsetFrom(samples: ClockSample[]): number | null { + const ok = samples.filter((s) => Number.isFinite(s.server) && s.received >= s.sent) + if (!ok.length) return null + const best = ok.reduce((a, b) => (b.received - b.sent < a.received - a.sent ? b : a)) + return Math.round(best.server - (best.sent + best.received) / 2) +} + +let measuring: Promise | null = null + +/** Measures the offset over a few round trips to the server. Safe to call often: one runs at a time. */ +export function measureServerClock(rounds = 5) { + measuring ??= (async () => { + const samples: ClockSample[] = [] + for (let i = 0; i < rounds; i++) { + const sent = Date.now() + const { data } = await api.GET('/time', { signal: AbortSignal.timeout(3000) }).catch(() => ({ data: undefined })) + const received = Date.now() + if (data) samples.push({ sent, received, server: data.ms }) + } + const o = offsetFrom(samples) + if (o !== null) { + offset = o + measured = true + } + })().finally(() => { + measuring = null + }) + return measuring +} + /** How far the server's clock is ahead of ours, in ms. */ export function serverOffset() { return offset diff --git a/web/src/lib/room-socket.ts b/web/src/lib/room-socket.ts index 6303607..68b940f 100644 --- a/web/src/lib/room-socket.ts +++ b/web/src/lib/room-socket.ts @@ -6,7 +6,7 @@ import { box, isBox, runDisplayCommand, type BoxInfo, type DisplayCommand } from import { deviceKind, devicesQuery, runDeviceCommand, type DeviceCommand } from './devices' import { chatQuery, dropChatMessage, putChatMessage, type ChatMessage } from './chat' import { meQuery } from './auth' -import { syncServerClock } from './clock' +import { measureServerClock, syncServerClock } from './clock' import { displayMeQuery, displaysQuery } from './displays' import { playRoundClips } from './game-clips' import { gameRoundQuery, gameScoresQuery, type GameRound, type GameScores } from './games' @@ -160,6 +160,7 @@ function handle(queryClient: QueryClient, roomId: string, ev: RoomEvent) { case 'hello': { const hello = ev.data as components['schemas']['RoomHello'] syncServerClock(hello.serverTime) + void measureServerClock() live.set({ roomId, status: 'live', members: hello.members }) // The games still up follow, one event each. queryClient.setQueryData(queueGamesQuery(roomId).queryKey, []) diff --git a/web/src/lib/speaker.ts b/web/src/lib/speaker.ts index 284fe2b..beb7790 100644 --- a/web/src/lib/speaker.ts +++ b/web/src/lib/speaker.ts @@ -753,7 +753,8 @@ class Speaker { const roomId = this.roomId if (!roomId || !item || this.mode !== 'speaker') return const positionMs = Math.round(item === this.curItem ? this.position() : 0) - const body = { deviceId: this.device, itemId: item.id, event, positionMs, error } + // When it was read: the report may wait behind the last one, and takes a moment to arrive. + const body = { deviceId: this.device, itemId: item.id, event, positionMs, at: Math.round(serverNow()), error } this.reports = this.reports .then(() => api.POST('/rooms/{roomId}/player/report', { params: { path: { roomId } }, body, signal: AbortSignal.timeout(REPORT_TIMEOUT) }), diff --git a/web/src/lib/tap-tempo.test.ts b/web/src/lib/tap-tempo.test.ts new file mode 100644 index 0000000..424d73e --- /dev/null +++ b/web/src/lib/tap-tempo.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' +import { beatAt, decode } from './beat-map' +import { alignToMap, fitTaps, mod4 } from './tap-tempo' + +// 120 BPM, a beat every 500 ms from 1 s; the first bar starts on the second beat (1500). +const map = decode({ + durationMs: 60_000, + bpm: 120, + confidence: 0.8, + beats: Array.from({ length: 110 }, (_, i) => 1000 + i * 500), + downbeat: 1, + sections: [{ startMs: 0, energy: 0.5 }], + frameRate: 2, + bandCount: 1, + bands: btoa(String.fromCharCode(0)), + loudness: btoa(String.fromCharCode(0)), + features: { energy: 0.5, brightness: 0.5, dynamics: 0.5 }, +}) + +// Wobbles a tap by up to ±15 ms, the way a thumb does. +const wobble = [7, -12, 3, 15, -6, -14, 9, 0, -3, 11] +const tapsAt = (first: number, period: number, n: number) => Array.from({ length: n }, (_, i) => first + i * period + wobble[i % 10]) + +describe('fitting taps', () => { + it('needs four taps', () => { + expect(fitTaps([0, 500, 1000])).toBeNull() + }) + + it('finds the tempo and the first beat', () => { + const fit = fitTaps(tapsAt(2000, 600, 8))! + expect(60000 / fit.period).toBeCloseTo(100, 0) + expect(Math.abs(fit.firstMs - 2000)).toBeLessThan(15) + }) + + it('counts a skipped beat rather than stretching the tempo', () => { + const t = tapsAt(0, 500, 8) + t.splice(4, 1) + const fit = fitTaps(t)! + expect(60000 / fit.period).toBeCloseTo(120, 0) + }) + + it('ignores a double tap', () => { + const t = tapsAt(0, 500, 8) + t.splice(3, 0, t[2] + 60) + const fit = fitTaps(t)! + expect(60000 / fit.period).toBeCloseTo(120, 0) + expect(Math.abs(fit.firstMs)).toBeLessThan(15) + }) +}) + +describe('aligning taps to the map', () => { + // Where the shifted map puts beat and bar for a position. + const placeAt = (pos: number, s: { offsetMs: number; barShift: number }) => { + const p = beatAt(map, pos - s.offsetMs)! + return { into: p.into, bar: mod4(p.bar - s.barShift) } + } + + it('moves the beats to the taps, and makes the first tap the one', () => { + // The real beat is 80 ms after the map's, and the user starts on map beat 4 (bar position 3). + const taps = tapsAt(1000 + 4 * 500 + 80, 500, 8) + const s = alignToMap(map, taps, fitTaps(taps)!.period)! + expect(s.offsetMs).toBeGreaterThan(70) + expect(s.offsetMs).toBeLessThan(90) + const at = placeAt(1000 + 4 * 500 + 80 + 30, s) + expect(Math.abs(at.into - 30)).toBeLessThan(15) + expect(at.bar).toBe(0) + }) + + it('handles a map that sits on the off-beat', () => { + const taps = tapsAt(1000 + 250, 500, 8) + const s = alignToMap(map, taps, fitTaps(taps)!.period)! + expect(Math.abs(Math.abs(s.offsetMs) - 250)).toBeLessThan(15) + const at = placeAt(1250 + 30, s) + expect(Math.abs(at.into - 30)).toBeLessThan(20) + expect(at.bar).toBe(0) + }) + + it('accepts taps on every other beat', () => { + const taps = tapsAt(3000 - 40, 1000, 6) + const s = alignToMap(map, taps, fitTaps(taps)!.period)! + expect(s.offsetMs).toBeCloseTo(-40, -1) + }) + + it('leaves a different tempo to a grid of its own', () => { + const taps = tapsAt(3000, 430, 8) + expect(alignToMap(map, taps, fitTaps(taps)!.period)).toBeNull() + }) +}) diff --git a/web/src/lib/tap-tempo.ts b/web/src/lib/tap-tempo.ts new file mode 100644 index 0000000..19a6670 --- /dev/null +++ b/web/src/lib/tap-tempo.ts @@ -0,0 +1,92 @@ +import { beatAt, type BeatMap } from './beat-map' + +// Tap tempo for the beat lab: turning a few taps on the beat into either a +// grid of its own, or a correction to the song's analysed beats. + +/** A straight line through the taps: the beat's length, and when beat 0 (the first tap) fell. */ +export type TapFit = { period: number; firstMs: number } + +/** + * Fits taps (song positions, ms, in order) to evenly spaced beats. People + * don't tap perfectly: a tap that comes a beat late counts the beat it + * skipped, and a double tap (two within half a beat) counts once. Null + * with fewer than four usable taps. + */ +export function fitTaps(times: number[]): TapFit | null { + if (times.length < 4) return null + const gaps = times.slice(1).map((t, i) => t - times[i]) + const typical = median(gaps) + if (!(typical > 0)) return null + // Drop double taps, then take the typical gap again without them. + const kept = [times[0]] + for (const t of times.slice(1)) if (t - kept[kept.length - 1] >= typical * 0.5) kept.push(t) + if (kept.length < 4) return null + const period0 = median(kept.slice(1).map((t, i) => t - kept[i])) + // Each tap's beat: the last one's, plus however many beats the gap spans. + const idx = [0] + for (let i = 1; i < kept.length; i++) idx.push(idx[i - 1] + Math.max(1, Math.round((kept[i] - kept[i - 1]) / period0))) + // Least squares: tap i lands at first + idx[i]·period. + const n = kept.length + const mi = idx.reduce((a, b) => a + b, 0) / n + const mt = kept.reduce((a, b) => a + b, 0) / n + let num = 0 + let den = 0 + kept.forEach((t, i) => { + num += (idx[i] - mi) * (t - mt) + den += (idx[i] - mi) ** 2 + }) + if (den === 0) return null + const period = num / den + if (!(period > 0)) return null + return { period, firstMs: mt - mi * period } +} + +/** How the taps move the song's analysed beats: later by offsetMs, and the bar starting barShift beats on. */ +export type MapShift = { offsetMs: number; barShift: number } + +/** + * When the taps keep the analysed tempo (or half of it, tapping every + * other beat), they only say where the beat really is. Keeps the map's own + * beats, which follow a live band's drift that one fixed grid can't, and + * works out how far they're off. The first tap is a "one". Null when the + * taps are at another tempo: the map's tempo is wrong, so a grid is better. + */ +export function alignToMap(map: BeatMap, times: number[], period: number): MapShift | null { + if (map.bpm <= 0 || times.length === 0) return null + const beats = (period * map.bpm) / 60000 + if (Math.abs(beats - 1) > 0.06 && Math.abs(beats - 2) > 0.12) return null + // Each tap's distance from its nearest beat, as a share of that beat. + const phases: number[] = [] + for (const t of times) { + const p = beatAt(map, t) + if (p) phases.push(p.into / p.period) + } + if (phases.length < 3) return null + // Phases wrap (0.95 and 0.05 are close), so centre them on their + // circular mean before taking the median, which ignores a stray tap. + const x = phases.reduce((a, f) => a + Math.cos(2 * Math.PI * f), 0) + const y = phases.reduce((a, f) => a + Math.sin(2 * Math.PI * f), 0) + const centre = Math.atan2(y, x) / (2 * Math.PI) + const wrap = (f: number) => f - Math.round(f) + const phase = centre + median(phases.map((f) => wrap(f - centre))) + const shifted = wrap(phase) + // In ms, at the tempo around the taps. + const near = beatAt(map, times[0]) + const offsetMs = shifted * (near?.period ?? 60000 / map.bpm) + // The map beat the first tap is on becomes the one. + const first = beatAt(map, times[0] - offsetMs) + if (!first) return { offsetMs, barShift: 0 } + const index = first.into > first.period / 2 ? first.index + 1 : first.index + return { offsetMs, barShift: mod4(index - map.downbeat) } +} + +export function mod4(n: number) { + return ((n % 4) + 4) % 4 +} + +function median(xs: number[]) { + if (xs.length === 0) return NaN + const s = [...xs].sort((a, b) => a - b) + const m = s.length >> 1 + return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2 +} From 99bfdb4d8e62ccd706a8a9764e77c470719578f1 Mon Sep 17 00:00:00 2001 From: Collin Pendleton Date: Tue, 10 Nov 2026 13:52:51 -0600 Subject: [PATCH 2/2] test: start the httpapi test clock at the real time It was fixed at 2026-10-05. Sessions last 30 days by that clock, but the test client's cookie jar runs on the real one, so from 2026-11-04 it dropped every session cookie and the signed-in tests failed. --- server/internal/httpapi/accounts_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/server/internal/httpapi/accounts_test.go b/server/internal/httpapi/accounts_test.go index c1f4545..22e03d9 100644 --- a/server/internal/httpapi/accounts_test.go +++ b/server/internal/httpapi/accounts_test.go @@ -82,7 +82,9 @@ type env struct { func newEnv(t *testing.T) *env { t.Helper() - e := &env{t: t, now: time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)} + // The fake clock starts at the real time: the client's cookie jar runs + // on the real clock, and drops a session cookie that expired by it. + e := &env{t: t, now: time.Now().UTC().Truncate(time.Hour)} var h http.Handler e.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(w, r) })) t.Cleanup(e.srv.Close)