forked from oney/RCTWebRTCDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
392 lines (354 loc) · 10.4 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
View,
TextInput,
ListView,
Platform,
} from 'react-native';
import io from 'socket.io-client';
const socket = io.connect('https://react-native-webrtc.herokuapp.com', {transports: ['websocket']});
import {
RTCPeerConnection,
RTCMediaStream,
RTCIceCandidate,
RTCSessionDescription,
RTCView,
MediaStreamTrack,
getUserMedia,
} from 'react-native-webrtc';
const configuration = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
const pcPeers = {};
let localStream;
function getLocalStream(isFront, callback) {
let videoSourceId;
// on android, you don't have to specify sourceId manually, just use facingMode
// uncomment it if you want to specify
if (Platform.OS === 'ios') {
MediaStreamTrack.getSources(sourceInfos => {
console.log("sourceInfos: ", sourceInfos);
for (const i = 0; i < sourceInfos.length; i++) {
const sourceInfo = sourceInfos[i];
if(sourceInfo.kind == "video" && sourceInfo.facing == (isFront ? "front" : "back")) {
videoSourceId = sourceInfo.id;
}
}
});
}
getUserMedia({
audio: true,
video: {
mandatory: {
minWidth: 640, // Provide your own width, height and frame rate here
minHeight: 360,
minFrameRate: 30,
},
facingMode: (isFront ? "user" : "environment"),
optional: (videoSourceId ? [{sourceId: videoSourceId}] : []),
}
}, function (stream) {
console.log('getUserMedia success', stream);
callback(stream);
}, logError);
}
function join(roomID) {
socket.emit('join', roomID, function(socketIds){
console.log('join', socketIds);
for (const i in socketIds) {
const socketId = socketIds[i];
createPC(socketId, true);
}
});
}
function createPC(socketId, isOffer) {
const pc = new RTCPeerConnection(configuration);
pcPeers[socketId] = pc;
pc.onicecandidate = function (event) {
console.log('onicecandidate', event.candidate);
if (event.candidate) {
socket.emit('exchange', {'to': socketId, 'candidate': event.candidate });
}
};
function createOffer() {
pc.createOffer(function(desc) {
console.log('createOffer', desc);
pc.setLocalDescription(desc, function () {
console.log('setLocalDescription', pc.localDescription);
socket.emit('exchange', {'to': socketId, 'sdp': pc.localDescription });
}, logError);
}, logError);
}
pc.onnegotiationneeded = function () {
console.log('onnegotiationneeded');
if (isOffer) {
createOffer();
}
}
pc.oniceconnectionstatechange = function(event) {
console.log('oniceconnectionstatechange', event.target.iceConnectionState);
if (event.target.iceConnectionState === 'completed') {
setTimeout(() => {
getStats();
}, 1000);
}
if (event.target.iceConnectionState === 'connected') {
createDataChannel();
}
};
pc.onsignalingstatechange = function(event) {
console.log('onsignalingstatechange', event.target.signalingState);
};
pc.onaddstream = function (event) {
console.log('onaddstream', event.stream);
container.setState({info: 'One peer join!'});
const remoteList = container.state.remoteList;
remoteList[socketId] = event.stream.toURL();
container.setState({ remoteList: remoteList });
};
pc.onremovestream = function (event) {
console.log('onremovestream', event.stream);
};
pc.addStream(localStream);
function createDataChannel() {
if (pc.textDataChannel) {
return;
}
const dataChannel = pc.createDataChannel("text");
dataChannel.onerror = function (error) {
console.log("dataChannel.onerror", error);
};
dataChannel.onmessage = function (event) {
console.log("dataChannel.onmessage:", event.data);
container.receiveTextData({user: socketId, message: event.data});
};
dataChannel.onopen = function () {
console.log('dataChannel.onopen');
container.setState({textRoomConnected: true});
};
dataChannel.onclose = function () {
console.log("dataChannel.onclose");
};
pc.textDataChannel = dataChannel;
}
return pc;
}
function exchange(data) {
const fromId = data.from;
let pc;
if (fromId in pcPeers) {
pc = pcPeers[fromId];
} else {
pc = createPC(fromId, false);
}
if (data.sdp) {
console.log('exchange sdp', data);
pc.setRemoteDescription(new RTCSessionDescription(data.sdp), function () {
if (pc.remoteDescription.type == "offer")
pc.createAnswer(function(desc) {
console.log('createAnswer', desc);
pc.setLocalDescription(desc, function () {
console.log('setLocalDescription', pc.localDescription);
socket.emit('exchange', {'to': fromId, 'sdp': pc.localDescription });
}, logError);
}, logError);
}, logError);
} else {
console.log('exchange candidate', data);
pc.addIceCandidate(new RTCIceCandidate(data.candidate));
}
}
function leave(socketId) {
console.log('leave', socketId);
const pc = pcPeers[socketId];
const viewIndex = pc.viewIndex;
pc.close();
delete pcPeers[socketId];
const remoteList = container.state.remoteList;
delete remoteList[socketId]
container.setState({ remoteList: remoteList });
container.setState({info: 'One peer leave!'});
}
socket.on('exchange', function(data){
exchange(data);
});
socket.on('leave', function(socketId){
leave(socketId);
});
socket.on('connect', function(data) {
console.log('connect');
getLocalStream(true, function(stream) {
localStream = stream;
container.setState({selfViewSrc: stream.toURL()});
container.setState({status: 'ready', info: 'Please enter or create room ID'});
});
});
function logError(error) {
console.log("logError", error);
}
function mapHash(hash, func) {
const array = [];
for (const key in hash) {
const obj = hash[key];
array.push(func(obj, key));
}
return array;
}
function getStats() {
const pc = pcPeers[Object.keys(pcPeers)[0]];
if (pc.getRemoteStreams()[0] && pc.getRemoteStreams()[0].getAudioTracks()[0]) {
const track = pc.getRemoteStreams()[0].getAudioTracks()[0];
console.log('track', track);
pc.getStats(track, function(report) {
console.log('getStats report', report);
}, logError);
}
}
let container;
const RCTWebRTCDemo = React.createClass({
getInitialState: function() {
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => true});
return {
info: 'Initializing',
status: 'init',
roomID: '',
isFront: true,
selfViewSrc: null,
remoteList: {},
textRoomConnected: false,
textRoomData: [],
textRoomValue: '',
};
},
componentDidMount: function() {
container = this;
},
_press(event) {
this.refs.roomID.blur();
this.setState({status: 'connect', info: 'Connecting'});
join(this.state.roomID);
},
_switchVideoType() {
const isFront = !this.state.isFront;
this.setState({isFront});
getLocalStream(isFront, function(stream) {
if (localStream) {
for (const id in pcPeers) {
const pc = pcPeers[id];
pc && pc.removeStream(localStream);
}
localStream.release();
}
localStream = stream;
container.setState({selfViewSrc: stream.toURL()});
for (const id in pcPeers) {
const pc = pcPeers[id];
pc && pc.addStream(localStream);
}
});
},
receiveTextData(data) {
const textRoomData = this.state.textRoomData.slice();
textRoomData.push(data);
this.setState({textRoomData, textRoomValue: ''});
},
_textRoomPress() {
if (!this.state.textRoomValue) {
return
}
const textRoomData = this.state.textRoomData.slice();
textRoomData.push({user: 'Me', message: this.state.textRoomValue});
for (const key in pcPeers) {
const pc = pcPeers[key];
pc.textDataChannel.send(this.state.textRoomValue);
}
this.setState({textRoomData, textRoomValue: ''});
},
_renderTextRoom() {
return (
<View style={styles.listViewContainer}>
<ListView
dataSource={this.ds.cloneWithRows(this.state.textRoomData)}
renderRow={rowData => <Text>{`${rowData.user}: ${rowData.message}`}</Text>}
/>
<TextInput
style={{width: 200, height: 30, borderColor: 'gray', borderWidth: 1}}
onChangeText={value => this.setState({textRoomValue: value})}
value={this.state.textRoomValue}
/>
<TouchableHighlight
onPress={this._textRoomPress}>
<Text>Send</Text>
</TouchableHighlight>
</View>
);
},
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
{this.state.info}
</Text>
{this.state.textRoomConnected && this._renderTextRoom()}
<View style={{flexDirection: 'row'}}>
<Text>
{this.state.isFront ? "Use front camera" : "Use back camera"}
</Text>
<TouchableHighlight
style={{borderWidth: 1, borderColor: 'black'}}
onPress={this._switchVideoType}>
<Text>Switch camera</Text>
</TouchableHighlight>
</View>
{ this.state.status == 'ready' ?
(<View>
<TextInput
ref='roomID'
autoCorrect={false}
style={{width: 200, height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({roomID: text})}
value={this.state.roomID}
/>
<TouchableHighlight
onPress={this._press}>
<Text>Enter room</Text>
</TouchableHighlight>
</View>) : null
}
<RTCView streamURL={this.state.selfViewSrc} style={styles.selfView}/>
{
mapHash(this.state.remoteList, function(remote, index) {
return <RTCView key={index} streamURL={remote} style={styles.remoteView}/>
})
}
</View>
);
}
});
const styles = StyleSheet.create({
selfView: {
width: 200,
height: 150,
},
remoteView: {
width: 200,
height: 150,
},
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
listViewContainer: {
height: 150,
},
});
AppRegistry.registerComponent('RCTWebRTCDemo', () => RCTWebRTCDemo);