iOS에서 IMA DAI SDK 사용

Google Cloud Video Stitcher API에 등록된 라이브 스트림 재생

이 가이드에서는 iOS용 IMA DAI SDK를 사용하여 Google Cloud Video Stitcher API에 등록된 이벤트의 라이브 스트림을 요청하고 재생하는 방법과 재생 중에 광고 시점을 삽입하는 방법을 설명합니다.

이 가이드에서는 IMA DAI용 시작 가이드의 기본 예시를 설명합니다.

다른 플랫폼과 통합하거나 IMA 클라이언트 측 SDK를 사용하는 방법에 대한 자세한 내용은 양방향 미디어 광고 SDK를 참조하세요.

Google Cloud 프로젝트 설정

IMA SDK에서 사용할 다음 변수를 입력합니다.

위치
라이브 구성이 생성된 Google Cloud 리전: LOCATION
프로젝트 번호
Video Stitcher API를 사용하는 Google Cloud 프로젝트 번호: PROJECT_NUMBER
OAuth 토큰

Video Stitcher 사용자 역할이 포함된 서비스 계정의 단기 OAuth 토큰:

OAUTH_TOKEN

서비스 계정의 단기 사용자 인증 정보 만들기에 대해 자세히 알아보세요. OAuth 토큰은 만료되지 않은 한 여러 요청에서 재사용될 수 있습니다.

네트워크 코드

광고 요청에 사용되는 Ad Manager 네트워크 코드: NETWORK_CODE

라이브 구성 ID
라이브 스트림 이벤트를 만들 때 지정한 라이브 구성 ID: LIVE_CONFIG_ID
커스텀 애셋 키
Video Stitcher API를 사용하여 라이브 스트림 이벤트 구성을 만드는 과정에서 생성된 Ad Manager 커스텀 애셋 키: CUSTOM_ASSET_KEY

사용자 컨텍스트
요청 추적에 사용되는 사용자 컨텍스트. nil일 수 있습니다. 이 가이드에서 기본값은 nil입니다.

기본 예시 다운로드 및 준비

iOS용 IMA DAI 예시를 다운로드하고 기본 예시를 새 폴더에 추출합니다. 이 예시는 CocoaPods를 사용하여 IMA SDK를 로드하는 Xcode 프로젝트입니다.

샘플 실행을 준비하려면 CocoaPods가 설치되어 있는지 확인한 후 터미널에서 기본 예시 폴더를 열고 다음 명령어를 실행합니다.

pod install --repo-update

이 명령어가 완료되면 프로젝트 폴더에 BasicExample.xcworkspace 파일이 표시됩니다. Xcode에서 이 파일을 열고 샘플을 실행하여 테스트 동영상과 광고가 예상대로 재생되는지 확인합니다.

라이브 스트림 요청

샘플 스트림을 라이브 스트림으로 바꾸려면 Google Ad Manager로 광고 세션을 자동으로 만드는 IMAVideoStitcherLiveStreamRequest 클래스를 사용해야 합니다. Google Ad Manager UI를 사용하면 모니터링 및 디버깅 목적으로 생성된 DAI 세션을 찾을 수 있습니다.

기존 샘플에는 Google DAI 서버에서 VOD 스트림이나 라이브 스트림을 요청하는 예시가 있습니다. Google Cloud Video Stitcher API에서 샘플을 사용하려면 현재 requestStream 함수를 IMAVideoStitcherLiveStreamRequest 클래스를 사용하는 함수로 바꿔야 합니다.

ViewController.m

#import <GoogleInteractiveMediaAds/GoogleInteractiveMediaAds.h>

/// Fallback URL in case something goes wrong in loading the stream. If all goes well,
/// this will not be used.
static NSString *const kTestAppContentUrl_M3U8 =
    @"//devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8";


static NSString *const kLiveConfigId = @"LIVE_CONFIG_ID";
static NSString *const kLocation = @"LOCATION";
static NSString *const kProjectNumber = @"PROJECT_NUMBER";
static NSString *const kOAuthToken = @"OAUTH_TOKEN";
static NSString *const kNetworkCode = @"NETWORK_CODE";
static NSString *const kCustomAssetKey = @"CUSTOM_ASSET_KEY";


@interface ViewController () <IMAAdsLoaderDelegate, IMAStreamManagerDelegate>
...
- (void)requestStream {
  // Create an ad display container for ad rendering.
  IMAAdDisplayContainer *adDisplayContainer =
      [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView
                                          viewController:self
                                          companionSlots:nil];
  // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player.
  IMAAVPlayerVideoDisplay *imaVideoDisplay =
      [[IMAAVPlayerVideoDisplay alloc] initWithAVPlayer:self.contentPlayer];


  IMAVideoStitcherLiveStreamRequest *request =
      [[IMAVideoStitcherLiveStreamRequest alloc] initWithLiveStreamEventID:kLiveConfigId
                                                                    region:kLocation
                                                             projectNumber:kProjectNumber
                                                                OAuthToken:kOAuthToken
                                                               networkCode:kNetworkCode
                                                            customAssetKey:kCustomAssetKey
                                                        adDisplayContainer:adDisplayContainer
                                                              videoDisplay:imaVideoDisplay
                                                               userContext:nil
                                                               videoStitcherSessionOptions:nil];

  [self.adsLoader requestStreamWithRequest:request];
}

(선택사항) 스트리밍 세션 옵션 추가

IMAVideoStitcherLiveStreamRequestvideoStitcherSessionOptions 매개변수를 채워 기본 Cloud Video Stitcher API 구성을 재정의하는 세션 옵션을 추가하여 스트림 요청을 맞춤설정합니다. 인식할 수 없는 옵션을 제공하면 Cloud Video Stitcher API에서 HTTP 400 오류로 응답합니다. 도움이 필요하면 문제 해결 가이드를 참조하세요.

예를 들어 다음 코드 스니펫으로 매니페스트 옵션을 재정의할 수 있으며 이 옵션에서는 가장 낮은 비트 전송률에서 가장 높은 비트 전송률 순으로 변환되는 스트림 매니페스트 2개를 요청합니다.

Objective-C

 // define session options JSON string
 NSString *sessionOptionsStr =
   @"{"
   "  \"manifestOptions\": {"
   "    \"includeRenditions\":["
   "      {\"bitrateBps\": 3000, \"codecs\": \"hvc1.1.4.L126.B0, mp4a.40.2\"},"
   "      {\"bitrateBps\": 2000, \"codecs\": \"avc1.64001f, mp4a.40.2\"},"
   "    ]"
   "  }"
   "}";
 // convert JSON NSString to NSDictionary
 NSData *sessionOptionsData = [sessionOptionsStr dataUsingEncoding:NSUTF8StringEncoding];
 NSError *error = nil;
 NSDictionary *sessionOptions = [NSJSONSerialization
                       JSONObjectWithData:sessionOptionsData
                       options:0
                       error:&error];
 // make stream request
 IMAVideoStitcherLiveStreamRequest *request =
     [[IMAVideoStitcherLiveStreamRequest alloc] initWithLiveStreamEventID:kLiveConfigId
                                                                   region:kRegion
                                                           projectNumber:kProjectNumber
                                                               OAuthToken:kOAuthToken
                                                             networkCode:kNetworkCode
                                                           customAssetKey:kCustomAssetKey
                                                       adDisplayContainer:adDisplayContainer
                                                             videoDisplay:imaVideoDisplay
                                                             userContext:nil
                                             videoStitcherSessionOptions:sessionOptions];
 [self.adsLoader requestStreamWithRequest:request];

Swift

 // define session options JSON string
 let sessionOptionsStr = """
     {
       "manifestOptions": {
         "includeRenditions": [
           {"bitrateBps": 3000, "codecs": "hvc1.1.4.L126.B0, mp4a.40.2"},
           {"bitrateBps": 2000, "codecs": "avc1.64001f, mp4a.40.2"},
         ],
         "bitrateOrder": "ascending"
       }
     }
     """
 // convert JSON string to dictionary
 guard let sessionOptionsData = sessionOptionsStr.data(using: .utf8, allowLossyConversion: false) else { return nil }
 let sessionOptions = try? JSONSerialization.jsonObject(with: sessionOptionsData, options: .mutableContainers)
 // make stream request
 let request = IMAVideoStitcherLiveStreamRequest(
   liveStreamEventID:ViewController.liveConfigId
   region:ViewController.region
   projectNumber:ViewController.projectNumber
   OAuthToken:ViewController.oAuthToken
   networkCode:ViewController.networkCode
   customAssetKey:ViewController.customAssetKey
   adDisplayContainer:adDisplayContainer
   videoDisplay:imaVideoDisplay
   userContext:nil
   videoStitcherSessionOptions:sessionOptions)
 adsLoader?.requestStream(with: request)

프로젝트를 실행하면 커스텀 라이브 스트림을 요청하고 재생할 수 있습니다.

광고 시점 삽입

Google Cloud Video Stitcher API는 각 광고 시점의 광고 태그에서 검색된 광고를 삽입합니다. 광고 시점은 광고 마커를 사용하여 매니페스트에 표시됩니다. 라이브 스트림 인코더에서 광고 마커를 삽입합니다.

  • 자체 라이브 스트림을 사용하는 경우 사용자가 광고 마커를 삽입해야 합니다. 지원되는 HLS 및 DASH 광고 마커에 대한 자세한 내용은 광고 마커 문서를 참조하세요.

  • Google Cloud Livestream API를 사용하여 라이브 스트림을 만든 경우 광고 시점 채널 이벤트를 삽입합니다.

광고 시점이 삽입되면 바로 광고가 재생됩니다.

삭제

이제 Google Cloud Video Stitcher API를 사용하여 라이브 스트림을 성공적으로 호스팅하고 iOS용 IMA DAI SDK를 사용하여 요청했으므로 모든 제공 리소스를 삭제해야 합니다.

라이브 스트림 삭제 가이드에 따라 불필요한 리소스와 애셋을 삭제합니다.