Transcoder APIをCloud Run Functionsで動かしてみた

Google Cloud
この記事は約9分で読めます。

こんにちは!大嶋です!
みなさんは動画を変換するときに何を使っているでしょうか。

今回はGoogle Cloudが提供しているTranscoder APIをCloud Run Functionsを使って動画を変換する方法を紹介したいと思います。

本記事でわかること

  • Transcoder APIの概要
  • Cloud Run Functionsを使った時の実装方法

Transcoder APIの概要

Google Cloud Transcoder APIは、動画の変換(トランスコード)を行うための強力なツールです。このAPIを使用することで、さまざまな解像度やビットレートに動画を変換し、異なるデバイスやネットワーク条件に最適化することができます。

Transcoder APIのメリット

  1. サーバーレスアーキテクチャ: Transcoder APIは完全にマネージドなサービスであり、インフラストラクチャの管理が不要です。これにより、Cloud Functionsなどのサーバーレス環境で簡単に利用できます。
  2. 高いスケーラビリティ: Google Cloudのインフラストラクチャを利用することで、大量の動画を高速に処理することができます。
  3. コスト効率: 使用した分だけ課金されるため、コストを最小限に抑えることができます。
  4. 多様なフォーマット対応: 多くの動画フォーマットに対応しており、さまざまなデバイスやプラットフォーム向けに最適化された出力を生成できます。
  5. 簡単な統合: 他のGoogle Cloudサービス(Cloud Storage、Cloud Functionsなど)とシームレスに統合できるため、ワークフローの自動化が容易です。
  6. 高品質な出力: Googleの高度なエンコーディング技術を利用することで、高品質な動画出力が可能です。

Cloud Run Functionsを使った時の実装方法

前提条件

  • Google Cloud Platform (GCP) アカウント
  • gcloud CLIがインストールされていること
  • Cloud FunctionsとTranscoder APIが有効化されていること

実装

今回は以下のディレクトリで、動画のHLS変換と解像度の変換をpythonで行います。

my-transcoder-function/
├── main.py
└── requirements.txt

main.py

import os
import time
from google.protobuf import duration_pb2 
from google.cloud.video.transcoder_v1 import TranscoderServiceClient
from google.cloud.video.transcoder_v1.types import Job, JobConfig, ElementaryStream, MuxStream, VideoStream, SegmentSettings, Manifest

def transcode_video(event, context):
    try:
        print("Starting transcode_video function")
        client = TranscoderServiceClient()

        project_id = os.getenv('GCP_PROJECT') 
        location = 'asia-northeast1'  # 必要に応じてリージョンを変更
        input_uri = f"gs://{event['bucket']}/{event['name']}"
        output_uri = f"gs://{os.getenv('OUTPUT_BUCKET')}/{event['name']}/"  
        input_filename = os.path.splitext(event['name'])[0]  

        job = Job(
            input_uri=input_uri,
            output_uri=output_uri,
            config=JobConfig(
                elementary_streams=[
                    ElementaryStream(
                        key='video_1440p',
                        video_stream=VideoStream(
                            h264=VideoStream.H264CodecSettings(
                                height_pixels=1440,
                                width_pixels=2560,
                                bitrate_bps=8000000,
                                frame_rate=30
                            )
                        )
                    ),
                    ElementaryStream(
                        key='video_2160p',
                        video_stream=VideoStream(
                            h264=VideoStream.H264CodecSettings(
                                height_pixels=2160,
                                width_pixels=3840,
                                bitrate_bps=12000000,
                                frame_rate=30
                            )
                        )
                    )
                ],
                mux_streams=[
                    MuxStream(
                        key='qhd',
                        container='ts',
                        elementary_streams=['video_1440p'],
                        file_name=f"{input_filename}_1440p",
                        segment_settings=SegmentSettings(segment_duration=duration_pb2.Duration(seconds=6)) # デフォルト6秒
                    ),
                    MuxStream(
                        key='uhd',
                        container='ts',
                        elementary_streams=['video_2160p'],
                        file_name=f"{input_filename}_2160p",
                        segment_settings=SegmentSettings(segment_duration=duration_pb2.Duration(seconds=6)) # デフォルト6秒
                    )
                ],
                manifests=[
                    Manifest(
                        file_name=f"{input_filename}.m3u8", 
                        type_='HLS',
                        mux_streams=['qhd', 'uhd']
                    )
                ]
            )
        )

        parent = f"projects/{project_id}/locations/{location}"
        response = client.create_job(parent=parent, job=job)
        print(f"Created job: {response.name}")

    except Exception as e:
        print(f"Error: {e}")

requirements.txt

google-cloud-video-transcoder==1.13.0
protobuf==5.28.3

今回は、自分の指定したバケット内でのファイル作成をトリガーにして実装します。

gcloud functions deploy transcode_video_hls \
    --gen2 \
    --runtime python39 \
    --trigger-event google.storage.object.finalize \
    --trigger-resource "インプット元バケット" \
    --entry-point transcode_video \
    --region asia-northeast1 \
    --set-env-vars GCP_PROJECT="プロジェクトID",OUTPUT_BUCKET="アウトプット先バケット"

上記まで実装できたら実際にバケットに動画を格納して、動作確認をしてください。

まとめ

以上で、Google Cloud Functionsを使用してTranscoder APIを実装する方法についての解説は終了です。これで、高解像度の動画変換を自動化するための強力なツールを手に入れることができました。Transcoder APIのメリットを活用して、効率的に動画変換を行いましょう。ぜひ試してみてください!

おわり。

Google および Google Cloud Platform™ service は Google LLC の商標であり、この記事は Google によって承認されたり、Google と提携したりするものではありません。

コメント

タイトルとURLをコピーしました