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,9 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EventTarget = exports.PromiseQueue = void 0;
4
+ exports.notifySafely = notifySafely;
4
5
  exports.enumerate = enumerate;
5
6
  exports.divide = divide;
6
7
  const node_events_1 = require("node:events");
8
+ /**
9
+ * Run one notification to listeners (an `Event.execute`, an `on*` handler or
10
+ * an `emit`) so that an exception a listener throws is logged and never
11
+ * interrupts the caller's own processing (state propagation, cleanup).
12
+ */
13
+ function notifySafely(log, name, notify) {
14
+ try {
15
+ notify();
16
+ }
17
+ catch (error) {
18
+ log(`${name} listener failed`, error);
19
+ }
20
+ }
7
21
  function enumerate(arr) {
8
22
  return arr.map((v, i) => [i, v]);
9
23
  }
@@ -81,11 +95,33 @@ class EventTarget extends node_events_1.EventEmitter {
81
95
  });
82
96
  }
83
97
  emit(type, ...args) {
98
+ return super.emit(type, ...this.eventArgs(type, args));
99
+ }
100
+ /**
101
+ * @internal
102
+ * Like {@link emit}, but every listener runs even if an earlier one
103
+ * throws: each exception is passed to `onError` (`once` listeners still
104
+ * run once). Unlike `emit("error")`, nothing is thrown when no listener
105
+ * is registered.
106
+ */
107
+ emitIsolated(onError, type, ...args) {
108
+ const eventArgs = this.eventArgs(type, args);
109
+ for (const listener of this.rawListeners(type)) {
110
+ try {
111
+ listener.apply(this, eventArgs);
112
+ }
113
+ catch (error) {
114
+ onError(error);
115
+ }
116
+ }
117
+ }
118
+ /** The DOM-like event arguments: an Event with `type` as the first one. */
119
+ eventArgs(type, args) {
84
120
  if (typeof type !== "string") {
85
- return super.emit(type, ...args);
121
+ return args;
86
122
  }
87
123
  if (args.length === 0) {
88
- return super.emit(type, new Event(type));
124
+ return [new Event(type)];
89
125
  }
90
126
  const [event, ...rest] = args;
91
127
  if (event && typeof event === "object" && !("type" in event)) {
@@ -97,10 +133,10 @@ class EventTarget extends node_events_1.EventEmitter {
97
133
  });
98
134
  }
99
135
  catch {
100
- return super.emit(type, { type, ...event }, ...rest);
136
+ return [{ type, ...event }, ...rest];
101
137
  }
102
138
  }
103
- return super.emit(type, event, ...rest);
139
+ return [event, ...rest];
104
140
  }
105
141
  }
106
142
  exports.EventTarget = EventTarget;
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../src/helper.ts"],"names":[],"mappings":";;;AAEA,8BAEC;AAED,wBAGC;AATD,6CAA2C;AAE3C,SAAgB,SAAS,CAAI,GAAQ;IACnC,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACnC,CAAC;AAED,SAAgB,MAAM,CAAC,IAAY,EAAE,KAA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AI,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;IAC1C,CAAC;CAmBF;AA3CD,kCA2CC","sourcesContent":["import { EventEmitter } from \"node:events\";\n\nexport function enumerate<T>(arr: T[]): [number, T][] {\n return arr.map((v, i) => [i, v]);\n}\n\nexport function divide(from: string, split: string): [string, string] {\n const arr = from.split(split);\n return [arr[0], arr.slice(1).join(split)];\n}\n\nexport class PromiseQueue {\n queue: { promise: () => Promise<any>; done: () => void }[] = [];\n running = false;\n\n push = (promise: () => Promise<any>) =>\n new Promise<void>((r) => {\n this.queue.push({ promise, done: r });\n if (!this.running) this.run();\n });\n\n private async run() {\n const task = this.queue.shift();\n if (task) {\n this.running = true;\n await task.promise();\n task.done();\n\n this.run();\n } else {\n this.running = false;\n }\n }\n}\n\nexport class EventTarget extends EventEmitter {\n override emit(type: string | symbol, ...args: any[]) {\n if (typeof type !== \"string\") {\n return super.emit(type, ...args);\n }\n\n if (args.length === 0) {\n return super.emit(type, new Event(type));\n }\n\n const [event, ...rest] = args;\n if (event && typeof event === \"object\" && !(\"type\" in event)) {\n try {\n Object.defineProperty(event, \"type\", {\n configurable: true,\n enumerable: true,\n value: type,\n });\n } catch {\n return super.emit(type, { type, ...event }, ...rest);\n }\n }\n\n return super.emit(type, event, ...rest);\n }\n\n addEventListener = (\n type: string,\n listener: (...args: any[]) => void,\n options?: boolean | { once?: boolean },\n ) => {\n if (typeof options === \"object\" && options?.once) {\n this.once(type, listener);\n return;\n }\n this.addListener(type, listener);\n };\n\n removeEventListener = (type: string, listener: (...args: any[]) => void) => {\n this.removeListener(type, listener);\n };\n\n dispatchEvent = (event: Event) => this.emit(event.type, event);\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../src/helper.ts"],"names":[],"mappings":";;;AAOA,oCAUC;AAED,8BAEC;AAED,wBAGC;AA1BD,6CAA2C;AAE3C;;;;GAIG;AACH,SAAgB,YAAY,CAC1B,GAAiC,EACjC,IAAY,EACZ,MAA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AAK,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,CAAC;YACjB,CAAC;QACH,CAAC;IACH,CAAC;IAED,2EAA2E;IACnE,SAAS,CAAC,IAAqB,EAAE,IAAW;QAClD,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3B,CAAC;QAED,MAAM,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;QAC9B,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC;YAC7D,IAAI,CAAC;gBACH,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE;oBACnC,YAAY,EAAE,IAAI;oBAClB,UAAU,EAAE,IAAI;oBAChB,KAAK,EAAE,IAAI;iBACZ,CAAC,CAAC;YACL,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,KAAK,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;YACvC,CAAC;QACH,CAAC;QAED,OAAO,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;IAC1B,CAAC;CAmBF;AAtED,kCAsEC","sourcesContent":["import { EventEmitter } from \"node:events\";\n\n/**\n * Run one notification to listeners (an `Event.execute`, an `on*` handler or\n * an `emit`) so that an exception a listener throws is logged and never\n * interrupts the caller's own processing (state propagation, cleanup).\n */\nexport function notifySafely(\n log: (...args: unknown[]) => void,\n name: string,\n notify: () => void,\n) {\n try {\n notify();\n } catch (error) {\n log(`${name} listener failed`, error);\n }\n}\n\nexport function enumerate<T>(arr: T[]): [number, T][] {\n return arr.map((v, i) => [i, v]);\n}\n\nexport function divide(from: string, split: string): [string, string] {\n const arr = from.split(split);\n return [arr[0], arr.slice(1).join(split)];\n}\n\nexport class PromiseQueue {\n queue: { promise: () => Promise<any>; done: () => void }[] = [];\n running = false;\n\n push = (promise: () => Promise<any>) =>\n new Promise<void>((r) => {\n this.queue.push({ promise, done: r });\n if (!this.running) this.run();\n });\n\n private async run() {\n const task = this.queue.shift();\n if (task) {\n this.running = true;\n await task.promise();\n task.done();\n\n this.run();\n } else {\n this.running = false;\n }\n }\n}\n\nexport class EventTarget extends EventEmitter {\n override emit(type: string | symbol, ...args: any[]) {\n return super.emit(type, ...this.eventArgs(type, args));\n }\n\n /**\n * @internal\n * Like {@link emit}, but every listener runs even if an earlier one\n * throws: each exception is passed to `onError` (`once` listeners still\n * run once). Unlike `emit(\"error\")`, nothing is thrown when no listener\n * is registered.\n */\n emitIsolated(\n onError: (error: unknown) => void,\n type: string,\n ...args: any[]\n ) {\n const eventArgs = this.eventArgs(type, args);\n for (const listener of this.rawListeners(type)) {\n try {\n (listener as (...args: any[]) => void).apply(this, eventArgs);\n } catch (error) {\n onError(error);\n }\n }\n }\n\n /** The DOM-like event arguments: an Event with `type` as the first one. */\n private eventArgs(type: string | symbol, args: any[]): any[] {\n if (typeof type !== \"string\") {\n return args;\n }\n\n if (args.length === 0) {\n return [new Event(type)];\n }\n\n const [event, ...rest] = args;\n if (event && typeof event === \"object\" && !(\"type\" in event)) {\n try {\n Object.defineProperty(event, \"type\", {\n configurable: true,\n enumerable: true,\n value: type,\n });\n } catch {\n return [{ type, ...event }, ...rest];\n }\n }\n\n return [event, ...rest];\n }\n\n addEventListener = (\n type: string,\n listener: (...args: any[]) => void,\n options?: boolean | { once?: boolean },\n ) => {\n if (typeof options === \"object\" && options?.once) {\n this.once(type, listener);\n return;\n }\n this.addListener(type, listener);\n };\n\n removeEventListener = (type: string, listener: (...args: any[]) => void) => {\n this.removeListener(type, listener);\n };\n\n dispatchEvent = (event: Event) => this.emit(event.type, event);\n}\n"]}
@@ -1,17 +1,63 @@
1
1
  import type { Kind } from "../types/domain";
2
- import type { RTCRtpCodecParameters } from "./parameters";
2
+ import { RTCRtpCodecParameters } from "./parameters";
3
3
  /**
4
4
  * Lower-cased MIME type with the legacy `video/AV1X` name folded into
5
5
  * `video/av1`, so both names negotiate with each other.
6
6
  */
7
7
  export declare function normalizeCodecMimeType(mimeType: string): string;
8
+ /**
9
+ * Whether `source` (a track's codec or a remote codec) can be carried as
10
+ * `configured`: the same MIME type, clock rate and channels, and the same
11
+ * format-identifying parameters (`FORMAT_PARAMETERS`: H264 mode / profile,
12
+ * VP9 profile, AV1 profile). A parameter omitted on either side matches any
13
+ * value.
14
+ */
8
15
  export declare function isCodecCompatible(source: RTCRtpCodecParameters, configured: RTCRtpCodecParameters): boolean;
16
+ /**
17
+ * The fallback predicate negotiation pairs a configured codec with a remote
18
+ * one by when no remote codec has its format (`pairCodecs`): the same MIME
19
+ * type. The negotiated codec is then in the remote's form (payload type,
20
+ * fmtp, rtcp-fb), which may differ from the configured one, but it is what
21
+ * the configured codec negotiated, so a later offer lists it as it is
22
+ * (RFC 3264 §8.3.2).
23
+ */
24
+ export declare function negotiatesAs(configured: RTCRtpCodecParameters, negotiated: RTCRtpCodecParameters): boolean;
25
+ /**
26
+ * Pair each configured primary codec with at most one of `others` (and each
27
+ * of `others` with at most one configured codec), the rule negotiation
28
+ * (`setRemoteDescription()` / `createAnswer()`) and a later offer share,
29
+ * in three passes over the configured codecs, each pass only for the codecs
30
+ * still unpaired:
31
+ *
32
+ * 1. the codec of exactly the same format (`sameFormat`: MIME type, clock
33
+ * rate, channels and every `a=fmtp` parameter, for any codec: VP9
34
+ * `profile-id`, AV1 `profile`, H264 `packetization-mode` /
35
+ * `profile-level-id`, Opus parameters, ...);
36
+ * 2. a compatible one (`isCodecCompatible`: the same format-identifying
37
+ * parameters, H264 mode / profile, VP9 / AV1 profile, where an omitted
38
+ * one matches any value);
39
+ * 3. one of the same MIME type (`negotiatesAs`, for instance an H264 of
40
+ * another level or a VP9 of another profile).
41
+ *
42
+ * So when the configured codecs hold several formats of one MIME type (H264
43
+ * mode 0 and mode 1, VP9 profile 0 and profile 2), each pairs with its own
44
+ * format whatever the order, and an answer does not switch the format the
45
+ * offer meant. RTX / RED are not paired. `accept` limits the candidates (a
46
+ * fixed track source).
47
+ */
48
+ export declare function pairCodecs(configured: readonly RTCRtpCodecParameters[], others: readonly RTCRtpCodecParameters[], accept?: (configured: RTCRtpCodecParameters, other: RTCRtpCodecParameters) => boolean): Map<RTCRtpCodecParameters, RTCRtpCodecParameters>;
9
49
  /**
10
50
  * remote track が実際に配信する codec を返す。
11
51
  * audio の RED は RTCRtpReceiver が primary へ展開してから track へ渡すため、
12
52
  * RED が参照する primary codec (不明なら先頭の primary) を track の codec とする。
13
53
  */
14
54
  export declare function deliveredTrackCodec(kind: string, codec: RTCRtpCodecParameters | undefined, negotiated: readonly RTCRtpCodecParameters[]): RTCRtpCodecParameters | undefined;
55
+ /**
56
+ * 交渉済み codec 列から remote track の codec を決める。
57
+ * 先頭の RTX (と video の RED / FEC) は飛ばし、audio の RED は
58
+ * {@link deliveredTrackCodec} と同じく primary へ解決する。
59
+ */
60
+ export declare function primaryTrackCodec(kind: string, negotiated: readonly RTCRtpCodecParameters[]): RTCRtpCodecParameters | undefined;
15
61
  /**
16
62
  * RTX / RED を除く primary codec に MIME 一致が 1 つでもあるか。
17
63
  * remote m-line を local capability で扱えるかの判定 (Issue #705) に使う。
@@ -26,3 +72,43 @@ export declare function assertCodecsSupported(options: {
26
72
  source: readonly RTCRtpCodecParameters[] | undefined;
27
73
  preferences: readonly RTCRtpCodecParameters[] | undefined;
28
74
  }): RTCRtpCodecParameters[];
75
+ /**
76
+ * Configured codecs a negotiated m-line offers, before payload types are
77
+ * mapped (`keepNegotiatedPayloadTypes`): `capability` plus the configured
78
+ * counterpart (`pairCodecs`, the rule negotiation pairs by) of every
79
+ * negotiated codec that `capability` lacks.
80
+ *
81
+ * `eligible` is every configured codec of the kind with the fixed source and
82
+ * the codec preferences applied but no direction filter, and `capability` is
83
+ * the same for the current direction. A direction change (`direction`,
84
+ * `removeTrack()`) therefore never takes a negotiated codec off the m-line;
85
+ * only an answer does. Preferences and a fixed source still exclude one. An
86
+ * RTX / RED is kept when its primaries are and it is in `capability` or
87
+ * negotiated for the same primaries. The order is that of `eligible`
88
+ * (preferences, then configuration), the order of a first offer.
89
+ */
90
+ export declare function withNegotiatedCodecs(eligible: readonly RTCRtpCodecParameters[], capability: readonly RTCRtpCodecParameters[], negotiated: readonly RTCRtpCodecParameters[]): RTCRtpCodecParameters[];
91
+ /**
92
+ * Offer codecs for a negotiated m-line (RFC 8829 §5.2.2, RFC 3264 §8.3.2):
93
+ * `capability` (configured codecs, in offer order) with each configured codec
94
+ * that is already negotiated replaced by the negotiated codec itself, so its
95
+ * payload type, fmtp and rtcp-fb stay as negotiated (also when the remote's
96
+ * form differs from the configured one). Configured and negotiated codecs
97
+ * pair as negotiation pairs them (`pairCodecs`: the same format first, then
98
+ * the same MIME type). Another format of a negotiated MIME type that the
99
+ * answer left out (H264 mode 1 next to a negotiated mode 0) is offered again
100
+ * like any other codec, so a later answer can move to it; an answer that
101
+ * still has the negotiated format pairs with it, since negotiation prefers
102
+ * the same format. A negotiated RTX / RED for the offered primaries is
103
+ * offered as negotiated too.
104
+ *
105
+ * A codec offered again keeps its configured payload type unless that type is
106
+ * already used on this m-line or maps to another codec in `taken` (every
107
+ * payload type the session uses; the same codec with other format parameters
108
+ * or RTCP feedback, such as a RED with other primaries, is another codec);
109
+ * then it takes a free dynamic type (96-127,
110
+ * then 35-63). RTX `apt` and RED references follow their primaries, and an
111
+ * RTX / RED whose primary is not offered is dropped. The order of
112
+ * `capability` is kept.
113
+ */
114
+ export declare function keepNegotiatedPayloadTypes(capability: readonly RTCRtpCodecParameters[], negotiated: readonly RTCRtpCodecParameters[], taken: ReadonlyMap<number, RTCRtpCodecParameters>): RTCRtpCodecParameters[];
@@ -2,14 +2,20 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normalizeCodecMimeType = normalizeCodecMimeType;
4
4
  exports.isCodecCompatible = isCodecCompatible;
5
+ exports.negotiatesAs = negotiatesAs;
6
+ exports.pairCodecs = pairCodecs;
5
7
  exports.deliveredTrackCodec = deliveredTrackCodec;
8
+ exports.primaryTrackCodec = primaryTrackCodec;
6
9
  exports.hasCommonPrimaryMimeType = hasCommonPrimaryMimeType;
7
10
  exports.intersectCodecs = intersectCodecs;
8
11
  exports.applyCodecPreferences = applyCodecPreferences;
9
12
  exports.resolveCodecs = resolveCodecs;
10
13
  exports.assertCodecsSupported = assertCodecsSupported;
14
+ exports.withNegotiatedCodecs = withNegotiatedCodecs;
15
+ exports.keepNegotiatedPayloadTypes = keepNegotiatedPayloadTypes;
11
16
  const errors_1 = require("../errors");
12
17
  const sdp_1 = require("../sdp");
18
+ const parameters_1 = require("./parameters");
13
19
  /**
14
20
  * Lower-cased MIME type with the legacy `video/AV1X` name folded into
15
21
  * `video/av1`, so both names negotiate with each other.
@@ -24,13 +30,29 @@ function codecName(codec) {
24
30
  function optionalEqual(left, right) {
25
31
  return left == undefined || right == undefined || left === right;
26
32
  }
27
- function h264Parameters(codec) {
33
+ /**
34
+ * The `a=fmtp` parameters that tell the formats of one MIME type apart (a
35
+ * decoder for one cannot take the other): H264 `packetization-mode` and
36
+ * `profile-level-id` (RFC 6184), VP9 `profile-id` (RFC 9628) and AV1
37
+ * `profile` (AV1 RTP payload format). Values are compared case-insensitively.
38
+ */
39
+ const FORMAT_PARAMETERS = {
40
+ h264: ["packetization-mode", "profile-level-id"],
41
+ vp9: ["profile-id"],
42
+ av1: ["profile"],
43
+ av1x: ["profile"],
44
+ };
45
+ function formatIdentity(codec) {
28
46
  const parameters = (0, sdp_1.codecParametersFromString)(codec.parameters ?? "");
29
- return {
30
- packetizationMode: parameters["packetization-mode"],
31
- profileLevelId: parameters["profile-level-id"]?.toString().toLowerCase(),
32
- };
47
+ return (FORMAT_PARAMETERS[codecName(codec)] ?? []).map((name) => parameters[name]?.toString().toLowerCase());
33
48
  }
49
+ /**
50
+ * Whether `source` (a track's codec or a remote codec) can be carried as
51
+ * `configured`: the same MIME type, clock rate and channels, and the same
52
+ * format-identifying parameters (`FORMAT_PARAMETERS`: H264 mode / profile,
53
+ * VP9 profile, AV1 profile). A parameter omitted on either side matches any
54
+ * value.
55
+ */
34
56
  function isCodecCompatible(source, configured) {
35
57
  if (normalizeCodecMimeType(source.mimeType) !==
36
58
  normalizeCodecMimeType(configured.mimeType)) {
@@ -40,14 +62,68 @@ function isCodecCompatible(source, configured) {
40
62
  return false;
41
63
  if (!optionalEqual(source.channels, configured.channels))
42
64
  return false;
43
- if (codecName(source) !== "h264")
44
- return true;
45
- const sourceParameters = h264Parameters(source);
46
- const configuredParameters = h264Parameters(configured);
47
- if (!optionalEqual(sourceParameters.packetizationMode, configuredParameters.packetizationMode)) {
48
- return false;
65
+ const sourceIdentity = formatIdentity(source);
66
+ const configuredIdentity = formatIdentity(configured);
67
+ return sourceIdentity.every((value, index) => optionalEqual(value, configuredIdentity[index]));
68
+ }
69
+ /**
70
+ * The fallback predicate negotiation pairs a configured codec with a remote
71
+ * one by when no remote codec has its format (`pairCodecs`): the same MIME
72
+ * type. The negotiated codec is then in the remote's form (payload type,
73
+ * fmtp, rtcp-fb), which may differ from the configured one, but it is what
74
+ * the configured codec negotiated, so a later offer lists it as it is
75
+ * (RFC 3264 §8.3.2).
76
+ */
77
+ function negotiatesAs(configured, negotiated) {
78
+ return (normalizeCodecMimeType(configured.mimeType) ===
79
+ normalizeCodecMimeType(negotiated.mimeType));
80
+ }
81
+ /**
82
+ * Pair each configured primary codec with at most one of `others` (and each
83
+ * of `others` with at most one configured codec), the rule negotiation
84
+ * (`setRemoteDescription()` / `createAnswer()`) and a later offer share,
85
+ * in three passes over the configured codecs, each pass only for the codecs
86
+ * still unpaired:
87
+ *
88
+ * 1. the codec of exactly the same format (`sameFormat`: MIME type, clock
89
+ * rate, channels and every `a=fmtp` parameter, for any codec: VP9
90
+ * `profile-id`, AV1 `profile`, H264 `packetization-mode` /
91
+ * `profile-level-id`, Opus parameters, ...);
92
+ * 2. a compatible one (`isCodecCompatible`: the same format-identifying
93
+ * parameters, H264 mode / profile, VP9 / AV1 profile, where an omitted
94
+ * one matches any value);
95
+ * 3. one of the same MIME type (`negotiatesAs`, for instance an H264 of
96
+ * another level or a VP9 of another profile).
97
+ *
98
+ * So when the configured codecs hold several formats of one MIME type (H264
99
+ * mode 0 and mode 1, VP9 profile 0 and profile 2), each pairs with its own
100
+ * format whatever the order, and an answer does not switch the format the
101
+ * offer meant. RTX / RED are not paired. `accept` limits the candidates (a
102
+ * fixed track source).
103
+ */
104
+ function pairCodecs(configured, others, accept = () => true) {
105
+ const pairs = new Map();
106
+ const used = new Set();
107
+ const passes = [
108
+ sameFormat,
109
+ (codec, other) => isCodecCompatible(other, codec),
110
+ negotiatesAs,
111
+ ];
112
+ for (const matches of passes) {
113
+ for (const codec of configured) {
114
+ if (isAuxiliary(codec) || pairs.has(codec))
115
+ continue;
116
+ const other = others.find((candidate) => !isAuxiliary(candidate) &&
117
+ !used.has(candidate) &&
118
+ matches(codec, candidate) &&
119
+ accept(codec, candidate));
120
+ if (!other)
121
+ continue;
122
+ pairs.set(codec, other);
123
+ used.add(other);
124
+ }
49
125
  }
50
- return optionalEqual(sourceParameters.profileLevelId, configuredParameters.profileLevelId);
126
+ return pairs;
51
127
  }
52
128
  function isAuxiliary(codec) {
53
129
  return ["rtx", "red"].includes(codecName(codec));
@@ -66,6 +142,18 @@ function deliveredTrackCodec(kind, codec, negotiated) {
66
142
  negotiated.find((candidate) => !isAuxiliary(candidate)) ??
67
143
  codec);
68
144
  }
145
+ /**
146
+ * 交渉済み codec 列から remote track の codec を決める。
147
+ * 先頭の RTX (と video の RED / FEC) は飛ばし、audio の RED は
148
+ * {@link deliveredTrackCodec} と同じく primary へ解決する。
149
+ */
150
+ function primaryTrackCodec(kind, negotiated) {
151
+ const first = negotiated.find((codec) => kind === "audio"
152
+ ? codecName(codec) !== "rtx"
153
+ : !isAuxiliary(codec) &&
154
+ !["ulpfec", "flexfec-03"].includes(codecName(codec))) ?? negotiated[0];
155
+ return deliveredTrackCodec(kind, first, negotiated);
156
+ }
69
157
  /**
70
158
  * RTX / RED を除く primary codec に MIME 一致が 1 つでもあるか。
71
159
  * remote m-line を local capability で扱えるかの判定 (Issue #705) に使う。
@@ -82,8 +170,10 @@ function referencedPayloadTypes(codec) {
82
170
  return Number.isNaN(apt) ? [] : [apt];
83
171
  }
84
172
  if (codecName(codec) === "red") {
173
+ // `Number("")` is 0: a RED without fmtp references nothing.
85
174
  return parameters
86
175
  .split("/")
176
+ .filter((value) => value.trim() !== "")
87
177
  .map(Number)
88
178
  .filter((value) => !Number.isNaN(value));
89
179
  }
@@ -146,4 +236,240 @@ function assertCodecsSupported(options) {
146
236
  }
147
237
  return effective;
148
238
  }
239
+ /**
240
+ * Configured codecs a negotiated m-line offers, before payload types are
241
+ * mapped (`keepNegotiatedPayloadTypes`): `capability` plus the configured
242
+ * counterpart (`pairCodecs`, the rule negotiation pairs by) of every
243
+ * negotiated codec that `capability` lacks.
244
+ *
245
+ * `eligible` is every configured codec of the kind with the fixed source and
246
+ * the codec preferences applied but no direction filter, and `capability` is
247
+ * the same for the current direction. A direction change (`direction`,
248
+ * `removeTrack()`) therefore never takes a negotiated codec off the m-line;
249
+ * only an answer does. Preferences and a fixed source still exclude one. An
250
+ * RTX / RED is kept when its primaries are and it is in `capability` or
251
+ * negotiated for the same primaries. The order is that of `eligible`
252
+ * (preferences, then configuration), the order of a first offer.
253
+ */
254
+ function withNegotiatedCodecs(eligible, capability, negotiated) {
255
+ const candidates = [
256
+ ...eligible,
257
+ ...capability.filter((codec) => !eligible.includes(codec)),
258
+ ];
259
+ const primaryOf = (codecs, payloadType) => codecs.find((codec) => !isAuxiliary(codec) && codec.payloadType === payloadType);
260
+ const pairs = pairCodecs(candidates, negotiated);
261
+ const kept = new Set(candidates.filter((codec) => !isAuxiliary(codec) && (capability.includes(codec) || pairs.has(codec))));
262
+ const negotiatedForSamePrimaries = (codec) => {
263
+ const primaries = referencedPayloadTypes(codec).map((payloadType) => primaryOf(candidates, payloadType));
264
+ return negotiated.some((other) => {
265
+ if (codecName(other) !== codecName(codec))
266
+ return false;
267
+ const otherPrimaries = referencedPayloadTypes(other).map((payloadType) => primaryOf(negotiated, payloadType));
268
+ return (otherPrimaries.length === primaries.length &&
269
+ primaries.every((primary, index) => {
270
+ const otherPrimary = otherPrimaries[index];
271
+ return (primary != undefined &&
272
+ otherPrimary != undefined &&
273
+ pairs.get(primary) === otherPrimary);
274
+ }));
275
+ });
276
+ };
277
+ return candidates.filter((codec) => {
278
+ if (!isAuxiliary(codec))
279
+ return kept.has(codec);
280
+ const primaries = referencedPayloadTypes(codec).map((payloadType) => primaryOf(candidates, payloadType));
281
+ if (primaries.some((primary) => primary == undefined || !kept.has(primary)))
282
+ return false;
283
+ return capability.includes(codec) || negotiatedForSamePrimaries(codec);
284
+ });
285
+ }
286
+ /**
287
+ * The format parameters (`a=fmtp`) a payload type stands for, in a form that
288
+ * compares equal when the parameters mean the same: parameter names are
289
+ * case-insensitive and unordered, and H264 gets its RFC 6184 §8.1 defaults
290
+ * (`packetization-mode` 0, `profile-level-id` 42000A, case-insensitive), so
291
+ * an omitted parameter and its default are the same format. Anything else
292
+ * (an RTX `apt`, the primaries of a RED `110/110`) is compared as written.
293
+ */
294
+ function formatParameters(codec) {
295
+ const entries = new Map();
296
+ for (const item of (codec.parameters ?? "").split(";")) {
297
+ const parameter = item.trim();
298
+ if (parameter.length === 0)
299
+ continue;
300
+ const separator = parameter.indexOf("=");
301
+ if (separator < 0) {
302
+ entries.set(parameter, "");
303
+ continue;
304
+ }
305
+ entries.set(parameter.slice(0, separator).trim().toLowerCase(), parameter.slice(separator + 1).trim());
306
+ }
307
+ if (codecName(codec) === "h264") {
308
+ entries.set("packetization-mode", entries.get("packetization-mode") ?? "0");
309
+ entries.set("profile-level-id", (entries.get("profile-level-id") ?? "42000a").toLowerCase());
310
+ }
311
+ return [...entries]
312
+ .map(([name, value]) => `${name}=${value}`)
313
+ .sort()
314
+ .join(";");
315
+ }
316
+ /**
317
+ * The RTCP feedback (`a=rtcp-fb`) a payload type stands for, unordered and
318
+ * without duplicates, with the type and parameter compared case-insensitively.
319
+ */
320
+ function feedbackTypes(codec) {
321
+ return [
322
+ ...new Set(codec.rtcpFeedback.map((feedback) => `${feedback.type} ${feedback.parameter ?? ""}`.trim().toLowerCase())),
323
+ ]
324
+ .sort()
325
+ .join(";");
326
+ }
327
+ /**
328
+ * Whether two codecs can share a payload type in one BUNDLE group (RFC 3264
329
+ * §8.3.2, RFC 8843 §9.1): the same codec with the same format parameters and
330
+ * RTCP feedback, the attributes RFC 8859 puts in the IDENTICAL-PER-PT
331
+ * category (`a=fmtp`, `a=rtcp-fb`). So an H264 format with another
332
+ * `packetization-mode` or `profile-level-id`, an RTX for another `apt`, a RED
333
+ * with other primaries or a VP8 with other feedback is another codec.
334
+ */
335
+ function samePayloadMapping(left, right) {
336
+ return (sameFormat(left, right) && feedbackTypes(left) === feedbackTypes(right));
337
+ }
338
+ /**
339
+ * The same media format (`a=rtpmap` and `a=fmtp`, RFC 4566): MIME type,
340
+ * clock rate, channels and the format parameters (`formatParameters`), for
341
+ * every codec. RTCP feedback is not part of the format.
342
+ */
343
+ function sameFormat(left, right) {
344
+ return (normalizeCodecMimeType(left.mimeType) ===
345
+ normalizeCodecMimeType(right.mimeType) &&
346
+ left.clockRate === right.clockRate &&
347
+ (left.channels ?? 1) === (right.channels ?? 1) &&
348
+ formatParameters(left) === formatParameters(right));
349
+ }
350
+ function withPayloadType(codec, payloadType, parameters = codec.parameters) {
351
+ if (codec.payloadType === payloadType && codec.parameters === parameters) {
352
+ return codec;
353
+ }
354
+ const next = new parameters_1.RTCRtpCodecParameters({
355
+ mimeType: codec.mimeType,
356
+ clockRate: codec.clockRate,
357
+ ...(codec.channels != undefined ? { channels: codec.channels } : {}),
358
+ payloadType,
359
+ rtcpFeedback: codec.rtcpFeedback.map((feedback) => ({ ...feedback })),
360
+ ...(parameters != undefined ? { parameters } : {}),
361
+ direction: codec.direction,
362
+ });
363
+ return next;
364
+ }
365
+ /**
366
+ * Offer codecs for a negotiated m-line (RFC 8829 §5.2.2, RFC 3264 §8.3.2):
367
+ * `capability` (configured codecs, in offer order) with each configured codec
368
+ * that is already negotiated replaced by the negotiated codec itself, so its
369
+ * payload type, fmtp and rtcp-fb stay as negotiated (also when the remote's
370
+ * form differs from the configured one). Configured and negotiated codecs
371
+ * pair as negotiation pairs them (`pairCodecs`: the same format first, then
372
+ * the same MIME type). Another format of a negotiated MIME type that the
373
+ * answer left out (H264 mode 1 next to a negotiated mode 0) is offered again
374
+ * like any other codec, so a later answer can move to it; an answer that
375
+ * still has the negotiated format pairs with it, since negotiation prefers
376
+ * the same format. A negotiated RTX / RED for the offered primaries is
377
+ * offered as negotiated too.
378
+ *
379
+ * A codec offered again keeps its configured payload type unless that type is
380
+ * already used on this m-line or maps to another codec in `taken` (every
381
+ * payload type the session uses; the same codec with other format parameters
382
+ * or RTCP feedback, such as a RED with other primaries, is another codec);
383
+ * then it takes a free dynamic type (96-127,
384
+ * then 35-63). RTX `apt` and RED references follow their primaries, and an
385
+ * RTX / RED whose primary is not offered is dropped. The order of
386
+ * `capability` is kept.
387
+ */
388
+ function keepNegotiatedPayloadTypes(capability, negotiated, taken) {
389
+ const offered = capability.map(() => undefined);
390
+ const used = new Set();
391
+ const primaryPayloadType = new Map();
392
+ const matched = new Set();
393
+ const isFree = (payloadType, codec) => {
394
+ if (used.has(payloadType))
395
+ return false;
396
+ const owner = taken.get(payloadType);
397
+ return owner == undefined || samePayloadMapping(owner, codec);
398
+ };
399
+ const pick = (preferred, codec) => {
400
+ if (isFree(preferred, codec))
401
+ return preferred;
402
+ for (const [from, to] of [
403
+ [96, 127],
404
+ [35, 63],
405
+ ]) {
406
+ for (let payloadType = from; payloadType <= to; payloadType++) {
407
+ if (isFree(payloadType, codec))
408
+ return payloadType;
409
+ }
410
+ }
411
+ return undefined;
412
+ };
413
+ const place = (index, codec) => {
414
+ offered[index] = codec;
415
+ used.add(codec.payloadType);
416
+ };
417
+ // 1. Negotiated primaries are offered as negotiated (payload type, fmtp,
418
+ // rtcp-fb), each in place of the configured codec it pairs with
419
+ // (`pairCodecs`: the same format first, then the same MIME type).
420
+ for (const [codec, match] of pairCodecs(capability, negotiated)) {
421
+ if (used.has(match.payloadType))
422
+ continue;
423
+ matched.add(match);
424
+ primaryPayloadType.set(codec.payloadType, match.payloadType);
425
+ place(capability.indexOf(codec), match);
426
+ }
427
+ // 2. Primaries offered again.
428
+ capability.forEach((codec, index) => {
429
+ if (isAuxiliary(codec) || offered[index])
430
+ return;
431
+ const payloadType = pick(codec.payloadType, codec);
432
+ if (payloadType == undefined)
433
+ return;
434
+ primaryPayloadType.set(codec.payloadType, payloadType);
435
+ place(index, withPayloadType(codec, payloadType));
436
+ });
437
+ // 3. RTX / RED follow their primaries.
438
+ capability.forEach((codec, index) => {
439
+ if (!isAuxiliary(codec))
440
+ return;
441
+ const references = referencedPayloadTypes(codec).map((payloadType) => primaryPayloadType.get(payloadType));
442
+ // A video RED has no fmtp (nothing references a primary): it is offered
443
+ // as configured. An RTX, or a RED that names primaries, needs them offered.
444
+ const standalone = codecName(codec) === "red" && references.length === 0;
445
+ if (!standalone &&
446
+ (references.length === 0 ||
447
+ references.some((payloadType) => payloadType == undefined))) {
448
+ return;
449
+ }
450
+ const parameters = standalone
451
+ ? codec.parameters
452
+ : codecName(codec) === "rtx"
453
+ ? (codec.parameters ?? "").replace(/(^|;)\s*apt=\d+/, `$1apt=${references[0]}`)
454
+ : references.join("/");
455
+ // The RTX / RED negotiated for these primaries is offered as negotiated.
456
+ const negotiatedAuxiliary = negotiated.find((other) => codecName(other) === codecName(codec) &&
457
+ !matched.has(other) &&
458
+ !used.has(other.payloadType) &&
459
+ (codecName(codec) === "rtx"
460
+ ? referencedPayloadTypes(other)[0] === references[0]
461
+ : (other.parameters ?? "") === (parameters ?? "")));
462
+ if (negotiatedAuxiliary) {
463
+ matched.add(negotiatedAuxiliary);
464
+ place(index, negotiatedAuxiliary);
465
+ return;
466
+ }
467
+ const candidate = withPayloadType(codec, codec.payloadType, parameters);
468
+ const payloadType = pick(codec.payloadType, candidate);
469
+ if (payloadType == undefined)
470
+ return;
471
+ place(index, withPayloadType(candidate, payloadType));
472
+ });
473
+ return offered.filter((codec) => codec != undefined);
474
+ }
149
475
  //# sourceMappingURL=codecCompatibility.js.map