Alibaba Cloud ApsaraVideo VOD (VOD) provides the preview feature. This topic describes how to enable the preview feature and provides best practices for obtaining a preview URL.

Overview

After you enable the preview feature, users can preview a predefined duration of the audio or video file. This feature is typically used for paid media assets. You can call the GetPlayInfo operation on the server side to specify the preview duration. This operation returns the preview URL. Alternatively, you can construct a preview URL that contains the preview information. The constructed URL is a signed URL.

Notice If the preview duration that you specified exceeds the total duration of the video, you can use the preview URL that is returned by ApsaraVideo VOD to play the complete video.

The preview feature of Alibaba Cloud ApsaraVideo VOD is implemented based on Alibaba Cloud CDN. The basic principle of the preview feature is that the player uses the URL of an accelerated domain name that contains information about the specified preview duration to access VOD. Before a file is returned, VOD must verify the URL. If the preview URL passes the verification, the specified file is returned. Otherwise, access is denied and the HTTP 403 status code is returned. The following figure shows how the preview feature of ApsaraVideo VOD works.

Process
  1. You configure an accelerated domain name for CDN and enable the preview feature.
    Notice Before you can use the preview feature, you must configure a domain name and enable the preview feature. For more information, see Enable the preview feature.
  2. The player sends a preview request to ApsaraVideo VOD.
  3. ApsaraVideo VOD generates a preview URL based on the domain name settings and the preview duration settings in the preview request.
    Note ApsaraVideo VOD allows you to call an API operation on the server side to generate a preview URL or construct a preview URL. For more information, see Call the GetPlayInfo operation to obtain the preview URL and Construct a preview URL.
  4. The player uses the preview URL to request the video from CDN.

Limits

  • ApsaraVideo VOD allows you to preview video files in the MP4 and HLS formats. The metadata of MP4 files must be contained in the file header. MP4 files whose metadata is contained in the file tail cannot be previewed. When ApsaraVideo VOD transcodes a video and converts its container format to MP4, the system places the metadata in the file header.
  • The preview duration is determined based on keyframes. We recommend that you do not use the preview feature for short videos. For long videos, we recommend that you set the preview duration to at least 30 seconds. By default, the keyframe interval of transcoded videos is 10 seconds.
    Note You can modify the keyframe interval in transcoding templates. For more information, see Configure transcoding template groups.
  • The preview granularity of HLS files is the duration of each TS segment. The specified preview duration and the actual preview duration of the returned video may be different. The actual preview duration of the returned video is rounded up based on the specified preview duration. For example, if the TS segment duration is 10 seconds and the specified preview duration is 15 seconds, the preview duration of the returned video is 20 seconds.

Enable the preview feature

Before you call an operation to obtain the preview URL or you construct a preview URL, you must configure the domain name and enable the preview feature. To enable the preview feature, perform the following steps:

  1. Configure an accelerated domain name for CDN. For more information, see Add a domain name for CDN.
    Notice To use the preview feature, an accelerated domain name for CDN must be configured.
  2. Enable URL authentication and turn on Support Previewing. For more information, see Configure URL authentication.
    Notice If the preview feature is not enabled for a domain name, requests for video playback cannot include preview parameters and the returned URL cannot be accessed. You must turn on Support Previewing when you configure URL authentication.

    The following figure shows how to enable the preview feature in the VOD console.

    Note To manually construct a preview URL, you must specify the privateKey parameter to calculate the authentication value. The value is the Primary Key or Secondary Key value that is generated or entered in the console. Record the preceding values for subsequent use.
    Enable the preview feature
  3. Enable Back-to-origin of Range and Drag/Drop Playback for the domain name. For more information, see Object chunking and Video seeking.

Call the GetPlayInfo operation to obtain the preview URL

ApsaraVideo VOD allows you to call the GetPlayInfo operation to obtain the preview URL of a video. For more information, see GetPlayInfo. You can integrate server SDKs and use the SDKs to call this operation to obtain the preview URL. To obtain the preview URL, perform the following steps.

Notice Before you call this operation, make sure that the preview feature is enabled. For more information, see Enable the preview feature.
  1. Integrate server SDKs based on your business requirements. For more information, see Server SDK Reference.
  2. Use the SDKs to call the GetPlayInfo operation. You can specify the preview duration by using PreviewTime in PlayConfig when you call this operation. The server returns the preview URL based on the preview duration settings. For more information about the PlayConfig parameter, see Request parameters.
Sample code for obtaining a preview URL (Java)
Note
  • For more information about sample code in other programming languages, see OpenAPI.
  • Obtain an AccessKey pair to complete identity verification so that you can call server API operations. For more information about how to obtain an AccessKey pair, see Obtain an AccessKey pair.


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;

/**
 * @date 2021/12/30
 */
public class VodPreviewTest {
    public static void main(String[] args) throws ClientException {
        // Specify the region of ApsaraVideo VOD. For more information, see Region IDs of ApsaraVideo VOD. 
        String regionId = "cn-shanghai";
        // Specify the AccessKey ID of your Alibaba Cloud account. 
        String accessKeyId = "<your accessKeyId>";
        // Specify the AccessKey Secret of your Alibaba Cloud account. 
        String accessKeySecret = "<your accessKeySecret>";
        // Specify the ID of the video. Example: 533606af570e4db4961248d0978b****. After you upload a video in the VOD console, you can log on to the VOD console and choose Media Files > Audio/Video to view the ID of the video. If you upload a video by calling the CreateUploadVideo operation, the ID of the video is the value of VideoId in the response. 
        String videoId = "<your videoId>";
        DefaultAcsClient client = InitVodClient(regionId, accessKeyId, accessKeySecret);
        GetPlayInfoResponse response = null;
        try {
            response = getPlayInfo(client, videoId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("response = " + JSONObject.toJSONString(response));

    }

    /**
     * Initialize the client.
     *
     * @param regionId
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws ClientException
     */
    public static DefaultAcsClient InitVodClient(String regionId, String accessKeyId, String accessKeySecret) throws ClientException {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /**
     * Obtain the video playback URL.
     *
     * @param client
     * @param videoId
     * @return
     * @throws Exception
     */
    public static GetPlayInfoResponse getPlayInfo(DefaultAcsClient client, String videoId) throws Exception {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        // Specify the validity period in seconds. Default value: 3600.
        request.setAuthTimeout(3600L);
        request.setFormats("mp4");
        JSONObject playConfig = new JSONObject();
        // Specify the preview duration in seconds. Minimum value: 1.
        playConfig.put("PreviewTime", "30");
        request.setPlayConfig(playConfig.toJSONString());
        return client.getAcsResponse(request);
    }
}
                

Construct a preview URL

ApsaraVideo VOD allows you to construct a signed URL that contains the preview information. To construct a signed URL, perform the following steps.

Notice Before you construct a preview URL, make sure that the preview feature is enabled. For more information, see Enable the preview feature.
  1. Construct a signed URL that contains the preview parameters. When you calculate the MD5 hash value for a signed preview URL, you must add previewTime that is used to calculate the preview duration.
    MD5 hash calculation for the URL of a video MD5 hash calculation for a preview URL
    MD5(uri-timestamp-rand-uid-PrivateKey) MD5(uri-timestamp-rand-uid-PrivateKey-previewTime)
    Note For more information about parameters in MD5 hash calculation and the methods that are used to construct a signed URL, see URL authentication. If you want to play the complete video, do not configure the previewTime parameter.
  2. Append &end=, followed by previewTime, to the end of the constructed signed URL.
Sample code for combining the dependencies required for JAR packages (Java)
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
Sample code for constructing a preview URL (Java)
    import java.util.UUID;
    import java.net.URL;
    import org.apache.commons.lang3.StringUtils;
    private String generateRand() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    private String md5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes("UTF-8"));
            return bytesToHex(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String genAuthKey(String object, String privateKey, Long expireTime, Long previewTime) {
        String rand = "0";
        String uid = "0";
        if (StringUtils.isBlank(privateKey)) {
            return "";
        }
        rand = generateRand();
        long timestamp = System.currentTimeMillis() / 1000 + (expireTime == null ? 0 : expireTime);
        String authStr = timestamp + "-" + rand + "-" + uid;
        String md5Str = object + "-" + authStr + "-" + privateKey;
        if(previewTime!=0)
            md5Str = md5Str + "-" + previewTime;
        String auth_key = authStr + "-" + this.md5(md5Str);
        return auth_key;
    }

    public void previewTest() throws Exception {
        try {
            String key = "<Your PrivateKey>";// The primary key or secondary key that you configured in the VOD console. For more information, see Enable the preview feature. 
            String fileUrl = "<Your File URL>";// The URL of the file. Example: http://example.aliyundoc.com/test/bee21427ca3346848835c1bd786054c5-19bd8528c1d51576cd726cf86471ca0****.mp4.
            URL url = new URL(fileUrl);
            String file = url.getFile();
            Long previewTime=120L; // The preview duration. 
            Long expireTime = 1800L;
            String auth_key =genAuthKey(file, key, expireTime, previewTime);
            fileUrl = fileUrl + "?auth_key=" + auth_key;
            if(previewTime != 0)
                fileUrl = fileUrl + "&end=" + previewTime;
            System.out.println(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }