UNPKG

@4players/odin

Version:

A cross-platform SDK enabling developers to integrate real-time VoIP chat technology into their projects

436 lines (435 loc) 19.6 kB
import { Backend } from '@4players/odin-common'; import { Infer, RoomCommands } from '@4players/odin-common/api'; import { OdinEventTarget } from '../../utils/odin-event-target'; import { AudioActivityPayload, AudioInputPayload, AudioOutputPayload, JoinParams, LeftPayload, MediaPayload, MessageReceivedPayload, PeerJoinedPayload, PeerLeftPayload, RoomDataChangedPayload, RoomEvents, RoomStatus, RoomStatusChangedPayload, UserDataChangedPayload, VideoInputPayload, VideoOutputPayload, ConnectionStats, JoinedPayload } from './types'; import { AudioOutput } from '../media/audio-output'; import { AudioInput } from '../media/audio-input'; import { RoomToken } from '../../utils/token'; import { VideoOutput } from '../media/video-output'; import { VideoInput } from '../media/video-input'; import { RemotePeer } from '../peer/remote-peer'; import { LocalPeer } from '../peer/local-peer'; import Plugin = Backend.Plugin; import DeviceParameters = Backend.DeviceParameters; import Cipher = Backend.Cipher; import JitterStats = Backend.JitterStats; import PlaybackVolume = Backend.PlaybackVolume; /** * Represents a room within the Odin framework, managing connections, peers, and media. * The `Room` class provides functionality to join and interact with an audio/video room, * monitor its state, handle events, and manage media streams. * * This class extends `OdinEventTarget` to handle custom event types and listeners. */ export declare class Room extends OdinEventTarget<RoomEvents> { #private; /** * Interval how often the connection statistics are updated. */ connectionStatsInterval: number; /** * The default gateway if no gateway was specified when joining the room. */ readonly defaultGateway = "https://gateway.odin.4players.io"; /** * A callback function that is invoked when this room was joined. Also gets called after a reconnect was successfully performed. * * @param {PeerJoinedPayload} payload - An object containing the peer and the room. */ onJoined?: (payload: JoinedPayload) => void; /** * A callback function that is invoked, when the room was disconnected by the server. * @TODO Check if it makes sense to call this method also by user disconnects. * * @param {LeftPayload} payload - An object containing the room and the reason. */ onLeft?: (payload: LeftPayload) => void; /** * A callback function invoked whenever the status of a room changes. * * @param {RoomStatusChangedPayload} payload - The payload containing details about the room's status change. */ onStatusChanged?: (payload: RoomStatusChangedPayload) => void; /** * A callback function that is invoked whenever the data of the room changed. This can only be done * via admin tokens. * * @param {RoomDataChangedPayload} payload - An object containing the room. */ onDataChanged?: (payload: RoomDataChangedPayload) => void; /** * A callback function that is invoked when a new peer joins. * * @param {PeerJoinedPayload} payload - An object containing the peer and the room. */ onPeerJoined?: (payload: PeerJoinedPayload) => void; /** * A callback function that is invoked when a peer leaves. * * @param {PeerLeftPayload} payload - An object containing the peer and the room. */ onPeerLeft?: (payload: PeerLeftPayload) => void; /** * A callback function invoked when user data is changed. * * @param {UserDataChangedPayload} payload - An object containing the peer and the room. */ onUserDataChanged?: (payload: UserDataChangedPayload) => void; /** * A callback function that is invoked when audio activity occurs and voice activity detection (VAD) was set to true. * * @param {AudioActivityPayload} payload - An object containing the AudioMedia. */ onAudioActivity?: (payload: AudioActivityPayload) => void; /** * A callback function invoked when there is an update to the audio power level in rmsDBFS. * This function can be used to handle or process audio activity, such as * monitoring sound levels or visualizing audio input. * * @param {AudioActivityPayload} payload - An object containing the AudioMedia. */ onAudioPowerLevel?: (payload: AudioActivityPayload) => void; /** * A callback function that gets invoked when a message is received. * * @param {MessageReceivedPayload} payload - An object containing the room, peer, and message. */ onMessageReceived?: (payload: MessageReceivedPayload) => void; onAudioStats?: (payload: JitterStats) => void; /** * A callback function invoked to handle connection statistics. * * @param {ConnectionStats} payload - An object containing the connection statistics details. */ onConnectionStats?: (payload: ConnectionStats) => void; /** * A callback function that gets invoked when a new audio or video media was started. * * @param {MediaPayload} payload - An object containing the media that was started. */ onMediaStarted?: (payload: MediaPayload) => void; /** * A callback function that gets invoked when an audio or video media was stopped. * * @param {MediaPayload} payload - An object containing the media that was stopped. */ onMediaStopped?: (payload: MediaPayload) => void; /** * A callback function that gets invoked when an AudioInput was started. * * @param {AudioInputPayload} payload - An object containing the AudioInput that was started. */ onAudioInputStarted?: (payload: AudioInputPayload) => void; /** * A callback function that gets invoked when an AudioInput was stopped. * * @param {AudioInputPayload} payload - An object containing the AudioInput that was stopped. */ onAudioInputStopped?: (payload: AudioInputPayload) => void; /** * A callback function that gets invoked when an AudioOutput was started. * * @param {AudioOutputPayload} payload - An object containing the AudioOutput that was started. */ onAudioOutputStarted?: (payload: AudioOutputPayload) => void; /** * A callback function that gets invoked when an AudioOutput was stopped. * * @param {AudioOutputPayload} payload - An object containing the AudioOutput that was stopped. */ onAudioOutputStopped?: (payload: AudioOutputPayload) => void; /** * A callback function that gets invoked when a VideoOutput was started. * * @param {AudioOutputPayload} payload - An object containing the VideoOutput that was started. */ onVideoOutputStarted?: (payload: VideoOutputPayload) => void; /** * A callback function that gets invoked when a VideoOutput was stopped. * * @param {VideoOutputPayload} payload - An object containing the VideoOutput that was stopped. */ onVideoOutputStopped?: (payload: VideoOutputPayload) => void; /** * A callback function that gets invoked when a VideoInput was started. * * @param {VideoInputPayload} payload - An object containing the VideoInput that was started. */ onVideoInputStarted?: (payload: VideoInputPayload) => void; /** * A callback function that gets invoked when a VideoInput was stopped. * * @param {VideoInputPayload} payload - An object containing the VideoInput that was stopped. */ onVideoInputStopped?: (payload: VideoInputPayload) => void; constructor(); /** * The id of the room. If the room was not joined, the id is undefined as * the id is provided by the token provided when joining. * * @return {string|undefined} The unique identifier of the object. */ get id(): string | undefined; /** * The latest token (inclusive reconnect tokens). * * @return {RoomToken | undefined} The current RoomToken if available, otherwise undefined. */ get token(): RoomToken | undefined; /** * Retrieves the cipher associated with the current room, if available. * * @return {Cipher|undefined} The cipher object if it exists; otherwise, undefined. */ get cipher(): Cipher | undefined; /** * Retrieves connection statistics for the current room. * * @return {ConnectionStats} An object containing the connection statistics, including: * - `bytesSent`: Total bytes sent. * - `bytesReceived`: Total bytes received. * - `packetsSent`: Total packets sent. * - `packetsReceived`: Total packets received. * - `rtt`: Round-trip time in milliseconds. * If the room isn't connected, returns default stats with all values set to 0. */ get connectionStats(): Backend.ConnectionStats; /** * Address of the SFU (Voice Server) which was either assigned by the gateway or provided by the token when joining the room. * * @return {string} The address of the sfu if available, otherwise returns an empty string. */ get address(): string; /** * The id of the own peer. Id 0 means not connected. * * @return {number} The ID of the own peer. */ get ownPeerId(): number; /** * A collection of peers. * * @return {Map<number, Peer>} A map containing peers with their numeric IDs as keys. */ get peers(): Map<number, LocalPeer | RemotePeer>; /** * Retrieves the "own" Peer instance associated with the current `ownPeerId` while connected. * * @return {Peer | undefined} The Peer instance if it exists, or `undefined` if not found. */ get ownPeer(): LocalPeer | undefined; get remotePeers(): Map<number, RemotePeer>; /** * Retrieves the customer ID associated with the current token, if available. * * @return {string | undefined} The customer ID as a string if present, otherwise undefined. */ get customer(): string | undefined; /** * Retrieves the current position as a 3D coordinate. * * @return {Array<number>} An array containing three numbers representing the x, y, and z coordinates of the position. */ get position(): [number, number, number]; /** * Gets the room data. * * @return {Uint8Array | undefined} The room data as a Uint8Array or undefined if no data is available. */ get roomData(): Uint8Array | undefined; /** * Sets the user data of the own peer with the provided Uint8Array. * * @param {Uint8Array} data - The data to be set as user data. */ set userData(data: Uint8Array); /** * Retrieves the own user data. * * @return {Uint8Array} The user data as a Uint8Array. */ get userData(): Uint8Array; /** * Retrieves the volume of the current instance. * * @return {PlaybackVolume} The current volume value. */ get volume(): PlaybackVolume; /** * Retrieves the current status of the room. * * @return {RoomStatus} The current status of the room. */ get status(): RoomStatus; /** * Retrieves a list of all AudioOutputs that are assigned to this room. * * @return {AudioOutput[]} An array of AudioOutput devices filtered from the outputs list. */ get audioOutputs(): AudioOutput[]; /** * Retrieves a list of VideoOutput devices that are assigned to this room. * * This method filters the available outputs to return only those * categorized as VideoOutput devices. * * @return {VideoOutput[]} An array of VideoOutput devices. */ get videoOutputs(): VideoOutput[]; /** * Sets the volume for the audio outputs. * * @param {PlaybackVolume} value - The volume level to set. * @return {Promise<void>} A promise that resolves when the volume is set for all audio outputs. */ setVolume(value: PlaybackVolume | number): Promise<void>; /** * Retrieves the available audio input devices that are assigned to this room. * * @return {AudioInput[]} An array of AudioInput objects representing the currently available audio inputs. */ get audioInputs(): AudioInput[]; /** * Retrieves an AudioOutput device by its media ID. * * @param {number} mediaId - The media id of the desired AudioOutput. * @return {AudioOutput | undefined} The AudioOutput object if found, otherwise undefined. */ getAudioOutputById(mediaId: number): AudioOutput | undefined; /** * Retrieves an VideoOutput device by its media ID. * * @param {number} mediaId - The media id of the desired VideoOutput. * @return {VideoOutput | undefined} The VideoOutput object if found, otherwise undefined. */ getVideoOutputById(mediaId: number): VideoOutput | undefined; /** * Adds a vVideoInput to start streaming. * * @param {VideoInput} input - The VideoInput source to be added. * @return {Promise<void>} Resolves when the VideoInput has been successfully added to the room. */ addVideoInput(input: VideoInput): Promise<void>; /** * Adds an AudioInput to start streaming. * * @param {AudioInput} input - The AudioInput instance to be added. * @return {Promise<void>} Resolves when the AudioInput is successfully added. * @throws Will throw an error if no audio plugin is available. */ addAudioInput(input: AudioInput): Promise<void>; /** * Removes the specified AudioInput and stops streaming. * * @param {AudioInput} input - The AudioInput instance to be removed. * @return {void} Does not return a value. */ removeAudioInput(input: AudioInput): void; /** * Removes the specified VideoInput and stops streaming. * * @param {VideoInput} input - The VideoInput instance to be removed. * @return {void} Does not return a value. */ removeVideoInput(input: VideoInput): void; /** * Starts the specified VideoOutput. After the VideoOutput was started, its MediaStream will be available. * * @param {VideoOutput} output - The VideoOutput object to start. The output must already exist in the room. * @return {Promise<void>} A promise that resolves when the video output is successfully started. */ startVideoOutput(output: VideoOutput): Promise<void>; /** * Stops the VideoOutput and stops streaming. * * @param {VideoOutput} output - The VideoOutput object containing the media and playback information. * @return {void} No return value. */ stopVideoOutput(output: VideoOutput): void; /** * Sets the audio output device to the specified device. * Currently, the same audio output is used across all rooms (in the same plugin that was used). * * @param {DeviceParameters} [device={}] - The parameters of the audio output device to be set. * @return {Promise<void>} A promise that resolves when the audio output device has been successfully set. */ setAudioOutputDevice(device?: DeviceParameters): Promise<void>; /** * Updates the position of the peer within the room. * * @param {number} offsetX - The X-coordinate of the new position. * @param {number} offsetY - The Y-coordinate of the new position. * @param {number} offsetZ - The Z-coordinate of the new position. * @return {Promise<void>} A promise that resolves when the position has been successfully updated. * @throws {Error} If the room is not joined. */ setPosition(offsetX: number, offsetY: number, offsetZ: number): Promise<void>; /** * Joins the room using the provided token and options. * * @param {string} token - The token that was generated with an access key and provided to the app. * @param {JoinParams} [options] - An optional object containing additional parameters for joining the room. * @param {string} [options.gateway] - The gateway URL to connect to. * @param {string} [options.roomId] - Specifies the unique ID of the room to join. Only useful for multi-room scenarios. * @param {object} [options.userData] - Own user data that other peers can see after the room was joined. * @param {boolean} [options.position] - Indicates whether to use a specific joining position. * @param {object} [options.cipher] - Configuration for encryption settings, if applicable. * @param {Transport} [options.transport] - Specifies the transport layer configuration. * @return {Promise<void>} Resolves when the join request is successful and the room is connected. * @throws {OdinError} Throws an error if the room joining process fails. */ join(token: string, options?: JoinParams): Promise<void>; /** * Disconnects the room resets the connection state. * * @param {string} [reason='Room left by user request'] - The reason for leaving the room. * @return {void} Does not return a value. */ leave(reason?: string): void; /** * Flushes the current user's data by sending an update request to the server. * Ensures the room is joined before proceeding with the operation. * * @return {Promise<void>} A promise that resolves once the user data update request is completed. */ flushUserData(): Promise<void>; /** * Send a rpc to the SFU. * * @param {Name} name - The name of the command to be executed. Must be a key of RoomCommands. * @param {Infer<RoomCommands[Name]['request']>} properties - The properties required for the specified command. * @return {Promise<void>} A promise that resolves when the request is successfully processed. */ request<Name extends Extract<keyof RoomCommands, string>>(name: Name, properties: Infer<RoomCommands[Name]['request']>): Promise<void>; /** * Sends a message with arbitrary data to all peers in the room or optionally to a list of specified peers. * * @param {Uint8Array} message - The message content to be sent. * @param {?number[]} [targetPeerIds] - An optional array of peer IDs to specify the message recipients. * If not provided, the message will be broadcasted to all peers. * @return {Promise<void>} A promise that resolves once the message has been successfully sent. * If the client is not connected or not in the room, an error will be thrown. */ sendMessage(message: Uint8Array, targetPeerIds?: number[]): Promise<void>; /** * Resumes a remote media on the audio server that was paused before. * The MediaID can be found at the AudioOutput of a peer. * * @param {number} mediaId - The unique identifier of the media to resume. * @return {Promise<void>} A promise that resolves when the media is successfully resumed or rejects with an error. */ resumeMedia(mediaId: number): Promise<void>; /** * Pauses a remote media on the audio server that was paused before. * The MediaID can be found at the AudioOutput of a peer. * @TODO Add a pause method to peers. * * @param {number} mediaId - The id of the media to be paused. * @return {Promise<void>} Resolves when the media is successfully paused or logs a warning if an error occurs. */ pauseMedia(mediaId: number): Promise<void>; getPlugin(): Promise<Plugin>; set status(state: RoomStatus); removeAudioOutput(output: AudioOutput): Promise<void>; addAudioOutput(output: AudioOutput): Promise<AudioOutput>; }