ads_manager.js에서 스트림 요청을 하고, 광고 모음 매니페스트를 가져오고, IMA 스트림 이벤트를 수신하고, emsg 이벤트를 IMA SDK에 전달하는 IMA SDK StreamManager의 래퍼 클래스를 정의합니다.
ads_manager.js에서 IMA HbbTV 샘플 앱은 다음 메서드를 설정합니다.
requestStream()
onStreamEvent()
onEmsgEvent()
loadAdPodManifest()
광고 관리자 초기화
광고 관리자 클래스를 초기화하고 IMA 스트림 이벤트의 리스너를 설정합니다. 이 호출에서 VideoPlayer.setEmsgEventHandler() 메서드를 사용하여 emsg 이벤트 핸들러를 설정합니다.
/** * Wraps IMA SDK ad stream manager. * @param {!VideoPlayer} videoPlayer Reference an instance of the wrapper from * video_player.js. */varAdManager=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=newgoogle.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);};
Google Ad Manager 네트워크 코드와 스트림의 맞춤 애셋 키를 사용하여 PodStreamRequest 객체를 만드는 AdManager.requestStream() 메서드를 만듭니다. 다음 스트림 매개변수를 사용하여 스트림을 제공하는 IMA 샘플 DASH 포드를 사용하여 HbbTV 앱을 테스트합니다.
네트워크 코드: '21775744923'
맞춤 애셋 키: '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){varstreamRequest=newgoogle.ima.dai.api.PodStreamRequest();streamRequest.networkCode=networkCode;streamRequest.customAssetKey=customAssetKey;streamRequest.format='dash';debugView.log('AdsManager: make PodStreamRequest');this.streamManager.requestStream(streamRequest);};
IMA 스트림 이벤트 STREAM_INITIALIZED, AD_BREAK_STARTED, AD_BREAK_ENDED에 대한 앱의 응답을 처리하는 AdManager.onStreamEvent() 메서드를 만듭니다.
/** * 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.casegoogle.ima.dai.api.StreamEvent.Type.STREAM_INITIALIZED:debugView.log('IMA SDK: stream initialized');this.streamData=event.getStreamData();break;casegoogle.ima.dai.api.StreamEvent.Type.ERROR:break;// Hide video controls while ad is playing.casegoogle.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.casegoogle.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.casegoogle.ima.dai.api.StreamEvent.Type.AD_PROGRESS:break;default:debugView.log('IMA SDK: '+event.type);break;}};
emsg 이벤트 정보를 IMA에 전달하려면 StreamManager.processMetadata() 메서드를 사용하여 AdManager.onEmsgEvent() 메서드를 만듭니다. 동영상 플레이어 클래스는 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){vardata=event.event.messageData;varpts=event.event.calculatedPresentationTime;if((datainstanceofUint8Array) && data.byteLength > 0){this.streamManager.processMetadata('ID3',data,pts);}};
동영상 플레이어로 광고 모음 매니페스트를 미리 로드하는 AdManager.loadAdPodManifest() 메서드를 만듭니다. 방법: DASH 포드 매니페스트의 구조를 사용하여 매니페스트 URL을 구성합니다.
/** * 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('IMA SDK: No DAI pod session registered.');return;}varMANIFEST_BASE_URL='https://dai.google.com/linear/pods/v1/dash/network/';// Method: DASH pod manifest reference docs:// https://developers.google.com/ad-manager/dynamic-ad-insertion/api/pod-serving/reference/live#method_dash_pod_manifestvarmanifestUrl=MANIFEST_BASE_URL+networkCode+'/custom_asset/'+customAssetKey+'/stream/'+this.streamData.streamId+'/pod/'+this.getPodId()+'/manifest.mpd?pd='+podDuration;this.videoPlayer.preload(manifestUrl);};
HbbTV 샘플 앱은 무작위로 생성된 고유한 podId를 사용합니다. 프로덕션 앱에서 podId는 1로 시작하고 광고 시점마다 1씩 증가하는 정수입니다. podId가 광고 시청자 모두에게 동일한 값인지 확인합니다. podId를 얻으려면 EABN(Early Ad Break Notification) API를 사용하는 것이 좋습니다. 프로덕션 환경에서는 HbbTV 스트림 이벤트 AD_BREAK_ANNOUNCE에 podId 및 podDuration를 포함합니다.
다음으로 HbbTV 방송과 상호작용하는 HbbTV 앱의 기본 애플리케이션 클래스를 만듭니다.
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eThis guide outlines how to integrate the IMA SDK into an HbbTV app to manage ad streams, including setting up an \u003ccode\u003eAdManager\u003c/code\u003e class to handle stream requests and events.\u003c/p\u003e\n"],["\u003cp\u003eFor HbbTV, it is crucial to omit the \u003ccode\u003eadUiElement\u003c/code\u003e in the \u003ccode\u003eStreamManager\u003c/code\u003e constructor to avoid serving incompatible ads, as the IMA SDK does not support ad UI on this platform.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eAdManager\u003c/code\u003e class defines methods to request ad streams, handle IMA events (like \u003ccode\u003eSTREAM_INITIALIZED\u003c/code\u003e, \u003ccode\u003eAD_BREAK_STARTED\u003c/code\u003e, and \u003ccode\u003eAD_BREAK_ENDED\u003c/code\u003e), and process ad stream metadata using emsg events.\u003c/p\u003e\n"],["\u003cp\u003eAd pod manifests are preloaded by constructing a URL using Google Ad Manager parameters (network code, custom asset key) and stream information (\u003ccode\u003estreamId\u003c/code\u003e, \u003ccode\u003epodId\u003c/code\u003e), ensuring the \u003ccode\u003epodId\u003c/code\u003e remains consistent for viewers of the same ad break.\u003c/p\u003e\n"],["\u003cp\u003eBefore proceeding with these steps, complete the setup outlined in the "Set up the player class" guide to lay the foundation for the HbbTV player.\u003c/p\u003e\n"]]],["The `ads_manager.js` file defines an `AdManager` class to manage IMA SDK stream interactions. This includes `requestStream()` for sending stream requests using a network code and custom asset key, `onStreamEvent()` to handle IMA stream events like `STREAM_INITIALIZED`, `AD_BREAK_STARTED`, and `AD_BREAK_ENDED`. `onEmsgEvent()` passes emsg event data to the IMA SDK, and `loadAdPodManifest()` preloads the ad pod manifest using a constructed URL. The `podId` should be unique for each ad break.\n"],null,["| **Note:** Before moving forward with this guide, you must complete the steps in [Set up the player class](/ad-manager/dynamic-ad-insertion/sdk/html5/hbbtv-player).\n\nIn `ads_manager.js`, define a wrapper class for the IMA SDK StreamManager that\nmakes stream requests, gets the ad pod manifest, listens to IMA stream events,\nand passes emsg events to the IMA SDK.\n\nIn `ads_manager.js`, the IMA HbbTV sample app sets up the following methods:\n\n- `requestStream()`\n- `onStreamEvent()`\n- `onEmsgEvent()`\n- `loadAdPodManifest()`\n\nInitialize ads manager\n\nInitialize the ads manager class and set listeners for the IMA stream events. In\nthis call, set the emsg event handler with the\n`VideoPlayer.setEmsgEventHandler()` method.\n**Key Point:** The IMA SDK does not support ad UI on HbbTV. Don't pass the `adUiElement` parameter in the `StreamManager` constructor. Passing `adUiElement` can lead to Ad Manager serving incompatible ads. \n\n /**\n * Wraps IMA SDK ad stream manager.\n * @param {!VideoPlayer} videoPlayer Reference an instance of the wrapper from\n * video_player.js.\n */\n var AdManager = function(videoPlayer) {\n this.streamData = null;\n this.videoPlayer = videoPlayer;\n // Ad UI is not supported for HBBTV, so no 'adUiElement' is passed in the\n // StreamManager constructor.\n this.streamManager = new google.ima.dai.api.StreamManager(\n this.videoPlayer.videoElement);\n this.streamManager.addEventListener(\n [\n google.ima.dai.api.StreamEvent.Type.STREAM_INITIALIZED,\n google.ima.dai.api.StreamEvent.Type.ERROR,\n google.ima.dai.api.StreamEvent.Type.CLICK,\n google.ima.dai.api.StreamEvent.Type.STARTED,\n google.ima.dai.api.StreamEvent.Type.FIRST_QUARTILE,\n google.ima.dai.api.StreamEvent.Type.MIDPOINT,\n google.ima.dai.api.StreamEvent.Type.THIRD_QUARTILE,\n google.ima.dai.api.StreamEvent.Type.COMPLETE,\n google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED,\n google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED,\n google.ima.dai.api.StreamEvent.Type.AD_PROGRESS,\n google.ima.dai.api.StreamEvent.Type.PAUSED,\n google.ima.dai.api.StreamEvent.Type.RESUMED\n ],\n this.onStreamEvent.bind(this),\n false);\n\n this.videoPlayer.setEmsgEventHandler(this.onEmsgEvent, this);\n }; \n https://github.com/googleads/googleads-ima-html5-dai/blob/d215db4a053d12c842e899da470684142ff732f6/hbbtv/ads_manager.js#L18-L50\n\nMake a request for an ad pod stream\n\nCreate the `AdManager.requestStream()` method to create a `PodStreamRequest`\nobject using your Google Ad Manager network code and the stream's custom asset\nkey. Test your HbbTV app using the IMA sample DASH pod serving stream with the\nfollowing stream parameters:\n\n- **Network code** : `'21775744923'`\n- **Custom asset key** : `'hbbtv-dash'`\n\n /**\n * Makes a pod stream request.\n * @param {string} networkCode The network code.\n * @param {string} customAssetKey The custom asset key.\n */\n AdManager.prototype.requestStream = function(networkCode, customAssetKey) {\n var streamRequest = new google.ima.dai.api.PodStreamRequest();\n streamRequest.networkCode = networkCode;\n streamRequest.customAssetKey = customAssetKey;\n streamRequest.format = 'dash';\n debugView.log('AdsManager: make PodStreamRequest');\n this.streamManager.requestStream(streamRequest);\n }; \n https://github.com/googleads/googleads-ima-html5-dai/blob/d215db4a053d12c842e899da470684142ff732f6/hbbtv/ads_manager.js#L54-L66\n\nListen to ad stream events\n\nCreate the `AdManager.onStreamEvent()` method to handle your app's response to\nthe IMA stream events, `STREAM_INITIALIZED`, `AD_BREAK_STARTED`, and\n`AD_BREAK_ENDED`. \n\n /**\n * Handles IMA playback events.\n * @param {!Event} event The event object.\n */\n AdManager.prototype.onStreamEvent = function(event) {\n switch (event.type) {\n // Once the stream response data is received, generate pod manifest url\n // for the video stream.\n case google.ima.dai.api.StreamEvent.Type.STREAM_INITIALIZED:\n debugView.log('IMA SDK: stream initialized');\n this.streamData = event.getStreamData();\n break;\n case google.ima.dai.api.StreamEvent.Type.ERROR:\n break;\n // Hide video controls while ad is playing.\n case google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED:\n debugView.log('IMA SDK: ad break started');\n this.adPlaying = true;\n this.adBreakStarted = true;\n break;\n // Show video controls when ad ends.\n case google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED:\n debugView.log('IMA SDK: ad break ended');\n this.adPlaying = false;\n this.adBreakStarted = false;\n break;\n // Update ad countdown timers.\n case google.ima.dai.api.StreamEvent.Type.AD_PROGRESS:\n break;\n default:\n debugView.log('IMA SDK: ' + event.type);\n break;\n }\n }; \n https://github.com/googleads/googleads-ima-html5-dai/blob/d215db4a053d12c842e899da470684142ff732f6/hbbtv/ads_manager.js#L70-L103\n\nHandle ad stream metadata\n\nTo pass the emsg event info to IMA, create the `AdManager.onEmsgEvent()` method\nusing the `StreamManager.processMetadata()` method. The video player class calls\nthis method with the `VideoPlayer.setEmsgEventHandler()` method. \n\n /**\n * Callback on Emsg event.\n * Instructs IMA SDK to fire back VAST events accordingly.\n * @param {!Event} event The event object.\n */\n AdManager.prototype.onEmsgEvent = function(event) {\n var data = event.event.messageData;\n var pts = event.event.calculatedPresentationTime;\n if ((data instanceof Uint8Array) && data.byteLength \u003e 0) {\n this.streamManager.processMetadata('ID3', data, pts);\n }\n }; \n https://github.com/googleads/googleads-ima-html5-dai/blob/d215db4a053d12c842e899da470684142ff732f6/hbbtv/ads_manager.js#L107-L118\n\nLoad the ad pod manifest\n\nCreate the `AdManager.loadAdPodManifest()` method to preload the ad pod manifest\nwith the video player. Construct the manifest URL using the structure in\n[Method: DASH pod manifest](/ad-manager/dynamic-ad-insertion/api/pod-serving/reference/live#method_dash_pod_manifest). \n\n /**\n * Creates DAI pod url and instructs video player to load manifest.\n * @param {string} networkCode The network code.\n * @param {string} customAssetKey The custom asset key.\n * @param {number} podDuration The duration of the ad pod.\n */\n AdManager.prototype.loadAdPodManifest =\n function(networkCode, customAssetKey, podDuration) {\n if (!this.streamData) {\n debugView.log('IMA SDK: No DAI pod session registered.');\n return;\n }\n\n var MANIFEST_BASE_URL = 'https://dai.google.com/linear/pods/v1/dash/network/';\n // Method: DASH pod manifest reference docs:\n // https://developers.google.com/ad-manager/dynamic-ad-insertion/api/pod-serving/reference/live#method_dash_pod_manifest\n var manifestUrl = MANIFEST_BASE_URL + networkCode + '/custom_asset/' +\n customAssetKey + '/stream/' + this.streamData.streamId + '/pod/' +\n this.getPodId() + '/manifest.mpd?pd=' + podDuration;\n this.videoPlayer.preload(manifestUrl);\n }; \n https://github.com/googleads/googleads-ima-html5-dai/blob/d215db4a053d12c842e899da470684142ff732f6/hbbtv/ads_manager.js#L122-L142\n\nThe\n[HbbTV sample app](//github.com/googleads/googleads-ima-html5-dai/tree/main/hbbtv)\nuses a randomly generated unique `podId`. In production apps, the `podId` is an\ninteger that starts at one, and increments by one for each ad break. Verify the\n`podId` is the same value for all viewers of the ad break. To get a `podId`, we\nrecommend using the\n[Early ad break notifications](/ad-manager/video/Early.ad.break.notification)\n(EABN) API. In a production environment, include the `podId` and `podDuration`\nin the HbbTV stream event `AD_BREAK_ANNOUNCE`.\n\nNext, create the main application class for your HbbTV app that interacts with\nthe HbbTV broadcast."]]