Настройка IMA SDK для DAI

Выберите платформу: HTML5 Android iOS tvOS Cast Roku

Выберите интересующее вас решение DAI.

Полный спектр услуг DAI

В этом руководстве показано, как воспроизводить поток DAI с помощью SDK IMA CAF DAI. Если вы хотите посмотреть или проследить за завершенной интеграцией на примере, скачайте пример .

Перед использованием этого руководства обязательно ознакомьтесь с протоколом Web Receiver платформы Chromecast Application Framework . Это руководство предполагает базовое знакомство с концепциями приемника CAF, такими как перехватчики сообщений и объекты mediaInformation , а также знакомство с использованием инструмента Cast Command and Control для эмуляции отправителя CAF.

Для использования IMA DAI вам необходима учетная запись Ad Manager 360. Если у вас уже есть учетная запись Ad Manager, обратитесь к своему менеджеру по работе с клиентами за дополнительной информацией. Информацию о регистрации в Ad Manager можно найти в Справочном центре Ad Manager .

Для получения информации об интеграции с другими платформами или об использовании клиентских SDK IMA см. раздел «SDK для интерактивной рекламы» .

Обзор CAF DAI

Внедрение DAI с использованием IMA CAF DAI SDK включает в себя два основных компонента, как показано в этом руководстве:

  • StreamRequest : Объект, определяющий запрос потока данных на рекламные серверы Google. Запросы потока данных бывают двух основных типов:

    • LiveStreamRequest : указывает ключ ресурса , а также другие необязательные параметры.
    • VODStreamRequest : Указывает идентификатор источника контента , идентификатор видео , а также другие необязательные параметры.
    • Оба типа запросов могут дополнительно включать ключ API , необходимый для доступа к указанным потокам, и сетевой код Google Ad Manager для обработки идентификаторов рекламы в SDK IMA, как указано в настройках Google Ad Manager.
  • StreamManager : Объект, который обрабатывает обмен данными между видеопотоком и SDK IMA DAI, например, отправляет запросы на отслеживание и пересылает события потока издателю.

Предварительные требования

  • Учетная запись в консоли разработчика Cast с зарегистрированным тестовым устройством.
  • Приложение веб-приемника , зарегистрированное в консоли разработчика Cast, которое можно модифицировать для размещения кода, предоставленного в этом руководстве.
  • Приложение-отправитель, настроенное для использования вашего веб-приложения-приемника. В этом примере в качестве отправителя используется инструмент Cast Command and Control .

Настройте объекты MediaInfo отправителя.

Сначала настройте объект MediaInfo вашего приложения-отправителя, добавив в него следующие поля:

contentId Уникальный идентификатор данного медиафайла.
contentUrl URL резервного потока, который будет загружен в случае, если запрос DAI StreamRequest завершится неудачей по какой-либо причине.
streamType Для прямых трансляций это значение следует установить на `LIVE`. Для видео по запросу это значение следует установить на `BUFFERED`.
customData assetKey Только прямые трансляции. Указывает, какую прямую трансляцию следует загрузить.
contentSourceId Только потоковое видео по запросу (VOD). Определяет медиапоток, содержащий запрошенный поток.
videoId Только для потокового видео по запросу (VOD). Идентифицирует запрошенный поток в указанном медиапотоке.
networkCode (Необязательно) Ваш сетевой код Google Ad Manager.
ApiKey Необязательный ключ API, который может потребоваться для получения URL-адреса потока из SDK IMA DAI.
senderCanSkip Логическое значение, позволяющее получателю узнать, поддерживает ли отправляющее устройство кнопку пропуска, что дает возможность пропускать рекламу.

Чтобы настроить эти значения в инструменте управления трансляцией, перейдите на вкладку «Загрузка медиафайлов» и установите пользовательский тип запроса на загрузку в LOAD . Затем замените данные JSON в текстовом поле одним из следующих объектов JSON:

ЖИТЬ

{
  "media": {
    "contentId": "bbb",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/bbb.m3u8",
    "streamType": "LIVE",
    "customData": {
      "assetKey": "c-rArva4ShKVIAkNfy6HUQ",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

VOD

{
  "media": {
    "contentId": "tos",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/tos.m3u8",
    "streamType": "BUFFERED",
    "customData": {
      "contentSourceId": "2548831",
      "videoId": "tears-of-steel",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

Этот пользовательский объект запроса на загрузку можно отправить получателю для проверки следующих шагов.

Создайте базовый CAF-приемник.

Следуя руководству по созданию базового веб-приемника в CAF SDK, создайте простой веб-приемник.

Код вашего получателя должен выглядеть следующим образом:

<html>
<head>
  <script type="text/javascript"
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js">
  </script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    cast.framework.CastReceiverContext.getInstance().start();
  </script>
</body>
</html>

Импортируйте SDK IMA DAI и получите менеджер проигрывателя.

Добавьте тег <script> для импорта SDK IMA DAI для CAF в ваш веб-приемник сразу после скрипта загрузки CAF. SDK CAF DAI является постоянно обновляемым, поэтому нет необходимости указывать конкретную версию. Затем в следующем теге <script> сохраните контекст приемника и менеджер проигрывателя в качестве констант перед запуском приемника.

<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();

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

Инициализируйте менеджер потоков IMA.

Инициализируйте менеджер потоков SDK CAF DAI.

<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>

Создайте перехватчик сообщений о загрузке.

SDK CAF DAI использует перехватчик сообщений загрузки CAF для отправки запросов на поток и замены URL-адреса контента на конечный поток DAI. Перехватчик сообщений вызывает streamManager.requestStream() , который обрабатывает установку рекламных пауз, запрос потока и замену существующего contentURL .

Может быть только один перехватчик сообщений загрузки, поэтому, если вашему приложению требуется использование перехватчика, вам необходимо включить все пользовательские функции в ту же функцию обратного вызова.

<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();

    const getStreamRequest = (request) => null;

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                this.broadcast('Stream request successful.');
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

Сформировать запрос на поток.

Для завершения интеграции CAF DAI необходимо сформировать запрос на потоковую передачу , используя данные, содержащиеся в объекте mediaInfo от отправителя.

<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();

    const getStreamRequest = (request) => {
      const imaRequestData = request.media.customData;
      let streamRequest = null;
      if (imaRequestData.assetKey) {
        // Live stream
        streamRequest = new google.ima.cast.dai.api.LiveStreamRequest();
        streamRequest.assetKey = imaRequestData.assetKey;
      } else if (imaRequestData.contentSourceId) {
        // VOD stream
        streamRequest = new google.ima.cast.dai.api.VODStreamRequest();
        streamRequest.contentSourceId = imaRequestData.contentSourceId;
        streamRequest.videoId = imaRequestData.videoId;
      }
      if (streamRequest && imaRequestData.networkCode) {
        streamRequest.networkCode = imaRequestData.networkCode;
      }
      if (streamRequest && imaRequestData.ApiKey) {
        streamRequest.ApiKey = imaRequestData.ApiKey;
      }
      if (streamRequest && imaRequestData.senderCanSkip) {
        streamRequest.senderCanSkip = imaRequestData.senderCanSkip;
      }
      return streamRequest;
    };

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

Теперь вы можете запрашивать и воспроизводить потоки DAI с помощью SDK CAF DAI от Google. Чтобы узнать о более продвинутых функциях SDK, ознакомьтесь с другими руководствами или загрузите наши примеры приложений-приемников .

,
Выберите платформу: HTML5 Android iOS tvOS Cast Roku

Выберите интересующее вас решение DAI.

Полный спектр услуг DAI

В этом руководстве показано, как воспроизводить поток DAI с помощью SDK IMA CAF DAI. Если вы хотите посмотреть или проследить за завершенной интеграцией на примере, скачайте пример .

Перед использованием этого руководства обязательно ознакомьтесь с протоколом Web Receiver платформы Chromecast Application Framework . Это руководство предполагает базовое знакомство с концепциями приемника CAF, такими как перехватчики сообщений и объекты mediaInformation , а также знакомство с использованием инструмента Cast Command and Control для эмуляции отправителя CAF.

Для использования IMA DAI вам необходима учетная запись Ad Manager 360. Если у вас уже есть учетная запись Ad Manager, обратитесь к своему менеджеру по работе с клиентами за дополнительной информацией. Информацию о регистрации в Ad Manager можно найти в Справочном центре Ad Manager .

Для получения информации об интеграции с другими платформами или об использовании клиентских SDK IMA см. раздел «SDK для интерактивной рекламы» .

Обзор CAF DAI

Внедрение DAI с использованием IMA CAF DAI SDK включает в себя два основных компонента, как показано в этом руководстве:

  • StreamRequest : Объект, определяющий запрос потока данных на рекламные серверы Google. Запросы потока данных бывают двух основных типов:

    • LiveStreamRequest : указывает ключ ресурса , а также другие необязательные параметры.
    • VODStreamRequest : Указывает идентификатор источника контента , идентификатор видео , а также другие необязательные параметры.
    • Оба типа запросов могут дополнительно включать ключ API , необходимый для доступа к указанным потокам, и сетевой код Google Ad Manager для обработки идентификаторов рекламы в SDK IMA, как указано в настройках Google Ad Manager.
  • StreamManager : Объект, который обрабатывает обмен данными между видеопотоком и SDK IMA DAI, например, отправляет запросы на отслеживание и пересылает события потока издателю.

Предварительные требования

  • Учетная запись в консоли разработчика Cast с зарегистрированным тестовым устройством.
  • Приложение веб-приемника , зарегистрированное в консоли разработчика Cast, которое можно модифицировать для размещения кода, предоставленного в этом руководстве.
  • Приложение-отправитель, настроенное для использования вашего веб-приложения-приемника. В этом примере в качестве отправителя используется инструмент Cast Command and Control .

Настройте объекты MediaInfo отправителя.

Сначала настройте объект MediaInfo вашего приложения-отправителя, добавив в него следующие поля:

contentId Уникальный идентификатор данного медиафайла.
contentUrl URL резервного потока, который будет загружен в случае, если запрос DAI StreamRequest завершится неудачей по какой-либо причине.
streamType Для прямых трансляций это значение следует установить на `LIVE`. Для видео по запросу это значение следует установить на `BUFFERED`.
customData assetKey Только прямые трансляции. Указывает, какую прямую трансляцию следует загрузить.
contentSourceId Только потоковое видео по запросу (VOD). Определяет медиапоток, содержащий запрошенный поток.
videoId Только для потокового видео по запросу (VOD). Идентифицирует запрошенный поток в указанном медиапотоке.
networkCode (Необязательно) Ваш сетевой код Google Ad Manager.
ApiKey Необязательный ключ API, который может потребоваться для получения URL-адреса потока из SDK IMA DAI.
senderCanSkip Логическое значение, позволяющее получателю узнать, поддерживает ли отправляющее устройство кнопку пропуска, что дает возможность пропускать рекламу.

Чтобы настроить эти значения в инструменте управления трансляцией, перейдите на вкладку «Загрузка медиафайлов» и установите пользовательский тип запроса на загрузку в LOAD . Затем замените данные JSON в текстовом поле одним из следующих объектов JSON:

ЖИТЬ

{
  "media": {
    "contentId": "bbb",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/bbb.m3u8",
    "streamType": "LIVE",
    "customData": {
      "assetKey": "c-rArva4ShKVIAkNfy6HUQ",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

VOD

{
  "media": {
    "contentId": "tos",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/tos.m3u8",
    "streamType": "BUFFERED",
    "customData": {
      "contentSourceId": "2548831",
      "videoId": "tears-of-steel",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

Этот пользовательский объект запроса на загрузку можно отправить получателю для проверки следующих шагов.

Создайте базовый CAF-приемник.

Следуя руководству по созданию базового веб-приемника в CAF SDK, создайте простой веб-приемник.

Код вашего получателя должен выглядеть следующим образом:

<html>
<head>
  <script type="text/javascript"
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js">
  </script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    cast.framework.CastReceiverContext.getInstance().start();
  </script>
</body>
</html>

Импортируйте SDK IMA DAI и получите менеджер проигрывателя.

Добавьте тег <script> для импорта SDK IMA DAI для CAF в ваш веб-приемник сразу после скрипта загрузки CAF. SDK CAF DAI является постоянно обновляемым, поэтому нет необходимости указывать конкретную версию. Затем в следующем теге <script> сохраните контекст приемника и менеджер проигрывателя в качестве констант перед запуском приемника.

<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();

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

Инициализируйте менеджер потоков IMA.

Инициализируйте менеджер потоков SDK CAF DAI.

<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>

Создайте перехватчик сообщений о загрузке.

SDK CAF DAI использует перехватчик сообщений загрузки CAF для отправки запросов на поток и замены URL-адреса контента на конечный поток DAI. Перехватчик сообщений вызывает streamManager.requestStream() , который обрабатывает установку рекламных пауз, запрос потока и замену существующего contentURL .

Может быть только один перехватчик сообщений загрузки, поэтому, если вашему приложению требуется использование перехватчика, вам необходимо включить все пользовательские функции в ту же функцию обратного вызова.

<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();

    const getStreamRequest = (request) => null;

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                this.broadcast('Stream request successful.');
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

Сформировать запрос на поток.

Для завершения интеграции CAF DAI необходимо сформировать запрос на потоковую передачу , используя данные, содержащиеся в объекте mediaInfo от отправителя.

<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();

    const getStreamRequest = (request) => {
      const imaRequestData = request.media.customData;
      let streamRequest = null;
      if (imaRequestData.assetKey) {
        // Live stream
        streamRequest = new google.ima.cast.dai.api.LiveStreamRequest();
        streamRequest.assetKey = imaRequestData.assetKey;
      } else if (imaRequestData.contentSourceId) {
        // VOD stream
        streamRequest = new google.ima.cast.dai.api.VODStreamRequest();
        streamRequest.contentSourceId = imaRequestData.contentSourceId;
        streamRequest.videoId = imaRequestData.videoId;
      }
      if (streamRequest && imaRequestData.networkCode) {
        streamRequest.networkCode = imaRequestData.networkCode;
      }
      if (streamRequest && imaRequestData.ApiKey) {
        streamRequest.ApiKey = imaRequestData.ApiKey;
      }
      if (streamRequest && imaRequestData.senderCanSkip) {
        streamRequest.senderCanSkip = imaRequestData.senderCanSkip;
      }
      return streamRequest;
    };

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

Теперь вы можете запрашивать и воспроизводить потоки DAI с помощью SDK CAF DAI от Google. Чтобы узнать о более продвинутых функциях SDK, ознакомьтесь с другими руководствами или загрузите наши примеры приложений-приемников .

,
Select platform: HTML5 Android iOS tvOS Cast Roku

Select the DAI solution you're interested in

Full service DAI

This guide demonstrates how to play a DAI stream, using the IMA CAF DAI SDK. If you would like to view or follow along with a completed sample integration, download the example .

Before using this guide, be sure to familiarize yourself with the Chromecast Application Framework's Web Receiver protocol. This guide assumes a basic level of familiarity with CAF receiver concepts, such as message interceptors and mediaInformation objects, as well as familiarity with using the Cast Command and Control tool to emulate a CAF sender.

To use IMA DAI, you must have an Ad Manager 360 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 .

For information on integrating with other platforms, or on using the IMA client-side SDKs, see Interactive Media Ads SDKs .

CAF DAI overview

Implementing DAI using the IMA CAF DAI SDK involves two main components as demonstrated in this guide:

  • StreamRequest : An object that defines a stream request to Google's advertising servers. Stream requests come in two main varieties:

    • LiveStreamRequest : specifies an Asset Key , as well as other optional parameters.
    • VODStreamRequest : Specifies a Content Source ID , a Video ID , as well as other optional parameters.
    • Both request types can optionally include an API key needed to access specified streams, and a Google Ad Manager network code for the IMA SDK to handle ads identifiers as specified in Google Ad Manager settings.
  • 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.

Предварительные требования

  • A Cast Developer Console account with a registered test device.
  • A hosted 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. This example uses the Cast Command and Control tool as the sender.

Configure the sender's MediaInfo objects

First, configure your sender app's MediaInfo object to include the following fields:

contentId A unique identifier for this media item
contentUrl The fallback stream URL to load if the DAI StreamRequest fails for any reason
streamType For live streams this value should be set to `LIVE`. For VOD streams, this value should be set to `BUFFERED`
customData assetKey Live streams only. Identifies the livestream to be loaded
contentSourceId VOD streams only. Identifies the media feed that contains the requested stream.
videoId VOD streams only. Identifies the requested stream within the specified media feed.
networkCode (Optional) Your Google Ad Manager network code.
ApiKey An optional API key that can be required to retrieve the stream URL from the IMA DAI SDK
senderCanSkip A boolean value to let the receiver know whether the sending device has the ability to display a skip button, enabling support for skippable ads

To configure these values in the cast command and control 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 one of the following JSON objects:

ЖИТЬ

{
  "media": {
    "contentId": "bbb",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/bbb.m3u8",
    "streamType": "LIVE",
    "customData": {
      "assetKey": "c-rArva4ShKVIAkNfy6HUQ",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

VOD

{
  "media": {
    "contentId": "tos",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/tos.m3u8",
    "streamType": "BUFFERED",
    "customData": {
      "contentSourceId": "2548831",
      "videoId": "tears-of-steel",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

This custom load request object can be sent to the receiver to test the following steps.

Create a basic CAF receiver

Following the CAF SDK Basic Receiver Guide, create a basic web receiver.

Your receiver's code should look like this:

<html>
<head>
  <script type="text/javascript"
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js">
  </script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    cast.framework.CastReceiverContext.getInstance().start();
  </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. The CAF DAI SDK is evergreen, so there is no need to set a specific version. Then in the script tag that follows, store the receiver context and player manager as constants before starting the receiver.

<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();

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

Initialize the IMA Stream Manager

Initialize the CAF DAI SDK's Stream Manager .

<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 load message interceptor

The CAF DAI SDK uses the CAF load message interceptor to make stream requests and replace the content URL with the final DAI stream. The message interceptor calls streamManager.requestStream() which handles setting ad breaks, requesting the stream, and replacing the existing contentURL .

There can only be one load message interceptor, so if your app requires the use of the interceptor, you need to incorporate any custom functions into the same callback.

<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();

    const getStreamRequest = (request) => null;

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                this.broadcast('Stream request successful.');
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

Build the stream request

To complete your CAF DAI integration, you need to build your stream request using the data that was included in the mediaInfo object from the sender.

<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();

    const getStreamRequest = (request) => {
      const imaRequestData = request.media.customData;
      let streamRequest = null;
      if (imaRequestData.assetKey) {
        // Live stream
        streamRequest = new google.ima.cast.dai.api.LiveStreamRequest();
        streamRequest.assetKey = imaRequestData.assetKey;
      } else if (imaRequestData.contentSourceId) {
        // VOD stream
        streamRequest = new google.ima.cast.dai.api.VODStreamRequest();
        streamRequest.contentSourceId = imaRequestData.contentSourceId;
        streamRequest.videoId = imaRequestData.videoId;
      }
      if (streamRequest && imaRequestData.networkCode) {
        streamRequest.networkCode = imaRequestData.networkCode;
      }
      if (streamRequest && imaRequestData.ApiKey) {
        streamRequest.ApiKey = imaRequestData.ApiKey;
      }
      if (streamRequest && imaRequestData.senderCanSkip) {
        streamRequest.senderCanSkip = imaRequestData.senderCanSkip;
      }
      return streamRequest;
    };

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

You're now able to request and playback DAI streams with Google's CAF DAI SDK. To learn about more advanced SDK features, see the other guides or download our sample receiver applications .

,
Select platform: HTML5 Android iOS tvOS Cast Roku

Select the DAI solution you're interested in

Full service DAI

This guide demonstrates how to play a DAI stream, using the IMA CAF DAI SDK. If you would like to view or follow along with a completed sample integration, download the example .

Before using this guide, be sure to familiarize yourself with the Chromecast Application Framework's Web Receiver protocol. This guide assumes a basic level of familiarity with CAF receiver concepts, such as message interceptors and mediaInformation objects, as well as familiarity with using the Cast Command and Control tool to emulate a CAF sender.

To use IMA DAI, you must have an Ad Manager 360 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 .

For information on integrating with other platforms, or on using the IMA client-side SDKs, see Interactive Media Ads SDKs .

CAF DAI overview

Implementing DAI using the IMA CAF DAI SDK involves two main components as demonstrated in this guide:

  • StreamRequest : An object that defines a stream request to Google's advertising servers. Stream requests come in two main varieties:

    • LiveStreamRequest : specifies an Asset Key , as well as other optional parameters.
    • VODStreamRequest : Specifies a Content Source ID , a Video ID , as well as other optional parameters.
    • Both request types can optionally include an API key needed to access specified streams, and a Google Ad Manager network code for the IMA SDK to handle ads identifiers as specified in Google Ad Manager settings.
  • 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.

Предварительные требования

  • A Cast Developer Console account with a registered test device.
  • A hosted 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. This example uses the Cast Command and Control tool as the sender.

Configure the sender's MediaInfo objects

First, configure your sender app's MediaInfo object to include the following fields:

contentId A unique identifier for this media item
contentUrl The fallback stream URL to load if the DAI StreamRequest fails for any reason
streamType For live streams this value should be set to `LIVE`. For VOD streams, this value should be set to `BUFFERED`
customData assetKey Live streams only. Identifies the livestream to be loaded
contentSourceId VOD streams only. Identifies the media feed that contains the requested stream.
videoId VOD streams only. Identifies the requested stream within the specified media feed.
networkCode (Optional) Your Google Ad Manager network code.
ApiKey An optional API key that can be required to retrieve the stream URL from the IMA DAI SDK
senderCanSkip A boolean value to let the receiver know whether the sending device has the ability to display a skip button, enabling support for skippable ads

To configure these values in the cast command and control 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 one of the following JSON objects:

ЖИТЬ

{
  "media": {
    "contentId": "bbb",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/bbb.m3u8",
    "streamType": "LIVE",
    "customData": {
      "assetKey": "c-rArva4ShKVIAkNfy6HUQ",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

VOD

{
  "media": {
    "contentId": "tos",
    "contentUrl": "https://storage.googleapis.com/interactive-media-ads/media/tos.m3u8",
    "streamType": "BUFFERED",
    "customData": {
      "contentSourceId": "2548831",
      "videoId": "tears-of-steel",
      "networkCode": "21775744923",
      "ApiKey": "",
      "senderCanSkip": true
    }
  },
  "credentials": "testCredentials"
}

This custom load request object can be sent to the receiver to test the following steps.

Create a basic CAF receiver

Following the CAF SDK Basic Receiver Guide, create a basic web receiver.

Your receiver's code should look like this:

<html>
<head>
  <script type="text/javascript"
      src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js">
  </script>
</head>
<body>
  <cast-media-player></cast-media-player>
  <script>
    cast.framework.CastReceiverContext.getInstance().start();
  </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. The CAF DAI SDK is evergreen, so there is no need to set a specific version. Then in the script tag that follows, store the receiver context and player manager as constants before starting the receiver.

<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();

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

Initialize the IMA Stream Manager

Initialize the CAF DAI SDK's Stream Manager .

<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 load message interceptor

The CAF DAI SDK uses the CAF load message interceptor to make stream requests and replace the content URL with the final DAI stream. The message interceptor calls streamManager.requestStream() which handles setting ad breaks, requesting the stream, and replacing the existing contentURL .

There can only be one load message interceptor, so if your app requires the use of the interceptor, you need to incorporate any custom functions into the same callback.

<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();

    const getStreamRequest = (request) => null;

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                this.broadcast('Stream request successful.');
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

Build the stream request

To complete your CAF DAI integration, you need to build your stream request using the data that was included in the mediaInfo object from the sender.

<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();

    const getStreamRequest = (request) => {
      const imaRequestData = request.media.customData;
      let streamRequest = null;
      if (imaRequestData.assetKey) {
        // Live stream
        streamRequest = new google.ima.cast.dai.api.LiveStreamRequest();
        streamRequest.assetKey = imaRequestData.assetKey;
      } else if (imaRequestData.contentSourceId) {
        // VOD stream
        streamRequest = new google.ima.cast.dai.api.VODStreamRequest();
        streamRequest.contentSourceId = imaRequestData.contentSourceId;
        streamRequest.videoId = imaRequestData.videoId;
      }
      if (streamRequest && imaRequestData.networkCode) {
        streamRequest.networkCode = imaRequestData.networkCode;
      }
      if (streamRequest && imaRequestData.ApiKey) {
        streamRequest.ApiKey = imaRequestData.ApiKey;
      }
      if (streamRequest && imaRequestData.senderCanSkip) {
        streamRequest.senderCanSkip = imaRequestData.senderCanSkip;
      }
      return streamRequest;
    };

    playerManager.setMessageInterceptor(
        cast.framework.messages.MessageType.LOAD, (request) => {
          return streamManager.requestStream(request, getStreamRequest(request))
              .then((request) => {
                return Promise.resolve(request);
              })
              .catch((error) => {
                this.broadcast('Stream request failed.');
                return Promise.resolve(request);
              });
        });

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

You're now able to request and playback DAI streams with Google's CAF DAI SDK. To learn about more advanced SDK features, see the other guides or download our sample receiver applications .