Creare il corso Gestione annunci

In ads_manager.js, definisci una classe wrapper per StreamManager dell'SDK IMA che effettua richieste di stream, recupera il manifest del pod di annunci, ascolta gli eventi di stream IMA e passa gli eventi emsg all'SDK IMA.

In ads_manager.js, l'app di esempio HbbTV dell'SDK IMA configura i seguenti metodi:

  • requestStream()
  • onStreamEvent()
  • onEmsgEvent()
  • loadAdPodManifest()

Inizializza Ads Manager

Inizializza la classe AdsManager e imposta i listener per gli eventi di flusso IMA. In questa chiamata, imposta il gestore di eventi emsg con il metodo VideoPlayer.setEmsgEventHandler().

/**
 * Wraps IMA SDK ad stream manager.
 * @param {!VideoPlayer} videoPlayer Reference an instance of the wrapper from
 * video_player.js.
 */
var AdManager = function(videoPlayer) {
  this.streamData = null;
  this.videoPlayer = videoPlayer;
  // Ad UI is not supported for HBBTV, so no 'adUiElement' is passed in the
  // StreamManager constructor.
  this.streamManager = new google.ima.dai.api.StreamManager(
      this.videoPlayer.videoElement);
  this.streamManager.addEventListener(
      [
        google.ima.dai.api.StreamEvent.Type.STREAM_INITIALIZED,
        google.ima.dai.api.StreamEvent.Type.ERROR,
        google.ima.dai.api.StreamEvent.Type.CLICK,
        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.AD_BREAK_STARTED,
        google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED,
        google.ima.dai.api.StreamEvent.Type.AD_PROGRESS,
        google.ima.dai.api.StreamEvent.Type.PAUSED,
        google.ima.dai.api.StreamEvent.Type.RESUMED
      ],
      this.onStreamEvent.bind(this),
      false);

  this.videoPlayer.setEmsgEventHandler(this.onEmsgEvent, this);
};

Inviare una richiesta per uno stream di pod di annunci

Crea il metodo AdManager.requestStream() per creare un oggetto PodStreamRequest utilizzando il codice di rete della rete Google Ad Manager e la chiave dell'asset personalizzato dello stream. Testa la tua app HbbTV utilizzando lo stream di pubblicazione di pod DASH di esempio IMA con i seguenti parametri dello stream:

  • Codice di rete: '21775744923'
  • Chiave asset personalizzata: 'hbbtv-dash'
/**
 * Makes a pod stream request.
 * @param {string} networkCode The network code.
 * @param {string} customAssetKey The custom asset key.
 */
AdManager.prototype.requestStream = function (networkCode, customAssetKey) {
  var streamRequest = new google.ima.dai.api.PodStreamRequest();
  var secretKey = getStreamSecretKeys();

  streamRequest.networkCode = networkCode;
  streamRequest.customAssetKey = customAssetKey;
  streamRequest.format = 'dash';

  if (secretKey.STREAM_CREATE_SECRET) {
    var expirationTime = Math.trunc(new Date().getTime() / 1000) + 3600;
    var params = {
      custom_asset_key: customAssetKey,
      exp: expirationTime,
      network_code: networkCode
    };
    streamRequest.authToken =
        this.generateAuthToken(params, secretKey.STREAM_CREATE_SECRET);
    debugView.log('AdsManager: make Auth-PodStreamRequest');
  } else {
    debugView.log('AdsManager: make PodStreamRequest without auth');
  }

  this.streamManager.requestStream(streamRequest);
};

Ascoltare gli eventi dello stream di annunci

Crea il metodo AdManager.onStreamEvent() per gestire la risposta della tua app agli eventi di stream IMA, STREAM_INITIALIZED, AD_BREAK_STARTED e AD_BREAK_ENDED.

/**
 * Handles IMA playback events.
 * @param {!Event} event The event object.
 */
AdManager.prototype.onStreamEvent = function(event) {
  switch (event.type) {
    // Once the stream response data is received, generate pod manifest url
    // for the video stream.
    case google.ima.dai.api.StreamEvent.Type.STREAM_INITIALIZED:
      debugView.log('IMA SDK: stream initialized');
      this.streamData = event.getStreamData();
      break;
    case google.ima.dai.api.StreamEvent.Type.ERROR:
      break;
    // Hide video controls while ad is playing.
    case google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED:
      debugView.log('IMA SDK: ad break started');
      this.adPlaying = true;
      this.adBreakStarted = true;
      break;
    // Show video controls when ad ends.
    case google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED:
      debugView.log('IMA SDK: ad break ended');
      this.adPlaying = false;
      this.adBreakStarted = false;
      break;
    // Update ad countdown timers.
    case google.ima.dai.api.StreamEvent.Type.AD_PROGRESS:
      break;
    default:
      debugView.log('IMA SDK: ' + event.type);
      break;
  }
};

Gestire i metadati dello stream di annunci

Per trasmettere le informazioni sull'evento emsg a IMA, crea il metodo AdManager.onEmsgEvent() utilizzando il metodo StreamManager.processMetadata(). La classe del video player chiama questo metodo con il metodo VideoPlayer.setEmsgEventHandler().

/**
 * Callback on Emsg event.
 * Instructs IMA SDK to fire back VAST events accordingly.
 * @param {!Event} event The event object.
 */
AdManager.prototype.onEmsgEvent = function(event) {
  var data = event.event.messageData;
  var pts = event.event.calculatedPresentationTime;
  if ((data instanceof Uint8Array) && data.byteLength > 0) {
    this.streamManager.processMetadata('ID3', data, pts);
  }
};

Carica il manifest del pod di annunci

Crea il metodo AdManager.loadAdPodManifest() per precaricare il manifest del pod di annunci con il video player. Crea un URL manifest autenticato utilizzando la struttura in Metodo: manifest del pod DASH.

/**
 * Creates DAI pod url and instructs video player to load manifest.
 * @param {string} networkCode The network code.
 * @param {string} customAssetKey The custom asset key.
 * @param {number} podDuration The duration of the ad pod.
 */
AdManager.prototype.loadAdPodManifest = function (networkCode, customAssetKey, podDuration) {
  if (!this.streamData) {
    debugView.log('AdsManager: No stream data available.');
    return;
  }

  var adBreakId = this.getAdBreakId();
  var expirationTime = Math.trunc(new Date().getTime() / 1000) + 3600;

  var params = {
    ad_break_id: adBreakId,
    custom_asset_key: customAssetKey,
    exp: expirationTime,
    network_code: networkCode,
    pd: podDuration
  };

  var secretKey = getStreamSecretKeys();
  var token = this.generateAuthToken(params, secretKey.MANIFEST_SECRET);
  var encodedToken = encodeURIComponent(token);

  var manifestUrl = 'https://dai.google.com/linear/pods/v1/dash/network/' +
    networkCode + '/custom_asset/' + customAssetKey + '/stream/' +
    this.streamData.streamId + '/ad_break_id/' + adBreakId +
    '/manifest.mpd?pd=' + podDuration + '&auth-token=' + encodedToken;

  this.videoPlayer.preload(manifestUrl);
};

L'app di esempio HbbTV utilizza un valore adBreakId univoco generato in modo casuale. Nelle app di produzione, il valore adBreakId è una stringa alfanumerica, ad esempio ab-001, che aumenta di uno per ogni interruzione pubblicitaria. Verifica che il valore di adBreakId sia lo stesso per tutti gli spettatori dell'interruzione pubblicitaria. Per ottenere un valore adBreakId, ti consigliamo di utilizzare l'API DAI Ad Break. In un ambiente di produzione, includi il valore adBreakId e il valore podDuration nell'evento di flusso HbbTV AD_BREAK_ANNOUNCE.

Successivamente, crea la classe dell'applicazione principale per la tua app HbbTV che interagisce con la trasmissione HbbTV.