-
Notifications
You must be signed in to change notification settings - Fork 142
/
streaming-client-api.js
290 lines (255 loc) · 9.28 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
'use strict';
import DID_API from './api.json' assert { type: '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 streamId;
let sessionId;
let sessionClientAnswer;
let statsIntervalId;
let videoIsPlaying;
let lastBytesReceived;
const talkVideo = document.getElementById('talk-video');
talkVideo.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 connectButton = document.getElementById('connect-button');
connectButton.onclick = async () => {
if (peerConnection && peerConnection.connectionState === 'connected') {
return;
}
stopAllStreams();
closePC();
const sessionResponse = await fetchWithRetries(`${DID_API.url}/talks/streams`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
source_url: 'https://d-id-public-bucket.s3.amazonaws.com/or-roman.jpg',
}),
});
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}/talks/streams/${streamId}/sdp`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
answer: sessionClientAnswer,
session_id: sessionId,
}),
});
};
const talkButton = document.getElementById('talk-button');
talkButton.onclick = async () => {
// connectionState not supported in firefox
if (peerConnection?.signalingState === 'stable' || peerConnection?.iceConnectionState === 'connected') {
const talkResponse = await fetchWithRetries(`${DID_API.url}/talks/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',
},
driver_url: 'bank://lively/',
config: {
stitch: true,
},
session_id: sessionId,
}),
});
}
};
const destroyButton = document.getElementById('destroy-button');
destroyButton.onclick = async () => {
await fetch(`${DID_API.url}/talks/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}/talks/streams/${streamId}/ice`, {
method: 'POST',
headers: {
Authorization: `Basic ${DID_API.key}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
candidate,
sdpMid,
sdpMLineIndex,
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;
}
function onSignalingStateChange() {
signalingStatusLabel.innerText = peerConnection.signalingState;
signalingStatusLabel.className = 'signalingState-' + peerConnection.signalingState;
}
function onVideoStatusChange(videoIsPlaying, stream) {
let status;
if (videoIsPlaying) {
status = 'streaming';
const remoteStream = stream;
setVideoElement(remoteStream);
} else {
status = 'empty';
playIdleVideo();
}
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 talk is streaming.
* To create this idle video use the POST https://api.d-id.com/talks 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.mediaType === 'video') {
const videoStatusChanged = videoIsPlaying !== report.bytesReceived > lastBytesReceived;
if (videoStatusChanged) {
videoIsPlaying = report.bytesReceived > lastBytesReceived;
onVideoStatusChange(videoIsPlaying, event.streams[0]);
}
lastBytesReceived = report.bytesReceived;
}
});
}, 500);
}
async function createPeerConnection(offer, iceServers) {
if (!peerConnection) {
peerConnection = new RTCPeerConnection({ iceServers });
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);
}
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 setVideoElement(stream) {
if (!stream) return;
talkVideo.srcObject = stream;
talkVideo.loop = false;
// safari hotfix
if (talkVideo.paused) {
talkVideo
.play()
.then((_) => {})
.catch((e) => {});
}
}
function playIdleVideo() {
talkVideo.srcObject = undefined;
talkVideo.src = 'or_idle.mp4';
talkVideo.loop = true;
}
function stopAllStreams() {
if (talkVideo.srcObject) {
console.log('stopping video streams');
talkVideo.srcObject.getTracks().forEach((track) => track.stop());
talkVideo.srcObject = null;
}
}
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);
clearInterval(statsIntervalId);
iceGatheringStatusLabel.innerText = '';
signalingStatusLabel.innerText = '';
iceStatusLabel.innerText = '';
peerStatusLabel.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}`);
}
}
}