@dtelecom/livekit-client 1.12.1

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 (279) hide show
  1. package/LICENSE +175 -0
  2. package/README.md +315 -0
  3. package/dist/@dtelecom/livekit-client.e2ee.worker.js +2 -0
  4. package/dist/@dtelecom/livekit-client.e2ee.worker.js.map +1 -0
  5. package/dist/@dtelecom/livekit-client.e2ee.worker.mjs +1633 -0
  6. package/dist/@dtelecom/livekit-client.e2ee.worker.mjs.map +1 -0
  7. package/dist/@dtelecom/livekit-client.esm.mjs +22545 -0
  8. package/dist/@dtelecom/livekit-client.esm.mjs.map +1 -0
  9. package/dist/@dtelecom/livekit-client.umd.js +2 -0
  10. package/dist/@dtelecom/livekit-client.umd.js.map +1 -0
  11. package/dist/@dtelecom/src/api/SignalClient.d.ts +102 -0
  12. package/dist/@dtelecom/src/api/SignalClient.d.ts.map +1 -0
  13. package/dist/@dtelecom/src/connectionHelper/ConnectionCheck.d.ts +26 -0
  14. package/dist/@dtelecom/src/connectionHelper/ConnectionCheck.d.ts.map +1 -0
  15. package/dist/@dtelecom/src/connectionHelper/checks/Checker.d.ts +59 -0
  16. package/dist/@dtelecom/src/connectionHelper/checks/Checker.d.ts.map +1 -0
  17. package/dist/@dtelecom/src/connectionHelper/checks/publishAudio.d.ts +6 -0
  18. package/dist/@dtelecom/src/connectionHelper/checks/publishAudio.d.ts.map +1 -0
  19. package/dist/@dtelecom/src/connectionHelper/checks/publishVideo.d.ts +6 -0
  20. package/dist/@dtelecom/src/connectionHelper/checks/publishVideo.d.ts.map +1 -0
  21. package/dist/@dtelecom/src/connectionHelper/checks/reconnect.d.ts +6 -0
  22. package/dist/@dtelecom/src/connectionHelper/checks/reconnect.d.ts.map +1 -0
  23. package/dist/@dtelecom/src/connectionHelper/checks/turn.d.ts +6 -0
  24. package/dist/@dtelecom/src/connectionHelper/checks/turn.d.ts.map +1 -0
  25. package/dist/@dtelecom/src/connectionHelper/checks/webrtc.d.ts +6 -0
  26. package/dist/@dtelecom/src/connectionHelper/checks/webrtc.d.ts.map +1 -0
  27. package/dist/@dtelecom/src/connectionHelper/checks/websocket.d.ts +6 -0
  28. package/dist/@dtelecom/src/connectionHelper/checks/websocket.d.ts.map +1 -0
  29. package/dist/@dtelecom/src/e2ee/E2eeManager.d.ts +47 -0
  30. package/dist/@dtelecom/src/e2ee/E2eeManager.d.ts.map +1 -0
  31. package/dist/@dtelecom/src/e2ee/KeyProvider.d.ts +44 -0
  32. package/dist/@dtelecom/src/e2ee/KeyProvider.d.ts.map +1 -0
  33. package/dist/@dtelecom/src/e2ee/constants.d.ts +15 -0
  34. package/dist/@dtelecom/src/e2ee/constants.d.ts.map +1 -0
  35. package/dist/@dtelecom/src/e2ee/errors.d.ts +11 -0
  36. package/dist/@dtelecom/src/e2ee/errors.d.ts.map +1 -0
  37. package/dist/@dtelecom/src/e2ee/index.d.ts +4 -0
  38. package/dist/@dtelecom/src/e2ee/index.d.ts.map +1 -0
  39. package/dist/@dtelecom/src/e2ee/types.d.ts +130 -0
  40. package/dist/@dtelecom/src/e2ee/types.d.ts.map +1 -0
  41. package/dist/@dtelecom/src/e2ee/utils.d.ts +24 -0
  42. package/dist/@dtelecom/src/e2ee/utils.d.ts.map +1 -0
  43. package/dist/@dtelecom/src/e2ee/worker/FrameCryptor.d.ts +176 -0
  44. package/dist/@dtelecom/src/e2ee/worker/FrameCryptor.d.ts.map +1 -0
  45. package/dist/@dtelecom/src/e2ee/worker/ParticipantKeyHandler.d.ts +65 -0
  46. package/dist/@dtelecom/src/e2ee/worker/ParticipantKeyHandler.d.ts.map +1 -0
  47. package/dist/@dtelecom/src/e2ee/worker/e2ee.worker.d.ts +2 -0
  48. package/dist/@dtelecom/src/e2ee/worker/e2ee.worker.d.ts.map +1 -0
  49. package/dist/@dtelecom/src/index.d.ts +38 -0
  50. package/dist/@dtelecom/src/index.d.ts.map +1 -0
  51. package/dist/@dtelecom/src/logger.d.ts +29 -0
  52. package/dist/@dtelecom/src/logger.d.ts.map +1 -0
  53. package/dist/@dtelecom/src/options.d.ts +104 -0
  54. package/dist/@dtelecom/src/options.d.ts.map +1 -0
  55. package/dist/@dtelecom/src/proto/livekit_models_pb.d.ts +1264 -0
  56. package/dist/@dtelecom/src/proto/livekit_models_pb.d.ts.map +1 -0
  57. package/dist/@dtelecom/src/proto/livekit_rtc_pb.d.ts +1373 -0
  58. package/dist/@dtelecom/src/proto/livekit_rtc_pb.d.ts.map +1 -0
  59. package/dist/@dtelecom/src/room/DefaultReconnectPolicy.d.ts +8 -0
  60. package/dist/@dtelecom/src/room/DefaultReconnectPolicy.d.ts.map +1 -0
  61. package/dist/@dtelecom/src/room/DeviceManager.d.ts +9 -0
  62. package/dist/@dtelecom/src/room/DeviceManager.d.ts.map +1 -0
  63. package/dist/@dtelecom/src/room/PCTransport.d.ts +41 -0
  64. package/dist/@dtelecom/src/room/PCTransport.d.ts.map +1 -0
  65. package/dist/@dtelecom/src/room/RTCEngine.d.ts +143 -0
  66. package/dist/@dtelecom/src/room/RTCEngine.d.ts.map +1 -0
  67. package/dist/@dtelecom/src/room/ReconnectPolicy.d.ts +24 -0
  68. package/dist/@dtelecom/src/room/ReconnectPolicy.d.ts.map +1 -0
  69. package/dist/@dtelecom/src/room/RegionUrlProvider.d.ts +17 -0
  70. package/dist/@dtelecom/src/room/RegionUrlProvider.d.ts.map +1 -0
  71. package/dist/@dtelecom/src/room/Room.d.ts +248 -0
  72. package/dist/@dtelecom/src/room/Room.d.ts.map +1 -0
  73. package/dist/@dtelecom/src/room/defaults.d.ts +8 -0
  74. package/dist/@dtelecom/src/room/defaults.d.ts.map +1 -0
  75. package/dist/@dtelecom/src/room/errors.d.ts +43 -0
  76. package/dist/@dtelecom/src/room/errors.d.ts.map +1 -0
  77. package/dist/@dtelecom/src/room/events.d.ts +477 -0
  78. package/dist/@dtelecom/src/room/events.d.ts.map +1 -0
  79. package/dist/@dtelecom/src/room/participant/LocalParticipant.d.ts +177 -0
  80. package/dist/@dtelecom/src/room/participant/LocalParticipant.d.ts.map +1 -0
  81. package/dist/@dtelecom/src/room/participant/Participant.d.ts +95 -0
  82. package/dist/@dtelecom/src/room/participant/Participant.d.ts.map +1 -0
  83. package/dist/@dtelecom/src/room/participant/ParticipantTrackPermission.d.ts +26 -0
  84. package/dist/@dtelecom/src/room/participant/ParticipantTrackPermission.d.ts.map +1 -0
  85. package/dist/@dtelecom/src/room/participant/RemoteParticipant.d.ts +55 -0
  86. package/dist/@dtelecom/src/room/participant/RemoteParticipant.d.ts.map +1 -0
  87. package/dist/@dtelecom/src/room/participant/publishUtils.d.ts +28 -0
  88. package/dist/@dtelecom/src/room/participant/publishUtils.d.ts.map +1 -0
  89. package/dist/@dtelecom/src/room/stats.d.ts +67 -0
  90. package/dist/@dtelecom/src/room/stats.d.ts.map +1 -0
  91. package/dist/@dtelecom/src/room/timers.d.ts +13 -0
  92. package/dist/@dtelecom/src/room/timers.d.ts.map +1 -0
  93. package/dist/@dtelecom/src/room/track/LocalAudioTrack.d.ts +25 -0
  94. package/dist/@dtelecom/src/room/track/LocalAudioTrack.d.ts.map +1 -0
  95. package/dist/@dtelecom/src/room/track/LocalTrack.d.ts +78 -0
  96. package/dist/@dtelecom/src/room/track/LocalTrack.d.ts.map +1 -0
  97. package/dist/@dtelecom/src/room/track/LocalTrackPublication.d.ts +38 -0
  98. package/dist/@dtelecom/src/room/track/LocalTrackPublication.d.ts.map +1 -0
  99. package/dist/@dtelecom/src/room/track/LocalVideoTrack.d.ts +54 -0
  100. package/dist/@dtelecom/src/room/track/LocalVideoTrack.d.ts.map +1 -0
  101. package/dist/@dtelecom/src/room/track/RemoteAudioTrack.d.ts +53 -0
  102. package/dist/@dtelecom/src/room/track/RemoteAudioTrack.d.ts.map +1 -0
  103. package/dist/@dtelecom/src/room/track/RemoteTrack.d.ts +15 -0
  104. package/dist/@dtelecom/src/room/track/RemoteTrack.d.ts.map +1 -0
  105. package/dist/@dtelecom/src/room/track/RemoteTrackPublication.d.ts +64 -0
  106. package/dist/@dtelecom/src/room/track/RemoteTrackPublication.d.ts.map +1 -0
  107. package/dist/@dtelecom/src/room/track/RemoteVideoTrack.d.ts +56 -0
  108. package/dist/@dtelecom/src/room/track/RemoteVideoTrack.d.ts.map +1 -0
  109. package/dist/@dtelecom/src/room/track/Track.d.ts +125 -0
  110. package/dist/@dtelecom/src/room/track/Track.d.ts.map +1 -0
  111. package/dist/@dtelecom/src/room/track/TrackPublication.d.ts +72 -0
  112. package/dist/@dtelecom/src/room/track/TrackPublication.d.ts.map +1 -0
  113. package/dist/@dtelecom/src/room/track/create.d.ts +24 -0
  114. package/dist/@dtelecom/src/room/track/create.d.ts.map +1 -0
  115. package/dist/@dtelecom/src/room/track/facingMode.d.ts +41 -0
  116. package/dist/@dtelecom/src/room/track/facingMode.d.ts.map +1 -0
  117. package/dist/@dtelecom/src/room/track/options.d.ts +272 -0
  118. package/dist/@dtelecom/src/room/track/options.d.ts.map +1 -0
  119. package/dist/@dtelecom/src/room/track/processor/types.d.ts +19 -0
  120. package/dist/@dtelecom/src/room/track/processor/types.d.ts.map +1 -0
  121. package/dist/@dtelecom/src/room/track/types.d.ts +24 -0
  122. package/dist/@dtelecom/src/room/track/types.d.ts.map +1 -0
  123. package/dist/@dtelecom/src/room/track/utils.d.ts +27 -0
  124. package/dist/@dtelecom/src/room/track/utils.d.ts.map +1 -0
  125. package/dist/@dtelecom/src/room/types.d.ts +26 -0
  126. package/dist/@dtelecom/src/room/types.d.ts.map +1 -0
  127. package/dist/@dtelecom/src/room/utils.d.ts +92 -0
  128. package/dist/@dtelecom/src/room/utils.d.ts.map +1 -0
  129. package/dist/@dtelecom/src/test/MockMediaStreamTrack.d.ts +26 -0
  130. package/dist/@dtelecom/src/test/MockMediaStreamTrack.d.ts.map +1 -0
  131. package/dist/@dtelecom/src/test/mocks.d.ts +12 -0
  132. package/dist/@dtelecom/src/test/mocks.d.ts.map +1 -0
  133. package/dist/@dtelecom/src/utils/AsyncQueue.d.ts +23 -0
  134. package/dist/@dtelecom/src/utils/AsyncQueue.d.ts.map +1 -0
  135. package/dist/@dtelecom/src/utils/browserParser.d.ts +12 -0
  136. package/dist/@dtelecom/src/utils/browserParser.d.ts.map +1 -0
  137. package/dist/@dtelecom/src/version.d.ts +3 -0
  138. package/dist/@dtelecom/src/version.d.ts.map +1 -0
  139. package/dist/ts4.2/@dtelecom/src/api/SignalClient.d.ts +105 -0
  140. package/dist/ts4.2/@dtelecom/src/connectionHelper/ConnectionCheck.d.ts +26 -0
  141. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/Checker.d.ts +59 -0
  142. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/publishAudio.d.ts +6 -0
  143. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/publishVideo.d.ts +6 -0
  144. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/reconnect.d.ts +6 -0
  145. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/turn.d.ts +6 -0
  146. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/webrtc.d.ts +6 -0
  147. package/dist/ts4.2/@dtelecom/src/connectionHelper/checks/websocket.d.ts +6 -0
  148. package/dist/ts4.2/@dtelecom/src/e2ee/E2eeManager.d.ts +47 -0
  149. package/dist/ts4.2/@dtelecom/src/e2ee/KeyProvider.d.ts +44 -0
  150. package/dist/ts4.2/@dtelecom/src/e2ee/constants.d.ts +15 -0
  151. package/dist/ts4.2/@dtelecom/src/e2ee/errors.d.ts +11 -0
  152. package/dist/ts4.2/@dtelecom/src/e2ee/index.d.ts +4 -0
  153. package/dist/ts4.2/@dtelecom/src/e2ee/types.d.ts +130 -0
  154. package/dist/ts4.2/@dtelecom/src/e2ee/utils.d.ts +24 -0
  155. package/dist/ts4.2/@dtelecom/src/e2ee/worker/FrameCryptor.d.ts +176 -0
  156. package/dist/ts4.2/@dtelecom/src/e2ee/worker/ParticipantKeyHandler.d.ts +65 -0
  157. package/dist/ts4.2/@dtelecom/src/e2ee/worker/e2ee.worker.d.ts +2 -0
  158. package/dist/ts4.2/@dtelecom/src/index.d.ts +38 -0
  159. package/dist/ts4.2/@dtelecom/src/logger.d.ts +29 -0
  160. package/dist/ts4.2/@dtelecom/src/options.d.ts +104 -0
  161. package/dist/ts4.2/@dtelecom/src/proto/livekit_models_pb.d.ts +1264 -0
  162. package/dist/ts4.2/@dtelecom/src/proto/livekit_rtc_pb.d.ts +1373 -0
  163. package/dist/ts4.2/@dtelecom/src/room/DefaultReconnectPolicy.d.ts +8 -0
  164. package/dist/ts4.2/@dtelecom/src/room/DeviceManager.d.ts +9 -0
  165. package/dist/ts4.2/@dtelecom/src/room/PCTransport.d.ts +43 -0
  166. package/dist/ts4.2/@dtelecom/src/room/RTCEngine.d.ts +143 -0
  167. package/dist/ts4.2/@dtelecom/src/room/ReconnectPolicy.d.ts +24 -0
  168. package/dist/ts4.2/@dtelecom/src/room/RegionUrlProvider.d.ts +17 -0
  169. package/dist/ts4.2/@dtelecom/src/room/Room.d.ts +248 -0
  170. package/dist/ts4.2/@dtelecom/src/room/defaults.d.ts +8 -0
  171. package/dist/ts4.2/@dtelecom/src/room/errors.d.ts +43 -0
  172. package/dist/ts4.2/@dtelecom/src/room/events.d.ts +477 -0
  173. package/dist/ts4.2/@dtelecom/src/room/participant/LocalParticipant.d.ts +177 -0
  174. package/dist/ts4.2/@dtelecom/src/room/participant/Participant.d.ts +95 -0
  175. package/dist/ts4.2/@dtelecom/src/room/participant/ParticipantTrackPermission.d.ts +26 -0
  176. package/dist/ts4.2/@dtelecom/src/room/participant/RemoteParticipant.d.ts +55 -0
  177. package/dist/ts4.2/@dtelecom/src/room/participant/publishUtils.d.ts +28 -0
  178. package/dist/ts4.2/@dtelecom/src/room/stats.d.ts +67 -0
  179. package/dist/ts4.2/@dtelecom/src/room/timers.d.ts +13 -0
  180. package/dist/ts4.2/@dtelecom/src/room/track/LocalAudioTrack.d.ts +25 -0
  181. package/dist/ts4.2/@dtelecom/src/room/track/LocalTrack.d.ts +78 -0
  182. package/dist/ts4.2/@dtelecom/src/room/track/LocalTrackPublication.d.ts +38 -0
  183. package/dist/ts4.2/@dtelecom/src/room/track/LocalVideoTrack.d.ts +54 -0
  184. package/dist/ts4.2/@dtelecom/src/room/track/RemoteAudioTrack.d.ts +53 -0
  185. package/dist/ts4.2/@dtelecom/src/room/track/RemoteTrack.d.ts +15 -0
  186. package/dist/ts4.2/@dtelecom/src/room/track/RemoteTrackPublication.d.ts +64 -0
  187. package/dist/ts4.2/@dtelecom/src/room/track/RemoteVideoTrack.d.ts +56 -0
  188. package/dist/ts4.2/@dtelecom/src/room/track/Track.d.ts +125 -0
  189. package/dist/ts4.2/@dtelecom/src/room/track/TrackPublication.d.ts +72 -0
  190. package/dist/ts4.2/@dtelecom/src/room/track/create.d.ts +24 -0
  191. package/dist/ts4.2/@dtelecom/src/room/track/facingMode.d.ts +41 -0
  192. package/dist/ts4.2/@dtelecom/src/room/track/options.d.ts +280 -0
  193. package/dist/ts4.2/@dtelecom/src/room/track/processor/types.d.ts +19 -0
  194. package/dist/ts4.2/@dtelecom/src/room/track/types.d.ts +24 -0
  195. package/dist/ts4.2/@dtelecom/src/room/track/utils.d.ts +27 -0
  196. package/dist/ts4.2/@dtelecom/src/room/types.d.ts +26 -0
  197. package/dist/ts4.2/@dtelecom/src/room/utils.d.ts +92 -0
  198. package/dist/ts4.2/@dtelecom/src/test/MockMediaStreamTrack.d.ts +26 -0
  199. package/dist/ts4.2/@dtelecom/src/test/mocks.d.ts +12 -0
  200. package/dist/ts4.2/@dtelecom/src/utils/AsyncQueue.d.ts +23 -0
  201. package/dist/ts4.2/@dtelecom/src/utils/browserParser.d.ts +12 -0
  202. package/dist/ts4.2/@dtelecom/src/version.d.ts +3 -0
  203. package/package.json +102 -0
  204. package/src/api/SignalClient.ts +790 -0
  205. package/src/connectionHelper/ConnectionCheck.ts +90 -0
  206. package/src/connectionHelper/checks/Checker.ts +163 -0
  207. package/src/connectionHelper/checks/publishAudio.ts +33 -0
  208. package/src/connectionHelper/checks/publishVideo.ts +33 -0
  209. package/src/connectionHelper/checks/reconnect.ts +45 -0
  210. package/src/connectionHelper/checks/turn.ts +54 -0
  211. package/src/connectionHelper/checks/webrtc.ts +82 -0
  212. package/src/connectionHelper/checks/websocket.ts +27 -0
  213. package/src/e2ee/E2eeManager.ts +375 -0
  214. package/src/e2ee/KeyProvider.ts +78 -0
  215. package/src/e2ee/constants.ts +44 -0
  216. package/src/e2ee/errors.ts +16 -0
  217. package/src/e2ee/index.ts +3 -0
  218. package/src/e2ee/types.ts +161 -0
  219. package/src/e2ee/utils.ts +127 -0
  220. package/src/e2ee/worker/FrameCryptor.test.ts +19 -0
  221. package/src/e2ee/worker/FrameCryptor.ts +612 -0
  222. package/src/e2ee/worker/ParticipantKeyHandler.ts +175 -0
  223. package/src/e2ee/worker/e2ee.worker.ts +223 -0
  224. package/src/e2ee/worker/tsconfig.json +6 -0
  225. package/src/index.ts +85 -0
  226. package/src/logger.ts +64 -0
  227. package/src/options.ts +127 -0
  228. package/src/proto/livekit_models_pb.ts +2096 -0
  229. package/src/proto/livekit_rtc_pb.ts +2332 -0
  230. package/src/room/DefaultReconnectPolicy.ts +35 -0
  231. package/src/room/DeviceManager.ts +88 -0
  232. package/src/room/PCTransport.ts +452 -0
  233. package/src/room/RTCEngine.ts +1421 -0
  234. package/src/room/ReconnectPolicy.ts +27 -0
  235. package/src/room/RegionUrlProvider.ts +82 -0
  236. package/src/room/Room.test.ts +30 -0
  237. package/src/room/Room.ts +1907 -0
  238. package/src/room/defaults.ts +49 -0
  239. package/src/room/errors.ts +90 -0
  240. package/src/room/events.ts +535 -0
  241. package/src/room/participant/LocalParticipant.ts +1350 -0
  242. package/src/room/participant/Participant.ts +299 -0
  243. package/src/room/participant/ParticipantTrackPermission.ts +42 -0
  244. package/src/room/participant/RemoteParticipant.ts +359 -0
  245. package/src/room/participant/publishUtils.test.ts +189 -0
  246. package/src/room/participant/publishUtils.ts +399 -0
  247. package/src/room/stats.ts +136 -0
  248. package/src/room/timers.ts +16 -0
  249. package/src/room/track/LocalAudioTrack.ts +171 -0
  250. package/src/room/track/LocalTrack.ts +430 -0
  251. package/src/room/track/LocalTrackPublication.ts +87 -0
  252. package/src/room/track/LocalVideoTrack.test.ts +73 -0
  253. package/src/room/track/LocalVideoTrack.ts +513 -0
  254. package/src/room/track/RemoteAudioTrack.ts +248 -0
  255. package/src/room/track/RemoteTrack.ts +62 -0
  256. package/src/room/track/RemoteTrackPublication.ts +311 -0
  257. package/src/room/track/RemoteVideoTrack.test.ts +152 -0
  258. package/src/room/track/RemoteVideoTrack.ts +410 -0
  259. package/src/room/track/Track.ts +452 -0
  260. package/src/room/track/TrackPublication.ts +158 -0
  261. package/src/room/track/create.ts +143 -0
  262. package/src/room/track/facingMode.test.ts +31 -0
  263. package/src/room/track/facingMode.ts +103 -0
  264. package/src/room/track/options.ts +362 -0
  265. package/src/room/track/processor/types.ts +20 -0
  266. package/src/room/track/types.ts +25 -0
  267. package/src/room/track/utils.test.ts +111 -0
  268. package/src/room/track/utils.ts +183 -0
  269. package/src/room/types.ts +39 -0
  270. package/src/room/utils.test.ts +16 -0
  271. package/src/room/utils.ts +501 -0
  272. package/src/room/worker.d.ts +4 -0
  273. package/src/test/MockMediaStreamTrack.ts +84 -0
  274. package/src/test/mocks.ts +19 -0
  275. package/src/utils/AsyncQueue.test.ts +100 -0
  276. package/src/utils/AsyncQueue.ts +57 -0
  277. package/src/utils/browserParser.test.ts +88 -0
  278. package/src/utils/browserParser.ts +74 -0
  279. package/src/version.ts +4 -0
@@ -0,0 +1,1421 @@
1
+ import { EventEmitter } from 'events';
2
+ import type { MediaAttributes } from 'sdp-transform';
3
+ import type TypedEventEmitter from 'typed-emitter';
4
+ import type { SignalOptions } from '../api/SignalClient';
5
+ import { SignalClient } from '../api/SignalClient';
6
+ import log from '../logger';
7
+ import type { InternalRoomOptions } from '../options';
8
+ import {
9
+ ClientConfigSetting,
10
+ ClientConfiguration,
11
+ DataPacket,
12
+ DataPacket_Kind,
13
+ DisconnectReason,
14
+ ParticipantInfo,
15
+ ReconnectReason,
16
+ Room as RoomModel,
17
+ SpeakerInfo,
18
+ TrackInfo,
19
+ UserPacket,
20
+ } from '../proto/livekit_models_pb';
21
+ import {
22
+ AddTrackRequest,
23
+ ConnectionQualityUpdate,
24
+ JoinResponse,
25
+ LeaveRequest,
26
+ ReconnectResponse,
27
+ SignalTarget,
28
+ StreamStateUpdate,
29
+ SubscriptionPermissionUpdate,
30
+ SubscriptionResponse,
31
+ TrackPublishedResponse,
32
+ } from '../proto/livekit_rtc_pb';
33
+ import PCTransport, { PCEvents } from './PCTransport';
34
+ import type { ReconnectContext, ReconnectPolicy } from './ReconnectPolicy';
35
+ import type { RegionUrlProvider } from './RegionUrlProvider';
36
+ import { roomConnectOptionDefaults } from './defaults';
37
+ import {
38
+ ConnectionError,
39
+ ConnectionErrorReason,
40
+ NegotiationError,
41
+ TrackInvalidError,
42
+ UnexpectedConnectionState,
43
+ } from './errors';
44
+ import { EngineEvent } from './events';
45
+ import CriticalTimers from './timers';
46
+ import type LocalTrack from './track/LocalTrack';
47
+ import type LocalVideoTrack from './track/LocalVideoTrack';
48
+ import type { SimulcastTrackInfo } from './track/LocalVideoTrack';
49
+ import { Track } from './track/Track';
50
+ import type { TrackPublishOptions, VideoCodec } from './track/options';
51
+ import {
52
+ Mutex,
53
+ isVideoCodec,
54
+ isWeb,
55
+ sleep,
56
+ supportsAddTrack,
57
+ supportsSetCodecPreferences,
58
+ supportsTransceiver,
59
+ } from './utils';
60
+
61
+ const lossyDataChannel = '_lossy';
62
+ const reliableDataChannel = '_reliable';
63
+ const minReconnectWait = 2 * 1000;
64
+ const leaveReconnect = 'leave-reconnect';
65
+
66
+ enum PCState {
67
+ New,
68
+ Connected,
69
+ Disconnected,
70
+ Reconnecting,
71
+ Closed,
72
+ }
73
+
74
+ /** @internal */
75
+ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmitter<EngineEventCallbacks>) {
76
+ publisher?: PCTransport;
77
+
78
+ subscriber?: PCTransport;
79
+
80
+ client: SignalClient;
81
+
82
+ rtcConfig: RTCConfiguration = {};
83
+
84
+ peerConnectionTimeout: number = roomConnectOptionDefaults.peerConnectionTimeout;
85
+
86
+ fullReconnectOnNext: boolean = false;
87
+
88
+ /**
89
+ * @internal
90
+ */
91
+ latestJoinResponse?: JoinResponse;
92
+
93
+ get isClosed() {
94
+ return this._isClosed;
95
+ }
96
+
97
+ private lossyDC?: RTCDataChannel;
98
+
99
+ // @ts-ignore noUnusedLocals
100
+ private lossyDCSub?: RTCDataChannel;
101
+
102
+ private reliableDC?: RTCDataChannel;
103
+
104
+ private dcBufferStatus: Map<DataPacket_Kind, boolean>;
105
+
106
+ // @ts-ignore noUnusedLocals
107
+ private reliableDCSub?: RTCDataChannel;
108
+
109
+ private subscriberPrimary: boolean = false;
110
+
111
+ private primaryPC?: RTCPeerConnection;
112
+
113
+ private pcState: PCState = PCState.New;
114
+
115
+ private _isClosed: boolean = true;
116
+
117
+ private pendingTrackResolvers: {
118
+ [key: string]: { resolve: (info: TrackInfo) => void; reject: () => void };
119
+ } = {};
120
+
121
+ // true if publisher connection has already been established.
122
+ // this is helpful to know if we need to restart ICE on the publisher connection
123
+ private hasPublished: boolean = false;
124
+
125
+ // keep join info around for reconnect, this could be a region url
126
+ private url?: string;
127
+
128
+ private token?: string;
129
+
130
+ private signalOpts?: SignalOptions;
131
+
132
+ private reconnectAttempts: number = 0;
133
+
134
+ private reconnectStart: number = 0;
135
+
136
+ private clientConfiguration?: ClientConfiguration;
137
+
138
+ private attemptingReconnect: boolean = false;
139
+
140
+ private reconnectPolicy: ReconnectPolicy;
141
+
142
+ private reconnectTimeout?: ReturnType<typeof setTimeout>;
143
+
144
+ private participantSid?: string;
145
+
146
+ /** keeps track of how often an initial join connection has been tried */
147
+ private joinAttempts: number = 0;
148
+
149
+ /** specifies how often an initial join connection is allowed to retry */
150
+ private maxJoinAttempts: number = 1;
151
+
152
+ private closingLock: Mutex;
153
+
154
+ private dataProcessLock: Mutex;
155
+
156
+ private shouldFailNext: boolean = false;
157
+
158
+ private regionUrlProvider?: RegionUrlProvider;
159
+
160
+ constructor(private options: InternalRoomOptions) {
161
+ super();
162
+ this.client = new SignalClient();
163
+ this.client.signalLatency = this.options.expSignalLatency;
164
+ this.reconnectPolicy = this.options.reconnectPolicy;
165
+ this.registerOnLineListener();
166
+ this.closingLock = new Mutex();
167
+ this.dataProcessLock = new Mutex();
168
+ this.dcBufferStatus = new Map([
169
+ [DataPacket_Kind.LOSSY, true],
170
+ [DataPacket_Kind.RELIABLE, true],
171
+ ]);
172
+
173
+ this.client.onParticipantUpdate = (updates) =>
174
+ this.emit(EngineEvent.ParticipantUpdate, updates);
175
+ this.client.onConnectionQuality = (update) =>
176
+ this.emit(EngineEvent.ConnectionQualityUpdate, update);
177
+ this.client.onRoomUpdate = (update) => this.emit(EngineEvent.RoomUpdate, update);
178
+ this.client.onSubscriptionError = (resp) => this.emit(EngineEvent.SubscriptionError, resp);
179
+ this.client.onSubscriptionPermissionUpdate = (update) =>
180
+ this.emit(EngineEvent.SubscriptionPermissionUpdate, update);
181
+ this.client.onSpeakersChanged = (update) => this.emit(EngineEvent.SpeakersChanged, update);
182
+ this.client.onStreamStateUpdate = (update) => this.emit(EngineEvent.StreamStateChanged, update);
183
+ }
184
+
185
+ async join(
186
+ url: string,
187
+ token: string,
188
+ opts: SignalOptions,
189
+ abortSignal?: AbortSignal,
190
+ ): Promise<JoinResponse> {
191
+ this.url = url;
192
+ this.token = token;
193
+ this.signalOpts = opts;
194
+ try {
195
+ this.joinAttempts += 1;
196
+ const joinResponse = await this.client.join(url, token, opts, abortSignal);
197
+ this._isClosed = false;
198
+ this.latestJoinResponse = joinResponse;
199
+
200
+ this.subscriberPrimary = joinResponse.subscriberPrimary;
201
+ if (!this.publisher) {
202
+ this.configure(joinResponse);
203
+ }
204
+
205
+ // create offer
206
+ if (!this.subscriberPrimary) {
207
+ this.negotiate();
208
+ }
209
+ this.setupSignalClientCallbacks();
210
+
211
+ this.clientConfiguration = joinResponse.clientConfiguration;
212
+
213
+ return joinResponse;
214
+ } catch (e) {
215
+ if (e instanceof ConnectionError) {
216
+ if (e.reason === ConnectionErrorReason.ServerUnreachable) {
217
+ log.warn(
218
+ `Couldn't connect to server, attempt ${this.joinAttempts} of ${this.maxJoinAttempts}`,
219
+ );
220
+ if (this.joinAttempts < this.maxJoinAttempts) {
221
+ return this.join(url, token, opts, abortSignal);
222
+ }
223
+ }
224
+ }
225
+ throw e;
226
+ }
227
+ }
228
+
229
+ async close() {
230
+ const unlock = await this.closingLock.lock();
231
+ if (this.isClosed) {
232
+ unlock();
233
+ return;
234
+ }
235
+ try {
236
+ this._isClosed = true;
237
+ this.emit(EngineEvent.Closing);
238
+ this.removeAllListeners();
239
+ this.deregisterOnLineListener();
240
+ this.clearPendingReconnect();
241
+ await this.cleanupPeerConnections();
242
+ await this.cleanupClient();
243
+ } finally {
244
+ unlock();
245
+ }
246
+ }
247
+
248
+ async cleanupPeerConnections() {
249
+ if (this.publisher && this.publisher.pc.signalingState !== 'closed') {
250
+ this.publisher.pc.getSenders().forEach((sender) => {
251
+ try {
252
+ // TODO: react-native-webrtc doesn't have removeTrack yet.
253
+ if (this.publisher?.pc.removeTrack) {
254
+ this.publisher?.pc.removeTrack(sender);
255
+ }
256
+ } catch (e) {
257
+ log.warn('could not removeTrack', { error: e });
258
+ }
259
+ });
260
+ }
261
+ if (this.publisher) {
262
+ this.publisher.close();
263
+ this.publisher = undefined;
264
+ }
265
+ if (this.subscriber) {
266
+ this.subscriber.close();
267
+ this.subscriber = undefined;
268
+ }
269
+
270
+ this.primaryPC = undefined;
271
+
272
+ const dcCleanup = (dc: RTCDataChannel | undefined) => {
273
+ if (!dc) return;
274
+ dc.close();
275
+ dc.onbufferedamountlow = null;
276
+ dc.onclose = null;
277
+ dc.onclosing = null;
278
+ dc.onerror = null;
279
+ dc.onmessage = null;
280
+ dc.onopen = null;
281
+ };
282
+ dcCleanup(this.lossyDC);
283
+ dcCleanup(this.lossyDCSub);
284
+ dcCleanup(this.reliableDC);
285
+ dcCleanup(this.reliableDCSub);
286
+
287
+ this.lossyDC = undefined;
288
+ this.lossyDCSub = undefined;
289
+ this.reliableDC = undefined;
290
+ this.reliableDCSub = undefined;
291
+ }
292
+
293
+ async cleanupClient() {
294
+ await this.client.close();
295
+ this.client.resetCallbacks();
296
+ }
297
+
298
+ addTrack(req: AddTrackRequest): Promise<TrackInfo> {
299
+ if (this.pendingTrackResolvers[req.cid]) {
300
+ throw new TrackInvalidError('a track with the same ID has already been published');
301
+ }
302
+ return new Promise<TrackInfo>((resolve, reject) => {
303
+ const publicationTimeout = setTimeout(() => {
304
+ delete this.pendingTrackResolvers[req.cid];
305
+ reject(
306
+ new ConnectionError('publication of local track timed out, no response from server'),
307
+ );
308
+ }, 10_000);
309
+ this.pendingTrackResolvers[req.cid] = {
310
+ resolve: (info: TrackInfo) => {
311
+ clearTimeout(publicationTimeout);
312
+ resolve(info);
313
+ },
314
+ reject: () => {
315
+ clearTimeout(publicationTimeout);
316
+ reject(new Error('Cancelled publication by calling unpublish'));
317
+ },
318
+ };
319
+ this.client.sendAddTrack(req);
320
+ });
321
+ }
322
+
323
+ /**
324
+ * Removes sender from PeerConnection, returning true if it was removed successfully
325
+ * and a negotiation is necessary
326
+ * @param sender
327
+ * @returns
328
+ */
329
+ removeTrack(sender: RTCRtpSender): boolean {
330
+ if (sender.track && this.pendingTrackResolvers[sender.track.id]) {
331
+ const { reject } = this.pendingTrackResolvers[sender.track.id];
332
+ if (reject) {
333
+ reject();
334
+ }
335
+ delete this.pendingTrackResolvers[sender.track.id];
336
+ }
337
+ try {
338
+ this.publisher?.pc.removeTrack(sender);
339
+ return true;
340
+ } catch (e: unknown) {
341
+ log.warn('failed to remove track', { error: e, method: 'removeTrack' });
342
+ }
343
+ return false;
344
+ }
345
+
346
+ updateMuteStatus(trackSid: string, muted: boolean) {
347
+ this.client.sendMuteTrack(trackSid, muted);
348
+ }
349
+
350
+ get dataSubscriberReadyState(): string | undefined {
351
+ return this.reliableDCSub?.readyState;
352
+ }
353
+
354
+ async getConnectedServerAddress(): Promise<string | undefined> {
355
+ if (this.primaryPC === undefined) {
356
+ return undefined;
357
+ }
358
+ return getConnectedAddress(this.primaryPC);
359
+ }
360
+
361
+ /* @internal */
362
+ setRegionUrlProvider(provider: RegionUrlProvider) {
363
+ this.regionUrlProvider = provider;
364
+ }
365
+
366
+ private configure(joinResponse: JoinResponse) {
367
+ // already configured
368
+ if (this.publisher || this.subscriber) {
369
+ return;
370
+ }
371
+
372
+ this.participantSid = joinResponse.participant?.sid;
373
+
374
+ const rtcConfig = this.makeRTCConfiguration(joinResponse);
375
+
376
+ if (this.signalOpts?.e2eeEnabled) {
377
+ log.debug('E2EE - setting up transports with insertable streams');
378
+ // this makes sure that no data is sent before the transforms are ready
379
+ // @ts-ignore
380
+ rtcConfig.encodedInsertableStreams = true;
381
+ }
382
+
383
+ const googConstraints = { optional: [{ googDscp: true }] };
384
+ this.publisher = new PCTransport(rtcConfig, googConstraints);
385
+ this.subscriber = new PCTransport(rtcConfig);
386
+
387
+ this.emit(EngineEvent.TransportsCreated, this.publisher, this.subscriber);
388
+
389
+ this.publisher.pc.onicecandidate = (ev) => {
390
+ if (!ev.candidate) return;
391
+ log.trace('adding ICE candidate for peer', ev.candidate);
392
+ this.client.sendIceCandidate(ev.candidate, SignalTarget.PUBLISHER);
393
+ };
394
+
395
+ this.subscriber.pc.onicecandidate = (ev) => {
396
+ if (!ev.candidate) return;
397
+ this.client.sendIceCandidate(ev.candidate, SignalTarget.SUBSCRIBER);
398
+ };
399
+
400
+ this.publisher.onOffer = (offer) => {
401
+ this.client.sendOffer(offer);
402
+ };
403
+
404
+ let primaryPC = this.publisher.pc;
405
+ let secondaryPC = this.subscriber.pc;
406
+ let subscriberPrimary = joinResponse.subscriberPrimary;
407
+ if (subscriberPrimary) {
408
+ primaryPC = this.subscriber.pc;
409
+ secondaryPC = this.publisher.pc;
410
+ // in subscriber primary mode, server side opens sub data channels.
411
+ this.subscriber.pc.ondatachannel = this.handleDataChannel;
412
+ }
413
+ this.primaryPC = primaryPC;
414
+ primaryPC.onconnectionstatechange = async () => {
415
+ log.debug(`primary PC state changed ${primaryPC.connectionState}`);
416
+ if (primaryPC.connectionState === 'connected') {
417
+ const shouldEmit = this.pcState === PCState.New;
418
+ this.pcState = PCState.Connected;
419
+ if (shouldEmit) {
420
+ this.emit(EngineEvent.Connected, joinResponse);
421
+ }
422
+ } else if (primaryPC.connectionState === 'failed') {
423
+ // on Safari, PeerConnection will switch to 'disconnected' during renegotiation
424
+ if (this.pcState === PCState.Connected) {
425
+ this.pcState = PCState.Disconnected;
426
+
427
+ this.handleDisconnect(
428
+ 'primary peerconnection',
429
+ subscriberPrimary
430
+ ? ReconnectReason.RR_SUBSCRIBER_FAILED
431
+ : ReconnectReason.RR_PUBLISHER_FAILED,
432
+ );
433
+ }
434
+ }
435
+ };
436
+ secondaryPC.onconnectionstatechange = async () => {
437
+ log.debug(`secondary PC state changed ${secondaryPC.connectionState}`);
438
+ // also reconnect if secondary peerconnection fails
439
+ if (secondaryPC.connectionState === 'failed') {
440
+ this.handleDisconnect(
441
+ 'secondary peerconnection',
442
+ subscriberPrimary
443
+ ? ReconnectReason.RR_PUBLISHER_FAILED
444
+ : ReconnectReason.RR_SUBSCRIBER_FAILED,
445
+ );
446
+ }
447
+ };
448
+
449
+ this.subscriber.pc.ontrack = (ev: RTCTrackEvent) => {
450
+ this.emit(EngineEvent.MediaTrackAdded, ev.track, ev.streams[0], ev.receiver);
451
+ };
452
+
453
+ this.createDataChannels();
454
+ }
455
+
456
+ private setupSignalClientCallbacks() {
457
+ // configure signaling client
458
+ this.client.onAnswer = async (sd) => {
459
+ if (!this.publisher) {
460
+ return;
461
+ }
462
+ log.debug('received server answer', {
463
+ RTCSdpType: sd.type,
464
+ signalingState: this.publisher.pc.signalingState.toString(),
465
+ });
466
+ await this.publisher.setRemoteDescription(sd);
467
+ };
468
+
469
+ // add candidate on trickle
470
+ this.client.onTrickle = (candidate, target) => {
471
+ if (!this.publisher || !this.subscriber) {
472
+ return;
473
+ }
474
+ log.trace('got ICE candidate from peer', { candidate, target });
475
+ if (target === SignalTarget.PUBLISHER) {
476
+ this.publisher.addIceCandidate(candidate);
477
+ } else {
478
+ this.subscriber.addIceCandidate(candidate);
479
+ }
480
+ };
481
+
482
+ // when server creates an offer for the client
483
+ this.client.onOffer = async (sd) => {
484
+ if (!this.subscriber) {
485
+ return;
486
+ }
487
+ log.debug('received server offer', {
488
+ RTCSdpType: sd.type,
489
+ signalingState: this.subscriber.pc.signalingState.toString(),
490
+ });
491
+ await this.subscriber.setRemoteDescription(sd);
492
+
493
+ // answer the offer
494
+ const answer = await this.subscriber.createAndSetAnswer();
495
+ this.client.sendAnswer(answer);
496
+ };
497
+
498
+ this.client.onLocalTrackPublished = (res: TrackPublishedResponse) => {
499
+ log.debug('received trackPublishedResponse', res);
500
+ const { resolve } = this.pendingTrackResolvers[res.cid];
501
+ if (!resolve) {
502
+ log.error(`missing track resolver for ${res.cid}`);
503
+ return;
504
+ }
505
+ delete this.pendingTrackResolvers[res.cid];
506
+ resolve(res.track!);
507
+ };
508
+
509
+ this.client.onTokenRefresh = (token: string) => {
510
+ this.token = token;
511
+ };
512
+
513
+ this.client.onClose = () => {
514
+ this.handleDisconnect('signal', ReconnectReason.RR_SIGNAL_DISCONNECTED);
515
+ };
516
+
517
+ this.client.onLeave = (leave?: LeaveRequest) => {
518
+ if (leave?.canReconnect) {
519
+ this.fullReconnectOnNext = true;
520
+ this.primaryPC = undefined;
521
+ // reconnect immediately instead of waiting for next attempt
522
+ this.handleDisconnect(leaveReconnect);
523
+ } else {
524
+ this.emit(EngineEvent.Disconnected, leave?.reason);
525
+ this.close();
526
+ }
527
+ log.trace('leave request', { leave });
528
+ };
529
+ }
530
+
531
+ private makeRTCConfiguration(serverResponse: JoinResponse | ReconnectResponse): RTCConfiguration {
532
+ const rtcConfig = { ...this.rtcConfig };
533
+
534
+ // update ICE servers before creating PeerConnection
535
+ if (serverResponse.iceServers && !rtcConfig.iceServers) {
536
+ const rtcIceServers: RTCIceServer[] = [];
537
+ serverResponse.iceServers.forEach((iceServer) => {
538
+ const rtcIceServer: RTCIceServer = {
539
+ urls: iceServer.urls,
540
+ };
541
+ if (iceServer.username) rtcIceServer.username = iceServer.username;
542
+ if (iceServer.credential) {
543
+ rtcIceServer.credential = iceServer.credential;
544
+ }
545
+ rtcIceServers.push(rtcIceServer);
546
+ });
547
+ rtcConfig.iceServers = rtcIceServers;
548
+ }
549
+
550
+ if (
551
+ serverResponse.clientConfiguration &&
552
+ serverResponse.clientConfiguration.forceRelay === ClientConfigSetting.ENABLED
553
+ ) {
554
+ rtcConfig.iceTransportPolicy = 'relay';
555
+ }
556
+
557
+ // @ts-ignore
558
+ rtcConfig.sdpSemantics = 'unified-plan';
559
+ // @ts-ignore
560
+ rtcConfig.continualGatheringPolicy = 'gather_continually';
561
+
562
+ return rtcConfig;
563
+ }
564
+
565
+ private createDataChannels() {
566
+ if (!this.publisher) {
567
+ return;
568
+ }
569
+
570
+ // clear old data channel callbacks if recreate
571
+ if (this.lossyDC) {
572
+ this.lossyDC.onmessage = null;
573
+ this.lossyDC.onerror = null;
574
+ }
575
+ if (this.reliableDC) {
576
+ this.reliableDC.onmessage = null;
577
+ this.reliableDC.onerror = null;
578
+ }
579
+
580
+ // create data channels
581
+ this.lossyDC = this.publisher.pc.createDataChannel(lossyDataChannel, {
582
+ // will drop older packets that arrive
583
+ ordered: true,
584
+ maxRetransmits: 0,
585
+ });
586
+ this.reliableDC = this.publisher.pc.createDataChannel(reliableDataChannel, {
587
+ ordered: true,
588
+ });
589
+
590
+ // also handle messages over the pub channel, for backwards compatibility
591
+ this.lossyDC.onmessage = this.handleDataMessage;
592
+ this.reliableDC.onmessage = this.handleDataMessage;
593
+
594
+ // handle datachannel errors
595
+ this.lossyDC.onerror = this.handleDataError;
596
+ this.reliableDC.onerror = this.handleDataError;
597
+
598
+ // set up dc buffer threshold, set to 64kB (otherwise 0 by default)
599
+ this.lossyDC.bufferedAmountLowThreshold = 65535;
600
+ this.reliableDC.bufferedAmountLowThreshold = 65535;
601
+
602
+ // handle buffer amount low events
603
+ this.lossyDC.onbufferedamountlow = this.handleBufferedAmountLow;
604
+ this.reliableDC.onbufferedamountlow = this.handleBufferedAmountLow;
605
+ }
606
+
607
+ private handleDataChannel = async ({ channel }: RTCDataChannelEvent) => {
608
+ if (!channel) {
609
+ return;
610
+ }
611
+ if (channel.label === reliableDataChannel) {
612
+ this.reliableDCSub = channel;
613
+ } else if (channel.label === lossyDataChannel) {
614
+ this.lossyDCSub = channel;
615
+ } else {
616
+ return;
617
+ }
618
+ log.debug(`on data channel ${channel.id}, ${channel.label}`);
619
+ channel.onmessage = this.handleDataMessage;
620
+ };
621
+
622
+ private handleDataMessage = async (message: MessageEvent) => {
623
+ // make sure to respect incoming data message order by processing message events one after the other
624
+ const unlock = await this.dataProcessLock.lock();
625
+ try {
626
+ // decode
627
+ let buffer: ArrayBuffer | undefined;
628
+ if (message.data instanceof ArrayBuffer) {
629
+ buffer = message.data;
630
+ } else if (message.data instanceof Blob) {
631
+ buffer = await message.data.arrayBuffer();
632
+ } else {
633
+ log.error('unsupported data type', message.data);
634
+ return;
635
+ }
636
+ const dp = DataPacket.fromBinary(new Uint8Array(buffer));
637
+ if (dp.value?.case === 'speaker') {
638
+ // dispatch speaker updates
639
+ this.emit(EngineEvent.ActiveSpeakersUpdate, dp.value.value.speakers);
640
+ } else if (dp.value?.case === 'user') {
641
+ this.emit(EngineEvent.DataPacketReceived, dp.value.value, dp.kind);
642
+ }
643
+ } finally {
644
+ unlock();
645
+ }
646
+ };
647
+
648
+ private handleDataError = (event: Event) => {
649
+ const channel = event.currentTarget as RTCDataChannel;
650
+ const channelKind = channel.maxRetransmits === 0 ? 'lossy' : 'reliable';
651
+
652
+ if (event instanceof ErrorEvent) {
653
+ const { error } = event.error;
654
+ log.error(`DataChannel error on ${channelKind}: ${event.message}`, error);
655
+ } else {
656
+ log.error(`Unknown DataChannel Error on ${channelKind}`, event);
657
+ }
658
+ };
659
+
660
+ private handleBufferedAmountLow = (event: Event) => {
661
+ const channel = event.currentTarget as RTCDataChannel;
662
+ const channelKind =
663
+ channel.maxRetransmits === 0 ? DataPacket_Kind.LOSSY : DataPacket_Kind.RELIABLE;
664
+
665
+ this.updateAndEmitDCBufferStatus(channelKind);
666
+ };
667
+
668
+ private setPreferredCodec(
669
+ transceiver: RTCRtpTransceiver,
670
+ kind: Track.Kind,
671
+ videoCodec: VideoCodec,
672
+ ) {
673
+ if (!('getCapabilities' in RTCRtpSender)) {
674
+ return;
675
+ }
676
+ const cap = RTCRtpSender.getCapabilities(kind);
677
+ if (!cap) return;
678
+ log.debug('get capabilities', cap);
679
+ const matched: RTCRtpCodecCapability[] = [];
680
+ const partialMatched: RTCRtpCodecCapability[] = [];
681
+ const unmatched: RTCRtpCodecCapability[] = [];
682
+ cap.codecs.forEach((c) => {
683
+ const codec = c.mimeType.toLowerCase();
684
+ if (codec === 'audio/opus') {
685
+ matched.push(c);
686
+ return;
687
+ }
688
+ const matchesVideoCodec = codec === `video/${videoCodec}`;
689
+ if (!matchesVideoCodec) {
690
+ unmatched.push(c);
691
+ return;
692
+ }
693
+ // for h264 codecs that have sdpFmtpLine available, use only if the
694
+ // profile-level-id is 42e01f for cross-browser compatibility
695
+ if (videoCodec === 'h264') {
696
+ if (c.sdpFmtpLine && c.sdpFmtpLine.includes('profile-level-id=42e01f')) {
697
+ matched.push(c);
698
+ } else {
699
+ partialMatched.push(c);
700
+ }
701
+ return;
702
+ }
703
+
704
+ matched.push(c);
705
+ });
706
+
707
+ if (supportsSetCodecPreferences(transceiver)) {
708
+ transceiver.setCodecPreferences(matched.concat(partialMatched, unmatched));
709
+ }
710
+ }
711
+
712
+ async createSender(
713
+ track: LocalTrack,
714
+ opts: TrackPublishOptions,
715
+ encodings?: RTCRtpEncodingParameters[],
716
+ ) {
717
+ if (supportsTransceiver()) {
718
+ const sender = await this.createTransceiverRTCRtpSender(track, opts, encodings);
719
+ return sender;
720
+ }
721
+ if (supportsAddTrack()) {
722
+ log.warn('using add-track fallback');
723
+ const sender = await this.createRTCRtpSender(track.mediaStreamTrack);
724
+ return sender;
725
+ }
726
+ throw new UnexpectedConnectionState('Required webRTC APIs not supported on this device');
727
+ }
728
+
729
+ async createSimulcastSender(
730
+ track: LocalVideoTrack,
731
+ simulcastTrack: SimulcastTrackInfo,
732
+ opts: TrackPublishOptions,
733
+ encodings?: RTCRtpEncodingParameters[],
734
+ ) {
735
+ // store RTCRtpSender
736
+ if (supportsTransceiver()) {
737
+ return this.createSimulcastTransceiverSender(track, simulcastTrack, opts, encodings);
738
+ }
739
+ if (supportsAddTrack()) {
740
+ log.debug('using add-track fallback');
741
+ return this.createRTCRtpSender(track.mediaStreamTrack);
742
+ }
743
+
744
+ throw new UnexpectedConnectionState('Cannot stream on this device');
745
+ }
746
+
747
+ private async createTransceiverRTCRtpSender(
748
+ track: LocalTrack,
749
+ opts: TrackPublishOptions,
750
+ encodings?: RTCRtpEncodingParameters[],
751
+ ) {
752
+ if (!this.publisher) {
753
+ throw new UnexpectedConnectionState('publisher is closed');
754
+ }
755
+
756
+ const streams: MediaStream[] = [];
757
+
758
+ if (track.mediaStream) {
759
+ streams.push(track.mediaStream);
760
+ }
761
+
762
+ const transceiverInit: RTCRtpTransceiverInit = { direction: 'sendonly', streams };
763
+ if (encodings) {
764
+ transceiverInit.sendEncodings = encodings;
765
+ }
766
+ // addTransceiver for react-native is async. web is synchronous, but await won't effect it.
767
+ const transceiver = await this.publisher.pc.addTransceiver(
768
+ track.mediaStreamTrack,
769
+ transceiverInit,
770
+ );
771
+
772
+ if (track.kind === Track.Kind.Video && opts.videoCodec) {
773
+ this.setPreferredCodec(transceiver, track.kind, opts.videoCodec);
774
+ track.codec = opts.videoCodec;
775
+ }
776
+ return transceiver.sender;
777
+ }
778
+
779
+ private async createSimulcastTransceiverSender(
780
+ track: LocalVideoTrack,
781
+ simulcastTrack: SimulcastTrackInfo,
782
+ opts: TrackPublishOptions,
783
+ encodings?: RTCRtpEncodingParameters[],
784
+ ) {
785
+ if (!this.publisher) {
786
+ throw new UnexpectedConnectionState('publisher is closed');
787
+ }
788
+ const transceiverInit: RTCRtpTransceiverInit = { direction: 'sendonly' };
789
+ if (encodings) {
790
+ transceiverInit.sendEncodings = encodings;
791
+ }
792
+ // addTransceiver for react-native is async. web is synchronous, but await won't effect it.
793
+ const transceiver = await this.publisher.pc.addTransceiver(
794
+ simulcastTrack.mediaStreamTrack,
795
+ transceiverInit,
796
+ );
797
+ if (!opts.videoCodec) {
798
+ return;
799
+ }
800
+ this.setPreferredCodec(transceiver, track.kind, opts.videoCodec);
801
+ track.setSimulcastTrackSender(opts.videoCodec, transceiver.sender);
802
+ return transceiver.sender;
803
+ }
804
+
805
+ private async createRTCRtpSender(track: MediaStreamTrack) {
806
+ if (!this.publisher) {
807
+ throw new UnexpectedConnectionState('publisher is closed');
808
+ }
809
+ return this.publisher.pc.addTrack(track);
810
+ }
811
+
812
+ // websocket reconnect behavior. if websocket is interrupted, and the PeerConnection
813
+ // continues to work, we can reconnect to websocket to continue the session
814
+ // after a number of retries, we'll close and give up permanently
815
+ private handleDisconnect = (connection: string, disconnectReason?: ReconnectReason) => {
816
+ if (this._isClosed) {
817
+ return;
818
+ }
819
+
820
+ log.warn(`${connection} disconnected`);
821
+ if (this.reconnectAttempts === 0) {
822
+ // only reset start time on the first try
823
+ this.reconnectStart = Date.now();
824
+ }
825
+
826
+ const disconnect = (duration: number) => {
827
+ log.warn(
828
+ `could not recover connection after ${this.reconnectAttempts} attempts, ${duration}ms. giving up`,
829
+ );
830
+ this.emit(EngineEvent.Disconnected);
831
+ this.close();
832
+ };
833
+
834
+ const duration = Date.now() - this.reconnectStart;
835
+ let delay = this.getNextRetryDelay({
836
+ elapsedMs: duration,
837
+ retryCount: this.reconnectAttempts,
838
+ });
839
+
840
+ if (delay === null) {
841
+ disconnect(duration);
842
+ return;
843
+ }
844
+ if (connection === leaveReconnect) {
845
+ delay = 0;
846
+ }
847
+
848
+ log.debug(`reconnecting in ${delay}ms`);
849
+
850
+ this.clearReconnectTimeout();
851
+ if (this.token && this.regionUrlProvider) {
852
+ // token may have been refreshed, we do not want to recreate the regionUrlProvider
853
+ // since the current engine may have inherited a regional url
854
+ this.regionUrlProvider.updateToken(this.token);
855
+ }
856
+ this.reconnectTimeout = CriticalTimers.setTimeout(
857
+ () => this.attemptReconnect(disconnectReason),
858
+ delay,
859
+ );
860
+ };
861
+
862
+ private async attemptReconnect(reason?: ReconnectReason) {
863
+ if (this._isClosed) {
864
+ return;
865
+ }
866
+ // guard for attempting reconnection multiple times while one attempt is still not finished
867
+ if (this.attemptingReconnect) {
868
+ return;
869
+ }
870
+ if (
871
+ this.clientConfiguration?.resumeConnection === ClientConfigSetting.DISABLED ||
872
+ // signaling state could change to closed due to hardware sleep
873
+ // those connections cannot be resumed
874
+ (this.primaryPC?.signalingState ?? 'closed') === 'closed'
875
+ ) {
876
+ this.fullReconnectOnNext = true;
877
+ }
878
+
879
+ try {
880
+ this.attemptingReconnect = true;
881
+ if (this.fullReconnectOnNext) {
882
+ await this.restartConnection();
883
+ } else {
884
+ await this.resumeConnection(reason);
885
+ }
886
+ this.clearPendingReconnect();
887
+ this.fullReconnectOnNext = false;
888
+ } catch (e) {
889
+ this.reconnectAttempts += 1;
890
+ let recoverable = true;
891
+ if (e instanceof UnexpectedConnectionState) {
892
+ log.debug('received unrecoverable error', { error: e });
893
+ // unrecoverable
894
+ recoverable = false;
895
+ } else if (!(e instanceof SignalReconnectError)) {
896
+ // cannot resume
897
+ this.fullReconnectOnNext = true;
898
+ }
899
+
900
+ if (recoverable) {
901
+ this.handleDisconnect('reconnect', ReconnectReason.RR_UNKNOWN);
902
+ } else {
903
+ log.info(
904
+ `could not recover connection after ${this.reconnectAttempts} attempts, ${
905
+ Date.now() - this.reconnectStart
906
+ }ms. giving up`,
907
+ );
908
+ this.emit(EngineEvent.Disconnected);
909
+ await this.close();
910
+ }
911
+ } finally {
912
+ this.attemptingReconnect = false;
913
+ }
914
+ }
915
+
916
+ private getNextRetryDelay(context: ReconnectContext) {
917
+ try {
918
+ return this.reconnectPolicy.nextRetryDelayInMs(context);
919
+ } catch (e) {
920
+ log.warn('encountered error in reconnect policy', { error: e });
921
+ }
922
+
923
+ // error in user code with provided reconnect policy, stop reconnecting
924
+ return null;
925
+ }
926
+
927
+ private async restartConnection(regionUrl?: string) {
928
+ try {
929
+ if (!this.url || !this.token) {
930
+ // permanent failure, don't attempt reconnection
931
+ throw new UnexpectedConnectionState('could not reconnect, url or token not saved');
932
+ }
933
+
934
+ log.info(`reconnecting, attempt: ${this.reconnectAttempts}`);
935
+ this.emit(EngineEvent.Restarting);
936
+
937
+ if (this.client.isConnected) {
938
+ await this.client.sendLeave();
939
+ }
940
+ await this.cleanupPeerConnections();
941
+ await this.cleanupClient();
942
+
943
+ let joinResponse: JoinResponse;
944
+ try {
945
+ if (!this.signalOpts) {
946
+ log.warn('attempted connection restart, without signal options present');
947
+ throw new SignalReconnectError();
948
+ }
949
+ // in case a regionUrl is passed, the region URL takes precedence
950
+ joinResponse = await this.join(regionUrl ?? this.url, this.token, this.signalOpts);
951
+ } catch (e) {
952
+ if (e instanceof ConnectionError && e.reason === ConnectionErrorReason.NotAllowed) {
953
+ throw new UnexpectedConnectionState('could not reconnect, token might be expired');
954
+ }
955
+ throw new SignalReconnectError();
956
+ }
957
+
958
+ if (this.shouldFailNext) {
959
+ this.shouldFailNext = false;
960
+ throw new Error('simulated failure');
961
+ }
962
+
963
+ this.client.setReconnected();
964
+ this.emit(EngineEvent.SignalRestarted, joinResponse);
965
+
966
+ await this.waitForPCReconnected();
967
+ this.regionUrlProvider?.resetAttempts();
968
+ // reconnect success
969
+ this.emit(EngineEvent.Restarted);
970
+ } catch (error) {
971
+ const nextRegionUrl = await this.regionUrlProvider?.getNextBestRegionUrl();
972
+ if (nextRegionUrl) {
973
+ await this.restartConnection(nextRegionUrl);
974
+ return;
975
+ } else {
976
+ // no more regions to try (or we're not on cloud)
977
+ this.regionUrlProvider?.resetAttempts();
978
+ throw error;
979
+ }
980
+ }
981
+ }
982
+
983
+ private async resumeConnection(reason?: ReconnectReason): Promise<void> {
984
+ if (!this.url || !this.token) {
985
+ // permanent failure, don't attempt reconnection
986
+ throw new UnexpectedConnectionState('could not reconnect, url or token not saved');
987
+ }
988
+ // trigger publisher reconnect
989
+ if (!this.publisher || !this.subscriber) {
990
+ throw new UnexpectedConnectionState('publisher and subscriber connections unset');
991
+ }
992
+
993
+ log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`);
994
+ this.emit(EngineEvent.Resuming);
995
+
996
+ try {
997
+ this.setupSignalClientCallbacks();
998
+ const res = await this.client.reconnect(this.url, this.token, this.participantSid, reason);
999
+ if (res) {
1000
+ const rtcConfig = this.makeRTCConfiguration(res);
1001
+ this.publisher.pc.setConfiguration(rtcConfig);
1002
+ this.subscriber.pc.setConfiguration(rtcConfig);
1003
+ }
1004
+ } catch (e) {
1005
+ let message = '';
1006
+ if (e instanceof Error) {
1007
+ message = e.message;
1008
+ }
1009
+ if (e instanceof ConnectionError && e.reason === ConnectionErrorReason.NotAllowed) {
1010
+ throw new UnexpectedConnectionState('could not reconnect, token might be expired');
1011
+ }
1012
+ throw new SignalReconnectError(message);
1013
+ }
1014
+ this.emit(EngineEvent.SignalResumed);
1015
+
1016
+ if (this.shouldFailNext) {
1017
+ this.shouldFailNext = false;
1018
+ throw new Error('simulated failure');
1019
+ }
1020
+
1021
+ this.subscriber.restartingIce = true;
1022
+
1023
+ // only restart publisher if it's needed
1024
+ if (this.hasPublished) {
1025
+ await this.publisher.createAndSendOffer({ iceRestart: true });
1026
+ }
1027
+
1028
+ await this.waitForPCReconnected();
1029
+ this.client.setReconnected();
1030
+
1031
+ // recreate publish datachannel if it's id is null
1032
+ // (for safari https://bugs.webkit.org/show_bug.cgi?id=184688)
1033
+ if (this.reliableDC?.readyState === 'open' && this.reliableDC.id === null) {
1034
+ this.createDataChannels();
1035
+ }
1036
+
1037
+ // resume success
1038
+ this.emit(EngineEvent.Resumed);
1039
+ }
1040
+
1041
+ async waitForPCInitialConnection(timeout?: number, abortController?: AbortController) {
1042
+ if (this.pcState === PCState.Connected) {
1043
+ return;
1044
+ }
1045
+ if (this.pcState !== PCState.New) {
1046
+ throw new UnexpectedConnectionState(
1047
+ 'Expected peer connection to be new on initial connection',
1048
+ );
1049
+ }
1050
+ return new Promise<void>((resolve, reject) => {
1051
+ const abortHandler = () => {
1052
+ log.warn('closing engine');
1053
+ CriticalTimers.clearTimeout(connectTimeout);
1054
+
1055
+ reject(
1056
+ new ConnectionError(
1057
+ 'room connection has been cancelled',
1058
+ ConnectionErrorReason.Cancelled,
1059
+ ),
1060
+ );
1061
+ };
1062
+ if (abortController?.signal.aborted) {
1063
+ abortHandler();
1064
+ }
1065
+ abortController?.signal.addEventListener('abort', abortHandler);
1066
+ const onConnected = () => {
1067
+ CriticalTimers.clearTimeout(connectTimeout);
1068
+ abortController?.signal.removeEventListener('abort', abortHandler);
1069
+ resolve();
1070
+ };
1071
+ const connectTimeout = CriticalTimers.setTimeout(() => {
1072
+ this.off(EngineEvent.Connected, onConnected);
1073
+ reject(new ConnectionError('could not establish pc connection'));
1074
+ }, timeout ?? this.peerConnectionTimeout);
1075
+ this.once(EngineEvent.Connected, onConnected);
1076
+ });
1077
+ }
1078
+
1079
+ private async waitForPCReconnected() {
1080
+ const startTime = Date.now();
1081
+ let now = startTime;
1082
+ this.pcState = PCState.Reconnecting;
1083
+
1084
+ log.debug('waiting for peer connection to reconnect');
1085
+ while (now - startTime < this.peerConnectionTimeout) {
1086
+ if (this.primaryPC === undefined) {
1087
+ // we can abort early, connection is hosed
1088
+ break;
1089
+ } else if (
1090
+ // on Safari, we don't get a connectionstatechanged event during ICE restart
1091
+ // this means we'd have to check its status manually and update address
1092
+ // manually
1093
+ now - startTime > minReconnectWait &&
1094
+ this.primaryPC?.connectionState === 'connected'
1095
+ ) {
1096
+ this.pcState = PCState.Connected;
1097
+ }
1098
+ if (this.pcState === PCState.Connected) {
1099
+ return;
1100
+ }
1101
+ await sleep(100);
1102
+ now = Date.now();
1103
+ }
1104
+
1105
+ // have not reconnected, throw
1106
+ throw new ConnectionError('could not establish PC connection');
1107
+ }
1108
+
1109
+ waitForRestarted = () => {
1110
+ return new Promise<void>((resolve, reject) => {
1111
+ if (this.pcState === PCState.Connected) {
1112
+ resolve();
1113
+ }
1114
+ const onRestarted = () => {
1115
+ this.off(EngineEvent.Disconnected, onDisconnected);
1116
+ resolve();
1117
+ };
1118
+ const onDisconnected = () => {
1119
+ this.off(EngineEvent.Restarted, onRestarted);
1120
+ reject();
1121
+ };
1122
+ this.once(EngineEvent.Restarted, onRestarted);
1123
+ this.once(EngineEvent.Disconnected, onDisconnected);
1124
+ });
1125
+ };
1126
+
1127
+ /* @internal */
1128
+ async sendDataPacket(packet: DataPacket, kind: DataPacket_Kind) {
1129
+ const msg = packet.toBinary();
1130
+
1131
+ // make sure we do have a data connection
1132
+ await this.ensurePublisherConnected(kind);
1133
+
1134
+ const dc = this.dataChannelForKind(kind);
1135
+ if (dc) {
1136
+ dc.send(msg);
1137
+ }
1138
+
1139
+ this.updateAndEmitDCBufferStatus(kind);
1140
+ }
1141
+
1142
+ private updateAndEmitDCBufferStatus = (kind: DataPacket_Kind) => {
1143
+ const status = this.isBufferStatusLow(kind);
1144
+ if (typeof status !== 'undefined' && status !== this.dcBufferStatus.get(kind)) {
1145
+ this.dcBufferStatus.set(kind, status);
1146
+ this.emit(EngineEvent.DCBufferStatusChanged, status, kind);
1147
+ }
1148
+ };
1149
+
1150
+ private isBufferStatusLow = (kind: DataPacket_Kind): boolean | undefined => {
1151
+ const dc = this.dataChannelForKind(kind);
1152
+ if (dc) {
1153
+ return dc.bufferedAmount <= dc.bufferedAmountLowThreshold;
1154
+ }
1155
+ };
1156
+
1157
+ /**
1158
+ * @internal
1159
+ */
1160
+ async ensureDataTransportConnected(
1161
+ kind: DataPacket_Kind,
1162
+ subscriber: boolean = this.subscriberPrimary,
1163
+ ) {
1164
+ const transport = subscriber ? this.subscriber : this.publisher;
1165
+ const transportName = subscriber ? 'Subscriber' : 'Publisher';
1166
+ if (!transport) {
1167
+ throw new ConnectionError(`${transportName} connection not set`);
1168
+ }
1169
+
1170
+ if (
1171
+ !subscriber &&
1172
+ !this.publisher?.isICEConnected &&
1173
+ this.publisher?.pc.iceConnectionState !== 'checking'
1174
+ ) {
1175
+ // start negotiation
1176
+ this.negotiate();
1177
+ }
1178
+
1179
+ const targetChannel = this.dataChannelForKind(kind, subscriber);
1180
+ if (targetChannel?.readyState === 'open') {
1181
+ return;
1182
+ }
1183
+
1184
+ // wait until ICE connected
1185
+ const endTime = new Date().getTime() + this.peerConnectionTimeout;
1186
+ while (new Date().getTime() < endTime) {
1187
+ if (
1188
+ transport.isICEConnected &&
1189
+ this.dataChannelForKind(kind, subscriber)?.readyState === 'open'
1190
+ ) {
1191
+ return;
1192
+ }
1193
+ await sleep(50);
1194
+ }
1195
+
1196
+ throw new ConnectionError(
1197
+ `could not establish ${transportName} connection, state: ${transport.pc.iceConnectionState}`,
1198
+ );
1199
+ }
1200
+
1201
+ private async ensurePublisherConnected(kind: DataPacket_Kind) {
1202
+ await this.ensureDataTransportConnected(kind, false);
1203
+ }
1204
+
1205
+ /* @internal */
1206
+ verifyTransport(): boolean {
1207
+ // primary connection
1208
+ if (!this.primaryPC) {
1209
+ return false;
1210
+ }
1211
+ if (
1212
+ this.primaryPC.connectionState === 'closed' ||
1213
+ this.primaryPC.connectionState === 'failed'
1214
+ ) {
1215
+ return false;
1216
+ }
1217
+
1218
+ // also verify publisher connection if it's needed or different
1219
+ if (this.hasPublished && this.subscriberPrimary) {
1220
+ if (!this.publisher) {
1221
+ return false;
1222
+ }
1223
+ if (
1224
+ this.publisher.pc.connectionState === 'closed' ||
1225
+ this.publisher.pc.connectionState === 'failed'
1226
+ ) {
1227
+ return false;
1228
+ }
1229
+ }
1230
+
1231
+ // ensure signal is connected
1232
+ if (!this.client.ws || this.client.ws.readyState === WebSocket.CLOSED) {
1233
+ return false;
1234
+ }
1235
+ return true;
1236
+ }
1237
+
1238
+ /** @internal */
1239
+ negotiate(): Promise<void> {
1240
+ // observe signal state
1241
+ return new Promise<void>((resolve, reject) => {
1242
+ if (!this.publisher) {
1243
+ reject(new NegotiationError('publisher is not defined'));
1244
+ return;
1245
+ }
1246
+
1247
+ this.hasPublished = true;
1248
+
1249
+ const handleClosed = () => {
1250
+ log.debug('engine disconnected while negotiation was ongoing');
1251
+ cleanup();
1252
+ resolve();
1253
+ return;
1254
+ };
1255
+
1256
+ if (this.isClosed) {
1257
+ reject('cannot negotiate on closed engine');
1258
+ }
1259
+ this.on(EngineEvent.Closing, handleClosed);
1260
+
1261
+ const negotiationTimeout = setTimeout(() => {
1262
+ reject('negotiation timed out');
1263
+ this.handleDisconnect('negotiation', ReconnectReason.RR_SIGNAL_DISCONNECTED);
1264
+ }, this.peerConnectionTimeout);
1265
+
1266
+ const cleanup = () => {
1267
+ clearTimeout(negotiationTimeout);
1268
+ this.off(EngineEvent.Closing, handleClosed);
1269
+ };
1270
+
1271
+ this.publisher.once(PCEvents.NegotiationStarted, () => {
1272
+ this.publisher?.once(PCEvents.NegotiationComplete, () => {
1273
+ cleanup();
1274
+ resolve();
1275
+ });
1276
+ });
1277
+
1278
+ this.publisher.once(PCEvents.RTPVideoPayloadTypes, (rtpTypes: MediaAttributes['rtp']) => {
1279
+ const rtpMap = new Map<number, VideoCodec>();
1280
+ rtpTypes.forEach((rtp) => {
1281
+ const codec = rtp.codec.toLowerCase();
1282
+ if (isVideoCodec(codec)) {
1283
+ rtpMap.set(rtp.payload, codec);
1284
+ }
1285
+ });
1286
+ this.emit(EngineEvent.RTPVideoMapUpdate, rtpMap);
1287
+ });
1288
+
1289
+ this.publisher.negotiate((e) => {
1290
+ cleanup();
1291
+ reject(e);
1292
+ if (e instanceof NegotiationError) {
1293
+ this.fullReconnectOnNext = true;
1294
+ }
1295
+ this.handleDisconnect('negotiation', ReconnectReason.RR_UNKNOWN);
1296
+ });
1297
+ });
1298
+ }
1299
+
1300
+ dataChannelForKind(kind: DataPacket_Kind, sub?: boolean): RTCDataChannel | undefined {
1301
+ if (!sub) {
1302
+ if (kind === DataPacket_Kind.LOSSY) {
1303
+ return this.lossyDC;
1304
+ }
1305
+ if (kind === DataPacket_Kind.RELIABLE) {
1306
+ return this.reliableDC;
1307
+ }
1308
+ } else {
1309
+ if (kind === DataPacket_Kind.LOSSY) {
1310
+ return this.lossyDCSub;
1311
+ }
1312
+ if (kind === DataPacket_Kind.RELIABLE) {
1313
+ return this.reliableDCSub;
1314
+ }
1315
+ }
1316
+ }
1317
+
1318
+ /* @internal */
1319
+ failNext() {
1320
+ // debugging method to fail the next reconnect/resume attempt
1321
+ this.shouldFailNext = true;
1322
+ }
1323
+
1324
+ private clearReconnectTimeout() {
1325
+ if (this.reconnectTimeout) {
1326
+ CriticalTimers.clearTimeout(this.reconnectTimeout);
1327
+ }
1328
+ }
1329
+
1330
+ private clearPendingReconnect() {
1331
+ this.clearReconnectTimeout();
1332
+ this.reconnectAttempts = 0;
1333
+ }
1334
+
1335
+ private handleBrowserOnLine = () => {
1336
+ // in case the engine is currently reconnecting, attempt a reconnect immediately after the browser state has changed to 'onLine'
1337
+ if (this.client.isReconnecting) {
1338
+ this.clearReconnectTimeout();
1339
+ this.attemptReconnect(ReconnectReason.RR_SIGNAL_DISCONNECTED);
1340
+ }
1341
+ };
1342
+
1343
+ private registerOnLineListener() {
1344
+ if (isWeb()) {
1345
+ window.addEventListener('online', this.handleBrowserOnLine);
1346
+ }
1347
+ }
1348
+
1349
+ private deregisterOnLineListener() {
1350
+ if (isWeb()) {
1351
+ window.removeEventListener('online', this.handleBrowserOnLine);
1352
+ }
1353
+ }
1354
+ }
1355
+
1356
+ async function getConnectedAddress(pc: RTCPeerConnection): Promise<string | undefined> {
1357
+ let selectedCandidatePairId = '';
1358
+ const candidatePairs = new Map<string, RTCIceCandidatePairStats>();
1359
+ // id -> candidate ip
1360
+ const candidates = new Map<string, string>();
1361
+ const stats: RTCStatsReport = await pc.getStats();
1362
+ stats.forEach((v) => {
1363
+ switch (v.type) {
1364
+ case 'transport':
1365
+ selectedCandidatePairId = v.selectedCandidatePairId;
1366
+ break;
1367
+ case 'candidate-pair':
1368
+ if (selectedCandidatePairId === '' && v.selected) {
1369
+ selectedCandidatePairId = v.id;
1370
+ }
1371
+ candidatePairs.set(v.id, v);
1372
+ break;
1373
+ case 'remote-candidate':
1374
+ candidates.set(v.id, `${v.address}:${v.port}`);
1375
+ break;
1376
+ default:
1377
+ }
1378
+ });
1379
+
1380
+ if (selectedCandidatePairId === '') {
1381
+ return undefined;
1382
+ }
1383
+ const selectedID = candidatePairs.get(selectedCandidatePairId)?.remoteCandidateId;
1384
+ if (selectedID === undefined) {
1385
+ return undefined;
1386
+ }
1387
+ return candidates.get(selectedID);
1388
+ }
1389
+
1390
+ class SignalReconnectError extends Error {}
1391
+
1392
+ export type EngineEventCallbacks = {
1393
+ connected: (joinResp: JoinResponse) => void;
1394
+ disconnected: (reason?: DisconnectReason) => void;
1395
+ resuming: () => void;
1396
+ resumed: () => void;
1397
+ restarting: () => void;
1398
+ restarted: () => void;
1399
+ signalResumed: () => void;
1400
+ signalRestarted: (joinResp: JoinResponse) => void;
1401
+ closing: () => void;
1402
+ mediaTrackAdded: (
1403
+ track: MediaStreamTrack,
1404
+ streams: MediaStream,
1405
+ receiver?: RTCRtpReceiver,
1406
+ ) => void;
1407
+ activeSpeakersUpdate: (speakers: Array<SpeakerInfo>) => void;
1408
+ dataPacketReceived: (userPacket: UserPacket, kind: DataPacket_Kind) => void;
1409
+ transportsCreated: (publisher: PCTransport, subscriber: PCTransport) => void;
1410
+ /** @internal */
1411
+ trackSenderAdded: (track: Track, sender: RTCRtpSender) => void;
1412
+ rtpVideoMapUpdate: (rtpMap: Map<number, VideoCodec>) => void;
1413
+ dcBufferStatusChanged: (isLow: boolean, kind: DataPacket_Kind) => void;
1414
+ participantUpdate: (infos: ParticipantInfo[]) => void;
1415
+ roomUpdate: (room: RoomModel) => void;
1416
+ connectionQualityUpdate: (update: ConnectionQualityUpdate) => void;
1417
+ speakersChanged: (speakerUpdates: SpeakerInfo[]) => void;
1418
+ streamStateChanged: (update: StreamStateUpdate) => void;
1419
+ subscriptionError: (resp: SubscriptionResponse) => void;
1420
+ subscriptionPermissionUpdate: (update: SubscriptionPermissionUpdate) => void;
1421
+ };