@fishjam-cloud/ts-client 0.8.1 → 0.10.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.
Files changed (57) hide show
  1. package/dist/index.d.mts +1308 -0
  2. package/dist/index.mjs +1 -0
  3. package/package.json +23 -33
  4. package/dist/src/FishjamClient.d.ts +0 -511
  5. package/dist/src/FishjamClient.js +0 -669
  6. package/dist/src/auth.d.ts +0 -3
  7. package/dist/src/auth.js +0 -8
  8. package/dist/src/connectEventsHandler.d.ts +0 -2
  9. package/dist/src/connectEventsHandler.js +0 -22
  10. package/dist/src/index.d.ts +0 -7
  11. package/dist/src/index.js +0 -3
  12. package/dist/src/protos/fishjam/peer_notifications.d.ts +0 -51
  13. package/dist/src/protos/fishjam/peer_notifications.js +0 -309
  14. package/dist/src/protos/index.d.ts +0 -1
  15. package/dist/src/protos/index.js +0 -1
  16. package/dist/src/reconnection.d.ts +0 -27
  17. package/dist/src/reconnection.js +0 -119
  18. package/dist/src/webrtc/CommandsQueue.d.ts +0 -23
  19. package/dist/src/webrtc/CommandsQueue.js +0 -87
  20. package/dist/src/webrtc/ConnectionManager.d.ts +0 -27
  21. package/dist/src/webrtc/ConnectionManager.js +0 -65
  22. package/dist/src/webrtc/bitrate.d.ts +0 -12
  23. package/dist/src/webrtc/bitrate.js +0 -12
  24. package/dist/src/webrtc/deferred.d.ts +0 -8
  25. package/dist/src/webrtc/deferred.js +0 -17
  26. package/dist/src/webrtc/index.d.ts +0 -3
  27. package/dist/src/webrtc/index.js +0 -1
  28. package/dist/src/webrtc/internal.d.ts +0 -26
  29. package/dist/src/webrtc/internal.js +0 -34
  30. package/dist/src/webrtc/mediaEvent.d.ts +0 -10
  31. package/dist/src/webrtc/mediaEvent.js +0 -16
  32. package/dist/src/webrtc/tracks/Local.d.ts +0 -50
  33. package/dist/src/webrtc/tracks/Local.js +0 -280
  34. package/dist/src/webrtc/tracks/LocalTrack.d.ts +0 -62
  35. package/dist/src/webrtc/tracks/LocalTrack.js +0 -225
  36. package/dist/src/webrtc/tracks/LocalTrackManager.d.ts +0 -38
  37. package/dist/src/webrtc/tracks/LocalTrackManager.js +0 -77
  38. package/dist/src/webrtc/tracks/Remote.d.ts +0 -38
  39. package/dist/src/webrtc/tracks/Remote.js +0 -200
  40. package/dist/src/webrtc/tracks/RemoteTrack.d.ts +0 -39
  41. package/dist/src/webrtc/tracks/RemoteTrack.js +0 -64
  42. package/dist/src/webrtc/tracks/TrackCommon.d.ts +0 -8
  43. package/dist/src/webrtc/tracks/TrackCommon.js +0 -1
  44. package/dist/src/webrtc/tracks/bandwidth.d.ts +0 -1
  45. package/dist/src/webrtc/tracks/bandwidth.js +0 -27
  46. package/dist/src/webrtc/tracks/encodings.d.ts +0 -1
  47. package/dist/src/webrtc/tracks/encodings.js +0 -5
  48. package/dist/src/webrtc/tracks/muteTrackUtils.d.ts +0 -3
  49. package/dist/src/webrtc/tracks/muteTrackUtils.js +0 -19
  50. package/dist/src/webrtc/tracks/transceivers.d.ts +0 -2
  51. package/dist/src/webrtc/tracks/transceivers.js +0 -91
  52. package/dist/src/webrtc/types.d.ts +0 -314
  53. package/dist/src/webrtc/types.js +0 -2
  54. package/dist/src/webrtc/voiceActivityDetection.d.ts +0 -2
  55. package/dist/src/webrtc/voiceActivityDetection.js +0 -2
  56. package/dist/src/webrtc/webRTCEndpoint.d.ts +0 -297
  57. package/dist/src/webrtc/webRTCEndpoint.js +0 -686
@@ -0,0 +1,1308 @@
1
+ import TypedEmitter from 'typed-emitter';
2
+ import { BinaryWriter, BinaryReader } from '@bufbuild/protobuf/wire';
3
+
4
+ declare enum Variant {
5
+ VARIANT_UNSPECIFIED = 0,
6
+ VARIANT_LOW = 1,
7
+ VARIANT_MEDIUM = 2,
8
+ VARIANT_HIGH = 3,
9
+ UNRECOGNIZED = -1
10
+ }
11
+ /** Contains information about an ICE candidate which will be sent to the peer/server */
12
+ interface Candidate {
13
+ candidate: string;
14
+ sdpMLineIndex: number;
15
+ sdpMid: string;
16
+ usernameFragment: string;
17
+ }
18
+ declare const Candidate: MessageFns$2<Candidate>;
19
+ type Builtin$2 = Date | Function | Uint8Array | string | number | boolean | undefined;
20
+ type DeepPartial$2<T> = T extends Builtin$2 ? T : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial$2<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial$2<U>> : T extends {} ? {
21
+ [K in keyof T]?: DeepPartial$2<T[K]>;
22
+ } : Partial<T>;
23
+ type KeysOfUnion$2<T> = T extends T ? keyof T : never;
24
+ type Exact$2<P, I extends P> = P extends Builtin$2 ? P : P & {
25
+ [K in keyof P]: Exact$2<P[K], I[K]>;
26
+ } & {
27
+ [K in Exclude<keyof I, KeysOfUnion$2<P>>]: never;
28
+ };
29
+ interface MessageFns$2<T> {
30
+ encode(message: T, writer?: BinaryWriter): BinaryWriter;
31
+ decode(input: BinaryReader | Uint8Array, length?: number): T;
32
+ fromJSON(object: any): T;
33
+ toJSON(message: T): unknown;
34
+ create<I extends Exact$2<DeepPartial$2<T>, I>>(base?: I): T;
35
+ fromPartial<I extends Exact$2<DeepPartial$2<T>, I>>(object: I): T;
36
+ }
37
+
38
+ interface MediaEvent_Track_SimulcastConfig {
39
+ enabled: boolean;
40
+ enabledVariants: Variant[];
41
+ disabledVariants: Variant[];
42
+ }
43
+ declare const MediaEvent_Track_SimulcastConfig: MessageFns$1<MediaEvent_Track_SimulcastConfig>;
44
+ interface MediaEvent_OfferData_TrackTypes {
45
+ audio: number;
46
+ video: number;
47
+ }
48
+ declare const MediaEvent_OfferData_TrackTypes: MessageFns$1<MediaEvent_OfferData_TrackTypes>;
49
+ type Builtin$1 = Date | Function | Uint8Array | string | number | boolean | undefined;
50
+ type DeepPartial$1<T> = T extends Builtin$1 ? T : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial$1<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial$1<U>> : T extends {} ? {
51
+ [K in keyof T]?: DeepPartial$1<T[K]>;
52
+ } : Partial<T>;
53
+ type KeysOfUnion$1<T> = T extends T ? keyof T : never;
54
+ type Exact$1<P, I extends P> = P extends Builtin$1 ? P : P & {
55
+ [K in keyof P]: Exact$1<P[K], I[K]>;
56
+ } & {
57
+ [K in Exclude<keyof I, KeysOfUnion$1<P>>]: never;
58
+ };
59
+ interface MessageFns$1<T> {
60
+ encode(message: T, writer?: BinaryWriter): BinaryWriter;
61
+ decode(input: BinaryReader | Uint8Array, length?: number): T;
62
+ fromJSON(object: any): T;
63
+ toJSON(message: T): unknown;
64
+ create<I extends Exact$1<DeepPartial$1<T>, I>>(base?: I): T;
65
+ fromPartial<I extends Exact$1<DeepPartial$1<T>, I>>(object: I): T;
66
+ }
67
+
68
+ /** Defines any type of message sent from Peer to Membrane RTC Engine */
69
+ interface MediaEvent$1 {
70
+ connect?: MediaEvent_Connect | undefined;
71
+ disconnect?: MediaEvent_Disconnect | undefined;
72
+ updateEndpointMetadata?: MediaEvent_UpdateEndpointMetadata | undefined;
73
+ updateTrackMetadata?: MediaEvent_UpdateTrackMetadata | undefined;
74
+ renegotiateTracks?: MediaEvent_RenegotiateTracks | undefined;
75
+ candidate?: Candidate | undefined;
76
+ sdpOffer?: MediaEvent_SdpOffer | undefined;
77
+ trackBitrates?: MediaEvent_TrackBitrates | undefined;
78
+ enableTrackVariant?: MediaEvent_EnableTrackVariant | undefined;
79
+ disableTrackVariant?: MediaEvent_DisableTrackVariant | undefined;
80
+ setTargetTrackVariant?: MediaEvent_SetTargetTrackVariant | undefined;
81
+ }
82
+ declare const MediaEvent$1: MessageFns<MediaEvent$1>;
83
+ interface MediaEvent_VariantBitrate {
84
+ variant: Variant;
85
+ bitrate: number;
86
+ }
87
+ declare const MediaEvent_VariantBitrate: MessageFns<MediaEvent_VariantBitrate>;
88
+ /** Sent when a peer wants to join WebRTC Endpoint. */
89
+ interface MediaEvent_Connect {
90
+ metadataJson: string;
91
+ }
92
+ declare const MediaEvent_Connect: MessageFns<MediaEvent_Connect>;
93
+ /** Sent when a peer disconnects from WebRTC Endpoint. */
94
+ interface MediaEvent_Disconnect {
95
+ }
96
+ declare const MediaEvent_Disconnect: MessageFns<MediaEvent_Disconnect>;
97
+ /** Sent when a peer wants to update its metadata */
98
+ interface MediaEvent_UpdateEndpointMetadata {
99
+ metadataJson: string;
100
+ }
101
+ declare const MediaEvent_UpdateEndpointMetadata: MessageFns<MediaEvent_UpdateEndpointMetadata>;
102
+ /** Sent when a peer wants to update its track's metadata */
103
+ interface MediaEvent_UpdateTrackMetadata {
104
+ trackId: string;
105
+ metadataJson: string;
106
+ }
107
+ declare const MediaEvent_UpdateTrackMetadata: MessageFns<MediaEvent_UpdateTrackMetadata>;
108
+ /** Sent when peer wants to renegatiate connection due to adding a track or removing a track */
109
+ interface MediaEvent_RenegotiateTracks {
110
+ }
111
+ declare const MediaEvent_RenegotiateTracks: MessageFns<MediaEvent_RenegotiateTracks>;
112
+ /**
113
+ * Sent as a response to `offerData` media event during renegotiation
114
+ * Maps contain only information about current peer's `sendonly` tracks.
115
+ * The "mid" is an identifier used to associate an RTP packet with an MLine from the SDP offer/answer.
116
+ */
117
+ interface MediaEvent_SdpOffer {
118
+ /** The value of the `sessionDescription.sdp` */
119
+ sdp: string;
120
+ trackIdToMetadataJson: {
121
+ [key: string]: string;
122
+ };
123
+ /** Maps track_id to its bitrate. The track_id in the TrackBitrates message is ignored (we use the map key), so it can be ommited. */
124
+ trackIdToBitrates: {
125
+ [key: string]: MediaEvent_TrackBitrates;
126
+ };
127
+ midToTrackId: {
128
+ [key: string]: string;
129
+ };
130
+ }
131
+ declare const MediaEvent_SdpOffer: MessageFns<MediaEvent_SdpOffer>;
132
+ /** Sent when Peer wants to update its track's bitrate */
133
+ interface MediaEvent_TrackBitrates {
134
+ trackId: string;
135
+ /** Bitrate of each variant. For non-simulcast tracks use VARIANT_UNSPECIFIED. */
136
+ variantBitrates: MediaEvent_VariantBitrate[];
137
+ }
138
+ declare const MediaEvent_TrackBitrates: MessageFns<MediaEvent_TrackBitrates>;
139
+ /** Sent when client disables one of the track variants */
140
+ interface MediaEvent_DisableTrackVariant {
141
+ trackId: string;
142
+ variant: Variant;
143
+ }
144
+ declare const MediaEvent_DisableTrackVariant: MessageFns<MediaEvent_DisableTrackVariant>;
145
+ /** Sent when client enables one of the track variants */
146
+ interface MediaEvent_EnableTrackVariant {
147
+ trackId: string;
148
+ variant: Variant;
149
+ }
150
+ declare const MediaEvent_EnableTrackVariant: MessageFns<MediaEvent_EnableTrackVariant>;
151
+ interface MediaEvent_SetTargetTrackVariant {
152
+ trackId: string;
153
+ variant: Variant;
154
+ }
155
+ declare const MediaEvent_SetTargetTrackVariant: MessageFns<MediaEvent_SetTargetTrackVariant>;
156
+ type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
157
+ type DeepPartial<T> = T extends Builtin ? T : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? {
158
+ [K in keyof T]?: DeepPartial<T[K]>;
159
+ } : Partial<T>;
160
+ type KeysOfUnion<T> = T extends T ? keyof T : never;
161
+ type Exact<P, I extends P> = P extends Builtin ? P : P & {
162
+ [K in keyof P]: Exact<P[K], I[K]>;
163
+ } & {
164
+ [K in Exclude<keyof I, KeysOfUnion<P>>]: never;
165
+ };
166
+ interface MessageFns<T> {
167
+ encode(message: T, writer?: BinaryWriter): BinaryWriter;
168
+ decode(input: BinaryReader | Uint8Array, length?: number): T;
169
+ fromJSON(object: any): T;
170
+ toJSON(message: T): unknown;
171
+ create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;
172
+ fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;
173
+ }
174
+
175
+ type SerializedMediaEvent = Uint8Array;
176
+ interface MediaEvent {
177
+ type: keyof MediaEvent$1;
178
+ key?: string;
179
+ data?: any;
180
+ }
181
+
182
+ type MediaStreamTrackId = string;
183
+ type TrackKind = 'audio' | 'video';
184
+ /**
185
+ * Type describing Voice Activity Detection statuses.
186
+ *
187
+ * - `speech` - voice activity has been detected
188
+ * - `silence` - lack of voice activity has been detected
189
+ */
190
+ type VadStatus = 'speech' | 'silence';
191
+ /**
192
+ * Type describing maximal bandwidth that can be used, in kbps. 0 is interpreted as unlimited bandwidth.
193
+ */
194
+ type BandwidthLimit = number;
195
+ /**
196
+ * Type describing bandwidth limit for simulcast track.
197
+ * It is a mapping (encoding => BandwidthLimit).
198
+ * If encoding isn't present in this mapping, it will be assumed that this particular encoding shouldn't have any bandwidth limit
199
+ */
200
+ type SimulcastBandwidthLimit = Map<Variant, BandwidthLimit>;
201
+ /**
202
+ * Type describing bandwidth limitation of a Track, including simulcast and non-simulcast tracks.
203
+ * A sum type of `BandwidthLimit` and `SimulcastBandwidthLimit`
204
+ */
205
+ type TrackBandwidthLimit = BandwidthLimit | SimulcastBandwidthLimit;
206
+ /**
207
+ * Type describing possible reasons for currently selected encoding.
208
+ * - `other` - the exact reason couldn't be determined
209
+ * - `encodingInactive` - previously selected encoding became inactive
210
+ * - `lowBandwidth` - there is no longer enough bandwidth to maintain previously selected encoding
211
+ */
212
+ type EncodingReason = 'other' | 'encodingInactive' | 'lowBandwidth';
213
+ /**
214
+ * Track's context i.e. all data that can be useful when operating on track.
215
+ */
216
+ interface TrackContextFields {
217
+ readonly track: MediaStreamTrack | null;
218
+ /**
219
+ * Stream this track belongs to.
220
+ */
221
+ readonly stream: MediaStream | null;
222
+ /**
223
+ * Endpoint this track comes from.
224
+ */
225
+ readonly endpoint: Endpoint;
226
+ /**
227
+ * Track id. It is generated by RTC engine and takes form `endpoint_id:<random_uuidv4>`.
228
+ * It is WebRTC agnostic i.e. it does not contain `mid` or `stream id`.
229
+ */
230
+ readonly trackId: string;
231
+ /**
232
+ * Simulcast configuration.
233
+ * Only present for local tracks.
234
+ */
235
+ readonly simulcastConfig?: MediaEvent_Track_SimulcastConfig;
236
+ /**
237
+ * Any info that was passed in {@link WebRTCEndpoint.addTrack}.
238
+ */
239
+ readonly metadata?: unknown;
240
+ readonly maxBandwidth?: TrackBandwidthLimit;
241
+ readonly vadStatus: VadStatus;
242
+ /**
243
+ * Encoding that is currently received.
244
+ * Only present for remote tracks.
245
+ */
246
+ readonly encoding?: Variant;
247
+ /**
248
+ * The reason of currently selected encoding.
249
+ * Only present for remote tracks.
250
+ */
251
+ readonly encodingReason?: EncodingReason;
252
+ }
253
+ interface TrackContextEvents$1 {
254
+ /**
255
+ * Emitted each time track encoding has changed.
256
+ *
257
+ * Track encoding can change in the following cases:
258
+ * - when user requested a change
259
+ * - when sender stopped sending some encoding (because of bandwidth change)
260
+ * - when receiver doesn't have enough bandwidth
261
+ *
262
+ * Some of those reasons are indicated in {@link TrackContext.encodingReason}.
263
+ */
264
+ encodingChanged: (context: TrackContext) => void;
265
+ /**
266
+ * Emitted every time an update about voice activity is received from the server.
267
+ */
268
+ voiceActivityChanged: (context: TrackContext) => void;
269
+ }
270
+ interface TrackContext extends TrackContextFields, TypedEmitter<Required<TrackContextEvents$1>> {
271
+ }
272
+ type TrackNegotiationStatus = 'awaiting' | 'offered' | 'done';
273
+ /**
274
+ * Events emitted by the {@link WebRTCEndpoint} instance.
275
+ */
276
+ interface WebRTCEndpointEvents {
277
+ /**
278
+ * Emitted each time WebRTCEndpoint need to send some data to the server.
279
+ */
280
+ sendMediaEvent: (mediaEvent: SerializedMediaEvent) => void;
281
+ /**
282
+ * Emitted when endpoint of this {@link WebRTCEndpoint} instance is ready. Triggered by {@link WebRTCEndpoint.connect}
283
+ */
284
+ connected: (endpointId: string, otherEndpoints: Endpoint[]) => void;
285
+ /**
286
+ * Emitted when endpoint of this {@link WebRTCEndpoint} instance was removed.
287
+ */
288
+ disconnected: () => void;
289
+ /**
290
+ * Emitted when data in a new track arrives.
291
+ *
292
+ * This event is always emitted after {@link trackAdded}.
293
+ * It informs the user that data related to the given track arrives and can be played or displayed.
294
+ */
295
+ trackReady: (ctx: TrackContext) => void;
296
+ /**
297
+ * Emitted each time the endpoint which was already in the room, adds new track. Fields track and stream will be set to null.
298
+ * These fields will be set to non-null value in {@link trackReady}
299
+ */
300
+ trackAdded: (ctx: TrackContext) => void;
301
+ /**
302
+ * Emitted when some track will no longer be sent.
303
+ *
304
+ * It will also be emitted before {@link endpointRemoved} for each track of this endpoint.
305
+ */
306
+ trackRemoved: (ctx: TrackContext) => void;
307
+ /**
308
+ * Emitted each time endpoint has its track metadata updated.
309
+ */
310
+ trackUpdated: (ctx: TrackContext) => void;
311
+ /**
312
+ * Emitted each time new endpoint is added to the room.
313
+ */
314
+ endpointAdded: (endpoint: Endpoint) => void;
315
+ /**
316
+ * Emitted each time endpoint is removed, emitted only for other endpoints.
317
+ */
318
+ endpointRemoved: (endpoint: Endpoint) => void;
319
+ /**
320
+ * Emitted each time endpoint has its metadata updated.
321
+ */
322
+ endpointUpdated: (endpoint: Endpoint) => void;
323
+ /**
324
+ * Emitted in case of errors related to multimedia session e.g. ICE connection.
325
+ */
326
+ connectionError: (error: {
327
+ message: string;
328
+ event: Event;
329
+ }) => void;
330
+ /**
331
+ * Emitted in case of errors related to multimedia session e.g. ICE connection.
332
+ */
333
+ signalingError: (error: {
334
+ message: string;
335
+ }) => void;
336
+ /**
337
+ * Currently, this event is only emitted when DisplayManager in RTC Engine is
338
+ * enabled and simulcast is disabled.
339
+ *
340
+ * Emitted when priority of video tracks have changed.
341
+ * @param enabledTracks - list of tracks which will be sent to client from SFU
342
+ * @param disabledTracks - list of tracks which will not be sent to client from SFU
343
+ */
344
+ tracksPriorityChanged: (enabledTracks: TrackContext[], disabledTracks: TrackContext[]) => void;
345
+ /**
346
+ * Emitted every time the server estimates client's bandwidth.
347
+ *
348
+ * @param {bigint} estimation - client's available incoming bitrate estimated
349
+ * by the server. It's measured in bits per second.
350
+ */
351
+ bandwidthEstimationChanged: (estimation: bigint) => void;
352
+ /**
353
+ * Emitted each time track encoding has been disabled.
354
+ */
355
+ trackEncodingDisabled: (context: TrackContext, encoding: Variant) => void;
356
+ /**
357
+ * Emitted each time track encoding has been enabled.
358
+ */
359
+ trackEncodingEnabled: (context: TrackContext, encoding: Variant) => void;
360
+ targetTrackEncodingRequested: (event: {
361
+ trackId: string;
362
+ variant: Variant;
363
+ }) => void;
364
+ disconnectRequested: (event: any) => void;
365
+ localTrackAdded: (event: {
366
+ trackId: string;
367
+ track: MediaStreamTrack;
368
+ stream: MediaStream;
369
+ trackMetadata?: unknown;
370
+ simulcastConfig: MediaEvent_Track_SimulcastConfig;
371
+ maxBandwidth: TrackBandwidthLimit;
372
+ }) => void;
373
+ localTrackRemoved: (event: {
374
+ trackId: string;
375
+ }) => void;
376
+ localTrackReplaced: (event: {
377
+ trackId: string;
378
+ track: MediaStreamTrack | null;
379
+ }) => void;
380
+ localTrackMuted: (event: {
381
+ trackId: string;
382
+ }) => void;
383
+ localTrackUnmuted: (event: {
384
+ trackId: string;
385
+ }) => void;
386
+ localTrackBandwidthSet: (event: {
387
+ trackId: string;
388
+ bandwidth: BandwidthLimit;
389
+ }) => void;
390
+ localTrackEncodingBandwidthSet: (event: {
391
+ trackId: string;
392
+ rid: Variant;
393
+ bandwidth: BandwidthLimit;
394
+ }) => void;
395
+ localTrackEncodingEnabled: (event: {
396
+ trackId: string;
397
+ encoding: Variant;
398
+ }) => void;
399
+ localTrackEncodingDisabled: (event: {
400
+ trackId: string;
401
+ encoding: Variant;
402
+ }) => void;
403
+ localEndpointMetadataChanged: (event: {
404
+ metadata: unknown;
405
+ }) => void;
406
+ localTrackMetadataChanged: (event: {
407
+ trackId: string;
408
+ metadata: unknown;
409
+ }) => void;
410
+ }
411
+ /**
412
+ * Interface describing Endpoint.
413
+ */
414
+ interface Endpoint {
415
+ /**
416
+ * Endpoint's id. It is assigned by user in custom logic that use backend API.
417
+ */
418
+ id: string;
419
+ /**
420
+ * Type of the endpoint, e.g. "webrtc", "hls" or "rtsp".
421
+ */
422
+ type: string;
423
+ /**
424
+ * Any information that was provided in {@link WebRTCEndpoint.connect}.
425
+ */
426
+ metadata?: unknown;
427
+ /**
428
+ * List of tracks that are sent by the endpoint.
429
+ */
430
+ tracks: Map<string, TrackContext>;
431
+ }
432
+
433
+ declare const TrackContextImpl_base: new () => TypedEmitter<Required<TrackContextEvents$1>>;
434
+ declare class TrackContextImpl extends TrackContextImpl_base implements TrackContext {
435
+ endpoint: Endpoint;
436
+ trackId: string;
437
+ track: MediaStreamTrack | null;
438
+ trackKind: TrackKind | null;
439
+ stream: MediaStream | null;
440
+ metadata?: unknown;
441
+ metadataParsingError?: any;
442
+ simulcastConfig?: MediaEvent_Track_SimulcastConfig;
443
+ maxBandwidth: TrackBandwidthLimit;
444
+ encoding?: Variant;
445
+ encodingReason?: EncodingReason;
446
+ vadStatus: VadStatus;
447
+ negotiationStatus: TrackNegotiationStatus;
448
+ pendingMetadataUpdate: boolean;
449
+ constructor(endpoint: Endpoint, trackId: string, metadata: any, simulcastConfig?: MediaEvent_Track_SimulcastConfig);
450
+ }
451
+ type EndpointWithTrackContext = Omit<Endpoint, 'tracks'> & {
452
+ tracks: Map<string, TrackContextImpl>;
453
+ };
454
+
455
+ declare class ConnectionManager {
456
+ private readonly connection;
457
+ constructor(iceServers: RTCIceServer[]);
458
+ isConnectionUnstable: () => boolean;
459
+ getConnection: () => RTCPeerConnection;
460
+ addTransceiversIfNeeded: (serverTracks: MediaEvent_OfferData_TrackTypes) => void;
461
+ addTransceiver: (track: MediaStreamTrack, transceiverConfig: RTCRtpTransceiverInit) => void;
462
+ setOnTrackReady: (onTrackReady: (event: RTCTrackEvent) => void) => void;
463
+ setRemoteDescription: (data: RTCSessionDescriptionInit) => Promise<void>;
464
+ isTrackInUse: (track: MediaStreamTrack) => boolean;
465
+ removeTrack: (sender: RTCRtpSender) => void;
466
+ findSender: (mediaStreamTrackId: MediaStreamTrackId) => RTCRtpSender;
467
+ addIceCandidate: (iceCandidate: RTCIceCandidate) => Promise<void>;
468
+ }
469
+
470
+ declare const WebRTCEndpoint_base: new () => TypedEmitter<Required<WebRTCEndpointEvents>>;
471
+ /**
472
+ * Main class that is responsible for connecting to the RTC Engine, sending and receiving media.
473
+ */
474
+ declare class WebRTCEndpoint extends WebRTCEndpoint_base {
475
+ private readonly localTrackManager;
476
+ private readonly remote;
477
+ private readonly local;
478
+ private readonly commandsQueue;
479
+ private proposedIceServers;
480
+ bandwidthEstimation: bigint;
481
+ connectionManager?: ConnectionManager;
482
+ private clearConnectionCallbacks;
483
+ constructor();
484
+ /**
485
+ * Tries to connect to the RTC Engine. If user is successfully connected then {@link WebRTCEndpointEvents.connected}
486
+ * will be emitted.
487
+ *
488
+ * @param metadata - Any information that other endpoints will receive in {@link WebRTCEndpointEvents.endpointAdded}
489
+ * after accepting this endpoint
490
+ *
491
+ * @example
492
+ * ```ts
493
+ * let webrtc = new WebRTCEndpoint();
494
+ * webrtc.connect({displayName: "Bob"});
495
+ * ```
496
+ */
497
+ connect: (metadata: unknown) => void;
498
+ /**
499
+ * Feeds media event received from RTC Engine to {@link WebRTCEndpoint}.
500
+ * This function should be called whenever some media event from RTC Engine
501
+ * was received and can result in {@link WebRTCEndpoint} generating some other
502
+ * media events.
503
+ *
504
+ * @param mediaEvent - String data received over custom signalling layer.
505
+ *
506
+ * @example
507
+ * This example assumes phoenix channels as signalling layer.
508
+ * As phoenix channels require objects, RTC Engine encapsulates binary data into
509
+ * map with one field that is converted to object with one field on the TS side.
510
+ * ```ts
511
+ * webrtcChannel.on("mediaEvent", (event) => webrtc.receiveMediaEvent(event.data));
512
+ * ```
513
+ */
514
+ receiveMediaEvent: (mediaEvent: SerializedMediaEvent) => Promise<void>;
515
+ private getEndpointId;
516
+ private onTrackReady;
517
+ /**
518
+ * Retrieves statistics related to the RTCPeerConnection.
519
+ * These statistics provide insights into the performance and status of the connection.
520
+ *
521
+ * @return {Promise<RTCStatsReport>}
522
+ *
523
+ * @external RTCPeerConnection#getStats()
524
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats | MDN Web Docs: RTCPeerConnection.getStats()}
525
+ */
526
+ getStatistics(selector?: MediaStreamTrack | null): Promise<RTCStatsReport>;
527
+ /**
528
+ * Returns a snapshot of currently received remote tracks.
529
+ *
530
+ * @example
531
+ * if (webRTCEndpoint.getRemoteTracks()[trackId]?.simulcastConfig?.enabled) {
532
+ * webRTCEndpoint.setTargetTrackEncoding(trackId, encoding);
533
+ * }
534
+ */
535
+ getRemoteTracks(): Record<string, TrackContext>;
536
+ /**
537
+ * Returns a snapshot of currently received remote endpoints.
538
+ */
539
+ getRemoteEndpoints(): Record<string, EndpointWithTrackContext>;
540
+ getLocalEndpoint(): EndpointWithTrackContext;
541
+ getBandwidthEstimation(): bigint;
542
+ private handleMediaEvent;
543
+ private onSdpAnswer;
544
+ /**
545
+ * Adds track that will be sent to the RTC Engine.
546
+ * @param track - Audio or video track e.g. from your microphone or camera.
547
+ * @param trackMetadata - Any information about this track that other endpoints will
548
+ * receive in {@link WebRTCEndpointEvents.endpointAdded}. E.g. this can source of the track - whether it's
549
+ * screensharing, webcam or some other media device.
550
+ * @param simulcastConfig - Simulcast configuration. By default simulcast is disabled.
551
+ * For more information refer to {@link SimulcastConfig}.
552
+ * @param maxBandwidth - maximal bandwidth this track can use.
553
+ * Defaults to 0 which is unlimited.
554
+ * This option has no effect for simulcast and audio tracks.
555
+ * For simulcast tracks use `{@link WebRTCEndpoint.setTrackBandwidth}.
556
+ * @returns {string} Returns id of added track
557
+ * @example
558
+ * ```ts
559
+ * let localStream: MediaStream = new MediaStream();
560
+ * try {
561
+ * localAudioStream = await navigator.mediaDevices.getUserMedia(
562
+ * AUDIO_CONSTRAINTS
563
+ * );
564
+ * localAudioStream
565
+ * .getTracks()
566
+ * .forEach((track) => localStream.addTrack(track));
567
+ * } catch (error) {
568
+ * console.error("Couldn't get microphone permission:", error);
569
+ * }
570
+ *
571
+ * try {
572
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
573
+ * VIDEO_CONSTRAINTS
574
+ * );
575
+ * localVideoStream
576
+ * .getTracks()
577
+ * .forEach((track) => localStream.addTrack(track));
578
+ * } catch (error) {
579
+ * console.error("Couldn't get camera permission:", error);
580
+ * }
581
+ *
582
+ * localStream
583
+ * .getTracks()
584
+ * .forEach((track) => webrtc.addTrack(track, localStream));
585
+ * ```
586
+ */
587
+ addTrack(track: MediaStreamTrack, trackMetadata?: unknown, simulcastConfig?: MediaEvent_Track_SimulcastConfig, maxBandwidth?: TrackBandwidthLimit): Promise<string>;
588
+ /**
589
+ * Replaces a track that is being sent to the RTC Engine.
590
+ * @param trackId - Audio or video track.
591
+ * @param {string} trackId - Id of audio or video track to replace.
592
+ * @param {MediaStreamTrack} newTrack
593
+ * @returns {Promise<boolean>} success
594
+ * @example
595
+ * ```ts
596
+ * // setup camera
597
+ * let localStream: MediaStream = new MediaStream();
598
+ * try {
599
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
600
+ * VIDEO_CONSTRAINTS
601
+ * );
602
+ * localVideoStream
603
+ * .getTracks()
604
+ * .forEach((track) => localStream.addTrack(track));
605
+ * } catch (error) {
606
+ * console.error("Couldn't get camera permission:", error);
607
+ * }
608
+ * let oldTrackId;
609
+ * localStream
610
+ * .getTracks()
611
+ * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
612
+ *
613
+ * // change camera
614
+ * const oldTrack = localStream.getVideoTracks()[0];
615
+ * let videoDeviceId = "abcd-1234";
616
+ * navigator.mediaDevices.getUserMedia({
617
+ * video: {
618
+ * ...(VIDEO_CONSTRAINTS as {}),
619
+ * deviceId: {
620
+ * exact: videoDeviceId,
621
+ * },
622
+ * }
623
+ * })
624
+ * .then((stream) => {
625
+ * let videoTrack = stream.getVideoTracks()[0];
626
+ * webrtc.replaceTrack(oldTrackId, videoTrack);
627
+ * })
628
+ * .catch((error) => {
629
+ * console.error('Error switching camera', error);
630
+ * })
631
+ * ```
632
+ */
633
+ replaceTrack(trackId: string, newTrack: MediaStreamTrack | null): Promise<void>;
634
+ /**
635
+ * Updates maximum bandwidth for the track identified by trackId.
636
+ * This value directly translates to quality of the stream and, in case of video, to the amount of RTP packets being sent.
637
+ * In case trackId points at the simulcast track bandwidth is split between all of the variant streams proportionally to their resolution.
638
+ *
639
+ * @param {string} trackId
640
+ * @param {BandwidthLimit} bandwidth in kbps
641
+ * @returns {Promise<boolean>} success
642
+ */
643
+ setTrackBandwidth(trackId: string, bandwidth: BandwidthLimit): Promise<void>;
644
+ /**
645
+ * Updates maximum bandwidth for the given simulcast encoding of the given track.
646
+ *
647
+ * @param {string} trackId - id of the track
648
+ * @param {string} rid - rid of the encoding
649
+ * @param {BandwidthLimit} bandwidth - desired max bandwidth used by the encoding (in kbps)
650
+ * @returns
651
+ */
652
+ setEncodingBandwidth(trackId: string, rid: Variant, bandwidth: BandwidthLimit): Promise<void>;
653
+ /**
654
+ * Removes a track from connection that was sent to the RTC Engine.
655
+ * @param {string} trackId - Id of audio or video track to remove.
656
+ * @example
657
+ * ```ts
658
+ * // setup camera
659
+ * let localStream: MediaStream = new MediaStream();
660
+ * try {
661
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
662
+ * VIDEO_CONSTRAINTS
663
+ * );
664
+ * localVideoStream
665
+ * .getTracks()
666
+ * .forEach((track) => localStream.addTrack(track));
667
+ * } catch (error) {
668
+ * console.error("Couldn't get camera permission:", error);
669
+ * }
670
+ *
671
+ * let trackId
672
+ * localStream
673
+ * .getTracks()
674
+ * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
675
+ *
676
+ * // remove track
677
+ * webrtc.removeTrack(trackId)
678
+ * ```
679
+ */
680
+ removeTrack(trackId: string): Promise<void>;
681
+ /**
682
+ * Sets track variant that server should send to the client library.
683
+ *
684
+ * The variant will be sent whenever it is available.
685
+ * If chosen variant is temporarily unavailable, some other variant
686
+ * will be sent until the chosen variant becomes active again.
687
+ *
688
+ * @param {string} trackId - id of track
689
+ * @param {Encoding} variant - variant to receive
690
+ * @example
691
+ * ```ts
692
+ * webrtc.setTargetTrackEncoding(incomingTrackCtx.trackId, "l")
693
+ * ```
694
+ */
695
+ setTargetTrackEncoding(trackId: string, variant: Variant): void;
696
+ /**
697
+ * Enables track encoding so that it will be sent to the server.
698
+ * @param {string} trackId - id of track
699
+ * @param {Encoding} encoding - encoding that will be enabled
700
+ * @example
701
+ * ```ts
702
+ * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, activeEncodings: ["l", "m", "h"]});
703
+ * webrtc.disableTrackEncoding(trackId, "l");
704
+ * // wait some time
705
+ * webrtc.enableTrackEncoding(trackId, "l");
706
+ * ```
707
+ */
708
+ enableTrackEncoding: (trackId: string, encoding: Variant) => Promise<void>;
709
+ /**
710
+ * Disables track encoding so that it will be no longer sent to the server.
711
+ * @param {string} trackId - id of track
712
+ * @param {Encoding} encoding - encoding that will be disabled
713
+ * @example
714
+ * ```ts
715
+ * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, activeEncodings: ["l", "m", "h"]});
716
+ * webrtc.disableTrackEncoding(trackId, "l");
717
+ * ```
718
+ */
719
+ disableTrackEncoding: (trackId: string, encoding: Variant) => Promise<void>;
720
+ /**
721
+ * Updates the metadata for the current endpoint.
722
+ * @param metadata - Data about this endpoint that other endpoints will receive upon being added.
723
+ *
724
+ * If the metadata is different from what is already tracked in the room, the optional
725
+ * event `endpointUpdated` will be emitted for other endpoint in the room.
726
+ */
727
+ updateEndpointMetadata: (metadata: any) => void;
728
+ /**
729
+ * Updates the metadata for a specific track.
730
+ * @param trackId - trackId (generated in addTrack) of audio or video track.
731
+ * @param trackMetadata - Data about this track that other endpoint will receive upon being added.
732
+ *
733
+ * If the metadata is different from what is already tracked in the room, the optional
734
+ * event `trackUpdated` will be emitted for other endpoints in the room.
735
+ */
736
+ updateTrackMetadata: (trackId: string, trackMetadata: any) => void;
737
+ /**
738
+ * Disconnects from the room. This function should be called when user disconnects from the room
739
+ * in a clean way e.g. by clicking a dedicated, custom button `disconnect`.
740
+ * As a result there will be generated one more media event that should be
741
+ * sent to the RTC Engine. Thanks to it each other endpoint will be notified
742
+ * that endpoint was removed in {@link WebRTCEndpointEvents.endpointRemoved},
743
+ */
744
+ disconnect: () => void;
745
+ /**
746
+ * Cleans up {@link WebRTCEndpoint} instance.
747
+ */
748
+ cleanUp: () => void;
749
+ private getTrackId;
750
+ private sendMediaEvent;
751
+ private createAndSendOffer;
752
+ private onOfferData;
753
+ private setupConnectionListeners;
754
+ private createNewConnection;
755
+ private onRemoteCandidate;
756
+ private onLocalCandidate;
757
+ private onIceCandidateError;
758
+ private onConnectionStateChange;
759
+ private onIceConnectionStateChange;
760
+ }
761
+
762
+ declare const AUTH_ERROR_REASONS: readonly ["missing token", "invalid token", "expired token", "room not found", "peer not found"];
763
+ type AuthErrorReason = (typeof AUTH_ERROR_REASONS)[number];
764
+ declare const isAuthError: (error: string) => error is AuthErrorReason;
765
+
766
+ declare const FishjamClient_base: {
767
+ new <PeerMetadata_1, ServerMetadata_1>(): TypedEmitter<MessageEvents<PeerMetadata_1, ServerMetadata_1>>;
768
+ };
769
+ /**
770
+ * FishjamClient is the main class to interact with Fishjam.
771
+ *
772
+ * @example
773
+ * ```typescript
774
+ * const client = new FishjamClient<PeerMetadata>();
775
+ * const peerToken = "YOUR_PEER_TOKEN";
776
+ *
777
+ * // You can listen to events emitted by the client
778
+ * client.on("joined", (peerId, peersInRoom) => {
779
+ * console.log("join success");
780
+ * });
781
+ *
782
+ * // Start the peer connection
783
+ * client.connect({
784
+ * peerMetadata: {},
785
+ * isSimulcastOn: false,
786
+ * token: peerToken
787
+ * });
788
+ *
789
+ * // Close the peer connection
790
+ * client.disconnect();
791
+ * ```
792
+ *
793
+ * You can register callbacks to handle the events emitted by the Client.
794
+ *
795
+ * @example
796
+ * ```typescript
797
+ *
798
+ * client.on("trackReady", (ctx) => {
799
+ * console.log("On track ready");
800
+ * });
801
+ * ```
802
+ */
803
+ declare class FishjamClient<PeerMetadata = GenericMetadata, ServerMetadata = GenericMetadata> extends FishjamClient_base<PeerMetadata, ServerMetadata> {
804
+ private websocket;
805
+ private webrtc;
806
+ private removeEventListeners;
807
+ status: 'new' | 'initialized';
808
+ private connectConfig;
809
+ private reconnectManager;
810
+ private sendStatisticsInterval;
811
+ constructor(config?: CreateConfig);
812
+ /**
813
+ * Uses the {@link !WebSocket} connection and {@link !WebRTCEndpoint | WebRTCEndpoint} to join to the room. Registers the callbacks to
814
+ * handle the events emitted by the {@link !WebRTCEndpoint | WebRTCEndpoint}. Make sure that peer metadata is serializable.
815
+ *
816
+ * @example
817
+ * ```typescript
818
+ * const client = new FishjamClient<PeerMetadata>();
819
+ *
820
+ * client.connect({
821
+ * peerMetadata: {},
822
+ * token: peerToken
823
+ * });
824
+ * ```
825
+ *
826
+ * @param {ConnectConfig} config - Configuration object for the client
827
+ */
828
+ connect(config: ConnectConfig<PeerMetadata>): Promise<void>;
829
+ private initConnection;
830
+ private getUrl;
831
+ private initWebsocket;
832
+ /**
833
+ * Retrieves statistics related to the RTCPeerConnection.
834
+ * These statistics provide insights into the performance and status of the connection.
835
+ *
836
+ * @return {Promise<RTCStatsReport>}
837
+ *
838
+ * @external RTCPeerConnection#getStats()
839
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats | MDN Web Docs: RTCPeerConnection.getStats()}
840
+ */
841
+ getStatistics(selector?: MediaStreamTrack | null): Promise<RTCStatsReport>;
842
+ /**
843
+ * Returns a snapshot of currently received remote tracks.
844
+ *
845
+ * @example
846
+ * if (client.getRemoteTracks()[trackId]?.simulcastConfig?.enabled) {
847
+ * client.setTargetTrackEncoding(trackId, encoding);
848
+ * }
849
+ */
850
+ getRemoteTracks(): Readonly<Record<string, FishjamTrackContext>>;
851
+ /**
852
+ * Returns a snapshot of currently received remote peers.
853
+ */
854
+ getRemotePeers(): Record<string, Peer<PeerMetadata, ServerMetadata>>;
855
+ getRemoteComponents(): Record<string, Component>;
856
+ getLocalPeer(): Peer<PeerMetadata, ServerMetadata> | null;
857
+ getBandwidthEstimation(): bigint;
858
+ private setupCallbacks;
859
+ private sendStatistics;
860
+ /**
861
+ * Register a callback to be called when the event is emitted.
862
+ * Full list of callbacks can be found here {@link MessageEvents}.
863
+ *
864
+ * @example
865
+ * ```ts
866
+ * const callback = ()=>{ };
867
+ *
868
+ * client.on("onJoinSuccess", callback);
869
+ * ```
870
+ *
871
+ * @param event - Event name from {@link MessageEvents}
872
+ * @param listener - Callback function to be called when the event is emitted
873
+ * @returns This
874
+ */
875
+ on<E extends keyof MessageEvents<PeerMetadata, ServerMetadata>>(event: E, listener: MessageEvents<PeerMetadata, ServerMetadata>[E]): this;
876
+ /**
877
+ * Remove a callback from the list of callbacks to be called when the event is emitted.
878
+ *
879
+ * @example
880
+ * ```ts
881
+ * const callback = ()=>{ };
882
+ *
883
+ * client.on("onJoinSuccess", callback);
884
+ *
885
+ * client.off("onJoinSuccess", callback);
886
+ * ```
887
+ *
888
+ * @param event - Event name from {@link MessageEvents}
889
+ * @param listener - Reference to function to be removed from called callbacks
890
+ * @returns This
891
+ */
892
+ off<E extends keyof MessageEvents<PeerMetadata, ServerMetadata>>(event: E, listener: MessageEvents<PeerMetadata, ServerMetadata>[E]): this;
893
+ private handleWebRTCNotInitialized;
894
+ /**
895
+ * Adds track that will be sent to the RTC Engine.
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * const localStream: MediaStream = new MediaStream();
900
+ * try {
901
+ * const localAudioStream = await navigator.mediaDevices.getUserMedia(
902
+ * { audio: true }
903
+ * );
904
+ * localAudioStream
905
+ * .getTracks()
906
+ * .forEach((track) => localStream.addTrack(track));
907
+ * } catch (error) {
908
+ * console.error("Couldn't get microphone permission:", error);
909
+ * }
910
+ *
911
+ * try {
912
+ * const localVideoStream = await navigator.mediaDevices.getUserMedia(
913
+ * { video: true }
914
+ * );
915
+ * localVideoStream
916
+ * .getTracks()
917
+ * .forEach((track) => localStream.addTrack(track));
918
+ * } catch (error) {
919
+ * console.error("Couldn't get camera permission:", error);
920
+ * }
921
+ *
922
+ * localStream
923
+ * .getTracks()
924
+ * .forEach((track) => client.addTrack(track, localStream));
925
+ * ```
926
+ *
927
+ * @param track - Audio or video track e.g. from your microphone or camera.
928
+ * @param trackMetadata - Any information about this track that other peers will receive in
929
+ * {@link MessageEvents.peerJoined}. E.g. this can source of the track - wheather it's screensharing, webcam or some
930
+ * other media device.
931
+ * @param simulcastConfig - Simulcast configuration. By default, simulcast is disabled. For more information refer to
932
+ * {@link !SimulcastConfig | SimulcastConfig}.
933
+ * @param maxBandwidth - Maximal bandwidth this track can use. Defaults to 0 which is unlimited. This option has no
934
+ * effect for simulcast and audio tracks. For simulcast tracks use {@link FishjamClient.setTrackBandwidth}.
935
+ * @returns {string} Returns id of added track
936
+ */
937
+ addTrack(track: MediaStreamTrack, trackMetadata?: TrackMetadata, simulcastConfig?: MediaEvent_Track_SimulcastConfig, maxBandwidth?: TrackBandwidthLimit): Promise<string>;
938
+ /**
939
+ * Replaces a track that is being sent to the RTC Engine.
940
+ *
941
+ * @example
942
+ * ```ts
943
+ * // setup camera
944
+ * let localStream: MediaStream = new MediaStream();
945
+ * try {
946
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
947
+ * VIDEO_CONSTRAINTS
948
+ * );
949
+ * localVideoStream
950
+ * .getTracks()
951
+ * .forEach((track) => localStream.addTrack(track));
952
+ * } catch (error) {
953
+ * console.error("Couldn't get camera permission:", error);
954
+ * }
955
+ * let oldTrackId;
956
+ * localStream
957
+ * .getTracks()
958
+ * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
959
+ *
960
+ * // change camera
961
+ * const oldTrack = localStream.getVideoTracks()[0];
962
+ * let videoDeviceId = "abcd-1234";
963
+ * navigator.mediaDevices.getUserMedia({
964
+ * video: {
965
+ * ...(VIDEO_CONSTRAINTS as {}),
966
+ * deviceId: {
967
+ * exact: videoDeviceId,
968
+ * },
969
+ * }
970
+ * })
971
+ * .then((stream) => {
972
+ * let videoTrack = stream.getVideoTracks()[0];
973
+ * webrtc.replaceTrack(oldTrackId, videoTrack);
974
+ * })
975
+ * .catch((error) => {
976
+ * console.error('Error switching camera', error);
977
+ * })
978
+ * ```
979
+ *
980
+ * @param {string} trackId - Id of audio or video track to replace.
981
+ * @param {MediaStreamTrack} newTrack - New audio or video track.
982
+ * @returns {Promise<boolean>} Success
983
+ */
984
+ replaceTrack(trackId: string, newTrack: MediaStreamTrack | null): Promise<void>;
985
+ /**
986
+ * Updates maximum bandwidth for the track identified by trackId. This value directly translates to quality of the
987
+ * stream and, in case of video, to the amount of RTP packets being sent. In case trackId points at the simulcast
988
+ * track bandwidth is split between all of the variant streams proportionally to their resolution.
989
+ *
990
+ * @param {string} trackId
991
+ * @param {BandwidthLimit} bandwidth In kbps
992
+ * @returns {Promise<boolean>} Success
993
+ */
994
+ setTrackBandwidth(trackId: string, bandwidth: BandwidthLimit): Promise<boolean>;
995
+ /**
996
+ * Updates maximum bandwidth for the given simulcast encoding of the given track.
997
+ *
998
+ * @param {string} trackId - Id of the track
999
+ * @param {string} rid - Rid of the encoding
1000
+ * @param {BandwidthLimit} bandwidth - Desired max bandwidth used by the encoding (in kbps)
1001
+ * @returns
1002
+ */
1003
+ setEncodingBandwidth(trackId: string, rid: Variant, bandwidth: BandwidthLimit): Promise<boolean>;
1004
+ /**
1005
+ * Removes a track from connection that was being sent to the RTC Engine.
1006
+ *
1007
+ * @example
1008
+ * ```ts
1009
+ * // setup camera
1010
+ * let localStream: MediaStream = new MediaStream();
1011
+ * try {
1012
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
1013
+ * VIDEO_CONSTRAINTS
1014
+ * );
1015
+ * localVideoStream
1016
+ * .getTracks()
1017
+ * .forEach((track) => localStream.addTrack(track));
1018
+ * } catch (error) {
1019
+ * console.error("Couldn't get camera permission:", error);
1020
+ * }
1021
+ *
1022
+ * let trackId
1023
+ * localStream
1024
+ * .getTracks()
1025
+ * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
1026
+ *
1027
+ * // remove track
1028
+ * webrtc.removeTrack(trackId)
1029
+ * ```
1030
+ *
1031
+ * @param {string} trackId - Id of audio or video track to remove.
1032
+ */
1033
+ removeTrack(trackId: string): Promise<void>;
1034
+ /**
1035
+ * Sets track encoding that server should send to the client library.
1036
+ *
1037
+ * The encoding will be sent whenever it is available. If chosen encoding is temporarily unavailable, some other
1038
+ * encoding will be sent until chosen encoding becomes active again.
1039
+ *
1040
+ * @example
1041
+ * ```ts
1042
+ * webrtc.setTargetTrackEncoding(incomingTrackCtx.trackId, "l")
1043
+ * ```
1044
+ *
1045
+ * @param {string} trackId - Id of track
1046
+ * @param {Encoding} encoding - Encoding to receive
1047
+ */
1048
+ setTargetTrackEncoding(trackId: string, encoding: Variant): void;
1049
+ /**
1050
+ * Enables track encoding so that it will be sent to the server.
1051
+ *
1052
+ * @example
1053
+ * ```ts
1054
+ * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, active_encodings: ["l", "m", "h"]});
1055
+ * webrtc.disableTrackEncoding(trackId, "l");
1056
+ * // wait some time
1057
+ * webrtc.enableTrackEncoding(trackId, "l");
1058
+ * ```
1059
+ *
1060
+ * @param {string} trackId - Id of track
1061
+ * @param {Encoding} encoding - Encoding that will be enabled
1062
+ */
1063
+ enableTrackEncoding(trackId: string, encoding: Variant): Promise<void>;
1064
+ /**
1065
+ * Disables track encoding so that it will be no longer sent to the server.
1066
+ *
1067
+ * @example
1068
+ * ```ts
1069
+ * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, active_encodings: ["l", "m", "h"]});
1070
+ * webrtc.disableTrackEncoding(trackId, "l");
1071
+ * ```
1072
+ *
1073
+ * @param {string} trackId - Id of track
1074
+ * @param {Encoding} encoding - Encoding that will be disabled
1075
+ */
1076
+ disableTrackEncoding(trackId: string, encoding: Variant): Promise<void>;
1077
+ /**
1078
+ * Updates the metadata for the current peer.
1079
+ *
1080
+ * @param peerMetadata - Data about this peer that other peers will receive upon joining.
1081
+ *
1082
+ * If the metadata is different from what is already tracked in the room, the event {@link MessageEvents.peerUpdated} will
1083
+ * be emitted for other peers in the room.
1084
+ */
1085
+ updatePeerMetadata: (peerMetadata: PeerMetadata) => void;
1086
+ /**
1087
+ * Updates the metadata for a specific track.
1088
+ *
1089
+ * @param trackId - TrackId (generated in addTrack) of audio or video track.
1090
+ * @param trackMetadata - Data about this track that other peers will receive upon joining.
1091
+ *
1092
+ * If the metadata is different from what is already tracked in the room, the event {@link MessageEvents.trackUpdated} will
1093
+ * be emitted for other peers in the room.
1094
+ */
1095
+ updateTrackMetadata: (trackId: string, trackMetadata: TrackMetadata) => void;
1096
+ isReconnecting(): boolean;
1097
+ /**
1098
+ * Leaves the room. This function should be called when user leaves the room in a clean way e.g. by clicking a
1099
+ * dedicated, custom button `disconnect`. As a result there will be generated one more media event that should be sent
1100
+ * to the RTC Engine. Thanks to it each other peer will be notified that peer left in {@link MessageEvents.peerLeft},
1101
+ */
1102
+ leave: () => void;
1103
+ private isOpen;
1104
+ /**
1105
+ * Disconnect from the room, and close the websocket connection. Tries to leave the room gracefully, but if it fails,
1106
+ * it will close the websocket anyway.
1107
+ *
1108
+ * @example
1109
+ * ```typescript
1110
+ * const client = new FishjamClient<PeerMetadata>();
1111
+ *
1112
+ * client.connect({ ... });
1113
+ *
1114
+ * client.disconnect();
1115
+ * ```
1116
+ */
1117
+ disconnect(): void;
1118
+ cleanup(): void;
1119
+ }
1120
+
1121
+ type ReconnectionStatus = 'reconnecting' | 'idle' | 'error';
1122
+ type ReconnectConfig = {
1123
+ maxAttempts?: number;
1124
+ initialDelay?: number;
1125
+ delay?: number;
1126
+ addTracksOnReconnect?: boolean;
1127
+ };
1128
+
1129
+ type TrackMetadata = {
1130
+ type: 'camera' | 'microphone' | 'screenShareVideo' | 'screenShareAudio';
1131
+ paused: boolean;
1132
+ displayName?: string;
1133
+ };
1134
+ type GenericMetadata = Record<string, unknown> | undefined;
1135
+ type Metadata<P = GenericMetadata, S = GenericMetadata> = {
1136
+ peer: P;
1137
+ server: S;
1138
+ };
1139
+ type TrackContextEvents = {
1140
+ encodingChanged: (context: FishjamTrackContext) => void;
1141
+ voiceActivityChanged: (context: FishjamTrackContext) => void;
1142
+ };
1143
+ interface FishjamTrackContext extends TypedEmitter<TrackContextEvents> {
1144
+ readonly track: MediaStreamTrack | null;
1145
+ readonly stream: MediaStream | null;
1146
+ readonly endpoint: Endpoint;
1147
+ readonly trackId: string;
1148
+ readonly simulcastConfig?: MediaEvent_Track_SimulcastConfig;
1149
+ readonly metadata?: TrackMetadata;
1150
+ readonly maxBandwidth?: TrackBandwidthLimit;
1151
+ readonly vadStatus: VadStatus;
1152
+ readonly encoding?: Variant;
1153
+ readonly encodingReason?: EncodingReason;
1154
+ }
1155
+ type Peer<PeerMetadata = GenericMetadata, ServerMetadata = GenericMetadata> = {
1156
+ id: string;
1157
+ type: string;
1158
+ metadata?: Metadata<PeerMetadata, ServerMetadata>;
1159
+ tracks: Map<string, FishjamTrackContext>;
1160
+ };
1161
+ type Component = Omit<Endpoint, 'type'> & {
1162
+ type: 'recording' | 'hls' | 'file' | 'rtsp' | 'sip';
1163
+ };
1164
+ /**
1165
+ * Events emitted by the client with their arguments.
1166
+ */
1167
+ type MessageEvents<P, S> = {
1168
+ /**
1169
+ * Emitted when connect method invoked
1170
+ *
1171
+ */
1172
+ connectionStarted: () => void;
1173
+ /**
1174
+ * Emitted when the websocket connection is closed
1175
+ *
1176
+ * @param {CloseEvent} event - Close event object from the websocket
1177
+ */
1178
+ socketClose: (event: CloseEvent) => void;
1179
+ /**
1180
+ * Emitted when occurs an error in the websocket connection
1181
+ *
1182
+ * @param {Event} event - Event object from the websocket
1183
+ */
1184
+ socketError: (event: Event) => void;
1185
+ /**
1186
+ * Emitted when the websocket connection is opened
1187
+ *
1188
+ * @param {Event} event - Event object from the websocket
1189
+ */
1190
+ socketOpen: (event: Event) => void;
1191
+ /** Emitted when authentication is successful */
1192
+ authSuccess: () => void;
1193
+ /** Emitted when authentication fails */
1194
+ authError: (reason: AuthErrorReason) => void;
1195
+ /** Emitted when the connection is closed */
1196
+ disconnected: () => void;
1197
+ /** Emitted when the process of reconnection starts */
1198
+ reconnectionStarted: () => void;
1199
+ /** Emitted on successful reconnection */
1200
+ reconnected: () => void;
1201
+ /** Emitted when the maximum number of reconnection retries is reached */
1202
+ reconnectionRetriesLimitReached: () => void;
1203
+ /**
1204
+ * Called when peer was accepted.
1205
+ */
1206
+ joined: (peerId: string, peers: Peer<P, S>[], components: Component[]) => void;
1207
+ /**
1208
+ * Called when peer was not accepted
1209
+ * @param metadata - Pass through for client application to communicate further actions to frontend
1210
+ */
1211
+ joinError: (metadata: any) => void;
1212
+ /**
1213
+ * Called when data in a new track arrives.
1214
+ *
1215
+ * This callback is always called after {@link MessageEvents.trackAdded}.
1216
+ * It informs user that data related to the given track arrives and can be played or displayed.
1217
+ */
1218
+ trackReady: (ctx: FishjamTrackContext) => void;
1219
+ /**
1220
+ * Called each time the peer which was already in the room, adds new track. Fields track and stream will be set to null.
1221
+ * These fields will be set to non-null value in {@link MessageEvents.trackReady}
1222
+ */
1223
+ trackAdded: (ctx: FishjamTrackContext) => void;
1224
+ /**
1225
+ * Called when some track will no longer be sent.
1226
+ *
1227
+ * It will also be called before {@link MessageEvents.peerLeft} for each track of this peer.
1228
+ */
1229
+ trackRemoved: (ctx: FishjamTrackContext) => void;
1230
+ /**
1231
+ * Called each time peer has its track metadata updated.
1232
+ */
1233
+ trackUpdated: (ctx: FishjamTrackContext) => void;
1234
+ /**
1235
+ * Called each time new peer joins the room.
1236
+ */
1237
+ peerJoined: (peer: Peer<P, S>) => void;
1238
+ /**
1239
+ * Called each time peer leaves the room.
1240
+ */
1241
+ peerLeft: (peer: Peer<P, S>) => void;
1242
+ /**
1243
+ * Called each time peer has its metadata updated.
1244
+ */
1245
+ peerUpdated: (peer: Peer<P, S>) => void;
1246
+ /**
1247
+ * Called each time new peer joins the room.
1248
+ */
1249
+ componentAdded: (peer: Component) => void;
1250
+ /**
1251
+ * Called each time peer leaves the room.
1252
+ */
1253
+ componentRemoved: (peer: Component) => void;
1254
+ /**
1255
+ * Called each time peer has its metadata updated.
1256
+ */
1257
+ componentUpdated: (peer: Component) => void;
1258
+ /**
1259
+ * Called in case of errors related to multimedia session e.g. ICE connection.
1260
+ */
1261
+ connectionError: (error: {
1262
+ message: string;
1263
+ event?: Event;
1264
+ }) => void;
1265
+ /**
1266
+ * Currently, this callback is only invoked when DisplayManager in RTC Engine is
1267
+ * enabled and simulcast is disabled.
1268
+ *
1269
+ * Called when priority of video tracks have changed.
1270
+ * @param enabledTracks - list of tracks which will be sent to client from SFU
1271
+ * @param disabledTracks - list of tracks which will not be sent to client from SFU
1272
+ */
1273
+ tracksPriorityChanged: (enabledTracks: FishjamTrackContext[], disabledTracks: FishjamTrackContext[]) => void;
1274
+ /**
1275
+ * Called every time the server estimates client's bandiwdth.
1276
+ *
1277
+ * @param {bigint} estimation - client's available incoming bitrate estimated
1278
+ * by the server. It's measured in bits per second.
1279
+ */
1280
+ bandwidthEstimationChanged: (estimation: bigint) => void;
1281
+ targetTrackEncodingRequested: (event: Parameters<WebRTCEndpointEvents['targetTrackEncodingRequested']>[0]) => void;
1282
+ localTrackAdded: (event: Parameters<WebRTCEndpointEvents['localTrackAdded']>[0]) => void;
1283
+ localTrackRemoved: (event: Parameters<WebRTCEndpointEvents['localTrackRemoved']>[0]) => void;
1284
+ localTrackReplaced: (event: Parameters<WebRTCEndpointEvents['localTrackReplaced']>[0]) => void;
1285
+ localTrackMuted: (event: Parameters<WebRTCEndpointEvents['localTrackMuted']>[0]) => void;
1286
+ localTrackUnmuted: (event: Parameters<WebRTCEndpointEvents['localTrackUnmuted']>[0]) => void;
1287
+ localTrackBandwidthSet: (event: Parameters<WebRTCEndpointEvents['localTrackBandwidthSet']>[0]) => void;
1288
+ localTrackEncodingBandwidthSet: (event: Parameters<WebRTCEndpointEvents['localTrackEncodingBandwidthSet']>[0]) => void;
1289
+ localTrackEncodingEnabled: (event: Parameters<WebRTCEndpointEvents['localTrackEncodingEnabled']>[0]) => void;
1290
+ localTrackEncodingDisabled: (event: Parameters<WebRTCEndpointEvents['localTrackEncodingDisabled']>[0]) => void;
1291
+ localPeerMetadataChanged: (event: Parameters<WebRTCEndpointEvents['localEndpointMetadataChanged']>[0]) => void;
1292
+ localTrackMetadataChanged: (event: Parameters<WebRTCEndpointEvents['localTrackMetadataChanged']>[0]) => void;
1293
+ disconnectRequested: (event: Parameters<WebRTCEndpointEvents['disconnectRequested']>[0]) => void;
1294
+ };
1295
+ /** Configuration object for the client */
1296
+ interface ConnectConfig<PeerMetadata> {
1297
+ /** Metadata for the peer */
1298
+ peerMetadata: PeerMetadata;
1299
+ /** Token for authentication */
1300
+ token: string;
1301
+ /** Fishjam url */
1302
+ url: string;
1303
+ }
1304
+ type CreateConfig = {
1305
+ reconnect?: ReconnectConfig | boolean;
1306
+ };
1307
+
1308
+ export { AUTH_ERROR_REASONS, type AuthErrorReason, type BandwidthLimit, type Component, type ConnectConfig, type CreateConfig, type EncodingReason, type Endpoint, FishjamClient, type FishjamTrackContext, type GenericMetadata, type MediaEvent, type MessageEvents, type Metadata, type Peer, type ReconnectConfig, type ReconnectionStatus, type SerializedMediaEvent, type SimulcastBandwidthLimit, MediaEvent_Track_SimulcastConfig as SimulcastConfig, type TrackBandwidthLimit, type TrackContext, type TrackContextEvents$1 as TrackContextEvents, type TrackKind, type TrackMetadata, type VadStatus, Variant, WebRTCEndpoint, type WebRTCEndpointEvents, isAuthError };