You can use video transcoding to change encoding formats, reduce resolution and bitrate, convert container formats, and modify video parameters to meet different business requirements. This topic describes how to configure video transcoding parameters and provides examples of video transcoding.
Scenarios
Adaption to different terminal devices and network environments
You can change the resolution and bitrate of a media file to ensure its adaptability with various terminal devices and network environments.
Efficient encoding for reduced costs
You can use efficient encoding algorithms in media processing to reduce the bitrate and stuttering in playback without compromising the video quality. This saves storage and traffic costs.
Smart production technologies for video enhancement and reproduction
You can leverage media processing technologies and advanced production technologies, such as video AI and super-resolution, to transcode low-quality videos into higher-definition versions and create new media files by adding watermarks, capturing video frames, or performing edits.
Prerequisites
Intelligent Media Management (IMM) is activated. For more information, see Activate IMM.
The corresponding Object Storage Service (OSS) bucket is bound to an IMM project. For information about how to bind an OSS bucket to an IMM project in the OSS console, see Get started. For information about how to bind a bucket to an IMM project by using the IMM API, see AttachOSSBucket.
The required permissions are granted to the Resource Access Management (RAM) user that you use to use IMM features. For more information, see Permissions.
Usage notes
Video transcoding supports only asynchronous processing (x-oss-async-process).
Video transcoding does not support anonymous access.
Video transcoding supports the following video formats: MP4, MPEG-TS, MKV, MOV, AVI, FLV, M3U8, WebM, WMV, RM, and VOB.
You are charged for using video transcoding. Fees for media processing are included in your IMM bills. For more information, see Billable items.
Process
The following figure shows the video transcoding process.
Upload a video file to a bucket.
Create a media transcoding task.
After the media transcoding task is executed, save the transcoded video file to OSS.
Parameters
Action: video/convert
The following table describes the parameters for video transcoding.
Parameter | Type | Required | Description |
ss | int | No | The start time of the video from which transcoding begins. Unit: milliseconds. Valid values:
|
t | int | No | The duration of video content to be transcoded after the specified start time. Unit: milliseconds. Valid values:
|
f | string | Yes | The type of the media container. Valid values:
|
vn | int | No | Specifies whether to disable video stream generation. Valid values:
|
vcodec | string | No | The encoding format of the output video. Valid values:
|
fps | float | No | The desired frame rate. Valid values: 0 to 240. |
fpsopt | int | No | The frame rate option. Valid values:
|
pixfmt | string | No | The desired pixel format. By default, the desired pixel format matches the source pixel format. Valid values:
|
s | string | No | The desired resolution.
|
sopt | int | No | The resolution option. Valid values:
|
scaletype | string | No | The resizing mode. Valid values:
|
arotate | int | No | Specifies whether to enable adaptive resolution orientation. Valid values:
|
g | int | No | The keyframe interval. Valid values: 1 to 100000. |
vb | int | No | The desired video bitrate. Unit: bit/s. Valid values: 10000 to 100000000. |
vbopt | int | No | The video bitrate option. Valid values:
|
crf | float | No | The constant rate factor (CRF). Valid values: 0 to 51. |
maxrate | int | No | The maximum bitrate. Unit: bit/s. Valid values: 10000 to 100000000. |
bufsize | int | No | The buffer size. Unit: bit. Valid values: 10000 to 200000000. |
an | int | No | Specifies whether to disable audio stream generation. Valid values:
|
acodec | string | No | The encoding format of the audio. Valid values:
|
ar | int | No | The sampling rate of the output audio. Valid values:
|
ac | int | No | The number of sound channels in the output audio. By default, the output audio retains the same number of channels as the source audio. Valid values: 1 to 8. |
aq | int | No | The audio compression quality. This parameter and the ab parameter are mutually exclusive. Valid values: 0 to 100. |
ab | int | No | The desired audio bitrate. This parameter and the aq parameter are mutually exclusive. Valid values: 1000 to 10000000. |
abopt | int | No | The audio bitrate option. Valid values:
|
sn | int | No | Specifies whether to disable subtitle generation. Valid values:
|
adepth | int | No | The sampling bit depth of the output audio. Valid values: 16 and 24. Note This parameter takes effect only if you set the acodec parameter to flac. |
segment | string | No | The media segmentation settings. By default, segmentation is not applied. |
f | string | No | The media segmentation mode. Valid values:
Parent node: segment |
t | int | No | The length of the segment. Unit: milliseconds. Valid values: 0 to 3600000. Parent node: segment |
You may also need to use the sys/saveas and notify parameters in a video transcoding task. For more information, see sys/saveas and Message notification.
Use the OSS API
Convert from AVI to MP4
Transcoding task information
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: 1920 × 1080
Video frame rate: 30 fps
Video bitrate: 2 Mbit/s
Audio information
Audio stream format: AAC
Audio bitrate: 100 Kbit/s
Subtitle stream: disabled
Output path: oss://outbucket/outobjprefix.mp4
Example
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 to the MP4 container format and specify H.265 as the video stream format. Set the resolution to 1920 x 1080, frame rate to 30 fps, and video bitrate to 2 Mbit/s. Specify AAC as the audio stream format and set the audio bitrate to 100 Kbit/s. Disable subtitle stream generation. Save the output object as 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_b3V0b2JqcHJlZml4LnthdXRvZXh0fQConvert from AVI to TS
Transcoding task information
Source object
Video format: AVI
Video name: example.avi
Processing method
Length to be transcoded: Transcode 60,000 milliseconds of the video, starting from the 1,000th millisecond of the video.
Segmentation: Create HTTP Live Streaming (HLS) segments at intervals of 30 seconds.
Transcoding completion notification: Send Simple Message Queue (SMQ, formerly MNS) messages.
Destination object
Video information
Video format: TS
Video stream format: H.264
Video bitrate: 1 Mbit/s
Audio information
Audio format: AAC
Audio bitrate: 100 Kbit/s
Output paths:
TS objects: oss://outbucket/outobjprefix-%d.ts
M3U8 object: oss://outbucket/outobjprefix.m3u8
Example
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 video.
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_QXVkaW9Db252ZXJ0Convert from AVI to MP3
Transcoding task information
Source object
Video name: example.avi
Video format: AVI
Processing method: Extract and convert audio.
Destination object
Audio container format: MP3
Audio coding format: MP3
Audio bitrate: 100 Kbit/s
Video stream: disabled
Subtitle stream: disabled
Output path: oss://outbucket/outobjprefix.mp3 (If the video contains multiple audio channels, only the first channel is processed by default.)
Example
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 audio from the example.avi object and transcode the extracted audio.
x-oss-async-process=video/convert,f_mp3,acodec_mp3,ab_100000,vn_1,sn_1|sys/saveas,b_b3V0YnVja2V0,o_b3V0b2JqcHJlZml4LnthdXRvZXh0fQUse OSS SDKs
You can use OSS SDK for Java, Python, or Go to transcode videos in asynchronous mode.
Java
If you want to use OSS SDK for Java, make sure that the SDK version is V3.17.4 or later.
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 {
// Specify the endpoint of the region in which the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the ID of the Alibaba Cloud region in which the bucket is located. 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 configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the name of the output video.
String targetKey = "dest.avi";
// Specify the name of the source video.
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 {
// Create a style variable of the string type to store 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");
// Create an 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);
// Execute the asynchronous processing tasks.
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.
ossClient.shutdown();
}
}
}Python
If you want to use OSS SDK for Python, make sure that the SDK version is V2.18.4 or later.
# -*- coding: utf-8 -*-
import base64
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the name of the bucket.
bucket_name = 'examplebucket'
# Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
region = 'cn-hangzhou'
# Create a bucket.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Specify the name of the source video.
source_key = 'src.mp4'
# Specify the name of the output video.
target_key = 'dest.avi'
# Create a style variable of the string type to store video transcoding parameters.
style = 'video/convert,f_avi,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1'
process = "{0}|sys/saveas,o_{1}".format(style,
oss2.compat.to_string(base64.urlsafe_b64encode(
oss2.compat.to_bytes(target_key))).replace('=', ''))
# Call the media processing operation.
try:
# Run 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
If you want to use OSS SDK for Go, make sure that the SDK version is V3.0.2 or later.
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 configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your 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 name of the bucket in which the source video is stored. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
// Specify the name of the output video.
targetObject := "dest.avi"
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the source video.
sourceObject := "src.mp4"
// Create a style variable of the string type to store video transcoding parameters.
style := "video/convert,f_avi,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1"
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)
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)
}
FAQ
How do I fix a ResourceNotFound error for a video transcoding task?
To fix the "ResourceNotFound: The specified resource Attachment is not found" error during video transcoding, make sure that a storage bucket is created and bound to your IMM project. For more information, see Step 2: Bind an OSS bucket.
Can I save the output object of a video transcoding task to the path of the source object?
No, you cannot save the output object of a video transcoding task to the same path as the source object. To prevent issues such as execution loops of triggers or accidental overwriting of the source object, do not use the input path as the prefix of the output path.
Can I specify an audio bit depth in a video transcoding task?
Yes, you can specify an audio bit depth in a video transcoding task by including the pixfmt parameter in x-oss-process.
How do I retrieve the task execution result for video transcoding by using the returned task ID?
To retrieve the task execution result for video transcoding by using the returned task ID, we recommend that you call the GetTask operation in IMM.
How does OSS handle the retrieval and deletion of objects with a specific format based on their suffix during video transcoding?
OSS does not support searching for objects by suffix, as it offers an unordered storage service.
What do I do if message pushing for video transcoding is configured but the backend does not receive messages?
Check whether the SMQ topic is created and the subscription is configured. If the SMQ topic does not exist or is deleted, reconfigure the subscription. Restart the transcoding process based on the current subscription configuration.
Can I use a specific template to transcode a video after uploading the video to OSS?
Yes, you can configure a trigger to implement the feature. For existing and new videos in a bucket, video processing tasks can be manually or automatically initiated by using batch processing configurations and triggers. When you create tasks, batch processors, or triggers, you can use system or custom styles. For more information, see Batch processing and Triggers.
Am I charged storage fees for both the transcoded video and the source video? If the transcoded video has a different prefix than the source video, will the transcoded video replace the source video?
Yes, you are charged storage fees for both the transcoded video and the source video. This is because the transcoded video also consumes storage space. If you use the same path for the transcoded video and the source video, loops may occur.