Live view at head office, relayed through the agent's outbound connection

I got this wrong first time. "Head office cannot show live video cheaply"
conflated TRUE VIDEO with SEEING THE CAMERA NOW, and only the first needs
WebRTC and a TURN server.

The shop PC is behind a router with no inbound route, so head office
cannot pull the engine's MJPEG. It can answer the agent's outbound
requests, which is the shape of everything else here: the server holds a
poll open, the agent asks "is anyone watching?", and pushes JPEGs up for
exactly as long as somebody is.

Measured on the office camera: 98 KB full frame, 20.8 KB re-encoded at
640/q60, so one watcher costs ~83 KB/s. 47 frames arrived in 12 seconds -
4 fps, as configured. The UI says "about 4 frames a second" rather than
letting anyone conclude the camera stutters.

Nothing is uploaded when nobody is looking, which is the whole cost
argument: Publish returns false once the last viewer goes, interest lapses
on a timer each viewer refreshes as it reads (so a closed tab stops the
upload within seconds), one push is capped at five minutes, and the UI
streams one camera at a time.

LiveHub is deliberately the opposite of the arrivals Hub. There a doorbell
pushes nothing because nothing may be lost; here a dropped frame is the
correct outcome, so each viewer has a one-slot buffer that is overwritten -
the only frame worth having is the newest, and a queue would show an
ever-growing delay behind the shop instead of dropping back to live.

Ownership is proved once, before anything streams: the relay is keyed on a
camera id, a hub does not know whose camera it holds, and a camera id is
not a secret. Verified: another tenant gets 404, no session gets 401, and
an agent cannot push into another site's camera.

Also fixes a bug I introduced with it - the Live button was gated on
`connected`, which is head office's last report and up to two minutes
stale, so it hid itself during every reconnect. "Is that camera really
down?" is exactly when somebody wants to look, and a hidden control says
"you cannot" where the honest answer is "here is why".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HViLj9gYNRtSr7YVZmW5sn
This commit is contained in:
2026-09-04 16:46:23 +05:30
parent 2cd7a78ddc
commit 18686cbceb
23 changed files with 1250 additions and 67 deletions

View File

@@ -261,3 +261,70 @@ export function streamArrivals({ cursor, siteId, onPage, onError, signal }) {
run()
return () => { stopped = true }
}
// streamCameraLive renders one camera's live view into an <img>.
//
// Frames arrive base64 over SSE for the same reason the snapshot is fetched
// rather than linked: an <img> cannot send an Authorization header, and minting
// a URL that works without a session — for LIVE video of a shop floor — would
// be a far worse trade than the 33% base64 costs.
//
// The frame is written straight into `img.src` as a data URL rather than an
// object URL. Object URLs would have to be revoked one per frame, several times
// a second, and a single missed revoke is a leak that grows for as long as the
// view is open. A data URL is owned by the element and replaced by the next one.
export function streamCameraLive({ cameraId, img, onState, signal }) {
let stopped = false
const run = async () => {
while (!stopped) {
try {
const { access } = tokens()
const res = await fetch(`/api/cameras/${cameraId}/live`, {
headers: { Authorization: 'Bearer ' + access, Accept: 'text/event-stream' },
signal,
})
if (res.status === 401) { await refresh(); continue }
if (!res.ok || !res.body) throw new Error('live view unavailable')
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
while (!stopped) {
const { value, done } = await reader.read()
if (done) break
buf += decoder.decode(value, { stream: true })
let split
while ((split = buf.indexOf('\n\n')) !== -1) {
const chunk = buf.slice(0, split)
buf = buf.slice(split + 2)
let event = 'message', data = ''
for (const line of chunk.split('\n')) {
if (line.startsWith('event: ')) event = line.slice(7).trim()
else if (line.startsWith('data: ')) data = line.slice(6)
}
if (event === 'frame' && data) {
if (img.current) img.current.src = 'data:image/jpeg;base64,' + data
onState?.('live')
} else if (event === 'waiting') {
// The server has registered us; the shop PC has not started
// pushing yet. Saying so beats an empty box, because the wait is
// a real second or two while the agent is asked.
onState?.('waiting')
}
}
}
} catch (err) {
if (stopped || signal?.aborted) return
onState?.('reconnecting')
}
if (stopped) return
// The server caps one push so a tab left open for a week does not leave
// a shop uploading for a week. Reconnecting is how a viewer who IS still
// watching carries on, so this is a normal event, not an error.
await new Promise(r => setTimeout(r, 1500))
}
}
run()
return () => { stopped = true }
}