@fishjam-cloud/ts-client 0.5.1

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 (52) hide show
  1. package/README.md +134 -0
  2. package/dist/src/FishjamClient.d.ts +523 -0
  3. package/dist/src/FishjamClient.js +666 -0
  4. package/dist/src/auth.d.ts +3 -0
  5. package/dist/src/auth.js +8 -0
  6. package/dist/src/index.d.ts +7 -0
  7. package/dist/src/index.js +3 -0
  8. package/dist/src/protos/fishjam/peer_notifications.d.ts +78 -0
  9. package/dist/src/protos/fishjam/peer_notifications.js +302 -0
  10. package/dist/src/protos/index.d.ts +1 -0
  11. package/dist/src/protos/index.js +1 -0
  12. package/dist/src/reconnection.d.ts +27 -0
  13. package/dist/src/reconnection.js +121 -0
  14. package/dist/src/webrtc/CommandsQueue.d.ts +23 -0
  15. package/dist/src/webrtc/CommandsQueue.js +102 -0
  16. package/dist/src/webrtc/ConnectionManager.d.ts +29 -0
  17. package/dist/src/webrtc/ConnectionManager.js +82 -0
  18. package/dist/src/webrtc/bitrate.d.ts +12 -0
  19. package/dist/src/webrtc/bitrate.js +12 -0
  20. package/dist/src/webrtc/deferred.d.ts +8 -0
  21. package/dist/src/webrtc/deferred.js +17 -0
  22. package/dist/src/webrtc/index.d.ts +3 -0
  23. package/dist/src/webrtc/index.js +1 -0
  24. package/dist/src/webrtc/internal.d.ts +26 -0
  25. package/dist/src/webrtc/internal.js +34 -0
  26. package/dist/src/webrtc/mediaEvent.d.ts +10 -0
  27. package/dist/src/webrtc/mediaEvent.js +16 -0
  28. package/dist/src/webrtc/tracks/Local.d.ts +51 -0
  29. package/dist/src/webrtc/tracks/Local.js +289 -0
  30. package/dist/src/webrtc/tracks/LocalTrack.d.ts +62 -0
  31. package/dist/src/webrtc/tracks/LocalTrack.js +235 -0
  32. package/dist/src/webrtc/tracks/LocalTrackManager.d.ts +38 -0
  33. package/dist/src/webrtc/tracks/LocalTrackManager.js +83 -0
  34. package/dist/src/webrtc/tracks/Remote.d.ts +38 -0
  35. package/dist/src/webrtc/tracks/Remote.js +200 -0
  36. package/dist/src/webrtc/tracks/RemoteTrack.d.ts +39 -0
  37. package/dist/src/webrtc/tracks/RemoteTrack.js +64 -0
  38. package/dist/src/webrtc/tracks/TrackCommon.d.ts +8 -0
  39. package/dist/src/webrtc/tracks/TrackCommon.js +1 -0
  40. package/dist/src/webrtc/tracks/bandwidth.d.ts +1 -0
  41. package/dist/src/webrtc/tracks/bandwidth.js +27 -0
  42. package/dist/src/webrtc/tracks/encodings.d.ts +1 -0
  43. package/dist/src/webrtc/tracks/encodings.js +7 -0
  44. package/dist/src/webrtc/tracks/transceivers.d.ts +2 -0
  45. package/dist/src/webrtc/tracks/transceivers.js +78 -0
  46. package/dist/src/webrtc/types.d.ts +306 -0
  47. package/dist/src/webrtc/types.js +2 -0
  48. package/dist/src/webrtc/voiceActivityDetection.d.ts +2 -0
  49. package/dist/src/webrtc/voiceActivityDetection.js +2 -0
  50. package/dist/src/webrtc/webRTCEndpoint.d.ts +299 -0
  51. package/dist/src/webrtc/webRTCEndpoint.js +730 -0
  52. package/package.json +82 -0
package/README.md ADDED
@@ -0,0 +1,134 @@
1
+ [![NPM Version](https://img.shields.io/npm/v/@fishjam-cloud/ts-client)](https://www.npmjs.com/package/@fishjam-cloud/ts-client)
2
+ [![TypeScript Strict](https://badgen.net/badge/TS/Strict)](https://www.typescriptlang.org)
3
+ [![TypeDoc](https://img.shields.io/badge/TypeDoc-8A2BE2)](https://fishjam-cloud.github.io/web-client-sdk/)
4
+
5
+ # Fishjam TS Client
6
+
7
+ TypeScript client library for [Fishjam Cloud](https://cloud.fishjam.stream).
8
+
9
+ ## Installation
10
+
11
+ You can install this package using `npm`:
12
+
13
+ ```bash
14
+ npm install @fishjam-cloud/ts-client
15
+ ```
16
+
17
+ or `yarn`:
18
+
19
+ ```bash
20
+ yarn @fishjam-cloud/react-client
21
+ ```
22
+
23
+ ## Documentation
24
+
25
+ Documentation is available
26
+ [here](https://fishjam-cloud.github.io/web-client-sdk/modules/_fishjam_dev_ts_client.html/).
27
+
28
+ For a more comprehensive tutorial on Fishjam, its capabilities and usage in
29
+ production, refer to the [Fishjam Cloud Docs](https://cloud.fishjam.stream/).
30
+
31
+ ## Usage
32
+
33
+ Prerequisites:
34
+
35
+ - Account on Fishjam Cloud with App configured.
36
+ - Created room and token of peer in that room. You can use Room Manager to
37
+ create room and peer token.
38
+
39
+ The following code snippet is based on the
40
+ [minimal](../../examples/ts-client//minimal/) example.
41
+
42
+ ```ts
43
+ import { FishjamClient, WebRTCEndpoint } from '@fishjam-cloud/ts-client';
44
+
45
+ const SCREEN_SHARING_MEDIA_CONSTRAINTS = {
46
+ video: {
47
+ frameRate: { ideal: 20, max: 25 },
48
+ width: { max: 1920, ideal: 1920 },
49
+ height: { max: 1080, ideal: 1080 },
50
+ },
51
+ };
52
+
53
+ // Example metadata types for peer and track
54
+ // You can define your own metadata types, just make sure they are serializable
55
+ type PeerMetadata = {
56
+ name: string;
57
+ };
58
+
59
+ type TrackMetadata = {
60
+ type: 'camera' | 'screen';
61
+ };
62
+
63
+ // Create a new FishjamClient object to interact with Fishjam
64
+ const client = new FishjamClient<PeerMetadata, TrackMetadata>();
65
+
66
+ const peerToken = prompt('Enter peer token') ?? 'YOUR_PEER_TOKEN';
67
+
68
+ // Start the peer connection
69
+ client.connect({
70
+ peerMetadata: { name: 'peer' },
71
+ token: peerToken,
72
+ // if the 'signaling' field is missing, the client will connect to ws://localhost:5002/socket/peer/websocket
73
+ });
74
+
75
+ // You can listen to events emitted by the client
76
+ client.on('joined', (peerId, peersInRoom) => {
77
+ // Check if webrtc is initialized
78
+ if (!client.webrtc) return console.error('webrtc is not initialized');
79
+
80
+ // To start broadcasting your media, you will need a source of MediaStream like a camera, microphone, or screen
81
+ // In this example, we will use screen sharing
82
+ startScreenSharing(client.webrtc);
83
+ });
84
+
85
+ // To receive media from other peers, you need to listen to the onTrackReady event
86
+ client.on('trackReady', (ctx) => {
87
+ const peerId = ctx.peer.id;
88
+
89
+ document.getElementById(peerId)?.remove(); // remove previous video element if it exists
90
+
91
+ // Create a new video element to display the media
92
+ const videoPlayer = document.createElement('video');
93
+ videoPlayer.id = peerId;
94
+ videoPlayer.oncanplaythrough = function () {
95
+ // Chrome blocks autoplay of unmuted video
96
+ videoPlayer.muted = true;
97
+ videoPlayer.play();
98
+ };
99
+ document.body.appendChild(videoPlayer);
100
+
101
+ videoPlayer.srcObject = ctx.stream; // assign MediaStream to video element
102
+ });
103
+
104
+ // Cleanup video element when track is removed
105
+ client.on('trackRemoved', (ctx) => {
106
+ const peerId = ctx.peer.id;
107
+ document.getElementById(peerId)?.remove(); // remove video element
108
+ });
109
+
110
+ async function startScreenSharing(webrtc: WebRTCEndpoint) {
111
+ // Get screen sharing MediaStream
112
+ const screenStream = await navigator.mediaDevices.getDisplayMedia(
113
+ SCREEN_SHARING_MEDIA_CONSTRAINTS,
114
+ );
115
+
116
+ // Add local MediaStream to webrtc
117
+ screenStream
118
+ .getTracks()
119
+ .forEach((track) => webrtc.addTrack(track, { type: 'screen' }));
120
+ }
121
+ ```
122
+
123
+ ## Examples
124
+
125
+ For more examples, see the [examples](../../examples/ts-client/) folder.
126
+
127
+ ## Copyright and License
128
+
129
+ Copyright 2024,
130
+ [Software Mansion](https://swmansion.com/?utm_source=git&utm_medium=readme&utm_campaign=fishjam-ts)
131
+
132
+ [![Software Mansion](https://logo.swmansion.com/logo?color=white&variant=desktop&width=200&tag=fishjam-github)](https://swmansion.com/?utm_source=git&utm_medium=readme&utm_campaign=fishjam-ts)
133
+
134
+ Licensed under the [Apache License, Version 2.0](LICENSE)
@@ -0,0 +1,523 @@
1
+ import type { BandwidthLimit, Endpoint, SimulcastConfig, TrackBandwidthLimit, TrackContext, Encoding, MetadataParser, WebRTCEndpointEvents } from './webrtc';
2
+ import type TypedEmitter from 'typed-emitter';
3
+ import type { ReconnectConfig } from './reconnection';
4
+ import type { AuthErrorReason } from './auth';
5
+ export type Peer<PeerMetadata, TrackMetadata> = Endpoint<PeerMetadata, TrackMetadata> & {
6
+ type: 'webrtc';
7
+ };
8
+ export type Component<PeerMetadata, TrackMetadata> = Omit<Endpoint<PeerMetadata, TrackMetadata>, 'type'> & {
9
+ type: 'recording' | 'hls' | 'file' | 'rtsp' | 'sip';
10
+ };
11
+ /**
12
+ * Events emitted by the client with their arguments.
13
+ */
14
+ export interface MessageEvents<PeerMetadata, TrackMetadata> {
15
+ /**
16
+ * Emitted when the websocket connection is closed
17
+ *
18
+ * @param {CloseEvent} event - Close event object from the websocket
19
+ */
20
+ socketClose: (event: CloseEvent) => void;
21
+ /**
22
+ * Emitted when occurs an error in the websocket connection
23
+ *
24
+ * @param {Event} event - Event object from the websocket
25
+ */
26
+ socketError: (event: Event) => void;
27
+ /**
28
+ * Emitted when the websocket connection is opened
29
+ *
30
+ * @param {Event} event - Event object from the websocket
31
+ */
32
+ socketOpen: (event: Event) => void;
33
+ /** Emitted when authentication is successful */
34
+ authSuccess: () => void;
35
+ /** Emitted when authentication fails */
36
+ authError: (reason: AuthErrorReason) => void;
37
+ /** Emitted when the connection is closed */
38
+ disconnected: () => void;
39
+ /** Emitted when the process of reconnection starts */
40
+ reconnectionStarted: () => void;
41
+ /** Emitted on successful reconnection */
42
+ reconnected: () => void;
43
+ /** Emitted when the maximum number of reconnection retries is reached */
44
+ reconnectionRetriesLimitReached: () => void;
45
+ /**
46
+ * Called when peer was accepted.
47
+ */
48
+ joined: (peerId: string, peers: Peer<PeerMetadata, TrackMetadata>[], components: Component<PeerMetadata, TrackMetadata>[]) => void;
49
+ /**
50
+ * Called when peer was not accepted
51
+ * @param metadata - Pass through for client application to communicate further actions to frontend
52
+ */
53
+ joinError: (metadata: any) => void;
54
+ /**
55
+ * Called when data in a new track arrives.
56
+ *
57
+ * This callback is always called after {@link MessageEvents.trackAdded}.
58
+ * It informs user that data related to the given track arrives and can be played or displayed.
59
+ */
60
+ trackReady: (ctx: TrackContext<PeerMetadata, TrackMetadata>) => void;
61
+ /**
62
+ * Called each time the peer which was already in the room, adds new track. Fields track and stream will be set to null.
63
+ * These fields will be set to non-null value in {@link MessageEvents.trackReady}
64
+ */
65
+ trackAdded: (ctx: TrackContext<PeerMetadata, TrackMetadata>) => void;
66
+ /**
67
+ * Called when some track will no longer be sent.
68
+ *
69
+ * It will also be called before {@link MessageEvents.peerLeft} for each track of this peer.
70
+ */
71
+ trackRemoved: (ctx: TrackContext<PeerMetadata, TrackMetadata>) => void;
72
+ /**
73
+ * Called each time peer has its track metadata updated.
74
+ */
75
+ trackUpdated: (ctx: TrackContext<PeerMetadata, TrackMetadata>) => void;
76
+ /**
77
+ * Called each time new peer joins the room.
78
+ */
79
+ peerJoined: (peer: Peer<PeerMetadata, TrackMetadata>) => void;
80
+ /**
81
+ * Called each time peer leaves the room.
82
+ */
83
+ peerLeft: (peer: Peer<PeerMetadata, TrackMetadata>) => void;
84
+ /**
85
+ * Called each time peer has its metadata updated.
86
+ */
87
+ peerUpdated: (peer: Peer<PeerMetadata, TrackMetadata>) => void;
88
+ /**
89
+ * Called each time new peer joins the room.
90
+ */
91
+ componentAdded: (peer: Component<PeerMetadata, TrackMetadata>) => void;
92
+ /**
93
+ * Called each time peer leaves the room.
94
+ */
95
+ componentRemoved: (peer: Component<PeerMetadata, TrackMetadata>) => void;
96
+ /**
97
+ * Called each time peer has its metadata updated.
98
+ */
99
+ componentUpdated: (peer: Component<PeerMetadata, TrackMetadata>) => void;
100
+ /**
101
+ * Called in case of errors related to multimedia session e.g. ICE connection.
102
+ */
103
+ connectionError: (error: {
104
+ message: string;
105
+ event?: Event;
106
+ }) => void;
107
+ /**
108
+ * Currently, this callback is only invoked when DisplayManager in RTC Engine is
109
+ * enabled and simulcast is disabled.
110
+ *
111
+ * Called when priority of video tracks have changed.
112
+ * @param enabledTracks - list of tracks which will be sent to client from SFU
113
+ * @param disabledTracks - list of tracks which will not be sent to client from SFU
114
+ */
115
+ tracksPriorityChanged: (enabledTracks: TrackContext<PeerMetadata, TrackMetadata>[], disabledTracks: TrackContext<PeerMetadata, TrackMetadata>[]) => void;
116
+ /**
117
+ * Called every time the server estimates client's bandiwdth.
118
+ *
119
+ * @param {bigint} estimation - client's available incoming bitrate estimated
120
+ * by the server. It's measured in bits per second.
121
+ */
122
+ bandwidthEstimationChanged: (estimation: bigint) => void;
123
+ targetTrackEncodingRequested: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['targetTrackEncodingRequested']>[0]) => void;
124
+ localTrackAdded: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackAdded']>[0]) => void;
125
+ localTrackRemoved: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackRemoved']>[0]) => void;
126
+ localTrackReplaced: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackReplaced']>[0]) => void;
127
+ localTrackMuted: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackMuted']>[0]) => void;
128
+ localTrackUnmuted: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackUnmuted']>[0]) => void;
129
+ localTrackBandwidthSet: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackBandwidthSet']>[0]) => void;
130
+ localTrackEncodingBandwidthSet: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackEncodingBandwidthSet']>[0]) => void;
131
+ localTrackEncodingEnabled: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackEncodingEnabled']>[0]) => void;
132
+ localTrackEncodingDisabled: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackEncodingDisabled']>[0]) => void;
133
+ localPeerMetadataChanged: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localEndpointMetadataChanged']>[0]) => void;
134
+ localTrackMetadataChanged: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['localTrackMetadataChanged']>[0]) => void;
135
+ disconnectRequested: (event: Parameters<WebRTCEndpointEvents<PeerMetadata, TrackMetadata>['disconnectRequested']>[0]) => void;
136
+ }
137
+ export type SignalingUrl = {
138
+ /**
139
+ * Protocol of the websocket server
140
+ * Default is `"ws"`
141
+ */
142
+ protocol?: string;
143
+ /**
144
+ * Host of the websocket server
145
+ * Default is `"localhost:5002"`
146
+ */
147
+ host?: string;
148
+ /**
149
+ * Path of the websocket server
150
+ * Default is `"/socket/peer/websocket"`
151
+ */
152
+ path?: string;
153
+ };
154
+ /** Configuration object for the client */
155
+ export interface ConnectConfig<PeerMetadata> {
156
+ /** Metadata for the peer */
157
+ peerMetadata: PeerMetadata;
158
+ /** Token for authentication */
159
+ token: string;
160
+ signaling?: SignalingUrl;
161
+ }
162
+ export type CreateConfig<PeerMetadata, TrackMetadata> = {
163
+ peerMetadataParser?: MetadataParser<PeerMetadata>;
164
+ trackMetadataParser?: MetadataParser<TrackMetadata>;
165
+ reconnect?: ReconnectConfig | boolean;
166
+ };
167
+ declare const FishjamClient_base: new <PeerMetadata_1, TrackMetadata_1>() => TypedEmitter<Required<MessageEvents<PeerMetadata_1, TrackMetadata_1>>>;
168
+ /**
169
+ * FishjamClient is the main class to interact with Fishjam.
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * const client = new FishjamClient<PeerMetadata, TrackMetadata>();
174
+ * const peerToken = "YOUR_PEER_TOKEN";
175
+ *
176
+ * // You can listen to events emitted by the client
177
+ * client.on("joined", (peerId, peersInRoom) => {
178
+ * console.log("join success");
179
+ * });
180
+ *
181
+ * // Start the peer connection
182
+ * client.connect({
183
+ * peerMetadata: {},
184
+ * isSimulcastOn: false,
185
+ * token: peerToken
186
+ * });
187
+ *
188
+ * // Close the peer connection
189
+ * client.disconnect();
190
+ * ```
191
+ *
192
+ * You can register callbacks to handle the events emitted by the Client.
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ *
197
+ * client.on("trackReady", (ctx) => {
198
+ * console.log("On track ready");
199
+ * });
200
+ * ```
201
+ */
202
+ export declare class FishjamClient<PeerMetadata, TrackMetadata> extends FishjamClient_base<PeerMetadata, TrackMetadata> {
203
+ private websocket;
204
+ private webrtc;
205
+ private removeEventListeners;
206
+ status: 'new' | 'initialized';
207
+ private connectConfig;
208
+ private reconnectManager;
209
+ private sendStatisticsInterval;
210
+ private readonly peerMetadataParser;
211
+ private readonly trackMetadataParser;
212
+ constructor(config?: CreateConfig<PeerMetadata, TrackMetadata>);
213
+ /**
214
+ * Uses the {@link !WebSocket} connection and {@link !WebRTCEndpoint | WebRTCEndpoint} to join to the room. Registers the callbacks to
215
+ * handle the events emitted by the {@link !WebRTCEndpoint | WebRTCEndpoint}. Make sure that peer metadata is serializable.
216
+ *
217
+ * @example
218
+ * ```typescript
219
+ * const client = new FishjamClient<PeerMetadata, TrackMetadata>();
220
+ *
221
+ * client.connect({
222
+ * peerMetadata: {},
223
+ * token: peerToken
224
+ * });
225
+ * ```
226
+ *
227
+ * @param {ConnectConfig} config - Configuration object for the client
228
+ */
229
+ connect(config: ConnectConfig<PeerMetadata>): void;
230
+ private initConnection;
231
+ private initWebsocket;
232
+ /**
233
+ * Retrieves statistics related to the RTCPeerConnection.
234
+ * These statistics provide insights into the performance and status of the connection.
235
+ *
236
+ * @return {Promise<RTCStatsReport>}
237
+ *
238
+ * @external RTCPeerConnection#getStats()
239
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats | MDN Web Docs: RTCPeerConnection.getStats()}
240
+ */
241
+ getStatistics(selector?: MediaStreamTrack | null): Promise<RTCStatsReport>;
242
+ /**
243
+ * Returns a snapshot of currently received remote tracks.
244
+ *
245
+ * @example
246
+ * if (client.getRemoteTracks()[trackId]?.simulcastConfig?.enabled) {
247
+ * client.setTargetTrackEncoding(trackId, encoding);
248
+ * }
249
+ */
250
+ getRemoteTracks(): Readonly<Record<string, TrackContext<PeerMetadata, TrackMetadata>>>;
251
+ /**
252
+ * Returns a snapshot of currently received remote peers.
253
+ */
254
+ getRemotePeers(): Record<string, Peer<PeerMetadata, TrackMetadata>>;
255
+ getRemoteComponents(): Record<string, Component<PeerMetadata, TrackMetadata>>;
256
+ getLocalPeer(): Endpoint<PeerMetadata, TrackMetadata> | null;
257
+ getBandwidthEstimation(): bigint;
258
+ private setupCallbacks;
259
+ private sendStatistics;
260
+ /**
261
+ * Register a callback to be called when the event is emitted.
262
+ * Full list of callbacks can be found here {@link MessageEvents}.
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * const callback = ()=>{ };
267
+ *
268
+ * client.on("onJoinSuccess", callback);
269
+ * ```
270
+ *
271
+ * @param event - Event name from {@link MessageEvents}
272
+ * @param listener - Callback function to be called when the event is emitted
273
+ * @returns This
274
+ */
275
+ on<E extends keyof MessageEvents<PeerMetadata, TrackMetadata>>(event: E, listener: Required<MessageEvents<PeerMetadata, TrackMetadata>>[E]): this;
276
+ /**
277
+ * Remove a callback from the list of callbacks to be called when the event is emitted.
278
+ *
279
+ * @example
280
+ * ```ts
281
+ * const callback = ()=>{ };
282
+ *
283
+ * client.on("onJoinSuccess", callback);
284
+ *
285
+ * client.off("onJoinSuccess", callback);
286
+ * ```
287
+ *
288
+ * @param event - Event name from {@link MessageEvents}
289
+ * @param listener - Reference to function to be removed from called callbacks
290
+ * @returns This
291
+ */
292
+ off<E extends keyof MessageEvents<PeerMetadata, TrackMetadata>>(event: E, listener: Required<MessageEvents<PeerMetadata, TrackMetadata>>[E]): this;
293
+ private handleWebRTCNotInitialized;
294
+ /**
295
+ * Adds track that will be sent to the RTC Engine.
296
+ *
297
+ * @example
298
+ * ```ts
299
+ * const localStream: MediaStream = new MediaStream();
300
+ * try {
301
+ * const localAudioStream = await navigator.mediaDevices.getUserMedia(
302
+ * { audio: true }
303
+ * );
304
+ * localAudioStream
305
+ * .getTracks()
306
+ * .forEach((track) => localStream.addTrack(track));
307
+ * } catch (error) {
308
+ * console.error("Couldn't get microphone permission:", error);
309
+ * }
310
+ *
311
+ * try {
312
+ * const localVideoStream = await navigator.mediaDevices.getUserMedia(
313
+ * { video: true }
314
+ * );
315
+ * localVideoStream
316
+ * .getTracks()
317
+ * .forEach((track) => localStream.addTrack(track));
318
+ * } catch (error) {
319
+ * console.error("Couldn't get camera permission:", error);
320
+ * }
321
+ *
322
+ * localStream
323
+ * .getTracks()
324
+ * .forEach((track) => client.addTrack(track, localStream));
325
+ * ```
326
+ *
327
+ * @param track - Audio or video track e.g. from your microphone or camera.
328
+ * @param stream - Stream that this track belongs to.
329
+ * @param trackMetadata - Any information about this track that other peers will receive in
330
+ * {@link MessageEvents.peerJoined}. E.g. this can source of the track - wheather it's screensharing, webcam or some
331
+ * other media device.
332
+ * @param simulcastConfig - Simulcast configuration. By default, simulcast is disabled. For more information refer to
333
+ * {@link !SimulcastConfig | SimulcastConfig}.
334
+ * @param maxBandwidth - Maximal bandwidth this track can use. Defaults to 0 which is unlimited. This option has no
335
+ * effect for simulcast and audio tracks. For simulcast tracks use {@link FishjamClient.setTrackBandwidth}.
336
+ * @returns {string} Returns id of added track
337
+ */
338
+ addTrack(track: MediaStreamTrack, trackMetadata?: TrackMetadata, simulcastConfig?: SimulcastConfig, maxBandwidth?: TrackBandwidthLimit): Promise<string>;
339
+ /**
340
+ * Replaces a track that is being sent to the RTC Engine.
341
+ *
342
+ * @example
343
+ * ```ts
344
+ * // setup camera
345
+ * let localStream: MediaStream = new MediaStream();
346
+ * try {
347
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
348
+ * VIDEO_CONSTRAINTS
349
+ * );
350
+ * localVideoStream
351
+ * .getTracks()
352
+ * .forEach((track) => localStream.addTrack(track));
353
+ * } catch (error) {
354
+ * console.error("Couldn't get camera permission:", error);
355
+ * }
356
+ * let oldTrackId;
357
+ * localStream
358
+ * .getTracks()
359
+ * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
360
+ *
361
+ * // change camera
362
+ * const oldTrack = localStream.getVideoTracks()[0];
363
+ * let videoDeviceId = "abcd-1234";
364
+ * navigator.mediaDevices.getUserMedia({
365
+ * video: {
366
+ * ...(VIDEO_CONSTRAINTS as {}),
367
+ * deviceId: {
368
+ * exact: videoDeviceId,
369
+ * },
370
+ * }
371
+ * })
372
+ * .then((stream) => {
373
+ * let videoTrack = stream.getVideoTracks()[0];
374
+ * webrtc.replaceTrack(oldTrackId, videoTrack);
375
+ * })
376
+ * .catch((error) => {
377
+ * console.error('Error switching camera', error);
378
+ * })
379
+ * ```
380
+ *
381
+ * @param {string} trackId - Id of audio or video track to replace.
382
+ * @param {MediaStreamTrack} newTrack - New audio or video track.
383
+ * @param {TrackMetadata} [newTrackMetadata] - Optional track metadata to apply to the new track. If no track metadata is passed, the
384
+ * old track metadata is retained.
385
+ * @returns {Promise<boolean>} Success
386
+ */
387
+ replaceTrack(trackId: string, newTrack: MediaStreamTrack | null, newTrackMetadata?: TrackMetadata): Promise<void>;
388
+ /**
389
+ * Updates maximum bandwidth for the track identified by trackId. This value directly translates to quality of the
390
+ * stream and, in case of video, to the amount of RTP packets being sent. In case trackId points at the simulcast
391
+ * track bandwidth is split between all of the variant streams proportionally to their resolution.
392
+ *
393
+ * @param {string} trackId
394
+ * @param {BandwidthLimit} bandwidth In kbps
395
+ * @returns {Promise<boolean>} Success
396
+ */
397
+ setTrackBandwidth(trackId: string, bandwidth: BandwidthLimit): Promise<boolean>;
398
+ /**
399
+ * Updates maximum bandwidth for the given simulcast encoding of the given track.
400
+ *
401
+ * @param {string} trackId - Id of the track
402
+ * @param {string} rid - Rid of the encoding
403
+ * @param {BandwidthLimit} bandwidth - Desired max bandwidth used by the encoding (in kbps)
404
+ * @returns
405
+ */
406
+ setEncodingBandwidth(trackId: string, rid: string, bandwidth: BandwidthLimit): Promise<boolean>;
407
+ /**
408
+ * Removes a track from connection that was being sent to the RTC Engine.
409
+ *
410
+ * @example
411
+ * ```ts
412
+ * // setup camera
413
+ * let localStream: MediaStream = new MediaStream();
414
+ * try {
415
+ * localVideoStream = await navigator.mediaDevices.getUserMedia(
416
+ * VIDEO_CONSTRAINTS
417
+ * );
418
+ * localVideoStream
419
+ * .getTracks()
420
+ * .forEach((track) => localStream.addTrack(track));
421
+ * } catch (error) {
422
+ * console.error("Couldn't get camera permission:", error);
423
+ * }
424
+ *
425
+ * let trackId
426
+ * localStream
427
+ * .getTracks()
428
+ * .forEach((track) => trackId = webrtc.addTrack(track, localStream));
429
+ *
430
+ * // remove track
431
+ * webrtc.removeTrack(trackId)
432
+ * ```
433
+ *
434
+ * @param {string} trackId - Id of audio or video track to remove.
435
+ */
436
+ removeTrack(trackId: string): Promise<void>;
437
+ /**
438
+ * Sets track encoding that server should send to the client library.
439
+ *
440
+ * The encoding will be sent whenever it is available. If chosen encoding is temporarily unavailable, some other
441
+ * encoding will be sent until chosen encoding becomes active again.
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * webrtc.setTargetTrackEncoding(incomingTrackCtx.trackId, "l")
446
+ * ```
447
+ *
448
+ * @param {string} trackId - Id of track
449
+ * @param {Encoding} encoding - Encoding to receive
450
+ */
451
+ setTargetTrackEncoding(trackId: string, encoding: Encoding): void;
452
+ /**
453
+ * Enables track encoding so that it will be sent to the server.
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, active_encodings: ["l", "m", "h"]});
458
+ * webrtc.disableTrackEncoding(trackId, "l");
459
+ * // wait some time
460
+ * webrtc.enableTrackEncoding(trackId, "l");
461
+ * ```
462
+ *
463
+ * @param {string} trackId - Id of track
464
+ * @param {Encoding} encoding - Encoding that will be enabled
465
+ */
466
+ enableTrackEncoding(trackId: string, encoding: Encoding): Promise<void>;
467
+ /**
468
+ * Disables track encoding so that it will be no longer sent to the server.
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * const trackId = webrtc.addTrack(track, stream, {}, {enabled: true, active_encodings: ["l", "m", "h"]});
473
+ * webrtc.disableTrackEncoding(trackId, "l");
474
+ * ```
475
+ *
476
+ * @param {string} trackId - Id of track
477
+ * @param {rackEncoding} encoding - Encoding that will be disabled
478
+ */
479
+ disableTrackEncoding(trackId: string, encoding: Encoding): Promise<void>;
480
+ /**
481
+ * Updates the metadata for the current peer.
482
+ *
483
+ * @param peerMetadata - Data about this peer that other peers will receive upon joining.
484
+ *
485
+ * If the metadata is different from what is already tracked in the room, the event {@link MessageEvents.peerUpdated} will
486
+ * be emitted for other peers in the room.
487
+ */
488
+ updatePeerMetadata: (peerMetadata: PeerMetadata) => void;
489
+ /**
490
+ * Updates the metadata for a specific track.
491
+ *
492
+ * @param trackId - TrackId (generated in addTrack) of audio or video track.
493
+ * @param trackMetadata - Data about this track that other peers will receive upon joining.
494
+ *
495
+ * If the metadata is different from what is already tracked in the room, the event {@link MessageEvents.trackUpdated} will
496
+ * be emitted for other peers in the room.
497
+ */
498
+ updateTrackMetadata: (trackId: string, trackMetadata: TrackMetadata) => void;
499
+ isReconnecting(): boolean;
500
+ /**
501
+ * Leaves the room. This function should be called when user leaves the room in a clean way e.g. by clicking a
502
+ * dedicated, custom button `disconnect`. As a result there will be generated one more media event that should be sent
503
+ * to the RTC Engine. Thanks to it each other peer will be notified that peer left in {@link MessageEvents.peerLeft},
504
+ */
505
+ leave: () => void;
506
+ private isOpen;
507
+ /**
508
+ * Disconnect from the room, and close the websocket connection. Tries to leave the room gracefully, but if it fails,
509
+ * it will close the websocket anyway.
510
+ *
511
+ * @example
512
+ * ```typescript
513
+ * const client = new FishjamClient<PeerMetadata, TrackMetadata>();
514
+ *
515
+ * client.connect({ ... });
516
+ *
517
+ * client.disconnect();
518
+ * ```
519
+ */
520
+ disconnect(): void;
521
+ cleanup(): void;
522
+ }
523
+ export {};