Atualizar um endpoint de entrada

Atualizar um recurso de endpoint de entrada de transmissão ao vivo.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C#

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API C# da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


using Google.Cloud.Video.LiveStream.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class UpdateInputSample
{
    public async Task<Input> UpdateInputAsync(
         string projectId, string locationId, string inputId)
    {
        // Create the client.
        LivestreamServiceClient client = LivestreamServiceClient.Create();

        UpdateInputRequest request = new UpdateInputRequest
        {
            Input = new Input
            {
                InputName = InputName.FromProjectLocationInput(projectId, locationId, inputId),
                PreprocessingConfig = new PreprocessingConfig
                {
                    Crop = new PreprocessingConfig.Types.Crop
                    {
                        TopPixels = 5,
                        BottomPixels = 5
                    }
                }
            },
            UpdateMask = new FieldMask { Paths = { "preprocessing_config" } }
        };

        // Make the request.
        Operation<Input, OperationMetadata> response = await client.UpdateInputAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<Input, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Go da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	"cloud.google.com/go/video/livestream/apiv1/livestreampb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateInput updates an existing input endpoint. This sample adds a
// preprocessing configuration to an existing input.
func updateInput(w io.Writer, projectID, location, inputID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputID := "my-input"
	ctx := context.Background()
	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &livestreampb.UpdateInputRequest{
		Input: &livestreampb.Input{
			Name: fmt.Sprintf("projects/%s/locations/%s/inputs/%s", projectID, location, inputID),
			PreprocessingConfig: &livestreampb.PreprocessingConfig{
				Crop: &livestreampb.PreprocessingConfig_Crop{
					TopPixels:    5,
					BottomPixels: 5,
				},
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"preprocessing_config",
			},
		},
	}
	// Updates the input.
	op, err := client.UpdateInput(ctx, req)
	if err != nil {
		return fmt.Errorf("UpdateInput: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Updated input: %v", response.Name)
	return nil
}

Java

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Java da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import com.google.cloud.video.livestream.v1.Input;
import com.google.cloud.video.livestream.v1.InputName;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;
import com.google.cloud.video.livestream.v1.PreprocessingConfig;
import com.google.cloud.video.livestream.v1.PreprocessingConfig.Crop;
import com.google.cloud.video.livestream.v1.UpdateInputRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateInput {

  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 inputId = "my-input-id";

    updateInput(projectId, location, inputId);
  }

  public static void updateInput(String projectId, String location, String inputId)
      throws InterruptedException, ExecutionException, TimeoutException, 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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create();
    var updateInputRequest =
        UpdateInputRequest.newBuilder()
            .setInput(
                Input.newBuilder()
                    .setName(InputName.of(projectId, location, inputId).toString())
                    .setPreprocessingConfig(
                        PreprocessingConfig.newBuilder()
                            .setCrop(Crop.newBuilder().setTopPixels(5).setBottomPixels(5).build())
                            .build())
                    .build())
            .setUpdateMask(FieldMask.newBuilder().addPaths("preprocessing_config").build())
            .build();
    // First API call in a project can take up to 10 minutes.
    Input result =
        livestreamServiceClient.updateInputAsync(updateInputRequest).get(10, TimeUnit.MINUTES);
    System.out.println("Updated input: " + result.getName());
    livestreamServiceClient.close();
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Node.js da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

// Imports the Livestream library
const {LivestreamServiceClient} = require('@google-cloud/livestream').v1;

// Instantiates a client
const livestreamServiceClient = new LivestreamServiceClient();

async function updateInput() {
  // Construct request
  const request = {
    input: {
      name: livestreamServiceClient.inputPath(projectId, location, inputId),
      preprocessingConfig: {
        crop: {
          topPixels: 5,
          bottomPixels: 5,
        },
      },
    },
    updateMask: {
      paths: ['preprocessing_config'],
    },
  };

  // Run request
  const [operation] = await livestreamServiceClient.updateInput(request);
  const response = await operation.promise();
  const [input] = response;
  console.log(`Updated input: ${input.name}`);
}

updateInput();

PHP

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API PHP da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\Cloud\Video\LiveStream\V1\Input;
use Google\Cloud\Video\LiveStream\V1\Client\LivestreamServiceClient;
use Google\Cloud\Video\LiveStream\V1\PreprocessingConfig;
use Google\Cloud\Video\LiveStream\V1\UpdateInputRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates an input.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the input
 * @param string  $inputId            The ID of the input to be updated
 */
function update_input(
    string $callingProjectId,
    string $location,
    string $inputId
): void {
    // Instantiate a client.
    $livestreamClient = new LivestreamServiceClient();

    $formattedName = $livestreamClient->inputName($callingProjectId, $location, $inputId);
    $crop = (new PreprocessingConfig\Crop())
        ->setTopPixels(5)
        ->setBottomPixels(5);
    $config = (new PreprocessingConfig())
        ->setCrop($crop);
    $input = (new Input())
        ->setName($formattedName)
        ->setPreprocessingConfig($config);

    $updateMask = new FieldMask([
        'paths' => ['preprocessing_config']
    ]);

    // Run the input update request. The response is a long-running operation ID.
    $request = (new UpdateInputRequest())
        ->setInput($input)
        ->setUpdateMask($updateMask);
    $operationResponse = $livestreamClient->updateInput($request);

    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Updated input: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Python da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import argparse

from google.cloud.video import live_stream_v1
from google.cloud.video.live_stream_v1.services.livestream_service import (
    LivestreamServiceClient,
)
from google.protobuf import field_mask_pb2 as field_mask

def update_input(
    project_id: str, location: str, input_id: str
) -> live_stream_v1.types.Input:
    """Updates an input.
    Args:
        project_id: The GCP project ID.
        location: The location of the input.
        input_id: The user-defined input ID."""

    client = LivestreamServiceClient()

    name = f"projects/{project_id}/locations/{location}/inputs/{input_id}"

    input = live_stream_v1.types.Input(
        name=name,
        preprocessing_config=live_stream_v1.types.PreprocessingConfig(
            crop=live_stream_v1.types.PreprocessingConfig.Crop(
                top_pixels=5,
                bottom_pixels=5,
            )
        ),
    )
    update_mask = field_mask.FieldMask(paths=["preprocessing_config"])

    operation = client.update_input(input=input, update_mask=update_mask)
    response = operation.result(600)
    print(f"Updated input: {response.name}")

    return response

Ruby

Para saber como instalar e usar a biblioteca de cliente da API Live Stream, consulte Bibliotecas de cliente da API Live Stream. Para mais informações, consulte a documentação de referência da API Ruby da API Live Stream.

Para autenticar na API Live Stream, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

require "google/cloud/video/live_stream"

##
# Update an input endpoint
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location [String] The location (e.g. "us-central1")
# @param input_id [String] Your input name (e.g. "my-input")
#
def update_input project_id:, location:, input_id:
  # Create a Live Stream client.
  client = Google::Cloud::Video::LiveStream.livestream_service

  # Build the resource name of the input.
  name = client.input_path project: project_id, location: location, input: input_id

  # Set the update mask.
  update_mask = { paths: ["preprocessing_config"] }

  # Update the input pre-processing config field.
  update_input = {
    name: name,
    preprocessing_config: {
      crop: {
        top_pixels: 5,
        bottom_pixels: 5
      }
    }
  }

  operation = client.update_input update_mask: update_mask, input: update_input

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the input name.
  puts "Updated input: #{operation.response.name}"
  puts "Updated pre-processing config: #{operation.response.preprocessing_config.crop.top_pixels}"
end

A seguir

Para pesquisar e filtrar amostras de código para outros produtos do Google Cloud, consulte o navegador de amostra do Google Cloud.