@myrialabs/clopen 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/.env.example +4 -4
  2. package/backend/engine/adapters/opencode/server.ts +72 -33
  3. package/backend/tunnel/cloudflared/binary.ts +153 -0
  4. package/backend/tunnel/cloudflared/index.ts +21 -0
  5. package/backend/tunnel/cloudflared/tunnel.ts +389 -0
  6. package/backend/tunnel/global-tunnel-manager.ts +538 -152
  7. package/backend/tunnel/project-tunnel-manager.ts +6 -14
  8. package/backend/tunnel/tunnel-config.ts +234 -0
  9. package/backend/utils/env.ts +5 -5
  10. package/backend/ws/tunnel/config.ts +108 -0
  11. package/backend/ws/tunnel/index.ts +3 -1
  12. package/backend/ws/tunnel/operations.ts +290 -43
  13. package/bin/clopen.ts +21 -298
  14. package/dist/assets/addon-clipboard-wHJhZAA4.js +1 -0
  15. package/dist/assets/addon-fit-DX4qG4td.js +1 -0
  16. package/dist/assets/addon-ligatures-DpDY8N_X.js +2 -0
  17. package/dist/assets/addon-unicode11-Bt8F3D7-.js +7 -0
  18. package/dist/assets/addon-web-links-DIbG5aQx.js +1 -0
  19. package/dist/assets/index-C-eR9PGW.js +2 -0
  20. package/dist/assets/main-D1IISCsM.js +247 -0
  21. package/dist/assets/main-DzSwlujO.css +1 -0
  22. package/dist/assets/xterm-B-qIQCd3.js +16 -0
  23. package/{index.html → dist/index.html} +2 -1
  24. package/package.json +11 -3
  25. package/scripts/start.ts +3 -3
  26. package/shared/utils/logger.ts +1 -1
  27. package/.dockerignore +0 -5
  28. package/.github/workflows/ci.yml +0 -86
  29. package/CONTRIBUTING.md +0 -188
  30. package/bun.lock +0 -1131
  31. package/docker-compose.yml +0 -31
  32. package/frontend/App.svelte +0 -76
  33. package/frontend/app-environment.ts +0 -10
  34. package/frontend/app.css +0 -313
  35. package/frontend/components/auth/InvitePage.svelte +0 -215
  36. package/frontend/components/auth/LoginPage.svelte +0 -129
  37. package/frontend/components/auth/SetupPage.svelte +0 -1054
  38. package/frontend/components/chat/ChatInterface.svelte +0 -426
  39. package/frontend/components/chat/formatters/ErrorMessage.svelte +0 -57
  40. package/frontend/components/chat/formatters/MessageFormatter.svelte +0 -244
  41. package/frontend/components/chat/formatters/TextMessage.svelte +0 -383
  42. package/frontend/components/chat/formatters/Tools.svelte +0 -79
  43. package/frontend/components/chat/formatters/index.ts +0 -3
  44. package/frontend/components/chat/input/ChatInput.svelte +0 -492
  45. package/frontend/components/chat/input/components/ChatInputActions.svelte +0 -88
  46. package/frontend/components/chat/input/components/DragDropOverlay.svelte +0 -30
  47. package/frontend/components/chat/input/components/EditModeIndicator.svelte +0 -33
  48. package/frontend/components/chat/input/components/EngineModelPicker.svelte +0 -642
  49. package/frontend/components/chat/input/components/FileAttachmentPreview.svelte +0 -48
  50. package/frontend/components/chat/input/components/LoadingIndicator.svelte +0 -43
  51. package/frontend/components/chat/input/composables/use-animations.svelte.ts +0 -217
  52. package/frontend/components/chat/input/composables/use-chat-actions.svelte.ts +0 -152
  53. package/frontend/components/chat/input/composables/use-file-handling.svelte.ts +0 -216
  54. package/frontend/components/chat/input/composables/use-input-state.svelte.ts +0 -357
  55. package/frontend/components/chat/input/composables/use-textarea-resize.svelte.ts +0 -69
  56. package/frontend/components/chat/message/ChatMessage.svelte +0 -509
  57. package/frontend/components/chat/message/ChatMessages.svelte +0 -553
  58. package/frontend/components/chat/message/DateSeparator.svelte +0 -86
  59. package/frontend/components/chat/message/MessageBubble.svelte +0 -114
  60. package/frontend/components/chat/message/MessageHeader.svelte +0 -143
  61. package/frontend/components/chat/modal/DebugModal.svelte +0 -59
  62. package/frontend/components/chat/shared/index.ts +0 -2
  63. package/frontend/components/chat/shared/utils.ts +0 -116
  64. package/frontend/components/chat/tools/AgentTool.svelte +0 -96
  65. package/frontend/components/chat/tools/AskUserQuestionTool.svelte +0 -391
  66. package/frontend/components/chat/tools/BashOutputTool.svelte +0 -35
  67. package/frontend/components/chat/tools/BashTool.svelte +0 -51
  68. package/frontend/components/chat/tools/CustomMcpTool.svelte +0 -141
  69. package/frontend/components/chat/tools/EditTool.svelte +0 -48
  70. package/frontend/components/chat/tools/EnterPlanModeTool.svelte +0 -24
  71. package/frontend/components/chat/tools/ExitPlanModeTool.svelte +0 -29
  72. package/frontend/components/chat/tools/GlobTool.svelte +0 -51
  73. package/frontend/components/chat/tools/GrepTool.svelte +0 -90
  74. package/frontend/components/chat/tools/ListMcpResourcesTool.svelte +0 -31
  75. package/frontend/components/chat/tools/NotebookEditTool.svelte +0 -38
  76. package/frontend/components/chat/tools/ReadMcpResourceTool.svelte +0 -34
  77. package/frontend/components/chat/tools/ReadTool.svelte +0 -41
  78. package/frontend/components/chat/tools/SkillTool.svelte +0 -21
  79. package/frontend/components/chat/tools/TaskStopTool.svelte +0 -26
  80. package/frontend/components/chat/tools/TaskTool.svelte +0 -64
  81. package/frontend/components/chat/tools/TodoWriteTool.svelte +0 -75
  82. package/frontend/components/chat/tools/WebFetchTool.svelte +0 -35
  83. package/frontend/components/chat/tools/WebSearchTool.svelte +0 -84
  84. package/frontend/components/chat/tools/WriteTool.svelte +0 -33
  85. package/frontend/components/chat/tools/components/CodeBlock.svelte +0 -79
  86. package/frontend/components/chat/tools/components/DiffBlock.svelte +0 -408
  87. package/frontend/components/chat/tools/components/FileHeader.svelte +0 -59
  88. package/frontend/components/chat/tools/components/InfoLine.svelte +0 -19
  89. package/frontend/components/chat/tools/components/StatsBadges.svelte +0 -27
  90. package/frontend/components/chat/tools/components/TerminalCommand.svelte +0 -61
  91. package/frontend/components/chat/tools/components/index.ts +0 -7
  92. package/frontend/components/chat/tools/index.ts +0 -30
  93. package/frontend/components/chat/widgets/ContextIndicator.svelte +0 -186
  94. package/frontend/components/chat/widgets/FloatingTodoList.svelte +0 -367
  95. package/frontend/components/checkpoint/ConflictResolutionModal.svelte +0 -189
  96. package/frontend/components/checkpoint/TimelineModal.svelte +0 -447
  97. package/frontend/components/checkpoint/timeline/TimelineEdge.svelte +0 -26
  98. package/frontend/components/checkpoint/timeline/TimelineGraph.svelte +0 -87
  99. package/frontend/components/checkpoint/timeline/TimelineNode.svelte +0 -119
  100. package/frontend/components/checkpoint/timeline/TimelineVersionGroup.svelte +0 -59
  101. package/frontend/components/checkpoint/timeline/animation.ts +0 -168
  102. package/frontend/components/checkpoint/timeline/config.ts +0 -44
  103. package/frontend/components/checkpoint/timeline/graph-builder.ts +0 -304
  104. package/frontend/components/checkpoint/timeline/types.ts +0 -69
  105. package/frontend/components/checkpoint/timeline/utils.ts +0 -53
  106. package/frontend/components/common/display/AvatarBubble.svelte +0 -56
  107. package/frontend/components/common/display/Button.svelte +0 -71
  108. package/frontend/components/common/display/Card.svelte +0 -102
  109. package/frontend/components/common/display/Icon.svelte +0 -58
  110. package/frontend/components/common/display/PageTemplate.svelte +0 -76
  111. package/frontend/components/common/display/ProjectUserAvatars.svelte +0 -79
  112. package/frontend/components/common/display/ThemeToggle.svelte +0 -44
  113. package/frontend/components/common/editor/MonacoEditor.svelte +0 -583
  114. package/frontend/components/common/feedback/Alert.svelte +0 -139
  115. package/frontend/components/common/feedback/ConnectionBanner.svelte +0 -55
  116. package/frontend/components/common/feedback/LoadingScreen.svelte +0 -52
  117. package/frontend/components/common/feedback/LoadingSpinner.svelte +0 -48
  118. package/frontend/components/common/feedback/NotificationToast.svelte +0 -128
  119. package/frontend/components/common/feedback/RestartRequiredModal.svelte +0 -53
  120. package/frontend/components/common/feedback/UpdateBanner.svelte +0 -99
  121. package/frontend/components/common/form/Checkbox.svelte +0 -48
  122. package/frontend/components/common/form/FolderBrowser.svelte +0 -856
  123. package/frontend/components/common/form/Input.svelte +0 -72
  124. package/frontend/components/common/form/ModelSelector.svelte +0 -110
  125. package/frontend/components/common/form/Select.svelte +0 -98
  126. package/frontend/components/common/form/Textarea.svelte +0 -80
  127. package/frontend/components/common/lucide-icons.ts +0 -1642
  128. package/frontend/components/common/material-icons.ts +0 -1082
  129. package/frontend/components/common/media/MediaPreview.svelte +0 -187
  130. package/frontend/components/common/overlay/Dialog.svelte +0 -251
  131. package/frontend/components/common/overlay/Lightbox.svelte +0 -233
  132. package/frontend/components/common/overlay/Modal.svelte +0 -177
  133. package/frontend/components/common/overlay/ModalProvider.svelte +0 -28
  134. package/frontend/components/common/xterm/XTerm.svelte +0 -743
  135. package/frontend/components/common/xterm/index.ts +0 -16
  136. package/frontend/components/common/xterm/terminal-config.ts +0 -68
  137. package/frontend/components/common/xterm/types.ts +0 -32
  138. package/frontend/components/common/xterm/xterm-service.ts +0 -437
  139. package/frontend/components/files/FileNode.svelte +0 -327
  140. package/frontend/components/files/FileTree.svelte +0 -690
  141. package/frontend/components/files/FileViewer.svelte +0 -551
  142. package/frontend/components/files/SearchResults.svelte +0 -303
  143. package/frontend/components/git/BranchManager.svelte +0 -446
  144. package/frontend/components/git/ChangesSection.svelte +0 -196
  145. package/frontend/components/git/CommitForm.svelte +0 -128
  146. package/frontend/components/git/ConflictResolver.svelte +0 -158
  147. package/frontend/components/git/DiffViewer.svelte +0 -298
  148. package/frontend/components/git/FileChangeItem.svelte +0 -119
  149. package/frontend/components/git/GitButton.svelte +0 -33
  150. package/frontend/components/git/GitLog.svelte +0 -401
  151. package/frontend/components/git/GitModal.svelte +0 -80
  152. package/frontend/components/history/HistoryModal.svelte +0 -602
  153. package/frontend/components/history/HistoryView.svelte +0 -561
  154. package/frontend/components/index.ts +0 -34
  155. package/frontend/components/preview/browser/BrowserPreview.svelte +0 -558
  156. package/frontend/components/preview/browser/components/Canvas.svelte +0 -1523
  157. package/frontend/components/preview/browser/components/ConsolePanel.svelte +0 -757
  158. package/frontend/components/preview/browser/components/Container.svelte +0 -507
  159. package/frontend/components/preview/browser/components/ContextMenu.svelte +0 -236
  160. package/frontend/components/preview/browser/components/SelectDropdown.svelte +0 -224
  161. package/frontend/components/preview/browser/components/Toolbar.svelte +0 -358
  162. package/frontend/components/preview/browser/components/VirtualCursor.svelte +0 -36
  163. package/frontend/components/preview/browser/core/cleanup.svelte.ts +0 -155
  164. package/frontend/components/preview/browser/core/coordinator.svelte.ts +0 -885
  165. package/frontend/components/preview/browser/core/interactions.svelte.ts +0 -113
  166. package/frontend/components/preview/browser/core/mcp-handlers.svelte.ts +0 -331
  167. package/frontend/components/preview/browser/core/native-ui-handlers.svelte.ts +0 -391
  168. package/frontend/components/preview/browser/core/stream-handler.svelte.ts +0 -288
  169. package/frontend/components/preview/browser/core/tab-manager.svelte.ts +0 -210
  170. package/frontend/components/preview/browser/core/tab-operations.svelte.ts +0 -241
  171. package/frontend/components/preview/index.ts +0 -2
  172. package/frontend/components/settings/SettingsModal.svelte +0 -263
  173. package/frontend/components/settings/SettingsView.svelte +0 -50
  174. package/frontend/components/settings/account/AccountSettings.svelte +0 -5
  175. package/frontend/components/settings/admin/InviteManagement.svelte +0 -239
  176. package/frontend/components/settings/admin/UserManagement.svelte +0 -127
  177. package/frontend/components/settings/appearance/AppearanceSettings.svelte +0 -104
  178. package/frontend/components/settings/appearance/LayoutPresetSettings.svelte +0 -160
  179. package/frontend/components/settings/appearance/LayoutPreview.svelte +0 -76
  180. package/frontend/components/settings/engines/AIEnginesSettings.svelte +0 -917
  181. package/frontend/components/settings/general/AdvancedSettings.svelte +0 -193
  182. package/frontend/components/settings/general/AuthModeSettings.svelte +0 -229
  183. package/frontend/components/settings/general/DataManagementSettings.svelte +0 -89
  184. package/frontend/components/settings/general/GeneralSettings.svelte +0 -20
  185. package/frontend/components/settings/general/UpdateSettings.svelte +0 -130
  186. package/frontend/components/settings/git/GitSettings.svelte +0 -392
  187. package/frontend/components/settings/model/EngineModelPicker.svelte +0 -284
  188. package/frontend/components/settings/model/ModelSettings.svelte +0 -240
  189. package/frontend/components/settings/notifications/NotificationSettings.svelte +0 -205
  190. package/frontend/components/settings/security/SecuritySettings.svelte +0 -10
  191. package/frontend/components/settings/system/SystemSettings.svelte +0 -10
  192. package/frontend/components/settings/user/UserSettings.svelte +0 -270
  193. package/frontend/components/terminal/Terminal.svelte +0 -338
  194. package/frontend/components/terminal/TerminalTabs.svelte +0 -88
  195. package/frontend/components/terminal/TerminalView.svelte +0 -55
  196. package/frontend/components/tunnel/TunnelActive.svelte +0 -157
  197. package/frontend/components/tunnel/TunnelButton.svelte +0 -60
  198. package/frontend/components/tunnel/TunnelInactive.svelte +0 -287
  199. package/frontend/components/tunnel/TunnelModal.svelte +0 -48
  200. package/frontend/components/tunnel/TunnelQRCode.svelte +0 -49
  201. package/frontend/components/workspace/DesktopNavigator.svelte +0 -445
  202. package/frontend/components/workspace/MobileNavigator.svelte +0 -427
  203. package/frontend/components/workspace/PanelContainer.svelte +0 -100
  204. package/frontend/components/workspace/PanelHeader.svelte +0 -664
  205. package/frontend/components/workspace/ViewMenu.svelte +0 -146
  206. package/frontend/components/workspace/WorkspaceLayout.svelte +0 -169
  207. package/frontend/components/workspace/layout/DesktopLayout.svelte +0 -15
  208. package/frontend/components/workspace/layout/MobileLayout.svelte +0 -17
  209. package/frontend/components/workspace/layout/split-pane/Container.svelte +0 -42
  210. package/frontend/components/workspace/layout/split-pane/Handle.svelte +0 -85
  211. package/frontend/components/workspace/layout/split-pane/Layout.svelte +0 -62
  212. package/frontend/components/workspace/panels/ChatPanel.svelte +0 -282
  213. package/frontend/components/workspace/panels/FilesPanel.svelte +0 -1376
  214. package/frontend/components/workspace/panels/GitPanel.svelte +0 -1601
  215. package/frontend/components/workspace/panels/PreviewPanel.svelte +0 -153
  216. package/frontend/components/workspace/panels/TerminalPanel.svelte +0 -73
  217. package/frontend/main.ts +0 -17
  218. package/frontend/services/chat/chat.service.ts +0 -975
  219. package/frontend/services/chat/index.ts +0 -7
  220. package/frontend/services/notification/global-stream-monitor.ts +0 -120
  221. package/frontend/services/notification/index.ts +0 -8
  222. package/frontend/services/notification/push.service.ts +0 -144
  223. package/frontend/services/notification/sound.service.ts +0 -127
  224. package/frontend/services/preview/browser/browser-console.service.ts +0 -61
  225. package/frontend/services/preview/browser/browser-webcodecs.service.ts +0 -1643
  226. package/frontend/services/preview/browser/mcp-integration.svelte.ts +0 -67
  227. package/frontend/services/preview/index.ts +0 -23
  228. package/frontend/services/project/index.ts +0 -8
  229. package/frontend/services/project/status.service.ts +0 -170
  230. package/frontend/services/snapshot/snapshot.service.ts +0 -86
  231. package/frontend/services/terminal/background/index.ts +0 -130
  232. package/frontend/services/terminal/background/session-restore.ts +0 -274
  233. package/frontend/services/terminal/background/stream-manager.ts +0 -286
  234. package/frontend/services/terminal/index.ts +0 -14
  235. package/frontend/services/terminal/persistence.service.ts +0 -260
  236. package/frontend/services/terminal/project.service.ts +0 -1004
  237. package/frontend/services/terminal/session.service.ts +0 -364
  238. package/frontend/services/terminal/terminal.service.ts +0 -379
  239. package/frontend/stores/core/app.svelte.ts +0 -296
  240. package/frontend/stores/core/files.svelte.ts +0 -87
  241. package/frontend/stores/core/presence.svelte.ts +0 -128
  242. package/frontend/stores/core/projects.svelte.ts +0 -325
  243. package/frontend/stores/core/sessions.svelte.ts +0 -452
  244. package/frontend/stores/features/auth.svelte.ts +0 -336
  245. package/frontend/stores/features/claude-accounts.svelte.ts +0 -58
  246. package/frontend/stores/features/models.svelte.ts +0 -89
  247. package/frontend/stores/features/settings.svelte.ts +0 -151
  248. package/frontend/stores/features/terminal.svelte.ts +0 -747
  249. package/frontend/stores/features/tunnel.svelte.ts +0 -163
  250. package/frontend/stores/features/user.svelte.ts +0 -54
  251. package/frontend/stores/ui/chat-input.svelte.ts +0 -57
  252. package/frontend/stores/ui/chat-model.svelte.ts +0 -61
  253. package/frontend/stores/ui/connection.svelte.ts +0 -40
  254. package/frontend/stores/ui/dialog.svelte.ts +0 -59
  255. package/frontend/stores/ui/edit-mode.svelte.ts +0 -214
  256. package/frontend/stores/ui/notification.svelte.ts +0 -169
  257. package/frontend/stores/ui/settings-modal.svelte.ts +0 -109
  258. package/frontend/stores/ui/theme.svelte.ts +0 -179
  259. package/frontend/stores/ui/todo-panel.svelte.ts +0 -39
  260. package/frontend/stores/ui/update.svelte.ts +0 -159
  261. package/frontend/stores/ui/workspace.svelte.ts +0 -798
  262. package/frontend/utils/chat/date-separator.ts +0 -39
  263. package/frontend/utils/chat/message-grouper.ts +0 -329
  264. package/frontend/utils/chat/message-processor.ts +0 -169
  265. package/frontend/utils/chat/tool-handler.ts +0 -287
  266. package/frontend/utils/chat/virtual-scroll.svelte.ts +0 -142
  267. package/frontend/utils/click-outside.ts +0 -20
  268. package/frontend/utils/context-manager.ts +0 -55
  269. package/frontend/utils/file-icon-mappings.ts +0 -769
  270. package/frontend/utils/file-type.ts +0 -68
  271. package/frontend/utils/folder-icon-mappings.ts +0 -1030
  272. package/frontend/utils/git-status.ts +0 -68
  273. package/frontend/utils/native-ui.ts +0 -73
  274. package/frontend/utils/platform.ts +0 -113
  275. package/frontend/utils/port-check.ts +0 -65
  276. package/frontend/utils/preview-constants.ts +0 -45
  277. package/frontend/utils/terminal-formatter.ts +0 -207
  278. package/frontend/utils/theme.ts +0 -6
  279. package/frontend/utils/tree-visualizer.ts +0 -320
  280. package/frontend/utils/ws.ts +0 -90
  281. package/scripts/dev.ts +0 -46
  282. package/scripts/generate-icons.ts +0 -87
  283. package/svelte.config.js +0 -20
  284. package/tsconfig.json +0 -41
  285. package/vite.config.ts +0 -51
  286. /package/{static → dist}/audio/notification.ogg +0 -0
  287. /package/{static → dist}/favicon.svg +0 -0
  288. /package/{static → dist}/fonts/dm-sans/dm-sans-italic-latin-ext.woff2 +0 -0
  289. /package/{static → dist}/fonts/dm-sans/dm-sans-italic-latin.woff2 +0 -0
  290. /package/{static → dist}/fonts/dm-sans/dm-sans-normal-latin-ext.woff2 +0 -0
  291. /package/{static → dist}/fonts/dm-sans/dm-sans-normal-latin.woff2 +0 -0
  292. /package/{static → dist}/fonts/dm-sans.css +0 -0
  293. /package/{static → dist}/manifest.json +0 -0
@@ -1,1643 +0,0 @@
1
- /**
2
- * Browser WebCodecs Service
3
- *
4
- * Client-side service for receiving WebCodecs-encoded video/audio via DataChannel.
5
- * Achieves ultra low-latency (~20-40ms) with lower bandwidth than traditional WebRTC.
6
- *
7
- * Flow:
8
- * 1. Request offer from server (headless browser creates offer with DataChannel)
9
- * 2. Create RTCPeerConnection and set remote description (offer)
10
- * 3. Create and send answer
11
- * 4. Exchange ICE candidates
12
- * 5. Receive encoded chunks via DataChannel
13
- * 6. Decode with VideoDecoder + AudioDecoder
14
- * 7. Render video to canvas, play audio
15
- */
16
-
17
- import ws from '$frontend/utils/ws';
18
- import { debug } from '$shared/utils/logger';
19
-
20
- export interface BrowserWebCodecsStreamStats {
21
- isConnected: boolean;
22
- connectionState: RTCPeerConnectionState;
23
- iceConnectionState: RTCIceConnectionState;
24
- videoBytesReceived: number;
25
- audioBytesReceived: number;
26
- videoFramesReceived: number;
27
- audioFramesReceived: number;
28
- videoFramesDecoded: number;
29
- audioFramesDecoded: number;
30
- videoFramesDropped: number;
31
- audioFramesDropped: number;
32
- frameWidth: number;
33
- frameHeight: number;
34
- // Bandwidth stats
35
- videoBitrate: number; // bits per second
36
- audioBitrate: number; // bits per second
37
- totalBitrate: number; // bits per second
38
- totalBandwidthMBps: number; // MB per second
39
- // Codec info
40
- videoCodec: string;
41
- audioCodec: string;
42
- // First frame status
43
- firstFrameRendered: boolean;
44
- }
45
-
46
- export class BrowserWebCodecsService {
47
- private projectId: string; // REQUIRED for project isolation
48
- private sessionId: string | null = null;
49
- private peerConnection: RTCPeerConnection | null = null;
50
- private dataChannel: RTCDataChannel | null = null;
51
- private videoDecoder: VideoDecoder | null = null;
52
- private audioDecoder: AudioDecoder | null = null;
53
- private audioContext: AudioContext | null = null;
54
- private canvas: HTMLCanvasElement | null = null;
55
- private ctx: CanvasRenderingContext2D | null = null;
56
- private isConnected = false;
57
- private isCleaningUp = false;
58
-
59
- // Frame rendering optimization with timestamp-based scheduling
60
- private pendingFrame: VideoFrame | null = null;
61
- private isRenderingFrame = false;
62
- private renderFrameId: number | null = null;
63
- private lastFrameTime = 0;
64
- private startTime = 0;
65
- private firstFrameTimestamp = 0; // Timestamp of first frame (for relative timing)
66
-
67
- // AV Sync: Shared timeline reference
68
- // When first video frame arrives, we establish: realTime = streamTimestamp mapping
69
- private syncEstablished = false;
70
- private syncRealTimeOrigin = 0; // performance.now() when first video frame decoded
71
- private syncStreamTimestamp = 0; // stream timestamp of first video frame (microseconds)
72
- private lastVideoTimestamp = 0; // Last rendered video timestamp for audio sync
73
- private lastVideoRealTime = 0; // performance.now() when last video frame was rendered
74
-
75
- // Audio playback scheduling
76
- private nextAudioPlayTime = 0; // When the next audio chunk should play
77
- private audioBufferQueue: Array<{ buffer: AudioBuffer; scheduledTime: number }> = [];
78
- private maxAudioQueueSize = 10; // Limit queue to prevent audio lag
79
- private audioSyncInitialized = false; // Track if audio sync is initialized
80
- private audioCalibrationSamples = 0; // Count calibration samples for initial sync
81
- private audioOffsetAccumulator = 0; // Accumulate offset during calibration
82
- private readonly CALIBRATION_SAMPLES = 5; // Number of samples needed for calibration
83
- private calibratedAudioOffset = 0; // Final calibrated offset in seconds
84
-
85
- // Codec configuration
86
- private videoCodecConfig: VideoDecoderConfig | null = null;
87
- private audioCodecConfig: AudioDecoderConfig | null = null;
88
-
89
- // Stats tracking
90
- private stats: BrowserWebCodecsStreamStats = {
91
- isConnected: false,
92
- connectionState: 'new',
93
- iceConnectionState: 'new',
94
- videoBytesReceived: 0,
95
- audioBytesReceived: 0,
96
- videoFramesReceived: 0,
97
- audioFramesReceived: 0,
98
- videoFramesDecoded: 0,
99
- audioFramesDecoded: 0,
100
- videoFramesDropped: 0,
101
- audioFramesDropped: 0,
102
- frameWidth: 0,
103
- frameHeight: 0,
104
- videoBitrate: 0,
105
- audioBitrate: 0,
106
- totalBitrate: 0,
107
- totalBandwidthMBps: 0,
108
- videoCodec: 'unknown',
109
- audioCodec: 'unknown',
110
- firstFrameRendered: false
111
- };
112
-
113
- // Bandwidth tracking
114
- private lastVideoBytesReceived = 0;
115
- private lastAudioBytesReceived = 0;
116
- private lastStatsTime = 0;
117
-
118
- // ICE servers - empty for local connections (both peers on same machine)
119
- // STUN servers are unnecessary for localhost and add 100-500ms ICE gathering latency
120
- private readonly iceServers: RTCIceServer[] = [];
121
-
122
- // Callbacks
123
- private onConnectionChange: ((connected: boolean) => void) | null = null;
124
- private onConnectionFailed: (() => void) | null = null;
125
- private onNavigationReconnect: (() => void) | null = null; // Fast reconnection after navigation
126
- private onReconnectingStart: (() => void) | null = null; // Signals reconnecting state started (for UI)
127
- private onFirstFrame: (() => void) | null = null; // Fires immediately when first frame is decoded
128
- private onError: ((error: Error) => void) | null = null;
129
- private onStats: ((stats: BrowserWebCodecsStreamStats) => void) | null = null;
130
- private onCursorChange: ((cursor: string) => void) | null = null;
131
-
132
- // Navigation state - when true, DataChannel close is expected and recovery is suppressed
133
- private isNavigating = false;
134
- private navigationCleanupFn: (() => void) | null = null;
135
- private navigationSafetyTimeout: ReturnType<typeof setTimeout> | null = null;
136
-
137
- // SPA navigation frame freeze — holds last frame briefly during SPA transitions
138
- private spaFreezeUntil = 0;
139
-
140
- // WebSocket cleanup
141
- private wsCleanupFunctions: Array<() => void> = [];
142
-
143
- // Stats interval
144
- private statsIntervalId: ReturnType<typeof setInterval> | null = null;
145
-
146
- // Bandwidth logging interval
147
- private bandwidthLogIntervalId: ReturnType<typeof setInterval> | null = null;
148
-
149
- // User gesture listener for AudioContext resume (needed after page refresh)
150
- private userGestureHandler: (() => void) | null = null;
151
-
152
- constructor(projectId: string) {
153
- if (!projectId) {
154
- throw new Error('projectId is required for BrowserWebCodecsService');
155
- }
156
- this.projectId = projectId;
157
-
158
- // Register a one-time user gesture listener to resume suspended AudioContext.
159
- // After page refresh, AudioContext cannot resume without a user gesture.
160
- // This listener fires on the first click/keydown and resumes it.
161
- this.userGestureHandler = () => {
162
- if (this.audioContext && this.audioContext.state === 'suspended') {
163
- this.audioContext.resume().catch(() => {});
164
- debug.log('webcodecs', 'AudioContext resumed via user gesture');
165
- }
166
- // Remove listeners after first successful gesture
167
- if (this.userGestureHandler) {
168
- document.removeEventListener('click', this.userGestureHandler);
169
- document.removeEventListener('keydown', this.userGestureHandler);
170
- this.userGestureHandler = null;
171
- }
172
- };
173
- document.addEventListener('click', this.userGestureHandler, { once: false });
174
- document.addEventListener('keydown', this.userGestureHandler, { once: false });
175
- }
176
-
177
- /**
178
- * Check if WebCodecs is supported
179
- */
180
- static isSupported(): boolean {
181
- return (
182
- typeof VideoDecoder !== 'undefined' &&
183
- typeof AudioDecoder !== 'undefined' &&
184
- typeof RTCPeerConnection !== 'undefined'
185
- );
186
- }
187
-
188
- /**
189
- * Start WebCodecs streaming for a preview session
190
- */
191
- async startStreaming(sessionId: string, canvas: HTMLCanvasElement): Promise<boolean> {
192
- debug.log('webcodecs', `[DIAG] startStreaming called: sessionId=${sessionId}, isConnected=${this.isConnected}, existingSessionId=${this.sessionId}`);
193
-
194
- if (!BrowserWebCodecsService.isSupported()) {
195
- debug.error('webcodecs', 'Not supported in this browser');
196
- if (this.onError) {
197
- this.onError(new Error('WebCodecs not supported'));
198
- }
199
- return false;
200
- }
201
-
202
- // Pre-initialize AudioContext NOW, during user gesture context.
203
- // Browsers require a user gesture to start AudioContext — creating it
204
- // later (e.g. when first audio chunk arrives) results in a permanently
205
- // suspended context that never plays audio.
206
- if (!this.audioContext || this.audioContext.state === 'closed') {
207
- this.audioContext = new AudioContext({ sampleRate: 48000 });
208
- }
209
- if (this.audioContext.state === 'suspended') {
210
- // Fire-and-forget: don't await — after page refresh (no user gesture),
211
- // resume() returns a promise that NEVER resolves until user interacts.
212
- // Awaiting it would block streaming indefinitely. Audio will resume
213
- // automatically on first user interaction via the safety net in playAudioFrame.
214
- this.audioContext.resume().catch(() => {});
215
- }
216
-
217
- // Clean up any existing connection
218
- if (this.peerConnection || this.isConnected || this.sessionId) {
219
- debug.log('webcodecs', 'Cleaning up previous connection');
220
- await this.cleanupConnection();
221
- }
222
-
223
- this.isCleaningUp = false;
224
- this.stats.firstFrameRendered = false;
225
-
226
- this.sessionId = sessionId;
227
- this.canvas = canvas;
228
- this.ctx = canvas.getContext('2d', {
229
- alpha: false,
230
- desynchronized: true,
231
- willReadFrequently: false
232
- });
233
-
234
- if (this.ctx) {
235
- this.ctx.imageSmoothingEnabled = true;
236
- this.ctx.imageSmoothingQuality = 'medium';
237
- }
238
-
239
- this.clearCanvas();
240
-
241
- try {
242
- // Setup WebSocket listeners
243
- this.setupEventListeners();
244
-
245
- // Request server to start streaming and get offer
246
- // Send explicit tabId to ensure backend targets the correct tab
247
- // even if user switches tabs during the async negotiation
248
- debug.log('webcodecs', `[DIAG] Sending preview:browser-stream-start for session: ${sessionId}`);
249
- const response = await ws.http('preview:browser-stream-start', { tabId: sessionId }, 30000);
250
- debug.log('webcodecs', `[DIAG] preview:browser-stream-start response: success=${response.success}, hasOffer=${!!response.offer}, message=${response.message}`);
251
-
252
- if (!response.success) {
253
- throw new Error(response.message || 'Failed to start streaming');
254
- }
255
-
256
- // Create peer connection
257
- await this.createPeerConnection();
258
-
259
- // Set remote description (offer)
260
- if (response.offer) {
261
- debug.log('webcodecs', `[DIAG] Using offer from stream-start response`);
262
- await this.handleOffer({
263
- type: response.offer.type as RTCSdpType,
264
- sdp: response.offer.sdp
265
- });
266
- } else {
267
- // Offer not ready yet — peer may still be initializing. Retry with backoff.
268
- debug.log('webcodecs', `[DIAG] No offer in stream-start response, retrying stream-offer with backoff`);
269
-
270
- let offer: { type: string; sdp?: string } | undefined;
271
- const offerMaxRetries = 5;
272
- const offerRetryDelay = 200;
273
-
274
- for (let attempt = 0; attempt < offerMaxRetries; attempt++) {
275
- if (attempt > 0) {
276
- await new Promise(resolve => setTimeout(resolve, offerRetryDelay * attempt));
277
- }
278
- debug.log('webcodecs', `[DIAG] stream-offer attempt ${attempt + 1}/${offerMaxRetries}`);
279
- const offerResponse = await ws.http('preview:browser-stream-offer', { tabId: sessionId }, 10000);
280
- if (offerResponse.offer) {
281
- offer = offerResponse.offer;
282
- break;
283
- }
284
- }
285
-
286
- if (offer) {
287
- await this.handleOffer({
288
- type: offer.type as RTCSdpType,
289
- sdp: offer.sdp
290
- });
291
- } else {
292
- throw new Error('No offer received from server after retries');
293
- }
294
- }
295
-
296
- debug.log('webcodecs', '[DIAG] Streaming setup complete, waiting for ICE/DataChannel');
297
- return true;
298
- } catch (error) {
299
- debug.error('webcodecs', 'Failed to start streaming:', error);
300
-
301
- if (this.onError) {
302
- this.onError(error instanceof Error ? error : new Error(String(error)));
303
- }
304
-
305
- await this.cleanup();
306
- return false;
307
- }
308
- }
309
-
310
- /**
311
- * Create RTCPeerConnection
312
- */
313
- private async createPeerConnection(): Promise<void> {
314
- const config: RTCConfiguration = {
315
- iceServers: this.iceServers,
316
- bundlePolicy: 'max-bundle',
317
- rtcpMuxPolicy: 'require',
318
- iceCandidatePoolSize: 0
319
- };
320
-
321
- this.peerConnection = new RTCPeerConnection(config);
322
-
323
- // Handle DataChannel
324
- this.peerConnection.ondatachannel = (event) => {
325
- debug.log('webcodecs', 'DataChannel received');
326
- this.dataChannel = event.channel;
327
- this.dataChannel.binaryType = 'arraybuffer';
328
-
329
- this.dataChannel.onopen = () => {
330
- debug.log('webcodecs', 'DataChannel open');
331
- };
332
-
333
- this.dataChannel.onclose = () => {
334
- debug.log('webcodecs', 'DataChannel closed');
335
- // Clear navigation safety timeout — DataChannel closed normally
336
- if (this.navigationSafetyTimeout) {
337
- clearTimeout(this.navigationSafetyTimeout);
338
- this.navigationSafetyTimeout = null;
339
- }
340
- // Trigger recovery if channel closed while we were connected
341
- // BUT skip recovery if we're navigating (expected behavior during page navigation)
342
- if (this.isConnected && !this.isCleaningUp && !this.isNavigating && this.onConnectionFailed) {
343
- debug.warn('webcodecs', 'DataChannel closed unexpectedly - triggering recovery');
344
- this.onConnectionFailed();
345
- } else if (this.isNavigating) {
346
- debug.log('webcodecs', 'DataChannel closed during navigation - scheduling fast reconnect');
347
- // Signal reconnecting state IMMEDIATELY (for UI - keeps progress bar showing)
348
- if (this.onReconnectingStart) {
349
- this.onReconnectingStart();
350
- }
351
- // Backend is already ready (navigation-complete fires after backend setup).
352
- // Short delay to let state settle, then trigger fast reconnection.
353
- setTimeout(() => {
354
- if (this.isCleaningUp) return;
355
- debug.log('webcodecs', '🔄 Triggering fast reconnection after navigation');
356
- this.isNavigating = false; // Reset navigation state
357
- // Use dedicated navigation reconnect handler (fast path, no delay)
358
- if (this.onNavigationReconnect) {
359
- this.onNavigationReconnect();
360
- } else if (this.onConnectionFailed) {
361
- // Fallback to regular recovery if no navigation handler
362
- this.onConnectionFailed();
363
- }
364
- }, 100);
365
- }
366
- };
367
-
368
- this.dataChannel.onerror = (error) => {
369
- // Suppress error log during intentional cleanup (User-Initiated Abort is expected)
370
- if (this.isCleaningUp) {
371
- debug.log('webcodecs', 'DataChannel error during cleanup (expected, suppressed)');
372
- return;
373
- }
374
-
375
- debug.error('webcodecs', 'DataChannel error:', error);
376
- debug.log('webcodecs', `DataChannel error state: isConnected=${this.isConnected}, isNavigating=${this.isNavigating}`);
377
- // Trigger recovery on DataChannel error
378
- // BUT skip recovery if we're navigating (expected behavior during page navigation)
379
- if (this.isConnected && !this.isNavigating && this.onConnectionFailed) {
380
- debug.warn('webcodecs', 'DataChannel error - triggering recovery');
381
- this.onConnectionFailed();
382
- } else if (this.isNavigating) {
383
- debug.log('webcodecs', '🛡️ DataChannel error during navigation - recovery suppressed');
384
- }
385
- };
386
-
387
- this.dataChannel.onmessage = (event) => {
388
- this.handleDataChannelMessage(event.data);
389
- };
390
- };
391
-
392
- // Handle ICE candidates
393
- this.peerConnection.onicecandidate = (event) => {
394
- if (event.candidate && this.sessionId) {
395
- const candidateInit: RTCIceCandidateInit = {
396
- candidate: event.candidate.candidate,
397
- sdpMid: event.candidate.sdpMid,
398
- sdpMLineIndex: event.candidate.sdpMLineIndex
399
- };
400
-
401
- ws.http('preview:browser-stream-ice', { candidate: candidateInit, tabId: this.sessionId }).catch((error) => {
402
- debug.warn('webcodecs', 'Failed to send ICE candidate:', error);
403
- });
404
-
405
- // Also send loopback version for VPN compatibility (same-machine peers)
406
- const loopback = this.createLoopbackCandidate(candidateInit);
407
- if (loopback) {
408
- ws.http('preview:browser-stream-ice', { candidate: loopback, tabId: this.sessionId }).catch(() => {});
409
- }
410
- }
411
- };
412
-
413
- // Handle connection state
414
- this.peerConnection.onconnectionstatechange = () => {
415
- const state = this.peerConnection?.connectionState || 'closed';
416
- debug.log('webcodecs', `Connection state: ${state}`);
417
-
418
- this.stats.connectionState = state as RTCPeerConnectionState;
419
-
420
- if (state === 'connected') {
421
- this.isConnected = true;
422
- this.stats.isConnected = true;
423
- this.startStatsCollection();
424
- // this.startBandwidthLogging();
425
- if (this.onConnectionChange) {
426
- this.onConnectionChange(true);
427
- }
428
- } else if (state === 'failed') {
429
- debug.error('webcodecs', 'Connection FAILED');
430
- this.isConnected = false;
431
- this.stats.isConnected = false;
432
- this.stopStatsCollection();
433
- this.stopBandwidthLogging();
434
- if (this.onConnectionChange) {
435
- this.onConnectionChange(false);
436
- }
437
- if (this.onConnectionFailed) {
438
- this.onConnectionFailed();
439
- }
440
- } else if (state === 'disconnected' || state === 'closed') {
441
- this.isConnected = false;
442
- this.stats.isConnected = false;
443
- this.stopStatsCollection();
444
- this.stopBandwidthLogging();
445
- if (this.onConnectionChange) {
446
- this.onConnectionChange(false);
447
- }
448
- }
449
- };
450
-
451
- // Handle ICE connection state
452
- this.peerConnection.oniceconnectionstatechange = () => {
453
- const state = this.peerConnection?.iceConnectionState || 'closed';
454
- debug.log('webcodecs', `ICE connection state: ${state}`);
455
- this.stats.iceConnectionState = state as RTCIceConnectionState;
456
-
457
- if (state === 'failed') {
458
- debug.error('webcodecs', 'ICE connection FAILED');
459
- if (this.onConnectionFailed) {
460
- this.onConnectionFailed();
461
- }
462
- }
463
- };
464
- }
465
-
466
- /**
467
- * Handle offer from headless browser
468
- */
469
- private async handleOffer(offer: RTCSessionDescriptionInit): Promise<void> {
470
- if (!this.peerConnection) {
471
- throw new Error('Peer connection not initialized');
472
- }
473
-
474
- await this.peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
475
- debug.log('webcodecs', 'Remote description set');
476
-
477
- const answer = await this.peerConnection.createAnswer();
478
- await this.peerConnection.setLocalDescription(answer);
479
- debug.log('webcodecs', 'Local description set');
480
-
481
- if (this.sessionId) {
482
- await ws.http('preview:browser-stream-answer', {
483
- answer: {
484
- type: answer.type,
485
- sdp: answer.sdp
486
- },
487
- tabId: this.sessionId
488
- });
489
- }
490
- }
491
-
492
- /**
493
- * Handle DataChannel message (encoded video/audio chunks)
494
- */
495
- private handleDataChannelMessage(data: ArrayBuffer): void {
496
- try {
497
- const view = new DataView(data);
498
-
499
- // Parse packet header
500
- const type = view.getUint8(0); // 0 = video, 1 = audio
501
-
502
- if (type === 0) {
503
- // Video packet
504
- // Format: [type(1)][timestamp(8)][keyframe(1)][size(4)][data]
505
- const timestamp = Number(view.getBigUint64(1, true));
506
- const isKeyframe = view.getUint8(9) === 1;
507
- const size = view.getUint32(10, true);
508
- const chunkData = new Uint8Array(data, 14, size);
509
-
510
- this.stats.videoBytesReceived += size;
511
- this.stats.videoFramesReceived++;
512
-
513
- this.handleVideoChunk(chunkData, timestamp, isKeyframe);
514
- } else if (type === 1) {
515
- // Audio packet
516
- // Format: [type(1)][timestamp(8)][size(4)][data]
517
- const timestamp = Number(view.getBigUint64(1, true));
518
- const size = view.getUint32(9, true);
519
- const chunkData = new Uint8Array(data, 13, size);
520
-
521
- this.stats.audioBytesReceived += size;
522
- this.stats.audioFramesReceived++;
523
-
524
- this.handleAudioChunk(chunkData, timestamp);
525
- }
526
- } catch (error) {
527
- debug.error('webcodecs', 'DataChannel message parse error:', error);
528
- }
529
- }
530
-
531
- /**
532
- * Handle video chunk - decode and render
533
- */
534
- private async handleVideoChunk(data: Uint8Array, timestamp: number, isKeyframe: boolean): Promise<void> {
535
- // Initialize decoder on first keyframe
536
- if (!this.videoDecoder && isKeyframe) {
537
- await this.initVideoDecoder(data);
538
- }
539
-
540
- if (!this.videoDecoder) {
541
- this.stats.videoFramesDropped++;
542
- return;
543
- }
544
-
545
- try {
546
- const chunk = new EncodedVideoChunk({
547
- type: isKeyframe ? 'key' : 'delta',
548
- timestamp,
549
- data
550
- });
551
-
552
- this.videoDecoder.decode(chunk);
553
- } catch (error) {
554
- debug.error('webcodecs', 'Video decode error:', error);
555
- this.stats.videoFramesDropped++;
556
- }
557
- }
558
-
559
- /**
560
- * Handle audio chunk - decode and queue for playback
561
- */
562
- private async handleAudioChunk(data: Uint8Array, timestamp: number): Promise<void> {
563
- // Initialize decoder on first chunk
564
- if (!this.audioDecoder) {
565
- await this.initAudioDecoder();
566
- }
567
-
568
- if (!this.audioDecoder) {
569
- this.stats.audioFramesDropped++;
570
- return;
571
- }
572
-
573
- try {
574
- const chunk = new EncodedAudioChunk({
575
- type: 'key', // Opus frames are all keyframes
576
- timestamp,
577
- data
578
- });
579
-
580
- this.audioDecoder.decode(chunk);
581
- } catch (error) {
582
- debug.error('webcodecs', 'Audio decode error:', error);
583
- this.stats.audioFramesDropped++;
584
- }
585
- }
586
-
587
- /**
588
- * Initialize VideoDecoder
589
- */
590
- private async initVideoDecoder(firstChunkData: Uint8Array): Promise<void> {
591
- // Use VP8 codec
592
- const codec = 'vp8';
593
- this.stats.videoCodec = 'vp8';
594
-
595
- this.videoCodecConfig = {
596
- codec,
597
- optimizeForLatency: true
598
- };
599
-
600
- try {
601
- const support = await VideoDecoder.isConfigSupported(this.videoCodecConfig);
602
- if (!support.supported) {
603
- throw new Error(`Video codec ${codec} not supported`);
604
- }
605
-
606
- this.videoDecoder = new VideoDecoder({
607
- output: (frame) => this.handleDecodedVideoFrame(frame),
608
- error: (e) => {
609
- debug.error('webcodecs', 'VideoDecoder error:', e);
610
- // Null out so next keyframe triggers reinitialization.
611
- // Without this, the decoder stays in 'closed' state but non-null,
612
- // causing handleVideoChunk's `!this.videoDecoder` check to never fire
613
- // → all subsequent frames permanently dropped (stuck frames bug).
614
- this.videoDecoder = null;
615
- }
616
- });
617
-
618
- this.videoDecoder.configure(this.videoCodecConfig);
619
- debug.log('webcodecs', 'VideoDecoder initialized:', codec);
620
- } catch (error) {
621
- debug.error('webcodecs', 'VideoDecoder init error:', error);
622
- throw error;
623
- }
624
- }
625
-
626
- /**
627
- * Initialize AudioDecoder
628
- */
629
- private async initAudioDecoder(): Promise<void> {
630
- this.audioCodecConfig = {
631
- codec: 'opus',
632
- sampleRate: 48000,
633
- numberOfChannels: 2
634
- };
635
-
636
- try {
637
- const support = await AudioDecoder.isConfigSupported(this.audioCodecConfig);
638
- if (!support.supported) {
639
- throw new Error('Opus audio codec not supported');
640
- }
641
-
642
- this.audioDecoder = new AudioDecoder({
643
- output: (frame) => this.handleDecodedAudioFrame(frame),
644
- error: (e) => {
645
- debug.error('webcodecs', 'AudioDecoder error:', e);
646
- // Null out so next chunk triggers reinitialization.
647
- this.audioDecoder = null;
648
- }
649
- });
650
-
651
- this.audioDecoder.configure(this.audioCodecConfig);
652
- this.stats.audioCodec = 'opus';
653
-
654
- // Initialize AudioContext for playback
655
- await this.initAudioContext();
656
-
657
- debug.log('webcodecs', 'AudioDecoder initialized: opus');
658
- } catch (error) {
659
- debug.error('webcodecs', 'AudioDecoder init error:', error);
660
- }
661
- }
662
-
663
- /**
664
- * Initialize AudioContext for audio playback
665
- */
666
- private async initAudioContext(): Promise<void> {
667
- try {
668
- // Reuse AudioContext created in startStreaming (user gesture context)
669
- if (!this.audioContext || this.audioContext.state === 'closed') {
670
- this.audioContext = new AudioContext({ sampleRate: 48000 });
671
- }
672
-
673
- // Resume if suspended — fire-and-forget, same reason as in startStreaming
674
- if (this.audioContext.state === 'suspended') {
675
- this.audioContext.resume().catch(() => {});
676
- }
677
-
678
- debug.log('webcodecs', `AudioContext initialized (state: ${this.audioContext.state})`);
679
- } catch (error) {
680
- debug.error('webcodecs', 'AudioContext init error:', error);
681
- }
682
- }
683
-
684
- /**
685
- * Handle decoded video frame - render to canvas with timestamp-based optimization
686
- */
687
- private handleDecodedVideoFrame(frame: VideoFrame): void {
688
- if (this.isCleaningUp || !this.canvas || !this.ctx) {
689
- frame.close();
690
- return;
691
- }
692
-
693
- // During SPA navigation freeze, skip rendering to hold the last frame
694
- // This prevents brief white flashes during SPA page transitions
695
- if (this.spaFreezeUntil > 0 && Date.now() < this.spaFreezeUntil) {
696
- frame.close();
697
- return;
698
- }
699
- // Auto-reset freeze after it expires
700
- if (this.spaFreezeUntil > 0) {
701
- this.spaFreezeUntil = 0;
702
- }
703
-
704
- try {
705
- // Update stats
706
- this.stats.videoFramesDecoded++;
707
- this.stats.frameWidth = frame.displayWidth;
708
- this.stats.frameHeight = frame.displayHeight;
709
-
710
- // Establish AV sync reference on first video frame
711
- if (!this.syncEstablished) {
712
- this.syncEstablished = true;
713
- this.syncRealTimeOrigin = performance.now();
714
- this.syncStreamTimestamp = frame.timestamp;
715
- debug.log('webcodecs', `AV Sync established: realTime=${this.syncRealTimeOrigin.toFixed(0)}ms, streamTs=${this.syncStreamTimestamp}μs`);
716
- }
717
-
718
- // Track last video timestamp and real time for audio sync
719
- this.lastVideoTimestamp = frame.timestamp;
720
- this.lastVideoRealTime = performance.now();
721
-
722
- // Mark first frame rendered
723
- if (!this.stats.firstFrameRendered) {
724
- this.stats.firstFrameRendered = true;
725
- this.startTime = performance.now();
726
- this.firstFrameTimestamp = frame.timestamp;
727
- debug.log('webcodecs', 'First video frame rendered');
728
-
729
- // Notify immediately so UI can hide loading overlay without polling delay
730
- if (this.onFirstFrame) {
731
- this.onFirstFrame();
732
- }
733
-
734
- // Reset navigation state - frames are flowing, navigation is complete
735
- if (this.isNavigating) {
736
- debug.log('webcodecs', 'Navigation complete - frames received, resetting navigation state');
737
- this.isNavigating = false;
738
- if (this.navigationSafetyTimeout) {
739
- clearTimeout(this.navigationSafetyTimeout);
740
- this.navigationSafetyTimeout = null;
741
- }
742
- }
743
- }
744
-
745
- // Drop old pending frame if exists (frame skipping for performance)
746
- if (this.pendingFrame) {
747
- this.pendingFrame.close();
748
- this.stats.videoFramesDropped++;
749
- }
750
-
751
- // Store frame for next render cycle
752
- this.pendingFrame = frame;
753
-
754
- // Schedule render if not already scheduled
755
- if (!this.isRenderingFrame) {
756
- this.scheduleFrameRender();
757
- }
758
- } catch (error) {
759
- debug.error('webcodecs', 'Video frame handle error:', error);
760
- frame.close();
761
- }
762
- }
763
-
764
- /**
765
- * Schedule frame rendering using requestAnimationFrame with timestamp awareness
766
- * This mimics requestVideoFrameCallback behavior for optimal video rendering
767
- */
768
- private scheduleFrameRender(): void {
769
- if (this.isRenderingFrame) return;
770
-
771
- this.isRenderingFrame = true;
772
- this.renderFrameId = requestAnimationFrame((timestamp) => {
773
- this.renderPendingFrame(timestamp);
774
- });
775
- }
776
-
777
- /**
778
- * Render pending frame to canvas with timestamp-based scheduling
779
- * This approach provides similar benefits to requestVideoFrameCallback
780
- */
781
- private renderPendingFrame(timestamp: DOMHighResTimeStamp): void {
782
- this.isRenderingFrame = false;
783
-
784
- if (!this.pendingFrame || this.isCleaningUp || !this.canvas || !this.ctx) {
785
- if (this.pendingFrame) {
786
- this.pendingFrame.close();
787
- this.pendingFrame = null;
788
- }
789
- return;
790
- }
791
-
792
- try {
793
- // Calculate frame timing (similar to requestVideoFrameCallback metadata)
794
- // Use relative timestamp from first frame to sync with frontend clock
795
- const frameTimestamp = (this.pendingFrame.timestamp - this.firstFrameTimestamp) / 1000; // convert to ms
796
- const elapsedTime = timestamp - this.startTime;
797
-
798
- const timeDrift = elapsedTime - frameTimestamp;
799
-
800
- // Auto-reset timing when drift exceeds 2 seconds.
801
- // This handles stale timing state after reconnects or rapid tab switches
802
- // where startTime/firstFrameTimestamp were not properly reset.
803
- if (Math.abs(timeDrift) > 2000 && this.startTime > 0) {
804
- debug.warn('webcodecs', `Frame timing drift reset (was ${timeDrift.toFixed(0)}ms)`);
805
- this.startTime = timestamp;
806
- this.firstFrameTimestamp = this.pendingFrame.timestamp;
807
- }
808
-
809
- // Render to canvas with optimal settings
810
- this.ctx.drawImage(this.pendingFrame, 0, 0, this.canvas.width, this.canvas.height);
811
-
812
- this.lastFrameTime = timestamp;
813
- } catch (error) {
814
- debug.error('webcodecs', 'Video frame render error:', error);
815
- } finally {
816
- // Close frame immediately to free memory
817
- this.pendingFrame.close();
818
- this.pendingFrame = null;
819
- }
820
- }
821
-
822
- /**
823
- * Handle decoded audio frame - play audio
824
- */
825
- private handleDecodedAudioFrame(frame: AudioData): void {
826
- if (this.isCleaningUp || !this.audioContext) {
827
- frame.close();
828
- return;
829
- }
830
-
831
- try {
832
- this.stats.audioFramesDecoded++;
833
-
834
- // Simple playback: convert AudioData to AudioBuffer and play
835
- // For production, use AudioWorklet for better latency
836
- this.playAudioFrame(frame);
837
- } catch (error) {
838
- debug.error('webcodecs', 'Audio frame playback error:', error);
839
- } finally {
840
- frame.close();
841
- }
842
- }
843
-
844
- /**
845
- * Play audio frame using simple back-to-back scheduling.
846
- *
847
- * Frames are scheduled immediately one after another. When a gap occurs
848
- * (e.g. silence was skipped server-side and audio resumes), the schedule
849
- * is reset with a 50ms lookahead so playback starts cleanly without
850
- * audible pops or stutters from scheduling in the past.
851
- */
852
- private playAudioFrame(audioData: AudioData): void {
853
- if (!this.audioContext) return;
854
-
855
- // Safety net: resume AudioContext if suspended
856
- if (this.audioContext.state === 'suspended') {
857
- this.audioContext.resume().catch(() => {});
858
- }
859
-
860
- try {
861
- const buffer = this.audioContext.createBuffer(
862
- audioData.numberOfChannels,
863
- audioData.numberOfFrames,
864
- audioData.sampleRate
865
- );
866
-
867
- for (let channel = 0; channel < audioData.numberOfChannels; channel++) {
868
- const options = {
869
- planeIndex: channel,
870
- frameOffset: 0,
871
- frameCount: audioData.numberOfFrames,
872
- format: 'f32-planar' as AudioSampleFormat
873
- };
874
- // allocationSize() returns bytes — wrap in ArrayBuffer so Float32Array length is correct
875
- const tempFloat32 = new Float32Array(new ArrayBuffer(audioData.allocationSize(options)));
876
- audioData.copyTo(tempFloat32, options);
877
- buffer.getChannelData(channel).set(tempFloat32);
878
- }
879
-
880
- const currentTime = this.audioContext.currentTime;
881
-
882
- // When the scheduler has fallen behind (gap due to silence or decode delay),
883
- // reset with a 50ms lookahead so the next chunk starts cleanly.
884
- if (this.nextAudioPlayTime < currentTime) {
885
- this.nextAudioPlayTime = currentTime + 0.05;
886
- }
887
-
888
- const source = this.audioContext.createBufferSource();
889
- source.buffer = buffer;
890
- source.connect(this.audioContext.destination);
891
- source.start(this.nextAudioPlayTime);
892
-
893
- // Back-to-back: next chunk plays immediately after this one ends
894
- this.nextAudioPlayTime += buffer.duration;
895
- } catch (error) {
896
- debug.warn('webcodecs', 'Audio playback error:', error);
897
- }
898
- }
899
-
900
- /**
901
- * Setup WebSocket event listeners
902
- */
903
- private setupEventListeners(): void {
904
- const cleanupIce = ws.on('preview:browser-stream-ice', async (data) => {
905
- if (data.sessionId === this.sessionId && data.from === 'headless') {
906
- await this.addIceCandidate(data.candidate);
907
- }
908
- });
909
-
910
- const cleanupState = ws.on('preview:browser-stream-state', (data) => {
911
- if (data.sessionId === this.sessionId) {
912
- debug.log('webcodecs', `Server connection state: ${data.state}`);
913
- }
914
- });
915
-
916
- const cleanupCursor = ws.on('preview:browser-cursor-change', (data) => {
917
- if (data.sessionId === this.sessionId && this.onCursorChange) {
918
- this.onCursorChange(data.cursor);
919
- }
920
- });
921
-
922
- // Listen for navigation events DIRECTLY to set isNavigating flag immediately
923
- // This bypasses Svelte's reactive chain which can be too slow
924
- debug.log('webcodecs', `🔧 Registering navigation listener for session: ${this.sessionId}`);
925
- const cleanupNavLoading = ws.on('preview:browser-navigation-loading', (data) => {
926
- debug.log('webcodecs', `📡 Navigation-loading WS event: eventSessionId=${data.sessionId}, mySessionId=${this.sessionId}`);
927
- // Set isNavigating regardless of sessionId match to ensure recovery is suppressed
928
- // Multiple tabs scenario: only suppress for current tab, but log all
929
- if (data.sessionId === this.sessionId) {
930
- this.isNavigating = true;
931
- debug.log('webcodecs', `✅ Navigation started - isNavigating=true for session ${data.sessionId}`);
932
- }
933
- });
934
-
935
- const cleanupNavComplete = ws.on('preview:browser-navigation', (data) => {
936
- if (data.sessionId === this.sessionId) {
937
- debug.log('webcodecs', `Navigation completed (direct WS) for session ${data.sessionId}`);
938
-
939
- // If isNavigating was NOT set by navigation-loading (SPA-like case where
940
- // framenavigated fires without a document request), set it now so the
941
- // subsequent DataChannel close triggers fast reconnect instead of full recovery
942
- if (!this.isNavigating) {
943
- this.isNavigating = true;
944
- debug.log('webcodecs', '✅ Set isNavigating=true on navigation complete (no loading event preceded)');
945
- }
946
-
947
- // Signal reconnecting state IMMEDIATELY when navigation completes
948
- // This eliminates the gap between isNavigating=false and DataChannel close
949
- // ensuring the overlay stays visible continuously
950
- if (this.onReconnectingStart) {
951
- debug.log('webcodecs', '🔄 Pre-emptive reconnecting state on navigation complete');
952
- this.onReconnectingStart();
953
- }
954
-
955
- // Fast safety timeout: if DataChannel doesn't close within 100ms,
956
- // force a full recovery (stop + start fresh stream). Sometimes
957
- // the old WebRTC connection lingers for 10-16s before ICE timeout.
958
- // Using onConnectionFailed triggers attemptRecovery (full stop+start),
959
- // which is the same path as tab switching and takes ~100ms to first frame.
960
- if (this.navigationSafetyTimeout) {
961
- clearTimeout(this.navigationSafetyTimeout);
962
- }
963
- this.navigationSafetyTimeout = setTimeout(() => {
964
- this.navigationSafetyTimeout = null;
965
- if (this.isCleaningUp || !this.isNavigating) return;
966
- debug.warn('webcodecs', '⏰ Navigation safety timeout - forcing full recovery');
967
- this.isNavigating = false;
968
- if (this.onConnectionFailed) {
969
- this.onConnectionFailed();
970
- }
971
- }, 100);
972
- }
973
- });
974
-
975
- // Listen for SPA navigation events (pushState/replaceState/hash changes)
976
- // Reset isNavigating if it was set by a preceding navigation-loading event
977
- // that the SPA router intercepted (cancelled the full navigation)
978
- const cleanupNavSpa = ws.on('preview:browser-navigation-spa', (data) => {
979
- if (data.sessionId === this.sessionId && this.isNavigating) {
980
- debug.log('webcodecs', '🔄 SPA navigation received - resetting isNavigating (no stream restart needed)');
981
- this.isNavigating = false;
982
- }
983
- });
984
-
985
- this.wsCleanupFunctions = [cleanupIce, cleanupState, cleanupCursor, cleanupNavLoading, cleanupNavComplete, cleanupNavSpa];
986
- }
987
-
988
- /**
989
- * Create a loopback (127.0.0.1) copy of a host ICE candidate.
990
- * Ensures WebRTC connects via loopback when VPN (e.g. Cloudflare WARP)
991
- * interferes with host candidate connectivity between same-machine peers.
992
- */
993
- private createLoopbackCandidate(candidate: RTCIceCandidateInit): RTCIceCandidateInit | null {
994
- if (!candidate.candidate) return null;
995
- if (!candidate.candidate.includes('typ host')) return null;
996
-
997
- const parts = candidate.candidate.split(' ');
998
- if (parts.length < 8) return null;
999
-
1000
- // Index 4 is the address field in ICE candidate format
1001
- const address = parts[4];
1002
- if (address === '127.0.0.1' || address === '::1') return null;
1003
-
1004
- parts[4] = '127.0.0.1';
1005
- return { ...candidate, candidate: parts.join(' ') };
1006
- }
1007
-
1008
- /**
1009
- * Add ICE candidate (+ loopback variant for VPN compatibility)
1010
- */
1011
- private async addIceCandidate(candidate: RTCIceCandidateInit): Promise<void> {
1012
- if (!this.peerConnection) return;
1013
-
1014
- try {
1015
- await this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
1016
- } catch (error) {
1017
- debug.warn('webcodecs', 'Add ICE candidate error:', error);
1018
- }
1019
-
1020
- // Also try loopback version for VPN compatibility (same-machine peers)
1021
- const loopback = this.createLoopbackCandidate(candidate);
1022
- if (loopback) {
1023
- try {
1024
- await this.peerConnection.addIceCandidate(new RTCIceCandidate(loopback));
1025
- } catch {
1026
- // Expected to fail if loopback is not applicable
1027
- }
1028
- }
1029
- }
1030
-
1031
- /**
1032
- * Start stats collection
1033
- */
1034
- private startStatsCollection(): void {
1035
- if (this.statsIntervalId) return;
1036
-
1037
- this.statsIntervalId = setInterval(async () => {
1038
- await this.collectStats();
1039
- }, 1000);
1040
- }
1041
-
1042
- /**
1043
- * Stop stats collection
1044
- */
1045
- private stopStatsCollection(): void {
1046
- if (this.statsIntervalId) {
1047
- clearInterval(this.statsIntervalId);
1048
- this.statsIntervalId = null;
1049
- }
1050
- }
1051
-
1052
- /**
1053
- * Collect stats
1054
- */
1055
- private async collectStats(): Promise<void> {
1056
- const now = performance.now();
1057
-
1058
- // Calculate bandwidth if we have previous measurements
1059
- if (this.lastStatsTime > 0) {
1060
- const timeDelta = (now - this.lastStatsTime) / 1000; // seconds
1061
-
1062
- // Video bitrate
1063
- const videoBytesReceived = this.stats.videoBytesReceived - this.lastVideoBytesReceived;
1064
- this.stats.videoBitrate = (videoBytesReceived * 8) / timeDelta;
1065
-
1066
- // Audio bitrate
1067
- const audioBytesReceived = this.stats.audioBytesReceived - this.lastAudioBytesReceived;
1068
- this.stats.audioBitrate = (audioBytesReceived * 8) / timeDelta;
1069
-
1070
- // Total
1071
- this.stats.totalBitrate = this.stats.videoBitrate + this.stats.audioBitrate;
1072
- this.stats.totalBandwidthMBps = this.stats.totalBitrate / 8 / 1024 / 1024;
1073
- }
1074
-
1075
- this.lastVideoBytesReceived = this.stats.videoBytesReceived;
1076
- this.lastAudioBytesReceived = this.stats.audioBytesReceived;
1077
- this.lastStatsTime = now;
1078
-
1079
- if (this.onStats) {
1080
- this.onStats(this.stats);
1081
- }
1082
- }
1083
-
1084
- /**
1085
- * Start bandwidth logging
1086
- */
1087
- private startBandwidthLogging(): void {
1088
- if (this.bandwidthLogIntervalId) return;
1089
-
1090
- this.bandwidthLogIntervalId = setInterval(() => {
1091
- this.logBandwidthStats();
1092
- }, 1000); // Log every 5 seconds
1093
- }
1094
-
1095
- /**
1096
- * Stop bandwidth logging
1097
- */
1098
- private stopBandwidthLogging(): void {
1099
- if (this.bandwidthLogIntervalId) {
1100
- clearInterval(this.bandwidthLogIntervalId);
1101
- this.bandwidthLogIntervalId = null;
1102
- }
1103
- }
1104
-
1105
- /**
1106
- * Log bandwidth statistics to console
1107
- */
1108
- private logBandwidthStats(): void {
1109
- const videoKbps = (this.stats.videoBitrate / 1000).toFixed(1);
1110
- const audioKbps = (this.stats.audioBitrate / 1000).toFixed(1);
1111
- const totalKbps = (this.stats.totalBitrate / 1000).toFixed(1);
1112
- const totalMBps = this.stats.totalBandwidthMBps.toFixed(3);
1113
-
1114
- debug.log('webcodecs',
1115
- `📊 Bandwidth Usage:\n` +
1116
- ` Video: ${videoKbps} Kbps (${this.stats.videoCodec}) - ${this.stats.frameWidth}x${this.stats.frameHeight}\n` +
1117
- ` Audio: ${audioKbps} Kbps (${this.stats.audioCodec})\n` +
1118
- ` Total: ${totalKbps} Kbps (${totalMBps} MB/s)\n` +
1119
- ` Frames: Video ${this.stats.videoFramesDecoded} (dropped: ${this.stats.videoFramesDropped}), ` +
1120
- `Audio ${this.stats.audioFramesDecoded} (dropped: ${this.stats.audioFramesDropped})`
1121
- );
1122
- }
1123
-
1124
- /**
1125
- * Stop streaming
1126
- */
1127
- async stopStreaming(): Promise<void> {
1128
- debug.log('webcodecs', 'Stopping streaming');
1129
- await this.cleanup();
1130
- }
1131
-
1132
- /**
1133
- * Reconnect to existing backend stream (after navigation)
1134
- * This does NOT tell backend to stop - just reconnects WebRTC locally
1135
- */
1136
- async reconnectToExistingStream(sessionId: string, canvas: HTMLCanvasElement): Promise<boolean> {
1137
- debug.log('webcodecs', `🔄 Reconnecting to existing stream for session: ${sessionId}`);
1138
-
1139
- // Cleanup local WebRTC state WITHOUT notifying backend
1140
- await this.cleanupLocalConnection();
1141
-
1142
- this.isCleaningUp = false;
1143
- this.stats.firstFrameRendered = false;
1144
- this.isNavigating = false;
1145
-
1146
- this.sessionId = sessionId;
1147
- this.canvas = canvas;
1148
- this.ctx = canvas.getContext('2d', {
1149
- alpha: false,
1150
- desynchronized: true,
1151
- willReadFrequently: false
1152
- });
1153
-
1154
- if (this.ctx) {
1155
- this.ctx.imageSmoothingEnabled = true;
1156
- this.ctx.imageSmoothingQuality = 'medium';
1157
- }
1158
-
1159
- try {
1160
- // Setup WebSocket listeners
1161
- this.setupEventListeners();
1162
-
1163
- // Create peer connection
1164
- await this.createPeerConnection();
1165
-
1166
- // Get offer from backend's existing peer (don't start new streaming)
1167
- const offerResponse = await ws.http('preview:browser-stream-offer', { tabId: sessionId }, 10000);
1168
- if (offerResponse.offer) {
1169
- await this.handleOffer({
1170
- type: offerResponse.offer.type as RTCSdpType,
1171
- sdp: offerResponse.offer.sdp
1172
- });
1173
- } else {
1174
- throw new Error('No offer received from backend');
1175
- }
1176
-
1177
- debug.log('webcodecs', 'Reconnection setup complete');
1178
- return true;
1179
- } catch (error) {
1180
- debug.error('webcodecs', 'Failed to reconnect:', error);
1181
- if (this.onError) {
1182
- this.onError(error instanceof Error ? error : new Error(String(error)));
1183
- }
1184
- return false;
1185
- }
1186
- }
1187
-
1188
- /**
1189
- * Cleanup local WebRTC connection WITHOUT notifying backend
1190
- */
1191
- private async cleanupLocalConnection(): Promise<void> {
1192
- this.isCleaningUp = true;
1193
-
1194
- this.stopStatsCollection();
1195
- this.stopBandwidthLogging();
1196
-
1197
- // Cancel pending frame render
1198
- if (this.renderFrameId !== null) {
1199
- cancelAnimationFrame(this.renderFrameId);
1200
- this.renderFrameId = null;
1201
- }
1202
-
1203
- // Close pending frame
1204
- if (this.pendingFrame) {
1205
- this.pendingFrame.close();
1206
- this.pendingFrame = null;
1207
- }
1208
-
1209
- // Cleanup WebSocket listeners
1210
- try {
1211
- this.wsCleanupFunctions.forEach((cleanup) => cleanup());
1212
- } catch (e) {
1213
- debug.warn('webcodecs', 'Error in ws cleanup:', e);
1214
- }
1215
- this.wsCleanupFunctions = [];
1216
-
1217
- // Close decoders immediately (reset + close, no flush).
1218
- // Flushing processes all queued frames which is slow and can fire
1219
- // stale callbacks during rapid tab switching.
1220
- if (this.videoDecoder) {
1221
- try {
1222
- this.videoDecoder.reset();
1223
- this.videoDecoder.close();
1224
- } catch (e) {}
1225
- this.videoDecoder = null;
1226
- }
1227
-
1228
- if (this.audioDecoder) {
1229
- try {
1230
- this.audioDecoder.reset();
1231
- this.audioDecoder.close();
1232
- } catch (e) {}
1233
- this.audioDecoder = null;
1234
- }
1235
-
1236
- // Keep AudioContext alive across reconnections — it was created during
1237
- // user gesture in startStreaming() and closing it means we can't resume
1238
- // without another user gesture. Just reset playback state below.
1239
-
1240
- // Close data channel
1241
- if (this.dataChannel) {
1242
- this.dataChannel.close();
1243
- this.dataChannel = null;
1244
- }
1245
-
1246
- // Close peer connection
1247
- if (this.peerConnection) {
1248
- this.peerConnection.close();
1249
- this.peerConnection = null;
1250
- }
1251
-
1252
- this.isConnected = false;
1253
- // NOTE: Don't clear sessionId - we're reconnecting to same session
1254
-
1255
- // Reset playback state
1256
- this.nextAudioPlayTime = 0;
1257
- this.audioBufferQueue = [];
1258
- this.audioSyncInitialized = false;
1259
- this.audioCalibrationSamples = 0;
1260
- this.audioOffsetAccumulator = 0;
1261
- this.calibratedAudioOffset = 0;
1262
-
1263
- this.isRenderingFrame = false;
1264
- this.lastFrameTime = 0;
1265
- this.startTime = 0;
1266
- this.firstFrameTimestamp = 0;
1267
-
1268
- this.syncEstablished = false;
1269
- this.syncRealTimeOrigin = 0;
1270
- this.syncStreamTimestamp = 0;
1271
- this.lastVideoTimestamp = 0;
1272
- this.lastVideoRealTime = 0;
1273
-
1274
- if (this.onConnectionChange) {
1275
- this.onConnectionChange(false);
1276
- }
1277
-
1278
- this.isCleaningUp = false;
1279
- }
1280
-
1281
- /**
1282
- * Cleanup resources
1283
- */
1284
- private async cleanup(): Promise<void> {
1285
- this.isCleaningUp = true;
1286
-
1287
- this.stopStatsCollection();
1288
- this.stopBandwidthLogging();
1289
-
1290
- // Cancel pending frame render
1291
- if (this.renderFrameId !== null) {
1292
- cancelAnimationFrame(this.renderFrameId);
1293
- this.renderFrameId = null;
1294
- }
1295
-
1296
- // Close pending frame
1297
- if (this.pendingFrame) {
1298
- this.pendingFrame.close();
1299
- this.pendingFrame = null;
1300
- }
1301
-
1302
- // Cleanup WebSocket listeners
1303
- try {
1304
- this.wsCleanupFunctions.forEach((cleanup) => cleanup());
1305
- } catch (e) {
1306
- debug.warn('webcodecs', 'Error in ws cleanup:', e);
1307
- }
1308
- this.wsCleanupFunctions = [];
1309
-
1310
- // Notify server with explicit tabId (fire-and-forget for speed during rapid switching)
1311
- if (this.sessionId) {
1312
- ws.http('preview:browser-stream-stop', { tabId: this.sessionId }).catch(() => {});
1313
- }
1314
-
1315
- // Close decoders immediately (reset + close, no flush for speed)
1316
- if (this.videoDecoder) {
1317
- try {
1318
- this.videoDecoder.reset();
1319
- this.videoDecoder.close();
1320
- } catch (e) {}
1321
- this.videoDecoder = null;
1322
- }
1323
-
1324
- if (this.audioDecoder) {
1325
- try {
1326
- this.audioDecoder.reset();
1327
- this.audioDecoder.close();
1328
- } catch (e) {}
1329
- this.audioDecoder = null;
1330
- }
1331
-
1332
- // Keep AudioContext alive across stop/start cycles — it was created during
1333
- // a user gesture in startStreaming() and closing it means we can't resume
1334
- // without another user gesture. Only destroy() should close it.
1335
- // Just reset audio playback scheduling state below.
1336
-
1337
- // Close data channel
1338
- if (this.dataChannel) {
1339
- this.dataChannel.close();
1340
- this.dataChannel = null;
1341
- }
1342
-
1343
- // Close peer connection
1344
- if (this.peerConnection) {
1345
- this.peerConnection.close();
1346
- this.peerConnection = null;
1347
- }
1348
-
1349
- this.isConnected = false;
1350
- this.sessionId = null;
1351
- this.canvas = null;
1352
- this.ctx = null;
1353
-
1354
- // Reset stats
1355
- this.stats = {
1356
- isConnected: false,
1357
- connectionState: 'closed',
1358
- iceConnectionState: 'closed',
1359
- videoBytesReceived: 0,
1360
- audioBytesReceived: 0,
1361
- videoFramesReceived: 0,
1362
- audioFramesReceived: 0,
1363
- videoFramesDecoded: 0,
1364
- audioFramesDecoded: 0,
1365
- videoFramesDropped: 0,
1366
- audioFramesDropped: 0,
1367
- frameWidth: 0,
1368
- frameHeight: 0,
1369
- videoBitrate: 0,
1370
- audioBitrate: 0,
1371
- totalBitrate: 0,
1372
- totalBandwidthMBps: 0,
1373
- videoCodec: 'unknown',
1374
- audioCodec: 'unknown',
1375
- firstFrameRendered: false
1376
- };
1377
-
1378
- this.lastVideoBytesReceived = 0;
1379
- this.lastAudioBytesReceived = 0;
1380
- this.lastStatsTime = 0;
1381
-
1382
- // Reset audio playback state
1383
- this.nextAudioPlayTime = 0;
1384
- this.audioBufferQueue = [];
1385
- this.audioSyncInitialized = false;
1386
- this.audioCalibrationSamples = 0;
1387
- this.audioOffsetAccumulator = 0;
1388
- this.calibratedAudioOffset = 0;
1389
-
1390
- // Reset frame rendering state
1391
- this.isRenderingFrame = false;
1392
- this.lastFrameTime = 0;
1393
- this.startTime = 0;
1394
- this.firstFrameTimestamp = 0;
1395
-
1396
- // Reset AV sync state
1397
- this.syncEstablished = false;
1398
- this.syncRealTimeOrigin = 0;
1399
- this.syncStreamTimestamp = 0;
1400
- this.lastVideoTimestamp = 0;
1401
- this.lastVideoRealTime = 0;
1402
-
1403
- // Reset navigation state
1404
- this.isNavigating = false;
1405
- if (this.navigationSafetyTimeout) {
1406
- clearTimeout(this.navigationSafetyTimeout);
1407
- this.navigationSafetyTimeout = null;
1408
- }
1409
-
1410
- if (this.onConnectionChange) {
1411
- this.onConnectionChange(false);
1412
- }
1413
-
1414
- this.isCleaningUp = false;
1415
- }
1416
-
1417
- /**
1418
- * Cleanup connection (internal)
1419
- */
1420
- private async cleanupConnection(): Promise<void> {
1421
- this.isCleaningUp = true;
1422
-
1423
- this.stopStatsCollection();
1424
- this.stopBandwidthLogging();
1425
-
1426
- // Cancel pending frame render
1427
- if (this.renderFrameId !== null) {
1428
- cancelAnimationFrame(this.renderFrameId);
1429
- this.renderFrameId = null;
1430
- }
1431
-
1432
- // Close pending frame
1433
- if (this.pendingFrame) {
1434
- this.pendingFrame.close();
1435
- this.pendingFrame = null;
1436
- }
1437
-
1438
- try {
1439
- this.wsCleanupFunctions.forEach((cleanup) => cleanup());
1440
- } catch (e) {
1441
- debug.warn('webcodecs', 'Error in ws cleanup:', e);
1442
- }
1443
- this.wsCleanupFunctions = [];
1444
-
1445
- if (this.videoDecoder) {
1446
- try {
1447
- this.videoDecoder.reset();
1448
- this.videoDecoder.close();
1449
- } catch (e) {}
1450
- this.videoDecoder = null;
1451
- }
1452
-
1453
- if (this.audioDecoder) {
1454
- try {
1455
- this.audioDecoder.reset();
1456
- this.audioDecoder.close();
1457
- } catch (e) {}
1458
- this.audioDecoder = null;
1459
- }
1460
-
1461
- // Keep AudioContext alive — same rationale as cleanup()
1462
-
1463
- if (this.dataChannel) {
1464
- this.dataChannel.close();
1465
- this.dataChannel = null;
1466
- }
1467
-
1468
- if (this.peerConnection) {
1469
- this.peerConnection.close();
1470
- this.peerConnection = null;
1471
- }
1472
-
1473
- this.isConnected = false;
1474
- this.sessionId = null;
1475
-
1476
- // Reset stats (prevent stale firstFrameRendered from skipping timing reset)
1477
- this.stats.firstFrameRendered = false;
1478
- this.stats.isConnected = false;
1479
-
1480
- // Reset audio playback state
1481
- this.nextAudioPlayTime = 0;
1482
- this.audioBufferQueue = [];
1483
- this.audioSyncInitialized = false;
1484
- this.audioCalibrationSamples = 0;
1485
- this.audioOffsetAccumulator = 0;
1486
- this.calibratedAudioOffset = 0;
1487
-
1488
- // Reset frame rendering state
1489
- this.isRenderingFrame = false;
1490
- this.lastFrameTime = 0;
1491
- this.startTime = 0;
1492
- this.firstFrameTimestamp = 0;
1493
-
1494
- // Reset AV sync state
1495
- this.syncEstablished = false;
1496
- this.syncRealTimeOrigin = 0;
1497
- this.syncStreamTimestamp = 0;
1498
- this.lastVideoTimestamp = 0;
1499
- this.lastVideoRealTime = 0;
1500
-
1501
- // Clear navigation safety timeout
1502
- if (this.navigationSafetyTimeout) {
1503
- clearTimeout(this.navigationSafetyTimeout);
1504
- this.navigationSafetyTimeout = null;
1505
- }
1506
-
1507
- this.isCleaningUp = false;
1508
- }
1509
-
1510
- /**
1511
- * Clear canvas
1512
- */
1513
- private clearCanvas(): void {
1514
- if (this.canvas && this.ctx) {
1515
- this.ctx.fillStyle = '#f1f5f9';
1516
- this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
1517
- }
1518
- }
1519
-
1520
- /**
1521
- * Get stats
1522
- */
1523
- getStats(): BrowserWebCodecsStreamStats {
1524
- return { ...this.stats };
1525
- }
1526
-
1527
- /**
1528
- * Get connection status
1529
- */
1530
- getConnectionStatus(): boolean {
1531
- return this.isConnected;
1532
- }
1533
-
1534
- /**
1535
- * Immediately block frame rendering without closing the WebRTC connection.
1536
- * Call this as soon as a tab switch is detected to prevent the old session's
1537
- * frames from painting onto the canvas after it has been cleared/snapshot-restored.
1538
- * The cleanup + new connection will complete asynchronously via stopStreaming/startStreaming.
1539
- */
1540
- pauseRendering(): void {
1541
- this.isCleaningUp = true;
1542
- if (this.renderFrameId !== null) {
1543
- cancelAnimationFrame(this.renderFrameId);
1544
- this.renderFrameId = null;
1545
- }
1546
- if (this.pendingFrame) {
1547
- this.pendingFrame.close();
1548
- this.pendingFrame = null;
1549
- }
1550
- }
1551
-
1552
- // Event handlers
1553
- setConnectionChangeHandler(handler: (connected: boolean) => void): void {
1554
- this.onConnectionChange = handler;
1555
- }
1556
-
1557
- setConnectionFailedHandler(handler: () => void): void {
1558
- this.onConnectionFailed = handler;
1559
- }
1560
-
1561
- setNavigationReconnectHandler(handler: () => void): void {
1562
- this.onNavigationReconnect = handler;
1563
- }
1564
-
1565
- setReconnectingStartHandler(handler: () => void): void {
1566
- this.onReconnectingStart = handler;
1567
- }
1568
-
1569
- setFirstFrameHandler(handler: () => void): void {
1570
- this.onFirstFrame = handler;
1571
- }
1572
-
1573
- /**
1574
- * Freeze frame rendering briefly during SPA navigation.
1575
- * Holds the current canvas content to prevent white flash during
1576
- * SPA page transitions (pushState/replaceState).
1577
- */
1578
- freezeForSpaNavigation(durationMs = 150): void {
1579
- this.spaFreezeUntil = Date.now() + durationMs;
1580
- }
1581
-
1582
- setErrorHandler(handler: (error: Error) => void): void {
1583
- this.onError = handler;
1584
- }
1585
-
1586
- setStatsHandler(handler: (stats: BrowserWebCodecsStreamStats) => void): void {
1587
- this.onStats = handler;
1588
- }
1589
-
1590
- setOnCursorChange(handler: (cursor: string) => void): void {
1591
- this.onCursorChange = handler;
1592
- }
1593
-
1594
- /**
1595
- * Set navigation state
1596
- * When navigating, DataChannel close/error won't trigger recovery
1597
- * Backend will restart streaming after navigation completes
1598
- */
1599
- setNavigating(navigating: boolean): void {
1600
- this.isNavigating = navigating;
1601
- // Clear safety timeout when navigation state is externally reset
1602
- if (!navigating && this.navigationSafetyTimeout) {
1603
- clearTimeout(this.navigationSafetyTimeout);
1604
- this.navigationSafetyTimeout = null;
1605
- }
1606
- debug.log('webcodecs', `Navigation state set: ${navigating}`);
1607
- }
1608
-
1609
- /**
1610
- * Check if currently navigating
1611
- */
1612
- getNavigating(): boolean {
1613
- return this.isNavigating;
1614
- }
1615
-
1616
- /**
1617
- * Destroy service
1618
- */
1619
- destroy(): void {
1620
- this.cleanup();
1621
-
1622
- // Close AudioContext only on full destroy (not reused after this)
1623
- if (this.audioContext && this.audioContext.state !== 'closed') {
1624
- this.audioContext.close().catch(() => {});
1625
- this.audioContext = null;
1626
- }
1627
-
1628
- this.onConnectionChange = null;
1629
- this.onConnectionFailed = null;
1630
- this.onNavigationReconnect = null;
1631
- this.onReconnectingStart = null;
1632
- this.onError = null;
1633
- this.onStats = null;
1634
- this.onCursorChange = null;
1635
-
1636
- // Remove user gesture listener
1637
- if (this.userGestureHandler) {
1638
- document.removeEventListener('click', this.userGestureHandler);
1639
- document.removeEventListener('keydown', this.userGestureHandler);
1640
- this.userGestureHandler = null;
1641
- }
1642
- }
1643
- }