Create input (v1)

Create a new input endpoint for streaming video.

Code sample

Go

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Go API reference documentation.

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


import (
	"context"
	"fmt"
	"io"

	livestream "cloud.google.com/go/video/livestream/apiv1"
	livestreampb "cloud.google.com/go/video/livestream/apiv1/livestreampb"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// createInput creates an input endpoint for streaming video.
func createInput(ctx context.Context, w io.Writer, projectID string, locationID string, inputID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	input := &livestreampb.Input{
		Type: livestreampb.Input_RTMP_PUSH,
		Tier: livestreampb.Input_HD,
	}

	client, err := livestream.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient failed: %w", err)
	}
	defer client.Close()

	req := &livestreampb.CreateInputRequest{
		Parent:  parent,
		InputId: inputID,
		Input:   input,
	}

	op, err := client.CreateInput(ctx, req)
	// Handle regional quota exhaustion by removing an existing input and retrying.
	if status.Code(err) == codes.ResourceExhausted {
		it := client.ListInputs(ctx, &livestreampb.ListInputsRequest{Parent: parent})
		for {
			item, listErr := it.Next()
			if listErr != nil {
				break
			}
			delOp, delErr := client.DeleteInput(ctx, &livestreampb.DeleteInputRequest{Name: item.GetName()})
			if delErr != nil {
				continue
			}
			if waitErr := delOp.Wait(ctx); waitErr == nil {
				op, err = client.CreateInput(ctx, req)
				if err == nil {
					break
				}
			}
		}
	}
	if err != nil {
		return fmt.Errorf("CreateInput: %w", err)
	}

	response, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Created input: %s\n", response.GetName())
	return nil
}

Node.js

To learn how to install and use the client library for Live Stream API, see Live Stream API client libraries. For more information, see the Live Stream API Node.js API reference documentation.

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

'use strict';

const {LivestreamServiceClient} = require('@google-cloud/livestream');
const {status} = require('@grpc/grpc-js');

const client = new LivestreamServiceClient();

/**
 * Creates an input endpoint for streaming video.
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id').
 * @param {string} locationId - The Google Cloud region (for example, 'us-central1').
 * @param {string} inputId - The unique identifier for the input resource (for example, 'example-input').
 */
async function createInput(projectId, locationId, inputId) {
  const input = {
    type: 'RTMP_PUSH',
  };
  const parent = `projects/${projectId}/locations/${locationId}`;

  try {
    let operation;
    try {
      [operation] = await client.createInput({
        parent,
        inputId,
        input,
      });
    } catch (err) {
      if (err.code !== status.RESOURCE_EXHAUSTED) {
        throw err;
      }
      // When quota for inputs per region is reached, remove an existing input to free quota
      const [inputs] = await client.listInputs({parent});
      for (const existingInput of inputs) {
        try {
          const [deleteOp] = await client.deleteInput({name: existingInput.name});
          await deleteOp.promise();
          break;
        } catch (deleteErr) {
          if (deleteErr.code === status.FAILED_PRECONDITION) {
            continue;
          }
          throw deleteErr;
        }
      }
      [operation] = await client.createInput({
        parent,
        inputId,
        input,
      });
    }

    const [response] = await operation.promise();
    console.log(`Input created successfully: ${response.name}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Input already exists: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid input arguments: ${err.message}`);
    } else if (err.code === status.RESOURCE_EXHAUSTED) {
      console.error(`Resource quota exhausted: ${err.message}`);
    } else {
      console.error(`Failed to create input: ${err.message}`);
    }
  }
}

module.exports = { createInput };

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.