Create a VOD session

Using the Video Stitcher API, you create a video-on-demand (VOD) session each time you dynamically insert ads prior to delivery to client devices. When you create a session, the response includes the playback URL and information about the ads that you inserted into the video.

This document describes how to create a VOD session. For more details, see the REST documentation.

Define a session

To create a VOD session, supply the following fields:

  • sourceUri: Required. Specifies the URL to the video asset to insert the ads into. The Video Stitcher API returns an HLS playback URL if the provided URL references an HLS manifest; likewise, a DASH playback URL is returned if this field references a DASH manifest.
  • adTagUri: Required. Specifies the URL of the ad server that returns the ad metadata. By default, ad impressions trigger on the server side when client devices fetch the ad video segments.
  • adTracking: Required. Determines if the client player is expected to trigger playback and activity events or if the Video Stitcher API is expected to trigger playback events on behalf of the client player. For more information on client-side ad tracking, see Handle VOD client ad tracking.

  • manifestOptions: Optional. Specifies which video renditions are generated in the stitched video manifest. The field also supports the ordering of the renditions in the stitched video manifest. For more information, see the manifest options documentation.

Create a session

To create a session for an ad-stitched video, use the projects.locations.vodSessions.create method. The following example uses server-side ad tracking.

REST

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number located in the Project number field on the IAM Settings page
  • LOCATION: the location in which to create your session; use one of the supported regions
    Show locations
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • VOD_URI: The URI of the media to stitch. This URI must reference either an MPEG-DASH manifest (.mpd) file or an M3U playlist manifest (.m3u8) file. Use a public URI or an unsigned URI for which you registered a CDN key.
  • AD_TAG_URI: the public URI of the ad tag; if you don't have one, you can use a VMAP Pre-roll sample

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/vodSessions/SESSION_ID",
  "interstitials": {
    "sessionContent": {
      "duration": "60s"
    }
  },
  "playUri": "PLAY_URI", # This is the ad-stitched VOD URI
  "sourceUri": "VOD_URI",
  "adTagUri": "AD_TAG_URI",
  "assetId": "ASSET_ID",
  "adTracking": "SERVER"
}

C#

Before trying this sample, follow the C# setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API C# API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;

public class CreateVodSessionSample
{
    public VodSession CreateVodSession(
        string projectId, string location, string sourceUri, string adTagUri)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CreateVodSessionRequest request = new CreateVodSessionRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            VodSession = new VodSession
            {
                SourceUri = sourceUri,
                AdTagUri = adTagUri,
                AdTracking = AdTracking.Server
            }
        };

        // Call the API.
        VodSession session = client.CreateVodSession(request);

        // Return the result.
        return session;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Go API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

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

// createVodSession creates a video on demand (VOD) session in which to insert ads.
// VOD sessions are ephemeral resources that expire after a few hours.
func createVodSession(w io.Writer, projectID, sourceURI string) error {
	// projectID := "my-project-id"

	// Uri of the media to stitch; this URI must reference either an MPEG-DASH
	// manifest (.mpd) file or an M3U playlist manifest (.m3u8) file.
	// sourceURI := "https://storage.googleapis.com/my-bucket/main.mpd"

	// See https://cloud.google.com/video-stitcher/docs/concepts for information
	// on ad tags and ad metadata. This sample uses an ad tag URL that displays
	// a VMAP Pre-roll ad
	// (https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags).
	adTagURI := "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpreonly&ciu_szs=300x250%2C728x90&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&correlator="
	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 := &stitcherstreampb.CreateVodSessionRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		VodSession: &stitcherstreampb.VodSession{
			SourceUri:  sourceURI,
			AdTagUri:   adTagURI,
			AdTracking: stitcherstreampb.AdTracking_SERVER,
		},
	}
	// Creates the VOD session.
	response, err := client.CreateVodSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateVodSession: %w", err)
	}

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

Java

Before trying this sample, follow the Java setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Java API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.video.stitcher.v1.AdTracking;
import com.google.cloud.video.stitcher.v1.CreateVodSessionRequest;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodSession;
import java.io.IOException;

public class CreateVodSession {

  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";
    // Uri of the media to stitch; this URI must reference either an MPEG-DASH
    // manifest (.mpd) file or an M3U playlist manifest (.m3u8) file.
    String sourceUri = "https://storage.googleapis.com/my-bucket/main.mpd";
    // See VMAP Pre-roll
    // (https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags)
    String adTagUri = "https://pubads.g.doubleclick.net/gampad/ads...";
    createVodSession(projectId, location, sourceUri, adTagUri);
  }

  public static void createVodSession(
      String projectId, String location, String sourceUri, String adTagUri) 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()) {
      CreateVodSessionRequest createVodSessionRequest =
          CreateVodSessionRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setVodSession(
                  VodSession.newBuilder()
                      .setSourceUri(sourceUri)
                      .setAdTagUri(adTagUri)
                      .setAdTracking(AdTracking.SERVER)
                      .build())
              .build();

      VodSession response = videoStitcherServiceClient.createVodSession(createVodSessionRequest);
      System.out.println("Created VOD session: " + response.getName());
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Node.js API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// sourceUri = 'https://storage.googleapis.com/my-bucket/main.mpd';
// See VMAP Pre-roll
// (https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags)
// adTagUri = 'https://pubads.g.doubleclick.net/gampad/ads...';

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

async function createVodSession() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    vodSession: {
      sourceUri: sourceUri,
      adTagUri: adTagUri,
      adTracking: 'SERVER',
    },
  };
  const [session] = await stitcherClient.createVodSession(request);
  console.log(`VOD session: ${session.name}`);
}

createVodSession();

PHP

Before trying this sample, follow the PHP setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API PHP API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Video\Stitcher\V1\AdTracking;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateVodSessionRequest;
use Google\Cloud\Video\Stitcher\V1\VodSession;

/**
 * Creates a VOD session. VOD sessions are ephemeral resources that expire
 * after a few hours.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the session
 * @param string $sourceUri            Uri of the media to stitch; this URI must
 *                                     reference either an MPEG-DASH manifest
 *                                     (.mpd) file or an M3U playlist manifest
 *                                     (.m3u8) file.
 * @param string $adTagUri             The Uri of the ad tag
 */
function create_vod_session(
    string $callingProjectId,
    string $location,
    string $sourceUri,
    string $adTagUri
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $vodSession = new VodSession();
    $vodSession->setSourceUri($sourceUri);
    $vodSession->setAdTagUri($adTagUri);
    $vodSession->setAdTracking(AdTracking::SERVER);

    // Run VOD session creation request
    $request = (new CreateVodSessionRequest())
        ->setParent($parent)
        ->setVodSession($vodSession);
    $response = $stitcherClient->createVodSession($request);

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

Python

Before trying this sample, follow the Python setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Python API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import argparse

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


def create_vod_session(
    project_id: str, location: str, source_uri: str, ad_tag_uri: str
) -> stitcher_v1.types.VodSession:
    """Creates a VOD session. VOD sessions are ephemeral resources that expire
    after a few hours.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the session.
        source_uri: Uri of the media to stitch; this URI must reference either an MPEG-DASH
                    manifest (.mpd) file or an M3U playlist manifest (.m3u8) file.
        ad_tag_uri: Uri of the ad tag.

    Returns:
        The VOD session resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    vod_session = stitcher_v1.types.VodSession(
        source_uri=source_uri, ad_tag_uri=ad_tag_uri, ad_tracking="SERVER"
    )

    response = client.create_vod_session(parent=parent, vod_session=vod_session)
    print(f"VOD session: {response.name}")
    return response

Ruby

Before trying this sample, follow the Ruby setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Ruby API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/video/stitcher"

##
# Create a video on demand (VOD) session. VOD sessions are ephemeral resources
# that expire after a few hours.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param source_uri [String] The URI of an MPEG-DASH manifest (.mpd) file or
#   an M3U playlist manifest (.m3u8) file
#   (e.g. "https://storage.googleapis.com/my-bucket/main.mpd")
# @param ad_tag_uri [String] The URI of the ad tag. See VMAP Pre-roll at
#   https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags.
#
def create_vod_session project_id:, location:, source_uri:, ad_tag_uri:
  # 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

  # Set the session fields.
  new_vod_session = {
    source_uri: source_uri,
    ad_tag_uri: ad_tag_uri,
    ad_tracking: Google::Cloud::Video::Stitcher::V1::AdTracking::SERVER
  }

  response = client.create_vod_session parent: parent,
                                       vod_session: new_vod_session

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

The Video Stitcher API generates a unique session ID for each request. A session expires after 4 hours.

An ad must be encoded before it can be stitched into a VOD session. When you create a session for an ad-stitched video, the Video Stitcher API determines if the ad has already been encoded from a previous session. If it has, the JSON response will indicate ad break events. The API only looks for encoded ads created by sessions associated with your Google Cloud project. For more information on this process, see the Overview.

Look at the JSON response. This response indicates that an ad was not stitched into the session. If this is the case, wait 5 minutes (for ad encoding) and then re-run the create session command. The response should now be similar to the following:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/vodSessions/SESSION_ID",
  "interstitials": {
    "adBreaks": [
      {
        "progressEvents": [
          {
            "timeOffset": "0s",
            "events": [
              {
                "type": "IMPRESSION",
                "uri": "https://securepubads.g.doubleclick.net/pcs/view..."
              },
              {
                "type": "START",
                "uri": "https://pubads.g.doubleclick.net/pagead/interaction/..."
              },
              ...
            ]
          },
          ...
        ],
        "ads": [
          {
            "duration": "10s",
            "activityEvents": [
              {
                "type": "ERROR",
                "uri": "https://pubads.g.doubleclick.net/pagead/interaction/..."
              },
              {
                "type": "CLICK_THROUGH",
                "uri": "https://pubads.g.doubleclick.net/pcs/click...",
                "id": "GDFP"
              },
              ...
            ]
          }
        ],
        "endTimeOffset": "10s",
        "startTimeOffset": "0s"
      }
    ],
    "sessionContent": {
      "duration": "70s"
    }
  },
  "playUri": "PLAY_URI",
  "sourceUri": "VOD_URI",
  "adTagUri": "AD_TAG_URI",
  "assetId": "ASSET_ID",
  "adTracking": "SERVER"
}

The response is a VodSession object that contains the following fields:

  • A name field that shows the VOD SESSION_ID. Use this ID to get the session.
  • An interstitials field that contains metadata about the ads that were inserted (see the ad metadata concepts).
  • A playUri field that shows the URL that the client device uses to play the conditioned video asset.

If you're generating a session on behalf of your customers' devices, set the following parameters via HTTP headers:

Parameter HTTP Header
CLIENT_IP x-user-ip
REFERRER_URL referer
USER_AGENT user-agent

You can add the following headers to the preceding curl request:

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

Ad tag macros

An ad tag can contain macros, which can result in a different ad tag for each session. Macros are denoted by square brackets in the ad tag, as illustrated by the following example:

AD_TAG_URI&macro=[value]

To substitute the value in the ad tag macro, provide a mapping in the adTagMacroMap field. For example, if you want to replace [value] with the string bar, you need to provide the following:

{
  ...
  "adTagUri": "AD_TAG_URI&macro=[value]",
  "adTagMacroMap": {
    "value": "bar"
  },
  ...
}

When the Video Stitcher API requests the ad metadata, it uses the following ad tag:

AD_TAG_URI&macro=bar

Get a session

To get the session for an ad-stitched video, use the projects.locations.vodSessions.get method.

REST

Before using any of the request data, make the following replacements:

  • PROJECT_NUMBER: your Google Cloud project number located in the Project number field on the IAM Settings page
  • LOCATION: the location of your session; use one of the supported regions
    Show locations
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • SESSION_ID: the identifier for the VOD session

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/vodSessions/SESSION_ID",
  "interstitials": {
    "adBreaks": [
      {
        "progressEvents": [
          {
            "timeOffset": "0s",
            "events": [
              {
                "type": "IMPRESSION",
                "uri": "https://securepubads.g.doubleclick.net/pcs/view..."
              },
              {
                "type": "START",
                "uri": "https://pubads.g.doubleclick.net/pagead/interaction/..."
              },
              ...
            ]
          },
          ...
        ],
        "ads": [
          {
            "duration": "10s",
            "activityEvents": [
              {
                "type": "ERROR",
                "uri": "https://pubads.g.doubleclick.net/pagead/interaction/..."
              },
              {
                "type": "CLICK_THROUGH",
                "uri": "https://pubads.g.doubleclick.net/pcs/click...",
                "id": "GDFP"
              },
              ...
            ]
          }
        ],
        "endTimeOffset": "10s",
        "startTimeOffset": "0s"
      }
    ],
    "sessionContent": {
      "duration": "70s"
    }
  },
  "playUri": "PLAY_URI",
  "sourceUri": "VOD_URI",
  "adTagUri": "AD_TAG_URI",
  "assetId": "ASSET_ID",
  "adTracking": "SERVER"
}

C#

Before trying this sample, follow the C# setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API C# API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Cloud.Video.Stitcher.V1;

public class GetVodSessionSample
{
    public VodSession GetVodSession(
        string projectId, string location, string sessionId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        GetVodSessionRequest request = new GetVodSessionRequest
        {
            VodSessionName = VodSessionName.FromProjectLocationVodSession(projectId, location, sessionId)
        };

        // Call the API.
        VodSession session = client.GetVodSession(request);

        // Return the result.
        return session;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Go API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

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

// getVodSession gets a VOD session by ID.
func getVodSession(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 := &stitcherstreampb.GetVodSessionRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/vodSessions/%s", projectID, location, sessionID),
	}
	// Gets the session.
	response, err := client.GetVodSession(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetVodSession: %w", err)
	}
	b, err := json.MarshalIndent(response, "", " ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}

	fmt.Fprintf(w, "VOD session:\n%s", string(b))
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Java API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.video.stitcher.v1.GetVodSessionRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VodSession;
import com.google.cloud.video.stitcher.v1.VodSessionName;
import java.io.IOException;

public class GetVodSession {

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

    getVodSession(projectId, location, sessionId);
  }

  public static void getVodSession(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()) {
      GetVodSessionRequest getVodSessionRequest =
          GetVodSessionRequest.newBuilder()
              .setName(VodSessionName.of(projectId, location, sessionId).toString())
              .build();

      VodSession response = videoStitcherServiceClient.getVodSession(getVodSessionRequest);
      System.out.println("VOD session: " + response.getName());
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Node.js API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * 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 getVodSession() {
  // Construct request
  const request = {
    name: stitcherClient.vodSessionPath(projectId, location, sessionId),
  };
  const [session] = await stitcherClient.getVodSession(request);
  console.log(`VOD session: ${session.name}`);
}

getVodSession();

PHP

Before trying this sample, follow the PHP setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API PHP API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

/**
 * Gets a VOD 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_vod_session(
    string $callingProjectId,
    string $location,
    string $sessionId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->vodSessionName($callingProjectId, $location, $sessionId);
    $request = (new GetVodSessionRequest())
        ->setName($formattedName);
    $session = $stitcherClient->getVodSession($request);

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

Python

Before trying this sample, follow the Python setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Python API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import argparse

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


def get_vod_session(
    project_id: str, location: str, session_id: str
) -> stitcher_v1.types.VodSession:
    """Gets a VOD session. VOD sessions are ephemeral resources that expire
    after a few hours.
    Args:
        project_id: The GCP project ID.
        location: The location of the session.
        session_id: The ID of the VOD session.

    Returns:
        The VOD session resource.
    """

    client = VideoStitcherServiceClient()

    name = client.vod_session_path(project_id, location, session_id)
    response = client.get_vod_session(name=name)
    print(f"VOD session: {response.name}")
    return response

Ruby

Before trying this sample, follow the Ruby setup instructions in the Video Stitcher API quickstart using client libraries. For more information, see the Video Stitcher API Ruby API reference documentation.

To authenticate to Video Stitcher API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/video/stitcher"

##
# Get a VOD session. VOD sessions are ephemeral resources that expire
# after a few hours.
#
# @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 VOD session ID (e.g. "my-vod-session-id")
#
def get_vod_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 VOD session.
  name = client.vod_session_path project: project_id, location: location,
                                 vod_session: session_id

  # Get the VOD session.
  session = client.get_vod_session name: name

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

Sample ad-stitched playlist

The following shows a sample source VOD playlist before ad stitching:

#EXTM3U
#EXT-X-TARGETDURATION:6
#EXT-X-VERSION:4
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:6.000,
segment_01.ts
#EXTINF:6.000,
segment_02.ts
#EXTINF:6.000,
segment_03.ts
#EXTINF:6.000,
segment_04.ts
#EXTINF:6.000,
segment_05.ts
#EXTINF:6.000,
segment_06.ts
#EXT-X-ENDLIST

The following shows a sample source VOD playlist after ad stitching with pre-roll, mid-roll, and post-roll ads:

#EXTM3U
#EXT-X-VERSION:4
#EXT-X-TARGETDURATION:6
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-DISCONTINUITY
#EXTINF:4,
https://ads.us-west1.cdn.videostitcher.goog/preroll_ad/seg_01.ts
#EXTINF:4,
https://ads.us-west1.cdn.videostitcher.goog/preroll_ad/seg_02.ts
#EXTINF:1.99,
https://ads.us-west1.cdn.videostitcher.goog/preroll_ad/seg_03.ts
#EXT-X-DISCONTINUITY
#EXTINF:6,
segment_01.ts
#EXTINF:6,
segment_02.ts
#EXT-X-DISCONTINUITY
#EXTINF:4,
https://ads.us-west1.cdn.videostitcher.goog/midroll_ad/seg_01.ts
#EXTINF:0.99,
https://ads.us-west1.cdn.videostitcher.goog/midroll_ad/seg_02.ts
#EXT-X-DISCONTINUITY
#EXTINF:6.000,
segment_03.ts
#EXTINF:6.000,
segment_04.ts
#EXTINF:6.000,
segment_05.ts
#EXTINF:6.000,
segment_06.ts
#EXT-X-DISCONTINUITY
#EXTINF:4,
https://ads.us-west1.cdn.videostitcher.goog/postroll_ad/seg_01.ts
#EXTINF:4,
https://ads.us-west1.cdn.videostitcher.goog/postroll_ad/seg_02.ts
#EXTINF:1.99,
https://ads.us-west1.cdn.videostitcher.goog/postroll_ad/seg_03.ts
#EXT-X-ENDLIST

Avoid ad-break misalignment

For VOD stitching, you should pre-condition the source video manifest for midroll ad breaks and configure the Video Multiple Ad Playlist (VMAP) ad tag to return midroll ad breaks at the pre-conditioned offset positions. The Video Stitcher API takes the result of the transcoded output and inserts ads as close as possible to where you specify. Use pre-conditioned inputs for midroll ad breaks to make ad stitching behavior consistent and accurate.

For example, the following video playlist shows an ad placement opportunity at the seven second mark:

#EXTM3U

#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-TARGETDURATION:4

#EXTINF:2.0
../video/180_250000/hls/segment_0.ts
#EXTINF:2.0
../video/180_250000/hls/segment_1.ts
#EXTINF:2.0
../video/180_250000/hls/segment_2.ts
#EXTINF:1.0
../video/180_250000/hls/segment_3.ts
#EXT-X-PLACEMENT-OPPORTUNITY
#EXTINF:2.0
../video/180_250000/hls/segment_4.ts

The following audio playlist shows an ad placement opportunity at the seven second mark:

#EXTM3U

#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-TARGETDURATION:4

#EXTINF:1.99
../audio/1_stereo_128000/hls/segment_0.ts
#EXTINF:1.99
../audio/1_stereo_128000/hls/segment_1.ts
#EXTINF:1.99
../audio/1_stereo_128000/hls/segment_2.ts
#EXTINF:1.03
../audio/1_stereo_128000/hls/segment_3.ts
#EXT-X-PLACEMENT-OPPORTUNITY
#EXTINF:1.99
../audio/1_stereo_128000/hls/segment_4.ts

The following VMAP configuration specifies an ad break to occur at the seven second mark. The video and audio playlists will contain ad breaks at exactly the seven second mark:

<vmap:VMAP xmlns:vmap="http://www.iab.net/videosuite/vmap" version="1.0">
<vmap:AdBreak timeOffset="00:00:07.000" breakType="linear" breakId="midroll‑1">
<vmap:AdSource id="midroll-1‑ad‑1" allowMultipleAds="false" followRedirects="true">
<vmap:AdTagURI templateType="vast3">
<![CDATA[
https://securepubads.g.doubleclick.net/gampad/ads?...
]]>
</vmap:AdTagURI>
</vmap:AdSource>
</vmap:AdBreak>
</vmap:VMAP>

For more information on ad server formats, see Ad server compliance.