diff --git a/.changeset/dirty-suns-punch.md b/.changeset/dirty-suns-punch.md new file mode 100644 index 0000000000..7b4f916a35 --- /dev/null +++ b/.changeset/dirty-suns-punch.md @@ -0,0 +1,5 @@ +--- +"livekit-client": patch +--- + +Wait for participant in onTrack diff --git a/src/room/Room.ts b/src/room/Room.ts index ab4bef202a..01abf2e18e 100644 --- a/src/room/Room.ts +++ b/src/room/Room.ts @@ -1412,7 +1412,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) this.maybeCreateEngine(); } - private onTrackAdded( + private async onTrackAdded( mediaTrack: MediaStreamTrack, stream: MediaStream, receiver: RTCRtpReceiver, @@ -1458,16 +1458,34 @@ class Room extends (EventEmitter as new () => TypedEmitter) return; } - const participant = Array.from(this.remoteParticipants.values()).find( - (p) => p.sid === participantSid, - ) as RemoteParticipant | undefined; + const findParticipant = () => + Array.from(this.remoteParticipants.values()).find((p) => p.sid === participantSid) as + | RemoteParticipant + | undefined; + + let participant = findParticipant(); if (!participant) { - this.log.error( - `Tried to add a track for a participant, that's not present. Sid: ${participantSid}`, - this.logContext, - ); - return; + const waitForParticipant = async () => { + const start = performance.now(); + while (performance.now() - start < 300) { + await sleep(20); + const p = findParticipant(); + if (p) { + return p; + } + } + }; + participant = await waitForParticipant(); + + if (!participant) { + // participant still not found after waiting for it, giving up + this.log.error( + `Tried to add a track for a participant, that's not present. Sid: ${participantSid}`, + this.logContext, + ); + return; + } } let adaptiveStreamSettings: AdaptiveStreamSettings | undefined;