fix(cctv): bound HLS sessions and isolate consumer playback leases

This commit is contained in:
Bilawal Sidhu committed 2026-09-15 10:52:30 -05:00
1 parent 48666cb9a4
commit 292cd610f3
22 files changed
+665 -730

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHlsPuller, fetchHlsBytes, parseHlsMedia, HLS_LIMITS } from '../../server/providers/cctv/stream.js';
const playlist = '#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:12\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n';
const base = 'https://camera.example/live/list.m3u8';
test('playlist parser uses sequence, refuses escaping and unsupported references', () => {
assert.deepEqual(parseHlsMedia(playlist, base).map((s) => s.seq), [12, 13, 14]);
for (const bad of [playlist.replace('a.ts', 'https://evil.example/a.ts'), playlist.replace('a.ts', '//evil.example/a.ts'), '#EXTM3U\n#EXT-X-KEY:METHOD=AES-128\n' + playlist, playlist.replace('12', '-1'), playlist.replace('2,', 'Infinity,')]) assert.throws(() => parseHlsMedia(bad, base));
});
test('downloads reject redirect responses, oversized declared and chunked bodies', async () => {
let init;
await assert.rejects(fetchHlsBytes(base, { maxBytes: 5, fetchImpl: async (_url, options) => { init = options; return new Response('', { status: 302, headers: { Location: 'https://evil.example' } }); } }));
assert.equal(init.redirect, 'error');
await assert.rejects(fetchHlsBytes(base, { maxBytes: 5, fetchImpl: async () => new Response('abcdef') }));
await assert.rejects(fetchHlsBytes(base, { maxBytes: 5, fetchImpl: async () => new Response('a', { headers: { 'content-length': '100' } }) }));
});
test('one session is reserved before await; disk-free cache and capacity remain bounded', async () => {
const manager = createHlsPuller({ limits: { ...HLS_LIMITS, sessions: 1, segmentBytes: 4, sessionBytes: 6, segments: 2, pollMs: 100000 }, fetchImpl: async (url) => new Response(url.endsWith('.m3u8') ? playlist : 'abc') });
const [a, b] = await Promise.all([manager.ensure('a', base), manager.ensure('a', base)]);
assert.equal(a, b);
await assert.rejects(manager.ensure('b', base));
assert.equal(await manager.waitReady(a), true);
assert.deepEqual(manager.stats(), { sessions: 1, bytes: 6 });
const text = await manager.buildPlaylist(a, 'a');
assert.match(text, /seg_0\.ts\?session=/);
assert.equal(manager.getSegment('a', 'stale-token', 0), null);
assert.equal(manager.getSegment('a', a.token, 0).length, 3);
manager.stop('a', 'stale-token');
assert.equal(manager.stats().sessions, 1);
manager.stop('a', a.token);
assert.deepEqual(manager.stats(), { sessions: 0, bytes: 0 });
await manager.shutdown();
});
test('shutdown cancels in-flight downloads and late responses cannot refill cache', async () => {
let observed;
const manager = createHlsPuller({ fetchImpl: async (_url, { signal }) => { observed = signal; return new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })); } });
const entry = await manager.ensure('a', base);
await manager.shutdown();
assert.equal(observed.aborted, true);
assert.equal(entry.stopping, true);
assert.deepEqual(manager.stats(), { sessions: 0, bytes: 0 });
await assert.rejects(manager.ensure('a', base));
});
test('idle cleanup stops all polling without a background sweep', async () => {
let calls = 0;
const manager = createHlsPuller({ limits: { ...HLS_LIMITS, idleMs: 15, pollMs: 100000 }, fetchImpl: async (url) => { calls++; return new Response(url.endsWith('.m3u8') ? playlist : 'abc'); } });
await manager.ensure('a', base);
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(manager.stats(), { sessions: 0, bytes: 0 });
const stoppedCalls = calls;
await new Promise((r) => setTimeout(r, 30));
assert.equal(calls, stoppedCalls);
await manager.shutdown();
});
test('agency sequence rollback creates a monotonic local discontinuity', async () => {
let current = playlist;
const manager = createHlsPuller({ limits: { ...HLS_LIMITS, pollMs: 5 }, fetchImpl: async (url) => new Response(url.endsWith('.m3u8') ? current : 'abc') });
const entry = await manager.ensure('a', base);
await manager.waitReady(entry);
const before = await manager.buildPlaylist(entry, 'a');
assert.match(before, /seg_0\.ts/);
current = playlist.replace('SEQUENCE:12', 'SEQUENCE:0');
await new Promise((r) => setTimeout(r, 30));
const after = await manager.buildPlaylist(entry, 'a');
assert.match(after, /#EXT-X-DISCONTINUITY\n#EXTINF:2\.000,\n\/api\/cctv\/media\/a\/seg_3\.ts/);
await manager.shutdown();
});
test('upstream discontinuity tags survive the media parser', () => {
const parsed = parseHlsMedia(playlist.replace('a.ts', 'a.ts\n#EXT-X-DISCONTINUITY'), base);
assert.equal(parsed[0].discontinuity, false);
assert.equal(parsed[1].discontinuity, true);
});
test('a reused agency sequence with changed segment URI cannot remain stale', async () => {
let current = playlist;
const manager = createHlsPuller({ limits: { ...HLS_LIMITS, pollMs: 5 }, fetchImpl: async (url) => new Response(url.endsWith('.m3u8') ? current : 'abc') });
const entry = await manager.ensure('a', base);
await manager.waitReady(entry);
current = playlist.replaceAll('.ts', '.ts?generation=2');
await new Promise((r) => setTimeout(r, 30));
assert.match(await manager.buildPlaylist(entry, 'a'), /#EXT-X-DISCONTINUITY\n#EXTINF:2\.000,\n\/api\/cctv\/media\/a\/seg_3\.ts/);
await manager.shutdown();
});
test('two consumers share downloads but release and abandoned expiry are independent', async () => {
let downloads = 0;
const manager = createHlsPuller({ limits: { ...HLS_LIMITS, pollMs: 100000, leasesPerSession: 2 }, fetchImpl: async (url) => {
downloads++;
return new Response(url.endsWith('.m3u8') ? playlist : 'abc');
} });
const [a, b] = await Promise.all([manager.ensure('camera', base, 'viewer-a'), manager.ensure('camera', base, 'viewer-b')]);
assert.equal(a, b);
await manager.waitReady(a);
assert.equal(downloads, 4); // One manifest and three segments, not per consumer.
assert.equal(a.leases.size, 2);
await assert.rejects(manager.ensure('camera', base, 'viewer-c'));
manager.release('camera', 'viewer-a');
assert.equal(manager.stats().sessions, 1);
assert.equal(manager.getSegment('camera', a.token, 0, 'viewer-a'), null);
assert.equal(manager.getSegment('camera', a.token, 0, 'viewer-b').length, 3);
assert.match(await manager.buildPlaylist(b, 'camera', 'viewer-b'), /lease=viewer-b/);
manager.release('camera', 'viewer-a'); // Duplicate/late release cannot stop B.
assert.equal(b.controller.signal.aborted, false);
manager.release('camera', 'viewer-b');
assert.equal(b.controller.signal.aborted, true);
assert.deepEqual(manager.stats(), { sessions: 0, bytes: 0 });
await manager.shutdown();
});
test('an abandoned consumer expires while a renewed consumer keeps the session', async () => {
const manager = createHlsPuller({ limits: { ...HLS_LIMITS, idleMs: 80, pollMs: 100000 }, fetchImpl: async (url) => new Response(url.endsWith('.m3u8') ? playlist : 'abc') });
const entry = await manager.ensure('camera', base, 'abandoned');
await manager.ensure('camera', base, 'active');
await new Promise((r) => setTimeout(r, 50));
await manager.ensure('camera', base, 'active');
await new Promise((r) => setTimeout(r, 50));
assert.equal(entry.leases.has('abandoned'), false);
assert.equal(entry.leases.has('active'), true);
assert.equal(entry.controller.signal.aborted, false);
await manager.shutdown();
});
+4
View File
@@ -136,6 +136,10 @@ export const DATA_CREDITS = [
'CCTV cameras & frames (Texas): ' +
'<a href="https://its.txdot.gov/" target="_blank" rel="noopener">Texas Department of Transportation</a> (courtesy)',
},
{
key: 'deldot-cctv',
html: 'CCTV live video (Delaware): <a href="https://deldot.gov/map/" target="_blank" rel="noopener">DelDOT — Delaware Department of Transportation</a>',
},
{
key: 'caltrans-cctv',
html:
+1 -1
View File
@@ -83,7 +83,7 @@ export function createPresentation({
mountHeightM: camera.mountHeightM,
active: isActive,
feedType: camera.feedType,
isVideo: parts.model.isVideoFeedType(camera.feedType),
isVideo: parts.model.isVideoFeedType(camera.feedType) && record.projection?.mode !== 'image',
sourceKind:
health?.sourceKind ||
camera.sourceKind ||
+27 -99
View File
@@ -1,3 +1,4 @@
import { attachCctvVideo } from './videoPlayback.js';
import * as Cesium from 'cesium';
import {
CCTV_PROJECTION_OVERLAY_SOURCE_ID,
@@ -168,79 +169,6 @@ export function createProjection({
* @returns {Object|null} Projection runtime, or null if no viewer.
*/
async function attachVideoSource(runtime, url, feedType) {
const video = runtime?.video;
if (!video) return;
if (feedType !== 'hls') {
video.src = url;
return;
}
try {
const { default: Hls } = await import('hls.js');
if (runtime.disposed || runtime.video !== video) return;
if (!Hls.isSupported()) {
video.src = url;
return;
}
const hls = new Hls({
lowLatencyMode: false,
enableWorker: true,
liveSyncDurationCount: 5,
liveMaxLatencyDurationCount: 6,
maxBufferLength: 60,
backBufferLength: 30,
});
hls.on(Hls.Events.ERROR, (_event, data) => {
if (!data?.fatal) return;
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
// reread master for a fresh session
console.warn(
'[Data:CCTV] hls network error, reloading source:',
data.details,
);
setTimeout(() => {
if (runtime.hls === hls) hls.loadSource(url);
}, 2000);
return;
}
if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
hls.recoverMediaError();
return;
}
console.warn('[Data:CCTV] hls fatal:', data.type, data.details);
hls.destroy();
if (runtime.hls === hls) runtime.hls = null;
});
hls.loadSource(url);
hls.attachMedia(video);
runtime.hls = hls;
// Rate governor: DelDOT cameras deliver ~52 s of content per 60 s wall
// time. Hold playbackRate by buffer depth so the stream never starves;
// cameras with honest clocks sit at 1.0 and never leave it.
const governor = setInterval(() => {
if (runtime.video !== video || !runtime.hls) {
clearInterval(governor);
return;
}
const b = video.buffered;
if (!b.length) return;
const ahead = b.end(b.length - 1) - video.currentTime;
let rate = 1.0;
if (ahead < 15) rate = 0.75;
else if (ahead < 20) rate = 0.85;
else if (ahead < 30) rate = 0.93;
else if (ahead > 40) rate = 1.05;
if (Math.abs(video.playbackRate - rate) > 0.01)
video.playbackRate = rate;
}, 1000);
runtime.rateGovernor = governor;
} catch (error) {
console.warn('[Data:CCTV] hls.js unavailable:', error?.message || error);
video.src = url;
}
}
function createProjectionRuntime(record) {
if (!layerState._viewer) return null;
const canvas = document.createElement('canvas');
@@ -291,9 +219,6 @@ export function createProjection({
video.playsInline = true;
video.crossOrigin = 'anonymous';
video.preload = 'auto';
video.addEventListener('canplay', () => {
video.play().catch(() => {});
});
// Cesium sizes the video texture from the element's width/height
// attributes at first upload. Set them from the real stream dimensions
// and rebind on any resolution change (camera switch, adaptive source).
@@ -308,12 +233,20 @@ export function createProjection({
video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture);
runtime.video = video;
runtime.hls = null;
attachVideoSource(
runtime,
parts.frames.mediaUrlFor(record.camera),
feedType,
);
runtime.playback = attachCctvVideo(video, parts.frames.mediaUrlFor(record.camera), feedType, {
onFailure: () => {
if (runtime.disposed) return;
runtime.video = null;
runtime.mode = 'image';
runtime.image = new Image();
runtime.image.decoding = 'async';
runtime.image.onload = () => { runtime.imageLoading = false; runtime.imageReady = true; runtime.imageStamp = Date.now(); };
runtime.image.onerror = () => { runtime.imageLoading = false; runtime.imageReady = false; };
runtime.planeMaterial.image = runtime.canvas;
parts.frames.refreshProjectionImage(record, true);
parts.presentation.notifyListeners();
},
});
} else {
const img = new Image();
img.decoding = 'async';
@@ -361,7 +294,7 @@ export function createProjection({
function ensureProjectionRuntime(record) {
if (!record) return null;
if (record.projection) return record.projection;
if (record.projection && !record.projection.disposed) return record.projection;
const runtime = createProjectionRuntime(record);
record.projection = runtime;
if (runtime) {
@@ -377,16 +310,11 @@ export function createProjection({
*/
function destroyProjectionRuntime(runtime) {
if (!runtime) return;
if (!runtime || runtime.disposed) return;
runtime.disposed = true;
if (runtime.hls) {
runtime.hls.destroy();
runtime.hls = null;
}
if (runtime.rateGovernor) {
clearInterval(runtime.rateGovernor);
runtime.rateGovernor = null;
}
runtime.playback?.dispose();
runtime.playback = null;
if (runtime.image) { runtime.image.onload = null; runtime.image.onerror = null; runtime.image.src = ''; }
if (runtime.video) {
runtime.video.pause();
runtime.video.removeAttribute('src');
@@ -423,10 +351,7 @@ export function createProjection({
const active = parts.selection.getActiveRecord();
if (layerState._enabled && layerState._showProjection && active) {
ensureProjectionRuntime(active);
if (active.projection?.video) {
active.projection.video.play().catch(() => {});
}
if (active.projection) {
if (active.projection && !active.projection.video) {
parts.frames.drawProjectionFrame(active);
parts.frames.refreshProjectionTextures(active);
}
@@ -460,6 +385,7 @@ export function createProjection({
* @returns {HTMLVideoElement|null}
*/
function getActiveVideoElement() {
if (!layerState._enabled) return null;
return parts.selection.getActiveRecord()?.projection?.video || null;
}
@@ -468,12 +394,14 @@ export function createProjection({
if (!record.projection?.video) continue;
if (
record.camera.id === activeId &&
layerState._enabled &&
layerState._showProjection
layerState._enabled
) {
record.projection.video.play().catch(() => {});
} else {
record.projection.video.pause();
const runtime = record.projection;
destroyProjectionRuntime(runtime);
record.projection = null;
layerState._projectionEntities = layerState._projectionEntities.filter((entry) => entry !== runtime);
}
}
}
+1 -1
View File
@@ -215,7 +215,7 @@ export function createRendering({
// (set at creation) — see the field-test far-zoom submerge fix there.
}
if (layerState._enabled && layerState._showProjection && isActive) {
if (layerState._enabled && isActive && (layerState._showProjection || parts.model.isVideoFeedType(record.camera.feedType))) {
parts.projection.ensureProjectionRuntime(record);
}
// One live plane in the world at a time (§2c): only the active camera's
+81
View File
@@ -0,0 +1,81 @@
/** One decoder per active camera; both surfaces consume this video element. */
export function attachCctvVideo(video, url, feedType, {
loadHls = () => import('hls.js'),
onFailure = () => {},
fetchImpl = globalThis.fetch,
} = {}) {
let disposed = false;
let hls = null;
const leaseId = feedType === 'hls' ? globalThis.crypto.randomUUID() : null;
const mediaUrl = feedType === 'hls' ? `${url}${url.includes('?') ? '&' : '?'}lease=${leaseId}` : url;
let timer = null;
let startup = null;
let governor = null;
let retries = 0;
const release = () => {
if (feedType === 'hls') {
void fetchImpl?.(mediaUrl, { method: 'DELETE', keepalive: true }).catch(() => {});
}
};
const dispose = () => {
if (disposed) return;
disposed = true;
clearTimeout(timer);
clearTimeout(startup);
clearInterval(governor);
hls?.destroy();
hls = null;
video.removeEventListener('canplay', play);
video.removeEventListener('error', fail);
video.pause();
video.removeAttribute('src');
video.load();
release();
};
const fail = () => {
if (disposed) return;
dispose();
onFailure();
};
const play = () => {
if (disposed) return;
clearTimeout(startup);
video.play().catch(() => {});
};
video.addEventListener('canplay', play);
video.addEventListener('error', fail);
startup = setTimeout(fail, 30000);
const ready = (async () => {
if (feedType !== 'hls') { video.src = mediaUrl; return; }
try {
const { default: Hls } = await loadHls();
if (disposed) return;
if (!Hls.isSupported()) {
if (video.canPlayType('application/vnd.apple.mpegurl')) video.src = mediaUrl;
else fail();
return;
}
hls = new Hls({ enableWorker: true, maxBufferLength: 24, maxMaxBufferLength: 30, backBufferLength: 0, maxBufferSize: 16 * 1024 * 1024, liveSyncDurationCount: 3 });
hls.on(Hls.Events.ERROR, (_event, data) => {
if (disposed || !data?.fatal) return;
if (++retries > 2) { fail(); return; }
clearTimeout(timer);
timer = setTimeout(() => {
if (disposed) return;
if (data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError();
else hls.loadSource(mediaUrl);
}, 2000);
});
governor = setInterval(() => {
if (disposed || !video.buffered?.length) return;
const ahead = video.buffered.end(video.buffered.length - 1) - video.currentTime;
// Some agency encoders publish less media time than wall time. Bound
// correction rather than repeatedly draining the live buffer at 1x.
video.playbackRate = ahead < 6 ? 0.8 : ahead < 12 ? 0.9 : ahead > 24 ? 1.05 : 1;
}, 1000);
hls.attachMedia(video);
hls.loadSource(mediaUrl);
} catch { fail(); }
})();
return { dispose, ready };
}
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { attachCctvVideo } from './videoPlayback.js';
function video() {
const v = new EventTarget();
Object.assign(v, { src: '', pause() {}, load() {}, removeAttribute() {}, play: () => Promise.resolve() });
return v;
}
test('switch during lazy import never starts the stale decoder', async () => {
let resolve;
let constructed = 0;
class Hls { constructor() { constructed++; } static isSupported() { return true; } }
const source = video();
const playback = attachCctvVideo(source, '/api/cctv/media/a', 'hls', { loadHls: () => new Promise((r) => { resolve = r; }) });
playback.dispose();
resolve({ default: Hls });
await playback.ready;
assert.equal(constructed, 0);
assert.equal(source.src, '');
});
test('missing decoder uses honest failure fallback once', async () => {
let failures = 0;
const playback = attachCctvVideo(video(), '/api/cctv/media/a', 'hls', { loadHls: async () => { throw new Error('unavailable'); }, onFailure: () => failures++ });
await playback.ready;
playback.dispose();
assert.equal(failures, 1);
});
test('native HLS releases its client lease without response-header access', async () => {
const source = video();
source.canPlayType = () => 'probably';
const releases = [];
const playback = attachCctvVideo(source, '/api/cctv/media/a', 'hls', {
loadHls: async () => ({ default: { isSupported: () => false } }),
fetchImpl: async (url, init) => { releases.push({ url, init }); },
});
await playback.ready;
assert.match(source.src, /\/api\/cctv\/media\/a\?lease=[a-f0-9-]{36}$/);
const requested = source.src;
playback.dispose();
playback.dispose();
assert.equal(releases.length, 1);
assert.equal(releases[0].url, requested);
assert.equal(releases[0].init.method, 'DELETE');
});
+7
View File
@@ -38,6 +38,11 @@ export class CctvControls {
this._calibrationEdit = null;
this._actionGeneration = 0;
this._initCctvPanel();
if (this._cctvVideo && typeof MutationObserver !== 'undefined') {
this._videoVisibilityObserver = new MutationObserver(() => this._renderCctvState(this._cctvState));
if (this._cctvPanel) this._videoVisibilityObserver.observe(this._cctvPanel, { attributes: true, attributeFilter: ['class', 'hidden'] });
this.listen(document, 'visibilitychange', () => this._renderCctvState(this._cctvState));
}
}
listen(target, type, handler, options = {}) {
target?.addEventListener(type, handler, {
@@ -99,6 +104,8 @@ export class CctvControls {
destroy() {
if (this.destroyed) return;
this.destroyed = true;
this._cctvVideoSurface?.stop();
this._videoVisibilityObserver?.disconnect();
this._actionGeneration++;
this.listeners.abort();
this._cctvUnsubscribe?.();
+9 -32
View File
@@ -1,3 +1,4 @@
import { createCctvVideoSurface } from './cctvVideo.js';
export function _calBadgeLabel(badge) {
switch (badge) {
case 'calibrated':
@@ -164,42 +165,18 @@ export function _renderCctvState(state) {
}
}
// Live video: for HLS cameras, paint the active camera's decoded <video>
// element onto a canvas each frame (one decoder, two surfaces — the plane
// reads the same element). The loop rides through hls.js pipeline resets
// (a null element or unchanged currentTime is a skipped frame, not an exit)
// and self-stops when the card hides or the feed goes away. The still-image
// path below is suppressed while a live feed is showing.
const liveIntent = enabled && !!activeCamera?.isVideo;
if (this._cctvVideo) {
this._cctvVideo.hidden = !liveIntent;
if (this._cctvFrame) this._cctvFrame.hidden = liveIntent;
this._cctvVideoActive = liveIntent;
if (liveIntent && !this._cctvVideoRaf) {
const canvas = this._cctvVideo;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
let lastTime = -1;
const paint = () => {
if (this.destroyed || !this._cctvVideoActive) {
this._cctvVideoRaf = 0;
return;
}
const v = this.cctv.getActiveVideoElement();
if (v && v.currentTime !== lastTime) {
lastTime = v.currentTime;
if (
canvas.width !== v.videoWidth ||
canvas.height !== v.videoHeight
) {
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
}
ctx.drawImage(v, 0, 0);
}
this._cctvVideoRaf = requestAnimationFrame(paint);
};
this._cctvVideoRaf = requestAnimationFrame(paint);
const visible = liveIntent && !document.hidden && !this._cctvPanel?.classList.contains('collapsed');
if (!visible || this._cctvVideoCameraId !== activeId) {
this._cctvVideoSurface?.stop();
this._cctvVideoSurface = null;
}
this._cctvVideoCameraId = activeId;
if (visible && !this._cctvVideoSurface) {
this._cctvVideoSurface = createCctvVideoSurface(this._cctvVideo, () => this.cctv.getActiveVideoElement?.());
}
}
+31
View File
@@ -0,0 +1,31 @@
/** Paint a second surface from the projection decoder, bounded to 640px/15 fps. */
export function createCctvVideoSurface(canvas, getVideo, { requestFrame = requestAnimationFrame, cancelFrame = cancelAnimationFrame } = {}) {
const ctx = canvas.getContext('2d');
let handle = 0;
let stopped = false;
let previous = null;
let previousTime = -1;
let paintedAt = -Infinity;
const paint = (now) => {
if (stopped) return;
const video = getVideo();
if (video !== previous) {
ctx?.clearRect(0, 0, canvas.width, canvas.height);
previous = video;
previousTime = -1;
}
if (ctx && video?.readyState >= 2 && video.videoWidth > 0 && video.videoHeight > 0 && now - paintedAt >= 1000 / 15 && video.currentTime !== previousTime) {
const width = Math.min(640, video.videoWidth);
const height = Math.max(1, Math.round(width * video.videoHeight / video.videoWidth));
if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; }
try {
ctx.drawImage(video, 0, 0, width, height);
previousTime = video.currentTime;
paintedAt = now;
} catch { /* A resolution/decode transition retries on the next frame. */ }
}
handle = requestFrame(paint);
};
handle = requestFrame(paint);
return { stop() { stopped = true; cancelFrame(handle); ctx?.clearRect(0, 0, canvas.width, canvas.height); } };
}
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCctvVideoSurface } from './cctvVideo.js';
test('second surface uses shared decoder, caps draws, clears switch and cancels teardown', () => {
let callback;
let draws = 0;
let clears = 0;
let cancelled = 0;
const canvas = { width: 1, height: 1, getContext: () => ({ drawImage: () => draws++, clearRect: () => clears++ }) };
let v = { readyState: 2, videoWidth: 1920, videoHeight: 1080, currentTime: 1 };
const surface = createCctvVideoSurface(canvas, () => v, { requestFrame: (fn) => { callback = fn; return 1; }, cancelFrame: () => cancelled++ });
callback(0); callback(20); callback(80);
assert.equal(draws, 1);
assert.equal(canvas.width, 640);
v = { ...v }; callback(160);
assert.equal(draws, 2);
assert.equal(clears, 2);
surface.stop(); callback(200);
assert.equal(cancelled, 1);
assert.equal(draws, 2);
});
-2
View File
@@ -234,8 +234,6 @@
image inside is taller — and the wrap is overflow:hidden, which clipped
the bottom of the frame right back off. Never shrink the preview. */
flex-shrink: 0;
aspect-ratio: 16/9;
min-height: 0;
}
/* Lightweight loading shimmer while the active frame is fetching */