@dtelecom/livekit-client 1.12.14 → 1.12.16

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/src/room/Room.ts CHANGED
@@ -59,7 +59,7 @@ import RemoteTrackPublication from './track/RemoteTrackPublication';
59
59
  import { Track } from './track/Track';
60
60
  import type { TrackPublication } from './track/TrackPublication';
61
61
  import type { AdaptiveStreamSettings } from './track/types';
62
- import { getNewAudioContext, sourceToKind } from './track/utils';
62
+ import { getNewAudioContext, kindToSource, sourceToKind } from './track/utils';
63
63
  import type { SimulationOptions, SimulationScenario } from './types';
64
64
  import {
65
65
  Future,
@@ -71,7 +71,10 @@ import {
71
71
  supportsSetSinkId,
72
72
  unpackStreamId,
73
73
  unwrapConstraint,
74
- } from './utils';
74
+ isSafari,
75
+ getDisconnectReasonFromConnectionError,
76
+ } from './utils'
77
+ import { FallbackUrlProvider } from './FallbackUrlProvider';
75
78
 
76
79
  export enum ConnectionState {
77
80
  Disconnected = 'disconnected',
@@ -142,6 +145,8 @@ class Room extends EventEmitter<RoomEventCallbacks> {
142
145
 
143
146
  private connectionReconcileInterval?: ReturnType<typeof setInterval>;
144
147
 
148
+ private fallbackUrlProvider?: FallbackUrlProvider
149
+
145
150
  /**
146
151
  * Creates a new Room, the primary construct for a LiveKit session.
147
152
  * @param options
@@ -345,7 +350,17 @@ class Room extends EventEmitter<RoomEventCallbacks> {
345
350
  * @experimental
346
351
  */
347
352
  async prepareConnection(url: string) {
348
- await fetch(`http${url.substring(2)}`, { method: 'HEAD' });
353
+ if (this.connOptions?.fallbackUrls) {
354
+ this.fallbackUrlProvider = new FallbackUrlProvider(this.connOptions.fallbackUrls)
355
+ const nextUrl = this.fallbackUrlProvider.getNextUrl()
356
+
357
+ if (nextUrl && this.state === ConnectionState.Disconnected) {
358
+ await fetch(`http${nextUrl.substring(2)}`, { method: 'HEAD' });
359
+ log.debug(`prepared connection to ${nextUrl}`);
360
+ }
361
+ } else {
362
+ await fetch(`http${url.substring(2)}`, { method: 'HEAD' });
363
+ }
349
364
  }
350
365
 
351
366
  connect = async (url: string, token: string, opts?: RoomConnectOptions): Promise<void> => {
@@ -368,6 +383,10 @@ class Room extends EventEmitter<RoomEventCallbacks> {
368
383
 
369
384
  const urlProvider = new RegionUrlProvider(url, token);
370
385
 
386
+ if (opts?.fallbackUrls) {
387
+ this.fallbackUrlProvider = new FallbackUrlProvider(opts.fallbackUrls)
388
+ }
389
+
371
390
  const connectFn = async (
372
391
  resolve: () => void,
373
392
  reject: (reason: any) => void,
@@ -387,29 +406,44 @@ class Room extends EventEmitter<RoomEventCallbacks> {
387
406
  resolve();
388
407
  } catch (e) {
389
408
  if (
390
- isCloud(new URL(url)) &&
409
+ (isCloud(new URL(url)) || this.fallbackUrlProvider) &&
391
410
  e instanceof ConnectionError &&
392
411
  e.reason !== ConnectionErrorReason.Cancelled
393
412
  ) {
394
413
  let nextUrl: string | null = null;
395
414
  try {
396
- nextUrl = await urlProvider.getNextBestRegionUrl(this.abortController?.signal);
415
+ if (this.fallbackUrlProvider) {
416
+ nextUrl = this.fallbackUrlProvider.getNextUrl()
417
+ } else {
418
+ nextUrl = await urlProvider.getNextBestRegionUrl(this.abortController?.signal);
419
+ }
397
420
  } catch (error) {
398
421
  if (
399
422
  error instanceof ConnectionError &&
400
423
  (error.status === 401 || error.reason === ConnectionErrorReason.Cancelled)
401
424
  ) {
425
+ this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);
402
426
  reject(error);
403
427
  return;
404
428
  }
405
429
  }
430
+
406
431
  if (nextUrl) {
407
432
  log.debug('initial connection failed, retrying with another region');
408
433
  await connectFn(resolve, reject, nextUrl);
409
434
  } else {
435
+ this.handleDisconnect(
436
+ this.options.stopLocalTrackOnUnpublish,
437
+ getDisconnectReasonFromConnectionError(e)
438
+ );
410
439
  reject(e);
411
440
  }
412
441
  } else {
442
+ let disconnectReason = DisconnectReason.UNKNOWN_REASON;
443
+ if (e instanceof ConnectionError) {
444
+ disconnectReason = getDisconnectReasonFromConnectionError(e);
445
+ }
446
+ this.handleDisconnect(this.options.stopLocalTrackOnUnpublish, disconnectReason);
413
447
  reject(e);
414
448
  }
415
449
  }
@@ -439,6 +473,7 @@ class Room extends EventEmitter<RoomEventCallbacks> {
439
473
  typeof roomOptions.adaptiveStream === 'object' ? true : roomOptions.adaptiveStream,
440
474
  maxRetries: connectOptions.maxRetries,
441
475
  e2eeEnabled: !!this.e2eeManager,
476
+ fallbackUrs: connectOptions.fallbackUrls
442
477
  },
443
478
  abortController.signal,
444
479
  );
@@ -522,8 +557,8 @@ class Room extends EventEmitter<RoomEventCallbacks> {
522
557
  this.setupLocalParticipantEvents();
523
558
  this.emit(RoomEvent.SignalConnected);
524
559
  } catch (err) {
560
+ await this.engine.close();
525
561
  this.recreateEngine();
526
- this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);
527
562
  const resultingError = new ConnectionError(`could not establish signal connection`);
528
563
  if (err instanceof Error) {
529
564
  resultingError.message = `${resultingError.message}: ${err.message}`;
@@ -537,8 +572,8 @@ class Room extends EventEmitter<RoomEventCallbacks> {
537
572
  }
538
573
 
539
574
  if (abortController.signal.aborted) {
575
+ await this.engine.close();
540
576
  this.recreateEngine();
541
- this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);
542
577
  throw new ConnectionError(`Connection attempt aborted`);
543
578
  }
544
579
 
@@ -548,8 +583,8 @@ class Room extends EventEmitter<RoomEventCallbacks> {
548
583
  abortController,
549
584
  );
550
585
  } catch (e) {
586
+ await this.engine.close();
551
587
  this.recreateEngine();
552
- this.handleDisconnect(this.options.stopLocalTrackOnUnpublish);
553
588
  throw e;
554
589
  }
555
590
 
@@ -1270,6 +1305,67 @@ class Room extends EventEmitter<RoomEventCallbacks> {
1270
1305
  };
1271
1306
 
1272
1307
  private handleDeviceChange = async () => {
1308
+ const previousDevices = DeviceManager.getInstance().previousDevices;
1309
+ // check for available devices, but don't request permissions in order to avoid prompts for kinds that haven't been used before
1310
+ const availableDevices = await DeviceManager.getInstance().getDevices(undefined, false);
1311
+ const browser = getBrowser();
1312
+ if (browser?.name === 'Chrome' && browser.os !== 'iOS') {
1313
+ for (let availableDevice of availableDevices) {
1314
+ const previousDevice = previousDevices.find(
1315
+ (info) => info.deviceId === availableDevice.deviceId,
1316
+ );
1317
+ if (
1318
+ previousDevice &&
1319
+ previousDevice.label !== '' &&
1320
+ previousDevice.kind === availableDevice.kind &&
1321
+ previousDevice.label !== availableDevice.label
1322
+ ) {
1323
+ // label has changed on device the same deviceId, indicating that the default device has changed on the OS level
1324
+ if (this.getActiveDevice(availableDevice.kind) === 'default') {
1325
+ // emit an active device change event only if the selected output device is actually on `default`
1326
+ this.emit(
1327
+ RoomEvent.ActiveDeviceChanged,
1328
+ availableDevice.kind,
1329
+ availableDevice.deviceId,
1330
+ );
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ const kinds: MediaDeviceKind[] = ['audiooutput', 'audioinput', 'videoinput'];
1337
+ for (let kind of kinds) {
1338
+ const targetSource = kindToSource(kind);
1339
+ const targetPublication = this.localParticipant.getTrack(targetSource);
1340
+ if (targetPublication && targetPublication.track?.isUserProvided) {
1341
+ // if the track is user provided, we don't want to switch devices on behalf of the user
1342
+ continue;
1343
+ }
1344
+ const devicesOfKind = availableDevices.filter((d) => d.kind === kind);
1345
+ const activeDevice = this.getActiveDevice(kind);
1346
+
1347
+ if (activeDevice === previousDevices.filter((info) => info.kind === kind)[0]?.deviceId) {
1348
+ // in Safari the first device is always the default, so we assume a user on the default device would like to switch to the default once it changes
1349
+ // FF doesn't emit an event when the default device changes, so we perform the same best effort and switch to the new device once connected and if it's the first in the array
1350
+ if (devicesOfKind.length > 0 && devicesOfKind[0]?.deviceId !== activeDevice) {
1351
+ await this.switchActiveDevice(kind, devicesOfKind[0].deviceId);
1352
+ continue;
1353
+ }
1354
+ }
1355
+
1356
+ if ((kind === 'audioinput' && !isSafari()) || kind === 'videoinput') {
1357
+ // airpods on Safari need special handling for audioinput as the track doesn't end as soon as you take them out
1358
+ continue;
1359
+ }
1360
+ // switch to first available device if previously active device is not available any more
1361
+ if (
1362
+ devicesOfKind.length > 0 &&
1363
+ !devicesOfKind.find((deviceInfo) => deviceInfo.deviceId === this.getActiveDevice(kind))
1364
+ ) {
1365
+ await this.switchActiveDevice(kind, devicesOfKind[0].deviceId);
1366
+ }
1367
+ }
1368
+
1273
1369
  this.emit(RoomEvent.MediaDevicesChanged);
1274
1370
  };
1275
1371
 
package/src/room/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ClientInfo, ClientInfo_SDK } from '../proto/livekit_models';
1
+ import { ClientInfo, ClientInfo_SDK, DisconnectReason } from '../proto/livekit_models'
2
2
  import { getBrowser } from '../utils/browserParser';
3
3
  import { protocolVersion, version } from '../version';
4
4
  import type LocalAudioTrack from './track/LocalAudioTrack';
@@ -6,6 +6,8 @@ import type RemoteAudioTrack from './track/RemoteAudioTrack';
6
6
  import { VideoCodec, videoCodecs } from './track/options';
7
7
  import { getNewAudioContext } from './track/utils';
8
8
  import type { LiveKitReactNativeInfo } from './types';
9
+ import type { ConnectionError } from './errors'
10
+ import { ConnectionErrorReason } from './errors'
9
11
 
10
12
  const separator = '|';
11
13
  export const ddExtensionURI =
@@ -457,3 +459,14 @@ export function unwrapConstraint(constraint: ConstrainDOMString): string {
457
459
  }
458
460
  throw Error('could not unwrap constraint');
459
461
  }
462
+
463
+ export function getDisconnectReasonFromConnectionError(e: ConnectionError) {
464
+ switch (e.reason) {
465
+ case ConnectionErrorReason.Cancelled:
466
+ return DisconnectReason.CLIENT_INITIATED;
467
+ case ConnectionErrorReason.ServerUnreachable:
468
+ return DisconnectReason.JOIN_FAILURE;
469
+ default:
470
+ return DisconnectReason.UNKNOWN_REASON;
471
+ }
472
+ }