werift 0.25.2 → 0.26.0

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 (314) hide show
  1. package/lib/common/src/asn1.d.ts +42 -0
  2. package/lib/common/src/asn1.js +163 -0
  3. package/lib/common/src/asn1.js.map +1 -0
  4. package/lib/common/src/binaryData.js.map +1 -1
  5. package/lib/common/src/index.d.ts +6 -5
  6. package/lib/common/src/index.js +6 -5
  7. package/lib/common/src/index.js.map +1 -1
  8. package/lib/common/src/log.d.ts +12 -1
  9. package/lib/common/src/log.js +137 -5
  10. package/lib/common/src/log.js.map +1 -1
  11. package/lib/common/src/network.js.map +1 -1
  12. package/lib/common/src/queue.d.ts +41 -0
  13. package/lib/common/src/queue.js +146 -0
  14. package/lib/common/src/queue.js.map +1 -0
  15. package/lib/common/src/transport.d.ts +15 -2
  16. package/lib/common/src/transport.js +98 -14
  17. package/lib/common/src/transport.js.map +1 -1
  18. package/lib/dtls/src/cipher/create.js.map +1 -1
  19. package/lib/dtls/src/cipher/ec.js +8 -8
  20. package/lib/dtls/src/cipher/ec.js.map +1 -1
  21. package/lib/dtls/src/cipher/namedCurve.js +6 -7
  22. package/lib/dtls/src/cipher/namedCurve.js.map +1 -1
  23. package/lib/dtls/src/cipher/prf.d.ts +2 -2
  24. package/lib/dtls/src/cipher/prf.js +29 -8
  25. package/lib/dtls/src/cipher/prf.js.map +1 -1
  26. package/lib/dtls/src/cipher/suites/aead.d.ts +1 -1
  27. package/lib/dtls/src/context/certificate.d.ts +32 -0
  28. package/lib/dtls/src/context/certificate.js +54 -0
  29. package/lib/dtls/src/context/certificate.js.map +1 -0
  30. package/lib/dtls/src/context/cipher.d.ts +12 -6
  31. package/lib/dtls/src/context/cipher.js +52 -103
  32. package/lib/dtls/src/context/cipher.js.map +1 -1
  33. package/lib/dtls/src/context/transport.d.ts +4 -0
  34. package/lib/dtls/src/context/transport.js +14 -0
  35. package/lib/dtls/src/context/transport.js.map +1 -1
  36. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  37. package/lib/dtls/src/flight/flight.js +8 -1
  38. package/lib/dtls/src/flight/flight.js.map +1 -1
  39. package/lib/dtls/src/flight/server/flight2.js.map +1 -1
  40. package/lib/dtls/src/flight/server/flight4.d.ts +2 -1
  41. package/lib/dtls/src/flight/server/flight4.js +8 -2
  42. package/lib/dtls/src/flight/server/flight4.js.map +1 -1
  43. package/lib/dtls/src/handshake/extensions/signature.d.ts +1 -1
  44. package/lib/dtls/src/handshake/extensions/signature.js.map +1 -1
  45. package/lib/dtls/src/handshake/message/alert.js +1 -1
  46. package/lib/dtls/src/handshake/message/alert.js.map +1 -1
  47. package/lib/dtls/src/handshake/message/certificate.js +1 -1
  48. package/lib/dtls/src/handshake/message/certificate.js.map +1 -1
  49. package/lib/dtls/src/handshake/message/changeCipherSpec.js +2 -3
  50. package/lib/dtls/src/handshake/message/changeCipherSpec.js.map +1 -1
  51. package/lib/dtls/src/handshake/message/client/certificateVerify.d.ts +1 -1
  52. package/lib/dtls/src/handshake/message/client/certificateVerify.js +1 -1
  53. package/lib/dtls/src/handshake/message/client/certificateVerify.js.map +1 -1
  54. package/lib/dtls/src/handshake/message/client/hello.js +1 -1
  55. package/lib/dtls/src/handshake/message/client/hello.js.map +1 -1
  56. package/lib/dtls/src/handshake/message/client/keyExchange.js +1 -1
  57. package/lib/dtls/src/handshake/message/client/keyExchange.js.map +1 -1
  58. package/lib/dtls/src/handshake/message/server/certificateRequest.d.ts +1 -1
  59. package/lib/dtls/src/handshake/message/server/certificateRequest.js +1 -1
  60. package/lib/dtls/src/handshake/message/server/certificateRequest.js.map +1 -1
  61. package/lib/dtls/src/handshake/message/server/hello.d.ts +1 -1
  62. package/lib/dtls/src/handshake/message/server/hello.js +2 -2
  63. package/lib/dtls/src/handshake/message/server/hello.js.map +1 -1
  64. package/lib/dtls/src/handshake/message/server/helloDone.js +1 -1
  65. package/lib/dtls/src/handshake/message/server/helloDone.js.map +1 -1
  66. package/lib/dtls/src/handshake/message/server/helloVerifyRequest.js +1 -1
  67. package/lib/dtls/src/handshake/message/server/helloVerifyRequest.js.map +1 -1
  68. package/lib/dtls/src/handshake/message/server/keyExchange.d.ts +1 -1
  69. package/lib/dtls/src/handshake/message/server/keyExchange.js +1 -1
  70. package/lib/dtls/src/handshake/message/server/keyExchange.js.map +1 -1
  71. package/lib/dtls/src/handshake/random.d.ts +2 -2
  72. package/lib/dtls/src/handshake/random.js +2 -2
  73. package/lib/dtls/src/handshake/random.js.map +1 -1
  74. package/lib/dtls/src/imports/common.d.ts +1 -0
  75. package/lib/dtls/src/imports/common.js +1 -0
  76. package/lib/dtls/src/imports/common.js.map +1 -1
  77. package/lib/dtls/src/index.d.ts +2 -2
  78. package/lib/dtls/src/index.js +2 -2
  79. package/lib/dtls/src/index.js.map +1 -1
  80. package/lib/dtls/src/record/message/fragment.d.ts +1 -1
  81. package/lib/dtls/src/record/message/fragment.js +3 -3
  82. package/lib/dtls/src/record/message/fragment.js.map +1 -1
  83. package/lib/dtls/src/record/message/header.js +2 -2
  84. package/lib/dtls/src/record/message/header.js.map +1 -1
  85. package/lib/dtls/src/server.js +1 -1
  86. package/lib/dtls/src/server.js.map +1 -1
  87. package/lib/dtls/src/socket.d.ts +2 -2
  88. package/lib/dtls/src/socket.js +2 -2
  89. package/lib/dtls/src/socket.js.map +1 -1
  90. package/lib/ice/src/exceptions.d.ts +30 -0
  91. package/lib/ice/src/exceptions.js +43 -1
  92. package/lib/ice/src/exceptions.js.map +1 -1
  93. package/lib/ice/src/helper.d.ts +1 -1
  94. package/lib/ice/src/ice.d.ts +142 -0
  95. package/lib/ice/src/ice.js +809 -53
  96. package/lib/ice/src/ice.js.map +1 -1
  97. package/lib/ice/src/iceBase.d.ts +49 -0
  98. package/lib/ice/src/iceBase.js.map +1 -1
  99. package/lib/ice/src/index.d.ts +5 -5
  100. package/lib/ice/src/index.js +5 -5
  101. package/lib/ice/src/index.js.map +1 -1
  102. package/lib/ice/src/internal/resolveHostAddresses.d.ts +26 -0
  103. package/lib/ice/src/internal/resolveHostAddresses.js +45 -0
  104. package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -0
  105. package/lib/ice/src/stun/protocol.d.ts +3 -1
  106. package/lib/ice/src/stun/protocol.js +16 -0
  107. package/lib/ice/src/stun/protocol.js.map +1 -1
  108. package/lib/ice/src/stun/tcpProtocol.d.ts +2 -0
  109. package/lib/ice/src/stun/tcpProtocol.js +16 -1
  110. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  111. package/lib/ice/src/stun/transaction.d.ts +5 -0
  112. package/lib/ice/src/stun/transaction.js +7 -1
  113. package/lib/ice/src/stun/transaction.js.map +1 -1
  114. package/lib/ice/src/turn/protocol.d.ts +73 -4
  115. package/lib/ice/src/turn/protocol.js +241 -12
  116. package/lib/ice/src/turn/protocol.js.map +1 -1
  117. package/lib/ice/src/utils.js.map +1 -1
  118. package/lib/ice-server/src/stun/message.d.ts +5 -1
  119. package/lib/ice-server/src/stun/message.js +33 -2
  120. package/lib/ice-server/src/stun/message.js.map +1 -1
  121. package/lib/ice-server/src/turn/auth.d.ts +1 -1
  122. package/lib/index.mjs +16273 -10807
  123. package/lib/nonstandard/index.mjs +8644 -7911
  124. package/lib/polyfill/dom.mjs +22435 -16965
  125. package/lib/polyfill/index.mjs +22435 -16965
  126. package/lib/rtp/src/codec/h264.d.ts +1 -1
  127. package/lib/rtp/src/codec/h264.js.map +1 -1
  128. package/lib/rtp/src/extra/container/webm/container.d.ts +1 -1
  129. package/lib/rtp/src/extra/container/webm/ebml/ebml.d.ts +6 -0
  130. package/lib/rtp/src/extra/container/webm/ebml/ebml.js +20 -1
  131. package/lib/rtp/src/extra/container/webm/ebml/ebml.js.map +1 -1
  132. package/lib/rtp/src/extra/processor/depacketizer.d.ts +1 -1
  133. package/lib/rtp/src/extra/processor/depacketizer.js +1 -1
  134. package/lib/rtp/src/extra/processor/depacketizer.js.map +1 -1
  135. package/lib/rtp/src/extra/processor/depacketizerCallback.d.ts +1 -11
  136. package/lib/rtp/src/extra/processor/depacketizerTransformer.d.ts +1 -1
  137. package/lib/rtp/src/extra/processor/dtxCallback.d.ts +1 -11
  138. package/lib/rtp/src/extra/processor/interface.d.ts +16 -11
  139. package/lib/rtp/src/extra/processor/interface.js.map +1 -1
  140. package/lib/rtp/src/extra/processor/jitterBufferCallback.d.ts +1 -11
  141. package/lib/rtp/src/extra/processor/jitterBufferTransformer.d.ts +1 -1
  142. package/lib/rtp/src/extra/processor/mp4.js +1 -1
  143. package/lib/rtp/src/extra/processor/mp4.js.map +1 -1
  144. package/lib/rtp/src/extra/processor/nack.d.ts +1 -1
  145. package/lib/rtp/src/extra/processor/nack.js +1 -1
  146. package/lib/rtp/src/extra/processor/nack.js.map +1 -1
  147. package/lib/rtp/src/extra/processor/nackHandlerCallback.d.ts +1 -11
  148. package/lib/rtp/src/extra/processor/ntpTime.js.map +1 -1
  149. package/lib/rtp/src/extra/processor/ntpTimeCallback.d.ts +1 -11
  150. package/lib/rtp/src/extra/processor/rtcpCallback.d.ts +1 -1
  151. package/lib/rtp/src/extra/processor/rtcpCallback.js.map +1 -1
  152. package/lib/rtp/src/extra/processor/rtpCallback.d.ts +1 -1
  153. package/lib/rtp/src/extra/processor/rtpCallback.js +1 -1
  154. package/lib/rtp/src/extra/processor/rtpCallback.js.map +1 -1
  155. package/lib/rtp/src/extra/processor/rtpStream.d.ts +2 -2
  156. package/lib/rtp/src/extra/processor/rtpStream.js.map +1 -1
  157. package/lib/rtp/src/extra/processor/rtpTime.js.map +1 -1
  158. package/lib/rtp/src/extra/processor/rtpTimeCallback.d.ts +1 -11
  159. package/lib/rtp/src/extra/processor/webm.d.ts +27 -0
  160. package/lib/rtp/src/extra/processor/webm.js +43 -16
  161. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  162. package/lib/rtp/src/extra/processor/webmCallback.js +6 -1
  163. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  164. package/lib/rtp/src/extra/processor/webmStream.js.map +1 -1
  165. package/lib/rtp/src/helper.d.ts +2 -2
  166. package/lib/rtp/src/helper.js +2 -6
  167. package/lib/rtp/src/helper.js.map +1 -1
  168. package/lib/rtp/src/index.d.ts +3 -2
  169. package/lib/rtp/src/index.js +3 -2
  170. package/lib/rtp/src/index.js.map +1 -1
  171. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js +2 -1
  172. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js.map +1 -1
  173. package/lib/rtp/src/rtcp/rtcp.js +2 -1
  174. package/lib/rtp/src/rtcp/rtcp.js.map +1 -1
  175. package/lib/rtp/src/rtcp/sr.d.ts +4 -3
  176. package/lib/rtp/src/rtcp/sr.js +3 -2
  177. package/lib/rtp/src/rtcp/sr.js.map +1 -1
  178. package/lib/rtp/src/srtp/cipher/ctr.d.ts +2 -2
  179. package/lib/rtp/src/srtp/cipher/ctr.js +1 -1
  180. package/lib/rtp/src/srtp/cipher/ctr.js.map +1 -1
  181. package/lib/rtp/src/srtp/cipher/gcm.d.ts +1 -1
  182. package/lib/rtp/src/srtp/cipher/gcm.js +1 -1
  183. package/lib/rtp/src/srtp/cipher/gcm.js.map +1 -1
  184. package/lib/rtp/src/srtp/context/context.d.ts +29 -1
  185. package/lib/rtp/src/srtp/context/context.js +78 -24
  186. package/lib/rtp/src/srtp/context/context.js.map +1 -1
  187. package/lib/rtp/src/srtp/context/srtp.js +23 -15
  188. package/lib/rtp/src/srtp/context/srtp.js.map +1 -1
  189. package/lib/sctp/src/index.d.ts +4 -3
  190. package/lib/sctp/src/index.js +10 -8
  191. package/lib/sctp/src/index.js.map +1 -1
  192. package/lib/sctp/src/sctp.d.ts +11 -2
  193. package/lib/sctp/src/sctp.js +47 -28
  194. package/lib/sctp/src/sctp.js.map +1 -1
  195. package/lib/webrtc/src/api/peerConfig.d.ts +264 -0
  196. package/lib/webrtc/src/api/peerConfig.js +250 -0
  197. package/lib/webrtc/src/api/peerConfig.js.map +1 -0
  198. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +36 -0
  199. package/lib/webrtc/src/api/peerConnectionEvents.js +44 -0
  200. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -0
  201. package/lib/webrtc/src/dataChannel.d.ts +1 -1
  202. package/lib/webrtc/src/dataChannel.js +1 -1
  203. package/lib/webrtc/src/dataChannel.js.map +1 -1
  204. package/lib/webrtc/src/index.d.ts +2 -2
  205. package/lib/webrtc/src/index.js +2 -2
  206. package/lib/webrtc/src/index.js.map +1 -1
  207. package/lib/webrtc/src/media/index.d.ts +1 -1
  208. package/lib/webrtc/src/media/index.js +1 -1
  209. package/lib/webrtc/src/media/index.js.map +1 -1
  210. package/lib/webrtc/src/media/receiver/nack.js +3 -4
  211. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  212. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  213. package/lib/webrtc/src/media/router.d.ts +116 -5
  214. package/lib/webrtc/src/media/router.js +281 -29
  215. package/lib/webrtc/src/media/router.js.map +1 -1
  216. package/lib/webrtc/src/media/rtpReceiver.d.ts +107 -12
  217. package/lib/webrtc/src/media/rtpReceiver.js +255 -28
  218. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  219. package/lib/webrtc/src/media/rtpSender.d.ts +56 -3
  220. package/lib/webrtc/src/media/rtpSender.js +180 -21
  221. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  222. package/lib/webrtc/src/media/rtpTransceiver.d.ts +94 -1
  223. package/lib/webrtc/src/media/rtpTransceiver.js +111 -2
  224. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  225. package/lib/webrtc/src/media/sender/senderBWE.d.ts +2 -1
  226. package/lib/webrtc/src/media/sender/senderBWE.js +22 -10
  227. package/lib/webrtc/src/media/sender/senderBWE.js.map +1 -1
  228. package/lib/webrtc/src/media/track.d.ts +1 -1
  229. package/lib/webrtc/src/media/track.js +1 -1
  230. package/lib/webrtc/src/media/track.js.map +1 -1
  231. package/lib/webrtc/src/negotiation/bundleTopology.d.ts +107 -0
  232. package/lib/webrtc/src/negotiation/bundleTopology.js +380 -0
  233. package/lib/webrtc/src/negotiation/bundleTopology.js.map +1 -0
  234. package/lib/webrtc/src/negotiation/descriptionValidation.d.ts +51 -0
  235. package/lib/webrtc/src/negotiation/descriptionValidation.js +261 -0
  236. package/lib/webrtc/src/negotiation/descriptionValidation.js.map +1 -0
  237. package/lib/webrtc/src/negotiation/iceRestartRequest.d.ts +21 -0
  238. package/lib/webrtc/src/negotiation/iceRestartRequest.js +61 -0
  239. package/lib/webrtc/src/negotiation/iceRestartRequest.js.map +1 -0
  240. package/lib/webrtc/src/negotiation/internalState.d.ts +34 -0
  241. package/lib/webrtc/src/negotiation/internalState.js +21 -0
  242. package/lib/webrtc/src/negotiation/internalState.js.map +1 -0
  243. package/lib/webrtc/src/negotiation/negotiationNeeded.d.ts +44 -0
  244. package/lib/webrtc/src/negotiation/negotiationNeeded.js +118 -0
  245. package/lib/webrtc/src/negotiation/negotiationNeeded.js.map +1 -0
  246. package/lib/webrtc/src/negotiation/remoteCandidates.d.ts +86 -0
  247. package/lib/webrtc/src/negotiation/remoteCandidates.js +344 -0
  248. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -0
  249. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +71 -0
  250. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +398 -0
  251. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -0
  252. package/lib/webrtc/src/negotiation/transportActivation.d.ts +59 -0
  253. package/lib/webrtc/src/negotiation/transportActivation.js +345 -0
  254. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -0
  255. package/lib/webrtc/src/negotiationTransaction.d.ts +233 -0
  256. package/lib/webrtc/src/negotiationTransaction.js +591 -0
  257. package/lib/webrtc/src/negotiationTransaction.js.map +1 -0
  258. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  259. package/lib/webrtc/src/nonstandard/index.d.ts +1 -1
  260. package/lib/webrtc/src/nonstandard/index.js +1 -1
  261. package/lib/webrtc/src/nonstandard/index.js.map +1 -1
  262. package/lib/webrtc/src/nonstandard/navigator.js.map +1 -1
  263. package/lib/webrtc/src/nonstandard/recorder/writer/index.d.ts +1 -1
  264. package/lib/webrtc/src/nonstandard/recorder/writer/index.js.map +1 -1
  265. package/lib/webrtc/src/nonstandard/recorder/writer/webm.d.ts +2 -2
  266. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +2 -2
  267. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  268. package/lib/webrtc/src/nonstandard/userMedia/packetizer.d.ts +2 -2
  269. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js.map +1 -1
  270. package/lib/webrtc/src/nonstandard/userMedia.d.ts +2 -2
  271. package/lib/webrtc/src/nonstandard/userMedia.js +2 -2
  272. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  273. package/lib/webrtc/src/peerConnection.d.ts +132 -237
  274. package/lib/webrtc/src/peerConnection.js +971 -908
  275. package/lib/webrtc/src/peerConnection.js.map +1 -1
  276. package/lib/webrtc/src/polyfill/api.d.ts +5 -5
  277. package/lib/webrtc/src/polyfill/api.js.map +1 -1
  278. package/lib/webrtc/src/polyfill/index.js.map +1 -1
  279. package/lib/webrtc/src/polyfill/install.js +1 -1
  280. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  281. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  282. package/lib/webrtc/src/polyfill/registers/mp4Webm.js.map +1 -1
  283. package/lib/webrtc/src/polyfill/registers/rtpRtcp.js.map +1 -1
  284. package/lib/webrtc/src/polyfill/selectSettings.js.map +1 -1
  285. package/lib/webrtc/src/polyfill/sourceIo.js.map +1 -1
  286. package/lib/webrtc/src/sctpManager.d.ts +66 -2
  287. package/lib/webrtc/src/sctpManager.js +122 -5
  288. package/lib/webrtc/src/sctpManager.js.map +1 -1
  289. package/lib/webrtc/src/sdp.js.map +1 -1
  290. package/lib/webrtc/src/sdpManager.d.ts +55 -11
  291. package/lib/webrtc/src/sdpManager.js +364 -87
  292. package/lib/webrtc/src/sdpManager.js.map +1 -1
  293. package/lib/webrtc/src/secureTransportManager.d.ts +38 -25
  294. package/lib/webrtc/src/secureTransportManager.js +130 -34
  295. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  296. package/lib/webrtc/src/transceiverManager.d.ts +62 -18
  297. package/lib/webrtc/src/transceiverManager.js +264 -104
  298. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  299. package/lib/webrtc/src/transport/dtls.d.ts +11 -2
  300. package/lib/webrtc/src/transport/dtls.js +37 -13
  301. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  302. package/lib/webrtc/src/transport/ice.d.ts +254 -7
  303. package/lib/webrtc/src/transport/ice.js +608 -52
  304. package/lib/webrtc/src/transport/ice.js.map +1 -1
  305. package/lib/webrtc/src/transport/iceCandidateAttribute.d.ts +98 -0
  306. package/lib/webrtc/src/transport/iceCandidateAttribute.js +129 -0
  307. package/lib/webrtc/src/transport/iceCandidateAttribute.js.map +1 -0
  308. package/lib/webrtc/src/transport/sctp.d.ts +4 -1
  309. package/lib/webrtc/src/transport/sctp.js +83 -17
  310. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  311. package/lib/webrtc/src/utils.d.ts +3 -3
  312. package/lib/webrtc/src/utils.js +1 -1
  313. package/lib/webrtc/src/utils.js.map +1 -1
  314. package/package.json +13 -14
@@ -1,20 +1,32 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RTCTrackEvent = exports.defaultPeerConfig = exports.findCodecByMimeType = exports.RTCPeerConnection = void 0;
3
+ exports.RTCPeerConnection = exports.RTCTrackEvent = exports.findCodecByMimeType = exports.defaultPeerConfig = void 0;
4
4
  const crypto_1 = require("crypto");
5
- const src_1 = require("../../sctp/src");
5
+ const peerConfig_1 = require("./api/peerConfig");
6
+ const peerConnectionEvents_1 = require("./api/peerConnectionEvents");
6
7
  const errors_1 = require("./errors");
7
8
  const helper_1 = require("./helper");
8
9
  const common_1 = require("./imports/common");
9
10
  const media_1 = require("./media");
10
- const codecCompatibility_1 = require("./media/codecCompatibility");
11
11
  const stats_1 = require("./media/stats");
12
+ const bundleTopology_1 = require("./negotiation/bundleTopology");
13
+ const descriptionValidation_1 = require("./negotiation/descriptionValidation");
14
+ const iceRestartRequest_1 = require("./negotiation/iceRestartRequest");
15
+ const negotiationNeeded_1 = require("./negotiation/negotiationNeeded");
16
+ const remoteCandidates_1 = require("./negotiation/remoteCandidates");
17
+ const remoteMediaApplication_1 = require("./negotiation/remoteMediaApplication");
18
+ const transportActivation_1 = require("./negotiation/transportActivation");
19
+ const negotiationTransaction_1 = require("./negotiationTransaction");
12
20
  const sctpManager_1 = require("./sctpManager");
13
21
  const sdp_1 = require("./sdp");
14
22
  const sdpManager_1 = require("./sdpManager");
15
23
  const secureTransportManager_1 = require("./secureTransportManager");
16
- const sctp_1 = require("./transport/sctp");
17
24
  const utils_1 = require("./utils");
25
+ var peerConfig_2 = require("./api/peerConfig");
26
+ Object.defineProperty(exports, "defaultPeerConfig", { enumerable: true, get: function () { return peerConfig_2.defaultPeerConfig; } });
27
+ Object.defineProperty(exports, "findCodecByMimeType", { enumerable: true, get: function () { return peerConfig_2.findCodecByMimeType; } });
28
+ var peerConnectionEvents_2 = require("./api/peerConnectionEvents");
29
+ Object.defineProperty(exports, "RTCTrackEvent", { enumerable: true, get: function () { return peerConnectionEvents_2.RTCTrackEvent; } });
18
30
  const log = (0, common_1.debug)("werift:packages/webrtc/src/peerConnection.ts");
19
31
  /**
20
32
  * W3C compatibility notes kept near the public RTCPeerConnection surface so the
@@ -40,6 +52,23 @@ const log = (0, common_1.debug)("werift:packages/webrtc/src/peerConnection.ts");
40
52
  * even when generated docs are not committed in the same change.
41
53
  */
42
54
  class RTCPeerConnection extends helper_1.EventTarget {
55
+ /** W3C [[NegotiationNeeded]]. */
56
+ get negotiationneeded() {
57
+ return this.negotiationNeed.flag;
58
+ }
59
+ set negotiationneeded(value) {
60
+ this.negotiationNeed.flag = value;
61
+ }
62
+ /** A `restartIce()` request that no committed negotiation satisfied yet. */
63
+ get needRestart() {
64
+ return this.iceRestartRequest.requested;
65
+ }
66
+ set needRestart(value) {
67
+ if (value)
68
+ this.iceRestartRequest.requested = true;
69
+ else
70
+ this.iceRestartRequest.clear();
71
+ }
43
72
  get ondatachannel() {
44
73
  return this.eventHandlers.ondatachannel ?? null;
45
74
  }
@@ -112,7 +141,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
112
141
  enumerable: true,
113
142
  configurable: true,
114
143
  writable: true,
115
- value: generateDefaultPeerConfig()
144
+ value: (0, peerConfig_1.generateDefaultPeerConfig)()
116
145
  });
117
146
  Object.defineProperty(this, "signalingState", {
118
147
  enumerable: true,
@@ -120,77 +149,90 @@ class RTCPeerConnection extends helper_1.EventTarget {
120
149
  writable: true,
121
150
  value: "stable"
122
151
  });
123
- Object.defineProperty(this, "negotiationneeded", {
152
+ Object.defineProperty(this, "negotiationNeed", {
124
153
  enumerable: true,
125
154
  configurable: true,
126
155
  writable: true,
127
- value: false
156
+ value: new negotiationNeeded_1.NegotiationNeeded({
157
+ signalingState: () => this.signalingState,
158
+ isClosed: () => this.isClosed,
159
+ invalidate: () => this.invalidateLastCreatedDescriptions(),
160
+ fire: () => {
161
+ this.onNegotiationneeded.execute();
162
+ if (this.onnegotiationneeded) {
163
+ this.onnegotiationneeded(new globalThis.Event("negotiationneeded"));
164
+ }
165
+ this.emit("negotiationneeded");
166
+ },
167
+ })
128
168
  });
129
- /**同じ tick の複数の変更で negotiationneeded を重複発火しないための予約フラグ */
130
- Object.defineProperty(this, "negotiationneededScheduled", {
169
+ Object.defineProperty(this, "iceRestartRequest", {
131
170
  enumerable: true,
132
171
  configurable: true,
133
172
  writable: true,
134
- value: false
173
+ value: new iceRestartRequest_1.IceRestartRequest()
135
174
  });
136
- /**交渉が必要な変更の通し番号 */
137
- Object.defineProperty(this, "negotiationChangeSeq", {
175
+ Object.defineProperty(this, "router", {
138
176
  enumerable: true,
139
177
  configurable: true,
140
178
  writable: true,
141
- value: 0
179
+ value: new media_1.RtpRouter()
142
180
  });
143
- /**answer まで確定した local offer が反映している変更の通し番号 */
144
- Object.defineProperty(this, "negotiatedChangeSeq", {
181
+ Object.defineProperty(this, "sdpManager", {
145
182
  enumerable: true,
146
183
  configurable: true,
147
184
  writable: true,
148
- value: 0
185
+ value: void 0
149
186
  });
150
- /**適用中の local offer が反映している変更の通し番号 (rollback で破棄) */
151
- Object.defineProperty(this, "pendingOfferChangeSeq", {
187
+ Object.defineProperty(this, "transceiverManager", {
152
188
  enumerable: true,
153
189
  configurable: true,
154
190
  writable: true,
155
191
  value: void 0
156
192
  });
157
- Object.defineProperty(this, "lastCreatedOfferChangeSeq", {
193
+ Object.defineProperty(this, "sctpManager", {
158
194
  enumerable: true,
159
195
  configurable: true,
160
196
  writable: true,
161
- value: 0
197
+ value: void 0
162
198
  });
163
- Object.defineProperty(this, "needRestart", {
199
+ Object.defineProperty(this, "secureManager", {
164
200
  enumerable: true,
165
201
  configurable: true,
166
202
  writable: true,
167
- value: false
203
+ value: void 0
168
204
  });
169
- Object.defineProperty(this, "router", {
205
+ Object.defineProperty(this, "negotiation", {
170
206
  enumerable: true,
171
207
  configurable: true,
172
208
  writable: true,
173
- value: new media_1.RtpRouter()
209
+ value: void 0
174
210
  });
175
- Object.defineProperty(this, "sdpManager", {
211
+ Object.defineProperty(this, "topology", {
176
212
  enumerable: true,
177
213
  configurable: true,
178
214
  writable: true,
179
215
  value: void 0
180
216
  });
181
- Object.defineProperty(this, "transceiverManager", {
217
+ Object.defineProperty(this, "remoteCandidates", {
182
218
  enumerable: true,
183
219
  configurable: true,
184
220
  writable: true,
185
221
  value: void 0
186
222
  });
187
- Object.defineProperty(this, "sctpManager", {
223
+ Object.defineProperty(this, "validator", {
188
224
  enumerable: true,
189
225
  configurable: true,
190
226
  writable: true,
191
227
  value: void 0
192
228
  });
193
- Object.defineProperty(this, "secureManager", {
229
+ Object.defineProperty(this, "remoteMedia", {
230
+ enumerable: true,
231
+ configurable: true,
232
+ writable: true,
233
+ value: void 0
234
+ });
235
+ Object.defineProperty(this, "activation", {
194
236
  enumerable: true,
195
237
  configurable: true,
196
238
  writable: true,
@@ -202,29 +244,59 @@ class RTCPeerConnection extends helper_1.EventTarget {
202
244
  writable: true,
203
245
  value: false
204
246
  });
205
- Object.defineProperty(this, "shouldNegotiationneeded", {
247
+ Object.defineProperty(this, "applyingIceRestart", {
206
248
  enumerable: true,
207
249
  configurable: true,
208
250
  writable: true,
209
251
  value: false
210
252
  });
253
+ /**
254
+ * The last operation of the chain: `done` when it finished, `applied` when
255
+ * the description it applies is in place (setLocalDescription's gathering
256
+ * wait comes after it). addIceCandidate only needs `applied`.
257
+ */
258
+ Object.defineProperty(this, "descriptionTail", {
259
+ enumerable: true,
260
+ configurable: true,
261
+ writable: true,
262
+ value: {
263
+ done: Promise.resolve(),
264
+ applied: Promise.resolve(),
265
+ }
266
+ });
267
+ /** Marks the running operation's description as applied (see descriptionTail). */
268
+ Object.defineProperty(this, "markDescriptionApplied", {
269
+ enumerable: true,
270
+ configurable: true,
271
+ writable: true,
272
+ value: () => { }
273
+ });
211
274
  Object.defineProperty(this, "lastCreatedAnswer", {
212
275
  enumerable: true,
213
276
  configurable: true,
214
277
  writable: true,
215
278
  value: void 0
216
279
  });
280
+ /** Reusable by a parameterless setLocalDescription while still valid. */
217
281
  Object.defineProperty(this, "lastCreatedOffer", {
218
282
  enumerable: true,
219
283
  configurable: true,
220
284
  writable: true,
221
285
  value: void 0
222
286
  });
223
- Object.defineProperty(this, "pendingRemoteCandidates", {
287
+ /**
288
+ * W3C [[LastCreatedOffer]] and its generation record: the SDP of this
289
+ * peer's latest createOffer and the transceiver each of its MIDs was
290
+ * created for. Only createOffer replaces it; an explicit local offer must
291
+ * match the SDP. Applying the offer takes the MIDs from the SDP and this
292
+ * record (never from state kept elsewhere); its ICE restart generations are
293
+ * registered on the transports (see RTCIceTransport.localGenerationFor).
294
+ */
295
+ Object.defineProperty(this, "createdOffer", {
224
296
  enumerable: true,
225
297
  configurable: true,
226
298
  writable: true,
227
- value: []
299
+ value: void 0
228
300
  });
229
301
  Object.defineProperty(this, "iceGatheringStateChange", {
230
302
  enumerable: true,
@@ -298,8 +370,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
298
370
  configurable: true,
299
371
  writable: true,
300
372
  value: () => {
301
- this.negotiationChangeSeq++;
302
- this.scheduleNegotiationneeded();
373
+ this.negotiationNeed.change();
303
374
  }
304
375
  });
305
376
  this.setConfiguration(config);
@@ -312,7 +383,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
312
383
  this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);
313
384
  this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);
314
385
  this.transceiverManager.onTrack.subscribe(({ track, streams, transceiver }) => {
315
- const event = new RTCTrackEvent({
386
+ const event = new peerConnectionEvents_1.RTCTrackEvent({
316
387
  track,
317
388
  streams,
318
389
  transceiver,
@@ -326,6 +397,15 @@ class RTCPeerConnection extends helper_1.EventTarget {
326
397
  });
327
398
  this.transceiverManager.onNegotiationNeeded.subscribe(() => this.needNegotiation());
328
399
  this.sctpManager = new sctpManager_1.SctpTransportManager();
400
+ this.negotiation = new negotiationTransaction_1.NegotiationTransaction(this.sdpManager, this.transceiverManager, this.router, this.sctpManager);
401
+ this.topology = new bundleTopology_1.BundleTopology(this.sdpManager, this.transceiverManager, this.sctpManager, this.negotiation, () => this.findOrCreateTransport(true), () => this.isClosed);
402
+ this.remoteMedia = new remoteMediaApplication_1.RemoteMediaApplication(this.sdpManager, this.transceiverManager, this.sctpManager, this.router, this.negotiation, {
403
+ createSctpTransport: () => this.createSctpTransport(),
404
+ createTransport: () => this.findOrCreateTransport(),
405
+ createOwnerTransport: () => this.createOwnerTransport(),
406
+ onRemoteTransceiverAdded: (transceiver) => this.onRemoteTransceiverAdded.execute(transceiver),
407
+ });
408
+ this.validator = new descriptionValidation_1.DescriptionValidation(this.config, this.sdpManager, this.transceiverManager, this.sctpManager, this.negotiation, this.topology);
329
409
  this.sctpManager.onDataChannel.subscribe((channel) => {
330
410
  this.onDataChannel.execute(channel);
331
411
  const event = { type: "datachannel", channel };
@@ -337,6 +417,14 @@ class RTCPeerConnection extends helper_1.EventTarget {
337
417
  sctpManager: this.sctpManager,
338
418
  transceiverManager: this.transceiverManager,
339
419
  });
420
+ this.remoteCandidates = new remoteCandidates_1.RemoteCandidates(this.sdpManager, this.secureManager, this.negotiation, this.topology, {
421
+ signalingState: () => this.signalingState,
422
+ hasRemoteDescription: () => !!this.remoteDescription && !!this.sdpManager._remoteDescription,
423
+ });
424
+ this.activation = new transportActivation_1.TransportActivation(this.sdpManager, this.secureManager, this.transceiverManager, this.sctpManager, this.negotiation, this.topology, {
425
+ signalingState: () => this.signalingState,
426
+ createTransport: () => this.findOrCreateTransport(),
427
+ });
340
428
  this.secureManager.iceGatheringStateChange.subscribe((state) => {
341
429
  this.iceGatheringStateChange.execute(state);
342
430
  this.onicegatheringstatechange?.(new globalThis.Event("icegatheringstatechange"));
@@ -451,91 +539,21 @@ class RTCPeerConnection extends helper_1.EventTarget {
451
539
  return this.transceiverManager.getReceivers();
452
540
  }
453
541
  setConfiguration(config) {
454
- const normalizedConfig = normalizePeerConfiguration(config);
455
542
  const isReconfiguration = !!this.sdpManager;
456
- if (normalizedConfig.rtcpMuxPolicy &&
457
- normalizedConfig.rtcpMuxPolicy !== "require") {
458
- throw new Error("rtcpMuxPolicy must be require");
459
- }
460
- if (normalizedConfig.iceCandidatePoolSize !== undefined &&
461
- (!Number.isInteger(normalizedConfig.iceCandidatePoolSize) ||
462
- normalizedConfig.iceCandidatePoolSize < 0)) {
463
- throw new Error("iceCandidatePoolSize must be a non-negative integer");
464
- }
465
- if (isReconfiguration &&
466
- normalizedConfig.bundlePolicy !== undefined &&
467
- normalizedConfig.bundlePolicy !== this.config.bundlePolicy) {
468
- throw new Error("bundlePolicy cannot be changed");
469
- }
470
- if (normalizedConfig.mLineReuse !== undefined &&
471
- !MLineReuseModes.includes(normalizedConfig.mLineReuse)) {
472
- throw (0, errors_1.createWebRtcTypeError)(`mLineReuse must be one of ${MLineReuseModes.join(", ")}`);
473
- }
474
- if (isReconfiguration &&
475
- normalizedConfig.mLineReuse !== undefined &&
476
- normalizedConfig.mLineReuse !== this.config.mLineReuse) {
477
- throw (0, errors_1.createWebRtcDomException)("InvalidModificationError", "mLineReuse cannot be changed");
478
- }
479
- if (isReconfiguration &&
480
- normalizedConfig.rtcpMuxPolicy !== undefined &&
481
- normalizedConfig.rtcpMuxPolicy !== this.config.rtcpMuxPolicy) {
482
- throw new Error("rtcpMuxPolicy cannot be changed");
483
- }
484
- if (isReconfiguration &&
485
- normalizedConfig.certificates !== undefined &&
486
- !hasSameCertificates(normalizedConfig.certificates, this.config.certificates)) {
487
- throw new Error("certificates cannot be changed");
488
- }
489
- if (isReconfiguration &&
490
- normalizedConfig.iceCandidatePoolSize !== undefined &&
491
- this.localDescription &&
492
- normalizedConfig.iceCandidatePoolSize !== this.config.iceCandidatePoolSize) {
493
- throw new Error("iceCandidatePoolSize cannot be changed after setLocalDescription");
494
- }
495
- if ((normalizedConfig.iceCandidatePoolSize ?? 0) > 0) {
496
- throw new Error("iceCandidatePoolSize > 0 is not supported");
497
- }
498
- if (normalizedConfig.sctp !== undefined) {
499
- const requestedSctpMtu = normalizedConfig.sctp.mtu ?? src_1.DEFAULT_SCTP_MTU;
500
- (0, src_1.validateSctpMtu)(requestedSctpMtu);
501
- if (this.sctpManager?.sctpTransport &&
502
- requestedSctpMtu !== this.config.sctp.mtu) {
503
- throw new Error("sctp.mtu cannot be changed after SCTP transport creation");
504
- }
505
- }
506
- (0, utils_1.deepMerge)(this.config, normalizedConfig);
507
- this.config.sctp = {
508
- mtu: this.config.sctp?.mtu ?? src_1.DEFAULT_SCTP_MTU,
509
- };
510
- if (this.config.icePortRange) {
511
- const [min, max] = this.config.icePortRange;
512
- if (min === max)
513
- throw new Error("should not be same value");
514
- if (min >= max)
515
- throw new Error("The min must be less than max");
516
- }
517
- if (!Number.isInteger(this.config.maxMessageSize) ||
518
- this.config.maxMessageSize < 0) {
519
- throw new Error("maxMessageSize must be a non-negative integer");
520
- }
543
+ const normalizedConfig = (0, peerConfig_1.mergePeerConfiguration)(this.config, config, {
544
+ isReconfiguration,
545
+ hasLocalDescription: isReconfiguration && !!this.localDescription,
546
+ hasSctpTransport: !!this.sctpManager?.sctpTransport,
547
+ });
548
+ this.router.keyFrameRequestRouting = this.config.keyFrameRequestRouting;
521
549
  if (this.sctpManager?.sctpTransport) {
522
550
  this.sctpManager.sctpTransport.maxMessageSize =
523
551
  this.config.maxMessageSize;
524
552
  }
525
- assignDynamicPayloadTypes(this.config);
526
- [
527
- ...(this.config.headerExtensions.audio || []),
528
- ...(this.config.headerExtensions.video || []),
529
- ].forEach((v, i) => {
530
- v.id = 1 + i;
531
- });
532
- // Propagate ICE server changes only to transports still in gathering
533
- // state "new". JSEP (RFC 8829 §4.1.18): STUN/TURN changes affect the next
534
- // gathering phase; once gathering has started or finished, nothing is
535
- // applied to the live Connection (WHIP: createOffer → setConfiguration →
536
- // setLocalDescription). Per-transport state is used so a gatherer that
537
- // was reset to "new" (e.g. after ICE restart) is not blocked by a stale
538
- // manager aggregate of "complete".
553
+ // JSEP (RFC 8829 §4.1.18): STUN/TURN changes affect the next gathering
554
+ // phase. Transports still in gathering state "new" take them now (WHIP:
555
+ // createOffer → setConfiguration → setLocalDescription); the others keep
556
+ // the live Connection untouched and take them at their next ICE restart.
539
557
  if (isReconfiguration &&
540
558
  this.secureManager &&
541
559
  (normalizedConfig.iceServers !== undefined ||
@@ -544,13 +562,45 @@ class RTCPeerConnection extends helper_1.EventTarget {
544
562
  }
545
563
  }
546
564
  getConfiguration() {
547
- return clonePeerConfiguration(this.config);
565
+ return (0, peerConfig_1.clonePeerConfiguration)(this.config);
548
566
  }
549
- async createOffer({ iceRestart } = {}) {
550
- if (iceRestart || this.needRestart) {
551
- this.needRestart = false;
552
- this.secureManager.restartIce();
567
+ /**
568
+ * W3C operations chain: createOffer runs after every earlier description
569
+ * operation, so an offer it produces cannot invalidate a setLocalDescription
570
+ * that was called before it.
571
+ */
572
+ createOffer(options = {}) {
573
+ return this.enqueueDescriptionOperation(() => this.createOfferNow(options));
574
+ }
575
+ /** createOffer body; call directly only from inside a queued operation. */
576
+ async createOfferNow({ iceRestart } = {}) {
577
+ // Transports prepared for an applied pending offer stay until that offer
578
+ // is replaced or rolled back; setLocalDescription stages new ones first.
579
+ if (this.signalingState === "stable")
580
+ this.negotiation.snapshotForOffer();
581
+ const restartRequested = !!iceRestart || this.needRestart;
582
+ if (restartRequested) {
583
+ if (this.sdpManager.currentLocalDescription &&
584
+ this.sdpManager.currentRemoteDescription) {
585
+ this.secureManager.stageIceRestart(undefined, {
586
+ replacing: this.iceRestartRequest.replacing,
587
+ });
588
+ }
589
+ else {
590
+ // No current credentials to replace: fresh ones satisfy restartIce().
591
+ this.iceRestartRequest.clear();
592
+ this.secureManager.restartIce();
593
+ }
594
+ }
595
+ else if (["stable", "have-local-offer", "have-remote-pranswer"].includes(this.signalingState)) {
596
+ // An offer without a restart carries the live credentials, or those of
597
+ // the applied pending offer (JSEP 5.2.1). Only the selection changes;
598
+ // registered generations stay.
599
+ this.secureManager.discardUnappliedIceRestart();
553
600
  }
601
+ // While a remote offer is pending, an offer without a restart carries the
602
+ // generation the answer would commit: applied once that answer made the
603
+ // session stable, its credentials are the live ones.
554
604
  await this.secureManager.ensureCerts();
555
605
  for (const transceiver of this.transceiverManager.getTransceivers()) {
556
606
  if (transceiver.codecs.length === 0 ||
@@ -562,10 +612,34 @@ class RTCPeerConnection extends helper_1.EventTarget {
562
612
  this.config.headerExtensions[transceiver.kind] ?? [];
563
613
  }
564
614
  }
565
- const description = this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(), this.sctpTransport);
615
+ // As in develop, an offer created where it can be applied associates its
616
+ // MIDs and m-line positions now (issue 705 expectations). While a remote
617
+ // offer is pending it cannot be applied, so the associations stay as the
618
+ // pending offer made them; the offer's generation record keeps the MIDs
619
+ // it assigned and applying it later takes them from there.
620
+ const unapplicable = ["have-remote-offer", "have-local-pranswer"].includes(this.signalingState);
621
+ const transceivers = this.transceiverManager.getTransceivers();
622
+ const positions = transceivers.map((t) => [t.mid, t.mLineIndex]);
623
+ const sctp = this.sctpTransport;
624
+ const sctpPosition = sctp && [sctp.mid, sctp.mLineIndex];
625
+ const description = this.sdpManager.buildOfferSdp(transceivers, this.sctpTransport);
626
+ const transceiverByMid = new Map(transceivers
627
+ .filter((t) => t.mid != undefined)
628
+ .map((t) => [t.mid, t]));
629
+ if (unapplicable) {
630
+ transceivers.forEach((t, i) => {
631
+ [t.mid, t.mLineIndex] = positions[i];
632
+ });
633
+ if (sctp && sctpPosition)
634
+ [sctp.mid, sctp.mLineIndex] = sctpPosition;
635
+ }
566
636
  const createdOffer = description.toJSON();
567
637
  this.lastCreatedOffer = createdOffer;
568
- this.lastCreatedOfferChangeSeq = this.negotiationChangeSeq;
638
+ this.createdOffer = {
639
+ sdp: createdOffer.sdp,
640
+ transceiverByMid,
641
+ changeSeq: this.negotiationNeed.noteCreatedOffer(),
642
+ };
569
643
  return createdOffer;
570
644
  }
571
645
  createSctpTransport() {
@@ -594,84 +668,137 @@ class RTCPeerConnection extends helper_1.EventTarget {
594
668
  this.needNegotiation();
595
669
  }
596
670
  }
597
- /**未交渉の変更が残っていれば negotiationneeded を予約する (stable 復帰時の再判定にも使う) */
598
- scheduleNegotiationneeded() {
599
- this.invalidateLastCreatedDescriptions();
600
- this.shouldNegotiationneeded = true;
601
- if (this.negotiationneeded ||
602
- this.negotiationneededScheduled ||
603
- this.signalingState !== "stable") {
604
- return;
605
- }
606
- this.shouldNegotiationneeded = false;
607
- this.negotiationneededScheduled = true;
608
- setImmediate(() => {
609
- this.negotiationneededScheduled = false;
610
- if (this.negotiatedChangeSeq >= this.negotiationChangeSeq) {
611
- // 発火前に適用された local offer が変更をすべて含んでいる
612
- return;
613
- }
614
- if (this.signalingState !== "stable") {
615
- // stable に戻った時点で改めて判定する
616
- this.shouldNegotiationneeded = true;
617
- return;
618
- }
619
- this.negotiationneeded = true;
620
- this.onNegotiationneeded.execute();
621
- if (this.onnegotiationneeded) {
622
- this.onnegotiationneeded(new globalThis.Event("negotiationneeded"));
671
+ /**
672
+ * The transceiver each audio / video m-line of a local offer associates:
673
+ * the one with that MID, or the one the offer's generation record created
674
+ * the MID for while it is still unassociated (an offer created while a
675
+ * remote offer was pending, or one whose rollback took the MID back).
676
+ */
677
+ planOfferAssignments(description, sdp) {
678
+ const transceivers = this.transceiverManager.getTransceivers();
679
+ const record = this.createdOffer?.sdp === sdp ? this.createdOffer : undefined;
680
+ const assignments = [];
681
+ for (const [index, media] of description.media.entries()) {
682
+ const mid = media.rtp.muxId;
683
+ if (!mid || !["audio", "video"].includes(media.kind))
684
+ continue;
685
+ let transceiver = transceivers.find((t) => t.mid === mid);
686
+ if (!transceiver) {
687
+ const created = record?.transceiverByMid.get(mid);
688
+ if (created &&
689
+ created.mid == undefined &&
690
+ !created.stopped &&
691
+ transceivers.includes(created)) {
692
+ transceiver = created;
693
+ }
623
694
  }
624
- this.emit("negotiationneeded");
625
- });
695
+ if (transceiver)
696
+ assignments.push({ transceiver, mid, index });
697
+ }
698
+ return assignments;
699
+ }
700
+ selectDescribedIceGenerations(description) {
701
+ for (const media of description.media) {
702
+ if (media.port === 0 || !media.iceParams || !media.rtp.muxId)
703
+ continue;
704
+ const transport = this.negotiation.transportByMid.get(media.rtp.muxId) ??
705
+ this.topology.currentTransportForMid(media.rtp.muxId);
706
+ transport?.iceTransport.selectLocalGeneration(media.iceParams.usernameFragment, media.iceParams.password);
707
+ }
626
708
  }
627
709
  invalidateLastCreatedDescriptions() {
628
710
  this.lastCreatedAnswer = undefined;
629
711
  this.lastCreatedOffer = undefined;
630
712
  }
631
713
  async waitForPendingDescriptionTask() {
632
- this.assertNotClosed();
633
714
  await Promise.resolve();
634
- if (this.isClosed) {
635
- await new Promise(() => undefined);
715
+ this.assertOpenAfterYield();
716
+ }
717
+ /**
718
+ * W3C "chain an operation", in one place: an operation registered on a
719
+ * closed connection is rejected at once; one that close() overtook while
720
+ * it waited for the previous operation, or while it ran, is rejected with
721
+ * InvalidStateError when it resumes. Every operation's promise settles
722
+ * (W3C would leave an overtaken one pending forever; werift settles it so
723
+ * an application awaiting it is never stuck).
724
+ */
725
+ async enqueueDescriptionOperation(operation, { afterApplied = false, } = {}) {
726
+ this.assertNotClosed();
727
+ const previous = this.descriptionTail;
728
+ let releaseDone;
729
+ let releaseApplied;
730
+ const done = new Promise((resolve) => {
731
+ releaseDone = resolve;
732
+ });
733
+ const applied = new Promise((resolve) => {
734
+ releaseApplied = resolve;
735
+ });
736
+ this.descriptionTail = afterApplied
737
+ ? {
738
+ done: Promise.all([previous.done, done]).then(() => undefined),
739
+ applied: Promise.all([previous.applied, done]).then(() => undefined),
740
+ }
741
+ : { done, applied };
742
+ try {
743
+ await (afterApplied ? previous.applied : previous.done);
744
+ this.assertOpenAfterYield();
745
+ if (!afterApplied)
746
+ this.markDescriptionApplied = releaseApplied;
747
+ let result;
748
+ try {
749
+ result = await operation();
750
+ }
751
+ catch (error) {
752
+ // An operation close() overtook fails as overtaken, not with the
753
+ // error its interrupted step raised.
754
+ this.assertOpenAfterYield();
755
+ throw error;
756
+ }
757
+ // W3C: an operation that close() overtook does not report success.
758
+ this.assertOpenAfterYield();
759
+ return result;
760
+ }
761
+ finally {
762
+ releaseApplied();
763
+ releaseDone();
636
764
  }
637
765
  }
638
- findOrCreateTransport() {
766
+ findOrCreateTransport(forceNew = false) {
767
+ // A closed connection creates no transport (close() could not stop it).
768
+ this.assertNotClosed();
639
769
  const existingDtlsTransport = this.dtlsTransports.find((transport) => transport.state !== "closed");
770
+ const existing = existingDtlsTransport?.iceTransport;
640
771
  // Gather ICE candidates for only one track. If the remote endpoint is not bundle-aware, negotiate only one media track.
641
772
  // https://w3c.github.io/webrtc-pc/#rtcbundlepolicy-enum
642
- if (this.sdpManager.bundlePolicy === "max-bundle" ||
643
- (this.sdpManager.bundlePolicy !== "disable" && this.remoteIsBundled)) {
773
+ if (!forceNew &&
774
+ (this.sdpManager.bundlePolicy === "max-bundle" ||
775
+ (this.sdpManager.bundlePolicy !== "disable" && this.remoteIsBundled))) {
644
776
  if (existingDtlsTransport) {
645
777
  return existingDtlsTransport;
646
778
  }
647
779
  }
648
- return this.createDtlsTransport();
649
- }
650
- /**
651
- * @param inheritCredentials false の場合は BUNDLE 外の独立 transport として
652
- * 既存 transport と異なる ICE credentials を使う
653
- */
654
- createDtlsTransport({ inheritCredentials = true } = {}) {
655
- const dtlsTransport = this.secureManager.createTransport({
656
- inheritCredentials,
657
- });
780
+ const dtlsTransport = this.secureManager.createTransport(forceNew);
658
781
  dtlsTransport.onRtp.subscribe((rtp) => {
659
782
  this.router.routeRtp(rtp);
660
783
  });
661
784
  dtlsTransport.onRtcp.subscribe((rtcp) => {
662
785
  this.router.routeRtcp(rtcp);
663
786
  });
787
+ this.negotiation.noteCreatedTransport(dtlsTransport);
664
788
  const iceTransport = dtlsTransport.iceTransport;
665
789
  iceTransport.onNegotiationNeeded.subscribe(() => {
666
790
  this.needNegotiation();
667
791
  });
668
792
  iceTransport.onIceCandidate.subscribe((candidate) => {
793
+ if (this.applyingIceRestart ||
794
+ this.negotiation.isPendingOnlyTransport(iceTransport.id))
795
+ return;
669
796
  if (!this.localDescription) {
670
797
  log("localDescription not found when ice candidate was gathered");
671
798
  return;
672
799
  }
673
800
  if (!candidate) {
674
- this.sdpManager.setLocal(this._localDescription, this.transceiverManager.getTransceivers(), this.sctpTransport);
801
+ this.sdpManager.setLocal(this._localDescription, this.transceiverManager.getTransceivers(), this.sctpTransport, this.negotiation.transportByMid);
675
802
  this.onIceCandidate.execute(undefined);
676
803
  if (this.onicecandidate) {
677
804
  this.onicecandidate({ candidate: undefined });
@@ -697,21 +824,16 @@ class RTCPeerConnection extends helper_1.EventTarget {
697
824
  });
698
825
  return dtlsTransport;
699
826
  }
700
- /**
701
- * local candidate の sdpMid / sdpMLineIndex を、その ICE transport を実際に
702
- * 所有する受け入れ済み m-line (BUNDLE なら tag) に合わせる。
703
- */
827
+ /**Resolve candidate metadata from an accepted m-line that owns this transport. */
704
828
  resolveLocalCandidateOwner(iceTransport) {
705
829
  const description = this._localDescription;
706
- if (!description) {
830
+ if (!description)
707
831
  return;
708
- }
709
832
  const owners = description.media
710
833
  .map((media, index) => ({ media, index }))
711
834
  .filter(({ media }) => {
712
- if (media.port === 0) {
835
+ if (media.port === 0)
713
836
  return false;
714
- }
715
837
  const mid = media.rtp.muxId;
716
838
  if (media.kind === "application") {
717
839
  return (!!this.sctpTransport &&
@@ -721,18 +843,15 @@ class RTCPeerConnection extends helper_1.EventTarget {
721
843
  }
722
844
  const transceiver = this.transceiverManager
723
845
  .getTransceivers()
724
- .find((t) => t.mid != undefined && t.mid === mid);
725
- return (!!transceiver &&
726
- !transceiver.stopped &&
727
- transceiver.dtlsTransport?.iceTransport.id === iceTransport.id);
846
+ .find((t) => t.mid === mid && !t.stopped);
847
+ return transceiver?.dtlsTransport?.iceTransport.id === iceTransport.id;
728
848
  });
729
849
  const tags = description.group
730
850
  .filter((group) => group.semantic === "BUNDLE")
731
851
  .map((group) => group.items[0]);
732
852
  const owner = owners.find(({ media }) => tags.includes(media.rtp.muxId)) ?? owners[0];
733
- if (!owner) {
853
+ if (!owner)
734
854
  return;
735
- }
736
855
  return { mid: owner.media.rtp.muxId, index: owner.index };
737
856
  }
738
857
  /**
@@ -753,6 +872,9 @@ class RTCPeerConnection extends helper_1.EventTarget {
753
872
  .filter((t) => t.stopped)
754
873
  .map((t) => t.dtlsTransport)) {
755
874
  const live = new Set(this.dtlsTransports.map((t) => t.id));
875
+ for (const transport of this.negotiation.transportByMid.values()) {
876
+ live.add(transport.id);
877
+ }
756
878
  for (const transport of new Set(candidates)) {
757
879
  if (!transport ||
758
880
  transport.state === "closed" ||
@@ -765,602 +887,676 @@ class RTCPeerConnection extends helper_1.EventTarget {
765
887
  }
766
888
  }
767
889
  async setLocalDescription(sessionDescription) {
768
- // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/setLocalDescription#type
769
- const implicitOfferState = [
770
- "stable",
771
- "have-local-offer",
772
- "have-remote-pranswer",
773
- ];
774
- await this.waitForPendingDescriptionTask();
775
- if (sessionDescription?.type === "rollback") {
776
- this.sdpManager.rollbackLocalDescription(this.signalingState);
777
- for (const transceiver of this.transceiverManager.getTransceivers()) {
778
- transceiver.pendingLocalOfferCodecs = undefined;
890
+ return this.enqueueDescriptionOperation(async () => {
891
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/setLocalDescription#type
892
+ const implicitOfferState = [
893
+ "stable",
894
+ "have-local-offer",
895
+ "have-remote-pranswer",
896
+ ];
897
+ await this.waitForPendingDescriptionTask();
898
+ if (sessionDescription?.type === "rollback") {
899
+ this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription);
900
+ this.sdpManager.rollbackLocalDescription(this.signalingState);
901
+ this.secureManager.rollbackStagedIceRestart();
902
+ await this.negotiation.rollback();
903
+ this.assertOpenAfterYield();
904
+ await this.activation.cleanupInitialProvisional();
905
+ this.assertOpenAfterYield();
906
+ this.setSignalingState("stable");
907
+ this.negotiationNeed.discardPendingOffer();
908
+ // An unsatisfied restartIce() request makes negotiation needed again.
909
+ if (this.negotiationNeed.recheck || this.needRestart) {
910
+ this.negotiationNeed.schedule();
911
+ }
912
+ this.invalidateLastCreatedDescriptions();
913
+ return;
779
914
  }
780
- this.pendingOfferChangeSeq = undefined;
781
- this.setSignalingState("stable");
782
- if (this.shouldNegotiationneeded) {
783
- this.scheduleNegotiationneeded();
915
+ const needsGeneratedDescription = !sessionDescription?.type ||
916
+ !sessionDescription.sdp ||
917
+ sessionDescription.sdp.length === 0;
918
+ const generatedDescription = needsGeneratedDescription
919
+ ? sessionDescription?.type === "offer"
920
+ ? (this.lastCreatedOffer ?? (await this.createOfferNow()))
921
+ : sessionDescription?.type === "answer" ||
922
+ sessionDescription?.type === "pranswer"
923
+ ? (this.lastCreatedAnswer ?? (await this.createAnswerNow()))
924
+ : implicitOfferState.includes(this.signalingState)
925
+ ? (this.lastCreatedOffer ?? (await this.createOfferNow()))
926
+ : (this.lastCreatedAnswer ?? (await this.createAnswerNow()))
927
+ : undefined;
928
+ this.assertOpenAfterYield();
929
+ sessionDescription = {
930
+ type: sessionDescription?.type ?? generatedDescription.type,
931
+ sdp: sessionDescription?.sdp && sessionDescription.sdp.length > 0
932
+ ? sessionDescription.sdp
933
+ : generatedDescription.sdp,
934
+ };
935
+ // W3C setLocalDescription: an offer must be the last one this peer's
936
+ // createOffer produced. A peer that never created an offer accepts none,
937
+ // so an offer from another peer and local SDP munging (codec,
938
+ // direction, BUNDLE, ICE) are refused before any transaction or live
939
+ // state is touched.
940
+ if (sessionDescription.type === "offer" &&
941
+ sessionDescription.sdp !== this.createdOffer?.sdp) {
942
+ throw (0, errors_1.createWebRtcDomException)("InvalidModificationError", "setLocalDescription must use the latest created offer");
784
943
  }
785
- this.invalidateLastCreatedDescriptions();
786
- return;
787
- }
788
- const needsGeneratedDescription = !sessionDescription?.type ||
789
- !sessionDescription.sdp ||
790
- sessionDescription.sdp.length === 0;
791
- const generatedDescription = needsGeneratedDescription
792
- ? sessionDescription?.type === "offer"
793
- ? (this.lastCreatedOffer ?? (await this.createOffer()))
794
- : sessionDescription?.type === "answer" ||
795
- sessionDescription?.type === "pranswer"
796
- ? (this.lastCreatedAnswer ?? (await this.createAnswer()))
797
- : implicitOfferState.includes(this.signalingState)
798
- ? (this.lastCreatedOffer ?? (await this.createOffer()))
799
- : (this.lastCreatedAnswer ?? (await this.createAnswer()))
800
- : undefined;
801
- sessionDescription = {
802
- type: sessionDescription?.type ?? generatedDescription.type,
803
- sdp: sessionDescription?.sdp && sessionDescription.sdp.length > 0
804
- ? sessionDescription.sdp
805
- : generatedDescription.sdp,
806
- };
807
- if (sessionDescription.type === "offer" &&
808
- this.lastCreatedOffer &&
809
- sessionDescription.sdp !== this.lastCreatedOffer.sdp) {
810
- throw (0, errors_1.createWebRtcDomException)("InvalidModificationError", "setLocalDescription must use the latest created offer");
811
- }
812
- // # parse and validate description
813
- const descriptionType = sessionDescription.type;
814
- const descriptionSdp = sessionDescription.sdp;
815
- const description = this.sdpManager.parseSdp({
816
- sdp: descriptionSdp,
817
- isLocal: true,
818
- signalingState: this.signalingState,
819
- type: descriptionType,
820
- });
821
- // # update signaling state
822
- if (description.type === "offer") {
823
- // この offer は作成時点までの変更を含む。answer の適用で交渉済みにする
824
- this.pendingOfferChangeSeq =
825
- this.lastCreatedOffer?.sdp === sessionDescription.sdp
826
- ? this.lastCreatedOfferChangeSeq
827
- : undefined;
828
- this.setSignalingState("have-local-offer");
829
- }
830
- else if (description.type === "answer") {
831
- this.setSignalingState("stable");
832
- }
833
- else if (description.type === "pranswer") {
834
- this.setSignalingState("have-local-pranswer");
835
- }
836
- if (description.type === "answer") {
837
- // answer の確定で拒否予定の m-line を停止し、RTP pipeline / 遊休 transport を解放する
838
- this.transceiverManager.commitRemoteOffer();
839
- // port 0 で答えた m-line (aggressive の inactive など) は offerer 側で拒否として停止が確定する。
840
- // answerer 側も同じ位置を停止確定にし、offerer が新 MID で再利用できるようにする
841
- for (const media of description.media) {
842
- if (!["audio", "video"].includes(media.kind) || media.port !== 0) {
843
- continue;
944
+ // # build the proposal from the SDP and its generation record
945
+ // Nothing below writes live or transaction state until every check
946
+ // passed: a failure while parsing, validating or staging leaves the
947
+ // peer exactly as it was.
948
+ const descriptionType = sessionDescription.type;
949
+ const description = this.sdpManager.parseSdp({
950
+ sdp: sessionDescription.sdp,
951
+ isLocal: true,
952
+ signalingState: this.signalingState,
953
+ type: descriptionType,
954
+ });
955
+ const offerAssignments = description.type === "offer"
956
+ ? this.planOfferAssignments(description, sessionDescription.sdp)
957
+ : [];
958
+ // The SCTP m-line of an offer belongs to the SCTP transport (a
959
+ // rollback may have taken its MID back).
960
+ const sctpAssignment = description.type === "offer" && this.sctpTransport
961
+ ? description.media
962
+ .map((media, index) => ({ media, index }))
963
+ .find(({ media }) => media.kind === "application" &&
964
+ media.port !== 0 &&
965
+ !!media.rtp.muxId &&
966
+ (this.sctpTransport.mid == undefined ||
967
+ this.sctpTransport.mid === media.rtp.muxId))
968
+ : undefined;
969
+ const assignedTransports = new Map(offerAssignments.map(({ mid, transceiver }) => [
970
+ mid,
971
+ transceiver.dtlsTransport,
972
+ ]));
973
+ if (sctpAssignment && this.sctpTransport) {
974
+ assignedTransports.set(sctpAssignment.media.rtp.muxId, this.sctpTransport.dtlsTransport);
975
+ }
976
+ this.validator.validateLocal(description, (mid) => assignedTransports.get(mid));
977
+ // Stage the offer's new transports before retiring anything pending.
978
+ const stagedOfferTopology = description.type === "offer"
979
+ ? await this.topology.stageLocalOffer(description, assignedTransports)
980
+ : undefined;
981
+ this.assertOpenAfterYield();
982
+ // # apply
983
+ try {
984
+ if (description.type === "offer" &&
985
+ this.signalingState === "have-remote-pranswer") {
986
+ this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription);
987
+ this.sdpManager.setRemoteDescription({ type: "rollback" }, this.signalingState);
988
+ this.secureManager.rollbackStagedIceRestart();
989
+ await this.negotiation.rollback();
990
+ this.assertOpenAfterYield();
991
+ await this.activation.cleanupInitialProvisional();
992
+ this.assertOpenAfterYield();
993
+ this.setSignalingState("stable");
994
+ // A "stable" handler may close the connection.
995
+ this.assertOpenAfterYield();
996
+ }
997
+ if (description.type === "offer") {
998
+ if (this.signalingState === "have-local-offer") {
999
+ await this.negotiation.replace();
1000
+ this.assertOpenAfterYield();
1001
+ this.sdpManager.pendingLocalDescription = undefined;
1002
+ }
1003
+ else {
1004
+ this.negotiation.begin({ fromCreatedOffer: true });
1005
+ }
1006
+ for (const { transceiver, mid, index } of offerAssignments) {
1007
+ transceiver.mid = mid;
1008
+ transceiver.mLineIndex = index;
1009
+ transceiver.pendingLocalOfferCodecs = [
1010
+ ...description.media[index].rtp.codecs,
1011
+ ];
1012
+ }
1013
+ if (sctpAssignment && this.sctpTransport) {
1014
+ this.sctpTransport.mid = sctpAssignment.media.rtp.muxId;
1015
+ this.sctpTransport.mLineIndex = sctpAssignment.index;
1016
+ }
1017
+ }
1018
+ // Each transport takes the ICE generation the description carries.
1019
+ this.selectDescribedIceGenerations(description);
1020
+ this.negotiation.validate();
1021
+ this.negotiation.prepare();
1022
+ if (stagedOfferTopology) {
1023
+ this.topology.installLocalOffer(description, stagedOfferTopology);
844
1024
  }
845
- const transceiver = this.transceiverManager
846
- .getTransceivers()
847
- .find((t) => t.mid === media.rtp.muxId && !t.stopped);
848
- transceiver?.commitStopped({ rejected: true });
849
1025
  }
850
- this.closeIdleTransports();
851
- }
852
- // # assign MID
853
- for (const [i, media] of (0, helper_1.enumerate)(description.media)) {
854
- const mid = media.rtp.muxId;
855
- this.sdpManager.registerMid(mid);
856
- if (["audio", "video"].includes(media.kind) && media.port !== 0) {
857
- // 停止済み、別 kind、別 MID の transceiver には割り当てない (MID の一意性を保つ)
858
- const transceiver = this.transceiverManager
859
- .getTransceivers()
860
- .find((t) => t.mLineIndex === i &&
861
- !t.stopped &&
862
- t.kind === media.kind &&
863
- (t.mid == null || t.mid === mid));
864
- if (transceiver) {
865
- transceiver.mid = mid;
866
- if (description.type === "offer") {
867
- transceiver.pendingLocalOfferCodecs = [...media.rtp.codecs];
1026
+ catch (error) {
1027
+ // Staged transports not yet owned by the transaction are stopped.
1028
+ await Promise.allSettled((stagedOfferTopology ?? [])
1029
+ .filter(({ transport, pendingOnly }) => pendingOnly &&
1030
+ !this.negotiation.isPendingOnlyTransport(transport.iceTransport.id))
1031
+ .map(({ transport }) => transport.stop()));
1032
+ throw error;
1033
+ }
1034
+ // The applied answer (or pranswer) fixes the codecs: the transceiver
1035
+ // takes them from the description itself. Whatever was resolved since
1036
+ // createAnswer() (setCodecPreferences, addTrack, or a createOffer() that
1037
+ // was never applied) does not reach the sender / receiver; it is
1038
+ // resolved again for the next offer.
1039
+ const resolveAfterAnswer = [];
1040
+ if (description.type === "answer" || description.type === "pranswer") {
1041
+ for (const transceiver of this.transceiverManager.getTransceivers()) {
1042
+ if (!transceiver.mid || transceiver.stopping || transceiver.stopped) {
1043
+ continue;
1044
+ }
1045
+ const answered = description.media.find((media) => media.rtp.muxId === transceiver.mid &&
1046
+ media.kind === transceiver.kind &&
1047
+ media.port !== 0);
1048
+ if (!answered || answered.rtp.codecs.length === 0)
1049
+ continue;
1050
+ const resolved = transceiver.codecs;
1051
+ transceiver.codecs = [...answered.rtp.codecs];
1052
+ if (!sameCodecList(resolved, transceiver.codecs)) {
1053
+ resolveAfterAnswer.push(transceiver);
868
1054
  }
869
1055
  }
870
1056
  }
871
- if (media.kind === "application" && this.sctpTransport) {
872
- this.sctpTransport.mid = mid;
1057
+ if (description.type === "answer" &&
1058
+ this.sdpManager.currentRemoteDescription) {
1059
+ this.topology.applyPending(description);
1060
+ await this.commitIceRestartIfAnyStaged();
1061
+ this.assertOpenAfterYield();
1062
+ await this.activation.activatePendingRemote();
1063
+ this.assertOpenAfterYield();
1064
+ for (const transceiver of this.transceiverManager.getTransceivers()) {
1065
+ if (transceiver.mid && transceiver.codecs.length > 0) {
1066
+ transceiver.sender.prepareSend(this.transceiverManager.getLocalRtpParams(transceiver));
1067
+ }
1068
+ }
1069
+ this.commitAnsweredCodecs();
873
1070
  }
874
- }
875
- // setup ice,dtls role
876
- const role = description.media.find((media) => media.dtlsParams)?.dtlsParams
877
- ?.role;
878
- // transport ごとに、その transport を使う受け入れ済み m-line の a=setup を適用する
879
- // (BUNDLE group 外の独立 transport は先頭 m-line と異なる role を持ちうる)
880
- const roleOfTransport = new Map();
881
- for (const media of description.media) {
882
- const mid = media.rtp.muxId;
883
- const mediaRole = media.dtlsParams?.role;
884
- if (media.port === 0 || mid == undefined || !mediaRole) {
885
- continue;
1071
+ if (description.type === "pranswer" &&
1072
+ this.sdpManager.currentRemoteDescription) {
1073
+ await this.activation.activatePendingRemote(true);
1074
+ this.assertOpenAfterYield();
1075
+ // Like a remote pranswer, a local one sends provisionally with the
1076
+ // codecs it answered; the baseline restores them on rollback.
1077
+ for (const transceiver of this.transceiverManager.getTransceivers()) {
1078
+ if (transceiver.mid && transceiver.codecs.length > 0) {
1079
+ transceiver.sender.prepareSend(this.transceiverManager.getLocalRtpParams(transceiver));
1080
+ }
1081
+ }
886
1082
  }
887
- const owner = media.kind === "application"
888
- ? this.sctpTransport?.mid === mid
889
- ? this.sctpTransport
890
- : undefined
891
- : this.transceiverManager
892
- .getTransceivers()
893
- .find((t) => t.mid === mid && !t.stopped);
894
- if (owner?.dtlsTransport && !roleOfTransport.has(owner.dtlsTransport)) {
895
- roleOfTransport.set(owner.dtlsTransport, mediaRole);
1083
+ // A first negotiation has no current session to protect: its pranswer
1084
+ // already sends and receives with the codecs it answered (a rollback
1085
+ // returns to the baseline), and the final answer commits them.
1086
+ if ((description.type === "answer" || description.type === "pranswer") &&
1087
+ !this.sdpManager.currentRemoteDescription) {
1088
+ this.commitAnsweredCodecs();
896
1089
  }
897
- }
898
- this.secureManager.setLocalRole({
899
- type: description.type === "offer" ? "offer" : "answer",
900
- role,
901
- roleOfTransport,
902
- });
903
- // # configure direction
904
- if (["answer", "pranswer"].includes(description.type)) {
1090
+ for (const transceiver of resolveAfterAnswer) {
1091
+ transceiver.codecPreferencesNeedResolution = true;
1092
+ }
1093
+ // # assign MID
1094
+ for (const [i, media] of (0, helper_1.enumerate)(description.media)) {
1095
+ const mid = media.rtp.muxId;
1096
+ this.sdpManager.registerMid(mid);
1097
+ if (["audio", "video"].includes(media.kind) && media.port !== 0) {
1098
+ // 停止済み、別 kind、別 MID の transceiver には割り当てない (MID の一意性を保つ)
1099
+ const transceiver = this.transceiverManager
1100
+ .getTransceivers()
1101
+ .find((t) => t.mLineIndex === i &&
1102
+ !t.stopped &&
1103
+ t.kind === media.kind &&
1104
+ (t.mid == null || t.mid === mid));
1105
+ if (transceiver) {
1106
+ transceiver.mid = mid;
1107
+ }
1108
+ }
1109
+ // A rejected application m-line binds no SCTP transport: one the
1110
+ // application created stays unbound for the next offer.
1111
+ if (media.kind === "application" &&
1112
+ media.port !== 0 &&
1113
+ this.sctpTransport) {
1114
+ this.sctpTransport.mid = mid;
1115
+ }
1116
+ }
1117
+ // setup ice,dtls role. Each transport takes the role of its own m-line:
1118
+ // a BUNDLE split owner is a new association whose role can differ from
1119
+ // the transport the first m-line keeps.
1120
+ const fallbackRole = description.media.find((media) => media.dtlsParams)
1121
+ ?.dtlsParams?.role;
1122
+ const roleByTransport = new Map();
905
1123
  for (const media of description.media) {
906
- const t = this.transceiverManager
907
- .getTransceivers()
908
- .find((t) => t.mid != undefined && t.mid === media.rtp.muxId);
909
- if (!t || t.stopped || t.pendingRejection) {
910
- continue;
1124
+ const transport = this.topology.currentTransportForMid(media.rtp.muxId ?? "");
1125
+ const role = media.dtlsParams?.role;
1126
+ if (transport && role && !roleByTransport.has(transport)) {
1127
+ roleByTransport.set(transport, role);
911
1128
  }
912
- const direction = t.stopping
913
- ? "inactive"
914
- : (0, utils_1.andDirection)(t.direction, t.offerDirection);
915
- t.setCurrentDirection(direction);
916
1129
  }
917
- }
918
- // for trickle ice
919
- this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport);
920
- await this.gatherCandidates().catch((e) => {
921
- log("gatherCandidates failed", e);
922
- });
923
- // connect transports
924
- if (description.type === "answer") {
925
- this.connect().catch((err) => {
926
- log("connect failed", err);
927
- this.secureManager.setConnectionState("failed");
1130
+ this.secureManager.setLocalRole({
1131
+ type: description.type === "offer" ? "offer" : "answer",
1132
+ // A transport without an m-line of its own here only takes the
1133
+ // fallback while it has no role yet; an established association
1134
+ // (such as a BUNDLE split owner) keeps its role.
1135
+ role: (transport) => roleByTransport.get(transport) ??
1136
+ (transport.role === "auto" ? fallbackRole : undefined),
928
1137
  });
929
- }
930
- this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport);
931
- // answerer の stop() は次の自分の offer で交渉する
932
- const hasUnnegotiatedStop = description.type === "answer" && this.settleStoppingTransceivers();
933
- if (this.shouldNegotiationneeded || hasUnnegotiatedStop) {
934
- this.scheduleNegotiationneeded();
935
- }
936
- this.invalidateLastCreatedDescriptions();
937
- return description;
1138
+ // # configure direction
1139
+ if (["answer", "pranswer"].includes(description.type)) {
1140
+ // Only transceivers with an m-line in this answer are negotiated; one
1141
+ // the application added after the offer stays without a direction.
1142
+ const answeredMids = new Set(description.media.map((media) => media.rtp.muxId));
1143
+ for (const t of this.transceiverManager.getTransceivers()) {
1144
+ if (!t.mid || !answeredMids.has(t.mid))
1145
+ continue;
1146
+ if (t.stopped || t.pendingRejection)
1147
+ continue;
1148
+ // The direction the applied answer / pranswer carries (it is what
1149
+ // the peer was told), else the one the transceiver would answer.
1150
+ const answered = description.media.find((media) => media.rtp.muxId === t.mid && media.port !== 0)?.direction;
1151
+ const direction = t.stopping
1152
+ ? "inactive"
1153
+ : (answered ?? (0, utils_1.andDirection)(t.direction, t.offerDirection));
1154
+ t.setCurrentDirection(direction);
1155
+ }
1156
+ }
1157
+ if (description.type === "answer") {
1158
+ // answer の確定で拒否予定の m-line を停止し、RTP pipeline を解放する
1159
+ this.transceiverManager.commitRemoteOffer();
1160
+ // port 0 で答えた m-line (aggressive の inactive など) は offerer 側で拒否として
1161
+ // 停止が確定する。answerer 側も同じ位置を停止確定にし、offerer が新 MID で再利用できるようにする
1162
+ for (const media of description.media) {
1163
+ if (!["audio", "video"].includes(media.kind) || media.port !== 0) {
1164
+ continue;
1165
+ }
1166
+ const transceiver = this.transceiverManager
1167
+ .getTransceivers()
1168
+ .find((t) => t.mid === media.rtp.muxId && !t.stopped);
1169
+ transceiver?.commitStopped({ rejected: true });
1170
+ }
1171
+ }
1172
+ // for trickle ice
1173
+ this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport, this.negotiation.transportByMid);
1174
+ if (description.type === "offer") {
1175
+ this.secureManager.markStagedIceRestartApplied();
1176
+ this.negotiation.settle();
1177
+ // この offer は作成時点までの変更を含む。answer の適用で交渉済みにする
1178
+ this.negotiationNeed.noteAppliedOffer(this.createdOffer.changeSeq);
1179
+ this.setSignalingState("have-local-offer");
1180
+ }
1181
+ else if (description.type === "answer") {
1182
+ this.setSignalingState("stable");
1183
+ }
1184
+ else if (description.type === "pranswer") {
1185
+ // The final answer reuses the restart credentials this pranswer
1186
+ // already signalled.
1187
+ this.secureManager.markStagedIceRestartApplied();
1188
+ this.negotiation.stopUnusedProposalChecks(this.topology.transportsOf(description));
1189
+ this.negotiation.settle();
1190
+ this.setSignalingState("have-local-pranswer");
1191
+ }
1192
+ // A signalingstatechange handler may close the connection.
1193
+ this.assertOpenAfterYield();
1194
+ if (description.type === "offer") {
1195
+ this.secureManager.emitStagedIceCandidates();
1196
+ }
1197
+ else if (description.type === "answer") {
1198
+ this.secureManager.emitCommittedIceCandidates();
1199
+ }
1200
+ if (["offer", "answer", "pranswer"].includes(description.type)) {
1201
+ const prepared = this.negotiation.takePreparedCandidateTransports();
1202
+ for (const transport of prepared) {
1203
+ const mediaIndex = description.media.findIndex((media) => this.negotiation.transportByMid.get(media.rtp.muxId ?? "") ===
1204
+ transport);
1205
+ if (mediaIndex < 0)
1206
+ continue;
1207
+ for (const described of transport.iceTransport.localCandidates) {
1208
+ // Notify a copy: the transport's candidates also render the local
1209
+ // description, whose foundation must stay without "candidate:".
1210
+ const candidate = Object.assign(Object.create(Object.getPrototypeOf(described)), described, {
1211
+ sdpMid: description.media[mediaIndex].rtp.muxId,
1212
+ sdpMLineIndex: mediaIndex,
1213
+ });
1214
+ if (candidate.foundation &&
1215
+ !candidate.foundation.startsWith("candidate:")) {
1216
+ candidate.foundation = `candidate:${candidate.foundation}`;
1217
+ }
1218
+ this.secureManager.onIceCandidate.execute(candidate);
1219
+ }
1220
+ }
1221
+ if (prepared.length > 0) {
1222
+ this.secureManager.onIceCandidate.execute(undefined);
1223
+ }
1224
+ }
1225
+ if (description.type === "answer") {
1226
+ await this.negotiation.commit();
1227
+ this.assertOpenAfterYield();
1228
+ this.completeEndedCurrentGenerations();
1229
+ }
1230
+ // The description is in place: a queued addIceCandidate need not wait
1231
+ // for the gathering below.
1232
+ this.markDescriptionApplied();
1233
+ await this.gatherCandidates().catch((e) => {
1234
+ log("gatherCandidates failed", e);
1235
+ });
1236
+ this.assertOpenAfterYield();
1237
+ // connect transports
1238
+ if (description.type === "answer" || description.type === "pranswer") {
1239
+ if (description.type === "pranswer") {
1240
+ this.activation
1241
+ .connectPending()
1242
+ .catch((err) => log("pending connect failed", err));
1243
+ }
1244
+ this.activation.connect().catch((err) => {
1245
+ log("connect failed", err);
1246
+ this.secureManager.setConnectionState("failed");
1247
+ });
1248
+ }
1249
+ this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport, this.negotiation.transportByMid);
1250
+ if (description.type === "answer")
1251
+ this.iceRestartRequest.settle(this.sdpManager.currentLocalDescription);
1252
+ // answerer の stop() は次の自分の offer で交渉する
1253
+ const hasUnnegotiatedStop = description.type === "answer" && this.settleStoppingTransceivers();
1254
+ if (this.negotiationNeed.recheck || hasUnnegotiatedStop) {
1255
+ this.negotiationNeed.schedule();
1256
+ }
1257
+ this.invalidateLastCreatedDescriptions();
1258
+ return description;
1259
+ });
938
1260
  }
939
1261
  async gatherCandidates() {
940
1262
  await this.secureManager.gatherCandidates();
941
1263
  }
942
- async addIceCandidate(candidateMessage = {}) {
943
- if (this.isClosed) {
944
- throw (0, errors_1.createWebRtcDomException)("InvalidStateError", "is closed");
945
- }
946
- if (!this.remoteDescription || !this.sdpManager._remoteDescription) {
947
- this.pendingRemoteCandidates.push(candidateMessage);
948
- return;
949
- }
950
- await this.applyRemoteIceCandidate(candidateMessage);
951
- }
952
- async applyRemoteIceCandidate(candidateMessage) {
953
- const sdp = this.sdpManager._remoteDescription;
954
- if (!sdp) {
955
- return;
956
- }
957
- const appliedCandidate = await this.secureManager.addIceCandidate(sdp, candidateMessage);
958
- const remoteDescription = this.sdpManager._remoteDescription;
959
- if (!remoteDescription || !appliedCandidate) {
960
- return;
961
- }
962
- if (appliedCandidate.kind === "end-of-candidates") {
963
- for (const mediaIndex of appliedCandidate.mediaIndices) {
964
- const media = remoteDescription.media[mediaIndex];
965
- if (media) {
966
- media.iceCandidatesComplete = true;
967
- }
968
- }
969
- return;
970
- }
971
- for (const mediaIndex of appliedCandidate.mediaIndices) {
972
- const media = remoteDescription.media[mediaIndex];
973
- if (!media) {
1264
+ /**
1265
+ * The local answer commits the codecs it answered for every live media
1266
+ * m-line of the remote offer: the sender, the receive codec / RTX tables, the
1267
+ * remote track codec and TWCC switch now, whatever changed them (a codec
1268
+ * preference, the remote offer or the payload types it uses). Pending
1269
+ * descriptions only added receive keys; the commit replaces the tables.
1270
+ */
1271
+ commitAnsweredCodecs() {
1272
+ for (const transceiver of this.transceiverManager.getTransceivers()) {
1273
+ if (!transceiver.mid ||
1274
+ transceiver.codecs.length === 0 ||
1275
+ transceiver.stopping ||
1276
+ transceiver.stopped ||
1277
+ transceiver.pendingRejection) {
974
1278
  continue;
975
1279
  }
976
- media.iceCandidates.push(appliedCandidate.candidate);
1280
+ const remoteMedia = this.sdpManager.pendingRemoteDescription?.media.find((media) => media.rtp.muxId === transceiver.mid && media.port !== 0);
1281
+ if (remoteMedia && ["audio", "video"].includes(remoteMedia.kind)) {
1282
+ this.transceiverManager.commitAnswerCodecs(transceiver, remoteMedia);
1283
+ }
977
1284
  }
978
1285
  }
979
- async flushPendingRemoteCandidates() {
980
- while (this.pendingRemoteCandidates.length > 0 &&
981
- this.remoteDescription &&
982
- this.sdpManager._remoteDescription) {
983
- const candidate = this.pendingRemoteCandidates.shift();
984
- await this.applyRemoteIceCandidate(candidate ?? null);
1286
+ /** Always called on answer; see commitIceRestartIfAnyStaged on secureManager for why this is unconditional. */
1287
+ async commitIceRestartIfAnyStaged() {
1288
+ this.applyingIceRestart = true;
1289
+ try {
1290
+ await this.secureManager.commitIceRestartIfAnyStaged();
1291
+ }
1292
+ finally {
1293
+ this.applyingIceRestart = false;
985
1294
  }
986
1295
  }
987
- async connect() {
988
- log("start connect");
989
- const res = await Promise.allSettled(this.dtlsTransports.map(async (dtlsTransport) => {
990
- const { iceTransport } = dtlsTransport;
991
- if (iceTransport.state === "connected") {
992
- return;
993
- }
994
- const checkDtlsConnected = () => dtlsTransport.state === "connected";
995
- if (checkDtlsConnected()) {
996
- return;
1296
+ async addIceCandidate(candidateMessage = {}) {
1297
+ return this.enqueueDescriptionOperation(async () => {
1298
+ if (this.isClosed) {
1299
+ throw (0, errors_1.createWebRtcDomException)("InvalidStateError", "is closed");
997
1300
  }
998
- this.secureManager.setConnectionState("connecting");
999
- await iceTransport.start().catch((err) => {
1000
- log("iceTransport.start failed", err);
1001
- throw err;
1002
- });
1003
- if (checkDtlsConnected()) {
1301
+ candidateMessage = (0, remoteCandidates_1.normalizeCandidateUfrag)(candidateMessage);
1302
+ if (!this.remoteDescription || !this.sdpManager._remoteDescription) {
1303
+ const ufrag = candidateMessage?.usernameFragment;
1304
+ if (this.negotiation.isRetiredRemoteUfrag(ufrag)) {
1305
+ throw (0, errors_1.createWebRtcDomException)("OperationError", "ICE generation was rolled back or replaced");
1306
+ }
1307
+ this.remoteCandidates.queued.push(candidateMessage);
1004
1308
  return;
1005
1309
  }
1006
- await dtlsTransport.start().catch((err) => {
1007
- log("dtlsTransport.start failed", err);
1008
- throw err;
1009
- });
1010
- if (this.sctpTransport &&
1011
- this.sctpTransport.dtlsTransport.id === dtlsTransport.id) {
1012
- await this.sctpManager.connectSctp();
1013
- }
1014
- }));
1015
- if (res.find((r) => r.status === "rejected")) {
1016
- this.secureManager.setConnectionState("failed");
1017
- }
1018
- else {
1019
- this.secureManager.setConnectionState("connected");
1020
- }
1310
+ await this.remoteCandidates.apply(candidateMessage);
1311
+ }, { afterApplied: true });
1021
1312
  }
1022
1313
  restartIce() {
1023
- this.needRestart = true;
1314
+ this.iceRestartRequest.request(this.sdpManager.currentLocalDescription, this.sdpManager.pendingLocalDescription);
1024
1315
  this.needNegotiation();
1025
1316
  }
1026
1317
  async setRemoteDescription(sessionDescription) {
1027
- if (sessionDescription instanceof sdp_1.SessionDescription) {
1028
- sessionDescription = sessionDescription.toSdp();
1029
- }
1030
- await this.waitForPendingDescriptionTask();
1031
- let codecPlan = new Map();
1032
- if (sessionDescription.type &&
1033
- sessionDescription.type !== "rollback" &&
1034
- sessionDescription.sdp) {
1035
- const preview = this.sdpManager.parseSdp({
1318
+ return this.enqueueDescriptionOperation(async () => {
1319
+ if (sessionDescription instanceof sdp_1.SessionDescription) {
1320
+ sessionDescription = sessionDescription.toSdp();
1321
+ }
1322
+ await this.waitForPendingDescriptionTask();
1323
+ if (sessionDescription.type === "rollback") {
1324
+ this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription);
1325
+ this.sdpManager.setRemoteDescription(sessionDescription, this.signalingState);
1326
+ this.secureManager.rollbackStagedIceRestart();
1327
+ await this.negotiation.rollback();
1328
+ this.assertOpenAfterYield();
1329
+ await this.activation.cleanupInitialProvisional();
1330
+ this.assertOpenAfterYield();
1331
+ this.setSignalingState("stable");
1332
+ this.negotiationNeed.discardPendingOffer();
1333
+ if (this.negotiationNeed.recheck || this.needRestart) {
1334
+ this.negotiationNeed.schedule();
1335
+ }
1336
+ this.invalidateLastCreatedDescriptions();
1337
+ return;
1338
+ }
1339
+ if (!sessionDescription.type || !sessionDescription.sdp) {
1340
+ throw (0, errors_1.createWebRtcDomException)("OperationError", "Invalid remote description");
1341
+ }
1342
+ const previousPending = this.sdpManager.pendingRemoteDescription;
1343
+ if (previousPending?.type === sessionDescription.type &&
1344
+ previousPending.toJSON().sdp === sessionDescription.sdp) {
1345
+ return;
1346
+ }
1347
+ // Validate the whole proposal before implicit rollback, publication or any
1348
+ // media/transport mutation. A rejected proposal leaves the old transaction.
1349
+ const remoteSdp = this.sdpManager.parseSdp({
1036
1350
  sdp: sessionDescription.sdp,
1037
1351
  isLocal: false,
1038
1352
  signalingState: this.signalingState,
1039
1353
  type: sessionDescription.type,
1040
1354
  });
1041
- // 本適用と同じ対応付けで全 m-line の codec を副作用なしに解決する
1042
- const planned = new Set();
1043
- codecPlan = this.transceiverManager.planRemoteRtpCodecs(preview, (remoteMedia, index) => {
1044
- const transceiver = this.findTransceiverForRemoteMedia(remoteMedia, index, planned);
1045
- if (transceiver)
1046
- planned.add(transceiver);
1047
- return transceiver;
1048
- });
1049
- }
1050
- const needsImplicitLocalRollback = sessionDescription.type === "offer" &&
1051
- ["have-local-offer", "have-local-pranswer"].includes(this.signalingState);
1052
- if (needsImplicitLocalRollback) {
1053
- this.sdpManager.rollbackLocalDescription(this.signalingState);
1054
- for (const transceiver of this.transceiverManager.getTransceivers()) {
1055
- transceiver.pendingLocalOfferCodecs = undefined;
1056
- }
1057
- this.pendingOfferChangeSeq = undefined;
1058
- this.shouldNegotiationneeded = true;
1059
- this.setSignalingState("stable");
1060
- await Promise.resolve();
1061
- }
1062
- // # parse and validate description
1063
- this.assertAnswerKeepsSharedTransports(sessionDescription);
1064
- const remoteSdp = this.sdpManager.setRemoteDescription(sessionDescription, this.signalingState);
1065
- if (!remoteSdp) {
1066
- // 非対応 re-offer などの rollback では元の transceiver 対応を復元する
1067
- const transportsBeforeRollback = this.transceiverManager
1068
- .getTransceivers()
1069
- .map((t) => t.dtlsTransport);
1070
- this.transceiverManager.rollbackRemoteOffer();
1071
- this.closeIdleTransports(transportsBeforeRollback);
1072
- this.setSignalingState("stable");
1073
- if (this.shouldNegotiationneeded) {
1074
- this.scheduleNegotiationneeded();
1355
+ this.validator.validateRemote(remoteSdp, this.signalingState);
1356
+ // Resolve codec compatibility before implicit rollback or any transaction
1357
+ // mutation, then pass the same plan into the staged m-line application.
1358
+ const codecPlan = this.remoteMedia.planCodecs(remoteSdp);
1359
+ // Queued candidates are placed against the parsed proposal before any
1360
+ // state changes or application events (track, transceiver) fire.
1361
+ // Only a non-empty queue awaits, so ordinary offers keep their timing.
1362
+ if (this.remoteCandidates.queued.length > 0) {
1363
+ await this.remoteCandidates.validateQueued(remoteSdp);
1364
+ this.assertOpenAfterYield();
1075
1365
  }
1076
- this.invalidateLastCreatedDescriptions();
1077
- return;
1078
- }
1079
- if (remoteSdp.type === "offer") {
1080
- this.transceiverManager.beginRemoteOffer();
1081
- }
1082
- // # apply description
1083
- const bundleGroups = this.config.bundlePolicy === "disable"
1084
- ? []
1085
- : remoteSdp.group.filter((group) => group.semantic === "BUNDLE");
1086
- const groupOfMid = (mid) => mid == undefined
1087
- ? undefined
1088
- : bundleGroups.find((group) => group.items.includes(mid));
1089
- // ## associate m-lines with transceivers / sctp
1090
- const associated = new Set();
1091
- const entries = remoteSdp.media.map((remoteMedia, index) => {
1092
- if (["audio", "video"].includes(remoteMedia.kind)) {
1093
- let transceiver = this.findTransceiverForRemoteMedia(remoteMedia, index, associated);
1094
- if (!transceiver) {
1095
- if (remoteMedia.port === 0) {
1096
- // 未知の MID の拒否済み m-line には transceiver を関連付けない
1097
- return { remoteMedia, index };
1098
- }
1099
- transceiver = this.addRemoteTransceiver(remoteMedia, index);
1100
- }
1101
- else if (transceiver.mid == null) {
1102
- this.transceiverManager.associateMLine(transceiver, index);
1103
- }
1104
- associated.add(transceiver);
1105
- return { remoteMedia, index, transceiver };
1106
- }
1107
- else if (remoteMedia.kind === "application") {
1108
- let sctpTransport = this.sctpTransport;
1109
- if (!sctpTransport) {
1110
- sctpTransport = this.createSctpTransport();
1111
- sctpTransport.mid = remoteMedia.rtp.muxId;
1112
- }
1113
- return { remoteMedia, index, sctpTransport };
1366
+ const needsImplicitLocalRollback = sessionDescription.type === "offer" &&
1367
+ ["have-local-offer", "have-local-pranswer"].includes(this.signalingState);
1368
+ if (needsImplicitLocalRollback) {
1369
+ this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription);
1370
+ this.sdpManager.rollbackLocalDescription(this.signalingState);
1371
+ this.secureManager.rollbackStagedIceRestart();
1372
+ await this.negotiation.rollback();
1373
+ this.assertOpenAfterYield();
1374
+ await this.activation.cleanupInitialProvisional();
1375
+ this.assertOpenAfterYield();
1376
+ this.negotiationNeed.discardPendingOffer();
1377
+ this.negotiationNeed.recheck = true;
1378
+ this.setSignalingState("stable");
1379
+ // The implicit rollback's "stable" is observable on its own: yield a
1380
+ // task so handlers run before the offer moves to have-remote-offer.
1381
+ await new Promise((resolve) => setImmediate(resolve));
1382
+ this.assertOpenAfterYield();
1114
1383
  }
1115
- else {
1116
- throw new Error("invalid media kind");
1384
+ if (remoteSdp.type === "offer" &&
1385
+ this.signalingState === "have-remote-offer") {
1386
+ // A replacement offer retires the old proposal before it can donate
1387
+ // transceivers, routes or candidates to the new revision.
1388
+ this.negotiation.retireRemoteGeneration(this.sdpManager.pendingRemoteDescription);
1389
+ await this.negotiation.replace(remoteSdp);
1390
+ this.assertOpenAfterYield();
1391
+ this.secureManager.rollbackStagedIceRestart();
1392
+ this.sdpManager.pendingRemoteDescription = undefined;
1117
1393
  }
1118
- });
1119
- if (remoteSdp.type === "offer") {
1120
- this.transceiverManager.releaseUnassociatedReservations(associated, remoteSdp.media.length);
1121
- }
1122
- const ownerOf = (entry) => entry.transceiver ?? entry.sctpTransport;
1123
- // ## transport ownership
1124
- // remote offer の所有関係は bundlePolicy によらず offer の BUNDLE group だけで決まる
1125
- // (max-bundle は自分の offer にだけ効く)。group ごとに 1 つの transport を共有し、
1126
- // 異なる group や group 外の m-line とは共有しない。
1127
- // remote answer では offer で渡した ICE credentials を保つため transport を作り直さない
1128
- // (共有 transport を分割する answer は assertAnswerKeepsSharedTransports で事前に拒否済み)
1129
- const isRemoteOffer = remoteSdp.type === "offer";
1130
- const liveTransport = (transport) => !!transport && transport.state !== "closed";
1131
- const groupTransports = new Map();
1132
- const claimed = new Set();
1133
- for (const group of bundleGroups) {
1134
- const members = entries.filter((entry) => !!ownerOf(entry) &&
1135
- group.items.includes(entry.remoteMedia.rtp.muxId));
1136
- if (members.length === 0) {
1137
- continue;
1394
+ if (remoteSdp.type === "offer" &&
1395
+ this.signalingState !== "have-remote-offer") {
1396
+ this.negotiation.begin();
1138
1397
  }
1139
- // 既存 member の transport を優先し、他の group が使っていれば新しい transport を作る
1140
- let shared = members
1141
- .map((entry) => ownerOf(entry).dtlsTransport)
1142
- .find((transport) => liveTransport(transport) &&
1143
- (!isRemoteOffer || !claimed.has(transport)));
1144
- if (!shared) {
1145
- shared = this.createDtlsTransport({ inheritCredentials: false });
1146
- }
1147
- groupTransports.set(group, shared);
1148
- claimed.add(shared);
1149
- for (const entry of members) {
1150
- const owner = ownerOf(entry);
1151
- if (owner.dtlsTransport !== shared) {
1152
- owner.setDtlsTransport(shared);
1398
+ this.negotiation.validate();
1399
+ this.negotiation.prepare();
1400
+ // Pre-validation rejects every known failure before this point. Should
1401
+ // applying still throw, undo this operation's own changes so no partial
1402
+ // application stays. An offer rolls its transaction back to stable (a
1403
+ // replacement offer has already released the previous proposal); an
1404
+ // answer or pranswer returns to the checkpoint of its pending offer.
1405
+ const openedHere = remoteSdp.type === "offer";
1406
+ const checkpoint = this.negotiation.checkpoint();
1407
+ try {
1408
+ if (remoteSdp.type === "answer" || remoteSdp.type === "pranswer") {
1409
+ this.negotiation.discardStagedRemoteAnswer();
1153
1410
  }
1154
- }
1155
- }
1156
- if (isRemoteOffer) {
1157
- // group 外 (group のない offer を含む) で受け入れた m-line は独立した transport / ICE credentials を持つ
1158
- for (const entry of entries) {
1159
- const owner = ownerOf(entry);
1160
- if (!owner ||
1161
- entry.remoteMedia.port === 0 ||
1162
- groupOfMid(entry.remoteMedia.rtp.muxId)) {
1163
- continue;
1411
+ if (remoteSdp.type === "answer") {
1412
+ this.topology.applyPending(remoteSdp);
1164
1413
  }
1165
- if (!liveTransport(owner.dtlsTransport) ||
1166
- claimed.has(owner.dtlsTransport)) {
1167
- owner.setDtlsTransport(this.createDtlsTransport({ inheritCredentials: false }));
1414
+ const { preserveCurrentTransport, transportUpdates, endOfCandidates, provisionalIce, associated, } = this.remoteMedia.apply(remoteSdp, codecPlan);
1415
+ if (remoteSdp.type === "answer") {
1416
+ // Every answer reaches this point, but it only actually restarts
1417
+ // ICE on transports that staged a restart for the applied offer
1418
+ // (see commitIceRestartIfAnyStaged). Run after every fallible step
1419
+ // and before its remote ICE parameters apply, so only the
1420
+ // generation the applied offer carries is switched.
1421
+ this.secureManager.discardUnappliedIceRestart();
1422
+ await this.commitIceRestartIfAnyStaged();
1423
+ this.assertOpenAfterYield();
1168
1424
  }
1169
- claimed.add(owner.dtlsTransport);
1170
- }
1171
- }
1172
- // ## apply RTP / SCTP (受け入れ判定)
1173
- const acceptedEntries = new Set();
1174
- for (const entry of entries) {
1175
- const { remoteMedia, index } = entry;
1176
- if (entry.transceiver) {
1177
- if (this.transceiverManager.setRemoteRTP(entry.transceiver, remoteMedia, remoteSdp.type, index, codecPlan.get(index) ?? [])) {
1178
- acceptedEntries.add(entry);
1425
+ for (const update of transportUpdates)
1426
+ update();
1427
+ for (const iceTransport of new Set(endOfCandidates)) {
1428
+ iceTransport.deliverRemoteCandidate(undefined);
1179
1429
  }
1180
- }
1181
- else if (entry.sctpTransport) {
1182
- this.sctpManager.setRemoteSCTP(remoteMedia, index);
1183
- acceptedEntries.add(entry);
1184
- }
1185
- }
1186
- // ICE / DTLS パラメータは group で最初に受け入れた member (tag) から適用する
1187
- // (codec 不一致で拒否した member のパラメータは使わない)
1188
- const groupParamSources = new Map();
1189
- for (const group of bundleGroups) {
1190
- for (const mid of group.items) {
1191
- const entry = entries.find((e) => e.remoteMedia.rtp.muxId === mid &&
1192
- e.remoteMedia.port !== 0 &&
1193
- acceptedEntries.has(e));
1194
- if (entry) {
1195
- groupParamSources.set(group, entry);
1196
- break;
1430
+ if (preserveCurrentTransport) {
1431
+ await this.remoteCandidates.deliverSameGenerationDescription(remoteSdp);
1432
+ this.assertOpenAfterYield();
1197
1433
  }
1198
- }
1199
- }
1200
- // ## apply transport parameters
1201
- for (const entry of entries) {
1202
- const { remoteMedia } = entry;
1203
- const owner = ownerOf(entry);
1204
- if (!owner) {
1205
- continue;
1206
- }
1207
- const accepted = acceptedEntries.has(entry);
1208
- const dtlsTransport = owner.dtlsTransport;
1209
- const group = groupOfMid(remoteMedia.rtp.muxId);
1210
- if (remoteMedia.port === 0 ||
1211
- !dtlsTransport ||
1212
- dtlsTransport.state === "closed" ||
1213
- // group 外の拒否 section の transport は使わない
1214
- (!accepted && !group)) {
1215
- continue;
1216
- }
1217
- const iceTransport = dtlsTransport.iceTransport;
1218
- const ownsTransportParams = !group || groupParamSources.get(group) === entry;
1219
- if (ownsTransportParams) {
1220
- if (remoteMedia.iceParams) {
1221
- const renomination = !!this.sdpManager.inactiveRemoteMedia;
1222
- iceTransport.setRemoteParams(remoteMedia.iceParams, renomination);
1223
- // One agent full, one lite: The full agent MUST take the controlling role, and the lite agent MUST take the controlled role
1224
- // RFC 8445 S6.1.1
1225
- if (remoteMedia.iceParams.iceLite &&
1226
- !iceTransport.connection.iceLite) {
1227
- iceTransport.connection.iceControlling = true;
1228
- }
1434
+ // A description that repeats an ICE generation which already ended
1435
+ // on its transport records that end too, so it cannot become current
1436
+ // promising candidates the live transport no longer accepts.
1437
+ this.remoteCandidates.completeSharedTransportMedia(remoteSdp, remoteSdp.media.map((_, index) => index));
1438
+ for (const [iceTransport, media] of provisionalIce) {
1439
+ await this.activation.applyProvisionalIce(iceTransport, media);
1440
+ this.assertOpenAfterYield();
1229
1441
  }
1230
- if (remoteMedia.dtlsParams) {
1231
- dtlsTransport.setRemoteParams(remoteMedia.dtlsParams);
1442
+ if (remoteSdp.type === "answer") {
1443
+ // answer に含まれない既存 m-line は remote 起因の停止として確定する。
1444
+ // 適用していない createOffer が予約しただけの MID (answer する offer にも
1445
+ // current にも m-line がない) は m-line を持たないので停止せず、予約を
1446
+ // 外す (確定した session の後の remote offer がその MID を使える)。その
1447
+ // offer を後で適用するときは生成記録から MID を取り直す。
1448
+ const described = new Set([
1449
+ this.sdpManager.pendingLocalDescription,
1450
+ this.sdpManager.currentLocalDescription,
1451
+ ].flatMap((description) => description?.media.map((media) => media.rtp.muxId) ?? []));
1452
+ for (const transceiver of this.transceiverManager.getTransceivers()) {
1453
+ if (associated.has(transceiver) ||
1454
+ transceiver.mid == undefined ||
1455
+ transceiver.stopped) {
1456
+ continue;
1457
+ }
1458
+ if (described.has(transceiver.mid)) {
1459
+ transceiver.commitStopped({ rejected: true });
1460
+ }
1461
+ else {
1462
+ transceiver.mid = null;
1463
+ transceiver.mLineIndex = undefined;
1464
+ }
1465
+ }
1466
+ // SCTP の予約だけの MID も同じく外す。
1467
+ const sctp = this.sctpTransport;
1468
+ if (sctp?.mid != undefined && !described.has(sctp.mid)) {
1469
+ sctp.mid = undefined;
1470
+ sctp.mLineIndex = undefined;
1471
+ }
1232
1472
  }
1233
1473
  }
1234
- // # add ICE candidates
1235
- remoteMedia.iceCandidates.forEach(iceTransport.addRemoteCandidate);
1236
- if (remoteMedia.iceCandidatesComplete) {
1237
- iceTransport.addRemoteCandidate(undefined);
1474
+ catch (error) {
1475
+ // close() already released everything: recovery would only create
1476
+ // state (or transports) on a closed connection.
1477
+ if (this.isClosed)
1478
+ throw error;
1479
+ if (openedHere) {
1480
+ this.secureManager.rollbackStagedIceRestart();
1481
+ await this.negotiation.rollback();
1482
+ await this.activation.cleanupInitialProvisional();
1483
+ if (this.signalingState !== "stable")
1484
+ this.setSignalingState("stable");
1485
+ }
1486
+ else {
1487
+ await this.negotiation.restoreCheckpoint(checkpoint);
1488
+ }
1489
+ throw error;
1238
1490
  }
1239
- // # set DTLS role
1240
- if (remoteSdp.type === "answer" && remoteMedia.dtlsParams?.role) {
1241
- dtlsTransport.role =
1242
- remoteMedia.dtlsParams.role === "client" ? "server" : "client";
1491
+ if (remoteSdp.type === "offer") {
1492
+ this.sdpManager.applyRemoteDescription(remoteSdp);
1493
+ this.negotiation.settle();
1494
+ this.setSignalingState("have-remote-offer");
1243
1495
  }
1244
- }
1245
- if (remoteSdp.type === "answer") {
1246
- // answer に含まれない既存 m-line は remote 起因の停止として確定する
1247
- for (const transceiver of this.transceiverManager.getTransceivers()) {
1248
- if (!associated.has(transceiver) &&
1249
- transceiver.mid != undefined &&
1250
- !transceiver.stopped) {
1251
- transceiver.commitStopped({ rejected: true });
1252
- }
1496
+ else if (remoteSdp.type === "answer") {
1497
+ this.sdpManager.applyRemoteDescription(remoteSdp);
1498
+ await this.negotiation.commit();
1499
+ this.assertOpenAfterYield();
1500
+ this.completeEndedCurrentGenerations();
1501
+ this.setSignalingState("stable");
1502
+ // Candidates a committed ICE restart gathered with changed servers.
1503
+ this.secureManager.emitCommittedIceCandidates();
1253
1504
  }
1254
- this.closeIdleTransports();
1255
- }
1256
- if (remoteSdp.type === "offer") {
1257
- this.setSignalingState("have-remote-offer");
1258
- }
1259
- else if (remoteSdp.type === "answer") {
1260
- this.setSignalingState("stable");
1261
- }
1262
- else if (remoteSdp.type === "pranswer") {
1263
- this.setSignalingState("have-remote-pranswer");
1264
- }
1265
- await this.flushPendingRemoteCandidates();
1266
- // connect transports
1267
- if (remoteSdp.type === "answer") {
1268
- log("caller start connect");
1269
- this.connect().catch((err) => {
1270
- log("connect failed", err);
1271
- this.secureManager.setConnectionState("failed");
1272
- });
1273
- }
1274
- this.negotiationneeded = false;
1275
- if (remoteSdp.type === "answer" &&
1276
- this.pendingOfferChangeSeq != undefined) {
1277
- this.negotiatedChangeSeq = Math.max(this.negotiatedChangeSeq, this.pendingOfferChangeSeq);
1278
- this.pendingOfferChangeSeq = undefined;
1279
- }
1280
- const hasUnnegotiatedStop = remoteSdp.type === "answer" && this.settleStoppingTransceivers();
1281
- if (this.shouldNegotiationneeded || hasUnnegotiatedStop) {
1282
- this.scheduleNegotiationneeded();
1283
- }
1284
- this.invalidateLastCreatedDescriptions();
1285
- }
1286
- /**
1287
- * remote answer / pranswer の検証 (offerer 側、状態を変更する前に実行する)。
1288
- * local offer で 1 つの transport を共有した m-line を、answer が同じ BUNDLE group に置かずに
1289
- * 異なる ICE credentials で受け入れることはできない (RFC 8843 7.3.2)。共有 transport は分割できず、
1290
- * 新しい transport を作ると offer で渡した ICE credentials とも一致しなくなる。
1291
- * group の記述が MID と一致しなくても remote の ICE credentials が同じなら、同じ transport のまま扱う。
1292
- */
1293
- assertAnswerKeepsSharedTransports(sessionDescription) {
1294
- if (!["answer", "pranswer"].includes(sessionDescription.type ?? "") ||
1295
- !["have-local-offer", "have-local-pranswer"].includes(this.signalingState) ||
1296
- !sessionDescription.sdp ||
1297
- this.config.bundlePolicy === "disable") {
1298
- return;
1299
- }
1300
- const answer = sdp_1.SessionDescription.parse(sessionDescription.sdp);
1301
- const answerGroups = answer.group.filter((g) => g.semantic === "BUNDLE");
1302
- const byTransport = new Map();
1303
- for (const media of answer.media) {
1304
- const mid = media.rtp.muxId;
1305
- if (media.port === 0 || mid == undefined) {
1306
- continue;
1505
+ else if (remoteSdp.type === "pranswer") {
1506
+ this.sdpManager.applyRemoteDescription(remoteSdp);
1507
+ this.negotiation.stopUnusedProposalChecks(this.topology.transportsOf(remoteSdp));
1508
+ this.negotiation.settle();
1509
+ this.setSignalingState("have-remote-pranswer");
1307
1510
  }
1308
- const owner = media.kind === "application"
1309
- ? this.sctpTransport?.mid === mid
1310
- ? this.sctpTransport
1311
- : undefined
1312
- : this.transceiverManager
1313
- .getTransceivers()
1314
- .find((t) => t.mid === mid && !t.stopped);
1315
- const transport = owner?.dtlsTransport;
1316
- if (!transport) {
1317
- continue;
1511
+ await this.remoteCandidates.flushQueued();
1512
+ this.assertOpenAfterYield();
1513
+ // connect transports
1514
+ if (remoteSdp.type === "answer" || remoteSdp.type === "pranswer") {
1515
+ log("caller start connect");
1516
+ if (remoteSdp.type === "pranswer") {
1517
+ this.activation
1518
+ .connectPending()
1519
+ .catch((err) => log("pending connect failed", err));
1520
+ }
1521
+ this.activation.connect().catch((err) => {
1522
+ log("connect failed", err);
1523
+ this.secureManager.setConnectionState("failed");
1524
+ });
1318
1525
  }
1319
- const current = {
1320
- group: answerGroups.find((g) => g.items.includes(mid)),
1321
- credentials: `${media.iceParams?.usernameFragment}:${media.iceParams?.password}`,
1322
- };
1323
- const first = byTransport.get(transport);
1324
- if (!first) {
1325
- byTransport.set(transport, current);
1326
- continue;
1526
+ this.negotiationneeded = false;
1527
+ if (remoteSdp.type === "answer") {
1528
+ // 確定した local offer が反映していた変更は交渉済みになる
1529
+ this.negotiationNeed.commitPendingOffer();
1327
1530
  }
1328
- const sameGroup = !!current.group && current.group === first.group;
1329
- if (!sameGroup && current.credentials !== first.credentials) {
1330
- throw (0, errors_1.createWebRtcDomException)("InvalidAccessError", `mid=${mid} shares a transport in the local offer but the remote ${sessionDescription.type} moves it out of that BUNDLE group`);
1531
+ if (remoteSdp.type === "answer")
1532
+ this.iceRestartRequest.settle(this.sdpManager.currentLocalDescription);
1533
+ const hasUnnegotiatedStop = remoteSdp.type === "answer" && this.settleStoppingTransceivers();
1534
+ if (this.negotiationNeed.recheck || hasUnnegotiatedStop) {
1535
+ this.negotiationNeed.schedule();
1331
1536
  }
1332
- }
1537
+ this.invalidateLastCreatedDescriptions();
1538
+ });
1333
1539
  }
1334
1540
  /**
1335
- * remote m-line に対応する transceiver を探す。MID の一致を優先し、
1336
- * 未関連付け transceiver は同じ offer 内で異なる m-line に割り当てる。
1541
+ * The committed remote description now lies on the committed transports.
1542
+ * A generation that already ended on one of them is ended for every
1543
+ * m-line it carries there too, also one the proposal had split off but
1544
+ * that the answer kept on the same transport.
1337
1545
  */
1338
- findTransceiverForRemoteMedia(remoteMedia, index, associated) {
1339
- const candidates = this.transceiverManager
1340
- .getTransceivers()
1341
- .filter((t) => !associated.has(t) && t.kind === remoteMedia.kind);
1342
- const mid = remoteMedia.rtp.muxId;
1343
- const byMid = mid != undefined ? candidates.find((t) => t.mid === mid) : undefined;
1344
- if (byMid) {
1345
- return byMid;
1346
- }
1347
- if (remoteMedia.port === 0) {
1546
+ completeEndedCurrentGenerations() {
1547
+ const current = this.sdpManager.currentRemoteDescription;
1548
+ if (!current)
1348
1549
  return;
1349
- }
1350
- const unassociated = candidates.filter((t) => t.mid == null && !t.stopping && !t.stopped);
1351
- return unassociated.find((t) => t.mLineIndex === index) ?? unassociated[0];
1550
+ this.remoteCandidates.completeSharedTransportMedia(current, current.media.map((_, index) => index));
1352
1551
  }
1353
1552
  /**
1354
- * remote offer / answer の m-line 用に transceiver を作る。
1355
- * 同じ位置に停止済みの旧 transceiver があれば、それを復活させず新しい receiver/router で置き換える。
1553
+ * remote description の transport 所有で使う独立 transport (別 ICE credentials) を作る。
1554
+ * rollback で使われなくなれば transaction が閉じる。
1356
1555
  */
1357
- addRemoteTransceiver(remoteMedia, index) {
1358
- const dtlsTransport = this.findOrCreateTransport();
1359
- const transceiver = this.transceiverManager.addTransceiver(remoteMedia.kind, dtlsTransport, { direction: "recvonly" }, { remoteMLineIndex: index });
1360
- transceiver.mid = remoteMedia.rtp.muxId ?? null;
1361
- this.secureManager.updateIceConnectionState();
1362
- this.onRemoteTransceiverAdded.execute(transceiver);
1363
- return transceiver;
1556
+ createOwnerTransport() {
1557
+ const transport = this.findOrCreateTransport(true);
1558
+ this.negotiation.rememberOwnerTransport(transport);
1559
+ return transport;
1364
1560
  }
1365
1561
  addTransceiver(trackOrKind, options = {}) {
1366
1562
  const dtlsTransport = this.findOrCreateTransport();
@@ -1382,24 +1578,50 @@ class RTCPeerConnection extends helper_1.EventTarget {
1382
1578
  this.needNegotiation();
1383
1579
  return transceiver.sender;
1384
1580
  }
1385
- async createAnswer() {
1581
+ /** W3C operations chain: createAnswer is ordered with SLD/SRD calls. */
1582
+ createAnswer() {
1583
+ return this.enqueueDescriptionOperation(() => this.createAnswerNow());
1584
+ }
1585
+ /** createAnswer body; call directly only from inside a queued operation. */
1586
+ async createAnswerNow() {
1386
1587
  this.assertNotClosed();
1387
1588
  await this.secureManager.ensureCerts();
1388
- // setCodecPreferences() で無効化された transceiver を再解決する。
1389
- // offer 側と異なり answer は remote offer との交渉結果を使い、
1390
- // sender/receiver の codec 状態も新しい negotiated codec に同期する。
1589
+ const currentRemote = this.sdpManager.currentRemoteDescription;
1590
+ const pendingOffer = this.sdpManager.pendingRemoteDescription;
1591
+ if (currentRemote && pendingOffer?.type === "offer") {
1592
+ // An ICE restart keeps the DTLS association (RFC 8842): stage the new
1593
+ // generation on the existing ICE transport of each BUNDLE owner whose
1594
+ // credentials changed. A MID that moves to a new owner (BUNDLE split)
1595
+ // brings its credentials to its own pending transport instead, so the
1596
+ // transport it leaves is not restarted.
1597
+ const restarted = new Set();
1598
+ for (const [owner, plan] of this.topology.planPending(pendingOffer)
1599
+ .owners) {
1600
+ const live = plan.reuse?.iceTransport;
1601
+ const proposed = pendingOffer.media.find((media) => media.rtp.muxId === owner)?.iceParams?.usernameFragment;
1602
+ const committed = live?.getRemoteParameters()?.usernameFragment;
1603
+ if (live && proposed && committed && proposed !== committed) {
1604
+ restarted.add(live);
1605
+ }
1606
+ }
1607
+ this.secureManager.stageIceRestart(restarted, {
1608
+ answering: pendingOffer,
1609
+ });
1610
+ }
1611
+ await this.topology.preparePending();
1612
+ // setCodecPreferences() は negotiated codec と分けて保持される。
1613
+ // Answer SDP 用の候補だけを再解決し、送受信の live table は commit まで触らない。
1391
1614
  for (const transceiver of this.transceiverManager.getTransceivers()) {
1392
1615
  if (transceiver.codecs.length !== 0 &&
1393
1616
  !transceiver.codecPreferencesNeedResolution) {
1394
1617
  continue;
1395
1618
  }
1396
- // 拒否予定 / 停止済みの m-line は port 0 で answer するため codec を解決しない
1397
1619
  if (transceiver.pendingRejection ||
1398
1620
  transceiver.stopping ||
1399
1621
  transceiver.stopped) {
1400
1622
  continue;
1401
1623
  }
1402
- const remoteDescription = this.sdpManager._remoteDescription;
1624
+ const remoteDescription = this.sdpManager.pendingRemoteDescription;
1403
1625
  const remoteMedia = remoteDescription?.media.find((media) => media.rtp.muxId != undefined &&
1404
1626
  media.rtp.muxId === transceiver.mid &&
1405
1627
  media.kind === transceiver.kind) ??
@@ -1407,7 +1629,9 @@ class RTCPeerConnection extends helper_1.EventTarget {
1407
1629
  ? remoteDescription?.media[transceiver.mLineIndex]
1408
1630
  : undefined);
1409
1631
  if (remoteMedia && ["audio", "video"].includes(remoteMedia.kind)) {
1410
- this.transceiverManager.resyncAnswerCodecs(transceiver, remoteMedia);
1632
+ // The live sender/receiver tables follow at the local answer commit
1633
+ // (commitAnswerCodecs), so pending RTP keeps the current codecs.
1634
+ this.transceiverManager.refreshAnswerCodecs(transceiver, remoteMedia);
1411
1635
  }
1412
1636
  else {
1413
1637
  this.transceiverManager.assignTransceiverCodecs(transceiver);
@@ -1421,18 +1645,30 @@ class RTCPeerConnection extends helper_1.EventTarget {
1421
1645
  transceivers: this.transceiverManager.getTransceivers(),
1422
1646
  sctpTransport: this.sctpTransport,
1423
1647
  signalingState: this.signalingState,
1648
+ transportByMid: this.negotiation.transportByMid,
1424
1649
  });
1425
1650
  const createdAnswer = description.toJSON();
1426
1651
  this.lastCreatedAnswer = createdAnswer;
1427
1652
  return createdAnswer;
1428
1653
  }
1654
+ /**
1655
+ * A description operation resumes after an await or after an event it
1656
+ * fired: when close() ran in the meantime (an event handler, a timer) it
1657
+ * stops before changing anything, and the operation fails with
1658
+ * InvalidStateError (W3C).
1659
+ */
1660
+ assertOpenAfterYield() {
1661
+ this.assertNotClosed();
1662
+ }
1429
1663
  assertNotClosed() {
1430
1664
  if (this.isClosed) {
1431
1665
  throw (0, errors_1.createWebRtcDomException)("InvalidStateError", "RTCPeerConnection is closed");
1432
1666
  }
1433
1667
  }
1434
1668
  setSignalingState(state) {
1435
- if (this.signalingState === state) {
1669
+ // "closed" is final: an operation still finishing after close() must not
1670
+ // move the state back.
1671
+ if (this.signalingState === state || this.signalingState === "closed") {
1436
1672
  return;
1437
1673
  }
1438
1674
  log("signalingStateChange", state);
@@ -1472,15 +1708,22 @@ class RTCPeerConnection extends helper_1.EventTarget {
1472
1708
  }
1473
1709
  return (0, stats_1.buildStatsReport)(stats, this.transceiverManager.getStatsRootIds(selector));
1474
1710
  }
1711
+ /**
1712
+ * `"closed"` is final: a description operation that close() overtook
1713
+ * rejects with InvalidStateError and changes nothing more, and every
1714
+ * transport only the negotiation holds (proposal, pending-only, prepared)
1715
+ * stops with the live ones.
1716
+ */
1475
1717
  async close() {
1476
1718
  if (this.isClosed)
1477
1719
  return;
1478
1720
  this.isClosed = true;
1479
- this.pendingRemoteCandidates.length = 0;
1721
+ this.remoteCandidates.queued.length = 0;
1480
1722
  this.setSignalingState("closed");
1481
1723
  this.transceiverManager.close();
1482
1724
  // SCTP ABORT は DTLS/ICE が生きている間に送る(close は abrupt であり SHUTDOWN ではない)
1483
1725
  await this.sctpManager.close();
1726
+ await this.negotiation.dispose();
1484
1727
  await this.secureManager.close();
1485
1728
  // 公開 Event を完了させ、購読者・クロージャが PeerConnection を保持し続けないようにする
1486
1729
  this.completePeerEvents();
@@ -1506,191 +1749,11 @@ class RTCPeerConnection extends helper_1.EventTarget {
1506
1749
  }
1507
1750
  }
1508
1751
  exports.RTCPeerConnection = RTCPeerConnection;
1509
- const MLineReuseModes = ["compatible", "aggressive"];
1510
- const findCodecByMimeType = (codecs, target) => codecs.find((localCodec) => (0, codecCompatibility_1.normalizeCodecMimeType)(localCodec.mimeType) ===
1511
- (0, codecCompatibility_1.normalizeCodecMimeType)(target.mimeType))
1512
- ? target
1513
- : undefined;
1514
- exports.findCodecByMimeType = findCodecByMimeType;
1515
- function assignDynamicPayloadTypes(config) {
1516
- for (const [i, codecParams] of (0, helper_1.enumerate)([
1517
- ...(config.codecs.audio || []),
1518
- ...(config.codecs.video || []),
1519
- ])) {
1520
- if (codecParams.payloadType != undefined) {
1521
- continue;
1522
- }
1523
- codecParams.payloadType = 96 + i;
1524
- switch (codecParams.name.toLowerCase()) {
1525
- case "rtx":
1526
- {
1527
- codecParams.parameters = `apt=${codecParams.payloadType - 1}`;
1528
- }
1529
- break;
1530
- case "red":
1531
- {
1532
- if (codecParams.contentType === "audio") {
1533
- const redundant = codecParams.payloadType + 1;
1534
- codecParams.parameters = `${redundant}/${redundant}`;
1535
- codecParams.payloadType = 63;
1536
- }
1537
- }
1538
- break;
1539
- }
1540
- }
1541
- }
1542
- function generateDefaultPeerConfig() {
1543
- return {
1544
- codecs: (0, media_1.defaultCodecs)(),
1545
- headerExtensions: {
1546
- audio: [],
1547
- video: [],
1548
- },
1549
- iceTransportPolicy: "all",
1550
- iceLite: false,
1551
- iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
1552
- icePortRange: undefined,
1553
- iceInterfaceAddresses: undefined,
1554
- iceAdditionalHostAddresses: undefined,
1555
- iceUseIpv4: true,
1556
- iceUseIpv6: true,
1557
- iceUseTcp: false,
1558
- iceTcpPassive: true,
1559
- iceStunGatherTimeout: undefined,
1560
- iceTurnConnectTimeout: undefined,
1561
- turnTransport: undefined,
1562
- turnTlsOptions: undefined,
1563
- turnUdpFamily: undefined,
1564
- iceFilterStunResponse: undefined,
1565
- iceFilterCandidatePair: undefined,
1566
- icePasswordPrefix: undefined,
1567
- iceUseLinkLocalAddress: undefined,
1568
- dtls: {},
1569
- bundlePolicy: "max-compat",
1570
- rtcpMuxPolicy: "require",
1571
- iceCandidatePoolSize: 0,
1572
- certificates: [],
1573
- debug: {},
1574
- midSuffix: false,
1575
- forceTurnTCP: false,
1576
- maxMessageSize: sctp_1.DEFAULT_MAX_MESSAGE_SIZE,
1577
- sctp: { mtu: src_1.DEFAULT_SCTP_MTU },
1578
- pendingRtp: false,
1579
- mLineReuse: "compatible",
1580
- };
1581
- }
1582
- exports.defaultPeerConfig = generateDefaultPeerConfig();
1583
- function normalizePeerConfiguration(config) {
1584
- const input = Object(config ?? {});
1585
- const normalizedConfig = { ...input };
1586
- if (input.sctp !== undefined) {
1587
- normalizedConfig.sctp = { ...input.sctp };
1588
- }
1589
- if (input.bundlePolicy === "balanced") {
1590
- normalizedConfig.bundlePolicy = "max-compat";
1591
- }
1592
- if ("certificates" in input) {
1593
- if (input.certificates === undefined) {
1594
- normalizedConfig.certificates = undefined;
1595
- }
1596
- else if (!Array.isArray(input.certificates) ||
1597
- input.certificates.some((certificate) => certificate == null)) {
1598
- throw (0, errors_1.createWebRtcTypeError)("certificates must be an array of RTCCertificate");
1599
- }
1600
- else {
1601
- normalizedConfig.certificates = [...input.certificates];
1602
- }
1603
- }
1604
- if ("iceCandidatePoolSize" in input) {
1605
- normalizedConfig.iceCandidatePoolSize = coerceUnsignedShort(input.iceCandidatePoolSize, "iceCandidatePoolSize");
1606
- }
1607
- return normalizedConfig;
1608
- }
1609
- function coerceUnsignedShort(value, name) {
1610
- const coerced = Number(value);
1611
- if (!Number.isFinite(coerced) ||
1612
- !Number.isInteger(coerced) ||
1613
- coerced < 0 ||
1614
- coerced > 65535) {
1615
- throw (0, errors_1.createWebRtcTypeError)(`${name} must be an unsigned short`);
1616
- }
1617
- return coerced;
1618
- }
1619
- function hasSameCertificates(left, right) {
1620
- return (left.length === right.length &&
1621
- left.every((certificate, index) => certificate === right[index]));
1622
- }
1623
- function clonePeerConfiguration(config) {
1624
- return {
1625
- ...config,
1626
- codecs: {
1627
- audio: config.codecs.audio ? [...config.codecs.audio] : undefined,
1628
- video: config.codecs.video ? [...config.codecs.video] : undefined,
1629
- },
1630
- headerExtensions: {
1631
- audio: config.headerExtensions.audio
1632
- ? [...config.headerExtensions.audio]
1633
- : undefined,
1634
- video: config.headerExtensions.video
1635
- ? [...config.headerExtensions.video]
1636
- : undefined,
1637
- },
1638
- iceServers: config.iceServers.map((server) => ({
1639
- ...server,
1640
- urls: Array.isArray(server.urls) ? [...server.urls] : server.urls,
1641
- })),
1642
- icePortRange: config.icePortRange
1643
- ? [...config.icePortRange]
1644
- : undefined,
1645
- iceAdditionalHostAddresses: config.iceAdditionalHostAddresses
1646
- ? [...config.iceAdditionalHostAddresses]
1647
- : undefined,
1648
- dtls: { ...config.dtls },
1649
- certificates: [...config.certificates],
1650
- debug: { ...config.debug },
1651
- sctp: { ...config.sctp },
1652
- pendingRtp: typeof config.pendingRtp === "object" && config.pendingRtp != undefined
1653
- ? { ...config.pendingRtp }
1654
- : config.pendingRtp,
1655
- };
1656
- }
1657
- class RTCTrackEvent {
1658
- constructor(init) {
1659
- Object.defineProperty(this, "type", {
1660
- enumerable: true,
1661
- configurable: true,
1662
- writable: true,
1663
- value: "track"
1664
- });
1665
- Object.defineProperty(this, "track", {
1666
- enumerable: true,
1667
- configurable: true,
1668
- writable: true,
1669
- value: void 0
1670
- });
1671
- Object.defineProperty(this, "streams", {
1672
- enumerable: true,
1673
- configurable: true,
1674
- writable: true,
1675
- value: void 0
1676
- });
1677
- Object.defineProperty(this, "transceiver", {
1678
- enumerable: true,
1679
- configurable: true,
1680
- writable: true,
1681
- value: void 0
1682
- });
1683
- Object.defineProperty(this, "receiver", {
1684
- enumerable: true,
1685
- configurable: true,
1686
- writable: true,
1687
- value: void 0
1688
- });
1689
- this.track = init.track;
1690
- this.streams = [...init.streams];
1691
- this.transceiver = init.transceiver;
1692
- this.receiver = init.receiver;
1693
- }
1752
+ /** Same payload types with the same codec, in the same order. */
1753
+ function sameCodecList(a, b) {
1754
+ return (a.length === b.length &&
1755
+ a.every((codec, index) => codec.payloadType === b[index].payloadType &&
1756
+ codec.mimeType.toLowerCase() === b[index].mimeType.toLowerCase() &&
1757
+ (codec.parameters ?? "") === (b[index].parameters ?? "")));
1694
1758
  }
1695
- exports.RTCTrackEvent = RTCTrackEvent;
1696
1759
  //# sourceMappingURL=peerConnection.js.map