forked from livekit/client-sdk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample.ts
More file actions
297 lines (260 loc) · 9.02 KB
/
sample.ts
File metadata and controls
297 lines (260 loc) · 9.02 KB
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
//@ts-ignore
import {rtcDrmGetVersion, rtcDrmConfigure, rtcDrmOnTrack, rtcDrmEnvironments} from './rtc-drm-transform.min.js';
import {
ConnectionQuality,
DisconnectReason,
LocalAudioTrack,
LogLevel,
Participant,
ParticipantEvent,
RemoteParticipant,
Room,
RoomConnectOptions,
RoomEvent,
RoomOptions,
TrackPublication,
VideoPresets,
createAudioAnalyser,
setLogLevel
} from '../src/index';
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
let currentRoom: Room | undefined;
let startTime: number;
const searchParams = new URLSearchParams(window.location.search);
const storedUrl = searchParams.get('url') ?? 'ws://localhost:7880';
const storedToken = searchParams.get('token') ?? '';
(<HTMLInputElement>$('url')).value = storedUrl;
(<HTMLInputElement>$('token')).value = storedToken;
// DRMtoday
const merchant = searchParams.get('merchant') ?? '';
const storedKeyId = searchParams.get('keyid') ?? '00000000000000000000000000000001';
const storedIV = searchParams.get('iv') ?? 'd5fbd6b82ed93e4ef98ae40931ee33b7';
(<HTMLInputElement>$('keyid')).value = storedKeyId;
(<HTMLInputElement>$('iv')).value = storedIV;
function hexStringToUint8Array(hexString: string) {
if (hexString.length % 2 !== 0) {
console.error('hexStringToUint8Array: invalid hex string');
return null;
}
const array = new Uint8Array(hexString.length / 2);
for (let i = 0; i < hexString.length; i += 2) {
const byte = parseInt(hexString.substr(i, 2), 16);
if (isNaN(byte)) {
console.error('hexStringToUint8Array: invalid hex string');
return null;
}
array[i / 2] = byte;
}
return array;
}
function updateSearchParams(url: string, token: string) {
const params = new URLSearchParams({ merchant, url, token });
window.history.replaceState(null, '', `${window.location.pathname}?${params.toString()}`);
}
// handles actions from the HTML
const appActions = {
connectWithFormInput: async () => {
const url = (<HTMLInputElement>$('url')).value;
const token = (<HTMLInputElement>$('token')).value;
const simulcast = false;
const dynacast = false;
const forceTURN = false;
const adaptiveStream = false;
const shouldPublish = false;
const autoSubscribe = true;
setLogLevel(LogLevel.debug);
updateSearchParams(url, token);
console.log('rtcDrmGetVersion:', rtcDrmGetVersion());
const keyId = hexStringToUint8Array((<HTMLInputElement>$('keyid')).value);
const iv = hexStringToUint8Array((<HTMLInputElement>$('iv')).value);
const drmConfig = {
merchant,
environment: rtcDrmEnvironments.Staging,
videoElement: $('remote-video'),
audioElement: $('remote-audio'),
video: {codec: 'H264', encryption: 'cbcs', keyId, iv},
audio: {codec: 'opus', encryption: 'clear'}
};
try {
rtcDrmConfigure(drmConfig);
}
catch (err) {
alert(`DRM initialization error: ${err}`);
}
const roomOpts: RoomOptions = {
adaptiveStream,
dynacast,
publishDefaults: {
simulcast,
videoSimulcastLayers: [VideoPresets.h90, VideoPresets.h216],
videoCodec: 'h264',
backupCodec: false,
dtx: true,
red: true,
forceStereo: false
},
videoCaptureDefaults: {
resolution: VideoPresets.h720.resolution,
}
};
const connectOpts: RoomConnectOptions = {
autoSubscribe: autoSubscribe,
rtcConfig: {
encodedInsertableStreams: true,
iceTransportPolicy: forceTURN ? 'relay' : 'all'
}
};
await appActions.connectToRoom(url, token, roomOpts, connectOpts, shouldPublish);
},
connectToRoom: async (
url: string,
token: string,
roomOptions?: RoomOptions,
connectOptions?: RoomConnectOptions,
shouldPublish?: boolean,
): Promise<Room | undefined> => {
const room = new Room(roomOptions);
startTime = Date.now();
await room.prepareConnection(url, token);
const prewarmTime = Date.now() - startTime;
appendLog(`prewarmed connection in ${prewarmTime}ms`);
room
.on(RoomEvent.ParticipantConnected, participantConnected)
.on(RoomEvent.ParticipantDisconnected, participantDisconnected)
.on(RoomEvent.Disconnected, handleRoomDisconnect)
.on(RoomEvent.Reconnecting, () => appendLog('Reconnecting to room'))
.on(RoomEvent.Reconnected, async () => {
appendLog(
'Successfully reconnected. server',
await room.engine.getConnectedServerAddress(),
);
})
.on(RoomEvent.LocalTrackPublished, (pub) => {
const track = pub.track as LocalAudioTrack;
if (track instanceof LocalAudioTrack) {
const { calculateVolume } = createAudioAnalyser(track);
setInterval(() => {
$('local-volume')?.setAttribute('value', calculateVolume().toFixed(4));
}, 200);
}
})
.on(
RoomEvent.ConnectionQualityChanged,
(quality: ConnectionQuality, participant?: Participant) => {
appendLog('connection quality changed', participant?.identity, quality);
},
)
.on(RoomEvent.TrackSubscribed, (track, pub, participant) => {
appendLog('subscribed to track', pub.trackSid, participant.identity, track);
// rtcDrmOntrack expects the original RTCPeerConnection track event,
// of which track, receiver and streams are utilized
let event = { track, receiver: track.receiver, streams: [track.mediaStream] };
rtcDrmOnTrack(event);
})
.on(RoomEvent.TrackUnsubscribed, (_, pub, participant) => {
appendLog('unsubscribed from track', pub.trackSid);
})
.on(RoomEvent.SignalConnected, async () => {
const signalConnectionTime = Date.now() - startTime;
appendLog(`signal connection established in ${signalConnectionTime}ms`);
})
.on(RoomEvent.TrackStreamStateChanged, (pub, streamState, participant) => {
appendLog(
`stream state changed for ${pub.trackSid} (${
participant.identity
}) to ${streamState.toString()}`,
);
});
try {
await room.connect(url, token, connectOptions);
const elapsed = Date.now() - startTime;
appendLog(
`successfully connected to ${room.name} in ${Math.round(elapsed)}ms`,
await room.engine.getConnectedServerAddress(),
);
} catch (error: any) {
let message: any = error;
if (error.message) {
message = error.message;
}
appendLog('could not connect:', message);
return;
}
currentRoom = room;
window.currentRoom = room;
setButtonsForState(true);
room.participants.forEach((participant) => {
participantConnected(participant);
});
participantConnected(room.localParticipant);
return room;
},
disconnectRoom: () => {
if (currentRoom) {
currentRoom.disconnect();
}
}
};
declare global {
interface Window {
currentRoom: any;
appActions: typeof appActions;
}
}
window.appActions = appActions;
// --------------------------- event handlers ------------------------------- //
function participantConnected(participant: Participant) {
appendLog('participant', participant.identity, 'connected', participant.metadata);
console.log('tracks', participant.tracks);
participant
.on(ParticipantEvent.TrackMuted, (pub: TrackPublication) => {
appendLog('track was muted', pub.trackSid, participant.identity);
})
.on(ParticipantEvent.TrackUnmuted, (pub: TrackPublication) => {
appendLog('track was unmuted', pub.trackSid, participant.identity);
})
.on(ParticipantEvent.IsSpeakingChanged, () => {
})
.on(ParticipantEvent.ConnectionQualityChanged, () => {
});
}
function clearMediaElements() {
(<HTMLVideoElement>$('remote-video')).srcObject = null;
(<HTMLAudioElement>$('remote-audio')).srcObject = null;
}
function participantDisconnected(participant: RemoteParticipant) {
appendLog('participant', participant.sid, 'disconnected');
clearMediaElements();
}
function handleRoomDisconnect(reason?: DisconnectReason) {
if (!currentRoom) return;
appendLog('disconnected from room', { reason });
clearMediaElements();
setButtonsForState(false);
currentRoom = undefined;
window.currentRoom = undefined;
}
function setButtonsForState(connected: boolean) {
const connectedSet = ['disconnect-room-button'];
const disconnectedSet = ['connect-button'];
const toRemove = connected ? connectedSet : disconnectedSet;
const toAdd = connected ? disconnectedSet : connectedSet;
toRemove.forEach((id) => $(id)?.removeAttribute('disabled'));
toAdd.forEach((id) => $(id)?.setAttribute('disabled', 'true'));
}
function appendLog(...args: any[]) {
const logger = $('log')!;
for (let i = 0; i < arguments.length; i += 1) {
if (typeof args[i] === 'object') {
logger.innerHTML += `${
JSON && JSON.stringify ? JSON.stringify(args[i], undefined, 2) : args[i]
} `;
} else {
logger.innerHTML += `${args[i]} `;
}
}
logger.innerHTML += '\n';
(() => {
logger.scrollTop = logger.scrollHeight;
})();
}