This repository was archived by the owner on Jun 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDeviceManager.ts
671 lines (556 loc) · 23.3 KB
/
DeviceManager.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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import type {
AudioOrVideoType,
CurrentDevices,
DeviceError,
DeviceManagerConfig,
DevicesStatus,
DeviceState,
Errors,
GetMedia,
InitMediaConfig,
Media,
StorageConfig,
UseUserMediaStartConfig,
} from "./types";
import { NOT_FOUND_ERROR, OVERCONSTRAINED_ERROR, parseError, PERMISSION_DENIED, UNHANDLED_ERROR } from "./types";
import { loadObject, saveObject } from "./localStorage";
import {
getExactDeviceConstraint,
prepareConstraints,
prepareMediaTrackConstraints,
toMediaTrackConstraints,
} from "./constraints";
import EventEmitter from "events";
import type TypedEmitter from "typed-emitter";
import type { TrackType } from "./ScreenShareManager";
const removeExact = (
trackConstraints: boolean | MediaTrackConstraints | undefined,
): boolean | MediaTrackConstraints | undefined => {
if (typeof trackConstraints === "object") {
const copy: MediaTrackConstraints = { ...trackConstraints };
delete copy["deviceId"];
return copy;
}
return trackConstraints;
};
const REQUESTING = "Requesting";
const NOT_REQUESTED = "Not requested";
const isVideo = (device: MediaDeviceInfo) => device.kind === "videoinput";
const isAudio = (device: MediaDeviceInfo) => device.kind === "audioinput";
const getDeviceInfo = (trackDeviceId: string | null, devices: MediaDeviceInfo[]): MediaDeviceInfo | null =>
(trackDeviceId && devices.find(({ deviceId }) => trackDeviceId === deviceId)) || null;
const getCurrentDevicesSettings = (
requestedDevices: MediaStream,
mediaDeviceInfos: MediaDeviceInfo[],
): CurrentDevices => {
const currentDevices: CurrentDevices = { videoinput: null, audioinput: null };
for (const track of requestedDevices.getTracks()) {
const settings = track.getSettings();
if (settings.deviceId) {
const currentDevice = mediaDeviceInfos.find((device) => device.deviceId == settings.deviceId);
const kind = currentDevice?.kind ?? null;
if ((currentDevice && kind === "videoinput") || kind === "audioinput") {
currentDevices[kind] = currentDevice ?? null;
}
}
}
return currentDevices;
};
const isDeviceDifferentFromLastSession = (lastDevice: MediaDeviceInfo | null, currentDevice: MediaDeviceInfo | null) =>
lastDevice && (currentDevice?.deviceId !== lastDevice.deviceId || currentDevice?.label !== lastDevice?.label);
const isAnyDeviceDifferentFromLastSession = (
lastVideoDevice: MediaDeviceInfo | null,
lastAudioDevice: MediaDeviceInfo | null,
currentDevices: CurrentDevices | null,
): boolean =>
!!(
(currentDevices?.videoinput &&
isDeviceDifferentFromLastSession(lastVideoDevice, currentDevices?.videoinput || null)) ||
(currentDevices?.audioinput &&
isDeviceDifferentFromLastSession(lastAudioDevice, currentDevices?.audioinput || null))
);
const stopTracks = (requestedDevices: MediaStream) => {
for (const track of requestedDevices.getTracks()) {
track.stop();
}
};
const getMedia = async (constraints: MediaStreamConstraints, previousErrors: Errors): Promise<GetMedia> => {
try {
const mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
return { stream: mediaStream, type: "OK", constraints, previousErrors };
} catch (error: unknown) {
const parsedError: DeviceError | null = parseError(error);
return { error: parsedError, type: "Error", constraints };
}
};
const handleNotFoundError = async (constraints: MediaStreamConstraints): Promise<GetMedia> => {
const withoutVideo = await getMedia(
{ video: false, audio: constraints.audio },
{
video: NOT_FOUND_ERROR,
},
);
if (withoutVideo.type === "OK") {
return withoutVideo;
}
const withoutAudio = await getMedia({ video: constraints.video, audio: false }, { audio: NOT_FOUND_ERROR });
if (withoutAudio.type === "OK") {
return withoutAudio;
}
return await getMedia({ video: false, audio: false }, { audio: NOT_FOUND_ERROR, video: NOT_FOUND_ERROR });
};
const handleOverconstrainedError = async (constraints: MediaStreamConstraints): Promise<GetMedia> => {
const notExactVideo = await getMedia(
{
video: removeExact(constraints.video),
audio: constraints.audio,
},
{ video: OVERCONSTRAINED_ERROR },
);
if (notExactVideo.type === "OK" || notExactVideo.error?.name === "NotAllowedError") {
return notExactVideo;
}
const notExactAudio = await getMedia(
{
video: constraints.video,
audio: removeExact(constraints.audio),
},
{ audio: OVERCONSTRAINED_ERROR },
);
if (notExactAudio.type === "OK" || notExactAudio.error?.name === "NotAllowedError") {
return notExactAudio;
}
return await getMedia(
{ video: removeExact(constraints.video), audio: removeExact(constraints.audio) },
{
video: OVERCONSTRAINED_ERROR,
audio: OVERCONSTRAINED_ERROR,
},
);
};
const handleNotAllowedError = async (constraints: MediaStreamConstraints): Promise<GetMedia> => {
const withoutVideo = await getMedia({ video: false, audio: constraints.audio }, { video: PERMISSION_DENIED });
if (withoutVideo.type === "OK") {
return withoutVideo;
}
const withoutAudio = await getMedia({ video: constraints.video, audio: false }, { audio: PERMISSION_DENIED });
if (withoutAudio.type === "OK") {
return withoutAudio;
}
return await getMedia({ video: false, audio: false }, { video: PERMISSION_DENIED, audio: PERMISSION_DENIED });
};
const getError = (result: GetMedia, type: AudioOrVideoType): DeviceError | null => {
if (result.type === "OK") {
return result.previousErrors[type] || null;
}
console.warn({ name: "Unhandled DeviceManager error", result });
return UNHANDLED_ERROR;
};
const prepareStatus = (
requested: boolean,
track: MediaStreamTrack | null,
deviceError: DeviceError | null,
): [DevicesStatus, DeviceError | null] => {
if (!requested) return ["Not requested", null];
if (track) return ["OK", null];
if (deviceError) return ["Error", deviceError];
return ["Error", null];
};
const prepareDeviceState = (
stream: MediaStream | null,
track: MediaStreamTrack | null,
devices: MediaDeviceInfo[],
error: DeviceError | null,
shouldAsk: boolean,
): DeviceState => {
const deviceInfo = getDeviceInfo(track?.getSettings()?.deviceId || null, devices);
const [devicesStatus, newError] = prepareStatus(shouldAsk, track, error);
return {
devices,
devicesStatus,
media: {
stream: track ? stream : null,
track: track,
deviceInfo,
enabled: !!track,
},
mediaStatus: devicesStatus,
error: error ?? newError,
};
};
const LOCAL_STORAGE_VIDEO_DEVICE_KEY = "last-selected-video-device";
const LOCAL_STORAGE_AUDIO_DEVICE_KEY = "last-selected-audio-device";
const DISABLE_STORAGE_CONFIG: StorageConfig = {
getLastVideoDevice: null,
getLastAudioDevice: null,
saveLastAudioDevice: () => {},
saveLastVideoDevice: () => {},
};
const LOCAL_STORAGE_CONFIG: StorageConfig = {
getLastAudioDevice: () => loadObject<MediaDeviceInfo | null>(LOCAL_STORAGE_AUDIO_DEVICE_KEY, null),
saveLastAudioDevice: (info: MediaDeviceInfo) => saveObject<MediaDeviceInfo>(LOCAL_STORAGE_AUDIO_DEVICE_KEY, info),
getLastVideoDevice: () => loadObject<MediaDeviceInfo | null>(LOCAL_STORAGE_VIDEO_DEVICE_KEY, null),
saveLastVideoDevice: (info: MediaDeviceInfo) => saveObject<MediaDeviceInfo>(LOCAL_STORAGE_VIDEO_DEVICE_KEY, info),
};
export type DeviceManagerEvents = {
managerStarted: (
event: {
trackType: TrackType;
videoConstraints: MediaTrackConstraints | undefined;
audioConstraints: MediaTrackConstraints | undefined;
},
state: DeviceManagerState,
) => void;
managerInitialized: (event: { audio?: DeviceState; video?: DeviceState }, state: DeviceManagerState) => void;
devicesStarted: (
event: {
audio?: DeviceState & { restarting: boolean; constraints?: string | boolean };
video?: DeviceState & { restarting: boolean; constraints?: string | boolean };
},
state: DeviceManagerState,
) => void;
// todo: This event is never used.
deviceReady: (event: { trackType: TrackType; stream: MediaStream }, state: DeviceManagerState) => void;
devicesReady: (
event: {
video: DeviceState & { restarted: boolean };
audio: DeviceState & { restarted: boolean };
},
state: DeviceManagerState,
) => void;
deviceStopped: (event: { trackType: TrackType }, state: DeviceManagerState) => void;
deviceEnabled: (event: { trackType: TrackType }, state: DeviceManagerState) => void;
deviceDisabled: (event: { trackType: TrackType }, state: DeviceManagerState) => void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: (event: any, state: DeviceManagerState) => void;
};
export type DeviceManagerState = {
video: DeviceState;
audio: DeviceState;
};
export type DeviceManagerStatus = "uninitialized" | "initializing" | "initialized" | "error";
export class DeviceManager extends (EventEmitter as new () => TypedEmitter<DeviceManagerEvents>) {
private readonly defaultAudioConstraints: MediaTrackConstraints | undefined;
private readonly defaultVideoConstraints: MediaTrackConstraints | undefined;
private readonly defaultStorageConfig: StorageConfig;
private audioConstraints: MediaTrackConstraints | undefined;
private videoConstraints: MediaTrackConstraints | undefined;
private storageConfig: StorageConfig | undefined;
private status: DeviceManagerStatus = "uninitialized";
public video: DeviceState = {
media: null,
mediaStatus: "Not requested",
devices: null,
devicesStatus: "Not requested",
error: null,
};
public audio: DeviceState = {
media: null,
mediaStatus: "Not requested",
devices: null,
devicesStatus: "Not requested",
error: null,
};
constructor(defaultConfig?: DeviceManagerConfig) {
super();
this.defaultStorageConfig = this.createStorageConfig(defaultConfig?.storage);
this.defaultAudioConstraints = defaultConfig?.audioTrackConstraints
? toMediaTrackConstraints(defaultConfig.audioTrackConstraints)
: undefined;
this.defaultVideoConstraints = defaultConfig?.videoTrackConstraints
? toMediaTrackConstraints(defaultConfig.videoTrackConstraints)
: undefined;
}
private createStorageConfig(storage: boolean | StorageConfig | undefined): StorageConfig {
if (storage === false) return DISABLE_STORAGE_CONFIG;
if (storage === true || storage === undefined) return LOCAL_STORAGE_CONFIG;
return storage;
}
private getVideoConstraints(
currentConstraints: boolean | MediaTrackConstraints | undefined,
): MediaTrackConstraints | undefined {
if (currentConstraints === false) return undefined;
if (currentConstraints === undefined || currentConstraints === true)
return this.videoConstraints ?? this?.defaultVideoConstraints;
return currentConstraints ?? this.videoConstraints ?? this?.defaultVideoConstraints;
}
private getAudioConstraints(
currentConstraints: boolean | MediaTrackConstraints | undefined,
): MediaTrackConstraints | undefined {
if (currentConstraints === false) return undefined;
if (currentConstraints === undefined || currentConstraints === true)
return this.audioConstraints ?? this?.defaultAudioConstraints;
return currentConstraints ?? this.audioConstraints ?? this?.defaultAudioConstraints;
}
public getStatus(): DeviceManagerStatus {
return this.status;
}
public async init(config?: InitMediaConfig): Promise<"initialized" | "error"> {
if (this.status !== "uninitialized") {
return Promise.reject("Device manager already initialized");
}
this.status = "initializing";
if (!navigator?.mediaDevices) {
console.error("Cannot initialize DeviceManager. Navigator is available only in secure contexts");
return Promise.resolve("error");
}
const videoTrackConstraints = this.getVideoConstraints(config?.videoTrackConstraints);
const audioTrackConstraints = this.getAudioConstraints(config?.audioTrackConstraints);
const previousVideoDevice: MediaDeviceInfo | null = this.getLastVideoDevice() ?? null;
const previousAudioDevice: MediaDeviceInfo | null = this.getLastAudioDevice() ?? null;
const shouldAskForVideo = !!videoTrackConstraints;
const shouldAskForAudio = !!audioTrackConstraints;
this.video.devicesStatus =
shouldAskForVideo && videoTrackConstraints ? REQUESTING : this.video.devicesStatus ?? NOT_REQUESTED;
this.audio.devicesStatus =
shouldAskForAudio && audioTrackConstraints ? REQUESTING : this.audio.devicesStatus ?? NOT_REQUESTED;
this.video.mediaStatus = this.video.devicesStatus;
this.audio.mediaStatus = this.audio.devicesStatus;
this.emit(
"managerStarted",
{ trackType: "audiovideo", videoConstraints: videoTrackConstraints, audioConstraints: audioTrackConstraints },
{
audio: this.audio,
video: this.video,
},
);
let requestedDevices: MediaStream | null = null;
const constraints = {
video: shouldAskForVideo && getExactDeviceConstraint(videoTrackConstraints, previousVideoDevice?.deviceId),
audio: shouldAskForAudio && getExactDeviceConstraint(audioTrackConstraints, previousAudioDevice?.deviceId),
};
let result: GetMedia = await getMedia(constraints, {});
if (result.type === "Error" && result.error?.name === "NotFoundError") {
result = await handleNotFoundError(constraints);
}
if (result.type === "Error" && result.error?.name === "OverconstrainedError") {
result = await handleOverconstrainedError(result.constraints);
}
if (result.type === "Error" && result.error?.name === "NotAllowedError") {
result = await handleNotAllowedError(result.constraints);
}
const mediaDeviceInfos: MediaDeviceInfo[] = await navigator.mediaDevices.enumerateDevices();
if (result.type === "OK") {
requestedDevices = result.stream;
// Safari changes deviceId between sessions, therefore we cannot rely on deviceId for identification purposes.
// We can switch a random device that comes from safari to one that has the same label as the one used in the previous session.
const currentDevices = getCurrentDevicesSettings(requestedDevices, mediaDeviceInfos);
const shouldCorrectDevices = isAnyDeviceDifferentFromLastSession(
previousVideoDevice,
previousAudioDevice,
currentDevices,
);
if (shouldCorrectDevices) {
const videoIdToStart = mediaDeviceInfos.find((info) => info.label === previousVideoDevice?.label)?.deviceId;
const audioIdToStart = mediaDeviceInfos.find((info) => info.label === previousAudioDevice?.label)?.deviceId;
if (videoIdToStart || audioIdToStart) {
stopTracks(requestedDevices);
const exactConstraints: MediaStreamConstraints = {
video: !!result.constraints.video && prepareConstraints(videoIdToStart, videoTrackConstraints),
audio: !!result.constraints.video && prepareConstraints(audioIdToStart, audioTrackConstraints),
};
const correctedResult = await getMedia(exactConstraints, result.previousErrors);
if (correctedResult.type === "OK") {
requestedDevices = correctedResult.stream;
} else {
console.error("Device Manager unexpected error");
}
}
}
}
const video: DeviceState = prepareDeviceState(
requestedDevices,
requestedDevices?.getVideoTracks()[0] || null,
mediaDeviceInfos.filter(isVideo),
getError(result, "video"),
shouldAskForVideo,
);
const audio: DeviceState = prepareDeviceState(
requestedDevices,
requestedDevices?.getAudioTracks()[0] || null,
mediaDeviceInfos.filter(isAudio),
getError(result, "audio"),
shouldAskForAudio,
);
this.video = video;
this.audio = audio;
if (video.media?.deviceInfo) {
this.saveLastVideoDevice(video.media?.deviceInfo);
}
if (audio.media?.deviceInfo) {
this.saveLastAudioDevice(audio.media?.deviceInfo);
}
this.setupOnEndedCallback();
this.emit("managerInitialized", { audio, video }, { audio: this.audio, video: this.video });
return Promise.resolve("initialized");
}
private setupOnEndedCallback() {
if (this.video?.media?.track) {
this.video.media.track.addEventListener(
"ended",
async (event) => await this.onTrackEnded("video", (event.target as MediaStreamTrack).id),
);
}
if (this.audio?.media?.track) {
this.audio.media.track.addEventListener(
"ended",
async (event) => await this.onTrackEnded("audio", (event.target as MediaStreamTrack).id),
);
}
}
private onTrackEnded = async (type: AudioOrVideoType, trackId: string) => {
if (trackId === this?.[type].media?.track?.id) {
await this.stop(type);
}
};
private getLastVideoDevice(): MediaDeviceInfo | null {
return this.storageConfig?.getLastVideoDevice?.() ?? this.defaultStorageConfig?.getLastVideoDevice?.() ?? null;
}
private saveLastVideoDevice(info: MediaDeviceInfo) {
if (this.storageConfig?.saveLastVideoDevice) {
this.storageConfig.saveLastVideoDevice(info);
} else {
this.defaultStorageConfig.saveLastVideoDevice?.(info);
}
}
private saveLastAudioDevice(info: MediaDeviceInfo) {
if (this.storageConfig?.saveLastAudioDevice) {
this.storageConfig.saveLastAudioDevice(info);
} else {
this.defaultStorageConfig.saveLastAudioDevice?.(info);
}
}
private getLastAudioDevice(): MediaDeviceInfo | null {
return this.storageConfig?.getLastAudioDevice?.() ?? this.defaultStorageConfig?.getLastAudioDevice?.() ?? null;
}
// todo `audioDeviceId / videoDeviceId === true` means use last device
public async start({ audioDeviceId, videoDeviceId }: UseUserMediaStartConfig) {
const shouldRestartVideo = !!videoDeviceId && videoDeviceId !== this.video.media?.deviceInfo?.deviceId;
const shouldRestartAudio = !!audioDeviceId && audioDeviceId !== this.audio.media?.deviceInfo?.deviceId;
const newVideoDevice = videoDeviceId === true ? this.getLastVideoDevice?.()?.deviceId || true : videoDeviceId;
const newAudioDevice = audioDeviceId === true ? this.getLastAudioDevice?.()?.deviceId || true : audioDeviceId;
const videoTrackConstraints = this.getVideoConstraints(true);
const audioTrackConstraints = this.getAudioConstraints(true);
const exactConstraints: MediaStreamConstraints = {
video: shouldRestartVideo && prepareMediaTrackConstraints(newVideoDevice, videoTrackConstraints),
audio: shouldRestartAudio && prepareMediaTrackConstraints(newAudioDevice, audioTrackConstraints),
};
if (!exactConstraints.video && !exactConstraints.audio) return;
if (exactConstraints.audio) {
this.audio.mediaStatus = "Requesting";
}
if (exactConstraints.video) {
this.video.mediaStatus = "Requesting";
}
this.emit(
"devicesStarted",
{
audio: { ...this.audio, restarting: shouldRestartAudio, constraints: audioDeviceId },
video: { ...this.video, restarting: shouldRestartVideo, constraints: videoDeviceId },
},
{ audio: this.audio, video: this.video },
);
const result = await getMedia(exactConstraints, {});
if (result.type === "OK") {
const stream = result.stream;
const currentVideoDeviceId = result.stream.getVideoTracks()?.[0]?.getSettings()?.deviceId;
const videoInfo = currentVideoDeviceId ? getDeviceInfo(currentVideoDeviceId, this.video.devices ?? []) : null;
if (videoInfo) {
this.saveLastVideoDevice?.(videoInfo);
}
const currentAudioDeviceId = result.stream.getAudioTracks()?.[0]?.getSettings()?.deviceId;
const audioInfo = currentAudioDeviceId ? getDeviceInfo(currentAudioDeviceId, this.audio.devices ?? []) : null;
if (audioInfo) {
this.saveLastAudioDevice(audioInfo);
}
// The device manager assumes that there is only one audio and video track.
// All previous tracks are deactivated even if the browser is able to handle multiple active sessions. (Chrome, Firefox)
//
// Safari always deactivates the track and emits the `ended` event.
// Its handling is asynchronous and can be executed even before returning a value from the re-execution of `getUserMedia`.
// In such a case, the tracks are already deactivated at this point (logic in `onTrackEnded` method).
// The track is null, so the stop method will not execute.
//
// However, if Safari has not yet handled this event, the tracks are manually stopped at this point.
// Manually stopping tracks on its own does not generate the `ended` event.
// The ended event in Safari has already been emitted and will be handled in the future.
// Therefore, in the `onTrackEnded` method, events for already stopped tracks are filtered out to prevent the state from being damaged.
if (shouldRestartVideo) {
this.video?.media?.track?.stop();
}
if (shouldRestartAudio) {
this.audio?.media?.track?.stop();
}
const videoMedia: Media | null = shouldRestartVideo
? {
stream: stream,
track: stream.getVideoTracks()[0] || null,
deviceInfo: videoInfo,
enabled: true,
}
: this.video.media;
const audioMedia: Media | null = shouldRestartAudio
? {
stream: stream,
track: stream.getAudioTracks()[0] || null,
deviceInfo: audioInfo,
enabled: true,
}
: this.audio.media;
this.video.media = videoMedia;
this.audio.media = audioMedia;
this.setupOnEndedCallback();
if (exactConstraints.audio) {
this.audio.mediaStatus = "OK";
}
if (exactConstraints.video) {
this.video.mediaStatus = "OK";
}
this.emit(
"devicesReady",
{
video: { ...this.video, restarted: shouldRestartVideo },
audio: { ...this.audio, restarted: shouldRestartAudio },
},
{ audio: this.audio, video: this.video },
);
} else {
const parsedError = result.error;
const event = {
parsedError,
constraints: exactConstraints,
};
const videoError = exactConstraints.video ? parsedError : this.video.error;
const audioError = exactConstraints.audio ? parsedError : this.audio.error;
this.video.error = videoError;
this.audio.error = audioError;
this.emit("error", event, { audio: this.audio, video: this.video });
}
}
public async stop(type: AudioOrVideoType) {
this[type].media?.track?.stop();
this[type].media = null;
this.emit("deviceStopped", { trackType: type }, { audio: this.audio, video: this.video });
}
public setEnable(type: AudioOrVideoType, value: boolean) {
if (!this[type].media || !this[type].media?.track) {
return;
}
this[type!].media!.track!.enabled = value;
this[type!].media!.enabled = value;
if (value) {
this.emit("deviceEnabled", { trackType: type }, { audio: this.audio, video: this.video });
} else {
this.emit("deviceDisabled", { trackType: type }, { audio: this.audio, video: this.video });
}
}
public setConfig(config?: DeviceManagerConfig) {
this.storageConfig = this.createStorageConfig(config?.storage);
this.audioConstraints = config?.audioTrackConstraints
? toMediaTrackConstraints(config.audioTrackConstraints)
: undefined;
this.videoConstraints = config?.videoTrackConstraints
? toMediaTrackConstraints(config.videoTrackConstraints)
: undefined;
}
}