> ## Documentation Index
> Fetch the complete documentation index at: https://docs.streampixel.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrating from v1

> Move a v1 StreamPixelApplication page to the Streampixel Web SDK v2 in one of two ways: keep your code with the streampixelsdk compatibility package, or move to the @streampixel/web-sdk API with before-and-after code and a check list.

Intermediate For a developer with a page built on the v1 SDK. After this page, that page runs on the current engine: either with its code unchanged, or rewritten for the v2 API.

> [!NOTE]
>
> **Public beta.** These pages describe version 2.0.0-beta.2 of `@streampixel/web-sdk`. Names and behaviour can still change before the stable 2.0.0 release. See the [changelog](https://docs.streampixel.io/resources/web-sdk-v2/changelog.md).

v1 is the `StreamPixelApplication` function of the `streampixelsdk` package. v2 is `@streampixel/web-sdk`.

> [!WARNING]
>
> Keep v1 in production until you have tested v2 with your own project.

## Choose your path

There are two ways to move a v1 page. Both end on the same engine.

| | Path 1: keep your code | Path 2: move to the v2 API |
| - | - | - |
| What you do | One install command. Your code stays as it is. | Rewrite the file that starts the stream, using this page. |
| Package | [`streampixelsdk`](https://www.npmjs.com/package/streampixelsdk) from npm: the v1 API, running on the v2 engine | `@streampixel/web-sdk` |
| You get | The v2 engine and its automatic updates, behind the v1 names | The same, plus the v2 API: typed states and errors, your own screens, new features |
| Choose it when | You want the page on the current engine now, with no rewrite | You are working on the page anyway, or want v2 features |

Why move: v1 is no longer developed. Fixes and new features arrive in v2, whose engine updates without a reinstall and recovers from more network problems.

## Before you start

These three checks apply to both paths. None of them needs code.

### Check the access setting of each project

Your page follows the access setting of the project in the dashboard:

| Project access in the dashboard | What your page does |
| - | - |
| Public | Streams. |
| Password | Waits for the password (state `awaitingPassword`). `@streampixel/ui` draws the password screen. |
| Single sign-on | Sends the viewer to the sign-in page. |
| Your app only (not available yet) | Needs a ticket from your server. |

Check each project's access setting before you move its page, so that a password or sign-in screen does not surprise your viewers. If you put a password on a project only to protect its share link, and your site has its own sign-in, **Your app only** (not available yet) is the mode for you (see [Access](#access)).

### The allowed-domains list

The platform checks the project's allowed-domains list when the page connects. It compares **the exact origin** of the page: scheme, host and port.

| Listed | Page | Result |
| - | - | - |
| `example.com` | `https://www.example.com` | Not the same origin today. Handling of `www.` is being fixed on the platform. |
| `example.com` | `https://app.example.com` | Refused: list each origin you use. |
| `*.example.com` | any | Do not rely on wildcard entries: list each origin. |
| (your domains) | `http://localhost:3000` | Do not assume it is allowed: test your local address. |

A page on an origin that is not allowed is refused when it connects: the session ends with code `1008`. If your project has a list, test the page on its real domain before going live.

### Content-Security-Policy

v1 was one bundle. v2 downloads its engine from Streampixel's servers when the stream starts, and talks to different hosts. If your site sends a Content-Security-Policy header:

```text theme={"dark"}
script-src  https://js.streampixel.io https://js-backup.streampixel.io;
connect-src https://*.streampixel.io wss://*.streampixel.io;
```

Add `wss://*.livekit.cloud https://*.livekit.cloud` to `connect-src` if you use chat. Entries that only v1 needed can be removed. If the engine cannot be downloaded, the stream does not start (`create()` rejects with `EngineLoadError`); there is no copy inside the package. The full list is under [Content-Security-Policy](https://docs.streampixel.io/resources/web-sdk-v2/installation.md#content-security-policy).

## The two paths, step by step

> [tab] Path 1: keep your code
>
> **1. Install the compatibility package**
>
> ```bash theme={"dark"}
> npm install streampixelsdk@next
> ```
>
> It replaces the v1 package of the same name.
>
> **2. Leave your code as it is**
>
> Imports and calls stay the same:
>
> ```js theme={"dark"}
> import { StreamPixelApplication } from 'streampixelsdk';
>
> const { appStream, pixelStreaming, queueHandler, UIControl, reconnectStream } =
>   await StreamPixelApplication({ appId: 'YOUR_PROJECT_ID', AutoConnect: true });
>
> appStream.onVideoInitialized = () => {
>   document.getElementById('stream').appendChild(appStream.rootElement);
> };
> ```
>
> **3. Check what is different**
>
> Read [What is different](#what-is-different) below against your page.
>
> **4. Build, test and release**
>
> Build the page and test it once with your own project before you release it.
>
> > [!TIP]
> >
> > The stream starts in your page as before. If the project is set to password or single sign-on, the viewer sees that screen first.

> [tab] Path 2: move to the v2 API
>
> **1. Install the v2 packages**
>
> ```bash theme={"dark"}
> npm uninstall streampixelsdk
> npm install @streampixel/web-sdk @streampixel/ui
> ```
>
> **2. Replace the start call**
>
> `StreamPixelApplication(...)` becomes `Streampixel.create(...)` with a `container`. See [Start a stream](#start-a-stream) and [Settings](#settings).
>
> **3. Add the screens**
>
> v1 drew its own screens. In v2, `mountUI(stream, { container })` draws them. See [The screens v1 drew for you](#the-screens-v1-drew-for-you).
>
> **4. Move messages and controls**
>
> Messages move to the `stream` object. See [Messages to and from your application](#messages-to-and-from-your-application) and [Controls](#controls).
>
> **5. Clean up and test**
>
> Use `signal` in React effects and `destroy()` before a new `create()`. Then work through the [check list](#check-list).
>
> > [!TIP]
> >
> > The loading screen of `@streampixel/ui` appears, then the stream. When the session ends, the end message appears.

## Keep your code: the compatibility package

`streampixelsdk@next` is the v1 API (`StreamPixelApplication`) running on the v2 engine. A page written for v1 keeps its code. Underneath, every session is a v2 session: it is opened with a session ticket, it follows the project's access setting, and it runs the engine that Streampixel serves and updates.

The compatibility package receives fixes, not new features. New features arrive in the v2 API.

### What you get

* **Access screens built in.** A password project asks for its password, and a single sign-on project sends the viewer to sign in, with no code from you.
* **A self-updating engine.** Fixes to connection, recovery and telemetry reach your page without a reinstall.
* **Recovery.** A dropped connection is repaired for up to 180 seconds (v1: 60 seconds).
* **A direct connection first.** The stream uses the relay only when the network needs it.

### What is different

Check each of these against your page.

| Area | With the compatibility package |
| - | - |
| Password and single sign-on projects | The project's access setting applies: the password screen is shown, or the viewer is sent to sign in. If your page has not placed `appStream.rootElement` yet, the password screen is shown over the page until the password is accepted. |
| Allowed domains | The platform checks the project's list against the exact origin of the page. A page on another origin hears that the session ended. See [The allowed-domains list](#the-allowed-domains-list). |
| A start that fails | The five objects are returned, and the failure is reported as a session that ended at once: `appStream.onDisconnect` and `reconnectStream`'s `disconnected`. In v1 the function resolved to `null`. |
| `disconnected` | Fires once, when the session has really ended. The same holds for the `webRtcDisconnected` and `webRtcFailed` events of `pixelStreaming`. In v1 it fired on every socket close. |
| Recovery | Tries for 180 seconds. `reconnecting`, `retrying` and `connected` keep their order. |
| `forceTurn` left out | Direct when the network allows it, relay when it does not. Pass `forceTurn: true` to keep the v1 behaviour (relay only). |
| `minQP`, `maxQP` | Ignored, with a console warning. They are set in the dashboard. |
| Resolution | Never above the project's maximum stream quality. |
| `emitConsoleCommand()` | Returns `false` unless the application allows console commands. |
| `pixelStreaming.reconnect()` | Starts a new session and reports it as a reconnect. |
| Screens | Drawn by `@streampixel/ui`. `appStream.showTextOverlay()` and the other overlay functions draw nothing, with a console warning. |
| A shared-session viewer without a `streamerId` | Reported as a start that failed. |

> [accordion] What stays the same
>
> `StreamPixelApplication(settings)` resolves to the same five objects.
>
> | Object | What works as in v1 |
> | - | - |
> | `appStream` | `rootElement`, `stream`, `uiFeaturesElement`, `statsPanel`, and the `onVideoInitialized` and `onDisconnect` functions your page assigns |
> | `pixelStreaming` | `connect()`, `reconnect()`, `disconnect()`, `addEventListener()`, `removeEventListener()`, `addResponseEventListener()`, `removeResponseEventListener()`, `emitUIInteraction()`, `emitConsoleCommand()`, `sendTextboxEntry()`, `play()`, `toggleXR()`, `unmuteMicrophone()`, `muteMicrophone()`, `unmuteCamera()`, `muteCamera()`, `videoElementParent` |
> | `queueHandler(callback)` | The callback receives `{ message: 'You are in Queue', position }` |
> | `UIControl` | `toggleAudio()`, `toggleHoveringMouse()`, `handleResMax()`, `getStreamStats()`, `getResolution()`, `parseStatistics()` |
> | `reconnectStream` | `on(event, callback)` with the events `reconnecting`, `retrying`, `connected`, `disconnected` and `failed` |
>
> Also exported, with their v1 names:
>
> * `StreamPixelVoiceChat`: the same constructor and methods.
> * `Flags`, `NumericParameters`, `TextParameters` and `ControlSchemeType`: the setting names of the Pixel Streaming library, as plain values.
>
> The stream-state messages that v1 posted to an embedding page are posted in the same shape. Page styles that hid a v1 screen by its id, such as `#afkOverlay { display: none }`, still hide the screen that stands for it.

> [accordion] Options, and the new v2 option
>
> Every v1 option is accepted. An option you leave out follows the project's dashboard setting.
>
> | v1 option | In the compatibility package |
> | - | - |
> | `AutoConnect` | `true` connects at once. Otherwise the "click to start" screen is shown, and `pixelStreaming.connect()` also starts the stream. |
> | `streamerId` | Kept. Only letters, digits, `_` and `-` are allowed: other characters are replaced by `_`, with a console warning. |
> | `sfuHost`, `sfuPlayer` | Kept: a shared session as host, or as viewer of the host with the same `streamerId`. |
> | `primaryCodec`, `fallBackCodec` | Kept: `AV1`, `H264`, `VP9` or `VP8`. Another value is ignored, with a console warning. |
> | `minBitrate`, `maxBitrate` | Kept, in kilobits per second. |
> | `minQP`, `maxQP` | Ignored, with a console warning. |
> | `showResolution` | Kept: decides whether `UIControl.getResolution()` returns a list. |
>
> One option is new. `v2` passes [v2 options](https://docs.streampixel.io/resources/web-sdk-v2/options.md) to the engine as they are, on top of the translated v1 options. Use it for what v1 could not express:
>
> ```js highlight={4-7} theme={"dark"}
> await StreamPixelApplication({
>   appId: 'YOUR_PROJECT_ID',
>   AutoConnect: true,
>   v2: {
>     engine: { channel: 'beta' },          // try the next engine release
>     launchParams: { level: 'showroom' },  // values for your Unreal application
>   },
> });
> ```
>
> `container` and `signal` are set by the package and cannot be passed.

> [accordion] Voice and text chat
>
> * `StreamPixelVoiceChat` needs the stream: call `StreamPixelApplication` first. `join()` waits for the stream, and for a password that is still being typed.
> * The project must have chat switched on in the dashboard.
> * A room belongs to the project. A room name equal to the project ID is the project's room; any other name is a room inside the project. A v2 room is not the v1 room of the same name.
> * `getToken()` throws. The engine obtains the room token when `join()` runs.

> [accordion] What the package cannot cover
>
> * **The classes of the Pixel Streaming library are not exported.** `Config`, `PixelStreaming`, `Application`, the overlay classes and the settings panel are not part of the package. A page that built its own `PixelStreaming` object needs the v2 API.
> * **`pixelStreaming` is a stand-in.** The engine builds a new library object whenever it rebuilds the connection, so the package returns one stable object that forwards to the live one. Do not keep references to its inner objects across a reconnect.
> * **Statistics.** `getStreamStats()` returns the v1 keys that the library fills. `Audio Bitrate (kbps)`, `Audio codec` and `Players` are present only when the library has a value for them.
> * **The engine is not in your bundle.** It is loaded from Streampixel's servers when the stream starts. A page that must work without access to `js.streampixel.io` cannot use this package.

## Move to the v2 API

The rest of this page maps v1 to v2, topic by topic. In each pair of code blocks, choose **v1** or **v2**: your choice applies to every pair on the page.

First replace the package:

```bash theme={"dark"}
npm uninstall streampixelsdk
npm install @streampixel/web-sdk @streampixel/ui
```

[`@streampixel/ui`](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays) draws the screens v1 drew by itself (see [The screens v1 drew for you](#the-screens-v1-drew-for-you)). Without a bundler, the core is also available from a script tag (`https://js.streampixel.io/v2/loader.js`, global `StreampixelSDK`); `@streampixel/ui` and chat are npm only.

## Start a stream

```js v1 theme={"dark"}
import { StreamPixelApplication } from 'streampixelsdk';

const { appStream, pixelStreaming, queueHandler, UIControl, reconnectStream } =
  await StreamPixelApplication({ appId: 'PROJECT_ID', AutoConnect: true });

appStream.onVideoInitialized = () => {
  document.getElementById('stream').append(appStream.rootElement);
};
```

```ts v2 theme={"dark"}
import { Streampixel, AuthError, EngineLoadError } from '@streampixel/web-sdk';
import { mountUI } from '@streampixel/ui';

const container = document.getElementById('stream')!; // give it a width and a height

try {
  const stream = await Streampixel.create({ appId: 'PROJECT_ID', container });
  mountUI(stream, { container }); // loading, password, "Click to start", idle warning, text input, end message
} catch (err) {
  if (err instanceof AuthError) showMessage(`${err.kind}: ${err.message}`);          // 'project-offline', 'project-not-found', …
  else if (err instanceof EngineLoadError) showMessage('The player could not be loaded.');
  else throw err;
}
```

| v1 | v2 |
| - | - |
| Five returned objects | One object, `stream`. |
| Returned `null` or `{}` when it could not start | `create()` throws: `AuthError` (with a `kind`), `EngineLoadError`, or `TypeError` for a wrong option. |
| One stream per page (a second call returned `{}`) | Any number. Call `stream.destroy()` before starting another stream in the same container. |
| You appended `appStream.rootElement` | You pass `container`; the SDK puts the video in it. The container must be an element with a width; see [Quick start](https://docs.streampixel.io/resources/web-sdk-v2/quick-start.md). |
| `AutoConnect: false`, then `pixelStreaming.connect()` | `create()` always starts the stream. Call `create()` when the viewer presses your button (below). |
| `pixelStreaming.reconnect()`, "click to restart" | `ended` is final. Call `stream.destroy()`, then `create()` again, and attach your listeners again. |

To start on a button press:

```ts theme={"dark"}
document.getElementById('play')!.onclick = async () => {
  const stream = await Streampixel.create({ appId: 'PROJECT_ID', container });
  mountUI(stream, { container });
};
```

> [accordion] React: pass a signal instead of calling disconnect()
>
> v1 examples called `disconnect()` in the effect cleanup. In v2 pass a `signal` and abort it: without it, React StrictMode's double effect (or a fast unmount) leaves a session streaming in the background. [Quick start](https://docs.streampixel.io/resources/web-sdk-v2/quick-start.md) has a full hook.
>
> ```tsx highlight={11,15-18} theme={"dark"}
> import { useEffect, useRef } from 'react';
> import { Streampixel } from '@streampixel/web-sdk';
> import { mountUI, type MountedUI } from '@streampixel/ui';
>
> export function Stream({ appId }: { appId: string }) {
>   const ref = useRef<HTMLDivElement>(null);
>
>   useEffect(() => {
>     const container = ref.current;
>     if (!container) return;
>     const ac = new AbortController();
>     let ui: MountedUI | undefined;
>
>     Streampixel.create({ appId, container, signal: ac.signal })
>       .then((stream) => { ui = mountUI(stream, { container }); })
>       .catch((err) => { if (err.name !== 'AbortError') showError(String(err)); });
>
>     return () => {
>       ui?.destroy(); // the UI first
>       ac.abort();    // before create() resolves: nothing starts. After: the stream is destroyed.
>     };
>   }, [appId]);
>
>   return <div ref={ref} style={{ width: '100%', height: '100%' }} />;
> }
> ```

## Settings

| v1 | v2 |
| - | - |
| `appId` | `appId`. (`projectId` is accepted too, with a console warning.) |
| `AutoConnect` | Removed: `create()` always connects. |
| `streamerId` | `advanced: { streamerId }`. Letters, digits, `_` and `-` only. v2 connects as `<streamerId>_<projectId>`. |
| `sfuHost: 'true'` | `shared: { role: 'host' }` (see [Shared sessions](#shared-sessions)) |
| `sfuPlayer: 'true'` | `shared: { role: 'viewer', hostStreamerId }` (see [Shared sessions](#shared-sessions)) |
| `forceTurn: true` | `advanced: { iceTransportPolicy: 'relay' }`. v1 forced the relay unless you turned it off; v2 does not (see [Behaviour that changed](#behaviour-that-changed)). |
| `primaryCodec`, `fallBackCodec` | `codec: { primary, fallback }`. `fallback` is `'H264'` or `'VP8'`. |
| `maxStreamQuality` | `resolution: { max }`. In v1 it only shortened the picker list; in v2 it is a real upper limit. |
| `startResolution`, `startResolutionMobile`, `startResolutionTab` | `resolution: { start, mobileStart, tabletStart }`. The `'360p (640x360)'` preset is written `{ width: 640, height: 360 }`. |
| `resolutionMode: 'Fixed Resolution Mode'` / `'Dynamic Resolution Mode'` / `'Crop on Resize Mode'` | `resolution: { mode: 'fixed' }` / `'dynamic'` / `'crop'` |
| `minBitrate`, `maxBitrate` | `bitrate: { min, max }` in **kilobits per second**: 20 Mbps is `20_000`. The v1 pages called these Mbps; give v2 the rate you actually want. |
| `minQP`, `maxQP` | No option. Set in the dashboard. |
| `mouseInput`, `keyBoardInput`, `touchInput`, `hoverMouse`, `gamepadInput`, `xrInput`, `fakeMouseWithTouches` | `input: { mouse, keyboard, touch, hover, gamepad, xr, fakeMouseWithTouches }` |
| `useMic`, `useCamera` | `media: { mic, camera }` |
| `afktimeout` | `afk: { timeoutSec }`. Only shorter than the dashboard's value (see [Behaviour that changed](#behaviour-that-changed)). |
| `showResolution` | Removed. Build a picker with `stream.allowedResolutions` and `stream.setResolution()`. |

What you leave out comes from the project's dashboard settings. An option name v2 does not know is ignored with a console warning, so a v1 name left in place does not fail silently. Every v2 option is on [Options](https://docs.streampixel.io/resources/web-sdk-v2/options.md).

## Messages to and from your application

The method names of Epic's Pixel Streaming library that your v1 code calls are on the v2 `stream` object. The shortest move changes only the object in front of them:

```ts theme={"dark"}
appStream.stream.emitUIInteraction({ type: 'setColor', value: 'red' });        // [!code --]
pixelStreaming.emitConsoleCommand('stat fps');                                 // [!code --]
pixelStreaming.addResponseEventListener('handle_responses', onResponse);      // [!code --]
stream.emitUIInteraction({ type: 'setColor', value: 'red' });                  // [!code ++]
stream.emitConsoleCommand('stat fps');                                         // [!code ++]
stream.addResponseEventListener('handle_responses', onResponse);              // [!code ++]
```

> [!TIP]
>
> **Coming from Epic's Pixel Streaming library?** Its method names work on the stream object too: `emitUIInteraction()`, `emitConsoleCommand()` and `addResponseEventListener()`. They are the same calls as `send()`, `consoleCommand()` and `on('ueMessage')`. Use whichever you know. See [Talk to your Unreal app](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md).

The same three lines with the SDK's own names:

```ts theme={"dark"}
stream.send({ type: 'setColor', value: 'red' });        // returns false when it was not sent
stream.consoleCommand('stat fps');                      // returns false when it was not sent
stream.on('ueMessage', (response) => {
  const data = typeof response === 'string' && response.trim().startsWith('{') ? JSON.parse(response) : response;
  console.log(data);
});
```

With either set of names, sending returns `false` when the message was not handed to the stream (before the video is up, while reconnecting, after the end). Nothing is queued. See [Talk to your Unreal app](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md).

## The screens v1 drew for you

v1 drew its own connecting screen, queue text, idle countdown, text box for phones and "Disconnected" screen. **The v2 core draws only the video.** A page moved to the core alone has no idle warning, no end message, no "Click to start" when the browser blocks autoplay, and text fields in the application stop working on phones.

The simplest move is `mountUI(stream, { container })` from `@streampixel/ui`, which draws all of these:

| v1 screen | `@streampixel/ui` part (option name) |
| - | - |
| Connecting screen, queue text | `loading`: the project's logo, banner and loading texts, queue position, reconnecting status |
| (none) | `password` |
| Play overlay | `playPrompt`: "Click to start" when the browser blocks autoplay |
| Idle countdown | `afk` |
| Text box for phones | `osk` |
| "Disconnected code:N. Click To Restart" | `disconnect`: the end message in plain language and a button |
| Stats panel, settings | `controls`: sound, fullscreen, a statistics popup |
| (none) | `files`, `links`, `tcpToast`: files and links the application sends, and the warning when UDP is blocked |

CSS written for v1's elements (`#afkOverlay`, `#connectOverlay`, `#infoOverlay`, `#uiFeatures`) matches nothing in v2; `@streampixel/ui` uses `spx-*` class names. `appStream.showDisconnectOverlay()`, `appStream.showTextOverlay()` and `appStream.statsPanel` have no v2 call.

To draw a screen yourself, switch that part off and use the events:

```ts theme={"dark"}
mountUI(stream, { container, loading: false, disconnect: false });
```

### Loading, queue, reconnecting, ended

```js v1 theme={"dark"}
pixelStreaming.addEventListener('webRtcConnecting', () => setStatus('Connecting…'));
pixelStreaming.addEventListener('webRtcConnected', () => setStatus('Loading…'));
appStream.onVideoInitialized = () => hideLoading();
queueHandler((msg) => setStatus(`In queue: ${msg.position}`));
reconnectStream.on('state', (d) => {
  if (d.status === 'reconnecting') setStatus('Reconnecting…');
  if (d.status === 'failed') setStatus('Could not reconnect');
});
```

```ts v2 theme={"dark"}
// one state event
stream.on('state', (s) => {
  switch (s.kind) {
    case 'awaitingPassword': break;                                     // your own password form, or mountUI's
    case 'connecting':   setStatus('Connecting…'); break;
    case 'queued':       setStatus(`In queue: ${s.position}`); break;
    case 'streaming':    hideLoading(); break;
    case 'awaitingPlay': showStartButton(() => stream.play()); break;   // the browser blocked autoplay
    case 'reconnecting': setStatus('Reconnecting…'); break;             // automatic, up to 180 s
    case 'recovering':   setStatus('Restarting the stream…'); break;
    case 'ended':        setStatus(s.message); break;                   // also s.code, s.reason, s.endKind
  }
});
stream.on('progress', ({ stage }) => setStep(stage));                   // 'offer', then 'answer', then 'connected'
```

| v1 | v2 |
| - | - |
| `webRtcConnecting`, `webRtcSdp`, `webRtcConnected`, `streamLoading` | state `connecting` (or `queued`); `progress` for the steps |
| `playStream`, `appStream.onVideoInitialized` | state `streaming` (or `awaitingPlay` when autoplay is blocked) |
| `webRtcDisconnected`, `webRtcFailed` | state `reconnecting` or `recovering` (automatic), or `ended` |
| `queueHandler(fn)` | `stream.on('queue', ({ position, message }) => …)`, or state `queued` |
| `reconnectStream` `reconnecting` / `retrying` | state `reconnecting` |
| `reconnectStream` `connected` | state `streaming` |
| `reconnectStream` `failed` (code 4007) | `ended` with `code === 4007` |
| `reconnectStream` `disconnected` | `ended` |
| `statsReceived` | `stats` |
| (none) | `ended` `{ code, reason, endKind, message }`, `session`, `stalled`, `autoplayBlocked`, `openUrl`, `file`, `fileProgress`, `screenshot`, `relayFallback` |

All listeners added with `stream.on()` are removed when the session ends. Do not keep a reference to the `<video>` element or to `stream.pixelStreaming`: v2 replaces both when it rebuilds the connection. Every state and event is on [Events and states](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states.md).

### Idle warning

```js v1 theme={"dark"}
pixelStreaming.addEventListener('afkWarningActivate', (e) => showWarning(e.data.countDown, e.data.dismissAfk));
pixelStreaming.addEventListener('afkWarningUpdate', (e) => updateWarning(e.data.countDown));
pixelStreaming.addEventListener('afkWarningDeactivate', () => hideWarning());
pixelStreaming.addEventListener('afkTimedOut', () => showMessage('Session ended'));
```

```ts v2 theme={"dark"}
stream.on('afkWarning', (w) => {
  if (w.kind === 'countdown') showIdleWarning(w.secondsRemaining, w.dismiss);
  else hideIdleWarning();
});
stream.on('ended', (e) => {
  if (e.endKind === 'afk') showMessage(e.message);
});
```

### Text input on phones

v1 opened a text box by itself when the application asked for the keyboard. In v2, `mountUI` does it, or you do:

```ts theme={"dark"}
stream.on('osk', ({ contents }) => openTextInput(contents, (text) => stream.sendTextboxEntry(text)));
stream.on('oskHide', () => closeTextInput());
```

## Controls

```js v1 theme={"dark"}
UIControl.toggleAudio();
UIControl.handleResMax('1920x1080');
UIControl.toggleHoveringMouse(true);
const options = UIControl.getResolution();
const stats = UIControl.getStreamStats();      // stats['Framerate'], stats['Net RTT (ms)'] …
```

```ts v2 theme={"dark"}
const audible = stream.toggleAudio();            // true when the sound is now on; or stream.setMuted(true / false), stream.muted
const sentSize = stream.setResolution(1920, 1080); // { width, height } as sent, or null when nothing was sent
stream.setHoverMouse(true);
buildPicker(stream.allowedResolutions);          // ['360p (640x360)', …] up to the project's maximum
stream.on('stats', (s) => {                      // every second
  console.log(s.fps, s.latencyMs, s.bitrateKbps, s.resolution, s.codec,
    s.framesDecoded, s.framesDropped, s.packetsLost, s.bytesReceived, s.relayTransport, s.avgQp);
});
```

| v1 | v2 |
| - | - |
| `UIControl.toggleAudio()` | `stream.toggleAudio()`, `stream.setMuted(bool)`, `stream.muted` |
| `appStream.stream._webRtcController.streamController.audioElement`, `video.muted` | `stream.setMuted(bool)` |
| `UIControl.handleResMax('1920x1080')` | `stream.setResolution(1920, 1080)`. Never above the project's maximum. |
| `UIControl.toggleHoveringMouse(on)` | `stream.setHoverMouse(on)` |
| `UIControl.getResolution()` | `stream.allowedResolutions` (always the list; v1 returned nothing when the dashboard hid the picker) |
| `UIControl.getStreamStats()` | the `stats` event: `Framerate` → `fps`, `Net RTT (ms)` → `latencyMs`, `Video Bitrate (kbps)` → `bitrateKbps`, plus `resolution`, `codec`, `framesDecoded`, `framesDropped`, `packetsLost`, `bytesReceived`, `relayTransport`, `avgQp`. There is no v2 field for audio codec, audio bitrate or duration. |

Every method is on [Stream methods and properties](https://docs.streampixel.io/resources/web-sdk-v2/stream-api.md).

### Microphone and camera to the application

```js v1 theme={"dark"}
pixelStreaming.unmuteMicrophone(true);
pixelStreaming.unmuteCamera(true);
```

```ts v2 theme={"dark"}
const withMic = await Streampixel.create({ appId: 'PROJECT_ID', container, media: { mic: true } });
showMicButton(async () => {
  const live = await withMic.setMicrophone(true);   // false to switch it off again; setCamera(on) for the camera
  console.log('microphone live:', live);
});
```

The microphone or camera must be allowed when the stream starts (`media`, or the dashboard). With it allowed, the browser asks for permission once the video is up, and `setMicrophone(on)` / `setCamera(on)` switch it afterwards.

> [!WARNING]
>
> Do not call `unmuteMicrophone()` or `unmuteCamera()` on `stream.pixelStreaming`: they make Epic's library reconnect on its own, against the SDK.

## Access

What your page does for each access setting:

| Project access | What to do |
| - | - |
| Password | With `mountUI`, nothing: the password screen is drawn. With your own form: `create()` resolves in the state `awaitingPassword`; call `stream.submitPassword(typed)`. A wrong password comes back as `awaitingPassword` with `wrong: true`; too many attempts as `locked: true` (and `hard: true` when every attempt is refused for now). See [Access](https://docs.streampixel.io/resources/web-sdk-v2/access.md). |
| Single sign-on | Nothing: the SDK sends the viewer to the sign-in page and finishes when they come back. A refused sign-in rejects `create()` with `AuthError` kind `sso-failed`. |
| Your app only (not available yet) | Your server requests a ticket with the project's server key; your page passes the whole response as `auth: { mode: 'ticket', ticket }`. See [Your app only](https://docs.streampixel.io/resources/web-sdk-v2/access.md#your-app-only). |

> [!WARNING]
>
> Never put a project password in your page's code: anyone can read it there.

## Shared sessions

A shared session runs one application for several people: a host who controls it and viewers who watch.

```js v1 theme={"dark"}
// host and viewers used the same streamerId
await StreamPixelApplication({ appId, AutoConnect: true, sfuHost: 'true', streamerId: 'room1' });
await StreamPixelApplication({ appId, AutoConnect: true, sfuPlayer: 'true', streamerId: 'room1' });
```

```ts v2 theme={"dark"}
const host = await Streampixel.create({ appId, container, shared: { role: 'host' } });
sendToViewers(host.streamerId);                  // the id viewers need
await Streampixel.create({ appId, container, shared: { role: 'viewer', hostStreamerId } });
```

**`hostStreamerId` must be exactly the host's `stream.streamerId`.** In v2 that id is `<id>_<projectId>`, not the bare id. Porting `streamerId: 'room1'` to both sides gives a viewer that never joins. If both pages already agree on a room name, keep it like this:

```ts theme={"dark"}
// host
await Streampixel.create({ appId, container, shared: { role: 'host' }, advanced: { streamerId: 'room1' } });
// viewer: the host's id is "<room>_<appId>"
await Streampixel.create({ appId, container, shared: { role: 'viewer', hostStreamerId: `room1_${appId}` } });
```

| Topic | v2 |
| - | - |
| Room names | Letters, digits, `_` and `-` only. |
| One host per room | Whoever opens a room first is its host. A second host for the same room is refused: `create()` rejects with `AuthError` kind `shared-room-taken`. The host's own tab can come back to its room after a reload. |
| Host page reload | Without a room name of your own, the host returns to the same room after a reload of its tab. |
| Viewers | Cannot control the application and are not disconnected for being idle. |
| Host's application restarts | Viewers wait up to 10 minutes (state `reconnecting` with `waitingForHost: true`). |
| "Your app only" projects (not available yet) | The host's ticket must ask for the host role. See [Shared sessions](https://docs.streampixel.io/resources/web-sdk-v2/shared-sessions.md). |

## Voice and text chat

```js v1 theme={"dark"}
import { StreamPixelVoiceChat } from 'streampixelsdk';
const chat = new StreamPixelVoiceChat('room-1', userName, true, avatar, true);
await chat.join();
chat.onMessage((m) => show(m.from, m.text));
chat.onParticipantUpdate((p) => list(p.remoteParticipants));
chat.toggleMic();
chat.muteSelected(id);
```

```ts v2 theme={"dark"}
import { VoiceChat } from '@streampixel/web-sdk/voice';

const chat = await VoiceChat.for(stream, { userName, avatar, voice: true, roomId: 'room-1' });
await chat.join();
chat.on('message', (m) => show(m.from, m.text));
chat.on('roster', (r) => list(r.remoteParticipants));
await chat.toggleMic(false);                     // pass the state you want
chat.setRemoteAudio(false, participantId);       // without an id: everyone
```

| v1 | v2 |
| - | - |
| `new StreamPixelVoiceChat(room, user, voiceChat, avatar, micStart)` | `await VoiceChat.for(stream, { userName, avatar, voice, roomId })` |
| A room name you choose | The room belongs to the project. `roomId` is a room inside it; without it everyone on the project shares one room. A v2 room is not the v1 room of the same name. |
| No project setting | Chat must be switched on for the project; otherwise `VoiceChat.for()` rejects. |
| `micStart` | `voice: true` |
| `toggleMic()` | `toggleMic(enable)`, resolves to whether it took effect; also `toggleCamera(enable)` |
| `onMessage(fn)`, `onParticipantUpdate(fn)` | `on('message', fn)`, `on('roster', fn)`; also `typing`, `deviceError`. Any number of listeners. |
| `muteAllRemote()`, `unmuteAllRemote()`, `muteSelected(id)`, `unmuteSelected(id)` | `setRemoteAudio(enabled, id?)` |

See [Voice chat](https://docs.streampixel.io/resources/web-sdk-v2/voice-chat.md).

## Pixel Streaming names that work in v2

These names of Epic's Pixel Streaming library are on the v2 `stream` object. They are equal to the SDK's own names: use whichever you know.

```ts theme={"dark"}
stream.emitUIInteraction({ type: 'setColor', value: 'red' });
stream.emitConsoleCommand('stat fps');
stream.addResponseEventListener('handle_responses', (response) => console.log(response));
stream.addEventListener('playStream', () => console.log('playing'));
```

| On `stream` | Note |
| - | - |
| `emitUIInteraction(data)`, `emitConsoleCommand(cmd)` | The same calls as `send()` and `consoleCommand()`. |
| `addResponseEventListener(name, fn)`, `removeResponseEventListener(name)` | The same messages as `on('ueMessage')`, as a string. |
| `addEventListener(epicEventName, fn)`, `removeEventListener(epicEventName, fn)` | Epic's events by their original names. Your listeners are attached again when the SDK rebuilds the connection. |
| `pixelStreaming` | Epic's `PixelStreaming` object. It is replaced when the connection is rebuilt: read it each time. |

> [!NOTE]
>
> Through `addEventListener`, `webRtcDisconnected` fires on every signalling drop, including the ones v2 recovers from by itself. A v1 handler that shows "Disconnected" on that event will show it during a reconnect that succeeds. Drive your screens from the `state` event.

## What has no equivalent

| v1 | In v2 |
| - | - |
| Epic's classes exported by `streampixelsdk` (`Config`, `Flags`, `PixelStreaming`, `Application`, `AFKOverlay`, `SettingUI…`, `Logger`, …) | Not exported. `stream.pixelStreaming` is an instance, not the classes. |
| `appStream.showDisconnectOverlay()`, `appStream.showTextOverlay()`, `appStream.statsPanel`, `appStream.uiFeaturesElement` | No call. `@streampixel/ui` draws its own screens. |
| `pixelStreaming.connect()` with `AutoConnect: false`, `pixelStreaming.reconnect()` | No manual connect or reconnect. `create()` starts; `destroy()` then `create()` starts again. |
| `minQP`, `maxQP` options | Dashboard only. |
| The `stream-state` messages v1 posted to `window.parent` (`disconnected` with code 4007, `afkAbort`) | Nothing is posted. Post your own from the events (below). |
| Statistics for audio codec, audio bitrate and duration | Not in `StreamStats`. Epic's `statsReceived` event is still reachable with `stream.addEventListener('statsReceived', fn)`. |
| Mixpanel analytics | Removed. v2 reports to Streampixel's own telemetry only; no third-party tracker. |

```ts theme={"dark"}
stream.on('ended', ({ code, endKind }) => {
  window.parent.postMessage({ type: 'stream-state', value: 'disconnected', code, endKind }, 'https://your-site.example');
});
```

## Behaviour that changed

| Topic | v1 | v2 |
| - | - | - |
| Relay | Every session was forced through the TURN relay unless you set `forceTurn: false`. | Direct when the network allows it. Set `advanced: { iceTransportPolicy: 'relay' }`, or the project's "force TURN" setting, if you depend on relay-only (for example firewall rules written for the relay). |
| Reconnecting | 60 seconds, one retry every 5 seconds, signalling only. | 180 seconds, retries after about 1, 2, 4, 8 and then 15 seconds. The whole connection is rebuilt when needed. Viewers of a shared session wait 10 minutes. |
| No video | Not detected. | After 10 seconds without a frame the SDK starts one fresh session: a new application process, so its state is lost and `launchParams` are sent again. |
| Blocked network | Not detected. | The session ends after about 8 seconds with `endKind: 'network-blocked'` (code `4100`). |
| End codes | The server's close code, and `4007` when reconnecting failed. | The same, plus codes the SDK decides in the browser: `4100` to `4104`. See [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md#how-a-session-ends). |
| Idle time | The page's `afktimeout` was used as given. | Never longer than the dashboard's value; 600 seconds when neither is set; cannot be switched off. Raise it in the dashboard if you used a long value in code. |
| Resolution | `handleResMax` sent any size. | Never above the project's maximum stream quality. |
| The first click | Spent on activating the application's window. | Reaches the application. |
| Keyboard | Every key went to the application. | Keys typed into your page's own inputs are not sent to the application. |

## Check list

> [tab] Path 1: keep your code
>
> * [ ] Access setting of each project checked in the dashboard
> * [ ] Allowed-domains list checked against the exact origins of your pages, and tested
> * [ ] Content-Security-Policy updated, if you have one
> * [ ] `streampixelsdk@next` installed; imports and code unchanged
> * [ ] [What is different](#what-is-different) read against your page: `disconnected` handlers, a start that fails, overlay functions, `minQP` / `maxQP`
> * [ ] Relay: `forceTurn: true` if you depended on relay-only
> * [ ] Built and tested with your own project, on a phone and through a short network drop

> [tab] Path 2: move to the v2 API
>
> * [ ] Access setting of each project checked in the dashboard
> * [ ] Allowed-domains list checked against the exact origins of your pages, and tested
> * [ ] Content-Security-Policy updated, if you have one
> * [ ] `streampixelsdk` removed; `@streampixel/web-sdk` (and `@streampixel/ui`) installed
> * [ ] `StreamPixelApplication(...)` replaced by `Streampixel.create(...)` with a `container` that has a size
> * [ ] `mountUI` added, or your own screens for: loading, queue, password, "Click to start", idle warning, text input, end message
> * [ ] Messages moved to the `stream` object: Epic's names, or `stream.send()` and `stream.on('ueMessage')`
> * [ ] Cleanup: `signal` in React effects; `destroy()` before a new `create()`
> * [ ] Shared sessions: viewers receive the host's `stream.streamerId`
> * [ ] Relay: `advanced.iceTransportPolicy: 'relay'` if you depended on relay-only
> * [ ] Tested on a phone (text input, autoplay, a link or file from the application) and through a short network drop

## Next steps

> [card] [Quick start](https://docs.streampixel.io/resources/web-sdk-v2/quick-start.md)
>
> A real page on the v2 API, in plain JavaScript and in React.

> [card] [UI overlays](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays.md)
>
> The screens `@streampixel/ui` draws, and how to replace one.

> [card] [Options](https://docs.streampixel.io/resources/web-sdk-v2/options.md)
>
> Every option of `Streampixel.create()`.

> [card] [Stream methods and properties](https://docs.streampixel.io/resources/web-sdk-v2/stream-api.md)
>
> Everything on the stream object.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.