style(cctv): format live video integration

This commit is contained in:
Bilawal Sidhu committed 2026-09-15 10:54:40 -05:00
1 parent 3571284782
commit 6f40fff09e
13 files changed
+564 -144

No files matched your search

+120 -23
View File
@@ -1,25 +1,77 @@
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';
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));
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' } }); } }));
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' } }) }));
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)]);
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);
@@ -37,7 +89,16 @@ test('one session is reserved before await; disk-free cache and capacity remain
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 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);
@@ -48,7 +109,13 @@ test('shutdown cancels in-flight downloads and late responses cannot refill cach
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'); } });
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 });
@@ -60,7 +127,11 @@ test('idle cleanup stops all polling without a background sweep', async () => {
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 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');
@@ -68,34 +139,53 @@ test('agency sequence rollback creates a monotonic local discontinuity', async (
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/);
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);
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 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/);
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')]);
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.
@@ -105,7 +195,10 @@ test('two consumers share downloads but release and abandoned expiry are indepen
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/);
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');
@@ -115,7 +208,11 @@ test('two consumers share downloads but release and abandoned expiry are indepen
});
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 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));
+3 -1
View File
@@ -83,7 +83,9 @@ export function createPresentation({
mountHeightM: camera.mountHeightM,
active: isActive,
feedType: camera.feedType,
isVideo: parts.model.isVideoFeedType(camera.feedType) && record.projection?.mode !== 'image',
isVideo:
parts.model.isVideoFeedType(camera.feedType) &&
record.projection?.mode !== 'image',
sourceKind:
health?.sourceKind ||
camera.sourceKind ||
+36 -20
View File
@@ -233,20 +233,32 @@ export function createProjection({
video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture);
runtime.video = video;
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();
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';
@@ -294,7 +306,8 @@ export function createProjection({
function ensureProjectionRuntime(record) {
if (!record) return null;
if (record.projection && !record.projection.disposed) return record.projection;
if (record.projection && !record.projection.disposed)
return record.projection;
const runtime = createProjectionRuntime(record);
record.projection = runtime;
if (runtime) {
@@ -314,7 +327,11 @@ export function createProjection({
runtime.disposed = true;
runtime.playback?.dispose();
runtime.playback = null;
if (runtime.image) { runtime.image.onload = null; runtime.image.onerror = null; runtime.image.src = ''; }
if (runtime.image) {
runtime.image.onload = null;
runtime.image.onerror = null;
runtime.image.src = '';
}
if (runtime.video) {
runtime.video.pause();
runtime.video.removeAttribute('src');
@@ -392,16 +409,15 @@ export function createProjection({
function pauseInactiveProjectionFeeds(activeId) {
for (const record of layerState._records) {
if (!record.projection?.video) continue;
if (
record.camera.id === activeId &&
layerState._enabled
) {
if (record.camera.id === activeId && layerState._enabled) {
record.projection.video.play().catch(() => {});
} else {
const runtime = record.projection;
destroyProjectionRuntime(runtime);
record.projection = null;
layerState._projectionEntities = layerState._projectionEntities.filter((entry) => entry !== runtime);
layerState._projectionEntities = layerState._projectionEntities.filter(
(entry) => entry !== runtime,
);
}
}
}
+6 -1
View File
@@ -215,7 +215,12 @@ export function createRendering({
// (set at creation) — see the field-test far-zoom submerge fix there.
}
if (layerState._enabled && isActive && (layerState._showProjection || parts.model.isVideoFeedType(record.camera.feedType))) {
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
+42 -14
View File
@@ -1,20 +1,30 @@
/** 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,
} = {}) {
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;
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(() => {});
void fetchImpl?.(mediaUrl, { method: 'DELETE', keepalive: true }).catch(
() => {},
);
}
};
const dispose = () => {
@@ -46,19 +56,33 @@ export function attachCctvVideo(video, url, feedType, {
video.addEventListener('error', fail);
startup = setTimeout(fail, 30000);
const ready = (async () => {
if (feedType !== 'hls') { video.src = mediaUrl; return; }
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;
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 = 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; }
if (++retries > 2) {
fail();
return;
}
clearTimeout(timer);
timer = setTimeout(() => {
if (disposed) return;
@@ -68,14 +92,18 @@ export function attachCctvVideo(video, url, feedType, {
});
governor = setInterval(() => {
if (disposed || !video.buffered?.length) return;
const ahead = video.buffered.end(video.buffered.length - 1) - video.currentTime;
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;
video.playbackRate =
ahead < 6 ? 0.8 : ahead < 12 ? 0.9 : ahead > 24 ? 1.05 : 1;
}, 1000);
hls.attachMedia(video);
hls.loadSource(mediaUrl);
} catch { fail(); }
} catch {
fail();
}
})();
return { dispose, ready };
}
+30 -5
View File
@@ -3,15 +3,33 @@ 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() });
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; } }
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; }) });
const playback = attachCctvVideo(source, '/api/cctv/media/a', 'hls', {
loadHls: () =>
new Promise((r) => {
resolve = r;
}),
});
playback.dispose();
resolve({ default: Hls });
await playback.ready;
@@ -20,7 +38,12 @@ test('switch during lazy import never starts the stale decoder', async () => {
});
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++ });
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);
@@ -32,7 +55,9 @@ test('native HLS releases its client lease without response-header access', asyn
const releases = [];
const playback = attachCctvVideo(source, '/api/cctv/media/a', 'hls', {
loadHls: async () => ({ default: { isSupported: () => false } }),
fetchImpl: async (url, init) => { releases.push({ url, init }); },
fetchImpl: async (url, init) => {
releases.push({ url, init });
},
});
await playback.ready;
assert.match(source.src, /\/api\/cctv\/media\/a\?lease=[a-f0-9-]{36}$/);
+11 -3
View File
@@ -39,9 +39,17 @@ export class CctvControls {
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));
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 = {}) {
+7 -2
View File
@@ -169,14 +169,19 @@ export function _renderCctvState(state) {
if (this._cctvVideo) {
this._cctvVideo.hidden = !liveIntent;
if (this._cctvFrame) this._cctvFrame.hidden = liveIntent;
const visible = liveIntent && !document.hidden && !this._cctvPanel?.classList.contains('collapsed');
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?.());
this._cctvVideoSurface = createCctvVideoSurface(this._cctvVideo, () =>
this.cctv.getActiveVideoElement?.(),
);
}
}
+34 -6
View File
@@ -1,5 +1,12 @@
/** Paint a second surface from the projection decoder, bounded to 640px/15 fps. */
export function createCctvVideoSurface(canvas, getVideo, { requestFrame = requestAnimationFrame, cancelFrame = cancelAnimationFrame } = {}) {
export function createCctvVideoSurface(
canvas,
getVideo,
{
requestFrame = requestAnimationFrame,
cancelFrame = cancelAnimationFrame,
} = {},
) {
const ctx = canvas.getContext('2d');
let handle = 0;
let stopped = false;
@@ -14,18 +21,39 @@ export function createCctvVideoSurface(canvas, getVideo, { requestFrame = reques
previous = video;
previousTime = -1;
}
if (ctx && video?.readyState >= 2 && video.videoWidth > 0 && video.videoHeight > 0 && now - paintedAt >= 1000 / 15 && video.currentTime !== previousTime) {
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; }
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. */ }
} 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); } };
return {
stop() {
stopped = true;
cancelFrame(handle);
ctx?.clearRect(0, 0, canvas.width, canvas.height);
},
};
}
+25 -6
View File
@@ -6,16 +6,35 @@ test('second surface uses shared decoder, caps draws, clears switch and cancels
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);
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);
v = { ...v };
callback(160);
assert.equal(draws, 2);
assert.equal(clears, 2);
surface.stop(); callback(200);
surface.stop();
callback(200);
assert.equal(cancelled, 1);
assert.equal(draws, 2);
});