@dtelecom/server-sdk-node 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -888,7 +888,13 @@ var SignalRequest = {
888
888
  writeMessage(writer, 8, (w) => LeaveRequest.encode(message.leave, w));
889
889
  }
890
890
  if (message.ping !== void 0) {
891
- writer.uint32(72).int64(message.ping);
891
+ writer.uint32(112).int64(message.ping);
892
+ }
893
+ if (message.pingReq !== void 0) {
894
+ const nested = writer.uint32(130).fork();
895
+ nested.uint32(8).int64(message.pingReq.timestamp);
896
+ nested.uint32(16).int64(message.pingReq.rtt);
897
+ nested.ldelim();
892
898
  }
893
899
  return writer;
894
900
  }
@@ -946,6 +952,26 @@ var SignalResponse = {
946
952
  case 18:
947
953
  message.pong = reader.int64();
948
954
  break;
955
+ case 20: {
956
+ const pongEnd = reader.pos + reader.uint32();
957
+ const pongResp = { lastPingTimestamp: 0, timestamp: 0 };
958
+ while (reader.pos < pongEnd) {
959
+ const pongTag = reader.uint32();
960
+ switch (pongTag >>> 3) {
961
+ case 1:
962
+ pongResp.lastPingTimestamp = reader.int64();
963
+ break;
964
+ case 2:
965
+ pongResp.timestamp = reader.int64();
966
+ break;
967
+ default:
968
+ reader.skipType(pongTag & 7);
969
+ break;
970
+ }
971
+ }
972
+ message.pongResp = pongResp;
973
+ break;
974
+ }
949
975
  default:
950
976
  reader.skipType(tag & 7);
951
977
  break;
@@ -1154,9 +1180,17 @@ var SDK_NAME = "node";
1154
1180
  var SDK_VERSION = "0.1.0";
1155
1181
  var SignalClient = class extends TypedEmitter {
1156
1182
  ws = null;
1157
- pingInterval = null;
1158
1183
  _isConnected = false;
1159
1184
  joinResponse = null;
1185
+ /** App-level ping interval timer (sends ping every pingInterval seconds). */
1186
+ pingIntervalTimer = null;
1187
+ /** App-level pong timeout timer (fires if no pong within pingTimeout seconds). */
1188
+ pingTimeoutTimer = null;
1189
+ /** Server-provided ping config (seconds). */
1190
+ pingIntervalS = 0;
1191
+ pingTimeoutS = 0;
1192
+ /** RTT measured from last ping/pong round-trip. */
1193
+ rtt = 0;
1160
1194
  get isConnected() {
1161
1195
  return this._isConnected;
1162
1196
  }
@@ -1198,8 +1232,11 @@ var SignalClient = class extends TypedEmitter {
1198
1232
  clearTimeout(timeout);
1199
1233
  this.joinResponse = response.join;
1200
1234
  this._isConnected = true;
1201
- if (response.join.pingInterval > 0) {
1202
- this.startPing(response.join.pingInterval);
1235
+ this.pingTimeoutS = response.join.pingTimeout;
1236
+ this.pingIntervalS = response.join.pingInterval;
1237
+ if (this.pingTimeoutS > 0) {
1238
+ log.debug(`Ping config: interval=${this.pingIntervalS}s, timeout=${this.pingTimeoutS}s`);
1239
+ this.startPingInterval();
1203
1240
  }
1204
1241
  resolve(response.join);
1205
1242
  }
@@ -1216,7 +1253,7 @@ var SignalClient = class extends TypedEmitter {
1216
1253
  this.ws.on("close", (code, reason) => {
1217
1254
  clearTimeout(timeout);
1218
1255
  this._isConnected = false;
1219
- this.stopPing();
1256
+ this.stopPingInterval();
1220
1257
  const reasonStr = reason?.toString() || `code ${code}`;
1221
1258
  log.info(`WebSocket closed: ${reasonStr}`);
1222
1259
  this.emit("close", reasonStr);
@@ -1260,7 +1297,7 @@ var SignalClient = class extends TypedEmitter {
1260
1297
  }
1261
1298
  /** Close the WebSocket connection */
1262
1299
  close() {
1263
- this.stopPing();
1300
+ this.stopPingInterval();
1264
1301
  this._isConnected = false;
1265
1302
  if (this.ws) {
1266
1303
  this.ws.removeAllListeners();
@@ -1305,6 +1342,10 @@ var SignalClient = class extends TypedEmitter {
1305
1342
  }
1306
1343
  }
1307
1344
  handleResponse(response) {
1345
+ const types = Object.keys(response).filter((k) => response[k] !== void 0 && response[k] !== null);
1346
+ if (types.length > 0) {
1347
+ log.debug(`Signal response: ${types.join(", ")}`);
1348
+ }
1308
1349
  if (response.offer) {
1309
1350
  log.debug(`Received OFFER from server (type=${response.offer.type})`);
1310
1351
  this.emit("offer", response.offer);
@@ -1348,21 +1389,63 @@ var SignalClient = class extends TypedEmitter {
1348
1389
  if (response.mute) {
1349
1390
  }
1350
1391
  if (response.pong !== void 0) {
1392
+ this.resetPingTimeout();
1351
1393
  }
1352
- }
1353
- startPing(intervalSec) {
1354
- this.stopPing();
1355
- const intervalMs = intervalSec * 1e3;
1356
- this.pingInterval = setInterval(() => {
1357
- this.sendRequest({ ping: Date.now() });
1358
- }, intervalMs);
1359
- }
1360
- stopPing() {
1361
- if (this.pingInterval) {
1362
- clearInterval(this.pingInterval);
1363
- this.pingInterval = null;
1394
+ if (response.pongResp) {
1395
+ this.rtt = Date.now() - response.pongResp.lastPingTimestamp;
1396
+ this.resetPingTimeout();
1364
1397
  }
1365
1398
  }
1399
+ /**
1400
+ * Send app-level ping (both legacy and new format, matching client-sdk-js).
1401
+ * Proto: SignalRequest.ping (field 14) + SignalRequest.ping_req (field 16).
1402
+ */
1403
+ sendPing() {
1404
+ const now = Date.now();
1405
+ this.sendRequest({ ping: now });
1406
+ this.sendRequest({ pingReq: { timestamp: now, rtt: this.rtt } });
1407
+ }
1408
+ /** Start sending pings at pingIntervalS and watching for pong timeout. */
1409
+ startPingInterval() {
1410
+ this.stopPingInterval();
1411
+ this.resetPingTimeout();
1412
+ if (!this.pingIntervalS) return;
1413
+ this.pingIntervalTimer = setInterval(() => {
1414
+ this.sendPing();
1415
+ }, this.pingIntervalS * 1e3);
1416
+ }
1417
+ /** Stop ping interval + timeout timers. */
1418
+ stopPingInterval() {
1419
+ if (this.pingIntervalTimer) {
1420
+ clearInterval(this.pingIntervalTimer);
1421
+ this.pingIntervalTimer = null;
1422
+ }
1423
+ if (this.pingTimeoutTimer) {
1424
+ clearTimeout(this.pingTimeoutTimer);
1425
+ this.pingTimeoutTimer = null;
1426
+ }
1427
+ }
1428
+ /** Reset the pong-timeout timer. Called when we receive a pong. */
1429
+ resetPingTimeout() {
1430
+ if (this.pingTimeoutTimer) {
1431
+ clearTimeout(this.pingTimeoutTimer);
1432
+ this.pingTimeoutTimer = null;
1433
+ }
1434
+ if (!this.pingTimeoutS) return;
1435
+ this.pingTimeoutTimer = setTimeout(() => {
1436
+ this.pingTimeoutTimer = null;
1437
+ if (this._isConnected) {
1438
+ log.warn(`Ping timeout \u2014 no pong received within ${this.pingTimeoutS}s`);
1439
+ this._isConnected = false;
1440
+ if (this.ws) {
1441
+ this.ws.removeAllListeners();
1442
+ this.ws.close();
1443
+ this.ws = null;
1444
+ }
1445
+ this.emit("close", "ping_timeout");
1446
+ }
1447
+ }, this.pingTimeoutS * 1e3);
1448
+ }
1366
1449
  };
1367
1450
 
1368
1451
  // src/engine.ts
@@ -1380,6 +1463,8 @@ var RTCEngine = class extends TypedEmitter {
1380
1463
  pendingCandidates = [];
1381
1464
  joinResponse = null;
1382
1465
  publishWaiters = /* @__PURE__ */ new Map();
1466
+ _negotiateResolve = null;
1467
+ _publisherConnectedResolve = null;
1383
1468
  get isConnected() {
1384
1469
  return this._isConnected;
1385
1470
  }
@@ -1416,8 +1501,39 @@ var RTCEngine = class extends TypedEmitter {
1416
1501
  if (!this.subscriberPrimary) {
1417
1502
  await this.negotiate();
1418
1503
  }
1504
+ await this.waitForPrimaryConnected();
1419
1505
  return joinResponse;
1420
1506
  }
1507
+ /**
1508
+ * Wait for the primary PeerConnection ICE to reach "connected".
1509
+ * When subscriberPrimary=true the subscriber PC is primary;
1510
+ * otherwise the publisher PC is primary.
1511
+ */
1512
+ waitForPrimaryConnected(timeoutMs = 15e3) {
1513
+ const pc = this.subscriberPrimary ? this.subscriber : this.publisher;
1514
+ if (!pc) return Promise.resolve();
1515
+ const iceState = pc.iceConnectionState;
1516
+ if (iceState === "connected" || iceState === "completed") {
1517
+ return Promise.resolve();
1518
+ }
1519
+ return new Promise((resolve, reject) => {
1520
+ const timeout = setTimeout(() => {
1521
+ reject(new Error(
1522
+ `Primary PC ICE timed out after ${timeoutMs}ms (state: ${pc.iceConnectionState})`
1523
+ ));
1524
+ }, timeoutMs);
1525
+ const handler = (state) => {
1526
+ if (state === "connected" || state === "completed") {
1527
+ clearTimeout(timeout);
1528
+ resolve();
1529
+ } else if (state === "failed") {
1530
+ clearTimeout(timeout);
1531
+ reject(new Error("Primary PC ICE failed"));
1532
+ }
1533
+ };
1534
+ pc.iceConnectionStateChange.subscribe(handler);
1535
+ });
1536
+ }
1421
1537
  async addTransceiver(track) {
1422
1538
  if (!this.publisher) {
1423
1539
  throw new Error("Publisher PC not initialized");
@@ -1450,11 +1566,39 @@ var RTCEngine = class extends TypedEmitter {
1450
1566
  log2.debug(`Publisher signaling state before negotiate: ${this.publisher.signalingState}`);
1451
1567
  const offer = await this.publisher.createOffer();
1452
1568
  await this.publisher.setLocalDescription(offer);
1569
+ const answerPromise = new Promise((resolve, reject) => {
1570
+ const timeout = setTimeout(() => {
1571
+ reject(new Error("Timed out waiting for publisher answer"));
1572
+ }, 1e4);
1573
+ this._negotiateResolve = () => {
1574
+ clearTimeout(timeout);
1575
+ resolve();
1576
+ };
1577
+ });
1453
1578
  log2.debug("Sending publisher offer");
1454
1579
  this.signal.sendOffer({
1455
1580
  type: offer.type,
1456
1581
  sdp: offer.sdp
1457
1582
  });
1583
+ await answerPromise;
1584
+ log2.debug("Negotiate complete (answer applied)");
1585
+ }
1586
+ /** Wait for publisher ICE to reach connected state (DTLS+SRTP ready). */
1587
+ async waitForPublisherConnected(timeoutMs = 1e4) {
1588
+ if (!this.publisher) throw new Error("Publisher PC not initialized");
1589
+ const iceState = this.publisher.iceConnectionState;
1590
+ if (iceState === "connected" || iceState === "completed") {
1591
+ return;
1592
+ }
1593
+ return new Promise((resolve, reject) => {
1594
+ const timeout = setTimeout(() => {
1595
+ reject(new Error(`Publisher ICE timed out (state: ${this.publisher?.iceConnectionState})`));
1596
+ }, timeoutMs);
1597
+ this._publisherConnectedResolve = () => {
1598
+ clearTimeout(timeout);
1599
+ resolve();
1600
+ };
1601
+ });
1458
1602
  }
1459
1603
  sendData(data, kind) {
1460
1604
  const channel = kind === "reliable" ? this.reliableChannel : this.lossyChannel;
@@ -1512,6 +1656,12 @@ var RTCEngine = class extends TypedEmitter {
1512
1656
  });
1513
1657
  this.publisher.iceConnectionStateChange.subscribe((state) => {
1514
1658
  log2.debug(`Publisher ICE state: ${state}`);
1659
+ if (state === "connected" || state === "completed") {
1660
+ if (this._publisherConnectedResolve) {
1661
+ this._publisherConnectedResolve();
1662
+ this._publisherConnectedResolve = null;
1663
+ }
1664
+ }
1515
1665
  });
1516
1666
  log2.debug("Publisher PC created");
1517
1667
  }
@@ -1609,6 +1759,7 @@ var RTCEngine = class extends TypedEmitter {
1609
1759
  await this.subscriber.setRemoteDescription(
1610
1760
  new import_werift.RTCSessionDescription(sd.sdp, sd.type)
1611
1761
  );
1762
+ this.flushPendingCandidates(1 /* SUBSCRIBER */);
1612
1763
  const answer = await this.subscriber.createAnswer();
1613
1764
  await this.subscriber.setLocalDescription(answer);
1614
1765
  this.signal.sendAnswer({
@@ -1628,6 +1779,10 @@ var RTCEngine = class extends TypedEmitter {
1628
1779
  );
1629
1780
  log2.debug("Set publisher remote description");
1630
1781
  this.flushPendingCandidates(0 /* PUBLISHER */);
1782
+ if (this._negotiateResolve) {
1783
+ this._negotiateResolve();
1784
+ this._negotiateResolve = null;
1785
+ }
1631
1786
  } catch (err) {
1632
1787
  log2.error("Failed to handle publisher answer", err);
1633
1788
  }
@@ -1659,10 +1814,8 @@ var RTCEngine = class extends TypedEmitter {
1659
1814
  this.disconnect();
1660
1815
  });
1661
1816
  this.signal.on("close", (reason) => {
1662
- if (this._isConnected) {
1663
- this._isConnected = false;
1664
- this.emit("disconnected", reason);
1665
- }
1817
+ this._isConnected = false;
1818
+ this.emit("disconnected", reason);
1666
1819
  });
1667
1820
  }
1668
1821
  flushPendingCandidates(target) {
@@ -2184,6 +2337,8 @@ var TrackPublication = class extends TypedEmitter {
2184
2337
  source;
2185
2338
  mimeType;
2186
2339
  muted;
2340
+ /** Media ID assigned by SFU — used to match WebRTC transceivers to publications */
2341
+ mid;
2187
2342
  constructor(info) {
2188
2343
  super();
2189
2344
  this.sid = info.sid;
@@ -2192,6 +2347,7 @@ var TrackPublication = class extends TypedEmitter {
2192
2347
  this.source = info.source;
2193
2348
  this.mimeType = info.mimeType;
2194
2349
  this.muted = info.muted;
2350
+ this.mid = info.mid;
2195
2351
  }
2196
2352
  updateInfo(info) {
2197
2353
  const wasMuted = this.muted;
@@ -2201,6 +2357,7 @@ var TrackPublication = class extends TypedEmitter {
2201
2357
  this.source = info.source;
2202
2358
  this.mimeType = info.mimeType;
2203
2359
  this.muted = info.muted;
2360
+ this.mid = info.mid;
2204
2361
  if (wasMuted !== info.muted) {
2205
2362
  this.emit(info.muted ? "muted" : "unmuted");
2206
2363
  }
@@ -2256,22 +2413,49 @@ var LocalAudioTrack = class _LocalAudioTrack {
2256
2413
  */
2257
2414
  setTransceiver(transceiver) {
2258
2415
  this.transceiver = transceiver;
2259
- this.source.onEncodedFrame = (opusData) => {
2260
- if (this.mediaTrack.stopped) return;
2261
- try {
2262
- const info = this.packetizer.nextPacketInfo();
2263
- const header = new import_werift2.RtpHeader();
2264
- header.payloadType = OPUS_PAYLOAD_TYPE;
2265
- header.sequenceNumber = info.sequenceNumber;
2266
- header.timestamp = info.timestamp;
2267
- header.ssrc = info.ssrc;
2268
- header.marker = false;
2269
- const packet = new import_werift2.RtpPacket(header, opusData);
2270
- this.mediaTrack.writeRtp(packet);
2271
- } catch (err) {
2272
- log7.error("Failed to send RTP via track", err);
2273
- }
2416
+ const sender = transceiver.sender;
2417
+ const dtlsState = sender?.dtlsTransport?.state;
2418
+ log7.info(`setTransceiver: mid=${transceiver.mid}, codec=${sender?.codec?.name}, dtls=${dtlsState}`);
2419
+ const wireAudio = () => {
2420
+ let rtpWriteCount = 0;
2421
+ log7.info(`Audio wired: dtls=${sender?.dtlsTransport?.state}, codec=${sender?.codec?.name}`);
2422
+ this.source.onEncodedFrame = (opusData) => {
2423
+ if (this.mediaTrack.stopped) return;
2424
+ try {
2425
+ const info = this.packetizer.nextPacketInfo();
2426
+ const header = new import_werift2.RtpHeader();
2427
+ header.payloadType = OPUS_PAYLOAD_TYPE;
2428
+ header.sequenceNumber = info.sequenceNumber;
2429
+ header.timestamp = info.timestamp;
2430
+ header.ssrc = info.ssrc;
2431
+ header.marker = false;
2432
+ const packet = new import_werift2.RtpPacket(header, opusData);
2433
+ this.mediaTrack.writeRtp(packet);
2434
+ rtpWriteCount++;
2435
+ if (rtpWriteCount === 1) {
2436
+ log7.info(`First RTP sent: dtls=${sender?.dtlsTransport?.state}`);
2437
+ }
2438
+ } catch (err) {
2439
+ log7.error("Failed to send RTP via track", err);
2440
+ }
2441
+ };
2274
2442
  };
2443
+ if (dtlsState === "connected") {
2444
+ wireAudio();
2445
+ } else {
2446
+ const dtls = sender?.dtlsTransport;
2447
+ if (dtls?.onStateChange) {
2448
+ const { unSubscribe } = dtls.onStateChange.subscribe((state) => {
2449
+ if (state === "connected") {
2450
+ unSubscribe();
2451
+ wireAudio();
2452
+ }
2453
+ });
2454
+ } else {
2455
+ log7.warn("Cannot subscribe to DTLS state changes, wiring audio immediately");
2456
+ wireAudio();
2457
+ }
2458
+ }
2275
2459
  }
2276
2460
  /** Stop the track and release resources */
2277
2461
  stop() {
@@ -2379,8 +2563,9 @@ var LocalParticipant = class extends Participant {
2379
2563
  track.sid = response.track.sid;
2380
2564
  log8.debug(`Track published: cid=${track.cid}, sid=${track.sid}`);
2381
2565
  const transceiver = await this.engine.addTransceiver(track.mediaTrack);
2382
- track.setTransceiver(transceiver);
2383
2566
  await this.engine.negotiate();
2567
+ await this.engine.waitForPublisherConnected();
2568
+ track.setTransceiver(transceiver);
2384
2569
  const publication = new LocalTrackPublication(response.track, track);
2385
2570
  this._trackPublications.set(response.track.sid, publication);
2386
2571
  this.publishedTracks.set(track.cid, track);
@@ -2472,6 +2657,7 @@ var RemoteParticipant = class extends TypedEmitter {
2472
2657
  const activeSids = /* @__PURE__ */ new Set();
2473
2658
  for (const trackInfo of info.tracks) {
2474
2659
  activeSids.add(trackInfo.sid);
2660
+ log8.debug(`Track info for ${this.identity}: sid=${trackInfo.sid}, type=${trackInfo.type}, mid=${trackInfo.mid}`);
2475
2661
  const existing = this._trackPublications.get(trackInfo.sid);
2476
2662
  if (existing) {
2477
2663
  existing.updateInfo(trackInfo);
@@ -2565,6 +2751,8 @@ var Room = class extends TypedEmitter {
2565
2751
  _isConnected = false;
2566
2752
  activeSpeakers = [];
2567
2753
  roomInfo = null;
2754
+ /** Identity-prefixed logger for debugging multi-Room scenarios */
2755
+ log = log9;
2568
2756
  constructor() {
2569
2757
  super();
2570
2758
  this.engine = new RTCEngine();
@@ -2589,7 +2777,8 @@ var Room = class extends TypedEmitter {
2589
2777
  this.setupEngineHandlers();
2590
2778
  this.setupSignalHandlers();
2591
2779
  this._isConnected = true;
2592
- log9.info(`Connected to room "${this.name}" as "${this.localParticipant.identity}"`);
2780
+ this.log = log9;
2781
+ log9.info(`[${this.localParticipant.identity}] Connected to room "${this.name}"`);
2593
2782
  }
2594
2783
  /**
2595
2784
  * Disconnect from the room.
@@ -2676,6 +2865,7 @@ var Room = class extends TypedEmitter {
2676
2865
  });
2677
2866
  }
2678
2867
  handleParticipantUpdate(update) {
2868
+ const me = this.localParticipant?.identity ?? "?";
2679
2869
  for (const info of update.participants) {
2680
2870
  if (info.sid === this.localParticipant.sid || info.identity === this.localParticipant.identity) {
2681
2871
  this.localParticipant.updateInfo(info);
@@ -2686,36 +2876,78 @@ var Room = class extends TypedEmitter {
2686
2876
  if (participant) {
2687
2877
  participant.destroy();
2688
2878
  this.remoteParticipants.delete(info.sid);
2689
- log9.info(`Participant disconnected: ${participant.identity}`);
2879
+ log9.info(`[${me}] Participant disconnected: ${participant.identity}`);
2690
2880
  this.emit("participantDisconnected", participant);
2691
2881
  }
2692
2882
  } else {
2693
- const isNew = !this.remoteParticipants.has(info.sid);
2694
- const participant = this.getOrCreateParticipant(info);
2883
+ const { participant, isNew } = this.getOrCreateParticipant(info);
2695
2884
  if (isNew) {
2696
- log9.info(`Participant connected: ${participant.identity}`);
2885
+ log9.info(`[${me}] Participant connected: ${participant.identity}`);
2697
2886
  this.emit("participantConnected", participant);
2698
2887
  }
2699
2888
  }
2700
2889
  }
2890
+ if (this.pendingTracks.length > 0) {
2891
+ this.flushPendingTracks();
2892
+ }
2701
2893
  }
2894
+ /** Pending tracks waiting to be matched to a participant publication */
2895
+ pendingTracks = [];
2702
2896
  handleRemoteTrack(mediaTrack, transceiver) {
2703
- const mid = transceiver.mid;
2897
+ const mid = String(transceiver.mid);
2704
2898
  const mediaKind = mediaTrack?.kind;
2705
- const expectedType = mediaKind === "audio" ? 0 /* AUDIO */ : 1 /* VIDEO */;
2899
+ const me = this.localParticipant?.identity ?? "?";
2900
+ if (mediaKind !== "audio") {
2901
+ log9.debug(`[${me}] Skipping ${mediaKind} track (mid=${mid}, audio-only SDK)`);
2902
+ return;
2903
+ }
2904
+ log9.debug(`[${me}] handleRemoteTrack: mid=${mid}, kind=${mediaKind}`);
2905
+ if (this.matchTrack(mediaTrack, mid)) return;
2906
+ log9.debug(`[${me}] Queuing unmatched audio track (mid=${mid})`);
2907
+ this.pendingTracks.push({ mediaTrack, mid });
2908
+ }
2909
+ /**
2910
+ * Match a media track to a participant publication.
2911
+ * Strategy:
2912
+ * 1. Try matching by mid (SFU assigns mid in TrackInfo)
2913
+ * 2. Fall back to first unassigned audio publication (for SFUs that don't set mid)
2914
+ */
2915
+ matchTrack(mediaTrack, mid) {
2916
+ const me = this.localParticipant?.identity ?? "?";
2706
2917
  for (const participant of this.remoteParticipants.values()) {
2707
2918
  for (const [sid, pub] of participant.trackPublications) {
2708
- if (!pub.track && pub.kind === expectedType) {
2709
- if (mediaKind !== "audio") {
2710
- log9.debug(`Skipping ${mediaKind} track ${sid} (audio-only SDK)`);
2711
- return;
2712
- }
2919
+ if (pub.mid === mid && pub.kind === 0 /* AUDIO */) {
2920
+ log9.debug(`[${me}] Matched mid=${mid} \u2192 ${participant.identity}/${pub.name} (by mid)`);
2921
+ if (pub.track) participant.removeTrack(sid);
2713
2922
  participant.addSubscribedTrack(mediaTrack, sid, pub.name);
2714
- return;
2923
+ return true;
2715
2924
  }
2716
2925
  }
2717
2926
  }
2718
- log9.warn(`Received remote track (mid=${mid}, kind=${mediaKind}) but couldn't match to a participant`);
2927
+ for (const participant of this.remoteParticipants.values()) {
2928
+ for (const [sid, pub] of participant.trackPublications) {
2929
+ if (!pub.track && pub.kind === 0 /* AUDIO */) {
2930
+ log9.debug(`[${me}] Matched mid=${mid} \u2192 ${participant.identity}/${pub.name} (by kind, unassigned)`);
2931
+ participant.addSubscribedTrack(mediaTrack, sid, pub.name);
2932
+ return true;
2933
+ }
2934
+ }
2935
+ }
2936
+ log9.debug(`[${me}] No match for mid=${mid} (pubs: ${[...this.remoteParticipants.values()].map((p) => `${p.identity}=[${[...p.trackPublications.values()].map((t) => `${t.name}:mid=${t.mid}:has=${!!t.track}`).join(",")}]`).join(", ")})`);
2937
+ return false;
2938
+ }
2939
+ /** Try to match any pending tracks after participant updates arrive */
2940
+ flushPendingTracks() {
2941
+ const remaining = [];
2942
+ for (const pending of this.pendingTracks) {
2943
+ if (!this.matchTrack(pending.mediaTrack, pending.mid)) {
2944
+ remaining.push(pending);
2945
+ }
2946
+ }
2947
+ if (this.pendingTracks.length !== remaining.length) {
2948
+ log9.debug(`Matched ${this.pendingTracks.length - remaining.length} pending tracks`);
2949
+ }
2950
+ this.pendingTracks = remaining;
2719
2951
  }
2720
2952
  handleDataMessage(data, kind) {
2721
2953
  try {
@@ -2746,23 +2978,31 @@ var Room = class extends TypedEmitter {
2746
2978
  let participant = this.remoteParticipants.get(info.sid);
2747
2979
  if (participant) {
2748
2980
  participant.updateInfo(info);
2749
- } else {
2750
- participant = new RemoteParticipant(info);
2751
- this.remoteParticipants.set(info.sid, participant);
2752
- participant.on("trackSubscribed", (track, pub) => {
2753
- this.emit("trackSubscribed", track, pub, participant);
2754
- });
2755
- participant.on("trackUnsubscribed", (track, pub) => {
2756
- this.emit("trackUnsubscribed", track, pub, participant);
2757
- });
2758
- participant.on("trackPublished", (pub) => {
2759
- this.emit("trackPublished", pub, participant);
2760
- });
2761
- participant.on("trackUnpublished", (pub) => {
2762
- this.emit("trackUnpublished", pub, participant);
2763
- });
2981
+ return { participant, isNew: false };
2982
+ }
2983
+ for (const [oldSid, existing] of this.remoteParticipants) {
2984
+ if (existing.identity === info.identity) {
2985
+ this.remoteParticipants.delete(oldSid);
2986
+ existing.updateInfo(info);
2987
+ this.remoteParticipants.set(info.sid, existing);
2988
+ return { participant: existing, isNew: false };
2989
+ }
2764
2990
  }
2765
- return participant;
2991
+ participant = new RemoteParticipant(info);
2992
+ this.remoteParticipants.set(info.sid, participant);
2993
+ participant.on("trackSubscribed", (track, pub) => {
2994
+ this.emit("trackSubscribed", track, pub, participant);
2995
+ });
2996
+ participant.on("trackUnsubscribed", (track, pub) => {
2997
+ this.emit("trackUnsubscribed", track, pub, participant);
2998
+ });
2999
+ participant.on("trackPublished", (pub) => {
3000
+ this.emit("trackPublished", pub, participant);
3001
+ });
3002
+ participant.on("trackUnpublished", (pub) => {
3003
+ this.emit("trackUnpublished", pub, participant);
3004
+ });
3005
+ return { participant, isNew: true };
2766
3006
  }
2767
3007
  };
2768
3008
 
@@ -2842,12 +3082,21 @@ var AudioSource = class {
2842
3082
  this._onEncodedFrame = null;
2843
3083
  this.track = null;
2844
3084
  }
3085
+ _rtpCount = 0;
3086
+ _warnedNoCallback = false;
2845
3087
  encodeAndSend(pcm) {
2846
3088
  if (!this.encoder) return;
2847
3089
  try {
2848
3090
  const opusData = this.encoder.encode(pcm);
2849
3091
  if (this._onEncodedFrame) {
2850
3092
  this._onEncodedFrame(opusData);
3093
+ this._rtpCount++;
3094
+ if (this._rtpCount === 1) {
3095
+ log10.info(`First RTP packet sent (${opusData.byteLength} bytes)`);
3096
+ }
3097
+ } else if (!this._warnedNoCallback) {
3098
+ this._warnedNoCallback = true;
3099
+ log10.debug("Waiting for DTLS \u2014 buffered audio will be dropped");
2851
3100
  }
2852
3101
  } catch (err) {
2853
3102
  log10.error("Opus encode failed", err);