# Fishjam Docs
> Fishjam is a low-latency video conferencing and live streaming API created by Software Mansion. It lets developers build real-time video, audio, and data streaming applications using WebRTC without needing any WebRTC expertise.
This file contains all documentation content in a single document following the llmstxt.org standard.
## Agents
# Fishjam Agent Introduction
:::tip
We recommend going through the steps in the [Backend Quick Start](../tutorials/backend-quick-start)
before trying Fishjam agents, as you will need a working backend server to use them.
:::
This page gives an introduction to Fishjam agents and how to use them.
You can learn more about how Agents work on the [Agent Internals](../explanation/agent-internals) page.
## What is an Agent?
An agent is a piece of software that allows your backend server to participate in a Fishjam room, similar to how the Fishjam client SDKs allow your client-side application to participate in a Fishjam room.
They can be used to implement features such as real-time audio transcription, real-time content moderation, conversations with AI agents and more.
You can simply think of an agent as a peer running within your backend application.
## Writing an Agent
In this section we show how to implement an agent using the Fishjam server SDKs.
If you are not using the SDKs, then you can check out the [Agent Internals](../explanation/agent-internals#agent-lifecycle), to learn how to integrate with Fishjam Agents.
### Prerequisites
Before we create the actual agent, we need to [create a room](../tutorials/backend-quick-start#step-4-create-a-room) first, as agents are scoped to rooms.
Additionally, we will also create a peer so that the agent has someone to listen to and talk to.
```ts
const fishjamId = "";
const managementToken = "";
// ---cut---
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const room = await fishjamClient.createRoom();
const peer = await fishjamClient.createPeer(room.id);
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(fishjam_id, management_token)
room = fishjam_client.create_room()
peer = fishjam_client.create_peer(room.id)
```
### Creating a listening Agent
If you are using the server SDKs, then creating an agent and defining its behavior is very simple.
By default, agents receive all peers' audio streams.
However, it's likely that in your scenario you'll want to use the [Selective Subscriptions API](../how-to/backend/selective-subscriptions.mdx) for fine-grained control over which peers/tracks they should receive audio from.
```ts
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const room = await fishjamClient.createRoom();
// ---cut---
const agentOptions = {
subscribeMode: 'auto',
output: { audioFormat: 'pcm16', audioSampleRate: 16000 }
} satisfies PeerOptions;
const agentCallbacks = {
onError: console.error,
onClose: (code, reason) => console.log('Agent closed', code, reason)
} satisfies AgentCallbacks;
// [!code highlight:1]
const { agent } = await fishjamClient.createAgent(room.id, agentOptions, agentCallbacks);
// Register a callback for incoming audio data
agent.on('trackData', ({ track, peerId, data }) => {
// process the incoming data
})
```
```python
from fishjam import FishjamClient, AgentOptions
from fishjam.agent import IncomingTrackData
fishjam_client = FishjamClient(fishjam_id, management_token)
agent_options = AgentOptions(subscribe_mode="auto")
agent = fishjam_client.create_agent(room_id, agent_options)
async def run():
# the agent will disconnect once you exit the context
async with agent.connect() as session:
async for track_data in session.receive():
# process the incoming data
pass
asyncio.run(run())
```
### Multiple Agents in a Room
You can create multiple agents inside a single room by creating agents with the same room ID multiple times.
Each agent operates independently, with its own set of tracks and callbacks.
```ts
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const room = await fishjamClient.createRoom();
const agentOptions = {
subscribeMode: 'auto',
output: { audioFormat: 'pcm16', audioSampleRate: 16000 }
} satisfies PeerOptions;
const agentCallbacks = {
onError: console.error,
onClose: (code, reason) => console.log('Agent closed', code, reason)
} satisfies AgentCallbacks;
// ---cut---
const agentCallbacks1 = {
onError: console.error,
onClose: (code, reason) => console.log('Agent 1 closed', code, reason)
} satisfies AgentCallbacks;
const agentCallbacks2 = {
onError: console.error,
onClose: (code, reason) => console.log('Agent 2 closed', code, reason)
} satisfies AgentCallbacks;
const { agent: agent1 } = await fishjamClient.createAgent(room.id, agentOptions, agentCallbacks1);
const { agent: agent2 } = await fishjamClient.createAgent(room.id, agentOptions, agentCallbacks2);
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(fishjam_id, management_token)
agent1 = fishjam_client.create_agent(room_id)
agent2 = fishjam_client.create_agent(room_id)
```
### Making the Agent speak
Apart from just listening, agents can also send audio data to peers.
Let's assume that in the previous section we forwarded the peer's audio to some audio chatbot.
Now, the chatbot returns responses, and we want to play it back to the peer.
:::tip
You can interrupt the currently played audio chunk. See the example below.
:::
```ts
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const room = await fishjamClient.createRoom();
const { agent } = await fishjamClient.createAgent(room.id, {});
const chatbot: any = null;
// ---cut---
const codecParameters = {
encoding: 'pcm16',
sampleRate: 16000,
channels: 1,
} satisfies AudioCodecParameters;
const agentTrack = agent.createTrack(codecParameters);
// that's a dummy chatbot,
// you can bring your audio from anywhere
chatbot.on('response', (response: Uint8Array) => {
// [!code highlight:1]
agent.sendData(agentTrack.id, response);
// you're able to interrupt the currently played audio chunk
// [!code highlight:1]
agent.interruptTrack(agentTrack.id);
});
```
```python
from fishjam import FishjamClient, AgentOptions
from fishjam.agent import OutgoingAudioTrackOptions
from fishjam.events import TrackEncoding
fishjam_client = FishjamClient(fishjam_id, management_token)
agent_options = AgentOptions(subscribe_mode="auto")
agent = fishjam_client.create_agent(room_id, agent_options)
track_options = OutgoingAudioTrackOptions(encoding=TrackEncoding.TRACK_ENCODING_PCM16)
async def run():
# the agent will disconnect once you exit the context
async with agent.connect() as session:
outgoing_track = await session.add_track(track_options)
# that's a dummy chatbot
async for chatbot_data in chatbot.receive():
await outgoing_track.send_chunk(chatbot_data)
# you're able to interrupt the currently played audio chunk
# [!code highlight:1]
await outgoing_track.interrupt()
asyncio.run(run())
```
### Making the Agent see
Agents can also request video frames (JPEG images) from peers' video tracks.
Unlike audio, which streams continuously, video frames must be explicitly requested and arrive asynchronously.
:::important
Video frame capture is rate-limited to one frame per second per track.
:::
```ts
// @noErrors
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const room = await fishjamClient.createRoom();
const { agent } = await fishjamClient.createAgent(room.id, {});
const trackId: TrackId = '' as TrackId;
// ---cut---
// Listen for incoming video frames
agent.on('trackImage', (message: IncomingTrackImage) => {
const { contentType, data } = message;
// process the image data
});
// Request a frame periodically
setInterval(() => {
// [!code highlight:1]
agent.captureImage(trackId);
}, 1000);
```
```python
from fishjam import FishjamClient
from fishjam.agent import IncomingTrackImage
fishjam_client = FishjamClient(fishjam_id, management_token)
agent = fishjam_client.create_agent(room_id)
async def run():
async with agent.connect() as session:
# Request a frame
# [!code highlight:1]
await session.capture_image(track_id)
# Captured frames arrive as IncomingTrackImage messages
async for message in session.receive():
match message:
case IncomingTrackImage() as msg if msg.track_id == track_id:
data = msg.data
# process the image data
pass
asyncio.run(run())
```
### Disconnecting
After you're done using an agent, you can disconnect it from the room.
```ts
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const room = await fishjamClient.createRoom();
const { agent } = await fishjamClient.createAgent(room.id, {});
// ---cut---
agent.disconnect();
```
```python
async def run():
# the agent will disconnect once you exit the context
async with agent.connect() as session:
pass
asyncio.run(run())
```
:::danger[Remember to disconnect your agents!]
It's important to disconnect agents, because **every connected agent generates usage** just as a normal peer.
:::
## Pricing
Agents are billed as if they were normal peers.
For example, a room with 2 peers and 1 agent connected will be billed as if there were 3 peers connected to the room.
Exact pricing values can be found on our [pricing page](https://fishjam.io/#pricing).
## Using agents without our SDKs
If you are using Fishjam's REST API directly, then check out this [Agent Internals section](../explanation/agent-internals#step-1-creating-an-agent-in-fishjam).
## See also
Learn more about how agents work:
- [Agent Internals](../explanation/agent-internals)
- [Selective Subscriptions API](../how-to/backend/selective-subscriptions.mdx)
Writing a backend server with Fishjam:
- [Backend Quick Start](../tutorials/backend-quick-start)
- [How to Setup a Backend Server](../how-to/backend/server-setup)
- [Going to Production](../how-to/backend/production-deployment)
---
## Backend Quick Start
This tutorial will guide you through setting up a backend server that can create rooms and manage peers for your Fishjam application.
By the end, you'll have a working backend and understand how to integrate it with your client apps.
## Choose your language
Select your preferred backend language and all code examples will be shown for that language:
We'll use **Node.js with TypeScript** and the `@fishjam-cloud/js-server-sdk` package.
We'll use **Python** and the `fishjam-server-sdk` package.
## What you'll build
A simple backend server that can create rooms, add peers, and generate tokens for client apps.
## What you'll learn
- How to install and set up a Fishjam server SDK
- How to create and manage rooms
- How to create peers and generate tokens
## Prerequisites
- Node.js environment set up
- Access to [Fishjam Dashboard](https://fishjam.io/app) with your credentials
- Python environment set up
- Access to [Fishjam Dashboard](https://fishjam.io/app) with your credentials
## Step 1: Install the SDK
Install the JavaScript server SDK using your preferred package manager:
```bash
npm install @fishjam-cloud/js-server-sdk
```
```bash
yarn add @fishjam-cloud/js-server-sdk
```
```bash
pnpm add @fishjam-cloud/js-server-sdk
```
Install the Python server SDK using your preferred package manager:
```bash
pip install fishjam-server-sdk
```
```bash
poetry add fishjam-server-sdk
```
```bash
uv add fishjam-server-sdk
```
## Step 2: Get your credentials
1. Log in to [Fishjam Dashboard](https://fishjam.io/app)
2. Navigate to your app
3. Copy your **Fishjam ID** and **Management Token**
4. Store them as environment variables:
```bash
export FISHJAM_ID="your-fishjam-id"
export FISHJAM_MANAGEMENT_TOKEN="your-management-token"
```
```bash
export FISHJAM_ID="your-fishjam-id"
export FISHJAM_MANAGEMENT_TOKEN="your-management-token"
```
## Step 3: Set up the client
Create your Fishjam client:
```ts
process.env.FISHJAM_ID = "";
process.env.FISHJAM_MANAGEMENT_TOKEN = "";
// ---cut---
const fishjamId = process.env.FISHJAM_ID;
const managementToken = process.env.FISHJAM_MANAGEMENT_TOKEN;
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
```
```python
from fishjam import FishjamClient
fishjam_id = os.environ["FISHJAM_ID"]
management_token = os.environ["FISHJAM_MANAGEMENT_TOKEN"]
fishjam_client = FishjamClient(fishjam_id, management_token)
```
## Step 4: Create a room
Create your first room:
```ts
const fishjamId = "";
const managementToken = "";
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
// ---cut---
async function createRoom() {
const room = await fishjamClient.createRoom();
console.log('Room created:', room.id);
return room;
}
```
```python
def create_room():
room = fishjam_client.create_room()
print(f'Room created: {room.id}')
return room
```
## Step 5: Add a peer to the room
Create a peer and get a token for your client app:
```ts
const fishjamId = "";
const managementToken = "";
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
// ---cut---
async function addPeer(roomId: RoomId, peerName: string) {
const { peer, peerToken } = await fishjamClient.createPeer(roomId, {
metadata: { name: peerName },
});
console.log('Peer created:', peer.id);
console.log('Peer token:', peerToken);
return { peer, peerToken };
}
```
```python
from fishjam import PeerOptions
def add_peer(room_id: str, peer_name: str):
options = PeerOptions(metadata={"name": peer_name})
peer, peer_token = fishjam_client.create_peer(room_id, options=options)
print(f'Peer created: {peer.id}')
print(f'Peer token: {peer_token}')
return peer, peer_token
```
## Step 6: Create a simple API endpoint
Build a simple HTTP endpoint that your client apps can call:
```ts
process.env.FISHJAM_ID = "";
process.env.FISHJAM_MANAGEMENT_TOKEN = "";
// ---cut---
const app = express();
app.use(express.json());
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!
});
app.post('/join-room', async (req, res) => {
try {
const { roomName, peerName } = req.body;
// Create room
const room = await fishjamClient.createRoom();
// Add peer
const { peer, peerToken } = await fishjamClient.createPeer(room.id, {
metadata: { name: peerName },
});
res.json({
roomId: room.id,
peerToken,
});
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
```
Don't forget to install Express:
```bash
npm install express @types/express
```
```bash
yarn add express @types/express
```
```bash
pnpm add express @types/express
```
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fishjam import FishjamClient, PeerOptions
app = FastAPI()
fishjam_client = FishjamClient(
os.environ["FISHJAM_ID"],
os.environ["FISHJAM_MANAGEMENT_TOKEN"]
)
class JoinRoomRequest(BaseModel):
room_name: str
peer_name: str
@app.post("/join-room")
async def join_room(request: JoinRoomRequest):
try:
# Create room
room = fishjam_client.create_room()
# Add peer
options = PeerOptions(metadata={"name": request.peer_name})
peer, peer_token = fishjam_client.create_peer(room.id, options=options)
return {
"room_id": room.id,
"peer_token": peer_token,
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
```
Don't forget to install FastAPI:
```bash
pip install fastapi[standard]
```
```bash
poetry add fastapi[standard]
```
```bash
uv add fastapi[standard]
```
## Step 7: Run your server
Start your backend server:
```bash
# If using TypeScript directly
npx tsx server.ts
# Or compile and run
npx tsc server.ts && node server.js
```
```bash
fastapi run --port 3000
```
## Step 8: Test your backend
Test your endpoint:
```bash
curl -X POST http://localhost:3000/join-room \
-H "Content-Type: application/json" \
-d '{"roomName": "test-room", "peerName": "test-user"}'
```
```bash
curl -X POST http://localhost:3000/join-room \
-H "Content-Type: application/json" \
-d '{"room_name": "test-room", "peer_name": "test-user"}'
```
You should receive a response with:
- `roomId` / `room_id` - The ID of the created room
- `peerToken` / `peer_token` - Token for the client to join the room
## Complete example
Here's a complete working backend:
```ts
process.env.FISHJAM_ID = "";
process.env.FISHJAM_MANAGEMENT_TOKEN = "";
// ---cut---
const app = express();
app.use(express.json());
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!
});
app.post('/join-room', async (req, res) => {
try {
const { roomName, peerName } = req.body;
const room = await fishjamClient.createRoom();
const { peer, peerToken } = await fishjamClient.createPeer(room.id, {
metadata: { name: peerName },
});
res.json({
roomId: room.id,
peerToken,
});
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Fishjam backend running on port 3000');
});
```
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fishjam import FishjamClient, PeerOptions
app = FastAPI()
fishjam_client = FishjamClient(
os.environ["FISHJAM_ID"],
os.environ["FISHJAM_MANAGEMENT_TOKEN"]
)
class JoinRoomRequest(BaseModel):
room_name: str
peer_name: str
@app.post("/join-room")
async def join_room(request: JoinRoomRequest):
try:
room = fishjam_client.create_room()
options = PeerOptions(metadata={"name": request.peer_name})
peer, peer_token = fishjam_client.create_peer(room.id, options=options)
return {
"room_id": room.id,
"peer_token": peer_token
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
```
## Next steps
Now that you have a working backend, explore these guides:
- [How to set up a production deployment](../how-to/backend/production-deployment)
- [How to handle webhooks and events](../how-to/backend/server-setup#webhooks)
- [How to implement a FastAPI backend](../how-to/backend/fastapi-example)
- [How to implement a Fastify backend](../how-to/backend/fastify-example)
Or learn more about Fishjam concepts:
- [Understanding security and tokens](../explanation/security-tokens)
- [Rooms](../explanation/rooms)
---
## Add background blur to your camera Mobile
# Add background blur to your camera Mobile
:::note
This tutorial is exclusively for **Mobile** (React Native) applications.
:::
This tutorial continues from the [React Native Quick Start](./react-native-quick-start). You'll take the video call app you built there and add a button that blurs the background of your camera, for you and for everyone else in the room.
## What you'll build
The Quick Start video call app with a **Blur on / Blur off** button. When blur is on, other participants see you sharp in front of a blurred background.
## What you'll learn
- How to install and configure `@fishjam-cloud/video-effects`
- How to load the bundled segmentation model
- How to turn an effect into a camera middleware and switch it on and off with `useCamera`
## Prerequisites
- The finished app from the [React Native Quick Start](./react-native-quick-start), on Expo SDK 57 (React Native 0.86) with the New Architecture enabled
- `@fishjam-cloud/react-native-client` **0.30.2** or newer, `@fishjam-cloud/video-effects` **0.1.5** or newer and `react-native-webgpu` **0.10.1** or newer
- A physical device (iOS 16.4+ or Android 8.0+), or the iOS Simulator with a virtual camera from [SimCam](../how-to/client/ios-simulator-camera.mdx)
- A second device or simulator to join the room and see the result
## Step 1: Install and configure
### Install the packages
```bash npm2yarn
npm install @fishjam-cloud/video-effects @fishjam-cloud/react-native-worklets react-native-worklets react-native-webgpu expo-asset expo-file-system expo-build-properties
npm install --save-dev unplugin-typegpu @babel/plugin-transform-class-static-block
```
- `@fishjam-cloud/video-effects` contains the blur effect and the model that finds you in the picture.
- `@fishjam-cloud/react-native-worklets` and `react-native-worklets` run the effect on every camera frame, off the JS thread.
- `react-native-webgpu` gives the effect a GPU to draw with.
- `expo-asset` and `expo-file-system` load the model file that ships inside `@fishjam-cloud/video-effects`.
- `expo-build-properties` raises the Android minimum SDK version.
### Update the Babel config
The effect code needs the worklets Babel plugin, and TypeGPU (the GPU library it is written with) needs its own plugin, class static blocks and `import.meta`. Replace your `babel.config.js`, keeping `react-native-worklets/plugin` last:
```js title='babel.config.js'
module.exports = function (api) {
api.cache(true);
return {
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
plugins: [
"@babel/plugin-transform-class-static-block",
"unplugin-typegpu/babel",
"react-native-worklets/plugin",
],
};
};
```
### Let Metro bundle the model
The model ships as a `.ssgbin` file, which Metro doesn't bundle by default. Create `metro.config.js` in your project root:
```js title='metro.config.js'
const { getDefaultConfig } = require("expo/metro-config");
const config = getDefaultConfig(__dirname);
config.resolver.assetExts = [...config.resolver.assetExts, "ssgbin"];
module.exports = config;
```
### Raise the minimum OS versions
Expo SDK 57 needs iOS 16.4, and `react-native-webgpu` needs Android 8.0 (API 26), while Expo builds for API 24 by default. Set both in `app.json`: the iOS version in the Fishjam config plugin, the Android one with `expo-build-properties`:
```json title='app.json'
{
"expo": {
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"ios": {
"iphoneDeploymentTarget": "16.4"
}
}
],
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 26
}
}
]
]
}
}
```
If you already configure the Fishjam plugin, add `iphoneDeploymentTarget` to its existing `ios` options.
Without the Android setting, the Android build fails with `'AHardwareBuffer_allocate' is unavailable: introduced in Android 26`.
### Rebuild the app
The new packages contain native code, so a JS reload is not enough:
```bash
npx expo prebuild
npx expo run:ios # or run:android
```
```bash
cd ios && pod install
```
Start Metro with a cleared cache afterwards (`npx expo start --clear`), so the new Babel config is picked up.
## Step 2: Load the segmentation model
To blur the background, the effect first has to find you in every frame. A segmentation model does that on the GPU. Create `effects.ts` next to `App.tsx` and set up the model:
```ts title='effects.ts'
const segmentationModel = Asset.fromModule(
require("@fishjam-cloud/video-effects/assets/selfie_segmenter.ssgbin"),
);
// Android release builds can't fetch a bundled asset by URL, so read it from a local copy.
async function loadSegmentationModel(): Promise {
await segmentationModel.downloadAsync();
if (!segmentationModel.localUri) {
throw new Error("The segmentation model is not available.");
}
return new File(segmentationModel.localUri).arrayBuffer();
}
const segmentation = typeGpuPersonSegmentation({
loadModel: loadSegmentationModel,
});
```
Nothing is loaded yet: `typeGpuPersonSegmentation` only describes where the model comes from. The model is loaded the first time you switch blur on.
## Step 3: Create the blur middleware
Fishjam lets you put a [middleware](../how-to/client/camera-effects/stream-middleware.mdx) between your camera and the room: a function that receives the camera track and returns the track to publish instead. `createCameraEffectMiddleware` turns an effect into such a middleware.
Add the blur to the end of `effects.ts`:
```ts title='effects.ts'
declare const segmentation: PersonSegmentationProvider;
// ---cut---
export const backgroundBlur = createCameraEffectMiddleware(
createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })),
);
```
`radius` sets how strong the blur is, from `0` to `40`. The middleware is created once, at module scope, so it keeps the same identity for the whole app. You'll use that in the next step to tell whether blur is on.
## Step 4: Add a blur button
`useCamera` gives you two things for middleware: `setCameraTrackMiddleware` to set it, and `currentCameraMiddleware` to read what is set. Blur is on when the current middleware is `backgroundBlur`. Add a button component to `App.tsx`:
```tsx
declare const backgroundBlur: NonNullable;
// ---cut---
function BlurButton() {
const { currentCameraMiddleware, setCameraTrackMiddleware } = useCamera();
const isBlurOn = currentCameraMiddleware === backgroundBlur;
const toggleBlur = async () => {
try {
await setCameraTrackMiddleware(isBlurOn ? null : backgroundBlur);
} catch (error) {
console.warn("Background blur failed", error);
await setCameraTrackMiddleware(null); // go back to the plain camera
}
};
return (
);
}
```
Then render it in `VideoCall`, right above your own video:
```tsx
declare function BlurButton(): React.JSX.Element;
declare function VideoPlayer(props: { stream: MediaStream }): React.JSX.Element;
declare const cameraStream: MediaStream | null;
declare const styles: { section: object; sectionTitle: object };
const view = (
<>
// ---cut---
{cameraStream && (
Your Video
)}
// ---cut-after---
>
);
```
Rebuild, join the room and tap **Blur on**. The first time takes a moment, because the model is loaded and the GPU pipelines are built. Until blur is ready, your camera keeps being published as before, so the video never goes black.
Then join the same room from a second device. Its view of you shows the blurred background too: the blur is part of the camera track you publish, so the receiving side needs no changes.
A few things to notice:
- Blur stays on when the component that set it unmounts, because the middleware lives in Fishjam's camera state. Pass `null` to turn it off.
- Blur follows the camera. It is applied again when you switch between the front and back camera, or stop and restart the camera.
- If the device can't run the effect, `setCameraTrackMiddleware` rejects. The `catch` block then goes back to the plain camera, because at that point `currentCameraMiddleware` already points at the blur.
## Step 5: Report model loading problems
A failed model load doesn't reject `setCameraTrackMiddleware`: the middleware is still applied, but publishes the camera without blur. To find out about it, pass `onStatus` to the middleware. Update `backgroundBlur` in `effects.ts`:
```ts title='effects.ts'
declare const segmentation: PersonSegmentationProvider;
// ---cut---
export const backgroundBlur = createCameraEffectMiddleware(
createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })),
{
onStatus: (status, error) => {
if (status === "error") console.warn("Background blur failed", error);
},
},
);
```
`onStatus` is called with `"loading"` when the model starts loading, `"ready"` when blur is running, and `"error"` with the error if the model can't be loaded.
## Complete example
`effects.ts`:
```ts title='effects.ts'
const segmentationModel = Asset.fromModule(
require("@fishjam-cloud/video-effects/assets/selfie_segmenter.ssgbin"),
);
// Android release builds can't fetch a bundled asset by URL, so read it from a local copy.
async function loadSegmentationModel(): Promise {
await segmentationModel.downloadAsync();
if (!segmentationModel.localUri) {
throw new Error("The segmentation model is not available.");
}
return new File(segmentationModel.localUri).arrayBuffer();
}
const segmentation = typeGpuPersonSegmentation({
loadModel: loadSegmentationModel,
});
export const backgroundBlur = createCameraEffectMiddleware(
createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })),
{
onStatus: (status, error) => {
if (status === "error") console.warn("Background blur failed", error);
},
},
);
```
`App.tsx`, the Quick Start app with `BlurButton` added:
```tsx title='App.tsx'
// @filename: effects.ts
export declare const backgroundBlur: NonNullable;
// @filename: App.tsx
// ---cut---
FishjamProvider,
useConnection,
useCamera,
usePeers,
useInitializeDevices,
useSandbox,
RTCView,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
const FISHJAM_ID = "YOUR_FISHJAM_ID";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
if (!stream) {
return (
No video
);
}
return (
);
}
function BlurButton() {
const { currentCameraMiddleware, setCameraTrackMiddleware } = useCamera();
const isBlurOn = currentCameraMiddleware === backgroundBlur;
const toggleBlur = async () => {
try {
await setCameraTrackMiddleware(isBlurOn ? null : backgroundBlur);
} catch (error) {
console.warn("Background blur failed", error);
await setCameraTrackMiddleware(null); // go back to the plain camera
}
};
return (
);
}
function VideoCall() {
const { joinRoom, peerStatus } = useConnection();
const { cameraStream } = useCamera();
const { remotePeers } = usePeers();
const { initializeDevices } = useInitializeDevices();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const [isJoined, setIsJoined] = useState(false);
const handleJoin = async () => {
const roomName = "testRoom";
const peerName = `user_${Date.now()}`;
// Initialize devices first
await initializeDevices();
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken(roomName, peerName);
await joinRoom({ peerToken });
setIsJoined(true);
};
return (
Fishjam Video Call
Status: {peerStatus}
{!isJoined && }
{cameraStream && (
Your Video
)}
Other Participants
{remotePeers.length === 0 ? (
No other participants
) : (
remotePeers.map((peer) => (
{peer.cameraTrack?.stream && (
)}
))
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 10,
},
status: {
fontSize: 16,
marginBottom: 20,
},
section: {
marginTop: 20,
},
sectionTitle: {
fontSize: 18,
fontWeight: "600",
marginBottom: 10,
},
participant: {
marginBottom: 10,
},
video: {
height: 200,
width: "100%",
borderRadius: 8,
},
videoPlaceholder: {
height: 200,
width: "100%",
backgroundColor: "#000",
borderRadius: 8,
justifyContent: "center",
alignItems: "center",
},
});
export default function App() {
return (
);
}
```
## Next steps
- Replace the background with an image, change the blur strength, or scope the effect to one screen; see [Background effects](../how-to/client/camera-effects/background-effects.mdx)
- Draw your own shaders into the camera in the [WebGPU effects tutorial](./webgpu-effects)
- Learn [how camera effects work](../explanation/camera-effects.mdx) under the hood
- API reference: [Video Effects package](../api/video-effects/index.md)
---
## Compositions
This tutorial walks you through creating your first composition. You will overlay a small player camera on top of full-screen gameplay, publish the result to a livestream, and watch it in your browser.
Both sources are sample MP4 files, so you need no camera, no encoder, and no publishing tool to get a picture. Nothing else in the tutorial depends on that, so you can swap either one for a live camera afterwards.
## What you'll build
```text
[race.mp4] ──┐
├─▶ composition ──WHIP──▶ livestream ──WHEP──▶ [your browser]
[player.mp4] ──┘
```
The composed frame puts the race full-screen with the player in a small overlay in the top-left corner, standard gaming stream layout:
## What you'll learn
- How to create a composition and feed it media.
- How to describe a layout as a scene.
- How to publish the composed result and watch it.
- How to change the layout while the composition is running.
## Prerequisites
- A Fishjam account. Open the [**Fishjam developer panel**](https://fishjam.io/app) and copy your **Fishjam ID** and **Management Token** from the Dashboard tab, and your **Sandbox API URL** from the [Sandbox tab](https://fishjam.io/app/sandbox).
- A browser, to watch the result.
The [Composition API](../api/reference#compositions) lives on `https://rtc.fishjam.io` and takes your Management Token. The livestream you will publish to comes from the [Sandbox API](../explanation/sandbox-api-concept), which has its own URL and needs no token at all:
```bash
export FISHJAM_URL="https://fishjam.io/api/v1/connect/"
export SANDBOX_URL=""
export TOKEN=""
```
## Step 1: Create a composition
By default a composition auto-starts, and cleans itself up after five minutes in which none of its inputs carry any media.
```ts
const managementToken = "";
// ---cut---
const compositionClient = new CompositionClient({ managementToken });
const { compositionId } = await compositionClient.createComposition();
```
```python
from fishjam import CompositionClient
composition_client = CompositionClient(management_token=management_token)
composition = composition_client.create_composition()
composition_id = composition.composition_id
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{}'
```
The response contains the `composition_id` you will use for every subsequent call:
```json
{ "composition_id": "abc123", "api_url": "https://rtc.fishjam.io" }
```
Save the id:
```bash
export COMPOSITION="abc123"
```
## Step 2: Register two inputs
Register two `mp4` inputs, looping so they never run dry. The composition downloads them itself, so there is nothing to publish:
```ts
CompositionClient,
CompositionId,
InputId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
// ---cut---
await compositionClient.registerMp4Input(compositionId, "race" as InputId, {
url: "https://smelter.dev/videos/template-scene-race.mp4",
loop: true,
});
await compositionClient.registerMp4Input(compositionId, "player" as InputId, {
url: "https://smelter.dev/videos/template-scene-streamer.mp4",
loop: true,
});
```
```python
composition_client.register_mp4_input(
composition_id,
"race",
url="https://smelter.dev/videos/template-scene-race.mp4",
loop=True,
)
composition_client.register_mp4_input(
composition_id,
"player",
url="https://smelter.dev/videos/template-scene-streamer.mp4",
loop=True,
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/input/race/register" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"type": "mp4",
"url": "https://smelter.dev/videos/template-scene-race.mp4",
"loop": true
}'
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/input/player/register" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"type": "mp4",
"url": "https://smelter.dev/videos/template-scene-streamer.mp4",
"loop": true
}'
```
The names `race` and `player` are the `input_id`s you will refer to from the layout in Step 4. The scene only ever refers to inputs by id, so what sits behind an id is interchangeable: register `whip_server` instead of `mp4` to take a live camera, phone, or OBS feed here, or forward a whole [Fishjam room](../how-to/compositions/compose-a-fishjam-room) in. See [Choose inputs and outputs](../how-to/compositions/inputs-and-outputs) for every input type.
:::note
The file is fetched while the input is being registered, so an unreachable URL fails right here rather than later.
:::
## Step 3: Create a livestream to publish to
The composition needs somewhere to send the composed stream. The [Sandbox API](../explanation/sandbox-api-concept) creates a [livestream](./../explanation/livestreams) and hands back a **streamer token**:
```bash
curl "$SANDBOX_URL/livestream?roomName=composition-tutorial&public=false"
```
The response carries both things the next steps need, the token the composition publishes with and the livestream's id:
```json
{
"streamerToken": "",
"room": { "id": "", "name": "composition-tutorial" }
}
```
```bash
export STREAM=""
export STREAMER_TOKEN=""
```
:::note
The Sandbox API is for prototyping: it holds your Management Token server-side so a client can get a scoped token without a backend. In production you create livestreams yourself through the [Fishjam Server API](../api/reference#server), with your Management Token.
:::
## Step 4: Register an output with a layout
Register a `whip_client` output that publishes to the livestream's WHIP endpoint using the streamer token from Step 3. Its scene stacks two components: the race filling the frame, and the player rescaled into a rounded box in the top-left corner.
:::note
The output connects to `endpoint_url` while it is being registered, so the endpoint has to be reachable already. That is why the livestream comes first. Registering against a URL that does not accept the connection fails.
:::
```ts
CompositionClient,
CompositionId,
InputId,
OutputId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
const streamerToken = "";
const race = "race" as InputId;
const player = "player" as InputId;
// ---cut---
await compositionClient.registerWhipOutput(compositionId, "main" as OutputId, {
endpointUrl: "https://fishjam.io/api/v1/live/api/whip",
bearerToken: streamerToken,
video: {
resolution: { width: 1280, height: 720 },
initial: {
root: {
type: "view",
children: [
{ type: "rescaler", child: { type: "input_stream", inputId: race } },
{
type: "rescaler",
top: 20,
left: 20,
width: 355,
height: 200,
borderRadius: 44,
mode: "fill",
child: { type: "input_stream", inputId: player },
},
],
},
},
},
audio: { initial: { inputs: [{ inputId: player }] } },
});
```
```python
from fishjam.composition import (
AudioScene,
AudioSceneInput,
InputStream,
InputStreamType,
OutputWhipAudioOptions,
OutputWhipVideoOptions,
RescaleMode,
Rescaler,
RescalerType,
Resolution,
VideoScene,
View,
ViewType,
)
composition_client.register_whip_output(
composition_id,
"main",
endpoint_url="https://fishjam.io/api/v1/live/api/whip",
bearer_token=streamer_token,
video=OutputWhipVideoOptions(
resolution=Resolution(width=1280, height=720),
initial=VideoScene(
root=View(
type_=ViewType.VIEW,
children=[
Rescaler(
type_=RescalerType.RESCALER,
child=InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="race"
),
),
Rescaler(
type_=RescalerType.RESCALER,
top=20,
left=20,
width=355,
height=200,
border_radius=44,
mode=RescaleMode.FILL,
child=InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="player"
),
),
],
)
),
),
audio=OutputWhipAudioOptions(
initial=AudioScene(inputs=[AudioSceneInput(input_id="player")])
),
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/output/main/register" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d @- <
The scene is a tree of components. A `view` stacks its children in order, so the second `rescaler` draws on top of the first. Giving that second one `top` and `left` positions it in the corner instead of filling the frame, and `mode: "fill"` makes the video cover its box rather than letter-boxing inside it. See [Scenes](../explanation/compositions#scenes) for how scenes work and what each component does.
## Step 5: Watch it
That is the whole pipeline. The composition is already pulling both files, drawing the frame, and publishing it into your livestream.
Open the [livestreaming demo](https://livestreaming.fishjam.io) and give it your **Fishjam ID** and the same **Sandbox API URL** you used in Step 3. In the **Livestream Viewer** window, enter the room name you used in Step 3, `composition-tutorial`, and click **Connect to stream**.
You should see the race running.
## Step 6: Change the layout while it runs
A scene is not fixed once the output is registered. Leave the player watching and swap the corner overlay for a side-by-side grid:
```ts
CompositionClient,
CompositionId,
InputId,
OutputId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
const race = "race" as InputId;
const player = "player" as InputId;
// ---cut---
await compositionClient.updateOutput(compositionId, "main" as OutputId, {
video: {
root: {
type: "tiles",
children: [
{ type: "input_stream", inputId: race },
{ type: "input_stream", inputId: player },
],
},
},
audio: { inputs: [{ inputId: player }] },
});
```
```python
from fishjam.composition import Tiles, TilesType, UpdateOutputRequest
composition_client.update_output(
composition_id,
"main",
UpdateOutputRequest(
video=VideoScene(
root=Tiles(
type_=TilesType.TILES,
children=[
InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="race"
),
InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="player"
),
],
)
),
audio=AudioScene(inputs=[AudioSceneInput(input_id="player")]),
),
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/output/main/update" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"video": {
"root": {
"type": "tiles",
"children": [
{ "type": "input_stream", "input_id": "race" },
{ "type": "input_stream", "input_id": "player" }
]
}
},
"audio": { "inputs": [{ "input_id": "player" }] }
}'
```
The layout changes on the fly, with no interruption to the stream. Send the Step 4 scene again to go back to the corner overlay.
:::warning
An update has to carry the same sides the output was registered with. This output has both `video` and `audio`, so every update needs both, even when only the layout changed. Sending only one of them fails. See [Update a scene](../how-to/compositions/inputs-and-outputs#update-a-scene) for the full rule.
:::
## Step 7: Clean up
Delete the composition and the livestream when you are done. The Sandbox API only creates, so removing the livestream goes through the Server API with your Management Token:
```ts
CompositionClient,
CompositionId,
FishjamClient,
RoomId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const compositionId = "" as CompositionId;
const streamId = "" as RoomId;
// ---cut---
await compositionClient.deleteComposition(compositionId);
await fishjamClient.deleteRoom(streamId);
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
composition_client.delete_composition(composition_id)
fishjam_client.delete_room(stream_id)
```
```bash
curl -X DELETE "https://rtc.fishjam.io/api/composition/$COMPOSITION" \
-H "Authorization: Bearer $TOKEN"
curl -X DELETE "$FISHJAM_URL/livestream/$STREAM" \
-H "Authorization: Bearer $TOKEN"
```
## Next steps
Updating the scene by hand gets tedious once people are joining, leaving, muting, and unmuting, since each of those needs its own call. A **template** is a React component that receives the live room state and re-renders itself as the room changes, so you send no scene updates at all.
- [Write and deploy a template](../how-to/compositions/write-and-deploy-a-template) to replace the static scene with a live React layout.
- [Compose a Fishjam room](../how-to/compositions/compose-a-fishjam-room) to feed a whole room's peers in automatically.
- [Choose inputs and outputs](../how-to/compositions/inputs-and-outputs) for other protocols like RTMP and WHEP.
- [Record with a template](../how-to/recordings/record-with-a-template) to render your inputs straight into an MP4.
---
## Livestreaming
# Livestreaming with Fishjam
This section explains how to set up livestreaming using Fishjam.
We show how to quickly prototype a livestreaming scenario in [Quickstart with Sandbox API](#quickstart-with-sandbox-api)
and how to get ready for production in [Production Livestreaming with Server SDKs](#production-livestreaming-with-server-sdks).
:::tip
Fishjam implements two real-time streaming standards: WHIP (for publishing) and WHEP (for receiving).
In this tutorial we explain how to publish and view streams with the client SDKs, which wrap these standards.
If you prefer to use WHIP or WHEP directly, then you should read [WHIP/WHEP with Fishjam](../how-to/backend/whip-whep).
:::
:::info[Cost-effective audio livestreams]
Fishjam supports audio-only livestreams at a reduced cost of $0.20 per 1000 minutes of the streamer and each listener (compared to $0.80 for video livestreams).
This is ideal for podcasts, radio-style broadcasts, or any scenario where video isn't necessary.
See [Audio-only calls](../how-to/backend/audio-only-calls) for more information.
:::
## Quickstart with Sandbox API
If you don't have a backend server setup, you can still prototype a livestreaming use-case with the Sandbox API.
If you want to start by setting up your backend, then you can start by reading [Production Livestreaming with Server SDKs](#production-livestreaming-with-server-sdks).
For React/React Native apps, copy both the Fishjam ID from the [Dashboard tab](https://fishjam.io/app) and the Sandbox API URL from the [Sandbox tab](https://fishjam.io/app/sandbox): the Sandbox API URL allows to generate test peer tokens, while the Fishjam ID is passed to `FishjamProvider` for media server access.
### Streamer setup
To start streaming with Fishjam, we need two things: a _streamer token_ and video/audio sources.
#### Obtaining a token
The easiest way to obtain a sandbox streamer token is by using the Sandbox API in the client SDKs:
```tsx
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
const { getSandboxLivestream } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const {
streamerToken,
room: { id: roomId },
} = await getSandboxLivestream('example-room');
```
```tsx
const FISHJAM_ID = '';
// ---cut---
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
const { getSandboxLivestream } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const { streamerToken } = await getSandboxLivestream('example-room');
```
#### Starting the stream
We can now start sending media, which we can obtain from the user's camera, screen share or microphone:
```tsx
const streamerToken = '';
const roomId = '';
// ---cut---
useCamera,
useLivestreamStreamer,
useMicrophone,
} from '@fishjam-cloud/react-client';
const { cameraStream, toggleCamera } = useCamera();
const { microphoneStream, toggleMicrophone } = useMicrophone();
const { connect } = useLivestreamStreamer();
// ...
toggleCamera();
toggleMicrophone();
// ...
if (cameraStream && microphoneStream) {
await connect({
token: streamerToken,
inputs: { video: cameraStream, audio: microphoneStream }
});
}
```
```tsx
const streamerToken = '';
const roomId = '';
// ---cut---
useLivestreamStreamer,
useScreenShare,
} from '@fishjam-cloud/react-client';
const { stream: screenShareStream, startStreaming } = useScreenShare();
const { connect } = useLivestreamStreamer();
// ...
startStreaming();
// ...
if (screenShareStream) {
await connect({
token: streamerToken,
inputs: { video: screenShareStream, audio: screenShareStream }
});
}
```
```tsx
useInitializeDevices,
useSandbox,
useLivestreamStreamer,
useCamera,
useMicrophone,
RTCView,
} from '@fishjam-cloud/react-native-client';
const roomName = 'my-room';
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
// Inside your component:
const { getSandboxLivestream } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const { connect } = useLivestreamStreamer();
const { cameraStream } = useCamera();
const { microphoneStream } = useMicrophone();
const { initializeDevices } = useInitializeDevices();
// ...
await initializeDevices({ enableVideo: true, enableAudio: true });
const { streamerToken } = await getSandboxLivestream(roomName);
await connect({
inputs: {
video: cameraStream!,
audio: microphoneStream!,
},
token: streamerToken,
});
// Render the livestream
{cameraStream ? (
) : (
No video
)}
```
:::tip[Background streaming during screen sharing on iOS]
If you want to continue screen sharing when the app goes to the background, you need to:
1. Enable VoIP background mode by setting `enableVoIPBackgroundMode: true` in the plugin configuration or adding the VoIP background mode to your `Info.plist`
2. Use the [`useCallKitService`](../api/mobile/functions/useCallKitService) hook in your component to manage the CallKit session
See the [background calls documentation](../how-to/client/background-streaming) for detailed instructions and code examples.
:::
```tsx
useSandbox,
useLivestreamStreamer,
useScreenShare,
useInitializeDevices,
RTCView,
} from '@fishjam-cloud/react-native-client';
const roomName = 'my-room';
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
// Inside your component:
const { initializeDevices } = useInitializeDevices();
const { getSandboxLivestream } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const { connect } = useLivestreamStreamer();
const {
startStreaming: startScreenCapture,
stream: screenStream,
} = useScreenShare();
// ...
await initializeDevices({ enableVideo: true, enableAudio: true });
await startScreenCapture();
const { streamerToken } = await getSandboxLivestream(roomName);
await connect({
inputs: {
video: screenStream!,
},
token: streamerToken,
});
// Render the livestream
{screenStream ? (
) : (
No video
)}
```
Et voilà, we've published a livestream!
### Viewer setup
To receive the published livestream, we need one thing: a _viewer token_.
:::info
In this guide, we've created a _private_ livestream, where viewers need a token to join.
A livestream may also be _public_, where anyone can join if they know the livestream's room id.
You can learn more about public livestreams in [Livestreams](../explanation/livestreams).
:::
#### Obtaining a token
We obtain a sandbox viewer token using the Sandbox API in the client SDKs:
```tsx
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
const { getSandboxViewerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const viewerToken = await getSandboxViewerToken('example-room');
```
```tsx
const FISHJAM_ID = '';
// ---cut---
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
const { getSandboxViewerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const viewerToken = await getSandboxViewerToken('example-room');
```
#### Receiving the stream
We can now begin receiving the stream
```tsx
const viewerToken = '';
// ---cut---
const { connect, stream } = useLivestreamViewer();
await connect({ token: viewerToken });
// You can now use `stream` with a element or your player of choice
```
```tsx
useLivestreamViewer,
useSandbox,
RTCView,
} from '@fishjam-cloud/react-native-client';
const roomName = 'my-room';
const SANDBOX_API_URL = 'your-sandbox-api-url-here';
// Inside your component:
const { getSandboxViewerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const { connect, stream } = useLivestreamViewer();
const token = await getSandboxViewerToken(roomName);
await connect({ token });
// Render the livestream
{stream ? (
) : (
No video
)}
```
:::tip[Picture in Picture on React Native]
You can use `RTCPIPView` to enable Picture in Picture, allowing viewers to watch the livestream in a floating window while using other apps. See the [Picture in Picture guide](../how-to/client/picture-in-picture) to learn how to enable and configure this feature.
:::
That's it!
Now you can focus on your business logic and replace the Sandbox API usage in the future,
when your backend is ready, or continue on to see how to set up your backend for livestreaming.
## Production Livestreaming with Server SDKs
The [Quickstart with Sandbox API](#quickstart-with-sandbox-api) shows how to get livestreaming up and running quickly.
However, in a production scenario, we need a backend application with proper authentication and authorization.
In this section, we explain what such a backend application should do.
Our backend needs to do three things to be ready for streaming:
1. It needs to create a room of `livestream` type.
2. It needs to create a streamer token for that room.
3. It needs to create a viewer token for that room.
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
// 1.
const room = await fishjamClient.createRoom({ roomType: 'livestream' });
// 2.
const { token: streamerToken } = await fishjamClient.createLivestreamStreamerToken(room.id);
// 3.
const { token: viewerToken } = await fishjamClient.createLivestreamViewerToken(room.id);
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
# 1.
room = fishjam_client.create_room(RoomOptions(room_type="livestream"))
# 2.
streamer_token = fishjam_client.create_livestream_streamer_token(room.id)
# 3.
viewer_token = fishjam_client.create_livestream_viewer_token(room.id)
```
Now, you need to supply these generated tokens to your frontend applications (e.g. by exposing a REST endpoint).
You most likely will want to only supply these tokens to properly authenticate and authorize streamers and viewers before giving them tokens.
Then, you can start streaming as described in [Starting the stream](#starting-the-stream) and start receiving as describe in [Receiving the stream](#receiving-the-stream).
## See also
Learn how to use WHIP/WHEP with Fishjam:
- [WHIP/WHEP with Fishjam](../how-to/backend/whip-whep)
If you want to get a better understanding of livestreaming with Fishjam, make sure to check out:
- [Rooms](../explanation/rooms)
- [Livestreams](../explanation/livestreams)
If you have a different use case, then you should see
- [React Quickstart](../tutorials/react-quick-start)
- [React Native Quickstart](../tutorials/react-native-quick-start)
- [Audio-only Calls](../how-to/backend/audio-only-calls)
---
## Media over QUIC (MoQ)
Step-by-step guides for publishing and subscribing to live broadcasts over [Media over QUIC (MoQ)](https://datatracker.ietf.org/wg/moq/about/) with Fishjam. For the big-picture overview of how MoQ fits into Fishjam, see [Media over QUIC in Fishjam](../../explanation/moq-with-fishjam.mdx).
:::warning[MoQ is a standalone feature]
MoQ runs as a **separate delivery path** in Fishjam — it handles publishing and subscribing to a live broadcast over the MoQ relay, and the rest of Fishjam's feature set does not apply to a MoQ stream. In particular, a MoQ broadcast is not part of a WebRTC [room](../../explanation/rooms.mdx), so you cannot use features like [Agents](../agents.mdx), [data channels](../../explanation/data-channels.mdx), and others that are part of the Fishjam WebRTC ecosystem.
:::
---
## React Native Publishing
This tutorial explains how to **publish** a live stream from a **React Native mobile app** using [Media over QUIC (MoQ)](https://datatracker.ietf.org/wg/moq/about/) with Fishjam. To watch a stream instead, see [React Native Subscribing](./react-native-subscribing).
It uses [`react-native-moq`](https://github.com/software-mansion-labs/react-native-moq) — React Native bindings for MoQKit, with a small, reactive hooks-based API. For the web equivalent, see [Web Publishing](./web-publishing).
:::info
If you're new to MoQ, then we recommend getting familiar with the [MoQ with Fishjam](../../explanation/moq-with-fishjam) explanation.
:::
## Requirements
`react-native-moq` targets the React Native **New Architecture** (Fabric / TurboModules):
- iOS 16+
- Android API 30+
## Installation
```bash npm2yarn
npm install react-native-moq
```
Then install the iOS pods:
```sh
cd ios && pod install
```
Publishing captures the camera and microphone, so the host app is responsible for runtime permissions: request `CAMERA` / `RECORD_AUDIO` on Android, and add `NSCameraUsageDescription` / `NSMicrophoneUsageDescription` to `Info.plist` on iOS. The library does not request these for you.
:::tip
MoQ is a protocol with a well-defined negotiation, so a publisher and a subscriber don't need to use the same client library. A React Native app published with `react-native-moq` can be watched in the browser with [`@moq/watch`](./web-subscribing#connecting-and-subscribing), and vice versa.
:::
## Quickstart with the Sandbox API
If you don't have a backend server set up, you can prototype publishing using the [Sandbox API](../../explanation/sandbox-api-concept).
### Obtaining a publisher connection URL
For more on what the Sandbox API is and its limitations, see [What is the Sandbox API?](../../explanation/sandbox-api-concept).
:::info
To obtain a MoQ connection URL you'll need your Sandbox API URL. If you don't have it already, see [Sandbox API URL](../../explanation/sandbox-api-concept#sandbox-api-url-and-fishjam-id).
:::
The `useSandbox` hook from `@fishjam-cloud/react-native-client` wraps the Sandbox API request for you:
```tsx
// @noErrors
const PUBLISHER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// Inside a React component:
const { getSandboxMoqPublisherAccess } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
// Request a publisher connection URL scoped to the publisher path
const { connection_url: publishUrl } = await getSandboxMoqPublisherAccess(PUBLISHER_PATH);
```
If you don't want to pull in the whole client library just for the `useSandbox` hook, you can call the Sandbox API directly with `fetch`:
```ts
// @noErrors
const PUBLISHER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
const response = await fetch(
`${SANDBOX_API_URL}/moq/${PUBLISHER_PATH}/publisher`,
);
const { connection_url: publishUrl } = await response.json();
```
### Connecting and publishing
`react-native-moq` is hooks-based. You open a session against the relay, capture the camera and microphone, and hand them to a publisher.
Open the session with the publisher connection URL, capture the camera and microphone, and publish the tracks:
```tsx
// @noErrors
PublisherView,
useCamera,
useMicrophone,
usePublisher,
useSession,
} from "react-native-moq";
const PUBLISHER_PATH = "stream-alice";
const publishUrl = ""; // from the step above
function PublishScreen() {
// Open the MoQ session against the Fishjam relay using the publisher connection URL
const session = useSession(publishUrl, (s) => s.connect());
const camera = useCamera({ position: "front" });
const microphone = useMicrophone();
const publisher = usePublisher(session);
// Request camera + mic permissions on Android (iOS handles it automatically when Info.plist is configured)
useEffect(() => {
if (Platform.OS === "android") {
PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.CAMERA,
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
]);
}
}, []);
const isPublishing = publisher.state === "publishing";
return (
<>
{
if (isPublishing) publisher.stop();
else
publisher.publish({
path: PUBLISHER_PATH,
tracks: [camera, microphone],
});
}}
/>
>
);
}
```
Once `publisher.state === "publishing"`, the stream is live on the MoQ relay! Viewers can start watching by following [React Native Subscribing](./react-native-subscribing).
:::info
**Why a separate `useSession` and `publish()`?** \
The session owns the connection to the relay; the publisher reuses it. Because publishing rides on top of an open session, the same connection can subscribe and publish at once — pair `usePublisher(session)` with `useBroadcasts(session, prefix)` to do both.
:::
## Production with Server SDKs
The [Quickstart](#quickstart-with-the-sandbox-api) gets you publishing quickly. In production, your backend generates tokens with proper authorization, so you control who can publish.
A **publisher connection URL** grants write access to a specific path. Generate one on your backend and deliver it to the broadcasting client:
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const streamPath = 'stream-alice';
// Generate a connection URL that allows publishing to 'stream-alice'
const { connection_url: publishUrl } = await fishjamClient.createMoqAccess({
publishPath: streamPath,
});
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
stream_path = 'stream-alice'
# Generate a connection URL that allows publishing to 'stream-alice'
publish_url = fishjam_client.create_moq_access(publish_path=stream_path).connection_url
```
Deliver this connection URL to the mobile client, then use it to connect as described in [Connecting and publishing](#connecting-and-publishing).
## See also
- [React Native Subscribing](./react-native-subscribing) — watch a MoQ stream on mobile
- [Web Publishing](./web-publishing) — publish from the browser instead
- [MoQ with Fishjam](../../explanation/moq-with-fishjam) — how MoQ works in Fishjam
- [Livestreaming](../../tutorials/livestreaming) — the WebRTC (WHIP/WHEP) approach
---
## React Native Subscribing
This tutorial explains how to **subscribe** to a live stream and render it in a **React Native mobile app** using [Media over QUIC (MoQ)](https://datatracker.ietf.org/wg/moq/about/) with Fishjam. To broadcast a stream instead, see [React Native Publishing](./react-native-publishing).
It uses [`react-native-moq`](https://github.com/software-mansion-labs/react-native-moq) — React Native bindings for MoQKit, with a small, reactive hooks-based API. For the web equivalent, see [Web Subscribing](./web-subscribing).
:::info
If you're new to MoQ, then we recommend getting familiar with the [MoQ with Fishjam](../../explanation/moq-with-fishjam) explanation.
:::
## Requirements
`react-native-moq` targets the React Native **New Architecture** (Fabric / TurboModules):
- iOS 16+
- Android API 30+
## Installation
```bash npm2yarn
npm install react-native-moq
```
Then install the iOS pods:
```sh
cd ios && pod install
```
:::tip
The ready-made player chrome — `` with fullscreen controls, a volume slider, and matching context hooks — lives in a separate package so apps that build their own UI don't pay for it:
```bash npm2yarn
npm install react-native-moq-ui @react-native-vector-icons/material-icons
```
This tutorial uses the bare `` from the core package, but `` is a drop-in replacement if you want controls out of the box.
:::
## Quickstart with the Sandbox API
If you don't have a backend server set up, you can prototype subscribing using the [Sandbox API](../../explanation/sandbox-api-concept).
:::tip
MoQ is a protocol with a well-defined negotiation, so a publisher and a subscriber don't need to use the same client library. A stream published from the browser with [`@moq/publish`](./web-publishing) can be watched with `react-native-moq`, and vice versa.
:::
### Obtaining a subscriber connection URL
For more on what the Sandbox API is and its limitations, see [What is the Sandbox API?](../../explanation/sandbox-api-concept).
:::info
To obtain a MoQ connection URL you'll need your Sandbox API URL. If you don't have it already, see [Sandbox API URL](../../explanation/sandbox-api-concept#sandbox-api-url-and-fishjam-id).
:::
The `useSandbox` hook from `@fishjam-cloud/react-native-client` wraps the Sandbox API request for you:
```tsx
// @noErrors
const SUBSCRIBER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// Inside a React component:
const { getSandboxMoqSubscriberAccess } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
// Request a subscriber connection URL scoped to the subscriber path
const { connection_url: subscribeUrl } = await getSandboxMoqSubscriberAccess(SUBSCRIBER_PATH);
```
If you don't want to pull in the whole client library just for the `useSandbox` hook, you can call the Sandbox API directly with `fetch`:
```ts
// @noErrors
const SUBSCRIBER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
const response = await fetch(
`${SANDBOX_API_URL}/moq/${SUBSCRIBER_PATH}/subscriber`,
);
const { connection_url: subscribeUrl } = await response.json();
```
### Connecting and subscribing
Open a session, discover the broadcast under its path with `useBroadcasts`, and render it with ``. `useVideoPlayer` turns a discovered broadcast into a reactive player; the decoding and rendering pipeline is handled natively — no canvas, no manual WebCodecs setup:
```tsx
// @noErrors
VideoView,
useBroadcasts,
useSession,
useVideoPlayer,
} from "react-native-moq";
const SUBSCRIBER_PATH = "stream-alice";
const subscribeUrl = ""; // from the step above
function WatchScreen() {
// Connect to the Fishjam MoQ relay on mount using the subscriber connection URL
const session = useSession(subscribeUrl, (s) => s.connect());
// Discover broadcasts under the subscriber path
const broadcasts = useBroadcasts(session, SUBSCRIBER_PATH);
return (
<>
{broadcasts.map((broadcast) => (
))}
>
);
}
function BroadcastPlayer({ broadcast }: { broadcast: BroadcastInfo }) {
// Create a reactive player and start playback
const player = useVideoPlayer(broadcast, (p) => p.play());
return (
<>
>
);
}
```
That's it! The stream appears in the `` once the publisher starts broadcasting, and `useBroadcasts` re-populates automatically on reconnect.
:::info
**No canvas needed.** \
Unlike the web, where `Watch.MultiBackend` decodes frames through WebCodecs and paints them onto a ``, the React Native player decodes and renders natively. You just hand the `player` to a `` and size it like any other view.
:::
For audio-only streaming, use [`useAudioPlayer(broadcast)`](https://github.com/software-mansion-labs/react-native-moq/blob/main/docs/API.md#useaudioplayerbroadcast-setup) instead of `useVideoPlayer` — the video track is never subscribed, so no video bandwidth is consumed.
### Using the `` component
If you don't need fine-grained control over the rendering surface, the `react-native-moq-ui` package ships a ready-to-use `` that wraps `` with platform-styled play/pause, a volume slider, and a fullscreen modal — the React Native counterpart of the web `` element.
```tsx
// @noErrors
function BroadcastPlayer({ broadcast }: { broadcast: BroadcastInfo }) {
const player = useVideoPlayer(broadcast, (p) => p.play());
return (
);
}
```
It exposes imperative `enterFullscreen()` / `exitFullscreen()` methods on its ref, and the chrome is fully customizable. See [Default UI components](https://github.com/software-mansion-labs/react-native-moq/blob/main/docs/API.md#default-ui-components-react-native-moq-ui) in the API reference.
## Production with Server SDKs
The [Quickstart](#quickstart-with-the-sandbox-api) gets you watching quickly. In production, your backend generates tokens with proper authorization, so you control who can subscribe.
A **subscriber connection URL** grants read access to a specific path. Generate one on your backend and deliver it to the viewing client:
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const streamPath = 'stream-alice';
// Generate a connection URL that allows subscribing to 'stream-alice'
const { connection_url: subscribeUrl } = await fishjamClient.createMoqAccess({
subscribePath: streamPath,
});
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
stream_path = 'stream-alice'
# Generate a connection URL that allows subscribing to 'stream-alice'
subscribe_url = fishjam_client.create_moq_access(subscribe_path=stream_path).connection_url
```
Deliver this connection URL to the mobile client, then use it to connect as described in [Connecting and subscribing](#connecting-and-subscribing).
### Subscribe to a namespace
When multiple publishers join a room, you won't know their exact paths in advance.
Instead of consuming a single path, you can **discover** all broadcasts published under a namespace prefix and subscribe to each one as they appear.
To do this, generate a subscriber connection URL scoped to the room namespace instead of a single stream path.
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const roomName = 'my-room';
const { connection_url: alicePublisherUrl } = await fishjamClient.createMoqAccess({
publishPath: roomName + "/alice",
});
const { connection_url: bobPublisherUrl } = await fishjamClient.createMoqAccess({
publishPath: roomName + "/bob",
});
const { connection_url: namespaceUrl } = await fishjamClient.createMoqAccess({
subscribePath: roomName,
});
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
room_name = 'my-room'
alice_publisher_url = fishjam_client.create_moq_access(
publish_path=room_name + "/alice",
).connection_url
bob_publisher_url = fishjam_client.create_moq_access(
publish_path=room_name + "/bob",
).connection_url
namespace_url = fishjam_client.create_moq_access(subscribe_path=room_name).connection_url
```
On the client, pass the namespace connection URL to `useSession`, then call `useBroadcasts(session, roomName)` with the room prefix. It returns a reactive `BroadcastInfo[]` that re-renders every time a publisher joins or leaves — no manual diffing of an announce set. Map over it to mount a player per broadcast:
```tsx
// @noErrors
VideoView,
useBroadcasts,
useSession,
useVideoPlayer,
} from "react-native-moq";
const ROOM_NAME = "my-room";
const namespaceUrl = "";
function RoomGrid() {
const session = useSession(namespaceUrl, (s) => s.connect());
// Every broadcast published under the 'my-room' prefix, kept live
const broadcasts = useBroadcasts(session, ROOM_NAME);
return (
<>
{broadcasts.map((broadcast) => (
))}
>
);
}
function Tile({ broadcast }: { broadcast: BroadcastInfo }) {
const player = useVideoPlayer(broadcast, (p) => p.play());
return (
);
}
```
Because `useBroadcasts` starts the native subscription on mount and tears it down on unmount, players appear and disappear in lockstep with the publishers in the room — React's reconciliation handles mounting and unmounting tiles for you.
## See also
- [React Native Publishing](./react-native-publishing) — broadcast a MoQ stream from mobile
- [Web Subscribing](./web-subscribing) — subscribe from the browser instead
- [MoQ with Fishjam](../../explanation/moq-with-fishjam) — how MoQ works in Fishjam
- [Livestreaming](../../tutorials/livestreaming) — the WebRTC (WHIP/WHEP) approach
---
## Web Publishing
This tutorial explains how to **publish** a live stream from the browser using [Media over QUIC (MoQ)](https://datatracker.ietf.org/wg/moq/about/) with Fishjam. To watch a stream instead, see [Web Subscribing](./web-subscribing).
:::info
If you're new to MoQ, then we recommend getting familiar with the [MoQ with Fishjam](../../explanation/moq-with-fishjam) explanation.
:::
To start publishing a MoQ stream, you need a _publisher connection URL_ — the relay URL with a publisher token embedded as a `?jwt=` query parameter. We show how to quickly prototype with the [Sandbox API](#quickstart-with-the-sandbox-api) and how to get ready for [production](#production-with-server-sdks).
:::tip
MoQ is a protocol with a well-defined negotiation, so in theory any compliant MoQ client should work. That said, we recommend using the `@moq` client libraries — the reference TypeScript implementation maintained alongside the protocol. For more details, see the [documentation](https://doc.moq.dev/lib/js/).
:::
## Quickstart with the Sandbox API
If you don't have a backend server set up, you can prototype publishing using the [Sandbox API](../../explanation/sandbox-api-concept).
### Obtaining a publisher connection URL
For more on what the Sandbox API is and its limitations, see [What is the Sandbox API?](../../explanation/sandbox-api-concept).
:::info
To obtain a MoQ connection URL you'll need your Sandbox API URL. If you don't have it already, see [Sandbox API URL](../../explanation/sandbox-api-concept#sandbox-api-url-and-fishjam-id).
:::
If you're using React, the `useSandbox` hook from `@fishjam-cloud/react-client` wraps the Sandbox API request for you:
```tsx
// @noErrors
const PUBLISHER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// Inside a React component:
const { getSandboxMoqPublisherAccess } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
// Request a publisher connection URL scoped to the publisher path
const { connection_url: publishUrl } = await getSandboxMoqPublisherAccess(PUBLISHER_PATH);
```
If you don't want to use React or pull in the whole client library just for the `useSandbox` hook, you can call the Sandbox API directly with `fetch`:
```ts
// @noErrors
const PUBLISHER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
const response = await fetch(
`${SANDBOX_API_URL}/moq/${PUBLISHER_PATH}/publisher`,
);
const { connection_url: publishUrl } = await response.json();
```
### Connecting and publishing
Install the MoQ packages:
```bash npm2yarn
npm install @moq/lite @moq/publish
```
Use the connection URL to connect to the Fishjam MoQ relay and start broadcasting:
```ts
// @noErrors
const PUBLISHER_PATH = "stream-alice";
const publishUrl = "";
// ---cut---
// Connect to the Fishjam MoQ relay using the publisher connection URL
const connection = await Moq.Connection.connect(new URL(publishUrl));
const camera = new Publish.Source.Camera({ enabled: true });
const microphone = new Publish.Source.Microphone({ enabled: true });
// Set up a broadcast with video and audio tracks
const broadcast = new Publish.Broadcast({
connection,
name: Moq.Path.from(PUBLISHER_PATH),
enabled: true,
video: {
source: camera.source,
hd: { enabled: true },
},
audio: {
enabled: true,
source: microphone.source,
},
});
```
The stream is now live on the MoQ relay! Viewers can now start watching it — follow [Web Subscribing](./web-subscribing).
## Production with Server SDKs
The [Quickstart](#quickstart-with-the-sandbox-api) gets you publishing quickly. In production, your backend generates tokens with proper authorization, so you control who can publish.
A **publisher connection URL** grants write access to a specific path. Generate one on your backend and deliver it to the broadcasting client:
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const streamPath = 'stream-alice';
// Generate a connection URL that allows publishing to 'stream-alice'
const { connection_url: publishUrl } = await fishjamClient.createMoqAccess({
publishPath: streamPath,
});
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
stream_path = 'stream-alice'
# Generate a connection URL that allows publishing to 'stream-alice'
publish_url = fishjam_client.create_moq_access(publish_path=stream_path).connection_url
```
Deliver this connection URL to the broadcasting client, then use it to connect as described in [Connecting and publishing](#connecting-and-publishing).
## See also
- [Web Subscribing](./web-subscribing) — watch a MoQ stream in the browser
- [MoQ with Fishjam](../../explanation/moq-with-fishjam) — how MoQ works in Fishjam
- [Livestreaming](../../tutorials/livestreaming) — the WebRTC (WHIP/WHEP) approach
- [WHIP/WHEP with Fishjam](../../how-to/backend/whip-whep)
---
## Web Subscribing
This tutorial explains how to **subscribe** to a live stream and render it in the browser using [Media over QUIC (MoQ)](https://datatracker.ietf.org/wg/moq/about/) with Fishjam. To broadcast a stream instead, see [Web Publishing](./web-publishing).
:::info
If you're new to MoQ, then we recommend getting familiar with the [MoQ with Fishjam](../../explanation/moq-with-fishjam) explanation.
:::
To receive a MoQ stream you need one thing: a _subscriber connection URL_ — the relay URL with a subscriber token embedded as a `?jwt=` query parameter. We show how to quickly prototype with the [Sandbox API](#quickstart-with-the-sandbox-api) and how to get ready for [production](#production-with-server-sdks).
:::tip
MoQ is a protocol with a well-defined negotiation, so in theory any compliant MoQ client should work. That said, we recommend using the [`@moq`](https://github.com/moq-dev/moq) client libraries — the reference TypeScript implementation maintained alongside the protocol. For more details, see the [documentation](https://doc.moq.dev/lib/js/).
:::
## Quickstart with the Sandbox API
If you don't have a backend server set up, you can prototype subscribing using the [Sandbox API](../../explanation/sandbox-api-concept).
### Obtaining a subscriber connection URL
For more on what the Sandbox API is and its limitations, see [What is the Sandbox API?](../../explanation/sandbox-api-concept).
:::info
To obtain a MoQ connection URL you'll need your Sandbox API URL. If you don't have it already, see [Sandbox API URL](../../explanation/sandbox-api-concept#sandbox-api-url-and-fishjam-id).
:::
If you're using React, the `useSandbox` hook from `@fishjam-cloud/react-client` wraps the Sandbox API request for you:
```tsx
// @noErrors
const SUBSCRIBER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// Inside a React component:
const { getSandboxMoqSubscriberAccess } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
// Request a subscriber connection URL scoped to the subscriber path
const { connection_url: subscribeUrl } = await getSandboxMoqSubscriberAccess(SUBSCRIBER_PATH);
```
If you don't want to use React or pull in the whole client library just for the `useSandbox` hook, you can call the Sandbox API directly with `fetch`:
```ts
// @noErrors
const SUBSCRIBER_PATH = "stream-alice";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
const response = await fetch(
`${SANDBOX_API_URL}/moq/${SUBSCRIBER_PATH}/subscriber`,
);
const { connection_url: subscribeUrl } = await response.json();
```
### Connecting and subscribing
Install the MoQ packages:
```bash npm2yarn
npm install @moq/lite @moq/watch
```
Add a `` element to your page — `MultiBackend` will paint decoded frames onto it:
```html
```
Then use the connection URL to connect and render the stream onto that canvas:
```ts
// @noErrors
const SUBSCRIBER_PATH = "stream-alice";
const subscribeUrl = "";
// ---cut---
// Connect to the Fishjam MoQ relay using the subscriber connection URL
const connection = await Moq.Connection.connect(new URL(subscribeUrl));
// Subscribe to the broadcast
const broadcast = new Watch.Broadcast({
connection,
name: Moq.Path.from(SUBSCRIBER_PATH),
enabled: true,
});
// Grab the canvas from the DOM and hand it to MultiBackend,
// which handles decoding and rendering of both video and audio
const canvas = document.getElementById("remote") as HTMLCanvasElement;
const backend = new Watch.MultiBackend({
element: canvas,
broadcast,
paused: false,
});
```
:::info
**Why ``?** \
Watch.MultiBackend renders to a `` so it can decode frames directly through the WebCodecs API, which natively supports the codecs MoQ delivers. A `` element is also supported, but it relies on Media Source Extensions and requires remuxing each stream into fMP4 first.
:::
That's it! The stream will appear in the canvas once the publisher starts broadcasting.
### Using the `` web component
If you don't need fine-grained control over the rendering pipeline, the `@moq/watch` package ships a ready-to-use custom element that wraps connection, subscription, decoding, and rendering behind a single HTML tag.
Import once to register the elements — `@moq/watch/element` registers `` (which renders the stream) and `@moq/watch/ui` registers `` (which decorates a child `` with play/pause, volume, latency, and buffer controls):
```ts
```
Then drop `` wrapping `` into your HTML — pass the connection URL (returned by the SDK or Sandbox API, with the JWT already in the query string) and the broadcast path:
```html
```
The element observes attributes like `url`, `name`, `paused`, `muted`, `volume`, `latency`, and `reload`, so you can drive playback from JavaScript by updating them at runtime.
## Production with Server SDKs
The [Quickstart](#quickstart-with-the-sandbox-api) gets you watching quickly. In production, your backend generates tokens with proper authorization, so you control who can subscribe.
A **subscriber connection URL** grants read access to a specific path. Generate one on your backend and deliver it to the viewing client:
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const streamPath = 'stream-alice';
// Generate a connection URL that allows subscribing to 'stream-alice'
const { connection_url: subscribeUrl } = await fishjamClient.createMoqAccess({
subscribePath: streamPath,
});
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
stream_path = 'stream-alice'
# Generate a connection URL that allows subscribing to 'stream-alice'
subscribe_url = fishjam_client.create_moq_access(subscribe_path=stream_path).connection_url
```
Deliver this connection URL to the viewing client, then use it to connect as described in [Connecting and subscribing](#connecting-and-subscribing).
### Subscribe to a namespace
When multiple publishers join a room, you won't know their exact paths in advance.
Instead of consuming a single path, you can **discover** all broadcasts published under a namespace prefix and subscribe to each one as they appear.
To do this, generate a subscriber connection URL scoped to the room namespace instead of a single stream path.
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const roomName = 'my-room';
const { connection_url: alicePublisherUrl } = await fishjamClient.createMoqAccess({
publishPath: roomName + "/alice",
});
const { connection_url: bobPublisherUrl } = await fishjamClient.createMoqAccess({
publishPath: roomName + "/bob",
});
const { connection_url: namespaceUrl } = await fishjamClient.createMoqAccess({
subscribePath: roomName,
});
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
room_name = 'my-room'
alice_publisher_url = fishjam_client.create_moq_access(
publish_path=room_name + "/alice",
).connection_url
bob_publisher_url = fishjam_client.create_moq_access(
publish_path=room_name + "/bob",
).connection_url
namespace_url = fishjam_client.create_moq_access(subscribe_path=room_name).connection_url
```
Then on the client, read connection.announced — a reactive Set of the paths currently being published. Wrap the read in an Effect, and the callback re-runs every time a publisher joins or leaves, with the Set reflecting the live state. Iterate it to subscribe to any path you haven't seen yet:
```ts
// @noErrors
const namespaceUrl = "";
// ---cut---
// Reload manages the WebTransport session: it connects, auto-reconnects on drop,
// and exposes `announced` as a reactive Set of publishers currently online.
const connection = new Moq.Connection.Reload({
url: new Signal(new URL(namespaceUrl)),
enabled: new Signal(true),
});
// Tracks which broadcasts already have a tile, so we don't mount duplicates
// when the Effect below re-runs on every announce change.
const mountedStreams = new Set();
new Effect().run((effect) => {
for (const path of effect.get(connection.announced)) {
const key = path.toString();
if (mountedStreams.has(key)) continue;
mountedStreams.add(key);
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
new Watch.MultiBackend({
connection: connection.established,
broadcast: new Watch.Broadcast({
connection: connection.established,
name: path,
enabled: true,
}),
element: canvas,
});
}
});
```
## See also
- [Web Publishing](./web-publishing) — broadcast a MoQ stream from the browser
- [MoQ with Fishjam](../../explanation/moq-with-fishjam) — how MoQ works in Fishjam
- [Livestreaming](../../tutorials/livestreaming) — the WebRTC (WHIP/WHEP) approach
- [WHIP/WHEP with Fishjam](../../how-to/backend/whip-whep)
---
## React Native Quick Start
This tutorial will guide you through integrating Fishjam into your React Native application step by step.
By the end, you'll have a working video streaming app and understand the core concepts.
## What you'll build
A simple React Native app that can join conference calls and stream audio/video between participants.
## What you'll learn
- How to install and configure Fishjam SDK
- How to join a room and start streaming
- How to display video and play audio from other participants
- How to check connection status
## Prerequisites
- React Native development environment set up
- Access to [Fishjam Dashboard](https://fishjam.io/app)
## Step 1: Install and configure
### Install the package
```bash npm2yarn
npm install @fishjam-cloud/react-native-client
```
### Configure app permissions
Your app needs to have permissions configured in order to use the microphone and camera.
#### Android
Add required permissions to the `app.json` file:
```json title='app.json'
{
"expo": {
"android": {
"permissions": [
"android.permission.CAMERA",
"android.permission.RECORD_AUDIO",
"android.permission.MODIFY_AUDIO_SETTINGS",
"android.permission.ACCESS_NETWORK_STATE"
]
}
}
}
```
Add required permissions to the `AndroidManifest.xml` file:
```xml title='AndroidManifest.xml'
```
#### iOS
Add camera and microphone usage descriptions to `app.json`:
```json title='app.json'
{
"expo": {
"ios": {
"infoPlist": {
"NSCameraUsageDescription": "Allow $(PRODUCT_NAME) to access your camera.",
"NSMicrophoneUsageDescription": "Allow $(PRODUCT_NAME) to access your microphone."
}
}
}
}
```
Ensure `Info.plist` contains camera and microphone usage description entries:
```xml title='Info.plist'
NSCameraUsageDescription
Allow $(PRODUCT_NAME) to access your camera.
NSMicrophoneUsageDescription
Allow $(PRODUCT_NAME) to access your microphone.
```
### Build native dependencies
```bash
npx expo prebuild
```
```bash
cd ios && pod install
```
### Get your Fishjam ID and Sandbox API URL
1. Log in to [Fishjam Dashboard](https://fishjam.io/app)
2. Copy your Fishjam ID
3. Navigate to the [Sandbox tab](https://fishjam.io/app/sandbox)
4. Copy your Sandbox API URL from the **Sandbox API** section
The Fishjam ID is required by `FishjamProvider` to connect to the media server. The Sandbox API URL is used by `useSandbox` to request test peer tokens from the sandbox.
### Set up Fishjam context
Wrap your app in the `FishjamProvider` component:
```tsx
const App = () => null;
// ---cut---
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
export default function Root() {
return (
);
}
```
:::important
The iOS Simulator has no camera. To test camera features, use a real device or [SimCam](https://simcam.swmansion.com/), which injects a virtual camera the simulator picks up automatically. See [Camera on iOS Simulator](../how-to/client/ios-simulator-camera).
:::
For more detailed implementation follow the steps below.
## Step 2: Join a room and start streaming
Create a component that joins a room and starts streaming video:
```tsx
useConnection,
useSandbox,
useInitializeDevices,
} from "@fishjam-cloud/react-native-client";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
export function JoinRoomButton() {
const { joinRoom } = useConnection();
const { initializeDevices } = useInitializeDevices();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const handleJoinRoom = async () => {
const roomName = "testRoom";
const peerName = "testUser";
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken(roomName, peerName);
// Start camera by selecting the first available camera
await initializeDevices({ enableAudio: false }); // or just initializeDevices(); if you want both camera and mic
// Join the room
await joinRoom({ peerToken });
};
return ;
}
```
## Step 3: Check connection status
Monitor your connection status:
```tsx
// ---cut---
export function ConnectionStatus() {
const { peerStatus } = useConnection();
return Status: {peerStatus} ;
}
```
## Step 4: Display your video
Show your own video stream:
```tsx
export function StreamPreview() {
const { cameraStream } = useCamera();
return (
{cameraStream ? (
) : (
No camera stream
)}
);
}
```
## Step 5: Display other participants
Show video from other peers in the room:
```tsx
usePeers,
RTCView,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
return (
{stream ? (
) : (
No video
)}
);
}
export function ParticipantsView() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) => (
{peer.cameraTrack?.stream && (
)}
))}
);
}
```
## Complete example
Here's a complete working app:
```tsx
FishjamProvider,
useConnection,
useCamera,
usePeers,
useInitializeDevices,
useSandbox,
RTCView,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
const FISHJAM_ID = "YOUR_FISHJAM_ID";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// ---cut---
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
if (!stream) {
return (
No video
);
}
return (
);
}
function VideoCall() {
const { joinRoom, peerStatus } = useConnection();
const { cameraStream } = useCamera();
const { remotePeers } = usePeers();
const { initializeDevices } = useInitializeDevices();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const [isJoined, setIsJoined] = useState(false);
const handleJoin = async () => {
const roomName = "testRoom";
const peerName = `user_${Date.now()}`;
// Initialize devices first
await initializeDevices();
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken(roomName, peerName);
await joinRoom({ peerToken });
setIsJoined(true);
};
return (
Fishjam Video Call
Status: {peerStatus}
{!isJoined && }
{cameraStream && (
Your Video
)}
Other Participants
{remotePeers.length === 0 ? (
No other participants
) : (
remotePeers.map((peer) => (
{peer.cameraTrack?.stream && (
)}
))
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 10,
},
status: {
fontSize: 16,
marginBottom: 20,
},
section: {
marginTop: 20,
},
sectionTitle: {
fontSize: 18,
fontWeight: "600",
marginBottom: 10,
},
participant: {
marginBottom: 10,
},
video: {
height: 200,
width: "100%",
borderRadius: 8,
},
videoPlaceholder: {
height: 200,
width: "100%",
backgroundColor: "#000",
borderRadius: 8,
justifyContent: "center",
alignItems: "center",
},
});
export default function App() {
return (
);
}
```
## Next steps
Now that you have a basic app working, explore these how-to guides:
- [How to handle screen sharing](../how-to/client/screensharing)
- [How to blur your camera background](./background-blur)
- [How to implement background streaming](../how-to/client/background-streaming)
- [How to handle reconnections](../how-to/client/reconnection-handling)
- [How to work with metadata](../how-to/client/metadata)
- [Explore React Native examples](../examples/react-native)
Or learn more about Fishjam concepts:
- [Understanding Fishjam architecture](../explanation/architecture)
- [Rooms](../explanation/rooms)
---
## React/Web Quick Start
This tutorial will guide you through integrating Fishjam into your React web application step by step.
By the end, you'll have a working video streaming web app and understand the core concepts.
## What you'll build
A simple React web app that can join video calls and stream video between participants.
## What you'll learn
- How to install and set up Fishjam for React
- How to join a room and start streaming
- How to display video from other participants
- How to manage media devices
## Prerequisites
- React development environment set up
- Access to [Fishjam Dashboard](https://fishjam.io/app)
## Step 1: Install and set up
### Install the package
```bash npm2yarn
npm install @fishjam-cloud/react-client
```
### Get your Fishjam ID and Sandbox API URL
1. Log in to [Fishjam Dashboard](https://fishjam.io/app)
2. Navigate to the [Sandbox tab](https://fishjam.io/app/sandbox)
3. Copy your Fishjam ID
4. Copy your Sandbox API URL from the **Sandbox API** section
The Fishjam ID is required by `FishjamProvider` to connect to the media server. The Sandbox API URL is used by `useSandbox` to request test peer tokens.
### Set up Fishjam context
Wrap your app in the `FishjamProvider` component:
```tsx
const App = {} as any;
// ---cut---
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
ReactDOM.createRoot(document.getElementById("root")!).render(
,
);
```
## Step 2: Join a room and start streaming
Create a component that joins a room and starts streaming:
```tsx
useConnection,
useCamera,
useInitializeDevices,
useSandbox,
} from "@fishjam-cloud/react-client";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
export function JoinRoomButton() {
const { joinRoom } = useConnection();
const { selectCamera } = useCamera();
const { initializeDevices } = useInitializeDevices();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const handleJoinRoom = async () => {
const roomName = "testRoom";
const peerName = "testUser";
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken(roomName, peerName);
// Start camera by selecting the first available camera
await initializeDevices({ enableAudio: false }); // or just initializeDevices(); if you want both camera and mic
// Join the room
await joinRoom({ peerToken });
};
return Join Room ;
}
```
## Step 3: Display other participants
Show video from other peers:
```tsx
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
const videoRef = useRef(null);
useEffect(() => {
if (!videoRef.current) return;
videoRef.current.srcObject = stream ?? null;
}, [stream]);
return ;
}
export function ParticipantsView() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) => (
{peer.cameraTrack?.stream && (
)}
))}
);
}
```
## Step 4: Display your video
Show your own video stream:
```tsx
const VideoPlayer = ({
stream,
}: {
stream: MediaStream | null | undefined;
}) => {
return null;
};
// ---cut---
export function MyVideo() {
const { cameraStream } = useCamera();
return ;
}
```
## Step 5: Handle connection status
Monitor your connection:
```tsx
export function ConnectionStatus() {
const { peerStatus } = useConnection();
return Status: {peerStatus};
}
```
## Complete example
Here's a complete working app:
```tsx
FishjamProvider,
useConnection,
useCamera,
usePeers,
useInitializeDevices,
useSandbox,
} from "@fishjam-cloud/react-client";
// Check https://fishjam.io/app/ for your Fishjam ID
// Check https://fishjam.io/app/sandbox for your Sandbox API URL
const FISHJAM_ID = "YOUR_FISHJAM_ID";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// ---cut---
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
const videoRef = useRef(null);
useEffect(() => {
if (!videoRef.current) return;
videoRef.current.srcObject = stream ?? null;
}, [stream]);
return ;
}
function VideoCall() {
const { joinRoom, peerStatus } = useConnection();
const { cameraStream } = useCamera();
const { remotePeers } = usePeers();
const { initializeDevices } = useInitializeDevices();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const [isJoined, setIsJoined] = useState(false);
const handleJoin = async () => {
const roomName = "testRoom";
const peerName = `user_${Date.now()}`;
// Initialize devices first
await initializeDevices();
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken(roomName, peerName);
await joinRoom({ peerToken });
setIsJoined(true);
};
return (
Fishjam Video Call
Status: {peerStatus}
{!isJoined && Join Room }
{cameraStream && (
Your Video
)}
Other Participants
{remotePeers.map((peer) => (
{peer.cameraTrack?.stream && (
)}
))}
);
}
export default function App() {
return (
);
}
```
## Next steps
Now that you have a basic app working, explore these how-to guides:
- [How to manage media devices](../how-to/client/managing-devices)
- [How to implement livestreaming](../tutorials/livestreaming)
- [How to work with stream middleware](../how-to/client/camera-effects/stream-middleware)
- [How to handle custom sources](../how-to/client/custom-sources/web)
- [Explore React examples](../examples/react)
Or learn more about Fishjam concepts:
- [Understanding Fishjam architecture](../explanation/architecture)
- [Rooms](../explanation/rooms)
---
## TypeScript Quick Start
This tutorial shows how to use Fishjam from plain TypeScript, without any UI framework.
It uses `@fishjam-cloud/ts-client`, the same client that powers the React SDK. There are no hooks or providers: you call methods and listen to events.
## What you'll build
A single web page that joins a room, publishes your camera and microphone, and shows everyone else in the room.
## What you'll learn
- How to connect to a room with `FishjamClient`
- How to publish your camera and microphone
- How to display tracks from other participants
- How to leave the room
## Prerequisites
- A TypeScript web project with a bundler, for example `npm create vite@latest my-app -- --template vanilla-ts`
- Access to [Fishjam Dashboard](https://fishjam.io/app)
## Step 1: Install and set up
### Install the package
```bash npm2yarn
npm install @fishjam-cloud/ts-client
```
### Get your Fishjam ID and Sandbox API URL
1. Log in to [Fishjam Dashboard](https://fishjam.io/app)
2. Navigate to the [Sandbox tab](https://fishjam.io/app/sandbox)
3. Copy your Fishjam ID
4. Copy your Sandbox API URL from the **Sandbox API** section
## Step 2: Get a peer token
Every peer needs a peer token to join a room. For testing, request one from the Sandbox API:
```ts
// Check https://fishjam.io/app/sandbox for your Sandbox API URL
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
async function getPeerToken(roomName: string, peerName: string) {
const url = new URL(SANDBOX_API_URL);
url.searchParams.set("roomName", roomName);
url.searchParams.set("peerName", peerName);
const response = await fetch(url);
const { peerToken } = await response.json();
return peerToken as string;
}
```
:::warning
The Sandbox API is for prototyping only. In production, get the peer token from [your own backend](./backend-quick-start).
:::
## Step 3: Connect to a room
Create a `FishjamClient` and call `connect`. The returned promise resolves once you have joined the room:
```ts
const getPeerToken = async (roomName: string, peerName: string) => "";
// ---cut---
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "YOUR_FISHJAM_ID";
const client = new FishjamClient();
const peerToken = await getPeerToken("testRoom", `user_${Date.now()}`);
await client.connect({
url: `wss://fishjam.io/api/v1/connect/${FISHJAM_ID}`,
token: peerToken,
peerMetadata: {},
});
```
## Step 4: Publish your camera and microphone
Get a `MediaStream` from the browser and add each of its tracks to the client:
```ts
const client = new FishjamClient();
// ---cut---
const localStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true,
});
for (const track of localStream.getTracks()) {
await client.addTrack(track, {
type: track.kind === "video" ? "camera" : "microphone",
paused: false,
});
}
// Show your own video (muted, so you don't hear yourself)
const myVideo = document.createElement("video");
myVideo.autoplay = true;
myVideo.muted = true;
myVideo.srcObject = localStream;
document.body.appendChild(myVideo);
```
## Step 5: Display other participants
The client emits `trackReady` when media from another peer starts arriving, and `trackRemoved` when it stops.
Register these listeners **before** calling `connect`, so you also receive the tracks of peers who are already in the room:
```ts
const client = new FishjamClient();
// ---cut---
client.on("trackReady", (ctx) => {
if (!ctx.track) return;
const element = document.createElement(
ctx.track.kind === "video" ? "video" : "audio",
);
element.id = ctx.trackId;
element.autoplay = true;
element.srcObject = new MediaStream([ctx.track]);
document.body.appendChild(element);
});
client.on("trackRemoved", (ctx) => {
document.getElementById(ctx.trackId)?.remove();
});
```
## Step 6: Leave the room
```ts
const client = new FishjamClient();
// ---cut---
client.disconnect();
```
## Complete example
`index.html`:
```html
Join
Leave
```
`src/main.ts`:
```ts
// Check https://fishjam.io/app/ for your Fishjam ID
// Check https://fishjam.io/app/sandbox for your Sandbox API URL
const FISHJAM_ID = "YOUR_FISHJAM_ID";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
const videos = document.getElementById("videos")!;
const client = new FishjamClient();
let localStream: MediaStream | undefined;
async function getPeerToken(roomName: string, peerName: string) {
const url = new URL(SANDBOX_API_URL);
url.searchParams.set("roomName", roomName);
url.searchParams.set("peerName", peerName);
// For production apps, get the peerToken from your own backend instead
const response = await fetch(url);
const { peerToken } = await response.json();
return peerToken as string;
}
function addMediaElement(id: string, track: MediaStreamTrack, muted = false) {
const element = document.createElement(
track.kind === "video" ? "video" : "audio",
);
element.id = id;
element.autoplay = true;
element.muted = muted;
element.srcObject = new MediaStream([track]);
videos.appendChild(element);
}
client.on("trackReady", (ctx) => {
if (ctx.track) addMediaElement(ctx.trackId, ctx.track);
});
client.on("trackRemoved", (ctx) => {
document.getElementById(ctx.trackId)?.remove();
});
async function join() {
const peerToken = await getPeerToken("testRoom", `user_${Date.now()}`);
await client.connect({
url: `wss://fishjam.io/api/v1/connect/${FISHJAM_ID}`,
token: peerToken,
peerMetadata: {},
});
localStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true,
});
for (const track of localStream.getTracks()) {
await client.addTrack(track, {
type: track.kind === "video" ? "camera" : "microphone",
paused: false,
});
}
const myVideo = localStream.getVideoTracks()[0];
if (myVideo) addMediaElement("my-video", myVideo, true);
}
function leave() {
client.disconnect();
localStream?.getTracks().forEach((track) => track.stop());
videos.replaceChildren();
}
document.getElementById("join")!.addEventListener("click", join);
document.getElementById("leave")!.addEventListener("click", leave);
```
Run `npm run dev`, open the page in two browser tabs and click **Join** in both.
## Next steps
- [Everything the TypeScript client can do](../how-to/typescript-client): simulcast, data channels, livestreaming and more
- [Set up your own backend](./backend-quick-start) to create peer tokens in production
- [Understanding Fishjam architecture](../explanation/architecture)
- [Rooms](../explanation/rooms)
---
## Draw WebGPU effects into your published camera Mobile
# Draw WebGPU effects into your published camera Mobile
:::note
This tutorial is exclusively for **Mobile** (React Native) applications. On the web, publishing WebGPU output only requires capturing a canvas; see the web tab of the [WebGPU effects how-to](../how-to/client/camera-effects/webgpu-effects).
:::
This tutorial continues from the [React Native Quick Start](./react-native-quick-start). You'll take the video call app you built there and route its camera through your own WebGPU pipeline: first unchanged, then with a watermark image drawn on top, and finally recolored by a shader you write yourself.
## What you'll build
The Quick Start app, now publishing its camera through your own GPU pipeline: a camera feed with a "LIVE" watermark in the corner, recolored to grayscale by your own shader, switched on and off with a button.
## What you'll learn
- How to render the published camera yourself with a camera middleware and `createCameraFrameProcessorSession`
- How to load a PNG into a GPU texture and composite it over the camera as a second render pass
- How to write TypeGPU shaders that change the published camera pixels
## Prerequisites
- The finished app from the [React Native Quick Start](./react-native-quick-start), on Expo SDK 57 (React Native 0.86) with the New Architecture enabled
- `@fishjam-cloud/react-native-client` **0.30.2** or newer, `@fishjam-cloud/video-effects` **0.1.5** or newer and `react-native-webgpu` **0.10.1** or newer
- A physical device (iOS 16.4+ or Android 8.0+), or the iOS Simulator with a virtual camera from [SimCam](../how-to/client/ios-simulator-camera.mdx)
- A second device or simulator to join the room and see the result
## Step 1: Install and configure
### Install the packages
```bash npm2yarn
npm install @fishjam-cloud/video-effects @fishjam-cloud/react-native-worklets react-native-worklets react-native-webgpu typegpu expo-asset expo-file-system expo-build-properties
npm install --save-dev unplugin-typegpu @babel/plugin-transform-class-static-block
```
- `@fishjam-cloud/video-effects` hands you every camera frame as a GPU texture and publishes what you draw.
- `@fishjam-cloud/react-native-worklets` and `react-native-worklets` run your drawing code on every camera frame, off the JS thread.
- `react-native-webgpu` is the GPU API you draw with, and `typegpu` lets you write shaders in TypeScript.
- `expo-asset` and `expo-file-system` load the watermark image in Step 3.
- `expo-build-properties` raises the Android minimum SDK version.
### Update the Babel config
The shaders in this tutorial are written in [TypeGPU](https://docs.swmansion.com/TypeGPU/) (TGSL): typed TypeScript functions compiled to WGSL at build time by `unplugin-typegpu`. TypeGPU also needs class static blocks and `import.meta`, and your drawing code needs the worklets plugin. Replace your `babel.config.js`, keeping `react-native-worklets/plugin` last:
```js title='babel.config.js'
module.exports = function (api) {
api.cache(true);
return {
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
plugins: [
"@babel/plugin-transform-class-static-block",
"unplugin-typegpu/babel",
"react-native-worklets/plugin",
],
};
};
```
### Raise the minimum OS versions
Expo SDK 57 needs iOS 16.4, and `react-native-webgpu` needs Android 8.0 (API 26), while Expo builds for API 24 by default. Set both in `app.json`: the iOS version in the Fishjam config plugin, the Android one with `expo-build-properties`:
```json title='app.json'
{
"expo": {
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"ios": {
"iphoneDeploymentTarget": "16.4"
}
}
],
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 26
}
}
]
]
}
}
```
### Rebuild the app
```bash
npx expo prebuild
npx expo run:ios # or run:android
```
```bash
cd ios && pod install
```
Start Metro with a cleared cache afterwards (`npx expo start --clear`).
## Step 2: Route the camera through WebGPU
Fishjam lets you put a [middleware](../how-to/client/camera-effects/stream-middleware.mdx) between your camera and the room: a function that receives the camera track and returns the track to publish instead. Your middleware will return a track that you draw yourself. Three pieces make that work:
- `getCameraWebGpuDevice` provides a shared `GPUDevice`, requested with the features the camera import needs.
- `createCameraFrameProcessorSession` calls your `frameKernel` worklet for every camera frame. Calling `render(...)` inside it gives you a context with the command encoder, the live camera texture and the output texture. What you draw into the output texture is what peers receive.
- For now, draw the camera unchanged with the ready-made passthrough pass: `createCameraPassthroughPipeline` builds it once, `encodeCameraPassthrough` encodes it each frame, and `computeAspectFillCrop` fills the output like `objectFit: "cover"`.
Create `cameraEffect.ts` next to `App.tsx`:
```ts title='cameraEffect.ts'
computeAspectFillCrop,
createCameraFrameProcessorSession,
createCameraPassthroughPipeline,
encodeCameraPassthrough,
getCameraWebGpuDevice,
type CameraFrameKernel,
} from "@fishjam-cloud/video-effects/fishjam-react-native";
export const cameraEffect: TrackMiddleware = async (track) => {
const device = await getCameraWebGpuDevice();
// A ready-made camera → output render pass. The Fishjam camera arrives as RGB.
const passthrough = createCameraPassthroughPipeline(device, {
cameraPixelLayout: "rgb",
});
const frameKernel: CameraFrameKernel = (frame, render) => {
"worklet";
render((context) => {
// Crop the camera to fill the output, like `objectFit: "cover"`.
const crop = computeAspectFillCrop(
context.cameraWidth,
context.cameraHeight,
context.outputWidth / context.outputHeight,
);
encodeCameraPassthrough(
context.device,
passthrough,
context.cameraTexture,
context.outputView,
context.commandEncoder,
crop,
);
});
};
const session = await createCameraFrameProcessorSession({
track,
device,
width: 720,
height: 1280,
frameKernel,
});
// Publish the session's track; dispose it when the middleware is removed.
return { track: session.track, onClear: () => void session.dispose() };
};
```
Then add a button to `App.tsx` that switches the middleware on and off, the same way as any camera middleware:
```tsx
declare const cameraEffect: NonNullable;
// ---cut---
function EffectButton() {
const { currentCameraMiddleware, setCameraTrackMiddleware } = useCamera();
const isEffectOn = currentCameraMiddleware === cameraEffect;
const toggleEffect = async () => {
try {
await setCameraTrackMiddleware(isEffectOn ? null : cameraEffect);
} catch (error) {
console.warn("Camera effect failed", error);
await setCameraTrackMiddleware(null); // go back to the plain camera
}
};
return (
);
}
```
Render ` ` in `VideoCall`, right above your own video (` `).
Rebuild, join the room from two devices and tap **Effect on**. The feed looks the same as before, but every published pixel now flows through a pipeline you control. The next two steps build on it.
From here on, the [rules inside the frame kernel](../how-to/client/camera-effects/webgpu-effects#rules-inside-the-frame-kernel) apply: draw into the provided output view, call `render(...)` at most once per frame, and never call `queue.submit()` yourself.
## Step 3: Draw a watermark on top
### Make a watermark image
Any PNG with transparency works. Make one with red "LIVE" text on a transparent background, roughly 512×128, and save it as `assets/watermark.png` in your project. Keep the alpha straight (non-premultiplied), which is what image editors export by default. A colored watermark will make the effect in Step 4 easier to see.
### Build the watermark pipeline
The watermark needs its own pipeline: a texture holding the image, and a textured quad drawn over the bottom-right corner with alpha blending.
Note the following:
- Unlike the camera, which arrives as an external texture that expires every frame, the watermark is a plain `texture_2d`. It's uploaded once with `copyExternalImageToTexture`, and its bind group is built once and reused for every frame.
- The quad's corner placement is computed in plain JavaScript and baked into the vertex shader as constants. The output size is fixed, so no uniform buffer is needed.
- `tgpu.resolve` takes the shader functions as an array. The `.$name(...)` calls pin the WGSL entry-point names that `createRenderPipeline` looks up. If a name doesn't match, the failure is silent: WebGPU reports it as an asynchronous validation error, not a thrown exception, and the pass simply draws nothing.
Add the pipeline to `cameraEffect.ts`:
```ts title='cameraEffect.ts'
///
// ---cut---
// A plain 2D texture never expires (unlike the camera's external texture),
// so it is bound once and reused every frame.
const watermarkBindingDeclarations = /* wgsl */ `
@group(0) @binding(0) var watermarkTexture: texture_2d;
@group(0) @binding(1) var watermarkSampler: sampler;
`;
const sampleWatermark = tgpu.fn(
[d.vec2f],
d.vec4f,
)(/* wgsl */ `(uv: vec2f) -> vec4f {
return textureSample(watermarkTexture, watermarkSampler, uv);
}`);
// A quad over the given clip-space rect; the corners are baked in as
// constants when the shader is built.
function makeWatermarkVertexMain(rect: {
x0: number;
y0: number;
x1: number;
y1: number;
}) {
const { x0, y0, x1, y1 } = rect;
return tgpu
.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [
d.vec2f(x0, y0),
d.vec2f(x1, y0),
d.vec2f(x0, y1),
d.vec2f(x1, y1),
];
const uvs = [d.vec2f(0, 1), d.vec2f(1, 1), d.vec2f(0, 0), d.vec2f(1, 0)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: uvs[input.vertexIndex],
};
})
.$name("vertexMain");
}
const watermarkFragmentMain = tgpu
.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => sampleWatermark(input.uv))
.$name("fragmentMain");
function createWatermarkPipeline(
device: GPUDevice,
bitmap: ImageBitmap,
outputWidth: number,
outputHeight: number,
) {
// 1. Upload the image into a GPU texture (a one-time copy).
const texture = device.createTexture({
size: [bitmap.width, bitmap.height],
format: "rgba8unorm",
usage:
GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST |
GPUTextureUsage.RENDER_ATTACHMENT,
});
device.queue.copyExternalImageToTexture({ source: bitmap }, { texture }, [
bitmap.width,
bitmap.height,
]);
// 2. Bottom-right placement: 24 px margin, 40% of the output width,
// height from the image's aspect ratio, converted to clip space.
const widthPx = outputWidth * 0.4;
const heightPx = widthPx * (bitmap.height / bitmap.width);
const marginPx = 24;
const x1 = 1 - (2 * marginPx) / outputWidth;
const x0 = x1 - (2 * widthPx) / outputWidth;
const y0 = -1 + (2 * marginPx) / outputHeight;
const y1 = y0 + (2 * heightPx) / outputHeight;
// 3. The pipeline: a textured quad with straight-alpha blending.
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
],
});
const module = device.createShaderModule({
code:
watermarkBindingDeclarations +
tgpu.resolve([
makeWatermarkVertexMain({ x0, y0, x1, y1 }),
watermarkFragmentMain,
]),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [
{
format: getOutputSurfaceFormat(),
blend: {
color: {
srcFactor: "src-alpha",
dstFactor: "one-minus-src-alpha",
operation: "add",
},
alpha: {
srcFactor: "one",
dstFactor: "one-minus-src-alpha",
operation: "add",
},
},
},
],
},
primitive: { topology: "triangle-strip" },
});
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{ binding: 0, resource: texture.createView() },
{
binding: 1,
resource: device.createSampler({
magFilter: "linear",
minFilter: "linear",
}),
},
],
});
return { pipeline, bindGroup };
}
```
:::note
TypeGPU is not required; you can hand-write the same shaders in WGSL. See the [WebGPU effects how-to](../how-to/client/camera-effects/webgpu-effects) for the trade-offs.
:::
### Load the image and encode the overlay
Loading is asynchronous: read the bundled asset with `expo-asset` and `expo-file-system`, then decode it with `createImageBitmap` (provided globally by `react-native-webgpu`). Reading a local copy of the asset instead of fetching it by URL keeps working in Android release builds. There, `expo-asset` leaves a bundled image as a drawable resource name instead of a file, so the loader creates a second `Asset` without the image size, which `downloadAsync` copies to a local file. Add the loader to `cameraEffect.ts`:
```ts title='cameraEffect.ts'
///
// ---cut---
const watermarkAsset = Asset.fromModule(require("./assets/watermark.png"));
async function loadWatermarkBitmap(): Promise {
// Android release builds keep bundled images as drawable resources, which `File` can't
// open. An asset described without the image size is copied to a local file instead.
const asset = new Asset({
name: watermarkAsset.name,
type: watermarkAsset.type,
hash: watermarkAsset.hash,
uri: watermarkAsset.uri,
});
await asset.downloadAsync();
if (!asset.localUri) {
throw new Error("The watermark image is not available.");
}
const bytes = await new File(asset.localUri).arrayBuffer();
return createImageBitmap(bytes);
}
```
Then update the middleware. It builds the watermark pipeline before it creates the session, and waits for the GPU to finish the upload. `copyExternalImageToTexture` submits GPU work itself, and once frames flow the session owns the device queue, so a concurrent upload from the JS thread can crash the app. Inside the kernel, after the passthrough and still inside the same `render` callback, encode a second pass on the same command encoder. `loadOp: "load"` keeps the camera pixels underneath, so the quad blends on top:
```ts title='cameraEffect.ts'
///
computeAspectFillCrop,
createCameraFrameProcessorSession,
createCameraPassthroughPipeline,
encodeCameraPassthrough,
getCameraWebGpuDevice,
type CameraFrameKernel,
} from "@fishjam-cloud/video-effects/fishjam-react-native";
declare function loadWatermarkBitmap(): Promise;
declare function createWatermarkPipeline(
device: GPUDevice,
bitmap: ImageBitmap,
outputWidth: number,
outputHeight: number,
): { pipeline: GPURenderPipeline; bindGroup: GPUBindGroup };
// ---cut---
export const cameraEffect: TrackMiddleware = async (track) => {
const device = await getCameraWebGpuDevice();
const passthrough = createCameraPassthroughPipeline(device, {
cameraPixelLayout: "rgb",
});
// Upload the watermark before frames flow, and wait until the GPU is done.
const bitmap = await loadWatermarkBitmap();
const watermark = createWatermarkPipeline(device, bitmap, 720, 1280);
await device.queue.onSubmittedWorkDone();
const frameKernel: CameraFrameKernel = (frame, render) => {
"worklet";
render((context) => {
const crop = computeAspectFillCrop(
context.cameraWidth,
context.cameraHeight,
context.outputWidth / context.outputHeight,
);
encodeCameraPassthrough(
context.device,
passthrough,
context.cameraTexture,
context.outputView,
context.commandEncoder,
crop,
);
// `loadOp: "load"` keeps the camera pass underneath.
const pass = context.commandEncoder.beginRenderPass({
colorAttachments: [
{ view: context.outputView, loadOp: "load", storeOp: "store" },
],
});
pass.setPipeline(watermark.pipeline);
pass.setBindGroup(0, watermark.bindGroup);
pass.draw(4);
pass.end();
});
};
const session = await createCameraFrameProcessorSession({
track,
device,
width: 720,
height: 1280,
frameKernel,
});
return { track: session.track, onClear: () => void session.dispose() };
};
```
The worklet captures the watermark's pipeline and bind group once, which is safe because a plain 2D texture never expires. A single `render(...)` call may contain any number of passes; only calling `render` more than once per frame is not allowed.
Rebuild, switch the effect on and check the receiving side: "LIVE" sits over the bottom-right corner of the camera.
## Step 4: Change the colors with your own shader
An overlay draws on top of the camera pixels. To change the pixels themselves, replace the passthrough with your own pipeline: a full-screen triangle whose fragment shader samples the camera and returns a new color. `createCameraShaderBindings` gives your shader `sampleCamera(uv)`, which returns the upright camera color.
Add the effect next to the watermark code in `cameraEffect.ts`:
```ts title='cameraEffect.ts'
///
// ---cut---
createCameraShaderBindings,
getOutputSurfaceFormat,
} from "@fishjam-cloud/video-effects/fishjam-react-native";
// Full-screen triangle; uv spans the visible area.
const vertexMain = tgpu.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: d.vec2f((p.x + 1) * 0.5, 1 - (p.y + 1) * 0.5),
};
});
function createGrayscaleEffect(device: GPUDevice) {
const cameraBindings = createCameraShaderBindings(device, {
cameraPixelLayout: "rgb",
});
const fragmentMain = tgpu.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => {
const color = cameraBindings.sampleCamera(input.uv);
const gray = dot(color.xyz, d.vec3f(0.299, 0.587, 0.114));
return d.vec4f(gray, gray, gray, 1);
});
// TypeGPU cannot emit the camera's `texture_external` binding itself,
// so prepend the declarations that come with the bindings.
const module = device.createShaderModule({
code:
cameraBindings.bindingDeclarations +
tgpu.resolve([vertexMain, fragmentMain]),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [cameraBindings.bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [{ format: getOutputSurfaceFormat() }],
},
});
return { cameraBindings, pipeline };
}
```
In the middleware, build the effect and pass its `cameraBindings` to the session. In return, the render context carries a ready-made `cameraBindGroup`, rebuilt every frame because the camera's external texture expires with each frame. The kernel now encodes the grayscale pass instead of the passthrough, with the watermark pass unchanged on top. The passthrough and crop imports are no longer needed:
```ts title='cameraEffect.ts'
///
createCameraFrameProcessorSession,
createCameraShaderBindings,
getCameraWebGpuDevice,
type CameraFrameKernel,
} from "@fishjam-cloud/video-effects/fishjam-react-native";
declare function loadWatermarkBitmap(): Promise;
declare function createWatermarkPipeline(
device: GPUDevice,
bitmap: ImageBitmap,
outputWidth: number,
outputHeight: number,
): { pipeline: GPURenderPipeline; bindGroup: GPUBindGroup };
declare function createGrayscaleEffect(device: GPUDevice): {
cameraBindings: ReturnType;
pipeline: GPURenderPipeline;
};
// ---cut---
export const cameraEffect: TrackMiddleware = async (track) => {
const device = await getCameraWebGpuDevice();
const grayscale = createGrayscaleEffect(device);
const bitmap = await loadWatermarkBitmap();
const watermark = createWatermarkPipeline(device, bitmap, 720, 1280);
await device.queue.onSubmittedWorkDone();
const frameKernel: CameraFrameKernel = (frame, render) => {
"worklet";
render((context) => {
// 1. Your shader draws the recolored camera into the output.
const pass = context.commandEncoder.beginRenderPass({
colorAttachments: [
{ view: context.outputView, loadOp: "clear", storeOp: "store" },
],
});
pass.setPipeline(grayscale.pipeline);
pass.setBindGroup(0, context.cameraBindGroup!);
pass.draw(3);
pass.end();
// 2. The watermark still goes on top, unchanged.
const overlay = context.commandEncoder.beginRenderPass({
colorAttachments: [
{ view: context.outputView, loadOp: "load", storeOp: "store" },
],
});
overlay.setPipeline(watermark.pipeline);
overlay.setBindGroup(0, watermark.bindGroup);
overlay.draw(4);
overlay.end();
});
};
const session = await createCameraFrameProcessorSession({
track,
device,
width: 720,
height: 1280,
// Provides a per-frame `cameraBindGroup` in the render context.
cameraShaderBindings: grayscale.cameraBindings,
frameKernel,
});
return { track: session.track, onClear: () => void session.dispose() };
};
```
:::note
Sampling the full frame stretches the camera when its aspect ratio differs from 720×1280. The [aspect ratio helpers](../how-to/client/camera-effects/webgpu-effects#going-further) in the how-to cover aspect-correct sampling.
:::
Rebuild one last time and switch the effect on: the receiving side shows a grayscale camera with the watermark in full color on top. The watermark pass runs after your shader, so its pixels are drawn as-is.
## Complete example
The final `cameraEffect.ts`, top to bottom. In `App.tsx`, the Quick Start app gets only `EffectButton` from [Step 2](#step-2-route-the-camera-through-webgpu), rendered above your own video:
```ts title='cameraEffect.ts'
///
// ---cut---
createCameraFrameProcessorSession,
createCameraShaderBindings,
getCameraWebGpuDevice,
getOutputSurfaceFormat,
type CameraFrameKernel,
} from "@fishjam-cloud/video-effects/fishjam-react-native";
// --- Watermark: a textured quad blended over the camera ---
const watermarkAsset = Asset.fromModule(require("./assets/watermark.png"));
async function loadWatermarkBitmap(): Promise {
// Android release builds keep bundled images as drawable resources, which `File` can't
// open. An asset described without the image size is copied to a local file instead.
const asset = new Asset({
name: watermarkAsset.name,
type: watermarkAsset.type,
hash: watermarkAsset.hash,
uri: watermarkAsset.uri,
});
await asset.downloadAsync();
if (!asset.localUri) {
throw new Error("The watermark image is not available.");
}
const bytes = await new File(asset.localUri).arrayBuffer();
return createImageBitmap(bytes);
}
const watermarkBindingDeclarations = /* wgsl */ `
@group(0) @binding(0) var watermarkTexture: texture_2d;
@group(0) @binding(1) var watermarkSampler: sampler;
`;
const sampleWatermark = tgpu.fn(
[d.vec2f],
d.vec4f,
)(/* wgsl */ `(uv: vec2f) -> vec4f {
return textureSample(watermarkTexture, watermarkSampler, uv);
}`);
function makeWatermarkVertexMain(rect: {
x0: number;
y0: number;
x1: number;
y1: number;
}) {
const { x0, y0, x1, y1 } = rect;
return tgpu
.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [
d.vec2f(x0, y0),
d.vec2f(x1, y0),
d.vec2f(x0, y1),
d.vec2f(x1, y1),
];
const uvs = [d.vec2f(0, 1), d.vec2f(1, 1), d.vec2f(0, 0), d.vec2f(1, 0)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: uvs[input.vertexIndex],
};
})
.$name("vertexMain");
}
const watermarkFragmentMain = tgpu
.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => sampleWatermark(input.uv))
.$name("fragmentMain");
function createWatermarkPipeline(
device: GPUDevice,
bitmap: ImageBitmap,
outputWidth: number,
outputHeight: number,
) {
const texture = device.createTexture({
size: [bitmap.width, bitmap.height],
format: "rgba8unorm",
usage:
GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST |
GPUTextureUsage.RENDER_ATTACHMENT,
});
device.queue.copyExternalImageToTexture({ source: bitmap }, { texture }, [
bitmap.width,
bitmap.height,
]);
const widthPx = outputWidth * 0.4;
const heightPx = widthPx * (bitmap.height / bitmap.width);
const marginPx = 24;
const x1 = 1 - (2 * marginPx) / outputWidth;
const x0 = x1 - (2 * widthPx) / outputWidth;
const y0 = -1 + (2 * marginPx) / outputHeight;
const y1 = y0 + (2 * heightPx) / outputHeight;
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
],
});
const module = device.createShaderModule({
code:
watermarkBindingDeclarations +
tgpu.resolve([
makeWatermarkVertexMain({ x0, y0, x1, y1 }),
watermarkFragmentMain,
]),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [
{
format: getOutputSurfaceFormat(),
blend: {
color: {
srcFactor: "src-alpha",
dstFactor: "one-minus-src-alpha",
operation: "add",
},
alpha: {
srcFactor: "one",
dstFactor: "one-minus-src-alpha",
operation: "add",
},
},
},
],
},
primitive: { topology: "triangle-strip" },
});
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{ binding: 0, resource: texture.createView() },
{
binding: 1,
resource: device.createSampler({
magFilter: "linear",
minFilter: "linear",
}),
},
],
});
return { pipeline, bindGroup };
}
// --- Grayscale: your own shader instead of the passthrough ---
const vertexMain = tgpu.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: d.vec2f((p.x + 1) * 0.5, 1 - (p.y + 1) * 0.5),
};
});
function createGrayscaleEffect(device: GPUDevice) {
const cameraBindings = createCameraShaderBindings(device, {
cameraPixelLayout: "rgb",
});
const fragmentMain = tgpu.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => {
const color = cameraBindings.sampleCamera(input.uv);
const gray = dot(color.xyz, d.vec3f(0.299, 0.587, 0.114));
return d.vec4f(gray, gray, gray, 1);
});
const module = device.createShaderModule({
code:
cameraBindings.bindingDeclarations +
tgpu.resolve([vertexMain, fragmentMain]),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [cameraBindings.bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [{ format: getOutputSurfaceFormat() }],
},
});
return { cameraBindings, pipeline };
}
// --- The camera middleware ---
export const cameraEffect: TrackMiddleware = async (track) => {
const device = await getCameraWebGpuDevice();
const grayscale = createGrayscaleEffect(device);
const bitmap = await loadWatermarkBitmap();
const watermark = createWatermarkPipeline(device, bitmap, 720, 1280);
await device.queue.onSubmittedWorkDone();
const frameKernel: CameraFrameKernel = (frame, render) => {
"worklet";
render((context) => {
const pass = context.commandEncoder.beginRenderPass({
colorAttachments: [
{ view: context.outputView, loadOp: "clear", storeOp: "store" },
],
});
pass.setPipeline(grayscale.pipeline);
pass.setBindGroup(0, context.cameraBindGroup!);
pass.draw(3);
pass.end();
const overlay = context.commandEncoder.beginRenderPass({
colorAttachments: [
{ view: context.outputView, loadOp: "load", storeOp: "store" },
],
});
overlay.setPipeline(watermark.pipeline);
overlay.setBindGroup(0, watermark.bindGroup);
overlay.draw(4);
overlay.end();
});
};
const session = await createCameraFrameProcessorSession({
track,
device,
width: 720,
height: 1280,
cameraShaderBindings: grayscale.cameraBindings,
frameKernel,
});
return { track: session.track, onClear: () => void session.dispose() };
};
```
## Next steps
- See the [WebGPU effects how-to](../how-to/client/camera-effects/webgpu-effects) for the rules inside the frame kernel, platform notes and aspect ratio helpers
- Use ready-made [background blur or a background image](../how-to/client/camera-effects/background-effects.mdx) next to your own effects
- Learn [how camera effects work](../explanation/camera-effects.mdx) under the hood
- API reference: [Video Effects package](../api/video-effects/index.md)
---
## Audio-only Conferences and Livestreams
In many use cases, you only need real-time audio, without any video streaming.
If your use case falls into this category, then you can benefit greatly from using audio-only rooms in Fishjam.
## Why Should I Care?
Audio-only rooms are heavily discounted compared to normal rooms.
As described in more detail on the [pricing page](https://fishjam.io/#pricing), Fishjam rooms are priced based on the total connection time of peers in them.
Audio-only rooms come at a **75% discount** for both conferencing and livestreaming.
### Conferencing
For conferencing, the base price is $1 per 1000 participant minutes.
For example, if you have a normal room with 10 peers connected for 100 minutes, then the total cost of the room will be $1.
If the same room were audio-only, the final cost of the room would only be $0.25.
### Livestreaming
For livestreaming, the base price is $0.8 per 1000 minutes of streamer and each viewer.
In a livestream with 1 streamer and 9999 viewers, all connected for 100 minutes, the total connection time is 10,000 minutes.
For a normal livestream, this would cost $8.00.
If the same room were audio-only, the final cost would only be $2.00.
## How Do I Use It?
Using this feature is as easy as setting the `roomType` field when creating a room using our [Server SDKs](./server-setup).
:::info
Attempting to stream a video while connected to an `audio_only` or `audio_only_livestream` room will result in only the audio being sent to the other peers.
:::
### Conferencing
Set `roomType` to `audio_only` when creating a room:
```ts
const fishjamClient = new FishjamClient({
fishjamId: "aaa",
managementToken: "bbb",
});
// ---cut---
const audioOnlyRoom = await fishjamClient.createRoom({ roomType: 'audio_only' });
```
```python
options = RoomOptions(room_type="audio_only")
audio_only_room = fishjam_client.create_room(options)
```
Now, you can connect peers normally to the room as described in our [React & React Native connecting guide](../client/connecting).
### Livestreaming
Set `roomType` to `audio_only_livestream` when creating a room:
```ts
const fishjamClient = new FishjamClient({
fishjamId: "aaa",
managementToken: "bbb",
});
// ---cut---
const audioOnlyRoom = await fishjamClient.createRoom({ roomType: 'audio_only_livestream' });
```
```python
options = RoomOptions(room_type="audio_only_livestream")
audio_only_room = fishjam_client.create_room(options)
```
Refer to our [Livestreaming tutorial](../../tutorials/livestreaming.mdx) to learn how to connect streamers and viewers.
:::info
The React Native and React SDKs will log a warning in the console if any attempt to add video to an audio-only room is made.
This aims to assist in debugging, as adding video to an audio-only room has no effect and is most likely a mistake.
:::
---
## FastAPI
# FastAPI example
The example assumes you've already installed [**our SDK**](https://github.com/fishjam-cloud/python-server-sdk) and you're ready to go.
If you wish to see more general info, visit [**Set up your server**](../../how-to/backend/server-setup) article.
## Minimal setup
The same way as in the [**FastAPI docs**](https://fastapi.tiangolo.com/tutorial/first-steps/), the code below can be copied and run immediately.
Just make sure you set `FISHJAM_ID` and `FISHJAM_MANAGEMENT_TOKEN` environment variables.
The `Depends` function allows the `FishjamClient` to be provided to the route function as a dependency, which avoids code duplication and allows easy mocking.
```python
from typing import Annotated
from fastapi import Depends, FastAPI
from fishjam import FishjamClient
app = FastAPI()
def fishjam_client():
fishjam_id = os.environ["FISHJAM_ID"]
management_token = os.environ["FISHJAM_MANAGEMENT_TOKEN"]
return FishjamClient(fishjam_id=fishjam_id, management_token=management_token)
@app.get("/")
async def get_rooms(fishjam_client: Annotated[FishjamClient, Depends(fishjam_client)]):
rooms = fishjam_client.get_all_rooms()
return {"rooms": rooms}
```
## Listening to events
Fishjam emits messages upon certain events — see [Listening to events](../../how-to/backend/server-setup#listening-to-events) for how delivery, batching, and signing work.
### Webhooks
Create a dependency function that [verifies the webhook signature](../../how-to/backend/server-setup#verifying-webhook-signatures) and decodes the request body into notifications, then use pattern matching to respond to different kinds of events.
:::note
`decode_server_notifications` replaces the now-deprecated `receive_binary`.
:::
```python
from fastapi import Depends, FastAPI, HTTPException, Request
from fishjam import decode_server_notifications, verify_webhook_signature
from fishjam.events import ServerMessagePeerAdded
app = FastAPI()
async def parse_fishjam_notifications(request: Request):
binary = await request.body()
signature = request.headers.get("x-fishjam-signature-256", "")
if not verify_webhook_signature(binary, signature, os.environ["FISHJAM_WEBHOOK_SECRET"]):
raise HTTPException(status_code=401, detail="Invalid webhook signature")
return decode_server_notifications(binary)
@app.post("/fishjam-webhook")
async def fishjam_webhook(notifications = Depends(parse_fishjam_notifications)):
for notification in notifications:
match notification:
case ServerMessagePeerAdded():
print(f"Peer added: {notification.peer_id}")
case _:
...
```
### SDK Notifier
Use the `asyncio` library to run the SDK notifier.
It doesn't interact with the FastAPI library per se, just start the event loop and it will run alongside the server.
```python
from fishjam import FishjamNotifier
from fishjam.events import ServerMessagePeerAdded
notifier = FishjamNotifier(fishjam_id=fishjam_id, management_token=management_token)
@notifier.on_server_notification
def handle_notification(notification):
match notification:
case ServerMessagePeerAdded():
print(f"Peer added: {notification.peer_id}")
case _:
...
async def run_notifier():
notifier_task = asyncio.create_task(notifier.connect())
# Wait for the notifier to be ready to receive messages
await notifier.wait_ready()
await notifier_task
asyncio.run(run_notifier())
```
---
## Fastify
# Fastify example
The example assumes you've already installed [**our SDK**](https://www.npmjs.com/package/@fishjam-cloud/js-server-sdk) and you're ready to go.
If you wish to see more general info, visit [**set up your server**](../../how-to/backend/server-setup) article.
## Load environment variables to Fastify
Use [`@fastify/env` package](https://github.com/fastify/fastify-env) to load and set environment variables in your Fastify instance.
```ts title='main.ts'
const fastify = Fastify();
const envSchema = {
type: "object",
required: ["FISHJAM_ID", "FISHJAM_MANAGEMENT_TOKEN"],
properties: {
FISHJAM_ID: {
type: "string",
},
FISHJAM_MANAGEMENT_TOKEN: {
type: "string",
},
},
};
await fastify.register(fastifyEnv, { schema: envSchema });
fastify.listen({ port: 3000 });
```
## Setup Fishjam Fastify plugin
Fastify allows you to create plugins to encapsulate functionality in scopes.
Check out [fastify documentation](https://fastify.dev/docs/latest/Reference/Plugins) for a deeper understanding of the concept.
First, extend the `FastifyInstance` interface with `fishjam` entry.
This will provide types of FishjamClient wherever you access `fastify.fishjam` in the codebase.
Then, declare the plugin by invoking the `fp` function with the setup function with as an argument.
```ts title='fishjamPlugin.ts'
declare module "fastify" {
interface FastifyInstance {
fishjam: FishjamClient;
config: {
FISHJAM_ID: string;
FISHJAM_MANAGEMENT_TOKEN: string;
};
}
}
export const fishjamPlugin = fastifyPlugin((fastify) => {
const fishjamClient = new FishjamClient({
fishjamId: fastify.config.FISHJAM_ID,
managementToken: fastify.config.FISHJAM_MANAGEMENT_TOKEN,
});
fastify.decorate("fishjam", fishjamClient);
});
```
Now, after registering the plugin, we will be able to use Fishjam client by accessing the `fastify.fishjam` property.
```ts title='main.ts'
declare module "fastify" {
interface FastifyInstance {
fishjam: FishjamClient;
config: {
FISHJAM_ID: string;
FISHJAM_MANAGEMENT_TOKEN: string;
};
}
}
export const fishjamPlugin = fastifyPlugin((fastify) => {
const fishjamClient = new FishjamClient({
fishjamId: fastify.config.FISHJAM_ID,
managementToken: fastify.config.FISHJAM_MANAGEMENT_TOKEN,
});
fastify.decorate("fishjam", fishjamClient);
});
const fastify = Fastify();
// ---cut---
await fastify.register(fishjamPlugin);
fastify.get("/rooms", () => fastify.fishjam.getAllRooms());
fastify.listen({ port: 3000 });
```
## Listening to events
Fishjam emits messages upon certain events — see [Listening to events](../../how-to/backend/server-setup#listening-to-events) for how delivery, batching, and signing work.
### Webhooks
Add a content type parser to your global (or scoped) Fastify instance that [verifies the webhook signature](../../how-to/backend/server-setup#verifying-webhook-signatures) and decodes the body into typed notifications.
You can then iterate over the parsed notifications at `request.body`.
```ts title='main.ts'
decodeServerNotifications,
verifyWebhookSignature,
ServerNotification,
} from "@fishjam-cloud/js-server-sdk";
const fastify = Fastify();
fastify.addContentTypeParser(
"application/x-protobuf",
{ parseAs: "buffer" },
async (request: FastifyRequest, body: Buffer) => {
const signature = request.headers["x-fishjam-signature-256"];
if (
typeof signature !== "string" ||
!verifyWebhookSignature(
body,
signature,
process.env.FISHJAM_WEBHOOK_SECRET!,
)
) {
throw Object.assign(new Error("Invalid webhook signature"), {
statusCode: 401,
});
}
return decodeServerNotifications(body);
},
);
fastify.post<{ Body: ServerNotification[] }>("/fishjam-webhook", (request) => {
// handle each notification
for (const { type, notification } of request.body) {
console.log(type, notification);
}
});
```
### SDK Notifier
You can also leverage the Fastify plugin mechanism to use websockets to receive messages from Fishjam.
Let's create another plugin in `fishjamNotifierPlugin.ts` file.
In this case, we don't need to extend the Fastify instance type, because the plugin doesn't decorate the Fastify instance with any properties. It will work in the background.
```ts title='fishjamNotifierPlugin.ts'
declare module "fastify" {
interface FastifyInstance {
fishjam: FishjamClient;
config: {
FISHJAM_ID: string;
FISHJAM_MANAGEMENT_TOKEN: string;
};
}
}
export const fishjamPlugin = fastifyPlugin((fastify) => {
const fishjamClient = new FishjamClient({
fishjamId: fastify.config.FISHJAM_ID,
managementToken: fastify.config.FISHJAM_MANAGEMENT_TOKEN,
});
fastify.decorate("fishjam", fishjamClient);
});
const fastify = Fastify();
// ---cut---
export const fishjamNotifierPlugin = fp((fastify) => {
const fishjamId = fastify.config.FISHJAM_ID;
const managementToken = fastify.config.FISHJAM_MANAGEMENT_TOKEN;
const fishjamNotifier = new FishjamWSNotifier(
{ fishjamId, managementToken },
(err) => fastify.log.error(err),
() => fastify.log.info("Websocket connection to Fishjam closed"),
);
// handle the messages
const handleRoomCreated = console.log;
const handlePeerAdded = console.log;
fishjamNotifier.on("roomCreated", handleRoomCreated);
fishjamNotifier.on("peerAdded", handlePeerAdded);
});
```
Don't forget to register your plugin.
```ts title='main.ts'
declare module "fastify" {
interface FastifyInstance {
fishjam: FishjamClient;
config: {
FISHJAM_ID: string;
FISHJAM_MANAGEMENT_TOKEN: string;
};
}
}
export const fishjamPlugin = fastifyPlugin((fastify) => {
const fishjamClient = new FishjamClient({
fishjamId: "aaa",
managementToken: "bbb",
});
fastify.decorate("fishjam", fishjamClient);
});
const fastify = Fastify();
const fishjamNotifierPlugin = fastifyPlugin((fastify) => {
const fishjamNotifier = new FishjamWSNotifier(
{ fishjamId: "aaa", managementToken: "bbb" },
(err) => fastify.log.error(err),
(_code, _reason) =>
fastify.log.info("Websocket connection to Fishjam closed"),
);
});
// ---cut---
await fastify.register(fishjamPlugin);
await fastify.register(fishjamNotifierPlugin);
```
---
## How to Deploy Fishjam to Production
**How-to Guide** - _Deploy your Fishjam backend safely to production_
This guide covers the essential steps to move from development (using the Sandbox API) to a production-ready Fishjam backend deployment.
## Prerequisites
- Working Fishjam backend (see [Backend Quick Start](../../tutorials/backend-quick-start))
- A Fishjam account on the **Standard Jar** plan (recommended for production deployments)
- Domain and SSL certificates for your backend
- Production database and infrastructure
## Step 1: Get your Fishjam credentials
### Get credentials from the dashboard
1. Log in to [Fishjam Dashboard](https://fishjam.io/app)
2. Copy your **Fishjam ID** and **Management Token** from the dashboard
### Environment variables setup
Create your environment variables:
```bash
# Fishjam credentials
FISHJAM_ID="your-fishjam-id"
FISHJAM_MANAGEMENT_TOKEN="your-management-token"
# Your application settings
NODE_ENV="production"
PORT="3000"
DATABASE_URL="your-production-database-url"
# Security settings
JWT_SECRET="your-secure-jwt-secret"
CORS_ORIGIN="https://yourdomain.com"
```
## Step 2: Replace Sandbox API with proper authentication
### Replace Sandbox API calls
Remove any Sandbox API dependencies from your client code:
```typescript
// @noErrors: 2451
const authenticateUser = {} as any;
const app = express();
const sandboxApiUrl = "your-sandbox-api-url-here";
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl });
const userToken = "";
const roomName = "";
const userName = "";
// ---cut---
// ❌ Remove: Sandbox API calls
const peerToken = await getSandboxPeerToken(roomName, userName);
// ✅ Replace with: Your authenticated API
const response = await fetch("https://your-backend.com/api/join-room", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${userToken}`,
},
body: JSON.stringify({ roomName, userName }),
});
```
### Implement user authentication
Wire up the Fishjam client and your own authentication. The middleware below verifies the caller and attaches the user, so the next handler can mint a peer token for them.
```typescript
// @noErrors: 2339
const jwt = {} as any;
process.env.FISHJAM_ID = "";
process.env.FISHJAM_MANAGEMENT_TOKEN = "";
process.env.JWT_SECRET = "";
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!,
});
const app = express();
app.use(express.json()); // parse JSON request bodies
// Your own auth (JWT, session, ...)
const authenticateUser = async (
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) return res.status(401).json({ error: "Unauthorized" });
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
};
```
```python
from fastapi import Body, Depends, FastAPI, Header, HTTPException
from fishjam import FishjamClient, PeerOptions
app = FastAPI()
fishjam_client = FishjamClient(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["FISHJAM_MANAGEMENT_TOKEN"],
)
# Your own auth (JWT, session, ...)
async def authenticate_user(authorization: str = Header()):
token = authorization.removeprefix("Bearer ")
try:
return jwt.decode(token, os.environ["JWT_SECRET"], algorithms=["HS256"])
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Unauthorized")
```
### Create a room and add a peer
Now expose the endpoint your client calls to join the room. Fishjam rooms are identified by an `id`, so keep a mapping from your own room name to the Fishjam room id and create the room lazily on first join. Then add a peer tagged with the authenticated user and return its peer token.
```typescript
// @noErrors: 2339
const app = express();
declare const fishjamClient: FishjamClient;
declare const authenticateUser: express.RequestHandler;
// ---cut---
// Map your room name to a Fishjam room id (use your database in production)
const roomIds = new Map();
const getOrCreateRoom = async (roomName: string): Promise => {
const existing = roomIds.get(roomName);
if (existing) return existing;
const room = await fishjamClient.createRoom();
roomIds.set(roomName, room.id);
return room.id;
};
// Mint a Fishjam peer token for the authenticated user
app.post("/api/join-room", authenticateUser, async (req, res) => {
const { roomName } = req.body;
const roomId = await getOrCreateRoom(roomName);
const { peerToken } = await fishjamClient.createPeer(roomId, {
metadata: { userId: req.user.userId },
});
res.json({ peerToken });
});
```
```python
# Map your room name to a Fishjam room id (use your database in production)
room_ids: dict[str, str] = {}
def get_or_create_room(room_name: str) -> str:
room_id = room_ids.get(room_name)
if room_id is not None:
return room_id
room = fishjam_client.create_room()
room_ids[room_name] = room.id
return room.id
# Mint a Fishjam peer token for the authenticated user
@app.post("/api/join-room")
async def join_room(room_name: str = Body(embed=True), user=Depends(authenticate_user)):
room_id = get_or_create_room(room_name)
options = PeerOptions(metadata={"userId": user["userId"]})
_, peer_token = fishjam_client.create_peer(room_id, options)
return {"peerToken": peer_token}
```
## (Optional) Step 3: Handle webhooks and events
You may wish to receive events from Fishjam regarding created rooms and peers.
All you need for this is a single api endpoint:
### Webhook endpoint
Fishjam delivers notifications as a binary `application/x-protobuf` body. Read the raw body, [verify the webhook signature](../../how-to/backend/server-setup#verifying-webhook-signatures), and decode it with the SDK, then react to the events you care about. Store your webhook secret as `FISHJAM_WEBHOOK_SECRET`.
```typescript
decodeServerNotifications,
verifyWebhookSignature,
} from "@fishjam-cloud/js-server-sdk";
const app = express();
const handlePeerConnected = {} as any;
const handlePeerDisconnected = {} as any;
const handleRoomDeleted = {} as any;
// ---cut---
app.post(
"/api/webhooks/fishjam",
express.raw({ type: "application/x-protobuf" }),
(req: express.Request, res: express.Response) => {
const signature = req.headers["x-fishjam-signature-256"];
if (
typeof signature !== "string" ||
!verifyWebhookSignature(
req.body,
signature,
process.env.FISHJAM_WEBHOOK_SECRET!,
)
) {
return res.status(401).json({ error: "Invalid signature" });
}
for (const { type, notification } of decodeServerNotifications(req.body)) {
switch (type) {
case "peerConnected":
handlePeerConnected(notification);
break;
case "peerDisconnected":
handlePeerDisconnected(notification);
break;
case "roomDeleted":
handleRoomDeleted(notification);
break;
default:
break;
}
}
res.status(200).json({ received: true });
},
);
```
```python
from fastapi import FastAPI, HTTPException, Request
from fishjam import decode_server_notifications, verify_webhook_signature
from fishjam.events import (
ServerMessagePeerConnected,
ServerMessagePeerDisconnected,
ServerMessageRoomDeleted,
)
app = FastAPI()
@app.post("/api/webhooks/fishjam")
async def fishjam_webhook(request: Request):
raw_body = await request.body()
signature = request.headers.get("x-fishjam-signature-256", "")
if not verify_webhook_signature(raw_body, signature, os.environ["FISHJAM_WEBHOOK_SECRET"]):
raise HTTPException(status_code=401, detail="Invalid signature")
for notification in decode_server_notifications(raw_body):
match notification:
case ServerMessagePeerConnected():
handle_peer_connected(notification)
case ServerMessagePeerDisconnected():
handle_peer_disconnected(notification)
case ServerMessageRoomDeleted():
handle_room_deleted(notification)
case _:
...
return {"received": True}
```
### Enabling webhooks
Now, with your endpoint set up, register its URL in the **Webhooks** tab of the [Fishjam Dashboard](https://fishjam.io/app). Fishjam then delivers all notifications to that endpoint. We also recommend enabling [notification batching](../../how-to/backend/server-setup#webhooks) when creating rooms:
```typescript
const fishjamClient = {} as any;
// ---cut---
const createBatchedRoom = async (roomType = "conference") => {
const room = await fishjamClient.createRoom({
roomType,
// Coalesce notifications into batches for faster delivery and fewer requests
batchWebhookNotifications: true,
});
return room;
};
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["FISHJAM_MANAGEMENT_TOKEN"],
)
def create_batched_room(room_type="conference"):
options = RoomOptions(
room_type=room_type,
# Coalesce notifications into batches for faster delivery and fewer requests
batch_webhook_notifications=True,
)
return fishjam_client.create_room(options)
```
## Common production issues
### Issue: Token expiration handling
Peer tokens expire 24h after creation.
We encourage keeping room and peer lifetimes as short as possible
(typically a single room corresponds to a single video call or stream).
However, if you wish to reuse a single peer over multiple days, you can make use of token refreshing:
```ts
const fishjamClient = new FishjamClient({
fishjamId: "",
managementToken: "",
});
const roomId = "" as RoomId;
const peerId = "" as PeerId;
// ---cut---
const newToken = fishjamClient.refreshPeerToken(roomId, peerId);
```
```python
new_token = fishjam_client.refresh_peer_token(room_id, peer_id)
```
## See also
For scaling considerations:
- [Understanding Fishjam Architecture](../../explanation/architecture)
- [Security best practices](../../explanation/security-tokens)
For specific backend frameworks:
- [FastAPI example](../../how-to/backend/fastapi-example)
- [Fastify example](../../how-to/backend/fastify-example)
---
## Testing with the Sandbox API
The Sandbox API is a development tool that lets you create rooms and peers for testing without setting up your own backend server. This guide shows you how to use it effectively.
## Prerequisites
- Access to [Fishjam Dashboard](https://fishjam.io/app)
## Step 1: Get your Fishjam ID and Sandbox API URL
1. Log in to [Fishjam Dashboard](https://fishjam.io/app)
2. Navigate to the [Sandbox tab](https://fishjam.io/app/sandbox)
3. Copy your **Fishjam ID**
4. In the **Sandbox API** section, copy your **Sandbox API URL**
:::note
You need both values for React/React Native apps:
- `Sandbox API url` is used to call the Sandbox API to create test rooms and return peer tokens.
- `Fishjam ID` is passed to `FishjamProvider` so the client can connect to the Fishjam media server after it gets a peer token.
:::
## Step 2: Create a room and get peer tokens
### With the `useSandbox` hook
```ts
const FISHJAM_ID = "...";
const roomName = "testRoom";
const peerName = "testUser";
// ---cut---
// ...
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const peerToken = await getSandboxPeerToken(roomName, peerName);
```
```ts
const roomName = "testRoom";
const peerName = "testUser";
// ---cut---
// ...
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const peerToken = await getSandboxPeerToken(roomName, peerName);
```
### Required parameters
- `roomName` - Name of the room to create/join
- `peerName` - Name for the peer joining the room
### Optional parameters
- `roomType` - Type of room to create (defaults to `conference`)
- `videoCodec` - Video codec of the room: `vp8` (default) or `h264`. Accepted by both the peer and the livestream endpoints. Joining an existing room with a different codec returns `409 Conflict`; omit it to join a room regardless of its codec.
```bash
curl "$SANDBOX_API_URL?roomName=testRoom&peerName=testUser&videoCodec=h264"
```
### Room types available
- `conference` - For video/audio conferencing (default)
- `audio_only` - For audio-only conferencing
- `livestream` - For one-to-many video/audio streaming
## Step 3: Handle the response
The Sandbox API returns a JSON response with connection details:
```json
{
"peerToken": "",
"room": {
"id": "",
"name": "foo"
},
"peer": {
"id": "",
"name": "bar"
}
}
```
## Step 4: Use the tokens in your client app
Below are examples on how to use tokens from the Sandbox API in your frontend applications:
```tsx
const roomName = "testRoom";
const peerName = `user_${Date.now()}`;
const FISHJAM_ID = "...";
const SANDBOX_API_URL = "...";
const RoomView = (props: {peerToken: string}) => null;
// ---cut---
export default function TestScreen() {
const [peerToken, setPeerToken] = useState(null);
// fishjamId is provided through FishjamProvider
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
useEffect(() => {
const fetchPeerToken = async () => {
try {
const token = await getSandboxPeerToken(roomName, peerName);
setPeerToken(token);
} catch (error) {
console.error("Failed to create room:", error);
}
};
fetchPeerToken();
}, []);
if (!peerToken) {
return Creating room... ;
}
return (
);
}
```
```tsx
const FISHJAM_ID = "your-fishjam-id-here";
const SANDBOX_API_URL = "your-sandbox-api-url-here";
// ---cut---
function VideoCallComponent() {
const { joinRoom, peerStatus } = useConnection();
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const handleJoinRoom = async () => {
const roomName = "testRoom";
const peerName = `user_${Date.now()}`;
try {
const peerToken = await getSandboxPeerToken(roomName, peerName)
await joinRoom({ peerToken });
} catch (error) {
console.error("Failed to join room:", error);
}
};
const isConnected = peerStatus === "connected";
return (
{isConnected ? Connected to room! : Join Room }
);
}
export default function App() {
return (
);
}
```
## Step 5: Test different room types
### Testing audio-only rooms
```ts
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
// ---cut---
const audioOnlyPeerToken = await getSandboxPeerToken(
"audioTest",
"user1",
"audio_only",
);
```
### Testing livestream rooms
```ts
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const { getSandboxLivestream, getSandboxViewerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
// ---cut---
const livestreamName = "livestream1";
// For the streamer
const streamerData = await getSandboxLivestream(livestreamName);
// For viewers, you need a viewer token (different endpoint)
const viewerToken = await getSandboxViewerToken(livestreamName);
```
## Step 6: Handle multiple peers
To test with multiple participants, create multiple peer tokens with different peer names:
```ts
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
// ---cut---
// First peer
const peer1Response = await getSandboxPeerToken("multiTest", "alice");
// Second peer
const peer2Response = await getSandboxPeerToken("multiTest", "bob");
```
Both peers will join the same room (`multiTest`) and can communicate with each other.
## Common testing patterns
### Pattern 1: Random room names for isolation
```ts
const roomName = `test_${Math.random().toString(36).substring(7)}`;
const peerName = `user_${Date.now()}`;
```
### Pattern 2: Consistent naming for repeated tests
```ts
// @noErrors: 2451
const roomName = "development-room";
const peerName = `developer_1`;
```
### Pattern 3: Feature-specific room names
```ts
// @noErrors: 2451
const roomName = `screenshare-test-${Date.now()}`;
const roomName = `audio-only-test`;
const roomName = `livestream-demo`;
```
## Troubleshooting
### Issue: Room not found errors
**Problem**: Rooms might not persist between requests.
**Solution**: Always create rooms fresh for each test session.
### Issue: Connection failures
**Problem**: Invalid Fishjam ID, invalid Sandbox API URL, disabled Sandbox API, or network issues.
**Solution**:
1. Verify your Fishjam ID in the Fishjam Dashboard.
2. Verify your Sandbox API URL in the [Sandbox tab](https://fishjam.io/app/sandbox).
3. Make sure the Sandbox API is enabled.
4. Check network connectivity.
## Security reminder
:::danger
**The Sandbox API is not safe for production!**
- No authentication required
- Anyone with your Sandbox API URL can create rooms and peer tokens
- Identical room/peer names get the same tokens
- No rate limiting or abuse protection
Only use the Sandbox API for development and testing.
:::
## Managing your Sandbox API
Manage the Sandbox API from the [Sandbox tab](https://fishjam.io/app/sandbox):
- If your Sandbox API URL is exposed or credentials are compromised, click **Generate new URL**. This invalidates the old URL.
- If you want to stop using it, click **Disable Sandbox API**.
- When you want to use it again, click **Enable Sandbox API**.
Your `FISHJAM_ID` is still required by `FishjamProvider` to connect to the Fishjam media server. The Sandbox API URL is only used to request test room and peer tokens.
## Next steps
Once you've tested your integration with the Sandbox API:
- [Set up your own backend](../../tutorials/backend-quick-start)
- [Learn more about the Sandbox API](../../explanation/sandbox-api-concept)
- [Understand security implications](../../explanation/security-tokens)
For production deployment:
- [How to set up a production server](./server-setup)
- [How to implement proper authentication](../../explanation/security-tokens)
---
## Selective Subscriptions
In Fishjam, peers in a conferencing room automatically subscribe to every other peer by default.
Selective Subscriptions let you break from that — giving your backend the ability to decide who receives what.
In **manual subscription mode**, a peer or agent:
- does not automatically receive **any tracks**, and
- can **explicitly subscribe** to specific tracks from other peers.
## When to use Selective Subscriptions
- large-scale rooms with dozens or hundreds of peers,
- “stage & audience” models (viewers only see speakers),
- bandwidth optimization (e.g., audio-only dashboards, or delayed video activation).
---
## Core idea
- Peers have a `subscribeMode` — either **`auto`** or **`manual`**.
- Peers in **auto** mode subscribe to everyone automatically (default behavior).
- Peers in **manual** mode will **not** receive any media until you explicitly subscribe them using the **Server SDK**.
- Peers in manual mode can subscribe to:
- another **peer** (all of its tracks), or
- specific **tracks** of another peer.
---
## Step 1 — Create a peer with `manual` subscription mode
When creating a peer, set `subscribeMode` to `"manual"`.
This peer will start with zero subscriptions — it will not receive anyone’s audio or video.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
// ---cut---
// Create a conference room
const room = await fishjamClient.createRoom({
roomType: "conference",
});
// Create a normal publisher
const { peer: publisher } = await fishjamClient.createPeer(room.id, {
subscribeMode: "auto",
});
// Create a manual subscriber
const { peer: viewer } = await fishjamClient.createPeer(room.id, {
subscribeMode: "manual",
});
```
from fishjam import RoomOptions, PeerOptions
```python
room_options = RoomOptions(room_type="conference")
room = fishjam_client.create_room(room_options)
# Create a manual subscriber
peer_options = PeerOptions(subscribe_mode="manual")
publisher = fishjam_client.create_peer(room.id, peer_options)
viewer = fishjam_client.create_peer(room.id, peer_options)
```
---
## Step 2 — Subscribe a peer to another peer
Use this when you want your manual subscriber to receive **all tracks** published by another peer.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
const room = await fishjamClient.createRoom({
roomType: "conference",
});
const { peer: publisher } = await fishjamClient.createPeer(room.id, {
subscribeMode: "auto",
});
const { peer: subscriber } = await fishjamClient.createPeer(room.id, {
subscribeMode: "manual",
});
// ---cut---
// Subscribe viewer to everything published by publisher
await fishjamClient.subscribePeer(room.id, subscriber.id, publisher.id);
```
```python
fishjam_client.subscribe_peer(room.id, viewer_id, publisher_id)
```
This will make **every current and future track** of the publisher available to the subscriber.
It’s additive — the subscriber can listen to multiple publishers at once.
---
## Step 3 — Subscribe to specific tracks
Sometimes you only want a subset of a publisher’s tracks, for example:
- their **screenshare**, but not their camera,
- only **audio**, without video.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
const room = await fishjamClient.createRoom({
roomType: "conference",
});
const { peer: publisher } = await fishjamClient.createPeer(room.id, {
subscribeMode: "auto",
});
const { peer: subscriber } = await fishjamClient.createPeer(room.id, {
subscribeMode: "manual",
});
// ---cut---
// Get track IDs from your room state or webhook events
const audioTrackId = "track_audio_abc" as TrackId;
const screenTrackId = "track_screen_xyz" as TrackId;
// Subscribe to a single track
await fishjamClient.subscribeTracks(room.id, subscriber.id, [audioTrackId]);
// Or multiple
await fishjamClient.subscribeTracks(room.id, subscriber.id, [
audioTrackId,
screenTrackId,
]);
```
```python
audio_track_id = "track_audio_abc"
screen_track_id = "track_screen_xyz"
# Subscribe to one track
fishjam_client.subscribe_tracks(room.id, subscriber_id, [audio_track_id])
# Or multiple
fishjam_client.subscribe_tracks(room.id, subscriber_id, [audio_track_id, screen_track_id])
```
:::note
📘 Track IDs are available from [Fishjam’s events in your backend](/how-to/backend/server-setup#listening-to-events).
:::
---
## Step 4 — Combine multiple publishers
A manual peer can subscribe to **several** publishers at once.
Each call to `subscribePeer` adds more publishers — it doesn’t overwrite the previous ones.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
const room = await fishjamClient.createRoom({
roomType: "conference",
});
// ---cut---
const options = { subscribeMode: "manual" } satisfies PeerOptions;
const { peer: subscriber } = await fishjamClient.createPeer(room.id, options);
const { peer: publisherA } = await fishjamClient.createPeer(room.id, options);
const { peer: publisherB } = await fishjamClient.createPeer(room.id, options);
// Subscribe subscriber to two publishers
await fishjamClient.subscribePeer(room.id, subscriber.id, publisherA.id);
await fishjamClient.subscribePeer(room.id, subscriber.id, publisherB.id);
```
```python
fishjam_client.subscribe_peer(room.id, subscriber_id, publisher_a_id)
fishjam_client.subscribe_peer(room.id, subscriber_id, publisher_b_id)
```
The subscriber now receives tracks from **both** publishers simultaneously.
---
## Step 5 — Example: curated stage & audience
You can implement a “stage” system where:
- speakers are in auto mode (they see/hear each other),
- audience members are manual subscribers (they only see the stage).
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
const room = await fishjamClient.createRoom({
roomType: "conference",
});
const { peer: publisher } = await fishjamClient.createPeer(room.id, {
subscribeMode: "auto",
});
// ---cut---
// fetch room to get actual list of peers
const fetchedRoom = await fishjamClient.getRoom(room.id);
const currentSpeakers = fetchedRoom.peers;
// audience joins in manual mode
const { peer: audience } = await fishjamClient.createPeer(room.id, {
subscribeMode: "manual",
});
// subscribe them to all current speakers
await Promise.all(
currentSpeakers.map((speaker) =>
fishjamClient.subscribePeer(room.id, audience.id, speaker.id),
),
);
```
```python
audience = fishjam_client.create_peer(room.id, PeerOptions(subscribe_mode="manual"))
current_speakers = fishjam_client.get_room(room.id).peers
# audience peer already exists (manual)
for speaker in current_speakers:
fishjam_client.subscribe_peer(room.id, audience.id, speaker.id)
```
As new speakers join, simply call `subscribe_peer` again to add them to the audience’s feed.
---
:::note
Unsubscribe support is not yet implemented (for now, just remove peer sessions when needed).
:::
## See also
- [Rooms](../../explanation/rooms)
- [React quick start](../../tutorials/react-quick-start)
- [React Native quick start](../../tutorials/react-native-quick-start)
> 🗒️ For server-side recording or media processing, see [Agents](../../tutorials/agents.mdx) (documented separately).
---
## Set up your server
## Install the SDK
Install the SDK for the language of your choice. We provide libraries for [**Node**](https://github.com/fishjam-cloud/js-server-sdk) and [**Python**](https://github.com/fishjam-cloud/python-server-sdk).
It's also possible to use the bare REST API, in this case you can skip this step.
```bash
npm install @fishjam-cloud/js-server-sdk
```
```bash
yarn add @fishjam-cloud/js-server-sdk
```
```bash
pip install fishjam-server-sdk
```
```bash
poetry add fishjam-server-sdk
```
```bash
uv add fishjam-server-sdk
```
## Setup your client
Let's setup everything you need to start communicating with a Fishjam instance.
First of all, view your app in the [**Fishjam developer panel**](https://fishjam.io/app) and copy your **Fishjam ID** and the **Management Token**.
They are required to proceed. Now, we are ready to dive into the code.
`FishjamClient.create` constructs the client and pings the Fishjam backend with the supplied credentials, so a bad `fishjamId` or `managementToken` fails at startup instead of on the first room operation.
```ts
process.env.FISHJAM_ID = "aaa";
process.env.FISHJAM_MANAGEMENT_TOKEN = "bbb";
// ---cut---
let fishjamClient = await FishjamClient.create({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!,
});
// The above is roughly equivalent to:
fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN!,
});
await fishjamClient.checkCredentials();
```
```python
from fishjam import FishjamClient
fishjam_client = FishjamClient.create_and_verify(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["FISHJAM_MANAGEMENT_TOKEN"],
)
# The above is roughly equivalent to:
fishjam_client = FishjamClient(...)
fishjam_client.check_credentials()
```
### Managing rooms
Create a room to get the `roomId` and be able to start adding peers.
```ts
const fishjamClient = new FishjamClient({
fishjamId: "https://fishjam.io",
managementToken: "bbb",
});
// ---cut---
const createdRoom = await fishjamClient.createRoom();
const theSameRoom = await fishjamClient.getRoom(createdRoom.id);
await fishjamClient.deleteRoom(theSameRoom.id)
// puff, it's gone!
```
```python
created_room = fishjam_client.create_room()
the_same_room = fishjam_client.get_room(created_room.id)
fishjam_client.delete_room(the_same_room.id)
# puff, it's gone!
```
### Managing peers
Create a peer to obtain the peer token allowing your user to join the room.
At any time you can terminate user's access by deleting the peer.
```ts
const fishjamClient = new FishjamClient({
fishjamId: "https://fishjam.io",
managementToken: "bbb",
});
const created_room = await fishjamClient.createRoom();
// ---cut---
const { peer, peerToken } = await fishjamClient.createPeer(created_room.id);
await fishjamClient.deletePeer(created_room.id, peer.id);
```
```python
peer, token = fishjam_client.create_peer(room_id)
fishjam_client.delete_peer(room_id, peer.id)
```
#### Metadata
When creating a peer, you can also assign metadata to that peer, which can be read later with the [client SDK](../../how-to/client/metadata). This metadata can be only set when creating the peer and can't be updated later.
```ts
const fishjamClient = new FishjamClient({
fishjamId: "https://fishjam.io",
managementToken: "bbb",
});
const created_room = await fishjamClient.createRoom();
// ---cut---
const { peer, peerToken } = await fishjamClient.createPeer(created_room.id, {
metadata: { realName: 'Tom Reeves' },
});
```
```py
options = PeerOptions(
metadata={"realName": "Tom Reeves"},
)
peer, token = self.fishjam_client.create_peer(room_id, options=options)
```
## Listening to events
Fishjam instance is a stateful server that is emitting messages upon certain events.
You can listen for those messages and react as you prefer.
There are two options to obtain these.
### Webhooks
Configure your webhook URL in the **Webhooks** tab of the [Fishjam Dashboard](https://fishjam.io/app). Fishjam then delivers all notifications to that URL.
We recommend also enabling **notification batching** when creating a room. Fishjam then coalesces several notifications into a single request, delivering them faster and with fewer HTTP requests — which improves your backend's response time under load.
```ts
const fishjamClient = new FishjamClient({
fishjamId: "https://fishjam.io",
managementToken: "bbb",
});
// ---cut---
await fishjamClient.createRoom({ batchWebhookNotifications: true });
```
```python
from fishjam import RoomOptions
options = RoomOptions(
batch_webhook_notifications=True,
)
fishjam_client.create_room(options)
```
On the receiving side, decode the raw request body with the SDK's decoder, then iterate the result and react to the events you care about. The decoder returns a list of notifications and transparently unwraps a batch — a single notification simply comes back as a one-element list, so the same handler works whether or not batching is enabled.
```ts
declare const rawBody: Buffer;
// ---cut---
for (const { type, notification } of decodeServerNotifications(rawBody)) {
switch (type) {
case 'peerConnected':
console.log(`Peer ${notification.peerId} joined room ${notification.roomId}`);
break;
case 'peerDisconnected':
console.log(`Peer ${notification.peerId} left room ${notification.roomId}`);
break;
case 'roomCreated':
console.log(`Room ${notification.roomId} created`);
break;
default:
break;
}
}
```
```python
from fishjam import decode_server_notifications
from fishjam.events import (
ServerMessagePeerConnected,
ServerMessagePeerDisconnected,
ServerMessageRoomCreated,
)
for notification in decode_server_notifications(raw_body):
match notification:
case ServerMessagePeerConnected():
print(f"Peer {notification.peer_id} joined room {notification.room_id}")
case ServerMessagePeerDisconnected():
print(f"Peer {notification.peer_id} left room {notification.room_id}")
case ServerMessageRoomCreated():
print(f"Room {notification.room_id} created")
case _:
...
```
#### Verifying webhook signatures
Every webhook request is signed so you can confirm it really came from Fishjam. Each delivery carries an `x-fishjam-signature-256: sha256=` header — an HMAC-SHA256 of the **raw request body**, keyed with your webhook secret. Find (and rotate) that secret in the **Webhooks** tab of the [Fishjam Dashboard](https://fishjam.io/app).
Verify the header against the raw body **before** decoding, and reject mismatches with `401`. Verification needs the exact bytes Fishjam sent, so read the raw body before any parsing.
```ts
declare const rawBody: Buffer;
declare const signatureHeader: string;
// ---cut---
const secret = process.env.FISHJAM_WEBHOOK_SECRET!;
// rawBody: Buffer, signatureHeader: req.headers['x-fishjam-signature-256']
if (!verifyWebhookSignature(rawBody, signatureHeader, secret)) {
// respond with 401 here — how depends on your framework, see the examples linked below
throw new Error('Invalid webhook signature');
}
// signature is valid — safe to decode
const notifications = decodeServerNotifications(rawBody);
```
```python
from fishjam import verify_webhook_signature, decode_server_notifications
secret = os.environ["FISHJAM_WEBHOOK_SECRET"]
# raw_body: bytes, signature_header: request.headers["x-fishjam-signature-256"]
if not verify_webhook_signature(raw_body, signature_header, secret):
# respond with 401 here — how depends on your framework, see the examples linked below
raise PermissionError("Invalid webhook signature")
# signature is valid — safe to decode
notifications = decode_server_notifications(raw_body)
```
See the [Fastify](../../how-to/backend/fastify-example#webhooks) and [FastAPI](../../how-to/backend/fastapi-example#webhooks) examples for a full webhook handler wired into a web framework.
### SDK Notifier
Our SDKs come equipped with a Notifier allowing you to subscribe for messages.
It sets up a websocket connection with a Fishjam instance and provides a simple interface allowing you to handle messages.
```ts
const fishjamId = "https://fishjam.io";
const managementToken = "bbb";
// ---cut---
const onClose = console.log;
const onError = console.error;
const onConnectionFailed = console.error;
const fishjamNotifier = new FishjamWSNotifier({ fishjamId, managementToken }, onError, onClose);
fishjamNotifier.on('roomCreated', console.log);
```
```python
from fishjam import FishjamNotifier
from fishjam.events import ServerMessageRoomCreated
notifier = FishjamNotifier(fishjam_id, management_token)
@notifier.on_server_notification
def handle_notification(notification):
match notification:
case ServerMessageRoomCreated():
print(notification)
case _:
...
async def run_notifier():
notifier_task = asyncio.create_task(notifier.connect())
# Wait for notifier to be ready to receive messages
await notifier.wait_ready()
await notifier_task
asyncio.run(run_notifier())
```
---
## WHIP/WHEP with Fishjam
# Livestreaming using WHIP/WHEP
:::tip
Make sure to read [Livestreaming with Fishjam](../../tutorials/livestreaming) before reading this guide.
This guide focuses on a low-level way to communicate with Fishjam.
The majority of use-cases should prefer to use the methods described in [Livestreaming with Fishjam](../../tutorials/livestreaming).
:::
If you've reading this guide, it is more than likely that you've already heard of **WHIP** (WebRTC HTTP Ingress Protocol) and **WHEP** (WebRTC HTTP Egress Protocol).
If not, then we recommend to read our [article about WHIP/WHEP](https://blog.swmansion.com/building-interactive-streaming-apps-webrtc-whip-whep-explained-d38f4825ec90).
In short, these are two protocols which standardize real-time livestreaming.
This prevents vendor lock-in and allows implementations and solutions to be reused in different scenarios.
Fishjam supports both WHIP and WHEP, so you can choose how to publish and receive streams.
For example, you can use [OBS Studio](https://obsproject.com/) to publish a livestream with WHIP and then receive the stream using any public online WHEP player you like.
## WHIP with Fishjam
WHIP is the protocol used by streamers to start publishing.
To use WHIP you need two things:
1. The URL of an HTTP endpoint implementing the WHIP specification.
2. A token, used by the endpoint to authorize the streamer.
### Getting the URL
Fishjam's WHIP endpoint is available at
```sh
https://fishjam.io/api/v1/live/api/whip
```
You can paste this URL in your WHIP client of choice to start streaming.
### Getting the token
To authenticate a streamer, you need to first create a room of type `livestream` and a streamer token for that room.
You can read about this in detail in [Production Livestreaming with Server SDKs](../../tutorials/livestreaming#production-livestreaming-with-server-sdks), but the TL;DR is
```ts
const fishjamId = "";
const managementToken = "";
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const room = await fishjamClient.createRoom({ roomType: 'livestream' });
const { token: streamerToken } = await fishjamClient.createLivestreamStreamerToken(room.id); // [!code highlight]
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
room = fishjam_client.create_room(RoomOptions(room_type="livestream"))
streamer_token = fishjam_client.create_livestream_streamer_token(room.id) # [!code highlight]
```
The created streamer token must be supplied in the HTTP headers of the WHIP request:
```sh
POST https://fishjam.io/api/v1/live/api/whip
Authorization: Bearer [STREAMER-TOKEN]
```
## WHEP with Fishjam
WHEP is the protocol used by viewers to start receiving a published livestream.
The usage of WHEP is very similar to WHIP, as you need the following:
1. The URL of an HTTP endpoint implementing the WHEP specification.
2. **(Optional)** A token, used by the endpoint to authorize the viewer.
With Fishjam, if the livestream is private, then the **token is required**.
On the other hand, if the livestream is public, then the **token is omitted**.
[Livestreams](../../explanation/livestreams) explains private and public livestreams in more detail.
In this guide we demonstrate how to view each livestream type using WHEP directly.
### Private livestreams
#### Getting the URL
For private livestreams, Fishjam's WHEP endpoint is available at
```sh
https://fishjam.io/api/v1/live/api/whep
```
You can paste this URL in your WHEP client of choice to start viewing.
#### Getting the token
To authenticate a viewer, you need to create a viewer token for a room of `livestream` type.
You can read about this in detail in [Production Livestreaming with Server SDKs](../../tutorials/livestreaming#production-livestreaming-with-server-sdks), but the TL;DR is
```ts
const fishjamId = "";
const managementToken = "";
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const room = await fishjamClient.createRoom({ roomType: 'livestream', public: false });
// ...
const { token: viewerToken } = await fishjamClient.createLivestreamViewerToken(room.id); // [!code highlight]
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
room = fishjam_client.create_room(RoomOptions(room_type="livestream", public=False))
# ...
viewer_token = fishjam_client.create_livestream_viewer_token(room.id) # [!code highlight]
```
The created viewer token must be supplied in the HTTP headers of the WHEP request:
```sh
POST https://fishjam.io/api/v1/live/api/whep
Authorization: Bearer [VIEWER-TOKEN]
```
### Public livestreams
For public livestreams, you don't need a token, however you still need a room of `livestream` type with the `public` flag enabled.
```ts
const fishjamId = "";
const managementToken = "";
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
// ---cut---
const room = await fishjamClient.createRoom({ roomType: 'livestream', public: true });
// now you can use room.id to start viewing
```
```python
room = fishjam_client.create_room(room_type="livestream", public=True)
# now you can use room.id to start viewing
```
Once you have such a room, you can view a stream published to that room by supplying the following URL:
```sh
http://fishjam.io/api/v1/live/api/whep/[ROOM-ID]
```
## See also
More on livestreaming:
- [Livestreaming tutorial](../../tutorials/livestreaming)
- [Livestreams](../../explanation/livestreams)
If livestreaming doesn't fit your use case:
- [Rooms](../../explanation/rooms)
- [Videoconferencing in React Native](../../tutorials/react-native-quick-start)
- [Videoconferencing in React](../../tutorials/react-quick-start)
- [Audio-only calls](./audio-only-calls)
---
## Background calls
# Background calls Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
Both Android and iOS support calls running in the background, but they use different approaches:
- **Android**: Uses foreground services to keep the app active in the background
- **iOS**: Uses CallKit integration to maintain VoIP calls in the background
Below is configuration required to make it work:
You need to modify `app.json` file and add our plugin:
```json
{
"expo": {
...
"plugins": {
...
[
"@fishjam-cloud/react-native-client",
{
"android": {
"enableForegroundService": true
},
"ios": {
"enableVoIPBackgroundMode": true
}
}
],
...
}
}
}
```
**Android Configuration**
Add the following permissions and services to `AndroidManifest.xml`:
```xml title='AndroidManifest.xml'
...
...
```
**iOS Configuration**
You need to add VoIP background mode in `Info.plist`:
```xml title='Info.plist'
UIBackgroundModes
voip
```
## Usage
You can use [`useForegroundService`](../../api/mobile/variables/useForegroundService) hook to handle how foreground service behaves on Android.
:::important[Permissions]
If you want to use [`enableCamera`](../../api/mobile/type-aliases/ForegroundServiceConfig#enablecamera) or [`enableMicrophone`](../../api/mobile/type-aliases/ForegroundServiceConfig#enablemicrophone),
user must first grant permission for this resource. [`useForegroundService`](../../api/mobile/variables/useForegroundService) will check if permission is
granted and only then allow to start a service.
:::
```tsx
useForegroundService,
useCamera,
useMicrophone,
} from "@fishjam-cloud/react-native-client";
const { isCameraOn } = useCamera();
const { isMicrophoneOn } = useMicrophone();
useForegroundService({
// [!code highlight]
channelId: "io.fishjam.example.fishjamchat.foregroundservice.channel",
channelName: "Fishjam Chat Notifications",
notificationTitle: "Your video call is ongoing",
notificationContent: "Tap to return to the call.",
enableCamera: isCameraOn,
enableMicrophone: isMicrophoneOn,
// enableScreenSharing: true,
});
```
On iOS, background calls are achieved through CallKit integration. You can use the CallKit hooks to manage VoIP calls that continue running in the background.
### Manual CallKit Management
Use the [`useCallKit`](../../api/mobile/functions/useCallKit) hook for fine-grained control over CallKit sessions:
```tsx
const { startCallKitSession, endCallKitSession } = useCallKit();
// Start CallKit session when joining a room
const handleJoinRoom = async () => {
await startCallKitSession({
displayName: "John Doe",
isVideo: true,
});
// ... join room logic
};
// End CallKit session when leaving
const handleLeaveRoom = async () => {
await endCallKitSession();
// ... leave room logic
};
```
### Automatic CallKit Management
Use the [`useCallKitService`](../../api/mobile/functions/useCallKitService) hook for automatic session lifecycle management:
```tsx
function CallScreen({ username }: { username: string }) {
// CallKit session automatically starts when component mounts
// and ends when component unmounts
useCallKitService({
displayName: username,
isVideo: true,
});
return ... ;
}
```
### Listening to CallKit Events
Use the [`useCallKitEvent`](../../api/mobile/functions/useCallKitEvent) hook to respond to user interactions with the native CallKit interface:
```tsx
useCallKitEvent,
useCamera,
useMicrophone,
useConnection,
} from "@fishjam-cloud/react-native-client";
const { startMicrophone, stopMicrophone } = useMicrophone();
const { leaveRoom } = useConnection();
// Listen for mute toggle from CallKit UI
useCallKitEvent("muted", (isMuted?: boolean) => {
if (isMuted === true) {
stopMicrophone();
} else if (isMuted === false) {
startMicrophone();
}
});
// Listen for hold state changes
useCallKitEvent("held", (isHeld?: boolean) => {
console.log("Call hold state:", isHeld);
// Handle hold state in your app
});
// Listen for call end from CallKit UI
useCallKitEvent("ended", () => {
// Handle call termination
leaveRoom();
});
```
## See Also
For an enhanced user experience when your app is in the background, consider enabling [Picture in Picture](./picture-in-picture), which allows users to see video content in a floating window while using other apps.
To surface an incoming call as a native CallKit (iOS) or Telecom (Android) call driven by a push notification, see [VoIP calls](./voip-calls).
---
## Blur or replace the camera background
# Blur or replace the camera background Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
`@fishjam-cloud/video-effects` ships ready-made background effects: background blur and background image replacement. An effect runs on the camera track Fishjam already publishes, as a [camera track middleware](./stream-middleware.mdx). Your app keeps using [`useCamera`](../../../api/mobile/functions/useCamera), and other peers keep receiving your video as `peer.cameraTrack`, now with the effect applied.
Each camera frame reaches a worklet on a dedicated camera thread, a segmentation model finds the person on the GPU, and the effect draws the result into the published frame. The JS thread is not involved per frame. See [How camera effects work](../../../explanation/camera-effects.mdx) for the details.
:::tip[First time?]
The [background blur tutorial](../../../tutorials/background-blur.mdx) builds this step by step in a working app, from installing the packages to a blur toggle.
:::
## Prerequisites
- `@fishjam-cloud/react-native-client` **0.30.2** or newer, with your app wrapped in `FishjamProvider` (see [Installation](../installation.mdx))
- `@fishjam-cloud/video-effects` **0.1.5** or newer
- `react-native-webgpu` **0.10.1** or newer. Older versions leak one camera frame of graphics memory per frame on Android until the JavaScript garbage collector runs.
- React Native 0.86 (Expo SDK 57) with the New Architecture enabled
- iOS 16.4 or newer, or Android 8.0 (API 26) or newer
- A physical device, or the iOS Simulator with a virtual camera from [SimCam](../ios-simulator-camera.mdx)
## Install
```bash npm2yarn
npm install @fishjam-cloud/video-effects @fishjam-cloud/react-native-worklets react-native-worklets react-native-webgpu expo-asset expo-file-system expo-build-properties
npm install --save-dev unplugin-typegpu @babel/plugin-transform-class-static-block
```
What each package does:
- `@fishjam-cloud/video-effects`: the effects, the segmentation model and the camera middleware
- `@fishjam-cloud/react-native-worklets`: runs a worklet on every frame of the Fishjam camera track. Its minor version follows `react-native-worklets`: `0.12.x` works with `react-native-worklets` `0.12.x`.
- `react-native-webgpu`: the GPU the effects render with
- `expo-asset` and `expo-file-system`: load the bundled segmentation model
- `expo-build-properties`: raises the Android minimum SDK version
### Configure Babel
The effects rely on the `react-native-worklets` Babel plugin, and on TypeGPU, which needs `import.meta`, class static blocks and its own Babel plugin. Keep `react-native-worklets/plugin` as the last plugin:
```js title='babel.config.js'
module.exports = function (api) {
api.cache(true);
return {
presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]],
plugins: [
"@babel/plugin-transform-class-static-block",
"unplugin-typegpu/babel",
"react-native-worklets/plugin",
],
};
};
```
### Configure Metro
The segmentation model ships as a `.ssgbin` file. Add the extension to Metro's asset extensions so it can be bundled with your app:
```js title='metro.config.js'
const { getDefaultConfig } = require("expo/metro-config");
const config = getDefaultConfig(__dirname);
config.resolver.assetExts = [...config.resolver.assetExts, "ssgbin"];
module.exports = config;
```
### Set the minimum OS versions
Expo SDK 57 needs iOS 16.4, while the Fishjam config plugin sets 15.1 by default. `react-native-webgpu` needs Android 8.0 (API 26), while Expo defaults to API 24. Raise both in `app.json`, the Android one with `expo-build-properties`:
```json title='app.json'
{
"expo": {
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"ios": {
"iphoneDeploymentTarget": "16.4"
}
}
],
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 26
}
}
]
]
}
}
```
In a bare React Native app, set `platform :ios, '16.4'` in `ios/Podfile` and `minSdkVersion = 26` in `android/build.gradle` instead.
Then restart Metro with a cleared cache and rebuild the native app, since the new packages contain native code:
```bash
npx expo prebuild
npx expo run:ios # or run:android
```
## Load the segmentation model
Both effects need a segmentation provider, which finds the person in each frame. `typeGpuPersonSegmentation` runs the bundled model on the GPU. Create the provider once, at module scope, so every effect that uses it shares one loaded model:
```ts title='effects.ts'
const segmentationModel = Asset.fromModule(
require("@fishjam-cloud/video-effects/assets/selfie_segmenter.ssgbin"),
);
async function loadSegmentationModel(): Promise {
await segmentationModel.downloadAsync();
if (!segmentationModel.localUri) {
throw new Error("The segmentation model is not available.");
}
return new File(segmentationModel.localUri).arrayBuffer();
}
export const segmentation = typeGpuPersonSegmentation({
loadModel: loadSegmentationModel,
});
```
The model is read from a local copy of the asset instead of being fetched by URL, because an Android release build cannot `fetch` a bundled asset. If you host the model yourself, pass its address as `modelUrl` instead of `loadModel`.
## Blur the background
Wrap the effect in `createCameraEffectMiddleware` and keep the middleware at module scope. A stable identity lets you tell whether it is active by comparing it with `currentCameraMiddleware`:
```ts title='effects.ts'
declare const segmentation: PersonSegmentationProvider;
// ---cut---
export const backgroundBlur = createCameraEffectMiddleware(
createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })),
);
```
Then switch it on and off with `setCameraTrackMiddleware`:
```tsx
declare const backgroundBlur: NonNullable;
// ---cut---
export function BlurToggle() {
const { currentCameraMiddleware, setCameraTrackMiddleware } = useCamera();
const isBlurOn = currentCameraMiddleware === backgroundBlur;
const toggleBlur = async () => {
try {
await setCameraTrackMiddleware(isBlurOn ? null : backgroundBlur);
} catch (error) {
console.warn("Background blur failed", error);
await setCameraTrackMiddleware(null);
}
};
return (
);
}
```
How it behaves:
- The middleware lives in Fishjam's camera state, not in the component. It stays on across screens until you pass `null`, and it is applied again when the camera restarts or you switch cameras.
- You can set it before the camera starts. It is applied as soon as the camera track exists.
- Setting it up takes a moment: the model loads and the GPU pipelines are built. Until the blurred track is ready, peers keep receiving the previous track, so the video never goes black.
- If setting up fails, for example when the device has no suitable GPU, `setCameraTrackMiddleware` rejects. `currentCameraMiddleware` already points at the failed middleware at that point, so pass `null` to go back to the plain camera, as in the example.
## Replace the background with an image
`createBackgroundImageEffect` draws an image behind the person instead of blurring. Pass the image as a `uri`, or as `data` with its bytes. Background images need `@fishjam-cloud/video-effects` 0.1.4 or newer; on React Native, earlier versions publish the camera without the image:
```ts title='effects.ts'
declare const segmentation: PersonSegmentationProvider;
// ---cut---
export const beachBackground = createCameraEffectMiddleware(
createBackgroundImageEffect(() => ({
segmentation,
image: { uri: "https://example.com/beach.jpg" },
fit: "cover",
})),
);
```
The image is downloaded and decoded while the middleware sets up. If it cannot be loaded, the middleware reports an `"error"` status and publishes the camera without the effect.
### Use a bundled image
An Android release build cannot `fetch` a bundled asset, so read the bytes of a bundled image yourself and pass them as `data`. `expo-asset` keeps a bundled image as a drawable resource on Android release builds, so describe the asset again without its image size, which makes `downloadAsync` copy it to a local file:
```ts title='effects.ts'
declare const segmentation: PersonSegmentationProvider;
// ---cut---
async function loadBundledImage(moduleId: number): Promise {
const bundled = Asset.fromModule(moduleId);
const asset = new Asset({
name: bundled.name,
type: bundled.type,
hash: bundled.hash,
uri: bundled.uri,
});
await asset.downloadAsync();
if (!asset.localUri) throw new Error("The image is not available.");
return new File(asset.localUri).arrayBuffer();
}
let officeImage: ArrayBuffer | undefined;
export const officeImageLoaded = loadBundledImage(
require("./assets/office.jpg"),
).then((bytes) => {
officeImage = bytes;
});
export const officeBackground = createCameraEffectMiddleware(
createBackgroundImageEffect(() => ({
segmentation,
image: { data: officeImage, mimeType: "image/jpeg" },
})),
);
```
The options are read when the middleware is applied, so switch it on after `officeImageLoaded` resolves.
## Options
### Effect options
The options function passed to `createBackgroundBlurEffect` or `createBackgroundImageEffect` is read when the middleware is applied. To change an option, create a middleware with the new options and set it. Setting the same middleware again also re-reads its options.
| Option | Effect | Default | Description |
| ----------------- | ------ | -------------- | --------------------------------------------------------------------------------------------------- |
| `segmentation` | Both | — | The segmentation provider. Required. |
| `radius` | Blur | `18` | Blur strength, in pixels of the published frame, from `0` to `40`. |
| `edgeFeather` | Both | `0.2` | Softness of the person's outline, from `0` (sharp) to `0.5`. Defaults to `0.08` for images. |
| `enabled` | Both | `true` | Draws the camera untouched while `false`. |
| `image` | Image | — | `{ uri }` or `{ data, mimeType }`. Required. |
| `fit` | Image | `"cover"` | `"cover"` fills the frame and crops the image, `"contain"` fits the whole image inside the frame. |
| `backgroundColor` | Image | `[0, 0, 0, 1]` | RGBA color, each channel from `0` to `1`, shown where a `"contain"` image does not cover the frame. |
### Middleware options
`createCameraEffectMiddleware` takes a second, optional argument:
| Option | Default | Description |
| ---------- | ------- | ------------------------------------------------------------------------------------ |
| `width` | `720` | Width of the published video, in pixels. |
| `height` | `1280` | Height of the published video, in pixels. |
| `onStatus` | — | Called with the effect's status (`"loading"`, `"ready"` or `"error"`) and any error. |
The camera is scaled and cropped to fill the published size, like `objectFit: "cover"`. The defaults suit a phone held upright.
## Follow loading and errors
Pass `onStatus` to show a spinner while the model loads, or to report failures:
```ts
declare const segmentation: PersonSegmentationProvider;
// ---cut---
export const backgroundBlur = createCameraEffectMiddleware(
createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })),
{
onStatus: (status, error) => {
if (status === "error") console.warn("Background blur failed", error);
},
},
);
```
An `"error"` status means the segmentation model or the background image could not be loaded. The middleware is still applied, but it publishes the camera without the effect.
## Scope the effect to a component
`createCameraEffectMiddleware` keeps the effect on until you clear it. If the effect should only be on while a component is mounted, for example on a single call screen, use the `useFishjamCameraEffect` hook instead. It applies the effect while mounted, clears it on unmount, and reports the status as state:
```tsx
// @filename: effects.ts
export declare const segmentation: PersonSegmentationProvider;
// @filename: index.tsx
// ---cut---
export function CallControls() {
const [isBlurOn, setIsBlurOn] = useState(false);
const blur = useBackgroundBlur({ segmentation, radius: 24 });
const { status, error, retry } = useFishjamCameraEffect(
isBlurOn ? blur : null,
);
return (
<>
setIsBlurOn((value) => !value)}
/>
{status === "loading" && Loading blur… }
{error && }
>
);
}
```
While the effect loads, the hook publishes the plain camera. `useBackgroundImage` is the matching hook for image backgrounds.
:::warning[One camera middleware at a time]
The camera has a single middleware slot. `useFishjamCameraEffect` and `setCameraTrackMiddleware` write to the same slot, so don't mix them, or they replace each other's effect.
:::
## Good to know
- Effects improve how the video looks. They are not a privacy boundary: the model can miss parts of the background, for example around the edges of the person or in poor light, and let them show through.
- Remote peers need nothing special. The effect is part of the published camera track.
- The local preview from `useCamera().cameraStream` shows the effect too, because it renders the published track.
## Related guides
- [Background blur tutorial](../../../tutorials/background-blur.mdx): build a blur toggle step by step
- [Render WebGPU effects into the camera](./webgpu-effects.mdx): draw your own shaders instead of a ready-made effect
- [Process camera frames in a worklet](./frame-processing.mdx): read camera frames, for example for on-device ML
- [How camera effects work](../../../explanation/camera-effects.mdx)
- API reference: [`createCameraEffectMiddleware`](../../../api/video-effects/fishjam-react-native/functions/createCameraEffectMiddleware.md), [`useFishjamCameraEffect`](../../../api/video-effects/fishjam-react-native/functions/useFishjamCameraEffect.md), [`typeGpuPersonSegmentation`](../../../api/video-effects/segmentation/typegpu/functions/typeGpuPersonSegmentation.md), [Video Effects package](../../../api/video-effects/index.md)
---
## Process camera frames in a worklet
# Process camera frames in a worklet Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
`@fishjam-cloud/react-native-worklets` runs a worklet on every frame the Fishjam camera captures. The worklet gets the frame's native buffer, so you can hand it to on-device inference or other native frame-processing code, while the camera keeps publishing as usual.
Use this guide when you want to **read** frames. To **change** the published video, use [background effects](./background-effects.mdx) or [your own WebGPU effects](./webgpu-effects.mdx), which are built on the same mechanism.
## Prerequisites
- `@fishjam-cloud/react-native-client` **0.30.2** or newer, with your app wrapped in `FishjamProvider` (see [Installation](../installation.mdx))
- React Native 0.86 with the New Architecture enabled
- Android 8.0 (API 26) or newer on Android devices
```bash npm2yarn
npm install @fishjam-cloud/react-native-worklets react-native-worklets
```
The minor version of `@fishjam-cloud/react-native-worklets` follows `react-native-worklets`: `0.12.x` works with `react-native-worklets` `0.12.x`. Add the worklets Babel plugin as the last entry in your Babel plugins, then rebuild the native app:
```js title='babel.config.js'
module.exports = {
presets: ["babel-preset-expo"],
plugins: ["react-native-worklets/plugin"],
};
```
## Attach a frame callback
A frame callback attaches to a camera track through its frame processor: `getCameraFrameProcessor` from `@fishjam-cloud/react-native-webrtc` returns the processor, and `attachCameraFrameCallback` starts calling your worklet.
The easiest place to do this is a [camera track middleware](./stream-middleware.mdx) that returns the camera track unchanged. The middleware receives the raw camera track, and Fishjam runs it again whenever the camera restarts or you switch cameras, so the callback always follows the current camera:
```ts title='frameRateMonitor.ts'
function reportFrameRate(framesPerSecond: number) {
console.log(`Camera: ${framesPerSecond} fps`);
}
export const frameRateMonitor: TrackMiddleware = async (track) => {
const processor = await getCameraFrameProcessor(track);
const stats = { windowStartNs: 0, frames: 0 };
const subscription = await attachCameraFrameCallback(processor, (frame) => {
"worklet";
stats.frames += 1;
const elapsedNs = frame.timestampNanoseconds - stats.windowStartNs;
if (elapsedNs >= 1_000_000_000) {
scheduleOnRN(
reportFrameRate,
Math.round((stats.frames * 1e9) / elapsedNs),
);
stats.windowStartNs = frame.timestampNanoseconds;
stats.frames = 0;
}
});
// Publish the camera unchanged; stop the callback when the middleware is removed.
return { track, onClear: () => subscription.remove() };
};
```
Switch it on with `setCameraTrackMiddleware`:
```tsx
declare const frameRateMonitor: NonNullable;
// ---cut---
const { setCameraTrackMiddleware } = useCamera();
await setCameraTrackMiddleware(frameRateMonitor);
```
The callback runs on a dedicated camera frame thread, never on the JS thread. Use `scheduleOnRN` from `react-native-worklets` to send results back to the JS thread, as in the example.
## What a frame carries
| Field | Description |
| ---------------------- | ---------------------------------------------------------------------------------------------- |
| `nativeBuffer` | `CVPixelBufferRef` on iOS, `AHardwareBuffer*` on Android, as a `bigint` pointer |
| `width`, `height` | Size of the buffer, in pixels, before rotation |
| `rotationDegrees` | Clockwise rotation (`0`, `90`, `180` or `270`) that brings the frame upright |
| `isFrontCamera` | Whether the frame comes from the front camera |
| `timestampNanoseconds` | Presentation timestamp of the frame |
| `pixelFormat` | `"nv12"` or `"bgra8"` on iOS, depending on the camera; `"rgba8"` on Android |
| `release()` | Hands the buffer back to the camera before the callback returns. `isReleased` tells if it was. |
On Android, the camera tap converts each camera image to RGBA before your callback runs, so the buffer is always `rgba8`.
:::danger[Frame lifetime]
`nativeBuffer` is valid only until your callback returns or you call `release()`. Don't store the pointer for later use; copy what you need inside the callback.
:::
## How frames are delivered
- **Frames are dropped, never queued.** While your callback holds a frame, newer frames are dropped. A slow callback lowers the rate at which you see frames, not the rate at which the camera publishes.
- **One callback per camera track.** Remove the subscription before you attach another callback to the same track. The frame processor is also what [background effects](./background-effects.mdx) and [WebGPU effects](./webgpu-effects.mdx) use, so don't attach your own callback to a camera that already runs an effect.
- **One worklet runtime for the app.** All frame callbacks share one camera frame runtime, created the first time you attach a callback. Its closure copies follow the usual [worklet rules](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/getting-started): capture plain values and other worklets, and mutate objects captured by the worklet, not variables from the JS thread.
## Troubleshooting
- **`Camera frame worklets require the New Architecture.`** Turn on the New Architecture and rebuild the native app.
- **`Camera frame worklets require Android 8.0 (API 26).`** The device is too old for hardware buffers. Skip frame processing on such devices.
- **`@fishjam-cloud/react-native-worklets is not linked.`** Rebuild the native app after installing the package; a JS reload is not enough. On Android, if an older version was installed before, also delete `android/build/generated/autolinking` in your app.
- **`A camera frame callback is already attached.`** Remove the previous subscription first, or check that no effect middleware is running on the camera.
## Related guides
- [Background effects](./background-effects.mdx): blur or replace the background
- [Render WebGPU effects into the camera](./webgpu-effects.mdx): draw into the published frames
- [Stream middleware](./stream-middleware.mdx): how camera track middleware works
- [How camera effects work](../../../explanation/camera-effects.mdx)
- API reference: [`attachCameraFrameCallback`](../../../api/react-native-worklets/functions/attachCameraFrameCallback.md), [`CameraFrame`](../../../api/react-native-worklets/interfaces/CameraFrame.md), [React Native Worklets package](../../../api/react-native-worklets/index.md)
---
## Camera effects
Camera effects change the camera video before it leaves the device: blur the background, replace it with an image, or draw your own shaders into every frame. You can also read camera frames without changing the video, for example to run on-device ML.
All of this works on the camera Fishjam already manages. You keep using [`useCamera`](../../../api/mobile/functions/useCamera) to start, stop and switch the camera, and set the effect with `setCameraTrackMiddleware`. Other peers receive the result as your regular `cameraTrack`, so nothing changes on the receiving side.
```tsx
declare const backgroundBlur: NonNullable;
// ---cut---
const { setCameraTrackMiddleware } = useCamera();
await setCameraTrackMiddleware(backgroundBlur); // null turns the effect off
```
:::important
If you want to publish something that isn't your camera, such as a game render loop or a video file, see [Custom sources](../custom-sources/index.mdx) instead.
:::
## Choose a guide
| Guide | Platform | Use it when |
| ---------------------------------------------- | ------------------ | --------------------------------------------------------------------------------- |
| [Background effects](./background-effects.mdx) | 📱 Mobile | You want background blur or a background image, without writing shaders |
| [WebGPU effects](./webgpu-effects.mdx) | 📱 Mobile · 🌐 Web | You want to draw your own shaders, overlays or effects into the published video |
| [Frame processing](./frame-processing.mdx) | 📱 Mobile | You want to read camera frames, e.g. for on-device ML, without changing the video |
| [Stream middleware](./stream-middleware.mdx) | 📱 Mobile · 🌐 Web | You want to understand or write the middleware that the other guides are built on |
:::info[How it runs in React Native]
Effects run off the JS thread. `@fishjam-cloud/react-native-worklets` hands every camera frame to a worklet on a dedicated camera thread, and `@fishjam-cloud/video-effects` renders the result with WebGPU. See [How camera effects work](../../../explanation/camera-effects.mdx) for the full picture.
:::
:::tip[Using VisionCamera?]
If your app already captures the camera with [VisionCamera](https://react-native-vision-camera.com), you can publish that feed instead. See the [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source.mdx).
:::
## Guides in this section
## Further reading
- [Background blur tutorial](../../../tutorials/background-blur.mdx) and [WebGPU effects tutorial](../../../tutorials/webgpu-effects.mdx): build a working app step by step
- [How camera effects work](../../../explanation/camera-effects.mdx): concepts behind the pipeline
- API reference: [Video Effects package](../../../api/video-effects/index.md), [React Native Worklets package](../../../api/react-native-worklets/index.md)
---
## Stream middleware
Stream middleware in Fishjam allows you to intercept and manipulate media tracks before they are sent to the Fishjam server.
This feature is powerful for applying effects, custom encodings, or any other transformations to the media stream.
The camera and microphone keep being managed by Fishjam: device selection, starting and stopping, and publishing work as usual. The middleware only decides which track goes out in place of the raw device track. Other peers receive the result as your regular `cameraTrack` or `microphoneTrack`.
## Overview
Define a `TrackMiddleware` function ([Web](../../../api/web/type-aliases/TrackMiddleware) · [React Native](../../../api/mobile/type-aliases/TrackMiddleware)) which takes a `MediaStreamTrack` and returns, directly or as a promise, an object containing the modified `MediaStreamTrack` and an optional `onClear` function, which is called when the middleware is removed or replaced, or when the device track it processes goes away.
### Type definition
```typescript
type MiddlewareResult = {
track: MediaStreamTrack;
onClear?: () => void;
};
export type TrackMiddleware =
| ((track: MediaStreamTrack) => MiddlewareResult | Promise)
| null;
```
### Setting middleware
You can set the middleware for your media tracks using the `setCameraTrackMiddleware` and `setMicrophoneTrackMiddleware` methods of [`useCamera`](../../../api/web/functions/useCamera) and [`useMicrophone`](../../../api/web/functions/useMicrophone). These methods accept a `TrackMiddleware` or `null` for removing previously set middleware. `currentCameraMiddleware` and `currentMicrophoneMiddleware` return the middleware that is currently set.
### How middleware is applied
- **It is applied to every new device track.** A middleware set before the device starts is applied when it starts. It is applied again when the device restarts or you switch to another device, so the published track is never the raw one while a middleware is set.
- **The old track is published until the new one is ready.** An asynchronous middleware can take a moment to set up. Until it resolves, peers keep receiving the previous track. The previous middleware's `onClear` runs only after the new track has replaced it in the published stream.
- **The latest request wins.** If you set another middleware, or `null`, while one is still setting up, the one that was replaced is released as soon as it finishes setting up and is never published.
- **Tracks returned by the middleware are stopped for you.** When a middleware is removed, the track it returned is stopped, unless it is the input track itself. Release anything else your middleware created in `onClear`.
## Example: Applying a video effect
In React Native, a camera middleware typically runs a GPU effect on every frame of the camera track. `@fishjam-cloud/video-effects` creates such middleware for you. The example below toggles a background blur; see [Background effects](./background-effects.mdx) for the setup.
```tsx
declare const segmentation: PersonSegmentationProvider;
// ---cut---
// Create the middleware once, so its identity stays stable.
const backgroundBlur = createCameraEffectMiddleware(
createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })),
);
export function BlurToggle() {
// [!code highlight:2]
const { currentCameraMiddleware, setCameraTrackMiddleware } = useCamera();
const isBlurOn = currentCameraMiddleware === backgroundBlur;
return (
setCameraTrackMiddleware(isBlurOn ? null : backgroundBlur)} // [!code highlight]
/>
);
}
```
To write your own middleware, see [Render WebGPU effects into the camera](./webgpu-effects.mdx), which returns a WebGPU-rendered track, and [Process camera frames in a worklet](./frame-processing.mdx), which reads frames and returns the camera track unchanged.
## Example: Applying a blur effect
The following example demonstrates how to apply a custom blur effect to the camera track using the [`useCamera`](../../../api/web/functions/useCamera) hook and middleware.
```tsx
class BlurProcessor {
track: MediaStreamTrack;
constructor(stream: MediaStream) {
this.track = this.applyBlurEffect(stream);
}
private applyBlurEffect(stream: MediaStream): MediaStreamTrack {
return stream.getVideoTracks()[0];
}
destroy() {}
}
// ---cut---
export function CameraWithBlurEffect() {
const videoRef = useRef(null);
// [!code highlight:2]
const { cameraStream, currentCameraMiddleware, setCameraTrackMiddleware } =
useCamera();
useEffect(() => {
if (!videoRef.current) return;
videoRef.current.srcObject = cameraStream ?? null;
}, [cameraStream]);
// Define blur middleware
const blurMiddleware: TrackMiddleware = useCallback(
(track: MediaStreamTrack) => {
const streamToBlur = new MediaStream([track]);
// BlurProcessor is just an example,
// process the stream however you need
const blurProcessor = new BlurProcessor(streamToBlur);
return {
track: blurProcessor.track,
onClear: () => blurProcessor.destroy(),
};
},
[],
);
// Check if the current middleware is blur
const isBlurEnabled = currentCameraMiddleware === blurMiddleware;
// Toggle blur effect
const toggleBlur = () => {
setCameraTrackMiddleware(isBlurEnabled ? null : blurMiddleware); // [!code highlight]
};
return (
<>
{isBlurEnabled ? "Disable Blur" : "Enable Blur"}
{cameraStream && }
>
);
}
```
This example provides a button to toggle the blur effect on and off. The `BlurProcessor` handles the actual processing logic and is assumed to be implemented elsewhere.
## Related guides
- [Background effects](./background-effects.mdx): ready-made background blur and background image for React Native
- [Render WebGPU effects into the camera](./webgpu-effects.mdx): return a track you render yourself
- [Managing devices](../managing-devices.mdx): start, stop and switch the camera and microphone
- [How camera effects work](../../../explanation/camera-effects.mdx)
---
## Render WebGPU effects into the camera
This guide shows how to render each frame of your published camera yourself with WebGPU. Whatever you draw is what other peers receive.
The rendering code is plain WebGPU on both platforms. The integration differs:
- In **React Native**, return a WebGPU-rendered track from a [camera track middleware](./stream-middleware.mdx). `createCameraFrameProcessorSession` from `@fishjam-cloud/video-effects` calls your worklet for every frame of the Fishjam camera, with the camera as a GPU texture and an output texture to draw into. It handles the output track, GPU synchronization with the video encoder, timestamps and frame lifetimes. Peers receive the result as your regular camera track.
- On the **web**, render into a ``, capture it with [`captureStream`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/captureStream), and publish the stream as a [custom source](../custom-sources/web.mdx).
If you only need background blur or a background image, use the [ready-made background effects](./background-effects.mdx) instead of writing shaders.
## Prerequisites
- The packages (`@fishjam-cloud/video-effects` 0.1.5 or newer, `react-native-webgpu` 0.10.1 or newer) and the Babel and minimum OS configuration from [Background effects](./background-effects.mdx#install). The segmentation model and the Metro and `expo-asset` setup are not needed.
- `typegpu` in your app, if you write your shaders in TypeGPU as below
```bash npm2yarn
npm install typegpu
```
## Publish the camera through your own shaders
:::tip[First time?]
The [WebGPU effects tutorial](../../../tutorials/webgpu-effects.mdx) builds this pipeline step by step in a working app, from a passthrough render pass to a watermark overlay and a color effect.
:::
The example below publishes the camera in grayscale. It is a camera track middleware: it builds the pipeline, starts a frame processor on the raw camera track, and returns the processor's track in its place. To apply your own effect, replace the fragment stage.
:::note
The shaders are written in [TypeGPU](https://docs.swmansion.com/TypeGPU/) (TGSL): typed TypeScript functions compiled to WGSL by `unplugin-typegpu`. TypeGPU is not required; you can hand-write WGSL and prepend the bindings' `bindingDeclarations` yourself.
:::
```tsx title='grayscale.ts'
///
// ---cut---
createCameraFrameProcessorSession,
createCameraShaderBindings,
getCameraWebGpuDevice,
getOutputSurfaceFormat,
type CameraFrameKernel,
} from "@fishjam-cloud/video-effects/fishjam-react-native";
// Full-screen triangle; uv spans the visible area.
const vertexMain = tgpu.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: d.vec2f((p.x + 1) * 0.5, 1 - (p.y + 1) * 0.5),
};
});
function createGrayscalePipeline(device: GPUDevice) {
const cameraBindings = createCameraShaderBindings(device, {
cameraPixelLayout: "rgb",
});
const fragmentMain = tgpu.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => {
const color = cameraBindings.sampleCamera(input.uv);
const gray = dot(color.xyz, d.vec3f(0.299, 0.587, 0.114));
return d.vec4f(gray, gray, gray, 1);
});
// TypeGPU cannot emit the camera's external-texture binding itself, so
// prepend cameraBindings.bindingDeclarations to the resolved WGSL.
const module = device.createShaderModule({
code:
cameraBindings.bindingDeclarations +
tgpu.resolve([vertexMain, fragmentMain]),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [cameraBindings.bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [{ format: getOutputSurfaceFormat() }],
},
});
return { cameraBindings, pipeline };
}
export const grayscale: TrackMiddleware = async (track) => {
const device = await getCameraWebGpuDevice();
const { cameraBindings, pipeline } = createGrayscalePipeline(device);
const frameKernel: CameraFrameKernel = (frame, render) => {
"worklet";
render(({ commandEncoder, outputView, cameraBindGroup }) => {
const pass = commandEncoder.beginRenderPass({
colorAttachments: [
{ view: outputView, loadOp: "clear", storeOp: "store" },
],
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, cameraBindGroup!);
pass.draw(3);
pass.end();
});
};
const session = await createCameraFrameProcessorSession({
track,
device,
width: 720,
height: 1280,
cameraShaderBindings: cameraBindings,
frameKernel,
});
return { track: session.track, onClear: () => void session.dispose() };
};
```
Switch it on like any camera middleware:
```tsx
declare const grayscale: NonNullable;
// ---cut---
const { setCameraTrackMiddleware } = useCamera();
await setCameraTrackMiddleware(grayscale); // null restores the plain camera
```
How the example works:
- `getCameraWebGpuDevice()` returns the app-wide `GPUDevice`, requested with the features the camera import needs. Build your pipelines, textures and bind groups on this device.
- `createCameraShaderBindings(device, { cameraPixelLayout: "rgb" })` gives your shaders `sampleCamera(uv)`, which returns upright RGB. The Fishjam camera arrives as RGB on both platforms, so the layout is always `"rgb"`.
- TypeGPU cannot emit the camera's `texture_external` binding, so `cameraBindings.bindingDeclarations` is prepended to the resolved WGSL. The fragment stage targets `getOutputSurfaceFormat()` (`rgba8unorm` on Android, `bgra8unorm` on iOS).
- Passing `cameraShaderBindings` to the session makes the render context carry a ready-made `cameraBindGroup`, rebuilt every frame because the camera's external texture expires with each frame.
- `frameKernel` is a worklet. It runs on the camera frame thread for every frame, encodes one render pass, and the session submits it. The pipeline it uses is built on the JS thread and copied into the worklet.
- The middleware returns `session.track`, and `onClear` disposes the session when the middleware is replaced, cleared, or the camera stops.
## Rules inside the frame kernel
The kernel receives `frame`, with `timestampNanoseconds`, `isFrontCamera`, `width`, `height` and `rotationDegrees`, and `render`. The function you pass to `render(...)` receives a `WebGpuFrameRenderContext` with the `device`, `queue`, `commandEncoder`, the live `cameraTexture` (a `GPUExternalTexture`, already upright), the output surface (`outputTexture`, `outputView`, `outputWidth`, `outputHeight`), and the upright camera size (`cameraWidth`, `cameraHeight`).
:::warning[Rules your worklet must follow]
- **Always draw into the provided `outputView`.** Calling `outputTexture.createView()` per frame leaks native wrappers on the frame runtime, because `GPUTextureView` has no release API.
- **Call `render(...)` at most once per frame.** Skipping it drops the frame; nothing is published for it.
- **Don't call `queue.submit()` yourself.** The session submits your passes and synchronizes with the video encoder.
- **Finish GPU uploads before you create the session.** Helpers like [`queue.copyExternalImageToTexture`](https://developer.mozilla.org/en-US/docs/Web/API/GPUQueue/copyExternalImageToTexture) submit work internally. Running them from the JS thread while frames flow races the session's submissions and can crash the app, so upload textures in the middleware before `createCameraFrameProcessorSession`.
- **Camera bind groups cannot be cached across frames**, because the external texture changes every frame. Use `cameraBindGroup`, or call `createCameraBindGroup` inside the worklet each frame.
- **Capture only what a worklet can copy.** The kernel's closure is copied to the camera frame runtime when the session starts: GPU objects, numbers, strings and other worklets work. React state and TypeGPU root objects don't, and later changes on the JS thread are not seen by the kernel.
:::
## Going further
- **Overlays**: a frame may contain more than one render pass. Encode additional passes into the same `outputView` (with `loadOp: "load"`) after the camera pass to draw watermarks or other content on top.
- **Aspect ratio**: the grayscale example stretches the camera to 720×1280. `createCameraPassthroughPipeline` and `encodeCameraPassthrough` draw the camera cropped to fill the output, given a crop from `computeAspectFillCrop`. To sample a cropped camera from your own shaders, `createCameraTextureResolver` and `resolveCameraTexture` render it into an owned `rgba8unorm` texture first, at the cost of one extra render pass per frame.
- **Reading frames without drawing**: to run on-device inference on camera frames without changing the published video, see [Process camera frames in a worklet](./frame-processing.mdx).
- **Output size**: `width` and `height` set the published resolution. The camera is imported at its own resolution and your passes decide how it maps onto the output.
The full toolkit is documented in the [Video Effects API reference](../../../api/video-effects/index.md).
## Platform notes
- The Fishjam camera arrives as RGB on both platforms. On **Android** the camera tap converts the camera texture before handing it over; on **iOS** the camera buffer is imported directly.
- `getOutputSurfaceFormat()` returns the published surface format: `rgba8unorm` on Android, `bgra8unorm` on iOS. Use it for your fragment targets instead of hard-coding a format.
- The published frames are not mirrored. The local self-view mirrors the front camera when you render it with `mirror={true}`.
## Publish a canvas
If you already render with WebGPU (or Three.js, WebGL, or another canvas-based library), this is all the Fishjam-specific code you need:
```tsx
declare const canvas: HTMLCanvasElement;
// ---cut---
const { setStream } = useCustomSource("my-canvas");
setStream(canvas.captureStream(30));
```
`setStream` comes from the same [`useCustomSource`](../custom-sources/web.mdx) API as any custom source, and other peers receive the feed among their [`customVideoTracks`](../custom-sources/index.mdx#receiving-custom-tracks).
The rest of this guide builds a worked example that renders the camera in grayscale. Any render pass works the same way: replace the shaders and keep the rest.
## Browser support
WebGPU is available in modern Chromium browsers, Safari 26+, and Firefox 141+. It requires a secure context (HTTPS or `localhost`). Always feature-detect with `navigator.gpu` and fall back to a WebGL/canvas path where it matters.
## Example: the camera in grayscale
The example has two parts: the shaders, and a component that sets up WebGPU, renders every frame, and publishes the canvas.
### 1. Write the shaders
There are two shader stages:
- The **vertex** stage draws a full-screen triangle, so the fragment stage covers the whole canvas. `uv` spans the visible area.
- The **fragment** stage samples the camera at `uv` and weighs the color channels into gray.
The camera arrives as a `texture_external`, which TypeGPU cannot declare itself. The camera bindings are therefore written in raw WGSL, and sampling is wrapped in a WGSL-bodied `tgpu.fn` that the fragment shader can call. (On React Native, `createCameraShaderBindings` provides this recipe ready-made.)
```tsx
///
// ---cut---
// TypeGPU cannot emit `texture_external` bindings itself, so declare them in
// WGSL and sample through a WGSL-bodied `tgpu.fn` that TGSL shaders can call.
const bindingDeclarations = /* wgsl */ `
@group(0) @binding(0) var cameraTexture: texture_external;
@group(0) @binding(1) var cameraSampler: sampler;
`;
const sampleCamera = tgpu.fn(
[d.vec2f],
d.vec4f,
)(/* wgsl */ `(uv: vec2f) -> vec4f {
return textureSampleBaseClampToEdge(cameraTexture, cameraSampler, uv);
}`);
// Full-screen triangle; uv spans the visible area.
const vertexMain = tgpu.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: d.vec2f((p.x + 1) * 0.5, 1 - (p.y + 1) * 0.5),
};
});
const fragmentMain = tgpu.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => {
const color = sampleCamera(input.uv);
const gray = dot(color.xyz, d.vec3f(0.299, 0.587, 0.114));
return d.vec4f(gray, gray, gray, 1);
});
```
:::note
The shaders are written in [TypeGPU](https://docs.swmansion.com/TypeGPU/) (TGSL): typed TypeScript functions compiled to WGSL by the [`unplugin-typegpu`](https://docs.swmansion.com/TypeGPU/tooling/unplugin-typegpu/) plugin in your bundler (for Vite: `unplugin-typegpu/vite`). TypeGPU is not required; plain WGSL strings work the same.
:::
### 2. Render and publish
The component has five stages, marked in the code: get a GPU device, open the camera, build the pipeline, draw every frame, publish the canvas.
Note stage 4: camera external textures expire with the frame, so the loop imports the current camera frame and rebuilds the bind group on every iteration.
```tsx
///
const bindingDeclarations = /* wgsl */ `
@group(0) @binding(0) var cameraTexture: texture_external;
@group(0) @binding(1) var cameraSampler: sampler;
`;
const sampleCamera = tgpu.fn(
[d.vec2f],
d.vec4f,
)(/* wgsl */ `(uv: vec2f) -> vec4f {
return textureSampleBaseClampToEdge(cameraTexture, cameraSampler, uv);
}`);
const vertexMain = tgpu.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: d.vec2f((p.x + 1) * 0.5, 1 - (p.y + 1) * 0.5),
};
});
const fragmentMain = tgpu.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => {
const color = sampleCamera(input.uv);
const gray = dot(color.xyz, d.vec3f(0.299, 0.587, 0.114));
return d.vec4f(gray, gray, gray, 1);
});
// ---cut---
export function GrayscaleCameraPublisher() {
const canvasRef = useRef(null);
const { setStream } = useCustomSource("my-camera");
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || !navigator.gpu) return; // no WebGPU on this browser
let disposed = false;
let frameHandle = 0;
let camera: MediaStream | undefined;
const run = async () => {
// 1. Get a GPU device.
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) return;
const device = await adapter.requestDevice();
// 2. Open the camera and play it into a hidden .
camera = await navigator.mediaDevices.getUserMedia({ video: true });
const video = document.createElement("video");
video.srcObject = camera;
video.muted = true;
await video.play();
if (disposed) return;
// 3. Configure the canvas and build the render pipeline.
const context = canvas.getContext("webgpu") as GPUCanvasContext;
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format, alphaMode: "opaque" });
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.FRAGMENT,
externalTexture: {},
},
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
],
});
const sampler = device.createSampler();
const module = device.createShaderModule({
code: bindingDeclarations + tgpu.resolve([vertexMain, fragmentMain]),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: { module, entryPoint: "fragmentMain", targets: [{ format }] },
});
// 4. Draw every frame.
const renderFrame = () => {
if (disposed) return;
// External textures expire with the frame; import and bind every frame.
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: device.importExternalTexture({ source: video }),
},
{ binding: 1, resource: sampler },
],
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadOp: "clear",
storeOp: "store",
},
],
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
pass.draw(3);
pass.end();
device.queue.submit([encoder.finish()]);
frameHandle = requestAnimationFrame(renderFrame);
};
frameHandle = requestAnimationFrame(renderFrame);
// 5. Publish what the loop draws.
setStream(canvas.captureStream(30));
};
void run();
return () => {
disposed = true;
cancelAnimationFrame(frameHandle);
setStream(null);
camera?.getTracks().forEach((track) => track.stop());
};
}, [setStream]);
return ; // self-view
}
```
The same canvas serves as the self-view, so peers see exactly what you see.
The browser handles encoder synchronization, timestamps and frame lifetimes, so there is no frame processor session to create.
## Going further
### Sampling without external textures
Pipelines written against plain 2D textures can copy the video in with [`queue.copyExternalImageToTexture`](https://developer.mozilla.org/en-US/docs/Web/API/GPUQueue/copyExternalImageToTexture) instead of `importExternalTexture`. This costs one copy per frame, but avoids `texture_external` bindings in your shaders.
### Frame pacing and background tabs
`captureStream(30)` samples the canvas at up to 30 fps. For exact pacing, use `captureStream(0)` and call [`track.requestFrame()`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasCaptureMediaStreamTrack/requestFrame) after each render. To render only when the camera produces a frame, drive the loop with [`video.requestVideoFrameCallback`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/requestVideoFrameCallback) instead of `requestAnimationFrame`.
:::warning[Background tabs freeze the stream]
`requestAnimationFrame` stops when the page is hidden, which freezes the published video for other peers. If streaming must continue in a background tab, drive rendering from a worker with an [`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) transferred from the captured canvas.
:::
## Related guides
- [WebGPU effects tutorial](../../../tutorials/webgpu-effects.mdx): build this pipeline step by step in a working app
- [Background effects](./background-effects.mdx): ready-made background blur and background image
- [Process camera frames in a worklet](./frame-processing.mdx): read camera frames without changing the video
- [Custom sources on the web](../custom-sources/web.mdx): other ways to obtain a `MediaStream` on the web
- [WebGPU effects with VisionCamera](../../../integrations/vision-camera/webgpu-effects.mdx): the same toolkit on a VisionCamera feed
- [How camera effects work](../../../explanation/camera-effects.mdx)
- API reference: [`createCameraFrameProcessorSession`](../../../api/video-effects/fishjam-react-native/functions/createCameraFrameProcessorSession.md), [`createCameraShaderBindings`](../../../api/video-effects/fishjam-react-native/functions/createCameraShaderBindings.md), [Video Effects package](../../../api/video-effects/index.md)
---
## Connecting
This article will guide you through the process of connecting to a Fishjam room.
## Getting URL and token
In order to connect, you need to obtain a **Peer Token** (the token that will authenticate the peer in
your Room).
Once you create your account on [Fishjam](https://fishjam.io), you can [use the Sandbox API](../backend/sandbox-api-testing) to generate peer tokens for testing or development purposes without setting up your own backend.
This is basically a service that will create a Room, add your app as
the Room's Peer, and return the token required to use that Room. It is available to all accounts, including the free **Mini Jar** plan.
For React/React Native apps, copy both the Fishjam ID from the [Dashboard tab](https://fishjam.io/app) and Sandbox API URL from the [Sandbox tab](https://fishjam.io/app/sandbox): the Sandbox API URL is used to get peer tokens, while the Fishjam ID is passed to `FishjamProvider` for media server access.
```ts
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const roomName = "room";
const peerName = "user";
// ---cut---
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const peerToken = await getSandboxPeerToken(roomName, peerName);
```
```ts
const SANDBOX_API_URL = "your-sandbox-api-url-here";
const roomName = "room";
const peerName = "user";
// ---cut---
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl: SANDBOX_API_URL });
const peerToken = await getSandboxPeerToken(roomName, peerName);
```
For production, you need to implement your own backend service that will provide the user with a **Peer Token**. To do that,
follow our [server setup instructions](../backend/server-setup). The **Standard Jar** plan is recommended for production deployments.
## Connecting
Use the [`useConnection`](../../api/web/functions/useConnection) hook to get
the [`joinRoom`](../../api/web/functions/useConnection#joinroom) function.
```tsx
const SANDBOX_API_URL = "your-sandbox-api-url-here";
// ---cut-before---
export function JoinRoomButton() {
const { joinRoom } = useConnection(); // [!code highlight]
// get the peer token from sandbox or your backend
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const onJoinRoomPress = useCallback(async () => {
// [!code highlight:5]
const peerToken = await getSandboxPeerToken("Room", "User");
await joinRoom({ peerToken });
}, [joinRoom, getSandboxPeerToken]);
return Join room ;
}
```
```tsx
const SANDBOX_API_URL = "your-sandbox-api-url-here";
export function JoinRoomButton() {
const { joinRoom } = useConnection(); // [!code highlight]
// get the peer token from sandbox or your backend
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const onPressJoin = useCallback(async () => {
// in production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken("Room", "User");
await joinRoom({ peerToken }); // [!code highlight]
}, [joinRoom, getSandboxPeerToken]);
return ;
}
```
## Disconnecting
In order to close connection, use the [`leaveRoom`](../../api/web/functions/useConnection#leaveroom) method
from [`useConnection`](../../api/web/functions/useConnection) hook.
```tsx
export function LeaveRoomButton() {
const { leaveRoom } = useConnection(); // [!code highlight]
return Leave room ;
}
```
```tsx
export function LeaveRoomButton() {
const { leaveRoom } = useConnection(); // [!code highlight]
const onPressLeave = useCallback(async () => {
await leaveRoom(); // [!code highlight]
}, [leaveRoom]);
return ;
}
```
## Next Steps
Now that you're connected to a room, you can explore additional features:
- [Start Streaming](./start-streaming) - Enable your camera and microphone
- [List Other Peers](./list-other-peers) - Display video from other participants
- [Data Channels](../../explanation/data-channels) - Send and receive arbitrary data between peers (e.g., text chat)
- [Picture in Picture](./picture-in-picture) - Allow users to watch video in a floating window (Mobile)
- [Background Calls](./background-streaming) - Keep calls active when the app is backgrounded (Mobile)
---
## Custom sources
Custom sources allow you to publish media that doesn't come straight from the camera, microphone or screen share, for example a game render loop or an ML-processed camera feed. Any content you can produce as video frames or audio samples can be published.
:::important
If you only wish to send plain camera, microphone or screen share output through Fishjam, then you most likely should refer to [Streaming media](../start-streaming.mdx), [Managing devices](../managing-devices.mdx) and [Screen sharing](../screensharing.mdx) instead of this section. To blur the background or draw effects into your camera, see [Camera effects](../camera-effects/index.mdx).
:::
Every custom source follows the same contract: you register a `MediaStream` under a stable source ID with the `useCustomSource` hook ([Web](../../../api/web/functions/useCustomSource.md) · [React Native](../../../api/mobile/functions/useCustomSource.md)), and Fishjam publishes its video track as a `customVideo` track and its audio track as a `customAudio` track. Other peers receive them like any other track.
## Choose a guide
| Guide | Platform | Use it when |
| ------------------------------------------------------ | --------- | --------------------------------------------------------------------------------------------- |
| [Web](./web.mdx) | 🌐 Web | You have a `MediaStream` from a canvas, a media element, Web Audio, or a library like Smelter |
| [React Native](./react-native.mdx) | 📱 Mobile | You have a React Native `MediaStream` to publish, or want to publish app-generated audio |
| [Low-level frame API](./low-level-frame-api.mdx) | 📱 Mobile | You produce video frames yourself, e.g. from a native pipeline or your own renderer |
| [WebGPU effects](../camera-effects/webgpu-effects.mdx) | 🌐 Web | You render your own shaders into a canvas and want to publish it |
:::info[Platform support]
On the web you can publish both video and audio from any `MediaStream`. In React Native, custom video comes from the [low-level frame API](./low-level-frame-api.mdx) or the [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source.mdx), and custom audio from the [`useCustomAudioSource`](./react-native.mdx#publish-custom-audio) hook, which publishes PCM samples your app pushes.
:::
:::tip[Publishing from VisionCamera?]
If your app captures the camera with [VisionCamera](https://react-native-vision-camera.com), publish that feed as a custom source with the [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source.mdx).
:::
## Receiving custom tracks
Custom tracks published by other peers show up in the `usePeers` hook ([Web](../../../api/web/functions/usePeers.md) · [React Native](../../../api/mobile/functions/usePeers.md)), bucketed into the `customVideoTracks` and `customAudioTracks` arrays of each peer.
```tsx
const VideoRenderer: FC<{ stream?: MediaStream | null }> = (_) => ;
// ---cut---
export function RemoteCustomVideos() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) => (
{peer.customVideoTracks.map((track) => (
))}
))}
);
}
```
Remote `customAudioTracks` are played by attaching each track's `stream` to an `` element, the same way as microphone tracks.
```tsx
export function RemoteCustomVideos() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) =>
peer.customVideoTracks.map(
(track) =>
track.stream && (
),
),
)}
);
}
```
Incoming `customAudioTracks` are played back automatically; you don't render anything for them.
## Guides in this section
## Further reading
- [How custom sources work](../../../explanation/custom-sources.mdx): concepts behind the pipeline
- API reference: [`useCustomSource` (Web)](../../../api/web/functions/useCustomSource.md), [`useCustomSource` (React Native)](../../../api/mobile/functions/useCustomSource.md), [`useCustomAudioSource` (React Native)](../../../api/mobile/functions/useCustomAudioSource.md), [Custom Video Source package](../../../api/custom-video-source/index.md)
---
## Publish frames with the low-level API
# Publish frames with the low-level API Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
`@fishjam-cloud/react-native-custom-video-source` is the generic layer under the [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source). Use it directly when your frames come from another source, such as a native ML pipeline or your own renderer. It is built on the raw track primitives of `@fishjam-cloud/react-native-webrtc`, covered [at the end of this guide](#raw-track-primitives).
## Pick a mode
The two modes differ in how you produce frames:
| Mode | Hook | Use it when |
| -------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------- |
| **Forwarding** | `useManagedForwardTrack` | You already have finished native buffers (`CVPixelBufferRef` on iOS, `AHardwareBuffer*` on Android) |
| **Render-target (pooled)** | `useManagedPooledTrack` | You render the frames yourself; the hook allocates GPU-shareable surfaces for you to draw into |
Each hook manages the track's asynchronous lifecycle: creation, the published `stream`, and teardown. Your code only supplies frames.
## Prerequisites
- `@fishjam-cloud/react-native-webrtc` and `@fishjam-cloud/react-native-client`, with your app wrapped in `FishjamProvider`
- The New Architecture; custom video tracks require it and reject with a clear error on the old architecture
```bash npm2yarn
npm install @fishjam-cloud/react-native-custom-video-source
```
## Publish the managed stream
Both hooks return a `stream`. Publish it with [`useCustomSource`](./react-native), like any other custom source:
```tsx
useCustomSource,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
// ---cut---
export function usePublishStream(sourceId: string, stream: MediaStream | null) {
const { setStream } = useCustomSource(sourceId);
useEffect(() => {
if (!stream) return;
setStream(stream);
return () => {
setStream(null);
};
}, [stream, setStream]);
}
```
## Forward finished buffers
`useManagedForwardTrack` creates and owns the track; hand each buffer pointer to `forwardFrame`:
```tsx
declare function getNextFrameBuffer(): bigint; // your native pipeline
// ---cut---
const { track, stream, error } = useManagedForwardTrack(true /* enabled */);
// publish `stream` via useCustomSource, then per frame:
if (track) {
forwardFrame(track, {
nativeBuffer: getNextFrameBuffer(),
});
}
```
Buffer requirements:
- `nativeBuffer` is a retainable, IOSurface-backed `CVPixelBufferRef` (iOS) or an `AHardwareBuffer*` (Android), passed as a `bigint` pointer.
- The SDK retains the buffer for encoding; you may release your reference immediately after `forwardFrame` returns.
- `timestampNs` is optional: when omitted, frames are stamped with the native monotonic clock. Pass your own capture timestamps only if you need to align the video with an audio track you also produce.
- `rotation` (`0 | 90 | 180 | 270`) rotates the frame for the receiver. Don't set it if your buffers are already upright, or the frame gets rotated twice.
:::warning[One worklet runtime per track]
`forwardFrame` and `pushFrame` are worklet-safe, but a track's sink binds to the first worklet runtime that touches it. Feed each track from a single runtime (or from the JS thread) consistently.
:::
## Render into pooled surfaces
`useManagedPooledTrack` allocates a pool of native GPU-shareable surfaces; draw into a slot and hand it back with `pushFrame`:
```tsx
declare function renderInto(surfaceHandle: bigint): void; // your renderer
declare function nowNanoseconds(): number;
// ---cut---
const { track, stream, bufferDescriptors, error } = useManagedPooledTrack(
true, // enabled
720, // width
1280, // height
3, // poolSize
);
let nextSlot = 0;
function renderFrame() {
if (!track || !bufferDescriptors) return;
const descriptor = bufferDescriptors[nextSlot];
nextSlot = (nextSlot + 1) % bufferDescriptors.length;
renderInto(descriptor.surfaceHandle);
pushFrame(track, {
bufferIndex: descriptor.index,
timestampNs: nowNanoseconds(),
});
}
```
Each `WorkletBufferDescriptor` carries `{ index, surfaceHandle, width, height }`. Import each `surfaceHandle` into your GPU once and cache the result per index; don't re-import it every frame.
The surfaces are:
| Platform | Surface type | Pixel format | Import as |
| -------- | ----------------- | ------------ | ------------ |
| iOS | `IOSurface` | BGRA8 | `bgra8unorm` |
| Android | `AHardwareBuffer` | RGBA8 | `rgba8unorm` |
Rendering with the wrong format typically shows up as swapped red/blue channels, or the import is rejected outright.
Unlike forwarding, `timestampNs` is required here and must be strictly increasing.
### Synchronize with your GPU
If your renderer works asynchronously, pass a `fence` so the encoder waits for your rendering to finish instead of reading a half-drawn surface:
- **iOS**: `handle` is an `MTLSharedEvent` pointer and `signaledValue` the value your GPU work signals.
- **Android**: `handle` is a sync file descriptor; pass `0n` as `signaledValue`.
If you render with WebGPU, prefer the `/webgpu` toolkit of this package, or [`createCameraFrameProcessorSession`](../camera-effects/webgpu-effects.mdx) when you draw on the camera; they handle fencing, surface import, and frame lifetimes for you.
## Lifecycle and errors
- `track`, `stream` and `bufferDescriptors` are `null` until asynchronous creation finishes; failures surface in the hook's `error` field rather than throwing.
- Set `enabled: false` to tear everything down; the hooks stop the tracks (and dispose the pool) in the correct order on unmount too.
- Changing the pooled dimensions reallocates the pool, so release any GPU objects you imported when `bufferDescriptors` changes.
## Raw track primitives
The managed hooks wrap four primitives from `@fishjam-cloud/react-native-webrtc`: `createCustomVideoBufferPool`, `createCustomVideoTrack`, `pushFrame` and `forwardFrame`. Use them directly only when a React hook cannot own the lifecycle, for example inside a headless native-driven runtime:
```tsx
createCustomVideoBufferPool,
createCustomVideoTrack,
} from "@fishjam-cloud/react-native-webrtc";
// ---cut---
const pool = await createCustomVideoBufferPool({
width: 720,
height: 1280,
poolSize: 3,
});
const { stream, track } = await createCustomVideoTrack({ pool });
// render into pool.buffers[i].surfaceHandle, then pushFrame(track, ...)
// Teardown; order matters:
stream.getTracks().forEach((mediaStreamTrack) => mediaStreamTrack.stop());
await pool.dispose();
```
When using the primitives directly, you must follow the rules the hooks otherwise enforce:
- A pool binds to exactly one track.
- Stop the track's stream before disposing the pool; `dispose()` rejects while the track is live.
- Stopping a track never frees the pool; you own it and must dispose it yourself.
- `createCustomVideoTrack()` without a pool creates a forwarding track for `forwardFrame`.
## WebGPU render targets
The `/webgpu` entry point of this package is a camera-rendering toolkit for the pooled mode. It provides a shared camera-capable `GPUDevice`, camera sampling from your shaders, a passthrough pipeline, and crop helpers. It is covered in [WebGPU effects with VisionCamera](../../../integrations/vision-camera/webgpu-effects).
## Related guides
- [Custom sources in React Native](./react-native): publishing the stream
- [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source): the ready-made VisionCamera integration built on this layer
- [How custom sources work](../../../explanation/custom-sources)
- API reference: [Custom Video Source package](../../../api/custom-video-source/index)
---
## Custom sources in React Native
# Custom sources in React Native Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
`@fishjam-cloud/react-native-client` provides two hooks for publishing custom sources. Your app must be wrapped in [`FishjamProvider`](../../../api/mobile/functions/FishjamProvider).
- [`useCustomSource`](../../../api/mobile/functions/useCustomSource) publishes a `MediaStream`. It is the same hook that is available [on the web](./web), typed for the React Native [`MediaStream`](../../../api/mobile/classes/MediaStream). The stream typically comes from the [low-level frame API](./low-level-frame-api) or the [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source), whose hooks create it for you, but any `MediaStream` you hold works.
- [`useCustomAudioSource`](../../../api/mobile/functions/useCustomAudioSource) publishes audio your app generates itself: you push PCM samples and the hook manages the track and its stream. See [Publish custom audio](#publish-custom-audio).
## Publish a stream
Set the stream on a stable source ID; set `null` to unpublish. The cleanup function keeps the source in sync with the component lifecycle.
```tsx
useCustomSource,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
// ---cut---
export function usePublishStream(stream: MediaStream | null) {
const { setStream } = useCustomSource("my-custom-source");
useEffect(() => {
if (!stream) return;
setStream(stream);
return () => {
setStream(null);
};
}, [stream, setStream]);
}
```
:::info[When tracks are actually published]
Tracks are sent to Fishjam only while the peer is connected to a room. A stream set before joining is queued and published as soon as the connection is established, and pending sources are re-published automatically after a reconnect. Calls to `setStream` are serialized internally, so replacing one stream with another in quick succession is safe.
:::
:::important
Custom sources are shared by ID: every `useCustomSource` call with the same source ID returns the same state, so multiple components can control and read one source.
:::
## Show a self-view
The `stream` returned by `useCustomSource` renders like any other stream:
```tsx
// ---cut---
export function SelfView() {
const { stream } = useCustomSource("my-custom-source");
if (!stream) return null;
return (
);
}
```
## Remove the source
```tsx
// ---cut---
const { setStream } = useCustomSource("my-custom-source");
// ...
await setStream(null);
```
Removing a source unpublishes its tracks but does not stop them; the producer of the stream owns the tracks and should stop them itself.
## Publish custom audio
React Native has no equivalent of the web's `captureStream()` or Web Audio, so audio your app generates does not arrive as a `MediaStream`. The [`useCustomAudioSource`](../../../api/mobile/functions/useCustomAudioSource) hook covers this case: it creates a custom audio track, publishes it under its source ID, and cleans it up. Your code pushes raw PCM samples with `pushAudioSamples` whenever your source produces them, for example a synthesizer, a decoder, or [`react-native-audio-api`](https://docs.swmansion.com/react-native-audio-api/):
```tsx
useCustomAudioSource,
pushAudioSamples,
} from "@fishjam-cloud/react-native-client";
declare function onAudioChunk(callback: (chunk: Float32Array) => void): void; // your audio source
// ---cut---
const { startStreaming, stopStreaming, track } = useCustomAudioSource({
sampleRateHz: 48000,
channelCount: 1,
});
await startStreaming();
// Whenever your source produces audio:
onAudioChunk((chunk) => {
if (track) pushAudioSamples(track, chunk);
});
// When done:
await stopStreaming();
```
The published track behaves like a live microphone: pushes are re-paced into a continuous stream, and pauses in pushing play as silence. The device microphone is not involved; publishing does not trigger the recording permission, and microphone capture stays with [`useMicrophone`](../../../api/mobile/functions/useMicrophone).
Notes on pushing samples:
- Push any chunk size; the native layer re-frames and paces it. `Float32Array` samples are expected in `[-1, 1]`; `Int16Array` is taken as-is. Stereo tracks take interleaved samples.
- The `track` handle is plain and worklet-serializable, so samples can be pushed straight from a worklet without hopping through the JS thread.
- Pushed-but-not-yet-sent audio is buffered up to `maxBufferedDurationMs` and drains in real time, so a long clip (for example a text-to-speech utterance) can be handed over in one call.
### Options
| Option | Default | Description |
| ----------------------- | --------------------- | ---------------------------------------------------------------------------------------------------- |
| `sourceId` | `"customAudioSource"` | Source ID the track is published under. Give each instance that streams at the same time its own ID. |
| `sampleRateHz` | `48000` | Sample rate of the PCM you push; a positive multiple of `100`. Any rate is resampled downstream. |
| `channelCount` | `1` | `1` for mono, `2` for interleaved stereo. |
| `maxBufferedDurationMs` | `60000` | How much pushed-but-not-yet-sent audio to hold, in milliseconds, before the oldest is dropped. |
Custom audio tracks require the New Architecture. On the old architecture `startStreaming` does not throw; it fails internally and the failure surfaces in the hook's `error` field.
## Receiving on other peers
Custom tracks arrive in the `customVideoTracks` and `customAudioTracks` arrays of each peer returned by `usePeers`. See [Receiving custom tracks](./index.mdx#receiving-custom-tracks).
## Related guides
- [Camera effects](../camera-effects/index.mdx): blur the background or draw your own content into the published camera
- [VisionCamera integration](../../../integrations/vision-camera/vision-camera-source): publish a VisionCamera feed with frame processors
- [Low-level frame API](./low-level-frame-api): publish frames from your own pipeline
- [How custom sources work](../../../explanation/custom-sources)
---
## Custom sources on the web
# Custom sources on the web Web
:::note
This guide is exclusively for **Web** (React) applications. For React Native, see [Custom sources in React Native](./react-native).
:::
This guide demonstrates how to stream non-standard video or audio to other peers in your web app.
The utilities in this section allow you to integrate Fishjam with powerful browser APIs such as [WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) and [WebGPU](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API),
or higher level libraries, which leverage these APIs, such as [Three.js](https://threejs.org/), [Smelter](https://smelter.dev) or [PixiJS](https://pixijs.com/).
For a complete WebGPU render-and-publish pipeline, see [WebGPU effects](../camera-effects/webgpu-effects.mdx).
## Creating a custom source - [`useCustomSource()`](../../../api/web/functions/useCustomSource)
To create a custom source, you only need to do two things:
1. Call the `useCustomSource` hook.
2. Call the [`setStream`](../../../api/web/functions/useCustomSource#setstream) callback provided by the `useCustomSource` hook with a [MediaStream](#how-to-get-a-mediastream-object) object.
#### Usage Example
```tsx
const stream: MediaStream | null = null; // Replace with your MediaStream object
const { setStream } = useCustomSource("my-custom-source");
useEffect(() => {
setStream(stream);
}, [stream, setStream]);
```
### Using a created custom source
Once you have called [`setStream`](../../../api/web/functions/useCustomSource#setstream) for a given source ID (in the above example, `"my-custom-source"`), any subsequent calls to `useCustomSource` with the same ID will return the same state.
This enables multiple components to control and read a shared custom source.
### Deleting a custom source
If you wish to remove a custom source, then you should call the [`setStream`](../../../api/web/functions/useCustomSource#setstream) callback with `null` as its argument.
#### Usage Example
```tsx
// ---cut---
const { setStream } = useCustomSource("my-custom-source");
// ...
await setStream(null);
```
## How to get a MediaStream object?
Depending on your use-case, the way you can obtain a [MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream) will vary.
Below are some common examples of how to obtain one from an existing video or audio source.
### Canvas
If you have a `` HTML element, then you will need to call the [`captureStream`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/captureStream) method of the given canvas.
This is particularly useful if you are using [Three.js](https://threejs.org/) or [PixiJS](https://pixijs.com/) to render complex animations and more.
#### Usage Example
```tsx
export function CanvasExample() {
const [canvasStream, setCanvasStream] = useState();
const streamFromCanvas = useCallback((canvas: HTMLCanvasElement | null) => {
if (!canvas) return;
setCanvasStream(canvas.captureStream());
}, []);
// use canvasStream as desired
return ;
}
```
### Smelter
If you are using [Smelter](https://smelter.dev), then all you need to do is register an output via [`registerOutput`](https://smelter.dev/ts-sdk/outputs/wasm-stream/).
#### Usage Example
:::tip
If you want to see a full example React app which uses Fishjam with Smelter, then you can check out our [full example on GitHub](https://github.com/fishjam-cloud/web-client-sdk/tree/main/examples/react-client/minimal-smelter).
:::
```tsx
setWasmBundleUrl("/assets/smelter.wasm");
async function run() {
const smelter = new Smelter({ framerate: 30 });
const { stream } = await smelter.registerOutput("example-output", , {
type: "stream",
video: {
resolution: { width: 1920, height: 1080 },
},
});
await smelter.init();
}
```
### Video/Audio HTML tag
If you have a `` or `` element, then you need to call their [`captureStream`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream) method, analogously as you would with a [`canvas`](#canvas).
#### Usage Example
```tsx
const hasCaptureStream = (video: HTMLVideoElement): video is HTMLVideoElement & { captureStream: () => MediaStream } => "captureStream" in video && typeof video.captureStream === "function";
export function CanvasExample() {
const [stream, setStream] = useState();
const streamFromVideo = useCallback((video: HTMLVideoElement | null) => {
if (!video) return;
if(!hasCaptureStream(video)) {
console.warn("captureStream is not supported on this browser");
return;
}
setStream(video.captureStream());
}, []);
// use stream as desired
return ;
}
```
```tsx
export function CanvasExample() {
const [stream, setStream] = useState();
const streamFromAudio = useCallback((audio: HTMLAudioElement | null) => {
if (!audio) return;
setStream((audio as HTMLAudioElement & { captureStream(): MediaStream }).captureStream());
}, []);
// use stream as desired
return ;
}
```
## Related guides
- [Custom sources overview](./index.mdx): how custom tracks reach other peers
- [Custom sources in React Native](./react-native)
- [How custom sources work](../../../explanation/custom-sources)
---
## Debug logging
# Debug logging Web
:::note
This guide is exclusively for **Web** (React) applications.
:::
The Fishjam SDK includes a built-in debugging mode to help developers troubleshoot connectivity and media issues during development. This feature controls the verbosity of the SDK's internal logging mechanisms.
## Overview
By default, the SDK suppresses internal logs to keep your browser console clean in production environments. Enabling `debug` mode allows the SDK to output warnings and errors to the console, prefixed with `[FISHJAM]`.
## Usage
To enable debugging in a React application, pass the `debug` prop to the `FishjamProvider`.
```tsx
const App = () => null;
// ---cut---
function Root() {
return (
);
}
```
We recommend toggling this based on your environment variables:
```tsx
const process = {
env: { NODE_ENV: "development", FISHJAM_ID: "your-fishjam-id" },
};
const App = () => null;
// ---cut---
;
```
## Behavior
- **Enabled (`true`):** The SDK will log internal warnings (e.g., permission errors, socket closures, signaling issues) and errors to the browser console. All logs are prefixed with `[FISHJAM]` for easy filtering.
- **Disabled (`false` or `undefined`):** The SDK operates silently, suppressing internal `console.warn` and `console.error` calls to prevent console pollution.
### Example Output
When enabled, you may see logs similar to:
```text
[FISHJAM] Socket closed with reason: ...
[FISHJAM] Couldn't get camera permission: NotAllowedError ...
[FISHJAM] ICE connection: disconnected
```
---
## Installation
## 1. Install the package
```bash npm2yarn
npm install @fishjam-cloud/react-client
```
## 2. Setup Fishjam context
Wrap your app in our [`FishjamProvider`](../../api/web/functions/FishjamProvider) component. Get your Fishjam ID from [Fishjam Dashboard](https://fishjam.io/app) and pass it to the provider.
```tsx
const App = () => {
return Hello world;
};
// ---cut---
// import App from "./App";
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "your-fishjam-id";
ReactDOM.createRoot(document.getElementById("root")!).render(
// [!code highlight:5]
,
);
```
:::tip
It's possible to have many independent Fishjam contexts in one app.
Just render many [`FishjamProvider`](../../api/web/functions/FishjamProvider) components and make sure they don't overlap.
:::
## Optional: Create a New App
Follow these steps to create a new mobile app
If you don't have an existing project, you can create a new Expo app using a template
```bash
npx create-expo-app@latest my-video-app
```
As the next step, you have to generate native files with the `expo prebuild` command:
```bash
npx expo prebuild
```
You can also follow more detailed [Expo instructions](https://docs.expo.dev/get-started/introduction/).
## Step 1: Install the Package
Install `@fishjam-cloud/react-native-client` and `react-native-get-random-values` with your preferred package manager.
```bash npm2yarn
npm install @fishjam-cloud/react-native-client react-native-get-random-values@1.11.0
```
Expo SDK 54+ resolves native dependencies recursively, so `@fishjam-cloud/react-native-webrtc` (a transitive dependency) is autolinked automatically.
Install `@fishjam-cloud/react-native-client`, `@fishjam-cloud/react-native-webrtc`, and `react-native-get-random-values`:
```bash npm2yarn
npm install @fishjam-cloud/react-native-client @fishjam-cloud/react-native-webrtc react-native-get-random-values@1.11.0
```
Bare React Native and Expo SDK versions below 54 only autolink direct dependencies.
`@fishjam-cloud/react-native-webrtc` must be in your app's `package.json` for its native code to be linked.
## Step 2: Configure App Permissions
Your app needs to have permissions configured in order to use the microphone and camera.
### Android
The following Android permissions are required by Fishjam:
- `android.permission.CAMERA`
- `android.permission.RECORD_AUDIO`
- `android.permission.MODIFY_AUDIO_SETTINGS`
- `android.permission.ACCESS_NETWORK_STATE`
Add required permissions to the `app.json` file.
```json title='app.json'
{
"expo": {
...
"android": {
...
"permissions": [
"android.permission.CAMERA",
"android.permission.RECORD_AUDIO",
"android.permission.MODIFY_AUDIO_SETTINGS",
"android.permission.ACCESS_NETWORK_STATE"
]
}
}
}
```
Add required permissions to the `AndroidManifest.xml` file.
```xml title='AndroidManifest.xml'
...
...
```
### iOS
You don't have to make any changes to run app on iOS.
To update default content of permission alert, you can add these settings to `app.json`:
```json title='app.json'
{
"expo": {
...
"ios": {
...
"infoPlist": {
"NSCameraUsageDescription": "Allow $(PRODUCT_NAME) to access your camera.",
"NSMicrophoneUsageDescription": "Allow $(PRODUCT_NAME) to access your microphone."
}
},
}
}
```
Ensure `Info.plist` contains camera and microphone usage description entries:
```xml title='Info.plist'
NSCameraUsageDescription
Allow $(PRODUCT_NAME) to access your camera.
NSMicrophoneUsageDescription
Allow $(PRODUCT_NAME) to access your microphone.
```
## Step 3: Setup Fishjam Context
Wrap your app in the [`FishjamProvider`](../../api/mobile/functions/FishjamProvider) component:
```tsx
// Check https://fishjam.io/app/ for your Fishjam ID
const FISHJAM_ID = "your-fishjam-id";
export default function App() {
return (
{/* Your app components */}
);
}
```
## Camera and Microphone Permissions
:::info
You don't need to explicitly request permissions — they're automatically requested when your app calls `initializeDevices()`.
:::
If you need manual control over when permissions are requested, see [Managing Permissions](./managing-devices#managing-permissions-mobile-only).
---
## iOS Simulator Camera Mobile
# iOS Simulator Camera Mobile
The iOS Simulator has no camera, which means you normally need a physical device to test video streaming with Fishjam.
[SimCam](https://simcam.swmansion.com/) is a macOS app that injects a virtual camera into the simulator. It works through standard AVFoundation APIs, so `@fishjam-cloud/react-native-client` picks it up without any changes to your code.
## What SimCam provides
- **Live camera feed**: your Mac's camera streamed into the simulator
- **Video file**: a video clip you can replay for consistent test scenarios
- **QR code**: inject QR codes without holding a phone up to the screen
## Getting started
1. Download and install SimCam from [simcam.swmansion.com](https://simcam.swmansion.com/).
2. Launch SimCam and pick a camera source.
3. Run your app in the simulator. The virtual camera shows up just like a real one.
---
## Display media of other peers
To access data and media of other peers, use the [`usePeers`](../../api/web/functions/usePeers) hook.
It returns two properties, `remotePeers` and `localPeer`.
They contain all the tracks of other peers and all the tracks of the local user, respectively.
## Example of playing other peers' available media
```tsx
const VideoRenderer: FC<{ stream?: MediaStream | null }> = (_) => ;
const AudioPlayer: FC<{ stream?: MediaStream | null }> = (_) => ;
// ---cut---
export function Component() {
const { remotePeers } = usePeers();
return (
{remotePeers.map(({ id, cameraTrack, microphoneTrack }) => (
// remember to import
your VideoRenderer component
))}
);
}
```
```tsx
usePeers,
RTCView,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
function VideoPlayer({ stream }: { stream: MediaStream | null }) {
if (!stream) return No video ;
return (
);
}
export function ShowAllPeers() {
const { remotePeers, localPeer } = usePeers(); // [!code highlight]
return (
{/* Local camera */}
{localPeer?.cameraTrack?.stream && ( // [!code highlight]
)}
{/* Remote cameras */}
{remotePeers.map(
(
peer, // [!code highlight]
) => (
{peer.cameraTrack?.stream && (
)}
),
)}
);
}
```
:::tip[Enable Picture in Picture]
To allow users to continue watching video in a floating window when they background your app, use the `RTCPIPView` component. See the [Picture in Picture guide](./picture-in-picture) for more details.
:::
---
## Managing devices
The Fishjam SDK provides functions for dynamically controlling media device streams. This includes selecting desired cameras and microphones, turning them on and off, as well as muting and unmuting microphones.
## Selecting Camera and Microphone
To select the desired camera or microphone, use the `selectCamera` and `selectMicrophone` functions.
Lists of the available devices are available via the `cameraDevices` and `microphoneDevices` properties.
To select the desired camera or microphone, use [`selectCamera()`](../../api/web/functions/useCamera#selectcamera) and [`selectMicrophone()`](../../api/web/functions/useMicrophone#selectmicrophone) functions.
Lists of the available devices are available via the [`cameraDevices`](../../api/web/functions/useCamera#cameradevices) and [`microphoneDevices`](../../api/web/functions/useMicrophone#microphonedevices) properties.
#### Usage Example
```tsx
export function CameraControl() {
const { cameraDevices, selectCamera } = useCamera();
return (
{cameraDevices.map(({ deviceId, label }) => (
selectCamera(deviceId)}>{label}
))}
);
}
```
To select the desired camera, use the [`selectCamera`](../../api/mobile/functions/useCamera) method.
The list of the available camera devices is available via the [`cameraDevices`](../../api/mobile/functions/useCamera).
```tsx
export function FlipButton() {
const { cameraDevices, selectCamera } = useCamera(); // [!code highlight]
const [currentIndex, setCurrentIndex] = useState(0);
const onPressFlipCamera = useCallback(() => {
if (cameraDevices.length === 0) return;
// Cycle through available cameras
const nextIndex = (currentIndex + 1) % cameraDevices.length;
const nextCamera = cameraDevices[nextIndex];
if (nextCamera) {
selectCamera(nextCamera.deviceId); // [!code highlight]
setCurrentIndex(nextIndex);
}
}, [cameraDevices, currentIndex, selectCamera]);
return ;
}
```
:::tip[Testing on iOS Simulator]
The iOS Simulator has no camera. [SimCam](https://simcam.swmansion.com/) solves this by injecting a virtual feed (your Mac's camera or a video file), so you can test without a physical device. See [Camera on iOS Simulator](./ios-simulator-camera).
:::
## Turning Camera On and Off
Use the [`toggleCamera()`](../../api/web/functions/useCamera#togglecamera) method to control the physical operational state of the camera.
- **Turning the camera off**: This action stops the camera device, disables the media stream, and pauses streaming. The webcam indicator light will shut down.
- **Turning the camera on**: This action starts the camera and resumes streaming, allowing other participants to see video after a brief initialization period.
#### Usage Example
```tsx
export function CameraControl() {
const { toggleCamera } = useCamera();
return toggleCamera()}>Toggle Camera Device ;
}
```
You can use [`toggleCamera`](../../api/mobile/functions/useCamera) to toggle the camera state, or use [`startCamera`](../../api/mobile/functions/useCamera) and [`stopCamera`](../../api/mobile/functions/useCamera) for more explicit control.
#### Using toggleCamera
```tsx
export function ToggleCameraButton() {
const { isCameraOn, toggleCamera } = useCamera(); // [!code highlight]
return (
);
}
```
#### Using startCamera/stopCamera
```tsx
export function CameraControls() {
const { startCamera, stopCamera, isCameraOn } = useCamera();
return (
startCamera()}
title="Start Camera"
disabled={isCameraOn}
/>
stopCamera()}
title="Stop Camera"
disabled={!isCameraOn}
/>
);
}
```
## Turning Microphone On and Off
Use the [`toggleMicrophone()`](../../api/web/functions/useMicrophone#togglemicrophone) method to toggle the microphone's physical operational state. The function interacts with a physical device, so it might take a noticeable amount of time.
**Turning the microphone off**: This action turns the microphone off, disables the media stream, and pauses any audio transmission.
**Turning the microphone on**: This action turns the microphone on and resumes audio streaming.
You can use [`toggleMicrophone`](../../api/mobile/functions/useMicrophone) to toggle the microphone state, or use [`startMicrophone`](../../api/mobile/functions/useMicrophone) and [`stopMicrophone`](../../api/mobile/functions/useMicrophone) for more explicit control.
#### Using toggleMicrophone
```tsx
export function ToggleMicrophoneButton() {
const { isMicrophoneOn, toggleMicrophone } = useMicrophone(); // [!code highlight]
return (
);
}
```
#### Using startMicrophone/stopMicrophone
```tsx
export function MicrophoneControls() {
const { startMicrophone, stopMicrophone, isMicrophoneOn } = useMicrophone();
return (
startMicrophone()}
title="Start Microphone"
disabled={isMicrophoneOn}
/>
stopMicrophone()}
title="Stop Microphone"
disabled={!isMicrophoneOn}
/>
);
}
```
## Muting and Unmuting Microphone (Web only)
:::note
This feature is only available on Web. On mobile, use `toggleMicrophone` or `stopMicrophone` to disable audio transmission.
:::
Use [`toggleMicrophoneMute()`](../../api/web/functions/useMicrophone#togglemicrophonemute) to manage the audio stream's operational status without affecting the microphone's hardware state.
Muting and unmuting is faster than turning the microphone on/off, but a muted device still uses resources. This is useful, as it is common to mute and unmute during a meeting. Unmuting needs to be quick to capture the first word of a sentence.
- **Muting the microphone**: This action disables the media stream and stops audio transmission while keeping the microphone active.
- **Unmuting the microphone**: This action enables the media stream, allowing immediate transmission of sounds.
#### Usage Example
```tsx
export function MicrophoneControl() {
const { toggleMicrophone, toggleMicrophoneMute } = useMicrophone();
return (
toggleMicrophone()}>
Toggle Microphone Device
toggleMicrophoneMute()}>
Toggle Microphone Mute
);
}
```
## Audio processing: noise cancellation and auto gain control
When capturing a microphone, the browser (Web) or OS (Mobile) applies audio processing — **echo cancellation**, **noise suppression** (noise cancellation) and **auto gain control** — to make speech clearer. These are enabled by default and are the right choice for most voice and meeting use cases.
Turn them off only when you need the raw, unprocessed signal — for example capturing music or an instrument, or running your own audio processing — since these filters can distort non-speech audio.
On Web, audio processing follows the browser's defaults (noise suppression, auto gain control and echo cancellation are on by default). To set them explicitly, pass [`constraints`](../../api/web/interfaces/FishjamProviderProps#constraints) to `FishjamProvider`. The `audio` field accepts standard [`MediaTrackConstraints`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints).
```tsx
export function App({ fishjamId }: { fishjamId: string }) {
return (
{/* your app */}
);
}
```
To capture raw audio (for example, music), set `echoCancellation`, `noiseSuppression`, and `autoGainControl` to `false` instead.
:::note
These constraints are applied when `FishjamProvider` creates the microphone track. `selectMicrophone` and `startMicrophone` reuse the same constraints — they don't accept per-call overrides.
:::
On Mobile, echo cancellation, noise suppression and auto gain control are enabled by default in the native audio pipeline and aren't currently configurable from JavaScript.
## Managing Permissions (Mobile only)
The SDK provides built-in hooks for querying and requesting device permissions: `useCameraPermissions` and `useMicrophonePermissions` from `@fishjam-cloud/react-native-client`.
Both hooks return a `[query, request]` tuple:
- **`query()`** — checks the current permission status without prompting the user
- **`request()`** — triggers the native permission dialog and returns the resulting status
The returned `PermissionStatus` is one of: `'granted'`, `'denied'`, or `'prompt'`.
:::info
Requesting permissions manually is optional — `initializeDevices()` will automatically prompt for any permissions that haven't been granted yet.
However, you must always call `initializeDevices()` to set up camera and microphone devices.
:::
#### Usage Example
```tsx
// @noErrors: 2305
useCameraPermissions,
useMicrophonePermissions,
useInitializeDevices,
} from "@fishjam-cloud/react-native-client";
function RoomScreen() {
const [queryCamera, requestCamera] = useCameraPermissions(); // [!code highlight]
const [queryMicrophone, requestMicrophone] = useMicrophonePermissions(); // [!code highlight]
const { initializeDevices } = useInitializeDevices(); // [!code highlight]
useEffect(() => {
const setup = async () => {
let cam = await queryCamera();
let mic = await queryMicrophone();
if (cam !== "granted") cam = await requestCamera();
if (mic !== "granted") mic = await requestMicrophone();
if (cam === "granted" && mic === "granted") {
await initializeDevices(); // [!code highlight]
}
};
setup();
}, [
queryCamera,
requestCamera,
queryMicrophone,
requestMicrophone,
initializeDevices,
]);
}
```
---
## Metadata
Alongside audio and video, it is possible to send additional metadata with each peer. Metadata is just
JSON that can contain arbitrary information. Its most common use is sending a user name associated with a peer.
However, it can be also used to send the peer's camera type, application information etc.
:::info
You can also set metadata on [the server side, when adding user to the room](../backend/server-setup#metadata). This metadata is persistent throughout its lifetime and is useful for attaching information that
can't be overwritten by the peer, like information about real user names or basic permission info.
:::
## Setting metadata when joining the room
The `joinRoom` method from the `useConnection` hook has a `peerMetadata` parameter, that can be used for setting object metadata.
```tsx
const PEER_TOKEN = "some-peer-token";
// ---cut---
type PeerMetadata = {
displayName: string;
};
export function JoinRoomButton() {
const { joinRoom } = useConnection(); // [!code highlight]
const onJoinRoomPress = useCallback(async () => {
await joinRoom({
peerToken: PEER_TOKEN,
peerMetadata: { displayName: "John Wick" }, // [!code highlight]
});
}, [joinRoom]);
return Join room ;
}
```
```tsx
const PEER_TOKEN = "some-peer-token";
// ---cut---
type PeerMetadata = {
displayName: string;
};
export function JoinRoomButton() {
const { joinRoom } = useConnection();
const onPressJoin = useCallback(async () => {
// Note: fishjamId is passed to FishjamProvider, not joinRoom
await joinRoom({
peerToken: PEER_TOKEN,
peerMetadata: { displayName: "John Wick" }, // [!code highlight]
});
}, [joinRoom]);
return ;
}
```
## Updating metadata during connection
Once you've joined the room, you can update your peer metadata with the `updatePeerMetadata` method of the `useUpdatePeerMetadata` hook:
```tsx
type PeerMetadata = {
displayName: string;
};
export function JoinRoomButton() {
const { updatePeerMetadata } = useUpdatePeerMetadata(); // [!code highlight]
const onPressUpdateName = useCallback(async () => {
await updatePeerMetadata({ displayName: "Thomas A. Anderson" }); // [!code highlight]
}, [updatePeerMetadata]);
return Change name ;
}
```
```tsx
type PeerMetadata = {
displayName: string;
};
export function UpdateNameButton() {
const { updatePeerMetadata } = useUpdatePeerMetadata(); // [!code highlight]
const onPressUpdateName = useCallback(async () => {
await updatePeerMetadata({ displayName: "Thomas A. Anderson" }); // [!code highlight]
}, [updatePeerMetadata]);
return ;
}
```
## Reading metadata
Peer metadata is available as the `metadata` property for each peer. Therefore, when you list your peers with the `usePeers` hook, you can read
the metadata associated with them.
Note that the `metadata.peer` property contains only the metadata set by the client SDK (as in the examples examples above).
The metadata set on the server side is available as `metadata.server`.
Learn more about server metadata [here](../backend/server-setup#metadata).
```tsx
type PeerMetadata = {
displayName: string;
};
type ServerMetadata = {
realName: string;
};
export function ListAllNames() {
const { remotePeers } = usePeers(); // [!code highlight]
return (
{remotePeers.map((peer) => (
// [!code highlight:5]
Display name: {peer.metadata?.peer.displayName}
Real name: {peer.metadata?.server.realName}
))}
);
}
```
```tsx
type PeerMetadata = {
displayName: string;
};
type ServerMetadata = {
realName: string;
};
export function ListAllNames() {
const { remotePeers } = usePeers(); // [!code highlight]
return (
{remotePeers.map((peer) => (
// [!code highlight:4]
Display name: {peer.metadata?.peer?.displayName || "Unknown"}
Real name: {peer.metadata?.server?.realName || "Unknown"}
))}
);
}
```
---
## 0.25.x Migration Guide
# 0.25.x Migration Guide Mobile
# Upgrading @fishjam-cloud/react-native-client from 0.24 to 0.25
This guide will help you upgrade your React Native application from `@fishjam-cloud/react-native-client@0.24.x` to `@fishjam-cloud/react-native-client@0.25.x`.
## Overview
Version `0.25` of `@fishjam-cloud/react-native-client` introduces API changes that may require code updates.
## Required Android Permissions
Add the following WebRTC permissions to your Android configuration in `app.json`:
```json
{
"expo": {
"android": {
"permissions": [
"android.permission.CAMERA",
"android.permission.RECORD_AUDIO",
"android.permission.MODIFY_AUDIO_SETTINGS",
"android.permission.ACCESS_NETWORK_STATE"
]
}
}
}
```
## FishjamProvider Setup
In `0.25`, wrapping your app with `FishjamProvider` is required to provide the Fishjam ID context.
### Before
```tsx
// @noErrors
// ---cut---
const { joinRoom } = useConnection();
// fishjamId was passed directly to joinRoom
await joinRoom({ fishjamId: "your-fishjam-id", peerToken: "..." });
```
### After
```tsx
// ---cut---
// Wrap your app with FishjamProvider
export default function App() {
return (
// [!code highlight]
// [!code highlight]
);
}
const YourApp = () => {
return (
<>
Your app content
>
);
};
```
The `fishjamId` is now provided through the context, so you no longer need to pass it to `joinRoom` or `useSandbox`.
## Device Initialization
### Before
```tsx
// @noErrors
const { prepareCamera } = useCamera();
await prepareCamera({ cameraEnabled: true });
```
### After
```tsx
const { initializeDevices } = useInitializeDevices();
// Initialize devices when you first want to stream
await initializeDevices({ enableAudio: false }); // or initializeDevices() for both audio and video
```
:::important
On mobile, you should use `initializeDevices()` when you first want to stream. This gives your app access to all available devices and automatically requests camera and microphone permissions. After initialization, you can use `startCamera`/`stopCamera` or `startMicrophone`/`stopMicrophone` to manage device state.
:::
## Video Rendering and Accessing Peer Tracks
### Before
```tsx
// @noErrors
// ---cut---
usePeers,
VideoRendererView,
} from "@fishjam-cloud/react-native-client";
const { remotePeers, localPeer } = usePeers();
const videoTracks = remotePeers.flatMap((peer) =>
peer.tracks.filter((track) => track.type === "Video" && track.isActive),
);
const localTrack = localPeer?.tracks.find((t) => t.type === "Video");
{localTrack && (
)}
{videoTracks.map((track) => (
))}
;
```
### After
```tsx
// ---cut---
usePeers,
RTCView,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) {
return (
<>
{stream && (
)}
>
);
}
const { localPeer, remotePeers } = usePeers();
{
localPeer?.cameraTrack?.stream && (
);
}
{
remotePeers.map((peer) => (
<>
{peer.cameraTrack?.stream && (
)}
>
));
}
```
Key changes:
- `VideoRendererView` → `RTCView`
- `trackId` prop → `mediaStream` prop
- `peer.tracks` array → `peer.cameraTrack` and `peer.microphoneTrack` properties
- `track.isActive` removed (check if stream exists instead)
- `track.type` removed (use specific track properties)
## Connection API
### Before
```tsx
// @noErrors
const { joinRoom } = useConnection();
const { getSandboxPeerToken } = useSandbox({ fishjamId: "your-id" });
const peerToken = await getSandboxPeerToken("roomName", "peerName");
await joinRoom({ fishjamId: "your-id", peerToken });
```
### After
```tsx
const { joinRoom } = useConnection();
const sandboxApiUrl = "your-sandbox-api-url-here";
const { getSandboxPeerToken } = useSandbox({ sandboxApiUrl });
const peerToken = await getSandboxPeerToken("roomName", "peerName");
await joinRoom({ peerToken }); // fishjamId passed through FishjamProvider
```
## Device Management
### Camera Device Selection
### Before
```tsx
// @noErrors
const { cameras, switchCamera, currentCamera } = useCamera();
// find first camera facing opposite direction than current camera
const otherCamera = cameras.find(
(camera) => camera.facingDirection !== currentCamera?.facingDirection,
);
if (otherCamera) {
switchCamera(otherCamera.id);
}
```
### After
```tsx
const { cameraDevices, selectCamera } = useCamera();
// Select camera by deviceId
const nextCamera = cameraDevices[0];
if (nextCamera) {
selectCamera(nextCamera.deviceId);
}
```
Key changes:
- `cameras` → `cameraDevices`
- `switchCamera` → `selectCamera` (takes `deviceId` instead of direction)
- `facingDirection` property removed
### Camera Control
### Before
```tsx
// @noErrors
// ---cut---
const { isCameraOn, toggleCamera } = useCamera();
;
```
### After
```tsx
const { startCamera, stopCamera, toggleCamera } = useCamera();
await startCamera();
await stopCamera();
toggleCamera();
```
## Screen Sharing
### Before
```tsx
// @noErrors
// ---cut---
const { toggleScreenShare, isScreenShareOn } = useScreenShare();
const onPressToggle = useCallback(
() => toggleScreenShare(),
[toggleScreenShare],
);
;
```
### After
```tsx
// ---cut---
const { startStreaming, stopStreaming, stream } = useScreenShare();
const onPressToggle = () => {
if (stream) {
stopStreaming();
} else {
startStreaming();
}
};
;
```
Key changes:
- `toggleScreenShare()` → `startStreaming()` / `stopStreaming()`
- `isScreenShareOn` → check if `stream` exists
## Picture in Picture
### Before
```tsx
// @noErrors
// ---cut---
export function VideoCallScreen() {
return (
{/* Your video call UI */}
);
}
```
### After
```tsx
RTCPIPView,
startPIP,
stopPIP,
useCamera,
} from "@fishjam-cloud/react-native-client";
export function VideoCallScreen() {
const pipViewRef = useRef>(null);
const { cameraStream } = useCamera();
return (
startPIP(pipViewRef as any)} />
stopPIP(pipViewRef as any)} />
{cameraStream && (
)}
);
}
```
Key changes:
- `PipContainerView` → `RTCPIPView`
- Requires a ref for manual `startPIP`/`stopPIP` control
- Added `pip` prop for configuration
## Livestreaming Imports
### Before
```tsx
// @noErrors
useLivestreamStreamer,
useLivestreamViewer,
} from "@fishjam-cloud/react-native-client/livestream";
```
### After
```tsx
useLivestreamStreamer,
useLivestreamViewer,
} from "@fishjam-cloud/react-native-client";
```
The livestreaming hooks are now exported from the main package instead of a separate `/livestream` subpath.
## Removed Hooks and APIs
The following hooks and APIs have been removed and are no longer available:
### Permission Hooks
### Before
```tsx
// @noErrors
useCameraPermissions,
useMicrophonePermissions,
} from "@fishjam-cloud/react-native-client";
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [micPermission, requestMicPermission] = useMicrophonePermissions();
```
### After
Permissions are now handled automatically by the SDK. When you call initializeDevices(), the SDK will automatically request camera and microphone permissions if they haven't been granted yet.
---
## Picture in Picture
# Picture in Picture Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
Picture in Picture (PiP) allows your app to display video content in a small window that floats above other apps when the user backgrounds your application. This is especially useful for video calls and livestreaming where users want to multitask while staying connected.
The SDK provides two Picture in Picture modes depending on your use case:
- **Conferencing**: For interactive video calls with multiple participants. Uses a **custom split-screen layout** in the PiP window showing your local camera (left) and the active speaker (right) with automatic voice activity detection.
- **Livestreaming**: For viewing livestreams. Displays the **full WHEP stream video** in the Picture in Picture window using the native video player's PiP functionality.
Choose the scenario that matches your application below.
## Installation
You need to modify your `app.json` file and add our plugin with Picture in Picture support:
```json title='app.json'
{
"expo": {
...
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"android": {
"supportsPictureInPicture": true
},
"ios": {
"supportsPictureInPicture": true
}
}
]
]
}
}
```
**Android Configuration**
Add the `android:supportsPictureInPicture` attribute to your main activity in `AndroidManifest.xml`:
```xml title='AndroidManifest.xml'
```
**iOS Configuration**
Add the `audio` background mode to your `Info.plist`:
```xml title='Info.plist'
UIBackgroundModes
audio
```
:::tip[When do you need `voip`?]
The `audio` background mode is sufficient for PiP itself. The microphone continues to work in the background with just `audio`, but if your app also needs to keep the **camera** active while in the background (e.g., an ongoing video call), you need the `voip` background mode. See the [Background calls](./background-streaming) guide for setup instructions.
Adding `voip` to `UIBackgroundModes` triggers additional scrutiny during Apple's App Store review — only add it if your app genuinely requires VoIP functionality.
:::
You need to modify your `app.json` file and add our plugin with Picture in Picture support:
```json title='app.json'
{
"expo": {
...
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"android": {
"supportsPictureInPicture": true
},
"ios": {
"supportsPictureInPicture": true
}
}
]
]
}
}
```
**Android Configuration**
Add the `android:supportsPictureInPicture` attribute to your main activity in `AndroidManifest.xml`:
```xml title='AndroidManifest.xml'
```
**iOS Configuration**
Add the `audio` background mode to your `Info.plist`:
```xml title='Info.plist'
UIBackgroundModes
audio
```
## Usage
### Basic Usage
The `RTCPIPView` component displays video content that can be shown in Picture in Picture mode. Use `startPIP` and `stopPIP` to control PIP manually:
```tsx
RTCPIPView,
startPIP,
stopPIP,
useCamera,
} from "@fishjam-cloud/react-native-client";
export function VideoCallScreen() {
const pipViewRef = useRef>(null);
const { cameraStream } = useCamera();
return (
startPIP(pipViewRef as any)} />
stopPIP(pipViewRef as any)} />
{cameraStream && (
)}
);
}
```
By default, Picture in Picture will start automatically when the app goes to the background and stop when it returns to the foreground.
### Configuration Options
You can customize the Picture in Picture behavior using the `pip` prop on `RTCPIPView`:
```tsx
export function VideoCallScreen() {
const pipViewRef = useRef>(null);
const { cameraStream } = useCamera();
return (
{cameraStream && (
)}
);
}
```
#### Configuration Properties
**startAutomatically**: When `true`, Picture in Picture starts automatically when the app goes to the background. Default: `true`
**stopAutomatically**: When `true`, Picture in Picture stops automatically when the app returns to the foreground. Default: `true`
**enabled**: When `true`, enables Picture in Picture functionality for this view.
### Manual Control
For more control over when Picture in Picture starts and stops, use the `startPIP` and `stopPIP` functions with a ref:
```tsx
RTCPIPView,
startPIP,
stopPIP,
useCamera,
} from "@fishjam-cloud/react-native-client";
export function VideoCallScreen() {
const pipViewRef = useRef>(null);
const { cameraStream } = useCamera();
const handleStartPip = () => {
startPIP(pipViewRef as any);
};
const handleStopPip = () => {
stopPIP(pipViewRef as any);
};
return (
{cameraStream && (
)}
);
}
```
### Complete Example
Here's a complete example showing Picture in Picture with a video call:
```tsx
RTCPIPView,
RTCView,
startPIP,
stopPIP,
usePeers,
type MediaStream,
} from "@fishjam-cloud/react-native-client";
function VideoPlayer({ stream }: { stream: MediaStream | null }) {
if (!stream) return No video ;
return (
);
}
export function VideoCallScreen() {
const pipViewRef = useRef>(null);
const { localPeer, remotePeers } = usePeers();
const firstRemotePeer = remotePeers[0];
const remoteStream = firstRemotePeer?.cameraTrack?.stream;
return (
startPIP(pipViewRef as any)} />
stopPIP(pipViewRef as any)} />
{/* Render local video */}
{localPeer?.cameraTrack?.stream && (
)}
{/* Render first remote peer with PiP support */}
{remoteStream && (
)}
{/* Render remaining remote videos */}
peer.id}
renderItem={({ item: peer }) => (
{peer.cameraTrack?.stream && (
)}
)}
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
video: {
width: 200,
height: 200,
},
});
```
### Platform-Specific Behavior
Both Android and iOS display a split-screen layout in Picture in Picture mode with your local camera on the left and the active speaker on the right. The active speaker is automatically determined by voice activity detection (VAD).
#### Android
Picture in Picture is supported on Android 8.0 (API level 26) and above. The system automatically manages the PiP window size and position. Users can tap the PiP window to return to your app. On Android 12 (API level 31) and above, automatic Picture in Picture is supported when `startAutomatically` is `true`.
#### iOS
Picture in Picture on iOS can be used both while the app is in the foreground (as an in-app overlay) and when the app is backgrounded. The `audio` background mode is required for PiP to continue displaying video after the app moves to the background.
With only the `audio` background mode, the microphone continues to work but the outgoing camera track stops when the app is backgrounded. This is sufficient for audio-only calls or receive-only scenarios like livestream viewing. For video calls where the camera needs to keep working in the background, the `voip` background mode is additionally required — see the [Background calls](./background-streaming) guide.
When `allowsCameraInBackground` is enabled together with the `voip` background mode, the camera continues to capture in PiP mode (iOS 16.0+).
### Active Speaker Detection
The secondary view (right side) automatically displays the remote participant who is currently speaking, based on voice activity detection (VAD). When no one is speaking, it will show the last active speaker if available, fall back to the first remote participant with a video track, or show the placeholder text if no remote video is available.
This automatic switching ensures the most relevant video is always displayed in the Picture in Picture window.
### Combining with Background Calls
If your app needs to keep the camera active during a video call while in the background, PiP alone is not enough. Without the `voip` background mode on iOS, PiP displays received video and the microphone continues to work, but the outgoing camera track stops when the app is backgrounded.
To keep a full two-way call active in the background with a PiP overlay, combine PiP with [background calls](./background-streaming):
- **Android**: Enable foreground services alongside PiP.
- **iOS**: Enable the `voip` background mode alongside PiP.
:::caution
Adding `voip` to `UIBackgroundModes` triggers additional scrutiny during Apple's App Store review. Only enable it if your app genuinely requires VoIP functionality (active calls in the background). For receive-only scenarios like livestream viewing, the `audio` background mode configured during [PiP installation](#installation) is sufficient.
:::
Example configuration combining both features:
```json title='app.json (Expo)'
{
"expo": {
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"android": {
"enableForegroundService": true,
"supportsPictureInPicture": true
},
"ios": {
"enableVoIPBackgroundMode": true,
"supportsPictureInPicture": true
}
}
]
]
}
}
```
### Basic Usage
Use `RTCPIPView` to display the livestream with Picture in Picture support:
```tsx
RTCPIPView,
useLivestreamViewer,
useSandbox,
} from "@fishjam-cloud/react-native-client";
const SANDBOX_API_URL = "your-sandbox-api-url-here";
export function LivestreamScreen() {
const pipViewRef = useRef>(null);
const { connect, stream } = useLivestreamViewer();
const { getSandboxViewerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
useEffect(() => {
const connectToStream = async () => {
const token = await getSandboxViewerToken("room-name");
await connect({ token });
};
connectToStream();
}, []);
return (
{stream ? (
) : (
Connecting to stream...
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
viewer: {
flex: 1,
},
});
```
### Configuration Options
Configure Picture in Picture behavior using the `pip` prop:
```jsx
```
#### Configuration Properties
**enabled**: Enable or disable Picture in Picture functionality.
**startAutomatically**: When `true`, Picture in Picture starts automatically when the app goes to the background. Default: `true`
**stopAutomatically**: When `true`, Picture in Picture stops automatically when the app returns to the foreground. Default: `true`
### Complete Example
Here's a complete example showing how to connect to a livestream and display it with Picture in Picture:
```tsx
RTCPIPView,
useLivestreamViewer,
useSandbox,
startPIP,
stopPIP,
} from "@fishjam-cloud/react-native-client";
const SANDBOX_API_URL = "your-sandbox-api-url-here";
export function LivestreamViewerScreen() {
const pipViewRef = useRef>(null);
const { getSandboxViewerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const { connect, disconnect, stream } = useLivestreamViewer();
useEffect(() => {
const connectToStream = async () => {
try {
const token = await getSandboxViewerToken("room-name");
await connect({ token });
} catch (err) {
console.error("Failed to connect to livestream:", err);
}
};
connectToStream();
return () => {
disconnect();
};
}, []);
return (
startPIP(pipViewRef as any)} />
stopPIP(pipViewRef as any)} />
{stream ? (
) : (
Connecting to stream...
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#000",
},
viewer: {
flex: 1,
},
loading: {
color: "#fff",
textAlign: "center",
marginTop: 20,
},
});
```
### Platform-Specific Behavior
#### Android
Picture in Picture is supported on Android 8.0 (API level 26) and above. The native video player's PiP window displays the WHEP stream. PiP automatically stops when the app returns to the foreground. Users can tap the PiP window to return to your app.
#### iOS
Picture in Picture requires the `audio` background mode. Uses the native AVPictureInPictureController to display the video. The WHEP stream continues playing in the PiP window. When `autoStopPip` is enabled, PiP stops automatically when returning to the app.
---
## Reconnect
# Reconnect Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
If your connection is lost while you are connected to a room, the app will automatically handle the reconnection process.
You can monitor these events by utilizing the [`useConnection`](../../api/mobile/functions/useConnection) hook.
### Example hook that logs the current status to the console
```ts
ReconnectionStatus,
useConnection,
} from "@fishjam-cloud/react-native-client";
export function useLogConnectionStatus() {
const prevStatus = useRef("idle");
const { reconnectionStatus } = useConnection(); // [!code highlight]
useEffect(() => {
if (prevStatus.current === reconnectionStatus) return;
prevStatus.current = reconnectionStatus;
switch (reconnectionStatus) {
case "error":
return console.log("Failed to reconnect");
case "reconnecting":
return console.log("Connection is broken, reconnecting...");
default:
return console.log("Connected successfully");
}
}, [reconnectionStatus]);
}
```
---
## Screen sharing
# Screen sharing Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
Our SDK also allow to stream content of mobile device screen.
## Installation
### Android
To enable screen sharing on android, you need enable foreground services. Here is [instruction on how to enable it](./background-streaming).
### iOS
To enable screen sharing on iOS, you need to follow the steps below.
:::tip[Background streaming during screen sharing]
If you want to continue screen sharing when the app goes to the background, you need to enable VoIP background mode by setting `enableVoIPBackgroundMode: true` in the plugin configuration or adding the VoIP background mode to your `Info.plist`.
See the [background calls documentation](./background-streaming) for detailed instructions and code examples.
:::
You need to modify `app.json` file and add our plugin:
```json title='app.json'
{
"expo": {
...
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"ios": {
"enableScreensharing": true,
"enableVoIPBackgroundMode": true
},
"android": {
"enableForegroundService": true
}
}
]
]
}
}
```
#### EAS Build Configuration
If you're using [EAS Build](https://docs.expo.dev/build/introduction/), you need to declare the iOS App Extension in your `app.json` file. Otherwise your build will fail with missing provisioning profiles.
Add the following configuration to ensure the required credentials are generated and validated:
```json title='app.json'
{
"expo": {
...
"extra": {
"eas": {
"build": {
"experimental": {
"ios": {
"appExtensions": [
{
"targetName": "FishjamScreenBroadcastExtension",
"bundleIdentifier": "YOUR_BUNDLE_IDENTIFIER.FishjamScreenBroadcastExtension",
"entitlements": {
"com.apple.security.application-groups": [
"group.YOUR_BUNDLE_IDENTIFIER"
]
}
}
]
}
}
}
}
}
}
}
```
Replace `YOUR_BUNDLE_IDENTIFIER` with your app's bundle identifier (for example, `com.myapp.example`).
:::note
Learn more about iOS App Extensions with EAS Build in the [Expo documentation](https://docs.expo.dev/build-reference/app-extensions/).
:::
Configuring screen sharing on iOS is a little complicated.
1. Add camera and microphone permissions to your main `Info.plist`.
```xml title='Info.plist'
NSCameraUsageDescription
Allow $(PRODUCT_NAME) to use the camera
NSMicrophoneUsageDescription
Allow $(PRODUCT_NAME) to use the microphone
```
1. Open your `.xcworkspace` in Xcode
1. Create new Broadcast Upload Extension. Select `File → New → Target... → Broadcast Upload Extension → Next`. Choose the name for the new target, select Swift language and deselect "Include UI Extension".
1. Configure app group. Go to "Signing & Capabilities" tab, click "+ Capability" button in upper left corner and select "App Groups".
Then in the "App Groups" add a new group or select existing. Usually group name has format `group.`. Verify that both app and extension targets have app group and dev team set correctly.
1. A new folder with app extension should appear on the left.
Replace `SampleHandler.swift` with `FishjamBroadcastHandler.swift` and this code:
```swift
let appGroup = "group.{{BUNDLE_IDENTIFIER}}"
let logger = OSLog(subsystem: "{{BUNDLE_IDENTIFIER}}.FishjamBroadcastHandler", category: "Broadcaster")
class FishjamBroadcastSampleHandler: RPBroadcastSampleHandler {
let broadcastSource = BroadcastSampleSource(appGroup: appGroup)
var started: Bool = false
override func broadcastStarted(withSetupInfo _: [String: NSObject]?) {
started = broadcastSource.connect()
guard started else {
os_log("failed to connect with ipc server", log: logger, type: .debug)
super.finishBroadcastWithError(NSError(domain: "", code: 0, userInfo: nil))
return
}
broadcastSource.started()
}
override func broadcastPaused() {
broadcastSource.paused()
}
override func broadcastResumed() {
broadcastSource.resumed()
}
override func broadcastFinished() {
broadcastSource.finished()
}
override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {
guard started else {
return
}
broadcastSource.processFrame(sampleBuffer: sampleBuffer, ofType: sampleBufferType)
}
}
```
Replace `{{BUNDLE_IDENTIFIER}}` with your bundle identifier.
1. In project's Podfile add the following code:
```rb title='Podfile'
target 'FishjamScreenBroadcastExtension' do
pod 'FishjamCloudClient/Broadcast'
end
```
1. Add the following constants in your `Info.plist`:
```xml title='Info.plist'
AppGroupName
group.{{BUNDLE_IDENTIFIER}}
ScreencastExtensionBundleId
{{BUNDLE_IDENTIFIER}}.FishjamScreenBroadcastExtension
```
1. If you want to enable background streaming during screen sharing, add VoIP background mode to your `Info.plist`:
```xml title='Info.plist'
UIBackgroundModes
voip
```
1. Run `pod install`, rebuild your app and enjoy!
## Usage
You can use [`useScreenShare`](../../api/mobile/functions/useScreenShare) hook to enable screen sharing.
:::tip[Permissions]
Permission request is handled for you as soon as you call [`startStreaming`](../../api/mobile/functions/useScreenShare).
:::
:::tip[Android Foreground Service]
On Android API level >= 24, you must use a foreground service when screen sharing. This will be handled automatically for you. If you'd like to configure service behavior (like notification content, other permissions). Checkout `useForegroundService` hook.
:::
You can enable/disable screen sharing with [`startStreaming`](../../api/mobile/functions/useScreenShare) and [`stopStreaming`](../../api/mobile/functions/useScreenShare) methods.
And check current state by checking if [`stream`](../../api/mobile/functions/useScreenShare) exists.
```tsx
export function ScreenShareButton() {
const { startStreaming, stopStreaming, stream } = useScreenShare(); // [!code highlight]
const onPressToggle = useCallback(() => {
if (stream) {
stopStreaming(); // [!code highlight]
} else {
startStreaming(); // [!code highlight]
}
}, [stream, startStreaming, stopStreaming]);
return (
);
}
```
---
## Simulcast
This guide shows how to enable simulcast (multi-quality video streaming) so that senders publish multiple quality variants and receivers can independently choose which variant to receive.
## Prerequisites
Before configuring simulcast, you must be [connected to a room](./connecting) with video enabled.
:::tip
For a conceptual overview of how simulcast works, including when to use it and how variants flow through the server, see [Simulcast](../../explanation/simulcast).
:::
---
## Step 1: Configure sent qualities (sender side)
Pass `sentQualities` in the `videoConfig` prop of `FishjamProvider` to control which quality variants the sender publishes.
```tsx
const fishjamId = "your-fishjam-id";
// ---cut---
function App() {
return (
{/* your app */}
);
}
```
```tsx
const fishjamId = "your-fishjam-id";
// ---cut---
function App() {
return (
{/* your app */}
);
}
```
To disable simulcast entirely, pass `false`:
```tsx
const fishjamId = "your-fishjam-id";
// ---cut---
function App() {
return (
{/* your app */}
);
}
```
---
## Step 2: Select received quality (receiver side)
Remote tracks expose `setReceivedQuality`, which tells the server which variant to forward for that track.
```tsx
function VideoPlayer({ stream }: { stream: MediaStream | null }) {
return ;
}
function QualitySelector({ track }: { track: RemoteTrack }) {
return ;
}
// ---cut---
function RemoteVideos() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) =>
peer.tracks.map((track) => (
)),
)}
);
}
```
```tsx
usePeers,
type RemoteTrack,
RTCView,
} from "@fishjam-cloud/react-native-client";
function QualitySelector({ track }: { track: RemoteTrack }) {
return ;
}
// ---cut---
function RemoteVideos() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) =>
peer.tracks.map((track) => (
{track.stream && (
)}
)),
)}
);
}
```
---
## Step 3: Call `setReceivedQuality` based on your needs
In practice, you would call `setReceivedQuality` based on your application's state. For example, you could request high quality for a full-screen participant and low quality for thumbnails in a grid. The manual quality selector below is a simplified example to illustrate the API:
```tsx
const variants = [
{ label: "Low", value: Variant.VARIANT_LOW },
{ label: "Medium", value: Variant.VARIANT_MEDIUM },
{ label: "High", value: Variant.VARIANT_HIGH },
];
function QualitySelector({ track }: { track: RemoteTrack }) {
return (
{variants.map(({ label, value }) => (
track.setReceivedQuality(value)}>
{label}
))}
);
}
```
```tsx
// ---cut---
const variants = [
{ label: "Low", value: Variant.VARIANT_LOW },
{ label: "Medium", value: Variant.VARIANT_MEDIUM },
{ label: "High", value: Variant.VARIANT_HIGH },
];
function QualitySelector({ track }: { track: RemoteTrack }) {
return (
{variants.map(({ label, value }) => (
track.setReceivedQuality(value)}
>
{label}
))}
);
}
const styles = StyleSheet.create({
row: { flexDirection: "row", gap: 8, marginTop: 4 },
pill: {
paddingHorizontal: 12,
paddingVertical: 6,
borderRadius: 16,
backgroundColor: "#e0e0e0",
},
});
```
---
## Type differences: `Track` vs `RemoteTrack`
When using `usePeers`, the track types differ between local and remote peers:
- **`localPeer.tracks`** are typed as `Track` (no quality selection methods)
- **`remotePeers[].tracks`** are typed as `RemoteTrack` (extends `Track` with `setReceivedQuality`)
This means `setReceivedQuality` is only available on tracks from remote peers, which is the correct behavior. You don't need to select a quality variant for your own video.
---
## See also
- [Simulcast explanation](../../explanation/simulcast): conceptual overview of how simulcast works
- [Connecting to a room](./connecting): prerequisite for using simulcast
---
## Streaming media
This guide covers the basics of initializing and using camera and microphone devices. For more advanced device management (selecting specific devices, device switching, muting, etc.), see the [Managing devices](./managing-devices) guide.
## Initialize access to your devices
Fishjam provides an API to browse and manage media devices you can use.
To ask the browser for permission to list the available devices,
call the [`initializeDevices`](../../api/web/functions/useInitializeDevices#initializedevices)
function from [`useInitializeDevices`](../../api/web/functions/useInitializeDevices) hook.
You can choose whether to initialize both camera and microphone devices or just one of them by passing [`InitializeDevicesSettings`](../../api/web/type-aliases/InitializeDevicesSettings)
as an argument. By default, both camera and microphone are initialized.
The [`initializeDevices`](../../api/web/functions/useInitializeDevices#initializedevices) function will return a [`Promise`](../../api/web/type-aliases/InitializeDevicesResult) object.
```ts
export function useExample() {
const { initializeDevices } = useInitializeDevices();
useEffect(() => {
initializeDevices().then((result) => {
// optionally handle the result
console.log(result);
});
}, [initializeDevices]);
}
```
:::note
The [`useInitializeDevices`](../../api/web/functions/useInitializeDevices) hook gives you the convenience of asking the user for all permissions at once.
It is not the only way to enable the device. You can just toggle the device using [`useCamera`](../../api/web/functions/useCamera) or [`useMicrophone`](../../api/web/functions/useMicrophone) hooks.
:::
On mobile, you should use `initializeDevices()` when you first want to stream. This gives your app access to all available devices and automatically requests camera and microphone permissions. The SDK will show the system permission dialog if permissions haven't been granted yet.
Once devices are initialized, you can manage their state using the methods described in the [Managing devices](./managing-devices) guide.
## Device API
To manage users' camera and microphone devices, use the respective [`useCamera`](../../api/web/functions/useCamera) and [`useMicrophone`](../../api/web/functions/useMicrophone) hooks. Both of them have similar API. To keep things simple, we will just use the camera hook.
```tsx
export function ExampleCameraPreview() {
const videoRef = useRef(null);
const { activeCamera, selectCamera, cameraStream, cameraDevices } =
useCamera(); // [!code highlight]
useEffect(() => {
if (!videoRef.current) return;
videoRef.current.srcObject = cameraStream ?? null;
}, [cameraStream]);
return (
Active camera: {activeCamera?.label ?? "None"}
selectCamera(e.target.value)}>
{cameraDevices.map(({ label, deviceId }) => (
{label}
))}
{cameraStream && } // [!code highlight]
);
}
```
To manage users' camera and microphone devices, use the respective [`useCamera`](../../api/mobile/functions/useCamera) and [`useMicrophone`](../../api/mobile/functions/useMicrophone) hooks. Both of them have similar API. To keep things simple, we will just use the camera hook.
You can preview your camera stream using the `RTCView` component.
```tsx
export function CameraPreview() {
const { startCamera, cameraStream } = useCamera(); // [!code highlight]
useEffect(() => {
startCamera(); // [!code highlight]
}, [startCamera]);
return (
{cameraStream ? (
) : (
No camera stream
)}
);
}
```
---
## Text Chat
This guide shows how to implement text chat in your application using data channels. Data channels allow you to send and receive arbitrary binary data between peers in a room.
## Prerequisites
Before implementing text chat, you must be [connected to a room](./connecting). Data channels only work after you have successfully joined a room.
:::tip
For a deeper understanding of how data channels work, including channel types and broadcast behavior, see [Data Channels](../../explanation/data-channels).
:::
---
## Step 1 — Set up the chat hook
Use the [`useDataChannel`](/api/web/functions/useDataChannel) (web) or [`useDataChannel`](/api/mobile/functions/useDataChannel) (mobile) hook to work with data channels. The typical flow is:
1. Initialize the data channel after connecting to a room
2. Subscribe to incoming messages
3. Publish messages to other peers
```tsx
export function useChat() {
const { peerStatus } = useConnection();
const {
initializeDataChannel,
publishData,
subscribeData,
dataChannelReady,
} = useDataChannel();
const [messages, setMessages] = useState([]);
// Step 1: Initialize data channel when connected
useEffect(() => {
if (peerStatus === "connected") {
initializeDataChannel();
}
}, [peerStatus, initializeDataChannel]);
// Step 2: Subscribe to incoming messages
useEffect(() => {
if (!dataChannelReady) return;
const unsubscribe = subscribeData(
(data: Uint8Array) => {
const message = new TextDecoder().decode(data);
setMessages((prev) => [...prev, message]);
},
{ reliable: true },
);
return unsubscribe;
}, [subscribeData, dataChannelReady]);
// Step 3: Publish messages
const sendMessage = useCallback(
(text: string) => {
if (!dataChannelReady) return;
const encoded = new TextEncoder().encode(text);
publishData(encoded, { reliable: true });
},
[publishData, dataChannelReady],
);
return { messages, sendMessage, ready: dataChannelReady };
}
```
```tsx
useConnection,
useDataChannel,
} from "@fishjam-cloud/react-native-client";
export function useChat() {
const { peerStatus } = useConnection();
const {
initializeDataChannel,
publishData,
subscribeData,
dataChannelReady,
dataChannelLoading,
dataChannelError,
} = useDataChannel();
const [messages, setMessages] = useState([]);
useEffect(() => {
if (peerStatus === "connected") {
initializeDataChannel();
}
}, [peerStatus, initializeDataChannel]);
useEffect(() => {
if (dataChannelLoading || !dataChannelReady) return;
const unsubscribe = subscribeData(
(data: Uint8Array) => {
const message = new TextDecoder().decode(data);
setMessages((prev) => [...prev, message]);
},
{ reliable: true },
);
return unsubscribe;
}, [dataChannelReady, dataChannelLoading, subscribeData]);
const sendMessage = useCallback(
(text: string) => {
if (!dataChannelReady) return;
const encoded = new TextEncoder().encode(text);
publishData(encoded, { reliable: true });
},
[publishData, dataChannelReady],
);
return {
messages,
sendMessage,
ready: dataChannelReady,
loading: dataChannelLoading,
error: dataChannelError,
};
}
```
---
## Step 2 — Use the chat hook in your component
Once you have the hook, you can use it in any component to send and display messages:
```tsx
function useChat() {
const { peerStatus } = useConnection();
const {
initializeDataChannel,
publishData,
subscribeData,
dataChannelReady,
} = useDataChannel();
const [messages, setMessages] = useState([]);
useEffect(() => {
if (peerStatus === "connected") {
initializeDataChannel();
}
}, [peerStatus, initializeDataChannel]);
useEffect(() => {
if (!dataChannelReady) return;
const unsubscribe = subscribeData(
(data: Uint8Array) => {
const message = new TextDecoder().decode(data);
setMessages((prev) => [...prev, message]);
},
{ reliable: true },
);
return unsubscribe;
}, [subscribeData, dataChannelReady]);
const sendMessage = useCallback(
(text: string) => {
if (!dataChannelReady) return;
const encoded = new TextEncoder().encode(text);
publishData(encoded, { reliable: true });
},
[publishData, dataChannelReady],
);
return { messages, sendMessage, ready: dataChannelReady };
}
// ---cut---
function ChatPanel() {
const { messages, sendMessage, ready } = useChat();
const [input, setInput] = useState("");
const handleSend = () => {
if (input.trim()) {
sendMessage(input);
setInput("");
}
};
if (!ready) {
return Connecting to chat...;
}
return (
{messages.map((msg: string, i: number) => (
{msg}
))}
setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSend()}
/>
Send
);
}
```
```tsx
useConnection,
useDataChannel,
} from "@fishjam-cloud/react-native-client";
function useChat() {
const { peerStatus } = useConnection();
const {
initializeDataChannel,
publishData,
subscribeData,
dataChannelReady,
} = useDataChannel();
const [messages, setMessages] = useState([]);
useEffect(() => {
if (peerStatus === "connected") {
initializeDataChannel();
}
}, [peerStatus, initializeDataChannel]);
useEffect(() => {
if (!dataChannelReady) return;
const unsubscribe = subscribeData(
(data: Uint8Array) => {
const message = new TextDecoder().decode(data);
setMessages((prev) => [...prev, message]);
},
{ reliable: true },
);
return unsubscribe;
}, [subscribeData, dataChannelReady]);
const sendMessage = useCallback(
(text: string) => {
if (!dataChannelReady) return;
const encoded = new TextEncoder().encode(text);
publishData(encoded, { reliable: true });
},
[publishData, dataChannelReady],
);
return { messages, sendMessage, ready: dataChannelReady };
}
// ---cut---
function ChatPanel() {
const { messages, sendMessage, ready } = useChat();
const [input, setInput] = useState("");
const handleSend = () => {
if (input.trim()) {
sendMessage(input);
setInput("");
}
};
if (!ready) {
return Connecting to chat... ;
}
return (
String(i)}
renderItem={({ item }) => {item} }
/>
Send
);
}
```
---
## Why use the reliable channel?
For chat messages, we use `{ reliable: true }` because:
- **Ordered delivery**: Messages arrive in the order they were sent
- **Guaranteed delivery**: All messages will be delivered, with automatic retransmission if needed
This ensures no chat messages are lost or arrive out of order.
---
## See also
- [Data Channels](../../explanation/data-channels) — detailed explanation of channel types and broadcast behavior
- [Connecting to a room](./connecting) — prerequisite for using data channels
- [`useDataChannel` API reference (Web)](../../api/web/functions/useDataChannel)
- [`useDataChannel` API reference (Mobile)](../../api/mobile/functions/useDataChannel)
---
## VoIP calls
# VoIP calls Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
Your app can ring like the phone app: an incoming call shows up as a **native call**,
full-screen on a locked phone or as a call notification while the phone is in use,
even when the app is backgrounded or killed. A push notification wakes the app, and
answering the call has it join a Fishjam room, where the call takes place.
Each platform uses its own transport:
- **iOS**: a **VoIP push** over **APNs** wakes the app through **PushKit**, and the
SDK reports the call to **CallKit**.
- **Android**: a **high-priority data message** over **FCM** wakes the app, and the
SDK surfaces the call through **Telecom**.
**PushKit**, **CallKit**, and **Telecom** are the operating systems' own native VoIP
frameworks. The SDK drives them for you, so a single JS API works on both platforms.
Registering calls with the OS also gets you **remote surface control** for free: the
user can handle a call from a Bluetooth headset or Android Auto, and those actions
reach your app as the same state changes described in this guide.
:::tip[Working example]
Everything in this guide is wired together in the
[voip-call example](https://github.com/fishjam-cloud/web-client-sdk/tree/main/examples/mobile-client/voip-call),
whose README covers running it, including the APNs and FCM push credentials you must
generate yourself.
:::
:::info[You need a push sender]
Delivering a push notification is your backend's job: it sends a **VoIP push via APNs** (iOS)
or a **high-priority data message via FCM** (Android) to the device token your app
reports. This guide covers only the **app** side: wiring, native config, and the JS
call flow. For a working sender, see our
[voip-call example server](https://github.com/fishjam-cloud/web-client-sdk/tree/main/examples/mobile-client/voip-call/server).
Wiring up the sending credentials is backend work too. For iOS, connect to APNs with a
[certificate-based](https://developer.apple.com/documentation/usernotifications/establishing-a-certificate-based-connection-to-apns)
or [token-based](https://developer.apple.com/documentation/usernotifications/establishing-a-token-based-connection-to-apns)
connection; for Android,
[authorize your server to send via FCM](https://firebase.google.com/docs/cloud-messaging/auth-server).
:::
## How a call flows
1. Your backend sends a VoIP push to the callee's device.
2. The OS wakes the app, even if it was killed, and the SDK reports the call to
CallKit / Telecom. `callStatus` becomes `incoming`.
3. The user answers on the **system** call UI. `callStatus` becomes `connecting`.
4. **Your app** joins the Fishjam room and waits for the remote media.
5. Once media is live, **your app** calls
[`reportConnected()`](../../api/mobile/type-aliases/VoIPContextValue#reportconnected).
The SDK confirms the connection to the OS, the call timer starts, and `callStatus`
becomes `active`.
The SDK tracks the call's state and drives the native call UI; **joining the room and
reporting back is your app's job**. Step 5 has a **deadline**: an answered call that
isn't reported connected within `voip.fulfillAnswerCallTimeout` (10s by default) is
ended by the OS.
## 1. Install the SDK
Install the React Native SDK as described in the
[Installation guide](./installation#step-1-install-the-package). The exact packages
differ between Expo and bare React Native.
On **Expo**, also install [`@fishjam-cloud/ios-expo-voip`](https://www.npmjs.com/package/@fishjam-cloud/ios-expo-voip)
(**iOS only**). It registers PushKit at launch; without that registration the app never
receives VoIP pushes at all:
```bash
npx expo install @fishjam-cloud/ios-expo-voip
```
## 2. Configure the native project
Configure the Fishjam config plugin in your app's `app.json`: turn on Android VoIP and
the iOS VoIP background mode, and add the `voip` block, which wires up the rest of the
iOS setup and (optionally) tunes the timeouts:
```json title="app.json"
{
"expo": {
"plugins": [
[
"@fishjam-cloud/react-native-client",
{
"android": {
"enableVoIP": true
},
"ios": {
"enableVoIPBackgroundMode": true
},
"voip": {
"incomingCallTimeout": 15,
"outgoingCallTimeout": 20,
"fulfillAnswerCallTimeout": 5
}
}
]
]
}
}
```
The three options do different jobs, and VoIP calls need all three:
- **`android.enableVoIP`** turns on the Android half — the call permissions, the SDK's
call components, and the FCM messaging service.
- **`ios.enableVoIPBackgroundMode`** adds the `voip` background mode. iOS only delivers
PushKit pushes to an app that declares it, so calls don't work without it.
- **The `voip` block** wires up `@fishjam-cloud/ios-expo-voip` and puts calls in the
Phone app's **Recents** with [redial](#10-redial-from-recents-ios). What matters is
that it is **present** — every value inside it is optional, so `"voip": {}` is enough
to take the defaults: **45s** incoming ring, **60s** unconnected outgoing, and **10s**
for the answer handshake.
Because the block is what turns on the iOS wiring, setting it without
`@fishjam-cloud/ios-expo-voip` installed fails `expo prebuild` outright, with
`Fishjam VoIP options are enabled but @fishjam-cloud/ios-expo-voip is not installed`.
**iOS push entitlement.** iOS only issues a VoIP token to an app that declares
the [`aps-environment`](https://developer.apple.com/documentation/bundleresources/entitlements/aps-environment)
push entitlement, so add it in `app.json`:
```json title="app.json"
{
"expo": {
"ios": {
"entitlements": { "aps-environment": "development" }
}
}
}
```
Use `"production"` for TestFlight / App Store builds. For the underlying iOS
frameworks, see Apple's [PushKit](https://developer.apple.com/documentation/pushkit)
(VoIP pushes) and [CallKit](https://developer.apple.com/documentation/callkit).
**Android Firebase setup.** VoIP on Android is delivered over
[Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging). Point
Expo at your `google-services.json` so Firebase is wired into the build:
```json title="app.json"
{
"expo": {
"android": {
"package": "io.example.myapp",
"googleServicesFile": "./google-services.json"
}
}
}
```
Download `google-services.json` from the [Firebase console](https://console.firebase.google.com/)
and save it at your project
root. Its `package_name` must match `android.package` exactly. See
[Add Firebase to your Android project](https://firebase.google.com/docs/android/setup)
for the full Firebase setup, and Android's
[Telecom framework](https://developer.android.com/develop/connectivity/telecom) for
the call APIs.
:::warning[Both Android fields are required together]
`enableVoIP: true` **and** `googleServicesFile` must both be set. If `enableVoIP`
is on but `googleServicesFile` is missing, `expo prebuild` **succeeds** yet
Firebase is never wired up and pushes silently never arrive. If Android calls
don't ring, check this first.
:::
Config plugins only run during `expo prebuild`. In a bare project you own the
native directories, so apply the changes by hand.
**iOS**
Register [PushKit](https://developer.apple.com/documentation/pushkit) at launch in
`AppDelegate.swift`. A push can wake the app before any JS runs, so this must happen
at launch:
```swift title="AppDelegate.swift"
// in application(_:didFinishLaunchingWithOptions:)
VoIPManager.registerForVoIPPushes()
```
Expose the pod's Objective-C class to Swift through the target's
[bridging header](https://developer.apple.com/documentation/swift/importing-objective-c-into-swift).
An app with a Swift `AppDelegate` already has one at `ios//-Bridging-Header.h`;
add the import to it:
```objc title="myapp-Bridging-Header.h"
#import "VoIPManager.h"
```
If `"VoIPManager.h"` doesn't resolve, use the pod-qualified form
`#import `.
Add the push entitlement ([`aps-environment`](https://developer.apple.com/documentation/bundleresources/entitlements/aps-environment))
and the VoIP background mode. In Xcode → _Signing & Capabilities_ these are
**Push Notifications** and **Background Modes → Voice over IP**:
```xml title="Info.plist"
UIBackgroundModes
voip
NSMicrophoneUsageDescription
Allow $(PRODUCT_NAME) to access your microphone.
```
Adding the **Push Notifications** capability writes the entitlement for you; if you
edit the file directly it must contain:
```xml title="myapp.entitlements"
aps-environment
development
```
Use `production` for TestFlight / App Store builds.
**Android**
Apply the [`google-services`](https://firebase.google.com/docs/android/setup#add-config-file)
Gradle plugin to the **application** module and place `google-services.json` at
`android/app/google-services.json`:
```groovy title="android/build.gradle"
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.4.1'
}
}
```
```groovy title="android/app/build.gradle"
apply plugin: 'com.google.gms.google-services'
```
Then declare the SDK's VoIP components in `AndroidManifest.xml`:
```xml title="android/app/src/main/AndroidManifest.xml"
```
The `firebase_messaging_installation_id_enabled` flag is what makes FCM register the app
instance and hand back the [push token](#4-report-the-device-push-token).
**Timeouts (bare only).** The `voip` timeouts the Expo tab configures are plain native
values, so set them directly. On iOS add integers to `Info.plist`; on Android add the
same names as ``, both in seconds:
```xml title="Info.plist"
VoIPIncomingCallTimeout 15
VoIPOutgoingCallTimeout 20
VoIPFulfillAnswerTimeout 5
```
:::warning[Already using another FCM push library on Android?]
Android delivers every FCM message to a **single** messaging service. The SDK's
service claims that slot, so an app that also uses `expo-notifications` or
`@react-native-firebase/messaging` would otherwise stop receiving its other pushes.
Name that library so the SDK relays non-VoIP messages to it:
```json title="app.json"
[
"@fishjam-cloud/react-native-client",
{
"android": {
"enableVoIP": true,
"voipFallbackMessagingService": "expo-notifications"
}
}
]
```
Accepted values are `"expo-notifications"`, `"@react-native-firebase/messaging"`,
or a fully-qualified `FirebaseMessagingService` class name. iOS is unaffected: VoIP
pushes ride PushKit's separate channel.
If you'd rather own the messaging service yourself, set
`"voipMessagingService": false` instead. The SDK then declares no service at all, and
you forward calls to it from your own dispatcher with
`PushNotificationService.handleVoIPMessage(context, message)` and
`PushNotificationService.handleNewToken(token)`.
:::
:::note[Permissions]
A call still needs the camera and microphone. Configure those as in the
[Installation guide](./installation#step-2-configure-app-permissions), and request
them at runtime with [`useMicrophonePermissions`](../../api/mobile/functions/useMicrophonePermissions)
/ [`useCameraPermissions`](../../api/mobile/functions/useCameraPermissions) (see
[Managing devices](./managing-devices#managing-permissions-mobile-only)). On
**Android 13+** you must additionally request `POST_NOTIFICATIONS`, or the
incoming-call notification can't be posted:
```ts
// ---cut---
async function requestNotificationPermission() {
if (Platform.OS === "android" && Number(Platform.Version) >= 33) {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
);
}
}
```
:::
## 3. Mount the VoIP provider
[`VoIPProvider`](../../api/mobile/functions/VoIPProvider) tracks the call's state from
the CallKit / Telecom events and exposes it through
[`useVoIP`](../../api/mobile/functions/useVoIP). It doesn't touch the connection: joining
rooms, peer tokens, and media stay in your app (that's [step 5](#5-connect-calls-to-a-room)).
Mount it alongside [`FishjamProvider`](../../api/mobile/functions/FishjamProvider). The
order doesn't matter to `VoIPProvider`, but the hook that bridges the two (step 5) calls
both `useVoIP` and the Fishjam connection hooks, so it must sit **inside both**:
```tsx
FishjamProvider,
VoIPProvider,
} from "@fishjam-cloud/react-native-client";
declare const fishjamId: string;
declare function App(): ReactElement;
// ---cut---
function Root() {
return (
);
}
```
[`VoIPProviderProps`](../../api/mobile/type-aliases/VoIPProviderProps) accepts:
| Prop | Type | Required | Purpose |
| ----------------------- | ---------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `isVideo` | `boolean` | — | Marks outgoing calls as video, which registers the CallKit / Telecom session as video and labels the Android call notification. Incoming calls take their label from the push payload's [`isVideo`](#6-handle-an-incoming-call) instead. Make sure the room type matches. Default `false`. |
| `onWaitingCallDeclined` | `(payload: VoIPIncomingPayload) => void` | — | A second, waiting call was declined from the native UI. Signal the caller; local state is unchanged. |
## 4. Report the device push token
[`useVoIP`](../../api/mobile/functions/useVoIP) exposes the device's push token as
`voipToken`: the VoIP token from APNs on iOS, the FCM token on Android. Send it to your
backend; it's the push destination:
```tsx
declare function sendVoIPTokenToBackend(token: string, platform: string): void;
// ---cut---
function DeviceRegistration() {
const { voipToken } = useVoIP(); // [!code highlight]
useEffect(() => {
if (!voipToken) return;
// Persist this token on your backend, keyed by the signed-in user.
sendVoIPTokenToBackend(voipToken, Platform.OS);
}, [voipToken]);
return null;
}
```
A token is only valid with the service that issued it, so record each device's platform
at registration time and route through APNs or FCM accordingly. Both platforms reissue
tokens over time, so store the newest value per device rather than the first one you
saw.
## 5. Connect calls to a room
This step wires the native call to the Fishjam room: `VoIPProvider` tells you a call
needs a room; your app joins it and reports back. Split the work like this:
**The provider tells you** (through `useVoIP`):
- `callStatus` is `connecting`: join `currentCall.roomName` (see
[`CurrentCall`](../../api/mobile/type-aliases/CurrentCall)).
- `callStatus` left `connecting` / `active`: leave that room.
- `isOnHold` or `isMuted` changed: apply it to your tracks ([step 9](#9-hold-and-mute)).
**You tell the provider:**
- `reportConnected()` once media is live, or `reportConnectFailed()` if the join failed.
- `endCall('remote')` when the other side disappears from the room. `'remote'` means the
other party hung up — it's one of six
[`CallEndedReason`](../../api/mobile/type-aliases/CallEndedReason) values, all covered
in [step 8](#8-end-a-call).
A remote peer appearing in the room is what "media is live" means, so watch
[`usePeers`](../../api/mobile/functions/usePeers) and report from there. Start your
microphone (and camera, for a video call) **before** joining, so your tracks are
published with the join; skip it and the call connects silent. Mint the peer token
however your backend does; the SDK never sees it:
```tsx
useConnection,
useMicrophone,
usePeers,
useVoIP,
} from "@fishjam-cloud/react-native-client";
declare function getPeerToken(roomName: string): Promise;
// ---cut---
function useVoIPRoomConnection() {
const {
callStatus,
currentCall,
reportConnected,
reportConnectFailed,
endCall,
} = useVoIP();
const { joinRoom, leaveRoom } = useConnection();
const { startMicrophone, stopMicrophone } = useMicrophone();
const { remotePeers } = usePeers();
// Join the room the SDK is asking for; leave it when the call ends.
const targetRoom =
callStatus === "connecting" || callStatus === "active"
? currentCall?.roomName
: undefined;
useEffect(() => {
if (!targetRoom) return;
let cancelled = false;
(async () => {
try {
const peerToken = await getPeerToken(targetRoom);
if (cancelled) return;
await startMicrophone(); // publish media with the join // [!code highlight]
await joinRoom({ peerToken }); // [!code highlight]
} catch {
if (!cancelled) await reportConnectFailed(); // [!code highlight]
}
})();
return () => {
cancelled = true;
void stopMicrophone();
void leaveRoom();
};
}, [targetRoom]);
// A remote peer showing up means the call connected; it leaving means they hung up.
useEffect(() => {
if (callStatus === "connecting" && remotePeers.length > 0) {
void reportConnected(); // [!code highlight]
} else if (callStatus === "active" && remotePeers.length === 0) {
void endCall("remote");
}
}, [callStatus, remotePeers.length]);
}
```
Mount it once, anywhere inside both providers.
:::warning[Report connected before the deadline]
`reportConnected()` isn't optional; it fulfills CallKit's answer action and starts the
call timer. The native fulfil deadline (`voip.fulfillAnswerCallTimeout`, 10s by default)
covers your token fetch **and** room join, so be quick. Miss it and the OS ends the
call.
:::
## 6. Handle an incoming call
A push wakes the app, the system UI starts ringing, and `useVoIP` moves `callStatus` to
`'incoming'` with [`currentCall`](../../api/mobile/type-aliases/CurrentCall) populated.
**Answering happens on the system call UI** (the CallKit screen or Android's full-screen
activity), not from a button you build. On answer, `callStatus` moves to `'connecting'` and
the hook from [step 5](#5-connect-calls-to-a-room) joins the room and reports back;
you don't wire the accept path yourself.
You can still render your own screen off `callStatus` while a call rings (to match your app's
look), and decline from it with `endCall('rejected')`:
```tsx
declare function IncomingCallScreen(props: {
name?: string;
onReject: () => void;
}): ReactElement;
// ---cut---
function CallUI() {
const { callStatus, currentCall, endCall } = useVoIP();
// callStatus: 'available' | 'incoming' | 'connecting' | 'active' // [!code highlight]
if (callStatus === "incoming") {
return (
endCall("rejected")} // [!code highlight]
/>
);
}
return null;
}
```
:::note[What your backend must put in the push]
The push carries the call fields the SDK reads, as a
[`VoIPIncomingPayload`](../../api/mobile/type-aliases/VoIPIncomingPayload):
| Field | Required | Purpose |
| ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `roomName` | ✅ | The Fishjam room both parties join. Android drops a payload without it; iOS still rings, then throws in JS, so always send it. |
| `displayName` | — | Label shown in the system call UI. Both platforms fall back to **"Incoming call"**. |
| `handle` | — | Stable id of the caller; falls back to `displayName`. This is what iOS Recents hands back for redial, so use a real user id, since a display name isn't unique. |
| `isVideo` | — | Labels the incoming call as video; Android shows "Incoming video call" instead of "Incoming call". Defaults to `false`. |
| `avatarUrl` | — | Android renders it in the incoming-call UI. iOS delivers it to JS only, since CallKit can't show caller images. |
:::
:::warning[Android: send it as a high-priority data message]
On Android the push must be a **data message** carrying the discriminator
`"fishjam": "voip-incoming"`, or the SDK won't treat it as a call. Send it with
[high priority](https://firebase.google.com/docs/cloud-messaging/android/message-priority).
For the exact message our example server sends, see
[`main.ts`](https://github.com/fishjam-cloud/web-client-sdk/blob/main/examples/mobile-client/voip-call/server/main.ts).
:::
## 7. Place an outgoing call
You mint the room name and ring the callee through **your own** signaling backend, then
call `startCall(to, roomName)`. `startCall` only registers the call with CallKit /
Telecom and moves `callStatus` to `'connecting'`. It doesn't ring anyone and doesn't join;
the hook from [step 5](#5-connect-calls-to-a-room) joins once `callStatus` is `connecting`,
exactly as it does for an incoming call. The order is yours to choose, and doing signaling
first means a failed ring never shows a call that can't connect:
```tsx
declare function ringCallee(to: string, roomName: string): Promise;
declare function makeRoomName(): string;
// ---cut---
function usePlaceCall() {
const { startCall } = useVoIP();
return useCallback(
async (to: string) => {
const roomName = makeRoomName(); // you own the room name
await ringCallee(to, roomName); // your signaling rings the callee
await startCall(to, roomName); // [!code highlight] registers the native call, callStatus → 'connecting'
},
[startCall],
);
}
```
`to` is the callee's stable id, the value your backend looks up to decide who to ring. It
only affects the **caller's** own device, where the SDK uses it as both the handle and
the display name, so a raw user id shows up verbatim on their call screen. It never
reaches the callee: the name **they** see is the
[`displayName`](#6-handle-an-incoming-call) your backend puts in the push.
If `startCall`'s native session won't start, the provider ends the call as `failed` and
`callStatus` returns to `'available'`. A failed room join is reported by your hook's
`reportConnectFailed()` (step 5).
## 8. End a call
A call ends from several places: the system call UI, your room-connection hook
([step 5](#5-connect-calls-to-a-room)) when the remote peer disappears, or your own
in-call button. To hang up yourself:
```tsx
// ---cut---
const { endCall } = useVoIP();
await endCall(); // defaults to 'local'
```
`endCall` takes a [`CallEndedReason`](../../api/mobile/type-aliases/CallEndedReason)
saying how the call ended. Whatever ends the call (your `endCall`, the system UI, or your
hook passing `'remote'` when the peer drops) sets `lastEndedReason`, always **from your
device's point of view**: whether you ended it (`'local'`) or the other side did
(`'remote'`), and why. Read it to react to a missed or rejected call, for example with a
"missed call" notification:
| Reason | Meaning |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `local` | This device hung up. Also covers a decline on iOS, which CallKit can't distinguish. |
| `rejected` | The callee actively declined while ringing. Safe to pass on both, but CallKit has no case for it, so iOS ends the call exactly as `local`, and only Android reports it back distinctly. |
| `missed` | Rang and was never answered, including a native ring timeout. |
| `remote` | The other party hung up. |
| `answeredElsewhere` | Picked up on another of the user's devices. |
| `failed` | Setup failed: token fetch, room join, or the answer deadline. |
A push can't express a caller canceling or a callee rejecting, so map those across
devices over your own signaling channel: when the caller cancels while ringing, the
callee should end as `missed`; when the callee rejects, the caller should end as
`rejected`. Reserve `remote` for the other party hanging up a call that was already
connected.
## 9. Hold and mute
The OS holds your call when a cellular call arrives, and mirrors the system call UI's
mute button. `useVoIP` **reports** both as `isOnHold` and `isMuted`, but doesn't touch
your tracks. Applying them is your job, alongside the room connection from
[step 5](#5-connect-calls-to-a-room). Watch the flags and drive your own media hooks:
```tsx
// ---cut---
function useSyncMute() {
const { callStatus, isMuted } = useVoIP();
const { isMicrophoneOn, toggleMicrophone } = useMicrophone();
useEffect(() => {
if (callStatus !== "active") return; // only while a call is live // [!code highlight]
// Mirror the system mute onto your published track.
if (isMicrophoneOn === isMuted) void toggleMicrophone();
}, [isMuted, callStatus]);
}
```
Hold works the same way: when `isOnHold` flips on, stop the mic and camera and remember
what was live; when it flips off, restore exactly that. To request a hold from your **own**
button (rather than react to the OS), call `setCallHeld`, then act on `isOnHold` flipping:
```tsx
// ---cut---
const { isOnHold, setCallHeld } = useVoIP();
await setCallHeld(true); // request a hold; isOnHold flips when the OS applies it // [!code highlight]
```
In-call A/V beyond this is the normal Fishjam device API ([`useMicrophone`](../../api/mobile/functions/useMicrophone),
[`useCamera`](../../api/mobile/functions/useCamera)), exactly like any other Fishjam app.
See [Managing devices](./managing-devices) for the full device API.
## 10. Redial from Recents (iOS)
Every call is recorded in the iOS Phone app's **Recents**, and tapping an entry reopens
your app. The tap arrives as `pendingCallIntent`, carrying only the `handle` to redial, never a
room. Mint a room and place the call exactly as in [step 7](#7-place-an-outgoing-call),
then `clearCallIntent()` so it isn't replayed:
```tsx
declare function usePlaceCall(): (to: string) => Promise;
declare function useSessionReady(): boolean;
// ---cut---
function useRedialFromRecents() {
const { pendingCallIntent, clearCallIntent } = useVoIP();
const placeCall = usePlaceCall();
const isReady = useSessionReady();
useEffect(() => {
if (!pendingCallIntent || !isReady) return; // [!code highlight]
const { handle } = pendingCallIntent;
clearCallIntent();
void placeCall(handle);
}, [pendingCallIntent, isReady, clearCallIntent, placeCall]);
}
```
The SDK **holds** `pendingCallIntent` until you clear it, so an intent that arrives
before your app has restored its session isn't lost. Gate on your own readiness (as
`isReady` does here) and act on it once you can.
Enabling Recents itself is native setup:
The `voip` block from [step 2](#2-configure-the-native-project) is all this takes; there's
no option to enable. It sets the `FishjamVoIPEnabled` flag and the CallKit intent activity
types for you.
You own the `Info.plist`, so wire up the two halves the Expo plugin sets for you. First,
the plist: `FishjamVoIPEnabled` puts calls in Recents, and `NSUserActivityTypes` declares
that your app handles the "start call" [intents](https://developer.apple.com/documentation/sirikit/instartcallintent)
iOS hands back when someone taps a Recents entry. Without those types the tap opens your
app but no intent is delivered:
```xml title="Info.plist"
FishjamVoIPEnabled
NSUserActivityTypes
INStartCallIntent
INStartAudioCallIntent
INStartVideoCallIntent
```
Second, forward that intent to the SDK from your `AppDelegate`. The tap arrives as an
[`NSUserActivity`](https://developer.apple.com/documentation/foundation/nsuseractivity);
handing it to `VoIPManager` is what turns it into the `pendingCallIntent` your JS reads
above. Do this **before** React Native's own Linking handler so it isn't consumed as a
deep link:
```swift title="AppDelegate.swift"
// in application(_:continue:restorationHandler:), before React Native Linking
if VoIPManager.handleContinueUserActivity(userActivity) {
return true
}
```
## 11. Test it
Test on a **real device**: VoIP pushes never reach the iOS Simulator, and Android needs
**Google Play services** for FCM. Then check the key paths:
- Send a push and confirm the native call screen appears, even when the app is killed.
- Answer, and the call connects with the OS timer starting once media is live.
- Let a call ring out and confirm it ends as `missed`.
- On iOS, the call shows in **Recents** and tapping it redials.
- Take a cellular call with **Hold & Accept**: your mic and camera pause, then resume.
## Next steps
- [Managing devices](./managing-devices): control the camera and microphone during
a call.
---
## Compose a Fishjam room
A composition can include the peers of a [Fishjam room](./../../explanation/rooms). You forward the room's tracks to the composition with a single Fishjam API call: Fishjam then pushes each participant's media into the composition as inputs, and hooks from `@fishjam-cloud/composition` let a [template](./write-and-deploy-a-template) render one tile per participant and push the result to a [livestream](./../../explanation/livestreams).
```text
Fishjam room (peers) ──forwarded──▶ composition (template) ──WHIP──▶ Fishjam livestream ──WHEP──▶ [viewers]
```
:::note
Only [conference](./../../explanation/rooms#conference-rooms-default) and [audio-only](./../../explanation/rooms#audio-only-rooms) rooms can be forwarded. Forwarding a [livestream room](./../../explanation/rooms#livestream-rooms) fails.
To compose a single stream, such as OBS, a phone camera, or a browser tab, you don't need a room at all. Publish it straight into the composition through a [`whip_server` input](./inputs-and-outputs#inputs).
:::
## Prerequisites
- A [livestream](./../../explanation/livestreams) (or any other WHIP/RTMP destination) to publish the composed stream to.
- A template project scaffolded with the composition CLI (see [Write and deploy a template](./write-and-deploy-a-template)).
The [Composition API](./../../api/reference#compositions) lives on `https://rtc.fishjam.io`, while rooms and livestreams live on the [Fishjam Server API](./../../api/reference#server). Both take the same Management Token:
```bash
export FISHJAM_URL="https://fishjam.io/api/v1/connect/"
export TOKEN=""
```
## Step 1: Create a room and invite peers
Compositions consume h264 video, so the room has to enforce that codec. It is the default, but set it explicitly so a change of default cannot break the composition later:
```ts
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
// ---cut---
const room = await fishjamClient.createRoom({
roomType: "conference",
videoCodec: "h264",
});
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(fishjam_id=fishjam_id, management_token=management_token)
room = fishjam_client.create_room(
RoomOptions(room_type="conference", video_codec="h264"),
)
```
```bash
curl -X POST "$FISHJAM_URL/room" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "roomType": "conference", "videoCodec": "h264" }'
```
The room id comes back under `data.room.id`. Save it:
```bash
export ROOM_ID=""
```
Every participant needs their own peer token. Create one per person:
```ts
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const roomId = "" as RoomId;
// ---cut---
const { peer, peerToken } = await fishjamClient.createPeer(roomId);
```
```python
peer, peer_token = fishjam_client.create_peer(room.id)
```
```bash
curl -X POST "$FISHJAM_URL/room/$ROOM_ID/peer" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "type": "webrtc", "options": {} }'
```
Hand each `data.token` to a client and have it join, using [Connect to a room](./../client/connecting) or the [React quick start](./../../tutorials/react-quick-start). The composition renders whoever is publishing, so get at least one peer in with a camera on before you expect a picture.
## Step 2: Write a room-aware template
Hooks from `@fishjam-cloud/composition` give the template live room state; it re-renders automatically as participants join, leave, mute, or speak.
```tsx
// @jsx: react-jsx
// ---cut-before---
type PeerMetadata = { displayName?: string };
function PeerTile({ peer }: { peer: PeerWithStreams }) {
const camera = peer.cameraStream;
const cameraOn = camera?.video && !camera.video.paused;
const speaking = useSpeakingState(peer.id) === "speech";
const name = peer.metadata.peer?.displayName ?? peer.id;
return (
{cameraOn ? (
) : (
{name}
)}
);
}
export default function App() {
const peers = usePeers();
const connected = peers.filter((peer) => peer.streams.length > 0);
return (
{connected.map((peer) => (
))}
);
}
```
| Hook | Returns |
| -------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `usePeers()` | All peers in the forwarded room, each with its streams (`cameraStream`, `screenShareStream`, `customStreams`). |
| `usePeer(peerId)` | A single peer, or `undefined`. |
| `useRoom()` | The forwarded room `{ id }`, or `undefined` before a room is forwarded. |
| `useSpeakingState(peerId)` | `"speech"` or `"silence"` for active-speaker highlighting. |
The key link is `stream.inputId`: you pass it to ` ` to render that participant's forwarded track. A peer's streams fill in once its media actually starts flowing into the composition.
Build the bundle as usual with `npm run build`.
## Step 3: Create the composition and register the templated output
Create the composition with auto-start off, because the room's inputs only appear once forwarding starts.
Setting `cleanup_without_inputs` to `false` tightens the cleanup condition, so that it now takes both the inputs and the outputs going quiet rather than the inputs alone. Cleanup therefore fires less readily, and the composition survives the wait for the first peer to publish.
:::warning[A composition bills for the whole time it exists]
With that guard off, cleanup waits for the outputs to fall silent too, so one that keeps
publishing is never cleaned up for you. Delete it as soon as you are finished, and do not
leave one running after a test. See
[Cost and lifecycle](../../explanation/compositions#cost-and-lifecycle).
:::
```ts
const compositionClient = new CompositionClient({ managementToken: "" });
// ---cut---
const { compositionId } = await compositionClient.createComposition({
autostart: false,
cleanupWithoutInputs: false,
});
```
```python
from fishjam import CompositionClient
from fishjam.composition import CreateCompositionRequest
composition_client = CompositionClient(management_token=management_token)
composition = composition_client.create_composition(
CreateCompositionRequest(autostart=False, cleanup_without_inputs=False),
)
composition_id = composition.composition_id
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "autostart": false, "cleanup_without_inputs": false }'
```
Save the `composition_id` from the response, every call below uses it:
```bash
export COMPOSITION=""
```
Register a templated `whip_client` output that pushes to your livestream's WHIP endpoint. Create the livestream and its streamer token first, as in [Step 3 of the tutorial](./../../tutorials/compositions#step-3-create-a-livestream-to-publish-to). The output configuration and the template bundle go together in one multipart request:
```ts
CompositionClient,
CompositionId,
FishjamClient,
OutputId,
RoomId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
const livestreamId = "" as RoomId;
// ---cut---
const { token: streamerToken } =
await fishjamClient.createLivestreamStreamerToken(livestreamId);
await compositionClient.registerTemplateOutput(
compositionId,
outputId,
{
type: "whip_client",
endpointUrl: fishjamClient.livestreamWhipUrl(),
bearerToken: streamerToken,
video: {
resolution: { width: 1280, height: 720 },
initial: { root: { type: "view" } },
},
audio: { initial: { inputs: [] } },
},
"dist/App.js",
);
```
```python
from fishjam.composition import (
AudioScene,
OutputWhipAudioOptions,
OutputWhipVideoOptions,
Resolution,
VideoScene,
View,
ViewType,
WhipOutput,
WhipOutputType,
)
streamer_token = fishjam_client.create_livestream_streamer_token(livestream_id)
composition_client.register_template_output(
composition_id,
"main",
WhipOutput(
type_=WhipOutputType.WHIP_CLIENT,
endpoint_url=fishjam_client.livestream_whip_url(),
bearer_token=streamer_token,
video=OutputWhipVideoOptions(
resolution=Resolution(width=1280, height=720),
initial=VideoScene(root=View(type_=ViewType.VIEW)),
),
audio=OutputWhipAudioOptions(initial=AudioScene(inputs=[])),
),
"dist/App.js",
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/output/main/template" \
-H "Authorization: Bearer $TOKEN" \
-F 'config={
"type": "whip_client",
"endpoint_url": "",
"bearer_token": "",
"video": { "resolution": { "width": 1280, "height": 720 }, "initial": { "root": { "type": "view" } } },
"audio": { "initial": { "inputs": [] } }
};type=application/json' \
-F "template=@dist/App.js"
```
## Step 4: Forward the room into the composition
One call to `forwardRoomTracks` wires everything up:
```ts
CompositionClient,
CompositionId,
FishjamClient,
RoomId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const compositionId = "" as CompositionId;
const roomId = "" as RoomId;
// ---cut---
await fishjamClient.forwardRoomTracks(
roomId,
compositionClient.compositionUrl(compositionId),
);
```
```python
fishjam_client.forward_room_tracks(
room.id,
composition_client.composition_url(composition_id),
)
```
```bash
curl -X POST "$FISHJAM_URL/room/$ROOM_ID/track_forwardings" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{ \"compositionURL\": \"https://rtc.fishjam.io/api/composition/$COMPOSITION\", \"selector\": \"all\" }"
```
Everything else happens automatically: Fishjam links the room to the composition, registers an input for every forwarded track, and streams the media in. Your template's `usePeers()` fills with the room's peers as their media starts flowing. You never register room inputs by hand.
A room and a composition pair up one to one, in both directions. Repeating the call with the same `compositionURL` is a no-op, but pointing the room at a second composition, or a second room at this composition, fails. To compose two rooms, give each its own composition.
## Step 5: Start the composition
```ts
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
// ---cut---
await compositionClient.startComposition(compositionId);
```
```python
composition_client.start_composition(composition_id)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/start" \
-H "Authorization: Bearer $TOKEN"
```
Viewers can now watch the composed grid through the livestream's WHEP endpoint. If you'd like to keep an MP4 recording of the room without streaming it live, simply [record it with the same template](./../recordings/record-with-a-template).
## Step 6: Clean up
Delete the composition when you are done. Forwarding stops on the Fishjam side when the room itself stops, so delete the room too once you no longer need it. There is no separate call to remove a forwarding from a live room.
```ts
CompositionClient,
CompositionId,
FishjamClient,
RoomId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const compositionId = "" as CompositionId;
const roomId = "" as RoomId;
// ---cut---
await compositionClient.deleteComposition(compositionId);
await fishjamClient.deleteRoom(roomId);
```
```python
composition_client.delete_composition(composition_id)
fishjam_client.delete_room(room.id)
```
```bash
curl -X DELETE "https://rtc.fishjam.io/api/composition/$COMPOSITION" \
-H "Authorization: Bearer $TOKEN"
curl -X DELETE "$FISHJAM_URL/room/$ROOM_ID" \
-H "Authorization: Bearer $TOKEN"
```
---
## Drive a template with events
Once a [template](./write-and-deploy-a-template) is running, you can push **custom events** to it from your backend to change what it shows, such as toggling a live badge or updating a caption, without re-uploading the template.
## Handle events in the template
Inside a template, subscribe to events with the `eventBus`. Each `on` call returns an unsubscribe function. Event names and payloads are entirely defined by your application.
```tsx
// @jsx: react-jsx
// ---cut-before---
export default function App() {
const [caption, setCaption] = useState(null);
const [live, setLive] = useState(false);
useEffect(() => {
const unsubs = [
eventBus.on<{ text: string }>("SET_CAPTION", ({ text }) =>
setCaption(text),
),
eventBus.on("CLEAR_CAPTION", () => setCaption(null)),
eventBus.on<{ live: boolean }>("SET_LIVE", ({ live }) => setLive(live)),
];
return () => unsubs.forEach((off) => off());
}, []);
return (
{live && ● LIVE }
{caption && {caption} }
);
}
```
## Deploy it
Now create the composition. A caption-only template registers no inputs, and a composition with no input media cleans itself up after five minutes, so create this one with `cleanup_without_inputs` set to `false`:
```ts
const managementToken = "";
// ---cut---
const compositionClient = new CompositionClient({ managementToken });
const { compositionId } = await compositionClient.createComposition({
cleanupWithoutInputs: false,
});
```
```python
from fishjam import CompositionClient
from fishjam.composition import CreateCompositionRequest
composition_client = CompositionClient(management_token=management_token)
composition = composition_client.create_composition(
CreateCompositionRequest(cleanup_without_inputs=False),
)
composition_id = composition.composition_id
```
```bash
export TOKEN=""
curl -X POST "https://rtc.fishjam.io/api/composition" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "cleanup_without_inputs": false }'
```
Save the id from the response:
```bash
export COMPOSITION=""
```
:::warning[A composition bills for the whole time it exists]
With that guard off, cleanup waits for the outputs to fall silent too, so one that keeps
publishing is never cleaned up for you. Delete it as soon as you are finished, and do not
leave one running after a test. See
[Cost and lifecycle](../../explanation/compositions#cost-and-lifecycle).
:::
Build the bundle and register it as a templated output with `registerTemplateOutput`, as in [Write and deploy a template](./write-and-deploy-a-template).
That output has to publish somewhere, so create a livestream and take its streamer token first, as in [Step 3 of the compositions tutorial](./../../tutorials/compositions#step-3-create-a-livestream-to-publish-to). Watching it works the same way as there.
## Send events from your backend
Send an event with `sendEvent`. The event name is matched against your `eventBus.on(...)` subscriptions, and `data` is delivered as the handler's argument.
```ts
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
// ---cut---
await compositionClient.sendEvent(compositionId, {
eventName: "SET_CAPTION",
data: { text: "Welcome to the stream" },
});
```
```python
composition_client.send_event(composition_id, "SET_CAPTION", {"text": "Welcome to the stream"})
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/event" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "event_name": "SET_CAPTION", "data": { "text": "Welcome to the stream" } }'
```
```ts
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
// ---cut---
await compositionClient.sendEvent(compositionId, {
eventName: "SET_LIVE",
data: { live: true },
});
```
```python
composition_client.send_event(composition_id, "SET_LIVE", {"live": True})
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/event" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "event_name": "SET_LIVE", "data": { "live": true } }'
```
The template re-renders as soon as the event arrives.
:::note
Event names and payloads are an application-defined contract between your backend and your template. There is no canonical set of events; `SET_LIVE` and `SET_CAPTION` above are just examples. Pick names and payload shapes that fit your app, and keep them in sync on both sides.
:::
## Clean up
Delete the composition when you have finished testing, so it stops billing:
```ts
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
// ---cut---
await compositionClient.deleteComposition(compositionId);
```
```python
composition_client.delete_composition(composition_id)
```
```bash
curl -X DELETE "https://rtc.fishjam.io/api/composition/$COMPOSITION" \
-H "Authorization: Bearer $TOKEN"
```
---
## Choose inputs and outputs
A composition pulls media in through **inputs** and pushes the composed result out through **outputs**. Each is a tagged object whose `type` selects the protocol. This guide summarizes the available types and when to use each.
## Inputs
Register an input with the method for its protocol:
| SDK method | `type` | Use it when | Key fields |
| ------------------- | ------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `registerWhipInput` | `whip_server` | A WebRTC client should publish **to** the composition. | `bearer_token` (optional; generated and returned if omitted), `video` (optional, default `true`). |
| `registerWhepInput` | `whep_client` | The composition should **pull** a WebRTC stream from a WHEP endpoint. | `endpoint_url` (required), `bearer_token` (optional), `video` (optional). |
| `registerRtmpInput` | `rtmp_server` | An encoder (OBS, hardware) should push RTMP in. | `stream_key` (required). |
| `registerMp4Input` | `mp4` | You want to compose a file, optionally looped. | `url` (required), `loop` (optional). |
For `whip_server`, the register response returns the `bearer_token` a publisher uses to authenticate against the input's WHIP endpoint, together with the route to push to:
```json
{ "bearer_token": "", "endpoint_route": "/whip/camera_1" }
```
That token is the only one accepted on the publish endpoint. Your Management Token is rejected there.
`endpoint_route` is relative to the composition, so the full address is `https://rtc.fishjam.io/api/composition//whip/`. Point any WHIP publisher there and authenticate with that token. A `whip_server` input takes WebRTC from anything that speaks WHIP: a phone's camera, a laptop webcam, a browser tab, a screen share, or a hardware encoder. OBS has WHIP output built in.
Unregister any input with `unregisterInput`.
## Outputs
Register an output with the method for its protocol:
| SDK method | `type` | Use it when | Key fields |
| -------------------- | ------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
| `registerWhipOutput` | `whip_client` | Publish the composed result over WebRTC (for example to a Fishjam livestream). | `endpoint_url` (required), `bearer_token` (optional), `video`, `audio`. |
| `registerRtmpOutput` | `rtmp_client` | Publish to an RTMP destination (for example a social platform). | `url` (required), `video`, `audio`. |
There is no URL you can point a player at to watch a composition. An output **pushes** the composed video to a destination you name when you register it, and your viewers connect to that destination's own playback URL:
```text
whip_client ──▶ Fishjam livestream ──WHEP──▶ [viewers]
rtmp_client ──▶ YouTube, Twitch, any RTMP service ──▶ [viewers]
```
An output's `video` carries the resolution and initial [scene](./../../explanation/compositions#scenes), and `audio` carries the initial audio scene:
```json
{
"type": "whip_client",
"endpoint_url": "https://example.com/whip",
"video": {
"resolution": { "width": 1280, "height": 720 },
"initial": { "root": { "type": "tiles", "children": [] } }
},
"audio": { "initial": { "inputs": [] } }
}
```
`resolution` has to be even on both sides, and at most 3840x2160.
Other output operations:
- **Register a templated output** with `registerTemplateOutput` instead: it carries the same configuration plus a template bundle (see [Write and deploy a template](./write-and-deploy-a-template)).
- **Update the scene** live with `updateOutput` (see [Update a scene](#update-a-scene) below).
- **Force a keyframe** with `requestKeyframe`, useful when a new subscriber joins.
- **Unregister** with `unregisterOutput`.
- **Record** any output into an MP4 through the Fishjam Server API (see [Record a composition output](./../recordings/record-a-composition-output)).
## Update a scene
Replace an output's [scene](./../../explanation/compositions#scenes) while the composition is running:
```ts
CompositionId,
OutputId,
RendererId,
} from "@fishjam-cloud/js-server-sdk";
const managementToken = "";
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
const rendererId = "" as RendererId;
// ---cut---
const compositionClient = new CompositionClient({ managementToken });
await compositionClient.updateOutput(compositionId, outputId, {
video: {
root: {
type: "rescaler",
child: { type: "input_stream", inputId: "camera_1" },
},
},
audio: { inputs: [{ inputId: "camera_1" }] },
});
```
```python
from fishjam import CompositionClient
from fishjam.composition import (
AudioScene,
AudioSceneInput,
InputStream,
InputStreamType,
Rescaler,
RescalerType,
UpdateOutputRequest,
VideoScene,
)
composition_client = CompositionClient(management_token=management_token)
composition_client.update_output(
"",
"main",
UpdateOutputRequest(
video=VideoScene(
root=Rescaler(
type_=RescalerType.RESCALER,
child=InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="camera_1"
),
)
),
audio=AudioScene(inputs=[AudioSceneInput(input_id="camera_1")]),
),
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/output/main/update" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"video": {
"root": {
"type": "rescaler",
"child": { "type": "input_stream", "input_id": "camera_1" }
}
},
"audio": { "inputs": [{ "input_id": "camera_1" }] }
}'
```
An update has to mirror the sides the output was registered with. If you registered the output with both `video` and `audio`, every update must carry both, even when only one of them changed. If you registered only one of them, the update may only carry that one. Sending a mismatched update fails.
Add `schedule_time_ms` to apply the change at a chosen offset on the composition timeline, in milliseconds, instead of immediately:
```json
{
"video": { "root": { "type": "tiles", "children": [] } },
"audio": { "inputs": [] },
"schedule_time_ms": 5000
}
```
## Renderers
Renderers are shared assets you register once and then place in any scene.
### Images
Register an image with `registerImage`:
```ts
CompositionId,
OutputId,
RendererId,
} from "@fishjam-cloud/js-server-sdk";
const managementToken = "";
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
const rendererId = "" as RendererId;
// ---cut---
const compositionClient = new CompositionClient({ managementToken });
await compositionClient.registerImage(compositionId, rendererId, {
assetType: "auto",
url: "https://example.com/logo.png",
});
```
```python
from fishjam.composition import ImageSpecAuto, ImageSpecAutoAssetType
composition_client.register_image(
"",
"logo",
ImageSpecAuto(
asset_type=ImageSpecAutoAssetType.AUTO,
url="https://example.com/logo.png",
),
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/image/logo/register" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "asset_type": "auto", "url": "https://example.com/logo.png" }'
```
`asset_type` selects the format: `png`, `jpeg`, `svg`, `gif`, or `auto` to detect it from the URL. Each takes a `url`; `svg` also accepts a `resolution`. Place the image in a scene with an `image` component:
```json
{ "type": "image", "image_id": "logo" }
```
Unregister with `unregisterImage`.
### Fonts
Register a font with a multipart request carrying the font file in a single `font` part:
```ts
CompositionId,
OutputId,
RendererId,
} from "@fishjam-cloud/js-server-sdk";
const managementToken = "";
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
const rendererId = "" as RendererId;
// ---cut---
const compositionClient = new CompositionClient({ managementToken });
await compositionClient.registerFont(compositionId, "./BrandFont.ttf");
```
```python
composition_client.register_font("", "./BrandFont.ttf")
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/font/register" \
-H "Authorization: Bearer $TOKEN" \
-F "font=@BrandFont.ttf"
```
The font is then available to `text` components.
See the [Composition API](./../../api/reference#compositions) reference for the complete request and response schemas.
---
## Write and deploy a template
A **template** is a React component that describes an output's layout. Instead of sending a static scene, you write a component, bundle it into a single file with the composition CLI, and upload it when registering an output.
## Scaffold a project
Create a new template project with the CLI:
```bash npm2yarn
npx @fishjam-cloud/composition-cli init my-template
cd my-template
npm install
```
This generates a ready-to-build project: a `package.json` with `build` and `typecheck` scripts, a TypeScript config, and a starter `src/App.tsx`.
## Write the template
A template **default-exports a React component**. You lay out the composition with components from [`@swmansion/smelter`](https://smelter.dev/ts-sdk/overview).
The example below builds a grid that maintains itself. `useInputStreams()` returns every input currently registered on the composition, so the layout follows them without you sending a single scene update:
```tsx
// @jsx: react-jsx
// ---cut-before---
InputStream,
Rescaler,
Text,
Tiles,
View,
useInputStreams,
} from "@swmansion/smelter";
export default function App() {
const inputs = Object.values(useInputStreams());
const playing = inputs.filter((input) => input.videoState === "playing");
if (playing.length === 0) {
return (
Waiting for inputs
);
}
return (
{playing.map((input) => (
))}
);
}
```
Register an input and a tile appears; unregister it and the grid reflows. Each entry also carries `videoState` and `audioState`, one of `ready`, `playing`, `paused`, or `finished`, which is what the filter above uses to keep inputs off screen until their media actually starts.
` ` renders one of the composition's registered inputs. Layout, styling, and every visual component (`View`, `Tiles`, `InputStream`, `Rescaler`, `Text`, `Image`, …) come from `@swmansion/smelter`. See the [Smelter TypeScript SDK reference](https://smelter.dev/ts-sdk/overview) for every component and its style props.
## Build the bundle
```bash npm2yarn
npm run build
```
## Deploy the template
Now create the composition, as in [Step 1 of the tutorial](./../../tutorials/compositions#step-1-create-a-composition), and the livestream with its streamer token, as in [Step 3](./../../tutorials/compositions#step-3-create-a-livestream-to-publish-to):
```bash
export FISHJAM_URL="https://fishjam.io/api/v1/connect/"
export TOKEN=""
export COMPOSITION=""
export STREAM=""
export STREAMER_TOKEN=""
```
A templated output is registered with `registerTemplateOutput` in a **single request**. Do not register a plain output first. The request carries two parts:
- `config`: the same JSON body a regular output registration takes (see [Choose inputs and outputs](./inputs-and-outputs)). Its `video.initial` scene is only a placeholder; the template takes over rendering as soon as it loads.
- `template`: the built bundle.
`endpoint_url` is wherever the composed stream should go. The quickest destination to watch is a Fishjam livestream, exactly as in [the tutorial](./../../tutorials/compositions#step-3-create-a-livestream-to-publish-to): create one, take its streamer token, and publish to `https://fishjam.io/api/v1/live/api/whip`.
```ts
CompositionClient,
CompositionId,
OutputId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
const streamerToken = "";
// ---cut---
await compositionClient.registerTemplateOutput(
compositionId,
outputId,
{
type: "whip_client",
endpointUrl: "https://fishjam.io/api/v1/live/api/whip",
bearerToken: streamerToken,
video: {
resolution: { width: 1280, height: 720 },
initial: { root: { type: "view" } },
},
audio: { initial: { inputs: [] } },
},
"dist/App.js",
);
```
```python
from fishjam.composition import (
AudioScene,
OutputWhipAudioOptions,
OutputWhipVideoOptions,
Resolution,
VideoScene,
View,
ViewType,
WhipOutput,
WhipOutputType,
)
composition_client.register_template_output(
composition_id,
"main",
WhipOutput(
type_=WhipOutputType.WHIP_CLIENT,
endpoint_url="https://fishjam.io/api/v1/live/api/whip",
bearer_token=streamer_token,
video=OutputWhipVideoOptions(
resolution=Resolution(width=1280, height=720),
initial=VideoScene(root=View(type_=ViewType.VIEW)),
),
audio=OutputWhipAudioOptions(initial=AudioScene(inputs=[])),
),
"dist/App.js",
)
```
```bash
CONFIG=$(cat <
## Redeploy after an edit
Unregister the output first, then deploy again:
```ts
CompositionClient,
CompositionId,
OutputId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
// ---cut---
await compositionClient.unregisterOutput(compositionId, outputId);
```
```python
composition_client.unregister_output(composition_id, "main")
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/output/main/unregister" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{}'
```
Rebuild with `npm run build` and repeat the deploy request. The inputs stay registered, so only the layout changes.
## Clean up
Deleting the composition removes its inputs and outputs with it, so a finished experiment takes two calls:
```ts
CompositionClient,
CompositionId,
FishjamClient,
RoomId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const compositionId = "" as CompositionId;
const roomId = "" as RoomId;
// ---cut---
await compositionClient.deleteComposition(compositionId);
await fishjamClient.deleteRoom(roomId);
```
```python
composition_client.delete_composition(composition_id)
fishjam_client.delete_room(room_id)
```
```bash
curl -X DELETE "https://rtc.fishjam.io/api/composition/$COMPOSITION" \
-H "Authorization: Bearer $TOKEN"
curl -X DELETE "$FISHJAM_URL/livestream/$STREAM" \
-H "Authorization: Bearer $TOKEN"
```
## Next steps
To feed a whole Fishjam room's peers into the template, continue with [Compose a Fishjam room](./compose-a-fishjam-room). To update the template's on-screen state at runtime, see [Drive a template with events](./drive-a-template-with-events).
---
## Manage recordings
Once a recording exists, you manage it through the [Fishjam Server API](./../../api/reference#server) the same way, whether it was created [with a template](./record-with-a-template) or [from a composition output](./record-a-composition-output). Every call below is a method on the `FishjamClient` of the [JS and Python server SDKs](./../backend/server-setup).
```bash
export FISHJAM_URL="https://fishjam.io/api/v1/connect/"
export TOKEN=""
export RECORDING=""
```
## Check the status
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
declare const recording: Recording;
// ---cut---
const { status } = await fishjamClient.getRecording(recording.id);
```
```python
status = fishjam_client.get_recording(recording.id).status
```
```bash
curl "$FISHJAM_URL/recordings/$RECORDING" \
-H "Authorization: Bearer $TOKEN"
```
A recording has four statuses:
| Status | Meaning |
| ----------- | ------------------------------------------------------- |
| `active` | Media is being captured. |
| `finished` | Capture has ended and the file is being prepared. |
| `available` | The MP4 is ready and `files` contains the download URL. |
| `failed` | An error occurred and no file will be produced. |
Instead of polling, you can subscribe to [server notifications](./../../api/reference#protobufs): every status change emits a `RecordingStatusChanged` message containing the recording's id, its new status, and its metadata, delivered over your configured webhook or a websocket.
## Stop the recording
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
declare const recording: Recording;
// ---cut---
await fishjamClient.stopRecording(recording.id);
```
```python
fishjam_client.stop_recording(recording.id)
```
```bash
curl -X POST "$FISHJAM_URL/recordings/$RECORDING/stop" \
-H "Authorization: Bearer $TOKEN"
```
Finalization is asynchronous: the recording remains `active` until capture has ended, then transitions to `finished`. Stopping a recording that is no longer active has no effect.
Stopping a recording explicitly is optional. Capture also ends when the composition ends, so [deleting the composition](./../../explanation/compositions#cost-and-lifecycle) finalizes its recordings. A recording of a composition output also ends when that output ends.
## Download the MP4
Once the status is `available`, the recording's `files` field lists its media files in playback order as direct HTTPS URLs:
```json
{
"data": {
"id": "",
"status": "available",
"files": [{ "url": "https://media.fishjam.io/.../index.mp4" }],
"source": { "...": "..." },
"metadata": { "show": "weekly-standup" }
}
}
```
You can download the file or serve the URL to your users directly. Until the recording is `available`, `files` is empty.
Fishjam keeps recordings for 3 months after they are created, so download any file you need for longer. See [Retention](./../../explanation/recordings#retention).
## List your recordings
`GET /recordings` lists every recording in your app and accepts filters on status and metadata. A metadata filter matches recordings whose metadata contains all of the given pairs. Values are compared as strings, so numeric and boolean metadata values cannot be matched this way.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
// ---cut---
const recordings = await fishjamClient.getAllRecordings({
show: "weekly-standup",
});
```
```python
recordings = fishjam_client.get_all_recordings({"show": "weekly-standup"})
```
```bash
curl -g "$FISHJAM_URL/recordings?status=available&metadata[show]=weekly-standup" \
-H "Authorization: Bearer $TOKEN"
```
The `-g` flag prevents curl from interpreting the square brackets.
The SDK methods filter by metadata only. To filter by status as well, call the REST endpoint directly.
## Delete a recording
Recordings persist independently of the composition for 3 months. To remove one sooner, delete it. Deleting a recording also removes its files:
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
declare const recording: Recording;
// ---cut---
await fishjamClient.deleteRecording(recording.id);
```
```python
fishjam_client.delete_recording(recording.id)
```
```bash
curl -X DELETE "$FISHJAM_URL/recordings/$RECORDING" \
-H "Authorization: Bearer $TOKEN"
```
An `active` recording cannot be deleted. Stop it first and delete it once its status is no longer `active`.
See the [Server REST API](/api/rest) reference for the complete request and response schemas.
---
## Record a composition output
A **composition recording** mirrors an output that a composition already publishes: it captures that output's media from the moment it is created and stores it as an MP4 file. Use it to keep a copy of a live stream you are already running. To record something that is not published live, or to record a layout different from the live stream, [record with a template](./record-with-a-template) instead.
Compositions are managed through the [Composition API](./../../api/reference#compositions), while recordings are managed through the [Fishjam Server API](./../../api/reference#server): a single call there starts the recording, and Fishjam controls the capture inside the composition on your behalf. The [Recordings](./../../explanation/recordings) article explains this model and the recording lifecycle in more detail.
```mermaid
flowchart LR
Composition[composition] --> Output[output]
Output --> Livestream[livestream / RTMP]
Livestream --> Viewers[viewers]
Output -- recording --> MP4[MP4]
MP4 --> Download[download]
```
## Prerequisites
A running composition with its inputs registered, a livestream for it to publish to, and the livestream's streamer token. The [tutorial](./../../tutorials/compositions) sets these up in Steps 1 to 3; stop before Step 4, which registers the same output as Step 1 below.
```bash
export FISHJAM_URL="https://fishjam.io/api/v1/connect/"
export TOKEN=""
export COMPOSITION=""
export STREAMER_TOKEN=""
```
Step 1 uses the `CompositionClient`; every recording call from Step 2 onwards is a method on the `FishjamClient` of the [JS and Python server SDKs](./../backend/server-setup). Both are shown in the language tabs.
## Step 1: Register the output to record
A recording attaches to an output, so the composition must first have an output whose scene will be recorded. Register it like any other output. Every output publishes to a destination, so the output you record is also a live stream: in this example, `main` publishes to your livestream over WHIP, with the tutorial's two inputs side by side.
```ts
CompositionClient,
CompositionId,
FishjamClient,
InputId,
OutputId,
} from "@fishjam-cloud/js-server-sdk";
const compositionClient = new CompositionClient({ managementToken: "" });
const fishjamClient = new FishjamClient({ fishjamId: "", managementToken: "" });
const compositionId = "" as CompositionId;
const outputId = "" as OutputId;
const streamerToken = "";
const race = "race" as InputId;
const player = "player" as InputId;
// ---cut---
await compositionClient.registerWhipOutput(compositionId, outputId, {
endpointUrl: fishjamClient.livestreamWhipUrl(),
bearerToken: streamerToken,
video: {
resolution: { width: 1280, height: 720 },
initial: {
root: {
type: "tiles",
children: [
{ type: "input_stream", inputId: race },
{ type: "input_stream", inputId: player },
],
},
},
},
audio: { initial: { inputs: [{ inputId: player }] } },
});
```
```python
from fishjam.composition import (
AudioScene,
AudioSceneInput,
InputStream,
InputStreamType,
OutputWhipAudioOptions,
OutputWhipVideoOptions,
Resolution,
Tiles,
TilesType,
VideoScene,
)
composition_client.register_whip_output(
composition_id,
"main",
endpoint_url=fishjam_client.livestream_whip_url(),
bearer_token=streamer_token,
video=OutputWhipVideoOptions(
resolution=Resolution(width=1280, height=720),
initial=VideoScene(
root=Tiles(
type_=TilesType.TILES,
children=[
InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="race"
),
InputStream(
type_=InputStreamType.INPUT_STREAM, input_id="player"
),
],
)
),
),
audio=OutputWhipAudioOptions(
initial=AudioScene(inputs=[AudioSceneInput(input_id="player")])
),
)
```
```bash
curl -X POST "https://rtc.fishjam.io/api/composition/$COMPOSITION/output/main/register" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d @- <
The recording captures this scene and every subsequent update sent to `main`. If your composition already has the output you want to record, for example the templated output from [Compose a Fishjam room](./../compositions/compose-a-fishjam-room), skip to Step 2. See [Choose inputs and outputs](./../compositions/inputs-and-outputs) for the other output types.
## Step 2: Start the recording
Specify the composition and the output from Step 1 in `source`:
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
// ---cut---
const recording = await fishjamClient.createCompositionRecording({
source: {
compositionURL: "https://rtc.fishjam.io/api/composition/",
outputId: "main",
},
metadata: { show: "weekly-standup" },
});
```
The response returns the recording with status `active`; capture has already started.
```python
from fishjam import FishjamClient
from fishjam.recording import CompositionSource
fishjam_client = FishjamClient(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["MANAGEMENT_TOKEN"],
)
recording = fishjam_client.create_composition_recording(
source=CompositionSource(
composition_url="https://rtc.fishjam.io/api/composition/",
output_id="main",
),
metadata={"show": "weekly-standup"},
)
```
The response returns the recording with status `active`; capture has already started.
```bash
curl -X POST "$FISHJAM_URL/recordings" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"source\": {
\"compositionURL\": \"https://rtc.fishjam.io/api/composition/$COMPOSITION\",
\"outputId\": \"main\"
},
\"metadata\": { \"show\": \"weekly-standup\" }
}"
```
The response returns the recording with status `active`; capture has already started. Save its id from `data.id`:
```bash
export RECORDING=""
```
Note the following:
- The recording mirrors the output it captures: the same layout and resolution, including every scene update. The file is encoded separately from the live stream. To record at a different resolution than the live output, add `scaleRatio` to `source`: `0.5` records at half the output's resolution, and values above `1` upscale. The default is `1`.
- An output can have at most one recording at a time. To record the same output again, wait until the current recording is no longer `active`.
- `metadata` is optional and free-form. It is returned with the recording and can be used to filter recordings later.
## Step 3: Stop and download the recording
Stopping, checking the status, downloading the MP4, and deleting the recording work the same for every recording. Continue with [Manage recordings](./manage-recordings).
---
## Record with a template
A **template recording** renders a React [template](./../compositions/write-and-deploy-a-template) directly into an MP4 file. The template describes what the recording shows, and the recording is the only thing it produces: there is no output to register and no live stream to publish to.
```mermaid
flowchart LR
Inputs[inputs] --> Composition[composition]
Composition -- template --> Recording[recording]
Recording --> MP4[MP4]
MP4 --> Download[download]
```
The template runs inside a composition, which holds the inputs it renders. The [Recordings](./../../explanation/recordings) article explains how template recordings relate to compositions and to recordings of an existing output.
## Prerequisites
- A running composition with inputs. Either register inputs yourself, as in [Steps 1 and 2 of the compositions tutorial](./../../tutorials/compositions#step-1-create-a-composition), or forward a Fishjam room into it and start the composition, as in [Steps 4 and 5 of Compose a Fishjam room](./../compositions/compose-a-fishjam-room#step-4-forward-the-room-into-the-composition). A composition created with `autostart: false` renders nothing until it is started. You do not need a livestream or any other output.
- A template project scaffolded with the composition CLI (see [Write and deploy a template](./../compositions/write-and-deploy-a-template#scaffold-a-project)).
```bash
export FISHJAM_URL="https://fishjam.io/api/v1/connect/"
export TOKEN=""
export COMPOSITION=""
```
Every recording call is a method on the `FishjamClient` of the [JS and Python server SDKs](./../backend/server-setup), shown in the language tabs below.
## Step 1: Write and bundle the template
A recording template is written exactly like the template of an output. This one tiles every input that is playing, so the recording follows inputs as they come and go:
```tsx
// @jsx: react-jsx
// ---cut-before---
InputStream,
Rescaler,
Tiles,
View,
useInputStreams,
} from "@swmansion/smelter";
export default function App() {
const inputs = Object.values(useInputStreams());
const playing = inputs.filter((input) => input.videoState === "playing");
return (
{playing.map((input) => (
))}
);
}
```
The template decides everything the recording shows. It can use the room hooks from `@fishjam-cloud/composition`, such as `usePeers()`, to render a forwarded room (see [Compose a Fishjam room](./../compositions/compose-a-fishjam-room#step-2-write-a-room-aware-template)), and the `eventBus` to react to [events you send to the composition](./../compositions/drive-a-template-with-events).
Build the bundle:
```bash npm2yarn
npm run build
```
The bundle, `dist/App.js`, can weigh at most 1 MiB.
## Step 2: Start the recording
Pass the composition in `source` and the bundle alongside it:
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.MANAGEMENT_TOKEN!,
});
// ---cut---
const recording = await fishjamClient.createTemplateRecording(
{
source: {
compositionURL: "https://rtc.fishjam.io/api/composition/",
resolution: { width: 1280, height: 720 },
},
metadata: { show: "weekly-standup" },
},
"dist/App.js",
);
```
The template is either a path to the bundle or a `Blob` with its contents. The response returns the recording with status `active`; capture has already started.
```python
from fishjam import FishjamClient
from fishjam.recording import TemplateSource, TemplateSourceResolution
fishjam_client = FishjamClient(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["MANAGEMENT_TOKEN"],
)
recording = fishjam_client.create_template_recording(
source=TemplateSource(
composition_url="https://rtc.fishjam.io/api/composition/",
resolution=TemplateSourceResolution(width=1280, height=720),
),
template="dist/App.js",
metadata={"show": "weekly-standup"},
)
```
The template is either a path to the bundle or its contents as `bytes`. The response returns the recording with status `active`; capture has already started.
A template recording is created with a `multipart/form-data` request: the configuration in a `config` part and the bundle in a `template` part.
```bash
CONFIG=$(cat <
Note the following:
- `resolution` sets the size the template is rendered at. It defaults to 1280x720, has to be even on both sides, and can be at most 3840x2160.
- `audio` controls whether the recording captures audio. It defaults to `true`; set it to `false` for a video-only file.
- A composition can run several template recordings at once, each with its own template.
- `metadata` is optional and free-form. It is returned with the recording and can be used to filter recordings later.
## Step 3: Stop and download the recording
A template recording captures until you stop it or its composition ends. A composition ends when you delete it, or when it [cleans itself up](./../../explanation/compositions#cost-and-lifecycle) after five minutes without input media, so keep inputs flowing for as long as you want to record.
Stopping, checking the status, downloading the MP4, and deleting the recording work the same for every recording. Continue with [Manage recordings](./manage-recordings).
---
## TypeScript client
This guide lists everything `@fishjam-cloud/ts-client` can do, with a short example for each feature.
The TypeScript client has no UI bindings: you call methods on a `FishjamClient` and listen to its events.
If you have not used it before, start with the [TypeScript Quick Start](../tutorials/typescript-quick-start).
:::tip
Unless stated otherwise, the examples assume you have already created a client:
```ts
const client = new FishjamClient();
```
:::
## Connect to a room
### Create the client
```ts
// ---cut---
const client = new FishjamClient({
debug: true, // log SDK internals to the console
reconnect: true, // the default, see "Reconnect" below
});
```
### Join
`connect` resolves once you have joined the room and rejects if the token is rejected or the room can't be joined:
```ts
const client = new FishjamClient();
const FISHJAM_ID = "";
const peerToken = "";
// ---cut---
await client.connect({
url: `wss://fishjam.io/api/v1/connect/${FISHJAM_ID}`,
token: peerToken,
peerMetadata: {},
});
```
### Handle connection errors
Fishjam closes the connection with a reason you can check with `isAuthError` and `isJoinError`:
```ts
const client = new FishjamClient();
// ---cut---
client.on("authError", (reason) => {
// "missing token" | "invalid token" | "expired token" | "room not found" | "peer not found"
console.error("Token rejected:", reason);
});
client.on("joinError", (reason) => {
// e.g. "reached peers limit" | "room not found"
console.error("Could not join:", reason);
});
client.on("connectionError", ({ message }) => {
console.error("Media connection failed:", message);
});
```
Other connection events: `connectionStarted`, `socketOpen`, `socketClose`, `socketError`, `authSuccess`, `joined` and `disconnected`.
### Leave
```ts
const client = new FishjamClient();
// ---cut---
// Leave the room and close the connection
client.disconnect();
```
`client.leave()` only leaves the room and keeps the connection open. In most apps you want `disconnect()`.
## Reconnect
The client reconnects automatically when the connection drops. By default it makes up to 3 attempts, waiting 500 ms, 1000 ms and 1500 ms.
It does not retry after an authentication or join error.
```ts
// ---cut---
const client = new FishjamClient({
reconnect: {
maxAttempts: 5,
initialDelay: 1000, // ms to wait before the first attempt
delay: 1000, // ms added to the wait for each next attempt
addTracksOnReconnect: true, // publish your tracks again after reconnecting
},
});
client.on("reconnectionStarted", () => console.log("Reconnecting..."));
client.on("reconnected", () => console.log("Reconnected"));
client.on("reconnectionRetriesLimitReached", () => console.log("Gave up"));
```
Pass `reconnect: false` to turn it off. `client.isReconnecting()` tells you if a reconnection is in progress.
## Publish media
### Camera and microphone
`addTrack` takes a `MediaStreamTrack` and its metadata, and returns the track ID:
```ts
const client = new FishjamClient();
// ---cut---
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true,
});
const cameraTrackId = await client.addTrack(stream.getVideoTracks()[0], {
type: "camera",
paused: false,
});
const micTrackId = await client.addTrack(stream.getAudioTracks()[0], {
type: "microphone",
paused: false,
});
```
Available track types: `camera`, `microphone`, `screenShareVideo`, `screenShareAudio`, `customVideo` and `customAudio`.
Other peers see the type in the track's metadata.
:::note
In an [audio-only room](./backend/audio-only-calls), adding a video track throws `TrackTypeError`.
:::
### Switch device
`replaceTrack` swaps the source of a published track without creating a new one:
```ts
const client = new FishjamClient();
const cameraTrackId = "";
const deviceId = "";
// ---cut---
const newStream = await navigator.mediaDevices.getUserMedia({
video: { deviceId: { exact: deviceId } },
});
await client.replaceTrack(cameraTrackId, newStream.getVideoTracks()[0]);
```
### Mute and unmute
Replace the track with `null` and mark it as paused, so other peers know it is muted:
```ts
const client = new FishjamClient();
const cameraTrackId = "";
const cameraTrack = {} as MediaStreamTrack;
// ---cut---
// Mute
await client.replaceTrack(cameraTrackId, null);
client.updateTrackMetadata(cameraTrackId, { type: "camera", paused: true });
// Unmute
await client.replaceTrack(cameraTrackId, cameraTrack);
client.updateTrackMetadata(cameraTrackId, { type: "camera", paused: false });
```
### Share your screen
```ts
const client = new FishjamClient();
// ---cut---
const screen = await navigator.mediaDevices.getDisplayMedia({ video: true });
const screenTrackId = await client.addTrack(screen.getVideoTracks()[0], {
type: "screenShareVideo",
paused: false,
});
```
### Stop publishing
```ts
const client = new FishjamClient();
const screenTrackId = "";
// ---cut---
await client.removeTrack(screenTrackId);
```
The client also emits events about your own tracks: `localTrackAdded`, `localTrackRemoved`, `localTrackReplaced`, `localTrackMuted`, `localTrackUnmuted` and `localTrackMetadataChanged`.
## Receive media
### Peers
```ts
const client = new FishjamClient();
// ---cut---
client.on("joined", (myPeerId, peersInRoom) => {
console.log(
`Joined as ${myPeerId}, ${peersInRoom.length} peers already here`,
);
});
client.on("peerJoined", (peer) => console.log("Joined:", peer.id));
client.on("peerUpdated", (peer) => console.log("Updated:", peer.id));
client.on("peerLeft", (peer) => console.log("Left:", peer.id));
```
### Tracks
A remote track goes through these events:
1. `trackAdded`: the track exists, but no media has arrived yet
2. `trackReady`: media is arriving, `ctx.track` and `ctx.stream` are set
3. `trackUpdated`: its metadata changed, for example it was paused
4. `trackRemoved`: the peer stopped publishing it, or left
```ts
const client = new FishjamClient();
// ---cut---
client.on("trackReady", (ctx) => {
if (!ctx.track) return;
const element = document.createElement(
ctx.track.kind === "video" ? "video" : "audio",
);
element.id = ctx.trackId;
element.autoplay = true;
element.srcObject = new MediaStream([ctx.track]);
document.body.appendChild(element);
console.log(`${ctx.endpoint.id} sent a ${ctx.metadata?.type} track`);
});
client.on("trackUpdated", (ctx) => {
console.log(`Track ${ctx.trackId} paused:`, ctx.metadata?.paused);
});
client.on("trackRemoved", (ctx) => {
document.getElementById(ctx.trackId)?.remove();
});
```
:::tip
Register these listeners before calling `connect`, so you don't miss the tracks of peers who are already in the room.
:::
### Read the current state
Besides events, you can read a snapshot of the room at any time:
```ts
const client = new FishjamClient();
// ---cut---
const me = client.getLocalPeer();
const peers = client.getRemotePeers(); // keyed by peer ID
const tracks = client.getRemoteTracks(); // keyed by track ID
```
### Voice activity
Each remote audio track reports whether its peer is speaking:
```ts
const client = new FishjamClient();
// ---cut---
client.on("trackAdded", (ctx) => {
if (ctx.metadata?.type !== "microphone") return;
ctx.on("voiceActivityChanged", () => {
console.log(`${ctx.endpoint.id} is ${ctx.vadStatus}`); // "speech" | "silence"
});
});
```
### Components
Server-side components, such as recordings, are reported separately from peers:
```ts
const client = new FishjamClient();
// ---cut---
client.on("componentAdded", (component) => {
console.log("Component added:", component.type); // e.g. "recording"
});
const components = client.getRemoteComponents();
```
Also available: `componentUpdated` and `componentRemoved`.
## Metadata
Pass a type to `FishjamClient` to get typed peer metadata:
```ts
const FISHJAM_ID = "";
const peerToken = "";
// ---cut---
type PeerMetadata = { name: string };
const client = new FishjamClient();
await client.connect({
url: `wss://fishjam.io/api/v1/connect/${FISHJAM_ID}`,
token: peerToken,
peerMetadata: { name: "Alice" },
});
// Change it later; other peers get a "peerUpdated" event
client.updatePeerMetadata({ name: "Alice (away)" });
client.on("peerUpdated", (peer) => {
console.log(peer.metadata?.peer?.name); // set by the peer
console.log(peer.metadata?.server); // set by your backend when creating the peer
});
```
See [Metadata](./client/metadata) for how peer and server metadata differ.
## Simulcast
With [simulcast](../explanation/simulcast), you publish your video in several qualities and each receiver picks one.
### Publish several qualities
```ts
const client = new FishjamClient();
const cameraTrack = {} as MediaStreamTrack;
// ---cut---
const cameraTrackId = await client.addTrack(
cameraTrack,
{ type: "camera", paused: false },
{
enabled: true,
enabledVariants: [
Variant.VARIANT_LOW,
Variant.VARIANT_MEDIUM,
Variant.VARIANT_HIGH,
],
disabledVariants: [],
},
);
// Temporarily stop sending one of the qualities
await client.disableTrackEncoding(cameraTrackId, Variant.VARIANT_HIGH);
await client.enableTrackEncoding(cameraTrackId, Variant.VARIANT_HIGH);
```
### Choose the received quality
```ts
const client = new FishjamClient();
const remoteTrackId = "";
// ---cut---
// For example: low quality for thumbnails, high for the active speaker
client.setTargetTrackEncoding(remoteTrackId, Variant.VARIANT_LOW);
client.on("encodingChanged", (ctx) => {
// reason: "other" | "encodingInactive" | "lowBandwidth"
console.log(`Now receiving ${ctx.encoding}, reason: ${ctx.encodingReason}`);
});
```
If the chosen quality is not available, for example because the sender disabled it or your bandwidth is too low, Fishjam sends another one until it is.
## Limit bandwidth
All limits are in kilobits per second.
```ts
const client = new FishjamClient();
const cameraTrack = {} as MediaStreamTrack;
const cameraTrackId = "";
const simulcastConfig = {
enabled: false,
enabledVariants: [],
disabledVariants: [],
};
// ---cut---
// Cap a track when publishing it
await client.addTrack(
cameraTrack,
{ type: "camera", paused: false },
simulcastConfig,
1500,
);
// Change the cap later
await client.setTrackBandwidth(cameraTrackId, 800);
// For simulcast tracks, cap a single quality
await client.setEncodingBandwidth(cameraTrackId, Variant.VARIANT_HIGH, 1200);
```
To see how much bandwidth Fishjam estimates you can receive (in bits per second):
```ts
const client = new FishjamClient();
// ---cut---
console.log(client.getBandwidthEstimation());
client.on("bandwidthEstimationChanged", (estimation) => {
console.log(`Estimated incoming bandwidth: ${estimation} bps`);
});
```
## Data channels
Send binary data to everyone in the room. Use the reliable channel for chat messages and the lossy channel for frequent updates where only the latest value matters.
See [Data channels](../explanation/data-channels) for details.
Call these after joining the room:
```ts
const client = new FishjamClient();
// ---cut---
const unsubscribe = client.subscribeData(
(data) => console.log("Received:", new TextDecoder().decode(data)),
{ reliable: true },
);
client.on("dataChannelsReady", () => {
client.publishData(new TextEncoder().encode("Hello!"), { reliable: true });
});
client.on("dataChannelsError", (error) => console.error(error));
await client.createDataChannels();
```
`client.getDataChannelsReadiness()` tells you if the channels are ready.
## Livestreaming
For [livestreams](../explanation/livestreams), the package exports two standalone functions. They don't need a `FishjamClient`.
### Publish a livestream
Get a streamer token from [your backend](./backend/whip-whep):
```ts
const streamerToken = "";
// ---cut---
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true,
});
const { stopPublishing } = await publishLivestream(
stream,
"https://fishjam.io/api/v1/live/api/whip",
streamerToken,
);
// Later
await stopPublishing();
```
### Watch a livestream
For a private livestream, pass a viewer token. For a public one, add the room ID to the URL and skip the token:
```ts
const viewerToken = "";
const video = document.createElement("video");
// ---cut---
try {
const { stream, stop } = await receiveLivestream(
"https://fishjam.io/api/v1/live/api/whep",
viewerToken,
);
video.srcObject = stream;
} catch (error) {
if (error === LivestreamError.STREAM_NOT_FOUND) {
console.log("The stream has not started yet");
}
}
```
Possible errors: `UNAUTHORIZED`, `STREAM_NOT_FOUND`, `STREAMER_ALREADY_CONNECTED` and `UNKNOWN_ERROR`.
## Statistics
```ts
const client = new FishjamClient();
const micTrackId = "";
// ---cut---
// Standard WebRTC statistics for the whole connection
const stats = await client.getStatistics();
// Volume of your microphone, from 0 to 1, e.g. for a level meter
const audioLevel = await client.getLocalTrackAudioLevel(micTrackId);
console.log(audioLevel?.level);
```
`getStatistics` returns the browser's [`RTCStatsReport`](https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport), the same data as [`RTCPeerConnection.getStats()`](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats).
It is a map of reports, each with a `type`. The most useful ones:
- `outbound-rtp`: media you send, for example `bytesSent`, `framesPerSecond` and `qualityLimitationReason`
- `inbound-rtp`: media you receive, for example `bytesReceived`, `packetsLost`, `jitter` and `framesDropped`
- `candidate-pair`: the connection itself, for example `currentRoundTripTime` and `availableOutgoingBitrate`
Pass a `MediaStreamTrack` to get the statistics of that track only.
## Not included
The React and React Native SDKs add features on top of the TypeScript client. With the TypeScript client, use browser APIs directly instead:
- Listing and selecting cameras and microphones: use `navigator.mediaDevices`
- [Camera effects](../explanation/camera-effects) and [custom sources](../explanation/custom-sources): process or create the `MediaStreamTrack` yourself before `addTrack`
- Picture in Picture: use the browser's Picture-in-Picture API
- Sandbox API helpers: call the Sandbox API with `fetch`, as in the [quick start](../tutorials/typescript-quick-start#step-2-get-a-peer-token)
---
## Agent Internals
:::info
This explanation focuses on the inner workings of Fishjam Agents.
If you are looking for a tutorial that shows how to implement an agent, then you may find the [Agent Introduction](../tutorials/agents) more useful.
:::
## What is an Agent?
An agent is a piece of software that allows your backend server to participate in a Fishjam room, similar to how the Fishjam client SDKs allow your client-side application to participate in a Fishjam room.
They can be used to implement features such as real-time audio transcription, real-time content moderation, conversations with AI agents and more.
You can simply think of an agent as a peer running within your backend application.
## Agent lifecycle
There are four steps to the lifecycle of a Fishjam Agent:
1. The agent is created in the room `roomId`.
Fishjam generates a token that the agent will use to connect to the room.
2. The agent connects to the room `roomId` via a WebSocket connection.
3. The agent receives audio from **subscribed** peers in the room `roomId`.
Subscriptions are explained in the [Peer subscriptions](#peer-subscriptions) section.
4. The agent disconnects from the room `roomId` by closing the WebSocket connection.
We describe the steps of an agent's lifecycle in detail below.
:::tip
The Fishjam [server SDKs](../tutorials/agents#writing-an-agent) provide a simple way to integrate with the APIs described below.
:::
### Step 1. Creating an Agent in Fishjam
Agents are created via the `/room/{roomId}/peer` [REST API](../api/reference#rest-api) endpoint, by setting the `type` option to `"agent"`.
An example request with [cURL](https://curl.se/) would look like:
```bash
# [!code word:{"type"\: "agent"}]
curl -XPOST -H "Authorization: Bearer $FISHJAM_MANAGEMENT_TOKEN" \
"https://fishjam.io/api/v1/room/$ROOM_ID/peer" \
--json '{"type": "agent"}'
```
### Step 2. Connecting to the Room
Agents connect to Fishjam by initiating a WebSocket connection on the `/socket/agent/websocket` REST API endpoint.
All communication over the WebSocket between Agent the Fishjam is done using [Protobuf messages](https://protobuf.dev/).
Check [Fishjam Protobuf reference](../api/reference#protobufs) for more info.
Once connected, the agent must authenticate with Fishjam by sending an [`AgentRequest.AuthRequest` protobuf message](../api/reference#protobufs).
An example of initiating a connection using [websocat](https://github.com/vi/websocat) and [Buf CLI](https://buf.build/docs/cli/) would look like:
```bash
# Get the Fishjam protobuf definitions
git clone https://github.com/fishjam-cloud/protos.git
echo "{\"authRequest\": {\"token\": \"$AGENT_TOKEN\"}}" \
| buf convert protos/fishjam/agent_notifications.proto \
--type="fishjam.AgentRequest" --from="-#format=json" \
| websocat -vbn wss://fishjam.io/api/v1/connect/$FISHJAM_ID/socket/agent/websocket
```
In a backend application, we suggest using the [Protobuf compiler](https://protobuf.dev/installation/) to generate utilities for creating protobuf message from code.
### Step 3. Receiving Audio
Once connected, an agent will receive chunks of audio as [`AgentRequest.TrackData` protobuf message](../api/reference#protobufs).
### Step 4. Sending Audio
All further steps are done via the WebSocket connection created in [Step 2](#step-2-connecting-to-the-room).
To send audio to an agent, you need to create an audio track first.
This is done by sending an [`AgentRequest.CreateTrack` protobuf message](../api/reference#protobufs).
Once the track is created, you can send audio to it using [`AgentRequest.TrackData` protobuf message](../api/reference#protobufs).
### Step 5. Disconnecting from the Room
An agent disconnects from the room by closing the WebSocket connection created in [Step 2](#step-2-connecting-to-the-room).
It may reconnect using the same token it provided in [Step 2](#step-2-connecting-to-the-room).
:::danger[Remember to disconnect your agents!]
It's important to disconnect agents, because **every connected agent generates usage** just as a normal peer.
:::
## Peer subscriptions
By default, agents **won't** receive peers' audio streams.
This is by design and aims to prevent unnecessary resource usage by the agents.
For an agent to start receiving a peer's audio, the peer must be **created** with the **subscribe** option set.
The subscribe option contains parameters describing the desired output format of the peer's audio stream.
This output format will be sent to connected agents.
### Output format
Currently, only **16-bit PCM** (raw) audio output is supported.
### Output sample rate
The output can have either a sample rate of **16kHz** or **24kHz**.
The above values aim to be compatible with popular real-time AI audio APIs.
If you require a different output format, then make sure to contact us at `contact@fishjam.io`.
---
## Fishjam Architecture
_Understanding how Fishjam works under the hood_
This document explains the technical architecture of Fishjam and how data flows through the system.
## High-level Architecture
Streaming with Fishjam is simple: you create a room, add peers to it, and start streaming. Below is a high-level overview of how Fishjam works.

## Components Overview
### 1. Your Backend Server
Your application's backend server is responsible for:
- Authenticating users
- Creating rooms using Fishjam Server SDKs
- Generating peer tokens for clients
- Managing room lifecycle and permissions
### 2. Fishjam Media Server
The Fishjam Media Server is the core infrastructure component that:
- Routes audio and video streams between participants
- Handles WebRTC negotiations and connections
- Manages different room types (conference, audio-only, livestream)
- Processes and transcodes media when needed
- Enforces security policies and token validation
### 3. Client Applications
Client applications (React Native, React) use Fishjam Client SDKs to:
- Connect to rooms using peer tokens
- Send and receive audio/video streams
- Handle device management (cameras, microphones)
- Manage connection state and reconnections
## Data Flow
### 1. Room Creation Flow
```mermaid
sequenceDiagram
participant FM as Fishjam Media Server
participant BE as Your Backend
participant Client as Client App
Client->>BE: Request to join room
BE->>FM: Create room (Server SDK)
FM->>BE: Return room ID
BE->>FM: Create peer (Server SDK)
FM->>BE: Return peer token
BE->>Client: Send peer token + Fishjam ID
```
### 2. Media Streaming Flow
```mermaid
sequenceDiagram
participant C1 as Client 1
participant FM as Fishjam Media Server
participant C2 as Client 2
C1->>FM: Connect with peer token
C2->>FM: Connect with peer token
C1->>FM: Send video/audio stream
FM->>C2: Route stream to other peers
C2->>FM: Send video/audio stream
FM->>C1: Route stream to other peers
```
## Next Steps
To understand different room types in detail, see [Rooms](../explanation/rooms).
To learn about security and token management, see [Security & Token Model](../explanation/security-tokens).
Ready to implement? Start with our tutorials:
- [React Native Quick Start](../tutorials/react-native-quick-start)
- [Backend Quick Start](../tutorials/backend-quick-start)
---
## How camera effects work
[Camera effects](../how-to/client/camera-effects/index.mdx) change the camera video a React Native app publishes: a blurred background, a background image, or anything your own shaders draw. This page explains where effects plug into the Fishjam client, how camera frames reach a worklet and the GPU without copying pixels, and how effects such as background blur are structured.
## Middleware, custom source, or VisionCamera?
Fishjam clients offer three ways to publish processed camera video:
| Approach | What it does | When to use it |
| ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| [Camera track middleware](../how-to/client/camera-effects/stream-middleware.mdx) | Replaces the camera track Fishjam captures with a processed one before it's sent | Effects on the regular camera; peers receive them as your `cameraTrack` |
| [Custom sources](../how-to/client/custom-sources/index.mdx) | Publishes a `MediaStream` your app produced on its own as a `customVideo` track | Content that isn't the managed camera: renderers, compositors, file playback |
| [VisionCamera integration](../integrations/vision-camera/vision-camera-source.mdx) | Publishes a VisionCamera feed as a custom source | Your app already depends on VisionCamera for capture, device control or plugins |
Middleware is the default for effects: device selection, permissions, starting, stopping and switching cameras stay with [`useCamera`](../api/mobile/functions/useCamera), and the receiving side needs no changes.
## Where effects plug in
A camera track middleware is a function from the raw camera track to the track that is published instead. The Fishjam client owns when it runs:
- **Every new device track goes through it.** The middleware runs when the camera starts, restarts or is switched, so the raw track is never published while a middleware is set.
- **Publish first, release second.** When a middleware is set or replaced, the client builds the new track, swaps it into the published stream, and only then releases the previous one. Releasing a React Native track disposes it natively, so the order keeps the published stream from ever holding a dead track.
- **The latest request wins.** If a middleware is replaced while it is still setting up, it releases itself as soon as it finishes and is never published. Until a new track is ready, peers keep receiving the previous one.
The middleware and its `onClear` live in the client's camera state, not in a component, which is why an effect stays on across screens until it is cleared with `null`.
## The camera frame pipeline
An effect needs every camera frame, on the GPU, without slowing down the JS thread. React Native has no built-in way to do that, so the pipeline is split across three packages:
```mermaid
flowchart LR
camera["Camera capturer(react-native-webrtc)"] --> tap["Camera frame processoradmits one frame at a time"]
tap --> runtime["Camera frame runtime(react-native-worklets)"]
runtime --> kernel["Your frame kernelor a video effect"]
kernel --> gpu["WebGPU render intoa pooled output surface"]
gpu --> track["Pooled video track"]
track --> room["Published asyour cameraTrack"]
```
### The camera tap
`@fishjam-cloud/react-native-webrtc` exposes a **camera frame processor** for every local camera track, returned by `getCameraFrameProcessor`. A consumer attached to it receives the frames the camera captures, as native buffers: `CVPixelBufferRef`s on iOS and `AHardwareBuffer`s on Android.
Frames are admitted one at a time. While a consumer still holds a frame, newer frames are dropped on the capture thread instead of being queued, so a slow effect lowers its own frame rate but never builds up latency.
### The worklet runtime
`@fishjam-cloud/react-native-worklets` is the consumer. `attachCameraFrameCallback` calls a worklet for every admitted frame on a dedicated **camera frame runtime**: a separate JS runtime with its own thread, created once for the whole app. The JS thread is not involved per frame, and the buffer handoff is a synchronous JSI call, which is why the pipeline requires the New Architecture.
A worklet's closure is copied to that runtime when it is attached. Anything the per-frame code needs, such as GPU pipelines, bind groups and plain numbers, must be created up front on the JS thread and captured.
### The render pipeline
`createCameraFrameProcessorSession` in `@fishjam-cloud/video-effects` turns the tap into a published track:
- It allocates a pool of three GPU-shareable output surfaces and a custom video track that reads from them. One surface can be encoding while the next is being drawn.
- For every frame, it imports the camera buffer into WebGPU as an external texture, already rotated upright, and hands your frame kernel a context with that texture, a command encoder and the next output surface.
- After the kernel has encoded its passes, it submits them once and pushes the surface to the track with a GPU fence, so the video encoder waits for the drawing to finish instead of reading a half-drawn frame. The frame keeps the camera's timestamp.
Pixels stay in native GPU memory from the camera to the encoder; only handles move between the camera, the worklet and the track. The session's track is what the middleware returns, and its `dispose` detaches the tap and frees the pool.
## Effects, sessions and frame kernels
The ready-made effects use the same pipeline. An effect is described in three layers:
- A **video effect** (`createBackgroundBlurEffect`, `createBackgroundImageEffect`) is a plain descriptor: an ID, the segmentation provider it needs, and a function that reads its options.
- Creating the effect for a device builds a **session** on the JS thread: GPU textures, pipelines and, for background effects, the prepared segmentation model.
- The session exposes a **frame kernel**: its GPU objects as plain data, plus worklet functions that encode one frame. Plain data is what lets the kernel be copied into the camera frame runtime.
`createCameraEffectMiddleware` connects the layers: when the middleware runs it creates the session, captures its frame kernel and the effect's current options, and starts a frame processor session whose kernel calls the effect for every frame. Because the kernel works on a copy, options are read once, when the middleware is applied.
### Segmentation
Background effects need to know which pixels belong to the person. The segmentation provider from `typeGpuPersonSegmentation` runs a selfie segmentation model entirely on the GPU, written with [TypeGPU](https://docs.swmansion.com/TypeGPU/):
- The model file is loaded and parsed once per model source and shared by every session that uses the same provider; each session builds its own GPU pipelines for it.
- For each frame, the effect first offers the camera texture to the provider, which encodes the inference into the same command encoder as the effect. The mask the effect composites with therefore belongs to the same frame.
- The effect then blurs the background, or draws the image behind the person, and softens the outline with the mask. When no recent mask is available, for example right after the model has loaded, the frame is published unchanged.
If the model can't be loaded, the session is still created and reports an `"error"` status, and the effect publishes the camera as it is. A failure to create the session at all, for example on a device without the required GPU features, rejects the middleware instead.
## Platform foundations
- **iOS**: camera buffers are imported directly as multi-planar external textures, and output surfaces are IOSurface-backed BGRA8 (`bgra8unorm`). The shared GPU device is requested with the `dawn-multi-planar-formats` feature.
- **Android**: the camera tap converts each camera image to an RGBA `AHardwareBuffer` before handing it over, and output surfaces are RGBA8 (`rgba8unorm`). Hardware buffers require Android 8.0 (API 26).
- On both platforms, frame kernels sample the camera as RGB, so shaders written against `createCameraShaderBindings` with `cameraPixelLayout: "rgb"` work unchanged.
## Where to go next
- [Camera effects how-to guides](../how-to/client/camera-effects/index.mdx): background effects, your own WebGPU effects, frame processing and middleware
- [Background blur tutorial](../tutorials/background-blur.mdx) and [WebGPU effects tutorial](../tutorials/webgpu-effects.mdx)
- [How custom sources work](./custom-sources.mdx): the custom video track pipeline the render sessions build on
- API reference: [Video Effects package](../api/video-effects/index.md), [React Native Worklets package](../api/react-native-worklets/index.md)
---
## Compositions(Explanation)
_Understanding real-time stream composition in Fishjam_
A **composition** mixes multiple live media streams into a single output stream in real time. You send inputs (WebRTC, RTMP, or MP4), describe how they should be laid out, and it produces one composed stream that it publishes to a destination of your choosing, all without running any rendering infrastructure yourself.
Compositions are built on [Smelter](https://smelter.dev), the source-available real-time video compositing engine by [Software Mansion](https://swmansion.com), and are a native part of Fishjam: they authenticate with the same Fishjam credentials and can compose the peers of a [Fishjam room](./rooms) directly.
## What you can build
- **Multi-party layouts**: arrange the cameras of a conference room, or several independent streams, into grids, side-by-sides, or picture-in-picture.
- **Branded streams**: overlay logos, captions, lower-thirds, and backgrounds on top of live video.
- **Cross-protocol bridging**: take WebRTC inputs and republish the composed result over RTMP, for example broadcasting a conference to YouTube or Twitch, or the other way round.
- **Recordings**: render a template, or capture a composed stream you already publish, into an MP4 file to store, replay, or serve on demand.
## Core concepts
A **composition** is a single running compositing session. You register three kinds of things into it:
- **Inputs**: the live media sources being composed (WebRTC via WHIP/WHEP, RTMP, or MP4).
- **Outputs**: where the composed result is sent (WebRTC via WHIP, or RTMP). Each output carries a **scene** that describes the layout.
- **Renderers**: shared assets such as images and fonts you can place in a scene.
A composition produces video, it does not serve it. There is nowhere to point a player at a composition, so it always needs an output aimed at a destination your viewers can connect to instead: a [livestream](./livestreams) they watch over WHEP, or an RTMP service such as YouTube.
An output's scene can either be described directly in the API or rendered by a **template**: a React component, written with the layout components and the [`@fishjam-cloud/composition`](./../how-to/compositions/write-and-deploy-a-template) hooks, that updates the layout live as the room changes.
## Getting media in
There are two ways to feed a composition:
- **Publish straight to an input.** Register an input and point any source at it: OBS, a phone camera, a browser tab, an RTMP encoder, or an MP4 file. This is the simplest path and needs no room. See [Choose inputs and outputs](./../how-to/compositions/inputs-and-outputs).
- **Forward a Fishjam room.** Use this to compose every peer of a [conference or audio-only room](./rooms). Fishjam registers an input per participant and keeps them in sync as peers join and leave. Livestream rooms cannot be forwarded. See [Compose a Fishjam room](./../how-to/compositions/compose-a-fishjam-room).
## Cost and lifecycle
A running composition holds a live rendering session for as long as it exists, and you are billed for that time whether or not anyone is watching.
Two defaults keep that in check. A composition auto-starts, and it cleans itself up after five minutes in which none of its inputs carry any media.
`cleanup_without_inputs: false` turns that guard off. It tightens the condition so cleanup needs both the inputs and the outputs to go quiet, which is what you want when inputs arrive late, such as a room whose peers have not joined yet, or when a composition legitimately has no inputs, such as an output that renders only text. The cost is that a composition whose output keeps publishing is no longer cleaned up for you, so anything created that way is yours to delete, and a forgotten one bills until you do.
Delete a composition as soon as you are done with it:
```ts
const compositionClient = new CompositionClient({ managementToken: "" });
const compositionId = "" as CompositionId;
// ---cut---
await compositionClient.deleteComposition(compositionId);
```
```python
composition_client.delete_composition(composition_id)
```
```bash
curl -X DELETE "https://rtc.fishjam.io/api/composition/$COMPOSITION" \
-H "Authorization: Bearer $TOKEN"
```
## Recordings
A **recording** saves media rendered in a composition into an MP4 file that stays around after the composition is gone. A template recording renders its own scene from a React template, with no output or live stream involved; a composition recording mirrors an output the composition already publishes. Recordings are a resource of their own, managed through the [Fishjam Server API](./../api/reference#server) rather than the Composition API: [Recordings](./recordings) explains how they work, and [Record with a template](./../how-to/recordings/record-with-a-template) and [Record a composition output](./../how-to/recordings/record-a-composition-output) walk through making one.
## Scenes
Every video output carries a **scene**: a tree of components that describes how inputs, text, and images are arranged into the composed frame. Audio outputs carry an **audio scene** that describes which inputs are mixed together.
### The video scene tree
A video scene has a single `root` component. Each component has a `type` that determines how it lays out its children.
```json
{
"root": {
"type": "tiles",
"children": [
{ "type": "input_stream", "input_id": "camera_1" },
{ "type": "input_stream", "input_id": "camera_2" }
]
}
}
```
The available component types are:
| `type` | Purpose |
| -------------- | -------------------------------------------------------------------------------- |
| `input_stream` | Renders one registered input. Identified by `input_id`. |
| `view` | A container you position and style; the basic building block for custom layouts. |
| `tiles` | Automatically arranges its children into a grid. |
| `rescaler` | Fits a single child into a target area, preserving aspect ratio. |
| `text` | Renders a text string. |
| `image` | Renders a registered image. Identified by `image_id`. |
Components nest freely: a `tiles` of `rescaler`s wrapping `input_stream`s, a `view` with a `text` caption over an `input_stream`, and so on. The styling and full property set of each component come from Smelter itself; the [Smelter HTTP API reference](https://smelter.dev/http-api/overview) documents every component and its properties.
### The audio scene
An audio scene lists the inputs to mix and, optionally, their relative volume:
```json
{
"inputs": [
{ "input_id": "camera_1" },
{ "input_id": "camera_2", "volume": 0.5 }
]
}
```
`volume` defaults to `1.0`. Only the inputs you list are audible in the output.
### Setting a scene
You provide the initial scene when you register an output, under `video.initial` (a video scene) and `audio.initial` (an audio scene). See [Choose inputs and outputs](./../how-to/compositions/inputs-and-outputs) for the full output shape.
### Changing a scene over time
A scene is not fixed for the life of an output. You can replace it while the composition is running, immediately or at a chosen point on the composition timeline.
Either you push those updates yourself, or you hand the job to a **template**: a React component that receives the live room state and re-renders as the room changes. See [Choose inputs and outputs](./../how-to/compositions/inputs-and-outputs) to send an update, or [Write and deploy a template](./../how-to/compositions/write-and-deploy-a-template) to build one.
## Where to go next
- [Compositions tutorial](./../tutorials/compositions): create your first composition end to end.
- [Write and deploy a template](./../how-to/compositions/write-and-deploy-a-template): build a React layout with the composition SDK.
- [Compose a Fishjam room](./../how-to/compositions/compose-a-fishjam-room): turn a room's peers into one composed stream.
- [Record with a template](./../how-to/recordings/record-with-a-template): render a template straight into an MP4.
- [Record a composition output](./../how-to/recordings/record-a-composition-output): save an output you already publish as an MP4.
- [Composition API](./../api/reference#compositions): the full REST surface.
---
## How custom sources work
[Custom sources](../how-to/client/custom-sources/index.mdx) let an app publish media that Fishjam did not capture itself. This page explains how custom tracks are modeled and routed, when they are published, and how the React Native pipelines move video frames to the encoder without copying pixels and turn pushed PCM into a live audio track.
## Built-in source, middleware, or custom source?
Fishjam clients offer three ways to influence what a peer publishes:
| Approach | What it does | When to use it |
| --------------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| Built-in sources (`useCamera`, `useMicrophone`, `useScreenShare`) | Capture and publish a device the SDK manages end-to-end | Plain camera, microphone or screen sharing |
| [Track middleware](../how-to/client/camera-effects/stream-middleware) | Transforms a built-in track before it is sent (e.g. background blur) | You want the SDK's device handling, but with a processing step in between |
| [Custom sources](../how-to/client/custom-sources/index.mdx) | Publishes a `MediaStream` your app produced entirely on its own | Content that isn't a managed device: renderers, compositors, ML pipelines |
Capabilities differ slightly per platform:
| Capability | Web | React Native |
| -------------------------------------- | ---------------------------------- | --------------------------------------------------- |
| Publish any `MediaStream` | ✅ | ✅ |
| Frame-level video injection | via `canvas.captureStream()` | ✅ native buffer forwarding / pooled render targets |
| Custom audio | ✅ any audio track | ✅ PCM pushed through `useCustomAudioSource` |
| GPU rendering into the published video | ✅ WebGPU/WebGL via canvas capture | ✅ WebGPU toolkit with zero-copy camera import |
In React Native, effects on the camera, such as background blur or your own WebGPU shaders, run as track middleware on Fishjam's own camera; see [How camera effects work](./camera-effects.mdx). The custom video track pipeline described below is what those effects publish through.
## Streams and source IDs
A custom source is a `MediaStream` registered under a stable **source ID** with `useCustomSource(sourceId)`. The ID makes the source addressable:
- Every `useCustomSource` call with the same ID, in any component, returns the same state, so one component can produce the stream while another controls or renders it.
- A peer can publish any number of custom sources, each under its own ID.
When the stream is published, Fishjam takes its first video track and first audio track (whichever are present) and publishes them with the track metadata types `customVideo` and `customAudio`. The metadata is how the receiving side tells custom tracks apart from camera, microphone and screen-share tracks: `usePeers` groups each peer's tracks by type and exposes custom tracks in the `customVideoTracks` and `customAudioTracks` arrays.
## The publish lifecycle
`setStream` is asynchronous and connection-aware:
- Tracks are added to the session only while the peer is connected. A stream set before joining is stored as pending and published on connect.
- On disconnect, sources return to pending; after a reconnect they are re-published automatically.
- Calls to `setStream` are serialized: replacing one stream with another in quick succession cannot interleave, and a failed call does not affect subsequent ones.
- `setStream(null)` unpublishes and forgets the source. The tracks themselves are not stopped; the producer of the stream owns them.
## The React Native media pipelines
On the web, the browser can produce a `MediaStream` from a canvas, a media element or Web Audio, so the base hook is all you need. React Native has no such general facility, so the SDK provides its own pipelines, built into `@fishjam-cloud/react-native-webrtc`: custom video tracks fed with frames, and custom audio tracks fed with PCM samples.
### The video frame pipeline
```mermaid
flowchart LR
frames["Your frames(native buffers orrendered surfaces)"] --> track["Custom video track(react-native-webrtc)"]
track --> stream["MediaStream"]
stream --> hook["useCustomSource"]
hook --> room["Fishjam room"]
room --> peers["Other peerscustomVideoTracks"]
```
A **custom video track** looks like any other WebRTC video track to the rest of the stack, but its frames are supplied by your code through one of two modes:
- **Forwarding**: you already have finished frames as native buffers (`CVPixelBufferRef` on iOS, `AHardwareBuffer*` on Android). `forwardFrame` passes the buffer pointer to the track; the SDK retains the buffer for as long as encoding needs it, so you can release your reference immediately.
- **Render target (pooled)**: you draw the frames yourself. The SDK allocates a small pool of GPU-shareable surfaces (IOSurfaces on iOS, AHardwareBuffers on Android); you import a surface into your GPU once, render into it, and return it with `pushFrame`. A pool of about 3 surfaces keeps drawing and encoding overlapped: one surface can be encoding while the next is being drawn.
Both paths are zero-copy: pixels stay in the same native memory from your producer to the video encoder, and only a pointer moves.
The pipeline also handles:
- **GPU synchronization.** With asynchronous renderers, a pushed surface may not be fully drawn when the encoder reads it. `pushFrame` accepts a _fence_ (an `MTLSharedEvent` on iOS, a sync file descriptor on Android) so the encoder waits for your GPU work. The WebGPU hooks manage this automatically.
- **One timestamp domain.** Encoders require monotonically increasing timestamps. Forwarded frames without timestamps are stamped from the native monotonic clock, and the VisionCamera adapter normalizes VisionCamera's per-platform timestamp units onto one zero-based nanosecond timeline.
- **Worklet-friendly handles.** Track handles are plain, worklet-serializable objects, so frames can be pushed straight from a frame-processor worklet without hopping through the JS thread. This synchronous JSI handoff is also why custom video tracks require the New Architecture.
### The audio pipeline
A **custom audio track** takes raw PCM through `pushAudioSamples`, in any chunk size, from the JS thread or a worklet. The [`useCustomAudioSource`](../how-to/client/custom-sources/react-native.mdx#publish-custom-audio) hook wraps the underlying `createCustomAudioTrack` and registers the resulting stream through `useCustomSource`, so audio follows the same source-ID contract and publish lifecycle as every other custom source.
The native layer re-paces pushes into the continuous real-time frame stream the encoder expects and inserts silence when the buffer runs dry, so the track behaves like a live microphone: pauses in pushing are fine and the stream never ends. Pushed-but-not-yet-sent audio is buffered up to a configurable duration (one minute by default) and drains in real time. Like the video handles, the audio track handle is worklet-serializable and its push channel is a synchronous JSI binding, which is why custom audio tracks also require the New Architecture.
## Platform foundations
- **iOS**: video surfaces are IOSurface-backed, BGRA8 (`bgra8unorm` as a render target). The WebGPU camera import relies on Metal external-texture features that are only guaranteed on iOS 17+; publishing frames without WebGPU has no such requirement.
- **Android**: video surfaces are `AHardwareBuffer`s, RGBA8 (`rgba8unorm`). The camera arrives as an opaque YCbCr buffer, so the WebGPU toolkit's `sampleCamera` performs the BT.709 limited-range YUV→RGB conversion in-shader.
## Where to go next
- [Custom sources how-to guides](../how-to/client/custom-sources/index.mdx): publish from the web, React Native, or your own pipeline
- [How camera effects work](./camera-effects.mdx): effects on Fishjam's own camera
- [VisionCamera integration](../integrations/vision-camera/vision-camera-source.mdx): publish a VisionCamera feed
- API reference: [`useCustomSource` (Web)](../api/web/functions/useCustomSource), [`useCustomSource` (React Native)](../api/mobile/functions/useCustomSource), [`useCustomAudioSource` (React Native)](../api/mobile/functions/useCustomAudioSource), [Vision Camera Source package](../api/vision-camera-source/index), [Custom Video Source package](../api/custom-video-source/index)
---
## Data Channels
Data channels allow you to send and receive arbitrary binary data between peers in a room. This is useful for implementing features like text chat, file sharing, game state synchronization, or real-time cursor positions.
## Prerequisites
Before using data channels, you must be [connected to a room](../how-to/client/connecting). Data channels only work after you have successfully joined a room.
## Channel Types
The SDK provides two types of data channels, each optimized for different use cases:
### Reliable Channel
- **Ordered delivery**: Messages arrive in the order they were sent
- **Guaranteed delivery**: All messages will be delivered, with automatic retransmission if needed
- **Use cases**: Chat messages, file transfers, commands, or any data that must not be lost
### Lossy Channel
- **Unordered delivery**: Messages may arrive out of order
- **No retransmission**: Messages may be dropped if the network is congested
- **Lower latency**: Faster delivery since there's no waiting for retransmissions
- **Use cases**: Real-time cursor positions, game state updates, live sensor data, or any data where the latest value matters more than every value
## Broadcast Communication
Data channels work in a **broadcast fashion** - when you publish data, it is sent to all other peers in the room. Additionally:
- Messages sent on the **reliable channel** are only received by peers subscribed to the **reliable channel**
- Messages sent on the **lossy channel** are only received by peers subscribed to the **lossy channel**
This separation allows you to use both channels simultaneously for different purposes without interference.
## Using Data Channels
Use the `useDataChannel` hook to work with data channels. The hook is available in both the web and mobile SDKs with the same API:
Use [`useDataChannel`](../api/web/functions/useDataChannel) from `@fishjam-cloud/react-client`.
Use [`useDataChannel`](../api/mobile/functions/useDataChannel) from `@fishjam-cloud/react-native-client`.
The typical flow is:
1. Initialize the data channel after connecting to a room
2. Subscribe to incoming messages
3. Publish messages to other peers
For a complete step-by-step guide on implementing text chat, see [Text Chat](../how-to/client/text-chat).
---
## Glossary
A brief walk-through of the terms we use in the documentation.
### Room
A collection of peers that can send and receive video/audio to and from other peers.
### Peer
A user that is connected to a room. Each peer has some associated metadata and tracks.
### Agent
A program connected to a room using the Fishjam server SDK; a programmatic peer.
### Track
A single stream of video or audio from a peer. It could be a camera view, shared screen, or microphone audio. Each peer can stream multiple tracks.
### Management Token
A secret token that should be stored on your backend. It allows you to create rooms and add peers.
### Peer Token
A token that your backend should pass to end clients to allow access to a specific room.
### Fishjam ID
The ID of your Fishjam instance. It is used by your backend server to add peers to rooms (and create rooms). It is also used by end client apps to join rooms.
### Sandbox API
A simple testing API allowing you to test Fishjam features without requiring you to add any functionalities to your backend. It is intended for development and testing only, not for production use. You can find more details [here](/how-to/backend/sandbox-api-testing).
---
## Livestreams
:::info
This explanation only applies to Fishjam rooms with type `livestream`.
:::
When livestreaming with Fishjam, you can chose to make your livestream `private` or `public`.
By default, created livestreams are `private`, to prevent possible bugs.
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const privateRoom = await fishjamClient.createRoom({ roomType: 'livestream' }); // [!code highlight]
const publicRoom = await fishjamClient.createRoom({ roomType: 'livestream', public: true }); // [!code highlight]
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
private_room = fishjam_client.create_room(RoomOptions(room_type="livestream")) # [!code highlight]
public_room = fishjam_client.create_room(RoomOptions(room_type="livestream", public=True)) # [!code highlight]
```
The choice you make affects how **viewers** connect to the livestream and has no effect on streamers.
## Private livestreams
When you create a private livestream, viewers are required to provide a viewer token when connecting to the livestream.
This aims to provide control over who can view a livestream, but requires you to distribute tokens from your backend application to your frontend applications.
### Creating a viewer token
Below we show how you would create a livestream viewer token in a production scenario, with your own backend.
Note that for development purposes, you can [use the Sandbox API to generate a viewer token](../tutorials/livestreaming#obtaining-a-token-1).
```ts
const fishjamId = '';
const managementToken = '';
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId,
managementToken,
});
const privateRoom = await fishjamClient.createRoom({ roomType: 'livestream' });
const { token: viewerToken } = await fishjamClient.createLivestreamViewerToken(privateRoom.id); // [!code highlight]
```
```python
from fishjam import FishjamClient, RoomOptions
fishjam_client = FishjamClient(
fishjam_id=fishjam_id,
management_token=management_token,
)
private_room = fishjam_client.create_room(RoomOptions(room_type="livestream"))
viewer_token = fishjam_client.create_livestream_viewer_token(private_room.id) # [!code highlight]
```
### Connecting to a private room
Once you've created a viewer token, you can connect to a room using the Fishjam client SDKs (examples below), or alternatively you can use [WHEP](../how-to/backend/whip-whep#private-livestreams).
```tsx
const viewerToken = '';
// ---cut---
// ...
const { connect, stream } = useLivestreamViewer();
// ...
await connect({ token: viewerToken });
// after connecting stream will be available
```
```tsx
const viewerToken = '';
// ---cut---
// Inside your component:
const { connect, stream } = useLivestreamViewer();
// ...
await connect({ token: viewerToken });
// Render the stream
{stream && (
)}
```
## Public livestreams
Public livestreams simplify the viewing process by omitting the viewer token.
All a viewer needs to view a public livestream is the ID of the room, so your backend doesn't need to manage the creation and distribution of viewer tokens.
Note however, that public livestreams are _not suitable for all use-cases_.
For example, if you are developing an app, which includes exclusive live content that requires a subscription to view, then you will want to authorize viewers before allowing them to view a livestream.
Failing to do so may result in extra costs, as livestreams are billed per-viewer.
Such an application will benefit from the token-based authorization in [private livestreams](#private-livestreams).
### Connecting to a public room
Once you've created a room of type `livestream` with the `public` flag enabled, you may start connecting viewers to the stream via the Fishjam client SDKs or [WHEP](../how-to/backend/whip-whep#public-livestreams).
```tsx
const roomId = '';
// ---cut---
// ...
const { connect, stream } = useLivestreamViewer();
// ...
await connect({ streamId: roomId });
// after connecting `stream` will be available
```
```tsx
const roomId = '';
// ---cut---
// Inside your component:
const { connect, stream } = useLivestreamViewer();
// ...
await connect({ streamId: roomId });
// Render the stream
{stream && (
)}
```
---
## Media over QUIC in Fishjam
_How Media over QUIC (MoQ) works in Fishjam_
:::warning[MoQ is a standalone feature]
MoQ runs as a **separate delivery path** in Fishjam — it handles publishing and subscribing to a live broadcast over the MoQ relay, and the rest of Fishjam's feature set does not apply to a MoQ stream. In particular, a MoQ broadcast is not part of a WebRTC [room](./rooms), so you cannot use features like [Agents](../tutorials/agents), [data channels](./data-channels), and others that are part of the Fishjam WebRTC ecosystem.
What MoQ supports is covered end to end in the [MoQ tutorials](../tutorials/moq/web-publishing).
:::
## What is MoQ?
[Media over QUIC (MoQ)](https://datatracker.ietf.org/wg/moq/about/) is a new internet standard for live media delivery, designed from the ground up for **scalable, low-latency streaming to large audiences**.
Unlike WebRTC — which was primarily built for interactive, peer-to-peer conferencing — MoQ is optimized for the one-to-many broadcast model: one publisher, potentially thousands of simultaneous subscribers, all receiving the stream with minimal delay.
A few properties make MoQ stand out:
- **Built on QUIC.** QUIC is a modern transport protocol that eliminates head-of-line blocking, recovers from packet loss more gracefully than TCP, and establishes connections faster. For live video, this means more resilient delivery at low latency.
- **Standardized negotiation.** Because MoQ defines a common signaling and subscription protocol, any MoQ-compliant client can connect to any MoQ-compliant relay — you are not locked into a proprietary stack.
- **Relay-based architecture.** The relay is a first-class part of the MoQ protocol, not an add-on. Because relaying is built into the protocol's design, scaling delivery to large audiences is a native capability.
:::info
Fishjam also supports WebRTC-based livestreaming (WHIP/WHEP). See [Livestreams](./livestreams) for that approach.
:::
## How MoQ Works in Fishjam
Fishjam provides a **MoQ relay** that publishers push media to and subscribers pull media from.
```
Publisher → Fishjam MoQ Relay → Subscriber(s)
```
The relay is responsible for distributing the stream: it receives media from the publisher once and fans it out to every subscriber.
### The publish/subscribe model
MoQ uses a **publish/subscribe** model:
- A **publisher** connects to the relay, announces a stream under a specific path, and starts sending media.
- **Subscribers** connect to the relay, discover announced paths, and receive the media.
The relay manages the flow between them. Neither side needs a direct connection to the other.
### Paths
Every stream is identified by a **path** — a slash-separated string like `my-room/alice-camera`. Paths are used in two distinct ways:
1. **Addressing** — a subscriber consumes an exact path to receive that specific stream (e.g. `my-room/alice-camera`).
2. **Discovery** — a subscriber watches a prefix (e.g. `my-room`) to learn which streams are currently live under it. This returns a live feed of announced paths — each of which must then be consumed individually. This is how you can display all participants in a room without knowing their paths in advance.
Note that consuming an exact path and discovering a prefix are separate operations. Consuming `my-room` directly would fail unless a publisher is broadcasting at that exact path.
### Path Scoping
Every connection goes to `relay.fishjam.io/`. Your Fishjam ID is automatically used as the token's root namespace by the Fishjam Server — you never include it in `publishPath` or `subscribePath`; it is set for you. All paths you specify are **relative to that root**.
Path matching is **prefix-based**: a path of `"stream-name"` permits any broadcast whose full path starts with `stream-name/`, not just the exact string `"stream-name"`.
#### Publisher paths
The `publishPath` you set determines how much freedom the broadcaster has when naming their broadcast:
- **Broad path** (`publishPath: "stream-name"`) — the client can publish as any sub-path under `stream-name`, such as `stream-name/alice` or `stream-name/bob-camera`. The client chooses its own identity; the relay only enforces the prefix.
- **Specific path** (`publishPath: "stream-name/alice"`) — the client can **only** publish as `stream-name/alice`. If the broadcaster tries to use `stream-name/bob`, the relay rejects the announcement. This is how you enforce a broadcaster's identity from the server side.
Use the broad form when clients self-identify (e.g., users pick their own stream name). Use the specific form when your backend assigns identities (e.g., you issue a per-user token for a managed conference).
#### Subscriber paths
The `subscribePath` works the same way: it is a prefix that limits which broadcasts the subscriber can consume and discover.
- **Broad path** (`subscribePath: "stream-name"`) — the subscriber can consume any broadcast under `stream-name/` and will surface all publishers in that namespace as they come and go.
- **Specific path** (`subscribePath: "stream-name/alice"`) — the subscriber can only receive from `stream-name/alice`. Broadcasts at `stream-name/bob` are invisible to this client.
#### Example: a multi-publisher room
A typical room setup uses a combination of both patterns:
1. The backend issues each broadcaster a **specific** publisher token — `publishPath: "my-room/"` — so each user can only occupy their own slot.
2. The backend issues viewers a **broad** subscriber token — `subscribePath: "my-room"` — so they discover and consume every broadcast in the room.
3. When a new publisher joins or leaves, the viewer is informed by the relay
## Access Control: MoQ Tokens
Access to the relay is controlled by **MoQ tokens** — short-lived JWTs that are path-scoped:
| Token type | Grants | Typical recipient |
| ---------------- | ---------------------------------- | ----------------- |
| Publisher token | Write access to a specific path | Streamer |
| Subscriber token | Read access to a path or namespace | Viewer |
A token is attached to the relay URL as a query parameter (`?jwt=`). The relay validates the token and enforces its scope before allowing any media to flow. Both the Sandbox API and the Server SDK hand you the authenticated **connection URL** (the relay URL with the token already embedded), so the client can just take it as is and connect.
Keeping publisher and subscriber tokens separate ensures that a viewer can never accidentally publish to the stream, and a publisher cannot subscribe to paths it does not own.
## Where to get the Connection URL from?
There are two ways to obtain a MoQ connection URL, depending on where you are in the development lifecycle.
### Sandbox API (prototyping)
The **Sandbox API** is a ready-made backend provided by Fishjam for development and prototyping. It issues connection URLs without requiring you to build your own server, so you can start streaming immediately.
To get a publisher connection URL, call:
```
GET https://fishjam.io/api/v1/connect/{FISHJAM_ID}/room-manager/moq/{PUBLISHER-PATH}/publisher
```
To get a subscriber connection URL, call:
```
GET https://fishjam.io/api/v1/connect/{FISHJAM_ID}/room-manager/moq/{SUBSCRIBER-PATH}/subscriber
```
To get a full-access connection URL — one that can both publish to and subscribe on the path — call:
```
GET https://fishjam.io/api/v1/connect/{FISHJAM_ID}/room-manager/moq/{PATH}/full-access
```
Each returns a JSON object with a `connection_url` field — the relay URL with the JWT embedded as `?jwt=` — alongside the raw `token`.
The Sandbox API is **not intended for production** — it has no authentication and is only available in the Sandbox environment. See [What is the Sandbox API?](./sandbox-api-concept) for more context.
### Fishjam Server SDK (production)
In production, your backend generates connection URLs using the **Fishjam Server SDK**. This gives you full control over who can publish and who can subscribe.
The SDK's `createMoqAccess` method accepts a `publishPath`, a `subscribePath`, or both, and returns the MoQ access details — a `connection_url` (the relay URL with the JWT embedded) alongside the raw `token`:
- `publishPath` — returns a publisher connection URL scoped to that path.
- `subscribePath` — returns a subscriber connection URL scoped to that path or namespace prefix.
- both `publishPath` and `subscribePath` — returns a full-access connection URL that can publish and subscribe on those paths.
Your backend then delivers each connection URL to the appropriate client (publisher or viewer), which uses it to connect to the relay.
See the [Web Publishing](../tutorials/moq/web-publishing) and [Web Subscribing](../tutorials/moq/web-subscribing) tutorials (or their [React Native](../tutorials/moq/react-native-publishing) [counterparts](../tutorials/moq/react-native-subscribing)) for working code examples.
## See also
- [Web Publishing](../tutorials/moq/web-publishing) / [Web Subscribing](../tutorials/moq/web-subscribing) — step-by-step guides to publishing and subscribing
- [What is the Sandbox API?](./sandbox-api-concept) — when and why to use the Sandbox API
- [Security & Token Model](./security-tokens) — broader overview of Fishjam's token system
- [Livestreams](./livestreams) — WebRTC-based livestreaming with WHIP/WHEP
---
## Recordings
_Understanding how Fishjam captures composed media as files_
A **recording** captures media rendered inside a [composition](./compositions) and stores it as an MP4 file. A composition is a live process: it produces media while it runs and leaves nothing behind once it is deleted. A recording is the persistent artifact of that process. It remains available after the composition, and any room forwarded into it, are gone, and Fishjam keeps it for [3 months](#retention).
What a recording captures is set by its **source**. There are two kinds:
- A **template recording** renders its own scene from a React template. It is not bound to any output or live stream, and the recording is the only thing it produces. This is the default way to record.
- A **composition recording** mirrors an output that the composition already publishes, such as the one feeding a livestream. Use it to keep a copy of a live stream you are already running.
## Template recordings
```mermaid
flowchart LR
Inputs[inputs] --> Composition[composition]
Composition -- template --> Recording[recording]
Recording --> MP4[MP4]
MP4 --> Download[download]
```
A template recording still runs inside a composition. The composition is the workspace that holds your inputs, whether you register them yourself or forward a Fishjam room into it. The template decides how those inputs are rendered into the file, and nothing is published live: no output is registered and no livestream is needed.
The template is the same kind of React component as the [template of an output](./../how-to/compositions/write-and-deploy-a-template). You upload its bundle, at most 1 MiB, together with the request that creates the recording.
Besides the composition URL, a template recording accepts two options: `resolution`, the size the template is rendered at (1280x720 by default), and `audio`, which can be set to `false` for a video-only file. A composition can run several template recordings at once, each with its own template.
## Composition recordings
```mermaid
flowchart LR
Inputs[inputs] --> Composition[composition]
Composition --> Output[output]
Output --> Livestream[livestream / RTMP]
Livestream --> Viewers[viewers]
Output --> Recording[recording]
Recording --> MP4[MP4]
MP4 --> Download[download]
```
A composition produces media through its outputs, and a composition recording captures one of them. To create one, you specify a composition and one of its registered outputs, and Fishjam attaches a recorder to that output. The recorder captures the output as it is published: the same layout, including every scene update, at the output's resolution unless `scaleRatio` changes it, encoded separately from the live stream. If the recorded file should differ from the live stream, use a template recording instead.
Besides composition URL and output ID, a composition recording accepts a single option, `scaleRatio`, which sets the recording resolution as a fraction or multiple of the output's resolution. For example, `0.5` stores the recording at half the output resolution.
An output can have at most one recording at a time. To record the same output again, wait until the current recording is no longer `active`.
## Composition API and Server API
Compositions are managed through the [Composition API](./../api/reference#compositions), while recordings are created and managed through the [Fishjam Server API](./../api/reference#server), either directly or with the JS and Python server SDKs. This split reflects ownership: a composition is a running session that you configure, whereas a recording is a resource of your Fishjam app, stored alongside your rooms and livestreams and managed with the same management token. You do not call the Composition API to record; the Server API controls the capture inside the composition on your behalf, including loading the template of a template recording.
## Lifecycle
A recording has four statuses:
| Status | Meaning |
| ----------- | ------------------------------------------------------- |
| `active` | Media is being captured. |
| `finished` | Capture has ended and the file is being prepared. |
| `available` | The MP4 is ready and `files` contains the download URL. |
| `failed` | An error occurred and no file will be produced. |
Capture starts as soon as the recording is created. It ends when you stop the recording explicitly, or automatically when its composition ends: when you delete the composition, or when it [cleans itself up](./compositions#cost-and-lifecycle) after five minutes without input media. A composition recording also ends when the recorded output ends. Finalization is asynchronous: the recording remains `active` until capture has ended, then transitions through `finished` to `available` once the file is ready.
Every status change emits a `RecordingStatusChanged` [server notification](./../api/reference#protobufs) over your configured webhook or a websocket, so you can react to a file becoming available without polling.
Once a recording is `available`, its `files` field lists the media files in playback order as direct HTTPS URLs that you can download or serve to your users. To remove a recording and its files before they expire, delete the recording. A recording cannot be deleted while it is `active`.
## Retention
Fishjam keeps a recording and its files for 3 months after the recording is created. After that they are no longer available through the API, so download any file you need to keep for longer. For up to 6 months after creation, an expired recording can still be retrieved on request: contact us at `contact@fishjam.io`.
## Metadata
A recording carries optional free-form `metadata`, set at creation and returned with every read. Because recordings accumulate over time, metadata also serves as the primary way to locate them: listing recordings supports filtering by metadata pairs, for example to retrieve every recording for a given show or customer.
## Where to go next
- [Record with a template](./../how-to/recordings/record-with-a-template): render a template straight into an MP4.
- [Record a composition output](./../how-to/recordings/record-a-composition-output): mirror an output you already publish.
- [Manage recordings](./../how-to/recordings/manage-recordings): stop, download, list, and delete recordings.
- [Compositions](./compositions): the sessions recordings run in.
- [Server REST API](/api/rest): the complete request and response schemas.
---
## Rooms
_Understanding different types of rooms and when to use them_
Fishjam provides three distinct room types, each optimized for different use cases and scenarios.
Understanding these room types helps you choose the right approach for your application.
## Conference Rooms (Default)
### What are Conference Rooms?
Conference rooms are the default room type designed for multi-participant video conferencing scenarios. They support all Fishjam features and provide the most flexibility.
### Key Characteristics
- **Multi-participant**: Support for many participants simultaneously
- **Bidirectional media**: All participants can send and receive video/audio
- **Multiple sources**: Participants can share their camera, screen, microphone and more all at once
- **Flexible track management**: Participants can add/remove tracks dynamically
### Best Use Cases
- **Video conferencing applications**
- **Interactive webinars** with participant engagement
### Cost Considerations
Conference rooms are priced based on total connection time of all peers.
## Audio-only Rooms
### What are Audio-only Rooms?
Audio-only rooms are optimized specifically for voice communication, removing video capabilities to improve performance and reduce costs.
### Key Characteristics
- **Voice-only communication**: No video tracks allowed
- **Cheap pricing**: Audio only rooms cost much less than other room types
- **Optimized network usage**: Works well in degraded network conditions
### Best Use Cases
- **Audio chat applications**
- **Podcast recording** with multiple participants
- **Large-scale audio events** (town halls, announcements)
### Cost Benefits
Audio-only rooms come at a **75% discount** compared to conference rooms:
- 2 peers for 30 minutes = 60 minutes total time in conference room
- Same scenario in audio-only room = 15 minutes equivalent cost
### Video Behavior in Audio-only Rooms
If you attempt to add video to an audio-only room:
- Video tracks are ignored (not transmitted)
- SDKs log warnings to help with debugging
- Only audio from screen sharing is transmitted
- No errors thrown, graceful degradation
## Livestream Rooms
### What are Livestream Rooms?
Livestream rooms are designed for one-to-many livestreaming scenarios where a single streamer streams to multiple viewers.
### Key Characteristics
- **One sender**: Only one streamer can send media
- **Many receivers**: Unlimited viewers can watch
- **Optimized for scale**: Efficient distribution architecture
### Livestreaming Limitations
- **Single video track**: Only one video stream allowed
- **Single audio track**: Only one audio stream allowed
- **Additional tracks ignored**: Extra tracks are not forwarded to viewers
### Viewer Experience
- **Configurable access**: Livestreams can either be public, where anyone with the stream's ID can join, or private, where every viewer needs a token
- **Standard compatibility**: Any [WHEP](https://blog.swmansion.com/building-interactive-streaming-apps-webrtc-whip-whep-explained-d38f4825ec90)-compatible player works
### Best Use Cases
- **Live events**
- **Streaming platforms** and content distribution
- **Corporate livestreams** and announcements
- **Sports and entertainment** streaming
### Cost Benefits
Livestream rooms are **20% cheaper** than conference rooms for equivalent usage.
## Choosing the Right Room Type
### Decision Matrix
| Use Case | Room Type | Why |
| ---------------------- | ---------- | ------------------------------------------- |
| Classic video meetings | Conference | Multiple video sources |
| Voice-only meetings | Audio-only | Cheapest and most performant option |
| Live Podcasts | Audio-only | Cheapest and most performant option |
| Sport streaming | Livestream | Highly scalable and cheaper than conference |
| Interactive workshop | Conference | Multiple video sources |
## Video Codecs
Fishjam supports the following video codecs:
- **H.264** — A hardware-accelerated codec offering superior performance. Used by default. Its availability varies by device, and it may not perform optimally at lower bitrates.
- **VP8** — A software-based codec supported across all devices, ensuring maximum compatibility. Ideal for environments lacking hardware acceleration, such as Android emulators.
Fishjam uses H.264 by default. To solve an issue with Android emulators, the Sandbox API uses VP8 unless you pass the `videoCodec` query parameter (`vp8` or `h264`). Use H.264 if you want to [compose a room](../how-to/compositions/compose-a-fishjam-room) created with the Sandbox API.
You can override the default codec by setting the `videoCodec` parameter when [creating a room](../api/server/interfaces/RoomConfig#videocodec) using server SDKs.
We recommend using H.264 for production and VP8 for development as it works with Android emulators.
## Next Steps
To understand how to use each room type:
- [How to implement livestreaming](../tutorials/livestreaming)
- [How to create audio-only calls](../how-to/backend/audio-only-calls)
To learn about the underlying architecture:
- [Fishjam Architecture](../explanation/architecture)
- [Security & Token Model](../explanation/security-tokens)
Ready to start building? Check our tutorials:
- [React Native Quick Start](../tutorials/react-native-quick-start)
- [Backend Quick Start](../tutorials/backend-quick-start)
---
## What is the Sandbox API?
The Sandbox API is a development tool that simplifies getting started with Fishjam by providing a simple backend for testing, eliminating the need to build your own server initially.
## What can the Sandbox API do?
The Sandbox API is an HTTP server provided by us for development and testing.
It provides basic room creation and peer management functionality without requiring you to set up your own backend infrastructure.
### Key Characteristics
- **Development-purposed**: Designed for initial development and testing
- **No authentication**: Simplified access for quick prototyping
- **Testing-only**: Not intended for production use; use your own authenticated backend for production
## Sandbox API URL and Fishjam ID
You can find your sandbox credentials in the [Sandbox tab](https://fishjam.io/app/sandbox) of the Fishjam Dashboard.
The **Sandbox API** is a hosted HTTP backend you can use to test Fishjam without writing your own server. It creates [**rooms**](../explanation/rooms) and **peers** for conferencing, and supports [**livestreaming**](../explanation/livestreams) by issuing the streamer and viewer credentials. It's an example implementation of what you need to build using our [**JavaScript server SDK**](../api/server) to go to production.
You can use your sandbox credentials by passing them to the `useSandbox` hook in the client SDK, which will create rooms and peer tokens for you, or by calling the Sandbox API URL directly from your client and using the returned `peerToken` to connect to Fishjam.
The **Fishjam ID** from the [Dashboard tab](https://fishjam.io/app) is passed to `FishjamProvider` so the client can connect to the Fishjam media server after it gets a peer token.
If your Sandbox API URL is exposed or your credentials are compromised, generate a new URL from the Sandbox tab to invalidate the old one. You can also disable the Sandbox API and enable it again when you want to resume sandbox testing.
If you expose your Sandbox API URL in a public deployment, it can leak (for example through client code or network requests). Anyone who obtains that URL can create rooms and peers on your behalf.
## The Problem Sandbox API Solves
When starting with videoconferencing or livestreaming development, you typically need:
1. A **Backend server** to create rooms
2. An **Authentication system** to manage users
3. **Token management** for secure peer access
4. **API endpoints** for your frontend to call
This creates a problem: to test your frontend, you need a backend, but during prototyping you want to focus on frontend development first.
The Sandbox API mitigates this issue and allows you to start frontend development ASAP.
## Relationship to Server SDKs
The Sandbox API is essentially a simplified application built using the Fishjam Server SDKs:
```typescript
const fishjamId = "";
const managementToken = "";
const app = express();
// ---cut---
// What Sandbox API does internally (simplified)
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
app.get("/", async (req: express.Request, res: express.Response) => {
const { roomName, peerName, roomType } = req.query;
// Create or get room
const room = await fishjamClient.createRoom({
roomType: roomType as RoomType,
});
// Create or get peer
const { peer, peerToken } = await fishjamClient.createPeer(room.id);
res.json({ peerToken });
});
```
This shows you exactly what your production backend needs to do, just with proper authentication and error handling.
## See also
To understand how to use The Sandbox API for development:
- [How to use The Sandbox API for testing](../how-to/backend/sandbox-api-testing)
To learn about building your own backend:
- [Backend Quick Start Tutorial](../tutorials/backend-quick-start)
- [How to set up your server](../how-to/backend/server-setup)
To understand the security model:
- [Security & Token Model](../explanation/security-tokens)
---
## Security & Token Model
_Understanding Fishjam's security architecture and token system_
Fishjam uses a token-based security model to ensure secure access control while keeping the developer experience simple.
## Security Architecture Overview
Fishjam's security is built on a **two-tier token system**:
1. **Management Tokens**: For backend-to-Fishjam server communication
2. **Peer Tokens**: For client-to-Fishjam server communication
This separation ensures that sensitive operations remain on your backend while allowing clients secure, limited access to media streaming.
## Management Tokens
### Purpose
Management tokens provide your backend server with administrative access to Fishjam resources. They allow creating, managing, and deleting rooms and peers.
### Characteristics
- **Long-lived**: Management tokens remain valid until manually regenerated
- **High privilege**: Management tokens allow performing administrative operations and should only be used in backend applications.
- **Backend-only**: Management tokens should never be sent to client applications.
### What Management Tokens Can Do
Management tokens give permission to:
- Create and manage rooms and peers
- Setup [webhooks](../how-to/backend/server-setup#webhooks)
- Set [immutable peer metadata](../how-to/backend/server-setup#metadata)
## Peer Tokens
### Purpose
Peer tokens provide client applications with limited, time-bound access to join a specific room as a specific peer.
### Characteristics
- **Short-lived**: Peer tokens expire 24h after creation.
- **Scope-limited**: Peer tokens give access to one specific room as one specific peer only.
- **Client-safe**: Peer tokens are safe to send to frontend applications.
### What Peer Tokens Can Do
Peer tokens give permission to:
- Connect to the specific room they were issued for
- Participate in room activities (audio/video/screen sharing)
- Access peer metadata and room state
### What Peer Tokens Cannot Do
- Create or delete rooms
- Access multiple rooms
- Add or remove peers
### Generation Process
```typescript
const res = {} as any;
const managementToken = "";
const fishjamId = "";
const roomId = "" as unknown as RoomId;
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
// ---cut---
// Backend generates peer token (using management token)
const { peer, peerToken } = await fishjamClient.createPeer(roomId, {
metadata: { name: "John Doe", userId: "user-123" },
});
// Backend sends peer token to client
res.json({
peerToken, // Client uses this to connect
roomId, // Room information
});
```
### Client Usage
```typescript
const joinRoom = {} as any;
const peerToken = "";
// ---cut---
// Client uses peer token to connect (safe to use in frontend)
await joinRoom({ peerToken }); // This is safe in client code
```
## Next Steps
To implement secure authentication:
- [Backend Quick Start Tutorial](../tutorials/backend-quick-start)
- [How to set up your server](../how-to/backend/server-setup)
To understand the broader architecture:
- [Fishjam Architecture](../explanation/architecture)
To learn about the Sandbox API's security limitations:
- [Understanding the Sandbox API](../explanation/sandbox-api-concept)
---
## Simulcast(Explanation)
_Multi-quality video streaming for adaptive bandwidth and layout-aware rendering_
Simulcast allows a video sender to encode and transmit the same video at multiple quality levels (variants) simultaneously. Each receiver independently chooses which variant to receive, enabling adaptive quality based on network conditions, UI layout, or user preference.
## Why Simulcast?
Without simulcast, every receiver gets the same video quality. This creates a trade-off: receive high quality (wastes bandwidth for small thumbnails) or receive low quality (degrades the experience for full-screen viewers).
Simulcast solves this on the receiver side -- a sender publishes multiple variants, and each receiver requests only the quality it needs. The trade-off is increased upload bandwidth on the sender, since it encodes and transmits multiple variants simultaneously. If this overhead is not acceptable, the sender can [choose which variants to publish](#sender-configuration) or disable simulcast entirely.
- A **thumbnail grid** can request low quality for all participants
- A **spotlight view** can request high quality for the active speaker and low for everyone else
- A participant on a **slow connection** can request medium quality regardless of UI layout
## Quality Variants
Three predefined quality tiers are available via the `Variant` enum:
| Variant | Meaning |
| ------------------------ | --------------------------- |
| `Variant.VARIANT_LOW` | Low quality / resolution |
| `Variant.VARIANT_MEDIUM` | Medium quality / resolution |
| `Variant.VARIANT_HIGH` | High quality / resolution |
## How It Works
```mermaid
sequenceDiagram
participant Sender
participant Server as Fishjam Server
participant ReceiverA as Receiver A (thumbnail)
participant ReceiverB as Receiver B (full-screen)
Sender->>Server: Video (LOW + MEDIUM + HIGH)
ReceiverA->>Server: setReceivedQuality(LOW)
Server->>ReceiverA: Forwards LOW variant
ReceiverB->>Server: setReceivedQuality(HIGH)
Server->>ReceiverB: Forwards HIGH variant
```
1. The **sender** encodes the camera feed into up to three variants and sends all of them to the Fishjam server.
2. The **server** receives all variants but only forwards the one each receiver has requested.
3. Each **receiver** calls `setReceivedQuality` on a remote track to tell the server which variant it wants. The receiver can change this at any time.
## Sender Configuration
The sender controls which variants to publish via the `sentQualities` option in `FishjamProvider`'s `videoConfig`:
- **All variants** (default): Omit `sentQualities` or pass `[Variant.VARIANT_LOW, Variant.VARIANT_MEDIUM, Variant.VARIANT_HIGH]`
- **Subset**: Pass only the variants you need, e.g. `[Variant.VARIANT_LOW, Variant.VARIANT_HIGH]`
- **Disabled**: Pass `false` to send a single quality stream (no simulcast)
## Receiver Quality Selection
Remote tracks expose a `setReceivedQuality` method. This is only available on **remote** peer tracks. Your own local tracks don't have it, since you don't "receive" your own video.
The `RemoteTrack` type (exported from both `@fishjam-cloud/react-client` and `@fishjam-cloud/react-native-client`) extends the base `Track` type with a `setReceivedQuality(quality: Variant)` method.
When you call `setReceivedQuality`, the server switches which variant it forwards for that track. The change takes effect almost immediately.
## When to Use Simulcast
Simulcast is most valuable when:
- Your app has **multiple layout modes** (grid, spotlight, picture-in-picture)
- Participants have **varying network conditions**
- You want to **reduce bandwidth** for participants viewing many small thumbnails
- You're building **adaptive quality** that responds to UI state
For simple 1:1 calls where both sides always show full-screen video, simulcast adds encoding overhead without much benefit. Consider disabling it with `sentQualities: false`.
## See also
- [Simulcast how-to guide](../how-to/client/simulcast): step-by-step implementation
- [Architecture](./architecture): how Fishjam routes media
---
## What is Fishjam?
_Understanding the role and purpose of Fishjam_
Fishjam is a multimedia streaming toolkit that allows you to build real-time video and audio streaming applications.
It uses [WebRTC](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API) under the hood to ensure sub-second (in most cases **less than 300ms**) latency.
We provide the infrastructure, media server, and client SDKs so you can focus on building your apps.
**No WebRTC knowledge is required!**
## The Problem Fishjam Solves
Building real-time video and audio applications is complex. Developers typically need to:
- Set up and manage WebRTC infrastructure
- Handle complex peer-to-peer networking
- Manage media servers and scaling
- Deal with different devices and codec compatibility
- Implement secure token-based authentication
Fishjam abstracts away this complexity, providing a simple API and managed infrastructure.
## What Fishjam Provides
Fishjam consists of several components that work together to provide a seamless multimedia streaming experience:
| Component | Description |
| --------------------- | ------------------------------------------------------------------------------------------------------- |
| Developer panel | The place to access your credentials and manage your Fishjam usage. |
| Fishjam Media Servers | Media servers route your multimedia traffic. We host and manage them for you. |
| Fishjam Client SDKs | Toolkit used for multimedia integration on endpoint devices. |
| Fishjam Server SDKs | Toolkit for integrating your backend with Fishjam. We currently support Python and NodeJS. |
| Sandbox API | Simple backend for creating test rooms. You can test Fishjam without having to set up your own backend. |
## Use Cases
Fishjam is ideal for:
### Video Conferencing
Build videoconferencing applications with multiple participants in rooms, screen sharing, and audio/video.
### Livestreaming
Stream live content from one streamer to many viewers with low latency.
Perfect for live events or streaming platforms.
### Audio-only Applications
Create voice-only experiences like audio conferencing, podcasts, or voice chat applications.
## Next Steps
To understand how Fishjam works technically, see [Fishjam Architecture](../explanation/architecture).
To learn about the different types of rooms available, see [Rooms](../explanation/rooms).
Ready to start building? Check out our tutorials:
- [React Native Quick Start](../tutorials/react-native-quick-start)
- [React Quick Start](../tutorials/react-quick-start)
- [Backend Quick Start](../tutorials/backend-quick-start)
---
## Gemini Live Integration
:::info
This tutorial requires a working Fishjam backend. If you haven't set one up yet, please check the [Backend Quick Start](../tutorials/backend-quick-start).
:::
This guide demonstrates how to build a real-time speech-to-speech agent using Fishjam and [Google's Multimodal Live API](https://ai.google.dev/gemini-api/docs/live).
By connecting these two services, you can create a low-latency voice assistant that not only listens to peers in a room and responds with natural voice, but also provides a real-time transcription of the conversation.
## Overview
The implementation acts as a bridge between two real-time streams:
1. **Fishjam ➡️ Gemini:** The Agent receives audio from the room and forwards it to Google GenAI.
2. **Gemini ➡️ Fishjam:** The Agent receives audio generated by Gemini and plays it back into the room.
To ensure these streams connect without audio glitches (garbled voice, wrong pitch), the audio sample rates must match between services.
## Prerequisites
You will need:
- **Fishjam Server Credentials:** `fishjamId` and `managementToken`. You can get them at [fishjam.io/app](https://fishjam.io/app).
- **Google Gemini API Key:** Obtainable from [Google AI Studio](https://aistudio.google.com/).
### Installation
Since the Google integration is optional, you need to install the specific dependencies for your SDK.
First, ensure you have the Google GenAI SDK installed alongside Fishjam.
```bash
npm install @fishjam-cloud/js-server-sdk @google/genai
```
Install Fishjam with the `gemini` extra to pull in the necessary libraries.
```bash
pip install "fishjam-server-sdk[gemini]"
```
## Implementation
### Step 1: Initialize Clients
We provide a helper factory to initialize the Google Client.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_TOKEN!,
});
// [!code highlight:4]
const genAi = GeminiIntegration.createClient({
// Pass standard Google client options here
apiKey: process.env.GOOGLE_API_KEY!,
});
```
```python
from fishjam import FishjamClient
from fishjam.integrations.gemini import GeminiIntegration
fishjam_client = FishjamClient(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["FISHJAM_TOKEN"]
)
# pass standard Google client kwargs here
# [!code highlight:1]
gen_ai = GeminiIntegration.create_client(api_key=os.environ["GOOGLE_API_KEY"])
```
### Step 2: Configure the Agent
Create a Fishjam agent configured to match the audio format that the Google client expects (16kHz and 24kHz on Gemini input and output, respectively).
```ts
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
// ---cut---
const room = await fishjamClient.createRoom();
const { agent } = await fishjamClient.createAgent(room.id, {
subscribeMode: 'auto',
// Use our preset to match the required audio format (16kHz)
// [!code highlight:1]
output: GeminiIntegration.geminiInputAudioSettings,
});
```
```python
from fishjam import AgentOptions
from fishjam.integrations.gemini import GeminiIntegration
room = fishjam_client.create_room()
# Use our preset to match the required audio format (16kHz)
# [!code highlight:1]
agent_options = AgentOptions(output=GeminiIntegration.GEMINI_INPUT_AUDIO_SETTINGS)
agent = fishjam_client.create_agent(room.id, agent_options)
```
### Step 3: Connect the Streams
:::warning[Encoding]
Fishjam handles raw bytes, while Google GenAI SDKs often expect Base64 strings. Ensure you convert between them correctly as shown below.
:::
Now we setup the callbacks. We need to forward incoming Fishjam audio to Google, and forward incoming Google audio to Fishjam.
```ts
const fishjamId = '';
const managementToken = '';
const fishjamClient = new FishjamClient({ fishjamId, managementToken });
const genAi = GI.createClient({
apiKey: process.env.GOOGLE_API_KEY!,
});
const room = await fishjamClient.createRoom();
const { agent } = await fishjamClient.createAgent(room.id, {
subscribeMode: 'auto',
output: GI.geminiInputAudioSettings,
});
// ---cut---
const GEMINI_MODEL = 'gemini-2.5-flash-native-audio-preview-12-2025'
// Use our preset to match the required audio format (24kHz)
const agentTrack = agent.createTrack(GeminiIntegration.geminiOutputAudioSettings);
const session = await genAi.live.connect({
model: GEMINI_MODEL,
config: { responseModalities: [Modality.AUDIO] },
callbacks: {
// Google -> Fishjam
onmessage: (msg) => {
if (msg.data) {
const pcmData = Buffer.from(msg.data, 'base64');
agent.sendData(agentTrack.id, pcmData);
}
if (msg.serverContent?.interrupted) {
console.log('Agent was interrupted by user.');
// Clears the buffer on the Fishjam media server
agent.interruptTrack(agentTrack.id);
}
}
}
});
// Fishjam -> Google
agent.on('trackData', ({ data }) => {
session.sendRealtimeInput({
audio: {
mimeType: GeminiIntegration.inputMimeType,
data: Buffer.from(data).toString('base64'),
}
});
});
```
Now we connect the websocket loops. We need to forward incoming Fishjam audio to Google, and forward incoming Google audio to Fishjam.
```python
from google.genai.types import Blob, Modality
from fishjam.integrations.gemini import GeminiIntegration
GEMINI_MODEL = "gemini-2.5-flash-native-audio-preview-12-2025"
async def run():
async with agent.connect() as fishjam_session:
# Use our preset to match the required audio format (24kHz)
outgoing_track = await fishjam_session.add_track(GeminiIntegration.GEMINI_OUTPUT_AUDIO_SETTINGS)
async with gen_ai.aio.live.connect(
model=GEMINI_MODEL,
config={"response_modalities": [Modality.AUDIO]}
) as gemini_session:
# Fishjam -> Google
async def forward_audio_to_gemini():
async for track_data in fishjam_session.receive():
await gemini_session.send_realtime_input(audio=Blob(
mime_type=GeminiIntegration.GEMINI_AUDIO_MIME_TYPE,
data=track_data.data
))
# Google -> Fishjam
async def forward_audio_to_fishjam():
async for msg in gemini_session.receive():
server_content = msg.server_content
if server_content is None:
continue
if server_content.interrupted:
await outgoing_track.interrupt()
if server_content.model_turn and server_content.model_turn.parts:
for part in server_content.model_turn.parts:
if part.inline_data and part.inline_data.data:
await outgoing_track.send_chunk(part.inline_data.data)
# Run both loops concurrently
await asyncio.gather(
forward_audio_to_gemini(),
forward_audio_to_fishjam()
)
asyncio.run(run())
```
## Troubleshooting Gemini API keys
If your agent joins the room but silently does nothing — no audio, no transcription, and no error — the issue is often related to the Gemini API key.
:::warning[API key errors surface asynchronously]
`createClient` is a thin synchronous wrapper around Google's `GoogleGenAI` and makes no network call, so it does **not** validate your key — an invalid or unauthorized key is not rejected when you create the client. Unless you verify it explicitly (see below), the key is first exercised when `live.connect()` opens the Live websocket, and authentication or access failures then typically surface through the Live session callbacks (`onerror` / `onclose`) rather than as a thrown exception. (Other problems, such as a malformed config, can still reject the awaited `connect()` call — keep a `try/catch` around it too.)
:::
To catch a bad key up front, call `checkCredentials` before connecting: it makes a single network request and throws if the key is rejected, so misconfiguration fails fast instead of silently. Still implement the `onerror` and `onclose` callbacks and log the close code and reason — that is where model-specific rejections (see below) and other Live failures appear:
```ts
const genAi = GeminiIntegration.createClient({
apiKey: process.env.GOOGLE_API_KEY!,
});
const GEMINI_MODEL = "gemini-2.5-flash-native-audio-preview-12-2025";
const handleMessage = (msg: LiveServerMessage) => {};
// ---cut---
await GeminiIntegration.checkCredentials(genAi);
const session = await genAi.live.connect({
model: GEMINI_MODEL,
config: { responseModalities: [Modality.AUDIO] },
callbacks: {
onopen: () => console.log("Gemini Live connected"),
onerror: (e) => console.error("Gemini Live error:", e),
onclose: (e) =>
console.error(`Gemini Live closed: code=${e.code} reason=${e.reason}`),
onmessage: handleMessage,
},
});
```
### Common reasons a key doesn't work
- Wrong or mistyped key, or a key from the wrong Google Cloud project.
- The Gemini API is not enabled for the key's project.
- Region or country restriction — the Gemini API (or its free tier) is not available in your region.
- Model-specific rejection. The native-audio Live models (e.g. `gemini-2.5-flash-native-audio-preview-*`) can reject an otherwise-valid key: the websocket closes with code `1008` and the message _"Your API key was reported as leaked. Please use another API key."_ (even when the key is not actually leaked), or with code `1011` internal errors. A key that works for other models can still fail here.
### How to fix
- Verify or regenerate your key at [Google AI Studio](https://aistudio.google.com/app/apikey).
- Confirm the Gemini API is enabled for the key's project and that your region is supported.
- If you see the `1008` "leaked" message, rotate to a freshly generated key.
---
## VAPI Integration
:::info
This tutorial requires a working Fishjam backend. If you haven't set one up yet, please check the [Backend Quick Start](../tutorials/backend-quick-start).
:::
This guide shows how to add a [VAPI](https://vapi.ai/) voice AI agent to a Fishjam room.
Unlike custom agent integrations (such as [Gemini](./gemini-live-integration)), there is no need to build a WebSocket bridge yourself —
Fishjam connects to VAPI internally. You only need to create a VAPI call and pass its ID to Fishjam.
## Overview
The workflow has two steps:
1. **Create a VAPI call** using the VAPI SDK. This gives you a `callId`.
2. **Pass the call ID to Fishjam** via `createVapiAgent()` / `create_vapi_agent()`. Fishjam joins the call and streams audio to and from the room.
:::note
The VAPI peer receives audio from only one peer at a time, so this integration works best in 1-on-1 calls. All peers in the room hear VAPI's responses.
:::
## Prerequisites
You will need:
- **Fishjam Server Credentials:** `fishjamId` and `managementToken`. You can get them at [fishjam.io/app](https://fishjam.io/app).
- **VAPI Private API Key:** Obtainable from the [VAPI Dashboard](https://dashboard.vapi.ai/).
- **VAPI Assistant ID** _(optional)_**:** Create an assistant in the [VAPI Dashboard](https://dashboard.vapi.ai/), or provide a transient assistant configuration inline.
### Installation
```bash
npm install @fishjam-cloud/js-server-sdk @vapi-ai/server-sdk
```
```bash
pip install fishjam-server-sdk vapi_server_sdk
```
## Implementation
### Step 1: Create a VAPI Call
Use the VAPI SDK to create a call with `vapi.websocket` transport and `pcm_s16le` audio at `16000` Hz.
You can reference an existing assistant by its ID, or create a transient assistant inline by providing the full configuration via the `assistant` field instead of `assistantId`.
```ts
const vapiClient = new VapiClient({
token: process.env.VAPI_API_KEY!,
});
// [!code highlight:11]
const call = await vapiClient.calls.create({
assistantId: process.env.VAPI_ASSISTANT_ID!,
transport: {
provider: 'vapi.websocket',
audioFormat: {
format: 'pcm_s16le',
container: 'raw',
sampleRate: 16000,
},
},
}) as Vapi.Call;
```
```python
from vapi import Vapi
vapi_client = Vapi(token=os.environ["VAPI_API_KEY"])
# [!code highlight:11]
call = vapi_client.calls.create(
assistant_id=os.environ["VAPI_ASSISTANT_ID"],
transport={
"provider": "vapi.websocket",
"audioFormat": {
"format": "pcm_s16le",
"container": "raw",
"sampleRate": 16000,
},
},
)
```
### Step 2: Add the VAPI Peer to Fishjam
Pass the call ID and your VAPI API key to Fishjam. Fishjam handles the rest.
```ts
const vapiClient = new VapiClient({
token: process.env.VAPI_API_KEY!,
});
const call = await vapiClient.calls.create({
assistantId: process.env.VAPI_ASSISTANT_ID!,
transport: {
provider: 'vapi.websocket',
audioFormat: {
format: 'pcm_s16le',
container: 'raw',
sampleRate: 16000,
},
},
}) as Vapi.Call;
// ---cut---
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_TOKEN!,
});
const room = await fishjamClient.createRoom();
// [!code highlight:4]
await fishjamClient.createVapiAgent(room.id, {
callId: call.id,
apiKey: process.env.VAPI_API_KEY!,
});
```
```python
from fishjam import FishjamClient, PeerOptionsVapi
fishjam_client = FishjamClient(
fishjam_id=os.environ["FISHJAM_ID"],
management_token=os.environ["FISHJAM_TOKEN"],
)
room = fishjam_client.create_room()
# [!code highlight:2]
options = PeerOptionsVapi(api_key=os.environ["VAPI_API_KEY"], call_id=call.id)
peer = fishjam_client.create_vapi_agent(room.id, options)
```
## That's it
Once both steps are complete, the VAPI assistant is live in the room — peers can speak to it and hear its responses.
The VAPI peer's lifetime is tied to the underlying WebSocket connection. If there is a prolonged period of silence or the call ends for any other reason, the peer will disconnect and be removed from the room. You can detect this by listening for `PeerDisconnected` and `PeerDeleted` server notifications. If the peer crashes (e.g. due to an invalid transport configuration or call ID), a `PeerCrashed` notification is sent instead. See [Listening to events](../how-to/backend/server-setup#listening-to-events) for how to subscribe to these notifications.
## Ending the call automatically
Set `autoClose` to end the VAPI call once the last participant leaves the room.
The peer is then removed and a `PeerDeleted` notification is sent.
```ts
const fishjamClient = new FishjamClient({
fishjamId: process.env.FISHJAM_ID!,
managementToken: process.env.FISHJAM_TOKEN!,
});
const roomId = '' as RoomId;
const callId = '';
// ---cut---
await fishjamClient.createVapiAgent(roomId, {
callId,
apiKey: process.env.VAPI_API_KEY!,
// [!code highlight]
autoClose: true,
});
```
```python
options = PeerOptionsVapi(
api_key=os.environ["VAPI_API_KEY"],
call_id=call.id,
# [!code highlight]
auto_close=True,
)
```
## Billing
The VAPI peer is billed as a single Fishjam peer. VAPI's own usage pricing applies separately — see [VAPI pricing](https://vapi.ai/pricing) for details.
---
## Stream Vision Camera to Fishjam Mobile
# Stream Vision Camera to Fishjam Mobile
:::note
This tutorial is exclusively for **Mobile** (React Native) applications.
:::
:::tip[Don't need VisionCamera?]
Fishjam manages the camera itself with [`useCamera`](../../how-to/client/start-streaming.mdx), and can blur the background or run your own shaders on it. If you don't need VisionCamera for something else, follow the [background blur tutorial](../../tutorials/background-blur.mdx) or the [WebGPU effects tutorial](../../tutorials/webgpu-effects.mdx) instead.
:::
This tutorial walks you through publishing a [VisionCamera](https://react-native-vision-camera.com) feed to a Fishjam room, step by step.
By the end, your camera frames will reach other participants as a custom video track, the same path you'd later use to run frame processors or draw your own effects into the published video.
## What you'll build
A React Native app that joins a room and publishes the device camera through VisionCamera, with a live self-view.
## What you'll learn
- How to install and configure VisionCamera v5 alongside the Fishjam SDK
- How to publish camera frames with `useVisionCameraSource`
- How custom video tracks appear to other participants
## Prerequisites
- The [React Native Quick Start](../../tutorials/react-native-quick-start) completed, or an existing app wrapped in `FishjamProvider`
- A physical device, or the iOS Simulator with a virtual camera from [SimCam](../../how-to/client/ios-simulator-camera.mdx)
- The New Architecture enabled; custom video tracks require it
## Step 1: Install and configure
### Install the packages
```bash npm2yarn
npm install @fishjam-cloud/react-native-vision-camera-source react-native-vision-camera react-native-vision-camera-worklets react-native-worklets
```
### Configure the Babel plugin
VisionCamera's frame outputs run as worklets, which need the `react-native-worklets` Babel plugin. Add it as the **last** plugin:
```js title='babel.config.js'
module.exports = {
presets: ["babel-preset-expo"],
plugins: ["react-native-worklets/plugin"],
};
```
Restart Metro with a cleared cache afterwards (`npx expo start --clear`).
### Configure camera permission
```json title='app.json'
{
"expo": {
"android": {
"permissions": ["android.permission.CAMERA"]
},
"ios": {
"infoPlist": {
"NSCameraUsageDescription": "Allow $(PRODUCT_NAME) to access your camera."
}
}
}
}
```
```xml title='AndroidManifest.xml'
```
```xml title='Info.plist'
NSCameraUsageDescription
Allow $(PRODUCT_NAME) to access your camera.
```
### Rebuild the app
```bash
npx expo prebuild
npx expo run:ios # or run:android
```
```bash
cd ios && pod install
```
## Step 2: Join a room
As in the [quick start](../../tutorials/react-native-quick-start#step-2-join-a-room-and-start-streaming), join a room with a peer token. This time there is no need to initialize the camera through the Fishjam SDK, since VisionCamera will manage the camera:
```tsx
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
export function JoinRoomButton() {
const { joinRoom } = useConnection();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const handleJoinRoom = async () => {
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken("testRoom", "streamer");
await joinRoom({ peerToken });
};
return ;
}
```
## Step 3: Publish the camera
`useVisionCameraSource` creates the video track, publishes it under the given source ID, and cleans up on unmount. Plug its `frameOutput` into VisionCamera's `useCamera`:
```tsx
useCamera as useVisionCamera,
useCameraPermission,
} from "react-native-vision-camera";
export function CameraPublisher() {
const { hasPermission, canRequestPermission, requestPermission } =
useCameraPermission();
useEffect(() => {
if (!hasPermission && canRequestPermission) {
requestPermission();
}
}, [hasPermission, canRequestPermission, requestPermission]);
const { frameOutput, stream } = useVisionCameraSource("vision-camera");
useVisionCamera({
device: "front",
isActive: hasPermission,
outputs: [frameOutput],
});
if (!stream) return Starting camera… ;
return (
);
}
```
The `stream` also serves as your self-view. Frames are handed to Fishjam without copying pixels, and rotation and timestamps are handled for you.
## Step 4: Display it on the other side
Because the feed is a custom source, other participants find it in `customVideoTracks`, not in `cameraTrack`:
```tsx
export function RemoteStreams() {
const { remotePeers } = usePeers();
return (
{remotePeers.map((peer) =>
peer.customVideoTracks.map(
(track) =>
track.stream && (
),
),
)}
);
}
```
To verify end to end, join the same room from a second device or another client built in the [quick start](../../tutorials/react-native-quick-start), and watch the published feed arrive.
## Complete example
```tsx
FishjamProvider,
RTCView,
useConnection,
usePeers,
useSandbox,
} from "@fishjam-cloud/react-native-client";
useCamera as useVisionCamera,
useCameraPermission,
} from "react-native-vision-camera";
const FISHJAM_ID = "YOUR_FISHJAM_ID";
const SANDBOX_API_URL = "YOUR_SANDBOX_API_URL";
// ---cut---
function CameraPublisher() {
const { hasPermission, canRequestPermission, requestPermission } =
useCameraPermission();
useEffect(() => {
if (!hasPermission && canRequestPermission) {
requestPermission();
}
}, [hasPermission, canRequestPermission, requestPermission]);
const { frameOutput, stream } = useVisionCameraSource("vision-camera");
useVisionCamera({
device: "front",
isActive: hasPermission,
outputs: [frameOutput],
});
if (!stream) return Starting camera… ;
return (
);
}
function Room() {
const { joinRoom, peerStatus } = useConnection();
const { remotePeers } = usePeers();
const { getSandboxPeerToken } = useSandbox({
sandboxApiUrl: SANDBOX_API_URL,
});
const [isJoined, setIsJoined] = useState(false);
const handleJoin = async () => {
// For testing with the Sandbox API, use getSandboxPeerToken
// For production apps, get the peerToken from your own backend instead
const peerToken = await getSandboxPeerToken("testRoom", "streamer");
await joinRoom({ peerToken });
setIsJoined(true);
};
return (
Vision Camera × Fishjam
Status: {peerStatus}
{!isJoined && }
Your camera
Other participants
{remotePeers.map((peer) =>
peer.customVideoTracks.map(
(track) =>
track.stream && (
),
),
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 24,
fontWeight: "bold",
marginBottom: 10,
},
status: {
fontSize: 16,
marginBottom: 20,
},
sectionTitle: {
fontSize: 18,
fontWeight: "600",
marginVertical: 10,
},
video: {
height: 200,
width: 200,
borderRadius: 8,
},
});
export default function App() {
return (
);
}
```
## Next steps
- Run inference on the published frames; see [Publish a Vision Camera feed](./vision-camera-source#run-frame-processors-on-published-frames)
- Draw your own shaders into the VisionCamera feed; see [WebGPU effects with VisionCamera](./webgpu-effects.mdx)
- Explore the [custom sources overview](../../how-to/client/custom-sources/index.mdx) and the [low-level frame API](../../how-to/client/custom-sources/low-level-frame-api)
- Learn [how custom sources work](../../explanation/custom-sources) under the hood
---
## Publish a Vision Camera feed
# Publish a Vision Camera feed Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
`@fishjam-cloud/react-native-vision-camera-source` publishes a [VisionCamera](https://react-native-vision-camera.com) feed to Fishjam. Its hooks work like the other Fishjam source hooks ([`useCamera`](../../api/mobile/functions/useCamera), [`useScreenShare`](../../api/mobile/functions/useScreenShare), [`useCustomSource`](../../api/mobile/functions/useCustomSource)): they create the underlying track, publish it, and clean up on unmount. Each camera frame is handed to Fishjam without copying its pixels.
Use this package when you need VisionCamera capabilities alongside a Fishjam call, such as frame-processor plugins for on-device ML, precise device control, or [your own WebGPU rendering](./webgpu-effects) drawn into the published video. If you only want to stream the camera, use [`useCamera`](../../how-to/client/start-streaming.mdx) instead. To blur the background, draw your own shaders into the camera, or read camera frames in a worklet, you don't need VisionCamera either: see [Camera effects](../../how-to/client/camera-effects/index.mdx).
## Prerequisites
- `react-native-vision-camera` **v5** and `react-native-vision-camera-worklets`
- [`react-native-worklets`](https://docs.swmansion.com/react-native-worklets/) with its Babel plugin configured (required by VisionCamera's frame outputs)
- `@fishjam-cloud/react-native-client` with your app wrapped in `FishjamProvider` (see [Installation](../../how-to/client/installation.mdx))
- The New Architecture; custom video tracks require it
## Install
```bash npm2yarn
npm install @fishjam-cloud/react-native-vision-camera-source react-native-vision-camera react-native-vision-camera-worklets react-native-worklets
```
Add the worklets Babel plugin as the last entry in your Babel plugins, then restart Metro with a cleared cache:
```js title='babel.config.js'
module.exports = {
presets: ["babel-preset-expo"],
plugins: ["react-native-worklets/plugin"],
};
```
Camera permission setup (usage strings, requesting at runtime) follows the standard VisionCamera flow; see the [VisionCamera getting started guide](https://react-native-vision-camera.com/docs/guides).
## Publish the camera
Pass the hook's `frameOutput` to VisionCamera's `useCamera` outputs. The returned `stream` is your self-view; the same feed is published to the room under the given source ID.
```tsx
useCamera as useVisionCamera,
useCameraPermission,
} from "react-native-vision-camera";
export function CameraPublisher() {
const { hasPermission } = useCameraPermission();
const { frameOutput, stream } = useVisionCameraSource("my-camera");
useVisionCamera({
device: "front",
isActive: hasPermission,
outputs: [frameOutput],
});
if (!stream) return null;
return (
);
}
```
Frame rotation and timestamps are handled for you: the hook normalizes VisionCamera's per-platform timestamp units onto one monotonic timeline and applies the frame's orientation automatically.
Other peers receive the feed among their [`customVideoTracks`](../../how-to/client/custom-sources/index.mdx#receiving-custom-tracks).
:::warning[On-screen drawing is not published]
The published track carries the camera frames exactly as captured. Anything you draw on top of the preview (React Native views, a [Skia](https://shopify.github.io/react-native-skia/) canvas, or any other overlay) appears only in your local UI and is **not** sent to Fishjam. To render content into the published video itself, use [WebGPU effects with VisionCamera](./webgpu-effects.mdx) for effects and overlays on the camera feed, or the [low-level frame API](../../how-to/client/custom-sources/low-level-frame-api.mdx) when you produce the frames yourself.
:::
## Run frame processors on published frames
Pass an `onFrame` worklet to process every published frame, for example to run a VisionCamera frame-processor plugin for pose detection or other on-device inference. `onFrame` is for reading frames; it cannot draw into the published feed:
```tsx
declare function detectPose(frame: Frame): unknown;
// ---cut---
const onFrame = useCallback((frame: Frame) => {
"worklet";
const pose = detectPose(frame); // any VisionCamera frame-processor plugin
console.log(pose);
}, []);
const { frameOutput, stream } = useVisionCameraSource("my-camera", {
onFrame,
});
```
:::danger[Frame lifetime]
`onFrame` runs **after** the frame has been sent to Fishjam, and the frame is valid only for the duration of your synchronous callback; the hook releases it afterwards. Don't store the frame or its buffers for later use.
:::
:::warning
Keep the identity of `onFrame` stable (`useCallback` or module scope). A new function identity re-registers the frame callback on every render.
:::
## Options
| Option | Default | Description |
| -------------------------- | ------------ | --------------------------------------------------------------------------------------------------- |
| `enabled` | `true` | Creates and publishes the track while `true`; tears everything down when `false`. |
| `onFrame` | — | Worklet called with every camera frame after it has been sent. |
| `onFrameDropped` | — | Worklet called with the reason whenever a frame is skipped (for example when the pipeline is busy). |
| `frameIntervalNanoseconds` | `33_333_333` | Fallback frame spacing used when a frame arrives without a usable native timestamp. |
The options also accept VisionCamera's `FrameOutputOptions`. The hook forces `pixelFormat: 'native'` (the copy-free path) and defaults `dropFramesWhileBusy` to `true`.
## Next steps
- Follow the [Vision Camera tutorial](./stream-vision-camera) for a step-by-step walkthrough
- Draw your own content into the feed with [WebGPU effects](./webgpu-effects)
- API reference: [Vision Camera Source package](../../api/vision-camera-source/index)
---
## Render WebGPU effects into a Vision Camera feed
# Render WebGPU effects into a Vision Camera feed Mobile
:::note
This guide is exclusively for **Mobile** (React Native) applications.
:::
This guide shows how to render each frame of a published [VisionCamera](https://react-native-vision-camera.com) feed yourself with WebGPU, using the `/webgpu` entry point of `@fishjam-cloud/react-native-vision-camera-source`. For every camera frame, your worklet receives the camera as a GPU texture and an output texture to draw into. The [`useVisionCameraWebGpuSource`](../../api/vision-camera-source/index.md) hook handles publishing, GPU synchronization with the video encoder, timestamps and frame lifetimes.
:::tip[Don't need VisionCamera?]
The same kind of rendering works on the camera Fishjam manages itself, without VisionCamera. See [Render WebGPU effects into the camera](../../how-to/client/camera-effects/webgpu-effects.mdx).
:::
Every camera frame reaches your `onFrame` worklet. Calling `render(...)` gives you the live camera as a GPU texture and an output texture to draw into. Whatever you draw is what peers receive.
## Prerequisites
On top of the [Vision Camera setup](./vision-camera-source.mdx#prerequisites):
- `react-native-webgpu` ≥ 0.10.1
- `unplugin-typegpu` in your app's Babel config (the TGSL shaders need its build-time transform)
- iOS 17+: the camera-import path relies on Metal external-texture features not guaranteed on earlier versions. The [base integration](./vision-camera-source.mdx) has no such requirement, so you can keep your `ios.deploymentTarget` unchanged and gate WebGPU usage at runtime.
```bash npm2yarn
npm install react-native-webgpu typegpu unplugin-typegpu
```
```js title='babel.config.js'
module.exports = {
presets: ["babel-preset-expo"],
plugins: ["unplugin-typegpu/babel", "react-native-worklets/plugin"],
};
```
Keep `react-native-worklets/plugin` as the last plugin.
## Get a camera-capable GPU device
`useCameraWebGpuDevice` returns an app-wide shared `GPUDevice`, requested with the features the camera-import path needs:
```tsx
// ---cut---
const { device, error } = useCameraWebGpuDevice();
```
To use your own device instead, pass it as the `device` option of `useVisionCameraWebGpuSource`. It is validated against `getRequiredWebGpuCameraFeatures()`; a device missing any of the features surfaces a descriptive `error` instead of failing per frame.
## Publish the camera through your own shaders
:::tip[First time?]
The [WebGPU effects tutorial](../../tutorials/webgpu-effects.mdx) builds the same kind of pipeline step by step on Fishjam's own camera, from a passthrough render pass to a watermark overlay and a color effect. The shaders and render passes carry over; only the setup around them differs.
:::
The example below publishes the camera in grayscale. To apply your own effect, replace the fragment stage. Your component only does the drawing; the hook handles publishing, GPU synchronization with the video encoder, timestamps and frame lifetimes.
:::note
The shaders are written in [TypeGPU](https://docs.swmansion.com/TypeGPU/) (TGSL): typed TypeScript functions compiled to WGSL by `unplugin-typegpu`. TypeGPU is not required; you can hand-write WGSL and prepend the bindings' `bindingDeclarations` yourself.
:::
```tsx
// @baseUrl: .
// @paths: {"typegpu": ["packages/web-client-sdk/node_modules/typegpu"], "typegpu/*": ["packages/web-client-sdk/node_modules/typegpu/*"]}
useCamera as useVisionCamera,
useCameraPermission,
type Frame,
} from "react-native-vision-camera";
useVisionCameraWebGpuSource,
useCameraWebGpuDevice,
createCameraShaderBindings,
getOutputSurfaceFormat,
type WebGpuFrameRenderFunction,
} from "@fishjam-cloud/react-native-vision-camera-source/webgpu";
// Full-screen triangle; uv spans the visible area.
const vertexMain = tgpu.vertexFn({
in: { vertexIndex: d.builtin.vertexIndex },
out: { position: d.builtin.position, uv: d.location(0, d.vec2f) },
})((input) => {
const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)];
const p = positions[input.vertexIndex];
return {
position: d.vec4f(p.x, p.y, 0, 1),
uv: d.vec2f((p.x + 1) * 0.5, 1 - (p.y + 1) * 0.5),
};
});
export function GrayscaleCameraPublisher() {
const { hasPermission } = useCameraPermission();
const { device } = useCameraWebGpuDevice();
const effect = useMemo(() => {
if (device == null) return null;
const cameraBindings = createCameraShaderBindings(device);
const fragmentMain = tgpu.fragmentFn({
in: { uv: d.location(0, d.vec2f) },
out: d.vec4f,
})((input) => {
const color = cameraBindings.sampleCamera(input.uv);
const gray = dot(color.xyz, d.vec3f(0.299, 0.587, 0.114));
return d.vec4f(gray, gray, gray, 1);
});
// TypeGPU cannot emit the external-texture binding itself, so prepend
// cameraBindings.bindingDeclarations to the resolved WGSL.
const module = device.createShaderModule({
code:
cameraBindings.bindingDeclarations +
tgpu.resolve({ externals: { vertexMain, fragmentMain } }),
});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [cameraBindings.bindGroupLayout],
}),
vertex: { module, entryPoint: "vertexMain" },
fragment: {
module,
entryPoint: "fragmentMain",
targets: [{ format: getOutputSurfaceFormat() }],
},
});
return { cameraBindings, pipeline };
}, [device]);
const onFrame = useCallback(
(frame: Frame, render: WebGpuFrameRenderFunction) => {
"worklet";
if (effect == null) return; // drop frames until the pipeline is ready
render(({ commandEncoder, outputView, cameraBindGroup }) => {
const pass = commandEncoder.beginRenderPass({
colorAttachments: [
{ view: outputView, loadOp: "clear", storeOp: "store" },
],
});
pass.setPipeline(effect.pipeline);
pass.setBindGroup(0, cameraBindGroup!);
pass.draw(3);
pass.end();
});
},
[effect],
);
const { frameOutput, stream } = useVisionCameraWebGpuSource("my-camera", {
width: 720,
height: 1280,
cameraShaderBindings: effect?.cameraBindings,
onFrame,
});
useVisionCamera({
device: "front",
isActive: hasPermission,
outputs: [frameOutput],
});
if (!stream) return null;
return (
);
}
```
How the example works:
- `createCameraShaderBindings(device)` gives your shaders `sampleCamera(uv)`, which returns upright RGB on both platforms and handles the YUV decode for you.
- Everything created from the `device` (bindings, shaders, pipeline) lives in one `useMemo` keyed by the device. TypeGPU cannot emit the camera's `texture_external` binding, so `cameraBindings.bindingDeclarations` is prepended to the resolved WGSL, and the fragment targets `getOutputSurfaceFormat()` (`rgba8unorm` on Android, `bgra8unorm` on iOS).
- Passing `cameraShaderBindings` to the hook makes the render context carry a ready-made `cameraBindGroup`, rebuilt each frame because the camera's external texture expires with every frame.
- The worklet encodes one render pass; the hook submits it and synchronizes with the video encoder. `frameOutput` plugs into VisionCamera's `useCamera`; `stream` is the self-view.
Other peers receive the feed among their [`customVideoTracks`](../../how-to/client/custom-sources/index.mdx#receiving-custom-tracks).
## Rules inside `onFrame`
The callback you pass to `render(...)` receives a `WebGpuFrameRenderContext` with the `device`, `queue`, `commandEncoder`, the live `cameraTexture` (a `GPUExternalTexture`), the output surface (`outputTexture`, `outputView`, `outputWidth`, `outputHeight`), and camera metadata (`cameraWidth`, `cameraHeight`, `cameraIsMirrored`).
:::warning[Rules your worklet must follow]
- **Always draw into the provided `outputView`.** Calling `outputTexture.createView()` per frame leaks native wrappers on the frame runtime, because `GPUTextureView` has no release API.
- **Call `render(...)` at most once per frame.** Skipping it drops the frame; nothing is published for it.
- **Don't call `queue.submit()` yourself.** The hook submits your passes and synchronizes with the video encoder.
- **Finish GPU uploads before frames flow.** Helpers like [`queue.copyExternalImageToTexture`](https://developer.mozilla.org/en-US/docs/Web/API/GPUQueue/copyExternalImageToTexture) submit work internally. Running them from the JS thread while the source is active races the hook's submissions and can crash the app, so upload textures before activating the camera.
- **Camera bind groups cannot be cached across frames**, because the external texture changes every frame. The hook rebuilds `cameraBindGroup` for you; if you build your own, call `createCameraBindGroup` inside the worklet each frame.
- **Keep `onFrame`'s identity stable** (`useCallback` or module scope).
:::
After `render(...)` returns you may keep using the `frame` (for example, to run inference on it), but only until your callback returns; the hook releases it afterwards.
## Going further
- **Overlays**: a frame may contain more than one render pass. Encode additional passes into the same `outputView` (with `loadOp: "load"`) after the camera pass to draw watermarks or other content on top.
- **Cropping helpers**: the grayscale example stretches the camera to the output. `computeAspectFillCrop` and `computeSquareCrop` compute the crop that fills your output aspect ratio (like `objectFit: "cover"`); `packFrameCropParams` packs a crop for your own uniform buffers.
- **Pipelines that cannot sample `texture_external`** can resolve the camera into an owned `rgba8unorm` texture with `createCameraTextureResolver` and `resolveCameraTexture`, at the cost of one extra render pass per frame.
The full toolkit is documented in the [Custom Video Source API reference](../../api/custom-video-source/index.md).
## Platform notes
- `sampleCamera(uv)` returns upright RGB on both platforms. On **Android** it performs the BT.709 limited-range YUV→RGB decode in-shader; on **iOS** the camera already arrives as RGB.
- `getOutputSurfaceFormat()` returns the published surface format: `rgba8unorm` on Android, `bgra8unorm` on iOS. Use it for your fragment targets instead of hard-coding a format.
- The context's `cameraIsMirrored` tells you whether the camera feed is mirrored (typically the front camera).
## Related guides
- [Publish a Vision Camera feed](./vision-camera-source.mdx): publish the camera without custom rendering
- [Render WebGPU effects into the camera](../../how-to/client/camera-effects/webgpu-effects.mdx): the same approach on Fishjam's own camera
- [Low-level frame API](../../how-to/client/custom-sources/low-level-frame-api.mdx): the pooled-surface layer the hook builds on
- [How custom sources work](../../explanation/custom-sources.mdx)
- API reference: [Vision Camera Source package](../../api/vision-camera-source/index.md), [Custom Video Source package](../../api/custom-video-source/index.md)
---
## Reference
Describes APIs for direct interaction with Fishjam.
Fishjam publishes documentation for the Sandbox API, Fishjam Server APIs, and the Composition API.
## Sandbox API
[Sandbox API OpenAPI](https://github.com/fishjam-cloud/documentation/tree/main/static/api/room-manager-openapi.yaml)
See also: [What is the Sandbox API?](../explanation/sandbox-api-concept)
## Server
Fishjam Server provides a REST API for managing rooms, peers, and [recordings](../how-to/recordings/record-with-a-template), and
[Protobufs](https://protobuf.dev) for
receiving structured live updates from the server.
The notifications can be configured using Webhook or Websocket.
### REST API
[Server REST API Reference](/api/rest)
### Protobufs
- [Server Notification Protobufs](https://github.com/fishjam-cloud/documentation/tree/main/static/api/protobuf/server_notifications.proto)
- [Agent Message Protobufs](https://github.com/fishjam-cloud/documentation/tree/main/static/api/protobuf/agent_notifications.proto)
#### Webhook
When using webhooks for receiving notifications, configure your webhook URL in
the **Webhooks** tab of the [Fishjam Dashboard](https://fishjam.io/app).
Fishjam then delivers all notifications to that URL.
The HTTP POST to your webhook URL uses "application/x-protobuf" content type.
The body is binary data, that represents encoded `ServerMessage`.
Setting `batchWebhookNotifications` to `true` in the `RoomConfig` is recommended. Fishjam then coalesces several notifications into one POST: the body is still a single `ServerMessage`, but its `notification_batch` field holds a `NotificationBatch`, which carries the individual notifications as a repeated list of `ServerMessage`s (see `server_notifications.proto`). This delivers notifications faster and with fewer requests. The SDK decoders unwrap the batch for you.
For more information see also [server setup documentation](../how-to/backend/server-setup#webhooks)
#### Websocket
After opening the Websocket connection to
`https://fishjam.io/api/v1/connect/{fishjamId}/socket/server/websocket`,
the first message that must be sent is an `AuthRequest`,
with a valid Management Token.
Next, you can should subscribe to notifications by sending `SubscribeRequest` event with `SERVER_NOTIFICATION` event type.
## Compositions
[Compositions](../explanation/compositions) are managed through the Composition API. All requests go to `https://rtc.fishjam.io`.
### REST API
[Composition REST API Reference](/api/compositions)
Calls authenticate with your Management Token, from the [**Fishjam developer panel**](https://fishjam.io/app).
Request bodies are snake_case and closed: a field the endpoint does not define is rejected with `422` rather than ignored, so a misspelling fails loudly instead of silently doing nothing.
---
## @fishjam-cloud/react-native-client
React Native client SDK for building mobile video and audio apps with Fishjam.
## Connection
- [useConnection](functions/useConnection.md)
- [useDataChannel](functions/useDataChannel.md)
- [Metadata](type-aliases/Metadata.md)
- [useUpdatePeerMetadata](variables/useUpdatePeerMetadata.md)
- [useVAD](variables/useVAD.md)
## Other
- [failIncomingCallConnected](functions/failIncomingCallConnected.md)
- [FishjamProvider](functions/FishjamProvider.md)
- [fulfillIncomingCallConnected](functions/fulfillIncomingCallConnected.md)
- [getPendingAnswerRequestId](functions/getPendingAnswerRequestId.md)
- [isCallHeld](functions/isCallHeld.md)
- [pushAudioSamples](functions/pushAudioSamples.md)
- [reportOutgoingCallConnected](functions/reportOutgoingCallConnected.md)
- [RTCPIPView](functions/RTCPIPView.md)
- [RTCView](functions/RTCView.md)
- [setCallHeld](functions/setCallHeld.md)
- [setCallMuted](functions/setCallMuted.md)
- [startPIP](functions/startPIP.md)
- [stopPIP](functions/stopPIP.md)
- [useAudioOutput](functions/useAudioOutput.md)
- [useCallKit](functions/useCallKit.md)
- [useCallKitEvent](functions/useCallKitEvent.md)
- [useCallKitService](functions/useCallKitService.md)
- [useCamera](functions/useCamera.md)
- [useCameraPermissions](functions/useCameraPermissions.md)
- [useCustomAudioSource](functions/useCustomAudioSource.md)
- [useCustomSource](functions/useCustomSource.md)
- [useInitializeDevices](functions/useInitializeDevices.md)
- [useLivestreamStreamer](functions/useLivestreamStreamer.md)
- [useLivestreamViewer](functions/useLivestreamViewer.md)
- [useMicrophone](functions/useMicrophone.md)
- [useMicrophonePermissions](functions/useMicrophonePermissions.md)
- [usePeers](functions/usePeers.md)
- [useScreenShare](functions/useScreenShare.md)
- [useTelecom](functions/useTelecom.md)
- [useTelecomEvent](functions/useTelecomEvent.md)
- [useVoIP](functions/useVoIP.md)
- [VoIPProvider](functions/VoIPProvider.md)
- [AudioDeviceType](enumerations/AudioDeviceType.md)
- [Variant](enumerations/Variant.md)
- [MediaStream](classes/MediaStream.md)
- [MediaStreamTrack](classes/MediaStreamTrack.md)
- [CustomAudioSink](interfaces/CustomAudioSink.md)
- [CustomAudioTrack](interfaces/CustomAudioTrack.md)
- [DataChannelOptions](interfaces/DataChannelOptions.md)
- [JoinRoomConfig](interfaces/JoinRoomConfig.md)
- [SimulcastConfig](interfaces/SimulcastConfig.md)
- [UseCustomAudioSourceOptions](interfaces/UseCustomAudioSourceOptions.md)
- [UseCustomAudioSourceResult](interfaces/UseCustomAudioSourceResult.md)
- [AudioDevice](type-aliases/AudioDevice.md)
- [AudioOutputChangedInfo](type-aliases/AudioOutputChangedInfo.md)
- [AuthErrorReason](type-aliases/AuthErrorReason.md)
- [BandwidthLimits](type-aliases/BandwidthLimits.md)
- [Brand](type-aliases/Brand.md)
- [CallEndedReason](type-aliases/CallEndedReason.md)
- [CallKitAction](type-aliases/CallKitAction.md)
- [CallKitConfig](type-aliases/CallKitConfig.md)
- [ConnectStreamerConfig](type-aliases/ConnectStreamerConfig.md)
- [ConnectViewerConfig](type-aliases/ConnectViewerConfig.md)
- [CurrentCall](type-aliases/CurrentCall.md)
- [CustomSource](type-aliases/CustomSource.md)
- [DataCallback](type-aliases/DataCallback.md)
- [DeviceError](type-aliases/DeviceError.md)
- [DeviceItem](type-aliases/DeviceItem.md)
- [FishjamProviderProps](type-aliases/FishjamProviderProps.md)
- [ForegroundServiceConfig](type-aliases/ForegroundServiceConfig.md)
- [InitializeDevicesResult](type-aliases/InitializeDevicesResult.md)
- [InitializeDevicesSettings](type-aliases/InitializeDevicesSettings.md)
- [InitializeDevicesStatus](type-aliases/InitializeDevicesStatus.md)
- [JoinErrorReason](type-aliases/JoinErrorReason.md)
- [MiddlewareResult](type-aliases/MiddlewareResult.md)
- [PeerId](type-aliases/PeerId.md)
- [PeerStatus](type-aliases/PeerStatus.md)
- [PeerWithTracks](type-aliases/PeerWithTracks.md)
- [PermissionStatus](type-aliases/PermissionStatus.md)
- [PersistLastDeviceHandlers](type-aliases/PersistLastDeviceHandlers.md)
- [ReconnectConfig](type-aliases/ReconnectConfig.md)
- [ReconnectionStatus](type-aliases/ReconnectionStatus.md)
- [RemoteTrack](type-aliases/RemoteTrack.md)
- [RoomType](type-aliases/RoomType.md)
- [RTCPIPViewProps](type-aliases/RTCPIPViewProps.md)
- [RTCVideoViewProps](type-aliases/RTCVideoViewProps.md)
- [SandboxOptions](type-aliases/SandboxOptions.md)
- [SimulcastBandwidthLimit](type-aliases/SimulcastBandwidthLimit.md)
- [SimulcastBandwidthLimits](type-aliases/SimulcastBandwidthLimits.md)
- [StreamConfig](type-aliases/StreamConfig.md)
- [StreamerInputs](type-aliases/StreamerInputs.md)
- [TelecomConfig](type-aliases/TelecomConfig.md)
- [TelecomEvent](type-aliases/TelecomEvent.md)
- [TelecomEventType](type-aliases/TelecomEventType.md)
- [Track](type-aliases/Track.md)
- [TrackBandwidthLimit](type-aliases/TrackBandwidthLimit.md)
- [TrackFields](type-aliases/TrackFields.md)
- [TrackId](type-aliases/TrackId.md)
- [TrackMiddleware](type-aliases/TrackMiddleware.md)
- [TracksMiddleware](type-aliases/TracksMiddleware.md)
- [TracksMiddlewareResult](type-aliases/TracksMiddlewareResult.md)
- [UseAudioOutputResult](type-aliases/UseAudioOutputResult.md)
- [UseCameraResult](type-aliases/UseCameraResult.md)
- [UseCustomSourceResult](type-aliases/UseCustomSourceResult.md)
- [UseDataChannelResult](type-aliases/UseDataChannelResult.md)
- [UseInitializeDevicesParams](type-aliases/UseInitializeDevicesParams.md)
- [UseInitializeDevicesReturn](type-aliases/UseInitializeDevicesReturn.md)
- [UseLivestreamStreamerResult](type-aliases/UseLivestreamStreamerResult.md)
- [UseLivestreamViewerResult](type-aliases/UseLivestreamViewerResult.md)
- [UseMicrophoneResult](type-aliases/UseMicrophoneResult.md)
- [UseSandboxProps](type-aliases/UseSandboxProps.md)
- [UseScreenShareResult](type-aliases/UseScreenShareResult.md)
- [UseTelecomResult](type-aliases/UseTelecomResult.md)
- [VideoCodec](type-aliases/VideoCodec.md)
- [VoIPCallIntent](type-aliases/VoIPCallIntent.md)
- [VoIPCallStatus](type-aliases/VoIPCallStatus.md)
- [VoIPContextValue](type-aliases/VoIPContextValue.md)
- [VoIPEventHandlers](type-aliases/VoIPEventHandlers.md)
- [VoIPIncomingPayload](type-aliases/VoIPIncomingPayload.md)
- [VoIPProviderProps](type-aliases/VoIPProviderProps.md)
- [ScreenCapturePickerView](variables/ScreenCapturePickerView.md)
- [SimulcastConfig](variables/SimulcastConfig.md)
- [useForegroundService](variables/useForegroundService.md)
- [useSandbox](variables/useSandbox.md)
- [useVoIPEvents](variables/useVoIPEvents.md)
---
## @fishjam-cloud/react-client
React client SDK for building web video and audio apps with Fishjam.
## Connection
- [useConnection](functions/useConnection.md)
- [useDataChannel](functions/useDataChannel.md)
- [usePeers](functions/usePeers.md)
- [useUpdatePeerMetadata](functions/useUpdatePeerMetadata.md)
- [useVAD](functions/useVAD.md)
- [Metadata](type-aliases/Metadata.md)
## Devices
- [useCamera](functions/useCamera.md)
- [useInitializeDevices](functions/useInitializeDevices.md)
- [useMicrophone](functions/useMicrophone.md)
- [useScreenShare](functions/useScreenShare.md)
## Components
- [FishjamProvider](functions/FishjamProvider.md)
- [FishjamProviderProps](interfaces/FishjamProviderProps.md)
## Livestream
- [useLivestreamStreamer](functions/useLivestreamStreamer.md)
- [useLivestreamViewer](functions/useLivestreamViewer.md)
- [UseLivestreamStreamerResult](interfaces/UseLivestreamStreamerResult.md)
- [UseLivestreamViewerResult](interfaces/UseLivestreamViewerResult.md)
- [ConnectStreamerConfig](type-aliases/ConnectStreamerConfig.md)
- [StreamerInputs](type-aliases/StreamerInputs.md)
## Other
- [useCustomSource](functions/useCustomSource.md)
- [useSandbox](functions/useSandbox.md)
- [Variant](enumerations/Variant.md)
- [DataChannelOptions](interfaces/DataChannelOptions.md)
- [JoinRoomConfig](interfaces/JoinRoomConfig.md)
- [SimulcastConfig](interfaces/SimulcastConfig.md)
- [AuthErrorReason](type-aliases/AuthErrorReason.md)
- [BandwidthLimits](type-aliases/BandwidthLimits.md)
- [Brand](type-aliases/Brand.md)
- [ConnectViewerConfig](type-aliases/ConnectViewerConfig.md)
- [CustomSource](type-aliases/CustomSource.md)
- [DataCallback](type-aliases/DataCallback.md)
- [DeviceError](type-aliases/DeviceError.md)
- [DeviceItem](type-aliases/DeviceItem.md)
- [InitializeDevicesResult](type-aliases/InitializeDevicesResult.md)
- [InitializeDevicesSettings](type-aliases/InitializeDevicesSettings.md)
- [InitializeDevicesStatus](type-aliases/InitializeDevicesStatus.md)
- [JoinErrorReason](type-aliases/JoinErrorReason.md)
- [MiddlewareResult](type-aliases/MiddlewareResult.md)
- [MoqAccess](type-aliases/MoqAccess.md)
- [PeerId](type-aliases/PeerId.md)
- [PeerStatus](type-aliases/PeerStatus.md)
- [PeerWithTracks](type-aliases/PeerWithTracks.md)
- [PersistLastDeviceHandlers](type-aliases/PersistLastDeviceHandlers.md)
- [ReconnectConfig](type-aliases/ReconnectConfig.md)
- [ReconnectionStatus](type-aliases/ReconnectionStatus.md)
- [RemoteTrack](type-aliases/RemoteTrack.md)
- [RoomType](type-aliases/RoomType.md)
- [SandboxOptions](type-aliases/SandboxOptions.md)
- [SimulcastBandwidthLimit](type-aliases/SimulcastBandwidthLimit.md)
- [SimulcastBandwidthLimits](type-aliases/SimulcastBandwidthLimits.md)
- [StreamConfig](type-aliases/StreamConfig.md)
- [Track](type-aliases/Track.md)
- [TrackBandwidthLimit](type-aliases/TrackBandwidthLimit.md)
- [TrackId](type-aliases/TrackId.md)
- [TrackMiddleware](type-aliases/TrackMiddleware.md)
- [TracksMiddleware](type-aliases/TracksMiddleware.md)
- [TracksMiddlewareResult](type-aliases/TracksMiddlewareResult.md)
- [UseDataChannelResult](type-aliases/UseDataChannelResult.md)
- [UseInitializeDevicesParams](type-aliases/UseInitializeDevicesParams.md)
- [UseSandboxProps](type-aliases/UseSandboxProps.md)
- [VideoCodec](type-aliases/VideoCodec.md)
- [SimulcastConfig](variables/SimulcastConfig.md)
---
## @fishjam-cloud/js-server-sdk
Server-side Node.js SDK for creating and managing Fishjam rooms, peers, agents, and receiving real-time server notifications.
## Client
- [CompositionClient](classes/CompositionClient.md)
- [FishjamClient](classes/FishjamClient.md)
- [FishjamWSNotifier](classes/FishjamWSNotifier.md)
## Notifications
- [decodeServerNotifications](functions/decodeServerNotifications.md)
- [verifyWebhookSignature](functions/verifyWebhookSignature.md)
## Other
- [BadRequestException](classes/BadRequestException.md)
- [CompositionNotFoundException](classes/CompositionNotFoundException.md)
- [FishjamAgent](classes/FishjamAgent.md)
- [FishjamBaseException](classes/FishjamBaseException.md)
- [FishjamNotFoundException](classes/FishjamNotFoundException.md)
- [ForbiddenException](classes/ForbiddenException.md)
- [InputNotFoundException](classes/InputNotFoundException.md)
- [InvalidFishjamCredentialsException](classes/InvalidFishjamCredentialsException.md)
- [MissingFishjamIdException](classes/MissingFishjamIdException.md)
- [OutputNotFoundException](classes/OutputNotFoundException.md)
- [PeerNotFoundException](classes/PeerNotFoundException.md)
- [QuotaExceededException](classes/QuotaExceededException.md)
- [RecordingNotFoundException](classes/RecordingNotFoundException.md)
- [RendererNotFoundException](classes/RendererNotFoundException.md)
- [RoomNotFoundException](classes/RoomNotFoundException.md)
- [ServiceUnavailableException](classes/ServiceUnavailableException.md)
- [StaleSdkException](classes/StaleSdkException.md)
- [UnauthorizedException](classes/UnauthorizedException.md)
- [UnknownException](classes/UnknownException.md)
- [AgentOutput](interfaces/AgentOutput.md)
- [AudioScene](interfaces/AudioScene.md)
- [AudioSceneInput](interfaces/AudioSceneInput.md)
- [BoxShadow](interfaces/BoxShadow.md)
- [CompositionSource](interfaces/CompositionSource.md)
- [CreateCompositionRequest](interfaces/CreateCompositionRequest.md)
- [EasingFunctionBounce](interfaces/EasingFunctionBounce.md)
- [EasingFunctionCubicBezier](interfaces/EasingFunctionCubicBezier.md)
- [EasingFunctionLinear](interfaces/EasingFunctionLinear.md)
- [FishjamExceptionInfo](interfaces/FishjamExceptionInfo.md)
- [Image](interfaces/Image.md)
- [ImageSpecAuto](interfaces/ImageSpecAuto.md)
- [ImageSpecGif](interfaces/ImageSpecGif.md)
- [ImageSpecJpeg](interfaces/ImageSpecJpeg.md)
- [ImageSpecPng](interfaces/ImageSpecPng.md)
- [ImageSpecSvg](interfaces/ImageSpecSvg.md)
- [InputStream](interfaces/InputStream.md)
- [MoqAccess](interfaces/MoqAccess.md)
- [MoqAccessConfig](interfaces/MoqAccessConfig.md)
- [Mp4Input](interfaces/Mp4Input.md)
- [OutputEndCondition](interfaces/OutputEndCondition.md)
- [OutputRtmpClientAudioOptions](interfaces/OutputRtmpClientAudioOptions.md)
- [OutputRtmpClientVideoOptions](interfaces/OutputRtmpClientVideoOptions.md)
- [OutputWhipAudioOptions](interfaces/OutputWhipAudioOptions.md)
- [OutputWhipVideoOptions](interfaces/OutputWhipVideoOptions.md)
- [PeerOptionsAgent](interfaces/PeerOptionsAgent.md)
- [PeerOptionsVapi](interfaces/PeerOptionsVapi.md)
- [PeerOptionsWebRTC](interfaces/PeerOptionsWebRTC.md)
- [RecordingConfig](interfaces/RecordingConfig.md)
- [RegisterInputResponse](interfaces/RegisterInputResponse.md)
- [Rescaler](interfaces/Rescaler.md)
- [Resolution](interfaces/Resolution.md)
- [RoomConfig](interfaces/RoomConfig.md)
- [RtmpInput](interfaces/RtmpInput.md)
- [RtmpOutput](interfaces/RtmpOutput.md)
- [SendCompositionEventRequest](interfaces/SendCompositionEventRequest.md)
- [ServerMessage](interfaces/ServerMessage.md)
- [StreamerToken](interfaces/StreamerToken.md)
- [TemplateSource](interfaces/TemplateSource.md)
- [Text](interfaces/Text.md)
- [Tiles](interfaces/Tiles.md)
- [Transition](interfaces/Transition.md)
- [UnregisterInput](interfaces/UnregisterInput.md)
- [UnregisterOutput](interfaces/UnregisterOutput.md)
- [UnregisterRenderer](interfaces/UnregisterRenderer.md)
- [UpdateOutputRequest](interfaces/UpdateOutputRequest.md)
- [VideoScene](interfaces/VideoScene.md)
- [View](interfaces/View.md)
- [ViewerToken](interfaces/ViewerToken.md)
- [WhepInput](interfaces/WhepInput.md)
- [WhipAudioEncoderOptionsAny](interfaces/WhipAudioEncoderOptionsAny.md)
- [WhipAudioEncoderOptionsOpus](interfaces/WhipAudioEncoderOptionsOpus.md)
- [WhipInput](interfaces/WhipInput.md)
- [WhipOutput](interfaces/WhipOutput.md)
- [AgentCallbacks](type-aliases/AgentCallbacks.md)
- [AgentEvents](type-aliases/AgentEvents.md)
- [AgentTrack](type-aliases/AgentTrack.md)
- [AudioChannels](type-aliases/AudioChannels.md)
- [AudioCodecParameters](type-aliases/AudioCodecParameters.md)
- [AudioFormat](type-aliases/AudioFormat.md)
- [AudioMixingStrategy](type-aliases/AudioMixingStrategy.md)
- [AudioSampleRate](type-aliases/AudioSampleRate.md)
- [Brand](type-aliases/Brand.md)
- [ChannelAdded](type-aliases/ChannelAdded.md)
- [ChannelRemoved](type-aliases/ChannelRemoved.md)
- [CloseEventHandler](type-aliases/CloseEventHandler.md)
- [Component](type-aliases/Component.md)
- [Composition](type-aliases/Composition.md)
- [CompositionConfig](type-aliases/CompositionConfig.md)
- [CompositionId](type-aliases/CompositionId.md)
- [CompositionRecordingConfig](type-aliases/CompositionRecordingConfig.md)
- [EasingFunction](type-aliases/EasingFunction.md)
- [ErrorEventHandler](type-aliases/ErrorEventHandler.md)
- [ExpectedAgentEvents](type-aliases/ExpectedAgentEvents.md)
- [ExpectedEvents](type-aliases/ExpectedEvents.md)
- [FishjamConfig](type-aliases/FishjamConfig.md)
- [HorizontalAlign](type-aliases/HorizontalAlign.md)
- [IgnoredEvents](type-aliases/IgnoredEvents.md)
- [ImageSpec](type-aliases/ImageSpec.md)
- [IncomingTrackData](type-aliases/IncomingTrackData.md)
- [IncomingTrackImage](type-aliases/IncomingTrackImage.md)
- [InputId](type-aliases/InputId.md)
- [Mp4InputDurations](type-aliases/Mp4InputDurations.md)
- [NotificationEvents](type-aliases/NotificationEvents.md)
- [OpusEncoderPreset](type-aliases/OpusEncoderPreset.md)
- [OutgoingTrackData](type-aliases/OutgoingTrackData.md)
- [OutputId](type-aliases/OutputId.md)
- [Overflow](type-aliases/Overflow.md)
- [Override](type-aliases/Override.md)
- [Peer](type-aliases/Peer.md)
- [PeerAdded](type-aliases/PeerAdded.md)
- [PeerConnected](type-aliases/PeerConnected.md)
- [PeerCrashed](type-aliases/PeerCrashed.md)
- [PeerDeleted](type-aliases/PeerDeleted.md)
- [PeerDisconnected](type-aliases/PeerDisconnected.md)
- [PeerId](type-aliases/PeerId.md)
- [PeerMetadataUpdated](type-aliases/PeerMetadataUpdated.md)
- [PeerOptions](type-aliases/PeerOptions.md)
- [PeerStatus](type-aliases/PeerStatus.md)
- [PeerType](type-aliases/PeerType.md)
- [Recording](type-aliases/Recording.md)
- [RecordingId](type-aliases/RecordingId.md)
- [RecordingSource](type-aliases/RecordingSource.md)
- [RecordingStatus](type-aliases/RecordingStatus.md)
- [RecordingStatusChanged](type-aliases/RecordingStatusChanged.md)
- [RegisterInput](type-aliases/RegisterInput.md)
- [RegisterOutput](type-aliases/RegisterOutput.md)
- [RendererId](type-aliases/RendererId.md)
- [RescaleMode](type-aliases/RescaleMode.md)
- [Room](type-aliases/Room.md)
- [RoomCrashed](type-aliases/RoomCrashed.md)
- [RoomCreated](type-aliases/RoomCreated.md)
- [RoomDeleted](type-aliases/RoomDeleted.md)
- [RoomId](type-aliases/RoomId.md)
- [RoomType](type-aliases/RoomType.md)
- [ServerNotification](type-aliases/ServerNotification.md)
- [StreamerConnected](type-aliases/StreamerConnected.md)
- [StreamerDisconnected](type-aliases/StreamerDisconnected.md)
- [SubscribeMode](type-aliases/SubscribeMode.md)
- [TemplateRecordingConfig](type-aliases/TemplateRecordingConfig.md)
- [TextStyle](type-aliases/TextStyle.md)
- [TextWeight](type-aliases/TextWeight.md)
- [TextWrapMode](type-aliases/TextWrapMode.md)
- [Track](type-aliases/Track.md)
- [TrackAdded](type-aliases/TrackAdded.md)
- [TrackForwarding](type-aliases/TrackForwarding.md)
- [TrackForwardingRemoved](type-aliases/TrackForwardingRemoved.md)
- [TrackId](type-aliases/TrackId.md)
- [TrackMetadataUpdated](type-aliases/TrackMetadataUpdated.md)
- [TrackRemoved](type-aliases/TrackRemoved.md)
- [TrackType](type-aliases/TrackType.md)
- [VadNotification](type-aliases/VadNotification.md)
- [VadStatus](type-aliases/VadStatus.md)
- [VerticalAlign](type-aliases/VerticalAlign.md)
- [VideoCodec](type-aliases/VideoCodec.md)
- [ViewDirection](type-aliases/ViewDirection.md)
- [ViewerConnected](type-aliases/ViewerConnected.md)
- [ViewerDisconnected](type-aliases/ViewerDisconnected.md)
- [WhipAudioEncoderOptions](type-aliases/WhipAudioEncoderOptions.md)
- [WhipInputTarget](type-aliases/WhipInputTarget.md)
- [AudioChannels](variables/AudioChannels.md)
- [AudioFormat](variables/AudioFormat.md)
- [AudioMixingStrategy](variables/AudioMixingStrategy.md)
- [AudioSampleRate](variables/AudioSampleRate.md)
- [HorizontalAlign](variables/HorizontalAlign.md)
- [OpusEncoderPreset](variables/OpusEncoderPreset.md)
- [Overflow](variables/Overflow.md)
- [PeerStatus](variables/PeerStatus.md)
- [RescaleMode](variables/RescaleMode.md)
- [RoomType](variables/RoomType.md)
- [ServerMessage](variables/ServerMessage.md)
- [SubscribeMode](variables/SubscribeMode.md)
- [TextStyle](variables/TextStyle.md)
- [TextWeight](variables/TextWeight.md)
- [TextWrapMode](variables/TextWrapMode.md)
- [VerticalAlign](variables/VerticalAlign.md)
- [VideoCodec](variables/VideoCodec.md)
- [ViewDirection](variables/ViewDirection.md)