Live Stream Pre-fetch

The IMA SDK can be used to monetize live streams as well as video-on-demand. For live streams, you need to make a new ad request for each ad break. Stagger these requests to ensure that all of your viewers aren't requesting ads at the same time and bogging down the ad server(s).

To help with this, the IMA SDK has the AdsRequest.liveStreamPrefetchSeconds property. This property specifies the maximum number of seconds the SDK should wait before reaching out to the ad server after you call AdsLoader.requestAds(). The actual request time will be randomized. For example, if you set AdsRequest.liveStreamPrefetchSeconds to 30, the SDK waits 0 to 30 seconds after you call AdsLoader.requestAds() to actually make the request to the server.

Prerequisites

Check out our Get Started guide for the HTML5 SDK.

Live stream pre-fetch in practice

We recommend pre-fetching your next ad break as soon as an ad break completes. This ensures the maximum length of time is available for your pre-fetch window. Suppose you have 5 minutes between ad breaks. When an ad break completes, you can request your next ad break with a pre-fetch window of 290 seconds (5 minutes minus 10 seconds, to make sure the requests sent at the end of the pre-fetch window have enough time to resolve):

// 5 minutes == 300 seconds. We'll include a 10 second buffer
var AD_INTERVAL = 290;

function onAdEvent(adEvent) {
  var ad = adEvent.getAd();
  switch(adEvent.type) {
    case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
      // Pre-fetch our next ad break.
      requestAds();
      // Play those ads in 5 minutes. In a real-world implementation,
      // this will likely be done as the result of a message from your
      // streaming server, not a timeout.
      setTimeout(playAds, AD_INTERVAL * 1000);// Convert to ms.
  }
}

function requestAds() {
  // Destroy the current AdsManager, in case the tag you requested previously
  // contains post-rolls (we don't want to play those now).
  if (adsManager) {
    adsManager.destroy();
  }
  // Your AdsLoader will be set up on page-load. You should re-use the same
  // AdsLoader for every request. For more info on setting up the AdsLoader,
  // see the "Get Started" guide in the prerequisites above.
  if (adsLoader) {
    // Reset the IMA SDK.
    adsLoader.contentComplete();
  }
  var adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = '...';
  adsRequest.linearAdSlotWidth = <linear_width>;
  adsRequest.linearAdSlotHeight = <linear_height>;
  adsRequest.nonLinearAdSlotWidth = <nonlinear_width>;
  adsRequest.nonLinearAdSlotHeight = <nonlinear_height>;
  adsRequest.liveStreamPrefechSeconds = AD_INTERVAL;
  adsLoader.requestAds(adsRequest);
}

function playAds() {
  adsManager.init(
      <linear_width>,  <linear_height>, google.ima.ViewMode.NORMAL);
  adsManager.start();
}

Send feedback about...

IMA SDK for HTML5
Need help? Visit our support page.