Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dirty-suns-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-client": patch
---

Wait for participant in onTrack
36 changes: 27 additions & 9 deletions src/room/Room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1412,7 +1412,7 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
this.maybeCreateEngine();
}

private onTrackAdded(
private async onTrackAdded(
mediaTrack: MediaStreamTrack,
stream: MediaStream,
receiver: RTCRtpReceiver,
Expand Down Expand Up @@ -1458,16 +1458,34 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
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;
Expand Down
Loading