src.nth.io/

summaryrefslogtreecommitdiff
path: root/scrypted/scrypted-viewport.ts
AgeCommit message (Collapse)AuthorFilesLines
4 daysscrypted: stamp SCRIPT_VERSION = 118a04fLuke Hoersten1-1/+1
4 daysscrypted: subscribe only to selected wake-trigger interfacesLuke Hoersten1-31/+50
attachListener listened on BinarySensor+MotionSensor+ObjectDetector unconditionally and relied on handleCameraEvent to filter by trigger — correct, but a doorbell-only viewport still took a callback per motion re-assert on a chatty camera, and the "subscribed to [...]" log implied all three were wake sources. The listener set now follows the selected triggers (zero triggers = tap-only: no listeners at all), and the idempotency key becomes a "cameraId|triggers" signature (attachedCameraId -> attachedListenerSig) so a trigger change forces a re-attach through the existing rebind path. Event-time filtering stays as defense in depth (ObjectDetector still needs the person-class check).
4 daysscrypted: name viewports from discovery; editable name on settings pageLuke Hoersten1-2/+43
Creating a viewport with the name field blank fell back to "viewport" with no way to change it afterward — display_name is deliberately the canonical name (v.name drifts on reload), so the Scrypted device-name pencil never propagated. Two fixes: - createDevice: an empty name now inherits the discovered device's advertised TXT name, so picking "10.0.13.83 — kitchen (…)" from the host dropdown names the viewport "kitchen" without retyping. - child settings gain a "Viewport name" field: updates display_name, mirrors the name onto the Scrypted device record, and re-registers so the firmware name + mDNS hostname follow.
4 daysscrypted: stamp SCRIPT_VERSION = 3821512Luke Hoersten1-1/+1
4 daysscrypted: mdns discovery — browse, host choices, auto-healLuke Hoersten1-5/+243
Browse for _scrypted-viewport._tcp with a plain dgram socket on an EPHEMERAL port: per RFC 6762 §6.7 a query from a non-5353 source port is a legacy unicast query and responders reply unicast to that port — verified in the ESP-IDF responder (mdns_send.c answers to the querier's addr/port whenever src_port != 5353). No :5353 bind means no conflict with Scrypted's own HomeKit mDNS or a host avahi-daemon, and it works under Docker host-networking or native alike. One response packet carries PTR+SRV+TXT+A (RFC 6763 §12.1), so parsing is per-packet with no follow-up queries; the wire codec (name compression included) is ~150 lines, no dependencies. Surfaced three ways: - add-device form: host field is a combobox listing discovered viewports as "ip — name (vX, WxH)"; manual entry still works and only the address token is stored. - child settings page: same choices on the existing host field. - auto-heal: when a /config register fails, re-browse and match by MAC (seeded from /state and discovery; survives renames) then by name; on a hit at a new address, rewrite host and retry once. Runs only on register failure, so it's rate-limited to the 5-min cycle and removes the need for a DHCP reservation. Browses are best-effort ([] on any failure) and cached 30s so settings re-renders don't spam the LAN. diagnostic.ts gains the same browse as a paste-and-run probe that validates dgram + multicast reachability from inside the real Scrypted sandbox before trusting the feature.
4 daysscrypted: stamp SCRIPT_VERSION = 0ac000eLuke Hoersten1-1/+1
4 daysscrypted: code-review fixes — reload drain order, reconnect storm, wake guardsLuke Hoersten1-76/+190
- bootstrap: drain the shutdown-cleaner array FIRST, not after the child re-discovery loop. The old order tore down the listeners the loop had just attached, and since the instance maps still referenced them the attachListener fast-path blocked the 5-min register-cycle self-heal from ever re-attaching after a warm re-paste. The attach cleaner now also invalidates listeners/attachedCameraId (one cleaner per attach), so a drain by another instance can't strand dead registrations either. - stream socket: single-flight reconnect scheduled from 'close' only. A failed connect emits 'error' then 'close'; scheduling from both doubled outstanding attempts every 500ms against a rebooting device. openStreamSocket also destroys the previous socket first. - onRequest wake: same streams/streamStarting guard as every other start path (a concurrent second startStream overwrote the streams entry and orphaned the first ffmpeg), respond 204 immediately (the device's POST times out at 1s — awaiting startStream turned every tap-wake into a firmware state_post_failure), and skip the redundant wake POST back. - startStream: bail-out paths after the wake POST (camera missing, no usable stream, ffmpeg-input conversion failure) now send a compensating sleep instead of stranding the panel on Loading; the last-ditch getVideoStream fallback no longer rejects out of the call. - key streams/streamStarting/stopStream by nativeId — v.name drifts to the nativeId on reload, stranding or duplicating streams keyed under the drifted value; findByName matches display_name first for the same reason. - idle_timeout_ms=0: the Scrypted-side safety timeout still reclaims ffmpeg/socket but no longer POSTs sleep over the always-on setting. - pending bindingDebounce timers cleared across re-paste (they fired against the dead instance and attached duplicate listeners); releaseDevice drops lastRegisterSig/streamStarting/debounce entries. - start() single-flights bootstrap; createDevice drops its redundant second registerViewport; streamLogger rolls its window on quiet ticks (post-lull rates were diluted) and lastLogUs -> lastLogMs; hoist the JPEG EOI needle + resume-scan offset in the demux loop; postJSON drops the dead 204 check; remove unused sandbox declares and the legacy streams.interval field. - tsconfig: moduleResolution Node -> Bundler (removed in TS 6).
6 daysscrypted: stamp SCRIPT_VERSION = 2af69f7Luke Hoersten1-1/+1
6 daysscrypted: temp_c on the stats line; docs: triple-buffer model + window tuningLuke Hoersten1-1/+5
- Scrypted per-stream stats line gains temp=<c>C from /state temp_c — free thermal trending under streaming load. - README Display strategy rewritten for the tear-free triple-buffer model: why the deferred fb-index reload tears under double buffering, why scan-tracked buffer roles beat vsync-waiting, and the tear_guard_engaged counter. - New 'TCP window + EMAC tuning' section documenting the measured window raise, the EMAC-RX-pool-below-window RTO regression, and the pool >= TCP_WND invariant; stale 'window bump is safe but won't help' backlog text updated. - Memory strategy updated (3 fbs, decoder writes into them directly, stream body ring).
2026-07-01scrypted: stamp SCRIPT_VERSION = 01a588eLuke Hoersten1-1/+1
2026-07-01scrypted: fix stale Streaming header comment (TCP socket, q:v default 1, ↵Luke Hoersten1-5/+7
skip-oldest)
2026-07-01scrypted: stamp SCRIPT_VERSION = 0be8f18Luke Hoersten1-1/+1
2026-07-01scrypted: trim stream logging volumeLuke Hoersten1-18/+30
A chatty camera keeps a viewport streaming for long stretches, and the old logging emitted ~5 cold-start stamps + a 10s window line per ~10s per stream. Cut it down: - keep a single cold-start stamp (first ffmpeg frame); drop spawned / first stdout byte / first socket.write. - gate the 10s window line on noteworthy windows only (socket-not-ready drops, a buffer-cap flush this window, firmware shedding >=2fps, or painted <20fps); healthy 24fps windows print nothing — the per-wake lines already show liveness. - log "registered" only when the pushed config actually changes, not on every 5-minute reregister cycle. lastRegisterSig cleared on stop() for fresh-load parity. No behavior change beyond logging.
2026-06-30scrypted: stamp SCRIPT_VERSION = c6610c1Luke Hoersten1-1/+1
2026-06-30scrypted: remove the pre-stream snapshot entirelyLuke Hoersten1-156/+12
The prebuffered stream now paints in ~0.7s, so the takePicture→transform→POST first-paint bridge was consistently slower than the video it was meant to cover, while adding camera load and a stale-overpaint risk. Drop it: remove pushSnapshot and its call, the shouldPaint gate, and the firstStreamFrameSeen plumbing. On the slow paths (no/cold prebuffer) the panel holds its prior frame until the stream's first frame lands. buildVf stays (used by the live path).
2026-06-30scrypted: stamp SCRIPT_VERSION = 39aeeffLuke Hoersten1-1/+1
2026-06-30scrypted: gate snapshot POST on the live stream not yet paintingLuke Hoersten1-5/+23
Now that the prebuffered stream paints in ~0.7s, the parallel snapshot usually loses the race and, if slow (a Unifi takePicture cache-miss can be several seconds), would land after live video and overpaint it with a staler still. pushSnapshot takes a shouldPaint predicate; startStream passes () => !firstStreamFrameSeen (flipped by the ffmpeg first-frame handler), so a snapshot that finishes after the stream is already painting is dropped before the POST. Preserves the snapshot as a gap-filler for the slow paths (live-edge fallback / cold prebuffer) where the stream hasn't painted yet.
2026-06-30scrypted: stamp SCRIPT_VERSION = 860f539Luke Hoersten1-1/+1
2026-06-30scrypted: strip cold-start/event diagnosticsLuke Hoersten1-110/+7
Remove the temporary instrumentation used to diagnose the event-wake and cold-start work: the evtscan system-wide listener, the attach/trace/streamopt/ src/inputArgs logs, the StartStop entry logs, and ffmpeg -loglevel info/-nostats (back to error). Keep the lightweight one-shot cold-start stamps (spawned → first byte → first frame → first socket.write) and usingPrebuffer in the config line — cheap regression signals — plus all the actual fixes and the prebuffered- stream selection logic.
2026-06-30scrypted: stamp SCRIPT_VERSION = 24d6e90Luke Hoersten1-1/+1
2026-06-30scrypted: fix event wake, teardown, triggers; cut stream cold-start ~6s→~0.7sLuke Hoersten1-47/+390
Event/lifecycle fixes: - attachListener now self-heals: it's idempotent (tracks the bound camera per viewport) and re-runs on registerViewport success, so the camera subscription survives the reload/add storage-attach race that previously left a bound viewport with no listener until a manual re-save. - stop() always drains the global cleaner array (never gates on this.running) and also cancels bindingDebounce timers + clears the stream idle timeout on abort, so StartStop.stop()+start() == a fresh load with no orphaned ffmpeg, sockets, listeners, or intervals. - ignore all camera events while a stream is live or starting (guard moved to the top of handleCameraEvent) — the wake window is anchored to the first event; later events don't queue, relaunch, or extend it. - prune stale childIds whose storage container is gone (deleted device). Triggers: - default to person + doorbell (motion opt-in; doorbell cameras are chatty); doorbell only offered for doorbell-capable cameras. Reconcile stored triggers + re-render settings live when the camera binding changes. Cold-start (wake -> first live frame): ~6s -> ~0.7s. - Root cause: Unifi GOP is ~5s and the rebroadcast RTSP serves live-edge, so ffmpeg waited for the next keyframe. - Fix: select the prebuffered substream by id (smallest that covers the panel, not the 5MP High), request prebuffer >= GOP, and drop -avioflags direct / -fflags nobuffer on the prebuffer path so ffmpeg gulps the buffered-keyframe burst instead of trickling it. Live-edge fallback keeps the low-latency flags. Steady-state g2g unchanged (~50-100ms). Includes temporary diagnostics (evtscan, attach/trace/streamopt/src logs, ffmpeg -loglevel info) to be stripped in the follow-up commit.
2026-06-21scrypted: stamp SCRIPT_VERSION = 1bd5e9fLuke Hoersten1-1/+1
2026-06-21scrypted: subscribe log includes the interface listLuke Hoersten1-1/+1
2026-06-21scrypted: stamp SCRIPT_VERSION = 3a7ddbdLuke Hoersten1-1/+1
2026-06-21scrypted: fix listen() — one call per interface (was passing array, filter ↵Luke Hoersten1-51/+17
broken) ScryptedDevice.listen() takes a single ScryptedInterface | string | EventListenerOptions, not an array. We were passing [BinarySensor, MotionSensor, ObjectDetector] which stringifies to a comma-joined garbage filter, leaking unrelated events (Settings, ...) through and apparently dropping BinarySensor entirely — bell rings never surfaced. Also drops the child-device traversal: confirmed via unifi-protect/src/main.ts that the bell BinarySensor lives on the camera device itself for doorbells.
2026-06-21scrypted: stamp SCRIPT_VERSION = d2b75bdLuke Hoersten1-1/+1
2026-06-21scrypted: diagnostic — enumerate every BinarySensor deviceLuke Hoersten1-10/+10
2026-06-21scrypted: stamp SCRIPT_VERSION = c901984Luke Hoersten1-1/+1
2026-06-21scrypted: log every onBindingChanged re-attach with host/cameraIdLuke Hoersten1-0/+2
2026-06-21scrypted: stamp SCRIPT_VERSION = 5d7549bLuke Hoersten1-1/+1
2026-06-21scrypted: widen doorbell traversal — include BinarySensor siblings + ↵Luke Hoersten1-1/+26
diagnostic
2026-06-21scrypted: stamp SCRIPT_VERSION = f6d8e75Luke Hoersten1-1/+1
2026-06-21scrypted: override parent device type to Bridge (was hardcoded Unknown by ↵Luke Hoersten1-0/+31
Scripts plugin) The 'Unknown' text the user saw above the Status and Controls panel is the device TYPE, not the lifecycle state. Scripts plugin (plugins/core/src/script.ts:65) hardcodes type=ScryptedDeviceType.Unknown when it registers any script device, regardless of what interfaces the loaded class actually implements. Override it from inside the script: call deviceManager.onDeviceDiscovered ourselves with type=Bridge, which semantically fits our DeviceProvider that bridges multiple child viewport devices. The override runs after Scripts plugin's postRunScript-driven discovery so the later call wins. Pass the full interface set explicitly (auto-detection found from method names: Settings/DeviceProvider/DeviceCreator/HttpRequestHandler/ StartStop, plus Scripts base Scriptable+Program) — partial lists drop interfaces. The override is wrapped in try/catch — if the device record's provider mapping changes in a future Scrypted version, we degrade to the old Unknown label rather than the script failing to boot.
2026-06-21scrypted: stamp SCRIPT_VERSION = ba412e5Luke Hoersten1-1/+1
2026-06-21scrypted: drop OnOff — empirically StartStop is what the Scripts UI binds toLuke Hoersten1-46/+16
In v101fb3e we shipped StartStop + OnOff side-by-side to see which the 'Status and Controls' panel actually wired to. The v44c7a63 diagnostic session confirmed: clicking STOP fires stop() (StartStop), not turnOff() (OnOff). User's console showed: lifecycle: start() called (running=false) ... lifecycle: stop() called (running=true) stop: tearing down 1 resources So StartStop alone is the right interface. OnOff just produced a duplicate 'Status and Controls' panel for the same lifecycle. Drop it. Also dropping the verbose lifecycle: ... logging — we know the binding now. The cleanup mechanism is the load-bearing observable ('stop: tearing down N resources' from drainShutdownCleaners). The status text still rendering 'Unknown' (rather than Running/Stopped) is a separate cosmetic concern — possibly the duplicate panels were confusing the UI; with a single StartStop panel left, the displayed status may now reflect this.running correctly. To be verified.
2026-06-21scrypted: stamp SCRIPT_VERSION = 44c7a63Luke Hoersten1-1/+1
2026-06-21scrypted: log end-of-method state for lifecycle calls + bootstrap exceptionLuke Hoersten1-3/+10
start() previously logged only at entry, so a silent throw between 'Scrypted Viewport up' and 'this.running = true' would leave us guessing. Add explicit end-of-method logs with the post-write state, plus a try/catch around bootstrap that surfaces the exception message before re-throwing. This will tell us whether start() reaches its set this.running=true on script load (i.e. whether the prototype state-proxy write fires) or whether bootstrap is silently failing somewhere mid-way.
2026-06-21scrypted: stamp SCRIPT_VERSION = 101fb3eLuke Hoersten1-1/+1
2026-06-21scrypted: add OnOff alongside StartStop + lifecycle logging to identify ↵Luke Hoersten1-17/+41
panel binding The 'Status and Controls' panel in @scrypted/core 0.3.147 was rendering Unknown despite the previous commit adding StartStop. Reading the SDK (sdk/src/index.ts:195 + plugins/core/src/script.ts:47) confirmed how it should work: - ScryptedDeviceBase installs Object.defineProperty getters/setters for every interface property at runtime, so this.running = true propagates through _lazyLoadDeviceState → getDeviceState proxy → system state. - Scripts plugin's mergeHandler auto-detects interfaces by mapping method names: start/stop → StartStop, turnOn/turnOff → OnOff, putSetting/getSettings → Settings, etc. In theory the previous commit was sufficient. To pin down whether the panel is calling something different (older Scrypted UIs lean toward OnOff), this commit: - Implements OnOff alongside StartStop. Both pairs are bound to the same drain/bootstrap logic; whichever the panel calls, the user's intent succeeds. - Initialises this.running = false and this.on = false synchronously in the constructor so the device state record carries a defined value at registration time, instead of Scrypted defaulting to Unknown on undefined. - Logs 'lifecycle: X() called (...)' on every method entry. After the user reloads + clicks STOP / START, the console will reveal exactly which method Scrypted is invoking — or whether neither is. If one of the methods fires, the other is dead code we can drop. If neither fires on the panel's STOP/START button, the panel is a Scripts-runtime control unrelated to device interfaces and we need to look for a different lifecycle hook.
2026-06-21scrypted: stamp SCRIPT_VERSION = 39b0479Luke Hoersten1-1/+1
2026-06-21scrypted: log attachListener early-return when no camera assignedLuke Hoersten1-2/+5
Silent early-return at 'if (!v.cameraId) return;' makes a brand-new viewport with no camera selected look identical (in the console) to one that subscribed successfully — there's no positive or negative signal until you try to fire a camera event. After observing a fresh viewport produce zero output on a doorbell press, switching the early-return to a warning that says 'no camera assigned — open Settings and pick a camera; subscription skipped' so the missing configuration becomes self-evident.
2026-06-21scrypted: stamp SCRIPT_VERSION = 000ab3aLuke Hoersten1-1/+1
2026-06-21scrypted: implement StartStop for proper lifecycle UI + clean tear-downLuke Hoersten1-5/+50
The Scripts 'Status and Controls' panel previously rendered Unknown because the Provider exposed no lifecycle interface. STOP / START in that panel didn't do anything useful — Scrypted's only option was to unload the script entirely, which left the user's re-paste flow relying on the constructor-time globalThis cleanup hack (and even that didn't cover in-flight streams until 1ce49d3). This commit makes the panel real: class ScryptedViewportProvider ... implements ..., StartStop - async start() : drain shutdown cleaners, bootstrap, running=true - async stop() : drain shutdown cleaners, clear viewport+listener+ stream maps, running=false Both methods are idempotent (no-op when already in target state). The constructor calls start() automatically so script load still bootstraps without user action. The private start() method that did the actual provisioning is renamed to bootstrap() to free up the public name for the StartStop contract. registerShutdownCleaners is renamed to drainShutdownCleaners and now takes a 'reason' label so the log line distinguishes 'start: tearing down N resources' (previous load) from 'stop: tearing down N resources' (user-driven). Effect on the workflow the user described: 1. Click STOP in the Scripts UI → stop() drains every resource (streams, listeners, intervals) the provider currently holds. 2. Re-paste the new script. 3. New constructor runs → start() drains anything left behind → bootstrap re-discovers children + re-attaches listeners → ready. No more accumulating ghosts of prior loads.
2026-06-21scrypted: stamp SCRIPT_VERSION = 1ce49d3Luke Hoersten1-1/+1
2026-06-21scrypted: unified shutdown-cleaner array covers streams + listeners + timersLuke Hoersten1-32/+85
Scrypted's Scripts sandbox doesn't release a previous load's resources before constructing a new Provider instance, so anything long-lived survives a re-paste. Previously we hand-rolled cleanup via two separate globalThis hooks: __viewportListenerCleaners (camera event listeners) and __viewportRegisterInterval (the 5-minute re-register timer). Anything else — in-flight ffmpeg children, TCP sockets to the firmware, the per-stream stats interval — leaked across reloads. Visible symptom: re-pasting the script during an active stream left the old stream's ffmpeg + socket running against a dead Provider instance, accumulating across reloads until the host was restarted. Unify all cleanup into one globalThis array, __viewportShutdownCleaners, that every long-lived resource pushes onto. The next start() snapshots and drains it before doing anything else. Resources covered: - 5-minute re-register interval (clearInterval) - Every camera + child-device event listener (reg.removeListener) - Every in-flight stream's AbortController (abort.abort, which the existing abort listeners chain into socket.destroy() + ffmpeg SIGTERM + clearInterval on the stats logger) Each cleanup is removed from the array when the resource naturally ends (stream timeout / stopStream), so the list stays compact across many stream cycles rather than growing forever. Snapshot-before-walk avoids the iteration-skip bug where a stream abort fires its abort listener, which splices the closure out of the same array we're iterating. Snapshot the array, clear the original, then walk the snapshot. Doesn't address the 'Unknown' status panel in Scrypted Scripts UI — that's a separate cosmetic issue (we don't implement a lifecycle interface that reports running state).
2026-06-21scrypted: stamp SCRIPT_VERSION = 356e637Luke Hoersten1-1/+1
2026-06-21scrypted: retry once on Settings-page /state /config fetch failureLuke Hoersten1-4/+23
The Settings 'Status (live)' section reaches the device via two sequential GETs. A transient socket-level failure (httpd worker pool briefly saturated by the active stream connection, mid-reboot window, network jitter) used to leave the page showing 'device: offline / unreachable (fetch failed)' even though the device was fine — a refresh would clear it. One automatic 250 ms-backoff retry on either GET removes the sporadic false positive. The 3 s per-request timeout stays the same, so the worst-case page latency on a genuinely offline device is ~6.5 s (3 + 0.25 + 3) instead of 3 s — acceptable for a deliberate Settings open.
2026-06-21scrypted: stamp SCRIPT_VERSION = 2ca1307Luke Hoersten1-1/+1
2026-06-21scrypted: subscribe to camera child devices (fix Unifi doorbell wake)Luke Hoersten1-17/+39
Unifi doorbell cameras expose the bell button as a child device of the camera (separate nativeId, its own BinarySensor interface), not as a property of the camera itself. The previous code did cam.listen() on the parent camera only, so motion + person events arrived (those fire on the camera itself) but bell-press events never reached handleCameraEvent. HomeKit kept working because Scrypted's HomeKit bridge auto-syncs all child devices; our plugin was silently the only consumer missing the event. Confirmed by the trace log in 3b0ab73 staying silent across a bell press while motion events still printed. Fix: in attachListener, walk systemManager.getDeviceIds() and pick any device with providerId === cam.id as an additional listen target. Subscribe on all of them with the same iface list — listen() no-ops on unsupported ifaces, so we don't have to introspect each child. Tracking changed from Map<nativeId, EventListenerRegister> to Map<nativeId, EventListenerRegister[]> so detach/script-reload cleanup removes every listener, not just the camera's.
2026-06-20scrypted: stamp SCRIPT_VERSION = 3b0ab73Luke Hoersten1-1/+1