forked from AravisProject/aravis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebrtc.html
241 lines (215 loc) · 6.72 KB
/
webrtc.html
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
<html>
<head>
<meta charset="utf-8"/>
<style>
.error { color: red; }
</style>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
</head>
<body>
<div><video id="video" autoplay playsinline>Your browser doesn't support video</video></div>
<div>State: <span id="state">unknown</span></div>
<div><textarea id="text" cols=40 rows=4></textarea></div>
<div>Id is <b id="id">unknown</b></div>
<br/>
<div>
<div>getUserMedia constraints being used:</div>
<div><textarea id="constraints" cols=40 rows=4></textarea></div>
</div>
</body>
</html>
<script>
// Set this to use a specific peer id instead of a random one
var id = "argos"
// Override with your own STUN servers if you want
var connect_attempts = 0;
var peer;
var out;
var ws_conn;
function handleIncomingError(error) {
setError("ERROR: " + error);
//resetState();
}
function setStatus(s) {
console.log(s);
// Don't set the state if it already contains an error
//if (!state.classList.contains('error'))
state.textContent = s;
}
function setError(text) {
console.error(text);
state.textContent = text;
state.classList.add('error');
}
// SDP offer received from peer, set remote description and create an answer
function onIncomingSDP(sdp) {
peer.setRemoteDescription(sdp).then(() => {
setStatus("Remote SDP set");
if (sdp.type != "offer")
return;
peer.createAnswer().then(onLocalDescription)
}).catch(setError);
}
// Local description was set, send it to peer
function onLocalDescription(desc) {
console.log("Got local description: " + JSON.stringify(desc));
peer.setLocalDescription(desc).then(function() {
setStatus("Sending SDP " + desc.type);
sdp = {'sdp': peer.localDescription}
ws_conn.send(JSON.stringify(sdp));
});
}
function generateOffer() {
peer.createOffer().then(onLocalDescription).catch(setError);
}
// ICE candidate received from peer, add it to the peer connection
function onServerMessage(event) {
console.log("Received " + event.data);
if (event.data == "HELLO") {
setStatus("Registered with server, waiting for call");
return;
}
if (event.data.startsWith("ERROR")) {
handleIncomingError(event.data);
return;
}
if (event.data.startsWith("OFFER_REQUEST")) {
// The peer wants us to set up and then send an offer
if (!peer)
createCall(null).then(generateOffer);
} else {
// Handle incoming JSON SDP and ICE messages
try {
msg = JSON.parse(event.data);
} catch (e) {
if (e instanceof SyntaxError)
handleIncomingError("Error parsing incoming JSON: " + event.data);
else
handleIncomingError("Unknown error parsing response: " + event.data);
return;
}
// Incoming JSON signals the beginning of a call
if (!peer)
createCall(msg);
if (msg.sdp != null)
onIncomingSDP(msg.sdp);
else if (msg.ice != null)
peer.addIceCandidate(new RTCIceCandidate(msg.ice)).catch(setError);
else
handleIncomingError("Unknown incoming JSON: " + msg);
}
}
function onServerClose(event) {
setStatus('Disconnected from server');
video.pause();
video.src = "";
video.load();
if (peer) {
peer.close();
peer = null;
}
// Reset after a second
window.setTimeout(websocketServerConnect, 1000);
}
function onServerError(event) {
setError("Unable to connect to server, did you add an exception for the certificate?")
// Retry after 3 seconds
window.setTimeout(websocketServerConnect, 3000);
}
window.onload = websocketServerConnect;
function websocketServerConnect() {
connect_attempts++;
if (connect_attempts > 3) {
//setError("Too many connection attempts, aborting. Refresh page to try again");
//return;
}
state.classList.remove('error');
state.textContent = '';
var ws_port;
ws_port = ws_port || '8443';
var ws_server;
if (window.location.protocol.startsWith ("file")) {
ws_server = ws_server || "127.0.0.1";
} else if (window.location.protocol.startsWith ("http")) {
ws_server = ws_server || window.location.hostname;
} else {
throw new Error ("Don't know how to connect to the signalling server with uri" + window.location);
}
ws_server="webrtc.nirbheek.in"
var ws_url = 'wss://' + ws_server + ':' + ws_port
setStatus("Connecting to server " + ws_url);
ws_conn = new WebSocket(ws_url);
/* When connected, immediately register with the server */
ws_conn.addEventListener('open', (event) => {
document.getElementById("id").textContent = id;
ws_conn.send('HELLO ' + id);
setStatus("Registering with server");
});
ws_conn.addEventListener('error', onServerError);
ws_conn.addEventListener('message', onServerMessage);
ws_conn.addEventListener('close', onServerClose);
}
function onRemoteTrack(event) {
if (video.srcObject !== event.streams[0]) {
console.log('Incoming video');
video.srcObject = event.streams[0];
}
}
const handleDataChannelOpen = (event) =>{
console.log("dataChannel.OnOpen", event);
};
const handleDataChannelMessageReceived = (event) =>{
console.log("dataChannel.OnMessage:", event, event.data.type);
setStatus("Received data channel message");
if (typeof event.data === 'string' || event.data instanceof String) {
console.log('Incoming string message: ' + event.data);
text.value = text.value + '\n' + event.data
} else {
console.log('Incoming data message');
}
out.send("Hi! (from browser)");
};
const handleDataChannelError = (error) =>{
console.log("dataChannel.OnError:", error);
};
const handleDataChannelClose = (event) =>{
console.log("dataChannel.OnClose", event);
};
function onDataChannel(event) {
setStatus("Data channel created");
let receiveChannel = event.channel;
receiveChannel.onopen = handleDataChannelOpen;
receiveChannel.onmessage = handleDataChannelMessageReceived;
receiveChannel.onerror = handleDataChannelError;
receiveChannel.onclose = handleDataChannelClose;
}
function createCall(msg) {
// Reset connection attempts because we connected successfully
connect_attempts = 0;
console.log('Creating RTCPeerConnection');
peer = new RTCPeerConnection({iceServers: [{urls: "stun:stun.services.mozilla.com"},
{urls: "stun:stun.l.google.com:19302"}]});
out = peer.createDataChannel('label', null);
out.onopen = handleDataChannelOpen;
out.onmessage = handleDataChannelMessageReceived;
out.onerror = handleDataChannelError;
out.onclose = handleDataChannelClose;
peer.ondatachannel = onDataChannel;
peer.ontrack = onRemoteTrack;
if (msg != null && !msg.sdp) {
console.log("WARNING: First message wasn't an SDP message!?");
}
peer.onicecandidate = (event) => {
// We have a candidate, send it to the remote party with the
// same uuid
if (event.candidate == null) {
console.log("ICE Candidate was null, done");
return;
}
ws_conn.send(JSON.stringify({'ice': event.candidate}));
};
if (msg != null)
setStatus("Created peer connection for call, waiting for SDP");
}
// vim: ts=8 sw=8 noexpandtab smarttab :
</script>