# React Native & Expo

> Join Synento calls from iOS and Android apps with @synento/react-native: the phone's camera and microphone, everyone else's video and audio, and replay.

`@synento/react-native` puts an iOS or Android app into the same Synento
sessions as browser participants. It publishes the phone's camera and microphone,
shows and plays everyone else, and replays recordings. A phone's call is recorded
exactly like a browser's: replay, MP4 export and transcripts work the same.

It has native code (hardware H.264, Opus, echo cancellation), so it needs an
**Expo development build** or a bare React Native app. It does not run in Expo Go.

## Requirements

| | |
|---|---|
| Expo | SDK 58 or later, or bare React Native 0.88+ with Expo modules installed (`npx install-expo-modules@latest`) |
| iOS | 16.4 or later (Expo SDK 58's minimum) |
| Android | 7.0 (API 24) or later. Opus needs Android 10; older devices send PCM audio |

## Install

```bash
npx expo install @synento/react-native
```

Add the config plugin to `app.json`. It writes the camera and microphone
permission prompts (iOS) and permissions (Android):

```json
{
  "expo": {
    "plugins": [
      ["@synento/react-native", {
        "cameraPermission": "Allow $(PRODUCT_NAME) to use your camera for video calls.",
        "microphonePermission": "Allow $(PRODUCT_NAME) to use your microphone for calls.",
        "backgroundAudio": true
      }]
    ]
  }
}
```

`backgroundAudio` keeps call audio going while the app is in the background.
It applies to iOS only (see [Known limits](#known-limits) for Android). The
camera always pauses in the background, because neither platform allows it.

Then build the app with its native code:

```bash
npx expo prebuild
npx expo run:ios      # or run:android
```

For an EAS development build instead, add the development client first:
`npx expo install expo-dev-client`, then `eas build --profile development`.

## Tokens come from your server

Your API key must never ship in an app. Your backend mints a connection token
for the user with `@synento/node` (or `POST /v1/sessions/{id}/connection`), and
the app fetches it. This is the same flow as the browser; see the
[web quickstart](https://synento.com/docs/examples/web-quickstart.md).

```typescript
// Your server
import { createSynentoClient, resolveWsUrl } from "@synento/node";

const synento = createSynentoClient(); // SYNENTO_API_KEY

app.post("/api/synento/token", async (req, res) => {
  const { sessionId, userId } = req.body; // check the user may join first
  const token = await synento.createConnectionToken(sessionId, { userId });
  res.json({
    token: token.accessToken,
    wsUrl: resolveWsUrl({ apiBaseUrl: "https://api.synento.com", sessionId, userId }),
  });
});
```

## Join a call

Create the session on your server first (`POST /v1/sessions`, or
`synento.createSession()` in `@synento/node`); the app only joins it.

```tsx
import {
  SynentoLocalPreview,
  SynentoProvider,
  SynentoVideoView,
  useConnectionState,
  useLocalCamera,
  useParticipants,
} from "@synento/react-native";
import { useEffect, useMemo, useRef, useState } from "react";
import { Button, Text, View } from "react-native";

// Called on every connect and reconnect, so tokens rotate.
function tokenFetcher(sessionId: string, userId: string) {
  return async () => {
    const res = await fetch("https://your.app/api/synento/token", {
      body: JSON.stringify({ sessionId, userId }),
      headers: { "Content-Type": "application/json" },
      method: "POST",
    });
    if (!res.ok) throw new Error(`Token request failed (${res.status})`);
    return res.json(); // { wsUrl, token }
  };
}

export function CallScreen({ sessionId, userId }: { sessionId: string; userId: string }) {
  const getToken = useMemo(() => tokenFetcher(sessionId, userId), [sessionId, userId]);
  return (
    <SynentoProvider getToken={getToken} userId={userId}>
      <Call />
    </SynentoProvider>
  );
}

function Call() {
  const { state, error } = useConnectionState();
  const participants = useParticipants();
  const camera = useLocalCamera();
  const [problem, setProblem] = useState<string | null>(null);

  // Publish once, when first connected. (A refused permission rejects.)
  const started = useRef(false);
  const { publish } = camera;
  useEffect(() => {
    if (state !== "connected" || started.current) return;
    started.current = true;
    publish().catch((e: Error) => setProblem(e.message));
  }, [state, publish]);

  return (
    <View style={{ flex: 1 }}>
      {(problem ?? error) ? <Text>{problem ?? error?.message}</Text> : null}
      {participants.map((id) => (
        <SynentoVideoView key={id} participantId={id} style={{ aspectRatio: 3 / 4 }} />
      ))}
      <SynentoLocalPreview style={{ height: 160, width: 120 }} />
      <Button
        title={camera.microphoneEnabled ? "Mute" : "Unmute"}
        onPress={() => camera.setMicrophoneEnabled(!camera.microphoneEnabled)}
      />
      <Button title="Flip camera" onPress={camera.flip} />
    </View>
  );
}
```

`camera.publish()` asks for camera and microphone permission if it has not been
granted, and rejects if the camera is refused. To ask earlier (say on an
onboarding screen), call `requestPermissions()`.

For a call without video, publish the microphone alone:
`useSynentoRoom().publishMicrophone()`.

## What is the same as the browser

The provider and hooks are the ones `@synento/react` uses, from the same code:
`useConnectionState()`, `useConnectionError()`, `useParticipants()`,
`useChat()`, `useMicState()` and `useSynentoRoom()`. `useAudioPlayback()` is
there too, and always reports `playing`: a phone needs no tap to start sound.
`<SynentoProvider autoConnect={false}>` waits for `room.connect()`, for a
lobby. The `video` option (`{ width, height, fps, bitrate }`) bounds what the
camera sends, as in the browser.

The room reconnects with a fresh token on its own, and refuses to retry after a
plan limit or a rejected token, exactly as in the browser. On a phone it also
reconnects when the app comes back after 25 seconds or more in the background or
asleep, because the server drops a participant it has not heard from for 30.

`useMicState()` reports `blocked` on a phone when the system has taken the
microphone (a phone call, Siri, another app) and returns to `sending` when it
gives it back.

## Components

| Component | Shows |
|---|---|
| `<SynentoVideoView participantId track resizeMode />` | A remote participant's camera (or, with `track="screen"`, a browser participant's screen share). `resizeMode` is `contain` (default: the whole picture, letterboxed) or `cover`. On Android a track draws in one view at a time: with two, the newest shows it |
| `<SynentoLocalPreview mirror resizeMode />` | Your own camera, mirrored by default. What is sent is never mirrored |

## Replay

A replay token plays a recorded session through the same views. Mint it with
`replay: true` (`createConnectionToken(sessionId, { userId, replay: true })`) and
add `replay=true` to the WebSocket URL your server returns. Don't publish in a
replay. `room.on("replayComplete", …)` fires when it reaches the end.

## Testing on simulators

The iOS Simulator has no camera. Publish a moving test pattern instead:
`camera.publish({ source: "testPattern" })`. The Android emulator's virtual
camera works as a real one.

## Checking delay

`room.getStats()` (from `useSynentoRoom()`) says how late each participant's
video arrives, how much of their audio is queued, and how much this phone has
waiting to send. Poll it about once a second for a diagnostics overlay. Video
delay is arrival minus capture time, so it includes the two devices' clock
difference (usually tens of ms); what matters is that it stays flat.

Two things make delay look worse than it is in testing: the iOS Simulator's
software encoder adds about 430 ms that an iPhone's or iPad's hardware encoder
does not, and Debug builds run JavaScript much more slowly than Release. Media
never passes through JavaScript, but the rest of your app does.

The browser SDK's `trackFrame` event is not emitted on React Native: media
never reaches JavaScript, which is what keeps it fast.

## How it sends media

The SDK sends exactly what the browser SDK sends: the same 720p bounding box in
the camera's own shape, the same bitrate rule, a keyframe every two seconds,
H.264 with its parameter sets on every keyframe, and Opus (or 16 kHz PCM) audio
stamped with its capture time. That is why a phone's recording replays and
exports with the same lip-sync as a browser's.

## Known limits

- **Screen sharing from a phone** is not supported. Phones show screen shares
  from browser participants.
- **iOS shows VP8/VP9 video as unsupported.** A browser that cannot encode H.264
  (some Firefox builds) sends VP8 or VP9, which iOS cannot decode: that tile
  says so. Android decodes them.
- **Expo Go** cannot load the native module. Use a development build.
- **Camera in the background**: it pauses, by iOS and Android rule.
- **Android in the background**: there is no foreground service yet, so
  Android gives the app silence instead of the microphone once it leaves the
  screen. Others hear you again when you return. (`backgroundAudio` is iOS only.)

## Testing with Jest

The package ships ES modules, which Jest does not transform by default. With
`jest-expo`, add it to `transformIgnorePatterns`, for example
`"node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@synento/.*)"`.
Its native module is not available under Jest: mock `@synento/react-native` in
component tests.
