-
Notifications
You must be signed in to change notification settings - Fork 3
/
viewer.html
291 lines (246 loc) · 9.28 KB
/
viewer.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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.595.0.min.js"></script>
<script src="https://unpkg.com/amazon-kinesis-video-streams-webrtc/dist/kvs-webrtc.min.js"></script>
<script src="kvs_keys.js"></script>
<title>KVS Viewer</title>
</head>
<body>
<input type="checkbox" checked id="send_video_audio_check">send video/audio</input>
<button id="start_button" onclick="startViewer()">start viewer(offer)</button>
<button id="stop_button" onclick="stopViewer()">stop viewer</button>
<br />
<video id='local_video' width="240px" height="180px" style="border: solid black 1px;"></video>
<video id='remote_video' width="240px" height="180px" style="border: solid black 1px;"></video>
</body>
<script>
"use strict"
// refer
// https://github.com/awslabs/amazon-kinesis-video-streams-webrtc-sdk-js
// DescribeSignalingChannel API can also be used to get the ARN from a channel name.
const channelARN = AWS_CHANNEL_ARN;
// AWS Credentials
const accessKeyId = AWS_ACCESS_KEY_ID;
const secretAccessKey = AWS_SECRET_ACCESS_KEY;
// AWS region
const region = AWS_REGION;
// <video> HTML elements to use to display the local webcam stream and remote stream from the master
const localView = document.getElementById('local_video');
const remoteView = document.getElementById('remote_video');
const sendVideoAudioCheck = document.getElementById('send_video_audio_check');
const clientId = 'viewer-' + generateUuid(); //'viewer_client'; //'RANDOM_VALUE';
console.log('clientId=', clientId);
const globalKVS = {};
async function setupKVS() {
// --------- Create KVS Client -----
const kinesisVideoClient = new AWS.KinesisVideo({
region,
accessKeyId,
secretAccessKey,
});
globalKVS.kinesisVideoClient = kinesisVideoClient;
const getSignalingChannelEndpointResponse = await kinesisVideoClient
.getSignalingChannelEndpoint({
ChannelARN: channelARN,
SingleMasterChannelEndpointConfiguration: {
Protocols: ['WSS', 'HTTPS'],
Role: KVSWebRTC.Role.VIEWER,
},
})
.promise();
const endpointsByProtocol = getSignalingChannelEndpointResponse.ResourceEndpointList.reduce((endpoints, endpoint) => {
endpoints[endpoint.Protocol] = endpoint.ResourceEndpoint;
return endpoints;
}, {});
globalKVS.getSignalingChannelEndpointResponse = getSignalingChannelEndpointResponse;
globalKVS.endpointsByProtocol = endpointsByProtocol;
const kinesisVideoSignalingChannelsClient = new AWS.KinesisVideoSignalingChannels({
region,
accessKeyId,
secretAccessKey,
endpoint: endpointsByProtocol.HTTPS,
});
globalKVS.kinesisVideoSignalingChannelsClient = kinesisVideoSignalingChannelsClient;
const getIceServerConfigResponse = await kinesisVideoSignalingChannelsClient
.getIceServerConfig({
ChannelARN: channelARN,
})
.promise();
const iceServers = [
{ urls: `stun:stun.kinesisvideo.${region}.amazonaws.com:443` }
];
getIceServerConfigResponse.IceServerList.forEach(iceServer =>
iceServers.push({
urls: iceServer.Uris,
username: iceServer.Username,
credential: iceServer.Password,
}),
);
globalKVS.iceServers = iceServers;
const signalingClient = new KVSWebRTC.SignalingClient({
channelARN,
channelEndpoint: endpointsByProtocol.WSS,
clientId,
role: KVSWebRTC.Role.VIEWER,
region,
credentials: {
accessKeyId,
secretAccessKey,
},
});
globalKVS.signalingClient = signalingClient;
// Once the signaling channel connection is open, connect to the webcam and create an offer to send to the master
signalingClient.on('open', async () => {
console.log('signaling client open');
// --- prepare new peer ---
if (!globalKVS.peerConnection) {
globalKVS.peerConnection = prepareNewPeer(globalKVS.iceServers, globalKVS.signalingClient);
}
else {
console.warn('WARN: ALREADY peer exist');
}
if (isSendingVideoAudio()) {
// Get a stream from the webcam, add it to the peer connection, and display it in the local view
try {
const localStream = await navigator.mediaDevices.getUserMedia({
video: { width: { ideal: 1280 }, height: { ideal: 720 } },
audio: true,
});
globalKVS.localStream = localStream;
localStream.getTracks().forEach(track => globalKVS.peerConnection.addTrack(track, localStream));
playVideo(localView, localStream);
} catch (e) {
console.error('GUM , play error:', e);
// Could not find webcam
return;
}
}
else {
// --- recvonly ---
//const peer = new RTCPeerConnection({ sdpSemantics: 'unified-plan' });
if (globalKVS.peerConnection.addTransceiver) {
globalKVS.peerConnection.addTransceiver('video', { direction: 'recvonly' });
globalKVS.peerConnection.addTransceiver('audio', { direction: 'recvonly' });
}
}
// Create an SDP offer and send it to the master
const offer = await globalKVS.peerConnection.createOffer({
offerToReceiveAudio: true,
offerToReceiveVideo: true,
});
await globalKVS.peerConnection.setLocalDescription(offer);
console.log('send offer');
signalingClient.sendSdpOffer(globalKVS.peerConnection.localDescription);
});
// When the SDP answer is received back from the master, add it to the peer connection.
signalingClient.on('sdpAnswer', async answer => {
console.log('got answer');
await globalKVS.peerConnection.setRemoteDescription(answer);
});
// When an ICE candidate is received from the master, add it to the peer connection.
signalingClient.on('iceCandidate', candidate => {
console.log('got iceCandidate');
globalKVS.peerConnection.addIceCandidate(candidate);
});
signalingClient.on('close', () => {
// Handle client closures
console.warn('signalingClient close');
});
signalingClient.on('error', error => {
// Handle client errors
console.error('signalingClient error', error);
});
}
function prepareNewPeer(iceServers, signalingClient) {
const peerConnection = new RTCPeerConnection({ iceServers });
// Send any ICE candidates generated by the peer connection to the other peer
peerConnection.addEventListener('icecandidate', ({ candidate }) => {
if (candidate) {
console.log('send iceCandidate');
signalingClient.sendIceCandidate(candidate);
} else {
// No more ICE candidates will be generated
}
});
// As remote tracks are received, add them to the remote view
peerConnection.addEventListener('track', event => {
console.log('on track');
if (remoteView.srcObject) {
return;
}
playVideo(remoteView, event.streams[0]);
});
// handle disconnect
peerConnection.addEventListener('iceconnectionstatechange', event => {
console.log('on iceconnectionstatechange. iceState:', peerConnection.iceConnectionState, ' signalingState:', peerConnection.signalingState); //, 'connectionState:', peerConnection.connectionState);
if (peerConnection.iceConnectionState === 'failed') {
console.warn('remote peeer closed');
stopVideo(remoteView);
stopViewer();
}
});
return peerConnection;
}
async function playVideo(element, stream) {
element.srcObject = stream;
await element.play().catch(err => console.error(err));
element.volume = 0;
}
function stopVideo(element) {
if (element.srcObject) {
element.pause();
element.srcObject = null;
}
}
function generateUuid() {
// refer
// https://qiita.com/psn/items/d7ac5bdb5b5633bae165
// https://github.com/GoogleChrome/chrome-platform-analytics/blob/master/src/internal/identifier.js
// const FORMAT: string = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
let chars = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".split("");
for (let i = 0, len = chars.length; i < len; i++) {
switch (chars[i]) {
case "x":
chars[i] = Math.floor(Math.random() * 16).toString(16);
break;
case "y":
chars[i] = (Math.floor(Math.random() * 4) + 8).toString(16);
break;
}
}
return chars.join("");
}
function isSendingVideoAudio() {
return sendVideoAudioCheck.checked;
}
function startViewer() {
console.log('-- start Viewer --');
globalKVS.signalingClient.open();
}
function stopViewer() {
console.log('-- stop Viewer --');
stopVideo(localView);
stopVideo(remoteView);
if (globalKVS.signalingClient) {
globalKVS.signalingClient.close();
//globalKVS.signalingClient = null;
}
if (globalKVS.peerConnection) {
globalKVS.peerConnection.close();
globalKVS.peerConnection = null;
}
if (globalKVS.localStream) {
globalKVS.localStream.getTracks().forEach(track => track.stop());
globalKVS.localStream = null;
}
//if (globalKVS.remoteStream) {
// globalKVS.remoteStream.getTracks().forEach(track => track.stop());
// globalKVS.remoteStream = null;
//}
}
// --- init ---
setupKVS();
</script>
</html>