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