플레이어 클래스 설정

video_player.js에서 dash.js 플레이어를 시작하고 제어하는 동영상 플레이어 래퍼 클래스를 정의합니다.

브로드밴드 플레이어 설정

동영상 및 래퍼 태그를 만들어 앱에서 브로드밴드 플레이어를 배치할 위치를 정의합니다.

<div id="broadband-wrapper">
    <video id="broadband-video"></video>
</div>

동영상 플레이어 만들기

HTML 요소, dash.js 플레이어, 다른 클래스 메서드에서 사용할 수 있는 콜백의 변수로 동영상 플레이어 클래스를 초기화합니다.

/**
 * Video player wrapper class to control ad creative playback with dash.js in
 * broadband.
 */
var VideoPlayer = function() {
  this.videoElement = document.querySelector('video');
  this.broadbandWrapper = document.getElementById('broadband-wrapper');
  this.player = dashjs.MediaPlayer().create();
  this.onAdPodEndedCallback = null;

  // Function passed in VideoPlayer.prototype.setEmsgEventHandler.
  this.onCustomEventHandler = null;
  //  Scope (this) passed in VideoPlayer.prototype.setEmsgEventHandler.
  this.customEventHandlerScope = null;

  // Function to remove all of player event listeners.
  this.cleanUpPlayerListener = null;
  debugView.log('Player: Creating dash.js player');
};

재생 컨트롤 함수 정의

광고 플레이어를 표시하고 동영상 뷰를 연결하려면 VideoPlayer.play() 메서드를 만듭니다. 그런 다음 광고 모음이 완료된 후 정리를 처리하는 create VideoPlayer.stop() 메서드를 만듭니다.

/** Starts playback of ad stream. */
VideoPlayer.prototype.play = function() {
  debugView.log('Player: Start playback');
  this.show();
  this.player.attachView(this.videoElement);
};

/** Stops ad stream playback and deconstructs player. */
VideoPlayer.prototype.stop = function() {
  debugView.log('Player: Request to stop player');
  if (this.cleanUpPlayerListener) {
    this.cleanUpPlayerListener();
  }
  this.player.reset();
  this.player.attachView(null);
  this.player.attachSource(null);
  this.player = null;
  this.hide();
};

광고 스트림 매니페스트 미리 로드

콘텐츠 스트림 중에 광고가 충분히 로드되고 광고 시점이 시작되기 전에 광고가 로드되도록 하려면 VideoPlayer.preload()VideoPlayer.isPreloaded()를 사용하세요.

1. 광고 스트림 미리 로드

VideoPlayer.preload() 메서드를 만들어 광고 스트림 매니페스트를 미리 로드하고 광고 시점 전에 광고 버퍼를 빌드합니다. 플레이어 스트리밍 설정 'cacheInitSegments'true로 업데이트해야 합니다. 설정을 업데이트하면 init 세그먼트 캐싱이 사용 설정되어 광고로 전환할 때 지연이 방지됩니다.

/**
 * Starts ad stream prefetching into Media Source Extensions (MSE) buffer.
 * @param {string} url manifest url for ad stream playback.
 */
VideoPlayer.prototype.preload = function(url) {
  if (!this.player) {
    this.player = dashjs.MediaPlayer().create();
  }
  debugView.log('Player: init with ' + url);
  this.player.initialize(/* HTMLVideoElement */ null, url, /* autoplay */ true);

  this.player.updateSettings({
    'debug': {
      'logLevel': dashjs.Debug.LOG_LEVEL_WARNING,
      'dispatchEvent': true,  // flip to false to hide all debug events.
    },
    'streaming': {
      'cacheInitSegments': true,
    }
  });
  this.player.preload();
  this.attachPlayerListener();
  debugView.log('Player: Pre-loading into MSE buffer');
};

2. 미리 로드된 광고 버퍼 확인

VideoPlayer.isPreloaded() 메서드를 만들어 앱에 설정된 버퍼 기준점에 비해 충분한 광고 버퍼가 미리 로드되었는지 확인합니다.

// Ads will only play with 10 or more seconds of ad loaded.
var MIN_BUFFER_THRESHOLD = 10;
/**
 * Checks if the ad is preloaded and ready to play.
 * @return {boolean} whether the ad buffer level is sufficient.
 */
VideoPlayer.prototype.isPreloaded = function() {
  var currentBufferLevel = this.player.getDashMetrics()
      .getCurrentBufferLevel('video', true);
  return currentBufferLevel >= MIN_BUFFER_THRESHOLD;
};

플레이어 리스너 연결

dash.js 플레이어 이벤트에 대한 이벤트 리스너를 추가하려면 VideoPlayer.attachPlayerListener() 메서드(PLAYBACK_PLAYING, PLAYBACK_ENDED, LOG, ERROR)를 만듭니다. 이 메서드는 이러한 리스너를 삭제하는 정리 함수를 설정하는 것 외에도 스키마 ID URI의 이벤트도 처리합니다.

var SCHEME_ID_URI = 'https://developer.apple.com/streaming/emsg-id3';
/** Attaches event listener for various dash.js events.*/
VideoPlayer.prototype.attachPlayerListener = function() {
  var playingHandler = function() {
    this.onAdPodPlaying();
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['PLAYBACK_PLAYING'], playingHandler);
  var endedHandler = function() {
    this.onAdPodEnded();
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['PLAYBACK_ENDED'], endedHandler);
  var logHandler = function(e) {
    this.onLog(e);
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['LOG'], logHandler);
  var errorHandler = function(e) {
    this.onAdPodError(e);
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['ERROR'], errorHandler);

  var customEventHandler = null;
  if (this.onCustomEventHandler) {
    customEventHandler =
        this.onCustomEventHandler.bind(this.customEventHandlerScope);
    this.player.on(SCHEME_ID_URI, customEventHandler);
  }

  this.cleanUpPlayerListener = function() {
    this.player.off(
        dashjs.MediaPlayer.events['PLAYBACK_PLAYING'], playingHandler);
    this.player.off(dashjs.MediaPlayer.events['PLAYBACK_ENDED'], endedHandler);
    this.player.off(dashjs.MediaPlayer.events['LOG'], logHandler);
    this.player.off(dashjs.MediaPlayer.events['ERROR'], errorHandler);
    if (customEventHandler) {
      this.player.off(SCHEME_ID_URI, customEventHandler);
    }
  };
};

플레이어 이벤트 콜백 설정

플레이어 이벤트를 기반으로 광고 모음 재생을 관리하려면 VideoPlayer.onAdPodPlaying(), VideoPlayer.onAdPodEnded(), VideoPlayer.onAdPodError() 메서드를 만듭니다.

/**
 * Called when ad stream playback buffered and is playing.
 */
VideoPlayer.prototype.onAdPodPlaying = function() {
  debugView.log('Player: Ad Playback started');
};

/**
 * Called when ad stream playback has been completed.
 * Will call the restart of broadcast stream.
 */
VideoPlayer.prototype.onAdPodEnded = function() {
  debugView.log('Player: Ad Playback ended');
  this.stop();
  if (this.onAdPodEndedCallback) {
    this.onAdPodEndedCallback();
  }
};

/**
 * @param {!Event} event The error event to handle.
 */
VideoPlayer.prototype.onAdPodError = function(event) {
  debugView.log('Player: Ad Playback error from dash.js player.');
  this.stop();
  if (this.onAdPodEndedCallback) {
    this.onAdPodEndedCallback();
  }
};

onAdPodEnded 이벤트의 setter 만들기

VideoPlayer.setOnAdPodEnded() 메서드를 만들어 광고 모음이 종료될 때 실행되는 콜백 함수를 설정합니다. 앱 클래스는 이 메서드를 사용하여 광고 시점 후 콘텐츠 방송을 재개합니다.

/**
 * Sets a callback function for when an ad pod has ended.
 * @param {!Function} callback Callback function.
 */
VideoPlayer.prototype.setOnAdPodEnded = function(callback) {
  this.onAdPodEndedCallback = callback;
};

스트림 메타데이터 이벤트 처리

VideoPlayer.setEmsgEventHandler() 메서드를 만들어 emsg 이벤트를 기반으로 실행되는 콜백 함수를 설정합니다. 이 가이드에서는 video_player.js 외부에서 setEmsgEventHandler()를 호출하므로 scope 매개변수를 포함합니다.

/**
 * Sets emsg event handler.
 * @param {!Function} customEventHandler Event handler.
 * @param {!Object} scope JS scope in which event handler function is called.
 */
VideoPlayer.prototype.setEmsgEventHandler = function(
    customEventHandler, scope) {
  this.onCustomEventHandler = customEventHandler;
  this.customEventHandlerScope = scope;
};

광고 시점의 동영상 플레이어 표시 및 숨기기

광고 시점에 동영상 플레이어를 표시하고 광고 시점이 종료된 후 플레이어를 숨기려면 VideoPlayer.show()VideoPlayer.hide() 메서드를 만듭니다.

/** Shows the video player. */
VideoPlayer.prototype.show = function() {
  debugView.log('Player: show');
  this.broadbandWrapper.style.display = 'block';
};

/** Hides the video player. */
VideoPlayer.prototype.hide = function() {
  debugView.log('Player: hide');
  this.broadbandWrapper.style.display = 'none';
};

그런 다음 IMA SDK를 사용하여 스트림 요청을 하고, 광고 모음 매니페스트를 가져오고, IMA 스트림 이벤트를 리슨하고, emsg 이벤트를 IMA SDK에 전달하는 광고 관리자 클래스를 만듭니다.