werift 0.27.0 → 0.28.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 (224) hide show
  1. package/README.md +119 -8
  2. package/lib/common/src/event.d.ts +26 -0
  3. package/lib/common/src/event.js +87 -2
  4. package/lib/common/src/event.js.map +1 -1
  5. package/lib/common/src/network.d.ts +6 -1
  6. package/lib/common/src/network.js +8 -2
  7. package/lib/common/src/network.js.map +1 -1
  8. package/lib/common/src/transport.d.ts +12 -5
  9. package/lib/common/src/transport.js +3 -2
  10. package/lib/common/src/transport.js.map +1 -1
  11. package/lib/dtls/src/alert.d.ts +49 -0
  12. package/lib/dtls/src/alert.js +103 -0
  13. package/lib/dtls/src/alert.js.map +1 -0
  14. package/lib/dtls/src/client.js +15 -1
  15. package/lib/dtls/src/client.js.map +1 -1
  16. package/lib/dtls/src/context/dtls.d.ts +2 -0
  17. package/lib/dtls/src/context/dtls.js +7 -0
  18. package/lib/dtls/src/context/dtls.js.map +1 -1
  19. package/lib/dtls/src/context/transport.d.ts +17 -1
  20. package/lib/dtls/src/context/transport.js +38 -2
  21. package/lib/dtls/src/context/transport.js.map +1 -1
  22. package/lib/dtls/src/flight/client/flight5.js +4 -1
  23. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  24. package/lib/dtls/src/flight/flight.d.ts +5 -0
  25. package/lib/dtls/src/flight/flight.js +10 -1
  26. package/lib/dtls/src/flight/flight.js.map +1 -1
  27. package/lib/dtls/src/flight/server/flight6.js +4 -1
  28. package/lib/dtls/src/flight/server/flight6.js.map +1 -1
  29. package/lib/dtls/src/index.d.ts +3 -1
  30. package/lib/dtls/src/index.js +10 -1
  31. package/lib/dtls/src/index.js.map +1 -1
  32. package/lib/dtls/src/record/const.d.ts +9 -0
  33. package/lib/dtls/src/record/const.js +9 -1
  34. package/lib/dtls/src/record/const.js.map +1 -1
  35. package/lib/dtls/src/record/receive.d.ts +6 -0
  36. package/lib/dtls/src/record/receive.js +50 -19
  37. package/lib/dtls/src/record/receive.js.map +1 -1
  38. package/lib/dtls/src/server.js +19 -1
  39. package/lib/dtls/src/server.js.map +1 -1
  40. package/lib/dtls/src/socket.d.ts +134 -2
  41. package/lib/dtls/src/socket.js +322 -6
  42. package/lib/dtls/src/socket.js.map +1 -1
  43. package/lib/ice/src/candidateError.d.ts +155 -0
  44. package/lib/ice/src/candidateError.js +246 -0
  45. package/lib/ice/src/candidateError.js.map +1 -0
  46. package/lib/ice/src/candidateGatherer.d.ts +127 -0
  47. package/lib/ice/src/candidateGatherer.js +745 -0
  48. package/lib/ice/src/candidateGatherer.js.map +1 -0
  49. package/lib/ice/src/consent.d.ts +49 -0
  50. package/lib/ice/src/consent.js +258 -0
  51. package/lib/ice/src/consent.js.map +1 -0
  52. package/lib/ice/src/ice.d.ts +223 -71
  53. package/lib/ice/src/ice.js +873 -975
  54. package/lib/ice/src/ice.js.map +1 -1
  55. package/lib/ice/src/iceBase.d.ts +207 -8
  56. package/lib/ice/src/iceBase.js +94 -31
  57. package/lib/ice/src/iceBase.js.map +1 -1
  58. package/lib/ice/src/index.d.ts +1 -0
  59. package/lib/ice/src/index.js +1 -0
  60. package/lib/ice/src/index.js.map +1 -1
  61. package/lib/ice/src/internal/checkMessages.d.ts +41 -0
  62. package/lib/ice/src/internal/checkMessages.js +63 -0
  63. package/lib/ice/src/internal/checkMessages.js.map +1 -0
  64. package/lib/ice/src/internal/defaultRoute.d.ts +20 -0
  65. package/lib/ice/src/internal/defaultRoute.js +134 -0
  66. package/lib/ice/src/internal/defaultRoute.js.map +1 -0
  67. package/lib/ice/src/internal/hostInterfaces.d.ts +17 -0
  68. package/lib/ice/src/internal/hostInterfaces.js +77 -0
  69. package/lib/ice/src/internal/hostInterfaces.js.map +1 -0
  70. package/lib/ice/src/internal/hostPreference.d.ts +24 -0
  71. package/lib/ice/src/internal/hostPreference.js +38 -0
  72. package/lib/ice/src/internal/hostPreference.js.map +1 -0
  73. package/lib/ice/src/internal/resolveHostAddresses.d.ts +56 -8
  74. package/lib/ice/src/internal/resolveHostAddresses.js +127 -24
  75. package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -1
  76. package/lib/ice/src/internal/selectAddresses.d.ts +27 -0
  77. package/lib/ice/src/internal/selectAddresses.js +37 -18
  78. package/lib/ice/src/internal/selectAddresses.js.map +1 -1
  79. package/lib/ice/src/nomination/regularNomination.d.ts +200 -0
  80. package/lib/ice/src/nomination/regularNomination.js +311 -0
  81. package/lib/ice/src/nomination/regularNomination.js.map +1 -0
  82. package/lib/ice/src/nomination/selectionReplacement.d.ts +138 -0
  83. package/lib/ice/src/nomination/selectionReplacement.js +371 -0
  84. package/lib/ice/src/nomination/selectionReplacement.js.map +1 -0
  85. package/lib/ice/src/provisional.d.ts +139 -0
  86. package/lib/ice/src/provisional.js +468 -0
  87. package/lib/ice/src/provisional.js.map +1 -0
  88. package/lib/ice/src/stun/protocol.d.ts +9 -2
  89. package/lib/ice/src/stun/protocol.js +16 -17
  90. package/lib/ice/src/stun/protocol.js.map +1 -1
  91. package/lib/ice/src/stun/tcpProtocol.d.ts +1 -1
  92. package/lib/ice/src/stun/tcpProtocol.js +7 -7
  93. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  94. package/lib/ice/src/stun/transaction.js +4 -2
  95. package/lib/ice/src/stun/transaction.js.map +1 -1
  96. package/lib/ice/src/turn/protocol.d.ts +2 -2
  97. package/lib/ice/src/turn/protocol.js +6 -3
  98. package/lib/ice/src/turn/protocol.js.map +1 -1
  99. package/lib/ice/src/types/model.d.ts +16 -5
  100. package/lib/ice/src/types/model.js.map +1 -1
  101. package/lib/ice-server/src/stun/attributes.js +4 -0
  102. package/lib/ice-server/src/stun/attributes.js.map +1 -1
  103. package/lib/ice-server/src/stun/const.d.ts +20 -1
  104. package/lib/ice-server/src/stun/const.js +9 -1
  105. package/lib/ice-server/src/stun/const.js.map +1 -1
  106. package/lib/ice-server/src/stun/message.d.ts +28 -1
  107. package/lib/ice-server/src/stun/message.js +102 -15
  108. package/lib/ice-server/src/stun/message.js.map +1 -1
  109. package/lib/index.mjs +13394 -7732
  110. package/lib/nonstandard/index.mjs +680 -286
  111. package/lib/polyfill/dom.mjs +19605 -14243
  112. package/lib/polyfill/index.mjs +19605 -14243
  113. package/lib/rtp/src/index.d.ts +1 -0
  114. package/lib/rtp/src/index.js +1 -0
  115. package/lib/rtp/src/index.js.map +1 -1
  116. package/lib/rtp/src/rtp/continuity.d.ts +14 -1
  117. package/lib/rtp/src/rtp/continuity.js +24 -4
  118. package/lib/rtp/src/rtp/continuity.js.map +1 -1
  119. package/lib/rtp/src/rtp/timelineRewriter.d.ts +178 -0
  120. package/lib/rtp/src/rtp/timelineRewriter.js +417 -0
  121. package/lib/rtp/src/rtp/timelineRewriter.js.map +1 -0
  122. package/lib/sctp/src/sctp.d.ts +5 -0
  123. package/lib/sctp/src/sctp.js +81 -47
  124. package/lib/sctp/src/sctp.js.map +1 -1
  125. package/lib/webrtc/src/api/compatibilityOptions.d.ts +33 -0
  126. package/lib/webrtc/src/api/compatibilityOptions.js +33 -0
  127. package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -0
  128. package/lib/webrtc/src/api/peerConfig.d.ts +348 -34
  129. package/lib/webrtc/src/api/peerConfig.js +90 -24
  130. package/lib/webrtc/src/api/peerConfig.js.map +1 -1
  131. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +77 -1
  132. package/lib/webrtc/src/api/peerConnectionEvents.js +105 -1
  133. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
  134. package/lib/webrtc/src/helper.d.ts +8 -0
  135. package/lib/webrtc/src/helper.js +40 -4
  136. package/lib/webrtc/src/helper.js.map +1 -1
  137. package/lib/webrtc/src/media/codecCompatibility.d.ts +87 -1
  138. package/lib/webrtc/src/media/codecCompatibility.js +338 -12
  139. package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
  140. package/lib/webrtc/src/media/receiver/nack.d.ts +43 -10
  141. package/lib/webrtc/src/media/receiver/nack.js +245 -88
  142. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  143. package/lib/webrtc/src/media/router.d.ts +239 -51
  144. package/lib/webrtc/src/media/router.js +664 -237
  145. package/lib/webrtc/src/media/router.js.map +1 -1
  146. package/lib/webrtc/src/media/routing/pendingRoutes.d.ts +26 -0
  147. package/lib/webrtc/src/media/routing/pendingRoutes.js +48 -0
  148. package/lib/webrtc/src/media/routing/pendingRoutes.js.map +1 -0
  149. package/lib/webrtc/src/media/routing/ridRouting.d.ts +37 -0
  150. package/lib/webrtc/src/media/routing/ridRouting.js +74 -0
  151. package/lib/webrtc/src/media/routing/ridRouting.js.map +1 -0
  152. package/lib/webrtc/src/media/routing/routeTable.d.ts +60 -0
  153. package/lib/webrtc/src/media/routing/routeTable.js +95 -0
  154. package/lib/webrtc/src/media/routing/routeTable.js.map +1 -0
  155. package/lib/webrtc/src/media/routing/rtcpRouting.d.ts +34 -0
  156. package/lib/webrtc/src/media/routing/rtcpRouting.js +165 -0
  157. package/lib/webrtc/src/media/routing/rtcpRouting.js.map +1 -0
  158. package/lib/webrtc/src/media/routing/unknownSsrc.d.ts +55 -0
  159. package/lib/webrtc/src/media/routing/unknownSsrc.js +117 -0
  160. package/lib/webrtc/src/media/routing/unknownSsrc.js.map +1 -0
  161. package/lib/webrtc/src/media/rtpReceiver.d.ts +222 -0
  162. package/lib/webrtc/src/media/rtpReceiver.js +668 -28
  163. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  164. package/lib/webrtc/src/media/rtpSender.d.ts +7 -0
  165. package/lib/webrtc/src/media/rtpSender.js +9 -3
  166. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  167. package/lib/webrtc/src/media/rtpTransceiver.d.ts +18 -0
  168. package/lib/webrtc/src/media/rtpTransceiver.js +64 -2
  169. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  170. package/lib/webrtc/src/media/sender/senderReportHistory.d.ts +51 -0
  171. package/lib/webrtc/src/media/sender/senderReportHistory.js +111 -0
  172. package/lib/webrtc/src/media/sender/senderReportHistory.js.map +1 -0
  173. package/lib/webrtc/src/media/sender/senderStats.d.ts +6 -5
  174. package/lib/webrtc/src/media/sender/senderStats.js +14 -19
  175. package/lib/webrtc/src/media/sender/senderStats.js.map +1 -1
  176. package/lib/webrtc/src/media/track.d.ts +9 -0
  177. package/lib/webrtc/src/media/track.js +9 -0
  178. package/lib/webrtc/src/media/track.js.map +1 -1
  179. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +23 -6
  180. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +46 -22
  181. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -1
  182. package/lib/webrtc/src/negotiation/transceiverPairing.d.ts +1 -0
  183. package/lib/webrtc/src/negotiation/transceiverPairing.js +62 -0
  184. package/lib/webrtc/src/negotiation/transceiverPairing.js.map +1 -0
  185. package/lib/webrtc/src/negotiation/transportActivation.d.ts +8 -1
  186. package/lib/webrtc/src/negotiation/transportActivation.js +21 -0
  187. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
  188. package/lib/webrtc/src/negotiationTransaction.d.ts +35 -4
  189. package/lib/webrtc/src/negotiationTransaction.js +111 -8
  190. package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
  191. package/lib/webrtc/src/peerConnection.d.ts +65 -6
  192. package/lib/webrtc/src/peerConnection.js +283 -28
  193. package/lib/webrtc/src/peerConnection.js.map +1 -1
  194. package/lib/webrtc/src/polyfill/globals.d.ts +2 -1
  195. package/lib/webrtc/src/polyfill/globals.js.map +1 -1
  196. package/lib/webrtc/src/polyfill/install.js +2 -0
  197. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  198. package/lib/webrtc/src/sctpManager.js +4 -0
  199. package/lib/webrtc/src/sctpManager.js.map +1 -1
  200. package/lib/webrtc/src/sdp.d.ts +69 -0
  201. package/lib/webrtc/src/sdp.js +139 -14
  202. package/lib/webrtc/src/sdp.js.map +1 -1
  203. package/lib/webrtc/src/sdpManager.d.ts +85 -4
  204. package/lib/webrtc/src/sdpManager.js +214 -14
  205. package/lib/webrtc/src/sdpManager.js.map +1 -1
  206. package/lib/webrtc/src/secureTransportManager.d.ts +38 -1
  207. package/lib/webrtc/src/secureTransportManager.js +82 -7
  208. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  209. package/lib/webrtc/src/transceiverManager.d.ts +82 -4
  210. package/lib/webrtc/src/transceiverManager.js +231 -38
  211. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  212. package/lib/webrtc/src/transport/dtls.d.ts +95 -1
  213. package/lib/webrtc/src/transport/dtls.js +324 -28
  214. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  215. package/lib/webrtc/src/transport/ice.d.ts +61 -4
  216. package/lib/webrtc/src/transport/ice.js +180 -11
  217. package/lib/webrtc/src/transport/ice.js.map +1 -1
  218. package/lib/webrtc/src/transport/sctp.d.ts +23 -0
  219. package/lib/webrtc/src/transport/sctp.js +87 -2
  220. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  221. package/lib/webrtc/src/utils.d.ts +33 -0
  222. package/lib/webrtc/src/utils.js +52 -3
  223. package/lib/webrtc/src/utils.js.map +1 -1
  224. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"transportActivation.js","sourceRoot":"","sources":["../../../../src/negotiation/transportActivation.ts"],"names":[],"mappings":";;;AAAA,2CAA+C;AAC/C,8CAAsD;AAYtD,MAAM,GAAG,GAAG,IAAA,cAAK,EACf,+DAA+D,CAChE,CAAC;AAEF;;;;;GAKG;AACH,MAAa,mBAAmB;IAmB9B,YACE,GAAe,EACf,MAA8B,EAC9B,YAAgC,EAChC,IAA0B,EAC1B,WAAmC,EACnC,QAAwB,EACxB,IAIC;QA7Bc;;;;;WAAgB;QAChB;;;;;WAA+B;QAC/B;;;;;WAAiC;QACjC;;;;;WAA2B;QAC3B;;;;;WAAoC;QACpC;;;;;WAAyB;QACzB;;;;;WAIf;QAEF;;;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CAAI,CAAC,OAAO,EAAE,EAAE;QAChC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACnC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;YACnB,OAAO;QACT,CAAC;QACD,MAAM,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC,SAAS,CACrC,CAAC,KAAK,EAAE,EAAE;YACR,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC;gBAAE,OAAO;YACzB,WAAW,EAAE,CAAC;YACd,OAAO,CAAC,KAAK,CAAC,CAAC;QACjB,CAAC,EACD,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CACzB,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { SCTP_STATE } from \"../../../sctp/src\";\nimport { debug, type Event } from \"../imports/common\";\nimport type { TransceiverManager } from \"../media\";\nimport type { NegotiationTransaction } from \"../negotiationTransaction\";\nimport type { SctpTransportManager } from \"../sctpManager\";\nimport type { MediaDescription } from \"../sdp\";\nimport type { SDPManager } from \"../sdpManager\";\nimport type { SecureTransportManager } from \"../secureTransportManager\";\nimport type { RTCDtlsTransport } from \"../transport/dtls\";\nimport type { RTCIceTransport } from \"../transport/ice\";\nimport type { RTCSignalingState } from \"../types/domain\";\nimport type { BundleTopology } from \"./bundleTopology\";\n\nconst log = debug(\n \"werift:packages/webrtc/src/negotiation/transportActivation.ts\",\n);\n\n/**\n * Starting transports for a negotiation: connecting the live ICE / DTLS /\n * SCTP bindings, connecting a provisional (pranswer) generation beside them,\n * activating the transport parameters a re-offer staged once its answer\n * commits, and retiring a first negotiation's provisional connection.\n */\nexport class TransportActivation {\n private readonly sdp: SDPManager;\n private readonly secure: SecureTransportManager;\n private readonly transceivers: TransceiverManager;\n private readonly sctp: SctpTransportManager;\n private readonly negotiation: NegotiationTransaction;\n private readonly topology: BundleTopology;\n private readonly host: {\n signalingState: () => RTCSignalingState;\n /** The transport a transceiver starts on (BUNDLE policy aware). */\n createTransport: () => RTCDtlsTransport;\n };\n\n /**\n * Bumped when a first negotiation's provisional connection is retired: a\n * connect() still running for it no longer reports a connection state.\n */\n private connectEpoch = 0;\n\n constructor(\n sdp: SDPManager,\n secure: SecureTransportManager,\n transceivers: TransceiverManager,\n sctp: SctpTransportManager,\n negotiation: NegotiationTransaction,\n topology: BundleTopology,\n host: {\n signalingState: () => RTCSignalingState;\n /** The transport a transceiver starts on (BUNDLE policy aware). */\n createTransport: () => RTCDtlsTransport;\n },\n ) {\n this.sdp = sdp;\n this.secure = secure;\n this.transceivers = transceivers;\n this.sctp = sctp;\n this.negotiation = negotiation;\n this.topology = topology;\n this.host = host;\n }\n\n /** Retire a first negotiation's provisional connection without losing app objects. */\n async cleanupInitialProvisional() {\n if (this.sdp.currentLocalDescription || this.sdp.currentRemoteDescription) {\n return;\n }\n this.connectEpoch++;\n const transports = [...this.secure.dtlsTransports];\n // A transport the rolled-back proposal connected, or only gave remote\n // credentials and candidates, is replaced: nothing of it stays live.\n if (\n transports.some(\n (dtls) =>\n dtls.state !== \"new\" ||\n ![\"new\", \"closed\"].includes(dtls.iceTransport.state) ||\n !!dtls.iceTransport.getRemoteParameters(),\n )\n ) {\n if (this.sctp.sctpTransport) {\n await this.sctp.sctpTransport.stop();\n this.sctp.sctpRemotePort = undefined;\n }\n await Promise.all(transports.map((dtls) => dtls.stop()));\n for (const transceiver of this.transceivers.getTransceivers()) {\n transceiver.setDtlsTransport(this.host.createTransport());\n }\n if (this.sctp.sctpTransport) {\n this.sctp.sctpTransport.setDtlsTransport(this.host.createTransport());\n }\n }\n // Without a current session nothing is connected, whatever the\n // provisional connection had reported (the rolled-back proposal may also\n // have taken its transports with it): the public states start over.\n this.secure.updateIceConnectionState();\n this.secure.setConnectionState(\"new\");\n }\n\n /** Activate a re-offer's staged transport parameters at its final answer. */\n async activatePendingRemote(pendingOnly = false) {\n const offer = this.sdp.pendingRemoteDescription;\n if (!offer || offer.type !== \"offer\") return;\n type Media = (typeof offer.media)[number];\n // A BUNDLE group shares one transport: the tag m-line carries its ICE /\n // DTLS parameters, and candidates or end-of-candidates trickled on any\n // member m-line belong to that transport's generation.\n type TransportEntry = {\n provisional: boolean;\n tag?: Media;\n candidates: Map<string, Media[\"iceCandidates\"][number]>;\n eoc: boolean;\n members: Media[];\n };\n const byTransport = new Map<RTCIceTransport, TransportEntry>();\n for (const [index, media] of offer.media.entries()) {\n if (media.port === 0) continue;\n const dtls =\n (media.rtp.muxId &&\n this.negotiation.transportByMid.get(media.rtp.muxId)) ||\n (media.kind === \"application\"\n ? this.sctp.sctpTransport?.dtlsTransport\n : this.transceivers\n .getTransceivers()\n .find((t) => t.mid === media.rtp.muxId)?.dtlsTransport);\n if (!dtls) continue;\n const bundledNonTag = this.topology.isBundledNonTag(\n offer,\n media.rtp.muxId,\n );\n // A restart on a transport that keeps its SCTP association checks the\n // new generation beside the selected current pair.\n const provisional =\n pendingOnly &&\n !this.negotiation.isPendingOnlyTransport(dtls.iceTransport.id);\n if (media.kind === \"application\") {\n if (provisional) this.sctp.updateRemoteMaxMessageSize(media);\n else this.sctp.setRemoteSCTP(media, index);\n }\n const entry: TransportEntry = byTransport.get(dtls.iceTransport) ?? {\n provisional,\n candidates: new Map(),\n eoc: false,\n members: [],\n };\n byTransport.set(dtls.iceTransport, entry);\n entry.members.push(media);\n if (!bundledNonTag) {\n entry.tag = media;\n if (!provisional) {\n if (media.iceParams) {\n dtls.iceTransport.setRemoteParams(media.iceParams);\n }\n if (media.dtlsParams) dtls.setRemoteParams(media.dtlsParams);\n }\n }\n for (const candidate of media.iceCandidates) {\n entry.candidates.set(candidate.toJSON().candidate, candidate);\n }\n if (media.iceCandidatesComplete) entry.eoc = true;\n }\n for (const [transport, entry] of byTransport) {\n // A member's candidate of another ICE generation (its own ufrag) does\n // not belong to the tag's generation.\n const ufrag = entry.tag?.iceParams?.usernameFragment;\n for (const [key, candidate] of entry.candidates) {\n if (ufrag && candidate.ufrag && candidate.ufrag !== ufrag) {\n entry.candidates.delete(key);\n }\n }\n if (entry.provisional) {\n if (entry.tag) {\n await this.applyProvisionalIce(\n transport,\n entry.tag,\n [...entry.candidates.values()],\n entry.eoc,\n );\n }\n continue;\n }\n for (const candidate of entry.candidates.values()) {\n transport.deliverRemoteCandidate(candidate);\n }\n if (entry.eoc) transport.deliverRemoteCandidate(undefined);\n }\n // End-of-candidates completes the transport's generation, so every m-line\n // of the description it carries (a BUNDLE group) records it.\n for (const entry of byTransport.values()) {\n if (!entry.eoc) continue;\n for (const media of entry.members) media.iceCandidatesComplete = true;\n }\n }\n\n async applyProvisionalIce(\n iceTransport: RTCIceTransport,\n media: MediaDescription,\n candidates = media.iceCandidates,\n endOfCandidates = media.iceCandidatesComplete,\n ) {\n if (!iceTransport.hasStagedRestart || !media.iceParams) return;\n iceTransport.setProvisionalRemoteParams(media.iceParams);\n for (const candidate of candidates) {\n iceTransport.deliverProvisionalRemoteCandidate(candidate);\n }\n if (endOfCandidates) {\n iceTransport.deliverProvisionalRemoteCandidate(undefined);\n }\n }\n\n /**\n * Start ICE, DTLS and SCTP on every live transport that still needs it.\n *\n * ICE checks start only for a generation that has not run them (the first\n * negotiation or a committed restart); checks already running are\n * awaited, and an established, completed or failed generation is left to\n * its own state machine (consent freshness, a later ICE restart). A DTLS\n * handshake already running is awaited rather than started again. The\n * connection state changes only when this call started or awaited work.\n */\n async connect() {\n log(\"start connect\");\n const epoch = this.connectEpoch;\n\n const res = await Promise.allSettled(\n this.secure.dtlsTransports.map(async (dtlsTransport) => {\n const { iceTransport } = dtlsTransport;\n let progressed = false;\n let iceReady = [\"connected\", \"completed\"].includes(iceTransport.state);\n\n // Only a transport an applied description gave remote parameters\n // starts; one whose parameters arrive with a later description (a\n // renegotiation pranswer stages them for the final answer) waits.\n if (\n !iceTransport.checksStarted &&\n !iceTransport.getRemoteParameters()\n ) {\n return progressed;\n }\n if (!iceTransport.checksStarted) {\n progressed = true;\n this.secure.setConnectionState(\"connecting\");\n await iceTransport.start().catch((err) => {\n log(\"iceTransport.start failed\", err);\n throw err;\n });\n iceReady = true;\n } else if (iceTransport.state === \"checking\") {\n // Checks an earlier connect() (or a pranswer) started are awaited,\n // never started again.\n progressed = true;\n await iceTransport.checksSettled();\n iceReady = [\"connected\", \"completed\"].includes(iceTransport.state);\n if (!iceReady) {\n throw new Error(`ICE transport ${iceTransport.state}`);\n }\n }\n\n if (dtlsTransport.state === \"connecting\") {\n progressed = true;\n const state = await settledState(\n dtlsTransport.onStateChange,\n () => dtlsTransport.state,\n (state) => state !== \"connecting\",\n );\n if (state !== \"connected\") {\n throw new Error(`DTLS transport ${state}`);\n }\n this.startJoinedSctp(dtlsTransport);\n return true;\n }\n if (dtlsTransport.state === \"connected\") {\n this.startJoinedSctp(dtlsTransport);\n }\n if (\n dtlsTransport.state !== \"new\" ||\n !iceReady ||\n !dtlsTransport.hasRemoteParameters\n ) {\n return progressed;\n }\n\n progressed = true;\n this.secure.setConnectionState(\"connecting\");\n await dtlsTransport.start().catch((err) => {\n log(\"dtlsTransport.start failed\", err);\n throw err;\n });\n\n // SCTP on a newly started DTLS transport is ensured before this\n // transport activation completes.\n if (\n this.sctp.sctpTransport &&\n this.sctp.sctpTransport.dtlsTransport.id === dtlsTransport.id\n ) {\n await this.sctp.connectSctp();\n }\n return progressed;\n }),\n );\n\n if (epoch !== this.connectEpoch) return;\n if (res.find((r) => r.status === \"rejected\")) {\n this.secure.setConnectionState(\"failed\");\n } else if (res.some((r) => r.status === \"fulfilled\" && r.value)) {\n this.secure.setConnectionState(\"connected\");\n }\n }\n\n /**\n * An SCTP transport that joined an already connected DTLS transport (the\n * first application m-line of a renegotiation) starts its association\n * there; the DTLS start above only covers a new transport.\n */\n private startJoinedSctp(dtlsTransport: RTCDtlsTransport) {\n const sctp = this.sctp.sctpTransport;\n if (\n !sctp ||\n sctp.dtlsTransport !== dtlsTransport ||\n sctp.sctp.started ||\n sctp.sctp.associationState !== SCTP_STATE.CLOSED\n ) {\n return;\n }\n this.sctp.connectSctp().catch((error) => {\n log(\"sctp start failed\", error);\n });\n }\n\n /** Connect a provisional ICE/DTLS generation without changing live bindings. */\n async connectPending() {\n const pending = [\n ...new Set(this.negotiation.transportByMid.values()),\n ].filter((transport) =>\n this.negotiation.isPendingOnlyTransport(transport.iceTransport.id),\n );\n for (const iceTransport of this.secure.iceTransports) {\n if (!this.negotiation.isPendingOnlyTransport(iceTransport.id)) {\n iceTransport.startProvisionalChecks();\n }\n }\n // Like connect(): checks of a generation start once (a pranswer applied\n // again awaits the running ones, an established generation is left\n // alone), and a DTLS handshake starts once.\n await Promise.all(\n pending.map(async (transport) => {\n const { iceTransport } = transport;\n if (!iceTransport.checksStarted) {\n if (!iceTransport.getRemoteParameters()) return;\n iceTransport.connection.iceControlling =\n this.host.signalingState() === \"have-remote-pranswer\";\n await iceTransport.start();\n } else if (iceTransport.state === \"checking\") {\n await iceTransport.checksSettled();\n }\n if (![\"connected\", \"completed\"].includes(iceTransport.state)) return;\n if (transport.state === \"connecting\") {\n await settledState(\n transport.onStateChange,\n () => transport.state,\n (state) => state !== \"connecting\",\n );\n return;\n }\n if (transport.state === \"new\" && transport.hasRemoteParameters) {\n await transport.start();\n }\n }),\n );\n }\n}\n\n/**\n * The first state `done` accepts: the current one, or a later one `event`\n * reports. A completed event (the transport stopped) settles with the state\n * the transport is left in.\n */\nfunction settledState<S>(\n event: Event<[S]>,\n current: () => S,\n done: (state: S) => boolean,\n) {\n return new Promise<S>((resolve) => {\n if (done(current()) || event.ended) {\n resolve(current());\n return;\n }\n const { unSubscribe } = event.subscribe(\n (state) => {\n if (!done(state)) return;\n unSubscribe();\n resolve(state);\n },\n () => resolve(current()),\n );\n });\n}\n"]}
1
+ {"version":3,"file":"transportActivation.js","sourceRoot":"","sources":["../../../../src/negotiation/transportActivation.ts"],"names":[],"mappings":";;;AAAA,2CAA+C;AAC/C,8CAAsD;AAItD,gCAAgE;AAQhE,MAAM,GAAG,GAAG,IAAA,cAAK,EACf,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","sourcesContent":["import { SCTP_STATE } from \"../../../sctp/src\";\nimport { debug, type Event } from \"../imports/common\";\nimport type { TransceiverManager } from \"../media\";\nimport type { NegotiationTransaction } from \"../negotiationTransaction\";\nimport type { SctpTransportManager } from \"../sctpManager\";\nimport { type MediaDescription, parseIceOptions } from \"../sdp\";\nimport type { SDPManager } from \"../sdpManager\";\nimport type { SecureTransportManager } from \"../secureTransportManager\";\nimport type { RTCDtlsTransport } from \"../transport/dtls\";\nimport type { RTCIceTransport } from \"../transport/ice\";\nimport type { RTCSignalingState } from \"../types/domain\";\nimport type { BundleTopology } from \"./bundleTopology\";\n\nconst log = debug(\n \"werift:packages/webrtc/src/negotiation/transportActivation.ts\",\n);\n\n/**\n * Starting transports for a negotiation: connecting the live ICE / DTLS /\n * SCTP bindings, connecting a provisional (pranswer) generation beside them,\n * activating the transport parameters a re-offer staged once its answer\n * commits, and retiring a first negotiation's provisional connection.\n */\nexport class TransportActivation {\n private readonly sdp: SDPManager;\n private readonly secure: SecureTransportManager;\n private readonly transceivers: TransceiverManager;\n private readonly sctp: SctpTransportManager;\n private readonly negotiation: NegotiationTransaction;\n private readonly topology: BundleTopology;\n private readonly host: {\n signalingState: () => RTCSignalingState;\n /** The transport a transceiver starts on (BUNDLE policy aware). */\n createTransport: () => RTCDtlsTransport;\n };\n\n /**\n * Bumped when a first negotiation's provisional connection is retired: a\n * connect() still running for it no longer reports a connection state.\n */\n private connectEpoch = 0;\n\n constructor(\n sdp: SDPManager,\n secure: SecureTransportManager,\n transceivers: TransceiverManager,\n sctp: SctpTransportManager,\n negotiation: NegotiationTransaction,\n topology: BundleTopology,\n host: {\n signalingState: () => RTCSignalingState;\n /** The transport a transceiver starts on (BUNDLE policy aware). */\n createTransport: () => RTCDtlsTransport;\n },\n ) {\n this.sdp = sdp;\n this.secure = secure;\n this.transceivers = transceivers;\n this.sctp = sctp;\n this.negotiation = negotiation;\n this.topology = topology;\n this.host = host;\n }\n\n /** Retire a first negotiation's provisional connection without losing app objects. */\n async cleanupInitialProvisional() {\n if (this.sdp.currentLocalDescription || this.sdp.currentRemoteDescription) {\n return;\n }\n this.connectEpoch++;\n const transports = [...this.secure.dtlsTransports];\n // A transport the rolled-back proposal connected, or only gave remote\n // credentials and candidates, is replaced: nothing of it stays live.\n if (\n transports.some(\n (dtls) =>\n dtls.state !== \"new\" ||\n ![\"new\", \"closed\"].includes(dtls.iceTransport.state) ||\n !!dtls.iceTransport.getRemoteParameters(),\n )\n ) {\n if (this.sctp.sctpTransport) {\n await this.sctp.sctpTransport.stop();\n this.sctp.sctpRemotePort = undefined;\n }\n await Promise.all(transports.map((dtls) => dtls.stop()));\n for (const transceiver of this.transceivers.getTransceivers()) {\n transceiver.setDtlsTransport(this.host.createTransport());\n }\n if (this.sctp.sctpTransport) {\n this.sctp.sctpTransport.setDtlsTransport(this.host.createTransport());\n }\n }\n // Without a current session nothing is connected, whatever the\n // provisional connection had reported (the rolled-back proposal may also\n // have taken its transports with it): the public states start over.\n this.secure.updateIceConnectionState();\n this.secure.setConnectionState(\"new\");\n }\n\n /** Activate a re-offer's staged transport parameters at its final answer. */\n async activatePendingRemote(pendingOnly = false) {\n const offer = this.sdp.pendingRemoteDescription;\n if (!offer || offer.type !== \"offer\") return;\n type Media = (typeof offer.media)[number];\n // A BUNDLE group shares one transport: the tag m-line carries its ICE /\n // DTLS parameters, and candidates or end-of-candidates trickled on any\n // member m-line belong to that transport's generation.\n type TransportEntry = {\n provisional: boolean;\n tag?: Media;\n candidates: Map<string, Media[\"iceCandidates\"][number]>;\n eoc: boolean;\n members: Media[];\n };\n const byTransport = new Map<RTCIceTransport, TransportEntry>();\n for (const [index, media] of offer.media.entries()) {\n if (media.port === 0) continue;\n const dtls =\n (media.rtp.muxId &&\n this.negotiation.transportByMid.get(media.rtp.muxId)) ||\n (media.kind === \"application\"\n ? this.sctp.sctpTransport?.dtlsTransport\n : this.transceivers\n .getTransceivers()\n .find((t) => t.mid === media.rtp.muxId)?.dtlsTransport);\n if (!dtls) continue;\n const bundledNonTag = this.topology.isBundledNonTag(\n offer,\n media.rtp.muxId,\n );\n // A restart on a transport that keeps its SCTP association checks the\n // new generation beside the selected current pair.\n const provisional =\n pendingOnly &&\n !this.negotiation.isPendingOnlyTransport(dtls.iceTransport.id);\n if (media.kind === \"application\") {\n if (provisional) this.sctp.updateRemoteMaxMessageSize(media);\n else this.sctp.setRemoteSCTP(media, index);\n }\n const entry: TransportEntry = byTransport.get(dtls.iceTransport) ?? {\n provisional,\n candidates: new Map(),\n eoc: false,\n members: [],\n };\n byTransport.set(dtls.iceTransport, entry);\n entry.members.push(media);\n if (!bundledNonTag) {\n entry.tag = media;\n if (!provisional) {\n if (media.iceParams) {\n dtls.iceTransport.setRemoteParams(media.iceParams);\n dtls.iceTransport.setRemoteIceOptions(\n parseIceOptions(media.iceOptions),\n );\n }\n if (media.dtlsParams) dtls.setRemoteParams(media.dtlsParams);\n }\n }\n for (const candidate of media.iceCandidates) {\n entry.candidates.set(candidate.toJSON().candidate, candidate);\n }\n if (media.iceCandidatesComplete) entry.eoc = true;\n }\n for (const [transport, entry] of byTransport) {\n // A member's candidate of another ICE generation (its own ufrag) does\n // not belong to the tag's generation.\n const ufrag = entry.tag?.iceParams?.usernameFragment;\n for (const [key, candidate] of entry.candidates) {\n if (ufrag && candidate.ufrag && candidate.ufrag !== ufrag) {\n entry.candidates.delete(key);\n }\n }\n if (entry.provisional) {\n if (entry.tag) {\n await this.applyProvisionalIce(\n transport,\n entry.tag,\n [...entry.candidates.values()],\n entry.eoc,\n );\n }\n continue;\n }\n for (const candidate of entry.candidates.values()) {\n transport.deliverRemoteCandidate(candidate);\n }\n if (entry.eoc) transport.deliverRemoteCandidate(undefined);\n }\n // End-of-candidates completes the transport's generation, so every m-line\n // of the description it carries (a BUNDLE group) records it.\n for (const entry of byTransport.values()) {\n if (!entry.eoc) continue;\n for (const media of entry.members) media.iceCandidatesComplete = true;\n }\n }\n\n async applyProvisionalIce(\n iceTransport: RTCIceTransport,\n media: MediaDescription,\n candidates = media.iceCandidates,\n endOfCandidates = media.iceCandidatesComplete,\n ) {\n if (!iceTransport.hasStagedRestart || !media.iceParams) return;\n iceTransport.setProvisionalRemoteParams(media.iceParams);\n for (const candidate of candidates) {\n iceTransport.deliverProvisionalRemoteCandidate(candidate);\n }\n if (endOfCandidates) {\n iceTransport.deliverProvisionalRemoteCandidate(undefined);\n }\n }\n\n /**\n * Start ICE, DTLS and SCTP on every live transport that still needs it.\n *\n * ICE checks start only for a generation that has not run them (the first\n * negotiation or a committed restart); checks already running are\n * awaited, and an established, completed or failed generation is left to\n * its own state machine (consent freshness, a later ICE restart). A DTLS\n * handshake already running is awaited rather than started again. The\n * connection state changes only when this call started or awaited work.\n *\n * A DTLS transport that a live m-line still uses and that ends before it\n * was established makes `connectionState` `failed`, whether it became\n * `failed` (a fatal alert, a rejected certificate) or `closed` (the peer's\n * close_notify, a local `stop()`), so the attempt never stays\n * `connecting`. A retired transport (renegotiation, `close()`) leaves the\n * state to its owner.\n */\n async connect() {\n log(\"start connect\");\n const epoch = this.connectEpoch;\n\n const res = await Promise.allSettled(\n this.secure.dtlsTransports.map(async (dtlsTransport) => {\n const { iceTransport } = dtlsTransport;\n let progressed = false;\n let iceReady = [\"connected\", \"completed\"].includes(iceTransport.state);\n\n // Only a transport an applied description gave remote parameters\n // starts; one whose parameters arrive with a later description (a\n // renegotiation pranswer stages them for the final answer) waits.\n if (\n !iceTransport.checksStarted &&\n !iceTransport.getRemoteParameters()\n ) {\n return progressed;\n }\n if (!iceTransport.checksStarted) {\n progressed = true;\n this.secure.setConnectionState(\"connecting\");\n await iceTransport.start().catch((err) => {\n log(\"iceTransport.start failed\", err);\n throw err;\n });\n iceReady = true;\n } else if (iceTransport.state === \"checking\") {\n // Checks an earlier connect() (or a pranswer) started are awaited,\n // never started again.\n progressed = true;\n await iceTransport.checksSettled();\n iceReady = [\"connected\", \"completed\"].includes(iceTransport.state);\n if (!iceReady) {\n throw new Error(`ICE transport ${iceTransport.state}`);\n }\n }\n\n if (dtlsTransport.state === \"connecting\") {\n progressed = true;\n const state = await settledState(\n dtlsTransport.onStateChange,\n () => dtlsTransport.state,\n (state) => state !== \"connecting\",\n );\n if (state !== \"connected\") {\n throw new Error(`DTLS transport ${state}`);\n }\n this.startJoinedSctp(dtlsTransport);\n return true;\n }\n if (dtlsTransport.state === \"connected\") {\n this.startJoinedSctp(dtlsTransport);\n }\n if (\n dtlsTransport.state !== \"new\" ||\n !iceReady ||\n !dtlsTransport.hasRemoteParameters\n ) {\n return progressed;\n }\n\n progressed = true;\n this.secure.setConnectionState(\"connecting\");\n await dtlsTransport.start().catch((err) => {\n log(\"dtlsTransport.start failed\", err);\n throw err;\n });\n\n // start() also returns when the transport was closed meanwhile\n // (stop()): it never connected, so neither SCTP nor the connected\n // connectionState follows. A transport a live m-line still uses ends\n // the connection attempt as failed, so connecting never lingers; one\n // that was retired (renegotiation, close()) leaves the state to its\n // owner.\n if (\n (dtlsTransport.state as RTCDtlsTransport[\"state\"]) !== \"connected\"\n ) {\n if (this.secure.dtlsTransports.includes(dtlsTransport)) {\n throw new Error(`DTLS transport ${dtlsTransport.state}`);\n }\n return false;\n }\n\n // SCTP on a newly started DTLS transport is ensured before this\n // transport activation completes.\n if (\n this.sctp.sctpTransport &&\n this.sctp.sctpTransport.dtlsTransport.id === dtlsTransport.id\n ) {\n await this.sctp.connectSctp();\n }\n return progressed;\n }),\n );\n\n if (epoch !== this.connectEpoch) return;\n if (res.find((r) => r.status === \"rejected\")) {\n this.secure.setConnectionState(\"failed\");\n } else if (res.some((r) => r.status === \"fulfilled\" && r.value)) {\n this.secure.setConnectionState(\"connected\");\n }\n }\n\n /**\n * An SCTP transport that joined an already connected DTLS transport (the\n * first application m-line of a renegotiation) starts its association\n * there; the DTLS start above only covers a new transport.\n */\n private startJoinedSctp(dtlsTransport: RTCDtlsTransport) {\n const sctp = this.sctp.sctpTransport;\n if (\n !sctp ||\n sctp.dtlsTransport !== dtlsTransport ||\n sctp.sctp.started ||\n sctp.sctp.associationState !== SCTP_STATE.CLOSED\n ) {\n return;\n }\n this.sctp.connectSctp().catch((error) => {\n log(\"sctp start failed\", error);\n });\n }\n\n /** Connect a provisional ICE/DTLS generation without changing live bindings. */\n async connectPending() {\n const pending = [\n ...new Set(this.negotiation.transportByMid.values()),\n ].filter((transport) =>\n this.negotiation.isPendingOnlyTransport(transport.iceTransport.id),\n );\n for (const iceTransport of this.secure.iceTransports) {\n if (!this.negotiation.isPendingOnlyTransport(iceTransport.id)) {\n iceTransport.startProvisionalChecks();\n }\n }\n // Like connect(): checks of a generation start once (a pranswer applied\n // again awaits the running ones, an established generation is left\n // alone), and a DTLS handshake starts once.\n await Promise.all(\n pending.map(async (transport) => {\n const { iceTransport } = transport;\n if (!iceTransport.checksStarted) {\n if (!iceTransport.getRemoteParameters()) return;\n iceTransport.connection.iceControlling =\n this.host.signalingState() === \"have-remote-pranswer\";\n await iceTransport.start();\n } else if (iceTransport.state === \"checking\") {\n await iceTransport.checksSettled();\n }\n if (![\"connected\", \"completed\"].includes(iceTransport.state)) return;\n if (transport.state === \"connecting\") {\n await settledState(\n transport.onStateChange,\n () => transport.state,\n (state) => state !== \"connecting\",\n );\n return;\n }\n if (transport.state === \"new\" && transport.hasRemoteParameters) {\n await transport.start();\n }\n }),\n );\n }\n}\n\n/**\n * The first state `done` accepts: the current one, or a later one `event`\n * reports. A completed event (the transport stopped) settles with the state\n * the transport is left in.\n */\nfunction settledState<S>(\n event: Event<[S]>,\n current: () => S,\n done: (state: S) => boolean,\n) {\n return new Promise<S>((resolve) => {\n if (done(current()) || event.ended) {\n resolve(current());\n return;\n }\n const { unSubscribe } = event.subscribe(\n (state) => {\n if (!done(state)) return;\n unSubscribe();\n resolve(state);\n },\n () => resolve(current()),\n );\n });\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { RTCRtpTransceiver, RtpRouter, TransceiverManager } from "./media";
2
- import type { RouterSnapshot, TransceiversNegotiationState } from "./negotiation/internalState";
2
+ import { type RouterSnapshot, type TransceiversNegotiationState } from "./negotiation/internalState";
3
+ import { type PairingView } from "./negotiation/transceiverPairing";
3
4
  import type { SctpNegotiationState, SctpTransportManager } from "./sctpManager";
4
5
  import type { SessionDescription } from "./sdp";
5
6
  import type { SDPManager } from "./sdpManager";
@@ -90,6 +91,18 @@ export type NegotiationCheckpoint = {
90
91
  * - RTP / router: new routing keys at once, conflicting ones staged until K
91
92
  * (`RtpRouter`); codec and direction of current m-lines follow the
92
93
  * effective-value rules. R restores the baseline tables.
94
+ * - Codecs: every offer lists what each transceiver can use now, whatever
95
+ * the last answer kept, and the negotiated codecs as negotiated (payload
96
+ * type, fmtp, rtcp-fb; paired with the configured codecs by the rule
97
+ * negotiation uses, `pairCodecs`: the same format first, then the same
98
+ * MIME type)
99
+ * (`TransceiverManager.resolveOfferCodecs`, issue 818). The negotiated
100
+ * codecs stay in it whatever the direction is now (`direction`,
101
+ * `removeTrack()` never take one off the m-line; only an answer does), and
102
+ * preferences and a fixed source narrow them too. `createOffer` and
103
+ * applying the local offer leave `transceiver.codecs` (the negotiated
104
+ * codecs that the sender, receiver and router use) unchanged; the answer
105
+ * (or pranswer) to it replaces them, and R restores them.
93
106
  * - BUNDLE: current owners keep their transports; a changed topology gets
94
107
  * transports prepared for the proposal and switches at K (`BundleTopology`).
95
108
  * - ICE: a restart is staged on the live transport, with a provisional
@@ -108,6 +121,14 @@ export type NegotiationCheckpoint = {
108
121
  * `expectedLive` and `assertNegotiationInvariants` in
109
122
  * tests/negotiation/harness/negotiationTransactionUtils.ts.
110
123
  *
124
+ * A remote offer pairs its m-lines with transceivers after its implicit
125
+ * rollback, replacement or unapplied-createOffer revert, but resolves codecs
126
+ * before them (a rejected proposal must leave the old transaction):
127
+ * `pairingViewForRemoteOffer` gives the codec plan the transceiver state the
128
+ * association will see, so both pair every m-line with the same transceiver
129
+ * (a local `addTransceiver()` one that only the rolled-back local offer gave
130
+ * the remote MID is not paired by either).
131
+ *
111
132
  * Each component owns the snapshot of its reversible state and the rule for
112
133
  * restoring it; this class only composes them. Add new negotiation state to
113
134
  * its component's pair:
@@ -115,9 +136,9 @@ export type NegotiationCheckpoint = {
115
136
  * | Component | Snapshot / restore | Kept across rollback |
116
137
  * | --- | --- | --- |
117
138
  * | `RTCRtpTransceiver` (with sender, receiver) | `snapshotNegotiationState` / `restoreNegotiationState` | an application `stop()` made during the transaction |
118
- * | `RTCRtpReceiver` | `snapshotNegotiationState` / `restoreNegotiationState` | SSRCs learned from RID packets whose track survives |
119
- * | `TransceiverManager` | `snapshotNegotiationState` / `restoreNegotiationState` | transceivers the application uses (`heldByApplication`) |
120
- * | `RtpRouter` | `snapshotRoutes` / `restoreRoutes` | packet-learned SSRC routes, every live sender's route |
139
+ * | `RTCRtpReceiver` | `snapshotNegotiationState` / `restoreNegotiationState` | SSRCs learned from RID packets whose track survives; one packets dropped after the baseline (retired by a media SSRC change of its RID, or evicted) is not restored |
140
+ * | `TransceiverManager` | `snapshotNegotiationState` / `restoreNegotiationState` | transceivers the application uses (`heldByApplication`); what created each transceiver (`createdBy`), except that a kept remote one `addTrack()` reused becomes `addTrack` |
141
+ * | `RtpRouter` | `snapshotRoutes` / `restoreRoutes` | packet-learned SSRC routes (one packets dropped after the baseline is not restored), every live sender's route |
121
142
  * | `SctpTransportManager` | `snapshotNegotiationState` / `restoreNegotiationState` | an application-created SCTP transport (a pending-only association is replaced by an unstarted one) and its channels without a stream ID |
122
143
  */
123
144
  export declare class NegotiationTransaction {
@@ -171,6 +192,16 @@ export declare class NegotiationTransaction {
171
192
  * the new offer associates the same object and nothing is notified twice.
172
193
  */
173
194
  replace(next?: SessionDescription): Promise<void>;
195
+ /**
196
+ * Internal: the transceiver state a remote offer's m-line association will
197
+ * see once the operations that run before it are done: `"rollback"` (the
198
+ * implicit rollback of a local offer), `"replace"` (a replacement remote
199
+ * offer, `next`), or neither, where opening the transaction reverts what an
200
+ * unapplied `createOffer` associated. It mirrors `restoreState` /
201
+ * `TransceiverManager.restoreNegotiationState` and
202
+ * `revertUnappliedAssociations` without mutating anything.
203
+ */
204
+ pairingViewForRemoteOffer(next: SessionDescription, restore: "rollback" | "replace" | undefined): PairingView;
174
205
  rollback(): Promise<void>;
175
206
  /**
176
207
  * Record the state before one description operation mutates anything, so a
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.NegotiationTransaction = void 0;
4
+ const internalState_1 = require("./negotiation/internalState");
5
+ const transceiverPairing_1 = require("./negotiation/transceiverPairing");
4
6
  /**
5
7
  * Resources a pending proposal created or prepared. They belong to the
6
8
  * proposal: replacement and rollback drop them, a checkpoint copies them.
@@ -146,6 +148,18 @@ const RETIRED_UFRAG_HISTORY = 64;
146
148
  * - RTP / router: new routing keys at once, conflicting ones staged until K
147
149
  * (`RtpRouter`); codec and direction of current m-lines follow the
148
150
  * effective-value rules. R restores the baseline tables.
151
+ * - Codecs: every offer lists what each transceiver can use now, whatever
152
+ * the last answer kept, and the negotiated codecs as negotiated (payload
153
+ * type, fmtp, rtcp-fb; paired with the configured codecs by the rule
154
+ * negotiation uses, `pairCodecs`: the same format first, then the same
155
+ * MIME type)
156
+ * (`TransceiverManager.resolveOfferCodecs`, issue 818). The negotiated
157
+ * codecs stay in it whatever the direction is now (`direction`,
158
+ * `removeTrack()` never take one off the m-line; only an answer does), and
159
+ * preferences and a fixed source narrow them too. `createOffer` and
160
+ * applying the local offer leave `transceiver.codecs` (the negotiated
161
+ * codecs that the sender, receiver and router use) unchanged; the answer
162
+ * (or pranswer) to it replaces them, and R restores them.
149
163
  * - BUNDLE: current owners keep their transports; a changed topology gets
150
164
  * transports prepared for the proposal and switches at K (`BundleTopology`).
151
165
  * - ICE: a restart is staged on the live transport, with a provisional
@@ -164,6 +178,14 @@ const RETIRED_UFRAG_HISTORY = 64;
164
178
  * `expectedLive` and `assertNegotiationInvariants` in
165
179
  * tests/negotiation/harness/negotiationTransactionUtils.ts.
166
180
  *
181
+ * A remote offer pairs its m-lines with transceivers after its implicit
182
+ * rollback, replacement or unapplied-createOffer revert, but resolves codecs
183
+ * before them (a rejected proposal must leave the old transaction):
184
+ * `pairingViewForRemoteOffer` gives the codec plan the transceiver state the
185
+ * association will see, so both pair every m-line with the same transceiver
186
+ * (a local `addTransceiver()` one that only the rolled-back local offer gave
187
+ * the remote MID is not paired by either).
188
+ *
167
189
  * Each component owns the snapshot of its reversible state and the rule for
168
190
  * restoring it; this class only composes them. Add new negotiation state to
169
191
  * its component's pair:
@@ -171,9 +193,9 @@ const RETIRED_UFRAG_HISTORY = 64;
171
193
  * | Component | Snapshot / restore | Kept across rollback |
172
194
  * | --- | --- | --- |
173
195
  * | `RTCRtpTransceiver` (with sender, receiver) | `snapshotNegotiationState` / `restoreNegotiationState` | an application `stop()` made during the transaction |
174
- * | `RTCRtpReceiver` | `snapshotNegotiationState` / `restoreNegotiationState` | SSRCs learned from RID packets whose track survives |
175
- * | `TransceiverManager` | `snapshotNegotiationState` / `restoreNegotiationState` | transceivers the application uses (`heldByApplication`) |
176
- * | `RtpRouter` | `snapshotRoutes` / `restoreRoutes` | packet-learned SSRC routes, every live sender's route |
196
+ * | `RTCRtpReceiver` | `snapshotNegotiationState` / `restoreNegotiationState` | SSRCs learned from RID packets whose track survives; one packets dropped after the baseline (retired by a media SSRC change of its RID, or evicted) is not restored |
197
+ * | `TransceiverManager` | `snapshotNegotiationState` / `restoreNegotiationState` | transceivers the application uses (`heldByApplication`); what created each transceiver (`createdBy`), except that a kept remote one `addTrack()` reused becomes `addTrack` |
198
+ * | `RtpRouter` | `snapshotRoutes` / `restoreRoutes` | packet-learned SSRC routes (one packets dropped after the baseline is not restored), every live sender's route |
177
199
  * | `SctpTransportManager` | `snapshotNegotiationState` / `restoreNegotiationState` | an application-created SCTP transport (a pending-only association is replaced by an unstarted one) and its channels without a stream ID |
178
200
  */
179
201
  class NegotiationTransaction {
@@ -324,6 +346,7 @@ class NegotiationTransaction {
324
346
  for (const transceiver of this.transceivers.getTransceivers()) {
325
347
  transceiver.receiver.commitStagedReceive();
326
348
  }
349
+ this.transceivers.notifyCommittedRemoteTracks();
327
350
  // The recycling offer is final: the displaced transceiver stops for good.
328
351
  for (const transceiver of this.resources.displaced) {
329
352
  if (!transceiver.stopped)
@@ -379,16 +402,13 @@ class NegotiationTransaction {
379
402
  async replace(next) {
380
403
  if (!this.baseline)
381
404
  return;
382
- const describedAgain = (transceiver) => !!next?.media.some((media) => media.port !== 0 &&
383
- media.kind === transceiver.kind &&
384
- media.rtp.muxId === transceiver.mid);
385
- const carried = new Set([...this.resources.remoteCreated].filter(describedAgain));
405
+ const carried = new Set([...this.resources.remoteCreated].filter((t) => describedAgain(next, t)));
386
406
  // A transceiver that existed before the transaction and that the
387
407
  // replacing offer describes again keeps the track it already notified,
388
408
  // so the replacement fires no second track event (W3C [[FiredDirection]]).
389
409
  const notified = new Set(this.transceivers
390
410
  .getTransceivers()
391
- .filter((t) => !this.resources.remoteCreated.has(t) && describedAgain(t)));
411
+ .filter((t) => !this.resources.remoteCreated.has(t) && describedAgain(next, t)));
392
412
  await this.restoreState(this.baseline, this.resources.remoteCreated, this.resources.speculativeTransports, carried, notified);
393
413
  this.resources.clear();
394
414
  for (const transceiver of carried) {
@@ -397,6 +417,85 @@ class NegotiationTransaction {
397
417
  this.revision++;
398
418
  this.phase = "pending";
399
419
  }
420
+ /**
421
+ * Internal: the transceiver state a remote offer's m-line association will
422
+ * see once the operations that run before it are done: `"rollback"` (the
423
+ * implicit rollback of a local offer), `"replace"` (a replacement remote
424
+ * offer, `next`), or neither, where opening the transaction reverts what an
425
+ * unapplied `createOffer` associated. It mirrors `restoreState` /
426
+ * `TransceiverManager.restoreNegotiationState` and
427
+ * `revertUnappliedAssociations` without mutating anything.
428
+ */
429
+ pairingViewForRemoteOffer(next, restore) {
430
+ const baseline = this.baseline;
431
+ if (restore && baseline) {
432
+ const { states } = baseline.transceivers;
433
+ const remoteCreated = this.resources.remoteCreated;
434
+ const restored = (transceiver, state, createdBy = transceiver.createdBy) => ({
435
+ mid: state.mid,
436
+ mLineIndex: state.mLineIndex,
437
+ stopping: state.stopping ||
438
+ (0, internalState_1.getApplicationStopRevision)(transceiver) !==
439
+ state.applicationStopRevision,
440
+ stopped: state.stopped,
441
+ createdBy,
442
+ });
443
+ return (transceiver) => {
444
+ const base = states.get(transceiver);
445
+ if (base)
446
+ return restored(transceiver, base.transceiver);
447
+ if (remoteCreated.has(transceiver)) {
448
+ const created = this.createdStates.get(transceiver);
449
+ if (restore === "replace" && describedAgain(next, transceiver)) {
450
+ // Carried over with its MID and m-line, in its created state.
451
+ return created
452
+ ? {
453
+ ...restored(transceiver, created),
454
+ mid: transceiver.mid,
455
+ mLineIndex: transceiver.mLineIndex,
456
+ }
457
+ : (0, transceiverPairing_1.livePairingState)(transceiver);
458
+ }
459
+ if (!transceiver.heldByApplication)
460
+ return undefined;
461
+ const createdBy = transceiver.reusedForAddTrack
462
+ ? "addTrack"
463
+ : transceiver.createdBy;
464
+ return {
465
+ ...(created
466
+ ? restored(transceiver, created, createdBy)
467
+ : { ...(0, transceiverPairing_1.livePairingState)(transceiver), createdBy }),
468
+ mid: null,
469
+ mLineIndex: undefined,
470
+ };
471
+ }
472
+ // Added by the application during the transaction: not committed.
473
+ if (transceiver.stopped)
474
+ return (0, transceiverPairing_1.livePairingState)(transceiver);
475
+ return {
476
+ ...(0, transceiverPairing_1.livePairingState)(transceiver),
477
+ mid: null,
478
+ mLineIndex: undefined,
479
+ };
480
+ };
481
+ }
482
+ const snapshot = this.offerSnapshot;
483
+ if (!this.baseline && snapshot) {
484
+ const { states } = snapshot.transceivers;
485
+ return (transceiver) => {
486
+ const state = states.get(transceiver)?.transceiver;
487
+ if (!state || transceiver.currentDirection || transceiver.stopped) {
488
+ return (0, transceiverPairing_1.livePairingState)(transceiver);
489
+ }
490
+ return {
491
+ ...(0, transceiverPairing_1.livePairingState)(transceiver),
492
+ mid: state.mid,
493
+ mLineIndex: state.mLineIndex,
494
+ };
495
+ };
496
+ }
497
+ return transceiverPairing_1.livePairingView;
498
+ }
400
499
  async rollback() {
401
500
  if (!this.baseline)
402
501
  return;
@@ -601,4 +700,8 @@ class NegotiationTransaction {
601
700
  }
602
701
  }
603
702
  exports.NegotiationTransaction = NegotiationTransaction;
703
+ /** Whether a replacing offer describes the MID of `transceiver` again. */
704
+ const describedAgain = (next, transceiver) => !!next?.media.some((media) => media.port !== 0 &&
705
+ media.kind === transceiver.kind &&
706
+ media.rtp.muxId === transceiver.mid);
604
707
  //# sourceMappingURL=negotiationTransaction.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"negotiationTransaction.js","sourceRoot":"","sources":["../../../src/negotiationTransaction.ts"],"names":[],"mappings":";;;AAsBA;;;GAGG;AACH,MAAM,iBAAiB;IAAvB;QACE,2CAA2C;QAClC;;;;mBAAgB,IAAI,GAAG,EAAqB;WAAC;QACtD,wEAAwE;QAC/D;;;;mBAAY,IAAI,GAAG,EAAqB;WAAC;QAClD,oEAAoE;QAC3D;;;;mBAAW,IAAI,GAAG,EAA4B;WAAC;QACxD,oDAAoD;QAC3C;;;;mBAAc,IAAI,GAAG,EAAoB;WAAC;QACnD,4EAA4E;QACnE;;;;mBAAS,IAAI,GAAG,EAAoB;WAAC;QAC9C,qEAAqE;QAC5D;;;;mBAAoB,IAAI,GAAG,EAAU;WAAC;QAC/C,wDAAwD;QACxD;;;;;WAAiC;IA6BnC,CAAC;IA3BC,gDAAgD;IAChD,IAAI,qBAAqB;QACvB,OAAO,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,IAAI,iBAAiB,EAAE,CAAC,CAAC;IACvC,CAAC;IAED,IAAI;QACF,MAAM,IAAI,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,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CAAC,QAAQ;YACvB,YAAY,EAAE,IAAI,CAAC,GAAG,CAAC,uBAAuB;YAC9C,aAAa,EAAE,IAAI,CAAC,GAAG,CAAC,wBAAwB;YAChD,YAAY,EAAE,IAAI,CAAC,GAAG,CAAC,uBAAuB;YAC9C,aAAa,EAAE,IAAI,CAAC,GAAG,CAAC,wBAAwB;YAChD,oBAAoB,EAAE,IAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC;YAClE,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI;YAChD,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI;YAClD,iBAAiB,EAAE,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC;YAC9C,gBAAgB,EAAE,CAAC,CAAC,IAAI,CAAC,aAAa;SACvC,CAAC;IACJ,CAAC;CACF;AA5cD,wDA4cC","sourcesContent":["import type { RTCRtpTransceiver, RtpRouter, TransceiverManager } from \"./media\";\nimport type {\n RouterSnapshot,\n TransceiverNegotiationState,\n TransceiversNegotiationState,\n} from \"./negotiation/internalState\";\nimport type { SctpNegotiationState, SctpTransportManager } from \"./sctpManager\";\nimport type { SessionDescription } from \"./sdp\";\nimport type { SDPManager } from \"./sdpManager\";\nimport type { RTCDtlsTransport } from \"./transport/dtls\";\n\n/**\n * The reversible state of a negotiation. Each component captures and restores\n * its own part, so a new piece of state is added where it lives (its\n * `snapshot*` / `restore*` pair), not here.\n */\ntype Baseline = {\n transceivers: TransceiversNegotiationState;\n routes: RouterSnapshot;\n sctp: SctpNegotiationState;\n};\n\n/**\n * Resources a pending proposal created or prepared. They belong to the\n * proposal: replacement and rollback drop them, a checkpoint copies them.\n */\nclass ProposalResources {\n /** Transceivers a remote offer created. */\n readonly remoteCreated = new Set<RTCRtpTransceiver>();\n /** Transceivers whose m-line a remote offer recycled with a new MID. */\n readonly displaced = new Set<RTCRtpTransceiver>();\n /** Transport each MID uses under the proposal (BUNDLE topology). */\n readonly prepared = new Map<string, RTCDtlsTransport>();\n /** Prepared transports no live binding uses yet. */\n readonly pendingOnly = new Set<RTCDtlsTransport>();\n /** Transports a remote offer created to own a BUNDLE group or an m-line. */\n readonly owners = new Set<RTCDtlsTransport>();\n /** Pending-only transports whose candidates were already emitted. */\n readonly emittedCandidates = new Set<string>();\n /** The description the transports were prepared for. */\n preparedFor?: SessionDescription;\n\n /** Transports that only this proposal holds. */\n get speculativeTransports() {\n return [...this.pendingOnly, ...this.owners];\n }\n\n clear() {\n this.assign(new ProposalResources());\n }\n\n copy() {\n const copy = new ProposalResources();\n copy.assign(this);\n return copy;\n }\n\n assign(source: ProposalResources) {\n replaceSet(this.remoteCreated, source.remoteCreated);\n replaceSet(this.displaced, source.displaced);\n replaceSet(this.pendingOnly, source.pendingOnly);\n replaceSet(this.owners, source.owners);\n replaceSet(this.emittedCandidates, source.emittedCandidates);\n this.prepared.clear();\n for (const [mid, transport] of source.prepared) {\n this.prepared.set(mid, transport);\n }\n this.preparedFor = source.preparedFor;\n }\n}\n\nexport type NegotiationCheckpoint = {\n state: Baseline;\n resources: ProposalResources;\n};\n\n/** The DTLS transports a baseline binds (transceivers and SCTP). */\nfunction baselineTransports(baseline: Baseline | undefined) {\n if (!baseline) return [];\n return [\n ...[...baseline.transceivers.states.values()].map(\n ({ transceiver }) => transceiver.dtlsTransport,\n ),\n baseline.sctp.dtlsTransport,\n ].filter((transport): transport is RTCDtlsTransport => !!transport);\n}\n\nfunction replaceSet<T>(target: Set<T>, source: Iterable<T>) {\n const values = [...source];\n target.clear();\n for (const value of values) target.add(value);\n}\n\n/** Remote ufrags of retired generations kept to reject late callbacks. */\nconst RETIRED_UFRAG_HISTORY = 64;\n\n/**\n * One owner for the reversible metadata of a PeerConnection negotiation.\n *\n * Invariant: the last pair of descriptions that reached `stable` is\n * **current**. Its RTP routes, BUNDLE owners, ICE selected pair, DTLS session\n * and SCTP association stay usable while another negotiation is pending.\n * Packet-driven state (counters, consent, retransmission) belongs to the live\n * transport and is never part of a snapshot.\n *\n * An applied offer opens the transaction. The state before it is the\n * **rollback baseline**, captured once (first wins): a replacement offer or\n * pranswer replaces only the **pending** proposal and its resources\n * (`ProposalResources`, candidate buckets, provisional routes, new SCTP\n * associations). The final answer is the only commit boundary; a pranswer may\n * run provisional traffic without changing the current pair. An event already\n * delivered to the application (track, candidate, DataChannel) is never\n * retracted, and a repeated description does not deliver it again.\n *\n * Phases (owned here, driven by RTCPeerConnection):\n *\n * | Phase | Rule |\n * | --- | --- |\n * | begin | Capture the baseline once. `createOffer` in stable only records the snapshot its `setLocalDescription` adopts (`snapshotForOffer`); a remote offer captures its own. |\n * | replace/update | Retire the previous proposal's pending-only resources and candidate buckets; keep the baseline and the delivered-event history. A byte-identical description is idempotent. |\n * | validate | Every check (signaling transition, MIDs, BUNDLE, codecs, ICE credentials, DTLS role, SCTP port) runs before any live mutation (`DescriptionValidation`); a failure leaves the previous pending and current state untouched. |\n * | prepare | New transports and media objects are allocated under the proposal; a failure stops only what it allocated. |\n * | commit | Final answer only: switch BUNDLE routing, ICE generation, DTLS parameters, SCTP binding and RTP/router, then publish the current descriptions and `stable`. Nothing fallible runs after the switch; asynchronous connect work starts afterwards. |\n * | rollback | Stop provisional communication, drop pending candidates and resources, restore the baseline and publish `stable`. Rolling back a first negotiation resets the connection states to `new`. |\n * | cleanup | Stop orphan proposal resources; a transport created during the transaction that no binding holds at commit stops. |\n *\n * Signaling transitions (JSEP 3.2; `have-remote-pranswer` also accepts a\n * replacement local offer, which first rolls back the remote pranswer):\n *\n * | State | Local input | Remote input |\n * | --- | --- | --- |\n * | stable | offer → have-local-offer | offer → have-remote-offer |\n * | have-local-offer | offer, rollback → stable | pranswer → have-remote-pranswer; answer → stable; offer → implicit rollback, have-remote-offer |\n * | have-remote-offer | pranswer → have-local-pranswer; answer → stable | offer; rollback → stable |\n * | have-local-pranswer | pranswer; answer → stable | rollback → stable; offer → implicit rollback, have-remote-offer |\n * | have-remote-pranswer | rollback → stable; offer → have-local-offer | pranswer; answer → stable |\n *\n * What a pending proposal may change, per subsystem (K = final answer\n * commit, R = rollback):\n *\n * - RTP / router: new routing keys at once, conflicting ones staged until K\n * (`RtpRouter`); codec and direction of current m-lines follow the\n * effective-value rules. R restores the baseline tables.\n * - BUNDLE: current owners keep their transports; a changed topology gets\n * transports prepared for the proposal and switches at K (`BundleTopology`).\n * - ICE: a restart is staged on the live transport, with a provisional\n * generation during a pranswer (`RTCIceTransport`); K switches, R drops it.\n * - DTLS: the current session and role are kept; only a new association (a\n * BUNDLE split owner) handshakes during the proposal.\n * - SCTP: the current association stays live; a new pending association may\n * run at a pranswer and closes on R. A port change or move of an\n * established association is rejected in validate.\n * - Candidates / end-of-candidates: kept per generation (ufrag) and per\n * proposal; replacement and R drop the pending buckets\n * (`RemoteCandidates`).\n *\n * Which description each live value follows while pending (current,\n * provisional at a pranswer, both, or reject) is tabulated and checked by\n * `expectedLive` and `assertNegotiationInvariants` in\n * tests/negotiation/harness/negotiationTransactionUtils.ts.\n *\n * Each component owns the snapshot of its reversible state and the rule for\n * restoring it; this class only composes them. Add new negotiation state to\n * its component's pair:\n *\n * | Component | Snapshot / restore | Kept across rollback |\n * | --- | --- | --- |\n * | `RTCRtpTransceiver` (with sender, receiver) | `snapshotNegotiationState` / `restoreNegotiationState` | an application `stop()` made during the transaction |\n * | `RTCRtpReceiver` | `snapshotNegotiationState` / `restoreNegotiationState` | SSRCs learned from RID packets whose track survives |\n * | `TransceiverManager` | `snapshotNegotiationState` / `restoreNegotiationState` | transceivers the application uses (`heldByApplication`) |\n * | `RtpRouter` | `snapshotRoutes` / `restoreRoutes` | packet-learned SSRC routes, every live sender's route |\n * | `SctpTransportManager` | `snapshotNegotiationState` / `restoreNegotiationState` | an application-created SCTP transport (a pending-only association is replaced by an unstarted one) and its channels without a stream ID |\n */\nexport class NegotiationTransaction {\n private readonly sdp: SDPManager;\n private readonly transceivers: TransceiverManager;\n private readonly router: RtpRouter;\n private readonly sctp: SctpTransportManager;\n\n private baseline?: Baseline;\n private offerSnapshot?: Baseline;\n private readonly resources = new ProposalResources();\n private readonly retiredRemoteUfrags = new Set<string>();\n /**\n * Transports created since the last commit. One that no binding holds at\n * commit (e.g. a data channel's own transport that BUNDLE replaced) stops.\n */\n private readonly createdTransports = new Set<RTCDtlsTransport>();\n /** Negotiation state of each transceiver a remote offer created, at creation. */\n private readonly createdStates = new WeakMap<\n RTCRtpTransceiver,\n TransceiverNegotiationState\n >();\n private revision = 0;\n private phase:\n | \"idle\"\n | \"pending\"\n | \"validating\"\n | \"preparing\"\n | \"committing\" = \"idle\";\n\n constructor(\n sdp: SDPManager,\n transceivers: TransceiverManager,\n router: RtpRouter,\n sctp: SctpTransportManager,\n ) {\n this.sdp = sdp;\n this.transceivers = transceivers;\n this.router = router;\n this.sctp = sctp;\n }\n\n // # lifecycle\n\n /**\n * `createOffer` in stable records the baseline it would roll back to, but\n * does not open a transaction: nothing is pending until the offer is set.\n */\n snapshotForOffer() {\n if (this.baseline) return;\n const fresh = this.capture();\n if (!this.offerSnapshot) {\n this.offerSnapshot = fresh;\n return;\n }\n // Earlier createOffer calls were not applied: keep the state from before\n // the first of them (their MIDs and m-line indexes are not negotiated),\n // and only add transceivers the application created since.\n const { order, states } = this.offerSnapshot.transceivers;\n for (const [transceiver, state] of fresh.transceivers.states) {\n if (!states.has(transceiver)) {\n states.set(transceiver, state);\n order.push(transceiver);\n }\n }\n }\n\n /**\n * Open the transaction when a description is applied. A local offer uses\n * the snapshot taken by the `createOffer` that produced it, so MIDs that\n * createOffer assigned revert on rollback; anything else captures now.\n */\n begin({ fromCreatedOffer = false }: { fromCreatedOffer?: boolean } = {}) {\n if (!this.baseline && !fromCreatedOffer && this.offerSnapshot) {\n // When a remote offer opens the transaction instead, what an unapplied\n // createOffer associated goes back first.\n this.transceivers.revertUnappliedAssociations(\n this.offerSnapshot.transceivers,\n );\n this.sctp.revertUnappliedAssociation(this.offerSnapshot.sctp);\n }\n if (!this.baseline) {\n this.baseline =\n (fromCreatedOffer ? this.offerSnapshot : undefined) ?? this.capture();\n }\n this.offerSnapshot = undefined;\n this.revision++;\n this.phase = \"pending\";\n return this.revision;\n }\n\n /** A description was applied without committing: the proposal is pending. */\n settle() {\n if (this.baseline) this.phase = \"pending\";\n }\n\n validate() {\n this.phase = \"validating\";\n }\n\n prepare() {\n this.phase = \"preparing\";\n }\n\n async commit() {\n this.phase = \"committing\";\n // Routes and decode entries a pending proposal could not take from the\n // current session switch now, together with the descriptions.\n this.router.commitStaged();\n for (const transceiver of this.transceivers.getTransceivers()) {\n transceiver.receiver.commitStagedReceive();\n }\n // The recycling offer is final: the displaced transceiver stops for good.\n for (const transceiver of this.resources.displaced) {\n if (!transceiver.stopped) continue;\n transceiver.setCurrentDirection(\"stopped\");\n transceiver.receiver.stop();\n transceiver.sender.stop();\n }\n // Every transport the previous session or this transaction used is a\n // candidate; those no live binding holds after the commit stop.\n const candidates = new Set(this.createdTransports);\n for (const { transceiver } of this.baseline?.transceivers.states.values() ??\n []) {\n candidates.add(transceiver.dtlsTransport);\n }\n if (this.baseline?.sctp.dtlsTransport) {\n candidates.add(this.baseline.sctp.dtlsTransport);\n }\n this.createdTransports.clear();\n this.cleanup();\n const inUse = this.transportsInUse({ includeStopped: false });\n await Promise.all(\n [...candidates]\n .filter((transport) => !inUse.has(transport))\n .map((transport) => transport.stop()),\n );\n }\n\n /**\n * A pranswer replaced an earlier one: a transport the proposal prepared that\n * neither a live binding nor the pranswer (`used`) puts an m-line on stops\n * the checks the earlier pranswer started. It\n * stays held (a final answer may still use it) with its local generation.\n */\n stopUnusedProposalChecks(used: ReadonlySet<RTCDtlsTransport>) {\n const inUse = this.transportsInUse({ includeStopped: false });\n for (const transport of used) inUse.add(transport);\n for (const transport of new Set([\n ...this.createdTransports,\n ...this.resources.speculativeTransports,\n ])) {\n if (inUse.has(transport)) continue;\n if ([\"new\", \"closed\"].includes(transport.iceTransport.state)) continue;\n transport.iceTransport.resetRemoteGeneration();\n }\n }\n\n /**\n * A replacement proposal: back to the baseline, which stays for the new one.\n * A transceiver the replaced remote offer created for a MID the replacing\n * one describes again (same kind) is carried over in its created state, so\n * the new offer associates the same object and nothing is notified twice.\n */\n async replace(next?: SessionDescription) {\n if (!this.baseline) return;\n const describedAgain = (transceiver: RTCRtpTransceiver) =>\n !!next?.media.some(\n (media) =>\n media.port !== 0 &&\n media.kind === transceiver.kind &&\n media.rtp.muxId === transceiver.mid,\n );\n const carried = new Set(\n [...this.resources.remoteCreated].filter(describedAgain),\n );\n // A transceiver that existed before the transaction and that the\n // replacing offer describes again keeps the track it already notified,\n // so the replacement fires no second track event (W3C [[FiredDirection]]).\n const notified = new Set(\n this.transceivers\n .getTransceivers()\n .filter(\n (t) => !this.resources.remoteCreated.has(t) && describedAgain(t),\n ),\n );\n await this.restoreState(\n this.baseline,\n this.resources.remoteCreated,\n this.resources.speculativeTransports,\n carried,\n notified,\n );\n this.resources.clear();\n for (const transceiver of carried) {\n this.resources.remoteCreated.add(transceiver);\n }\n this.revision++;\n this.phase = \"pending\";\n }\n\n async rollback() {\n if (!this.baseline) return;\n await this.restoreState(\n this.baseline,\n this.resources.remoteCreated,\n this.resources.speculativeTransports,\n );\n this.cleanup();\n }\n\n /**\n * Record the state before one description operation mutates anything, so a\n * failure inside that operation can undo exactly its own changes.\n */\n checkpoint(): NegotiationCheckpoint {\n return { state: this.capture(), resources: this.resources.copy() };\n }\n\n /** Undo one failed description operation back to its checkpoint. */\n async restoreCheckpoint(checkpoint: NegotiationCheckpoint) {\n const before = checkpoint.resources;\n const kept = new Set(before.speculativeTransports);\n await this.restoreState(\n checkpoint.state,\n [...this.resources.remoteCreated].filter(\n (transceiver) => !before.remoteCreated.has(transceiver),\n ),\n this.resources.speculativeTransports.filter(\n (transport) => !kept.has(transport),\n ),\n );\n this.resources.assign(before);\n this.phase = \"pending\";\n }\n\n /**\n * PeerConnection close: stop every transport only the negotiation holds\n * (created for a proposal, pending-only, BUNDLE owners, prepared for a\n * topology), which no transceiver or SCTP binding would stop, then drop\n * every reference.\n */\n async dispose() {\n const transports = new Set([\n ...this.createdTransports,\n ...this.resources.speculativeTransports,\n ...this.resources.prepared.values(),\n // A transport only the rollback baseline still binds (a pending\n // description moved its m-lines to another transport): no binding\n // stops it at close.\n ...baselineTransports(this.baseline),\n ...baselineTransports(this.offerSnapshot),\n ]);\n this.createdTransports.clear();\n this.offerSnapshot = undefined;\n this.cleanup();\n await Promise.allSettled(\n [...transports].map((transport) => transport.stop()),\n );\n }\n\n // # proposal resources\n\n noteCreatedTransport(transport: RTCDtlsTransport) {\n this.createdTransports.add(transport);\n // A stopped transport needs no cleanup; do not keep referencing it.\n transport.onStateChange.subscribe((state) => {\n if (state === \"closed\") this.createdTransports.delete(transport);\n });\n }\n\n rememberRemoteTransceiver(transceiver: RTCRtpTransceiver) {\n this.resources.remoteCreated.add(transceiver);\n // Before the offer negotiates anything on it: a rollback that keeps the\n // transceiver (the application uses it) returns it to this state.\n this.createdStates.set(transceiver, transceiver.snapshotNegotiationState());\n }\n\n rememberOwnerTransport(transport: RTCDtlsTransport) {\n this.resources.owners.add(transport);\n }\n\n rememberDisplacedTransceiver(transceiver: RTCRtpTransceiver) {\n this.resources.displaced.add(transceiver);\n }\n\n get preparedDescription() {\n return this.resources.preparedFor;\n }\n\n get transportByMid() {\n return this.resources.prepared;\n }\n\n /**\n * Internal: whether the rollback baseline negotiated SCTP (it has a remote\n * port). A final answer rejecting m=application closes only an association\n * the proposal started (by a pranswer or the remote INIT); one the baseline\n * negotiated keeps running, as for every other rejection.\n */\n get baselineNegotiatedSctp() {\n return this.baseline?.sctp.remotePort !== undefined;\n }\n\n isPendingOnlyTransport(iceTransportId: string) {\n return [...this.resources.pendingOnly].some(\n (transport) => transport.iceTransport.id === iceTransportId,\n );\n }\n\n takePreparedCandidateTransports() {\n const { pendingOnly, emittedCandidates } = this.resources;\n const transports = [...pendingOnly].filter(\n (transport) => !emittedCandidates.has(transport.id),\n );\n for (const transport of transports) {\n emittedCandidates.add(transport.id);\n }\n return transports;\n }\n\n prepareTransport(\n description: SessionDescription,\n mid: string,\n transport: RTCDtlsTransport,\n pendingOnly = false,\n ) {\n this.resources.preparedFor = description;\n this.resources.prepared.set(mid, transport);\n if (pendingOnly) this.resources.pendingOnly.add(transport);\n }\n\n async discardPreparedTransports() {\n const { prepared, pendingOnly, emittedCandidates } = this.resources;\n const stopping = [...pendingOnly];\n prepared.clear();\n pendingOnly.clear();\n emittedCandidates.clear();\n this.resources.preparedFor = undefined;\n await Promise.allSettled(stopping.map((transport) => transport.stop()));\n }\n\n /**\n * A remote pranswer or answer replaces every earlier remote pranswer of\n * this offer: routes and receive values those staged are dropped before it\n * applies, so the commit switches only to what the latest description\n * carries.\n */\n discardStagedRemoteAnswer() {\n this.router.discardProvisional();\n this.router.restoreStaged({ ssrc: [], rid: [] });\n for (const transceiver of this.transceivers.getTransceivers()) {\n transceiver.receiver.discardStagedReceive();\n }\n }\n\n // # retired ICE generations\n\n retireRemoteGeneration(description?: SessionDescription) {\n for (const media of description?.media ?? []) {\n const ufrag = media.iceParams?.usernameFragment;\n if (ufrag) this.retiredRemoteUfrags.add(ufrag);\n }\n // A bounded history covers late callbacks without retaining every past\n // negotiation for the lifetime of a long-running peer.\n while (this.retiredRemoteUfrags.size > RETIRED_UFRAG_HISTORY) {\n this.retiredRemoteUfrags.delete(\n this.retiredRemoteUfrags.values().next().value!,\n );\n }\n }\n\n isRetiredRemoteUfrag(ufrag?: string | null) {\n return !!ufrag && this.retiredRemoteUfrags.has(ufrag);\n }\n\n // # state capture and restore\n\n private capture(): Baseline {\n return {\n transceivers: this.transceivers.snapshotNegotiationState(),\n routes: this.router.snapshotRoutes(),\n sctp: this.sctp.snapshotNegotiationState(),\n };\n }\n\n /**\n * Put transceivers, routes and SCTP back to `baseline`. Transceivers in\n * `added` and transports in `speculative` were created after it; those no\n * restored owner uses stop.\n */\n private async restoreState(\n baseline: Baseline,\n added: Iterable<RTCRtpTransceiver>,\n speculative: Iterable<RTCDtlsTransport>,\n carried: ReadonlySet<RTCRtpTransceiver> = new Set(),\n notified: ReadonlySet<RTCRtpTransceiver> = new Set(),\n ) {\n const removedTransports = this.transceivers.restoreNegotiationState(\n baseline.transceivers,\n added,\n (transceiver) => this.createdStates.get(transceiver),\n carried,\n notified,\n );\n const live = this.transceivers.getTransceivers();\n this.router.restoreRoutes(baseline.routes, {\n endpoints: new Set(live.flatMap((t) => [t.sender, t.receiver])),\n liveSenders: live\n .filter((t) => !t.stopped && !t.stopping)\n .map((t) => t.sender),\n });\n // The transport an SCTP transport the proposal created ran on (a remote\n // offer's application m-line) stops with it unless something else uses it.\n const proposedSctp = this.sctp.sctpTransport?.dtlsTransport;\n await this.sctp.restoreNegotiationState(baseline.sctp);\n\n const inUse = this.transportsInUse({ includeStopped: true });\n for (const transport of new Set([\n ...speculative,\n ...removedTransports,\n ...(proposedSctp ? [proposedSctp] : []),\n ])) {\n if (!inUse.has(transport)) await transport.stop();\n }\n }\n\n /** Transports a transceiver (optionally a stopped one) or SCTP is bound to. */\n private transportsInUse({ includeStopped }: { includeStopped: boolean }) {\n const inUse = new Set(\n this.transceivers\n .getTransceivers()\n .filter((transceiver) => includeStopped || !transceiver.stopped)\n .map((transceiver) => transceiver.dtlsTransport),\n );\n const sctp = this.sctp.sctpTransport?.dtlsTransport;\n if (sctp) inUse.add(sctp);\n return inUse;\n }\n\n private cleanup() {\n this.baseline = undefined;\n this.resources.clear();\n this.phase = \"idle\";\n }\n\n /** Internal test observation, never exposed on the public API. */\n inspect() {\n return {\n phase: this.phase,\n revision: this.revision,\n currentLocal: this.sdp.currentLocalDescription,\n currentRemote: this.sdp.currentRemoteDescription,\n pendingLocal: this.sdp.pendingLocalDescription,\n pendingRemote: this.sdp.pendingRemoteDescription,\n baselineTransceivers: this.baseline?.transceivers.states.size ?? 0,\n remoteCreated: this.resources.remoteCreated.size,\n pendingTransports: this.resources.pendingOnly.size,\n createdTransports: [...this.createdTransports],\n hasOfferSnapshot: !!this.offerSnapshot,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"negotiationTransaction.js","sourceRoot":"","sources":["../../../src/negotiationTransaction.ts"],"names":[],"mappings":";;;AACA,+DAKqC;AACrC,yEAK0C;AAiB1C;;;GAGG;AACH,MAAM,iBAAiB;IAAvB;QACE,2CAA2C;QAClC;;;;mBAAgB,IAAI,GAAG,EAAqB;WAAC;QACtD,wEAAwE;QAC/D;;;;mBAAY,IAAI,GAAG,EAAqB;WAAC;QAClD,oEAAoE;QAC3D;;;;mBAAW,IAAI,GAAG,EAA4B;WAAC;QACxD,oDAAoD;QAC3C;;;;mBAAc,IAAI,GAAG,EAAoB;WAAC;QACnD,4EAA4E;QACnE;;;;mBAAS,IAAI,GAAG,EAAoB;WAAC;QAC9C,qEAAqE;QAC5D;;;;mBAAoB,IAAI,GAAG,EAAU;WAAC;QAC/C,wDAAwD;QACxD;;;;;WAAiC;IA6BnC,CAAC;IA3BC,gDAAgD;IAChD,IAAI,qBAAqB;QACvB,OAAO,CAAC,GAAG,IAAI,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,IAAI,iBAAiB,EAAE,CAAC,CAAC;IACvC,CAAC;IAED,IAAI;QACF,MAAM,IAAI,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,CAAC,MAAyB;QAC9B,UAAU,CAAC,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,aAAa,CAAC,CAAC;QACrD,UAAU,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;QAC7C,UAAU,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QACjD,UAAU,CAAC,IAAI,CAAC,MAAM,EA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oB,EAAE,IAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC;YAClE,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI;YAChD,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI;YAClD,iBAAiB,EAAE,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC;YAC9C,gBAAgB,EAAE,CAAC,CAAC,IAAI,CAAC,aAAa;SACvC,CAAC;IACJ,CAAC;CACF;AA5hBD,wDA4hBC;AAED,0EAA0E;AAC1E,MAAM,cAAc,GAAG,CACrB,IAAoC,EACpC,WAA8B,EAC9B,EAAE,CACF,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAChB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,IAAI,KAAK,CAAC;IAChB,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,IAAI;IAC/B,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,WAAW,CAAC,GAAG,CACtC,CAAC","sourcesContent":["import type { RTCRtpTransceiver, RtpRouter, TransceiverManager } from \"./media\";\nimport {\n getApplicationStopRevision,\n type RouterSnapshot,\n type TransceiverNegotiationState,\n type TransceiversNegotiationState,\n} from \"./negotiation/internalState\";\nimport {\n livePairingState,\n livePairingView,\n type PairingState,\n type PairingView,\n} from \"./negotiation/transceiverPairing\";\nimport type { SctpNegotiationState, SctpTransportManager } from \"./sctpManager\";\nimport type { SessionDescription } from \"./sdp\";\nimport type { SDPManager } from \"./sdpManager\";\nimport type { RTCDtlsTransport } from \"./transport/dtls\";\n\n/**\n * The reversible state of a negotiation. Each component captures and restores\n * its own part, so a new piece of state is added where it lives (its\n * `snapshot*` / `restore*` pair), not here.\n */\ntype Baseline = {\n transceivers: TransceiversNegotiationState;\n routes: RouterSnapshot;\n sctp: SctpNegotiationState;\n};\n\n/**\n * Resources a pending proposal created or prepared. They belong to the\n * proposal: replacement and rollback drop them, a checkpoint copies them.\n */\nclass ProposalResources {\n /** Transceivers a remote offer created. */\n readonly remoteCreated = new Set<RTCRtpTransceiver>();\n /** Transceivers whose m-line a remote offer recycled with a new MID. */\n readonly displaced = new Set<RTCRtpTransceiver>();\n /** Transport each MID uses under the proposal (BUNDLE topology). */\n readonly prepared = new Map<string, RTCDtlsTransport>();\n /** Prepared transports no live binding uses yet. */\n readonly pendingOnly = new Set<RTCDtlsTransport>();\n /** Transports a remote offer created to own a BUNDLE group or an m-line. */\n readonly owners = new Set<RTCDtlsTransport>();\n /** Pending-only transports whose candidates were already emitted. */\n readonly emittedCandidates = new Set<string>();\n /** The description the transports were prepared for. */\n preparedFor?: SessionDescription;\n\n /** Transports that only this proposal holds. */\n get speculativeTransports() {\n return [...this.pendingOnly, ...this.owners];\n }\n\n clear() {\n this.assign(new ProposalResources());\n }\n\n copy() {\n const copy = new ProposalResources();\n copy.assign(this);\n return copy;\n }\n\n assign(source: ProposalResources) {\n replaceSet(this.remoteCreated, source.remoteCreated);\n replaceSet(this.displaced, source.displaced);\n replaceSet(this.pendingOnly, source.pendingOnly);\n replaceSet(this.owners, source.owners);\n replaceSet(this.emittedCandidates, source.emittedCandidates);\n this.prepared.clear();\n for (const [mid, transport] of source.prepared) {\n this.prepared.set(mid, transport);\n }\n this.preparedFor = source.preparedFor;\n }\n}\n\nexport type NegotiationCheckpoint = {\n state: Baseline;\n resources: ProposalResources;\n};\n\n/** The DTLS transports a baseline binds (transceivers and SCTP). */\nfunction baselineTransports(baseline: Baseline | undefined) {\n if (!baseline) return [];\n return [\n ...[...baseline.transceivers.states.values()].map(\n ({ transceiver }) => transceiver.dtlsTransport,\n ),\n baseline.sctp.dtlsTransport,\n ].filter((transport): transport is RTCDtlsTransport => !!transport);\n}\n\nfunction replaceSet<T>(target: Set<T>, source: Iterable<T>) {\n const values = [...source];\n target.clear();\n for (const value of values) target.add(value);\n}\n\n/** Remote ufrags of retired generations kept to reject late callbacks. */\nconst RETIRED_UFRAG_HISTORY = 64;\n\n/**\n * One owner for the reversible metadata of a PeerConnection negotiation.\n *\n * Invariant: the last pair of descriptions that reached `stable` is\n * **current**. Its RTP routes, BUNDLE owners, ICE selected pair, DTLS session\n * and SCTP association stay usable while another negotiation is pending.\n * Packet-driven state (counters, consent, retransmission) belongs to the live\n * transport and is never part of a snapshot.\n *\n * An applied offer opens the transaction. The state before it is the\n * **rollback baseline**, captured once (first wins): a replacement offer or\n * pranswer replaces only the **pending** proposal and its resources\n * (`ProposalResources`, candidate buckets, provisional routes, new SCTP\n * associations). The final answer is the only commit boundary; a pranswer may\n * run provisional traffic without changing the current pair. An event already\n * delivered to the application (track, candidate, DataChannel) is never\n * retracted, and a repeated description does not deliver it again.\n *\n * Phases (owned here, driven by RTCPeerConnection):\n *\n * | Phase | Rule |\n * | --- | --- |\n * | begin | Capture the baseline once. `createOffer` in stable only records the snapshot its `setLocalDescription` adopts (`snapshotForOffer`); a remote offer captures its own. |\n * | replace/update | Retire the previous proposal's pending-only resources and candidate buckets; keep the baseline and the delivered-event history. A byte-identical description is idempotent. |\n * | validate | Every check (signaling transition, MIDs, BUNDLE, codecs, ICE credentials, DTLS role, SCTP port) runs before any live mutation (`DescriptionValidation`); a failure leaves the previous pending and current state untouched. |\n * | prepare | New transports and media objects are allocated under the proposal; a failure stops only what it allocated. |\n * | commit | Final answer only: switch BUNDLE routing, ICE generation, DTLS parameters, SCTP binding and RTP/router, then publish the current descriptions and `stable`. Nothing fallible runs after the switch; asynchronous connect work starts afterwards. |\n * | rollback | Stop provisional communication, drop pending candidates and resources, restore the baseline and publish `stable`. Rolling back a first negotiation resets the connection states to `new`. |\n * | cleanup | Stop orphan proposal resources; a transport created during the transaction that no binding holds at commit stops. |\n *\n * Signaling transitions (JSEP 3.2; `have-remote-pranswer` also accepts a\n * replacement local offer, which first rolls back the remote pranswer):\n *\n * | State | Local input | Remote input |\n * | --- | --- | --- |\n * | stable | offer → have-local-offer | offer → have-remote-offer |\n * | have-local-offer | offer, rollback → stable | pranswer → have-remote-pranswer; answer → stable; offer → implicit rollback, have-remote-offer |\n * | have-remote-offer | pranswer → have-local-pranswer; answer → stable | offer; rollback → stable |\n * | have-local-pranswer | pranswer; answer → stable | rollback → stable; offer → implicit rollback, have-remote-offer |\n * | have-remote-pranswer | rollback → stable; offer → have-local-offer | pranswer; answer → stable |\n *\n * What a pending proposal may change, per subsystem (K = final answer\n * commit, R = rollback):\n *\n * - RTP / router: new routing keys at once, conflicting ones staged until K\n * (`RtpRouter`); codec and direction of current m-lines follow the\n * effective-value rules. R restores the baseline tables.\n * - Codecs: every offer lists what each transceiver can use now, whatever\n * the last answer kept, and the negotiated codecs as negotiated (payload\n * type, fmtp, rtcp-fb; paired with the configured codecs by the rule\n * negotiation uses, `pairCodecs`: the same format first, then the same\n * MIME type)\n * (`TransceiverManager.resolveOfferCodecs`, issue 818). The negotiated\n * codecs stay in it whatever the direction is now (`direction`,\n * `removeTrack()` never take one off the m-line; only an answer does), and\n * preferences and a fixed source narrow them too. `createOffer` and\n * applying the local offer leave `transceiver.codecs` (the negotiated\n * codecs that the sender, receiver and router use) unchanged; the answer\n * (or pranswer) to it replaces them, and R restores them.\n * - BUNDLE: current owners keep their transports; a changed topology gets\n * transports prepared for the proposal and switches at K (`BundleTopology`).\n * - ICE: a restart is staged on the live transport, with a provisional\n * generation during a pranswer (`RTCIceTransport`); K switches, R drops it.\n * - DTLS: the current session and role are kept; only a new association (a\n * BUNDLE split owner) handshakes during the proposal.\n * - SCTP: the current association stays live; a new pending association may\n * run at a pranswer and closes on R. A port change or move of an\n * established association is rejected in validate.\n * - Candidates / end-of-candidates: kept per generation (ufrag) and per\n * proposal; replacement and R drop the pending buckets\n * (`RemoteCandidates`).\n *\n * Which description each live value follows while pending (current,\n * provisional at a pranswer, both, or reject) is tabulated and checked by\n * `expectedLive` and `assertNegotiationInvariants` in\n * tests/negotiation/harness/negotiationTransactionUtils.ts.\n *\n * A remote offer pairs its m-lines with transceivers after its implicit\n * rollback, replacement or unapplied-createOffer revert, but resolves codecs\n * before them (a rejected proposal must leave the old transaction):\n * `pairingViewForRemoteOffer` gives the codec plan the transceiver state the\n * association will see, so both pair every m-line with the same transceiver\n * (a local `addTransceiver()` one that only the rolled-back local offer gave\n * the remote MID is not paired by either).\n *\n * Each component owns the snapshot of its reversible state and the rule for\n * restoring it; this class only composes them. Add new negotiation state to\n * its component's pair:\n *\n * | Component | Snapshot / restore | Kept across rollback |\n * | --- | --- | --- |\n * | `RTCRtpTransceiver` (with sender, receiver) | `snapshotNegotiationState` / `restoreNegotiationState` | an application `stop()` made during the transaction |\n * | `RTCRtpReceiver` | `snapshotNegotiationState` / `restoreNegotiationState` | SSRCs learned from RID packets whose track survives; one packets dropped after the baseline (retired by a media SSRC change of its RID, or evicted) is not restored |\n * | `TransceiverManager` | `snapshotNegotiationState` / `restoreNegotiationState` | transceivers the application uses (`heldByApplication`); what created each transceiver (`createdBy`), except that a kept remote one `addTrack()` reused becomes `addTrack` |\n * | `RtpRouter` | `snapshotRoutes` / `restoreRoutes` | packet-learned SSRC routes (one packets dropped after the baseline is not restored), every live sender's route |\n * | `SctpTransportManager` | `snapshotNegotiationState` / `restoreNegotiationState` | an application-created SCTP transport (a pending-only association is replaced by an unstarted one) and its channels without a stream ID |\n */\nexport class NegotiationTransaction {\n private readonly sdp: SDPManager;\n private readonly transceivers: TransceiverManager;\n private readonly router: RtpRouter;\n private readonly sctp: SctpTransportManager;\n\n private baseline?: Baseline;\n private offerSnapshot?: Baseline;\n private readonly resources = new ProposalResources();\n private readonly retiredRemoteUfrags = new Set<string>();\n /**\n * Transports created since the last commit. One that no binding holds at\n * commit (e.g. a data channel's own transport that BUNDLE replaced) stops.\n */\n private readonly createdTransports = new Set<RTCDtlsTransport>();\n /** Negotiation state of each transceiver a remote offer created, at creation. */\n private readonly createdStates = new WeakMap<\n RTCRtpTransceiver,\n TransceiverNegotiationState\n >();\n private revision = 0;\n private phase:\n | \"idle\"\n | \"pending\"\n | \"validating\"\n | \"preparing\"\n | \"committing\" = \"idle\";\n\n constructor(\n sdp: SDPManager,\n transceivers: TransceiverManager,\n router: RtpRouter,\n sctp: SctpTransportManager,\n ) {\n this.sdp = sdp;\n this.transceivers = transceivers;\n this.router = router;\n this.sctp = sctp;\n }\n\n // # lifecycle\n\n /**\n * `createOffer` in stable records the baseline it would roll back to, but\n * does not open a transaction: nothing is pending until the offer is set.\n */\n snapshotForOffer() {\n if (this.baseline) return;\n const fresh = this.capture();\n if (!this.offerSnapshot) {\n this.offerSnapshot = fresh;\n return;\n }\n // Earlier createOffer calls were not applied: keep the state from before\n // the first of them (their MIDs and m-line indexes are not negotiated),\n // and only add transceivers the application created since.\n const { order, states } = this.offerSnapshot.transceivers;\n for (const [transceiver, state] of fresh.transceivers.states) {\n if (!states.has(transceiver)) {\n states.set(transceiver, state);\n order.push(transceiver);\n }\n }\n }\n\n /**\n * Open the transaction when a description is applied. A local offer uses\n * the snapshot taken by the `createOffer` that produced it, so MIDs that\n * createOffer assigned revert on rollback; anything else captures now.\n */\n begin({ fromCreatedOffer = false }: { fromCreatedOffer?: boolean } = {}) {\n if (!this.baseline && !fromCreatedOffer && this.offerSnapshot) {\n // When a remote offer opens the transaction instead, what an unapplied\n // createOffer associated goes back first.\n this.transceivers.revertUnappliedAssociations(\n this.offerSnapshot.transceivers,\n );\n this.sctp.revertUnappliedAssociation(this.offerSnapshot.sctp);\n }\n if (!this.baseline) {\n this.baseline =\n (fromCreatedOffer ? this.offerSnapshot : undefined) ?? this.capture();\n }\n this.offerSnapshot = undefined;\n this.revision++;\n this.phase = \"pending\";\n return this.revision;\n }\n\n /** A description was applied without committing: the proposal is pending. */\n settle() {\n if (this.baseline) this.phase = \"pending\";\n }\n\n validate() {\n this.phase = \"validating\";\n }\n\n prepare() {\n this.phase = \"preparing\";\n }\n\n async commit() {\n this.phase = \"committing\";\n // Routes and decode entries a pending proposal could not take from the\n // current session switch now, together with the descriptions.\n this.router.commitStaged();\n for (const transceiver of this.transceivers.getTransceivers()) {\n transceiver.receiver.commitStagedReceive();\n }\n this.transceivers.notifyCommittedRemoteTracks();\n // The recycling offer is final: the displaced transceiver stops for good.\n for (const transceiver of this.resources.displaced) {\n if (!transceiver.stopped) continue;\n transceiver.setCurrentDirection(\"stopped\");\n transceiver.receiver.stop();\n transceiver.sender.stop();\n }\n // Every transport the previous session or this transaction used is a\n // candidate; those no live binding holds after the commit stop.\n const candidates = new Set(this.createdTransports);\n for (const { transceiver } of this.baseline?.transceivers.states.values() ??\n []) {\n candidates.add(transceiver.dtlsTransport);\n }\n if (this.baseline?.sctp.dtlsTransport) {\n candidates.add(this.baseline.sctp.dtlsTransport);\n }\n this.createdTransports.clear();\n this.cleanup();\n const inUse = this.transportsInUse({ includeStopped: false });\n await Promise.all(\n [...candidates]\n .filter((transport) => !inUse.has(transport))\n .map((transport) => transport.stop()),\n );\n }\n\n /**\n * A pranswer replaced an earlier one: a transport the proposal prepared that\n * neither a live binding nor the pranswer (`used`) puts an m-line on stops\n * the checks the earlier pranswer started. It\n * stays held (a final answer may still use it) with its local generation.\n */\n stopUnusedProposalChecks(used: ReadonlySet<RTCDtlsTransport>) {\n const inUse = this.transportsInUse({ includeStopped: false });\n for (const transport of used) inUse.add(transport);\n for (const transport of new Set([\n ...this.createdTransports,\n ...this.resources.speculativeTransports,\n ])) {\n if (inUse.has(transport)) continue;\n if ([\"new\", \"closed\"].includes(transport.iceTransport.state)) continue;\n transport.iceTransport.resetRemoteGeneration();\n }\n }\n\n /**\n * A replacement proposal: back to the baseline, which stays for the new one.\n * A transceiver the replaced remote offer created for a MID the replacing\n * one describes again (same kind) is carried over in its created state, so\n * the new offer associates the same object and nothing is notified twice.\n */\n async replace(next?: SessionDescription) {\n if (!this.baseline) return;\n const carried = new Set(\n [...this.resources.remoteCreated].filter((t) => describedAgain(next, t)),\n );\n // A transceiver that existed before the transaction and that the\n // replacing offer describes again keeps the track it already notified,\n // so the replacement fires no second track event (W3C [[FiredDirection]]).\n const notified = new Set(\n this.transceivers\n .getTransceivers()\n .filter(\n (t) =>\n !this.resources.remoteCreated.has(t) && describedAgain(next, t),\n ),\n );\n await this.restoreState(\n this.baseline,\n this.resources.remoteCreated,\n this.resources.speculativeTransports,\n carried,\n notified,\n );\n this.resources.clear();\n for (const transceiver of carried) {\n this.resources.remoteCreated.add(transceiver);\n }\n this.revision++;\n this.phase = \"pending\";\n }\n\n /**\n * Internal: the transceiver state a remote offer's m-line association will\n * see once the operations that run before it are done: `\"rollback\"` (the\n * implicit rollback of a local offer), `\"replace\"` (a replacement remote\n * offer, `next`), or neither, where opening the transaction reverts what an\n * unapplied `createOffer` associated. It mirrors `restoreState` /\n * `TransceiverManager.restoreNegotiationState` and\n * `revertUnappliedAssociations` without mutating anything.\n */\n pairingViewForRemoteOffer(\n next: SessionDescription,\n restore: \"rollback\" | \"replace\" | undefined,\n ): PairingView {\n const baseline = this.baseline;\n if (restore && baseline) {\n const { states } = baseline.transceivers;\n const remoteCreated = this.resources.remoteCreated;\n const restored = (\n transceiver: RTCRtpTransceiver,\n state: TransceiverNegotiationState,\n createdBy = transceiver.createdBy,\n ): PairingState => ({\n mid: state.mid,\n mLineIndex: state.mLineIndex,\n stopping:\n state.stopping ||\n getApplicationStopRevision(transceiver) !==\n state.applicationStopRevision,\n stopped: state.stopped,\n createdBy,\n });\n return (transceiver) => {\n const base = states.get(transceiver);\n if (base) return restored(transceiver, base.transceiver);\n if (remoteCreated.has(transceiver)) {\n const created = this.createdStates.get(transceiver);\n if (restore === \"replace\" && describedAgain(next, transceiver)) {\n // Carried over with its MID and m-line, in its created state.\n return created\n ? {\n ...restored(transceiver, created),\n mid: transceiver.mid,\n mLineIndex: transceiver.mLineIndex,\n }\n : livePairingState(transceiver);\n }\n if (!transceiver.heldByApplication) return undefined;\n const createdBy = transceiver.reusedForAddTrack\n ? \"addTrack\"\n : transceiver.createdBy;\n return {\n ...(created\n ? restored(transceiver, created, createdBy)\n : { ...livePairingState(transceiver), createdBy }),\n mid: null,\n mLineIndex: undefined,\n };\n }\n // Added by the application during the transaction: not committed.\n if (transceiver.stopped) return livePairingState(transceiver);\n return {\n ...livePairingState(transceiver),\n mid: null,\n mLineIndex: undefined,\n };\n };\n }\n const snapshot = this.offerSnapshot;\n if (!this.baseline && snapshot) {\n const { states } = snapshot.transceivers;\n return (transceiver) => {\n const state = states.get(transceiver)?.transceiver;\n if (!state || transceiver.currentDirection || transceiver.stopped) {\n return livePairingState(transceiver);\n }\n return {\n ...livePairingState(transceiver),\n mid: state.mid,\n mLineIndex: state.mLineIndex,\n };\n };\n }\n return livePairingView;\n }\n\n async rollback() {\n if (!this.baseline) return;\n await this.restoreState(\n this.baseline,\n this.resources.remoteCreated,\n this.resources.speculativeTransports,\n );\n this.cleanup();\n }\n\n /**\n * Record the state before one description operation mutates anything, so a\n * failure inside that operation can undo exactly its own changes.\n */\n checkpoint(): NegotiationCheckpoint {\n return { state: this.capture(), resources: this.resources.copy() };\n }\n\n /** Undo one failed description operation back to its checkpoint. */\n async restoreCheckpoint(checkpoint: NegotiationCheckpoint) {\n const before = checkpoint.resources;\n const kept = new Set(before.speculativeTransports);\n await this.restoreState(\n checkpoint.state,\n [...this.resources.remoteCreated].filter(\n (transceiver) => !before.remoteCreated.has(transceiver),\n ),\n this.resources.speculativeTransports.filter(\n (transport) => !kept.has(transport),\n ),\n );\n this.resources.assign(before);\n this.phase = \"pending\";\n }\n\n /**\n * PeerConnection close: stop every transport only the negotiation holds\n * (created for a proposal, pending-only, BUNDLE owners, prepared for a\n * topology), which no transceiver or SCTP binding would stop, then drop\n * every reference.\n */\n async dispose() {\n const transports = new Set([\n ...this.createdTransports,\n ...this.resources.speculativeTransports,\n ...this.resources.prepared.values(),\n // A transport only the rollback baseline still binds (a pending\n // description moved its m-lines to another transport): no binding\n // stops it at close.\n ...baselineTransports(this.baseline),\n ...baselineTransports(this.offerSnapshot),\n ]);\n this.createdTransports.clear();\n this.offerSnapshot = undefined;\n this.cleanup();\n await Promise.allSettled(\n [...transports].map((transport) => transport.stop()),\n );\n }\n\n // # proposal resources\n\n noteCreatedTransport(transport: RTCDtlsTransport) {\n this.createdTransports.add(transport);\n // A stopped transport needs no cleanup; do not keep referencing it.\n transport.onStateChange.subscribe((state) => {\n if (state === \"closed\") this.createdTransports.delete(transport);\n });\n }\n\n rememberRemoteTransceiver(transceiver: RTCRtpTransceiver) {\n this.resources.remoteCreated.add(transceiver);\n // Before the offer negotiates anything on it: a rollback that keeps the\n // transceiver (the application uses it) returns it to this state.\n this.createdStates.set(transceiver, transceiver.snapshotNegotiationState());\n }\n\n rememberOwnerTransport(transport: RTCDtlsTransport) {\n this.resources.owners.add(transport);\n }\n\n rememberDisplacedTransceiver(transceiver: RTCRtpTransceiver) {\n this.resources.displaced.add(transceiver);\n }\n\n get preparedDescription() {\n return this.resources.preparedFor;\n }\n\n get transportByMid() {\n return this.resources.prepared;\n }\n\n /**\n * Internal: whether the rollback baseline negotiated SCTP (it has a remote\n * port). A final answer rejecting m=application closes only an association\n * the proposal started (by a pranswer or the remote INIT); one the baseline\n * negotiated keeps running, as for every other rejection.\n */\n get baselineNegotiatedSctp() {\n return this.baseline?.sctp.remotePort !== undefined;\n }\n\n isPendingOnlyTransport(iceTransportId: string) {\n return [...this.resources.pendingOnly].some(\n (transport) => transport.iceTransport.id === iceTransportId,\n );\n }\n\n takePreparedCandidateTransports() {\n const { pendingOnly, emittedCandidates } = this.resources;\n const transports = [...pendingOnly].filter(\n (transport) => !emittedCandidates.has(transport.id),\n );\n for (const transport of transports) {\n emittedCandidates.add(transport.id);\n }\n return transports;\n }\n\n prepareTransport(\n description: SessionDescription,\n mid: string,\n transport: RTCDtlsTransport,\n pendingOnly = false,\n ) {\n this.resources.preparedFor = description;\n this.resources.prepared.set(mid, transport);\n if (pendingOnly) this.resources.pendingOnly.add(transport);\n }\n\n async discardPreparedTransports() {\n const { prepared, pendingOnly, emittedCandidates } = this.resources;\n const stopping = [...pendingOnly];\n prepared.clear();\n pendingOnly.clear();\n emittedCandidates.clear();\n this.resources.preparedFor = undefined;\n await Promise.allSettled(stopping.map((transport) => transport.stop()));\n }\n\n /**\n * A remote pranswer or answer replaces every earlier remote pranswer of\n * this offer: routes and receive values those staged are dropped before it\n * applies, so the commit switches only to what the latest description\n * carries.\n */\n discardStagedRemoteAnswer() {\n this.router.discardProvisional();\n this.router.restoreStaged({ ssrc: [], rid: [] });\n for (const transceiver of this.transceivers.getTransceivers()) {\n transceiver.receiver.discardStagedReceive();\n }\n }\n\n // # retired ICE generations\n\n retireRemoteGeneration(description?: SessionDescription) {\n for (const media of description?.media ?? []) {\n const ufrag = media.iceParams?.usernameFragment;\n if (ufrag) this.retiredRemoteUfrags.add(ufrag);\n }\n // A bounded history covers late callbacks without retaining every past\n // negotiation for the lifetime of a long-running peer.\n while (this.retiredRemoteUfrags.size > RETIRED_UFRAG_HISTORY) {\n this.retiredRemoteUfrags.delete(\n this.retiredRemoteUfrags.values().next().value!,\n );\n }\n }\n\n isRetiredRemoteUfrag(ufrag?: string | null) {\n return !!ufrag && this.retiredRemoteUfrags.has(ufrag);\n }\n\n // # state capture and restore\n\n private capture(): Baseline {\n return {\n transceivers: this.transceivers.snapshotNegotiationState(),\n routes: this.router.snapshotRoutes(),\n sctp: this.sctp.snapshotNegotiationState(),\n };\n }\n\n /**\n * Put transceivers, routes and SCTP back to `baseline`. Transceivers in\n * `added` and transports in `speculative` were created after it; those no\n * restored owner uses stop.\n */\n private async restoreState(\n baseline: Baseline,\n added: Iterable<RTCRtpTransceiver>,\n speculative: Iterable<RTCDtlsTransport>,\n carried: ReadonlySet<RTCRtpTransceiver> = new Set(),\n notified: ReadonlySet<RTCRtpTransceiver> = new Set(),\n ) {\n const removedTransports = this.transceivers.restoreNegotiationState(\n baseline.transceivers,\n added,\n (transceiver) => this.createdStates.get(transceiver),\n carried,\n notified,\n );\n const live = this.transceivers.getTransceivers();\n this.router.restoreRoutes(baseline.routes, {\n endpoints: new Set(live.flatMap((t) => [t.sender, t.receiver])),\n liveSenders: live\n .filter((t) => !t.stopped && !t.stopping)\n .map((t) => t.sender),\n });\n // The transport an SCTP transport the proposal created ran on (a remote\n // offer's application m-line) stops with it unless something else uses it.\n const proposedSctp = this.sctp.sctpTransport?.dtlsTransport;\n await this.sctp.restoreNegotiationState(baseline.sctp);\n\n const inUse = this.transportsInUse({ includeStopped: true });\n for (const transport of new Set([\n ...speculative,\n ...removedTransports,\n ...(proposedSctp ? [proposedSctp] : []),\n ])) {\n if (!inUse.has(transport)) await transport.stop();\n }\n }\n\n /** Transports a transceiver (optionally a stopped one) or SCTP is bound to. */\n private transportsInUse({ includeStopped }: { includeStopped: boolean }) {\n const inUse = new Set(\n this.transceivers\n .getTransceivers()\n .filter((transceiver) => includeStopped || !transceiver.stopped)\n .map((transceiver) => transceiver.dtlsTransport),\n );\n const sctp = this.sctp.sctpTransport?.dtlsTransport;\n if (sctp) inUse.add(sctp);\n return inUse;\n }\n\n private cleanup() {\n this.baseline = undefined;\n this.resources.clear();\n this.phase = \"idle\";\n }\n\n /** Internal test observation, never exposed on the public API. */\n inspect() {\n return {\n phase: this.phase,\n revision: this.revision,\n currentLocal: this.sdp.currentLocalDescription,\n currentRemote: this.sdp.currentRemoteDescription,\n pendingLocal: this.sdp.pendingLocalDescription,\n pendingRemote: this.sdp.pendingRemoteDescription,\n baselineTransceivers: this.baseline?.transceivers.states.size ?? 0,\n remoteCreated: this.resources.remoteCreated.size,\n pendingTransports: this.resources.pendingOnly.size,\n createdTransports: [...this.createdTransports],\n hasOfferSnapshot: !!this.offerSnapshot,\n };\n }\n}\n\n/** Whether a replacing offer describes the MID of `transceiver` again. */\nconst describedAgain = (\n next: SessionDescription | undefined,\n transceiver: RTCRtpTransceiver,\n) =>\n !!next?.media.some(\n (media) =>\n media.port !== 0 &&\n media.kind === transceiver.kind &&\n media.rtp.muxId === transceiver.mid,\n );\n"]}