-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsimple-room.ts
525 lines (470 loc) · 14.9 KB
/
simple-room.ts
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Infiniscene, Inc. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* -------------------------------------------------------------------------------------------- */
import { webrtcManager } from './index'
import { DataType, SpecialEvent } from './room-context'
import {
RoomEvent,
Participant,
LocalTrackPublication,
TrackPublication,
Track,
LocalTrack,
DataPacket_Kind,
} from 'livekit-client'
import { SDK } from '../namespaces'
import { log } from '../context'
const encoder = new TextEncoder()
const decoder = new TextDecoder()
const simpleRooms = new Map<string, SDK.Room>()
// TODO: Dispose of listeners when no longer needed
export const getRoom = (id: string) => {
if (!id) return null
if (simpleRooms.get(id)) return simpleRooms.get(id)
const room = webrtcManager.rooms.get(id)
if (!room) return null
const livekit = room.livekitRoom
const localParticipant = livekit?.localParticipant
// @ts-ignore
window.__StudioRoom = livekit
if (!localParticipant) log.warn('No local participant!')
const listeners = {
useTracks: new Set<Function>(),
useTrack: new Map<Function, string>(),
useParticipants: new Set<Function>(),
useParticipant: new Map<Function, string>(),
useChatHistory: new Set<Function>(),
}
type FullTrack = TrackPublication & { participant: Participant }
let latest = {
tracks: [] as FullTrack[],
participants: [] as Participant[],
result: {
participants: [] as SDK.Participant[],
tracks: [] as SDK.Track[],
},
chat: room.chatHistory,
}
const update = () => {
const participants = room.participants
const guestParticipantMetadata = room.guestParticipantMetadata
const tracks = participants.flatMap((participant: Participant) =>
participant.getTrackPublications().map((pub) => ({
...pub,
participant,
})),
) as FullTrack[]
const result = {
participants: participants.map((x) => {
// /* Updating the metadata of the participants in the room. */
const existingGuestParticipantMetadata = guestParticipantMetadata.find(
(g) => g.participantId === x.identity,
)
if (existingGuestParticipantMetadata) {
let participantMetadataJson = JSON.parse(x.metadata)
participantMetadataJson = {
...participantMetadataJson,
...existingGuestParticipantMetadata.metadata,
}
x.metadata = JSON.stringify(participantMetadataJson)
}
const meta = JSON.parse(x.metadata)
return {
id: x.identity,
isSelf: x === localParticipant,
connectionQuality: x.connectionQuality,
displayName: meta.displayName || x.name,
joinedAt: x.joinedAt,
role: meta.participantRole,
meta,
trackIds: tracks
.filter((p) => p.participant.sid === x.sid)
.map((x) => x.trackSid),
}
}) as SDK.Participant[],
tracks: tracks.map((x) => {
const meta = JSON.parse(x?.participant?.metadata)
/* A function that takes in a track and returns a track object. */
return {
mediaStreamTrack: x.track?.mediaStreamTrack,
id: x.trackSid,
participantId: x.participant?.identity,
isMuted: x.track?.isMuted,
type: x.source,
isExternal: Boolean(meta?.[x.trackSid]),
}
}) as SDK.Track[],
}
latest = {
tracks,
participants,
result,
chat: room.chatHistory,
}
// TODO: (Perf) Only call if something has changed
listeners.useTracks.forEach((cb) => cb(result.tracks))
listeners.useTrack.forEach((id, cb) => {
// TODO: subscribe to TrackEvents when track exists
// tracks.forEach(x => x.on(''))
cb(getTrack(id))
})
listeners.useParticipants.forEach((cb) => cb(result.participants))
listeners.useParticipant.forEach((id, cb) => {
cb(getParticipant(id))
})
listeners.useChatHistory.forEach((cb) => {
cb(latest.chat)
})
}
/** events on which we will update our simple room */
const updateEvents = [
RoomEvent.ParticipantConnected,
RoomEvent.ParticipantDisconnected,
RoomEvent.ParticipantMetadataChanged,
RoomEvent.Disconnected,
RoomEvent.TrackSubscribed,
RoomEvent.TrackUnsubscribed,
RoomEvent.LocalTrackPublished,
RoomEvent.LocalTrackUnpublished,
RoomEvent.ConnectionQualityChanged,
RoomEvent.TrackMuted,
RoomEvent.TrackUnmuted,
RoomEvent.TrackStreamStateChanged,
]
/* Subscribing to the RoomEvent.DataReceived event.
* Update the room participant info when Participant metadata gets updated
*/
room.subscribeToRoomEvent(
RoomEvent.DataReceived,
(payload, participant: Participant, kind: DataPacket_Kind) => {
const strData = decoder.decode(payload)
const data = JSON.parse(strData)
if (data.type === DataType.ParticipantMetadataUpdate) {
update()
}
},
)
const unsubscribers = updateEvents.map((evt) =>
room.subscribeToRoomEvent(evt, () => update()),
)
// Also subscribe to chat
unsubscribers.push(room.subscribeToSpecialEvent(SpecialEvent.Chat, update))
const unsubscribeFromAll = () => {
unsubscribers.forEach((cb) => cb())
}
const getTrack = (id: string) => {
return latest.result.tracks.find((x) => x.id === id)
}
const getParticipant = (id: string) => {
return latest.result.participants.find((x) => x.id === id)
}
const setTrackEnabled = (id: string, enabled: boolean) => {
const track = localParticipant.getTrackPublications().find((x) => {
return x.trackSid === id
})
if (track) {
if (enabled) {
// @ts-ignore
track.mute()
} else {
// @ts-ignore
track.unmute()
}
}
}
let settingCamera: boolean
let settingMic: boolean
const simpleRoom = {
id: room.roomName,
participantId: localParticipant.identity,
setTrackEnabled,
setCameraEnabled: (enabled = true) => {
return localParticipant.setCameraEnabled(enabled)
},
setMicrophoneEnabled: (enabled = true) => {
return localParticipant.setMicrophoneEnabled(enabled)
},
setCamera: async (options = {}) => {
if (settingCamera) {
log.warn('Cannot set camera until previous has resolved')
return
}
settingCamera = true
let published: LocalTrackPublication[]
try {
const existingWebcams = localParticipant
.getTrackPublications()
.filter((x) => {
return x?.source === Track.Source.Camera
})
const existingPrimaryWebCam = existingWebcams.find((x) => {
const track = getTrack(x?.trackSid)
return !track.isExternal
})
const tracks = await localParticipant.createTracks({
video: {
deviceId: {
exact: options.deviceId?.toString(),
},
resolution: options.resolution || {
width: 1280,
height: 720,
frameRate: 30,
aspectRatio: 16 / 9,
},
},
})
if (existingPrimaryWebCam?.isMuted) {
tracks.forEach((x) => {
x.mute()
})
}
published = await Promise.all(
tracks.map((x) => localParticipant.publishTrack(x)),
)
if (existingPrimaryWebCam) {
localParticipant.unpublishTrack(
existingPrimaryWebCam.track as LocalTrack,
)
}
} catch (e) {
throw e
} finally {
settingCamera = false
return getTrack(published[0]?.trackSid)
}
},
setMicrophone: async (options) => {
if (settingMic) {
log.warn('Cannot set microphone until previous has resolved')
return
}
settingMic = true
let published: LocalTrackPublication[]
try {
const existingMicroPhones = localParticipant
.getTrackPublications()
.filter((x) => {
return x.source === Track.Source.Microphone
})
const existingPrimaryMicrophone = existingMicroPhones.find((x) => {
const track = getTrack(x?.trackSid)
return !track.isExternal
})
const tracks = await localParticipant.createTracks({
audio: options || true,
})
if (existingPrimaryMicrophone?.isMuted) {
tracks.forEach((x) => {
x.mute()
})
}
published = await Promise.all(
tracks.map((x) => localParticipant.publishTrack(x)),
)
if (existingPrimaryMicrophone) {
localParticipant.unpublishTrack(
existingPrimaryMicrophone.track as LocalTrack,
)
}
} catch (e) {
throw e
} finally {
settingMic = false
return getTrack(published[0]?.trackSid)
}
},
addMicrophone: async (options) => {
if (settingMic) {
log.warn('Cannot set microphone until previous has resolved')
return
}
settingMic = true
const tracks = await localParticipant.createTracks({
audio: options || true,
})
const audioTracks = localParticipant
.getTrackPublications()
.filter((track) => {
return track.source === Track.Source.Microphone
})
const inUseTrack = audioTracks.find((x) => {
const track = getTrack(x?.trackSid)
track?.mediaStreamTrack?.getSettings()?.deviceId === options.deviceId &&
track?.isExternal
})
if (inUseTrack?.isMuted) {
tracks.forEach((x) => {
x.mute()
})
}
const published = await Promise.all(
tracks.map((x) => localParticipant.publishTrack(x)),
)
if (inUseTrack) {
localParticipant.unpublishTrack(inUseTrack.track as LocalTrack)
}
settingMic = false
return getTrack(published[0]?.trackSid)
},
addCamera: async (options = {}) => {
const tracks = await localParticipant.createTracks({
video: {
deviceId: {
exact: options.deviceId?.toString(),
},
resolution: options.resolution || {
width: 1280,
height: 720,
frameRate: 30,
aspectRatio: 16 / 9,
},
},
})
const inUseTrack = localParticipant.getTrackPublications().find((x) => {
return (
x?.source === Track.Source.Camera &&
x?.track?.mediaStreamTrack?.getSettings()?.deviceId ===
options.deviceId
)
})
if (inUseTrack?.isMuted) {
tracks.forEach((x) => {
x.mute()
})
}
const published = await Promise.all(
tracks.map((x) => localParticipant.publishTrack(x)),
)
if (inUseTrack) {
localParticipant.unpublishTrack(inUseTrack.track as LocalTrack)
}
settingMic = false
return getTrack(published[0]?.trackSid)
},
addScreen: async (options = { audio: false }) => {
const tracks = await localParticipant.createScreenTracks(options)
const published = await Promise.all(
tracks.map((x) => localParticipant.publishTrack(x)),
)
const screen = published.find((x) => x.kind === 'video')
const audio = published.find((x) => x.kind === 'audio')
return {
screen: getTrack(screen?.trackSid),
audio: getTrack(audio?.trackSid),
}
},
removeTrack: async (id: string) => {
const track = latest.tracks.find((x) => x.trackSid === id)
localParticipant.unpublishTrack(track.track as LocalTrack)
},
/* Setting the local participant metadata. */
setLocalParticipantMetadata: async (id, meta) => {
const data = JSON.stringify(meta)
const encoded = encoder.encode(
JSON.stringify({
metadata: meta,
type: DataType.ParticipantMetadataUpdate,
participantId: id,
}),
)
localParticipant.setMetadata(data)
return await localParticipant.publishData(encoded, { reliable: true })
},
setParticipantMetadata: (id, meta) => {
return room.updateParticipant(id, meta)
},
kickParticipant: room.kickParticipant,
muteTrackAsAdmin: room.muteTrackAsAdmin,
sendChatMessage: room.sendChatMessage,
// Callbacks
getTracks: () => latest.result.tracks,
useTracks: (cb) => {
listeners.useTracks.add(cb)
cb(latest.result.tracks)
return () => {
listeners.useTracks.delete(cb)
}
},
getTrack,
useTrack: (id, cb) => {
listeners.useTrack.set(cb, id)
cb(getTrack(id))
return () => {
listeners.useTrack.delete(cb)
}
},
getParticipant,
getParticipants: () => latest.result.participants,
useParticipants: (cb) => {
listeners.useParticipants.add(cb)
cb(latest.result.participants)
return () => {
listeners.useParticipants.delete(cb)
}
},
useParticipant: (id, cb) => {
listeners.useParticipant.set(cb, id)
cb(getParticipant(id))
return () => {
listeners.useTrack.delete(cb)
}
},
useChatHistory: (cb) => {
listeners.useChatHistory.add(cb)
cb(latest.chat)
return () => {
listeners.useChatHistory.delete(cb)
}
},
useActiveSpeakers: (cb) => {
const fn = (activeSpeakers: Participant[]) => {
cb(activeSpeakers.map((x) => x.identity))
}
room.livekitRoom?.on(RoomEvent.ActiveSpeakersChanged, fn)
fn(room.livekitRoom?.activeSpeakers)
return () => {
room.livekitRoom?.off(RoomEvent.ActiveSpeakersChanged, fn)
}
},
sendData: (data, recipientIds = []) => {
const encoded = encoder.encode(JSON.stringify(data))
const participants = recipientIds
?.map((x) => room.livekitRoom?.getParticipantByIdentity(x))
.filter(Boolean)
return localParticipant.publishData(encoded, {
reliable: true,
destinationIdentities: participants.map((x) => x.identity),
})
},
onData: (cb) => {
const fn = (encoded: any, participant: Participant) => {
const data = JSON.parse(decoder.decode(encoded))
cb(data, participant?.identity)
}
room.livekitRoom?.on(RoomEvent.DataReceived, fn)
return () => {
room.livekitRoom?.off(RoomEvent.DataReceived, fn)
}
},
connect: () => {
return room.connect()
},
disconnect: () => {
return room.livekitRoom?.disconnect()
},
onDisconnected: (cb) => {
room.livekitRoom?.on(RoomEvent.Disconnected, cb)
return () => {
room.livekitRoom?.off(RoomEvent.DataReceived, cb)
}
},
setAudioOutput: (deviceId: string) => {
return room.livekitRoom?.switchActiveDevice('audiooutput', deviceId)
},
} as SDK.Room
update()
simpleRooms.set(id, simpleRoom)
return simpleRoom
}