-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebrtc.js
390 lines (357 loc) · 11.3 KB
/
webrtc.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
const remoteVideo = document.getElementById('remote_video');
const dataTextInput = document.getElementById('data_text');
remoteVideo.controls = true;
let peerConnection = null;
let dataChannel = null;
let candidates = [];
let hasReceivedSdp = false;
// iceServer を定義
const iceServers = [{ 'urls': 'stun:stun.l.google.com:19302' }];
// peer connection の 設定
const peerConnectionConfig = {
'iceServers': iceServers
};
const isSSL = location.protocol === 'https:';
const wsProtocol = isSSL ? 'wss://' : 'ws://';
const wsUrl = wsProtocol + location.host + '/ws';
const ws = new WebSocket(wsUrl);
ws.onopen = onWsOpen.bind();
ws.onerror = onWsError.bind();
ws.onmessage = onWsMessage.bind();
function onWsError(error){
console.error('ws onerror() ERROR:', error);
}
function onWsOpen(event) {
console.log('ws open()');
}
function onWsMessage(event) {
console.log('ws onmessage() data:', event.data);
const message = JSON.parse(event.data);
if (message.type === 'offer') {
console.log('Received offer ...');
const offer = new RTCSessionDescription(message);
console.log('offer: ', offer);
setOffer(offer);
}
else if (message.type === 'answer') {
console.log('Received answer ...');
const answer = new RTCSessionDescription(message);
console.log('answer: ', answer);
setAnswer(answer);
}
else if (message.type === 'candidate') {
console.log('Received ICE candidate ...');
const candidate = new RTCIceCandidate(message.ice);
console.log('candidate: ', candidate);
if (hasReceivedSdp) {
addIceCandidate(candidate);
} else {
candidates.push(candidate);
}
}
else if (message.type === 'close') {
console.log('peer connection is closed ...');
}
}
function connect() {
console.group();
if (!peerConnection) {
console.log('make Offer');
makeOffer();
}
else {
console.warn('peer connection already exists.');
}
console.groupEnd();
}
function disconnect() {
console.group();
if (peerConnection) {
if (peerConnection.iceConnectionState !== 'closed') {
peerConnection.close();
peerConnection = null;
if (ws && ws.readyState === 1) {
const message = JSON.stringify({ type: 'close' });
ws.send(message);
}
console.log('sending close message');
cleanupVideoElement(remoteVideo);
return;
}
}
console.log('peerConnection is closed.');
console.groupEnd();
}
function drainCandidate() {
hasReceivedSdp = true;
candidates.forEach((candidate) => {
addIceCandidate(candidate);
});
candidates = [];
}
function addIceCandidate(candidate) {
if (peerConnection) {
peerConnection.addIceCandidate(candidate);
}
else {
console.error('PeerConnection does not exist!');
}
}
function sendIceCandidate(candidate) {
console.log('---sending ICE candidate ---');
const message = JSON.stringify({ type: 'candidate', ice: candidate });
console.log('sending candidate=' + message);
ws.send(message);
}
function playVideo(element, stream) {
element.srcObject = stream;
}
function prepareNewConnection() {
const peer = new RTCPeerConnection(peerConnectionConfig);
dataChannel = peer.createDataChannel("serial");
if ('ontrack' in peer) {
if (isSafari()) {
let tracks = [];
peer.ontrack = (event) => {
console.log('-- peer.ontrack()');
tracks.push(event.track)
// safari で動作させるために、ontrack が発火するたびに MediaStream を作成する
let mediaStream = new MediaStream(tracks);
playVideo(remoteVideo, mediaStream);
};
}
else {
let mediaStream = new MediaStream();
playVideo(remoteVideo, mediaStream);
peer.ontrack = (event) => {
console.log('-- peer.ontrack()');
mediaStream.addTrack(event.track);
};
}
}
else {
peer.onaddstream = (event) => {
console.log('-- peer.onaddstream()');
playVideo(remoteVideo, event.stream);
};
}
peer.onicecandidate = (event) => {
console.log('-- peer.onicecandidate()');
if (event.candidate) {
console.log(event.candidate);
sendIceCandidate(event.candidate);
} else {
console.log('empty ice event');
}
};
peer.oniceconnectionstatechange = () => {
console.log('-- peer.oniceconnectionstatechange()');
console.log('ICE connection Status has changed to ' + peer.iceConnectionState);
switch (peer.iceConnectionState) {
case 'closed':
case 'failed':
case 'disconnected':
break;
}
};
peer.addTransceiver('video', {direction: 'recvonly'});
peer.addTransceiver('audio', {direction: 'recvonly'});
dataChannel.onmessage = function (event) {
console.log("Got Data Channel Message:", new TextDecoder().decode(event.data));
};
return peer;
}
function browser() {
const ua = window.navigator.userAgent.toLocaleLowerCase();
if (ua.indexOf('edge') !== -1) {
return 'edge';
}
else if (ua.indexOf('chrome') !== -1 && ua.indexOf('edge') === -1) {
return 'chrome';
}
else if (ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1) {
return 'safari';
}
else if (ua.indexOf('opera') !== -1) {
return 'opera';
}
else if (ua.indexOf('firefox') !== -1) {
return 'firefox';
}
return ;
}
function isSafari() {
return browser() === 'safari';
}
function sendSdp(sessionDescription) {
console.log('---sending sdp ---');
const message = JSON.stringify(sessionDescription);
console.log('sending SDP=' + message);
ws.send(message);
}
async function makeOffer() {
peerConnection = prepareNewConnection();
try {
const sessionDescription = await peerConnection.createOffer({
'offerToReceiveAudio': true,
'offerToReceiveVideo': true
})
console.log('createOffer() success in promise, SDP=', sessionDescription.sdp);
switch (document.getElementById('codec').value) {
case 'H264':
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'VP8');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'VP9');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'AV1');
break;
case 'VP8':
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'H264');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'VP9');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'AV1');
break;
case 'VP9':
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'H264');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'VP8');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'AV1');
break;
case 'AV1':
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'H264');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'VP8');
sessionDescription.sdp = removeCodec(sessionDescription.sdp, 'VP9');
break;
}
await peerConnection.setLocalDescription(sessionDescription);
console.log('setLocalDescription() success in promise');
sendSdp(peerConnection.localDescription);
} catch (error) {
console.error('makeOffer() ERROR:', error);
}
}
async function makeAnswer() {
console.log('sending Answer. Creating remote session description...');
if (!peerConnection) {
console.error('peerConnection DOES NOT exist!');
return;
}
try {
const sessionDescription = await peerConnection.createAnswer();
console.log('createAnswer() success in promise');
await peerConnection.setLocalDescription(sessionDescription);
console.log('setLocalDescription() success in promise');
sendSdp(peerConnection.localDescription);
drainCandidate();
} catch (error) {
console.error('makeAnswer() ERROR:', error);
}
}
// offer sdp を生成する
function setOffer(sessionDescription) {
if (peerConnection) {
console.error('peerConnection already exists!');
}
const peerConnection = prepareNewConnection();
peerConnection.onnegotiationneeded = async function () {
try{
await peerConnection.setRemoteDescription(sessionDescription);
console.log('setRemoteDescription(offer) success in promise');
makeAnswer();
}catch(error) {
console.error('setRemoteDescription(offer) ERROR: ', error);
}
}
}
async function setAnswer(sessionDescription) {
if (!peerConnection) {
console.error('peerConnection DOES NOT exist!');
return;
}
try {
await peerConnection.setRemoteDescription(sessionDescription);
console.log('setRemoteDescription(answer) success in promise');
drainCandidate();
} catch(error) {
console.error('setRemoteDescription(answer) ERROR: ', error);
}
}
function cleanupVideoElement(element) {
element.pause();
element.srcObject = null;
}
/* getOffer() function is currently unused.
function getOffer() {
initiator = false;
createPeerConnection();
sendXHR(
".GetOffer",
JSON.stringify(peer_connection.localDescription),
function (respnse) {
peer_connection.setRemoteDescription(
new RTCSessionDescription(respnse),
function () {
peer_connection.createAnswer(
function (answer) {
peer_connection.setLocalDescription(answer);
}, function (e) { });
}, function (e) {
console.error(e);
});
}, true);
}
*/
// Stack Overflow より引用: https://stackoverflow.com/a/52760103
// https://stackoverflow.com/questions/52738290/how-to-remove-video-codecs-in-webrtc-sdp
function removeCodec(orgsdp, codec) {
const internalFunc = (sdp) => {
const codecre = new RegExp('(a=rtpmap:(\\d*) ' + codec + '\/90000\\r\\n)');
const rtpmaps = sdp.match(codecre);
if (rtpmaps == null || rtpmaps.length <= 2) {
return sdp;
}
const rtpmap = rtpmaps[2];
let modsdp = sdp.replace(codecre, "");
const rtcpre = new RegExp('(a=rtcp-fb:' + rtpmap + '.*\r\n)', 'g');
modsdp = modsdp.replace(rtcpre, "");
const fmtpre = new RegExp('(a=fmtp:' + rtpmap + '.*\r\n)', 'g');
modsdp = modsdp.replace(fmtpre, "");
const aptpre = new RegExp('(a=fmtp:(\\d*) apt=' + rtpmap + '\\r\\n)');
const aptmaps = modsdp.match(aptpre);
let fmtpmap = "";
if (aptmaps != null && aptmaps.length >= 3) {
fmtpmap = aptmaps[2];
modsdp = modsdp.replace(aptpre, "");
const rtppre = new RegExp('(a=rtpmap:' + fmtpmap + '.*\r\n)', 'g');
modsdp = modsdp.replace(rtppre, "");
}
let videore = /(m=video.*\r\n)/;
const videolines = modsdp.match(videore);
if (videolines != null) {
//If many m=video are found in SDP, this program doesn't work.
let videoline = videolines[0].substring(0, videolines[0].length - 2);
const videoelems = videoline.split(" ");
let modvideoline = videoelems[0];
videoelems.forEach((videoelem, index) => {
if (index === 0) return;
if (videoelem == rtpmap || videoelem == fmtpmap) {
return;
}
modvideoline += " " + videoelem;
})
modvideoline += "\r\n";
modsdp = modsdp.replace(videore, modvideoline);
}
return internalFunc(modsdp);
}
return internalFunc(orgsdp);
}
function play() {
remoteVideo.play();
}
function sendDataChannel() {
let textData = dataTextInput.value;
if (textData.length == 0) {
return;
}
if (dataChannel == null || dataChannel.readyState != "open") {
return;
}
dataChannel.send(new TextEncoder().encode(textData));
dataTextInput.value = "";