Files
tv-discord/activity/js/sync.js
T

89 lines
3.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
sync.js — pure playback-sync math (no DOM), unit-tested in test/sync.test.js.
Clock: the server sends `updatedAt`/`now` in its own clock. `offset` = server − local (ms),
estimated from ping/pong as the median of the last few samples.
*/
export const HARD_DRIFT = 1.5; // s — beyond this: seek
export const SOFT_DRIFT = 0.3; // s — beyond this: nudge playbackRate
export const RATE_SLOW = 0.95;
export const RATE_FAST = 1.05;
export const JUMP = 0.5; // s — a state change that moves the target by more than this is an explicit seek
/** Where playback should be right now, in seconds. */
export function targetTime(state, offset = 0, now = Date.now()) {
if (!state) return 0;
let t = Number(state.position) || 0;
if (state.playing) t += Math.max(0, (now + offset - (Number(state.updatedAt) || 0)) / 1000);
const d = Number(state.duration) || 0;
if (d > 0) t = Math.min(t, d);
return Math.max(0, t);
}
/**
* What to do about the difference between the local player and the target.
* → { action: 'seek' | 'rate' | 'none', drift, rate }
* drift > 0 means the local player is ahead.
* `canSeek` false (cooldown after a recent seek) downgrades a hard seek to a rate nudge.
*/
export function driftAction(current, target, { playing = true, canSeek = true } = {}) {
const drift = current - target;
const abs = Math.abs(drift);
if (!playing) {
// paused: rate does nothing, so line up exactly once we're noticeably off
if (abs > SOFT_DRIFT && canSeek) return { action: 'seek', drift, rate: 1 };
return { action: 'none', drift, rate: 1 };
}
if (abs > HARD_DRIFT && canSeek) return { action: 'seek', drift, rate: 1 };
if (abs > SOFT_DRIFT) return { action: 'rate', drift, rate: drift > 0 ? RATE_SLOW : RATE_FAST };
return { action: 'none', drift, rate: 1 };
}
/** True when `next` moved the playhead (seek, source/episode change) rather than just ticking on. */
export function isJump(prev, next, offset = 0, now = Date.now()) {
if (!prev || !next) return true;
return Math.abs(targetTime(prev, offset, now) - targetTime(next, offset, now)) > JUMP;
}
/** One ping/pong round trip → { offset, rtt } (ms). */
export function offsetSample(sentAt, serverNow, recvAt) {
const rtt = Math.max(0, recvAt - sentAt);
return { offset: serverNow - (sentAt + rtt / 2), rtt };
}
export function median(values) {
const v = values.filter((x) => Number.isFinite(x)).sort((a, b) => a - b);
if (!v.length) return 0;
const m = v.length >> 1;
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2;
}
/** Rolling clock-offset estimator: median of the last `size` samples. */
export function createClock(size = 5) {
const samples = [];
return {
add(sample) {
const o = typeof sample === 'number' ? sample : sample && sample.offset;
if (!Number.isFinite(o)) return;
samples.push(o);
while (samples.length > size) samples.shift();
},
offset() {
return median(samples);
},
get count() {
return samples.length;
},
};
}
export function formatTime(sec) {
sec = Math.max(0, Math.floor(Number(sec) || 0));
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = sec % 60;
const ss = String(s).padStart(2, '0');
return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`;
}