werift 0.25.1 → 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 (371) 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 +24263 -16477
  123. package/lib/nonstandard/index.mjs +9272 -6178
  124. package/lib/polyfill/dom.mjs +24872 -20543
  125. package/lib/polyfill/index.mjs +24872 -20543
  126. package/lib/rtp/src/codec/av1.d.ts +61 -1
  127. package/lib/rtp/src/codec/av1.js +332 -33
  128. package/lib/rtp/src/codec/av1.js.map +1 -1
  129. package/lib/rtp/src/codec/base.d.ts +49 -1
  130. package/lib/rtp/src/codec/base.js +81 -1
  131. package/lib/rtp/src/codec/base.js.map +1 -1
  132. package/lib/rtp/src/codec/g711.d.ts +37 -0
  133. package/lib/rtp/src/codec/g711.js +109 -0
  134. package/lib/rtp/src/codec/g711.js.map +1 -0
  135. package/lib/rtp/src/codec/g722.d.ts +31 -0
  136. package/lib/rtp/src/codec/g722.js +82 -0
  137. package/lib/rtp/src/codec/g722.js.map +1 -0
  138. package/lib/rtp/src/codec/h264.d.ts +81 -7
  139. package/lib/rtp/src/codec/h264.js +382 -21
  140. package/lib/rtp/src/codec/h264.js.map +1 -1
  141. package/lib/rtp/src/codec/h265.d.ts +101 -0
  142. package/lib/rtp/src/codec/h265.js +615 -0
  143. package/lib/rtp/src/codec/h265.js.map +1 -0
  144. package/lib/rtp/src/codec/index.d.ts +6 -1
  145. package/lib/rtp/src/codec/index.js +25 -0
  146. package/lib/rtp/src/codec/index.js.map +1 -1
  147. package/lib/rtp/src/codec/mp4a.d.ts +88 -0
  148. package/lib/rtp/src/codec/mp4a.js +386 -0
  149. package/lib/rtp/src/codec/mp4a.js.map +1 -0
  150. package/lib/rtp/src/codec/opus.d.ts +14 -2
  151. package/lib/rtp/src/codec/opus.js +32 -2
  152. package/lib/rtp/src/codec/opus.js.map +1 -1
  153. package/lib/rtp/src/codec/telephoneEvent.d.ts +102 -0
  154. package/lib/rtp/src/codec/telephoneEvent.js +176 -0
  155. package/lib/rtp/src/codec/telephoneEvent.js.map +1 -0
  156. package/lib/rtp/src/codec/vp8.d.ts +26 -1
  157. package/lib/rtp/src/codec/vp8.js +76 -2
  158. package/lib/rtp/src/codec/vp8.js.map +1 -1
  159. package/lib/rtp/src/codec/vp9.d.ts +25 -1
  160. package/lib/rtp/src/codec/vp9.js +64 -2
  161. package/lib/rtp/src/codec/vp9.js.map +1 -1
  162. package/lib/rtp/src/const.d.ts +1 -0
  163. package/lib/rtp/src/const.js +5 -0
  164. package/lib/rtp/src/const.js.map +1 -0
  165. package/lib/rtp/src/extra/container/mp4/container.js +4 -1
  166. package/lib/rtp/src/extra/container/mp4/container.js.map +1 -1
  167. package/lib/rtp/src/extra/container/mp4/h264.d.ts +26 -0
  168. package/lib/rtp/src/extra/container/mp4/h264.js +54 -0
  169. package/lib/rtp/src/extra/container/mp4/h264.js.map +1 -1
  170. package/lib/rtp/src/extra/container/webm/container.d.ts +1 -1
  171. package/lib/rtp/src/extra/container/webm/ebml/ebml.d.ts +6 -0
  172. package/lib/rtp/src/extra/container/webm/ebml/ebml.js +20 -1
  173. package/lib/rtp/src/extra/container/webm/ebml/ebml.js.map +1 -1
  174. package/lib/rtp/src/extra/processor/depacketizer.d.ts +1 -1
  175. package/lib/rtp/src/extra/processor/depacketizer.js +1 -1
  176. package/lib/rtp/src/extra/processor/depacketizer.js.map +1 -1
  177. package/lib/rtp/src/extra/processor/depacketizerCallback.d.ts +1 -11
  178. package/lib/rtp/src/extra/processor/depacketizerTransformer.d.ts +1 -1
  179. package/lib/rtp/src/extra/processor/dtxCallback.d.ts +1 -11
  180. package/lib/rtp/src/extra/processor/interface.d.ts +16 -11
  181. package/lib/rtp/src/extra/processor/interface.js.map +1 -1
  182. package/lib/rtp/src/extra/processor/jitterBufferCallback.d.ts +1 -11
  183. package/lib/rtp/src/extra/processor/jitterBufferTransformer.d.ts +1 -1
  184. package/lib/rtp/src/extra/processor/mp4.d.ts +16 -0
  185. package/lib/rtp/src/extra/processor/mp4.js +55 -21
  186. package/lib/rtp/src/extra/processor/mp4.js.map +1 -1
  187. package/lib/rtp/src/extra/processor/nack.d.ts +1 -1
  188. package/lib/rtp/src/extra/processor/nack.js +1 -1
  189. package/lib/rtp/src/extra/processor/nack.js.map +1 -1
  190. package/lib/rtp/src/extra/processor/nackHandlerCallback.d.ts +1 -11
  191. package/lib/rtp/src/extra/processor/ntpTime.js.map +1 -1
  192. package/lib/rtp/src/extra/processor/ntpTimeCallback.d.ts +1 -11
  193. package/lib/rtp/src/extra/processor/rtcpCallback.d.ts +1 -1
  194. package/lib/rtp/src/extra/processor/rtcpCallback.js.map +1 -1
  195. package/lib/rtp/src/extra/processor/rtpCallback.d.ts +1 -1
  196. package/lib/rtp/src/extra/processor/rtpCallback.js +1 -1
  197. package/lib/rtp/src/extra/processor/rtpCallback.js.map +1 -1
  198. package/lib/rtp/src/extra/processor/rtpStream.d.ts +2 -2
  199. package/lib/rtp/src/extra/processor/rtpStream.js.map +1 -1
  200. package/lib/rtp/src/extra/processor/rtpTime.js.map +1 -1
  201. package/lib/rtp/src/extra/processor/rtpTimeCallback.d.ts +1 -11
  202. package/lib/rtp/src/extra/processor/webm.d.ts +27 -0
  203. package/lib/rtp/src/extra/processor/webm.js +43 -16
  204. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  205. package/lib/rtp/src/extra/processor/webmCallback.js +6 -1
  206. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  207. package/lib/rtp/src/extra/processor/webmStream.js.map +1 -1
  208. package/lib/rtp/src/helper.d.ts +2 -2
  209. package/lib/rtp/src/helper.js +2 -6
  210. package/lib/rtp/src/helper.js.map +1 -1
  211. package/lib/rtp/src/index.d.ts +4 -2
  212. package/lib/rtp/src/index.js +4 -2
  213. package/lib/rtp/src/index.js.map +1 -1
  214. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js +2 -1
  215. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js.map +1 -1
  216. package/lib/rtp/src/rtcp/rtcp.js +2 -1
  217. package/lib/rtp/src/rtcp/rtcp.js.map +1 -1
  218. package/lib/rtp/src/rtcp/sr.d.ts +4 -3
  219. package/lib/rtp/src/rtcp/sr.js +3 -2
  220. package/lib/rtp/src/rtcp/sr.js.map +1 -1
  221. package/lib/rtp/src/rtp/mediaClock.d.ts +283 -0
  222. package/lib/rtp/src/rtp/mediaClock.js +655 -0
  223. package/lib/rtp/src/rtp/mediaClock.js.map +1 -0
  224. package/lib/rtp/src/srtp/cipher/ctr.d.ts +2 -2
  225. package/lib/rtp/src/srtp/cipher/ctr.js +1 -1
  226. package/lib/rtp/src/srtp/cipher/ctr.js.map +1 -1
  227. package/lib/rtp/src/srtp/cipher/gcm.d.ts +1 -1
  228. package/lib/rtp/src/srtp/cipher/gcm.js +1 -1
  229. package/lib/rtp/src/srtp/cipher/gcm.js.map +1 -1
  230. package/lib/rtp/src/srtp/context/context.d.ts +29 -1
  231. package/lib/rtp/src/srtp/context/context.js +78 -24
  232. package/lib/rtp/src/srtp/context/context.js.map +1 -1
  233. package/lib/rtp/src/srtp/context/srtp.js +23 -15
  234. package/lib/rtp/src/srtp/context/srtp.js.map +1 -1
  235. package/lib/rtp/src/util.d.ts +59 -6
  236. package/lib/rtp/src/util.js +88 -10
  237. package/lib/rtp/src/util.js.map +1 -1
  238. package/lib/sctp/src/index.d.ts +4 -3
  239. package/lib/sctp/src/index.js +10 -8
  240. package/lib/sctp/src/index.js.map +1 -1
  241. package/lib/sctp/src/sctp.d.ts +11 -2
  242. package/lib/sctp/src/sctp.js +47 -28
  243. package/lib/sctp/src/sctp.js.map +1 -1
  244. package/lib/webrtc/src/api/peerConfig.d.ts +264 -0
  245. package/lib/webrtc/src/api/peerConfig.js +250 -0
  246. package/lib/webrtc/src/api/peerConfig.js.map +1 -0
  247. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +36 -0
  248. package/lib/webrtc/src/api/peerConnectionEvents.js +44 -0
  249. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -0
  250. package/lib/webrtc/src/dataChannel.d.ts +1 -1
  251. package/lib/webrtc/src/dataChannel.js +1 -1
  252. package/lib/webrtc/src/dataChannel.js.map +1 -1
  253. package/lib/webrtc/src/index.d.ts +2 -2
  254. package/lib/webrtc/src/index.js +2 -2
  255. package/lib/webrtc/src/index.js.map +1 -1
  256. package/lib/webrtc/src/media/codec.d.ts +18 -0
  257. package/lib/webrtc/src/media/codec.js +43 -2
  258. package/lib/webrtc/src/media/codec.js.map +1 -1
  259. package/lib/webrtc/src/media/codecCompatibility.d.ts +5 -0
  260. package/lib/webrtc/src/media/codecCompatibility.js +15 -4
  261. package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
  262. package/lib/webrtc/src/media/index.d.ts +1 -1
  263. package/lib/webrtc/src/media/index.js +1 -1
  264. package/lib/webrtc/src/media/index.js.map +1 -1
  265. package/lib/webrtc/src/media/receiver/nack.js +3 -4
  266. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  267. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  268. package/lib/webrtc/src/media/router.d.ts +116 -5
  269. package/lib/webrtc/src/media/router.js +281 -29
  270. package/lib/webrtc/src/media/router.js.map +1 -1
  271. package/lib/webrtc/src/media/rtpReceiver.d.ts +107 -12
  272. package/lib/webrtc/src/media/rtpReceiver.js +255 -28
  273. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  274. package/lib/webrtc/src/media/rtpSender.d.ts +56 -3
  275. package/lib/webrtc/src/media/rtpSender.js +180 -21
  276. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  277. package/lib/webrtc/src/media/rtpTransceiver.d.ts +94 -1
  278. package/lib/webrtc/src/media/rtpTransceiver.js +111 -2
  279. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  280. package/lib/webrtc/src/media/sender/senderBWE.d.ts +2 -1
  281. package/lib/webrtc/src/media/sender/senderBWE.js +22 -10
  282. package/lib/webrtc/src/media/sender/senderBWE.js.map +1 -1
  283. package/lib/webrtc/src/media/track.d.ts +1 -1
  284. package/lib/webrtc/src/media/track.js +1 -1
  285. package/lib/webrtc/src/media/track.js.map +1 -1
  286. package/lib/webrtc/src/negotiation/bundleTopology.d.ts +107 -0
  287. package/lib/webrtc/src/negotiation/bundleTopology.js +380 -0
  288. package/lib/webrtc/src/negotiation/bundleTopology.js.map +1 -0
  289. package/lib/webrtc/src/negotiation/descriptionValidation.d.ts +51 -0
  290. package/lib/webrtc/src/negotiation/descriptionValidation.js +261 -0
  291. package/lib/webrtc/src/negotiation/descriptionValidation.js.map +1 -0
  292. package/lib/webrtc/src/negotiation/iceRestartRequest.d.ts +21 -0
  293. package/lib/webrtc/src/negotiation/iceRestartRequest.js +61 -0
  294. package/lib/webrtc/src/negotiation/iceRestartRequest.js.map +1 -0
  295. package/lib/webrtc/src/negotiation/internalState.d.ts +34 -0
  296. package/lib/webrtc/src/negotiation/internalState.js +21 -0
  297. package/lib/webrtc/src/negotiation/internalState.js.map +1 -0
  298. package/lib/webrtc/src/negotiation/negotiationNeeded.d.ts +44 -0
  299. package/lib/webrtc/src/negotiation/negotiationNeeded.js +118 -0
  300. package/lib/webrtc/src/negotiation/negotiationNeeded.js.map +1 -0
  301. package/lib/webrtc/src/negotiation/remoteCandidates.d.ts +86 -0
  302. package/lib/webrtc/src/negotiation/remoteCandidates.js +344 -0
  303. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -0
  304. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +71 -0
  305. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +398 -0
  306. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -0
  307. package/lib/webrtc/src/negotiation/transportActivation.d.ts +59 -0
  308. package/lib/webrtc/src/negotiation/transportActivation.js +345 -0
  309. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -0
  310. package/lib/webrtc/src/negotiationTransaction.d.ts +233 -0
  311. package/lib/webrtc/src/negotiationTransaction.js +591 -0
  312. package/lib/webrtc/src/negotiationTransaction.js.map +1 -0
  313. package/lib/webrtc/src/nonstandard/dummyMedia.js +20 -6
  314. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  315. package/lib/webrtc/src/nonstandard/index.d.ts +1 -1
  316. package/lib/webrtc/src/nonstandard/index.js +1 -1
  317. package/lib/webrtc/src/nonstandard/index.js.map +1 -1
  318. package/lib/webrtc/src/nonstandard/navigator.js.map +1 -1
  319. package/lib/webrtc/src/nonstandard/recorder/writer/index.d.ts +1 -1
  320. package/lib/webrtc/src/nonstandard/recorder/writer/index.js.map +1 -1
  321. package/lib/webrtc/src/nonstandard/recorder/writer/webm.d.ts +2 -2
  322. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +2 -2
  323. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  324. package/lib/webrtc/src/nonstandard/userMedia/packetizer.d.ts +4 -4
  325. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js +61 -306
  326. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js.map +1 -1
  327. package/lib/webrtc/src/nonstandard/userMedia.d.ts +4 -2
  328. package/lib/webrtc/src/nonstandard/userMedia.js +43 -9
  329. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  330. package/lib/webrtc/src/peerConnection.d.ts +132 -237
  331. package/lib/webrtc/src/peerConnection.js +971 -906
  332. package/lib/webrtc/src/peerConnection.js.map +1 -1
  333. package/lib/webrtc/src/polyfill/api.d.ts +5 -5
  334. package/lib/webrtc/src/polyfill/api.js.map +1 -1
  335. package/lib/webrtc/src/polyfill/index.js.map +1 -1
  336. package/lib/webrtc/src/polyfill/install.js +1 -1
  337. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  338. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  339. package/lib/webrtc/src/polyfill/registers/mp4Webm.js.map +1 -1
  340. package/lib/webrtc/src/polyfill/registers/rtpRtcp.js.map +1 -1
  341. package/lib/webrtc/src/polyfill/selectSettings.js.map +1 -1
  342. package/lib/webrtc/src/polyfill/sourceIo.js.map +1 -1
  343. package/lib/webrtc/src/sctpManager.d.ts +66 -2
  344. package/lib/webrtc/src/sctpManager.js +122 -5
  345. package/lib/webrtc/src/sctpManager.js.map +1 -1
  346. package/lib/webrtc/src/sdp.js.map +1 -1
  347. package/lib/webrtc/src/sdpManager.d.ts +55 -11
  348. package/lib/webrtc/src/sdpManager.js +367 -89
  349. package/lib/webrtc/src/sdpManager.js.map +1 -1
  350. package/lib/webrtc/src/secureTransportManager.d.ts +38 -25
  351. package/lib/webrtc/src/secureTransportManager.js +130 -34
  352. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  353. package/lib/webrtc/src/transceiverManager.d.ts +62 -18
  354. package/lib/webrtc/src/transceiverManager.js +266 -105
  355. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  356. package/lib/webrtc/src/transport/dtls.d.ts +11 -2
  357. package/lib/webrtc/src/transport/dtls.js +37 -13
  358. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  359. package/lib/webrtc/src/transport/ice.d.ts +254 -7
  360. package/lib/webrtc/src/transport/ice.js +608 -52
  361. package/lib/webrtc/src/transport/ice.js.map +1 -1
  362. package/lib/webrtc/src/transport/iceCandidateAttribute.d.ts +98 -0
  363. package/lib/webrtc/src/transport/iceCandidateAttribute.js +129 -0
  364. package/lib/webrtc/src/transport/iceCandidateAttribute.js.map +1 -0
  365. package/lib/webrtc/src/transport/sctp.d.ts +4 -1
  366. package/lib/webrtc/src/transport/sctp.js +83 -17
  367. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  368. package/lib/webrtc/src/utils.d.ts +3 -3
  369. package/lib/webrtc/src/utils.js +1 -1
  370. package/lib/webrtc/src/utils.js.map +1 -1
  371. package/package.json +13 -14
@@ -1,19 +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
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");
11
20
  const sctpManager_1 = require("./sctpManager");
12
21
  const sdp_1 = require("./sdp");
13
22
  const sdpManager_1 = require("./sdpManager");
14
23
  const secureTransportManager_1 = require("./secureTransportManager");
15
- const sctp_1 = require("./transport/sctp");
16
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; } });
17
30
  const log = (0, common_1.debug)("werift:packages/webrtc/src/peerConnection.ts");
18
31
  /**
19
32
  * W3C compatibility notes kept near the public RTCPeerConnection surface so the
@@ -39,6 +52,23 @@ const log = (0, common_1.debug)("werift:packages/webrtc/src/peerConnection.ts");
39
52
  * even when generated docs are not committed in the same change.
40
53
  */
41
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
+ }
42
72
  get ondatachannel() {
43
73
  return this.eventHandlers.ondatachannel ?? null;
44
74
  }
@@ -111,7 +141,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
111
141
  enumerable: true,
112
142
  configurable: true,
113
143
  writable: true,
114
- value: generateDefaultPeerConfig()
144
+ value: (0, peerConfig_1.generateDefaultPeerConfig)()
115
145
  });
116
146
  Object.defineProperty(this, "signalingState", {
117
147
  enumerable: true,
@@ -119,77 +149,90 @@ class RTCPeerConnection extends helper_1.EventTarget {
119
149
  writable: true,
120
150
  value: "stable"
121
151
  });
122
- Object.defineProperty(this, "negotiationneeded", {
152
+ Object.defineProperty(this, "negotiationNeed", {
123
153
  enumerable: true,
124
154
  configurable: true,
125
155
  writable: true,
126
- 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
+ })
127
168
  });
128
- /**同じ tick の複数の変更で negotiationneeded を重複発火しないための予約フラグ */
129
- Object.defineProperty(this, "negotiationneededScheduled", {
169
+ Object.defineProperty(this, "iceRestartRequest", {
130
170
  enumerable: true,
131
171
  configurable: true,
132
172
  writable: true,
133
- value: false
173
+ value: new iceRestartRequest_1.IceRestartRequest()
134
174
  });
135
- /**交渉が必要な変更の通し番号 */
136
- Object.defineProperty(this, "negotiationChangeSeq", {
175
+ Object.defineProperty(this, "router", {
137
176
  enumerable: true,
138
177
  configurable: true,
139
178
  writable: true,
140
- value: 0
179
+ value: new media_1.RtpRouter()
141
180
  });
142
- /**answer まで確定した local offer が反映している変更の通し番号 */
143
- Object.defineProperty(this, "negotiatedChangeSeq", {
181
+ Object.defineProperty(this, "sdpManager", {
144
182
  enumerable: true,
145
183
  configurable: true,
146
184
  writable: true,
147
- value: 0
185
+ value: void 0
148
186
  });
149
- /**適用中の local offer が反映している変更の通し番号 (rollback で破棄) */
150
- Object.defineProperty(this, "pendingOfferChangeSeq", {
187
+ Object.defineProperty(this, "transceiverManager", {
151
188
  enumerable: true,
152
189
  configurable: true,
153
190
  writable: true,
154
191
  value: void 0
155
192
  });
156
- Object.defineProperty(this, "lastCreatedOfferChangeSeq", {
193
+ Object.defineProperty(this, "sctpManager", {
157
194
  enumerable: true,
158
195
  configurable: true,
159
196
  writable: true,
160
- value: 0
197
+ value: void 0
161
198
  });
162
- Object.defineProperty(this, "needRestart", {
199
+ Object.defineProperty(this, "secureManager", {
163
200
  enumerable: true,
164
201
  configurable: true,
165
202
  writable: true,
166
- value: false
203
+ value: void 0
167
204
  });
168
- Object.defineProperty(this, "router", {
205
+ Object.defineProperty(this, "negotiation", {
169
206
  enumerable: true,
170
207
  configurable: true,
171
208
  writable: true,
172
- value: new media_1.RtpRouter()
209
+ value: void 0
173
210
  });
174
- Object.defineProperty(this, "sdpManager", {
211
+ Object.defineProperty(this, "topology", {
175
212
  enumerable: true,
176
213
  configurable: true,
177
214
  writable: true,
178
215
  value: void 0
179
216
  });
180
- Object.defineProperty(this, "transceiverManager", {
217
+ Object.defineProperty(this, "remoteCandidates", {
181
218
  enumerable: true,
182
219
  configurable: true,
183
220
  writable: true,
184
221
  value: void 0
185
222
  });
186
- Object.defineProperty(this, "sctpManager", {
223
+ Object.defineProperty(this, "validator", {
187
224
  enumerable: true,
188
225
  configurable: true,
189
226
  writable: true,
190
227
  value: void 0
191
228
  });
192
- 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", {
193
236
  enumerable: true,
194
237
  configurable: true,
195
238
  writable: true,
@@ -201,29 +244,59 @@ class RTCPeerConnection extends helper_1.EventTarget {
201
244
  writable: true,
202
245
  value: false
203
246
  });
204
- Object.defineProperty(this, "shouldNegotiationneeded", {
247
+ Object.defineProperty(this, "applyingIceRestart", {
205
248
  enumerable: true,
206
249
  configurable: true,
207
250
  writable: true,
208
251
  value: false
209
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
+ });
210
274
  Object.defineProperty(this, "lastCreatedAnswer", {
211
275
  enumerable: true,
212
276
  configurable: true,
213
277
  writable: true,
214
278
  value: void 0
215
279
  });
280
+ /** Reusable by a parameterless setLocalDescription while still valid. */
216
281
  Object.defineProperty(this, "lastCreatedOffer", {
217
282
  enumerable: true,
218
283
  configurable: true,
219
284
  writable: true,
220
285
  value: void 0
221
286
  });
222
- 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", {
223
296
  enumerable: true,
224
297
  configurable: true,
225
298
  writable: true,
226
- value: []
299
+ value: void 0
227
300
  });
228
301
  Object.defineProperty(this, "iceGatheringStateChange", {
229
302
  enumerable: true,
@@ -297,8 +370,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
297
370
  configurable: true,
298
371
  writable: true,
299
372
  value: () => {
300
- this.negotiationChangeSeq++;
301
- this.scheduleNegotiationneeded();
373
+ this.negotiationNeed.change();
302
374
  }
303
375
  });
304
376
  this.setConfiguration(config);
@@ -311,7 +383,7 @@ class RTCPeerConnection extends helper_1.EventTarget {
311
383
  this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);
312
384
  this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);
313
385
  this.transceiverManager.onTrack.subscribe(({ track, streams, transceiver }) => {
314
- const event = new RTCTrackEvent({
386
+ const event = new peerConnectionEvents_1.RTCTrackEvent({
315
387
  track,
316
388
  streams,
317
389
  transceiver,
@@ -325,6 +397,15 @@ class RTCPeerConnection extends helper_1.EventTarget {
325
397
  });
326
398
  this.transceiverManager.onNegotiationNeeded.subscribe(() => this.needNegotiation());
327
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);
328
409
  this.sctpManager.onDataChannel.subscribe((channel) => {
329
410
  this.onDataChannel.execute(channel);
330
411
  const event = { type: "datachannel", channel };
@@ -336,6 +417,14 @@ class RTCPeerConnection extends helper_1.EventTarget {
336
417
  sctpManager: this.sctpManager,
337
418
  transceiverManager: this.transceiverManager,
338
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
+ });
339
428
  this.secureManager.iceGatheringStateChange.subscribe((state) => {
340
429
  this.iceGatheringStateChange.execute(state);
341
430
  this.onicegatheringstatechange?.(new globalThis.Event("icegatheringstatechange"));
@@ -450,91 +539,21 @@ class RTCPeerConnection extends helper_1.EventTarget {
450
539
  return this.transceiverManager.getReceivers();
451
540
  }
452
541
  setConfiguration(config) {
453
- const normalizedConfig = normalizePeerConfiguration(config);
454
542
  const isReconfiguration = !!this.sdpManager;
455
- if (normalizedConfig.rtcpMuxPolicy &&
456
- normalizedConfig.rtcpMuxPolicy !== "require") {
457
- throw new Error("rtcpMuxPolicy must be require");
458
- }
459
- if (normalizedConfig.iceCandidatePoolSize !== undefined &&
460
- (!Number.isInteger(normalizedConfig.iceCandidatePoolSize) ||
461
- normalizedConfig.iceCandidatePoolSize < 0)) {
462
- throw new Error("iceCandidatePoolSize must be a non-negative integer");
463
- }
464
- if (isReconfiguration &&
465
- normalizedConfig.bundlePolicy !== undefined &&
466
- normalizedConfig.bundlePolicy !== this.config.bundlePolicy) {
467
- throw new Error("bundlePolicy cannot be changed");
468
- }
469
- if (normalizedConfig.mLineReuse !== undefined &&
470
- !MLineReuseModes.includes(normalizedConfig.mLineReuse)) {
471
- throw (0, errors_1.createWebRtcTypeError)(`mLineReuse must be one of ${MLineReuseModes.join(", ")}`);
472
- }
473
- if (isReconfiguration &&
474
- normalizedConfig.mLineReuse !== undefined &&
475
- normalizedConfig.mLineReuse !== this.config.mLineReuse) {
476
- throw (0, errors_1.createWebRtcDomException)("InvalidModificationError", "mLineReuse cannot be changed");
477
- }
478
- if (isReconfiguration &&
479
- normalizedConfig.rtcpMuxPolicy !== undefined &&
480
- normalizedConfig.rtcpMuxPolicy !== this.config.rtcpMuxPolicy) {
481
- throw new Error("rtcpMuxPolicy cannot be changed");
482
- }
483
- if (isReconfiguration &&
484
- normalizedConfig.certificates !== undefined &&
485
- !hasSameCertificates(normalizedConfig.certificates, this.config.certificates)) {
486
- throw new Error("certificates cannot be changed");
487
- }
488
- if (isReconfiguration &&
489
- normalizedConfig.iceCandidatePoolSize !== undefined &&
490
- this.localDescription &&
491
- normalizedConfig.iceCandidatePoolSize !== this.config.iceCandidatePoolSize) {
492
- throw new Error("iceCandidatePoolSize cannot be changed after setLocalDescription");
493
- }
494
- if ((normalizedConfig.iceCandidatePoolSize ?? 0) > 0) {
495
- throw new Error("iceCandidatePoolSize > 0 is not supported");
496
- }
497
- if (normalizedConfig.sctp !== undefined) {
498
- const requestedSctpMtu = normalizedConfig.sctp.mtu ?? src_1.DEFAULT_SCTP_MTU;
499
- (0, src_1.validateSctpMtu)(requestedSctpMtu);
500
- if (this.sctpManager?.sctpTransport &&
501
- requestedSctpMtu !== this.config.sctp.mtu) {
502
- throw new Error("sctp.mtu cannot be changed after SCTP transport creation");
503
- }
504
- }
505
- (0, utils_1.deepMerge)(this.config, normalizedConfig);
506
- this.config.sctp = {
507
- mtu: this.config.sctp?.mtu ?? src_1.DEFAULT_SCTP_MTU,
508
- };
509
- if (this.config.icePortRange) {
510
- const [min, max] = this.config.icePortRange;
511
- if (min === max)
512
- throw new Error("should not be same value");
513
- if (min >= max)
514
- throw new Error("The min must be less than max");
515
- }
516
- if (!Number.isInteger(this.config.maxMessageSize) ||
517
- this.config.maxMessageSize < 0) {
518
- throw new Error("maxMessageSize must be a non-negative integer");
519
- }
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;
520
549
  if (this.sctpManager?.sctpTransport) {
521
550
  this.sctpManager.sctpTransport.maxMessageSize =
522
551
  this.config.maxMessageSize;
523
552
  }
524
- assignDynamicPayloadTypes(this.config);
525
- [
526
- ...(this.config.headerExtensions.audio || []),
527
- ...(this.config.headerExtensions.video || []),
528
- ].forEach((v, i) => {
529
- v.id = 1 + i;
530
- });
531
- // Propagate ICE server changes only to transports still in gathering
532
- // state "new". JSEP (RFC 8829 §4.1.18): STUN/TURN changes affect the next
533
- // gathering phase; once gathering has started or finished, nothing is
534
- // applied to the live Connection (WHIP: createOffer → setConfiguration →
535
- // setLocalDescription). Per-transport state is used so a gatherer that
536
- // was reset to "new" (e.g. after ICE restart) is not blocked by a stale
537
- // 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.
538
557
  if (isReconfiguration &&
539
558
  this.secureManager &&
540
559
  (normalizedConfig.iceServers !== undefined ||
@@ -543,13 +562,45 @@ class RTCPeerConnection extends helper_1.EventTarget {
543
562
  }
544
563
  }
545
564
  getConfiguration() {
546
- return clonePeerConfiguration(this.config);
565
+ return (0, peerConfig_1.clonePeerConfiguration)(this.config);
547
566
  }
548
- async createOffer({ iceRestart } = {}) {
549
- if (iceRestart || this.needRestart) {
550
- this.needRestart = false;
551
- 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();
552
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.
553
604
  await this.secureManager.ensureCerts();
554
605
  for (const transceiver of this.transceiverManager.getTransceivers()) {
555
606
  if (transceiver.codecs.length === 0 ||
@@ -561,10 +612,34 @@ class RTCPeerConnection extends helper_1.EventTarget {
561
612
  this.config.headerExtensions[transceiver.kind] ?? [];
562
613
  }
563
614
  }
564
- 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
+ }
565
636
  const createdOffer = description.toJSON();
566
637
  this.lastCreatedOffer = createdOffer;
567
- this.lastCreatedOfferChangeSeq = this.negotiationChangeSeq;
638
+ this.createdOffer = {
639
+ sdp: createdOffer.sdp,
640
+ transceiverByMid,
641
+ changeSeq: this.negotiationNeed.noteCreatedOffer(),
642
+ };
568
643
  return createdOffer;
569
644
  }
570
645
  createSctpTransport() {
@@ -593,84 +668,137 @@ class RTCPeerConnection extends helper_1.EventTarget {
593
668
  this.needNegotiation();
594
669
  }
595
670
  }
596
- /**未交渉の変更が残っていれば negotiationneeded を予約する (stable 復帰時の再判定にも使う) */
597
- scheduleNegotiationneeded() {
598
- this.invalidateLastCreatedDescriptions();
599
- this.shouldNegotiationneeded = true;
600
- if (this.negotiationneeded ||
601
- this.negotiationneededScheduled ||
602
- this.signalingState !== "stable") {
603
- return;
604
- }
605
- this.shouldNegotiationneeded = false;
606
- this.negotiationneededScheduled = true;
607
- setImmediate(() => {
608
- this.negotiationneededScheduled = false;
609
- if (this.negotiatedChangeSeq >= this.negotiationChangeSeq) {
610
- // 発火前に適用された local offer が変更をすべて含んでいる
611
- return;
612
- }
613
- if (this.signalingState !== "stable") {
614
- // stable に戻った時点で改めて判定する
615
- this.shouldNegotiationneeded = true;
616
- return;
617
- }
618
- this.negotiationneeded = true;
619
- this.onNegotiationneeded.execute();
620
- if (this.onnegotiationneeded) {
621
- 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
+ }
622
694
  }
623
- this.emit("negotiationneeded");
624
- });
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
+ }
625
708
  }
626
709
  invalidateLastCreatedDescriptions() {
627
710
  this.lastCreatedAnswer = undefined;
628
711
  this.lastCreatedOffer = undefined;
629
712
  }
630
713
  async waitForPendingDescriptionTask() {
631
- this.assertNotClosed();
632
714
  await Promise.resolve();
633
- if (this.isClosed) {
634
- 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();
635
764
  }
636
765
  }
637
- findOrCreateTransport() {
766
+ findOrCreateTransport(forceNew = false) {
767
+ // A closed connection creates no transport (close() could not stop it).
768
+ this.assertNotClosed();
638
769
  const existingDtlsTransport = this.dtlsTransports.find((transport) => transport.state !== "closed");
770
+ const existing = existingDtlsTransport?.iceTransport;
639
771
  // Gather ICE candidates for only one track. If the remote endpoint is not bundle-aware, negotiate only one media track.
640
772
  // https://w3c.github.io/webrtc-pc/#rtcbundlepolicy-enum
641
- if (this.sdpManager.bundlePolicy === "max-bundle" ||
642
- (this.sdpManager.bundlePolicy !== "disable" && this.remoteIsBundled)) {
773
+ if (!forceNew &&
774
+ (this.sdpManager.bundlePolicy === "max-bundle" ||
775
+ (this.sdpManager.bundlePolicy !== "disable" && this.remoteIsBundled))) {
643
776
  if (existingDtlsTransport) {
644
777
  return existingDtlsTransport;
645
778
  }
646
779
  }
647
- return this.createDtlsTransport();
648
- }
649
- /**
650
- * @param inheritCredentials false の場合は BUNDLE 外の独立 transport として
651
- * 既存 transport と異なる ICE credentials を使う
652
- */
653
- createDtlsTransport({ inheritCredentials = true } = {}) {
654
- const dtlsTransport = this.secureManager.createTransport({
655
- inheritCredentials,
656
- });
780
+ const dtlsTransport = this.secureManager.createTransport(forceNew);
657
781
  dtlsTransport.onRtp.subscribe((rtp) => {
658
782
  this.router.routeRtp(rtp);
659
783
  });
660
784
  dtlsTransport.onRtcp.subscribe((rtcp) => {
661
785
  this.router.routeRtcp(rtcp);
662
786
  });
787
+ this.negotiation.noteCreatedTransport(dtlsTransport);
663
788
  const iceTransport = dtlsTransport.iceTransport;
664
789
  iceTransport.onNegotiationNeeded.subscribe(() => {
665
790
  this.needNegotiation();
666
791
  });
667
792
  iceTransport.onIceCandidate.subscribe((candidate) => {
793
+ if (this.applyingIceRestart ||
794
+ this.negotiation.isPendingOnlyTransport(iceTransport.id))
795
+ return;
668
796
  if (!this.localDescription) {
669
797
  log("localDescription not found when ice candidate was gathered");
670
798
  return;
671
799
  }
672
800
  if (!candidate) {
673
- this.sdpManager.setLocal(this._localDescription, this.transceiverManager.getTransceivers(), this.sctpTransport);
801
+ this.sdpManager.setLocal(this._localDescription, this.transceiverManager.getTransceivers(), this.sctpTransport, this.negotiation.transportByMid);
674
802
  this.onIceCandidate.execute(undefined);
675
803
  if (this.onicecandidate) {
676
804
  this.onicecandidate({ candidate: undefined });
@@ -696,21 +824,16 @@ class RTCPeerConnection extends helper_1.EventTarget {
696
824
  });
697
825
  return dtlsTransport;
698
826
  }
699
- /**
700
- * local candidate の sdpMid / sdpMLineIndex を、その ICE transport を実際に
701
- * 所有する受け入れ済み m-line (BUNDLE なら tag) に合わせる。
702
- */
827
+ /**Resolve candidate metadata from an accepted m-line that owns this transport. */
703
828
  resolveLocalCandidateOwner(iceTransport) {
704
829
  const description = this._localDescription;
705
- if (!description) {
830
+ if (!description)
706
831
  return;
707
- }
708
832
  const owners = description.media
709
833
  .map((media, index) => ({ media, index }))
710
834
  .filter(({ media }) => {
711
- if (media.port === 0) {
835
+ if (media.port === 0)
712
836
  return false;
713
- }
714
837
  const mid = media.rtp.muxId;
715
838
  if (media.kind === "application") {
716
839
  return (!!this.sctpTransport &&
@@ -720,18 +843,15 @@ class RTCPeerConnection extends helper_1.EventTarget {
720
843
  }
721
844
  const transceiver = this.transceiverManager
722
845
  .getTransceivers()
723
- .find((t) => t.mid != undefined && t.mid === mid);
724
- return (!!transceiver &&
725
- !transceiver.stopped &&
726
- transceiver.dtlsTransport?.iceTransport.id === iceTransport.id);
846
+ .find((t) => t.mid === mid && !t.stopped);
847
+ return transceiver?.dtlsTransport?.iceTransport.id === iceTransport.id;
727
848
  });
728
849
  const tags = description.group
729
850
  .filter((group) => group.semantic === "BUNDLE")
730
851
  .map((group) => group.items[0]);
731
852
  const owner = owners.find(({ media }) => tags.includes(media.rtp.muxId)) ?? owners[0];
732
- if (!owner) {
853
+ if (!owner)
733
854
  return;
734
- }
735
855
  return { mid: owner.media.rtp.muxId, index: owner.index };
736
856
  }
737
857
  /**
@@ -752,6 +872,9 @@ class RTCPeerConnection extends helper_1.EventTarget {
752
872
  .filter((t) => t.stopped)
753
873
  .map((t) => t.dtlsTransport)) {
754
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
+ }
755
878
  for (const transport of new Set(candidates)) {
756
879
  if (!transport ||
757
880
  transport.state === "closed" ||
@@ -764,602 +887,676 @@ class RTCPeerConnection extends helper_1.EventTarget {
764
887
  }
765
888
  }
766
889
  async setLocalDescription(sessionDescription) {
767
- // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/setLocalDescription#type
768
- const implicitOfferState = [
769
- "stable",
770
- "have-local-offer",
771
- "have-remote-pranswer",
772
- ];
773
- await this.waitForPendingDescriptionTask();
774
- if (sessionDescription?.type === "rollback") {
775
- this.sdpManager.rollbackLocalDescription(this.signalingState);
776
- for (const transceiver of this.transceiverManager.getTransceivers()) {
777
- 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;
778
914
  }
779
- this.pendingOfferChangeSeq = undefined;
780
- this.setSignalingState("stable");
781
- if (this.shouldNegotiationneeded) {
782
- 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");
783
943
  }
784
- this.invalidateLastCreatedDescriptions();
785
- return;
786
- }
787
- const needsGeneratedDescription = !sessionDescription?.type ||
788
- !sessionDescription.sdp ||
789
- sessionDescription.sdp.length === 0;
790
- const generatedDescription = needsGeneratedDescription
791
- ? sessionDescription?.type === "offer"
792
- ? (this.lastCreatedOffer ?? (await this.createOffer()))
793
- : sessionDescription?.type === "answer" ||
794
- sessionDescription?.type === "pranswer"
795
- ? (this.lastCreatedAnswer ?? (await this.createAnswer()))
796
- : implicitOfferState.includes(this.signalingState)
797
- ? (this.lastCreatedOffer ?? (await this.createOffer()))
798
- : (this.lastCreatedAnswer ?? (await this.createAnswer()))
799
- : undefined;
800
- sessionDescription = {
801
- type: sessionDescription?.type ?? generatedDescription.type,
802
- sdp: sessionDescription?.sdp && sessionDescription.sdp.length > 0
803
- ? sessionDescription.sdp
804
- : generatedDescription.sdp,
805
- };
806
- if (sessionDescription.type === "offer" &&
807
- this.lastCreatedOffer &&
808
- sessionDescription.sdp !== this.lastCreatedOffer.sdp) {
809
- throw (0, errors_1.createWebRtcDomException)("InvalidModificationError", "setLocalDescription must use the latest created offer");
810
- }
811
- // # parse and validate description
812
- const descriptionType = sessionDescription.type;
813
- const descriptionSdp = sessionDescription.sdp;
814
- const description = this.sdpManager.parseSdp({
815
- sdp: descriptionSdp,
816
- isLocal: true,
817
- signalingState: this.signalingState,
818
- type: descriptionType,
819
- });
820
- // # update signaling state
821
- if (description.type === "offer") {
822
- // この offer は作成時点までの変更を含む。answer の適用で交渉済みにする
823
- this.pendingOfferChangeSeq =
824
- this.lastCreatedOffer?.sdp === sessionDescription.sdp
825
- ? this.lastCreatedOfferChangeSeq
826
- : undefined;
827
- this.setSignalingState("have-local-offer");
828
- }
829
- else if (description.type === "answer") {
830
- this.setSignalingState("stable");
831
- }
832
- else if (description.type === "pranswer") {
833
- this.setSignalingState("have-local-pranswer");
834
- }
835
- if (description.type === "answer") {
836
- // answer の確定で拒否予定の m-line を停止し、RTP pipeline / 遊休 transport を解放する
837
- this.transceiverManager.commitRemoteOffer();
838
- // port 0 で答えた m-line (aggressive の inactive など) は offerer 側で拒否として停止が確定する。
839
- // answerer 側も同じ位置を停止確定にし、offerer が新 MID で再利用できるようにする
840
- for (const media of description.media) {
841
- if (!["audio", "video"].includes(media.kind) || media.port !== 0) {
842
- 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);
843
1024
  }
844
- const transceiver = this.transceiverManager
845
- .getTransceivers()
846
- .find((t) => t.mid === media.rtp.muxId && !t.stopped);
847
- transceiver?.commitStopped({ rejected: true });
848
1025
  }
849
- this.closeIdleTransports();
850
- }
851
- // # assign MID
852
- for (const [i, media] of (0, helper_1.enumerate)(description.media)) {
853
- const mid = media.rtp.muxId;
854
- this.sdpManager.registerMid(mid);
855
- if (["audio", "video"].includes(media.kind) && media.port !== 0) {
856
- // 停止済み、別 kind、別 MID の transceiver には割り当てない (MID の一意性を保つ)
857
- const transceiver = this.transceiverManager
858
- .getTransceivers()
859
- .find((t) => t.mLineIndex === i &&
860
- !t.stopped &&
861
- t.kind === media.kind &&
862
- (t.mid == null || t.mid === mid));
863
- if (transceiver) {
864
- transceiver.mid = mid;
865
- if (description.type === "offer") {
866
- 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);
867
1054
  }
868
1055
  }
869
1056
  }
870
- if (media.kind === "application" && this.sctpTransport) {
871
- 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();
872
1070
  }
873
- }
874
- // setup ice,dtls role
875
- const role = description.media.find((media) => media.dtlsParams)?.dtlsParams
876
- ?.role;
877
- // transport ごとに、その transport を使う受け入れ済み m-line の a=setup を適用する
878
- // (BUNDLE group 外の独立 transport は先頭 m-line と異なる role を持ちうる)
879
- const roleOfTransport = new Map();
880
- for (const media of description.media) {
881
- const mid = media.rtp.muxId;
882
- const mediaRole = media.dtlsParams?.role;
883
- if (media.port === 0 || mid == undefined || !mediaRole) {
884
- 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
+ }
885
1082
  }
886
- const owner = media.kind === "application"
887
- ? this.sctpTransport?.mid === mid
888
- ? this.sctpTransport
889
- : undefined
890
- : this.transceiverManager
891
- .getTransceivers()
892
- .find((t) => t.mid === mid && !t.stopped);
893
- if (owner?.dtlsTransport && !roleOfTransport.has(owner.dtlsTransport)) {
894
- 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();
895
1089
  }
896
- }
897
- this.secureManager.setLocalRole({
898
- type: description.type === "offer" ? "offer" : "answer",
899
- role,
900
- roleOfTransport,
901
- });
902
- // # configure direction
903
- 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();
904
1123
  for (const media of description.media) {
905
- const t = this.transceiverManager
906
- .getTransceivers()
907
- .find((t) => t.mid != undefined && t.mid === media.rtp.muxId);
908
- if (!t || t.stopped || t.pendingRejection) {
909
- 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);
910
1128
  }
911
- const direction = t.stopping
912
- ? "inactive"
913
- : (0, utils_1.andDirection)(t.direction, t.offerDirection);
914
- t.setCurrentDirection(direction);
915
1129
  }
916
- }
917
- // for trickle ice
918
- this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport);
919
- await this.gatherCandidates().catch((e) => {
920
- log("gatherCandidates failed", e);
921
- });
922
- // connect transports
923
- if (description.type === "answer") {
924
- this.connect().catch((err) => {
925
- log("connect failed", err);
926
- 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),
927
1137
  });
928
- }
929
- this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport);
930
- // answerer の stop() は次の自分の offer で交渉する
931
- const hasUnnegotiatedStop = description.type === "answer" && this.settleStoppingTransceivers();
932
- if (this.shouldNegotiationneeded || hasUnnegotiatedStop) {
933
- this.scheduleNegotiationneeded();
934
- }
935
- this.invalidateLastCreatedDescriptions();
936
- 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
+ });
937
1260
  }
938
1261
  async gatherCandidates() {
939
1262
  await this.secureManager.gatherCandidates();
940
1263
  }
941
- async addIceCandidate(candidateMessage = {}) {
942
- if (this.isClosed) {
943
- throw (0, errors_1.createWebRtcDomException)("InvalidStateError", "is closed");
944
- }
945
- if (!this.remoteDescription || !this.sdpManager._remoteDescription) {
946
- this.pendingRemoteCandidates.push(candidateMessage);
947
- return;
948
- }
949
- await this.applyRemoteIceCandidate(candidateMessage);
950
- }
951
- async applyRemoteIceCandidate(candidateMessage) {
952
- const sdp = this.sdpManager._remoteDescription;
953
- if (!sdp) {
954
- return;
955
- }
956
- const appliedCandidate = await this.secureManager.addIceCandidate(sdp, candidateMessage);
957
- const remoteDescription = this.sdpManager._remoteDescription;
958
- if (!remoteDescription || !appliedCandidate) {
959
- return;
960
- }
961
- if (appliedCandidate.kind === "end-of-candidates") {
962
- for (const mediaIndex of appliedCandidate.mediaIndices) {
963
- const media = remoteDescription.media[mediaIndex];
964
- if (media) {
965
- media.iceCandidatesComplete = true;
966
- }
967
- }
968
- return;
969
- }
970
- for (const mediaIndex of appliedCandidate.mediaIndices) {
971
- const media = remoteDescription.media[mediaIndex];
972
- 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) {
973
1278
  continue;
974
1279
  }
975
- 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
+ }
976
1284
  }
977
1285
  }
978
- async flushPendingRemoteCandidates() {
979
- while (this.pendingRemoteCandidates.length > 0 &&
980
- this.remoteDescription &&
981
- this.sdpManager._remoteDescription) {
982
- const candidate = this.pendingRemoteCandidates.shift();
983
- 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;
984
1294
  }
985
1295
  }
986
- async connect() {
987
- log("start connect");
988
- const res = await Promise.allSettled(this.dtlsTransports.map(async (dtlsTransport) => {
989
- const { iceTransport } = dtlsTransport;
990
- if (iceTransport.state === "connected") {
991
- return;
992
- }
993
- const checkDtlsConnected = () => dtlsTransport.state === "connected";
994
- if (checkDtlsConnected()) {
995
- return;
1296
+ async addIceCandidate(candidateMessage = {}) {
1297
+ return this.enqueueDescriptionOperation(async () => {
1298
+ if (this.isClosed) {
1299
+ throw (0, errors_1.createWebRtcDomException)("InvalidStateError", "is closed");
996
1300
  }
997
- this.secureManager.setConnectionState("connecting");
998
- await iceTransport.start().catch((err) => {
999
- log("iceTransport.start failed", err);
1000
- throw err;
1001
- });
1002
- 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);
1003
1308
  return;
1004
1309
  }
1005
- await dtlsTransport.start().catch((err) => {
1006
- log("dtlsTransport.start failed", err);
1007
- throw err;
1008
- });
1009
- if (this.sctpTransport &&
1010
- this.sctpTransport.dtlsTransport.id === dtlsTransport.id) {
1011
- await this.sctpManager.connectSctp();
1012
- }
1013
- }));
1014
- if (res.find((r) => r.status === "rejected")) {
1015
- this.secureManager.setConnectionState("failed");
1016
- }
1017
- else {
1018
- this.secureManager.setConnectionState("connected");
1019
- }
1310
+ await this.remoteCandidates.apply(candidateMessage);
1311
+ }, { afterApplied: true });
1020
1312
  }
1021
1313
  restartIce() {
1022
- this.needRestart = true;
1314
+ this.iceRestartRequest.request(this.sdpManager.currentLocalDescription, this.sdpManager.pendingLocalDescription);
1023
1315
  this.needNegotiation();
1024
1316
  }
1025
1317
  async setRemoteDescription(sessionDescription) {
1026
- if (sessionDescription instanceof sdp_1.SessionDescription) {
1027
- sessionDescription = sessionDescription.toSdp();
1028
- }
1029
- await this.waitForPendingDescriptionTask();
1030
- let codecPlan = new Map();
1031
- if (sessionDescription.type &&
1032
- sessionDescription.type !== "rollback" &&
1033
- sessionDescription.sdp) {
1034
- 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({
1035
1350
  sdp: sessionDescription.sdp,
1036
1351
  isLocal: false,
1037
1352
  signalingState: this.signalingState,
1038
1353
  type: sessionDescription.type,
1039
1354
  });
1040
- // 本適用と同じ対応付けで全 m-line の codec を副作用なしに解決する
1041
- const planned = new Set();
1042
- codecPlan = this.transceiverManager.planRemoteRtpCodecs(preview, (remoteMedia, index) => {
1043
- const transceiver = this.findTransceiverForRemoteMedia(remoteMedia, index, planned);
1044
- if (transceiver)
1045
- planned.add(transceiver);
1046
- return transceiver;
1047
- });
1048
- }
1049
- const needsImplicitLocalRollback = sessionDescription.type === "offer" &&
1050
- ["have-local-offer", "have-local-pranswer"].includes(this.signalingState);
1051
- if (needsImplicitLocalRollback) {
1052
- this.sdpManager.rollbackLocalDescription(this.signalingState);
1053
- for (const transceiver of this.transceiverManager.getTransceivers()) {
1054
- transceiver.pendingLocalOfferCodecs = undefined;
1055
- }
1056
- this.pendingOfferChangeSeq = undefined;
1057
- this.shouldNegotiationneeded = true;
1058
- this.setSignalingState("stable");
1059
- await Promise.resolve();
1060
- }
1061
- // # parse and validate description
1062
- this.assertAnswerKeepsSharedTransports(sessionDescription);
1063
- const remoteSdp = this.sdpManager.setRemoteDescription(sessionDescription, this.signalingState);
1064
- if (!remoteSdp) {
1065
- // 非対応 re-offer などの rollback では元の transceiver 対応を復元する
1066
- const transportsBeforeRollback = this.transceiverManager
1067
- .getTransceivers()
1068
- .map((t) => t.dtlsTransport);
1069
- this.transceiverManager.rollbackRemoteOffer();
1070
- this.closeIdleTransports(transportsBeforeRollback);
1071
- this.setSignalingState("stable");
1072
- if (this.shouldNegotiationneeded) {
1073
- 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();
1074
1365
  }
1075
- this.invalidateLastCreatedDescriptions();
1076
- return;
1077
- }
1078
- if (remoteSdp.type === "offer") {
1079
- this.transceiverManager.beginRemoteOffer();
1080
- }
1081
- // # apply description
1082
- const bundleGroups = this.config.bundlePolicy === "disable"
1083
- ? []
1084
- : remoteSdp.group.filter((group) => group.semantic === "BUNDLE");
1085
- const groupOfMid = (mid) => mid == undefined
1086
- ? undefined
1087
- : bundleGroups.find((group) => group.items.includes(mid));
1088
- // ## associate m-lines with transceivers / sctp
1089
- const associated = new Set();
1090
- const entries = remoteSdp.media.map((remoteMedia, index) => {
1091
- if (["audio", "video"].includes(remoteMedia.kind)) {
1092
- let transceiver = this.findTransceiverForRemoteMedia(remoteMedia, index, associated);
1093
- if (!transceiver) {
1094
- if (remoteMedia.port === 0) {
1095
- // 未知の MID の拒否済み m-line には transceiver を関連付けない
1096
- return { remoteMedia, index };
1097
- }
1098
- transceiver = this.addRemoteTransceiver(remoteMedia, index);
1099
- }
1100
- else if (transceiver.mid == null) {
1101
- this.transceiverManager.associateMLine(transceiver, index);
1102
- }
1103
- associated.add(transceiver);
1104
- return { remoteMedia, index, transceiver };
1105
- }
1106
- else if (remoteMedia.kind === "application") {
1107
- let sctpTransport = this.sctpTransport;
1108
- if (!sctpTransport) {
1109
- sctpTransport = this.createSctpTransport();
1110
- sctpTransport.mid = remoteMedia.rtp.muxId;
1111
- }
1112
- 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();
1113
1383
  }
1114
- else {
1115
- 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;
1116
1393
  }
1117
- });
1118
- if (remoteSdp.type === "offer") {
1119
- this.transceiverManager.releaseUnassociatedReservations(associated, remoteSdp.media.length);
1120
- }
1121
- const ownerOf = (entry) => entry.transceiver ?? entry.sctpTransport;
1122
- // ## transport ownership
1123
- // remote offer の所有関係は bundlePolicy によらず offer の BUNDLE group だけで決まる
1124
- // (max-bundle は自分の offer にだけ効く)。group ごとに 1 つの transport を共有し、
1125
- // 異なる group や group 外の m-line とは共有しない。
1126
- // remote answer では offer で渡した ICE credentials を保つため transport を作り直さない
1127
- // (共有 transport を分割する answer は assertAnswerKeepsSharedTransports で事前に拒否済み)
1128
- const isRemoteOffer = remoteSdp.type === "offer";
1129
- const liveTransport = (transport) => !!transport && transport.state !== "closed";
1130
- const groupTransports = new Map();
1131
- const claimed = new Set();
1132
- for (const group of bundleGroups) {
1133
- const members = entries.filter((entry) => !!ownerOf(entry) &&
1134
- group.items.includes(entry.remoteMedia.rtp.muxId));
1135
- if (members.length === 0) {
1136
- continue;
1394
+ if (remoteSdp.type === "offer" &&
1395
+ this.signalingState !== "have-remote-offer") {
1396
+ this.negotiation.begin();
1137
1397
  }
1138
- // 既存 member の transport を優先し、他の group が使っていれば新しい transport を作る
1139
- let shared = members
1140
- .map((entry) => ownerOf(entry).dtlsTransport)
1141
- .find((transport) => liveTransport(transport) &&
1142
- (!isRemoteOffer || !claimed.has(transport)));
1143
- if (!shared) {
1144
- shared = this.createDtlsTransport({ inheritCredentials: false });
1145
- }
1146
- groupTransports.set(group, shared);
1147
- claimed.add(shared);
1148
- for (const entry of members) {
1149
- const owner = ownerOf(entry);
1150
- if (owner.dtlsTransport !== shared) {
1151
- 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();
1152
1410
  }
1153
- }
1154
- }
1155
- if (isRemoteOffer) {
1156
- // group 外 (group のない offer を含む) で受け入れた m-line は独立した transport / ICE credentials を持つ
1157
- for (const entry of entries) {
1158
- const owner = ownerOf(entry);
1159
- if (!owner ||
1160
- entry.remoteMedia.port === 0 ||
1161
- groupOfMid(entry.remoteMedia.rtp.muxId)) {
1162
- continue;
1411
+ if (remoteSdp.type === "answer") {
1412
+ this.topology.applyPending(remoteSdp);
1163
1413
  }
1164
- if (!liveTransport(owner.dtlsTransport) ||
1165
- claimed.has(owner.dtlsTransport)) {
1166
- 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();
1167
1424
  }
1168
- claimed.add(owner.dtlsTransport);
1169
- }
1170
- }
1171
- // ## apply RTP / SCTP (受け入れ判定)
1172
- const acceptedEntries = new Set();
1173
- for (const entry of entries) {
1174
- const { remoteMedia, index } = entry;
1175
- if (entry.transceiver) {
1176
- if (this.transceiverManager.setRemoteRTP(entry.transceiver, remoteMedia, remoteSdp.type, index, codecPlan.get(index) ?? [])) {
1177
- acceptedEntries.add(entry);
1425
+ for (const update of transportUpdates)
1426
+ update();
1427
+ for (const iceTransport of new Set(endOfCandidates)) {
1428
+ iceTransport.deliverRemoteCandidate(undefined);
1178
1429
  }
1179
- }
1180
- else if (entry.sctpTransport) {
1181
- this.sctpManager.setRemoteSCTP(remoteMedia, index);
1182
- acceptedEntries.add(entry);
1183
- }
1184
- }
1185
- // ICE / DTLS パラメータは group で最初に受け入れた member (tag) から適用する
1186
- // (codec 不一致で拒否した member のパラメータは使わない)
1187
- const groupParamSources = new Map();
1188
- for (const group of bundleGroups) {
1189
- for (const mid of group.items) {
1190
- const entry = entries.find((e) => e.remoteMedia.rtp.muxId === mid &&
1191
- e.remoteMedia.port !== 0 &&
1192
- acceptedEntries.has(e));
1193
- if (entry) {
1194
- groupParamSources.set(group, entry);
1195
- break;
1430
+ if (preserveCurrentTransport) {
1431
+ await this.remoteCandidates.deliverSameGenerationDescription(remoteSdp);
1432
+ this.assertOpenAfterYield();
1196
1433
  }
1197
- }
1198
- }
1199
- // ## apply transport parameters
1200
- for (const entry of entries) {
1201
- const { remoteMedia } = entry;
1202
- const owner = ownerOf(entry);
1203
- if (!owner) {
1204
- continue;
1205
- }
1206
- const accepted = acceptedEntries.has(entry);
1207
- const dtlsTransport = owner.dtlsTransport;
1208
- const group = groupOfMid(remoteMedia.rtp.muxId);
1209
- if (remoteMedia.port === 0 ||
1210
- !dtlsTransport ||
1211
- dtlsTransport.state === "closed" ||
1212
- // group 外の拒否 section の transport は使わない
1213
- (!accepted && !group)) {
1214
- continue;
1215
- }
1216
- const iceTransport = dtlsTransport.iceTransport;
1217
- const ownsTransportParams = !group || groupParamSources.get(group) === entry;
1218
- if (ownsTransportParams) {
1219
- if (remoteMedia.iceParams) {
1220
- const renomination = !!this.sdpManager.inactiveRemoteMedia;
1221
- iceTransport.setRemoteParams(remoteMedia.iceParams, renomination);
1222
- // One agent full, one lite: The full agent MUST take the controlling role, and the lite agent MUST take the controlled role
1223
- // RFC 8445 S6.1.1
1224
- if (remoteMedia.iceParams.iceLite &&
1225
- !iceTransport.connection.iceLite) {
1226
- iceTransport.connection.iceControlling = true;
1227
- }
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();
1228
1441
  }
1229
- if (remoteMedia.dtlsParams) {
1230
- 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
+ }
1231
1472
  }
1232
1473
  }
1233
- // # add ICE candidates
1234
- remoteMedia.iceCandidates.forEach(iceTransport.addRemoteCandidate);
1235
- if (remoteMedia.iceCandidatesComplete) {
1236
- 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;
1237
1490
  }
1238
- // # set DTLS role
1239
- if (remoteSdp.type === "answer" && remoteMedia.dtlsParams?.role) {
1240
- dtlsTransport.role =
1241
- 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");
1242
1495
  }
1243
- }
1244
- if (remoteSdp.type === "answer") {
1245
- // answer に含まれない既存 m-line は remote 起因の停止として確定する
1246
- for (const transceiver of this.transceiverManager.getTransceivers()) {
1247
- if (!associated.has(transceiver) &&
1248
- transceiver.mid != undefined &&
1249
- !transceiver.stopped) {
1250
- transceiver.commitStopped({ rejected: true });
1251
- }
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();
1252
1504
  }
1253
- this.closeIdleTransports();
1254
- }
1255
- if (remoteSdp.type === "offer") {
1256
- this.setSignalingState("have-remote-offer");
1257
- }
1258
- else if (remoteSdp.type === "answer") {
1259
- this.setSignalingState("stable");
1260
- }
1261
- else if (remoteSdp.type === "pranswer") {
1262
- this.setSignalingState("have-remote-pranswer");
1263
- }
1264
- await this.flushPendingRemoteCandidates();
1265
- // connect transports
1266
- if (remoteSdp.type === "answer") {
1267
- log("caller start connect");
1268
- this.connect().catch((err) => {
1269
- log("connect failed", err);
1270
- this.secureManager.setConnectionState("failed");
1271
- });
1272
- }
1273
- this.negotiationneeded = false;
1274
- if (remoteSdp.type === "answer" &&
1275
- this.pendingOfferChangeSeq != undefined) {
1276
- this.negotiatedChangeSeq = Math.max(this.negotiatedChangeSeq, this.pendingOfferChangeSeq);
1277
- this.pendingOfferChangeSeq = undefined;
1278
- }
1279
- const hasUnnegotiatedStop = remoteSdp.type === "answer" && this.settleStoppingTransceivers();
1280
- if (this.shouldNegotiationneeded || hasUnnegotiatedStop) {
1281
- this.scheduleNegotiationneeded();
1282
- }
1283
- this.invalidateLastCreatedDescriptions();
1284
- }
1285
- /**
1286
- * remote answer / pranswer の検証 (offerer 側、状態を変更する前に実行する)。
1287
- * local offer で 1 つの transport を共有した m-line を、answer が同じ BUNDLE group に置かずに
1288
- * 異なる ICE credentials で受け入れることはできない (RFC 8843 7.3.2)。共有 transport は分割できず、
1289
- * 新しい transport を作ると offer で渡した ICE credentials とも一致しなくなる。
1290
- * group の記述が MID と一致しなくても remote の ICE credentials が同じなら、同じ transport のまま扱う。
1291
- */
1292
- assertAnswerKeepsSharedTransports(sessionDescription) {
1293
- if (!["answer", "pranswer"].includes(sessionDescription.type ?? "") ||
1294
- !["have-local-offer", "have-local-pranswer"].includes(this.signalingState) ||
1295
- !sessionDescription.sdp ||
1296
- this.config.bundlePolicy === "disable") {
1297
- return;
1298
- }
1299
- const answer = sdp_1.SessionDescription.parse(sessionDescription.sdp);
1300
- const answerGroups = answer.group.filter((g) => g.semantic === "BUNDLE");
1301
- const byTransport = new Map();
1302
- for (const media of answer.media) {
1303
- const mid = media.rtp.muxId;
1304
- if (media.port === 0 || mid == undefined) {
1305
- 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");
1306
1510
  }
1307
- const owner = media.kind === "application"
1308
- ? this.sctpTransport?.mid === mid
1309
- ? this.sctpTransport
1310
- : undefined
1311
- : this.transceiverManager
1312
- .getTransceivers()
1313
- .find((t) => t.mid === mid && !t.stopped);
1314
- const transport = owner?.dtlsTransport;
1315
- if (!transport) {
1316
- 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
+ });
1317
1525
  }
1318
- const current = {
1319
- group: answerGroups.find((g) => g.items.includes(mid)),
1320
- credentials: `${media.iceParams?.usernameFragment}:${media.iceParams?.password}`,
1321
- };
1322
- const first = byTransport.get(transport);
1323
- if (!first) {
1324
- byTransport.set(transport, current);
1325
- continue;
1526
+ this.negotiationneeded = false;
1527
+ if (remoteSdp.type === "answer") {
1528
+ // 確定した local offer が反映していた変更は交渉済みになる
1529
+ this.negotiationNeed.commitPendingOffer();
1326
1530
  }
1327
- const sameGroup = !!current.group && current.group === first.group;
1328
- if (!sameGroup && current.credentials !== first.credentials) {
1329
- 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();
1330
1536
  }
1331
- }
1537
+ this.invalidateLastCreatedDescriptions();
1538
+ });
1332
1539
  }
1333
1540
  /**
1334
- * remote m-line に対応する transceiver を探す。MID の一致を優先し、
1335
- * 未関連付け 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.
1336
1545
  */
1337
- findTransceiverForRemoteMedia(remoteMedia, index, associated) {
1338
- const candidates = this.transceiverManager
1339
- .getTransceivers()
1340
- .filter((t) => !associated.has(t) && t.kind === remoteMedia.kind);
1341
- const mid = remoteMedia.rtp.muxId;
1342
- const byMid = mid != undefined ? candidates.find((t) => t.mid === mid) : undefined;
1343
- if (byMid) {
1344
- return byMid;
1345
- }
1346
- if (remoteMedia.port === 0) {
1546
+ completeEndedCurrentGenerations() {
1547
+ const current = this.sdpManager.currentRemoteDescription;
1548
+ if (!current)
1347
1549
  return;
1348
- }
1349
- const unassociated = candidates.filter((t) => t.mid == null && !t.stopping && !t.stopped);
1350
- return unassociated.find((t) => t.mLineIndex === index) ?? unassociated[0];
1550
+ this.remoteCandidates.completeSharedTransportMedia(current, current.media.map((_, index) => index));
1351
1551
  }
1352
1552
  /**
1353
- * remote offer / answer の m-line 用に transceiver を作る。
1354
- * 同じ位置に停止済みの旧 transceiver があれば、それを復活させず新しい receiver/router で置き換える。
1553
+ * remote description の transport 所有で使う独立 transport (別 ICE credentials) を作る。
1554
+ * rollback で使われなくなれば transaction が閉じる。
1355
1555
  */
1356
- addRemoteTransceiver(remoteMedia, index) {
1357
- const dtlsTransport = this.findOrCreateTransport();
1358
- const transceiver = this.transceiverManager.addTransceiver(remoteMedia.kind, dtlsTransport, { direction: "recvonly" }, { remoteMLineIndex: index });
1359
- transceiver.mid = remoteMedia.rtp.muxId ?? null;
1360
- this.secureManager.updateIceConnectionState();
1361
- this.onRemoteTransceiverAdded.execute(transceiver);
1362
- return transceiver;
1556
+ createOwnerTransport() {
1557
+ const transport = this.findOrCreateTransport(true);
1558
+ this.negotiation.rememberOwnerTransport(transport);
1559
+ return transport;
1363
1560
  }
1364
1561
  addTransceiver(trackOrKind, options = {}) {
1365
1562
  const dtlsTransport = this.findOrCreateTransport();
@@ -1381,24 +1578,50 @@ class RTCPeerConnection extends helper_1.EventTarget {
1381
1578
  this.needNegotiation();
1382
1579
  return transceiver.sender;
1383
1580
  }
1384
- 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() {
1385
1587
  this.assertNotClosed();
1386
1588
  await this.secureManager.ensureCerts();
1387
- // setCodecPreferences() で無効化された transceiver を再解決する。
1388
- // offer 側と異なり answer は remote offer との交渉結果を使い、
1389
- // 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 まで触らない。
1390
1614
  for (const transceiver of this.transceiverManager.getTransceivers()) {
1391
1615
  if (transceiver.codecs.length !== 0 &&
1392
1616
  !transceiver.codecPreferencesNeedResolution) {
1393
1617
  continue;
1394
1618
  }
1395
- // 拒否予定 / 停止済みの m-line は port 0 で answer するため codec を解決しない
1396
1619
  if (transceiver.pendingRejection ||
1397
1620
  transceiver.stopping ||
1398
1621
  transceiver.stopped) {
1399
1622
  continue;
1400
1623
  }
1401
- const remoteDescription = this.sdpManager._remoteDescription;
1624
+ const remoteDescription = this.sdpManager.pendingRemoteDescription;
1402
1625
  const remoteMedia = remoteDescription?.media.find((media) => media.rtp.muxId != undefined &&
1403
1626
  media.rtp.muxId === transceiver.mid &&
1404
1627
  media.kind === transceiver.kind) ??
@@ -1406,7 +1629,9 @@ class RTCPeerConnection extends helper_1.EventTarget {
1406
1629
  ? remoteDescription?.media[transceiver.mLineIndex]
1407
1630
  : undefined);
1408
1631
  if (remoteMedia && ["audio", "video"].includes(remoteMedia.kind)) {
1409
- 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);
1410
1635
  }
1411
1636
  else {
1412
1637
  this.transceiverManager.assignTransceiverCodecs(transceiver);
@@ -1420,18 +1645,30 @@ class RTCPeerConnection extends helper_1.EventTarget {
1420
1645
  transceivers: this.transceiverManager.getTransceivers(),
1421
1646
  sctpTransport: this.sctpTransport,
1422
1647
  signalingState: this.signalingState,
1648
+ transportByMid: this.negotiation.transportByMid,
1423
1649
  });
1424
1650
  const createdAnswer = description.toJSON();
1425
1651
  this.lastCreatedAnswer = createdAnswer;
1426
1652
  return createdAnswer;
1427
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
+ }
1428
1663
  assertNotClosed() {
1429
1664
  if (this.isClosed) {
1430
1665
  throw (0, errors_1.createWebRtcDomException)("InvalidStateError", "RTCPeerConnection is closed");
1431
1666
  }
1432
1667
  }
1433
1668
  setSignalingState(state) {
1434
- 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") {
1435
1672
  return;
1436
1673
  }
1437
1674
  log("signalingStateChange", state);
@@ -1471,15 +1708,22 @@ class RTCPeerConnection extends helper_1.EventTarget {
1471
1708
  }
1472
1709
  return (0, stats_1.buildStatsReport)(stats, this.transceiverManager.getStatsRootIds(selector));
1473
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
+ */
1474
1717
  async close() {
1475
1718
  if (this.isClosed)
1476
1719
  return;
1477
1720
  this.isClosed = true;
1478
- this.pendingRemoteCandidates.length = 0;
1721
+ this.remoteCandidates.queued.length = 0;
1479
1722
  this.setSignalingState("closed");
1480
1723
  this.transceiverManager.close();
1481
1724
  // SCTP ABORT は DTLS/ICE が生きている間に送る(close は abrupt であり SHUTDOWN ではない)
1482
1725
  await this.sctpManager.close();
1726
+ await this.negotiation.dispose();
1483
1727
  await this.secureManager.close();
1484
1728
  // 公開 Event を完了させ、購読者・クロージャが PeerConnection を保持し続けないようにする
1485
1729
  this.completePeerEvents();
@@ -1505,190 +1749,11 @@ class RTCPeerConnection extends helper_1.EventTarget {
1505
1749
  }
1506
1750
  }
1507
1751
  exports.RTCPeerConnection = RTCPeerConnection;
1508
- const MLineReuseModes = ["compatible", "aggressive"];
1509
- const findCodecByMimeType = (codecs, target) => codecs.find((localCodec) => localCodec.mimeType.toLowerCase() === target.mimeType.toLowerCase())
1510
- ? target
1511
- : undefined;
1512
- exports.findCodecByMimeType = findCodecByMimeType;
1513
- function assignDynamicPayloadTypes(config) {
1514
- for (const [i, codecParams] of (0, helper_1.enumerate)([
1515
- ...(config.codecs.audio || []),
1516
- ...(config.codecs.video || []),
1517
- ])) {
1518
- if (codecParams.payloadType != undefined) {
1519
- continue;
1520
- }
1521
- codecParams.payloadType = 96 + i;
1522
- switch (codecParams.name.toLowerCase()) {
1523
- case "rtx":
1524
- {
1525
- codecParams.parameters = `apt=${codecParams.payloadType - 1}`;
1526
- }
1527
- break;
1528
- case "red":
1529
- {
1530
- if (codecParams.contentType === "audio") {
1531
- const redundant = codecParams.payloadType + 1;
1532
- codecParams.parameters = `${redundant}/${redundant}`;
1533
- codecParams.payloadType = 63;
1534
- }
1535
- }
1536
- break;
1537
- }
1538
- }
1539
- }
1540
- function generateDefaultPeerConfig() {
1541
- return {
1542
- codecs: (0, media_1.defaultCodecs)(),
1543
- headerExtensions: {
1544
- audio: [],
1545
- video: [],
1546
- },
1547
- iceTransportPolicy: "all",
1548
- iceLite: false,
1549
- iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
1550
- icePortRange: undefined,
1551
- iceInterfaceAddresses: undefined,
1552
- iceAdditionalHostAddresses: undefined,
1553
- iceUseIpv4: true,
1554
- iceUseIpv6: true,
1555
- iceUseTcp: false,
1556
- iceTcpPassive: true,
1557
- iceStunGatherTimeout: undefined,
1558
- iceTurnConnectTimeout: undefined,
1559
- turnTransport: undefined,
1560
- turnTlsOptions: undefined,
1561
- turnUdpFamily: undefined,
1562
- iceFilterStunResponse: undefined,
1563
- iceFilterCandidatePair: undefined,
1564
- icePasswordPrefix: undefined,
1565
- iceUseLinkLocalAddress: undefined,
1566
- dtls: {},
1567
- bundlePolicy: "max-compat",
1568
- rtcpMuxPolicy: "require",
1569
- iceCandidatePoolSize: 0,
1570
- certificates: [],
1571
- debug: {},
1572
- midSuffix: false,
1573
- forceTurnTCP: false,
1574
- maxMessageSize: sctp_1.DEFAULT_MAX_MESSAGE_SIZE,
1575
- sctp: { mtu: src_1.DEFAULT_SCTP_MTU },
1576
- pendingRtp: false,
1577
- mLineReuse: "compatible",
1578
- };
1579
- }
1580
- exports.defaultPeerConfig = generateDefaultPeerConfig();
1581
- function normalizePeerConfiguration(config) {
1582
- const input = Object(config ?? {});
1583
- const normalizedConfig = { ...input };
1584
- if (input.sctp !== undefined) {
1585
- normalizedConfig.sctp = { ...input.sctp };
1586
- }
1587
- if (input.bundlePolicy === "balanced") {
1588
- normalizedConfig.bundlePolicy = "max-compat";
1589
- }
1590
- if ("certificates" in input) {
1591
- if (input.certificates === undefined) {
1592
- normalizedConfig.certificates = undefined;
1593
- }
1594
- else if (!Array.isArray(input.certificates) ||
1595
- input.certificates.some((certificate) => certificate == null)) {
1596
- throw (0, errors_1.createWebRtcTypeError)("certificates must be an array of RTCCertificate");
1597
- }
1598
- else {
1599
- normalizedConfig.certificates = [...input.certificates];
1600
- }
1601
- }
1602
- if ("iceCandidatePoolSize" in input) {
1603
- normalizedConfig.iceCandidatePoolSize = coerceUnsignedShort(input.iceCandidatePoolSize, "iceCandidatePoolSize");
1604
- }
1605
- return normalizedConfig;
1606
- }
1607
- function coerceUnsignedShort(value, name) {
1608
- const coerced = Number(value);
1609
- if (!Number.isFinite(coerced) ||
1610
- !Number.isInteger(coerced) ||
1611
- coerced < 0 ||
1612
- coerced > 65535) {
1613
- throw (0, errors_1.createWebRtcTypeError)(`${name} must be an unsigned short`);
1614
- }
1615
- return coerced;
1616
- }
1617
- function hasSameCertificates(left, right) {
1618
- return (left.length === right.length &&
1619
- left.every((certificate, index) => certificate === right[index]));
1620
- }
1621
- function clonePeerConfiguration(config) {
1622
- return {
1623
- ...config,
1624
- codecs: {
1625
- audio: config.codecs.audio ? [...config.codecs.audio] : undefined,
1626
- video: config.codecs.video ? [...config.codecs.video] : undefined,
1627
- },
1628
- headerExtensions: {
1629
- audio: config.headerExtensions.audio
1630
- ? [...config.headerExtensions.audio]
1631
- : undefined,
1632
- video: config.headerExtensions.video
1633
- ? [...config.headerExtensions.video]
1634
- : undefined,
1635
- },
1636
- iceServers: config.iceServers.map((server) => ({
1637
- ...server,
1638
- urls: Array.isArray(server.urls) ? [...server.urls] : server.urls,
1639
- })),
1640
- icePortRange: config.icePortRange
1641
- ? [...config.icePortRange]
1642
- : undefined,
1643
- iceAdditionalHostAddresses: config.iceAdditionalHostAddresses
1644
- ? [...config.iceAdditionalHostAddresses]
1645
- : undefined,
1646
- dtls: { ...config.dtls },
1647
- certificates: [...config.certificates],
1648
- debug: { ...config.debug },
1649
- sctp: { ...config.sctp },
1650
- pendingRtp: typeof config.pendingRtp === "object" && config.pendingRtp != undefined
1651
- ? { ...config.pendingRtp }
1652
- : config.pendingRtp,
1653
- };
1654
- }
1655
- class RTCTrackEvent {
1656
- constructor(init) {
1657
- Object.defineProperty(this, "type", {
1658
- enumerable: true,
1659
- configurable: true,
1660
- writable: true,
1661
- value: "track"
1662
- });
1663
- Object.defineProperty(this, "track", {
1664
- enumerable: true,
1665
- configurable: true,
1666
- writable: true,
1667
- value: void 0
1668
- });
1669
- Object.defineProperty(this, "streams", {
1670
- enumerable: true,
1671
- configurable: true,
1672
- writable: true,
1673
- value: void 0
1674
- });
1675
- Object.defineProperty(this, "transceiver", {
1676
- enumerable: true,
1677
- configurable: true,
1678
- writable: true,
1679
- value: void 0
1680
- });
1681
- Object.defineProperty(this, "receiver", {
1682
- enumerable: true,
1683
- configurable: true,
1684
- writable: true,
1685
- value: void 0
1686
- });
1687
- this.track = init.track;
1688
- this.streams = [...init.streams];
1689
- this.transceiver = init.transceiver;
1690
- this.receiver = init.receiver;
1691
- }
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 ?? "")));
1692
1758
  }
1693
- exports.RTCTrackEvent = RTCTrackEvent;
1694
1759
  //# sourceMappingURL=peerConnection.js.map