Questa pagina spiega come generare un foglio sprite contenente frame di un video transcodificato. Questi fotogrammi di dimensioni ridotte, noti anche come miniature, sono utili per organizzare e visualizzare l'anteprima dei contenuti. Per generare lo spritesheet, utilizza l'array
spriteSheets
nel modello JobConfig
.
Per generare il foglio sprite sono disponibili due opzioni:
Genera un numero prestabilito di immagini in miniatura
La seguente configurazione genera uno spritesheet 10 x 10 di immagini di grandi dimensioni e un foglio sprite 10 x 10 di immagini piccole, ciascuno con 100 miniature. Tieni presente che i fogli sprite richiedono almeno un VideoStream
nella configurazione del job.
Puoi aggiungere questa configurazione a un modello di job o includerla in una configurazione di job ad hoc :
REST
Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:
PROJECT_ID
: l'ID del tuo progetto Google Cloud elencato nelle impostazioni IAM .
LOCATION
: la località in cui verrà eseguito il job. Utilizza una delle regioni supportate .
Mostra località
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
: il nome del bucket Cloud Storage che hai creato.
STORAGE_INPUT_VIDEO
: il nome del video nel bucket Cloud Storage che stai transcodificando, ad esempio my-vid.mp4
.
Questo campo deve tenere conto di eventuali cartelle create nel bucket (ad esempio, input/my-vid.mp4
).
STORAGE_OUTPUT_FOLDER
: il nome della cartella Cloud Storage in cui vuoi salvare gli output video codificati.
Nota: non è necessario creare l'oggetto cartella di output prima di creare il job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il nome della cartella specificato ai nomi degli oggetti salvati in Cloud Storage.
Per inviare la richiesta, espandi una di queste opzioni:
curl (Linux, macOS o Cloud Shell)
Nota:
il comando seguente presuppone che tu abbia eseguito l'accesso
all'interfaccia a riga di comando gcloud
con il tuo account utente eseguendo
gcloud init
o
gcloud auth login
oppure utilizzando
Cloud Shell ,
che ti consente di accedere automaticamente all'interfaccia a riga di comando gcloud
.
Puoi controllare l'account attualmente attivo eseguendo
gcloud auth list
.
Salva il corpo della richiesta in un file denominato request.json
.
Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory attuale:
cat > request.json << 'EOF'
{
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_INPUT_VIDEO "
}
],
"elementaryStreams": [
{
"key": "video-stream0",
"videoStream": {
"h264": {
"heightPixels": 360,
"widthPixels": 640,
"bitrateBps": 550000,
"frameRate": 60
}
}
},
{
"key": "audio-stream0",
"audioStream": {
"codec": "aac",
"bitrateBps": 64000
}
}
],
"muxStreams": [
{
"key": "sd",
"container": "mp4",
"elementaryStreams": [
"video-stream0",
"audio-stream0"
]
}
],
"output": {
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_OUTPUT_FOLDER /"
},
"spriteSheets": [
{
"filePrefix": "small-sprite-sheet",
"spriteHeightPixels": 32,
"spriteWidthPixels": 64,
"columnCount": 10,
"rowCount": 10,
"totalCount": 100
},
{
"filePrefix": "large-sprite-sheet",
"spriteHeightPixels": 72,
"spriteWidthPixels": 128,
"columnCount": 10,
"rowCount": 10,
"totalCount": 100
}
]
}
}
EOF
Quindi esegui questo comando per inviare la richiesta REST:
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json; charset=utf-8" \ -d @request.json \ "https://transcoder.googleapis.com/v1/projects/PROJECT_ID /locations/LOCATION /jobs"
PowerShell (Windows)
Nota:
il comando seguente presuppone che tu abbia eseguito l'accesso
all'interfaccia a riga di comando gcloud
con il tuo account utente eseguendo
gcloud init
o
gcloud auth login
oppure utilizzando
Cloud Shell ,
che ti consente di accedere automaticamente all'interfaccia a riga di comando gcloud
.
Puoi controllare l'account attualmente attivo eseguendo
gcloud auth list
.
Salva il corpo della richiesta in un file denominato request.json
.
Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory attuale:
@'
{
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_INPUT_VIDEO "
}
],
"elementaryStreams": [
{
"key": "video-stream0",
"videoStream": {
"h264": {
"heightPixels": 360,
"widthPixels": 640,
"bitrateBps": 550000,
"frameRate": 60
}
}
},
{
"key": "audio-stream0",
"audioStream": {
"codec": "aac",
"bitrateBps": 64000
}
}
],
"muxStreams": [
{
"key": "sd",
"container": "mp4",
"elementaryStreams": [
"video-stream0",
"audio-stream0"
]
}
],
"output": {
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_OUTPUT_FOLDER /"
},
"spriteSheets": [
{
"filePrefix": "small-sprite-sheet",
"spriteHeightPixels": 32,
"spriteWidthPixels": 64,
"columnCount": 10,
"rowCount": 10,
"totalCount": 100
},
{
"filePrefix": "large-sprite-sheet",
"spriteHeightPixels": 72,
"spriteWidthPixels": 128,
"columnCount": 10,
"rowCount": 10,
"totalCount": 100
}
]
}
}
'@ | Out-File -FilePath request.json -Encoding utf8
Quindi esegui questo comando per inviare la richiesta REST:
$cred = gcloud auth print-access-token $headers = @{ "Authorization" = "Bearer $cred" } Invoke-WebRequest ` -Method POST ` -Headers $headers ` -ContentType: "application/json; charset=utf-8" ` -InFile request.json ` -Uri "https://transcoder.googleapis.com/v1/projects/PROJECT_ID /locations/LOCATION /jobs" | Select-Object -Expand Content
Dovresti ricevere una risposta JSON simile alla seguente:
{
"name": "projects/PROJECT_NUMBER /locations/LOCATION /jobs/JOB_ID ",
"config": {
...
},
"state": "PENDING",
"createTime": CREATE_TIME ,
"ttlAfterCompletionDays": 30
}
gcloud
Crea un file request.json
che definisca i campi del job. Sostituisci
il comando
gcloud
come segue:
STORAGE_BUCKET_NAME : il nome del bucket Cloud Storage che hai creato.
STORAGE_INPUT_VIDEO : il nome del video nel bucket Cloud Storage che stai transcodificando, ad esempio my-vid.mp4
. Questo campo dovrebbe tenere conto di eventuali cartelle create nel bucket (ad esempio, input/my-vid.mp4
).
LOCATION : la località in cui verrà eseguito il job. Utilizza una località dall'elenco seguente.
Mostra località
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 : il nome della cartella Cloud Storage in cui vuoi salvare gli output video codificati.
Nota: non è necessario creare l'oggetto cartella di output prima di creare il job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il nome della cartella specificato ai nomi degli oggetti salvati in Cloud Storage.
{
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_INPUT_VIDEO "
}
],
"elementaryStreams": [
{
"key": "video-stream0",
"videoStream": {
"h264": {
"heightPixels": 360,
"widthPixels": 640,
"bitrateBps": 550000,
"frameRate": 60
}
}
},
{
"key": "audio-stream0",
"audioStream": {
"codec": "aac",
"bitrateBps": 64000
}
}
],
"muxStreams": [
{
"key": "sd",
"container": "mp4",
"elementaryStreams": [
"video-stream0",
"audio-stream0"
]
}
],
"output": {
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_OUTPUT_FOLDER /"
},
"spriteSheets": [
{
"filePrefix": "small-sprite-sheet",
"spriteHeightPixels": 32,
"spriteWidthPixels": 64,
"columnCount": 10,
"rowCount": 10,
"totalCount": 100
},
{
"filePrefix": "large-sprite-sheet",
"spriteHeightPixels": 72,
"spriteWidthPixels": 128,
"columnCount": 10,
"rowCount": 10,
"totalCount": 100
}
]
}
}
Esegui questo comando:
gcloud transcoder jobs create --location=LOCATION --file="request.json"
Dovresti visualizzare una risposta simile alla seguente:
{
"name": "projects/PROJECT_NUMBER /locations/LOCATION /jobs/JOB_ID ",
"config": {
...
},
"state": "PENDING",
"createTime": CREATE_TIME ,
"ttlAfterCompletionDays": 30
}
Go
Prima di provare questo esempio, segui le istruzioni di configurazione di Go disponibili nella
guida rapida dell'API Transcoder sull'utilizzo
delle librerie client .
Per maggiori informazioni, consulta la
documentazione di riferimento dell'API Go
per l'API Transcoder .
Per eseguire l'autenticazione all'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per maggiori informazioni, consulta
Configurare l'autenticazione per un ambiente di sviluppo locale .
import (
"context"
"fmt"
"io"
transcoder "cloud.google.com/go/video/transcoder/apiv1"
"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
)
// createJobWithSetNumberImagesSpritesheet creates a job from an ad-hoc configuration and generates
// two spritesheets from the input video. Each spritesheet contains a set number of images.
func createJobWithSetNumberImagesSpritesheet(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/"
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_Config{
Config: &transcoderpb.JobConfig{
ElementaryStreams: []*transcoderpb.ElementaryStream{
{
Key: "video_stream0",
ElementaryStream: &transcoderpb.ElementaryStream_VideoStream{
VideoStream: &transcoderpb.VideoStream{
CodecSettings: &transcoderpb.VideoStream_H264{
H264: &transcoderpb.VideoStream_H264CodecSettings{
BitrateBps: 550000,
FrameRate: 60,
HeightPixels: 360,
WidthPixels: 640,
},
},
},
},
},
{
Key: "audio_stream0",
ElementaryStream: &transcoderpb.ElementaryStream_AudioStream{
AudioStream: &transcoderpb.AudioStream{
Codec: "aac",
BitrateBps: 64000,
},
},
},
},
MuxStreams: []*transcoderpb.MuxStream{
{
Key: "sd",
Container: "mp4",
ElementaryStreams: []string{"video_stream0", "audio_stream0"},
},
},
SpriteSheets: []*transcoderpb.SpriteSheet{
{
FilePrefix: "small-sprite-sheet",
SpriteWidthPixels: 64,
SpriteHeightPixels: 32,
ColumnCount: 10,
RowCount: 10,
ExtractionStrategy: &transcoderpb.SpriteSheet_TotalCount{
TotalCount: 100,
},
},
{
FilePrefix: "large-sprite-sheet",
SpriteWidthPixels: 128,
SpriteHeightPixels: 72,
ColumnCount: 10,
RowCount: 10,
ExtractionStrategy: &transcoderpb.SpriteSheet_TotalCount{
TotalCount: 100,
},
},
},
},
},
},
}
// Creates the job. Jobs take a variable amount of time to run. You can query for the job state.
// See https://cloud.google.com/transcoder/docs/how-to/jobs#check_job_status for more info.
response, err := client.CreateJob(ctx, req)
if err != nil {
return fmt.Errorf("createJobWithSetNumberImagesSpritesheet: %w", err)
}
fmt.Fprintf(w, "Job: %v", response.GetName())
return nil
}
Node.js
Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js disponibili nella
guida rapida dell'API Transcoder sull'utilizzo
delle librerie client .
Per maggiori informazioni, consulta la
documentazione di riferimento dell'API Node.js
per l'API Transcoder .
Per eseguire l'autenticazione all'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per maggiori informazioni, consulta
Configurare l'autenticazione per un ambiente di sviluppo locale .
/**
* 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/';
// Imports the Transcoder library
const {TranscoderServiceClient} =
require('@google-cloud/video-transcoder').v1;
// Instantiates a client
const transcoderServiceClient = new TranscoderServiceClient();
async function createJobWithSetNumberImagesSpritesheet() {
// Construct request
const request = {
parent: transcoderServiceClient.locationPath(projectId, location),
job: {
inputUri: inputUri,
outputUri: outputUri,
config: {
elementaryStreams: [
{
key: 'video-stream0',
videoStream: {
h264: {
heightPixels: 360,
widthPixels: 640,
bitrateBps: 550000,
frameRate: 60,
},
},
},
{
key: 'audio-stream0',
audioStream: {
codec: 'aac',
bitrateBps: 64000,
},
},
],
muxStreams: [
{
key: 'sd',
container: 'mp4',
elementaryStreams: ['video-stream0', 'audio-stream0'],
},
],
spriteSheets: [
{
filePrefix: 'small-sprite-sheet',
spriteHeightPixels: 32,
spriteWidthPixels: 64,
columnCount: 10,
rowCount: 10,
totalCount: 100,
},
{
filePrefix: 'large-sprite-sheet',
spriteHeightPixels: 72,
spriteWidthPixels: 128,
columnCount: 10,
rowCount: 10,
totalCount: 100,
},
],
},
},
};
// Run request
const [response] = await transcoderServiceClient.createJob(request);
console.log(`Job: ${response.name}`);
}
createJobWithSetNumberImagesSpritesheet();
Python
Prima di provare questo esempio, segui le istruzioni di configurazione di Python disponibili nella
guida rapida dell'API Transcoder sull'utilizzo
delle librerie client .
Per maggiori informazioni, consulta la
documentazione di riferimento dell'API Python
per l'API Transcoder .
Per eseguire l'autenticazione all'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per maggiori informazioni, consulta
Configurare l'autenticazione per un ambiente di sviluppo locale .
import argparse
from google.cloud.video import transcoder_v1
from google.cloud.video.transcoder_v1.services.transcoder_service import (
TranscoderServiceClient,
)
def create_job_with_set_number_images_spritesheet(
project_id: str,
location: str,
input_uri: str,
output_uri: str,
) -> transcoder_v1.types.resources.Job:
"""Creates a job based on an ad-hoc job configuration that generates two spritesheets.
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.
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.config = transcoder_v1.types.JobConfig(
# Create an ad-hoc job. For more information, see https://cloud.google.com/transcoder/docs/how-to/jobs#create_jobs_ad_hoc.
# See all options for the job config at https://cloud.google.com/transcoder/docs/reference/rest/v1/JobConfig.
elementary_streams=[
# This section defines the output video stream.
transcoder_v1.types.ElementaryStream(
key="video-stream0",
video_stream=transcoder_v1.types.VideoStream(
h264=transcoder_v1.types.VideoStream.H264CodecSettings(
height_pixels=360,
width_pixels=640,
bitrate_bps=550000,
frame_rate=60,
),
),
),
# This section defines the output audio stream.
transcoder_v1.types.ElementaryStream(
key="audio-stream0",
audio_stream=transcoder_v1.types.AudioStream(
codec="aac", bitrate_bps=64000
),
),
],
# This section multiplexes the output audio and video together into a container.
mux_streams=[
transcoder_v1.types.MuxStream(
key="sd",
container="mp4",
elementary_streams=["video-stream0", "audio-stream0"],
),
],
# Generate two sprite sheets from the input video into the GCS bucket. For more information, see
# https://cloud.google.com/transcoder/docs/how-to/generate-spritesheet#generate_set_number_of_images.
sprite_sheets=[
# Generate a 10x10 sprite sheet with 64x32px images.
transcoder_v1.types.SpriteSheet(
file_prefix="small-sprite-sheet",
sprite_width_pixels=64,
sprite_height_pixels=32,
column_count=10,
row_count=10,
total_count=100,
),
# Generate a 10x10 sprite sheet with 128x72px images.
transcoder_v1.types.SpriteSheet(
file_prefix="large-sprite-sheet",
sprite_width_pixels=128,
sprite_height_pixels=72,
column_count=10,
row_count=10,
total_count=100,
),
],
)
response = client.create_job(parent=parent, job=job)
print(f"Job: {response.name}")
return response
Nota: per mantenere le proporzioni di origine, imposta il campo spriteWidthPixels
o il campo spriteHeightPixels
, ma non entrambi (l'API calcolerà automaticamente il campo mancante).
Utilizza questa configurazione nel video di esempio per generare i seguenti fogli sprite:
Figura 1. Foglio sprite con immagini piccolo (100 miniature)
Figura 2. Foglio sprite con immagini grande (100 miniature)
Generare periodicamente un'immagine in miniatura.
La configurazione seguente genera uno spritesheet di immagini piccole e uno spritesheet di immagini di grandi dimensioni. Ogni foglio sprite contiene miniature generate ogni 7 secondi dal video di input. Tieni presente che i fogli sprite richiedono almeno un VideoStream
nella configurazione del job.
Puoi aggiungere questa configurazione a un modello di job o includerla in una configurazione di job ad hoc :
REST
Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:
PROJECT_ID
: l'ID del tuo progetto Google Cloud elencato nelle impostazioni IAM .
LOCATION
: la località in cui verrà eseguito il job. Utilizza una delle regioni supportate .
Mostra località
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
: il nome del bucket Cloud Storage che hai creato.
STORAGE_INPUT_VIDEO
: il nome del video nel bucket Cloud Storage che stai transcodificando, ad esempio my-vid.mp4
.
Questo campo deve tenere conto di eventuali cartelle create nel bucket (ad esempio, input/my-vid.mp4
).
STORAGE_OUTPUT_FOLDER
: il nome della cartella Cloud Storage in cui vuoi salvare gli output video codificati.
Nota: non è necessario creare l'oggetto cartella di output prima di creare il job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il nome della cartella specificato ai nomi degli oggetti salvati in Cloud Storage.
Per inviare la richiesta, espandi una di queste opzioni:
curl (Linux, macOS o Cloud Shell)
Nota:
il comando seguente presuppone che tu abbia eseguito l'accesso
all'interfaccia a riga di comando gcloud
con il tuo account utente eseguendo
gcloud init
o
gcloud auth login
oppure utilizzando
Cloud Shell ,
che ti consente di accedere automaticamente all'interfaccia a riga di comando gcloud
.
Puoi controllare l'account attualmente attivo eseguendo
gcloud auth list
.
Salva il corpo della richiesta in un file denominato request.json
.
Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory attuale:
cat > request.json << 'EOF'
{
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_INPUT_VIDEO "
}
],
"elementaryStreams": [
{
"key": "video-stream0",
"videoStream": {
"h264": {
"heightPixels": 360,
"widthPixels": 640,
"bitrateBps": 550000,
"frameRate": 60
}
}
},
{
"key": "audio-stream0",
"audioStream": {
"codec": "aac",
"bitrateBps": 64000
}
}
],
"muxStreams": [
{
"key": "sd",
"container": "mp4",
"elementaryStreams": [
"video-stream0",
"audio-stream0"
]
}
],
"output": {
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_OUTPUT_FOLDER /"
},
"spriteSheets": [
{
"filePrefix": "small-sprite-sheet",
"spriteHeightPixels": 32,
"spriteWidthPixels": 64,
"interval": "7s"
},
{
"filePrefix": "large-sprite-sheet",
"spriteHeightPixels": 72,
"spriteWidthPixels": 128,
"interval": "7s"
}
]
}
}
EOF
Quindi esegui questo comando per inviare la richiesta REST:
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json; charset=utf-8" \ -d @request.json \ "https://transcoder.googleapis.com/v1/projects/PROJECT_ID /locations/LOCATION /jobs"
PowerShell (Windows)
Nota:
il comando seguente presuppone che tu abbia eseguito l'accesso
all'interfaccia a riga di comando gcloud
con il tuo account utente eseguendo
gcloud init
o
gcloud auth login
oppure utilizzando
Cloud Shell ,
che ti consente di accedere automaticamente all'interfaccia a riga di comando gcloud
.
Puoi controllare l'account attualmente attivo eseguendo
gcloud auth list
.
Salva il corpo della richiesta in un file denominato request.json
.
Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory attuale:
@'
{
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_INPUT_VIDEO "
}
],
"elementaryStreams": [
{
"key": "video-stream0",
"videoStream": {
"h264": {
"heightPixels": 360,
"widthPixels": 640,
"bitrateBps": 550000,
"frameRate": 60
}
}
},
{
"key": "audio-stream0",
"audioStream": {
"codec": "aac",
"bitrateBps": 64000
}
}
],
"muxStreams": [
{
"key": "sd",
"container": "mp4",
"elementaryStreams": [
"video-stream0",
"audio-stream0"
]
}
],
"output": {
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_OUTPUT_FOLDER /"
},
"spriteSheets": [
{
"filePrefix": "small-sprite-sheet",
"spriteHeightPixels": 32,
"spriteWidthPixels": 64,
"interval": "7s"
},
{
"filePrefix": "large-sprite-sheet",
"spriteHeightPixels": 72,
"spriteWidthPixels": 128,
"interval": "7s"
}
]
}
}
'@ | Out-File -FilePath request.json -Encoding utf8
Quindi esegui questo comando per inviare la richiesta REST:
$cred = gcloud auth print-access-token $headers = @{ "Authorization" = "Bearer $cred" } Invoke-WebRequest ` -Method POST ` -Headers $headers ` -ContentType: "application/json; charset=utf-8" ` -InFile request.json ` -Uri "https://transcoder.googleapis.com/v1/projects/PROJECT_ID /locations/LOCATION /jobs" | Select-Object -Expand Content
Dovresti ricevere una risposta JSON simile alla seguente:
{
"name": "projects/PROJECT_NUMBER /locations/LOCATION /jobs/JOB_ID ",
"config": {
...
},
"state": "PENDING",
"createTime": CREATE_TIME ,
"ttlAfterCompletionDays": 30
}
gcloud
Crea un file request.json
che definisca i campi del job. Sostituisci
il comando
gcloud
come segue:
STORAGE_BUCKET_NAME : il nome del bucket Cloud Storage che hai creato.
STORAGE_INPUT_VIDEO : il nome del video nel bucket Cloud Storage che stai transcodificando, ad esempio my-vid.mp4
. Questo campo dovrebbe tenere conto di eventuali cartelle create nel bucket (ad esempio, input/my-vid.mp4
).
LOCATION : la località in cui verrà eseguito il job. Utilizza una località dall'elenco seguente.
Mostra località
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 : il nome della cartella Cloud Storage in cui vuoi salvare gli output video codificati.
Nota: non è necessario creare l'oggetto cartella di output prima di creare il job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il nome della cartella specificato ai nomi degli oggetti salvati in Cloud Storage.
{
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_INPUT_VIDEO "
}
],
"elementaryStreams": [
{
"key": "video-stream0",
"videoStream": {
"h264": {
"heightPixels": 360,
"widthPixels": 640,
"bitrateBps": 550000,
"frameRate": 60
}
}
},
{
"key": "audio-stream0",
"audioStream": {
"codec": "aac",
"bitrateBps": 64000
}
}
],
"muxStreams": [
{
"key": "sd",
"container": "mp4",
"elementaryStreams": [
"video-stream0",
"audio-stream0"
]
}
],
"output": {
"uri": "gs://STORAGE_BUCKET_NAME /STORAGE_OUTPUT_FOLDER /"
},
"spriteSheets": [
{
"filePrefix": "small-sprite-sheet",
"spriteHeightPixels": 32,
"spriteWidthPixels": 64,
"interval": "7s"
},
{
"filePrefix": "large-sprite-sheet",
"spriteHeightPixels": 72,
"spriteWidthPixels": 128,
"interval": "7s"
}
]
}
}
Esegui questo comando:
gcloud transcoder jobs create --location=LOCATION --file="request.json"
Dovresti visualizzare una risposta simile alla seguente:
{
"name": "projects/PROJECT_NUMBER /locations/LOCATION /jobs/JOB_ID ",
"config": {
...
},
"state": "PENDING",
"createTime": CREATE_TIME ,
"ttlAfterCompletionDays": 30
}
Go
Prima di provare questo esempio, segui le istruzioni di configurazione di Go disponibili nella
guida rapida dell'API Transcoder sull'utilizzo
delle librerie client .
Per maggiori informazioni, consulta la
documentazione di riferimento dell'API Go
per l'API Transcoder .
Per eseguire l'autenticazione all'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per maggiori informazioni, consulta
Configurare l'autenticazione per un ambiente di sviluppo locale .
import (
"context"
"fmt"
"io"
"github.com/golang/protobuf/ptypes/duration"
transcoder "cloud.google.com/go/video/transcoder/apiv1"
"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
)
// createJobWithPeriodicImagesSpritesheet creates a job from an ad-hoc configuration and generates
// two spritesheets from the input video. Each spritesheet contains images that are captured
// periodically based on a user-defined time interval.
func createJobWithPeriodicImagesSpritesheet(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/"
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_Config{
Config: &transcoderpb.JobConfig{
ElementaryStreams: []*transcoderpb.ElementaryStream{
{
Key: "video_stream0",
ElementaryStream: &transcoderpb.ElementaryStream_VideoStream{
VideoStream: &transcoderpb.VideoStream{
CodecSettings: &transcoderpb.VideoStream_H264{
H264: &transcoderpb.VideoStream_H264CodecSettings{
BitrateBps: 550000,
FrameRate: 60,
HeightPixels: 360,
WidthPixels: 640,
},
},
},
},
},
{
Key: "audio_stream0",
ElementaryStream: &transcoderpb.ElementaryStream_AudioStream{
AudioStream: &transcoderpb.AudioStream{
Codec: "aac",
BitrateBps: 64000,
},
},
},
},
MuxStreams: []*transcoderpb.MuxStream{
{
Key: "sd",
Container: "mp4",
ElementaryStreams: []string{"video_stream0", "audio_stream0"},
},
},
SpriteSheets: []*transcoderpb.SpriteSheet{
{
FilePrefix: "small-sprite-sheet",
SpriteWidthPixels: 64,
SpriteHeightPixels: 32,
ExtractionStrategy: &transcoderpb.SpriteSheet_Interval{
Interval: &duration.Duration{
Seconds: 7,
},
},
},
{
FilePrefix: "large-sprite-sheet",
SpriteWidthPixels: 128,
SpriteHeightPixels: 72,
ExtractionStrategy: &transcoderpb.SpriteSheet_Interval{
Interval: &duration.Duration{
Seconds: 7,
},
},
},
},
},
},
},
}
// Creates the job. Jobs take a variable amount of time to run. You can query for the job state.
// See https://cloud.google.com/transcoder/docs/how-to/jobs#check_job_status for more info.
response, err := client.CreateJob(ctx, req)
if err != nil {
return fmt.Errorf("createJobWithPeriodicImagesSpritesheet: %w", err)
}
fmt.Fprintf(w, "Job: %v", response.GetName())
return nil
}
Python
Prima di provare questo esempio, segui le istruzioni di configurazione di Python disponibili nella
guida rapida dell'API Transcoder sull'utilizzo
delle librerie client .
Per maggiori informazioni, consulta la
documentazione di riferimento dell'API Python
per l'API Transcoder .
Per eseguire l'autenticazione all'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per maggiori informazioni, consulta
Configurare l'autenticazione per un ambiente di sviluppo locale .
import argparse
from google.cloud.video import transcoder_v1
from google.cloud.video.transcoder_v1.services.transcoder_service import (
TranscoderServiceClient,
)
from google.protobuf import duration_pb2 as duration
def create_job_with_periodic_images_spritesheet(
project_id: str,
location: str,
input_uri: str,
output_uri: str,
) -> transcoder_v1.types.resources.Job:
"""Creates a job based on an ad-hoc job configuration that generates two spritesheets.
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.
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.config = transcoder_v1.types.JobConfig(
# Create an ad-hoc job. For more information, see https://cloud.google.com/transcoder/docs/how-to/jobs#create_jobs_ad_hoc.
# See all options for the job config at https://cloud.google.com/transcoder/docs/reference/rest/v1/JobConfig.
elementary_streams=[
# This section defines the output video stream.
transcoder_v1.types.ElementaryStream(
key="video-stream0",
video_stream=transcoder_v1.types.VideoStream(
h264=transcoder_v1.types.VideoStream.H264CodecSettings(
height_pixels=360,
width_pixels=640,
bitrate_bps=550000,
frame_rate=60,
),
),
),
# This section defines the output audio stream.
transcoder_v1.types.ElementaryStream(
key="audio-stream0",
audio_stream=transcoder_v1.types.AudioStream(
codec="aac", bitrate_bps=64000
),
),
],
# This section multiplexes the output audio and video together into a container.
mux_streams=[
transcoder_v1.types.MuxStream(
key="sd",
container="mp4",
elementary_streams=["video-stream0", "audio-stream0"],
),
],
# Generate two sprite sheets from the input video into the GCS bucket. For more information, see
# https://cloud.google.com/transcoder/docs/how-to/generate-spritesheet#generate_image_periodically.
sprite_sheets=[
# Generate a sprite sheet with 64x32px images. An image is taken every 7 seconds from the video.
transcoder_v1.types.SpriteSheet(
file_prefix="small-sprite-sheet",
sprite_width_pixels=64,
sprite_height_pixels=32,
interval=duration.Duration(
seconds=7,
),
),
# Generate a sprite sheet with 128x72px images. An image is taken every 7 seconds from the video.
transcoder_v1.types.SpriteSheet(
file_prefix="large-sprite-sheet",
sprite_width_pixels=128,
sprite_height_pixels=72,
interval=duration.Duration(
seconds=7,
),
),
],
)
response = client.create_job(parent=parent, job=job)
print(f"Job: {response.name}")
return response
Nota: per mantenere le proporzioni di origine, imposta il campo spriteWidthPixels
o il campo spriteHeightPixels
, ma non entrambi (l'API calcolerà automaticamente il campo mancante).
Utilizza questa configurazione nel video di esempio per generare i seguenti fogli sprite:
Figura 3. Foglio sprite con immagini piccolo (1 miniatura ogni 7 secondi)
Figura 4. Foglio sprite con immagini grande (1 miniatura ogni 7 secondi)
Dal video di esempio, della durata di 60 secondi, vengono generate otto miniature.