Server Side Ad Insertion using MediaTailor
MediaTailor Ads
The MediaTailor library provides seamless integration with AWS MediaTailor for server-side ad insertion (SSAI) in video streaming applications.
Setup
Wiring Authorization Response
Once an asset is authorized for Playback (refer Authorize Playback for an Asset), the authorization response indicates the ssaiAdProvider should be mediatailor, adtype be ssai andcustom field will have mtSessionUrl. The mediatailor ad player must be setup only when all of the metadata are available.
| Name | Description |
|---|---|
| ssaiAdProvider | Indicates the ad provider |
| adtype | type of the ad being served either csai or ssai |
| mtSessionUrl | mediatailor session url to get content url and ad tracking url |
Usage
This first step is the creation of a MediaTailor Manager instance that will be used to intialize the session to retrieve playback URL and ad tracking URL to create MediaTailor Ad player.
Create a Mediatailor Manager
const mediatailorSession = flAdsMediatailor.createMediatailorSession();
Session creation
The initialize method orchestrates the MediaTailor session creation process
- Server Side
- Client Side
const mediaTailorSessionConfiguration: MediatailorSessionConfiguration = {
adsParams: { customAd: 'value1' }, // playbackAsset.custom.adsParams from playback Authorization
playerParams: { playerType: 'web' }, // playbackAsset.custom.playerParams from playback Authorization
manifestParams: { format: 'hls' },
availSuppression: {
mode: AvailSuppressionMode.BEHIND_LIVE_EDGE,
value: '00:00:21',
},
adSignaling: true,
originParams: {
customOriginParam1: 'value1',
customOriginParam2: 'value2',
region: 'us-east-1',
},
overlayAvails: OverlayAvailsMode.ON,
// Set reporting mode
reportingMode: ReportingMode.SERVER, // Optional. Default value is SERVER
};
const mediaTailorSessionConfiguration: MediatailorSessionConfiguration = {
adsParams: { customAd: 'value1' }, // playbackAsset.custom.adsParams from playback Authorization
playerParams: { playerType: 'web' }, // playbackAsset.custom.playerParams from playback Authorization
manifestParams: { format: 'hls' },
availSuppression: {
mode: AvailSuppressionMode.BEHIND_LIVE_EDGE,
value: '00:00:21',
},
adSignaling: true,
originParams: {
customOriginParam1: 'value1',
customOriginParam2: 'value2',
region: 'us-east-1',
},
overlayAvails: OverlayAvailsMode.ON,
// Set reporting mode
reportingMode: ReportingMode.CLIENT,
configId: "<datazoom-key>" ,
liveAdTrackingMode: AdTrackingUpdateMode.Full // Optional. Defaults to PAGINATION for live sessions.
};
MediaTailor Initialization
const mediatailorInitializationData: MediatailorInitializationData = {
sessionUrl: playbackAsset.custom.mtSessionUrl,
fallbackUrl: playbackAsset.contentUrl,
mediaTailorSessionConfiguration: mediaTailorSessionConfiguration,
maxRetries: 1,
connectionTimeoutInMS: 1000,
hlsAdTrackingPollIntervalInMS: 4000;
isLive: true; // true if content is LIVE and false for VOD
}
try {
const mediatailorMetadata: MediatailorMetadata = await mediatailorSession.initialize(
mediatailorInitializationData,
palConfiguration,
)
} catch (error: Error) {
console.log('Mediatailor session failure', error)
}
MediatailorInitializationData
| Name | Type | Optional | Description |
|---|---|---|---|
| sessionUrl | string | No | MediaTailor session url. |
| fallbackUrl | string | No | content url given by playback Authorization response in case of session failure |
| mediaTailorSessionConfiguration | MediaTailorSessionConfiguration | Yes | Ad targetting parameters. |
| maxRetries | number | Yes | Maxinum number of retries on network failures |
| connectionTimeoutInMS | number | Yes | Maximum amount of time (in milliseconds) to wait while trying to establish a connection before giving up. |
| hlsAdTrackingPollIntervalInMS | number | Yes | Interval to poll meditailor tracking api to get ad metadata for HLS live streams. NOTE: It would be nice to pass in minimum update period of the content. |
| isLive | boolean | Yes | true if the content is LIVE and false for VOD content |
MediatailorSessionConfiguration
| Parameter | Type | Description |
|---|---|---|
| adsParams | Map<String, Any>? | Key-value pairs that MediaTailor can read and send to the ad server in all session requests. This value will available from Playback Authorization response. |
| playerParams | Map<String, Any>? | Preceding configuration used for session initialization request that defines the player variables and their aliases. This value will available from Playback Authorization response. |
| manifestParams | Map<String, Any>? | Query parameters included in the parent manifest and tracking URLs in the response. |
| availSuppression | AvailSuppression | availSuppression |
| adSignaling | boolean | To enable ad ID signaling, add an adSignaling object as a top level object, and inside, add a parameter called enabled and value of true. The default adSignaling value is disabled. |
| originParams | Map<String, Any>? | custom origin parameters for the session. |
| overlayAvails | OverlayAvailsMode | MediaTailor support for overlay ads is enabled by default. A specific SCTE-35 ad-marker type in the manifest triggers the insertion of an overlay ad. Because some players might not support client-side rendering of overlay ads, you can disable the feature at the session level. |
| reportingMode | ReportingMode | MediaTailor supports a hybrid mode for session tracking. In this mode, the service emits playback-related ad-tracking events, but makes the complete client-side tracking payload available for the session. |
| liveAdTrackingMode | AdTrackingUpdateMode | Controls how ad tracking updates are retrieved from MediaTailor for live sessions only. Supported modes are FULL, PLAYHEAD, and PAGINATION. If not specified, live sessions default to PAGINATION. VOD sessions always use FULL, and this setting has no effect for VOD. |
AvailSuppression
| Parameter | Type | Description |
|---|---|---|
| mode | AvailSuppressionMode | ad break suppression |
| value | string | A time relative to the live edge in a live stream |
AvailSuppressionMode
| Parameter | Description |
|---|---|
| OFF | Ad suppression is OFF |
| BEHIND_LIVE_EDGE | When set to BEHIND_LIVE_EDGE, MediaTailor doesn't fill ad breaks on or behind the aws.availSuppressionValue time |
| AFTER_LIVE_EDGE_FULL_AVAIL_ONLY | MediaTailor doesn't fill ad breaks on or behind the avail suppression period and full avail suppression policy |
| AFTER_LIVE_EDGE_PARTIAL_AVAIL | MediaTailor doesn't fill ad breaks on or behind the avail suppression period and invoke partial ad break fills when and session starts mid-break |
OverlayAvailsMode
| Parameter | Description |
|---|---|
| ON | Enabling overlaying ads |
| OFF | Disabling overlaying ads |
ReportingMode
| Parameter | Description |
|---|---|
| SERVER | MediaTailor supports a hybrid mode for session tracking. In this mode, the service emits playback-related ad-tracking events, but makes the complete client-side tracking payload available for the session |
| CLIENT | Client-side ad tracking handled by the player/SDK. Requires initializing your analytics provider with its configId and passing a valid videoElement to createMediatailorPlayer for OMID/analytics. |
AdTrackingUpdateMode
| Parameter | Description |
|---|---|
| FULL | Retrieves ad tracking information for all ads in the current manifest window. |
| PLAYHEAD | Retrieves ad tracking information only for ad avails near the current playback position. Requires AWS MediaTailor playhead tracking support. |
| PAGINATION | Retrieves only newly available ad tracking information using a pagination token, avoiding retransmission of previously received data. |
PALConfiguration
| Property | Type | Description |
|---|---|---|
| willAdAutoPlay | boolean | Defines whether the ad will be auto played without waiting for user interaction or not. |
| willAdPlayMuted | boolean | Defines whether the ad will be played while muted or not. |
| continuousPlayback | boolean | Defines whether the player intends to continuously play the content videos one after another similar to TV broadcast or video playlist. |
| descriptionUrl | string | Defines the description URL of the content during which the ad will be played. |
| iconsSupported | boolean | Defines whether VAST icons are supported by the video player. |
| nonceLengthLimit | number | Defines the length limit of the generated nonce. |
| omidPartnerName | number | The name of the partner integrating OMID measurement. |
| omidPartnerVersion | string | The version of the partner integrating OMID measurement. |
| omidVersion | string | The version of OMID that the player responsible for ad playback integrates with. |
| playerType | string | The partner provided player type. |
| playerVersion | string | The partner provided player version. |
| ppid | string | The publisher provided ID. |
| videoHeight | number | The height of the ad video element. |
| videoWidth | number | The width of the ad video element. |
MediatailorMetadata
| Name | Type | Optional | Description |
|---|---|---|---|
| manifestUrl | string | No | content url |
| isFallback | boolean | No | Signals if the content is fallback or not |
| fallbackReason | Error | Yes | Detailed description on reason to fallback. Note: This will be reported as adError |
| trackingUrl | string | Yes | MediaTailor ad tracking url used to retrieve ad metadata |
| adMetadata | MediaTailorTrackingResponse | Yes | ad metadata from tracking api response |
| adSessionId | string | Yes | Mediatailor session id |
Create Ad Composed Player
AdComposedPlayer managers both content and ad playback. It basically extends the conventional Player functionality and adds ads rendering to it.
const contentPlayer: Player = createPlayerBuilder()
.mediaElement(mediaElement)
.mediaUrl(mediatailorMetadata.manifestUrl)
.mediaType(MediaType.HLS)
.build();
const adsPlayer = mediatailorSession.createMediatailorPlayer(
contentPlayer,
mediatailorMetadata,
adPlaybackPolicy,
logger,
videoElement // Required only for client-side reporting (OMID/analytics)
);
Backend-initialized MediaTailor sessions
The following options apply only to tenants where playback authorization
initializes the MediaTailor session. Choose the flow using the returned
adStack. The SDK-initialized integration above continues to use
mtSessionUrl and requires no changes.
Client-side tracking with MT-CSB
When authorization returns MT-CSB, use the returned mtContentUrl and
mtTrackingUrl to initialize a Datazoom MediaTailor session. Provide both URLs
and a Datazoom configId. Don't pass sessionUrl in this flow.
import {
AdTrackingUpdateMode,
createMediatailorSession,
} from '@quickplay/ads-mediatailor';
const mediatailorSession = createMediatailorSession();
const mediatailorMetadata = await mediatailorSession.initialize({
manifestUrl: authData.custom.mtContentUrl,
trackingUrl: authData.custom.mtTrackingUrl,
fallbackUrl: authData.contentUrl,
isLive: true, // Set to false for VOD.
mediatailorSessionConfiguration: {
configId: '<datazoom-config-id>',
liveAdTrackingMode: AdTrackingUpdateMode.PAGINATION,
},
});
const contentPlayer = createPlayerBuilder()
.mediaElement(videoElement)
.mediaUrl(mediatailorMetadata.manifestUrl)
.mediaType(MediaType.HLS)
.build();
const adsPlayer = mediatailorSession.createMediatailorPlayer(
contentPlayer,
mediatailorMetadata,
adPlaybackPolicy,
logger,
videoElement,
);
reportingMode defaults to ReportingMode.CLIENT in this flow. You can set it
explicitly in mediatailorSessionConfiguration. Live tracking defaults to
PAGINATION; VOD always uses FULL. The SDK doesn't initialize a PAL nonce
for a pre-initialized session. If initialization fails, the SDK returns the
fallback URL in the metadata.
Server-side beaconing with MT-SSB
When authorization returns MT-SSB, play mtContentUrl on the base player.
This flow doesn't use a tracking URL or create a MediaTailor ad player. If you
use Godavari, pass the ad stack and stream URL in the content metadata.
import type { GodavariContent } from '@quickplay/analytics';
const contentPlayer = createPlayerBuilder()
.mediaElement(videoElement)
.mediaUrl(authData.custom.mtContentUrl)
.mediaType(MediaType.HLS)
.build();
const content: GodavariContent = {
...baseContent,
adStack: authData.adStack, // 'MT-SSB'
streamUrl: authData.custom.mtContentUrl,
};
const playbackSession = await appSession.createPlaybackSession(content, 'search');
playbackSession.attachPlayer(contentPlayer);
playbackSession.start();
For MT-SSB, Godavari reports the aws.sessionId query parameter as the SSAI
session ID when the player doesn't provide one. It also reports the video as
monetizable.
Fallback with NONE
When authorization returns adStack: 'NONE' after a MediaTailor failure or
timeout, play the original contentUrl on the base player without initializing
a MediaTailor session.
const contentPlayer = createPlayerBuilder()
.mediaElement(videoElement)
.mediaUrl(authData.contentUrl)
.mediaType(MediaType.HLS)
.build();
Listening to Ad Events
Subscribe to ad lifecycle and tracking events to monitor ad playback state, ad breaks, errors, cue points, and user interactions.
adsPlayer.subscribe(AdEvent.ADVERT_BREAK_START, (adBreakInfo: AdBreakInfo) => {
console.log('Ad break started', adBreakInfo);
});
adsPlayer.subscribe(AdEvent.ADVERT_START, (adInfo: AdInfo) => {
console.log('Ad started', adInfo);
});
adsPlayer.subscribe(AdEvent.ADVERT_END, (adInfo: AdInfo) => {
console.log('Ad ended', adInfo);
});
adsPlayer.subscribe(AdEvent.ADVERT_BREAK_END, (adBreakInfo: AdBreakInfo) => {
console.log('Ad break ended', adBreakInfo);
});
adsPlayer.subscribe(AdEvent.ADVERT_ERROR, (error: Error) => {
console.log('Ad Error', error);
});
adsPlayer.subscribe(AdEvent.ADVERT_TRACKING_EVENT, (trackingEvent: AdTrackingEvent) => {
console.log('Ad tracking event received', trackingEvent);
});
adsPlayer.subscribe(AdEvent.ADVERT_CUEPOINTS, (cuepoints: number[]) => {
console.log('Ad cue points received', cuepoints);
});
adsPlayer.subscribe(AdEvent.ADVERT_CLICK, (clickUrl: string) => {
console.log('Ad click received', clickUrl);
});
For both the default and Datazoom MediaTailor handlers, AdInfo.delivery
reports technology as server-side, stitcher as MediaTailor, and
managerName as AWS MediaTailor. If your integration matches the stitcher
name, update it from AWS MediaTailor to MediaTailor.
The composed player also exposes the MediaTailor session ID through
adSessionId and the stitcher name through ssaiAdSticher. See
Godavari integration details for
how these values are used in analytics.
Ad frequency control
To limit how often viewers see ads, see Ad frequency control.