-
Notifications
You must be signed in to change notification settings - Fork 136
/
streaming-client-api.js
407 lines (361 loc) · 13.5 KB
/
streaming-client-api.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
'use strict';
const fetchJsonFile = await fetch("./api.json")
const DID_API = await fetchJsonFile.json()
if (DID_API.key == '🤫') alert('Please put your api key inside ./api.json and restart..');
const RTCPeerConnection = (
window.RTCPeerConnection ||
window.webkitRTCPeerConnection ||
window.mozRTCPeerConnection
).bind(window);
let peerConnection;
let pcDataChannel;
let streamId;
let sessionId;
let sessionClientAnswer;
let statsIntervalId;
let lastBytesReceived;
let videoIsPlaying = false;
let streamVideoOpacity = 0;
// Set this variable to true to request stream warmup upon connection to mitigate potential jittering issues
const stream_warmup = true;
let isStreamReady = !stream_warmup;
const idleVideoElement = document.getElementById('idle-video-element');
const streamVideoElement = document.getElementById('stream-video-element');
idleVideoElement.setAttribute('playsinline', '');
streamVideoElement.setAttribute('playsinline', '');
const peerStatusLabel = document.getElementById('peer-status-label');
const iceStatusLabel = document.getElementById('ice-status-label');
const iceGatheringStatusLabel = document.getElementById('ice-gathering-status-label');
const signalingStatusLabel = document.getElementById('signaling-status-label');
const streamingStatusLabel = document.getElementById('streaming-status-label');
const streamEventLabel = document.getElementById('stream-event-label');
const presenterInputByService = {
talks: {
source_url: 'https://d-id-public-bucket.s3.amazonaws.com/or-roman.jpg',
},
clips: {
presenter_id: 'rian-lZC6MmWfC1',
driver_id: 'mXra4jY38i',
},
};
const connectButton = document.getElementById('connect-button');
connectButton.onclick = async () => {
if (peerConnection && peerConnection.connectionState === 'connected') {
return;
}
stopAllStreams();
closePC();
/**
* Set 'stream_warmup' to 'true' in the payload to initiate idle streaming at the beginning of the connection, addressing jittering issues.
* The idle streaming process is transparent to the user and is concealed by triggering a 'stream/ready' event on the data channel,
* indicating that idle streaming has concluded and the stream channel is ready for use.
*/
const sessionResponse = await fetchWithRetries(`${DID_API.url}/${DID_API.service}/streams`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ ...presenterInputByService[DID_API.service], stream_warmup }),
});
const { id: newStreamId, offer, ice_servers: iceServers, session_id: newSessionId } = await sessionResponse.json();
streamId = newStreamId;
sessionId = newSessionId;
try {
sessionClientAnswer = await createPeerConnection(offer, iceServers);
} catch (e) {
console.log('error during streaming setup', e);
stopAllStreams();
closePC();
return;
}
const sdpResponse = await fetch(`${DID_API.url}/${DID_API.service}/streams/${streamId}/sdp`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
answer: sessionClientAnswer,
session_id: sessionId,
}),
});
};
const startButton = document.getElementById('start-button');
startButton.onclick = async () => {
// connectionState not supported in firefox
if (
(peerConnection?.signalingState === 'stable' || peerConnection?.iceConnectionState === 'connected') &&
isStreamReady
) {
const playResponse = await fetchWithRetries(`${DID_API.url}/${DID_API.service}/streams/${streamId}`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
script: {
type: 'audio',
audio_url: 'https://d-id-public-bucket.s3.us-west-2.amazonaws.com/webrtc.mp3',
},
...(DID_API.service === 'clips' && {
background: {
color: '#FFFFFF',
},
}),
config: {
stitch: true,
},
session_id: sessionId,
}),
});
}
};
const destroyButton = document.getElementById('destroy-button');
destroyButton.onclick = async () => {
await fetch(`${DID_API.url}/${DID_API.service}/streams/${streamId}`, {
method: 'DELETE',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ session_id: sessionId }),
});
stopAllStreams();
closePC();
};
function onIceGatheringStateChange() {
iceGatheringStatusLabel.innerText = peerConnection.iceGatheringState;
iceGatheringStatusLabel.className = 'iceGatheringState-' + peerConnection.iceGatheringState;
}
function onIceCandidate(event) {
console.log('onIceCandidate', event);
if (event.candidate) {
const { candidate, sdpMid, sdpMLineIndex } = event.candidate;
fetch(`${DID_API.url}/${DID_API.service}/streams/${streamId}/ice`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
candidate,
sdpMid,
sdpMLineIndex,
session_id: sessionId,
}),
});
} else {
// For the initial 2 sec idle stream at the beginning of the connection, we utilize a null ice candidate.
fetch(`${DID_API.url}/${DID_API.service}/streams/${streamId}/ice`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
}),
});
}
}
function onIceConnectionStateChange() {
iceStatusLabel.innerText = peerConnection.iceConnectionState;
iceStatusLabel.className = 'iceConnectionState-' + peerConnection.iceConnectionState;
if (peerConnection.iceConnectionState === 'failed' || peerConnection.iceConnectionState === 'closed') {
stopAllStreams();
closePC();
}
}
function onConnectionStateChange() {
// not supported in firefox
peerStatusLabel.innerText = peerConnection.connectionState;
peerStatusLabel.className = 'peerConnectionState-' + peerConnection.connectionState;
if (peerConnection.connectionState === 'connected') {
playIdleVideo();
/**
* A fallback mechanism: if the 'stream/ready' event isn't received within 5 seconds after asking for stream warmup,
* it updates the UI to indicate that the system is ready to start streaming data.
*/
setTimeout(() => {
if (!isStreamReady) {
console.log('forcing stream/ready');
isStreamReady = true;
streamEventLabel.innerText = 'ready';
streamEventLabel.className = 'streamEvent-ready';
}
}, 5000);
}
}
function onSignalingStateChange() {
signalingStatusLabel.innerText = peerConnection.signalingState;
signalingStatusLabel.className = 'signalingState-' + peerConnection.signalingState;
}
function onVideoStatusChange(videoIsPlaying, stream) {
let status;
if (videoIsPlaying) {
status = 'streaming';
streamVideoOpacity = isStreamReady ? 1 : 0;
setStreamVideoElement(stream);
} else {
status = 'empty';
streamVideoOpacity = 0;
}
streamVideoElement.style.opacity = streamVideoOpacity;
idleVideoElement.style.opacity = 1 - streamVideoOpacity;
streamingStatusLabel.innerText = status;
streamingStatusLabel.className = 'streamingState-' + status;
}
function onTrack(event) {
/**
* The following code is designed to provide information about wether currently there is data
* that's being streamed - It does so by periodically looking for changes in total stream data size
*
* This information in our case is used in order to show idle video while no video is streaming.
* To create this idle video use the POST https://api.d-id.com/talks (or clips) endpoint with a silent audio file or a text script with only ssml breaks
* https://docs.aws.amazon.com/polly/latest/dg/supportedtags.html#break-tag
* for seamless results use `config.fluent: true` and provide the same configuration as the streaming video
*/
if (!event.track) return;
statsIntervalId = setInterval(async () => {
const stats = await peerConnection.getStats(event.track);
stats.forEach((report) => {
if (report.type === 'inbound-rtp' && report.kind === 'video') {
const videoStatusChanged = videoIsPlaying !== report.bytesReceived > lastBytesReceived;
if (videoStatusChanged) {
videoIsPlaying = report.bytesReceived > lastBytesReceived;
onVideoStatusChange(videoIsPlaying, event.streams[0]);
}
lastBytesReceived = report.bytesReceived;
}
});
}, 500);
}
function onStreamEvent(message) {
/**
* This function handles stream events received on the data channel.
* The 'stream/ready' event received on the data channel signals the end of the 2sec idle streaming.
* Upon receiving the 'ready' event, we can display the streamed video if one is available on the stream channel.
* Until the 'ready' event is received, we hide any streamed video.
* Additionally, this function processes events for stream start, completion, and errors. Other data events are disregarded.
*/
if (pcDataChannel.readyState === 'open') {
let status;
const [event, _] = message.data.split(':');
switch (event) {
case 'stream/started':
status = 'started';
break;
case 'stream/done':
status = 'done';
break;
case 'stream/ready':
status = 'ready';
break;
case 'stream/error':
status = 'error';
break;
default:
status = 'dont-care';
break;
}
// Set stream ready after a short delay, adjusting for potential timing differences between data and stream channels
if (status === 'ready') {
setTimeout(() => {
console.log('stream/ready');
isStreamReady = true;
streamEventLabel.innerText = 'ready';
streamEventLabel.className = 'streamEvent-ready';
}, 1000);
} else {
console.log(event);
streamEventLabel.innerText = status === 'dont-care' ? event : status;
streamEventLabel.className = 'streamEvent-' + status;
}
}
}
async function createPeerConnection(offer, iceServers) {
if (!peerConnection) {
peerConnection = new RTCPeerConnection({ iceServers });
pcDataChannel = peerConnection.createDataChannel('JanusDataChannel');
peerConnection.addEventListener('icegatheringstatechange', onIceGatheringStateChange, true);
peerConnection.addEventListener('icecandidate', onIceCandidate, true);
peerConnection.addEventListener('iceconnectionstatechange', onIceConnectionStateChange, true);
peerConnection.addEventListener('connectionstatechange', onConnectionStateChange, true);
peerConnection.addEventListener('signalingstatechange', onSignalingStateChange, true);
peerConnection.addEventListener('track', onTrack, true);
pcDataChannel.addEventListener('message', onStreamEvent, true);
}
await peerConnection.setRemoteDescription(offer);
console.log('set remote sdp OK');
const sessionClientAnswer = await peerConnection.createAnswer();
console.log('create local sdp OK');
await peerConnection.setLocalDescription(sessionClientAnswer);
console.log('set local sdp OK');
return sessionClientAnswer;
}
function setStreamVideoElement(stream) {
if (!stream) return;
streamVideoElement.srcObject = stream;
streamVideoElement.loop = false;
streamVideoElement.mute = !isStreamReady;
// safari hotfix
if (streamVideoElement.paused) {
streamVideoElement
.play()
.then((_) => {})
.catch((e) => {});
}
}
function playIdleVideo() {
idleVideoElement.src = DID_API.service == 'clips' ? 'rian_idle.mp4' : 'or_idle.mp4';
}
function stopAllStreams() {
if (streamVideoElement.srcObject) {
console.log('stopping video streams');
streamVideoElement.srcObject.getTracks().forEach((track) => track.stop());
streamVideoElement.srcObject = null;
streamVideoOpacity = 0;
}
}
function closePC(pc = peerConnection) {
if (!pc) return;
console.log('stopping peer connection');
pc.close();
pc.removeEventListener('icegatheringstatechange', onIceGatheringStateChange, true);
pc.removeEventListener('icecandidate', onIceCandidate, true);
pc.removeEventListener('iceconnectionstatechange', onIceConnectionStateChange, true);
pc.removeEventListener('connectionstatechange', onConnectionStateChange, true);
pc.removeEventListener('signalingstatechange', onSignalingStateChange, true);
pc.removeEventListener('track', onTrack, true);
pc.removeEventListener('onmessage', onStreamEvent, true);
clearInterval(statsIntervalId);
isStreamReady = !stream_warmup;
streamVideoOpacity = 0;
iceGatheringStatusLabel.innerText = '';
signalingStatusLabel.innerText = '';
iceStatusLabel.innerText = '';
peerStatusLabel.innerText = '';
streamEventLabel.innerText = '';
console.log('stopped peer connection');
if (pc === peerConnection) {
peerConnection = null;
}
}
const maxRetryCount = 3;
const maxDelaySec = 4;
async function fetchWithRetries(url, options, retries = 1) {
try {
return await fetch(url, options);
} catch (err) {
if (retries <= maxRetryCount) {
const delay = Math.min(Math.pow(2, retries) / 4 + Math.random(), maxDelaySec) * 1000;
await new Promise((resolve) => setTimeout(resolve, delay));
console.log(`Request failed, retrying ${retries}/${maxRetryCount}. Error ${err}`);
return fetchWithRetries(url, options, retries + 1);
} else {
throw new Error(`Max retries exceeded. error: ${err}`);
}
}
}