Transcoder API を使用して動画をコード変換する

このページでは、Transcoder API と curl、Windows PowerShell、またはクライアント ライブラリのデフォルト設定を使用して、基本的な動画コード変換ジョブを作成する方法について説明します。

次のいずれかのプログラミング言語を使用して、Google Cloud Console でこのクイックスタートを直接実行することもできます。

始める前に

  1. Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. Google Cloud CLI をインストールします。
  3. gcloud CLI を初期化するには:

    gcloud init
  4. Google Cloud プロジェクトを作成または選択します

    • Google Cloud プロジェクトを作成します。

      gcloud projects create PROJECT_ID

      PROJECT_ID は、作成する Google Cloud プロジェクトの名前に置き換えます。

    • 作成した Google Cloud プロジェクトを選択します。

      gcloud config set project PROJECT_ID

      PROJECT_ID は、実際の Google Cloud プロジェクト名に置き換えます。

  5. Google Cloud プロジェクトで課金が有効になっていることを確認します

  6. Transcoder API を有効にします。

    gcloud services enable transcoder.googleapis.com
  7. Google アカウントのローカル認証情報を作成します。

    gcloud auth application-default login
  8. Google アカウントにロールを付与します。次の IAM ロールごとに次のコマンドを 1 回実行します。 roles/transcoder.admin, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID は、実際のプロジェクト ID に置き換えます。
    • EMAIL_ADDRESS は実際のメールアドレスに置き換えます。
    • ROLE は、個々のロールに置き換えます。
  9. Google Cloud CLI をインストールします。
  10. gcloud CLI を初期化するには:

    gcloud init
  11. Google Cloud プロジェクトを作成または選択します

    • Google Cloud プロジェクトを作成します。

      gcloud projects create PROJECT_ID

      PROJECT_ID は、作成する Google Cloud プロジェクトの名前に置き換えます。

    • 作成した Google Cloud プロジェクトを選択します。

      gcloud config set project PROJECT_ID

      PROJECT_ID は、実際の Google Cloud プロジェクト名に置き換えます。

  12. Google Cloud プロジェクトで課金が有効になっていることを確認します

  13. Transcoder API を有効にします。

    gcloud services enable transcoder.googleapis.com
  14. Google アカウントのローカル認証情報を作成します。

    gcloud auth application-default login
  15. Google アカウントにロールを付与します。次の IAM ロールごとに次のコマンドを 1 回実行します。 roles/transcoder.admin, roles/storage.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:EMAIL_ADDRESS" --role=ROLE
    • PROJECT_ID は、実際のプロジェクト ID に置き換えます。
    • EMAIL_ADDRESS は実際のメールアドレスに置き換えます。
    • ROLE は、個々のロールに置き換えます。

Cloud Storage バケットを作成する

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] ページに移動

  2. [バケットを作成] をクリックします。
  3. [バケットの作成] ページでユーザーのバケット情報を入力します。次のステップに進むには、[続行] をクリックします。
    • [バケット名] に、一意のバケット名を入力します。バケットの名前空間は世界中の誰でも閲覧可能なため、機密情報をバケット名に含めないようにしてください。
    • [データの保存場所の選択] で、次の操作を行います。
      • [ロケーション タイプ] オプションを選択します。
      • [ロケーション] オプションを選択します。
    • [データのデフォルトのストレージ クラスを選択する] で、次を選択します。 Standard.
    • [オブジェクトへのアクセスを制御する方法を選択する] で [アクセス制御] オプションを選択します。
    • [詳細設定(省略可)] には、暗号化メソッド保持ポリシー、またはバケットラベルを指定します。
  4. [作成] をクリックします。
  5. [フォルダを作成] をクリックし、名前を入力して、エンコードされた動画出力を保存するフォルダを作成します。

Transcoder API を使用して動画をコード変換する

次のステップでは、ローカルマシン内の 5 秒以上の長さの動画が必要です(サンプル動画)。サポートされている入出力形式の一覧をご覧ください。

Cloud Storage バケットに動画をアップロードする

  1. Google Cloud コンソールで、Cloud Storage ブラウザページに移動します。
    [Cloud Storage ブラウザ] ページに移動
  2. バケットの名前をクリックしてバケットを開きます。
  3. [ファイルをアップロード] をクリックします。
  4. ローカルマシンからアップロードする動画ファイルを選択します。

動画は Cloud Storage バケットに保存されました。

コード変換ジョブの作成

デフォルトでは、Transcoder API は H.264 エンコードと MP4、HLS、MPEG-DASH のパッケージングを使用して動画をコード変換します。各入力動画に対して、高解像度(1280x720 ピクセル)と標準解像度(640x360 ピクセル)で出力します。

ジョブを作成するには、projects.locations.jobs.create メソッドを使用します。 次のコードサンプルは、プリセットを使用して基本的なコード変換ジョブを作成する方法を示しています。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: IAM 設定に載っている Google Cloud プロジェクト ID。
  • LOCATION: ジョブを実行するロケーション。サポートされているリージョンのいずれかを使用します。
    3~7 つの店舗を表示
    • us-central1
    • us-west1
    • us-west2
    • us-east1
    • us-east4
    • southamerica-east1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • europe-west2
    • europe-west4
  • STORAGE_BUCKET_NAME: 作成した Cloud Storage バケットの名前。
  • STORAGE_INPUT_VIDEO: コード変換する Cloud Storage バケット内の動画の名前(my-vid.mp4 など)。このフィールドでは、バケットで作成したフォルダ(input/my-vid.mp4 など)を考慮する必要があります。
  • STORAGE_OUTPUT_FOLDER: エンコードされた動画出力を保存する Cloud Storage フォルダ名。

リクエストを送信するには、次のいずれかのオプションを展開します。

この REST の例は、オプションのクエリ パラメータ fields を使用して、作成されたリソース名のみをレスポンスに表示するためのものです。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID"
}

gcloud

  1. gcloud コマンドを次のように置き換えます。
    • STORAGE_BUCKET_NAME: 作成した Cloud Storage バケットの名前。
    • STORAGE_INPUT_VIDEO: コード変換する Cloud Storage バケット内の動画の名前(my-vid.mp4 など)。このフィールドでは、バケットで作成したフォルダ(input/my-vid.mp4 など)を考慮する必要があります。
    • LOCATION: ジョブを実行するロケーション。サポートされているリージョンのいずれかを使用します。
      3~7 つの店舗を表示
      • us-central1
      • us-west1
      • us-west2
      • us-east1
      • us-east4
      • southamerica-east1
      • asia-east1
      • asia-south1
      • asia-southeast1
      • europe-west1
      • europe-west2
      • europe-west4
    • STORAGE_OUTPUT_FOLDER: エンコードされた動画出力を保存する Cloud Storage フォルダ名。
  2. 次のコマンドを実行します。
    gcloud transcoder jobs create \
      --input-uri="gs://STORAGE_BUCKET_NAME/STORAGE_INPUT_VIDEO" \
      --location=LOCATION \
      --output-uri="gs://STORAGE_BUCKET_NAME/STORAGE_OUTPUT_FOLDER/"
    
    次のようなレスポンスが表示されます。
    {
      "config": {
       ...
      },
      "createTime": CREATE_TIME,
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID",
      "state": "PENDING",
      "ttlAfterCompletionDays": 30
    }
    

C#

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある C# の設定手順を行ってください。 詳細については、Transcoder API C# の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

public class CreateJobFromPresetSample
{
    public Job CreateJobFromPreset(
        string projectId, string location, string inputUri, string outputUri, string preset)
    {
        // Create the client.
        TranscoderServiceClient client = TranscoderServiceClient.Create();

        // Build the parent location name.
        LocationName parent = new LocationName(projectId, location);

        // Build the job.
        Job newJob = new Job
        {
            InputUri = inputUri,
            OutputUri = outputUri,
            TemplateId = preset
        };

        // Call the API.
        Job job = client.CreateJob(parent, newJob);

        // Return the result.
        return job;
    }
}

Go

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Go の設定手順を行ってください。 詳細については、Transcoder API Go の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

import (
	"context"
	"fmt"
	"io"

	transcoder "cloud.google.com/go/video/transcoder/apiv1"
	"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
)

// createJobFromPreset creates a job based on a given preset template. See
// https://cloud.google.com/transcoder/docs/how-to/jobs#create_jobs_presets
// for more information.
func createJobFromPreset(w io.Writer, projectID string, location string, inputURI string, outputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://my-bucket/my-video-file"
	// outputURI := "gs://my-bucket/my-output-folder/"
	preset := "preset/web-hd"
	ctx := context.Background()
	client, err := transcoder.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &transcoderpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Job: &transcoderpb.Job{
			InputUri:  inputURI,
			OutputUri: outputURI,
			JobConfig: &transcoderpb.Job_TemplateId{
				TemplateId: preset,
			},
		},
	}
	// Creates the job, Jobs take a variable amount of time to run.
	// You can query for the job state.
	response, err := client.CreateJob(ctx, req)
	if err != nil {
		return fmt.Errorf("createJobFromPreset: %w", err)
	}

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

Java

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Java の設定手順を行ってください。 詳細については、Transcoder API Java の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import com.google.cloud.video.transcoder.v1.CreateJobRequest;
import com.google.cloud.video.transcoder.v1.Job;
import com.google.cloud.video.transcoder.v1.LocationName;
import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
import java.io.IOException;

public class CreateJobFromPreset {

  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 inputUri = "gs://my-bucket/my-video-file";
    String outputUri = "gs://my-bucket/my-output-folder/";
    // See https://cloud.google.com/transcoder/docs/concepts/overview#job_template
    // for information on this preset.
    String preset = "preset/web-hd";

    createJobFromPreset(projectId, location, inputUri, outputUri, preset);
  }

  // Creates a job from a preset.
  public static void createJobFromPreset(
      String projectId, String location, String inputUri, String outputUri, String preset)
      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.
    try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              .setJob(
                  Job.newBuilder()
                      .setInputUri(inputUri)
                      .setOutputUri(outputUri)
                      .setTemplateId(preset)
                      .build())
              .setParent(LocationName.of(projectId, location).toString())
              .build();

      // Send the job creation request and process the response.
      Job job = transcoderServiceClient.createJob(createJobRequest);
      System.out.println("Job: " + job.getName());
    }
  }
}

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Node.js の設定手順を行ってください。 詳細については、Transcoder API Node.js の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// inputUri = 'gs://my-bucket/my-video-file';
// outputUri = 'gs://my-bucket/my-output-folder/';
// preset = 'preset/web-hd';

// Imports the Transcoder library
const {TranscoderServiceClient} =
  require('@google-cloud/video-transcoder').v1;

// Instantiates a client
const transcoderServiceClient = new TranscoderServiceClient();

async function createJobFromPreset() {
  // Construct request
  const request = {
    parent: transcoderServiceClient.locationPath(projectId, location),
    job: {
      inputUri: inputUri,
      outputUri: outputUri,
      templateId: preset,
    },
  };

  // Run request
  const [response] = await transcoderServiceClient.createJob(request);
  console.log(`Job: ${response.name}`);
}

createJobFromPreset();

PHP

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある PHP の設定手順を行ってください。 詳細については、Transcoder API PHP の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
use Google\Cloud\Video\Transcoder\V1\CreateJobRequest;
use Google\Cloud\Video\Transcoder\V1\Job;

/**
 * Creates a job based on a job preset.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 * @param string $location The location of the job.
 * @param string $inputUri Uri of the video in the Cloud Storage bucket.
 * @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
 * @param string $preset The preset template (for example, "preset/web-hd").
 */
function create_job_from_preset($projectId, $location, $inputUri, $outputUri, $preset)
{
    // Instantiate a client.
    $transcoderServiceClient = new TranscoderServiceClient();

    $formattedParent = $transcoderServiceClient->locationName($projectId, $location);
    $job = new Job();
    $job->setInputUri($inputUri);
    $job->setOutputUri($outputUri);
    $job->setTemplateId($preset);
    $request = (new CreateJobRequest())
        ->setParent($formattedParent)
        ->setJob($job);

    $response = $transcoderServiceClient->createJob($request);

    // Print job name.
    printf('Job: %s' . PHP_EOL, $response->getName());
}

Python

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Python の設定手順を行ってください。 詳細については、Transcoder API Python の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import argparse

from google.cloud.video import transcoder_v1
from google.cloud.video.transcoder_v1.services.transcoder_service import (
    TranscoderServiceClient,
)

def create_job_from_preset(
    project_id: str,
    location: str,
    input_uri: str,
    output_uri: str,
    preset: str,
) -> transcoder_v1.types.resources.Job:
    """Creates a job based on a job preset.

    Args:
        project_id: The GCP project ID.
        location: The location to start the job in.
        input_uri: Uri of the video in the Cloud Storage bucket.
        output_uri: Uri of the video output folder in the Cloud Storage bucket.
        preset: The preset template (for example, 'preset/web-hd').

    Returns:
        The job resource.
    """

    client = TranscoderServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    job = transcoder_v1.types.Job()
    job.input_uri = input_uri
    job.output_uri = output_uri
    job.template_id = preset

    response = client.create_job(parent=parent, job=job)
    print(f"Job: {response.name}")
    return response

Ruby

このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Ruby の設定手順を行ってください。 詳細については、Transcoder API Ruby の API のリファレンス ドキュメントをご覧ください。

Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# project_id  = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# location    = "YOUR-JOB-LOCATION"  # (e.g. "us-central1")
# input_uri   = "YOUR-GCS-INPUT-VIDEO"  # (e.g. "gs://my-bucket/my-video-file")
# output_uri  = "YOUR-GCS-OUTPUT-FOLDER/"  # (e.g. "gs://my-bucket/my-output-folder/")
# preset      = "YOUR-JOB-PRESET"  # (e.g. "preset/web-hd")

# Require the Transcoder client library.
require "google/cloud/video/transcoder"

# Create a Transcoder client.
client = Google::Cloud::Video::Transcoder.transcoder_service

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

# Set the job fields.
new_job = {
  input_uri: input_uri,
  output_uri: output_uri,
  template_id: preset
}

job = client.create_job parent: parent, job: new_job

# Print the job name.
puts "Job: #{job.name}"

返された JOB_ID をコピーします。ジョブのステータスを取得するには、この情報が必要です。

コード変換ジョブのステータスを確認する

ジョブのステータスを確認するには、projects.locations.jobs.get メソッドを使用します。 次のコードサンプルは、ジョブの詳細を取得してから、ジョブの状態を表示するためのものです。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • JOB_ID: 作成したジョブの ID。
  • PROJECT_ID: Google Cloud プロジェクト ID
  • LOCATION: ジョブのロケーション。サポートされているリージョンのいずれかを使用します。
    3~7 つの店舗を表示
    • us-central1
    • us-west1
    • us-west2
    • us-east1
    • us-east4
    • southamerica-east1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • europe-west2
    • europe-west4
  • リクエストを送信するには、次のいずれかのオプションを展開します。

    次のような JSON レスポンスが返されます。

    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID",
      "config": {
        "inputs": [
          {
            "key": "input0",
            "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_INPUT_VIDEO"
          }
        ],
        "editList": [
          {
            "key": "atom0",
            "inputs": [
              "input0"
            ],
            "startTimeOffset": "0s"
          }
        ],
        "elementaryStreams": [
          {
            "videoStream": {
              "h264": {
                "widthPixels": 640,
                "heightPixels": 360,
                "frameRate": 30,
                "bitrateBps": 550000,
                "pixelFormat": "yuv420p",
                "rateControlMode": "vbr",
                "crfLevel": 21,
                "gopDuration": "3s",
                "vbvSizeBits": 550000,
                "vbvFullnessBits": 495000,
                "entropyCoder": "cabac",
                "bFrameCount": 3,
                "aqStrength": 1,
                "profile": "high",
                "preset": "veryfast"
              }
            },
            "key": "video-stream0"
          },
          {
            "videoStream": {
              "h264": {
                "widthPixels": 1280,
                "heightPixels": 720,
                "frameRate": 30,
                "bitrateBps": 2500000,
                "pixelFormat": "yuv420p",
                "rateControlMode": "vbr",
                "crfLevel": 21,
                "gopDuration": "3s",
                "vbvSizeBits": 2500000,
                "vbvFullnessBits": 2250000,
                "entropyCoder": "cabac",
                "bFrameCount": 3,
                "aqStrength": 1,
                "profile": "high",
                "preset": "veryfast"
              }
            },
            "key": "video-stream1"
          },
          {
            "audioStream": {
              "codec": "aac",
              "bitrateBps": 64000,
              "channelCount": 2,
              "channelLayout": [
                "fl",
                "fr"
              ],
              "sampleRateHertz": 48000
            },
            "key": "audio-stream0"
          }
        ],
        "muxStreams": [
          {
            "key": "sd",
            "fileName": "sd.mp4",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream0",
              "audio-stream0"
            ]
          },
          {
            "key": "hd",
            "fileName": "hd.mp4",
            "container": "mp4",
            "elementaryStreams": [
              "video-stream1",
              "audio-stream0"
            ]
          },
          {
            "key": "media-sd",
            "fileName": "media-sd.ts",
            "container": "ts",
            "elementaryStreams": [
              "video-stream0",
              "audio-stream0"
            ]
          },
          {
            "key": "media-hd",
            "fileName": "media-hd.ts",
            "container": "ts",
            "elementaryStreams": [
              "video-stream1",
              "audio-stream0"
            ]
          },
          {
            "key": "video-only-sd",
            "fileName": "video-only-sd.m4s",
            "container": "fmp4",
            "elementaryStreams": [
              "video-stream0"
            ]
          },
          {
            "key": "video-only-hd",
            "fileName": "video-only-hd.m4s",
            "container": "fmp4",
            "elementaryStreams": [
              "video-stream1"
            ]
          },
          {
            "key": "audio-only",
            "fileName": "audio-only.m4s",
            "container": "fmp4",
            "elementaryStreams": [
              "audio-stream0"
            ]
          }
        ],
        "manifests": [
          {
            "fileName": "manifest.m3u8",
            "type": "HLS",
            "muxStreams": [
              "media-sd",
              "media-hd"
            ]
          },
          {
            "fileName": "manifest.mpd",
            "type": "DASH",
            "muxStreams": [
              "video-only-sd",
              "video-only-hd",
              "audio-only"
            ]
          }
        ],
        "output": {
          "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_OUTPUT_FOLDER/"
        }
      },
      "state": "PENDING",
      "createTime": CREATE_TIME,
      "ttlAfterCompletionDays": 30
    }
    

    gcloud

    1. gcloud コマンドを次のように置き換えます。
      • JOB_ID: 作成したジョブの ID。
      • LOCATION: ジョブのロケーション。サポートされているリージョンのいずれかを使用します。
        3~7 つの店舗を表示
        • us-central1
        • us-west1
        • us-west2
        • us-east1
        • us-east4
        • southamerica-east1
        • asia-east1
        • asia-south1
        • asia-southeast1
        • europe-west1
        • europe-west2
        • europe-west4
    2. 以下のコマンドを実行します。
      gcloud transcoder jobs describe JOB_ID --location=LOCATION
      次のようなレスポンスが表示されます。
      {
        "name": "projects/PROJECT_NUMBER/locations/LOCATION/jobs/JOB_ID",
        "config": {
          "inputs": [
            {
              "key": "input0",
              "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_INPUT_VIDEO"
            }
          ],
          "editList": [
            {
              "key": "atom0",
              "inputs": [
                "input0"
              ],
              "startTimeOffset": "0s"
            }
          ],
          "elementaryStreams": [
            {
              "videoStream": {
                "h264": {
                  "widthPixels": 640,
                  "heightPixels": 360,
                  "frameRate": 30,
                  "bitrateBps": 550000,
                  "pixelFormat": "yuv420p",
                  "rateControlMode": "vbr",
                  "crfLevel": 21,
                  "gopDuration": "3s",
                  "vbvSizeBits": 550000,
                  "vbvFullnessBits": 495000,
                  "entropyCoder": "cabac",
                  "bFrameCount": 3,
                  "aqStrength": 1,
                  "profile": "high",
                  "preset": "veryfast"
                }
              },
              "key": "video-stream0"
            },
            {
              "videoStream": {
                "h264": {
                  "widthPixels": 1280,
                  "heightPixels": 720,
                  "frameRate": 30,
                  "bitrateBps": 2500000,
                  "pixelFormat": "yuv420p",
                  "rateControlMode": "vbr",
                  "crfLevel": 21,
                  "gopDuration": "3s",
                  "vbvSizeBits": 2500000,
                  "vbvFullnessBits": 2250000,
                  "entropyCoder": "cabac",
                  "bFrameCount": 3,
                  "aqStrength": 1,
                  "profile": "high",
                  "preset": "veryfast"
                }
              },
              "key": "video-stream1"
            },
            {
              "audioStream": {
                "codec": "aac",
                "bitrateBps": 64000,
                "channelCount": 2,
                "channelLayout": [
                  "fl",
                  "fr"
                ],
                "sampleRateHertz": 48000
              },
              "key": "audio-stream0"
            }
          ],
          "muxStreams": [
            {
              "key": "sd",
              "fileName": "sd.mp4",
              "container": "mp4",
              "elementaryStreams": [
                "video-stream0",
                "audio-stream0"
              ]
            },
            {
              "key": "hd",
              "fileName": "hd.mp4",
              "container": "mp4",
              "elementaryStreams": [
                "video-stream1",
                "audio-stream0"
              ]
            },
            {
              "key": "media-sd",
              "fileName": "media-sd.ts",
              "container": "ts",
              "elementaryStreams": [
                "video-stream0",
                "audio-stream0"
              ]
            },
            {
              "key": "media-hd",
              "fileName": "media-hd.ts",
              "container": "ts",
              "elementaryStreams": [
                "video-stream1",
                "audio-stream0"
              ]
            },
            {
              "key": "video-only-sd",
              "fileName": "video-only-sd.m4s",
              "container": "fmp4",
              "elementaryStreams": [
                "video-stream0"
              ]
            },
            {
              "key": "video-only-hd",
              "fileName": "video-only-hd.m4s",
              "container": "fmp4",
              "elementaryStreams": [
                "video-stream1"
              ]
            },
            {
              "key": "audio-only",
              "fileName": "audio-only.m4s",
              "container": "fmp4",
              "elementaryStreams": [
                "audio-stream0"
              ]
            }
          ],
          "manifests": [
            {
              "fileName": "manifest.m3u8",
              "type": "HLS",
              "muxStreams": [
                "media-sd",
                "media-hd"
              ]
            },
            {
              "fileName": "manifest.mpd",
              "type": "DASH",
              "muxStreams": [
                "video-only-sd",
                "video-only-hd",
                "audio-only"
              ]
            }
          ],
          "output": {
            "uri": "gs://STORAGE_BUCKET_NAME/STORAGE_OUTPUT_FOLDER/"
          }
        },
        "state": "PENDING",
        "createTime": CREATE_TIME,
        "ttlAfterCompletionDays": 30
      }
      

    C#

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある C# の設定手順を行ってください。 詳細については、Transcoder API C# の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    using Google.Cloud.Video.Transcoder.V1;
    
    public class GetJobStateSample
    {
        public Job.Types.ProcessingState GetJobState(string projectId, string location, string jobId)
        {
            // Create the client.
            TranscoderServiceClient client = TranscoderServiceClient.Create();
    
            // Build the job name.
            JobName jobName = JobName.FromProjectLocationJob(projectId, location, jobId);
    
            // Call the API.
            Job job = client.GetJob(jobName);
    
            // Return the result.
            return job.State;
        }
    }

    Go

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Go の設定手順を行ってください。 詳細については、Transcoder API Go の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	transcoder "cloud.google.com/go/video/transcoder/apiv1"
    	"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
    )
    
    // getJobState gets the state for a previously-created job. See
    // https://cloud.google.com/transcoder/docs/how-to/jobs#check_job_status for
    // more information.
    func getJobState(w io.Writer, projectID string, location string, jobID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// jobID := "my-job-id"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.GetJobRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s", projectID, location, jobID),
    	}
    
    	response, err := client.GetJob(ctx, req)
    	if err != nil {
    		return fmt.Errorf("GetJob: %w", err)
    	}
    	fmt.Fprintf(w, "Job state: %v\n----\nJob failure reason:%v\n", response.State, response.Error)
    	return nil
    }
    

    Java

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Java の設定手順を行ってください。 詳細については、Transcoder API Java の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    import com.google.cloud.video.transcoder.v1.GetJobRequest;
    import com.google.cloud.video.transcoder.v1.Job;
    import com.google.cloud.video.transcoder.v1.JobName;
    import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class GetJobState {
    
      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 jobId = "my-job-id";
    
        getJobState(projectId, location, jobId);
      }
    
      // Gets the state of a job.
      public static void getJobState(String projectId, String location, String jobId)
          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.
        try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {
          JobName jobName =
              JobName.newBuilder().setProject(projectId).setLocation(location).setJob(jobId).build();
          GetJobRequest getJobRequest = GetJobRequest.newBuilder().setName(jobName.toString()).build();
    
          // Send the get job request and process the response.
          Job job = transcoderServiceClient.getJob(getJobRequest);
          System.out.println("Job state: " + job.getState());
        }
      }
    }

    Node.js

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Node.js の設定手順を行ってください。 詳細については、Transcoder API Node.js の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // jobId = 'my-job-id';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} =
      require('@google-cloud/video-transcoder').v1;
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function getJob() {
      // Construct request
      const request = {
        name: transcoderServiceClient.jobPath(projectId, location, jobId),
      };
      const [response] = await transcoderServiceClient.getJob(request);
      console.log(`Job state: ${response.state}`);
    }
    
    getJob();

    PHP

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある PHP の設定手順を行ってください。 詳細については、Transcoder API PHP の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
    use Google\Cloud\Video\Transcoder\V1\GetJobRequest;
    use Google\Cloud\Video\Transcoder\V1\Job;
    
    /**
     * Gets a Transcoder job's state.
     *
     * @param string $projectId The ID of your Google Cloud Platform project.
     * @param string $location The location of the job.
     * @param string $jobId The job ID.
     */
    function get_job_state($projectId, $location, $jobId)
    {
        // Instantiate a client.
        $transcoderServiceClient = new TranscoderServiceClient();
    
        $formattedName = $transcoderServiceClient->jobName($projectId, $location, $jobId);
        $request = (new GetJobRequest())
            ->setName($formattedName);
        $job = $transcoderServiceClient->getJob($request);
    
        // Print job state.
        printf('Job state: %s' . PHP_EOL, Job\ProcessingState::name($job->getState()));
    }

    Python

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Python の設定手順を行ってください。 詳細については、Transcoder API Python の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    import argparse
    
    from google.cloud.video import transcoder_v1
    from google.cloud.video.transcoder_v1.services.transcoder_service import (
        TranscoderServiceClient,
    )
    
    def get_job_state(
        project_id: str,
        location: str,
        job_id: str,
    ) -> transcoder_v1.types.resources.Job:
        """Gets a job's state.
    
        Args:
            project_id: The GCP project ID.
            location: The location this job is in.
            job_id: The job ID.
    
        Returns:
            The job resource.
        """
    
        client = TranscoderServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/jobs/{job_id}"
        response = client.get_job(name=name)
    
        print(f"Job state: {str(response.state.name)}")
        return response
    
    

    Ruby

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Ruby の設定手順を行ってください。 詳細については、Transcoder API Ruby の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    # project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
    # location   = "YOUR-JOB-LOCATION"  # (e.g. "us-central1")
    # job_id     = "YOUR-JOB-ID"  # (e.g. "c82c295b-3f5a-47df-8562-938a89d40fd0")
    
    # Require the Transcoder client library.
    require "google/cloud/video/transcoder"
    
    # Create a Transcoder client.
    client = Google::Cloud::Video::Transcoder.transcoder_service
    
    # Build the resource name of the job.
    name = client.job_path project: project_id, location: location, job: job_id
    
    # Get the job.
    job = client.get_job name: name
    
    # Print the job state.
    puts "Job state: #{job.state}"

    stateSUCCEEDED の場合、ジョブが完了し、動画出力は、エンコード ファイルの Cloud Storage バケットのリストに入っています。

    動画の再生

    Shaka Player で生成されたメディア ファイルを再生するには、次の手順に従います。

    1. 作成した Cloud Storage バケットを一般公開します
    2. Cloud Storage バケットでクロスオリジン リソース シェアリング(CORS)を有効にするには、次のようにします。
      1. 次の内容を含む JSON ファイルを作成します。
        [
          {
            "origin": ["https://shaka-player-demo.appspot.com/"],
            "responseHeader": ["Content-Type", "Range"],
            "method": ["GET", "HEAD"],
            "maxAgeSeconds": 3600
          }
        ]
      2. JSON_FILE_NAME を前の手順で作成した JSON ファイルの名前に置き換えてから、次のコマンドを実行します。
        gsutil cors set JSON_FILE_NAME.json gs://STORAGE_BUCKET_NAME
    3. Cloud Storage バケットのコード変換ジョブによって生成された MP4 またはマニフェスト ファイルのいずれかを選択します。ファイルの [公開アクセス] 列で [URL をコピー] をクリックします。
    4. オンライン ライブ ストリーム プレーヤーの Shaka Player に移動します。
    5. 上部のナビゲーション バーにある [CUSTOM CONTENT](カスタム コンテンツ)をクリックします。
    6. [+] ボタンをクリックします。
    7. ファイルの公開 URL を [Manifest URL] ボックスに貼り付けます。

      Shaka Player でファイルの URL を入力します。

    8. [Name] ボックスに名前を入力します。

    9. [保存] をクリックします。

    10. [Play] をクリックします。

    クリーンアップ

    このページで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、次の手順を行います。

    バケットの削除

    1. Google Cloud コンソールで、Cloud Storage ブラウザページに移動します。

      [Cloud Storage ブラウザ] ページに移動

    2. 作成したバケットの横にあるチェックボックスをオンにします。

    3. [削除] をクリックします。

    4. 表示されるポップアップ ウィンドウで、[削除] をクリックしてバケットとその内容を完全に削除します。

    ジョブを削除する

    REST

    リクエストのデータを使用する前に、次のように置き換えます。

  • JOB_ID: 作成したジョブの ID。
  • PROJECT_ID: Google Cloud プロジェクト ID
  • LOCATION: ジョブのロケーション。サポートされているリージョンのいずれかを使用します。
    3~7 つの店舗を表示
    • us-central1
    • us-west1
    • us-west2
    • us-east1
    • us-east4
    • southamerica-east1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • europe-west2
    • europe-west4
  • リクエストを送信するには、次のいずれかのオプションを展開します。

    次のような JSON レスポンスが返されます。

    {}
    

    gcloud

    1. gcloud コマンドを次のように置き換えます。
      • JOB_ID: 作成したジョブの ID。
      • LOCATION: ジョブのロケーション。サポートされているリージョンのいずれかを使用します。
        3~7 つの店舗を表示
        • us-central1
        • us-west1
        • us-west2
        • us-east1
        • us-east4
        • southamerica-east1
        • asia-east1
        • asia-south1
        • asia-southeast1
        • europe-west1
        • europe-west2
        • europe-west4
    2. 以下のコマンドを実行します。
      gcloud transcoder jobs delete JOB_ID --location=LOCATION
      次のようなレスポンスが表示されます。
      Deleted job [projects/PROJECT_ID/locations/LOCATION/jobs/JOB_ID].
      

    C#

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある C# の設定手順を行ってください。 詳細については、Transcoder API C# の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    using Google.Cloud.Video.Transcoder.V1;
    
    public class DeleteJobSample
    {
        public void DeleteJob(string projectId, string location, string jobId)
        {
            // Create the client.
            TranscoderServiceClient client = TranscoderServiceClient.Create();
    
            // Build the job name.
            JobName jobName = JobName.FromProjectLocationJob(projectId, location, jobId);
    
            // Call the API.
            client.DeleteJob(jobName);
        }
    }

    Go

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Go の設定手順を行ってください。 詳細については、Transcoder API Go の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	transcoder "cloud.google.com/go/video/transcoder/apiv1"
    	"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
    )
    
    // deleteJob deletes a previously-created job. See
    // https://cloud.google.com/transcoder/docs/how-to/jobs#delete_jobs for more
    // information.
    func deleteJob(w io.Writer, projectID string, location string, jobID string) error {
    	// projectID := "my-project-id"
    	// location := "us-central1"
    	// jobID := "my-job-id"
    	ctx := context.Background()
    	client, err := transcoder.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewClient: %w", err)
    	}
    	defer client.Close()
    
    	req := &transcoderpb.DeleteJobRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/jobs/%s", projectID, location, jobID),
    	}
    
    	err = client.DeleteJob(ctx, req)
    	if err != nil {
    		return fmt.Errorf("DeleteJob: %w", err)
    	}
    
    	fmt.Fprintf(w, "Deleted job")
    	return nil
    }
    

    Java

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Java の設定手順を行ってください。 詳細については、Transcoder API Java の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    import com.google.cloud.video.transcoder.v1.DeleteJobRequest;
    import com.google.cloud.video.transcoder.v1.JobName;
    import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
    import java.io.IOException;
    
    public class DeleteJob {
    
      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 jobId = "my-job-id";
    
        deleteJob(projectId, location, jobId);
      }
    
      // Deletes a job.
      public static void deleteJob(String projectId, String location, String jobId) 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.
        try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {
          JobName jobName =
              JobName.newBuilder().setProject(projectId).setLocation(location).setJob(jobId).build();
          DeleteJobRequest deleteJobRequest = DeleteJobRequest.newBuilder().setName(jobName.toString())
              .build();
    
          // Send the delete job request and process the response.
          transcoderServiceClient.deleteJob(deleteJobRequest);
          System.out.println("Deleted job");
        }
      }
    }

    Node.js

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Node.js の設定手順を行ってください。 詳細については、Transcoder API Node.js の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // projectId = 'my-project-id';
    // location = 'us-central1';
    // jobId = 'my-job-id';
    
    // Imports the Transcoder library
    const {TranscoderServiceClient} =
      require('@google-cloud/video-transcoder').v1;
    
    // Instantiates a client
    const transcoderServiceClient = new TranscoderServiceClient();
    
    async function deleteJob() {
      // Construct request
      const request = {
        name: transcoderServiceClient.jobPath(projectId, location, jobId),
      };
      await transcoderServiceClient.deleteJob(request);
      console.log('Deleted job');
    }
    
    deleteJob();

    PHP

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある PHP の設定手順を行ってください。 詳細については、Transcoder API PHP の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
    use Google\Cloud\Video\Transcoder\V1\DeleteJobRequest;
    
    /**
     * Deletes a Transcoder job.
     *
     * @param string $projectId The ID of your Google Cloud Platform project.
     * @param string $location The location of the job.
     * @param string $jobId The job ID.
     */
    function delete_job($projectId, $location, $jobId)
    {
        // Instantiate a client.
        $transcoderServiceClient = new TranscoderServiceClient();
    
        $formattedName = $transcoderServiceClient->jobName($projectId, $location, $jobId);
        $request = (new DeleteJobRequest())
            ->setName($formattedName);
        $transcoderServiceClient->deleteJob($request);
    
        print('Deleted job' . PHP_EOL);
    }

    Python

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Python の設定手順を行ってください。 詳細については、Transcoder API Python の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    
    import argparse
    
    from google.cloud.video.transcoder_v1.services.transcoder_service import (
        TranscoderServiceClient,
    )
    
    def delete_job(
        project_id: str,
        location: str,
        job_id: str,
    ) -> None:
        """Gets a job.
    
        Args:
            project_id: The GCP project ID.
            location: The location this job is in.
            job_id: The job ID."""
    
        client = TranscoderServiceClient()
    
        name = f"projects/{project_id}/locations/{location}/jobs/{job_id}"
        response = client.delete_job(name=name)
        print("Deleted job")
        return response
    
    

    Ruby

    このサンプルを試す前に、クライアント ライブラリを使用した Transcoder API クイックスタートにある Ruby の設定手順を行ってください。 詳細については、Transcoder API Ruby の API のリファレンス ドキュメントをご覧ください。

    Transcoder API への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

    # project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
    # location   = "YOUR-JOB-LOCATION"  # (e.g. "us-central1")
    # job_id     = "YOUR-JOB-ID"  # (e.g. "c82c295b-3f5a-47df-8562-938a89d40fd0")
    
    # Require the Transcoder client library.
    require "google/cloud/video/transcoder"
    
    # Create a Transcoder client.
    client = Google::Cloud::Video::Transcoder.transcoder_service
    
    # Build the resource name of the job.
    name = client.job_path project: project_id, location: location, job: job_id
    
    # Delete the job.
    client.delete_job name: name
    
    # Print a success message.
    puts "Deleted job"

    認証情報を取り消す

    1. 作成した認証情報を取り消して、ローカル認証情報ファイルを削除します。

      gcloud auth application-default revoke
    2. (省略可)gcloud CLI から認証情報を取り消します。

      gcloud auth revoke

    次のステップ