forked from mganeko/kvs_webrtc_example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
master.html
296 lines (253 loc) · 9.15 KB
/
master.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
292
293
294
295
296
<!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 Master</title>
</head>
<body>
<input type="checkbox" checked id="send_video_audio_check">send video/audio</input>
<button id="start_button" onclick="startMaster()">start master (answer)</button>
<button id="stop_button" onclick="stopMaster()">stop master</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 = null;
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.MASTER,
},
})
.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.MASTER,
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');
// await prepareMedia();
});
// When the SDP answer is received back from the master, add it to the peer connection.
signalingClient.on('sdpAnswer', async answer => {
console.warn('waiting offer');
});
const DERAULT_MASTER = 'AWS_DEFAULT_SINGLE_MASTER'
signalingClient.on('sdpOffer', async (offer, remoteClientId) => {
console.log('got Offer, remoteId=', remoteClientId);
// --- prepare new peer ---
if (!globalKVS.peerConnection) {
globalKVS.peerConnection = prepareNewPeer(globalKVS.iceServers, globalKVS.signalingClient, remoteClientId);
}
else {
console.warn('WARN: ALREADY peer exist');
}
const peer = globalKVS.peerConnection;
const localStream = globalKVS.localStream;
if (localStream) {
localStream.getTracks().forEach(track => peer.addTrack(track, localStream));
}
else {
// --- recvonly ---
//const peer = new RTCPeerConnection({ sdpSemantics: 'unified-plan' });
if (peer.addTransceiver) {
peer.addTransceiver('video', { direction: 'recvonly' });
peer.addTransceiver('audio', { direction: 'recvonly' });
}
}
await peer.setRemoteDescription(offer);
await peer.setLocalDescription(
await peer.createAnswer({
offerToReceiveAudio: true,
offerToReceiveVideo: true,
}),
);
// send back asnwer
console.log('sending answer, remoteId=', remoteClientId)
signalingClient.sendSdpAnswer(peer.localDescription, remoteClientId);
});
// When an ICE candidate is received from the master, add it to the peer connection.
signalingClient.on('iceCandidate', (candidate, remoteClientId) => {
console.log('got iceCandidate from', remoteClientId);
let peer = globalKVS.peerConnection;
peer.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, remoteClientId) {
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, remoteClientId);
} 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);
closePeer();
}
});
return peerConnection;
}
async function prepareMedia() {
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;
playVideo(localView, localStream);
} catch (e) {
console.error('GUM , play error:', e);
// Could not find webcam
return;
}
}
}
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 isSendingVideoAudio() {
return sendVideoAudioCheck.checked;
}
async function startMaster() {
console.log('-- start Master --');
await prepareMedia();
globalKVS.signalingClient.open();
}
function stopMaster() {
console.log('--- stop Master ---');
stopVideo(localView);
stopVideo(remoteView);
if (globalKVS.signalingClient) {
globalKVS.signalingClient.close();
//globalKVS.signalingClient = null;
}
else {
console.warn('NO globalKVS.signalingClient');
}
if (globalKVS.peerConnection) {
globalKVS.peerConnection.close();
globalKVS.peerConnection = null;
}
else {
console.warn('NO globalKVS.peerConnection');
}
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;
//}
}
function closePeer() {
if (globalKVS.peerConnection) {
globalKVS.peerConnection.close();
globalKVS.peerConnection = null;
}
}
// --- init ---
setupKVS();
</script>
</html>