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

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