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

# SmallWebRTCTransport

> A lightweight WebRTC transport for peer-to-peer connections with Pipecat

`SmallWebRTCTransport` enables peer-to-peer WebRTC connections between clients and your Pipecat application. It implements bidirectional audio and video streaming using WebRTC for real-time communication.

This transport is intended for lightweight implementations, particularly for local development and testing. It expects your Pipecat server to include the corresponding [`SmallWebRTCTransport` server-side](/api-reference/server/services/transport/small-webrtc) implementation.

## Usage

### Basic Setup

```javascript theme={null}
import { PipecatClient } from "@pipecat-ai/client-js";
import { SmallWebRTCTransport } from "@pipecat-ai/small-webrtc-transport";

const pcClient = new PipecatClient({
  transport: new SmallWebRTCTransport({
    // Optional configuration for the transport
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
  }),
  enableCam: false, // Default camera off
  enableMic: true, // Default microphone on
  callbacks: {
    // Event handlers
  },
});

await pcClient.connect({
  webrtcUrl: "/api/offer", // Your WebRTC signaling server endpoint
});
```

## API Reference

### Constructor Options

```typescript theme={null}
interface SmallWebRTCTransportConstructorOptions {
  iceServers?: RTCIceServer[];
  waitForICEGathering?: boolean;
  webrtcUrl?: string;
  audioCodec?: string;
  videoCodec?: string;
  mediaManager?: MediaManager;
}
```

#### Properties

<ParamField name="iceServers" type="RTCIceServer[]">
  Array of ICE server configurations for connection establishment. Default is `[{ urls: "stun:stun.l.google.com:19302" }]`.

  ```javascript theme={null}
  // Set custom ICE servers
  transport.iceServers = [
    { urls: "stun:stun.l.google.com:19302" },
    { urls: "stun:stun1.l.google.com:19302" },
  ];
  ```
</ParamField>

<ParamField name="waitForICEGathering" type="boolean" default="false">
  If `true`, the transport will wait for ICE gathering to complete before being
  considered `'connected'`.
</ParamField>

<ParamField name="webrtcUrl" type="string">
  URL of the WebRTC signaling server's offer endpoint. This endpoint may also be provided as part of `connect()`.

  Note: This field used to be called `connectionUrl` in versions prior to
  `1.2.0`.
</ParamField>

<ParamField name="audioCodec" type="string">
  Preferred audio codec to use. If not specified, your browser default will be
  used.
</ParamField>

<ParamField name="videoCodec" type="string">
  Preferred video codec to use. If not specified, your browser default will be
  used.
</ParamField>

<ParamField name="mediaManager" type="MediaManager" default="DailyMediaManager">
  The media manager to use for handling local audio and video streams. This
  should not be overridden unless you have a specific reason to use a different
  media manager. The default is `DailyMediaManager`, which is suitable for most
  use cases. Note that the `DailyMediaManager` does not use any of Daily's
  services, it simply takes advantage of vast media support provided by the
  Daily library.
</ParamField>

### TransportConnectionParams

```typescript theme={null}
export type SmallWebRTCTransportConnectionOptions = {
  webrtcUrl?: string;
};
```

On `connect()`, the `SmallWebRTCTransport` optionally takes a set of connection parameters. This can be provided directly to the `PipecatClient`'s `connect()` method or via a starting endpoint passed to the `PipecatClient`'s `startBotAndConnect()` method. If using an endpoint, your endpoint should return a JSON object matching the `SmallWebRTCTransportConnectionOptions` type, which currently expects a single `webrtcUrl` property.

<CodeGroup>
  ```typescript client theme={null}
  pcClient.startBotAndConnect({
    endpoint: '/api/start', // Your server endpoint to start the bot and return the webrtcUrl
  });
  // OR...
  pcClient.connect({
    webrtcUrl: '/api/offer', // Your WebRTC offer/answer endpoint
  });
  ```

  ```python server theme={null}
  # See
  # https://github.com/pipecat-ai/pipecat-examples/blob/main/p2p-webrtc/video-transform/server/server.py
  # for a complete example of how to implement the server-side endpoint.
  @app.post("/api/offer")
  async def offer(request: dict, background_tasks: BackgroundTasks):
      pipecat_connection = SmallWebRTCConnection(ice_servers)
      await pipecat_connection.initialize(sdp=request["sdp"], type=request["type"])

      @pipecat_connection.event_handler("closed")
      async def handle_disconnected(webrtc_connection: SmallWebRTCConnection):
          logger.info(f"Discarding peer connection for pc_id: {webrtc_connection.pc_id}")
          pcs_map.pop(webrtc_connection.pc_id, None)

      background_tasks.add_task(run_bot, pipecat_connection)

      answer = pipecat_connection.get_answer()

      return answer
  ```
</CodeGroup>

### Methods

For most operations, you will not interact with the transport directly. Most methods have an equivalent in the `PipecatClient` and should be called from the `PipecatClient`. However, there are a few transport-specific methods that you may need to call directly. When doing so, be sure to access your transport via the `transport` property of the `PipecatClient` instance.

<ResponseField name="setAudioCodec" type="method">
  Sets the preferred audio codec.

  ```javascript theme={null}
  transport.setAudioCodec("opus");
  ```
</ResponseField>

<ResponseField name="setVideoCodec" type="method">
  Sets the preferred video codec.

  ```javascript theme={null}
  transport.setVideoCodec("VP8");
  ```
</ResponseField>

## Events

The transport implements the various [`PipecatClient` event handlers](/api-reference/client/js/callbacks).

## Connection Process

The connection process follows these steps:

1. The transport negotiates a WebRTC connection with the corresponding pipecat transport, complete with transceivers for the media and a data channel for messaging.
2. The transport sends a message to the pipecat transport to let it know it's ready.
3. The Pipecat transport sends a message letting the client know it is ready.

## Reconnection Handling

The transport includes automatic reconnection logic:

* Up to 3 reconnection attempts after connection failures
* Detection of ICE connection state changes
* Graceful recovery from temporary disconnections
* Graceful disconnect when reconnection attempts fail

## More Information

<CardGroup cols={2}>
  <Card horizontal title="Video Transform Demo" icon="video" href="https://github.com/pipecat-ai/pipecat-examples/tree/main/p2p-webrtc/video-transform">
    Real-time video transformation example
  </Card>

  <Card horizontal title="Package" icon="browser" href="https://www.npmjs.com/package/@pipecat-ai/small-webrtc-transport">
    `@pipecat-ai/small-webrtc-transport`
  </Card>
</CardGroup>
