> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://fastpix.com/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://fastpix.com/docs/_mcp/server.

# Cast to Chromecast

> Cast FastPix videos to a Chromecast receiver from the FastPix Flutter Player. The receiver fetches the stream itself, and FastPixCastController sends it commands.

Cast FastPix videos from your Flutter app to a Chromecast receiver. Casting is not screen mirroring: the receiver fetches the stream itself, directly from FastPix, and `FastPixCastController` only sends it commands. Three things follow from that:

* The stream URL must be reachable by the receiver, so authentication travels in the URL. `FastPixPlayerDataSource.url` already carries the playback token as a query parameter, but `headers` are dropped, because the receiver makes its own request.
* Local and remote playback are mutually exclusive. Use `startCastingFrom` and `stopCastingTo` to move between them rather than driving both players by hand.
* DRM streams cannot be cast through Google's Default Media Receiver. See [DRM on Chromecast](#drm-on-chromecast).

Casting is supported on Android and iOS. On any other platform the controller settles on `FastPixCastState.unavailable` instead of throwing, so you can build cast UI unconditionally and let the state hide it.

\


## Platform setup

### Android

Add the discovery permissions and the Cast framework configuration to `android/app/src/main/AndroidManifest.xml`:

```xml
<!-- Cast discovery runs over mDNS on the local network -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

<!-- Android 13 (API 33) and above gate local network discovery behind a
     runtime permission. Without it MediaRouter reports no Cast routes and
     raises nothing. `neverForLocation` avoids the extra location prompt. -->
<uses-permission
    android:name="android.permission.NEARBY_WIFI_DEVICES"
    android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />

<application ...>
    <!-- Google Cast framework configuration -->
    <meta-data
        android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
        android:value="com.felnanuke.google_cast.GoogleCastOptionsProvider" />

    <!-- Media notification service for cast controls -->
    <service
        android:name="com.google.android.gms.cast.framework.media.MediaNotificationService"
        android:exported="false"
        android:foregroundServiceType="mediaPlayback" />
</application>
```

The SDK makes the runtime `NEARBY_WIFI_DEVICES` request itself from `startDiscovery()`, once per app process, so a viewer who declined is not prompted again on every screen. Casting also needs Google Play Services. When it is missing or too old, the failure arrives as `FP_CAST_PLAY_SERVICES_UNAVAILABLE`.

### iOS

Add the local network keys to `ios/Runner/Info.plist`. `NSBonjourServices` must list the Cast service and, when you use a custom receiver, the service for its application ID:

```xml
<key>NSLocalNetworkUsageDescription</key>
<string>${PRODUCT_NAME} uses the local network to discover Cast-enabled devices on your WiFi network.</string>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} uses Bluetooth to discover nearby Cast-enabled devices.</string>
<key>NSBonjourServices</key>
<array>
    <string>_googlecast._tcp</string>
    <string>_YOUR_APP_ID._googlecast._tcp</string>
</array>
```

On iOS, when the local network permission is denied, discovery simply returns zero devices, with no callback.

\


## Quick start

```dart
final cast = FastPixCastController(
  // Defaults to Google's Default Media Receiver. A custom receiver ID is
  // needed for branding, DRM, or receiver-side analytics.
  appId: 'YOUR_RECEIVER_APP_ID',
  // Set to fmp4 for CMAF packaged streams , see "Segment format" below.
  segmentFormat: FastPixCastSegmentFormat.fmp4,
);

// Cast state drives the cast button: show it only once a receiver exists.
cast.stateStream.listen((state) => setState(() => _canCast = state.canCast));
cast.devicesStream.listen((devices) => setState(() => _devices = devices));

await cast.initialize();

// Discovery is expensive in battery and Wi-Fi traffic. Start it when cast UI
// opens and stop it when it closes.
await cast.startDiscovery();
```

\


## Move playback between the phone and the TV

`startCastingFrom` connects, pauses the local player, and loads the stream on the receiver at the position playback had reached. The connection is established before local playback is touched, so a receiver that fails to connect leaves the phone playing where it was. If the receiver connects but the stream fails to load, the session is torn down and the error is rethrown, so a load failure arrives as an exception, not as `false`. Local playback resumes only if it was playing when casting started.

```dart
// Phone -> TV
try {
  final started = await cast.startCastingFrom(playerController, device);
  if (!started) showMessage(cast.lastError?.message ?? 'Could not connect');
} on UnsupportedError catch (error) {
  // DRM streams are refused here without a custom receiver
  showMessage(error.message.toString());
} on StateError catch (error) {
  // The player has no data source yet , initialize it before casting
  showMessage(error.message);
} catch (error) {
  // The session came up but the stream would not load. It has already been
  // torn down and local playback resumed.
  showMessage('Could not start playback on the TV');
}

// TV -> phone, resuming at the receiver's position
await cast.stopCastingTo(playerController);
```

Keep the `FastPixPlayer` widget mounted while casting. Hide it rather than removing it. Unmounting tears down the platform player, and `stopCastingTo` then has nothing to hand playback back to. It reports `FP_CAST_RESUME_UNAVAILABLE`, and the session still ends cleanly.

A session and the discovered device list can change from outside the app, such as the Google Home app, another sender, or the TV powering off. Treat `stateStream` and the cast events as the single source of truth rather than assuming a command succeeded.

\


## Control the receiver

```dart
await cast.play();
await cast.pause();
await cast.stop();                              // stops playback, keeps the session
await cast.seekTo(const Duration(minutes: 2));
await cast.setVolume(0.4);                      // receiver hardware volume

cast.remotePositionStream.listen((position) => setState(() => _position = position));

final isPlaying = cast.isRemotePlaying;
final position = cast.remotePosition;           // last position the receiver reported
```

`remoteVolume` is what this app last asked for, not ground truth. The Cast plugin provides no callback for volume, so changes made from the TV remote, the Google Home app, or the phone's volume buttons are not reflected.

To end the session entirely:

```dart
await cast.disconnect();                        // stops the receiver
await cast.disconnect(stopReceiver: false);     // leaves it playing for other senders
```

\


## Subtitles while casting

Subtitle tracks come from two places and are reported the same way. Tracks declared in `FastPixPlayerDataSource.subtitles` are sent to the receiver on load, and tracks inside the HLS manifest are found by the receiver. Both appear in `textTracks` only once the receiver has reported a media status.

```dart
cast.textTracksStream.listen((tracks) => setState(() => _tracks = tracks));
cast.activeTextTrackStream.listen((id) => setState(() => _activeId = id));

await cast.selectTextTrack(track);   // only tracks from `textTracks`
await cast.disableTextTrack();       // subtitles off
```

The selection is not recorded locally. The receiver confirms it in its next media status, which is also how a change made from a TV remote or another sender arrives.

\


## Cast events

Cast events are ordinary `FastPixPlayerEvent`s. Pass the player's event manager to the constructor to have them reach the same listeners as playback events:

```dart
final cast = FastPixCastController(eventManager: playerController.eventManager);

cast.addEventListener(FastPixPlayerEventTypes.castAvailable, (event) {
  // A receiver became reachable , the moment to reveal a cast button
});
cast.addEventListener(FastPixPlayerEventTypes.castStarted, (event) { /* ... */ });
cast.addEventListener(FastPixPlayerEventTypes.castEnded, (event) {
  final ended = event as FastPixCastEndedEvent;
  // Fired whichever side ended the session, with the last remote position
  debugPrint('${ended.device?.name} stopped at ${ended.position}');
});
cast.addEventListener(FastPixPlayerEventTypes.castError, (event) {
  final error = event as FastPixCastErrorEvent;
  debugPrint('${error.code}: ${error.message}');
});
```

| Event type      | Class                       | Fired when                                   |
| --------------- | --------------------------- | -------------------------------------------- |
| `castAvailable` | `FastPixCastAvailableEvent` | The first receiver becomes reachable         |
| `castStarted`   | `FastPixCastStartedEvent`   | A session becomes live                       |
| `castEnded`     | `FastPixCastEndedEvent`     | A session ends, whichever side ended it      |
| `castError`     | `FastPixCastErrorEvent`     | Discovery, a session, or a remote load fails |

`castError` deliberately does not extend `FastPixPlayerErrorEvent`: a cast failure is not a local playback failure, and the phone may still be playing.

\


## Handle cast errors

The most recent failure stays on `cast.lastError`, so UI that mounts after the failure can still render it. Branch on the classification rather than on the message:

```dart
final error = cast.lastError;
if (error != null) {
  if (error.isPermissionRelated) {
    await cast.openPermissionSettings();   // a permanently denied grant only Settings can fix
  } else if (error.isContentUnsupported) {
    // Never offer a retry , this content can never play on a receiver
  } else if (error.isRetryable) {
    // Trying again may work
  } else if (error.isFatal) {
    // Hide the cast button: casting is unusable on this device
  }
}
```

An empty device list on Android 13+ is usually the nearby devices permission. `requiresNearbyDevicesPermission` tells you whether that explanation can apply on the current device:

```dart
if (await cast.requiresNearbyDevicesPermission) {
  // Safe to suggest enabling "Nearby devices" for this app
}
```

### Cast error codes

| Code                                      | Meaning                                                                                |
| ----------------------------------------- | -------------------------------------------------------------------------------------- |
| `FP_CAST_INIT_FAILED`                     | The Google Cast context could not be created                                           |
| `FP_CAST_PLAY_SERVICES_UNAVAILABLE`       | Google Play Services is missing or too old (Android)                                   |
| `FP_CAST_NEARBY_PERMISSION_DENIED`        | The Android 13+ `NEARBY_WIFI_DEVICES` permission was not granted                       |
| `FP_CAST_LOCAL_NETWORK_PERMISSION_DENIED` | The iOS local network permission was denied (reserved; iOS exposes no callback for it) |
| `FP_CAST_DISCOVERY_FAILED`                | Discovery could not be started, stopped, or continued                                  |
| `FP_CAST_DEVICE_UNAVAILABLE`              | The chosen receiver is no longer in the discovered list                                |
| `FP_CAST_CONNECT_FAILED`                  | A session could not be established with the receiver                                   |
| `FP_CAST_CONNECT_TIMEOUT`                 | The receiver did not establish a session before the timeout elapsed                    |
| `FP_CAST_SESSION_TAKEN`                   | The receiver is already running a session for another sender                           |
| `FP_CAST_SESSION_FAILED`                  | An established session failed after it had connected                                   |
| `FP_CAST_DISCONNECT_FAILED`               | The session could not be ended cleanly                                                 |
| `FP_CAST_DRM_UNSUPPORTED`                 | DRM protected content was loaded without a custom receiver configured                  |
| `FP_CAST_MEDIA_UNSUPPORTED`               | The receiver refused the media: unsupported container or codec                         |
| `FP_CAST_LOAD_FAILED`                     | The load request failed for another reason                                             |
| `FP_CAST_COMMAND_FAILED`                  | A transport command (play, pause, stop, seek, subtitle change) failed                  |
| `FP_CAST_VOLUME_FAILED`                   | A volume change was rejected by the receiver                                           |
| `FP_CAST_RESUME_UNAVAILABLE`              | Casting stopped but local playback could not resume                                    |
| `FP_CAST_UNKNOWN`                         | The Cast SDK failed for a reason that maps to none of the above                        |

\


## DRM on Chromecast

Chromecast receivers speak Widevine only, never FairPlay, and Google's Default Media Receiver cannot perform a license request at all. Loading a DRM protected source without a custom receiver is refused: `loadMedia` throws `UnsupportedError` and emits `FP_CAST_DRM_UNSUPPORTED`.

The refusal happens at load time, not before connecting. `startCastingFrom` connects to the receiver and pauses local playback first, so a DRM source tears the fresh session down again on the way out. Check for DRM yourself before offering the cast button if you would rather the receiver were never woken.

With a custom receiver configured through `appId`, the SDK sends the license details in the media's `customData`, using the Widevine license URL derived from the playback ID even when the phone plays the same title locally through FairPlay:

```json
{
  "licenseUrl": "https://.../drm/license/widevine/{playbackId}?token=...",
  "protectionSystem": "widevine"
}
```

Your receiver application reads `loadRequest.media.customData.licenseUrl` and configures its playback manager with it. The FastPix license endpoint carries its token as a query parameter, so the receiver needs no custom headers.

\


## Segment format

A Cast receiver is a web player and must know how the segments are packaged before it can build a playback pipeline. When the manifest does not make that obvious, the receiver assumes MPEG-TS, and an fMP4/CMAF stream then connects, displays its title, and never starts playing, with no error on either side.

If casting connects but nothing plays, this is almost always the cause:

```dart
FastPixCastController(segmentFormat: FastPixCastSegmentFormat.fmp4);
```

Modern packaging is fMP4/CMAF, and any stream serving both Widevine and FairPlay from one source, which is how FastPix DRM works, is CMAF. `FastPixCastSegmentFormat.auto` (the default) sends no hint and is correct for plain MPEG-TS streams.

\


## What does not survive the trip

Because the receiver fetches and renders the stream itself, several data source options have no effect while casting:

* `headers` are dropped. Authentication has to be in the URL, which the FastPix playback token already is.
* Resolution hints (`resolution`, `minResolution`, `maxResolution`, `renditionOrder`) are sent as URL parameters, but adaptive switching is then the receiver's decision.
* `cacheEnabled`, `loop`, and `endAt` are local player behaviors with no receiver equivalent.

\


## Lifecycle

`dispose()` releases every subscription and stream the controller opened, but deliberately does not end a live session: a viewer who started casting expects the TV to keep playing when they leave the player screen. Call `disconnect()` first if the session should stop with the screen. For the same reason, hold the cast controller at app scope rather than rebuilding it per screen.

```dart
await cast.stopDiscovery();
await cast.dispose();
```

\


## What's next

* [Play a DRM-protected video](/docs/flutter-player/play-drm-protected-content) for how DRM works on the phone and on a custom receiver.
* [Manage a playlist](/docs/flutter-player/manage-a-playlist) to queue videos for playback.