amiudmodz 6.2.9 → 6.3.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 (311) hide show
  1. package/lib/Foundation/ai-rich.d.ts +123 -0
  2. package/lib/Foundation/ai-rich.d.ts.map +1 -0
  3. package/lib/Foundation/ai-rich.js +542 -0
  4. package/lib/Foundation/ai-rich.js.map +1 -0
  5. package/lib/Foundation/audio-duration.d.ts +3 -0
  6. package/lib/Foundation/audio-duration.d.ts.map +1 -0
  7. package/lib/Foundation/audio-duration.js +514 -0
  8. package/lib/Foundation/audio-duration.js.map +1 -0
  9. package/lib/Foundation/audio-samples.d.ts +3 -0
  10. package/lib/Foundation/audio-samples.d.ts.map +1 -0
  11. package/lib/Foundation/audio-samples.js +294 -0
  12. package/lib/Foundation/audio-samples.js.map +1 -0
  13. package/lib/Foundation/boom.d.ts +17 -0
  14. package/lib/Foundation/boom.d.ts.map +1 -0
  15. package/lib/Foundation/boom.js +37 -0
  16. package/lib/Foundation/boom.js.map +1 -0
  17. package/lib/Foundation/cache.d.ts +25 -0
  18. package/lib/Foundation/cache.d.ts.map +1 -0
  19. package/lib/Foundation/cache.js +112 -0
  20. package/lib/Foundation/cache.js.map +1 -0
  21. package/lib/Foundation/concurrency.d.ts +13 -0
  22. package/lib/Foundation/concurrency.d.ts.map +1 -0
  23. package/lib/Foundation/concurrency.js +62 -0
  24. package/lib/Foundation/concurrency.js.map +1 -0
  25. package/lib/Foundation/curve25519.d.ts +11 -0
  26. package/lib/Foundation/curve25519.d.ts.map +1 -0
  27. package/lib/Foundation/curve25519.js +178 -0
  28. package/lib/Foundation/curve25519.js.map +1 -0
  29. package/lib/Foundation/image-thumb.d.ts +13 -0
  30. package/lib/Foundation/image-thumb.d.ts.map +1 -0
  31. package/lib/Foundation/image-thumb.js +65 -0
  32. package/lib/Foundation/image-thumb.js.map +1 -0
  33. package/lib/Foundation/link-preview.d.ts +29 -0
  34. package/lib/Foundation/link-preview.d.ts.map +1 -0
  35. package/lib/Foundation/link-preview.js +309 -0
  36. package/lib/Foundation/link-preview.js.map +1 -0
  37. package/lib/Foundation/logger.d.ts +31 -0
  38. package/lib/Foundation/logger.d.ts.map +1 -0
  39. package/lib/Foundation/logger.js +54 -0
  40. package/lib/Foundation/logger.js.map +1 -0
  41. package/lib/Foundation/long.d.ts +33 -0
  42. package/lib/Foundation/long.d.ts.map +1 -0
  43. package/lib/Foundation/long.js +135 -0
  44. package/lib/Foundation/long.js.map +1 -0
  45. package/lib/Foundation/protobuf-minimal.d.ts +115 -0
  46. package/lib/Foundation/protobuf-minimal.d.ts.map +1 -0
  47. package/lib/Foundation/protobuf-minimal.js +614 -0
  48. package/lib/Foundation/protobuf-minimal.js.map +1 -0
  49. package/lib/Foundation/qrcode-terminal.d.ts +2 -0
  50. package/lib/Foundation/qrcode-terminal.d.ts.map +1 -0
  51. package/lib/Foundation/qrcode-terminal.js +405 -0
  52. package/lib/Foundation/qrcode-terminal.js.map +1 -0
  53. package/lib/Foundation/sql-database.d.ts +15 -0
  54. package/lib/Foundation/sql-database.d.ts.map +1 -0
  55. package/lib/Foundation/sql-database.js +719 -0
  56. package/lib/Foundation/sql-database.js.map +1 -0
  57. package/lib/Foundation/wa-crypto.d.ts +14 -0
  58. package/lib/Foundation/wa-crypto.d.ts.map +1 -0
  59. package/lib/Foundation/wa-crypto.js +48 -0
  60. package/lib/Foundation/wa-crypto.js.map +1 -0
  61. package/lib/Foundation/zip.d.ts +2 -0
  62. package/lib/Foundation/zip.d.ts.map +1 -0
  63. package/lib/Foundation/zip.js +98 -0
  64. package/lib/Foundation/zip.js.map +1 -0
  65. package/lib/Signal/libsignal.js +0 -3
  66. package/lib/Signal/libsignal.js.map +1 -1
  67. package/lib/Socket/business.d.ts +3 -1
  68. package/lib/Socket/business.d.ts.map +1 -1
  69. package/lib/Socket/communities.d.ts +3 -1
  70. package/lib/Socket/communities.d.ts.map +1 -1
  71. package/lib/Socket/index.d.ts.map +1 -1
  72. package/lib/Socket/index.js +19 -14
  73. package/lib/Socket/index.js.map +1 -1
  74. package/lib/Socket/messages-recv.d.ts +3 -1
  75. package/lib/Socket/messages-recv.d.ts.map +1 -1
  76. package/lib/Socket/messages-recv.js +6 -2
  77. package/lib/Socket/messages-recv.js.map +1 -1
  78. package/lib/Socket/messages-send.d.ts +3 -1
  79. package/lib/Socket/messages-send.d.ts.map +1 -1
  80. package/lib/Socket/messages-send.js +298 -52
  81. package/lib/Socket/messages-send.js.map +1 -1
  82. package/lib/Socket/newsletter.d.ts.map +1 -1
  83. package/lib/Socket/newsletter.js +4 -5
  84. package/lib/Socket/newsletter.js.map +1 -1
  85. package/lib/Utils/crypto.d.ts.map +1 -1
  86. package/lib/Utils/crypto.js +6 -7
  87. package/lib/Utils/crypto.js.map +1 -1
  88. package/lib/Utils/messages-media.d.ts.map +1 -1
  89. package/lib/Utils/messages-media.js +89 -26
  90. package/lib/Utils/messages-media.js.map +1 -1
  91. package/lib/Utils/messages.d.ts +6 -0
  92. package/lib/Utils/messages.d.ts.map +1 -1
  93. package/lib/Utils/messages.js +198 -27
  94. package/lib/Utils/messages.js.map +1 -1
  95. package/lib/VoIP/WaVoipCoordinator.d.ts +39 -0
  96. package/lib/VoIP/WaVoipCoordinator.d.ts.map +1 -0
  97. package/lib/VoIP/WaVoipCoordinator.js +156 -0
  98. package/lib/VoIP/WaVoipCoordinator.js.map +1 -0
  99. package/lib/VoIP/app-data/WaAppDataStream.d.ts +35 -0
  100. package/lib/VoIP/app-data/WaAppDataStream.d.ts.map +1 -0
  101. package/lib/VoIP/app-data/WaAppDataStream.js +174 -0
  102. package/lib/VoIP/app-data/WaAppDataStream.js.map +1 -0
  103. package/lib/VoIP/app-data/protocol.d.ts +28 -0
  104. package/lib/VoIP/app-data/protocol.d.ts.map +1 -0
  105. package/lib/VoIP/app-data/protocol.js +167 -0
  106. package/lib/VoIP/app-data/protocol.js.map +1 -0
  107. package/lib/VoIP/bytes.d.ts +19 -0
  108. package/lib/VoIP/bytes.d.ts.map +1 -0
  109. package/lib/VoIP/bytes.js +64 -0
  110. package/lib/VoIP/bytes.js.map +1 -0
  111. package/lib/VoIP/call/WaCallManager.d.ts +58 -0
  112. package/lib/VoIP/call/WaCallManager.d.ts.map +1 -0
  113. package/lib/VoIP/call/WaCallManager.js +434 -0
  114. package/lib/VoIP/call/WaCallManager.js.map +1 -0
  115. package/lib/VoIP/call/WaCallMediaSession.d.ts +143 -0
  116. package/lib/VoIP/call/WaCallMediaSession.d.ts.map +1 -0
  117. package/lib/VoIP/call/WaCallMediaSession.js +1674 -0
  118. package/lib/VoIP/call/WaCallMediaSession.js.map +1 -0
  119. package/lib/VoIP/call/call-state.d.ts +34 -0
  120. package/lib/VoIP/call/call-state.d.ts.map +1 -0
  121. package/lib/VoIP/call/call-state.js +189 -0
  122. package/lib/VoIP/call/call-state.js.map +1 -0
  123. package/lib/VoIP/crypto/encryption.d.ts +6 -0
  124. package/lib/VoIP/crypto/encryption.d.ts.map +1 -0
  125. package/lib/VoIP/crypto/encryption.js +14 -0
  126. package/lib/VoIP/crypto/encryption.js.map +1 -0
  127. package/lib/VoIP/crypto/primitives.d.ts +5 -0
  128. package/lib/VoIP/crypto/primitives.d.ts.map +1 -0
  129. package/lib/VoIP/crypto/primitives.js +22 -0
  130. package/lib/VoIP/crypto/primitives.js.map +1 -0
  131. package/lib/VoIP/crypto/rtcp.d.ts +6 -0
  132. package/lib/VoIP/crypto/rtcp.d.ts.map +1 -0
  133. package/lib/VoIP/crypto/rtcp.js +71 -0
  134. package/lib/VoIP/crypto/rtcp.js.map +1 -0
  135. package/lib/VoIP/crypto/srtp.d.ts +40 -0
  136. package/lib/VoIP/crypto/srtp.d.ts.map +1 -0
  137. package/lib/VoIP/crypto/srtp.js +174 -0
  138. package/lib/VoIP/crypto/srtp.js.map +1 -0
  139. package/lib/VoIP/crypto/ssrc.d.ts +4 -0
  140. package/lib/VoIP/crypto/ssrc.d.ts.map +1 -0
  141. package/lib/VoIP/crypto/ssrc.js +15 -0
  142. package/lib/VoIP/crypto/ssrc.js.map +1 -0
  143. package/lib/VoIP/index.d.ts +82 -104
  144. package/lib/VoIP/index.d.ts.map +1 -1
  145. package/lib/VoIP/index.js +596 -885
  146. package/lib/VoIP/index.js.map +1 -1
  147. package/lib/VoIP/media/WaAudioEngine.d.ts +79 -0
  148. package/lib/VoIP/media/WaAudioEngine.d.ts.map +1 -0
  149. package/lib/VoIP/media/WaAudioEngine.js +478 -0
  150. package/lib/VoIP/media/WaAudioEngine.js.map +1 -0
  151. package/lib/VoIP/media/WaVideoEngine.d.ts +31 -0
  152. package/lib/VoIP/media/WaVideoEngine.d.ts.map +1 -0
  153. package/lib/VoIP/media/WaVideoEngine.js +261 -0
  154. package/lib/VoIP/media/WaVideoEngine.js.map +1 -0
  155. package/lib/VoIP/media/audio-codec.d.ts +74 -0
  156. package/lib/VoIP/media/audio-codec.d.ts.map +1 -0
  157. package/lib/VoIP/media/audio-codec.js +0 -0
  158. package/lib/VoIP/media/audio-codec.js.map +1 -0
  159. package/lib/VoIP/media/audio-reorder.d.ts +19 -0
  160. package/lib/VoIP/media/audio-reorder.d.ts.map +1 -0
  161. package/lib/VoIP/media/audio-reorder.js +112 -0
  162. package/lib/VoIP/media/audio-reorder.js.map +1 -0
  163. package/lib/VoIP/media/h264.d.ts +21 -0
  164. package/lib/VoIP/media/h264.d.ts.map +1 -0
  165. package/lib/VoIP/media/h264.js +239 -0
  166. package/lib/VoIP/media/h264.js.map +1 -0
  167. package/lib/VoIP/media/mlow-codec.d.ts +77 -0
  168. package/lib/VoIP/media/mlow-codec.d.ts.map +1 -0
  169. package/lib/VoIP/media/mlow-codec.js +467 -0
  170. package/lib/VoIP/media/mlow-codec.js.map +1 -0
  171. package/lib/VoIP/media/rtcp.d.ts +10 -0
  172. package/lib/VoIP/media/rtcp.d.ts.map +1 -0
  173. package/lib/VoIP/media/rtcp.js +61 -0
  174. package/lib/VoIP/media/rtcp.js.map +1 -0
  175. package/lib/VoIP/media/rtp.d.ts +56 -0
  176. package/lib/VoIP/media/rtp.d.ts.map +1 -0
  177. package/lib/VoIP/media/rtp.js +225 -0
  178. package/lib/VoIP/media/rtp.js.map +1 -0
  179. package/lib/VoIP/protobuf.d.ts +3 -0
  180. package/lib/VoIP/protobuf.d.ts.map +1 -0
  181. package/lib/VoIP/protobuf.js +30 -0
  182. package/lib/VoIP/protobuf.js.map +1 -0
  183. package/lib/VoIP/relay/WaManualRelay.d.ts +62 -0
  184. package/lib/VoIP/relay/WaManualRelay.d.ts.map +1 -0
  185. package/lib/VoIP/relay/WaManualRelay.js +619 -0
  186. package/lib/VoIP/relay/WaManualRelay.js.map +1 -0
  187. package/lib/VoIP/relay/datachannel/pre-negotiated.d.ts +22 -0
  188. package/lib/VoIP/relay/datachannel/pre-negotiated.d.ts.map +1 -0
  189. package/lib/VoIP/relay/datachannel/pre-negotiated.js +34 -0
  190. package/lib/VoIP/relay/datachannel/pre-negotiated.js.map +1 -0
  191. package/lib/VoIP/relay/dtls/aead.d.ts +23 -0
  192. package/lib/VoIP/relay/dtls/aead.d.ts.map +1 -0
  193. package/lib/VoIP/relay/dtls/aead.js +41 -0
  194. package/lib/VoIP/relay/dtls/aead.js.map +1 -0
  195. package/lib/VoIP/relay/dtls/cert-builder.d.ts +6 -0
  196. package/lib/VoIP/relay/dtls/cert-builder.d.ts.map +1 -0
  197. package/lib/VoIP/relay/dtls/cert-builder.js +68 -0
  198. package/lib/VoIP/relay/dtls/cert-builder.js.map +1 -0
  199. package/lib/VoIP/relay/dtls/der.d.ts +19 -0
  200. package/lib/VoIP/relay/dtls/der.d.ts.map +1 -0
  201. package/lib/VoIP/relay/dtls/der.js +96 -0
  202. package/lib/VoIP/relay/dtls/der.js.map +1 -0
  203. package/lib/VoIP/relay/dtls/ecdhe.d.ts +9 -0
  204. package/lib/VoIP/relay/dtls/ecdhe.d.ts.map +1 -0
  205. package/lib/VoIP/relay/dtls/ecdhe.js +33 -0
  206. package/lib/VoIP/relay/dtls/ecdhe.js.map +1 -0
  207. package/lib/VoIP/relay/dtls/handshake-framing.d.ts +49 -0
  208. package/lib/VoIP/relay/dtls/handshake-framing.d.ts.map +1 -0
  209. package/lib/VoIP/relay/dtls/handshake-framing.js +102 -0
  210. package/lib/VoIP/relay/dtls/handshake-framing.js.map +1 -0
  211. package/lib/VoIP/relay/dtls/handshake-messages.d.ts +64 -0
  212. package/lib/VoIP/relay/dtls/handshake-messages.d.ts.map +1 -0
  213. package/lib/VoIP/relay/dtls/handshake-messages.js +154 -0
  214. package/lib/VoIP/relay/dtls/handshake-messages.js.map +1 -0
  215. package/lib/VoIP/relay/dtls/handshake.d.ts +28 -0
  216. package/lib/VoIP/relay/dtls/handshake.d.ts.map +1 -0
  217. package/lib/VoIP/relay/dtls/handshake.js +555 -0
  218. package/lib/VoIP/relay/dtls/handshake.js.map +1 -0
  219. package/lib/VoIP/relay/dtls/prf.d.ts +13 -0
  220. package/lib/VoIP/relay/dtls/prf.d.ts.map +1 -0
  221. package/lib/VoIP/relay/dtls/prf.js +35 -0
  222. package/lib/VoIP/relay/dtls/prf.js.map +1 -0
  223. package/lib/VoIP/relay/dtls/record.d.ts +25 -0
  224. package/lib/VoIP/relay/dtls/record.d.ts.map +1 -0
  225. package/lib/VoIP/relay/dtls/record.js +49 -0
  226. package/lib/VoIP/relay/dtls/record.js.map +1 -0
  227. package/lib/VoIP/relay/relay-ack.d.ts +31 -0
  228. package/lib/VoIP/relay/relay-ack.d.ts.map +1 -0
  229. package/lib/VoIP/relay/relay-ack.js +142 -0
  230. package/lib/VoIP/relay/relay-ack.js.map +1 -0
  231. package/lib/VoIP/relay/sctp/association.d.ts +22 -0
  232. package/lib/VoIP/relay/sctp/association.d.ts.map +1 -0
  233. package/lib/VoIP/relay/sctp/association.js +434 -0
  234. package/lib/VoIP/relay/sctp/association.js.map +1 -0
  235. package/lib/VoIP/relay/sctp/crc32c.d.ts +2 -0
  236. package/lib/VoIP/relay/sctp/crc32c.d.ts.map +1 -0
  237. package/lib/VoIP/relay/sctp/crc32c.js +20 -0
  238. package/lib/VoIP/relay/sctp/crc32c.js.map +1 -0
  239. package/lib/VoIP/relay/sctp/wire.d.ts +96 -0
  240. package/lib/VoIP/relay/sctp/wire.d.ts.map +1 -0
  241. package/lib/VoIP/relay/sctp/wire.js +206 -0
  242. package/lib/VoIP/relay/sctp/wire.js.map +1 -0
  243. package/lib/VoIP/relay/stun.d.ts +47 -0
  244. package/lib/VoIP/relay/stun.d.ts.map +1 -0
  245. package/lib/VoIP/relay/stun.js +459 -0
  246. package/lib/VoIP/relay/stun.js.map +1 -0
  247. package/lib/VoIP/shim/baileys-resolve.d.ts +2 -0
  248. package/lib/VoIP/shim/baileys-resolve.d.ts.map +1 -0
  249. package/lib/VoIP/shim/baileys-resolve.js +22 -0
  250. package/lib/VoIP/shim/baileys-resolve.js.map +1 -0
  251. package/lib/VoIP/shim/core.d.ts +32 -0
  252. package/lib/VoIP/shim/core.d.ts.map +1 -0
  253. package/lib/VoIP/shim/core.js +67 -0
  254. package/lib/VoIP/shim/core.js.map +1 -0
  255. package/lib/VoIP/shim/crypto.d.ts +2 -0
  256. package/lib/VoIP/shim/crypto.d.ts.map +1 -0
  257. package/lib/VoIP/shim/crypto.js +7 -0
  258. package/lib/VoIP/shim/crypto.js.map +1 -0
  259. package/lib/VoIP/shim/proto.d.ts +2 -0
  260. package/lib/VoIP/shim/proto.d.ts.map +1 -0
  261. package/lib/VoIP/shim/proto.js +10 -0
  262. package/lib/VoIP/shim/proto.js.map +1 -0
  263. package/lib/VoIP/shim/protocol.d.ts +32 -0
  264. package/lib/VoIP/shim/protocol.d.ts.map +1 -0
  265. package/lib/VoIP/shim/protocol.js +131 -0
  266. package/lib/VoIP/shim/protocol.js.map +1 -0
  267. package/lib/VoIP/shim/transport.d.ts +20 -0
  268. package/lib/VoIP/shim/transport.d.ts.map +1 -0
  269. package/lib/VoIP/shim/transport.js +83 -0
  270. package/lib/VoIP/shim/transport.js.map +1 -0
  271. package/lib/VoIP/shim/util.d.ts +13 -0
  272. package/lib/VoIP/shim/util.d.ts.map +1 -0
  273. package/lib/VoIP/shim/util.js +208 -0
  274. package/lib/VoIP/shim/util.js.map +1 -0
  275. package/lib/VoIP/signaling/bridge.d.ts +4 -0
  276. package/lib/VoIP/signaling/bridge.d.ts.map +1 -0
  277. package/lib/VoIP/signaling/bridge.js +103 -0
  278. package/lib/VoIP/signaling/bridge.js.map +1 -0
  279. package/lib/VoIP/signaling/screen-share.d.ts +40 -0
  280. package/lib/VoIP/signaling/screen-share.d.ts.map +1 -0
  281. package/lib/VoIP/signaling/screen-share.js +55 -0
  282. package/lib/VoIP/signaling/screen-share.js.map +1 -0
  283. package/lib/VoIP/signaling/signaling.d.ts +396 -0
  284. package/lib/VoIP/signaling/signaling.d.ts.map +1 -0
  285. package/lib/VoIP/signaling/signaling.js +488 -0
  286. package/lib/VoIP/signaling/signaling.js.map +1 -0
  287. package/lib/VoIP/types.d.ts +37 -12
  288. package/lib/VoIP/types.d.ts.map +1 -1
  289. package/lib/VoIP/types.js +65 -12
  290. package/lib/VoIP/types.js.map +1 -1
  291. package/lib/VoIP/voip-deps.d.ts +46 -0
  292. package/lib/VoIP/voip-deps.d.ts.map +1 -0
  293. package/lib/VoIP/voip-deps.js +244 -0
  294. package/lib/VoIP/voip-deps.js.map +1 -0
  295. package/lib/VoIP/voipClient.d.ts +34 -0
  296. package/lib/VoIP/voipClient.d.ts.map +1 -0
  297. package/lib/VoIP/voipClient.js +351 -0
  298. package/lib/VoIP/voipClient.js.map +1 -0
  299. package/lib/VoIP/wasm-engine.d.ts +2 -2
  300. package/lib/WABinary/decode.d.ts.map +1 -1
  301. package/lib/WABinary/decode.js +10 -0
  302. package/lib/WABinary/decode.js.map +1 -1
  303. package/lib/WABinary/encode.d.ts.map +1 -1
  304. package/lib/WABinary/encode.js +10 -0
  305. package/lib/WABinary/encode.js.map +1 -1
  306. package/lib/WABinary/generic-utils.js +1 -1
  307. package/lib/WABinary/generic-utils.js.map +1 -1
  308. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  309. package/lib/WABinary/jid-utils.js +18 -17
  310. package/lib/WABinary/jid-utils.js.map +1 -1
  311. package/package.json +1 -1
@@ -0,0 +1,1674 @@
1
+ import { toUserJid } from '../shim/protocol.js';
2
+ import { getFirstNodeChild, getNodeChildrenByTag } from '../shim/transport.js';
3
+ import { toError, uint8TimingSafeEqual } from '../shim/util.js';
4
+ import { concatBytes, EMPTY_BYTES, readUInt32BE, toArrayBuffer } from '../bytes.js';
5
+ import { derivePerJidSrtpKey } from '../crypto/encryption.js';
6
+ import { SrtpSession } from '../crypto/srtp.js';
7
+ import { SrtcpSendContext } from '../crypto/rtcp.js';
8
+ import { generateSecureSsrc } from '../crypto/ssrc.js';
9
+ import { WaAppDataStream } from '../app-data/WaAppDataStream.js';
10
+ import { buildScreenShareStanza, parseScreenShareNode, WA_SCREEN_SHARE_STATE } from '../signaling/screen-share.js';
11
+ import { MLowCodec } from '../media/mlow-codec.js';
12
+ import { RtpSession, RtpPacket, VideoRtpStream, VideoMediaFrameInfo, videoRtpDurationSamples } from '../media/rtp.js';
13
+ import { auHasIDR, buildAccessUnitPayload, packageH264NALU, H264AccessUnitAssembler } from '../media/h264.js';
14
+ import { buildSenderReportWithSdes, generateWhatsappRtcpCname } from '../media/rtcp.js';
15
+ import { WaAudioEngine } from '../media/WaAudioEngine.js';
16
+ import { WaVideoEngine } from '../media/WaVideoEngine.js';
17
+ import { parseRelayFromAck } from '../relay/relay-ack.js';
18
+ import { isRtpPacket, isStunPacket } from '../relay/stun.js';
19
+ import { deriveWasmRelayStreamSsrcs } from '../crypto/ssrc.js';
20
+ import { WaManualRelay } from '../relay/WaManualRelay.js';
21
+ import { buildAcceptReceiptStanza, buildAcceptStanza, buildMuteV2Stanza, buildPreacceptStanza, buildRaiseHandStanza, buildRejectStanza, buildRelaylatencyForwardStanza, buildRelayLatencyStanza, buildTerminateStanza, buildTransportStanza, buildVideoStateStanza, decryptCallKey, extractNodeInfo, extractRelayEndpoints, needsDecryption, parseMuteV2, parseRaiseHandState, VideoDecAccept, VideoDecRequest, VideoState } from '../signaling/signaling.js';
22
+ import { CallDirection, CallMediaType, CallState, EndCallReason, PayloadType, SRTP_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN, SRTP_SEND_AUTH_TAG_LEN } from '../types.js';
23
+ export class WaCallMediaSession {
24
+ constructor(options) {
25
+ this.rtpSession = null;
26
+ this.srtpSession = null;
27
+ this.opusCodec = null;
28
+ this.initialTransportSent = false;
29
+ this.outgoingPreacceptSent = false;
30
+ this.selfSsrc = 0;
31
+ this.selfSsrcJid = '';
32
+ this.peerSsrcs = [];
33
+ this.firstPacketSent = false;
34
+ this.acceptedByJid = null;
35
+ this.debeEnabled = true;
36
+ this.audioSendCount = 0;
37
+ this.audioDropCount = 0;
38
+ this.realAudioSendCount = 0;
39
+ this.encodeBufferA = null;
40
+ this.encodeBufferB = null;
41
+ this.encodeBuffer = null;
42
+ this.encodeBufferPos = 0;
43
+ this.authPaddingBuffer = null;
44
+ this.audioRecvCount = 0;
45
+ this.recvRealCount = 0;
46
+ this.recvDtxCount = 0;
47
+ this.srtpErrorCount = 0;
48
+ this.relayPacketCount = 0;
49
+ this.stunResponseCount = 0;
50
+ this.selfEchoCount = 0;
51
+ this.lastRecvSeq = -1;
52
+ this.recvSeqGaps = 0;
53
+ this.lastCapturedAtMs = undefined;
54
+ this.qLog = { n: 0, tiny: 0, sent: 0, octets: 0, retx: 0, rx: 0, plc: 0, late: 0, fec: 0, errors: 0 };
55
+ this.actualPeerSsrc = null;
56
+ this.ssrcResubscribed = false;
57
+ this.videoSsrc = 0;
58
+ this.videoRtpStream = null;
59
+ this.videoSrtpSession = null;
60
+ this.videoSendCount = 0;
61
+ this.videoKeyframeRequired = false;
62
+ this.videoFlushSeen = 0;
63
+ this.videoIdrSendCount = 0;
64
+ this.videoDropCount = 0;
65
+ this.audioRtcpSession = null;
66
+ this.videoRtcpSession = null;
67
+ this.audioRtcpCname = null;
68
+ this.videoRtcpCname = null;
69
+ this.audioOctetsSent = 0;
70
+ this.videoOctetsSent = 0;
71
+ this.rtcpTimer = null;
72
+ this.mediaStartedAtMs = null;
73
+ this.mediaFlowStarted = false;
74
+ this.peerVideoUpgradePending = false;
75
+ this.peerVideoActive = false;
76
+ this.peerVideoJids = new Set();
77
+ this.videoAssembler = null;
78
+ this.appDataStream = null;
79
+ this.appDataSrtpSession = null;
80
+ this.peerAppDataSsrcs = new Set();
81
+ this.onDecodedAudio = (pcm) => {
82
+ this.audioEngine.onPlaybackData(pcm);
83
+ this.delegate.emitInboundAudio?.(this.info, pcm);
84
+ };
85
+ this.deps = options.deps;
86
+ this.logger = options.logger;
87
+ this.info = options.info;
88
+ this.delegate = options.delegate;
89
+ this.sctpRelay = new WaManualRelay({
90
+ logger: this.logger.child({ component: 'sctp' })
91
+ });
92
+ this.audioEngine = new WaAudioEngine({
93
+ logger: this.logger.child({ component: 'audio-engine' })
94
+ });
95
+ this.audioEngine.setAudioSender(this);
96
+ this.audioEngine.setOnAudioFinished(() => {
97
+ this.delegate.emitOutboundAudioFinished(this.info);
98
+ });
99
+ this.videoEngine = new WaVideoEngine({
100
+ logger: this.logger.child({ component: 'video-engine' }),
101
+ ...(options.videoConfig || {})
102
+ });
103
+ this.videoEngine.setVideoSender(this);
104
+ this.sctpRelay.on('relay_connected', () => {
105
+ this.onRelayConnected();
106
+ });
107
+ this.sctpRelay.on('relay_receive', (relayInfo) => {
108
+ this.onRelayData(relayInfo.data);
109
+ });
110
+ }
111
+ get callId() {
112
+ return this.info.callId;
113
+ }
114
+ async initMedia(selfLid, peerJid) {
115
+ const ssrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid));
116
+ this.rtpSession = RtpSession.whatsappOpus(ssrc);
117
+ this.selfSsrc = ssrc;
118
+ this.selfSsrcJid = this.ensureDeviceJid(selfLid);
119
+ const peerSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(peerJid));
120
+ this.peerSsrcs = [peerSsrc];
121
+ this.logger.media('call media initialized', {
122
+ callId: this.info.callId,
123
+ selfSsrc: `0x${ssrc.toString(16).toUpperCase()}`,
124
+ peerSsrc: `0x${peerSsrc.toString(16).toUpperCase()}`
125
+ });
126
+ this.logger.warn('[DIAG] initMedia called', {
127
+ callId: this.info.callId,
128
+ selfSsrc: `0x${ssrc.toString(16).toUpperCase()}`,
129
+ peerSsrc: `0x${peerSsrc.toString(16).toUpperCase()}`,
130
+ videoEngineIsFresh: this.videoEngine?.proc === null
131
+ });
132
+ this.opusCodec = await MLowCodec.create({ logger: this.logger.child({ component: 'mlow' }) });
133
+ if (this.info.mediaType === CallMediaType.Video) {
134
+ this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
135
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
136
+ this.videoAssembler = new H264AccessUnitAssembler();
137
+ this.logger.media('video media initialized', {
138
+ callId: this.info.callId,
139
+ videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`
140
+ });
141
+ this.logger.warn('[DIAG] video media initialized', {
142
+ callId: this.info.callId,
143
+ videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`
144
+ });
145
+ }
146
+ }
147
+ resetOutgoingFlags() {
148
+ this.initialTransportSent = false;
149
+ this.outgoingPreacceptSent = false;
150
+ }
151
+ async acceptCall() {
152
+ if (!this.info.canAccept) {
153
+ throw new Error(`Call ${this.info.callId} cannot be accepted in state ${this.info.stateData.state}`);
154
+ }
155
+ this.info.applyTransition({ type: 'local_accepted' });
156
+ this.delegate.emitState(this.info);
157
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
158
+ const callId = this.info.callId;
159
+ const callCreator = this.info.callCreator;
160
+ const peerJid = this.info.peerJid;
161
+ const isVideo = this.info.mediaType === CallMediaType.Video;
162
+ this.acceptedByJid = peerJid;
163
+ this.initSrtpKeys();
164
+ try {
165
+ const muteNode = buildMuteV2Stanza(peerJid, callId, callCreator, 0, meId);
166
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
167
+ }
168
+ catch (err) {
169
+ this.logger.error('error sending mute_v2', {
170
+ message: toError(err).message
171
+ });
172
+ }
173
+ try {
174
+ const transportNode = buildTransportStanza(peerJid, callId, callCreator, meId, '1', '1');
175
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
176
+ }
177
+ catch (err) {
178
+ this.logger.error('error sending transport', {
179
+ message: toError(err).message
180
+ });
181
+ }
182
+ if (this.info.encryptionKey) {
183
+ const acceptStanza = await buildAcceptStanza(this.deps, this.info.callId, this.info.encryptionKey, this.info.peerJid, this.info.callCreator, isVideo);
184
+ try {
185
+ await this.deps.lowLevelCoordinator.sendNode(acceptStanza);
186
+ }
187
+ catch (err) {
188
+ this.logger.error('accept send error', {
189
+ message: toError(err).message
190
+ });
191
+ }
192
+ }
193
+ if (this.info.relayData) {
194
+ await this.connectRelays(this.info.relayData.endpoints);
195
+ }
196
+ this.logger.media('call accepted', { callId });
197
+ }
198
+ async rejectCall(reason = EndCallReason.Declined) {
199
+ this.info.applyTransition({ type: 'local_rejected', reason });
200
+ this.delegate.emitState(this.info);
201
+ const node = buildRejectStanza(this.info.peerJid, this.info.callId, this.info.callCreator);
202
+ try {
203
+ await this.deps.lowLevelCoordinator.sendNode(node);
204
+ }
205
+ catch (err) {
206
+ this.logger.warn('reject send failed', { message: toError(err).message });
207
+ }
208
+ this.cleanup();
209
+ }
210
+ async endCall(reason = EndCallReason.UserEnded) {
211
+ if (this.info.isEnded)
212
+ return;
213
+ const connectedAt = this.info.stateData.connectedAt;
214
+ const audioDurationMs = connectedAt ? Date.now() - connectedAt.getTime() : undefined;
215
+ this.info.applyTransition({ type: 'terminated', reason });
216
+ const terminateTarget = this.acceptedByJid ?? this.info.peerJid;
217
+ const node = buildTerminateStanza(terminateTarget, this.info.callId, this.info.callCreator, audioDurationMs);
218
+ this.delegate.emitEnded(this.info);
219
+ this.delegate.emitState(this.info);
220
+ try {
221
+ await this.deps.lowLevelCoordinator.sendNode(node);
222
+ }
223
+ catch (err) {
224
+ this.logger.warn('terminate send failed', { message: toError(err).message });
225
+ }
226
+ await new Promise((resolve) => setTimeout(resolve, 400));
227
+ this.cleanup();
228
+ }
229
+ setMute(muted) {
230
+ if (!this.info.isActive)
231
+ return;
232
+ this.info.applyTransition({ type: 'audio_mute_changed', muted });
233
+ this.delegate.emitState(this.info);
234
+ if (muted) {
235
+ this.audioEngine.stopCapture();
236
+ }
237
+ else {
238
+ this.audioEngine.startCapture();
239
+ }
240
+ }
241
+ async loadAudio(audioPath) {
242
+ this.audioEngine.setLoopMode(false);
243
+ await this.audioEngine.loadAudioFile(audioPath);
244
+ this.resetEncodeState();
245
+ this.logger.media('audio loaded for call', { callId: this.info.callId });
246
+ }
247
+ setExternalAudioMode(enabled) {
248
+ this.audioEngine.setExternalMode(enabled);
249
+ if (enabled) {
250
+ this.resetEncodeState();
251
+ this.logger.debug('external audio mode enabled', { callId: this.info.callId });
252
+ }
253
+ }
254
+ feedLiveAudio(data) {
255
+ return this.audioEngine.feedExternalAudio(data);
256
+ }
257
+ getLiveBufferMs() {
258
+ return this.audioEngine.getLiveBufferMs();
259
+ }
260
+ async sendIncomingPreaccept(peerJid) {
261
+ try {
262
+ const preacceptNode = buildPreacceptStanza(peerJid, this.info.callId, this.info.callCreator);
263
+ await this.deps.lowLevelCoordinator.sendNode(preacceptNode);
264
+ }
265
+ catch (err) {
266
+ this.logger.error('error sending preaccept', {
267
+ message: toError(err).message
268
+ });
269
+ }
270
+ }
271
+ async sendIncomingRelayLatency() {
272
+ if (!this.info.relayData)
273
+ return;
274
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
275
+ const callId = this.info.callId;
276
+ const callCreator = this.info.callCreator;
277
+ const destinationJids = this.info.relayData.participantJids || [];
278
+ const seenRelayNames = new Set();
279
+ for (const ep of this.info.relayData.endpoints) {
280
+ const name = ep.relayName || '';
281
+ if (!name || seenRelayNames.has(name))
282
+ continue;
283
+ seenRelayNames.add(name);
284
+ try {
285
+ const relayData = [
286
+ {
287
+ relayName: name,
288
+ latency: ep.c2rRtt || 0,
289
+ addressBytes: ep.addressBytes
290
+ }
291
+ ];
292
+ const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
293
+ await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
294
+ }
295
+ catch (err) {
296
+ this.logger.error('error sending incoming relaylatency', {
297
+ relayName: name,
298
+ message: toError(err).message
299
+ });
300
+ }
301
+ }
302
+ }
303
+ async handleCallAccept(node, peerJid) {
304
+ const nodeInfo = extractNodeInfo(node);
305
+ if (!nodeInfo)
306
+ return;
307
+ let srtpFromPeerKey = false;
308
+ if (needsDecryption(nodeInfo.tag)) {
309
+ try {
310
+ const peerCallKey = await decryptCallKey(this.deps, nodeInfo.innerNode, peerJid, this.logger.child({ component: 'signaling' }));
311
+ if (peerCallKey) {
312
+ const ourCallKey = this.info.encryptionKey;
313
+ const keysMatch = ourCallKey
314
+ ? uint8TimingSafeEqual(ourCallKey, peerCallKey)
315
+ : false;
316
+ if (!keysMatch && ourCallKey) {
317
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
318
+ const meJid = this.deps.authClient.getCurrentCredentials()?.meJid;
319
+ const ourCredJid = meLid || meJid || '';
320
+ const ourBase = ourCredJid ? toUserJid(ourCredJid) : '';
321
+ const participants = this.info.relayData?.participantJids || [];
322
+ const ourDeviceJid = participants.find((jid) => {
323
+ const jBase = toUserJid(jid);
324
+ return jBase === ourBase && /:\d+@/.test(jid);
325
+ }) || ourCredJid;
326
+ if (ourDeviceJid && peerJid) {
327
+ try {
328
+ const sendKeying = derivePerJidSrtpKey(ourCallKey, this.ensureDeviceJid(ourDeviceJid));
329
+ const recvKeying = derivePerJidSrtpKey(peerCallKey, this.ensureDeviceJid(peerJid));
330
+ this.srtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
331
+ srtpFromPeerKey = true;
332
+ this.logger.debug('srtp re-initialized with peer call_key', {
333
+ callId: this.info.callId
334
+ });
335
+ }
336
+ catch (err) {
337
+ this.logger.error('per-jid srtp re-derivation failed', {
338
+ message: toError(err).message
339
+ });
340
+ }
341
+ }
342
+ }
343
+ }
344
+ }
345
+ catch (err) {
346
+ this.logger.error('accept decrypt error', {
347
+ message: toError(err).message
348
+ });
349
+ }
350
+ }
351
+ try {
352
+ this.info.applyTransition({ type: 'remote_accepted' });
353
+ this.delegate.emitState(this.info);
354
+ }
355
+ catch (err) {
356
+ this.logger.trace('call transition skipped', { message: toError(err).message });
357
+ }
358
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
359
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
360
+ const ourJid = meLid || meId;
361
+ const ourBase = ourJid ? toUserJid(ourJid) : '';
362
+ const callId = this.info.callId;
363
+ const callCreator = this.info.callCreator;
364
+ const acceptingDeviceJid = peerJid;
365
+ this.acceptedByJid = acceptingDeviceJid;
366
+ if (this.actualPeerSsrc !== null) {
367
+ const calculatedJid = this.ensureDeviceJid(acceptingDeviceJid);
368
+ this.logger.debug('accept keeping actual peer ssrc', {
369
+ callId,
370
+ actualPeerSsrc: `0x${this.actualPeerSsrc.toString(16)}`,
371
+ calculatedJid
372
+ });
373
+ }
374
+ else {
375
+ const peerDeviceJidForSsrc = this.ensureDeviceJid(acceptingDeviceJid);
376
+ const acceptSsrc = generateSecureSsrc(callId, peerDeviceJidForSsrc);
377
+ this.peerSsrcs = [acceptSsrc];
378
+ this.logger.debug('accept ssrc assigned', {
379
+ callId,
380
+ jid: peerDeviceJidForSsrc,
381
+ ssrc: `0x${acceptSsrc.toString(16)}`
382
+ });
383
+ }
384
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
385
+ this.sctpRelay.resendSubscriptions();
386
+ if (!srtpFromPeerKey) {
387
+ this.initSrtpKeys();
388
+ }
389
+ if (this.info.relayData?.participantJids) {
390
+ const otherDevices = this.info.relayData.participantJids.filter((jid) => {
391
+ if (jid === acceptingDeviceJid)
392
+ return false;
393
+ const jidBase = toUserJid(jid);
394
+ if (jidBase === ourBase)
395
+ return false;
396
+ return true;
397
+ });
398
+ for (const deviceJid of otherDevices) {
399
+ try {
400
+ const terminateNode = buildTerminateStanza(deviceJid, callId, callCreator, undefined, 'accepted_elsewhere');
401
+ await this.deps.lowLevelCoordinator.sendNode(terminateNode);
402
+ }
403
+ catch (err) {
404
+ this.logger.error('error sending terminate_elsewhere', {
405
+ deviceJid,
406
+ message: toError(err).message
407
+ });
408
+ }
409
+ }
410
+ }
411
+ try {
412
+ const transportNode = buildTransportStanza(acceptingDeviceJid, callId, callCreator, meId, '1', '1');
413
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
414
+ }
415
+ catch (err) {
416
+ this.logger.error('error sending transport', {
417
+ message: toError(err).message
418
+ });
419
+ }
420
+ try {
421
+ const muteNode = buildMuteV2Stanza(acceptingDeviceJid, callId, callCreator, 0, meId);
422
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
423
+ }
424
+ catch (err) {
425
+ this.logger.error('error sending mute_v2', {
426
+ message: toError(err).message
427
+ });
428
+ }
429
+ const acceptMsgId = node.attrs?.id;
430
+ if (acceptMsgId) {
431
+ try {
432
+ const receiptNode = buildAcceptReceiptStanza(acceptingDeviceJid, acceptMsgId, callId, callCreator, ourJid);
433
+ await this.deps.lowLevelCoordinator.sendNode(receiptNode);
434
+ }
435
+ catch (err) {
436
+ this.logger.error('error sending accept receipt', {
437
+ message: toError(err).message
438
+ });
439
+ }
440
+ }
441
+ if (this.sctpRelay.hasConnection()) {
442
+ try {
443
+ this.info.applyTransition({ type: 'media_connected' });
444
+ this.delegate.emitState(this.info);
445
+ const MEDIA_START_DELAY_MS = 3000;
446
+ setTimeout(() => {
447
+ this.logger.warn('[DIAG] delayed startMediaFlow firing (path B)', {
448
+ callId: this.info.callId, state: this.info.stateData.state
449
+ });
450
+ if (this.info.stateData.state === CallState.Ended) {
451
+ return;
452
+ }
453
+ this.startMediaFlow();
454
+ }, MEDIA_START_DELAY_MS);
455
+ }
456
+ catch (err) {
457
+ this.logger.trace('call transition skipped', { message: toError(err).message });
458
+ }
459
+ }
460
+ else if (this.info.relayData) {
461
+ await this.connectRelays(this.info.relayData.endpoints);
462
+ }
463
+ }
464
+ async handleCallPreaccept(node, peerJid) {
465
+ const nodeInfo = extractNodeInfo(node);
466
+ if (!nodeInfo)
467
+ return;
468
+ if (this.info.direction === CallDirection.Outgoing && this.info.relayData) {
469
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
470
+ const callId = this.info.callId;
471
+ const callCreator = this.info.callCreator;
472
+ const destinationJids = this.info.relayData.participantJids || [];
473
+ const seenRelayNames = new Set();
474
+ for (const ep of this.info.relayData.endpoints) {
475
+ const name = ep.relayName || '';
476
+ if (!name || seenRelayNames.has(name))
477
+ continue;
478
+ seenRelayNames.add(name);
479
+ try {
480
+ const relayData = [
481
+ {
482
+ relayName: name,
483
+ latency: ep.c2rRtt || 0,
484
+ addressBytes: ep.addressBytes
485
+ }
486
+ ];
487
+ const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
488
+ await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
489
+ }
490
+ catch (err) {
491
+ this.logger.error('error sending relaylatency', {
492
+ relayName: name,
493
+ message: toError(err).message
494
+ });
495
+ }
496
+ }
497
+ if (!this.initialTransportSent) {
498
+ try {
499
+ const basePeerJid = toUserJid(peerJid);
500
+ const transportNode = buildTransportStanza(basePeerJid, callId, callCreator, meId);
501
+ await this.deps.lowLevelCoordinator.sendNode(transportNode);
502
+ this.initialTransportSent = true;
503
+ }
504
+ catch (err) {
505
+ this.logger.error('error sending initial transport', {
506
+ message: toError(err).message
507
+ });
508
+ }
509
+ }
510
+ }
511
+ }
512
+ async handleCallTransport(_node) {
513
+ const nodeInfo = extractNodeInfo(_node);
514
+ if (!nodeInfo)
515
+ return;
516
+ const relays = extractRelayEndpoints(nodeInfo.innerNode);
517
+ if (relays.length > 0 && !this.sctpRelay.hasConnection()) {
518
+ this.info.relayData = {
519
+ ...this.info.relayData,
520
+ endpoints: relays
521
+ };
522
+ await this.connectRelays(relays);
523
+ }
524
+ }
525
+ async handleCallAck(node) {
526
+ const ackType = node.attrs?.type;
527
+ if (ackType !== 'offer')
528
+ return;
529
+ const error = node.attrs?.error;
530
+ if (error) {
531
+ this.logger.error('ack error', { callId: this.info.callId, error });
532
+ return;
533
+ }
534
+ const { relays, participantJids, uuid, selfPid, peerPid, hbhKey } = parseRelayFromAck(node);
535
+ if (relays.length > 0) {
536
+ this.info.relayData = {
537
+ endpoints: relays,
538
+ participantJids,
539
+ uuid,
540
+ selfPid,
541
+ peerPid,
542
+ hbhKey
543
+ };
544
+ this.logger.debug('offer ack relays parsed', {
545
+ callId: this.info.callId,
546
+ relayCount: relays.length,
547
+ participantCount: participantJids.length
548
+ });
549
+ const callKey = this.info.encryptionKey;
550
+ if (participantJids.length > 0) {
551
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
552
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid;
553
+ const ourCredJid = meLid || meId || '';
554
+ const ourBase = ourCredJid ? toUserJid(ourCredJid) : '';
555
+ const ourDeviceJid = this.ensureDeviceJid(participantJids.find((jid) => {
556
+ const jidBase = toUserJid(jid);
557
+ return jidBase === ourBase && /:\d+@/.test(jid);
558
+ }) || ourCredJid);
559
+ const peerJids = participantJids.filter((jid) => {
560
+ const jidBase = toUserJid(jid);
561
+ return jidBase !== ourBase;
562
+ });
563
+ const peerCandidate = peerJids.find((jid) => /:\d+@/.test(jid) && !/:0@/.test(jid)) || peerJids[0];
564
+ const peerDeviceJid = peerCandidate ? this.ensureDeviceJid(peerCandidate) : undefined;
565
+ const newSelfSsrc = generateSecureSsrc(this.info.callId, ourDeviceJid);
566
+ if (newSelfSsrc !== this.selfSsrc) {
567
+ this.selfSsrc = newSelfSsrc;
568
+ this.selfSsrcJid = ourDeviceJid;
569
+ this.rtpSession = RtpSession.whatsappOpus(newSelfSsrc);
570
+ }
571
+ if (peerDeviceJid) {
572
+ const peerDeviceSsrc = generateSecureSsrc(this.info.callId, peerDeviceJid);
573
+ this.peerSsrcs = [peerDeviceSsrc];
574
+ }
575
+ if (callKey) {
576
+ this.initSrtpKeys();
577
+ }
578
+ else {
579
+ this.logger.media('no call_key, srtp not initialized', {
580
+ callId: this.info.callId
581
+ });
582
+ }
583
+ }
584
+ if (this.info.isInitiator && !this.outgoingPreacceptSent) {
585
+ try {
586
+ const preacceptNode = buildPreacceptStanza(this.info.peerJid, this.info.callId, this.info.callCreator);
587
+ await this.deps.lowLevelCoordinator.sendNode(preacceptNode);
588
+ this.outgoingPreacceptSent = true;
589
+ }
590
+ catch (err) {
591
+ this.logger.error('error sending preaccept (caller)', {
592
+ message: toError(err).message
593
+ });
594
+ }
595
+ }
596
+ await this.connectRelays(relays);
597
+ if (this.srtpSession &&
598
+ this.rtpSession &&
599
+ this.opusCodec &&
600
+ this.sctpRelay.hasConnection()) {
601
+ this.audioEngine.startSilenceCapture();
602
+ }
603
+ }
604
+ }
605
+ async handleCallRelaylatency(node, peerJid) {
606
+ const nodeInfo = extractNodeInfo(node);
607
+ if (!nodeInfo)
608
+ return;
609
+ const inner = nodeInfo.innerNode;
610
+ const callId = inner.attrs?.['call-id'] || this.info.callId;
611
+ const callCreator = inner.attrs?.['call-creator'] || this.info.callCreator;
612
+ const teNodes = getNodeChildrenByTag(inner, 'te');
613
+ if (teNodes.length === 0)
614
+ return;
615
+ const destinationJids = this.info.relayData?.participantJids || [];
616
+ if (destinationJids.length > 0) {
617
+ const forwardNode = buildRelaylatencyForwardStanza(peerJid, callId, callCreator, teNodes, destinationJids);
618
+ try {
619
+ await this.deps.lowLevelCoordinator.sendNode(forwardNode);
620
+ }
621
+ catch (err) {
622
+ this.logger.error('error forwarding relaylatency', {
623
+ message: toError(err).message
624
+ });
625
+ }
626
+ }
627
+ }
628
+ handleRelayElection(node) {
629
+ const inner = getFirstNodeChild(node);
630
+ if (!inner)
631
+ return;
632
+ let electedRelayIdx;
633
+ if (inner.attrs?.['elected_relay_idx'] !== undefined) {
634
+ const parsed = Number(inner.attrs['elected_relay_idx']);
635
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
636
+ electedRelayIdx = parsed;
637
+ }
638
+ else if (inner.attrs?.['relay_id'] !== undefined) {
639
+ const parsed = Number(inner.attrs['relay_id']);
640
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
641
+ electedRelayIdx = parsed;
642
+ }
643
+ else if (inner.content instanceof Uint8Array) {
644
+ const bytes = inner.content;
645
+ if (bytes.length >= 4)
646
+ electedRelayIdx = readUInt32BE(bytes, 0);
647
+ else if (bytes.length > 0)
648
+ electedRelayIdx = bytes[0];
649
+ }
650
+ if (electedRelayIdx !== undefined) {
651
+ this.info.electedRelayIdx = electedRelayIdx;
652
+ this.logger.debug('elected relay index', {
653
+ callId: this.info.callId,
654
+ electedRelayIdx
655
+ });
656
+ }
657
+ }
658
+ async handleCallMuteV2(node, peerJid) {
659
+ const nodeInfo = extractNodeInfo(node);
660
+ if (!nodeInfo)
661
+ return;
662
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
663
+ const callId = this.info.callId;
664
+ const callCreator = this.info.callCreator;
665
+ if (!this.isOwnAccountJid(peerJid)) {
666
+ const payload = parseMuteV2(nodeInfo.innerNode);
667
+ if (!payload.isRequest && payload.muted !== null && this.info.stateData.peerAudioMuted !== payload.muted) {
668
+ this.info.stateData.peerAudioMuted = payload.muted;
669
+ this.delegate.emitPeerMute?.(this.info, payload.muted);
670
+ }
671
+ }
672
+ try {
673
+ const muteNode = buildMuteV2Stanza(peerJid, callId, callCreator, 0, meId);
674
+ await this.deps.lowLevelCoordinator.sendNode(muteNode);
675
+ }
676
+ catch (err) {
677
+ this.logger.error('error sending mute_v2 response', {
678
+ message: toError(err).message
679
+ });
680
+ }
681
+ }
682
+ isOwnAccountJid(jid) {
683
+ const creds = this.deps.authClient.getCurrentCredentials();
684
+ const user = toUserJid(jid);
685
+ return ((!!creds?.meLid && user === toUserJid(creds.meLid)) ||
686
+ (!!creds?.meJid && user === toUserJid(creds.meJid)));
687
+ }
688
+ get videoSendActive() {
689
+ return !!(this.videoRtpStream && this.videoSrtpSession);
690
+ }
691
+ async setHandRaised(raised) {
692
+ if (!this.info.isActive)
693
+ return;
694
+ if (this.info.stateData.handRaised === raised)
695
+ return;
696
+ const node = buildRaiseHandStanza(this.acceptedByJid ?? this.info.peerJid, this.info.callId, this.info.callCreator, raised);
697
+ try {
698
+ await this.deps.lowLevelCoordinator.sendNode(node);
699
+ }
700
+ catch (err) {
701
+ this.logger.warn('raise hand send failed', {
702
+ raised,
703
+ message: toError(err).message
704
+ });
705
+ throw err;
706
+ }
707
+ this.info.applyTransition({ type: 'hand_raise_changed', raised });
708
+ this.delegate.emitState(this.info);
709
+ }
710
+ async setScreenShare(sharing) {
711
+ if (!this.info.isActive)
712
+ return;
713
+ if (this.info.stateData.screenSharing === sharing)
714
+ return;
715
+ if (sharing && !this.videoSendActive) {
716
+ throw new Error(`Call ${this.info.callId} carries no video to share the screen on`);
717
+ }
718
+ const peerDeviceJid = this.acceptedByJid ?? this.info.peerJid;
719
+ const state = sharing ? WA_SCREEN_SHARE_STATE.Started : WA_SCREEN_SHARE_STATE.Stopped;
720
+ try {
721
+ await this.deps.lowLevelCoordinator.sendNode(buildScreenShareStanza(peerDeviceJid, this.info.callId, this.info.callCreator, state));
722
+ }
723
+ catch (err) {
724
+ this.logger.warn('screen share request failed', {
725
+ sharing,
726
+ message: toError(err).message
727
+ });
728
+ throw err;
729
+ }
730
+ this.info.applyTransition({ type: 'screen_share_changed', sharing });
731
+ this.delegate.emitState(this.info);
732
+ }
733
+ handleCallUserAction(node, peerJid) {
734
+ this.applyPeerRaiseHand(node, peerJid);
735
+ }
736
+ handleCallRaiseHand(node, peerJid) {
737
+ this.applyPeerRaiseHand(node, peerJid);
738
+ }
739
+ applyPeerRaiseHand(node, peerJid) {
740
+ const nodeInfo = extractNodeInfo(node);
741
+ if (!nodeInfo)
742
+ return;
743
+ if (this.isOwnAccountJid(peerJid))
744
+ return;
745
+ const raised = parseRaiseHandState(nodeInfo.innerNode);
746
+ if (raised === null)
747
+ return;
748
+ const raisedHands = this.info.raisedHands;
749
+ if (raisedHands.has(peerJid) === raised)
750
+ return;
751
+ if (raised) {
752
+ if (raisedHands.size >= 64)
753
+ return;
754
+ raisedHands.add(peerJid);
755
+ }
756
+ else {
757
+ raisedHands.delete(peerJid);
758
+ }
759
+ this.delegate.emitHandRaise?.(this.info, peerJid, raised);
760
+ }
761
+ handleCallScreenShare(node) {
762
+ const nodeInfo = extractNodeInfo(node);
763
+ if (!nodeInfo)
764
+ return;
765
+ const share = parseScreenShareNode(nodeInfo.innerNode);
766
+ if (!share)
767
+ return;
768
+ this.info.peerScreenShare = share;
769
+ this.delegate.emitScreenShare?.(this.info, share);
770
+ this.delegate.emitState(this.info);
771
+ }
772
+ sendReaction(reaction) {
773
+ if (!this.appDataStream || !this.appDataSrtpSession)
774
+ return false;
775
+ if (!this.info.isActive)
776
+ return false;
777
+ return this.appDataStream.sendReaction(reaction);
778
+ }
779
+ openAppDataStream(selfDeviceJid) {
780
+ const ssrc = generateSecureSsrc(this.info.callId, selfDeviceJid, 6);
781
+ this.appDataStream?.close();
782
+ this.appDataStream = new WaAppDataStream({
783
+ logger: this.logger.child({ component: 'app-data' }),
784
+ ssrc,
785
+ sendPacket: (packet) => {
786
+ if (!this.appDataSrtpSession)
787
+ return false;
788
+ return this.sctpRelay.broadcast(toArrayBuffer(this.appDataSrtpSession.protect(packet)));
789
+ }
790
+ });
791
+ }
792
+ trackPeerAppDataSsrcs(deviceJids) {
793
+ for (const jid of deviceJids) {
794
+ if (!jid)
795
+ continue;
796
+ if (this.peerAppDataSsrcs.size >= 16)
797
+ break;
798
+ this.peerAppDataSsrcs.add(generateSecureSsrc(this.info.callId, this.ensureDeviceJid(jid), 6));
799
+ }
800
+ }
801
+ onAppDataPacket(data, payloadType, ssrc) {
802
+ const stream = this.appDataStream;
803
+ if (!stream || !this.appDataSrtpSession)
804
+ return;
805
+ try {
806
+ const packet = this.appDataSrtpSession.unprotect(data);
807
+ stream.observeInboundPayloadType(payloadType);
808
+ for (const reaction of stream.receive(packet.payload, ssrc)) {
809
+ this.delegate.emitCallReaction?.(this.info, reaction);
810
+ }
811
+ }
812
+ catch (err) {
813
+ this.logger.debug('app data packet dropped', {
814
+ callId: this.info.callId,
815
+ payloadType,
816
+ message: toError(err).message
817
+ });
818
+ }
819
+ }
820
+ async handleCallVideo(node) {
821
+ const nodeInfo = extractNodeInfo(node);
822
+ if (!nodeInfo)
823
+ return;
824
+ const inner = nodeInfo.innerNode;
825
+ const state = Number(inner.attrs?.state ?? Number.NaN);
826
+ if (!Number.isFinite(state))
827
+ return;
828
+ const peerJid = this.acceptedByJid || this.info.peerJid;
829
+ const callId = this.info.callId;
830
+ const callCreator = this.info.callCreator;
831
+ const sourceJid = nodeInfo.peerJid || peerJid;
832
+ const setPeerVideo = (on) => {
833
+ const before = this.peerVideoJids.size;
834
+ if (on)
835
+ this.peerVideoJids.add(sourceJid);
836
+ else
837
+ this.peerVideoJids.delete(sourceJid);
838
+ this.peerVideoActive = this.peerVideoJids.size > 0;
839
+ return { before, after: this.peerVideoJids.size };
840
+ };
841
+ this.logger.media('inbound video state', { callId, state });
842
+ switch (state) {
843
+ case VideoState.UpgradeRequest:
844
+ case VideoState.UpgradeRequestV2: {
845
+ setPeerVideo(true);
846
+ this.peerVideoUpgradePending = true;
847
+ await this.enableVideoMidCall();
848
+ try {
849
+ const accept = buildVideoStateStanza(peerJid, callId, callCreator, VideoState.UpgradeAccept, { dec: VideoDecAccept });
850
+ await this.deps.lowLevelCoordinator.sendNode(accept);
851
+ }
852
+ catch (err) {
853
+ this.logger.error('error sending video upgrade accept', { callId, message: toError(err).message });
854
+ }
855
+ this.peerVideoUpgradePending = false;
856
+ this.info.mediaType = CallMediaType.Video;
857
+ this.info.stateData.videoOff = false;
858
+ this.delegate.emitState(this.info);
859
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: true, raw: state, jid: sourceJid });
860
+ break;
861
+ }
862
+ case VideoState.Disabled:
863
+ case VideoState.Stopped: {
864
+ const { before, after } = setPeerVideo(false);
865
+ if (state === VideoState.Disabled && before === after)
866
+ break;
867
+ this.delegate.emitVideoState?.(this.info, {
868
+ active: false,
869
+ upgrade: false,
870
+ raw: state,
871
+ direction: 'inbound',
872
+ jid: sourceJid,
873
+ allOff: before > 0 && after === 0
874
+ });
875
+ break;
876
+ }
877
+ case VideoState.UpgradeReject:
878
+ case VideoState.UpgradeCancel: {
879
+ this.disableVideoMidCall({ keepSource: true });
880
+ this.delegate.emitVideoState?.(this.info, { active: false, upgrade: false, raw: state });
881
+ break;
882
+ }
883
+ case VideoState.Enabled: {
884
+ setPeerVideo(true);
885
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: false, raw: state, direction: 'inbound', jid: sourceJid });
886
+ break;
887
+ }
888
+ default:
889
+ break;
890
+ }
891
+ }
892
+ async startVideoMidCall() {
893
+ const peerJid = this.acceptedByJid || this.info.peerJid;
894
+ const request = buildVideoStateStanza(peerJid, this.info.callId, this.info.callCreator, VideoState.UpgradeRequestV2, { dec: VideoDecRequest });
895
+ await this.deps.lowLevelCoordinator.sendNode(request);
896
+ await this.enableVideoMidCall();
897
+ this.info.mediaType = CallMediaType.Video;
898
+ this.info.stateData.videoOff = false;
899
+ this.delegate.emitState(this.info);
900
+ this.delegate.emitVideoState?.(this.info, { active: true, upgrade: true, raw: VideoState.UpgradeRequestV2 });
901
+ }
902
+ async enableVideoMidCall() {
903
+ if (this.videoRtpStream && this.videoSrtpSession)
904
+ return;
905
+ const creds = this.deps.authClient.getCurrentCredentials();
906
+ const selfLid = creds?.meLid || creds?.meJid || '';
907
+ if (!this.videoSsrc) {
908
+ this.videoSsrc = generateSecureSsrc(this.info.callId, this.ensureDeviceJid(selfLid), 2);
909
+ }
910
+ this.videoRtpStream = new VideoRtpStream(this.videoSsrc, videoRtpDurationSamples(this.videoEngine.frameDurationMs));
911
+ if (this.srtpSession) {
912
+ const meLid = creds?.meLid;
913
+ const meId = creds?.meJid;
914
+ const ourBase = toUserJid(meLid || meId || '');
915
+ const participants = this.info.relayData?.participantJids || [];
916
+ const ourDeviceJid = this.ensureDeviceJid(participants.find((jid) => toUserJid(jid) === ourBase && /:\d+@/.test(jid)) || meLid || meId || '');
917
+ const peerDeviceJid = this.ensureDeviceJid(this.acceptedByJid || this.info.peerJid);
918
+ try {
919
+ const sendKeying = derivePerJidSrtpKey(this.info.encryptionKey, ourDeviceJid);
920
+ const recvKeying = derivePerJidSrtpKey(this.info.encryptionKey, peerDeviceJid);
921
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
922
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
923
+ }
924
+ catch (err) {
925
+ this.logger.error('video srtp key derivation failed', { callId: this.info.callId, message: toError(err).message });
926
+ }
927
+ }
928
+ this.videoAssembler = new H264AccessUnitAssembler();
929
+ if (!this.videoEngine.hasSource()) {
930
+ try {
931
+ await this.videoEngine.loadBlankSource();
932
+ }
933
+ catch (err) {
934
+ this.logger.error('blank video fallback unavailable', { callId: this.info.callId, message: toError(err).message });
935
+ }
936
+ }
937
+ if (this.sctpRelay.hasConnection()) {
938
+ this.videoEngine.start();
939
+ }
940
+ this.logger.media('video enabled mid-call', {
941
+ callId: this.info.callId,
942
+ videoSsrc: `0x${this.videoSsrc.toString(16).toUpperCase()}`,
943
+ source: this.videoEngine.sourceKind
944
+ });
945
+ }
946
+ async swapVideoSource(videoPath) {
947
+ if (this.info.mediaType !== CallMediaType.Video) {
948
+ throw new Error(`Call ${this.info.callId} has no active video stream to swap`);
949
+ }
950
+ this.videoEngine.stop({ keepSource: false });
951
+ await this.videoEngine.loadVideoFile(videoPath);
952
+ this.audioEngine.setLoopMode(true);
953
+ this.videoEngine.start();
954
+ this.logger.media('video source swapped', { callId: this.info.callId, videoPath });
955
+ }
956
+ async stopVideoMidCall({ keepSource = false } = {}) {
957
+ const peerJid = this.acceptedByJid || this.info.peerJid;
958
+ try {
959
+ const stop = buildVideoStateStanza(peerJid, this.info.callId, this.info.callCreator, VideoState.Stopped);
960
+ await this.deps.lowLevelCoordinator.sendNode(stop);
961
+ }
962
+ catch (err) {
963
+ this.logger.error('error sending video stop', { callId: this.info.callId, message: toError(err).message });
964
+ }
965
+ this.disableVideoMidCall({ keepSource });
966
+ this.info.stateData.videoOff = true;
967
+ this.delegate.emitState(this.info);
968
+ this.delegate.emitVideoState?.(this.info, { active: false, upgrade: false, raw: VideoState.Stopped });
969
+ }
970
+ disableVideoMidCall({ keepSource = false } = {}) {
971
+ this.videoEngine.stop({ keepSource });
972
+ this.videoRtpStream = null;
973
+ this.videoSrtpSession = null;
974
+ this.videoRtcpSession = null;
975
+ this.videoAssembler = null;
976
+ this.info.mediaType = CallMediaType.Audio;
977
+ this.logger.media('video disabled mid-call', { callId: this.info.callId, keptSource: keepSource });
978
+ }
979
+ handleCallTerminate() {
980
+ try {
981
+ this.info.applyTransition({
982
+ type: 'terminated',
983
+ reason: EndCallReason.UserEnded
984
+ });
985
+ }
986
+ catch (err) {
987
+ this.logger.trace('call transition skipped', { message: toError(err).message });
988
+ }
989
+ this.delegate.emitEnded(this.info);
990
+ this.delegate.emitState(this.info);
991
+ this.cleanup();
992
+ }
993
+ sendCapturedAudio(data) {
994
+ const nowMs = Date.now();
995
+ if (this.lastCapturedAtMs !== undefined) {
996
+ const gapMs = nowMs - this.lastCapturedAtMs;
997
+ if (gapMs > 300) {
998
+ this.logger.warn('captured audio frame gap larger than expected', {
999
+ callId: this.info.callId,
1000
+ gapMs,
1001
+ audioSendCount: this.audioSendCount,
1002
+ sctpBacklog: this.sctpRelay.getSendBacklog()
1003
+ });
1004
+ }
1005
+ }
1006
+ this.lastCapturedAtMs = nowMs;
1007
+ const hasRelay = this.sctpRelay.hasConnection();
1008
+ if (!this.rtpSession || !this.srtpSession || !this.opusCodec || !hasRelay) {
1009
+ this.audioDropCount++;
1010
+ if (this.audioDropCount === 1 || this.audioDropCount % 500 === 0) {
1011
+ const missing = [
1012
+ !this.rtpSession && 'rtpSession',
1013
+ !this.srtpSession && 'srtpSession',
1014
+ !this.opusCodec && 'opusCodec',
1015
+ !hasRelay && 'relayConnection'
1016
+ ]
1017
+ .filter(Boolean)
1018
+ .join(', ');
1019
+ this.logger.media('audio dropped', {
1020
+ callId: this.info.callId,
1021
+ dropCount: this.audioDropCount,
1022
+ missing
1023
+ });
1024
+ }
1025
+ return;
1026
+ }
1027
+ for (let i = 0; i < data.length; i++) {
1028
+ if (!Number.isFinite(data[i])) {
1029
+ data[i] = 0;
1030
+ }
1031
+ }
1032
+ const frameSamples = this.encodeFrameSamples;
1033
+ if (!this.encodeBuffer) {
1034
+ if (!this.encodeBufferA) {
1035
+ this.encodeBufferA = new Float32Array(frameSamples);
1036
+ this.encodeBufferB = new Float32Array(frameSamples);
1037
+ }
1038
+ this.encodeBuffer = this.encodeBufferA;
1039
+ this.encodeBufferPos = 0;
1040
+ }
1041
+ let offset = 0;
1042
+ while (offset < data.length) {
1043
+ const toCopy = Math.min(data.length - offset, frameSamples - this.encodeBufferPos);
1044
+ this.encodeBuffer.set(data.subarray(offset, offset + toCopy), this.encodeBufferPos);
1045
+ this.encodeBufferPos += toCopy;
1046
+ offset += toCopy;
1047
+ if (this.encodeBufferPos < frameSamples)
1048
+ break;
1049
+ const frameData = this.encodeBuffer;
1050
+ this.encodeBuffer =
1051
+ frameData === this.encodeBufferA ? this.encodeBufferB : this.encodeBufferA;
1052
+ this.encodeBufferPos = 0;
1053
+ try {
1054
+ const opusFrame = this.opusCodec.encode(frameData);
1055
+ if (opusFrame.length <= 18)
1056
+ this.qLog.tiny++;
1057
+ this.sendOpusFrame(opusFrame, false);
1058
+ this.realAudioSendCount++;
1059
+ }
1060
+ catch (err) {
1061
+ this.logger.error('encode error', {
1062
+ callId: this.info.callId,
1063
+ message: toError(err).message
1064
+ });
1065
+ }
1066
+ }
1067
+ }
1068
+ async loadVideo(videoPath) {
1069
+ if (this.info.mediaType !== CallMediaType.Video) {
1070
+ throw new Error(`Call ${this.info.callId} was not started with isVideo — no video SSRC/RTP stream to send on`);
1071
+ }
1072
+ await this.videoEngine.loadVideoFile(videoPath);
1073
+ this.audioEngine.setLoopMode(true);
1074
+ if (this.mediaFlowStarted && this.sctpRelay.hasConnection()) {
1075
+ this.videoEngine.start();
1076
+ }
1077
+ }
1078
+ sendCapturedVideoAU(au, durationMs) {
1079
+ const hasRelay = this.sctpRelay.hasConnection();
1080
+ if (!this.videoRtpStream || !this.videoSrtpSession || !hasRelay) {
1081
+ this.videoDropCount++;
1082
+ if (this.videoDropCount === 1 || this.videoDropCount % 150 === 0) {
1083
+ const missing = [
1084
+ !this.videoRtpStream && 'videoRtpStream',
1085
+ !this.videoSrtpSession && 'videoSrtpSession',
1086
+ !hasRelay && 'relayConnection'
1087
+ ].filter(Boolean).join(', ');
1088
+ this.logger.media('video access unit dropped', {
1089
+ callId: this.info.callId, dropCount: this.videoDropCount, missing
1090
+ });
1091
+ }
1092
+ return;
1093
+ }
1094
+ try {
1095
+ const payload = buildAccessUnitPayload(au);
1096
+ if (!payload)
1097
+ return;
1098
+ const idr = auHasIDR(au);
1099
+ const flushesBefore = this.sctpRelay.getVideoFlushCount();
1100
+ if (flushesBefore !== this.videoFlushSeen) {
1101
+ this.videoFlushSeen = flushesBefore;
1102
+ this.videoKeyframeRequired = true;
1103
+ }
1104
+ if (this.videoKeyframeRequired && !idr)
1105
+ return;
1106
+ const mediaFrameInfo = idr ? VideoMediaFrameInfo.IDR : VideoMediaFrameInfo.Delta;
1107
+ this.videoRtpStream.setTimestampStride(videoRtpDurationSamples(durationMs));
1108
+ const chunks = packageH264NALU(payload);
1109
+ for (let i = 0; i < chunks.length; i++) {
1110
+ const header = this.videoRtpStream.nextPacket(i === chunks.length - 1, mediaFrameInfo);
1111
+ const srtpData = this.videoSrtpSession.protect(new RtpPacket(header, chunks[i]));
1112
+ this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1113
+ this.videoOctetsSent = (this.videoOctetsSent + chunks[i].length) >>> 0;
1114
+ }
1115
+ const flushesAfter = this.sctpRelay.getVideoFlushCount();
1116
+ if (flushesAfter !== flushesBefore) {
1117
+ this.videoFlushSeen = flushesAfter;
1118
+ this.videoKeyframeRequired = true;
1119
+ }
1120
+ else if (idr) {
1121
+ this.videoKeyframeRequired = false;
1122
+ }
1123
+ this.videoSendCount++;
1124
+ if (idr)
1125
+ this.videoIdrSendCount++;
1126
+ if (idr || this.videoSendCount === 1 || this.videoSendCount % 150 === 0) {
1127
+ this.logger.media('video sent', {
1128
+ callId: this.info.callId, sendCount: this.videoSendCount,
1129
+ idrSentTotal: this.videoIdrSendCount,
1130
+ auBytes: au.length, packets: chunks.length, idr
1131
+ });
1132
+ }
1133
+ }
1134
+ catch (err) {
1135
+ this.logger.error('error sending video', {
1136
+ callId: this.info.callId, message: toError(err).message
1137
+ });
1138
+ }
1139
+ }
1140
+ cleanup() {
1141
+ this.logger.warn('[DIAG] cleanup entered', { callId: this.info.callId, state: this.info.stateData.state });
1142
+ const opusStats = this.opusCodec?.getStats();
1143
+ this.logger.media('call stats', {
1144
+ callId: this.info.callId,
1145
+ relayPackets: this.relayPacketCount,
1146
+ recvOk: this.audioRecvCount,
1147
+ srtpErrors: this.srtpErrorCount,
1148
+ sent: this.audioSendCount,
1149
+ dropped: this.audioDropCount,
1150
+ opusOk: opusStats?.success ?? 0,
1151
+ opusErr: opusStats?.errors ?? 0,
1152
+ videoSent: this.videoSendCount,
1153
+ videoIdrSent: this.videoIdrSendCount,
1154
+ videoDropped: this.videoDropCount
1155
+ });
1156
+ this.audioEngine.setOnAudioFinished(null);
1157
+ this.audioEngine.stop();
1158
+ this.videoEngine.stop();
1159
+ this.sctpRelay.cleanup();
1160
+ if (this.rtcpTimer) {
1161
+ clearInterval(this.rtcpTimer);
1162
+ this.rtcpTimer = null;
1163
+ }
1164
+ if (this.opusCodec) {
1165
+ this.opusCodec.destroy();
1166
+ this.opusCodec = null;
1167
+ }
1168
+ this.rtpSession = null;
1169
+ this.srtpSession = null;
1170
+ this.appDataStream?.close();
1171
+ this.appDataStream = null;
1172
+ this.appDataSrtpSession = null;
1173
+ this.peerAppDataSsrcs.clear();
1174
+ this.audioRtcpSession = null;
1175
+ this.audioRtcpCname = null;
1176
+ this.audioOctetsSent = 0;
1177
+ this.videoRtpStream = null;
1178
+ this.videoSrtpSession = null;
1179
+ this.videoRtcpSession = null;
1180
+ this.videoRtcpCname = null;
1181
+ this.videoOctetsSent = 0;
1182
+ this.videoSsrc = 0;
1183
+ this.videoAssembler = null;
1184
+ this.peerVideoUpgradePending = false;
1185
+ this.peerVideoActive = false;
1186
+ this.peerVideoJids.clear();
1187
+ this.mediaStartedAtMs = null;
1188
+ this.videoSendCount = 0;
1189
+ this.videoIdrSendCount = 0;
1190
+ this.videoDropCount = 0;
1191
+ this.audioSendCount = 0;
1192
+ this.audioDropCount = 0;
1193
+ this.audioRecvCount = 0;
1194
+ this.srtpErrorCount = 0;
1195
+ this.relayPacketCount = 0;
1196
+ this.stunResponseCount = 0;
1197
+ this.selfEchoCount = 0;
1198
+ this.lastRecvSeq = -1;
1199
+ this.recvSeqGaps = 0;
1200
+ this.actualPeerSsrc = null;
1201
+ this.ssrcResubscribed = false;
1202
+ this.recvRealCount = 0;
1203
+ this.recvDtxCount = 0;
1204
+ this.initialTransportSent = false;
1205
+ this.outgoingPreacceptSent = false;
1206
+ this.firstPacketSent = false;
1207
+ this.realAudioSendCount = 0;
1208
+ this.encodeBuffer = null;
1209
+ this.encodeBufferPos = 0;
1210
+ this.acceptedByJid = null;
1211
+ }
1212
+ get encodeFrameSamples() {
1213
+ return this.opusCodec?.getFrameSize() ?? 960;
1214
+ }
1215
+ get rtpTsDelta() {
1216
+ return this.encodeFrameSamples;
1217
+ }
1218
+ sendOpusFrame(opusFrame, isSilence) {
1219
+ if (!this.rtpSession || !this.srtpSession)
1220
+ return;
1221
+ try {
1222
+ let rtpPayload = opusFrame;
1223
+ const authPadding = SRTP_AUTH_TAG_LEN - SRTP_SEND_AUTH_TAG_LEN;
1224
+ if (authPadding > 0) {
1225
+ if (!this.authPaddingBuffer || this.authPaddingBuffer.length !== authPadding) {
1226
+ this.authPaddingBuffer = new Uint8Array(authPadding);
1227
+ }
1228
+ rtpPayload = concatBytes([rtpPayload, this.authPaddingBuffer]);
1229
+ }
1230
+ const marker = !this.firstPacketSent;
1231
+ const tsDelta = this.rtpTsDelta;
1232
+ const rtpPacket = this.rtpSession.createPacketWithDuration(rtpPayload, tsDelta, marker);
1233
+ if (this.debeEnabled) {
1234
+ rtpPacket.header.extension = true;
1235
+ rtpPacket.header.extensionProfile = 0xdebe;
1236
+ rtpPacket.header.extensionData = WaCallMediaSession.EMPTY_BYTES;
1237
+ }
1238
+ if (!this.firstPacketSent) {
1239
+ this.firstPacketSent = true;
1240
+ }
1241
+ const srtpData = this.srtpSession.protect(rtpPacket);
1242
+ this.sctpRelay.broadcast(toArrayBuffer(srtpData));
1243
+ this.audioSendCount++;
1244
+ this.audioOctetsSent = (this.audioOctetsSent + rtpPayload.length) >>> 0;
1245
+ if (this.audioSendCount === 1 || this.audioSendCount % 500 === 0) {
1246
+ this.logger.media('audio sent', {
1247
+ callId: this.info.callId,
1248
+ sendCount: this.audioSendCount,
1249
+ opusBytes: opusFrame.length,
1250
+ srtpBytes: srtpData.length,
1251
+ silence: isSilence,
1252
+ sctpBacklog: this.sctpRelay.getSendBacklog()
1253
+ });
1254
+ }
1255
+ }
1256
+ catch (err) {
1257
+ this.logger.error('error sending audio', {
1258
+ callId: this.info.callId,
1259
+ message: toError(err).message
1260
+ });
1261
+ }
1262
+ }
1263
+ ensureDeviceJid(jid) {
1264
+ if (/:\d+@/.test(jid))
1265
+ return jid;
1266
+ return jid.replace('@', ':0@');
1267
+ }
1268
+ initSrtpKeys() {
1269
+ const callKey = this.info.encryptionKey;
1270
+ if (!callKey) {
1271
+ this.logger.media('no call_key, srtp not initialized', { callId: this.info.callId });
1272
+ return;
1273
+ }
1274
+ const meLid = this.deps.authClient.getCurrentCredentials()?.meLid;
1275
+ const meId = this.deps.authClient.getCurrentCredentials()?.meJid;
1276
+ const ourCredJid = meLid || meId || '';
1277
+ const ourBase = toUserJid(ourCredJid);
1278
+ const participants = this.info.relayData?.participantJids || [];
1279
+ const ourDeviceJid = this.ensureDeviceJid(participants.find((jid) => {
1280
+ const jBase = toUserJid(jid);
1281
+ return jBase === ourBase && /:\d+@/.test(jid);
1282
+ }) || ourCredJid);
1283
+ let rawPeerJid = this.acceptedByJid || this.info.peerJid;
1284
+ if (!this.acceptedByJid) {
1285
+ const peerFromParticipants = participants.find((jid) => {
1286
+ const jBase = toUserJid(jid);
1287
+ return jBase !== ourBase;
1288
+ });
1289
+ if (peerFromParticipants)
1290
+ rawPeerJid = peerFromParticipants;
1291
+ }
1292
+ const peerDeviceJid = this.ensureDeviceJid(rawPeerJid);
1293
+ try {
1294
+ const sendKeying = derivePerJidSrtpKey(callKey, ourDeviceJid);
1295
+ const recvKeying = derivePerJidSrtpKey(callKey, peerDeviceJid);
1296
+ this.srtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1297
+ this.appDataSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1298
+ this.openAppDataStream(ourDeviceJid);
1299
+ this.peerAppDataSsrcs.clear();
1300
+ this.trackPeerAppDataSsrcs([peerDeviceJid, ...participants.filter((jid) => toUserJid(jid) !== ourBase)]);
1301
+ this.audioRtcpSession = new SrtcpSendContext(sendKeying);
1302
+ if (this.info.mediaType === CallMediaType.Video) {
1303
+ this.videoSrtpSession = new SrtpSession(sendKeying, recvKeying, SRTP_SEND_AUTH_TAG_LEN, SRTP_RECV_AUTH_TAG_LEN);
1304
+ this.videoRtcpSession = new SrtcpSendContext(sendKeying);
1305
+ }
1306
+ this.startRtcpSenderReports();
1307
+ this.logger.debug('srtp per-jid keys initialized', {
1308
+ callId: this.info.callId,
1309
+ sendJid: ourDeviceJid,
1310
+ recvJid: peerDeviceJid
1311
+ });
1312
+ }
1313
+ catch (err) {
1314
+ this.logger.debug('srtp key derivation failed', {
1315
+ callId: this.info.callId,
1316
+ message: toError(err).message
1317
+ });
1318
+ }
1319
+ }
1320
+ startRtcpSenderReports() {
1321
+ if (this.rtcpTimer)
1322
+ clearInterval(this.rtcpTimer);
1323
+ if (!this.audioRtcpCname)
1324
+ this.audioRtcpCname = generateWhatsappRtcpCname();
1325
+ if (!this.videoRtcpCname)
1326
+ this.videoRtcpCname = generateWhatsappRtcpCname();
1327
+ this.rtcpTimer = setInterval(() => {
1328
+ if (!this.sctpRelay.hasConnection())
1329
+ return;
1330
+ if (++this.qLog.n % 3 === 0)
1331
+ this.logVoipQuality();
1332
+ const nowMs = Date.now();
1333
+ try {
1334
+ if (this.audioRtcpSession && this.selfSsrc) {
1335
+ const stats = {
1336
+ packetsSent: this.audioSendCount,
1337
+ octetsSent: this.audioOctetsSent,
1338
+ rtpTimestamp: this.rtpSession?.timestamp ?? 0
1339
+ };
1340
+ const plain = buildSenderReportWithSdes(this.selfSsrc, stats, nowMs, this.audioRtcpCname);
1341
+ const protectedPacket = this.audioRtcpSession.protect(this.selfSsrc, plain);
1342
+ this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1343
+ }
1344
+ if (this.videoRtcpSession && this.videoSsrc && this.videoSendCount > 0) {
1345
+ const stats = {
1346
+ packetsSent: this.videoSendCount,
1347
+ octetsSent: this.videoOctetsSent,
1348
+ rtpTimestamp: this.videoRtpStream?.timestamp ?? 0
1349
+ };
1350
+ const plain = buildSenderReportWithSdes(this.videoSsrc, stats, nowMs, this.videoRtcpCname);
1351
+ const protectedPacket = this.videoRtcpSession.protect(this.videoSsrc, plain);
1352
+ this.sctpRelay.broadcast(toArrayBuffer(protectedPacket));
1353
+ }
1354
+ if (this.mediaStartedAtMs) {
1355
+ const wallElapsedMs = nowMs - this.mediaStartedAtMs;
1356
+ const audioElapsedMs = this.audioSendCount * 60;
1357
+ const videoElapsedMs = this.videoSendCount * (1000 / this.videoEngine.frameRate);
1358
+ this.logger.media('av sync check', {
1359
+ callId: this.info.callId,
1360
+ wallElapsedMs,
1361
+ audioElapsedMs,
1362
+ videoElapsedMs,
1363
+ audioMinusWallMs: audioElapsedMs - wallElapsedMs,
1364
+ videoMinusWallMs: Math.round(videoElapsedMs - wallElapsedMs)
1365
+ });
1366
+ }
1367
+ }
1368
+ catch (err) {
1369
+ this.logger.debug('rtcp sender report failed', {
1370
+ callId: this.info.callId,
1371
+ message: toError(err).message
1372
+ });
1373
+ }
1374
+ }, 1500);
1375
+ }
1376
+ resetEncodeState() {
1377
+ this.encodeBuffer = null;
1378
+ this.encodeBufferPos = 0;
1379
+ this.realAudioSendCount = 0;
1380
+ }
1381
+ onRelayConnected() {
1382
+ if (this.info.stateData.state === CallState.Connecting) {
1383
+ try {
1384
+ this.info.applyTransition({ type: 'media_connected' });
1385
+ this.delegate.emitState(this.info);
1386
+ this.logger.media('relay connected', {
1387
+ callId: this.info.callId, acceptedByJid: this.acceptedByJid ?? null
1388
+ });
1389
+ if (!this.acceptedByJid) {
1390
+ this.logger.media('relay connected before accept, deferring media start', {
1391
+ callId: this.info.callId
1392
+ });
1393
+ return;
1394
+ }
1395
+ const MEDIA_START_DELAY_MS = 3000;
1396
+ setTimeout(() => {
1397
+ this.logger.warn('[DIAG] delayed startMediaFlow firing (path A)', {
1398
+ callId: this.info.callId, state: this.info.stateData.state
1399
+ });
1400
+ if (this.info.stateData.state === CallState.Ended) {
1401
+ return;
1402
+ }
1403
+ this.startMediaFlow();
1404
+ }, MEDIA_START_DELAY_MS);
1405
+ }
1406
+ catch (err) {
1407
+ this.logger.trace('call transition skipped', { message: toError(err).message });
1408
+ }
1409
+ }
1410
+ }
1411
+ onRelayData(data) {
1412
+ this.relayPacketCount++;
1413
+ if (isStunPacket(data)) {
1414
+ this.stunResponseCount++;
1415
+ return;
1416
+ }
1417
+ if (!isRtpPacket(data))
1418
+ return;
1419
+ const pt = data[1] & 0x7f;
1420
+ if (this.peerAppDataSsrcs.size > 0 && data.length >= 12) {
1421
+ const appDataSsrc = readUInt32BE(data, 8);
1422
+ if (this.peerAppDataSsrcs.has(appDataSsrc)) {
1423
+ this.onAppDataPacket(data, pt, appDataSsrc);
1424
+ return;
1425
+ }
1426
+ }
1427
+ if (pt === PayloadType.H264) {
1428
+ this.onRelayVideoData(data);
1429
+ return;
1430
+ }
1431
+ if (!this.srtpSession || !this.opusCodec)
1432
+ return;
1433
+ if (pt !== 120)
1434
+ return;
1435
+ if (data.length >= 12) {
1436
+ const ssrc = ((data[8] << 24) | (data[9] << 16) | (data[10] << 8) | data[11]) >>> 0;
1437
+ if (ssrc === this.selfSsrc) {
1438
+ this.selfEchoCount++;
1439
+ return;
1440
+ }
1441
+ if (!this.ssrcResubscribed && this.actualPeerSsrc === null) {
1442
+ this.actualPeerSsrc = ssrc;
1443
+ const knownSsrc = this.peerSsrcs.includes(ssrc);
1444
+ if (!knownSsrc) {
1445
+ this.peerSsrcs = [ssrc];
1446
+ this.ssrcResubscribed = true;
1447
+ this.opusCodec.resetSequence();
1448
+ this.lastRecvSeq = -1;
1449
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1450
+ this.sctpRelay.resendSubscriptions();
1451
+ }
1452
+ }
1453
+ }
1454
+ try {
1455
+ const rtpPacket = this.srtpSession.unprotect(data);
1456
+ const opusPayload = rtpPacket.payload;
1457
+ this.audioRecvCount++;
1458
+ if (opusPayload.length === 0)
1459
+ return;
1460
+ const seq = rtpPacket.header.sequenceNumber;
1461
+ if (this.lastRecvSeq >= 0) {
1462
+ const gap = ((seq - this.lastRecvSeq + 65536) % 65536) - 1;
1463
+ if (gap > 0 && gap < 0x8000)
1464
+ this.recvSeqGaps += gap;
1465
+ }
1466
+ this.lastRecvSeq = seq;
1467
+ const isDtx = opusPayload.length <= 2;
1468
+ if (isDtx)
1469
+ this.recvDtxCount++;
1470
+ else
1471
+ this.recvRealCount++;
1472
+ this.opusCodec.decodeSequenced(seq, opusPayload, this.onDecodedAudio);
1473
+ if (this.audioRecvCount % 100 === 0) {
1474
+ const w = (this.lossWindow ?? (this.lossWindow = { gaps: 0, pkts: 0 }));
1475
+ const gaps = this.recvSeqGaps - w.gaps;
1476
+ const pkts = this.audioRecvCount - w.pkts;
1477
+ w.gaps = this.recvSeqGaps;
1478
+ w.pkts = this.audioRecvCount;
1479
+ const lossPct = pkts + gaps > 0 ? Math.min(100, Math.round((100 * gaps) / (pkts + gaps))) : 0;
1480
+ this.opusCodec.setExpectedPacketLossPercent(lossPct);
1481
+ }
1482
+ if (this.audioRecvCount % 1500 === 0) {
1483
+ const stats = this.opusCodec.getStats();
1484
+ this.logger.trace('audio recv stats', {
1485
+ callId: this.info.callId,
1486
+ recvCount: this.audioRecvCount,
1487
+ real: this.recvRealCount,
1488
+ dtx: this.recvDtxCount,
1489
+ decodeOk: stats.success,
1490
+ decodeErr: stats.errors,
1491
+ plc: stats.plc,
1492
+ fec: stats.fec,
1493
+ late: stats.late
1494
+ });
1495
+ }
1496
+ }
1497
+ catch (err) {
1498
+ this.srtpErrorCount++;
1499
+ if (this.srtpErrorCount <= 5) {
1500
+ const ssrc = data.length >= 12 ? readUInt32BE(data, 8) : 0;
1501
+ this.logger.debug('srtp recv error', {
1502
+ callId: this.info.callId,
1503
+ errorCount: this.srtpErrorCount,
1504
+ message: toError(err).message,
1505
+ ssrc: `0x${ssrc.toString(16)}`
1506
+ });
1507
+ }
1508
+ }
1509
+ }
1510
+ logVoipQuality() {
1511
+ try {
1512
+ const q = this.qLog;
1513
+ const pace = this.audioEngine.takePacingStats();
1514
+ const bl = this.sctpRelay.getSendBacklog?.() ?? {};
1515
+ const sent = this.audioSendCount - q.sent;
1516
+ const octets = ((this.audioOctetsSent - q.octets) >>> 0);
1517
+ const rs = this.opusCodec?.getStats() ?? { late: 0, plc: 0, fec: 0, errors: 0 };
1518
+ const line = {
1519
+ callId: this.info.callId,
1520
+ tSec: this.mediaStartedAtMs ? Math.round((Date.now() - this.mediaStartedAtMs) / 1000) : 0,
1521
+ txFrames: sent,
1522
+ txAvgB: sent > 0 ? Math.round(octets / sent) : 0,
1523
+ txTinyPct: sent > 0 ? Math.round((100 * (this.qLog.tiny)) / sent) : 0,
1524
+ tickLate90: pace.late90,
1525
+ tickLate200: pace.late200,
1526
+ tickBurst: pace.burst20,
1527
+ tickMaxGapMs: pace.maxGap,
1528
+ loopP50ms: pace.loopP50,
1529
+ loopP99ms: pace.loopP99,
1530
+ loopMaxMs: pace.loopMax,
1531
+ sctpInFlight: bl.inFlight ?? 0,
1532
+ sctpQueuedAudio: bl.queuedAudio ?? 0,
1533
+ sctpRetx: (bl.retransmits ?? 0) - q.retx,
1534
+ aLagMs: this.mediaStartedAtMs ? this.audioSendCount * 60 - (Date.now() - this.mediaStartedAtMs) : 0,
1535
+ vLagMs: this.mediaStartedAtMs && this.videoSendCount > 0 && this.videoEngine?.frameRate
1536
+ ? Math.round(this.videoSendCount * (1000 / this.videoEngine.frameRate) - (Date.now() - this.mediaStartedAtMs))
1537
+ : 0,
1538
+ vRestarts: this.videoEngine?._restartCount ?? 0,
1539
+ relayRx: this.relayPacketCount,
1540
+ srtpErr: this.srtpErrorCount,
1541
+ stun: this.sctpRelay.getRxStunStats?.() ?? {},
1542
+ rxPkts: this.audioRecvCount - q.rx,
1543
+ rxLate: rs.late - q.late,
1544
+ rxPlc: rs.plc - q.plc,
1545
+ rxFec: rs.fec - q.fec,
1546
+ rxDecErr: rs.errors - q.errors
1547
+ };
1548
+ this.logger.warn('[VOIPQ] ' + JSON.stringify(line));
1549
+ q.sent = this.audioSendCount;
1550
+ q.octets = this.audioOctetsSent;
1551
+ q.tiny = 0;
1552
+ q.retx = bl.retransmits ?? 0;
1553
+ q.rx = this.audioRecvCount;
1554
+ q.late = rs.late;
1555
+ q.plc = rs.plc;
1556
+ q.fec = rs.fec;
1557
+ q.errors = rs.errors;
1558
+ }
1559
+ catch (err) {
1560
+ this.logger.trace('voip quality log failed', { message: toError(err).message });
1561
+ }
1562
+ }
1563
+ onRelayVideoData(data) {
1564
+ if (!this.videoSrtpSession || !this.videoAssembler)
1565
+ return;
1566
+ try {
1567
+ const rtpPacket = this.videoSrtpSession.unprotect(data);
1568
+ const [accessUnit, complete] = this.videoAssembler.push(rtpPacket.header.sequenceNumber, rtpPacket.header.marker, rtpPacket.payload);
1569
+ if (complete && accessUnit) {
1570
+ this.delegate.emitInboundVideo?.(this.info, accessUnit);
1571
+ }
1572
+ }
1573
+ catch (err) {
1574
+ this.srtpErrorCount++;
1575
+ if (this.srtpErrorCount <= 5) {
1576
+ this.logger.debug('video srtp recv error', {
1577
+ callId: this.info.callId,
1578
+ message: toError(err).message
1579
+ });
1580
+ }
1581
+ }
1582
+ }
1583
+ async connectRelays(endpoints) {
1584
+ this.logger.debug('connecting relays', {
1585
+ callId: this.info.callId,
1586
+ endpointCount: endpoints.length
1587
+ });
1588
+ const seen = new Set();
1589
+ const uniqueEndpoints = [];
1590
+ for (const ep of endpoints) {
1591
+ if ((ep.protocol ?? 0) !== 0)
1592
+ continue;
1593
+ const key = `${ep.ip}:${ep.port}`;
1594
+ if (!seen.has(key)) {
1595
+ seen.add(key);
1596
+ uniqueEndpoints.push(ep);
1597
+ }
1598
+ }
1599
+ const usable = uniqueEndpoints.filter((ep) => ep.key && ep.rawToken);
1600
+ const inbound = this.info.direction === CallDirection.Incoming;
1601
+ let chosen = null;
1602
+ if (inbound) {
1603
+ chosen = usable.find((ep) => ep.isFna) ?? null;
1604
+ }
1605
+ if (!chosen) {
1606
+ chosen =
1607
+ usable.find((ep) => !ep.isFna && parseInt(ep.authTokenId, 10) !== 0) ??
1608
+ usable.find((ep) => !ep.isFna) ??
1609
+ usable[0] ??
1610
+ null;
1611
+ }
1612
+ const WA_RELAY_PORT = 3478;
1613
+ const relays = chosen
1614
+ ? [
1615
+ {
1616
+ ip: chosen.ip,
1617
+ port: WA_RELAY_PORT,
1618
+ token: chosen.token,
1619
+ authToken: chosen.authToken,
1620
+ rawAuthToken: chosen.rawAuthToken,
1621
+ rawToken: chosen.rawToken,
1622
+ key: chosen.key,
1623
+ relayId: chosen.relayId,
1624
+ name: chosen.relayName || `${chosen.ip}:${WA_RELAY_PORT}`,
1625
+ authTokenId: chosen.authTokenId,
1626
+ isFna: chosen.isFna
1627
+ }
1628
+ ]
1629
+ : [];
1630
+ if (relays.length === 0) {
1631
+ this.logger.error('no relay configs', { callId: this.info.callId });
1632
+ return;
1633
+ }
1634
+ this.logger.media('relay selected', {
1635
+ callId: this.info.callId,
1636
+ inbound,
1637
+ candidateCount: usable.length,
1638
+ chosen: relays[0].name,
1639
+ isFna: relays[0].isFna
1640
+ });
1641
+ if (this.selfSsrcJid) {
1642
+ this.sctpRelay.setStreamSsrcs(deriveWasmRelayStreamSsrcs(this.info.callId, this.selfSsrcJid));
1643
+ }
1644
+ this.sctpRelay.setSsrc(this.selfSsrc);
1645
+ if (this.info.mediaType === CallMediaType.Video) {
1646
+ this.sctpRelay.setVideoSsrc(this.videoSsrc);
1647
+ }
1648
+ this.sctpRelay.setSubscriptionSsrc(this.peerSsrcs[0] ?? 0);
1649
+ try {
1650
+ await this.sctpRelay.configureRelays(relays);
1651
+ this.logger.debug('sctp relays configured', {
1652
+ callId: this.info.callId,
1653
+ connected: this.sctpRelay.getConnectedCount()
1654
+ });
1655
+ }
1656
+ catch (err) {
1657
+ this.logger.error('sctp relay error', {
1658
+ callId: this.info.callId,
1659
+ message: toError(err).message
1660
+ });
1661
+ }
1662
+ }
1663
+ startMediaFlow() {
1664
+ this.mediaStartedAtMs = Date.now();
1665
+ this.mediaFlowStarted = true;
1666
+ this.logger.warn('[DIAG] startMediaFlow entered', { callId: this.info.callId });
1667
+ this.resetEncodeState();
1668
+ this.audioEngine.startPlayback();
1669
+ this.audioEngine.startCapture();
1670
+ this.videoEngine.start();
1671
+ }
1672
+ }
1673
+ WaCallMediaSession.EMPTY_BYTES = EMPTY_BYTES;
1674
+ //# sourceMappingURL=WaCallMediaSession.js.map