Video transcoding

更新时间:
复制 MD 格式

Use video transcoding to change video codecs, reduce resolution and bitrate, convert container formats, and adjust video parameters to suit various needs.

Feature description

Video transcoding converts a compressed and encoded video stream into another video stream. This process changes parameters, such as the video format, container format, resolution, frame rate, and bitrate, to adapt the video for playback on different devices and platforms. It also reduces the file size to optimize transmission efficiency.

image

Use cases

  • Multi-device compatibility: To ensure smooth playback on different devices, such as mobile phones, tablets, computers, and smart TVs, you can use video transcoding to convert videos into device-specific formats.

  • Streaming media playback: Streaming media services need to transcode videos into multiple formats and bitrates. This allows for dynamic adjustments based on a user's network conditions to improve the viewing experience.

  • Video compression: You can transcode a video to reduce its file size without significantly affecting its quality. This facilitates efficient storage and transmission, especially when network bandwidth is limited.

Get started

Prerequisites

  • Intelligent Media Management (IMM) is activated.

  • You have created a bucket and uploaded the files to process to the bucket.

  • You have created and bound an IMM project. You can bind the project in the OSS console or by calling an API. The IMM project must be in the same region as the bucket.

  • You have the required permissions for the operations. Alibaba Cloud accounts have all permissions by default. RAM users and roles require authorization through a RAM policy or bucket policy.

    Permissions

    • Grant the user permissions to access related resources.

      • Grant the user permissions to use OSS for data processing.

        API

        Action

        Description

        GetObject

        oss:GetObject

        Downloads an object.

        oss:GetObjectVersion

        This permission is required to download a specific object version by using the versionId parameter.

        kms:Decrypt

        This permission is required if the object metadata contains X-Oss-Server-Side-Encryption: KMS.

        None

        oss:ProcessImm

        Allows you to use IMM to process data through OSS.

        PostProcessTask

        oss:PostProcessTask

        Allows you to use data processing features through POST requests, such as asynchronous processing (x-oss-async-process).

      • Grant the user permissions to use the media transcoding feature of IMM.

        API

        Action

        Description

        CreateMediaConvertTask

        imm:CreateMediaConvertTask

        Allows you to use IMM for media transcoding.

    • Grant the role used by the IMM service (by default, AliyunIMMDefaultRole with the resource ARN acs:ram:*:<account-id>:role/aliyunimmdefaultrole) permissions to access related resources for data processing.

      API

      Action

      Description

      None

      ram:PassRole

      Allows a user to pass a role to another service, enabling cross-service resource access.

      GetObject

      oss:GetObject

      Downloads an object.

      oss:GetObjectVersion

      This permission is required to download a specific object version by using the versionId parameter.

      kms:Decrypt

      This permission is required if the object metadata contains X-Oss-Server-Side-Encryption: KMS.

      HeadObject

      oss:GetObject

      Obtains the metadata of an object.

      PutObject

      oss:PutObject

      Uploads an object.

      oss:PutObject

      Required to upload objects to a versioning-enabled bucket.

      kms:GenerateDataKey

      These permissions are required to upload an object with KMS server-side encryption.

      kms:Decrypt

Use the SDK

Video transcoding uses the asynchronous processing feature of the OSS SDKs for Java, Python, and Go.

Java

OSS SDK for Java 3.17.4 or later is required.

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AsyncProcessObjectRequest;
import com.aliyun.oss.model.AsyncProcessObjectResult;
import com.aliyuncs.exceptions.ClientException;

import java.util.Base64;

public class Demo {
    public static void main(String[] args) throws ClientException {
        // Set the endpoint. For example, if your bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region ID, for example, cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the name of the output video file.
        String targetKey = "dest.avi";
        // Specify the name of the source video file.
        String sourceKey = "src.mp4";

        // Create an OSSClient instance.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Build the video processing style string that includes video transcoding parameters.
            String style = String.format("video/convert,f_avi,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1");
            // Build the asynchronous processing instruction.
            String bucketEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(bucketName.getBytes());
            String targetEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(targetKey.getBytes());
            String process = String.format("%s|sys/saveas,b_%s,o_%s", style, bucketEncoded, targetEncoded);
            // Create an AsyncProcessObjectRequest object.
            AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
            // Start the asynchronous processing task.
            AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
            System.out.println("EventId: " + response.getEventId());
            System.out.println("RequestId: " + response.getRequestId());
            System.out.println("TaskId: " + response.getTaskId());

        } finally {
            // Shut down the OSSClient instance to release resources.
            ossClient.shutdown();
        }
    }
}

Python

OSS SDK for Python 2.18.4 or later is required.

# -*- coding: utf-8 -*-
import base64
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider


def main():
    # Set the endpoint. For example, if your bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

    # Specify the bucket name.
    bucket_name = 'examplebucket'
    # Specify the region ID, for example, cn-hangzhou.
    region = 'cn-hangzhou'
    # Create a Bucket object.
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

    # Specify the name of the source video file.
    source_key = 'src.mp4'
    # Specify the name of the output video file.
    target_key = 'dest.avi'
    # Build the video processing style string that includes video transcoding parameters.
    style = 'video/convert,f_avi,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1'
    # Build the asynchronous processing instruction.
    process = "{0}|sys/saveas,b_{1},o_{2}".format(style,
                                            oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(bucket_name))).replace('=', ''),
                                            oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(target_key))).replace('=', ''))

    # Call the asynchronous media processing API.
    try:
        # Start the asynchronous processing task.
        result = bucket.async_process_object(source_key, process)
        print(f"EventId: {result.event_id}")
        print(f"RequestId: {result.request_id}")
        print(f"TaskId: {result.task_id}")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()

Go

OSS SDK for Go 3.0.2 or later is required.

package main

import (
	"encoding/base64"
	"fmt"
	"os"
	"strings"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance.
	// Set the endpoint. For example, if your bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, specify the actual endpoint.
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the bucket name, for example, examplebucket.
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	// Specify the name of the output video file.
	targetObject := "dest.avi"
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the name of the source video file.
	sourceObject := "src.mp4"

	// Build the video processing style string that includes video transcoding parameters.
	style := "video/convert,f_avi,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1"
	// Build the asynchronous processing instruction.
	process := fmt.Sprintf("%s|sys/saveas,b_%v,o_%v", style, strings.TrimRight(base64.URLEncoding.EncodeToString([]byte(bucketName)), "="), strings.TrimRight(base64.URLEncoding.EncodeToString([]byte(targetObject)), "="))
	fmt.Printf("%#v\n", process)
	// Start the asynchronous processing task.
	rs, err := bucket.AsyncProcessObject(sourceObject, process)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Printf("EventId:%s\n", rs.EventId)
	fmt.Printf("RequestId:%s\n", rs.RequestId)
	fmt.Printf("TaskId:%s\n", rs.TaskId)
}

Parameters

Operation: video/convert

This table describes the parameters for this operation.

Parameter

Type

Required

Description

ss

int

No

The start time for transcoding, in milliseconds. Valid values:

  • 0 (default): Starts transcoding from the beginning of the video.

  • A value greater than 0: Starts transcoding from the millisecond specified by ss.

t

int

No

The duration for transcoding, in milliseconds. Valid values:

  • 0 (default): Transcodes until the end of the video.

  • A value greater than 0: Transcodes for t milliseconds.

f

string

Yes

The media container type. Valid values:

  • Audio/video containers: mp4, mkv, mov, asf, avi, mxf, ts, flv, and webm

  • Audio-only containers: mp3, aac, flac, oga, ac3, opus, and amr

vn

int

No

Specifies whether to disable the video stream. Valid values:

  • 0 (default): Keeps the video stream.

  • 1: Disables the video stream. The output file will not contain a video stream.

vcodec

string

No

The video codec. Valid values:

  • copy (default): Copies the source video stream without re-encoding.

  • h264: Encodes the video using the H.264 codec.

  • h265: Encodes the video using the H.265 codec.

  • vp9: Encodes the video using the VP9 codec.

fps

float

No

The video frame rate. The value must be in the range of 0 to 240.

fpsopt

int

No

Specifies how to apply the video frame rate. Valid values:

  • 0: Always uses the target frame rate.

  • 1: Uses the source video frame rate if it is lower than the target frame rate specified by fps.

  • 2: The transcoding fails if the source video frame rate is lower than the target frame rate specified by fps.

pixfmt

string

No

The pixel format. Defaults to the source video's pixel format. Valid values:

  • yuv420p

  • yuva420p

  • yuv420p10le

  • yuv422p

  • yuv422p10le

  • yuv444p

  • yuv444p10le

s

string

No

The target resolution.

  • Format: w x h (width x height).

  • Both the width and height must be a multiple of 2 and in the range of 64 to 4,096. For example, 4096x4096 and 64x64.

sopt

int

No

Specifies how to apply the target resolution. Valid values:

  • 0: Always uses the target resolution.

  • 1: Uses the source resolution if it is smaller than the target resolution specified by s.

  • 2: The transcoding fails if the source resolution is smaller than the target resolution specified by s.

scaletype

string

No

The resizing mode. Valid values:

  • crop: Resizes the video proportionally to fill the specified dimensions, then crops the excess from the center.

  • stretch (default): Stretches the video to the exact specified dimensions. This may alter the aspect ratio.

  • fill: Resizes the video proportionally to fit within the specified dimensions, then fills the remaining space with black bars.

  • fit: Resizes the video proportionally to fit within the specified dimensions without adding bars.

arotate

int

No

Enables or disables adaptive resolution orientation. Valid values:

  • 0 (default): Disabled.

  • 1: Enabled.

g

int

No

The keyframe interval. The value must be in the range of 1 to 100,000.

vb

int

No

The target video bitrate, in bits per second (bps). The value must be in the range of 10,000 to 100,000,000.

vbopt

int

No

Specifies how to apply the target video bitrate. Valid values:

  • 0: Always uses the target video bitrate.

  • 1: Uses the source video bitrate if it is lower than the target bitrate specified by vb.

  • 2: The transcoding fails if the source video bitrate is lower than the target bitrate specified by vb.

videoslim

int

No

The Narrowband HD mode. Valid values:

0 (default): Disables Narrowband HD.

1: Enables Narrowband HD for transcoding.

Note

For optimal results, use the recommended bitrate or CRF parameters with Narrowband HD.

Important

Narrowband HD supports only the h.264/h.265 video codecs, the yuv420p pixel format, and an 8-bit depth.

Narrowband HD.

crf

float

No

The constant rate factor (CRF). The value must be in the range of 0 to 51.

maxrate

int

No

The maximum bitrate, in bits per second (bps). The value must be in the range of 10,000 to 100,000,000.

bufsize

int

No

The buffer size, in bits. The value must be in the range of 10,000 to 200,000,000.

an

int

No

Specifies whether to disable the audio stream. Valid values:

  • 0 (default): Keeps the audio stream.

  • 1: Disables the audio stream. The output file will not contain an audio stream.

acodec

string

No

The audio codec. Valid values:

  • copy (default): Copies the source audio stream without re-encoding.

  • mp3: Encodes the audio using the MP3 codec.

  • aac: Encodes the audio using the AAC codec.

  • flac: Encodes the audio using the FLAC codec.

  • vorbis: Encodes the audio using the Vorbis codec.

  • ac3: Encodes the audio using the AC3 codec.

  • opus: Encodes the audio using the Opus codec.

  • amr: Encodes the audio using the AMR codec.

ar

int

No

The audio sampling rate. Valid values:

  • 8000

  • 11025

  • 12000

  • 16000

  • 22050

  • 24000

  • 32000

  • 44100

  • 48000

  • 88200

  • 96000

ac

int

No

The number of audio channels. Defaults to the number of channels in the source audio. The value must be in the range of 1 to 8.

aq

int

No

Audio compression quality. Mutually exclusive with the ab parameter. Value range: 0 to 100.

ab

int

No

The audio bitrate. This parameter is mutually exclusive with the aq parameter, and the unit is bits per second (bps). Value range: 1000 to 10000000.

abopt

int

No

Specifies how to apply the target audio bitrate. Valid values:

  • 0 (default): Always uses the target audio bitrate.

  • 1: Uses the source audio bitrate if it is lower than the target bitrate specified by ab.

  • 2: The transcoding fails if the source audio bitrate is lower than the target bitrate specified by ab.

sn

int

No

Specifies whether to disable subtitles. Valid values:

  • 0 (default): Keeps the subtitles.

  • 1: Disables the subtitles. The output file will not contain subtitles.

adepth

int

No

The audio sampling bit depth. The valid values are 16 and 24.

Note

This parameter is valid only when acodec is set to flac.

segment

string

No

Settings for media segmentation. By default, the video is not segmented.

f

string

No

The media segmentation format. Valid values:

  • hls

  • dash

Parent node: segment

t

int

No

The segment duration, in milliseconds. The value must be in the range of 0 to 3,600,000.

Parent node: segment

Video transcoding also supports the sys/saveas (Save As) and notify (message notification) parameters.

API reference

For advanced customization, send REST API requests directly. You must calculate a signature for the Authorization header. Signature V4 (Recommended).

Convert AVI to MP4

Job configuration

  • Source object

    • Video format: AVI

    • Video name: example.avi

  • Processing method: video transcoding

  • Destination object

    • Video information

      • Video format: MP4

      • Video name: outobjprefix.mp4

      • Video stream format: H.265

      • Video resolution: 1920x1080

      • Video frame rate: 30 fps

      • Video bitrate: 2 Mbps

    • Audio information

      • Audio stream format: AAC

      • Audio bitrate: 100 Kbps

      • Subtitle stream: disabled

    • Output path: oss://outbucket/outobjprefix.mp4

Sample request

POST /example.avi?x-oss-async-process HTTP/1.1
Host: video-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
 
// Transcode the example.avi object. The output is an MP4 file with an H.265 video stream (1920x1080, 30 fps, 2 Mbps) and an AAC audio stream (100 Kbps). Subtitles are disabled. The output is saved to oss://outbucket/outobjprefix.mp4.
x-oss-async-process=video/convert,f_mp4,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ

Convert AVI to TS

Job configuration

  • Source object

    • Video format: AVI

    • Video name: example.avi

  • Processing method

    • Transcoding duration: Transcodes a 60,000-millisecond segment of the input file, starting at the 10,000th millisecond.

    • Segment method: Creates 30-second HLS segments.

    • Transcoding completion notification: Sends MNS messages.

  • Destination object

    • Video information

      • Video format: TS

      • Video stream format: H.264

      • Video bitrate: 1 Mbps

    • Audio information

      • Audio stream format: MP3

      • Audio bitrate: 100 Kbps

    • Output path

      • TS object: oss://outbucket/outobjprefix-%d.ts

      • M3U8 object: oss://outbucket/outobjprefix.m3u8

Sample request

POST /example.avi?x-oss-async-process HTTP/1.1
Host: video-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
 
// Transcode the example.avi object.
x-oss-async-process=video/convert,ss_10000,t_60000,f_ts,vcodec_h264,vb_1000000,acodec_mp3,ab_100000/segment,f_hls,t_30000|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ/notify,topic_QXVkaW9Db252ZXJ0

Convert AVI to MP3

Job configuration

  • Source object

    • Video name: example.avi

    • Video format: AVI

  • Processing method: Extract and transcode the audio stream.

  • Destination object

    • Audio container: MP3

    • Audio coding format: MP3

    • Audio bitrate: 100 Kbps

    • Video stream: disabled

    • Subtitle stream: disabled

    • Output path: oss://outbucket/outobjprefix.mp3. If a source video has multiple audio streams, only the first is processed by default.

Sample request

POST /example.avi?x-oss-async-process HTTP/1.1
Host: video-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
 
// Extract and transcode the audio stream from the example.avi object.
x-oss-async-process=video/convert,f_mp3,acodec_mp3,ab_100000,vn_1,sn_1|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQ

Billing

Video transcoding generates billable items for both OSS and IMM:

  • OSS: OSS Product Pricing.

    API

    Billable item

    Description

    GetObject

    GET request

    Request fees are based on the number of successful requests.

    internet outbound traffic

    When you call the GetObject operation by using a public endpoint (for example, oss-cn-hangzhou.aliyuncs.com) or a transfer acceleration endpoint (for example, oss-accelerate.aliyuncs.com), you are charged for internet outbound traffic based on the amount of data transferred.

    Infrequent Access data retrieval

    If the retrieved data is in the Infrequent Access storage class, you are charged for Infrequent Access data retrieval based on the amount of data retrieved.

    Archive-Direct Read data retrieval

    If you read an Archive object from a bucket where Archive-Direct Read is enabled, you are charged for Archive-Direct Read data retrieval based on the amount of data retrieved.

    Transfer Acceleration

    If Transfer Acceleration is enabled and you access your bucket by using a transfer acceleration endpoint, you are charged for Transfer Acceleration based on the amount of data transferred.

    PutObject

    PUT request

    Request fees are based on the number of successful requests.

    storage fee

    Storage fees are based on an object's storage class, size, and storage duration.

    HeadObject

    HEAD request

    Request fees are based on the number of successful requests.

  • IMM: IMM billable items.

    API

    Billable item

    Description

    CreateMediaConvertTask

    VideoCompress264LD

    Fees for H.264-LD transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress264SD

    Fees for H.264-SD transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress264HD

    Fees for H.264-HD transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress2642K

    Fees for H.264-2K transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress2644K

    Fees for H.264-4K transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress265LD

    Fees for H.265-LD transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress265SD

    Fees for H.265-SD transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress265HD

    Fees for H.265-HD transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress2652K

    Fees for H.265-2K transcoding. Media processing fees are calculated based on the video's duration in seconds.

    VideoCompress2654K

    Fees for H.265-4K transcoding. Media processing fees are calculated based on the video's duration in seconds.

    AudioCompress

    Fees for audio transcoding.

Limits

  • Video transcoding is limited to asynchronous processing (x-oss-async-process).

  • Anonymous access is not supported.

  • The following video formats are supported: MP4, MPEG-TS, MKV, MOV, AVI, FLV, M3U8, WebM, WMV, RM, and VOB.

FAQ

"ResourceNotFound" error during video transcoding

The ResourceNotFound, The specified resource Attachment is not found. error indicates that no bucket is bound to your IMM project. Bind a bucket to the IMM project to resolve it. OSS data processing usage guide.

Saving output to the source path

No. The input path cannot be a prefix of the output path. This prevents unexpected behavior such as trigger loops or overwriting the source object.

Setting audio bit depth

Yes. Use the pixfmt parameter in an OSS x-oss-process request.

Getting task results with a task ID

Use the GetTask operation in IMM to retrieve task results.

Searching and deleting objects by suffix

No. OSS does not support searching for objects by suffix because it uses unordered storage.

Backend not receiving messages

Verify that the topic and subscription exist. If they do not exist or were deleted, reconfigure the subscription and restart transcoding.

Using a template for automatic transcoding

Yes. Configure triggers to automatically process new and existing videos in a bucket. Tasks, batch processing, and triggers support both system-defined and custom templates. Batch processing. Triggers.

Charges for transcoded videos

Yes. Transcoded videos occupy storage space, which incurs charges.

Saving output to the source path

Do not set the output path to be the same as the source path, as this will overwrite the source object.