Select platform: [HTML5](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/html5/get-started/pod-serving.md.txt "View this page for the HTML5 platform docs.") [Android](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/android/get-started/pod-serving.md.txt "View this page for the Android platform docs.") [iOS](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/ios/get-started/pod-serving.md.txt "View this page for the iOS platform docs.") [tvOS](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/tvos/get-started/pod-serving.md.txt "View this page for the tvOS platform docs.") [Cast](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/cast/get-started/pod-serving.md.txt "View this page for the Cast platform docs.") [Roku](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/roku/get-started/pod-serving.md.txt "View this page for the Roku platform docs.")

<br />

IMA SDKs simplify integrating multimedia ads into your websites and apps.

IMA SDKs can request ads from any
[VAST-compliant](https://www.iab.com/guidelines/digital-video-ad-serving-template-vast/)
ad server and manage ad playback in your apps.

With IMA DAI SDKs, apps make a stream request for ad and content video for
either VOD or live content. The SDK then returns a combined video stream, so
that you don't have to manage switching between ad and content video within your
app.

This guide demonstrates how to play a DAI Pod Serving stream, using the IMA
DAI SDK for CAF.


**Note:** The IMA DAI SDK for CAF supports both HLS and DASH streams, with no implementation differences.

<br />

Before using this guide, familiarize yourself with the
[Chromecast Application Framework's Web Receiver](https://developers.google.com/cast/docs/web_receiver.md.txt)
protocol. This guide assumes a basic understanding of CAF receiver concepts,
such as
[message interceptors](https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.PlayerManager.md.txt#setMessageInterceptor)
and
[mediaInformation](https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.messages.MediaInformation.md.txt)
objects, and familiarity with using the
[Cast Command and Control tool](https://developers.google.com/cast/docs/debugging/cac_tool.md.txt),
to emulate a CAF sender.

To use IMA DAI Pod Serving, you must be working with a Pod Serving partner and
must have an
[Ad Manager 360 Advanced](https://support.google.com/admanager/answer/3485387)
account. If you have an Ad Manager account, contact your account manager for
more details. For information about signing up for Ad Manager, visit the
[Ad Manager Help Center](https://support.google.com/admanager/answer/7084151).

For information on integrating with other platforms, or on using the IMA
client-side SDKs, see [Interactive Media Ads SDKs](https://developers.google.com/interactive-media-ads).

## IMA DAI Pod Serving overview

Implementing Pod Serving using the IMA CAF DAI SDK involves two main components,
which are demonstrated in this guide:

- [`StreamRequest`](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/cast/reference/js/PodStreamRequest): An object that defines a stream request to Google's advertising servers. Requests specify a Network Code, Custom Asset Key, and an optional API key, as well as other optional parameters.
- [`StreamManager`](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/cast/reference/js/StreamManager): An object that handles communication between the video stream and the IMA DAI SDK, such as firing tracking pings and forwarding stream events to the publisher.

## Prerequisites

- A [Cast Developer Console](https://cast.google.com/publish/) account with registered test devices.
- A hosted [web receiver
  app](https://developers.google.com/cast/docs/web_receiver/basic#create_a_basic_web_receiver_app) that is registered with your Cast Developer Console and which can be modified to host the code provided by this guide.
- A sending app that is configured to use your web receiver app. For the purposes of this example, use the [Cast Command and Control
  tool](https://developers.google.com/cast/docs/debugging/cac_tool) as your sender.

## Configure the sender's MediaInfo objects

First, configure your sender app's
[`MediaInfo` object](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media.MediaInfo.md.txt)
to include the following fields:
Field Contents `contentId` A unique identifier for this media item.

<var scope="content-id" class="edit" translate="no">CONTENT_ID</var>
`contentUrl` Optional. Backup stream URL to play if the DAI stream fails to load.


<var scope="content-url" class="edit" translate="no">BACKUP_STREAM_URL</var>
`contentType` Optional. Mimetype of the content backup streams. Only needed for [DASH
streams](https://developers.google.com/cast/docs/media/streaming_protocols#dynamic_adaptive_streaming_over_http_dash).

<var scope="content-type" class="edit" translate="no">CONTENT_STREAM_MIMETYPE</var>
`streamType` The string literal or constant used for this value varies by sender platform. `customData` The `customData` field contains a key-value store of additional required fields. In this sample, it contains your DAI stream parameters. In a production app you might instead pass an identifier that your cast receiver app would use to retrieve these parameters with a server-side request. Field Contents `daiStreamType` The type of your DAI stream. one of either `"LIVE"` or `"VOD"`

<var scope="dai-stream-type" class="edit" translate="no">DAI_STREAM_TYPE</var>
`networkCode` The network code for your Google Ad Manager 360 account.

<var scope="network-code" class="edit" translate="no">NETWORK_CODE</var>
`customAssetKey` This field is needed for Live streams only. The custom asset key that identifies your Pod Serving event in Google Ad Manager 360.

<var scope="custom-asset-key" class="edit" translate="no">CUSTOM_ASSET_KEY</var>
`apiKey` An optional API key to retrieve a Stream ID from the IMA DAI SDK.

<var scope="api-key" class="edit" translate="no">API_KEY</var>

Here are some code samples to help you get started:

### Web

To configure these values in a Cast web sender, first create a
[`MediaInfo`](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media.MediaInfo.md.txt)
object with the required data, then make a [load
request](https://developers.google.com/cast/docs/web_sender/integrate#media_control) to the web receiver.

```javascript
// Create mediaInfo object
const mediaInfo = new chrome.cast.media.MediaInfo("CONTENT_ID");
mediaInfo.contentUrl = "BACKUP_STREAM_URL";
mediaInfo.contentType = "CONTENT_STREAM_MIMETYPE";
mediaInfo.streamType = chrome.cast.media.StreamType.LIVE;
mediaInfo.customData = {
  daiStreamType: "DAI_STREAM_TYPE",
  networkCode: "NETWORK-CODE",
  customAssetKey: "CUSTOM_ASSET_KEY",
  apiKey: "API_KEY"
};

// Make load request to cast web receiver
const castSession = cast.framework.CastContext.getInstance().getCurrentSession();
const request = new chrome.cast.media.LoadRequest(mediaInfo);
castSession.loadMedia(request).then(
  () => { console.log('Load succeed'); },
  (errorCode) => { console.log('Error code: ' + errorCode); });
```

### Android

To configure these values in a Cast web sender, first create a
[MediaInfo](https://developers.google.com/android/reference/com/google/android/gms/cast/MediaInfo.md.txt) object
with the required data, then make a
[load request](https://developers.google.com/cast/docs/android_sender/integrate.md.txt#load_media) to the web
receiver.

```java
JSONObject customData = new JSONObject()?
  .put("daiStreamType", "DAI_STREAM_TYPE")
  .put("networkCode", "NETWORK-CODE")
  .put("customAssetKey", "CUSTOM_ASSET_KEY")
  .put("apiKey", "API_KEY");
MediaInfo mediaInfo = MediaInfo.Builder("CONTENT_ID")
  .setContentUrl("BACKUP_STREAM_URL")
  .setContentType("CONTENT_STREAM_MIMETYPE")
  .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
  .setCustomData(customData)
  .build();

RemoteMediaClient remoteMediaClient = mCastSession.getRemoteMediaClient();
remoteMediaClient.load(new MediaLoadRequestData.Builder().setMediaInfo(mediaInfo).build());
```

### iOS (Obj-C)

To configure these values in a Cast web sender, first create a
[`GCKMediaInformation`](https://developers.google.com/cast/docs/reference/ios/interface_g_c_k_media_information.md.txt)
object with the required data, then make a [load
request](https://developers.google.com/cast/docs/ios_sender/integrate#load_media) to the web receiver.

```objective-c
NSURL url = [NSURL URLWithString:@"BACKUP_STREAM_URL"];
NSDictionary *customData = @{
  @"daiStreamType": @"DAI_STREAM_TYPE",
  @"networkCode": @"NETWORK-CODE",
  @"customAssetKey": @"CUSTOM_ASSET_KEY",
  @"apiKey": @"API_KEY"};
mediaInfoBuilder.customData = customData;

GCKMediaInformationBuilder *mediaInfoBuilder =
  [[GCKMediaInformationBuilder alloc] initWithContentID: @"CONTENT_ID"];
mediaInfoBuilder.contentURL = url;
mediaInfoBuilder.contentType = @"CONTENT_STREAM_MIMETYPE";
mediaInfoBuilder.streamType = GCKMediaStreamTypeLive;
mediaInfoBuilder.customData = customData;
self.mediaInformation = [mediaInfoBuilder build];

GCKRequest *request = [self.sessionManager.currentSession.remoteMediaClient loadMedia:self.mediaInformation];
if (request != nil) {
  request.delegate = self;
}
```

### iOS (Swift)

To configure these values in a Cast web sender, first create a
[`GCKMediaInformation`](https://developers.google.com/cast/docs/reference/ios/interface_g_c_k_media_information.md.txt)
object with the required data, then make a [load
request](https://developers.google.com/cast/docs/ios_sender/integrate#load_media) to the web receiver.

```swift
let url = URL.init(string: "BACKUP_STREAM_URL")
guard let mediaURL = url else {
  print("invalid mediaURL")
  return
}

let customData = [
  "daiStreamType": "DAI_STREAM_TYPE",
  "networkCode": "NETWORK-CODE",
  "customAssetKey": "CUSTOM_ASSET_KEY",
  "region": "API_KEY"
]

let mediaInfoBuilder = GCKMediaInformationBuilder.init(contentId: "CONTENT_ID")
mediaInfoBuilder.contentURL = mediaUrl
mediaInfoBuilder.contentType = @"CONTENT_STREAM_MIMETYPE"
mediaInfoBuilder.streamType = GCKMediaStreamType.Live
mediaInfoBuilder.customData = customData
mediaInformation = mediaInfoBuilder.build()

guard let mediaInfo = mediaInformation else {
  print("invalid mediaInformation")
  return
}

if let request = sessionManager.currentSession?.remoteMediaClient?.loadMedia
(mediaInfo) {
  request.delegate = self
}
```

### CAC tool

To configure these values in the [Cast Command and Control
tool](https://developers.google.com/cast/docs/debugging/cac_tool), click the Load Media tab, and set the
custom load request type to LOAD. Then replace the JSON data in the text area
with this JSON:

```json
{
  "media": {
    "contentId": "CONTENT_ID",
    "contentUrl": "BACKUP_STREAM_URL",
    "contentType": ""CONTENT_STREAM_MIMETYPE"",
    "streamType": "LIVE",
    "customData": {
      "daiStreamType": "DAI_STREAM_TYPE",
      "networkCode": "NETWORK-CODE",
      "customAssetKey": "CUSTOM_ASSET_KEY",
      "oAuthToken": "API_KEY"
    }
  }
}
```

This custom load request can be sent to the receiver to test the rest of the
steps.

## Create a basic CAF receiver

Create a custom web receiver, as seen in the [CAF SDK Custom Web Receiver
Guide](https://developers.google.com/cast/docs/web_receiver/basic#create_a_basic_web_receiver_app).

Your receiver's code should look like this:

```html
<html>
<head>
  <script
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js">
  </script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    // ...
  </script>
</body>
</html>
```

## Import the IMA DAI SDK and get the Player Manager

Add a script tag to import the IMA DAI SDK for CAF to your web receiver, just
after the script loading CAF. In the script tag, store the receiver context and
player manager as constants before starting the receiver.

```html
<html>
<head>
  <script
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js"></script>
  <script src="//imasdk.googleapis.com/js/sdkloader/cast_dai.js"></script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    const castContext = cast.framework.CastReceiverContext.getInstance();
    const playerManager = castContext.getPlayerManager();

    castContext.start();
  </script>
</body>
</html>
```

## Initialize the IMA Stream Manager

Initialize the IMA Stream Manager.

```html
<html>
<head>
  <script type="text/javascript"
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js"></script>
  <script src="//imasdk.googleapis.com/js/sdkloader/cast_dai.js"></script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    const castContext = cast.framework.CastReceiverContext.getInstance();
    const playerManager = castContext.getPlayerManager();
    const streamManager = new google.ima.cast.dai.api.StreamManager();

    castContext.start();
  </script>
</body>
</html>
```

## Create the Stream Manager Load Interceptor

Before your media items are passed to CAF, create your stream request in a
[LOAD message
interceptor](https://developers.google.com/cast/docs/web_receiver/core_features#message_interception).

```javascript
    const castContext = cast.framework.CastReceiverContext.getInstance();
    const playerManager = castContext.getPlayerManager();
    const streamManager = new google.ima.cast.dai.api.StreamManager();

    /**
     * Creates a livestream request object for a Pod Serving stream.
     * @param {!LoadRequestData} castRequest The request object from the cast sender
     * @return {StreamRequest} an IMA stream request
     */
    const createStreamRequest = (castRequest) => { /* ... */};

    /**
     * Initates a DAI stream request for the final stream manifest.
     * @param {!LoadRequestData} castRequest The request object from the cast sender
     * @return {Promise<LoadRequestData>} a promise that resolves to an updated castRequest, containing the DAI stream manifest
     */
    const createDAICastRequest = (castRequest) => {
        return streamManager.requestStream(castRequest, createStreamRequest(castRequest))
          .then((castRequestWithPodStreamData) => {
            console.log('Successfully made DAI stream request.');
            // ...
            return castRequestWithPodStreamData;
          })
          .catch((error) => {
            console.log('Failed to make DAI stream request.');
            // CAF will automatically fallback to the content URL
            // that it can read from the castRequest object.
            return castRequest;
          });
    };

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, createDAICastRequest);

    castContext.start();
```

## Create the stream request

Complete the `createStreamRequest` function to create a Pod Serving stream based
on the CAF load request.

```javascript
    /**
     * Creates a livestream request object for a Pod Serving stream.
     * @param {!LoadRequestData} castRequest The request object from the cast sender
     * @return {StreamRequest} an IMA stream request
     */
    const createStreamRequest = (castRequest) => {
      const customData = castRequest.media.customData;
      let streamRequest;
      if (customData.daiStreamType == "LIVE") {
        streamRequest = new google.ima.cast.dai.api.PodStreamRequest();
        streamRequest.customAssetKey = customData.customAssetKey;
        streamRequest.networkCode = customData.networkCode;
        streamRequest.apiKey = customData.apiKey;
      } else if (customData.daiStreamType == "VOD") {
        streamRequest = new google.ima.cast.dai.api.PodVodStreamRequest();
        streamRequest.networkCode = customData.networkCode;
        streamRequest.apiKey = customData.apiKey;
      }
      return streamRequest;
    };
```

## Retrieve the stitched manifest from your VTP

If your stream request is successful, use `streamManager.getStreamId()` to
retrieve the stream's ID. Your Video Technical Partner (VTP) or custom manifest
manipulator will provide instructions to retrieve a manifest URL, using this
stream ID.

Once you have retrieved your manifest URL, replace the existing `contentUrl`
with the new `manifestUrl`.

Lastly, before returning the modified stream manifest, call the
[`loadStreamMetadata`](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/cast/reference/js/StreamManager#loadStreamMetadata)
method on your
[`streamManager`](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/cast/reference/js/StreamManager)
to inform the IMA SDK that it can safely request stream metadata. This call is
only necessary for VOD streams.

```javascript
    /**
     * Initates a DAI stream request for the final stream manifest.
     * @param {!LoadRequestData} castRequest The request object from the cast sender
     * @return {Promise<LoadRequestData>} a promise that resolves to an updated castRequest, containing the DAI stream manifest
     */
    const createDAICastRequest = (castRequest) => {
        return streamManager.requestStream(castRequest, createStreamRequest(castRequest))
          .then((castRequestWithPodStreamData) => {
            console.log('Successfully made DAI stream request.');

            // This is a sample VTP integration. Consult your VTP documentation
            // for how to retrieve an ad-stitched stream manifest URL.
            const manifestTemplate = "https://.../manifest.m3u8?gam_stream_id=[[STREAMID]]";
            const streamId = streamManager.getStreamId();
            const manifestUrl = manifestTemplate.replace('[[STREAMID]]', streamId)
            // Assign your manifestUrl to the request's content URL.
            castRequestWithPodStreamData.media.contentUrl = manifestUrl;

            // After generating the manifest URL, VOD streams must notify the
            // IMA SDK that it is safe to request ad pod metadata.
            // This is only necessary for VOD streams. It is a no-op for
            // livestreams, so no conditional is needed.
            streamManager.loadStreamMetadata();

            return castRequestWithPodStreamData;
          })
          .catch((error) => {
            console.log('Failed to make DAI stream request.');
            // CAF will automatically fallback to the content URL
            // that it can read from the castRequest object.
            return castRequest;
          });
    };
```

## Clean up IMA DAI assets

When you have successfully finished requesting and displaying ads in a Pod
Serving stream with IMA DAI SDK, we suggest you clean up any resources after the
Pod Serving session is complete. Call `StreamManager.destroy()` to stop stream
playback, stop all ad tracking, and release all of the loaded stream assets.