Questa pagina spiega come generare un foglio sprite che contiene frame da un
video transcodificato. Questi fotogrammi di dimensioni ridotte, noti anche come miniature, sono
è utile per organizzare
e visualizzare l'anteprima dei contenuti. Per generare il foglio sprite, usa
il
spriteSheets
nel modello JobConfig
.
Hai due opzioni per generare il foglio sprite:
Genera un numero prestabilito di immagini in miniatura
La seguente configurazione genera un foglio sprite 10x10 di grandi dimensioni
e uno spritesheet 10x10 di piccole immagini, ciascuna con 100
miniature. Tieni presente che i fogli sprite richiedono almeno un VideoStream
nel job
configurazione.
Puoi aggiungere questa configurazione
modello di lavoro o includerlo in un
configurazione ad hoc dei job :
REST
Prima di utilizzare i dati della richiesta,
effettua le seguenti sostituzioni:
PROJECT_ID
: il tuo ID progetto Google Cloud elencato in
nelle impostazioni IAM .
LOCATION
: la località in cui verrà eseguito il job. Utilizza le funzionalità di
in una delle regioni supportate .
Mostra località
us-central1
us-west1
us-west2
us-east1
us-east4
southamerica-east1
northamerica-northeast1
asia-east1
asia-northeast1
asia-northeast3
asia-south1
asia-southeast1
australia-southeast1
europe-west1
europe-west2
europe-west4
STORAGE_BUCKET_NAME
: il nome dell'istanza di Cloud Storage
che hai creato.
STORAGE_INPUT_VIDEO
: il nome del video nel tuo
Bucket Cloud Storage che stai transcodificando, ad esempio my-vid.mp4
.
Questo campo deve tenere conto di eventuali cartelle create nel
(ad esempio input/my-vid.mp4
).
STORAGE_OUTPUT_FOLDER
: il cloud storage
il nome della cartella in cui vuoi salvare gli output video codificati.
Nota: non è necessario creare l'oggetto cartella di output prima
la creazione del job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il carattere
il nome della cartella specificato come parte dei nomi degli oggetti salvati in Cloud Storage.
Per inviare la richiesta, espandi una delle seguenti opzioni:
curl (Linux, macOS o Cloud Shell)
Nota:
Il comando seguente presuppone che tu abbia eseguito l'accesso a
l'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
di Google.
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 corrente:
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 a
l'interfaccia a riga di comando gcloud
con il tuo account utente eseguendo
gcloud init
o
gcloud auth login
di Google.
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 corrente:
@'
{
"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 definisce i campi del job. Marca
le seguenti sostituzioni per
gcloud
:
STORAGE_BUCKET_NAME : il
del bucket Cloud Storage che hai creato.
STORAGE_INPUT_VIDEO : il
del video nel tuo bucket Cloud Storage
transcodifica, ad esempio my-vid.mp4
. Questo campo deve includere
prendi in considerazione le cartelle che hai creato nel bucket (ad esempio
input/my-vid.mp4
).
LOCATION : la località in cui
verrà eseguito il job. Utilizza una posizione dall'elenco seguente.
Mostra località
us-central1
us-west1
us-west2
us-east1
us-east4
southamerica-east1
northamerica-northeast1
asia-east1
asia-northeast1
asia-northeast3
asia-south1
asia-southeast1
australia-southeast1
europe-west1
europe-west2
europe-west4
STORAGE_OUTPUT_FOLDER : il
Nome della cartella di Cloud Storage in cui vuoi salvare il video codificato
come output.
Nota: non è necessario creare l'oggetto cartella di output prima
la creazione del job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il carattere
il nome della cartella specificato come parte dei 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 vedere 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 per la configurazione di Go nel
Guida rapida dell'API Transcoder mediante l'utilizzo di
librerie client .
Per ulteriori informazioni, consulta
API Go dell'API Transcoder
documentazione di riferimento .
Per eseguire l'autenticazione nell'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per ulteriori informazioni, vedi
Configura 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 per la configurazione di Node.js nel
Guida rapida dell'API Transcoder mediante l'utilizzo di
librerie client .
Per ulteriori informazioni, consulta
API Node.js dell'API Transcoder
documentazione di riferimento .
Per eseguire l'autenticazione nell'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per ulteriori informazioni, vedi
Configura 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 per la configurazione di Python nel
Guida rapida dell'API Transcoder mediante l'utilizzo di
librerie client .
Per ulteriori informazioni, consulta
API Python dell'API Transcoder
documentazione di riferimento .
Per eseguire l'autenticazione nell'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per ulteriori informazioni, vedi
Configura 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 dell'origine, imposta il campo spriteWidthPixels
oppure
il campo spriteHeightPixels
, ma non entrambi (l'API eseguirà automaticamente
calcolare il campo mancante).
Utilizza questa configurazione nel video di esempio
per generare i seguenti fogli sprite:
e
Figura 1. Foglio sprite di immagini piccolo (100 miniature)
e
Figura 2. Foglio sprite di immagini grandi (100 miniature)
Genera periodicamente un'immagine in miniatura
La seguente configurazione genera un foglio sprite di immagini di piccole dimensioni
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
nel job
configurazione.
Puoi aggiungere questa configurazione
modello di lavoro o includerlo in un
configurazione ad hoc dei job :
REST
Prima di utilizzare i dati della richiesta,
effettua le seguenti sostituzioni:
PROJECT_ID
: il tuo ID progetto Google Cloud elencato in
nelle impostazioni IAM .
LOCATION
: la località in cui verrà eseguito il job. Utilizza le funzionalità di
in una delle regioni supportate .
Mostra località
us-central1
us-west1
us-west2
us-east1
us-east4
southamerica-east1
northamerica-northeast1
asia-east1
asia-northeast1
asia-northeast3
asia-south1
asia-southeast1
australia-southeast1
europe-west1
europe-west2
europe-west4
STORAGE_BUCKET_NAME
: il nome dell'istanza di Cloud Storage
che hai creato.
STORAGE_INPUT_VIDEO
: il nome del video nel tuo
Bucket Cloud Storage che stai transcodificando, ad esempio my-vid.mp4
.
Questo campo deve tenere conto di eventuali cartelle create nel
(ad esempio input/my-vid.mp4
).
STORAGE_OUTPUT_FOLDER
: il cloud storage
il nome della cartella in cui vuoi salvare gli output video codificati.
Nota: non è necessario creare l'oggetto cartella di output prima
la creazione del job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il carattere
il nome della cartella specificato come parte dei nomi degli oggetti salvati in Cloud Storage.
Per inviare la richiesta, espandi una delle seguenti opzioni:
curl (Linux, macOS o Cloud Shell)
Nota:
Il comando seguente presuppone che tu abbia eseguito l'accesso a
l'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
di Google.
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 corrente:
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 a
l'interfaccia a riga di comando gcloud
con il tuo account utente eseguendo
gcloud init
o
gcloud auth login
di Google.
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 corrente:
@'
{
"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 definisce i campi del job. Marca
le seguenti sostituzioni per
gcloud
:
STORAGE_BUCKET_NAME : il
del bucket Cloud Storage che hai creato.
STORAGE_INPUT_VIDEO : il
del video nel tuo bucket Cloud Storage
transcodifica, ad esempio my-vid.mp4
. Questo campo deve includere
prendi in considerazione le cartelle che hai creato nel bucket (ad esempio
input/my-vid.mp4
).
LOCATION : la località in cui
verrà eseguito il job. Utilizza una posizione dall'elenco seguente.
Mostra località
us-central1
us-west1
us-west2
us-east1
us-east4
southamerica-east1
northamerica-northeast1
asia-east1
asia-northeast1
asia-northeast3
asia-south1
asia-southeast1
australia-southeast1
europe-west1
europe-west2
europe-west4
STORAGE_OUTPUT_FOLDER : il
Nome della cartella di Cloud Storage in cui vuoi salvare il video codificato
come output.
Nota: non è necessario creare l'oggetto cartella di output prima
la creazione del job. Durante l'elaborazione del job, l'API Transcoder antepone automaticamente il carattere
il nome della cartella specificato come parte dei 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 vedere 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 per la configurazione di Go nel
Guida rapida dell'API Transcoder mediante l'utilizzo di
librerie client .
Per ulteriori informazioni, consulta
API Go dell'API Transcoder
documentazione di riferimento .
Per eseguire l'autenticazione nell'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per ulteriori informazioni, vedi
Configura 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 per la configurazione di Python nel
Guida rapida dell'API Transcoder mediante l'utilizzo di
librerie client .
Per ulteriori informazioni, consulta
API Python dell'API Transcoder
documentazione di riferimento .
Per eseguire l'autenticazione nell'API Transcoder, configura Credenziali predefinite dell'applicazione.
Per ulteriori informazioni, vedi
Configura 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 dell'origine, imposta il campo spriteWidthPixels
oppure
il campo spriteHeightPixels
, ma non entrambi (l'API eseguirà automaticamente
calcolare il campo mancante).
Utilizza questa configurazione nel video di esempio
per generare i seguenti fogli sprite:
e
Figura 3. Foglio sprite di immagini piccolo (1 miniatura ogni 7 secondi)
e
Figura 4. Foglio sprite di immagini grande (1 miniatura ogni 7 secondi)
Dal video di esempio vengono generate otto miniature, della durata di 60 secondi.
lunghezza.