-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathLocalParticipant.ts
2059 lines (1888 loc) · 66.3 KB
/
LocalParticipant.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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AddTrackRequest,
ChatMessage as ChatMessageModel,
Codec,
DataPacket,
DataPacket_Kind,
Encryption_Type,
ParticipantInfo,
ParticipantPermission,
RequestResponse,
RequestResponse_Reason,
RpcAck,
RpcRequest,
RpcResponse,
SimulcastCodec,
SipDTMF,
SubscribedQualityUpdate,
TrackInfo,
TrackUnpublishedResponse,
UserPacket,
protoInt64,
} from '@livekit/protocol';
import type { InternalRoomOptions } from '../../options';
import { PCTransportState } from '../PCTransportManager';
import type RTCEngine from '../RTCEngine';
import { defaultVideoCodec } from '../defaults';
import {
DeviceUnsupportedError,
LivekitError,
SignalRequestError,
TrackInvalidError,
UnexpectedConnectionState,
} from '../errors';
import { EngineEvent, ParticipantEvent, TrackEvent } from '../events';
import {
MAX_PAYLOAD_BYTES,
type PerformRpcParams,
RpcError,
type RpcInvocationData,
byteLength,
} from '../rpc';
import LocalAudioTrack from '../track/LocalAudioTrack';
import LocalTrack from '../track/LocalTrack';
import LocalTrackPublication from '../track/LocalTrackPublication';
import LocalVideoTrack, { videoLayersFromEncodings } from '../track/LocalVideoTrack';
import { Track } from '../track/Track';
import type {
AudioCaptureOptions,
BackupVideoCodec,
CreateLocalTracksOptions,
ScreenShareCaptureOptions,
TrackPublishOptions,
VideoCaptureOptions,
} from '../track/options';
import { ScreenSharePresets, VideoPresets, isBackupCodec } from '../track/options';
import {
constraintsForOptions,
extractProcessorsFromOptions,
getLogContextFromTrack,
mergeDefaultOptions,
mimeTypeToVideoCodecString,
screenCaptureToDisplayMediaStreamOptions,
} from '../track/utils';
import type { ChatMessage, DataPublishOptions } from '../types';
import {
Future,
compareVersions,
isAudioTrack,
isE2EESimulcastSupported,
isFireFox,
isLocalAudioTrack,
isLocalTrack,
isLocalVideoTrack,
isSVCCodec,
isSafari17,
isVideoTrack,
isWeb,
sleep,
supportsAV1,
supportsVP9,
} from '../utils';
import Participant from './Participant';
import type { ParticipantTrackPermission } from './ParticipantTrackPermission';
import { trackPermissionToProto } from './ParticipantTrackPermission';
import {
computeTrackBackupEncodings,
computeVideoEncodings,
getDefaultDegradationPreference,
mediaTrackToLocalTrack,
} from './publishUtils';
export default class LocalParticipant extends Participant {
audioTrackPublications: Map<string, LocalTrackPublication>;
videoTrackPublications: Map<string, LocalTrackPublication>;
/** map of track sid => all published tracks */
trackPublications: Map<string, LocalTrackPublication>;
/** @internal */
engine: RTCEngine;
/** @internal */
activeDeviceMap: Map<MediaDeviceKind, string>;
private pendingPublishing = new Set<Track.Source>();
private pendingPublishPromises = new Map<LocalTrack, Promise<LocalTrackPublication>>();
private republishPromise: Promise<void> | undefined;
private cameraError: Error | undefined;
private microphoneError: Error | undefined;
private participantTrackPermissions: Array<ParticipantTrackPermission> = [];
private allParticipantsAllowedToSubscribe: boolean = true;
// keep a pointer to room options
private roomOptions: InternalRoomOptions;
private encryptionType: Encryption_Type = Encryption_Type.NONE;
private reconnectFuture?: Future<void>;
private pendingSignalRequests: Map<
number,
{
resolve: (arg: any) => void;
reject: (reason: LivekitError) => void;
values: Partial<Record<keyof LocalParticipant, any>>;
}
>;
private enabledPublishVideoCodecs: Codec[] = [];
private rpcHandlers: Map<string, (data: RpcInvocationData) => Promise<string>> = new Map();
private pendingAcks = new Map<string, { resolve: () => void; participantIdentity: string }>();
private pendingResponses = new Map<
string,
{
resolve: (payload: string | null, error: RpcError | null) => void;
participantIdentity: string;
}
>();
/** @internal */
constructor(sid: string, identity: string, engine: RTCEngine, options: InternalRoomOptions) {
super(sid, identity, undefined, undefined, undefined, {
loggerName: options.loggerName,
loggerContextCb: () => this.engine.logContext,
});
this.audioTrackPublications = new Map();
this.videoTrackPublications = new Map();
this.trackPublications = new Map();
this.engine = engine;
this.roomOptions = options;
this.setupEngine(engine);
this.activeDeviceMap = new Map([
['audioinput', 'default'],
['videoinput', 'default'],
['audiooutput', 'default'],
]);
this.pendingSignalRequests = new Map();
}
get lastCameraError(): Error | undefined {
return this.cameraError;
}
get lastMicrophoneError(): Error | undefined {
return this.microphoneError;
}
get isE2EEEnabled(): boolean {
return this.encryptionType !== Encryption_Type.NONE;
}
getTrackPublication(source: Track.Source): LocalTrackPublication | undefined {
const track = super.getTrackPublication(source);
if (track) {
return track as LocalTrackPublication;
}
}
getTrackPublicationByName(name: string): LocalTrackPublication | undefined {
const track = super.getTrackPublicationByName(name);
if (track) {
return track as LocalTrackPublication;
}
}
/**
* @internal
*/
setupEngine(engine: RTCEngine) {
this.engine = engine;
this.engine.on(EngineEvent.RemoteMute, (trackSid: string, muted: boolean) => {
const pub = this.trackPublications.get(trackSid);
if (!pub || !pub.track) {
return;
}
if (muted) {
pub.mute();
} else {
pub.unmute();
}
});
this.engine
.on(EngineEvent.Connected, this.handleReconnected)
.on(EngineEvent.SignalRestarted, this.handleReconnected)
.on(EngineEvent.SignalResumed, this.handleReconnected)
.on(EngineEvent.Restarting, this.handleReconnecting)
.on(EngineEvent.Resuming, this.handleReconnecting)
.on(EngineEvent.LocalTrackUnpublished, this.handleLocalTrackUnpublished)
.on(EngineEvent.SubscribedQualityUpdate, this.handleSubscribedQualityUpdate)
.on(EngineEvent.Disconnected, this.handleDisconnected)
.on(EngineEvent.SignalRequestResponse, this.handleSignalRequestResponse)
.on(EngineEvent.DataPacketReceived, this.handleDataPacket);
}
private handleReconnecting = () => {
if (!this.reconnectFuture) {
this.reconnectFuture = new Future<void>();
}
};
private handleReconnected = () => {
this.reconnectFuture?.resolve?.();
this.reconnectFuture = undefined;
this.updateTrackSubscriptionPermissions();
};
private handleDisconnected = () => {
if (this.reconnectFuture) {
this.reconnectFuture.promise.catch((e) => this.log.warn(e.message, this.logContext));
this.reconnectFuture?.reject?.('Got disconnected during reconnection attempt');
this.reconnectFuture = undefined;
}
};
private handleSignalRequestResponse = (response: RequestResponse) => {
const { requestId, reason, message } = response;
const targetRequest = this.pendingSignalRequests.get(requestId);
if (targetRequest) {
if (reason !== RequestResponse_Reason.OK) {
targetRequest.reject(new SignalRequestError(message, reason));
}
this.pendingSignalRequests.delete(requestId);
}
};
private handleDataPacket = (packet: DataPacket) => {
switch (packet.value.case) {
case 'rpcRequest':
let rpcRequest = packet.value.value as RpcRequest;
this.handleIncomingRpcRequest(
packet.participantIdentity,
rpcRequest.id,
rpcRequest.method,
rpcRequest.payload,
rpcRequest.responseTimeoutMs,
rpcRequest.version,
);
break;
case 'rpcResponse':
let rpcResponse = packet.value.value as RpcResponse;
let payload: string | null = null;
let error: RpcError | null = null;
if (rpcResponse.value.case === 'payload') {
payload = rpcResponse.value.value;
} else if (rpcResponse.value.case === 'error') {
error = RpcError.fromProto(rpcResponse.value.value);
}
this.handleIncomingRpcResponse(rpcResponse.requestId, payload, error);
break;
case 'rpcAck':
let rpcAck = packet.value.value as RpcAck;
this.handleIncomingRpcAck(rpcAck.requestId);
break;
}
};
/**
* Sets and updates the metadata of the local participant.
* Note: this requires `canUpdateOwnMetadata` permission.
* method will throw if the user doesn't have the required permissions
* @param metadata
*/
async setMetadata(metadata: string): Promise<void> {
await this.requestMetadataUpdate({ metadata });
}
/**
* Sets and updates the name of the local participant.
* Note: this requires `canUpdateOwnMetadata` permission.
* method will throw if the user doesn't have the required permissions
* @param metadata
*/
async setName(name: string): Promise<void> {
await this.requestMetadataUpdate({ name });
}
/**
* Set or update participant attributes. It will make updates only to keys that
* are present in `attributes`, and will not override others.
* Note: this requires `canUpdateOwnMetadata` permission.
* @param attributes attributes to update
*/
async setAttributes(attributes: Record<string, string>) {
await this.requestMetadataUpdate({ attributes });
}
private async requestMetadataUpdate({
metadata,
name,
attributes,
}: {
metadata?: string;
name?: string;
attributes?: Record<string, string>;
}) {
return new Promise<void>(async (resolve, reject) => {
try {
let isRejected = false;
const requestId = await this.engine.client.sendUpdateLocalMetadata(
metadata ?? this.metadata ?? '',
name ?? this.name ?? '',
attributes,
);
const startTime = performance.now();
this.pendingSignalRequests.set(requestId, {
resolve,
reject: (error: LivekitError) => {
reject(error);
isRejected = true;
},
values: { name, metadata, attributes },
});
while (performance.now() - startTime < 5_000 && !isRejected) {
if (
(!name || this.name === name) &&
(!metadata || this.metadata === metadata) &&
(!attributes ||
Object.entries(attributes).every(
([key, value]) =>
this.attributes[key] === value || (value === '' && !this.attributes[key]),
))
) {
this.pendingSignalRequests.delete(requestId);
resolve();
return;
}
await sleep(50);
}
reject(
new SignalRequestError('Request to update local metadata timed out', 'TimeoutError'),
);
} catch (e: any) {
if (e instanceof Error) reject(e);
}
});
}
/**
* Enable or disable a participant's camera track.
*
* If a track has already published, it'll mute or unmute the track.
* Resolves with a `LocalTrackPublication` instance if successful and `undefined` otherwise
*/
setCameraEnabled(
enabled: boolean,
options?: VideoCaptureOptions,
publishOptions?: TrackPublishOptions,
): Promise<LocalTrackPublication | undefined> {
return this.setTrackEnabled(Track.Source.Camera, enabled, options, publishOptions);
}
/**
* Enable or disable a participant's microphone track.
*
* If a track has already published, it'll mute or unmute the track.
* Resolves with a `LocalTrackPublication` instance if successful and `undefined` otherwise
*/
setMicrophoneEnabled(
enabled: boolean,
options?: AudioCaptureOptions,
publishOptions?: TrackPublishOptions,
): Promise<LocalTrackPublication | undefined> {
return this.setTrackEnabled(Track.Source.Microphone, enabled, options, publishOptions);
}
/**
* Start or stop sharing a participant's screen
* Resolves with a `LocalTrackPublication` instance if successful and `undefined` otherwise
*/
setScreenShareEnabled(
enabled: boolean,
options?: ScreenShareCaptureOptions,
publishOptions?: TrackPublishOptions,
): Promise<LocalTrackPublication | undefined> {
return this.setTrackEnabled(Track.Source.ScreenShare, enabled, options, publishOptions);
}
/** @internal */
setPermissions(permissions: ParticipantPermission): boolean {
const prevPermissions = this.permissions;
const changed = super.setPermissions(permissions);
if (changed && prevPermissions) {
this.emit(ParticipantEvent.ParticipantPermissionsChanged, prevPermissions);
}
return changed;
}
/** @internal */
async setE2EEEnabled(enabled: boolean) {
this.encryptionType = enabled ? Encryption_Type.GCM : Encryption_Type.NONE;
await this.republishAllTracks(undefined, false);
}
/**
* Enable or disable publishing for a track by source. This serves as a simple
* way to manage the common tracks (camera, mic, or screen share).
* Resolves with LocalTrackPublication if successful and void otherwise
*/
private async setTrackEnabled(
source: Extract<Track.Source, Track.Source.Camera>,
enabled: boolean,
options?: VideoCaptureOptions,
publishOptions?: TrackPublishOptions,
): Promise<LocalTrackPublication | undefined>;
private async setTrackEnabled(
source: Extract<Track.Source, Track.Source.Microphone>,
enabled: boolean,
options?: AudioCaptureOptions,
publishOptions?: TrackPublishOptions,
): Promise<LocalTrackPublication | undefined>;
private async setTrackEnabled(
source: Extract<Track.Source, Track.Source.ScreenShare>,
enabled: boolean,
options?: ScreenShareCaptureOptions,
publishOptions?: TrackPublishOptions,
): Promise<LocalTrackPublication | undefined>;
private async setTrackEnabled(
source: Track.Source,
enabled: true,
options?: VideoCaptureOptions | AudioCaptureOptions | ScreenShareCaptureOptions,
publishOptions?: TrackPublishOptions,
) {
this.log.debug('setTrackEnabled', { ...this.logContext, source, enabled });
if (this.republishPromise) {
await this.republishPromise;
}
let track = this.getTrackPublication(source);
if (enabled) {
if (track) {
await track.unmute();
} else {
let localTracks: Array<LocalTrack> | undefined;
if (this.pendingPublishing.has(source)) {
const pendingTrack = await this.waitForPendingPublicationOfSource(source);
if (!pendingTrack) {
this.log.info('waiting for pending publication promise timed out', {
...this.logContext,
source,
});
}
await pendingTrack?.unmute();
return pendingTrack;
}
this.pendingPublishing.add(source);
try {
switch (source) {
case Track.Source.Camera:
localTracks = await this.createTracks({
video: (options as VideoCaptureOptions | undefined) ?? true,
});
break;
case Track.Source.Microphone:
localTracks = await this.createTracks({
audio: (options as AudioCaptureOptions | undefined) ?? true,
});
break;
case Track.Source.ScreenShare:
localTracks = await this.createScreenTracks({
...(options as ScreenShareCaptureOptions | undefined),
});
break;
default:
throw new TrackInvalidError(source);
}
} catch (e: unknown) {
localTracks?.forEach((tr) => {
tr.stop();
});
if (e instanceof Error) {
this.emit(ParticipantEvent.MediaDevicesError, e);
}
this.pendingPublishing.delete(source);
throw e;
}
try {
const publishPromises: Array<Promise<LocalTrackPublication>> = [];
for (const localTrack of localTracks) {
this.log.info('publishing track', {
...this.logContext,
...getLogContextFromTrack(localTrack),
});
publishPromises.push(this.publishTrack(localTrack, publishOptions));
}
const publishedTracks = await Promise.all(publishPromises);
// for screen share publications including audio, this will only return the screen share publication, not the screen share audio one
// revisit if we want to return an array of tracks instead for v2
[track] = publishedTracks;
} catch (e) {
localTracks?.forEach((tr) => {
tr.stop();
});
throw e;
} finally {
this.pendingPublishing.delete(source);
}
}
} else {
if (!track?.track && this.pendingPublishing.has(source)) {
// if there's no track available yet first wait for pending publishing promises of that source to see if it becomes available
track = await this.waitForPendingPublicationOfSource(source);
if (!track) {
this.log.info('waiting for pending publication promise timed out', {
...this.logContext,
source,
});
}
}
if (track && track.track) {
// screenshare cannot be muted, unpublish instead
if (source === Track.Source.ScreenShare) {
track = await this.unpublishTrack(track.track);
const screenAudioTrack = this.getTrackPublication(Track.Source.ScreenShareAudio);
if (screenAudioTrack && screenAudioTrack.track) {
this.unpublishTrack(screenAudioTrack.track);
}
} else {
await track.mute();
}
}
}
return track;
}
/**
* Publish both camera and microphone at the same time. This is useful for
* displaying a single Permission Dialog box to the end user.
*/
async enableCameraAndMicrophone() {
if (
this.pendingPublishing.has(Track.Source.Camera) ||
this.pendingPublishing.has(Track.Source.Microphone)
) {
// no-op it's already been requested
return;
}
this.pendingPublishing.add(Track.Source.Camera);
this.pendingPublishing.add(Track.Source.Microphone);
try {
const tracks: LocalTrack[] = await this.createTracks({
audio: true,
video: true,
});
await Promise.all(tracks.map((track) => this.publishTrack(track)));
} finally {
this.pendingPublishing.delete(Track.Source.Camera);
this.pendingPublishing.delete(Track.Source.Microphone);
}
}
/**
* Create local camera and/or microphone tracks
* @param options
* @returns
*/
async createTracks(options?: CreateLocalTracksOptions): Promise<LocalTrack[]> {
options ??= {};
const { audioProcessor, videoProcessor, optionsWithoutProcessor } =
extractProcessorsFromOptions(options);
const mergedOptions = mergeDefaultOptions(
optionsWithoutProcessor,
this.roomOptions?.audioCaptureDefaults,
this.roomOptions?.videoCaptureDefaults,
);
const constraints = constraintsForOptions(mergedOptions);
let stream: MediaStream | undefined;
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
} catch (err) {
if (err instanceof Error) {
if (constraints.audio) {
this.microphoneError = err;
}
if (constraints.video) {
this.cameraError = err;
}
}
throw err;
}
if (constraints.audio) {
this.microphoneError = undefined;
this.emit(ParticipantEvent.AudioStreamAcquired);
}
if (constraints.video) {
this.cameraError = undefined;
}
return Promise.all(
stream.getTracks().map(async (mediaStreamTrack) => {
const isAudio = mediaStreamTrack.kind === 'audio';
let trackOptions = isAudio ? mergedOptions!.audio : mergedOptions!.video;
if (typeof trackOptions === 'boolean' || !trackOptions) {
trackOptions = {};
}
let trackConstraints: MediaTrackConstraints | undefined;
const conOrBool = isAudio ? constraints.audio : constraints.video;
if (typeof conOrBool !== 'boolean') {
trackConstraints = conOrBool;
}
const track = mediaTrackToLocalTrack(mediaStreamTrack, trackConstraints, {
loggerName: this.roomOptions.loggerName,
loggerContextCb: () => this.logContext,
});
if (track.kind === Track.Kind.Video) {
track.source = Track.Source.Camera;
} else if (track.kind === Track.Kind.Audio) {
track.source = Track.Source.Microphone;
track.setAudioContext(this.audioContext);
}
track.mediaStream = stream;
if (isAudioTrack(track) && audioProcessor) {
await track.setProcessor(audioProcessor);
} else if (isVideoTrack(track) && videoProcessor) {
await track.setProcessor(videoProcessor);
}
return track;
}),
);
}
/**
* Creates a screen capture tracks with getDisplayMedia().
* A LocalVideoTrack is always created and returned.
* If { audio: true }, and the browser supports audio capture, a LocalAudioTrack is also created.
*/
async createScreenTracks(options?: ScreenShareCaptureOptions): Promise<Array<LocalTrack>> {
if (options === undefined) {
options = {};
}
if (navigator.mediaDevices.getDisplayMedia === undefined) {
throw new DeviceUnsupportedError('getDisplayMedia not supported');
}
if (options.resolution === undefined && !isSafari17()) {
// we need to constrain the dimensions, otherwise it could lead to low bitrate
// due to encoding a huge video. Encoding such large surfaces is really expensive
// unfortunately Safari 17 has a but and cannot be constrained by default
options.resolution = ScreenSharePresets.h1080fps30.resolution;
}
const constraints = screenCaptureToDisplayMediaStreamOptions(options);
const stream: MediaStream = await navigator.mediaDevices.getDisplayMedia(constraints);
const tracks = stream.getVideoTracks();
if (tracks.length === 0) {
throw new TrackInvalidError('no video track found');
}
const screenVideo = new LocalVideoTrack(tracks[0], undefined, false, {
loggerName: this.roomOptions.loggerName,
loggerContextCb: () => this.logContext,
});
screenVideo.source = Track.Source.ScreenShare;
if (options.contentHint) {
screenVideo.mediaStreamTrack.contentHint = options.contentHint;
}
const localTracks: Array<LocalTrack> = [screenVideo];
if (stream.getAudioTracks().length > 0) {
this.emit(ParticipantEvent.AudioStreamAcquired);
const screenAudio = new LocalAudioTrack(
stream.getAudioTracks()[0],
undefined,
false,
this.audioContext,
{ loggerName: this.roomOptions.loggerName, loggerContextCb: () => this.logContext },
);
screenAudio.source = Track.Source.ScreenShareAudio;
localTracks.push(screenAudio);
}
return localTracks;
}
/**
* Publish a new track to the room
* @param track
* @param options
*/
async publishTrack(track: LocalTrack | MediaStreamTrack, options?: TrackPublishOptions) {
return this.publishOrRepublishTrack(track, options);
}
private async publishOrRepublishTrack(
track: LocalTrack | MediaStreamTrack,
options?: TrackPublishOptions,
isRepublish = false,
): Promise<LocalTrackPublication> {
if (isLocalAudioTrack(track)) {
track.setAudioContext(this.audioContext);
}
await this.reconnectFuture?.promise;
if (this.republishPromise && !isRepublish) {
await this.republishPromise;
}
if (isLocalTrack(track) && this.pendingPublishPromises.has(track)) {
await this.pendingPublishPromises.get(track);
}
let defaultConstraints: MediaTrackConstraints | undefined;
if (track instanceof MediaStreamTrack) {
defaultConstraints = track.getConstraints();
} else {
// we want to access constraints directly as `track.mediaStreamTrack`
// might be pointing to a non-device track (e.g. processed track) already
defaultConstraints = track.constraints;
let deviceKind: MediaDeviceKind | undefined = undefined;
switch (track.source) {
case Track.Source.Microphone:
deviceKind = 'audioinput';
break;
case Track.Source.Camera:
deviceKind = 'videoinput';
default:
break;
}
if (deviceKind && this.activeDeviceMap.has(deviceKind)) {
defaultConstraints = {
...defaultConstraints,
deviceId: this.activeDeviceMap.get(deviceKind),
};
}
}
// convert raw media track into audio or video track
if (track instanceof MediaStreamTrack) {
switch (track.kind) {
case 'audio':
track = new LocalAudioTrack(track, defaultConstraints, true, this.audioContext, {
loggerName: this.roomOptions.loggerName,
loggerContextCb: () => this.logContext,
});
break;
case 'video':
track = new LocalVideoTrack(track, defaultConstraints, true, {
loggerName: this.roomOptions.loggerName,
loggerContextCb: () => this.logContext,
});
break;
default:
throw new TrackInvalidError(`unsupported MediaStreamTrack kind ${track.kind}`);
}
} else {
track.updateLoggerOptions({
loggerName: this.roomOptions.loggerName,
loggerContextCb: () => this.logContext,
});
}
// is it already published? if so skip
let existingPublication: LocalTrackPublication | undefined;
this.trackPublications.forEach((publication) => {
if (!publication.track) {
return;
}
if (publication.track === track) {
existingPublication = <LocalTrackPublication>publication;
}
});
if (existingPublication) {
this.log.warn('track has already been published, skipping', {
...this.logContext,
...getLogContextFromTrack(existingPublication),
});
return existingPublication;
}
const isStereoInput =
('channelCount' in track.mediaStreamTrack.getSettings() &&
// @ts-ignore `channelCount` on getSettings() is currently only available for Safari, but is generally the best way to determine a stereo track https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings/channelCount
track.mediaStreamTrack.getSettings().channelCount === 2) ||
track.mediaStreamTrack.getConstraints().channelCount === 2;
const isStereo = options?.forceStereo ?? isStereoInput;
// disable dtx for stereo track if not enabled explicitly
if (isStereo) {
if (!options) {
options = {};
}
if (options.dtx === undefined) {
this.log.info(
`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,
{
...this.logContext,
...getLogContextFromTrack(track),
},
);
}
if (options.red === undefined) {
this.log.info(
`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,
);
}
options.dtx ??= false;
options.red ??= false;
}
const opts: TrackPublishOptions = {
...this.roomOptions.publishDefaults,
...options,
};
if (!isE2EESimulcastSupported() && this.roomOptions.e2ee) {
this.log.info(
`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`,
{
...this.logContext,
},
);
opts.simulcast = false;
}
if (opts.source) {
track.source = opts.source;
}
const publishPromise = this.publish(track, opts, isStereo);
this.pendingPublishPromises.set(track, publishPromise);
try {
const publication = await publishPromise;
return publication;
} catch (e) {
throw e;
} finally {
this.pendingPublishPromises.delete(track);
}
}
private async publish(track: LocalTrack, opts: TrackPublishOptions, isStereo: boolean) {
const existingTrackOfSource = Array.from(this.trackPublications.values()).find(
(publishedTrack) => isLocalTrack(track) && publishedTrack.source === track.source,
);
if (existingTrackOfSource && track.source !== Track.Source.Unknown) {
this.log.info(`publishing a second track with the same source: ${track.source}`, {
...this.logContext,
...getLogContextFromTrack(track),
});
}
if (opts.stopMicTrackOnMute && isAudioTrack(track)) {
track.stopOnMute = true;
}
if (track.source === Track.Source.ScreenShare && isFireFox()) {
// Firefox does not work well with simulcasted screen share
// we frequently get no data on layer 0 when enabled
opts.simulcast = false;
}
// require full AV1/VP9 SVC support prior to using it
if (opts.videoCodec === 'av1' && !supportsAV1()) {
opts.videoCodec = undefined;
}
if (opts.videoCodec === 'vp9' && !supportsVP9()) {
opts.videoCodec = undefined;
}
if (opts.videoCodec === undefined) {
opts.videoCodec = defaultVideoCodec;
}
if (this.enabledPublishVideoCodecs.length > 0) {
// fallback to a supported codec if it is not supported
if (
!this.enabledPublishVideoCodecs.some(
(c) => opts.videoCodec === mimeTypeToVideoCodecString(c.mime),
)
) {
opts.videoCodec = mimeTypeToVideoCodecString(this.enabledPublishVideoCodecs[0].mime);
}
}
const videoCodec = opts.videoCodec;
// handle track actions
track.on(TrackEvent.Muted, this.onTrackMuted);
track.on(TrackEvent.Unmuted, this.onTrackUnmuted);
track.on(TrackEvent.Ended, this.handleTrackEnded);
track.on(TrackEvent.UpstreamPaused, this.onTrackUpstreamPaused);
track.on(TrackEvent.UpstreamResumed, this.onTrackUpstreamResumed);
track.on(TrackEvent.AudioTrackFeatureUpdate, this.onTrackFeatureUpdate);
// create track publication from track
const req = new AddTrackRequest({
// get local track id for use during publishing
cid: track.mediaStreamTrack.id,
name: opts.name,
type: Track.kindToProto(track.kind),
muted: track.isMuted,
source: Track.sourceToProto(track.source),
disableDtx: !(opts.dtx ?? true),
encryption: this.encryptionType,
stereo: isStereo,
disableRed: this.isE2EEEnabled || !(opts.red ?? true),
stream: opts?.stream,
});
// compute encodings and layers for video
let encodings: RTCRtpEncodingParameters[] | undefined;
if (track.kind === Track.Kind.Video) {
let dims: Track.Dimensions = {
width: 0,
height: 0,
};
try {
dims = await track.waitForDimensions();
} catch (e) {
// use defaults, it's quite painful for congestion control without simulcast
// so using default dims according to publish settings
const defaultRes =
this.roomOptions.videoCaptureDefaults?.resolution ?? VideoPresets.h720.resolution;
dims = {
width: defaultRes.width,
height: defaultRes.height,
};
// log failure
this.log.error('could not determine track dimensions, using defaults', {
...this.logContext,
...getLogContextFromTrack(track),
dims,
});
}
// width and height should be defined for video
req.width = dims.width;
req.height = dims.height;
// for svc codecs, disable simulcast and use vp8 for backup codec
if (isLocalVideoTrack(track)) {
if (isSVCCodec(videoCodec)) {
if (track.source === Track.Source.ScreenShare) {
// vp9 svc with screenshare cannot encode multiple spatial layers
// doing so reduces publish resolution to minimal resolution
opts.scalabilityMode = 'L1T3';
// Chrome does not allow more than 5 fps with L1T3, and it has encoding bugs with L3T3
// It has a different path for screenshare handling and it seems to be untested/buggy
// As a workaround, we are setting contentHint to force it to go through the same
// path as regular camera video. While this is not optimal, it delivers the performance
// that we need
if ('contentHint' in track.mediaStreamTrack) {
track.mediaStreamTrack.contentHint = 'motion';
this.log.info('forcing contentHint to motion for screenshare with SVC codecs', {
...this.logContext,
...getLogContextFromTrack(track),
});
}
}
// set scalabilityMode to 'L3T3_KEY' by default
opts.scalabilityMode = opts.scalabilityMode ?? 'L3T3_KEY';
}
req.simulcastCodecs = [
new SimulcastCodec({
codec: videoCodec,
cid: track.mediaStreamTrack.id,
}),
];
// set up backup
if (opts.backupCodec === true) {
opts.backupCodec = { codec: defaultVideoCodec };
}
if (
opts.backupCodec &&
videoCodec !== opts.backupCodec.codec &&
// TODO remove this once e2ee is supported for backup codecs
req.encryption === Encryption_Type.NONE
) {
// multi-codec simulcast requires dynacast
if (!this.roomOptions.dynacast) {