### Run Sample Prebuilt Application Source: https://github.com/100mslive/web-sdks/blob/main/README.md Navigate to the prebuilt-react-integration example directory and start the development server. Append a room code from the 100ms dashboard to the localhost URL. ```bash cd examples/prebuilt-react-integration yarn dev ``` -------------------------------- ### Install HMSHLSPlayer SDK Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Install the HMSHLSPlayer SDK using npm or yarn. ```bash npm i @100mslive/hls-player ``` -------------------------------- ### Install 100ms Whiteboard SDK Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-whiteboard/README.md Install the @100mslive/hms-whiteboard package using yarn. ```bash yarn add @100mslive/hms-whiteboard ``` -------------------------------- ### Install 100ms React SDK Source: https://github.com/100mslive/web-sdks/blob/main/packages/react-sdk/README.md Install the latest version of the 100ms React SDK using npm or yarn. ```bash npm install @100mslive/react-sdk@latest --save ``` ```bash yarn add @100mslive/react-sdk@latest ``` -------------------------------- ### Install and Build Web SDKs Source: https://github.com/100mslive/web-sdks/blob/main/README.md Clone the web-sdks repository, install dependencies, and build the project. Ensure Node.js version 18.0.0 or later is used. ```bash git clone https://github.com/100mslive/web-sdks.git cd web-sdks yarn install yarn build ``` -------------------------------- ### Initialize and Use HMSReactiveStore Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-video-store/README.md Demonstrates how to initialize the HMSReactiveStore, get actions and store interfaces, and subscribe to state changes like the dominant speaker. ```javascript const hms = new HMSReactiveStore(); const hmsActions = hms.getHMSActions(); const hmsStore = hms.getStore(); const toggleAudio = () => { const isEnabled = hmsStore.getState(selectIsLocalAudioEnabled); hmsActions.setLocalAudioEnabled(!isEnabled); } const onSpeakerUpdate = (speaker, prevSpeaker) => { console.log("speaker changed from - ", prevSpeaker, ", to - ", speaker); } hmsStore.subscribe(onSpeakerUpdate, selectDominantSpeaker); ``` -------------------------------- ### Install hls-stats with Yarn Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-stats/README.md Install the hls-stats library using Yarn. ```shell yarn add @100mslive/hls-stats ``` -------------------------------- ### Install React Icons with npm Source: https://github.com/100mslive/web-sdks/blob/main/packages/react-icons/README.md Install the latest version of the @100mslive/react-icons package using npm. ```bash npm install @100mslive/react-icons@latest --save ``` -------------------------------- ### Install React Icons with yarn Source: https://github.com/100mslive/web-sdks/blob/main/packages/react-icons/README.md Install the latest version of the @100mslive/react-icons package using yarn. ```bash yarn add @100mslive/react-icons@latest ``` -------------------------------- ### Instantiate HMSEffectsPlugin with SDK Key Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Example of how to get the effects SDK key using useHMSStore and instantiate the HMSEffectsPlugin. ```jsx const effectsKey = useHMSStore(selectEffectsKey); ``` -------------------------------- ### Install hls-stats with NPM Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-stats/README.md Install the hls-stats library using NPM. ```shell npm install --save @100mslive/hls-stats ``` -------------------------------- ### Install Virtual Background Package Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Install the latest version of the @100mslive/hms-virtual-background package using npm. ```bash npm install --save @100mslive/hms-virtual-background@latest ``` -------------------------------- ### Re-install Dependencies and Build Source: https://github.com/100mslive/web-sdks/blob/main/README.md After updating package.json with a local roomkit-react package, run these commands to install dependencies and build the project. ```bash yarn && yarn build ``` -------------------------------- ### Install Room Kit React Library Source: https://github.com/100mslive/web-sdks/blob/main/packages/roomkit-react/README.md Install the latest version of the Room Kit React library using npm or yarn. ```bash // npm npm install @100mslive/roomkit-react@latest --save ``` ```bash // yarn yarn add @100mslive/roomkit-react@latest ``` -------------------------------- ### Test Local Changes Source: https://github.com/100mslive/web-sdks/blob/main/README.md Run 'yarn start' within the specific package directory to see changes reflect in the sample app. Ensure 'yarn build' has been run at least once prior. ```bash yarn start ``` -------------------------------- ### Build Roomkit-React Package Source: https://github.com/100mslive/web-sdks/blob/main/README.md Build the roomkit-react package to generate a .tgz file for local deployment. This command installs dependencies, builds the project, and then packs the specified package. ```bash yarn && yarn build; cd packages/roomkit-react; yarn pack ``` -------------------------------- ### Initialize and Add Virtual Background Plugin Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md This snippet shows how to initialize the HMSEffectsPlugin and add it to the video stream using the HMS SDK. It handles the initial setup and checks if the plugin is already present. ```jsx import { selectEffectsKey, selectIsLocalVideoPluginPresent selectLocalVideoTrackID, useHMSStore, } from '@100mslive/react-sdk'; import { HMSEffectsPlugin, HMSVirtualBackgroundTypes } from '@100mslive/hms-virtual-background'; import { VBHandler } from './VBHandler'; export const VirtualBackgroundPicker = () => { const hmsActions = useHMSActions(); // Get the effects SDK key here const effectsKey = useHMSStore(selectEffectsKey); const trackId = useHMSStore(selectLocalVideoTrackID); const isPluginAdded = useHMSStore(selectIsLocalVideoPluginPresent(VBHandler?.getName() || '')); // State can be used to show active selection const [background, setBackground] = useState( VBHandler.getBackground() as string | HMSVirtualBackgroundTypes, ); useEffect(() => { if (!track?.id) { return; } if (!isPluginAdded) { let vbObject = VBHandler.getVBObject(); if (!vbObject) { VBHandler.initialisePlugin(effectsKey); vbObject = VBHandler.getVBObject(); if (effectsKey) { hmsActions.addPluginsToVideoStream([vbObject as HMSEffectsPlugin]); } } } }, [hmsActions, isPluginAdded, effectsKey, track?.id]); // UI code for media picker can go here } ``` -------------------------------- ### Unit Test Example with Jest Source: https://github.com/100mslive/web-sdks/blob/main/internal-docs/AutomatedTesting.md Write unit tests for features or bug fixes that can be tested in isolation. Test files should be located near the module they are testing. ```javascript it('should add track', () => { navigator.mediaDevices .getUserMedia({ video: true, audio: false }) .then(stream => { return stream.getVideoTracks()[0]; }) .then(videoTrack => { actions.addTrack(videoTrack); const localPeer = store.getState(selectLocalPeer); expect(localPeer.auxiliaryTracks[0]).to.equal(videoTrack.id); }); }); ``` -------------------------------- ### Toggle Whiteboard (React) Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-whiteboard/README.md Utilize the useWhiteboard hook to get toggle, open, and isOwner states. The toggle button is hidden for non-admin users. ```jsx // React Example import React from 'react'; import { useWhiteboard } from '@100mslive/react-sdk'; export const WhiteboardToggle = () => { const { toggle, open, isOwner } = useWhiteboard(); // non-admin users cannot toggle the whiteboard if (!toggle) { return null; } return ( ); }; ``` -------------------------------- ### Manage Video Quality Levels Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Control the video quality by getting the current layer with getLayer() and setting a desired layer with setLayer(). The layer object includes properties like bitrate, height, width, and URL. ```javascript /** * * @returns returns HMSHLSLayer which represents current * quality. */ hlsPlayer.getLayer(): HMSHLSLayer | null; /** * * @param { HMSHLSLayer } layer - layer we want to set the stream to. * set { height: auto } to set the layer to auto */ hlsPlayer.setLayer(layer: HMSHLSLayer): void; // quality interface interface HMSHLSLayer { readonly bitrate: number; readonly height?: number; readonly id?: number; readonly width?: number; url: string; resolution?: string; } ``` -------------------------------- ### HLS Playback State Event Usage Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Example of how to use the playback state event to determine if the HLS player is currently paused. This is a simple demonstration of subscribing to player events. ```javascript const isPlaying = false; const playbackEventHandler = data => isPlaying = data.state === HLSPlaybackState.paused; hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler); ``` -------------------------------- ### HLS Video Current Time Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Get the current playback time of the HLS video. This event is useful for tracking progress or synchronizing external elements with the video playback. ```javascript hlsPlayer.on(HMSHLSPlayerEvents.CURRENT_TIME, (event: HMSHLSPlayerEvents, data: number): void => {}); ``` -------------------------------- ### HLS Quality Changed Data Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Subscribe to quality changed events to get notified when the HLS player updates its current playback layer. The event provides the details of the newly selected layer. ```javascript interface HMSHLSLayerUpdated { layer: HMSHLSLayer; } hlsPlayer.on(HMSHLSPlayerEvents.LAYER_UPDATED, (event: HMSHLSPlayerEvents, data: HMSHLSLayerUpdated): void => {}); ``` -------------------------------- ### Deploy to Vercel Source: https://github.com/100mslive/web-sdks/blob/main/README.md Configure Vercel by setting the root directory to 'examples/prebuilt-react-integration' and updating install/build commands to use root-level scripts. Append room code to the deployment URL. ```bash install: cd ../../ && yarn install build: cd ../../ && yarn build ``` -------------------------------- ### Initialize Hls.js and HlsStats Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-stats/README.md Initialize Hls.js with a video element and then initialize HlsStats with the Hls.js instance and video element. ```javascript import Hls from "hls.js"; /** * Initialize Hls.js and attach the video element. */ const hlsInstance = new Hls(); hlsInstance.loadSource(hlsUrl); hlsInstance.attachMedia(videoEl); /** * initialize HlsStats */ const hlsStats = new HlsStats(hlsController.getHlsJsInstance(), videoEl); ``` -------------------------------- ### Initialize HLS Player in Vanilla JavaScript Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Demonstrates how to initialize the HMSHLSPlayer in a vanilla JavaScript environment. It includes setting up event listeners for common playback events. ```javascript // Vanilla JavaScript Example import { HLSPlaybackState, HMSHLSPlayer, HMSHLSPlayerEvents } from "@100mslive/hls-player"; const videoEl; // reference for video element const hlsUrl; // reference to hls url // variable to handle ui and take some actions let isLive = true, isPaused = false, isAutoBlockedPaused = false; const handleError = data => console.error("[HLSView] error in hls", data); const handleNoLongerLive = ({ isLive }) => isLive = isLive; const playbackEventHandler = data => isPaused = (data.state === HLSPlaybackState.paused); const handleAutoplayBlock = data => isAutoBlockedPaused = !!data; const hlsPlayer = new HMSHLSPlayer(hlsUrl, videoEl); hlsPlayer.on(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, handleNoLongerLive); hlsPlayer.on(HMSHLSPlayerEvents.ERROR, handleError); hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler); hlsPlayer.on(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, handleAutoplayBlock); ``` -------------------------------- ### Initialize HMSHLSPlayer Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Create an instance of HMSHLSPlayer with a HLS URL and an optional video element. If no video element is provided, a new one will be created. ```javascript import { HMSHLSPlayer } from '@100mslive/hls-player'; // hls url should be provided which player will run. // second parameter is optional, if you had video element then pass to player else we will create one. const hlsPlayer = new HMSHLSPlayer(hlsURL, videoEl) // if video element is not present, we will create a new video element which can be attached to your ui. const videoEl = hlsPlayer.getVideoElement(); ``` -------------------------------- ### VBPlugin Class and Handler Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Demonstrates the implementation of a Virtual Background handler class using HMSEffectsPlugin. ```APIDOC ## VBPlugin Class and Handler ### Description This section shows a practical implementation of a `VBPlugin` class that wraps the `HMSEffectsPlugin` for easier management within an application. It includes methods for initialization, getting and setting background properties, and resetting the plugin. ### Class: `VBPlugin` - **`initialisePlugin(effectsSDKKey?: string): void`** Initializes the `HMSEffectsPlugin` if it hasn't been already. Requires an `effectsSDKKey`. - **`getBackground(): string | MediaStream | MediaStreamTrack | HTMLVideoElement | undefined`** Returns the current background set in the plugin. - **`getBlurAmount(): number | undefined`** Returns the current blur amount set in the plugin. - **`getVBObject(): HMSEffectsPlugin | undefined`** Returns the instance of `HMSEffectsPlugin`. - **`getName(): string | undefined`** Returns the name of the plugin. - **`setBlur(blurPower: number): Promise`** Asynchronously sets the blur power for the virtual background. - **`setBackground(mediaURL: string): Promise`** Asynchronously sets the virtual background using a media URL. - **`setPreset(preset: string): void`** Sets the preset quality for the virtual background. - **`getPreset(): string`** Retrieves the active preset quality. - **`removeEffects(): Promise`** Asynchronously removes all applied effects. - **`reset(): void`** Resets the `effectsPlugin` instance to undefined. ### Instance: `VBHandler` - **`VBHandler`**: An exported instance of the `VBPlugin` class, providing a singleton-like access point for managing virtual background functionalities. ### Example Usage ```javascript import { VBHandler } from './path/to/VBPlugin'; // Assuming VBPlugin is in a separate file // To initialize the plugin: // const effectsKey = "YOUR_EFFECTS_SDK_KEY"; // VBHandler.initialisePlugin(effectsKey); // To set a background image: // VBHandler.setBackground("https://example.com/image.jpg"); // To set blur intensity: // VBHandler.setBlur(0.7); // Sets blur to 70% // To remove effects: // VBHandler.removeEffects(); ``` ``` -------------------------------- ### HMSEffectsPlugin Initialization Callback Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Initialize the HMSEffectsPlugin and log a message once the required resources are downloaded. ```javascript const effectsPlugin = new HMSEffectsPlugin(, () => console.log("Plugin initialised")); ``` -------------------------------- ### Build Custom Icons Source: https://github.com/100mslive/web-sdks/blob/main/packages/react-icons/README.md After adding SVG files to the /assets directory, run the build command to autogenerate JSX files for the icons. ```bash yarn build ``` -------------------------------- ### Initialize HLS Player in React Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Shows how to initialize and manage the HMSHLSPlayer within a React component using the useEffect hook. It includes setting up and cleaning up event listeners. ```jsx // React Example import { HLSPlaybackState, HMSHLSPlayer, HMSHLSPlayerEvents } from "@100mslive/hls-player"; import { useEffect, useState } from 'react'; const videoEl; // reference for video element const hlsUrl; // reference to hls url // variable to handle ui and take some actions const [isVideoLive, setIsVideoLive] = useState(true); const [isHlsAutoplayBlocked, setIsHlsAutoplayBlocked] = useState(false); const [isPaused, setIsPaused] = useState(false); useEffect(() => { const handleError = data => console.error("[HLSView] error in hls", data); const handleNoLongerLive = ({ isLive }) => { setIsVideoLive(isLive); }; const playbackEventHandler = data => setIsPaused(data.state === HLSPlaybackState.paused); const handleAutoplayBlock = data => setIsHlsAutoplayBlocked(!!data); const hlsPlayer = new HMSHLSPlayer(hlsUrl, videoEl); hlsPlayer.on(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, handleNoLongerLive); hlsPlayer.on(HMSHLSPlayerEvents.ERROR, handleError); hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler); hlsPlayer.on(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, handleAutoplayBlock); return () => { hlsPlayer.off(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, handleNoLongerLive); hlsPlayer.off(HMSHLSPlayerEvents.ERROR, handleError); hlsPlayer.off(HMSHLSPlayerEvents.PLAYBACK_STATE, playbackEventHandler); hlsPlayer.off(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, handleAutoplayBlock); } }, []); ``` -------------------------------- ### Display Whiteboard (JavaScript) Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-whiteboard/README.md Subscribe to whiteboard state changes using selectWhiteboard. If the whiteboard is open and has a URL, an iframe is created; otherwise, any existing iframe is removed. ```javascript // Vanilla JavaScript Example import { selectWhiteboard } from '@100mslive/hms-video-store'; const whiteboard = hmsStore.subscribe((whiteboard) => { if (whiteboard?.open && whiteboard?.url) { const whiteboardIframe = document.createElement('iframe'); whiteboardIframe.src = whiteboard.url; } else { const whiteboardIframe = document.getElementById('whiteboard'); whiteboardIframe?.remove(); } }, selectWhiteboard); ``` -------------------------------- ### React Hook for Joining a Room Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-video-store/README.md Shows how to use React hooks to check room connection status and trigger the join action. Requires HMSRoomProvider for context. ```jsx function join() { const isConnected = useHMSStore(selectIsConnectedToRoom); const hmsActions = useHMSActions(); return <> { !isConnected && } } ``` -------------------------------- ### Initialize HMSRoomProvider Source: https://github.com/100mslive/web-sdks/blob/main/packages/react-sdk/README.md Wrap your application's top-level component with HMSRoomProvider to enable the use of 100ms hooks. This provider is essential for the hooks to function correctly. ```jsx ``` -------------------------------- ### Import RoomKit Web Component Source: https://github.com/100mslive/web-sdks/blob/main/packages/roomkit-web/README.md Import the RoomKit web component to make it available for use in your application. ```javascript import '@100mslive/roomkit-web' ``` -------------------------------- ### HMSHLSPlayer Methods Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md This section details the core methods available on the HMSHLSPlayer interface for controlling HLS playback. ```APIDOC ## HMSHLSPlayer Methods ### `getVideoElement()` **Description**: Retrieves the HTML video element associated with the player. **Returns**: `HTMLVideoElement` - The video element. ### `setVolume(volume: number)` **Description**: Sets the volume of the HLS player. **Parameters**: - **volume** (number) - Required - The volume level, in the range of 0 to 100. ### `getLayer(): HMSHLSLayer | null` **Description**: Gets the current video quality layer. **Returns**: `HMSHLSLayer | null` - The current quality layer or null if not available. ### `setLayer(layer: HMSHLSLayer)` **Description**: Sets the video quality layer for the stream. Use `{ height: 'auto' }` to set the layer to automatic quality. **Parameters**: - **layer** (`HMSHLSLayer`) - Required - The desired quality layer. ### `seekToLivePosition(): Promise` **Description**: Seeks the playback to the live position of the stream. **Returns**: `Promise` ### `play(): Promise` **Description**: Starts or resumes playback of the HLS stream. This should be called when an autoplay error is received. **Returns**: `Promise` ### `pause(): void` **Description**: Pauses the playback of the HLS stream. ### `seekTo(seekValue: number): void` **Description**: Updates the current playback time of the video. **Parameters**: - **seekValue** (number) - Required - The desired current time in seconds. ``` -------------------------------- ### Import HMSPrebuilt Component Source: https://github.com/100mslive/web-sdks/blob/main/README.md Import the HMSPrebuilt component after successfully setting up and building the roomkit-react package. ```javascript import { HMSPrebuilt } from '@100mslive/roomkit-react'; ``` -------------------------------- ### Display Whiteboard (React) Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-whiteboard/README.md Embed the Whiteboard component using the token and endpoint from useWhiteboard. The component requires specific styling and provides onMount callback. ```jsx // React Example import React from 'react'; import { useWhiteboard } from '@100mslive/react-sdk'; import { Whiteboard } from '@100mslive/hms-whiteboard'; import '@100mslive/hms-whiteboard/index.css'; const WhiteboardEmbed = () => { const { token, endpoint } = useWhiteboard(); if (!token) { return null; } return (
{ console.log(store, editor); }} />
); }; ``` -------------------------------- ### Toggle Whiteboard (JavaScript) Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-whiteboard/README.md Use the selectPermissions and selectWhiteboard selectors to manage whiteboard access and state. Non-admin users cannot toggle the whiteboard. ```javascript // Vanilla JavaScript Example import { selectPermissions, selectWhiteboard } from '@100mslive/hms-video-store'; const permissions = hmsStore.getState(selectPermissions)?.whiteboard; // Array<'read' | 'write' | 'admin'> const isAdmin = !!permissions?.includes('admin'); const whiteboard = hmsStore.getState(selectWhiteboard); const isOwner = whiteboard?.owner === localPeerUserId; const toggle = async () => { if (!isAdmin) { return; } if (whiteboard?.open) { isOwner && (await actions.interactivityCenter.whiteboard.close()); } else { await actions.interactivityCenter.whiteboard.open(); } }; // usage const toggleButton = document.getElementById('toggle-whiteboard'); // non-admin users cannot toggle the whiteboard toggleButton.disabled = !isAdmin; toggleButton.onclick = toggle; ``` -------------------------------- ### HMSEffectsPlugin Methods Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md This section details the methods available within the HMSEffectsPlugin class for managing virtual backgrounds and effects. ```APIDOC ## HMSEffectsPlugin Methods ### Description Provides methods to control virtual background features like blur intensity, background image replacement, preset quality, and effect removal. ### Methods - **`setBlur(blur: number): void`** Sets the blur intensity for the background. The intensity should be a value between 0 and 1. - **`setBackground(url: HMSEffectsBackground): void`** Sets a new background image using the provided media URL. The image can also be a pre-downloaded object URL. - **`getName(): string`** Retrieves the name of the plugin. Expected to return 'HMSEffects'. - **`getBackground(): string | MediaStream | MediaStreamTrack | HTMLVideoElement`** Retrieves the currently set background type or media stream URL. - **`setPreset(preset: string): Promise`** Sets the preset quality for the virtual background. Accepted values are 'balanced' (default) or 'quality'. 'quality' uses more CPU. - **`getPreset(): string`** Retrieves the currently active preset quality ('balanced' or 'quality'). - **`removeEffects(): void`** Removes all applied virtual background effects and filters. - **`stop(): void`** Stops the virtual background plugin. ### Callbacks - **Initialization Callback**: A callback function can be provided during initialization to be executed once the plugin's resources are downloaded. ```javascript const effectsPlugin = new HMSEffectsPlugin(, () => console.log("Plugin initialised")); ``` - **`onResolutionChange`**: A callback property that can be set to handle resolution changes (e.g., device rotation). ```javascript effectsPlugin.onResolutionChange = (width: number, height: number) => { console.log(`Resolution changed to ${width}x${height}`); }; ``` ``` -------------------------------- ### VBPlugin Class for Virtual Background Management Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md A class to manage the HMSEffectsPlugin, encapsulating initialization and method calls for virtual background features. ```javascript import { HMSEffectsPlugin, HMSVirtualBackgroundTypes } from '@100mslive/hms-virtual-background'; export class VBPlugin { private effectsPlugin?: HMSEffectsPlugin | undefined; initialisePlugin = (effectsSDKKey?: string) => { if (this.getVBObject()) { return; } if (effectsSDKKey) { this.effectsPlugin = new HMSEffectsPlugin(effectsSDKKey); } }; getBackground = () => { return this.effectsPlugin?.getBackground(); }; getBlurAmount = () => { return this.effectsPlugin?.getBlurAmount(); }; getVBObject = () => { return this.effectsPlugin; }; getName = () => { return this.effectsPlugin?.getName(); }; setBlur = async (blurPower: number) => { this.effectsPlugin?.setBlur(blurPower); }; setBackground = async (mediaURL: string) => { this.effectsPlugin?.setBackground(mediaURL); }; setPreset = (preset: string) => { this.effectsPlugin.setPreset(preset); }; getPreset = () => { return this.effectsPlugin?.getPreset() || ''; }; removeEffects = async () => { this.effectsPlugin?.removeEffects(); }; reset = () => { this.effectsPlugin = undefined; }; } export const VBHandler = new VBPlugin(); ``` -------------------------------- ### HMSEffectsPlugin Class Methods Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md API reference for the HMSEffectsPlugin class, detailing methods for setting blur, background images, presets, and managing effects. ```javascript /** * Sets the blur intensity. * @param {number} blur - The blur intensity, ranging from 0 to 1. * @returns {void} */ setBlur(blur) {} /** * Sets the virtual background using the provided media URL. * @param {HMSEffectsBackground} url - The media URL to set as the virtual background. * Alternatively, the background image can be downloaded beforehand and passed to setBackground as objectURL * @returns {void} */ setBackground(url) {} /** * Retrieves the name of the plugin. * @returns {string} The name of the plugin, 'HMSEffects'. */ getName() {} /** * Retrieves the currently enabled background type or media URL. * @returns {string|MediaStream|MediaStreamTrack|HTMLVideoElement} The background type or media URL. */ getBackground() {} /** * Sets the preset quality of the virtual background. * Options: "balanced" | "quality" * The 'quality' preset has a higher CPU usage than the 'balanced' preset which is the default * @param {string} preset - The preset quality to set. * @returns {Promise} */ setPreset(preset) {} /** * Retrieves the active preset quality of the virtual background. * @returns {string} The active preset quality. */ getPreset() {} /** * Clears all applied filters. * @returns {void} */ removeEffects() {} /** * Stops the plugin. * @returns {void} */ stop() {} ``` -------------------------------- ### Seek to a Specific Time Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Use the seekTo method to navigate to a specific point in the video by providing the time in seconds. ```javascript // seekValue Pass currentTime in second hlsPlayer.seekTo(5) ``` -------------------------------- ### Seek to Live Position Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Use the seekToLivePosition method to jump to the current live edge of the stream. ```javascript hlsPlayer.seekToLivePosition() ``` -------------------------------- ### Set Virtual Background Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Use this method to set a new virtual background from a media URL. It updates the active background state. ```jsx const setBackground = async(mediaURL : string) => { await VBHandler?.setBackground(mediaURL); // The selection can be highlighted using the activeBackground state setActiveBackground(mediaURL); } ``` -------------------------------- ### HMSHLSPlayer Events Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md This section describes the events that can be listened to on the HMSHLSPlayer instance for various playback states and occurrences. ```APIDOC ## HMSHLSPlayer Events ### `HMSHLSPlayerEvents` Enum This enum defines the available event types: - `TIMED_METADATA_LOADED` ('timed-metadata') - `SEEK_POS_BEHIND_LIVE_EDGE` ('seek-pos-behind-live-edge') - `CURRENT_TIME` ('current-time') - `AUTOPLAY_BLOCKED` ('autoplay-blocked') - `MANIFEST_LOADED` ('manifest-loaded') - `LAYER_UPDATED` ('layer-updated') - `ERROR` ('error') - `PLAYBACK_STATE` ('playback-state') - `STATS` ('stats') ### `PLAYBACK_STATE` Event **Description**: Listens for changes in the playback state (playing or paused). **Callback Signature**: `(event: HMSHLSPlayerEvents.PLAYBACK_STATE, data: HMSHLSPlaybackState) => void` **Data Structure**: `HMSHLSPlaybackState` ```typescript interface HMSHLSPlaybackState { state: HLSPlaybackState; } enum HLSPlaybackState { playing, paused, } ``` ``` -------------------------------- ### Handle Playback State Events Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Listen for playback state changes using the PLAYBACK_STATE event. The event data includes the current playback state (playing or paused). ```javascript enum HMSHLSPlayerEvents { TIMED_METADATA_LOADED = 'timed-metadata', SEEK_POS_BEHIND_LIVE_EDGE = 'seek-pos-behind-live-edge', CURRENT_TIME = 'current-time', AUTOPLAY_BLOCKED = 'autoplay-blocked', MANIFEST_LOADED = 'manifest-loaded', LAYER_UPDATED = 'layer-updated', ERROR = 'error', PLAYBACK_STATE = 'playback-state', STATS = 'stats', } enum HLSPlaybackState { playing, paused, } interface HMSHLSPlaybackState { state: HLSPlaybackState; } hlsPlayer.on(HMSHLSPlayerEvents.PLAYBACK_STATE, (event: HMSHLSPlayerEvents, data: HMSHLSPlaybackState): void => {}); ``` -------------------------------- ### Usage with Auth Token Source: https://github.com/100mslive/web-sdks/blob/main/packages/roomkit-react/README.md Integrate the HMSPrebuilt component into your React application using an authentication token. ```jsx import { HMSPrebuilt } from '@100mslive/roomkit-react' export default App() { return ( } /> ); } ``` -------------------------------- ### Play and Pause Playback Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Control the playback of the HLS stream using the play() and pause() methods on the hlsPlayer instance. ```javascript // return Promise hmsPlayer.play() hmsPlayer.pause() ``` -------------------------------- ### Vue Component Usage with RoomKit Source: https://github.com/100mslive/web-sdks/blob/main/packages/roomkit-web/README.md Integrate the hms-prebuilt component into a Vue.js application by importing the RoomKit library and using the component in your template with a room code. ```html ``` -------------------------------- ### HMSEffectsPlugin Resolution Change Callback Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Handle resolution changes for the virtual background plugin, such as on device rotation or aspect ratio changes. ```javascript effectsPlugin.onResolutionChange = (width: number, height: number) => { console.log(`Resolution changed to ${width}x${height}`) } ``` -------------------------------- ### Update Roomkit-React Package in App Source: https://github.com/100mslive/web-sdks/blob/main/README.md Modify the app's package.json to point to a local .tgz file of the roomkit-react package. After updating, re-install dependencies and build the project. ```json "@100mslive/roomkit-react":"https://github.com//web-sdks/raw/main/packages/roomkit-react/.tgz", ``` -------------------------------- ### HLS Error Handling Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Implement error handling for HLS playback by subscribing to error events. The event data includes error name, message, description, and a terminal flag to determine if the player will automatically restart. ```javascript interface HMSHLSException { name: string, message: string, description: string, isTerminal: boolean, // decide if player error will automatically restart(if false) } hlsPlayer.on(HMSHLSPlayerEvents.ERROR, (event: HMSHLSPlayerEvents, data: HMSHLSException): void => {}); hlsPlayer.on(HMSHLSPlayerEvents.AUTOPLAY_BLOCKED, (event: HMSHLSPlayerEvents, data: HMSHLSException): void => {}); ``` -------------------------------- ### Cypress: Wrap Promise in cy.wrap Source: https://github.com/100mslive/web-sdks/blob/main/internal-docs/AutomatedTesting.md When testing asynchronous operations in Cypress, wrap promises with cy.wrap to ensure expect statements within them are executed. ```javascript cy.wrap(actions.addTrack(videoTrack)); ``` -------------------------------- ### HLS Player Statistics Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Listen for HLS player statistics to monitor connection speed, bitrate, buffer duration, and dropped frames. The event provides detailed metrics about the current HLS stream. ```javascript interface HlsPlayerStats { /** Estimated bandwidth in bits/sec. Could be used to show connection speed. */ bandwidthEstimate?: number; /** The bitrate of the current level that is playing. Given in bits/sec */ bitrate?: number; /** the amount of video available in forward buffer. Given in ms */ bufferedDuration?: number; /** how far is the current playback from live edge.*/ distanceFromLive?: number; /** total Frames dropped since started watching the stream. */ droppedFrames?: number; /** the m3u8 url of the current level that is being played */ url?: string; /** the resolution of the level of the video that is being played */ videoSize?: { height: number; width: number; }; } hlsPlayer.on(HMSHLSPlayerEvents.STATS, (event: HMSHLSPlayerEvents, data: HlsPlayerStats): void => {}); ``` -------------------------------- ### Subscribe to HLS Stats Updates Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-stats/README.md Subscribe to receive HLS statistics updates at a specified interval. The subscribe function returns an unsubscribe function to stop receiving updates. ```javascript const unsubscribe = hlsStats.subscribe(state => { // ... }); ``` -------------------------------- ### Cypress: Return Promise from Cypress Chainable Source: https://github.com/100mslive/web-sdks/blob/main/internal-docs/AutomatedTesting.md Alternatively, return promises from Cypress chainables to ensure proper execution of subsequent expect statements. This is useful for testing flows that involve asynchronous actions. ```javascript cy.get('@onTrackJoin') .should('be.called') .then(() => { return actions.addTrack(videoTrack); }); ``` -------------------------------- ### HLS Timed-Metadata Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Handle HLS timed-metadata events to process metadata embedded within the HLS stream. The event provides cue information including ID, payload, duration, and start/end dates. ```javascript interface HMSHLSCue { id?: string; payload: string; duration: number; startDate: Date; endDate?: Date; } hlsPlayer.on(HMSHLSPlayerEvents.TIMED_METADATA_LOADED, (event: HMSHLSPlayerEvents, data: HMSHLSCue): void => {}); ``` -------------------------------- ### Usage with Room Code Source: https://github.com/100mslive/web-sdks/blob/main/packages/roomkit-react/README.md Integrate the HMSPrebuilt component into your React application using a room code. ```jsx import { HMSPrebuilt } from '@100mslive/roomkit-react' export default App() { return ( } /> ); } ``` -------------------------------- ### Clear Object Entry Iteration Naming Source: https://github.com/100mslive/web-sdks/blob/main/DEVELOPER.MD When iterating over object entries, use descriptive names for the key and value to clarify their meaning. ```TypeScript Object.entries(tracksMap).forEach((key, val) => {}); // ❌ Object.entries(tracksMap).forEach((trackId, track) => {}); // ✅ ``` -------------------------------- ### Descriptive Variable Naming Source: https://github.com/100mslive/web-sdks/blob/main/DEVELOPER.MD Use whole words and descriptive names for variables instead of cryptic abbreviations to improve readability. ```TypeScript let lYrCnt = 5; // ❌ let leapYearCount = 5; // ✅ ``` -------------------------------- ### HLS Manifest Loaded Data Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Receive manifest loaded data to access information about different quality layers available in the HLS stream. This event is triggered once the manifest URL has been successfully loaded. ```javascript interface HMSHLSManifestLoaded { layers: HMSHLSLayer[]; } hlsPlayer.on(HMSHLSPlayerEvents.MANIFEST_LOADED, (event: HMSHLSPlayerEvents, data: HMSHLSManifestLoaded): void => {}); ``` -------------------------------- ### Set Virtual Background Blur Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md This method applies a blur effect to the video stream. It updates the active background state to indicate blur is active. ```jsx const setBlur = async(blurAmount: number) => { await VBHandler?.setBlur(blurAmount); setActiveBackground(HMSVirtualBackgroundTypes.BLUR); } ``` -------------------------------- ### Set Playback Volume Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Adjust the volume of the HLS player using the setVolume method. The volume level is an integer between 0 and 100. The default volume is 100. ```javascript hlsPlayer.setVolume(50); ``` -------------------------------- ### Explicit Condition Abstraction Source: https://github.com/100mslive/web-sdks/blob/main/DEVELOPER.MD Abstract complex conditions into well-named variables to make conditional logic explicit and easier to understand. ```TypeScript // ❌ 😢 if (peers.length === 1 || peers.filter(peer => peer.isPublishing).length === 0) { } // ✅ const itsOnlyMeInTheRoom = peers.length === 1; const peersPublishing = peers.filter(peer => peer.isPublishing); const nooneIsPublishing = peersPublishing.length === 0; const showWebinarBanner = itsOnlyMeInTheRoom || nooneIsPublishing; if (showWebinarBanner) { } ``` -------------------------------- ### HLS Live Event Source: https://github.com/100mslive/web-sdks/blob/main/packages/hls-player/README.md Detect if the HLS player is currently playing live video. This event indicates whether the stream is live or a VOD. Use this to adjust UI elements or behavior based on live status. ```javascript interface HMSHLSStreamLive { isLive: boolean; } hlsPlayer.on(HMSHLSPlayerEvents.SEEK_POS_BEHIND_LIVE_EDGE, (event: HMSHLSPlayerEvents, data: HMSHLSStreamLive): void => {}); ``` -------------------------------- ### Clear Loop Variable Naming Source: https://github.com/100mslive/web-sdks/blob/main/DEVELOPER.MD Use clear and descriptive names for loop variables to indicate the type of items being iterated over. ```TypeScript for (let item of peers) { } for (let peer of peers) { } ``` -------------------------------- ### Disable Leave on Unload Source: https://github.com/100mslive/web-sdks/blob/main/packages/react-sdk/README.md By default, HMSRoomProvider calls leaveRoom when the tab/window is closed. Pass `leaveOnUnload={false}` to disable this behavior. Note that the leave event might not always be sent reliably due to browser limitations. ```jsx ``` -------------------------------- ### Remove Virtual Background Effects Source: https://github.com/100mslive/web-sdks/blob/main/packages/hms-virtual-background/README.md Call this method to remove any applied virtual background effects and reset the background state. ```jsx const removeEffects = async() => { await VBHandler.removeEffects(); setActiveBackground(HMSVirtualBackgroundTypes.NONE); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.