Open History to see the last commit
1import { createCanvasFrameSink } from "@t3tools/client-runtime/device/frame";
2import type { DuoControlState } from "@t3tools/client-runtime/device/duo-control";
3import {
4 createDeviceStreamClient,
5 type DeviceScreenSize,
6 type DeviceStreamClient,
7 type DeviceStreamStatus,
8} from "@t3tools/client-runtime/device/stream";
9import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
10import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
11import { Atom } from "effect/reactivity";
12
13import { refreshDeviceHubAccess } from "~/state/device";
14
15export interface DeviceStreamState {
16 readonly status: DeviceStreamStatus;
17 readonly detail: string | undefined;
18 /** A frame arrived during this session, so a reconnect can keep showing it. */
19 readonly hasFrame: boolean;
20 readonly screen: DeviceScreenSize | null;
21 readonly mjpegUrl: string | null;
22 readonly mjpegGeneration: number;
23 readonly input: { readonly connected: boolean; readonly detail?: string };
24 readonly duoControl: DuoControlState;
25 readonly phoneUnavailable: boolean;
26}
27
28export interface DeviceStreamSession {
29 readonly stream: DeviceStreamClient;
30 /** The stream draws here; the view mounts it and the 3D viewers sample it. */
31 readonly canvas: HTMLCanvasElement;
32 readonly setFrameListener: (listener: (() => void) | null) => void;
33 /** Called when the hub rejects a Duo control, so the 3D viewer drops its optimistic pose. */
34 readonly setControlRejectedListener: (listener: (() => void) | null) => void;
35 readonly markPhoneUnavailable: () => void;
36 readonly reconnect: () => void;
37 readonly state: DeviceStreamState;
38}
39
40export interface DeviceStreamKey {
41 readonly environmentId: EnvironmentId;
42 readonly hostId: string;
43 readonly platform: DevicePlatform;
44 readonly deviceId: string;
45 readonly access: DeviceHubAccess;
46 /** Each mounted view owns its own client: one canvas cannot be in two places. */
47 readonly viewId: string;
48}
49
50export const IDLE_DEVICE_STREAM_STATE: DeviceStreamState = {
51 status: "connecting",
52 detail: undefined,
53 hasFrame: false,
54 screen: null,
55 mjpegUrl: null,
56 mjpegGeneration: 0,
57 input: { connected: false },
58 duoControl: { pending: false, requested: null, error: null },
59 phoneUnavailable: false,
60};
61
62export const deviceScreenKey = (environmentId: EnvironmentId, hostId: string, deviceId: string) =>
63 `${environmentId}\u0000${hostId}\u0000${deviceId}`;
64
65/**
66 * The screen one view's stream last reported, null while that view streams nothing.
67 * Keyed by view, not device: two views of one device stream independently, and one
68 * ending must not clear the other's size. The mini player lays out its frame from it.
69 */
70export const deviceStreamScreenAtom = Atom.family((viewId: string) =>
71 Atom.make<DeviceScreenSize | null>(null).pipe(Atom.withLabel(`device-stream-screen:${viewId}`)),
72);
73
74/** A device's video and input connection, live while a view reads it. */
75export const deviceStreamSessionAtom = Atom.family((key: DeviceStreamKey) =>
76 Atom.make((get): DeviceStreamSession => {
77 const screenAtom = deviceStreamScreenAtom(key.viewId);
78 const canvas = document.createElement("canvas");
79 canvas.style.display = "block";
80 canvas.style.width = "100%";
81 canvas.style.height = "100%";
82 let frameListener: (() => void) | null = null;
83 let controlRejectedListener: (() => void) | null = null;
84 let state = IDLE_DEVICE_STREAM_STATE;
85 let session: DeviceStreamSession;
86 const update = (patch: Partial<DeviceStreamState>) => {
87 state = { ...state, ...patch };
88 session = { ...session, state };
89 get.setSelf(session);
90 };
91 const client = createDeviceStreamClient(
92 { platform: key.platform, deviceId: key.deviceId, access: key.access },
93 createCanvasFrameSink(canvas, () => frameListener?.()),
94 {
95 onDuoControl: (duoControl) => {
96 if (duoControl.error && duoControl.error !== state.duoControl.error)
97 controlRejectedListener?.();
98 update({ duoControl });
99 },
100 onDuoUnavailable: () => update({ phoneUnavailable: true }),
101 onStatus: (status, detail) =>
102 update({ status, detail, ...(status === "streaming" ? { hasFrame: true } : {}) }),
103 onScreen: (screen) => {
104 get.set(screenAtom, screen);
105 update({ screen });
106 },
107 onUnauthorized: () => refreshDeviceHubAccess(key.environmentId),
108 onMjpegFallback: (mjpegUrl) =>
109 update({ mjpegUrl, mjpegGeneration: state.mjpegGeneration + 1 }),
110 onCanvasVideo: () => update({ mjpegUrl: null }),
111 onInputConnected: (connected, detail) =>
112 update({ input: { connected, ...(detail ? { detail } : {}) } }),
113 },
114 );
115 session = {
116 stream: client,
117 canvas,
118 setFrameListener: (listener) => {
119 frameListener = listener;
120 },
121 setControlRejectedListener: (listener) => {
122 controlRejectedListener = listener;
123 },
124 markPhoneUnavailable: () => update({ phoneUnavailable: true }),
125 reconnect: () => {
126 client.stop();
127 update({ phoneUnavailable: false });
128 client.start();
129 },
130 state,
131 };
132 get.addFinalizer(() => {
133 client.stop();
134 get.registry.set(screenAtom, null);
135 });
136 client.start();
137 return session;
138 }).pipe(Atom.withLabel(`device-stream:${key.platform}:${key.deviceId}`)),
139);