react-native-webrtc 1.100.1 → 106.0.0-beta.1

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 (166) hide show
  1. package/ISSUE_TEMPLATE.md +17 -13
  2. package/README.md +46 -129
  3. package/android/src/main/java/com/oney/WebRTCModule/PeerConnectionObserver.java +160 -165
  4. package/android/src/main/java/com/oney/WebRTCModule/SerializeUtils.java +279 -0
  5. package/android/src/main/java/com/oney/WebRTCModule/WebRTCModule.java +361 -56
  6. package/android/src/main/java/com/oney/WebRTCModule/WebRTCView.java +5 -1
  7. package/ios/RCTWebRTC/RCTConvert+WebRTC.m +2 -6
  8. package/ios/RCTWebRTC/ScreenCapturer.m +0 -1
  9. package/ios/RCTWebRTC/SerializeUtils.h +25 -0
  10. package/ios/RCTWebRTC/SerializeUtils.m +219 -0
  11. package/ios/RCTWebRTC/WebRTCModule+RTCPeerConnection.m +284 -128
  12. package/ios/RCTWebRTC/WebRTCModule+Transceivers.m +216 -0
  13. package/ios/RCTWebRTC/WebRTCModule.h +15 -4
  14. package/ios/RCTWebRTC/WebRTCModule.m +26 -6
  15. package/lib/commonjs/EventEmitter.js +24 -0
  16. package/lib/commonjs/EventEmitter.js.map +1 -1
  17. package/lib/commonjs/Logger.js +65 -0
  18. package/lib/commonjs/Logger.js.map +1 -0
  19. package/lib/commonjs/MediaStream.js +1 -1
  20. package/lib/commonjs/MediaStream.js.map +1 -1
  21. package/lib/commonjs/MediaStreamTrack.js +4 -2
  22. package/lib/commonjs/MediaStreamTrack.js.map +1 -1
  23. package/lib/commonjs/Permissions.js +1 -1
  24. package/lib/commonjs/Permissions.js.map +1 -1
  25. package/lib/commonjs/RTCDataChannel.js.map +1 -1
  26. package/lib/commonjs/RTCErrorEvent.js +33 -0
  27. package/lib/commonjs/RTCErrorEvent.js.map +1 -0
  28. package/lib/commonjs/RTCPeerConnection.js +354 -103
  29. package/lib/commonjs/RTCPeerConnection.js.map +1 -1
  30. package/lib/commonjs/RTCRtcpParameters.js +24 -0
  31. package/lib/commonjs/RTCRtcpParameters.js.map +1 -0
  32. package/lib/commonjs/RTCRtpCapabilities.js +79 -0
  33. package/lib/commonjs/RTCRtpCapabilities.js.map +1 -0
  34. package/lib/commonjs/RTCRtpCodecCapability.js +25 -0
  35. package/lib/commonjs/RTCRtpCodecCapability.js.map +1 -0
  36. package/lib/commonjs/RTCRtpCodecParameters.js +33 -0
  37. package/lib/commonjs/RTCRtpCodecParameters.js.map +1 -0
  38. package/lib/commonjs/RTCRtpEncodingParameters.js +81 -0
  39. package/lib/commonjs/RTCRtpEncodingParameters.js.map +1 -0
  40. package/lib/commonjs/RTCRtpHeaderExtension.js +27 -0
  41. package/lib/commonjs/RTCRtpHeaderExtension.js.map +1 -0
  42. package/lib/commonjs/RTCRtpParameters.js +26 -0
  43. package/lib/commonjs/RTCRtpParameters.js.map +1 -0
  44. package/lib/commonjs/RTCRtpReceiveParameters.js +20 -0
  45. package/lib/commonjs/RTCRtpReceiveParameters.js.map +1 -0
  46. package/lib/commonjs/RTCRtpReceiver.js +51 -0
  47. package/lib/commonjs/RTCRtpReceiver.js.map +1 -0
  48. package/lib/commonjs/RTCRtpSendParameters.js +60 -0
  49. package/lib/commonjs/RTCRtpSendParameters.js.map +1 -0
  50. package/lib/commonjs/RTCRtpSender.js +85 -0
  51. package/lib/commonjs/RTCRtpSender.js.map +1 -0
  52. package/lib/commonjs/RTCRtpTransceiver.js +141 -0
  53. package/lib/commonjs/RTCRtpTransceiver.js.map +1 -0
  54. package/lib/commonjs/RTCSessionDescription.js.map +1 -1
  55. package/lib/commonjs/RTCTrackEvent.js +32 -0
  56. package/lib/commonjs/RTCTrackEvent.js.map +1 -0
  57. package/lib/commonjs/RTCUtil.js +20 -37
  58. package/lib/commonjs/RTCUtil.js.map +1 -1
  59. package/lib/commonjs/getDisplayMedia.js.map +1 -1
  60. package/lib/commonjs/getUserMedia.js.map +1 -1
  61. package/lib/commonjs/index.js +127 -3
  62. package/lib/commonjs/index.js.map +1 -1
  63. package/lib/module/EventEmitter.js +21 -0
  64. package/lib/module/EventEmitter.js.map +1 -1
  65. package/lib/module/Logger.js +53 -0
  66. package/lib/module/Logger.js.map +1 -0
  67. package/lib/module/MediaStream.js +1 -1
  68. package/lib/module/MediaStream.js.map +1 -1
  69. package/lib/module/MediaStreamTrack.js +4 -2
  70. package/lib/module/MediaStreamTrack.js.map +1 -1
  71. package/lib/module/Permissions.js +1 -1
  72. package/lib/module/Permissions.js.map +1 -1
  73. package/lib/module/RTCDataChannel.js.map +1 -1
  74. package/lib/module/RTCErrorEvent.js +22 -0
  75. package/lib/module/RTCErrorEvent.js.map +1 -0
  76. package/lib/module/RTCPeerConnection.js +348 -103
  77. package/lib/module/RTCPeerConnection.js.map +1 -1
  78. package/lib/module/RTCRtcpParameters.js +15 -0
  79. package/lib/module/RTCRtcpParameters.js.map +1 -0
  80. package/lib/module/RTCRtpCapabilities.js +63 -0
  81. package/lib/module/RTCRtpCapabilities.js.map +1 -0
  82. package/lib/module/RTCRtpCodecCapability.js +16 -0
  83. package/lib/module/RTCRtpCodecCapability.js.map +1 -0
  84. package/lib/module/RTCRtpCodecParameters.js +24 -0
  85. package/lib/module/RTCRtpCodecParameters.js.map +1 -0
  86. package/lib/module/RTCRtpEncodingParameters.js +72 -0
  87. package/lib/module/RTCRtpEncodingParameters.js.map +1 -0
  88. package/lib/module/RTCRtpHeaderExtension.js +18 -0
  89. package/lib/module/RTCRtpHeaderExtension.js.map +1 -0
  90. package/lib/module/RTCRtpParameters.js +17 -0
  91. package/lib/module/RTCRtpParameters.js.map +1 -0
  92. package/lib/module/RTCRtpReceiveParameters.js +8 -0
  93. package/lib/module/RTCRtpReceiveParameters.js.map +1 -0
  94. package/lib/module/RTCRtpReceiver.js +39 -0
  95. package/lib/module/RTCRtpReceiver.js.map +1 -0
  96. package/lib/module/RTCRtpSendParameters.js +49 -0
  97. package/lib/module/RTCRtpSendParameters.js.map +1 -0
  98. package/lib/module/RTCRtpSender.js +70 -0
  99. package/lib/module/RTCRtpSender.js.map +1 -0
  100. package/lib/module/RTCRtpTransceiver.js +125 -0
  101. package/lib/module/RTCRtpTransceiver.js.map +1 -0
  102. package/lib/module/RTCSessionDescription.js.map +1 -1
  103. package/lib/module/RTCTrackEvent.js +23 -0
  104. package/lib/module/RTCTrackEvent.js.map +1 -0
  105. package/lib/module/RTCUtil.js +18 -36
  106. package/lib/module/RTCUtil.js.map +1 -1
  107. package/lib/module/getDisplayMedia.js.map +1 -1
  108. package/lib/module/getUserMedia.js.map +1 -1
  109. package/lib/module/index.js +35 -4
  110. package/lib/module/index.js.map +1 -1
  111. package/lib/typescript/EventEmitter.d.ts +3 -0
  112. package/lib/typescript/Logger.d.ts +13 -0
  113. package/lib/typescript/MediaDevices.d.ts +2 -2
  114. package/lib/typescript/MediaStream.d.ts +6 -6
  115. package/lib/typescript/MediaStreamTrack.d.ts +10 -9
  116. package/lib/typescript/RTCDataChannel.d.ts +4 -2
  117. package/lib/typescript/RTCErrorEvent.d.ts +12 -0
  118. package/lib/typescript/RTCPeerConnection.d.ts +42 -11
  119. package/lib/typescript/RTCRtcpParameters.d.ts +8 -0
  120. package/lib/typescript/RTCRtpCapabilities.d.ts +19 -0
  121. package/lib/typescript/RTCRtpCodecCapability.d.ts +7 -0
  122. package/lib/typescript/RTCRtpCodecParameters.d.ts +14 -0
  123. package/lib/typescript/RTCRtpEncodingParameters.d.ts +21 -0
  124. package/lib/typescript/RTCRtpHeaderExtension.d.ts +10 -0
  125. package/lib/typescript/RTCRtpParameters.d.ts +14 -0
  126. package/lib/typescript/RTCRtpReceiveParameters.d.ts +4 -0
  127. package/lib/typescript/RTCRtpReceiver.d.ts +15 -0
  128. package/lib/typescript/RTCRtpSendParameters.d.ts +17 -0
  129. package/lib/typescript/RTCRtpSender.d.ts +21 -0
  130. package/lib/typescript/RTCRtpTransceiver.d.ts +35 -0
  131. package/lib/typescript/RTCTrackEvent.d.ts +15 -0
  132. package/lib/typescript/RTCUtil.d.ts +5 -9
  133. package/lib/typescript/getDisplayMedia.d.ts +2 -1
  134. package/lib/typescript/getUserMedia.d.ts +2 -1
  135. package/lib/typescript/index.d.ts +16 -3
  136. package/package.json +6 -4
  137. package/react-native-webrtc.podspec +1 -1
  138. package/src/EventEmitter.ts +21 -1
  139. package/src/Logger.ts +49 -0
  140. package/src/MediaStream.ts +11 -11
  141. package/src/MediaStreamTrack.ts +14 -13
  142. package/src/Permissions.ts +1 -1
  143. package/src/RTCDataChannel.ts +11 -8
  144. package/src/RTCErrorEvent.ts +21 -0
  145. package/src/RTCPeerConnection.ts +400 -158
  146. package/src/RTCRtcpParameters.ts +14 -0
  147. package/src/RTCRtpCapabilities.ts +54 -0
  148. package/src/RTCRtpCodecCapability.ts +13 -0
  149. package/src/RTCRtpCodecParameters.ts +23 -0
  150. package/src/RTCRtpEncodingParameters.ts +67 -0
  151. package/src/RTCRtpHeaderExtension.ts +18 -0
  152. package/src/RTCRtpParameters.ts +21 -0
  153. package/src/RTCRtpReceiveParameters.ts +7 -0
  154. package/src/RTCRtpReceiver.ts +35 -0
  155. package/src/RTCRtpSendParameters.ts +51 -0
  156. package/src/RTCRtpSender.ts +72 -0
  157. package/src/RTCRtpTransceiver.ts +125 -0
  158. package/src/RTCSessionDescription.ts +3 -3
  159. package/src/RTCTrackEvent.ts +21 -0
  160. package/src/RTCUtil.ts +20 -40
  161. package/src/getDisplayMedia.ts +1 -1
  162. package/src/getUserMedia.ts +2 -2
  163. package/src/index.ts +51 -6
  164. package/tools/build-webrtc.py +32 -33
  165. package/tools/downloadBitcode.sh +2 -12
  166. package/tools/downloadWebRTC.js +21 -12
@@ -1,19 +1,26 @@
1
1
 
2
- import { defineCustomEventTarget } from 'event-target-shim';
2
+ import { defineCustomEventTarget, Event } from 'event-target-shim';
3
3
  import { NativeModules } from 'react-native';
4
4
 
5
+ import Logger from './Logger';
5
6
  import MediaStream from './MediaStream';
6
- import MediaStreamEvent from './MediaStreamEvent';
7
- import MediaStreamTrackEvent from './MediaStreamTrackEvent';
7
+ import MediaStreamTrack from './MediaStreamTrack';
8
+ import RTCRtpTransceiver from './RTCRtpTransceiver';
8
9
  import RTCDataChannel from './RTCDataChannel';
9
10
  import RTCDataChannelEvent from './RTCDataChannelEvent';
11
+ import RTCTrackEvent from './RTCTrackEvent';
10
12
  import RTCSessionDescription from './RTCSessionDescription';
11
13
  import RTCIceCandidate from './RTCIceCandidate';
12
14
  import RTCIceCandidateEvent from './RTCIceCandidateEvent';
15
+ import RTCErrorEvent from './RTCErrorEvent';
13
16
  import RTCEvent from './RTCEvent';
14
17
  import * as RTCUtil from './RTCUtil';
15
- import EventEmitter from './EventEmitter';
18
+ import EventEmitter, { addListener, removeListener } from './EventEmitter';
19
+ import RTCRtpReceiver from './RTCRtpReceiver';
20
+ import RTCRtpSender from './RTCRtpSender';
21
+ import RTCRtpSendParameters from './RTCRtpSendParameters';
16
22
 
23
+ const log = new Logger('pc');
17
24
  const { WebRTCModule } = NativeModules;
18
25
 
19
26
  type RTCSignalingState =
@@ -48,8 +55,8 @@ const PEER_CONNECTION_EVENTS = [
48
55
  'negotiationneeded',
49
56
  'signalingstatechange',
50
57
  'datachannel',
51
- 'addstream',
52
- 'removestream'
58
+ 'track',
59
+ 'error'
53
60
  ];
54
61
 
55
62
  let nextPeerConnectionId = 0;
@@ -64,60 +71,58 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
64
71
  iceConnectionState: RTCIceConnectionState = 'new';
65
72
 
66
73
  _peerConnectionId: number;
67
- _localStreams: Array<MediaStream> = [];
68
- _remoteStreams: Array<MediaStream> = [];
69
- _subscriptions: Array<any> = [];
74
+ _subscriptions: any[] = [];
75
+ _transceivers: { order: number, transceiver: RTCRtpTransceiver }[] = [];
76
+ _remoteStreams: Map<string, MediaStream> = new Map<string, MediaStream>();
70
77
 
71
78
  constructor(configuration) {
72
79
  super();
73
80
  this._peerConnectionId = nextPeerConnectionId++;
74
81
  WebRTCModule.peerConnectionInit(configuration, this._peerConnectionId);
75
82
  this._registerEvents();
76
- }
77
-
78
- addStream(stream: MediaStream) {
79
- const index = this._localStreams.indexOf(stream);
80
- if (index !== -1) {
81
- return;
82
- }
83
- WebRTCModule.peerConnectionAddStream(stream._reactTag, this._peerConnectionId);
84
- this._localStreams.push(stream);
85
- }
86
83
 
87
- removeStream(stream: MediaStream) {
88
- const index = this._localStreams.indexOf(stream);
89
- if (index === -1) {
90
- return;
91
- }
92
- this._localStreams.splice(index, 1);
93
- WebRTCModule.peerConnectionRemoveStream(stream._reactTag, this._peerConnectionId);
84
+ log.debug(`${this._peerConnectionId} ctor`);
94
85
  }
95
86
 
96
87
  createOffer(options) {
88
+ log.debug(`${this._peerConnectionId} createOffer`);
89
+
97
90
  return new Promise((resolve, reject) => {
98
91
  WebRTCModule.peerConnectionCreateOffer(
99
92
  this._peerConnectionId,
100
- RTCUtil.normalizeOfferAnswerOptions(options),
93
+ RTCUtil.normalizeOfferOptions(options),
101
94
  (successful, data) => {
102
95
  if (successful) {
103
- resolve(data);
96
+ log.debug(`${this._peerConnectionId} createOffer OK`);
97
+
98
+ this._updateTransceivers(data.transceiversInfo);
99
+ resolve(data.sdpInfo);
104
100
  } else {
105
- reject(data); // TODO: convert to NavigatorUserMediaError
101
+ log.debug(`${this._peerConnectionId} createOffer ERROR`);
102
+
103
+ reject(data);
106
104
  }
107
105
  }
108
106
  );
109
107
  });
110
108
  }
111
109
 
112
- createAnswer(options = {}) {
110
+ createAnswer() {
111
+ log.debug(`${this._peerConnectionId} createAnswer`);
112
+
113
113
  return new Promise((resolve, reject) => {
114
114
  WebRTCModule.peerConnectionCreateAnswer(
115
115
  this._peerConnectionId,
116
- RTCUtil.normalizeOfferAnswerOptions(options),
116
+ {},
117
117
  (successful, data) => {
118
118
  if (successful) {
119
- resolve(data);
119
+ log.debug(`${this._peerConnectionId} createAnswer OK`);
120
+
121
+ this._updateTransceivers(data.transceiversInfo);
122
+ resolve(data.sdpInfo);
120
123
  } else {
124
+ log.debug(`${this._peerConnectionId} createAnswer ERROR`);
125
+
121
126
  reject(data);
122
127
  }
123
128
  }
@@ -125,29 +130,39 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
125
130
  });
126
131
  }
127
132
 
128
- setConfiguration(configuration) {
133
+ setConfiguration(configuration): void {
129
134
  WebRTCModule.peerConnectionSetConfiguration(configuration, this._peerConnectionId);
130
135
  }
131
136
 
132
137
  async setLocalDescription(sessionDescription?: RTCSessionDescription): Promise<void> {
138
+ log.debug(`${this._peerConnectionId} setLocalDescription`);
139
+
133
140
  const desc = sessionDescription
134
141
  ? sessionDescription.toJSON
135
142
  ? sessionDescription.toJSON()
136
143
  : sessionDescription
137
144
  : null;
138
- const newSdp = await WebRTCModule.peerConnectionSetLocalDescription(this._peerConnectionId, desc);
145
+ const { sdpInfo, transceiversInfo } = await WebRTCModule.peerConnectionSetLocalDescription(this._peerConnectionId, desc);
146
+
147
+ this.localDescription = new RTCSessionDescription(sdpInfo);
148
+ this._updateTransceivers(transceiversInfo);
139
149
 
140
- this.localDescription = new RTCSessionDescription(newSdp);
150
+ log.debug(`${this._peerConnectionId} setLocalDescription OK`);
141
151
  }
142
152
 
143
153
  setRemoteDescription(sessionDescription: RTCSessionDescription): Promise<void> {
154
+ log.debug(`${this._peerConnectionId} setRemoteDescription`);
155
+
144
156
  return new Promise((resolve, reject) => {
145
157
  WebRTCModule.peerConnectionSetRemoteDescription(
146
158
  sessionDescription.toJSON ? sessionDescription.toJSON() : sessionDescription,
147
159
  this._peerConnectionId,
148
160
  (successful, data) => {
149
161
  if (successful) {
150
- this.remoteDescription = new RTCSessionDescription(data);
162
+ log.debug(`${this._peerConnectionId} setRemoteDescription OK`);
163
+
164
+ this.remoteDescription = new RTCSessionDescription(data.sdpInfo);
165
+ this._updateTransceivers(data.transceiversInfo);
151
166
  resolve();
152
167
  } else {
153
168
  reject(data);
@@ -158,6 +173,8 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
158
173
  }
159
174
 
160
175
  async addIceCandidate(candidate): Promise<void> {
176
+ log.debug(`${this._peerConnectionId} addIceCandidate`);
177
+
161
178
  if (!candidate || !candidate.candidate) {
162
179
  // XXX end-of cantidates is not implemented: https://bugs.chromium.org/p/webrtc/issues/detail?id=9218
163
180
  return;
@@ -171,7 +188,113 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
171
188
  this.remoteDescription = new RTCSessionDescription(newSdp);
172
189
  }
173
190
 
191
+ /**
192
+ * @brief Adds a new track to the {@link RTCPeerConnection},
193
+ * and indicates that it is contained in the specified {@link MediaStream} array.
194
+ * This method has to be synchronous as the W3C API expects a track to be return
195
+ * @param {MediaStreamTrack} track The track to be added
196
+ * @param {MediaStream[]} streams An array of streams the track needs to be added to
197
+ * https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-addtrack
198
+ */
199
+ addTrack(track: MediaStreamTrack, streams: MediaStream[] = []): RTCRtpSender {
200
+ log.debug(`${this._peerConnectionId} addTrack`);
201
+
202
+ if (this.connectionState === 'closed') throw new Error("Peer Connection is closed");
203
+ if (this._trackExists(track)) throw new Error("Track already exists in a sender");
204
+
205
+ const streamIds = streams.map((s) => s.id);
206
+ const result = WebRTCModule.peerConnectionAddTrack(this._peerConnectionId, track.id, { streamIds });
207
+ if (result == null) throw new Error("Could not add sender");
208
+ const { transceiverOrder, transceiver, sender } = result;
209
+
210
+ // According to the W3C docs, the sender could have been reused, and
211
+ // so we check if that is the case, and update accordingly.
212
+ const [existingSender] = this
213
+ .getSenders()
214
+ .filter((s) => s.id === sender.id);
215
+
216
+ if (existingSender) {
217
+ // Update sender
218
+ existingSender._track = track;
219
+
220
+ // Update the corresponding transceiver as well
221
+ const [existingTransceiver] = this
222
+ .getTransceivers()
223
+ .filter((t) => t.sender.id === existingSender.id);
224
+ existingTransceiver._direction = transceiver.direction;
225
+ existingTransceiver._currentDirection = transceiver.currentDirection;
226
+ return existingSender;
227
+ }
228
+
229
+ // This is a new transceiver, should create a transceiver for it and add it
230
+ const newSender = new RTCRtpSender({ ...transceiver.sender, track });
231
+ const newTransceiver = new RTCRtpTransceiver({
232
+ ...transceiver,
233
+ sender: newSender,
234
+ receiver: new RTCRtpReceiver(transceiver.receiver),
235
+ });
236
+
237
+ this._insertTransceiverSorted(transceiverOrder, newTransceiver);
238
+
239
+ return newSender;
240
+ }
241
+
242
+ addTransceiver(source: 'audio' | 'video' | MediaStreamTrack, init): RTCRtpTransceiver {
243
+ log.debug(`${this._peerConnectionId} addTransceiver`);
244
+
245
+ let src = {};
246
+ if (source === 'audio') {
247
+ src = { type: 'audio' };
248
+ } else if (source === 'video') {
249
+ src = { type: 'video' };
250
+ } else {
251
+ src = { trackId: source.id };
252
+ }
253
+ // Extract the stream ids
254
+ if (init && init.streams) {
255
+ init.streamIds = init.streams.map((stream) => {
256
+ return stream.id;
257
+ });
258
+ }
259
+
260
+ const result = WebRTCModule.peerConnectionAddTransceiver(this._peerConnectionId, { ...src, init: { ...init } });
261
+ if (result == null) {
262
+ console.log("Error adding transceiver");
263
+ throw new Error("Transceiver could not be added");
264
+ }
265
+ const sender = new RTCRtpSender(result.transceiver.sender);
266
+ if (source instanceof MediaStreamTrack) {
267
+ sender._track = source;
268
+ }
269
+ const receiver = new RTCRtpReceiver(result.transceiver.receiver);
270
+ const transceiver = new RTCRtpTransceiver({
271
+ ...result.transceiver,
272
+ sender,
273
+ receiver
274
+ });
275
+ this._insertTransceiverSorted(result.transceiverOrder, transceiver);
276
+ return transceiver;
277
+ }
278
+
279
+ removeTrack(sender: RTCRtpSender) {
280
+ log.debug(`${this._peerConnectionId} removeTrack`);
281
+
282
+ if (this._peerConnectionId !== sender._peerConnectionId)
283
+ throw new Error("Sender does not belong to this peer connection");
284
+ if (this.connectionState === 'closed') throw new Error("Peer Connection is closed");
285
+
286
+ const existingSender = this
287
+ .getSenders()
288
+ .find((s) => s === sender);
289
+ if (!existingSender) throw new Error("Sender does not exist");
290
+ if (existingSender.track === null) return;
291
+
292
+ WebRTCModule.peerConnectionRemoveTrack(this._peerConnectionId, sender.id);
293
+ }
294
+
174
295
  getStats() {
296
+ log.debug(`${this._peerConnectionId} getStats`);
297
+
175
298
  return WebRTCModule.peerConnectionGetStats(this._peerConnectionId).then(data => {
176
299
  /* On both Android and iOS it is faster to construct a single
177
300
  JSON string representing the Map of StatsReports and have it
@@ -188,144 +311,222 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
188
311
  });
189
312
  }
190
313
 
191
- getLocalStreams() {
192
- return this._localStreams.slice();
314
+ getTransceivers(): RTCRtpTransceiver[] {
315
+ return this._transceivers.map(e => e.transceiver);
193
316
  }
194
317
 
195
- getRemoteStreams() {
196
- return this._remoteStreams.slice();
318
+ getSenders(): RTCRtpSender[] {
319
+ return this._transceivers.map(e => e.transceiver.sender);
197
320
  }
198
321
 
199
- close() {
200
- WebRTCModule.peerConnectionClose(this._peerConnectionId);
322
+ getReceivers(): RTCRtpReceiver[] {
323
+ return this._transceivers.map(e => e.transceiver.receiver);
201
324
  }
202
325
 
203
- restartIce() {
204
- WebRTCModule.peerConnectionRestartIce(this._peerConnectionId);
326
+ close(): void {
327
+ log.debug(`${this._peerConnectionId} close`);
328
+
329
+ // According to the W3C spec: https://w3c.github.io/webrtc-pc/#rtcpeerconnection-interface
330
+ // transceivers have to be stopped
331
+ this._transceivers.forEach(({ transceiver })=> {
332
+ transceiver.stop();
333
+ })
334
+ WebRTCModule.peerConnectionClose(this._peerConnectionId);
205
335
  }
206
336
 
207
- _unregisterEvents(): void {
208
- this._subscriptions.forEach(e => e.remove());
209
- this._subscriptions = [];
337
+ restartIce(): void {
338
+ WebRTCModule.peerConnectionRestartIce(this._peerConnectionId);
210
339
  }
211
340
 
212
341
  _registerEvents(): void {
213
- this._subscriptions = [
214
- EventEmitter.addListener('peerConnectionOnRenegotiationNeeded', ev => {
215
- if (ev.id !== this._peerConnectionId) {
216
- return;
217
- }
218
- // @ts-ignore
219
- this.dispatchEvent(new RTCEvent('negotiationneeded'));
220
- }),
221
- EventEmitter.addListener('peerConnectionIceConnectionChanged', ev => {
222
- if (ev.id !== this._peerConnectionId) {
223
- return;
224
- }
225
- this.iceConnectionState = ev.iceConnectionState;
226
- // @ts-ignore
227
- this.dispatchEvent(new RTCEvent('iceconnectionstatechange'));
228
- if (ev.iceConnectionState === 'closed') {
229
- // This PeerConnection is done, clean up event handlers.
230
- this._unregisterEvents();
231
- }
232
- }),
233
- EventEmitter.addListener('peerConnectionStateChanged', ev => {
234
- if (ev.id !== this._peerConnectionId) {
235
- return;
236
- }
237
- this.connectionState = ev.connectionState;
238
- // @ts-ignore
239
- this.dispatchEvent(new RTCEvent('connectionstatechange'));
240
- if (ev.connectionState === 'closed') {
241
- // This PeerConnection is done, clean up event handlers.
242
- this._unregisterEvents();
243
- }
244
- }),
245
- EventEmitter.addListener('peerConnectionSignalingStateChanged', ev => {
246
- if (ev.id !== this._peerConnectionId) {
247
- return;
248
- }
249
- this.signalingState = ev.signalingState;
250
- // @ts-ignore
251
- this.dispatchEvent(new RTCEvent('signalingstatechange'));
252
- }),
253
- EventEmitter.addListener('peerConnectionAddedStream', ev => {
254
- if (ev.id !== this._peerConnectionId) {
255
- return;
256
- }
257
- const stream = new MediaStream(ev);
258
- this._remoteStreams.push(stream);
259
- this.remoteDescription = new RTCSessionDescription(ev.sdp);
260
- // @ts-ignore
261
- this.dispatchEvent(new MediaStreamEvent('addstream', { stream }));
262
- }),
263
- EventEmitter.addListener('peerConnectionRemovedStream', ev => {
264
- if (ev.id !== this._peerConnectionId) {
265
- return;
266
- }
267
- const stream = this._remoteStreams.find(s => s._reactTag === ev.streamId);
268
- if (stream) {
269
- const index = this._remoteStreams.indexOf(stream);
270
- if (index !== -1) {
271
- this._remoteStreams.splice(index, 1);
272
- }
273
- }
274
- this.remoteDescription = new RTCSessionDescription(ev.sdp);
275
- // @ts-ignore
276
- this.dispatchEvent(new MediaStreamEvent('removestream', { stream }));
277
- }),
278
- EventEmitter.addListener('mediaStreamTrackMuteChanged', ev => {
279
- if (ev.peerConnectionId !== this._peerConnectionId) {
280
- return;
281
- }
282
- let track;
283
- for (const stream of this._remoteStreams) {
284
- const t = stream._tracks.find(track => track.id === ev.trackId);
285
- if (t) {
286
- track = t;
287
- break;
288
- }
289
- }
290
- if (track) {
291
- track._muted = ev.muted;
292
- const eventName = ev.muted ? 'mute' : 'unmute';
293
- track.dispatchEvent(new MediaStreamTrackEvent(eventName, { track }));
342
+ addListener(this, 'peerConnectionOnRenegotiationNeeded', ev => {
343
+ if (ev.id !== this._peerConnectionId) {
344
+ return;
345
+ }
346
+ // @ts-ignore
347
+ this.dispatchEvent(new RTCEvent('negotiationneeded'));
348
+ });
349
+ addListener(this, 'peerConnectionIceConnectionChanged', ev => {
350
+ if (ev.id !== this._peerConnectionId) {
351
+ return;
352
+ }
353
+ this.iceConnectionState = ev.iceConnectionState;
354
+ if (ev.iceConnectionState === 'closed') {
355
+ // This PeerConnection is done, clean up event handlers.
356
+ removeListener(this);
357
+ }
358
+ // @ts-ignore
359
+ this.dispatchEvent(new RTCEvent('iceconnectionstatechange'));
360
+ });
361
+ addListener(this, 'peerConnectionStateChanged', ev => {
362
+ if (ev.id !== this._peerConnectionId) {
363
+ return;
364
+ }
365
+ this.connectionState = ev.connectionState;
366
+ if (ev.connectionState === 'closed') {
367
+ // This PeerConnection is done, clean up event handlers.
368
+ removeListener(this);
369
+ }
370
+ // @ts-ignore
371
+ this.dispatchEvent(new RTCEvent('connectionstatechange'));
372
+ });
373
+ addListener(this, 'peerConnectionSignalingStateChanged', ev => {
374
+ if (ev.id !== this._peerConnectionId) {
375
+ return;
376
+ }
377
+ this.signalingState = ev.signalingState;
378
+ // @ts-ignore
379
+ this.dispatchEvent(new RTCEvent('signalingstatechange'));
380
+ })
381
+ addListener(this, 'peerConnectionOnTrack', ev => {
382
+ if (ev.id !== this._peerConnectionId) {
383
+ return;
384
+ }
385
+
386
+ log.debug(`${this._peerConnectionId} ontrack`);
387
+
388
+ const track = new MediaStreamTrack(ev.receiver.track);
389
+ let transceiver;
390
+
391
+ // Make sure transceivers are stored in timestamp order. Also, we have to make
392
+ // sure we do not add a transceiver if it exists.
393
+ // sure we do not add a transceiver if it exists.
394
+ // sure we do not add a transceiver if it exists.
395
+ let [{ transceiver: oldTransceiver } = { transceiver: null }] = this._transceivers.filter(({ transceiver }) => {
396
+ return transceiver.id === ev.transceiver.id;
397
+ });
398
+
399
+ if (!oldTransceiver) {
400
+ // Creating objects out of the event data.
401
+ const receiver = new RTCRtpReceiver({ ...ev.receiver, track });
402
+
403
+ transceiver = new RTCRtpTransceiver({ ...ev.transceiver, receiver });
404
+ this._insertTransceiverSorted(ev.transceiverOrder, transceiver);
405
+ } else {
406
+ transceiver = oldTransceiver;
407
+ transceiver._receiver._track = track;
408
+ transceiver._mid = ev.transceiver.mid;
409
+ transceiver._currentDirection = ev.transceiver.currentDirection;
410
+ transceiver._direction = ev.transceiver.direction;
411
+ }
412
+
413
+ // Get the stream object from the event. Create if necessary.
414
+ const streams = ev.streams.map(streamInfo => {
415
+ // Here we are making sure that we don't create stream objects that already exist
416
+ // So that event listeners do get the same object if it has been created before.
417
+ if (!this._remoteStreams.has(streamInfo.streamId)) {
418
+ const stream = new MediaStream({
419
+ streamId: streamInfo.streamId,
420
+ streamReactTag: streamInfo.streamReactTag,
421
+ tracks: []
422
+ });
423
+ this._remoteStreams.set(streamInfo.streamId, stream);
294
424
  }
295
- }),
296
- EventEmitter.addListener('peerConnectionGotICECandidate', ev => {
297
- if (ev.id !== this._peerConnectionId) {
298
- return;
425
+ const stream = this._remoteStreams.get(streamInfo.streamId);
426
+ stream?._tracks.push(track);
427
+ return stream;
428
+ });
429
+
430
+ const eventData = {
431
+ streams,
432
+ transceiver,
433
+ track,
434
+ receiver: transceiver.receiver
435
+ };
436
+
437
+ // @ts-ignore
438
+ this.dispatchEvent(new RTCTrackEvent('track', eventData));
439
+ });
440
+
441
+ addListener(this, 'peerConnectionOnRemoveTrack', ev => {
442
+ if (ev.peerConnectionId !== this._peerConnectionId) {
443
+ return;
444
+ }
445
+
446
+ log.debug(`${this._peerConnectionId} onremovetrack`);
447
+
448
+ // Based on the W3C specs https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-removetrack,
449
+ // we need to remove the track from any media streams
450
+ // that were previously passed to the `track` event.
451
+ for (const stream of this._remoteStreams.values()) {
452
+ const trackIdx = stream._tracks.findIndex(t => t.id === ev.trackId);
453
+ if (trackIdx !== -1) {
454
+ stream._tracks.splice(trackIdx, 1);
299
455
  }
456
+ }
457
+ });
458
+
459
+ addListener(this, 'peerConnectionOnRemoveTrackSuccessful', ev => {
460
+ if (ev.peerConnectionId !== this._peerConnectionId) {
461
+ return;
462
+ }
463
+ const [existingSender] = this
464
+ .getSenders()
465
+ .filter((s) => s.id === ev.senderId);
466
+
467
+ const oldTrack = existingSender._track;
468
+
469
+ if (oldTrack) {
470
+ oldTrack._muted = true;
471
+ }
472
+
473
+ existingSender._track = null;
474
+
475
+ const [existingTransceiver] = this
476
+ .getTransceivers()
477
+ .filter((t) => t.sender.id === existingSender.id);
478
+ existingTransceiver._direction = existingTransceiver.direction === 'sendrecv' ? 'recvonly' : 'inactive';
479
+ });
480
+
481
+ addListener(this, 'peerConnectionGotICECandidate', ev => {
482
+ if (ev.id !== this._peerConnectionId) {
483
+ return;
484
+ }
485
+ this.localDescription = new RTCSessionDescription(ev.sdp);
486
+ const candidate = new RTCIceCandidate(ev.candidate);
487
+ // @ts-ignore
488
+ this.dispatchEvent(new RTCIceCandidateEvent('icecandidate', { candidate }));
489
+ });
490
+
491
+ addListener(this, 'peerConnectionIceGatheringChanged', ev => {
492
+ if (ev.id !== this._peerConnectionId) {
493
+ return;
494
+ }
495
+ this.iceGatheringState = ev.iceGatheringState;
496
+
497
+ if (this.iceGatheringState === 'complete') {
300
498
  this.localDescription = new RTCSessionDescription(ev.sdp);
301
- const candidate = new RTCIceCandidate(ev.candidate);
302
499
  // @ts-ignore
303
- this.dispatchEvent(new RTCIceCandidateEvent('icecandidate', { candidate }));
304
- }),
305
- EventEmitter.addListener('peerConnectionIceGatheringChanged', ev => {
306
- if (ev.id !== this._peerConnectionId) {
307
- return;
308
- }
309
- this.iceGatheringState = ev.iceGatheringState;
500
+ this.dispatchEvent(new RTCIceCandidateEvent('icecandidate', { candidate: null }));
501
+ }
310
502
 
311
- if (this.iceGatheringState === 'complete') {
312
- this.localDescription = new RTCSessionDescription(ev.sdp);
313
- // @ts-ignore
314
- this.dispatchEvent(new RTCIceCandidateEvent('icecandidate', { candidate: null }));
315
- }
503
+ // @ts-ignore
504
+ this.dispatchEvent(new RTCEvent('icegatheringstatechange'));
505
+ });
316
506
 
317
- // @ts-ignore
318
- this.dispatchEvent(new RTCEvent('icegatheringstatechange'));
319
- }),
320
- EventEmitter.addListener('peerConnectionDidOpenDataChannel', ev => {
321
- if (ev.id !== this._peerConnectionId) {
322
- return;
323
- }
324
- const channel = new RTCDataChannel(ev.dataChannel);
325
- // @ts-ignore
326
- this.dispatchEvent(new RTCDataChannelEvent('datachannel', { channel }));
327
- })
328
- ];
507
+ addListener(this, 'peerConnectionDidOpenDataChannel', ev => {
508
+ if (ev.id !== this._peerConnectionId) {
509
+ return;
510
+ }
511
+ const channel = new RTCDataChannel(ev.dataChannel);
512
+ // @ts-ignore
513
+ this.dispatchEvent(new RTCDataChannelEvent('datachannel', { channel }));
514
+ });
515
+
516
+ // Since the current underlying architecture performs certain actions
517
+ // Asynchronously when the outer web API expects synchronous behaviour
518
+ // This is the only way to report error on operations for those who wish
519
+ // to handle them.
520
+ addListener(this, 'peerConnectionOnError', ev => {
521
+ if (ev.info.peerConnectionId !== this._peerConnectionId) {
522
+ return;
523
+ }
524
+
525
+ log.error(`onerror: ${JSON.stringify(ev)}`);
526
+
527
+ // @ts-ignore
528
+ this.dispatchEvent(new RTCErrorEvent('error', ev.func, ev.message));
529
+ });
329
530
  }
330
531
 
331
532
  /**
@@ -339,7 +540,7 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
339
540
  * values with which to initialize corresponding attributes of the new
340
541
  * instance such as id
341
542
  */
342
- createDataChannel(label: string, dataChannelDict?: RTCDataChannelInit) {
543
+ createDataChannel(label: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel {
343
544
  if (dataChannelDict && 'id' in dataChannelDict) {
344
545
  const id = dataChannelDict.id;
345
546
  if (typeof id !== 'number') {
@@ -355,4 +556,45 @@ export default class RTCPeerConnection extends defineCustomEventTarget(...PEER_C
355
556
 
356
557
  return new RTCDataChannel(channelInfo);
357
558
  }
559
+
560
+ /**
561
+ * Check whether a media stream track exists already in a sender.
562
+ * See https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-addtrack for more information
563
+ */
564
+ _trackExists(track: MediaStreamTrack): boolean {
565
+ const [sender] = this
566
+ .getSenders()
567
+ .filter(
568
+ (sender) => sender.track?.id === track.id
569
+ )
570
+ return sender? true : false;
571
+ }
572
+
573
+ /**
574
+ * updates transceivers after offer/answer updates if necessary
575
+ */
576
+ _updateTransceivers(transceiverUpdates) {
577
+ for (var update of transceiverUpdates) {
578
+ const [transceiver] = this
579
+ .getTransceivers()
580
+ .filter((t) => t.id === update.transceiverId);
581
+
582
+ if (!transceiver) continue;
583
+ transceiver._currentDirection = update.currentDirection;
584
+ transceiver._mid = update.mid;
585
+ transceiver._sender._rtpParameters = new RTCRtpSendParameters(update.senderRtpParameters);
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Inserts transceiver into the transceiver array in the order they are created (timestamp).
591
+ * @param order an index that refers to when it it was created relatively.
592
+ * @param transceiver the transceiver object to be inserted.
593
+ */
594
+ _insertTransceiverSorted(order: number, transceiver: RTCRtpTransceiver) {
595
+ this._transceivers.push({ order, transceiver });
596
+ this._transceivers.sort((a, b) => {
597
+ return a.order - b.order;
598
+ })
599
+ }
358
600
  }