创建实时会话

使用 Video Stitcher API,每次开始播放直播时,您都可以创建一个直播会话,直播的广告插播时间点会动态拼接广告。响应会指定实时会话的播放网址和配置。

本文档介绍了如何创建实时会话。如需了解详情,请参阅 REST 文档

准备工作

定义实时会话

定义实时会话时,以下字段是必填字段:

  • liveConfig

定义实时会话时,以下字段为选填字段:

  • adTagMacros
  • manifestOptions

adTagMacros 参数是用于替换广告代码宏的键值对列表。如需了解详情,请参阅“广告代码宏”部分

manifestOptions 参数指定在拼接的视频清单中生成哪些视频呈现。它还支持对拼接视频清单中的呈现排序。如需了解详情,请参阅清单选项文档

创建实时会话

如需创建实时会话,请使用 projects.locations.liveSessions.create 方法。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号,位于 IAM 设置页面的项目编号字段中
  • LOCATION:要在其中创建会话的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • LIVE_CONFIG_ID:用户定义的实时配置的标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID",
  "playUri": "PLAY_URI",
  "liveConfig": "projects/PROJECT_NUMBER/locations/LOCATION/liveConfigs/LIVE_CONFIG_ID",
}

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Video.Stitcher.V1;

public class CreateLiveSessionSample
{
    public LiveSession CreateLiveSession(
        string projectId, string location, string liveConfigId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CreateLiveSessionRequest request = new CreateLiveSessionRequest
        {
            Parent = $"projects/{projectId}/locations/{location}",
            LiveSession = new LiveSession
            {
                LiveConfig = LiveConfigName.FormatProjectLocationLiveConfig(projectId, location, liveConfigId)
            }
        };

        // Call the API.
        LiveSession session = client.CreateLiveSession(request);

        // Return the result.
        return session;
    }
}

Go

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	"cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createLiveSession creates a livestream session in which to insert ads.
// Live sessions are ephemeral resources that expire after a few minutes.
func createLiveSession(w io.Writer, projectID, liveConfigID string) error {
	// projectID := "my-project-id"
	// liveConfigID := "my-live-config"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherpb.CreateLiveSessionRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		LiveSession: &stitcherpb.LiveSession{
			LiveConfig: fmt.Sprintf("projects/%s/locations/%s/liveConfigs/%s", projectID, location, liveConfigID),
		},
	}
	// Creates the live session.
	response, err := client.CreateLiveSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateLiveSession: %w", err)
	}

	fmt.Fprintf(w, "Live session: %v\n", response.GetName())
	fmt.Fprintf(w, "Play URI: %v", response.GetPlayUri())
	return nil
}

Java

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.CreateLiveSessionRequest;
import com.google.cloud.video.stitcher.v1.LiveConfigName;
import com.google.cloud.video.stitcher.v1.LiveSession;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class CreateLiveSession {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String liveConfigId = "my-live-config-id";

    createLiveSession(projectId, location, liveConfigId);
  }

  public static void createLiveSession(String projectId, String location, String liveConfigId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CreateLiveSessionRequest createLiveSessionRequest =
          CreateLiveSessionRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setLiveSession(
                  LiveSession.newBuilder()
                      .setLiveConfig(LiveConfigName.format(projectId, location, liveConfigId)))
              .build();

      LiveSession response = videoStitcherServiceClient.createLiveSession(createLiveSessionRequest);
      System.out.println("Created live session: " + response.getName());
      System.out.println("Play URI: " + response.getPlayUri());
    }
  }
}

Node.js

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// liveConfigId = 'my-live-config-id';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function createLiveSession() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    liveSession: {
      liveConfig: stitcherClient.liveConfigPath(
        projectId,
        location,
        liveConfigId
      ),
    },
  };

  const [session] = await stitcherClient.createLiveSession(request);
  console.log(`Live session: ${session.name}`);
  console.log(`Play URI: ${session.playUri}`);
}

createLiveSession();

PHP

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateLiveSessionRequest;
use Google\Cloud\Video\Stitcher\V1\LiveSession;

/**
 * Creates a live session. Live sessions are ephemeral resources that expire
 * after a few minutes.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $liveConfigId         The live config ID to use to create the
 *                                     live session
 */
function create_live_session(
    string $callingProjectId,
    string $location,
    string $liveConfigId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $liveConfig = $stitcherClient->liveConfigName($callingProjectId, $location, $liveConfigId);
    $liveSession = new LiveSession();
    $liveSession->setLiveConfig($liveConfig);

    // Run live session creation request
    $request = (new CreateLiveSessionRequest())
        ->setParent($parent)
        ->setLiveSession($liveSession);
    $response = $stitcherClient->createLiveSession($request);

    // Print results
    printf('Live session: %s' . PHP_EOL, $response->getName());
}

Python

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def create_live_session(
    project_id: str, location: str, live_config_id: str
) -> stitcher_v1.types.LiveSession:
    """Creates a live session. Live sessions are ephemeral resources that expire
    after a few minutes.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the session.
        live_config_id: The user-defined live config ID.

    Returns:
        The live session resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    live_config = (
        f"projects/{project_id}/locations/{location}/liveConfigs/{live_config_id}"
    )

    live_session = stitcher_v1.types.LiveSession(live_config=live_config)

    response = client.create_live_session(parent=parent, live_session=live_session)
    print(f"Live session: {response.name}")
    return response

Ruby

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Create a live stream session. Live sessions are ephemeral resources
# that expire after a few minutes.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param live_config_id [String] Your live config name (e.g. "my-live-config")
#
def create_live_session project_id:, location:, live_config_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location

  # Build the resource name of the live config.
  live_config_name = client.live_config_path project: project_id,
                                             location: location,
                                             live_config: live_config_id

  # Set the session fields.
  new_live_session = {
    live_config: live_config_name
  }

  response = client.create_live_session parent: parent,
                                        live_session: new_live_session

  # Print the live session name.
  puts "Live session: #{response.name}"
end

Video Stitcher API 会为每个请求生成唯一的会话 ID。如果在过去 5 分钟内未请求 playUri,会话将过期。

广告必须先经过编码,然后才能拼接成实时会话。当您为拼接的视频创建会话时,Video Stitcher API 会确定该广告是否已在上一个会话中编码过。该 API 仅查找由与您的 Google Cloud 项目关联的会话创建的已编码广告。如需详细了解此过程,请参阅概览

响应是一个实时会话对象playUri 是客户端设备用于播放此直播活动的广告拼接视频流的网址。

如果您要代表客户的设备生成会话,则可以使用 HTTP 标头设置以下参数:

参数 HTTP 标头
CLIENT_IP x-forwarded-for
REFERRER_URL referer
USER_AGENT user-agent

您可以将以下标头添加到上述 curl 请求中:

-H "x-forwarded-for: CLIENT_IP" \
-H "referer: REFERRER_URL" \
-H "user-agent: USER_AGENT" \

如果未提供 x-forwarded-for 标头,Video Stitcher API 在广告元数据请求中使用客户端的 IP 地址。请注意,如果会话是代表客户的设备生成的,则客户端的 IP 地址可能与客户设备的 IP 不匹配。

广告代码宏

广告代码可以包含宏,这些宏可以为每个会话生成不同的广告代码。宏在广告代码中用方括号表示,如以下示例所示:

AD_TAG_URI&macro=[value]

adTagUri实时配置中定义。

如需替换广告代码宏中的值,请在 adTagMacros 字段中提供映射。例如,如果要将 [value] 宏替换为字符串 bar,您需要提供以下信息:

{
  ...
  "adTagMacros": {
    "value": "bar"
  },
  ...
}

当 Video Stitcher API 请求广告元数据时,它会使用以下广告代码:

AD_TAG_URI&macro=bar

获取会话

如需获取实时会话,请使用 projects.locations.liveSessions.get 方法。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_NUMBER:您的 Google Cloud 项目编号,位于 IAM 设置页面的项目编号字段中
  • LOCATION:要在其中创建会话的位置;请使用支持的区域之一
    显示位置信息
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • SESSION_ID:实时会话的标识符

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/liveSessions/SESSION_ID",
  "playUri": "ad-stitched-live-stream-uri",
  "liveConfig": "projects/PROJECT_NUMBER/locations/LOCATION/liveConfigs/LIVE_CONFIG_ID",
}

C#

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API C# API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Cloud.Video.Stitcher.V1;

public class GetLiveSessionSample
{
    public LiveSession GetLiveSession(
        string projectId, string location, string sessionId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        GetLiveSessionRequest request = new GetLiveSessionRequest
        {
            LiveSessionName = LiveSessionName.FromProjectLocationLiveSession(projectId, location, sessionId)
        };

        // Call the API.
        LiveSession session = client.GetLiveSession(request);

        // Return the result.
        return session;
    }
}

Go

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Go API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	"cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// getLiveSession gets a livestream session by ID.
func getLiveSession(w io.Writer, projectID, sessionID string) error {
	// projectID := "my-project-id"
	// sessionID := "123-456-789"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherpb.GetLiveSessionRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/liveSessions/%s", projectID, location, sessionID),
	}
	// Gets the session.
	response, err := client.GetLiveSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetLiveSession: %w", err)
	}

	fmt.Fprintf(w, "Live session: %+v", response)
	return nil
}

Java

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.GetLiveSessionRequest;
import com.google.cloud.video.stitcher.v1.LiveSession;
import com.google.cloud.video.stitcher.v1.LiveSessionName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class GetLiveSession {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String sessionId = "my-session-id";

    getLiveSession(projectId, location, sessionId);
  }

  public static void getLiveSession(String projectId, String location, String sessionId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. In this example, try-with-resources is used
    // which automatically calls close() on the client to clean up resources.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      GetLiveSessionRequest getLiveSessionRequest =
          GetLiveSessionRequest.newBuilder()
              .setName(LiveSessionName.of(projectId, location, sessionId).toString())
              .build();

      LiveSession response = videoStitcherServiceClient.getLiveSession(getLiveSessionRequest);
      System.out.println("Live session: " + response.getName());
    }
  }
}

Node.js

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Node.js API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// sessionId = 'my-session-id';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function getLiveSession() {
  // Construct request
  const request = {
    name: stitcherClient.liveSessionPath(projectId, location, sessionId),
  };
  const [session] = await stitcherClient.getLiveSession(request);
  console.log(`Live session: ${session.name}`);
}

getLiveSession();

PHP

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API PHP API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\GetLiveSessionRequest;

/**
 * Gets a live session.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $sessionId            The ID of the session
 */
function get_live_session(
    string $callingProjectId,
    string $location,
    string $sessionId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->liveSessionName($callingProjectId, $location, $sessionId);
    $request = (new GetLiveSessionRequest())
        ->setName($formattedName);
    $session = $stitcherClient->getLiveSession($request);

    // Print results
    printf('Live session: %s' . PHP_EOL, $session->getName());
}

Python

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Python API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def get_live_session(
    project_id: str, location: str, session_id: str
) -> stitcher_v1.types.LiveSession:
    """Gets a live session. Live sessions are ephemeral resources that expire
    after a few minutes.
    Args:
        project_id: The GCP project ID.
        location: The location of the session.
        session_id: The ID of the live session.

    Returns:
        The live session resource.
    """

    client = VideoStitcherServiceClient()

    name = client.live_session_path(project_id, location, session_id)
    response = client.get_live_session(name=name)
    print(f"Live session: {response.name}")
    return response

Ruby

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Get a live session. Live sessions are ephemeral resources
# that expire after a few minutes.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param session_id [String] The live session ID (e.g. "my-live-session-id")
#
def get_live_session project_id:, location:, session_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the live session.
  name = client.live_session_path project: project_id, location: location,
                                  live_session: session_id

  # Get the live session.
  session = client.get_live_session name: name

  # Print the live session name.
  puts "Live session: #{session.name}"
end

广告拼接的播放列表示例

以下代码展示了广告拼接之前的源直播播放列表示例:

#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:5
#EXTINF:10.010
segment_00005.ts
#EXTINF:10.010
segment_00006.ts
#EXT-X-DATERANGE:ID="2415919105",START-DATE="2021-06-22T08:32:00Z",DURATION=60,SCTE35-OUT=0xF...
#EXTINF:10.010
segment_00007.ts
#EXTINF:10.010
segment_00008.ts
#EXT-X-DATERANGE:ID="2415919105",START-DATE="2021-06-22T08:39:20Z",SCTE35-IN=0xF...
#EXTINF:10.010
segment_00009.ts

以下是广告拼接后的源直播播放列表示例:

#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:5
#EXTINF:10.010
segment_00005.ts
#EXTINF:10.010
segment_00006.ts
#EXT-X-DISCONTINUITY
#EXTINF:6.000
https://ads.us-west1.cdn.videostitcher.goog/ad-1/seg-1.ts
#EXTINF:5.000
https://ads.us-west1.cdn.videostitcher.goog/ad-1/seg-2.ts
#EXT-X-DISCONTINUITY
#EXTINF:6.000
https://ads.us-west1.cdn.videostitcher.goog/ad-2/seg-1.ts
#EXTINF:5.000
https://ads.us-west1.cdn.videostitcher.goog/ad-2/seg-2.ts
#EXT-X-DISCONTINUITY
#EXTINF:10.010
segment_00009.ts