Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install ima-dai-sdk@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin ima-dai-sdk v1.0.0 follows the Agent Plugins spec.
gh skills-hub install ima-dai-sdk Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/ima-dai-sdk/ Extract the ZIP to .github/skills/ in your repo. The folder name must match ima-dai-sdk for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 1.9 KB
---
name: ima-dai-sdk
description: >-
Integrates the Google Interactive Media Ads (IMA) Dynamic Ad Insertion (DAI)
SDK into websites, web apps, mobile apps, or TV apps.
Use when:
- A video player needs to load and play HLS or DASH streams in web apps,
Android apps, iOS apps, tvOS apps, Cast (CAF) receivers, or Roku channels.
- The app needs to make use of a Google DAI livestream event asset key, or
content source CMS ID, video ID for video on demand.
Don't use this skill to load and play a VAST or VMAP URL.
license: Apache-2.0
metadata:
author: Google LLC
version: "1.0.1"
category: GoogleAds
---
# IMA DAI SDK
Use the IMA DAI SDK to load HLS or DASH streams into the app for:
* **Livestream events** configured in Google Ad Manager.
* **Video on demand (VOD)** content ingested into Google Ad Manager.
## Prerequisites
Review the platform-specific integration guides for the target platforms:
* **Web/HTML5/ReactJs/NodeJs/Angular:** Read
[StreamManager guide](references/web-StreamManager-guide.md) for loading
stream URL from Google full-service DAI into `<video>` element.
* **ChromeCast:** Read
[StreamManager guide](references/cast-StreamManager-guide.md) for
integrating the IMA DAI SDK into a ChromeCast Web Receiver.
* **Android:** Read
[ImaServerSideAdInsertionMediaSource guide](references/android-ImaServerSideAdInsertionMediaSource-guide.md)
for integrating Media3 Exoplayer IMA extension.
* **iOS/tvOS:** Read
[IMAStreamRequest guide](references/ios-IMAStreamRequest-guide.md) for
playing streams with `AVPlayer`.
* **Roku:** Read [StreamManager guide](references/roku-StreamManager-guide.md)
for implementing DAI on Roku SceneGraph.
## Quick start (general workflow)
1. Import the SDK
2. Initialize the SDK
3. Add stream event listeners
4. Set up timed metadata forwarding
5. Make a stream request
6. Clean up SDK resources when the stream fails or the user leaves the stream.
android-ImaServerSideAdInsertionMediaSource-guide.md 8.1 KB
# Google IMA DAI SDK Android - ExoPlayer IMA Extension Guide
Use the `ImaServerSideAdInsertionMediaSource` class of the ExoPlayer IMA
extension (`androidx.media3:media3-exoplayer-ima`) to request livestream or VOD
stream from Google full-service DAI.
## Table of Contents
* [Dependencies](#dependencies) (Line 21)
* [IMA DAI SDK required permissions](#ima-dai-sdk-required-permissions)
(Line 57)
* [UI Setup](#ui-setup) (Line 66)
* [Early SDK Initialization](#early-sdk-initialization) (Line 89)
* [Create a reusable AdsLoader](#create-a-reusable-adsloader) (Line 104)
* [Listen to stream events and ad events](#listen-to-stream-events-and-ad-events)
(Line 123)
* [Initialize ExoPlayer with SSAI MediaSource Factory](#initialize-exoplayer-with-ssai-mediasource-factory)
(Line 155)
* [Request a livestream](#request-a-livestream) (Line 180)
* [Video on Demand (VOD) Streams](#video-on-demand-vod-streams) (Line 202)
* [Clean up SDK resources](#clean-up-sdk-resources) (Line 227)
* [Reference implementation](#reference-implementation) (Line 240)
## Dependencies
Add the Media3 ExoPlayer IMA extension in `build.gradle`. This component
automatically imports the IMA DAI SDK.
```groovy
apply plugin: "com.android.application"
android {
compileOptions {
// Required by IMA SDK v3.37.0+
coreLibraryDesugaringEnabled = true
}
defaultConfig {
minSdkVersion(23)
}
}
repositories {
google()
mavenCentral()
}
dependencies {
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
implementation("androidx.media3:media3-ui")
implementation("androidx.media3:media3-exoplayer")
implementation("androidx.media3:media3-exoplayer-hls")
implementation("androidx.media3:media3-exoplayer-dash")
implementation("androidx.media3:media3-exoplayer-ima")
}
```
Use latest versions as posted on
[Media3](https://developer.android.com/jetpack/androidx/releases/media3.md.txt)
## IMA DAI SDK required permissions
Ensure to declare the permissions required by the IMA DAI SDK in
`AndroidManifest.xml`:
```xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```
## UI Setup
Place the `PlayerView` inside the layout. For example:
```xml
<androidx.media3.ui.PlayerView android:id="@+id/player_view" />
```
If Jetpack Compose is used, create a `PlayerView` wrapping an exoplayer:
```kotlin
AndroidView(
factory = { ctx ->
PlayerView(ctx).apply {
player = exoPlayer
}
},
update = { playerView ->
playerView.player = exoPlayer
}
)
```
## Early SDK Initialization
Initialize the IMA SDK as early as possible in the app lifecycle (such as inside
`onCreate()` of `Application` or the main `Activity`) to minimize stream load
times:
Create a `ImaSdkSettings` object to initialize the SDK. Save it for reuse with
`ImaServerSideAdInsertionMediaSource`.
```kotlin
val imaSdkFactory = ImaSdkFactory.getInstance()
val sharedImaSdkSettings: ImaSdkSettings = imaSdkFactory.createImaSdkSettings()
imaSdkFactory.initialize(this, sharedImaSdkSettings)
```
## Create a reusable `AdsLoader`
Provide the `androidx.media3.ui.PlayerView` to build a
`ImaServerSideAdInsertionMediaSource.AdsLoader`.
Provide the same `ImaSdkSettings` from
`ImaSdkFactory.getInstance().initialize()` the previous step.
```kotlin
val playerView = findViewById(R.id.player_view)
val adsLoaderBuilder =
ImaServerSideAdInsertionMediaSource.AdsLoader.Builder(this, playerView)
val adsLoader = adsLoaderBuilder
.setAdEventListener(buildAdEventListener())
.setImaSdkSettings(sharedImaSdkSettings)
.build()
```
## Listen to stream events and ad events
Implement DAI stream event handling by creating an `AdEventListener`. Provide
this listener to the `AdsLoader` builder during instantiation.
```kotlin
val adEventListener = AdEvent.AdEventListener { event ->
when (event.type) {
AdEvent.AdEventType.LOADED,
AdEvent.AdEventType.CUEPOINTS_CHANGED,
AdEvent.AdEventType.AD_BREAK_STARTED,
AdEvent.AdEventType.AD_BREAK_ENDED,
AdEvent.AdEventType.AD_PERIOD_STARTED,
AdEvent.AdEventType.AD_PERIOD_ENDED,
AdEvent.AdEventType.STARTED,
AdEvent.AdEventType.FIRST_QUARTILE,
AdEvent.AdEventType.MIDPOINT,
AdEvent.AdEventType.THIRD_QUARTILE,
AdEvent.AdEventType.COMPLETED,
AdEvent.AdEventType.PAUSED,
AdEvent.AdEventType.RESUMED,
AdEvent.AdEventType.SKIPPABLE_STATE_CHANGED,
AdEvent.AdEventType.SKIPPED,
AdEvent.AdEventType.CLICKED -> Log.i(LOG_TAG, "Ad event: ${event.type}")
AdEvent.AdEventType.AD_PROGRESS -> {
// High-frequency event fired periodically during ad playback; ignore to prevent log spam
}
else -> Log.i(LOG_TAG, "Unhandled ad event: ${event.type}")
}
}
```
## Initialize ExoPlayer with SSAI MediaSource Factory
Create `DefaultMediaSourceFactory` and
`ImaServerSideAdInsertionMediaSource.Factory` objects to build the `ExoPlayer`
instance.
Ensure to call `AdsLoader.setPlayer()`, providing the `ExoPlayer` instance
above, before calling `ExoPlayer.setMediaItem` with a
`ImaServerSideAdInsertionUri`.
```kotlin
val dataSourceFactory: DataSource.Factory = DefaultDataSource.Factory(this)
val mediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory)
val adsMediaSourceFactory =
ImaServerSideAdInsertionMediaSource.Factory(adsLoader, mediaSourceFactory)
mediaSourceFactory.setServerSideAdInsertionMediaSourceFactory(adsMediaSourceFactory)
player = ExoPlayer.Builder(this)
.setMediaSourceFactory(mediaSourceFactory)
.build()
adsLoader.setPlayer(player)
```
## Request a livestream
Build a live stream URI using `ImaServerSideAdInsertionUriBuilder` with the
asset key:
```kotlin
val liveStreamUri: Uri = ImaServerSideAdInsertionUriBuilder()
.setNetworkCode(<NETWORK_CODE_PLACEHOLDER>)
.setAssetKey(<ASSET_KEY_PLACEHOLDER>)
.setFormat(androidx.media3.common.C.CONTENT_TYPE_HLS)
.build()
val liveStreamMediaItem: MediaItem = MediaItem.fromUri(liveStreamUri)
player.setMediaItem(liveStreamMediaItem)
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<ASSET_KEY_PLACEHOLDER>**: The livestream asset key configured in Google
Ad Manager.
### Video on Demand (VOD) Streams
Build a VOD stream URI using `ImaServerSideAdInsertionUriBuilder` with content
source ID (CMS ID) and video ID:
```kotlin
val vodStreamUri: Uri = ImaServerSideAdInsertionUriBuilder()
.setNetworkCode(<NETWORK_CODE_PLACEHOLDER>)
.setContentSourceId(<CONTENT_SOURCE_ID_PLACEHOLDER>)
.setVideoId(<VIDEO_ID_PLACEHOLDER>)
.setFormat(androidx.media3.common.C.CONTENT_TYPE_HLS)
.build()
val vodStreamItem: MediaItem = MediaItem.fromUri(vodStreamUri)
player.setMediaItem(vodStreamItem)
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<CONTENT_SOURCE_ID_PLACEHOLDER>**: The CMS ID in Google Ad Manager.
* **<VIDEO_ID_PLACEHOLDER>**: The video ID in the CMS.
For testing purposes, use values of DAI sample streams from
https://developers.google.com/ad-manager/dynamic-ad-insertion/streams.md.txt?utm_source=agent-skills&utm_medium=content&utm_campaign=adr-ss-ai&utm_content=ima-dai-sdk
## Clean up SDK resources
Call `ImaServerSideAdInsertionMediaSource.AdsLoader.release()` when releasing
the player or handling stream errors to tear down active DAI sessions.
Save the returned `AdsLoader.State` object to restore player during
configuration changes like screen rotations.
```kotlin
adsLoader?.setPlayer(null)
adsLoaderState = adsLoader?.release()
```
## Reference implementation
* [ExoPlayerExample/app/src/main/res/layout/activity_my.xml](https://raw.githubusercontent.com/googleads/googleads-ima-android-dai/refs/heads/main/ExoPlayerExample/app/src/main/res/layout/activity_my.xml)
* [ExoPlayerExample/app/src/main/java/com/google/ads/interactivemedia/v3/samples/videoplayerapp/MyActivity.java](https://raw.githubusercontent.com/googleads/googleads-ima-android-dai/refs/heads/main/ExoPlayerExample/app/src/main/java/com/google/ads/interactivemedia/v3/samples/videoplayerapp/MyActivity.java)
cast-StreamManager-guide.md 4.4 KB
# Google IMA DAI SDK Cast - StreamManager Guide
Use `StreamManager` to request and play a livestream or VOD stream from Google
full-service DAI in a Cast Application Framework (CAF) Web Receiver.
## Table of Contents
* [Import the IMA DAI SDK](#import-the-ima-dai-sdk) (Line 17)
* [SDK Initialization](#sdk-initialization) (Line 28)
* [Make stream requests](#make-stream-requests) (Line 43)
* [Stream Event and Error Handling](#stream-event-and-error-handling)
(Line 95)
* [DAI session events](#dai-session-events) (Line 103)
* [Ad break events](#ad-break-events) (Line 108)
* [Ad events](#ad-events) (Line 114)
* [Cleanup](#cleanup) (Line 124)
## Import the IMA DAI SDK
Add the script tag for the IMA DAI SDK for CAF immediately after the CAF
receiver framework script loader. The CAF DAI SDK is evergreen, so there is no
need to set a specific version.
```html
<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>
```
## SDK Initialization
Obtain the `CastReceiverContext` and `PlayerManager` instances.
Initialize the `StreamManager` so that the IMA DAI SDK can set up timed metadata
event listeners before playback starts.
```typescript
const castContext: cast.framework.CastReceiverContext =
cast.framework.CastReceiverContext.getInstance();
const playerManager: cast.framework.PlayerManager =
castContext.getPlayerManager();
const streamManager = new google.ima.cast.dai.api.StreamManager();
```
## Make stream requests
Create `google.ima.cast.dai.api.LiveStreamRequest` from sender app's cast
request.
```typescript
let streamRequest = new google.ima.cast.dai.api.LiveStreamRequest();
streamRequest.networkCode = <NETWORK_CODE_PLACEHOLDER>;
streamRequest.assetKey = <ASSET_KEY_PLACEHOLDER>;
```
Extract the following parameters from
`cast.framework.messages.MediaInformation.customData`:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<ASSET_KEY_PLACEHOLDER>**: The livestream asset key configured in Google
Ad Manager.
For VOD, create `google.ima.cast.dai.api.VODStreamRequest` from sender app's
cast request.
```typescript
let streamRequest = new google.ima.cast.dai.api.VODStreamRequest();
streamRequest.networkCode = <NETWORK_CODE_PLACEHOLDER>;
streamRequest.contentSourceId = <CMS_ID_PLACEHOLDER>;
streamRequest.videoId = <VIDEO_ID_PLACEHOLDER>;
```
Provide the following parameters from
`cast.framework.messages.MediaInformation.customData`:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<CMS_ID_PLACEHOLDER>**: The content source ID (CMS ID) in Google Ad
Manager.
* **<VIDEO_ID_PLACEHOLDER>**: The video ID in the CMS.
For testing purposes, use values of DAI sample streams from
https://developers.google.com/ad-manager/dynamic-ad-insertion/streams.md.txt?utm_source=agent-skills&utm_medium=content&utm_campaign=adr-ss-ai&utm_content=ima-dai-sdk
To play the stream immediately, create a load message interceptor to make stream
requests by calling `streamManager.requestStream()`:
```typescript
playerManager.setMessageInterceptor(
cast.framework.messages.MessageType.LOAD,
(loadRequestData: cast.framework.messages.LoadRequestData) => {
return streamManager.requestStream(loadRequestData, streamRequest);
}
);
```
## Stream Event and Error Handling
Add listeners on `google.ima.cast.dai.api.StreamManager` for all event types:
* DAI session events and errors
* Ad break events
* Individual ad events
### DAI session events
Listen for the `google.ima.cast.dai.api.StreamEvent.Type.ERROR` event to log the
`event.getStreamData().errorMessage` string and switch to a fallback stream.
### Ad break events
Listen for the `google.ima.cast.dai.api.StreamEvent.Type.AD_PERIOD_STARTED` and
`google.ima.cast.dai.api.StreamEvent.Type.AD_PERIOD_ENDED` events to disable and
restore playback controls, such as seeking.
### Ad events
Listen for the following events of individual ads to log them:
* `google.ima.cast.dai.api.StreamEvent.Type.STARTED`
* `google.ima.cast.dai.api.StreamEvent.Type.FIRST_QUARTILE`
* `google.ima.cast.dai.api.StreamEvent.Type.MIDPOINT`
* `google.ima.cast.dai.api.StreamEvent.Type.THIRD_QUARTILE`
* `google.ima.cast.dai.api.StreamEvent.Type.COMPLETE`
### Cleanup
Reset the `StreamManager` when a stream is ended, or a fatal error occurs.
```typescript
streamManager.reset();
```
ios-IMAStreamRequest-guide.md 5.7 KB
# Google IMA DAI SDK iOS/tvOS - IMAStreamRequest Guide
For Google full-service DAI, use `IMALiveStreamRequest` to request a livestream
and `IMAVODStreamRequest` to request a VOD stream.
## Table of Contents
* [Dependencies](#dependencies) (Line 19)
* [Use Swift Package Manager](#use-swift-package-manager) (Line 21)
* [SDK Initialization](#sdk-initialization) (Line 35)
* [UI Setup & Video Player](#ui-setup--video-player) (Line 51)
* [Make stream requests](#make-stream-requests) (Line 68)
* [Request a livestream](#request-a-livestream) (Line 72)
* [Request a VOD stream](#request-a-vod-stream) (Line 92)
* [Listen to Stream Load Events](#listen-to-stream-load-events) (Line 116)
* [Listen to Stream and Ad Events](#listen-to-stream-and-ad-events) (Line 119)
* [Reference Implementation](#reference-implementation) (Line 182)
## Dependencies
### Use Swift Package Manager
For iOS, add this package:
```
https://github.com/googleads/swift-package-manager-google-interactive-media-ads-ios
```
For tvOS, add this package:
```
https://github.com/googleads/swift-package-manager-google-interactive-media-ads-tvos
```
## SDK Initialization
Initialize the `IMAAdsLoader` early, such as in `ViewController.viewDidLoad`
event.
```swift
import GoogleInteractiveMediaAds
class ViewController {
override func viewDidLoad() {
super.viewDidLoad()
adsLoader = IMAAdsLoader(settings: IMASettings())
}
}
```
## UI Setup & Video Player
Create `IMAAdDisplayContainer` object using the `videoView` containing the
`AVPlayer`. Ad UI components will be rendered within the `videoView` over the
player.
```swift
adDisplayContainer = IMAAdDisplayContainer(adContainer: videoView, viewController: self)
```
Create `IMAAVPlayerVideoDisplay` with the `AVPlayer` instance so that the IMA
DAI SDK can listen to the video player for timed metadata during ad breaks.
```swift
imaVideoDisplay = IMAAVPlayerVideoDisplay(avPlayer: videoPlayer)
```
## Make stream requests
Reuse the same `AdsLoader` instance to make stream requests.
### Request a livestream
Instantiate `IMALiveStreamRequest` with the asset key and network code:
```swift
let request = IMALiveStreamRequest(
assetKey: <ASSET_KEY_PLACEHOLDER>,
networkCode: <NETWORK_CODE_PLACEHOLDER>,
adDisplayContainer: adDisplayContainer,
videoDisplay: imaVideoDisplay,
userContext: nil)
adsLoader.requestStream(with: request)
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<ASSET_KEY_PLACEHOLDER>**: The livestream asset key configured in Google
Ad Manager.
### Request a VOD stream
Instantiate `IMAVODStreamRequest` with content source ID (CMS ID) and video ID:
```swift
let request = IMAVODStreamRequest(
contentSourceID: <CONTENT_SOURCE_ID_PLACEHOLDER>,
videoID: <VIDEO_ID_PLACEHOLDER>,
networkCode: <NETWORK_CODE_PLACEHOLDER>,
adDisplayContainer: adDisplayContainer,
videoDisplay: imaVideoDisplay,
userContext: nil)
adsLoader.requestStream(with: request)
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<CONTENT_SOURCE_ID_PLACEHOLDER>**: The CMS ID in Google Ad Manager.
* **<VIDEO_ID_PLACEHOLDER>**: The video ID in the CMS.
For testing purposes, use values of DAI sample streams from
https://developers.google.com/ad-manager/dynamic-ad-insertion/streams.md.txt?utm_source=agent-skills&utm_medium=content&utm_campaign=adr-ss-ai&utm_content=ima-dai-sdk
## Listen to Stream Load Events
Implement `IMAAdsLoaderDelegate` to handle stream initialization or failure:
```swift
func adsLoader(_ loader: IMAAdsLoader, adsLoadedWith adsLoadedData: IMAAdsLoadedData) {
print("DAI session ID: \(adsLoadedData.streamManager!.streamId!)")
streamManager = adsLoadedData.streamManager!
streamManager!.initialize(with: nil)
}
func adsLoader(_ loader: IMAAdsLoader, failedWith adErrorData: IMAAdLoadingErrorData) {
print("Failed to load DAI stream. Error: \(adErrorData.adError.message ?? "")")
playBackupStream()
}
```
## Listen to Stream and Ad Events
Implement `IMAStreamManagerDelegate` to receive stream events, ad lifecycle
events, and errors:
```swift
func streamManager(_ streamManager: IMAStreamManager, didReceive event: IMAAdEvent) {
print("Ad event: \(event.typeString)")
switch event.type {
case IMAAdEventType.STARTED:
if let ad = event.ad {
let extendedAdPodInfo = String(
format: "Showing ad %zd/%zd, bumper: %@, title: %@, "
+ "description: %@, contentType:%@, pod index: %zd, "
+ "time offset: %lf, max duration: %lf.",
ad.adPodInfo.adPosition,
ad.adPodInfo.totalAds,
ad.adPodInfo.isBumper ? "YES" : "NO",
ad.adTitle,
ad.adDescription,
ad.contentType,
ad.adPodInfo.podIndex,
ad.adPodInfo.timeOffset,
ad.adPodInfo.maxDuration)
print("\(extendedAdPodInfo)")
}
break
case IMAAdEventType.AD_BREAK_STARTED:
print("Ad break started.")
break
case IMAAdEventType.AD_BREAK_ENDED:
print("Ad break ended.")
break
case IMAAdEventType.AD_PERIOD_STARTED:
print("Ad period started.")
break
case IMAAdEventType.AD_PERIOD_ENDED:
print("Ad period ended.")
break
default:
break
}
}
func streamManager(_ streamManager: IMAStreamManager, didReceive error: IMAAdError) {
print("Failed to play DAI stream. Error: \(error.message ?? "Unknown Error")")
playBackupStream()
}
```
## Reference Implementation
BasicExample:
* [iPhone.storyboard](https://raw.githubusercontent.com/googleads/googleads-ima-ios-dai/refs/heads/main/Swift/BasicExample/app/iPhone.storyboard)
* [ViewController.swift](https://raw.githubusercontent.com/googleads/googleads-ima-ios-dai/refs/heads/main/Swift/BasicExample/app/ViewController.swift)
roku-StreamManager-guide.md 7.2 KB
# Google IMA DAI SDK Roku - StreamManager Guide
For Google full-service DAI, use `CreateLiveStreamRequest` to request a
livestream and `CreateVodStreamRequest` to request a VOD stream.
## Table of Contents
* [Import the IMA DAI SDK](#import-the-ima-dai-sdk) (Line 21)
* [SDK Initialization](#sdk-initialization) (Line 43)
* [Video Player Setup](#video-player-setup) (Line 54)
* [Make Stream Requests](#make-stream-requests) (Line 87)
* [Request a livestream](#request-a-livestream) (Line 89)
* [Request a VOD stream](#request-a-vod-stream) (Line 105)
* [Execute stream request](#execute-stream-request) (Line 126)
* [Start Stream Playback](#start-stream-playback) (Line 153)
* [Timed Metadata Forwarding](#timed-metadata-forwarding) (Line 177)
* [Listen to Ad Events](#listen-to-ad-events) (Line 205)
* [Skippable Ads Support](#skippable-ads-support) (Line 244)
* [Reference Implementation](#reference-implementation) (Line 256)
## Import the IMA DAI SDK
Add the required libraries to `manifest`:
```
bs_libs_required=roku_ads_lib,googleima3
```
Create a Task component `components/Sdk.xml` to load libraries and run the SDK
on a background thread:
```xml
<component name="imasdk" extends="Task">
<script type="text/brightscript">
<![CDATA[
Library "Roku_Ads.brs"
Library "IMA3.brs"
]]>
</script>
</component>
```
## SDK Initialization
Initialize the IMA SDK instance using `New_IMASDK()`:
```brightscript
if m.sdk = invalid
m.sdk = New_IMASDK()
m.sdk.initSdk()
end if
```
## Video Player Setup
Create the player instance with `sdk.createPlayer()`.
```brightscript
m.player = m.sdk.createPlayer()
m.player.top = m.top
```
Create ad break callbacks:
```brightscript
m.player.loadUrl = Function(urlData)
m.top.video.enableTrickPlay = false
m.top.urlData = urlData
End Function
m.player.adBreakStarted = Function(adBreakInfo as Object)
m.top.adPlaying = true
m.top.video.enableTrickPlay = false
End Function
m.player.adBreakEnded = Function(adBreakInfo as Object)
m.top.adPlaying = false
m.top.video.enableTrickPlay = true
End Function
m.player.seek = Function(timeSeconds as Double)
m.top.video.seekMode = "accurate"
m.top.video.seek = timeSeconds
End Function
```
## Make Stream Requests
### Request a livestream
```brightscript
streamRequest = m.sdk.CreateLiveStreamRequest(
<ASSET_KEY_PLACEHOLDER>,
"", ' Replace the empty string with a Google DAI API key if the app uses one
<NETWORK_CODE_PLACEHOLDER>
)
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<ASSET_KEY_PLACEHOLDER>**: The livestream asset key configured in Google
Ad Manager.
### Request a VOD stream
```brightscript
streamRequest = m.sdk.CreateVodStreamRequest(
<CONTENT_SOURCE_ID_PLACEHOLDER>,
<VIDEO_ID_PLACEHOLDER>,
"", ' Replace the empty string with a Google DAI API key if the app uses one
<NETWORK_CODE_PLACEHOLDER>
)
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<CONTENT_SOURCE_ID_PLACEHOLDER>**: The content source ID (CMS ID) in
Google Ad Manager.
* **<VIDEO_ID_PLACEHOLDER>**: The video ID in the CMS.
For testing purposes, use values of DAI sample streams from
https://developers.google.com/ad-manager/dynamic-ad-insertion/streams.md.txt?utm_source=agent-skills&utm_medium=content&utm_campaign=adr-ss-ai&utm_content=ima-dai-sdk
### Execute stream request
Pass the player object and video node reference (`adUiNode`) to the request.
```brightscript
streamRequest.player = m.player
streamRequest.adUiNode = m.top.findNode("myVideo")
requestResult = m.sdk.requestStream(streamRequest)
If requestResult <> Invalid
print "Error requesting stream ";requestResult
Else
m.streamManager = Invalid
While m.streamManager = Invalid
sleep(50)
m.streamManager = m.sdk.getStreamManager()
End While
If m.streamManager = Invalid or (m.streamManager["type"] <> Invalid and m.streamManager["type"] = "error")
errors = CreateObject("roArray", 1, True)
print "error ";m.streamManager["info"]
errors.push(m.streamManager["info"])
m.top.errors = errors
Else
m.streamManager.start()
End If
End If
```
## Start Stream Playback
Listen for the stream manifest data in `MainScene.xml` and pass it to the
`Video` node:
```brightscript
m.sdkTask.observeField("urlData", "urlLoadRequested")
' Setting control to run starts the task thread.
m.sdkTask.control = "RUN"
Sub urlLoadRequested(message as Object)
data = message.getData()
vidContent = createObject("RoSGNode", "ContentNode")
vidContent.url = data.manifest
vidContent.title = m.videoTitle
vidContent.streamformat = data.format
m.video.content = vidContent
m.video.setFocus(true)
m.video.visible = true
m.video.control = "play"
m.video.EnableCookies()
End Sub
```
## Timed Metadata Forwarding
Forward all timed metadata and video node events to
`StreamManager.onMessage(msg)` during stream playback:
```brightscript
m.top.video.timedMetaDataSelectionKeys = ["*"]
m.port = CreateObject("roMessagePort")
fields = m.top.video.getFields()
for each field in fields
m.top.video.observeField(field, m.port)
end for
while true
msg = wait(1000, m.port)
if m.top.video = invalid
exit while
end if
m.streamManager.onMessage(msg)
currentTime = m.top.video.position
if currentTime > 3 and not m.top.adPlaying
m.top.video.enableTrickPlay = true
end if
end while
```
## Listen to Ad Events
Register event listeners on `m.streamManager` to monitor ad lifecycle and error
events:
```brightscript
m.streamManager.addEventListener(m.sdk.AdEvent.ERROR, errorCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.START, startCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.FIRST_QUARTILE, firstQuartileCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.MIDPOINT, midpointCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.THIRD_QUARTILE, thirdQuartileCallback)
m.streamManager.addEventListener(m.sdk.AdEvent.COMPLETE, completeCallback)
Function startCallback(ad as Object) as Void
print "Ad event: START"
End Function
Function firstQuartileCallback(ad as Object) as Void
print "Ad event: FIRST_QUARTILE"
End Function
Function midpointCallback(ad as Object) as Void
print "Ad event: MIDPOINT"
End Function
Function thirdQuartileCallback(ad as Object) as Void
print "Ad event: THIRD_QUARTILE"
End Function
Function completeCallback(ad as Object) as Void
print "Ad event: COMPLETE"
End Function
Function errorCallback(error as Object) as Void
print "Ad event: ERROR - "; error
m.errorState = true
End Function
```
### Skippable Ads Support
To support skippable ads, implement the `seek` callback method on `m.player` and
ensure `streamRequest.adUiNode` is set to the video node in the stream request:
```brightscript
m.player.seek = Function(timeSeconds as Double)
m.top.video.seekMode = "accurate"
m.top.video.seek = timeSeconds
End Function
```
## Reference Implementation
BasicExample:
* [Sdk.xml](https://raw.githubusercontent.com/googleads/googleads-ima-roku-dai/refs/heads/main/basic_example/components/Sdk.xml)
* [MainScene.xml](https://raw.githubusercontent.com/googleads/googleads-ima-roku-dai/refs/heads/main/basic_example/components/MainScene.xml)
web-StreamManager-guide.md 7.9 KB
# Google IMA DAI SDK HTML5 (Web) integration guide
This guide covers the integration of the Google IMA DAI (Dynamic Ad Insertion)
SDK for web applications to run in a desktop browser or mobile browser.
## Table of Contents
* [Integration flow](#integration-flow) (Line 24)
* [Import the SDK](#import-the-sdk) (Line 26)
* [Initialization](#initialization) (Line 35)
* [Request DAI streams](#request-dai-streams) (Line 55)
* [Request a livestream](#request-a-livestream) (Line 57)
* [Request a VOD stream](#request-a-vod-stream) (Line 86)
* [Timed metadata forwarding](#timed-metadata-forwarding) (Line 121)
* [Passing raw ID3 frames from HLS manifest](#passing-raw-id3-frames-from-hls-manifest)
(Line 126)
* [Passing custom event data from DASH manifest](#passing-custom-event-data-from-dash-manifest)
(Line 145)
* [Stream Event and Error Handling](#stream-event-and-error-handling)
(Line 165)
* [DAI session events](#dai-session-events) (Line 173)
* [Ad break events](#ad-break-events) (Line 181)
* [Ad events](#ad-events) (Line 187)
* [Cleanup](#cleanup) (Line 201)
* [Reference implementation](#reference-implementation) (Line 209)
## Integration flow
### Import the SDK
Load the IMA DAI SDK script loader at the page level. Ensure the SDK can access
`window.top.location.href`.
```html
<script src="https://imasdk.googleapis.com/js/sdkloader/ima3_dai.js"></script>
```
### Initialization
Instantiate the `StreamManager` early. It requires the HTML video element and an
HTML `div` element overlaying the video element for the ad UI elements.
```html
<div id="player-container">
<video id="video-element" controls></video>
<div id="ad-ui-element"></div>
</div>
```
```typescript
const videoElement = document.getElementById('video-element') as HTMLVideoElement;
const adUiElement = document.getElementById('ad-ui-element') as HTMLElement;
// Instantiate the StreamManager
const streamManager = new google.ima.dai.api.StreamManager(videoElement, adUiElement);
```
## Request DAI streams
### Request a livestream
Instantiate `google.ima.dai.api.LiveStreamRequest` to request a Google DAI
linear stream using the default HLS M3U8 format.
```typescript
const hlsLiveStreamRequest = new google.ima.dai.api.LiveStreamRequest();
hlsLiveStreamRequest.assetKey = <ASSET_KEY_PLACEHOLDER>;
hlsLiveStreamRequest.networkCode = <NETWORK_CODE_PLACEHOLDER>;
streamManager.requestStream(hlsLiveStreamRequest);
```
To request a Google DAI linear stream using the DASH MPD format, ensure to
explicitly set the `LiveStreamRequest.format` property as follows:
```typescript
const dashLiveStreamRequest = new google.ima.dai.api.LiveStreamRequest();
dashLiveStreamRequest.assetKey = <ASSET_KEY_PLACEHOLDER>;
dashLiveStreamRequest.networkCode = <NETWORK_CODE_PLACEHOLDER>;
dashLiveStreamRequest.format = 'dash';
streamManager.requestStream(dashLiveStreamRequest);
```
Provide the following parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<ASSET_KEY_PLACEHOLDER>**: The livestream asset key configured in Google
Ad Manager.
### Request a VOD stream
Instantiate `google.ima.dai.api.VODStreamRequest` to request a Google DAI VOD
stream using the default HLS M3U8 format.
```typescript
const hlsVodStreamRequest = new google.ima.dai.api.VODStreamRequest();
hlsVodStreamRequest.networkCode = <NETWORK_CODE_PLACEHOLDER>;
hlsVodStreamRequest.contentSourceId = <CONTENT_SOURCE_ID_PLACEHOLDER>;
hlsVodStreamRequest.videoId = <VIDEO_ID_PLACEHOLDER>;
streamManager.requestStream(hlsVodStreamRequest);
```
To request a Google DAI VOD stream using the DASH MPD format, set the
`VODStreamRequest.format` property as follows:
```typescript
const dashVodStreamRequest = new google.ima.dai.api.VODStreamRequest();
dashVodStreamRequest.networkCode = <NETWORK_CODE_PLACEHOLDER>;
dashVodStreamRequest.contentSourceId = <CONTENT_SOURCE_ID_PLACEHOLDER>;
dashVodStreamRequest.videoId = <VIDEO_ID_PLACEHOLDER>;
dashVodStreamRequest.format = 'dash';
streamManager.requestStream(dashVodStreamRequest);
```
Provide the following required parameters:
* **<NETWORK_CODE_PLACEHOLDER>**: The Google Ad Manager network code.
* **<CONTENT_SOURCE_ID_PLACEHOLDER>**: The content source ID (CMS ID) in
Google Ad Manager.
* **<VIDEO_ID_PLACEHOLDER>**: The video ID in the CMS.
For testing purposes, use values of DAI sample streams from
https://developers.google.com/ad-manager/dynamic-ad-insertion/streams.md.txt?utm_source=agent-skills&utm_medium=content&utm_campaign=adr-ss-ai&utm_content=ima-dai-sdk
## Timed metadata forwarding
For the SDK to trigger ad events, ensure to listen to the video player's events
to extract the timed metadata and pass it to the SDK for immediate processing.
### Passing raw ID3 frames from HLS manifest
Capture and pass the embedded ID3 metadata to the SDK for processing.
If HLS.js is used, listen for the `FRAG_PARSING_METADATA` event.
```typescript
import Hls, { FragParsingMetadataData } from 'hls.js';
hls.on(Hls.Events.FRAG_PARSING_METADATA, (event: Events.FRAG_PARSING_METADATA, data: FragParsingMetadataData): void => {
// Iterate over each parsed metadata sample
data.samples.forEach((sample) => {
// sample.data: Uint8Array containing raw ID3 data
// sample.pts: Presentation timestamp for precise synchronization
streamManager.processMetadata('ID3', sample.data, sample.pts);
});
});
```
### Passing custom event data from DASH manifest
If DASH.js is used, listen for the DASH custom event identified by the Google
DAI scheme ID and pass the event payload data to the SDK for processing.
```typescript
interface DashEventPayload {
event: {
messageData: Uint8Array;
calculatedPresentationTime: number;
};
}
dashPlayer.on('urn:google:dai:2018', (payload: DashEventPayload): void => {
const mediaId = payload.event.messageData;
const pts = payload.event.calculatedPresentationTime;
streamManager.processMetadata('urn:google:dai:2018', mediaId, pts);
});
```
## Stream Event and Error Handling
Add listeners on `google.ima.dai.api.StreamManager` for all event types:
* DAI session events and errors
* Ad break events
* Individual ad events
### DAI session events
Listen for the `google.ima.dai.api.StreamEvent.Type.LOADED` event to retrieve
and pass the `event.getStreamData().url` string to the video player.
Listen for the `google.ima.dai.api.StreamEvent.Type.ERROR` event to log the
`event.getStreamData().errorMessage` string and switch to a fallback stream.
### Ad break events
Listen for the `google.ima.dai.api.StreamEvent.Type.AD_PERIOD_STARTED` and
`google.ima.dai.api.StreamEvent.Type.AD_PERIOD_ENDED` events to disable and
restore playback controls, such as seeking.
### Ad events
Listen for the following events of individual ads to log them:
* `google.ima.dai.api.StreamEvent.Type.STARTED`
* `google.ima.dai.api.StreamEvent.Type.FIRST_QUARTILE`
* `google.ima.dai.api.StreamEvent.Type.MIDPOINT`
* `google.ima.dai.api.StreamEvent.Type.THIRD_QUARTILE`
* `google.ima.dai.api.StreamEvent.Type.COMPLETE`
* `google.ima.dai.api.StreamEvent.Type.CLICK`: When this click-through event
occurs, the SDK pauses the ad playback and takes the user to the ad landing
page. Ensure to prepare the app's UI for the user to resume ad playback upon
returning from the ad landing page.
### Cleanup
Reset the `StreamManager` when a stream is ended, or a fatal error occurs.
```typescript
streamManager.reset();
```
## Reference implementation
HLS.js integration:
* [HTML page](https://raw.githubusercontent.com/googleads/googleads-ima-html5-dai/refs/heads/main/hls_js/simple/dai.html)
* [App logic](https://raw.githubusercontent.com/googleads/googleads-ima-html5-dai/refs/heads/main/hls_js/simple/dai.js)
DASH.js integration:
* [HTML page](https://raw.githubusercontent.com/googleads/googleads-ima-html5-dai/refs/heads/main/dash_js/simple/dai.html)
* [App logic](https://raw.githubusercontent.com/googleads/googleads-ima-html5-dai/refs/heads/main/dash_js/simple/dai.js)
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE