ApsaraVideo VOD and ApsaraVideo Live support multiple video encryption methods. This topic describes how to use ApsaraVideo Player SDK to play videos encrypted with Alibaba Cloud proprietary encryption, HLS standard encryption, and DRM encryption.
Video encryption overview
ApsaraVideo VOD provides a comprehensive content security mechanism that includes access control, URL signing, remote authentication, video encryption, and secure download.
The Overview covers all available security policies. The following table compares the three video encryption methods.
|
Security policy |
Method |
Benefit |
Security level |
Deployment complexity |
|
Video encryption |
Alibaba Cloud proprietary cryptography |
ApsaraVideo VOD uses a proprietary cryptography algorithm to provide a cloud-device integrated video encryption solution. This ensures the security of transmission links. |
High |
Relatively low. You need to only perform simple configurations and integrate ApsaraVideo Player SDK. |
|
HTTP Live Streaming (HLS) encryption |
HLS encryption uses AES-128 to encrypt video content and supports all HLS-compatible players. However, the keys are prone to theft. |
High |
High. You must set up a key management service and a token issuance service. In addition, you must ensure the security of transmission links. |
|
|
Commercial DRM |
Native support for commercial DRM systems, including Apple FairPlay and Google Widevine. This method provides a high level of security and meets the requirements of most copyright holders. |
High |
High. You are charged based on the number of license calls (for third-party DRM, refer to the applicable billing standards). You only need to integrate ApsaraVideo Player SDK. |
ApsaraVideo Player SDK compatibility
-
Before using ApsaraVideo Player SDK for Web to play encrypted videos, check Browser compatibility and Feature compatibility. ApsaraVideo Player SDK for Web can play videos encrypted with Alibaba Cloud proprietary cryptography on mainstream mobile browsers. In the following table, ✔️ indicates supported and ❌ indicates unsupported.
-
To ensure compatibility, download the latest ApsaraVideo Player SDK from the SDK overview page.
-
Note: HLS uses the M3U8 format.
|
Client |
Playback method |
Proprietary cryptography (HLS) |
License-based cryptography (HLS) |
License-based cryptography (MP4) |
Proprietary cryptography (live FLV) |
HLS encryption |
Alibaba Cloud DRM |
Third-party DRM |
|
Web |
UrlSource-based playback |
❌ |
❌ |
❌ |
❌ |
✔️ |
❌ |
✔️ |
|
VidAuth-based playback |
✔️ |
❌ |
❌ |
❌ |
✔️ |
❌ |
❌ |
|
|
VidSts-based playback |
❌ |
❌ |
❌ |
❌ |
✔️ |
✔️ |
❌ |
|
|
UrlSource-based live streaming |
❌ |
❌ |
❌ |
❌ |
✔️ |
❌ |
✔️ |
|
|
LiveStsSource-based live streaming |
✔️ |
✔️ |
❌ |
❌ |
❌ |
✔️ |
❌ |
|
|
Native (iOS/Android/Flutter/Harmony) |
UrlSource-based playback |
✔️ |
✔️ Requires ApsaraVideo Player SDK v6.17.0 or later. |
✔️ Requires ApsaraVideo Player SDK v6.8.0 or later. |
❌ |
✔️ |
❌ |
✔️ Requires ApsaraVideo Player SDK v7.8.0 or later. Not supported on Flutter and Harmony. |
|
VidAuth-based playback |
✔️ |
✔️ |
❌ |
❌ |
✔️ |
❌ |
❌ |
|
|
VidSts-based playback |
✔️ |
✔️ |
❌ |
❌ |
✔️ |
✔️ Not supported on Flutter and Harmony. |
❌ |
|
|
UrlSource-based live streaming |
❌ |
❌ |
❌ |
❌ |
✔️ |
❌ |
✔️ Requires ApsaraVideo Player SDK v7.8.0 or later. Not supported on Flutter and Harmony. |
|
|
LiveStsSource-based live streaming |
✔️ |
✔️ |
❌ |
✔️ |
❌ |
✔️ Not supported on Flutter and Harmony. |
❌ |
Encryption overview
Alibaba Cloud video encryption (private encryption)
Alibaba Cloud Video Encryption (Private Encryption) encrypts video data so it stays encrypted even after download, preventing unauthorized redistribution and hotlinking. Alibaba Cloud Video Encryption (Private Encryption).
Alibaba Cloud Player SDK handles decryption and server-side interactions. You only need to configure encrypted transcoding and integrate the SDK.
-
Alibaba Cloud Video Encryption (Private Encryption) is free, but media transcoding is required for encryption and incurs fees. Media transcoding billing.
Configure private encryption
To configure Alibaba Cloud Video Encryption, follow the How-to guide.
Limitations
Alibaba Cloud Video Encryption (Private Encryption) supports encryption for videos in HLS, FLV, and MP4 formats. You can play these videos only with Alibaba Cloud Player. Web clients support only HLS playback. Native clients support playback for all these formats.
Alibaba Cloud video encryption (license-based private encryption)
Alibaba Cloud Video Encryption (License-based Private Encryption) builds on Private Encryption and enables playback directly from the encrypted video URL, improving startup speed. This is ideal for short video and short-form drama scenarios.
-
Alibaba Cloud Video Encryption (License-based Private Encryption) is free, but media transcoding is required for encryption and incurs fees. Media transcoding billing.
Configure license-based private encryption
To configure Alibaba Cloud Video Encryption, follow the How-to guide.
Limitations
Alibaba Cloud Video Encryption (License-based Private Encryption) supports encryption for videos in HLS and MP4 formats. You can play these encrypted videos only with Alibaba Cloud Player.
HLS standard encryption
HLS Standard Encryption uses AES-128 to encrypt video content. It is compatible with all HLS players, including self-developed and open-source ones, but is more complex to implement and less secure than proprietary methods. HLS Standard Encryption.
HLS Standard Encryption is free, but media transcoding is required for encryption and incurs fees. Media transcoding billing.
Configure HLS Standard Encryption
To configure HLS Standard Encryption, follow the Integration guide.
Limitations
HLS Standard Encryption is compatible with various HLS players. This topic uses Alibaba Cloud Player as an example. Alibaba Cloud Player supports token passing — the CDN dynamically adjusts the decryption URI in the HLS manifest file, adding a user token that your application can verify.
Alibaba Cloud DRM encryption
ApsaraVideo VOD supports industry-standard Digital Rights Management (DRM) encryption with Widevine and FairPlay schemes, providing a one-stop solution for managing copyrighted videos. DRM encryption.
DRM encryption is applied during transcoding (media transcoding fees apply). DRM license fees apply when a client requests a playback license. DRM billing.
Configure DRM encryption
Enable this feature on the ApsaraVideo Live and ApsaraVideo VOD consoles: Configure DRM encryption for ApsaraVideo Live and Configure DRM encryption for ApsaraVideo VOD.
Limitations
Currently, you can play DRM-encrypted videos only with Alibaba Cloud Player.
Third-party DRM encryption
ApsaraVideo VOD supports third-party DRM encryption, enabling an end-to-end workflow from video production in ApsaraVideo for Media Processing through third-party DRM encryption to playback with Alibaba Cloud Player SDK.
DRM encryption is applied during transcoding (media transcoding fees apply). DRM license fees apply when a client requests a playback license. DRM billing.
Configure DRM encryption
Enable this feature on the ApsaraVideo for Media Processing console on the Alibaba Cloud International site.
See the live packaging and VOD packaging features on the ApsaraVideo for Media Processing console. These features are currently available only on the Alibaba Cloud International site.
Web client
-
Before using ApsaraVideo Player SDK for Web, review browser compatibility for Alibaba Cloud proprietary encryption.
-
The H5 mode supports both desktop and mobile browsers. Feature support.
-
-
For security reasons, Alibaba Cloud proprietary encryption does not allow you to debug with real encrypted videos.
Procedure
Embed the web player into your web page.
-
Follow the Quick start guide to import ApsaraVideo Player SDK for Web into your page.
-
Select an encryption method and start playback.
The following code shows how to embed the player.
Alibaba Cloud proprietary encryption
VOD (VidAuth)
To play a video encrypted with Alibaba Cloud proprietary encryption using the ApsaraVideo VOD VidAuth method, you must also pass the encryptType: 1 parameter to enable proprietary encryption. This is not required for playing standard videos.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<title>VOD Proprietary Encryption Playback Test Case</title>
<link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
</head>
<body>
<div class="prism-player" id="J_prismPlayer"></div>
<script>
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
vid : '<your video ID>',// Required. The video ID. You can find this in the ApsaraVideo VOD console by choosing media library > Audio/Video. Example: 1e067a2831b641db90d570b6480f****.
playauth : '<your PlayAuth>',// Required. The playback credential. You can obtain this by calling the GetVideoPlayAuth operation.
encryptType: 1, // Required. Set this to 1 when playing streams with proprietary encryption. This parameter is not needed for other cases.
playConfig:{EncryptType:'AliyunVoDEncryption'}, // Required if your M3U8 stream also contains other streams that do not use proprietary encryption.
// authTimeout: 7200, // Optional. The validity period of the playback URL, in seconds. This value overrides the URL signing validity period set in the ApsaraVideo VOD console. If not specified, the default value is 7200. If set, ensure this value exceeds the video's duration to prevent the URL from expiring mid-playback.
},function(player){
console.log('The player is created.')
});
</script>
</body>
</html>
Live (LiveStsSource)
To play a live stream that uses proprietary encryption with the LiveStsSource method, you must provide the stream URL and an STS temporary credential. For information on how to generate the credential, see Obtain an STS token.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<title>Live Proprietary Encryption Playback Test Case</title>
<link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.35.6/skins/default/aliplayer-min.css" />
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.35.6/aliplayer-min.js"></script>
</head>
<body>
<div class="prism-player" id="J_prismPlayer"></div>
<script>
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
isLive: true, // Set to true for live streaming.
source: '<your live stream url>',// Required. The playback URL of the HLS live stream with proprietary encryption.
accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
securityToken: '<your STS token>',// Required. The STS security token. Generate this by calling the STS AssumeRole operation.
domain: '<your Domain>',// Required. The streaming domain for the live stream.
app:'<your App Name>',// Required. The AppName of the live stream.
stream:'<your Stream Name>',// Required. The StreamName of the original live stream, not a transcoded stream.
regionId: '<region of your video>',// Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
useHls2: false,
},function(player){
console.log('The player is created.')
});
</script>
</body>
</html>
-
To play encrypted on-demand videos in browsers on iOS versions earlier than 17.1, you must deploy an additional player plugin script. Follow these steps:
On iOS versions earlier than 17.1, proprietary encryption requires a plugin based on Service Worker technology. Browser security policies restrict service workers to same-origin scripts, so you must deploy the plugin to the same domain as your website.
-
Download the script: https://g.alicdn.com/apsara-media-box/imp-web-player/<version_number>/aliplayer-worker-min.js
-
Deploy the script: For example, if your video playback website is
https://www.aliyun.com/a/b.html, you must deploy the script tohttps://www.aliyun.com/a/aliplayer-worker-min.js, which is in the same directory as the web page. -
Pass this URL when you initialize the player:
new Aliplayer({ // ...other parameters swScriptURL: 'https://www.aliyun.com/a/aliplayer-worker-min.js' // Provide the full URL of the plugin script and ensure it is accessible. })
Note: Make sure that the player version exactly matches the plugin version.
-
-
If your web page runs within a custom-packaged iOS application (such as uni-app), add your domain to
WKAppBoundDomainsin the app'sInfo.plistfile to enable Service Worker inWKWebView. App-Bound Domains.
HLS standard encryption
VOD (VidAuth)
When playing a video with HLS standard encryption using the ApsaraVideo VOD VidAuth method, if the video also has other non-HLS standard encrypted streams or standard transcoded streams, you can set the EncryptType parameter to HLSEncryption to filter for and play only the HLS standard encrypted stream.
let player = new Aliplayer({
id:'J_prismPlayer',
vid:'<your video ID>', // Required. The video ID. Example: 1e067a2831b641db90d570b6480f****.
playauth:'<your PlayAuth>', // Required. The video playback credential.
playConfig: { // Optional.
MtsHlsUriToken: '', // Optional. If you need to validate MtsHlsUriToken (user token), pass it in this parameter.
EncryptType: 'HLSEncryption', // Optional. If you set this parameter to HLSEncryption, only streams with HLS standard encryption are returned.
},
});
VOD (VidSts)
When playing a video with HLS standard encryption using the ApsaraVideo VOD VidSts method, if the video also has other non-HLS standard encrypted streams or standard transcoded streams, you can set the EncryptType parameter to HLSEncryption to filter for and play only the HLS standard encrypted stream.
let player = new Aliplayer({
id: 'J_prismPlayer',
vid : '<your video ID>', // Required. The video ID. You can obtain the ID from the ApsaraVideo VOD console (media library > Audio/Video) or by calling the SearchMedia API operation after the video is uploaded. Example: 1e067a2831b641db90d570b6480f****.
accessKeyId: '<your AccessKey ID>', // Required. The AccessKey ID of the STS temporary credential pair, returned when you generate the STS security token.
securityToken: '<your STS token>', // Required. The STS security token. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>', // Required. The AccessKey secret of the STS temporary credential pair, returned when you generate the STS security token.
region: '<region of your video>', // Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
playConfig: { // Optional.
MtsHlsUriToken: '', // Optional. If you need to validate MtsHlsUriToken (user token), pass it in this parameter.
EncryptType: 'HLSEncryption', // Optional. If you set this parameter to HLSEncryption, only streams with HLS standard encryption are returned.
},
};
UrlSource
When you play a live or on-demand stream that uses HLS standard encryption with the UrlSource method, no additional parameters are required. The configuration is the same as for playing a standard video.
let player = new Aliplayer({
id:'J_prismPlayer',
source:'<your play URL>', // The playback URL, which can be for a live or on-demand stream.
isLive: true, // Set to true for live streaming.
});
DRM encryption
VOD (VidSts)
To play a DRM-encrypted video using the ApsaraVideo VOD VidSts method, you must also pass the isDrm: true parameter.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<title>VOD DRM Encryption Test Case</title>
<link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
</head>
<body>
<div class="prism-player" id="J_prismPlayer"></div>
<script>
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
isDrm: true,
vid: '<your video ID>',// Required. The video ID. You can find this in the ApsaraVideo VOD console by choosing media library > Audio/Video. Example: 1e067a2831b641db90d570b6480f****.
accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
securityToken: '<your STS token>',// Required. The STS security token. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
region: '<region of your video>', // Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
certId: '<your certificate ID>', // Required for playback on Apple devices. Use this parameter to request the Apple certificate. Obtain it from the ApsaraVideo VOD or ApsaraVideo Live console, depending on your DRM implementation.
// authTimeout: 7200, // Optional. The validity period of the playback URL, in seconds. This value overrides the URL signing validity period set in the ApsaraVideo VOD console. If not specified, the default value is 7200. If set, ensure this value exceeds the video's duration to prevent the URL from expiring mid-playback.
},function(player){
console.log('The player is created.')
});
</script>
</body>
</html>
Live (LiveStsSource)
To play a DRM-encrypted live stream using the LiveStsSource method, provide the stream URL and an STS temporary credential. For information on how to generate an STS temporary credential, see Obtain an STS token.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<title>Live DRM Encryption Test Case</title>
<link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/skins/default/aliplayer-min.css" />
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.16.3/aliplayer-min.js"></script>
</head>
<body>
<div class="prism-player" id="J_prismPlayer"></div>
<script>
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
isLive: true, // Set to true for live streaming.
isDrm: true,
source: '<your live stream url>',// Required. The playback URL of the DRM-encrypted live stream.
accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
securityToken: '<your STS token>',// Required. The STS security token. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
region: '<region of your video>', // Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
certId: '<your certificate ID>', // Required for playback on Apple devices. Use this parameter to request the Apple certificate. Obtain it from the ApsaraVideo VOD or ApsaraVideo Live console, depending on your DRM implementation.
},function(player){
console.log('The player is created.')
});
</script>
</body>
</html>
Android
Procedure
Integrate the Alibaba Cloud Player SDK for Android into your application. The following sections provide the steps and sample code.
-
Integrate the Alibaba Cloud Player SDK for Android.
-
Create a player to play a video.
Follow Basic features. For Step 3. Create a DataSource, choose one of the following methods based on your requirements.
Alibaba Cloud Video Encryption (private encryption)
Usage notes
HLS videos encrypted with Alibaba Cloud Video Encryption (private encryption) can be played using a URL after transcoding. Before transcoding, bind a license under the same account (Manage License), then set the EncryptType parameter when you create a transcoding template group. Example:
After you create the template, do not modify or save it on the console. Otherwise, the encryption method will be overwritten.
[{
"TranscodeTemplateId": "",
"TemplateName": "740P H.264 HLS local encryption",
"Type": "Normal",
"Container": {
"Format": "m3u8"
},
"TransConfig": {
"IsCheckReso": false,
"IsCheckResoFail": false,
"IsCheckVideoBitrate": false,
"IsCheckVideoBitrateFail": false,
"IsCheckAudioBitrate": false,
"IsCheckAudioBitrateFail": false
},
"Definition": "HD",
"MuxConfig": {
"Segment": {
"Duration": 5
}
},
"EncryptSetting": {
"EncryptType": "AliyunVoDLicenseEncryption"
},
"Video": {
"Height": 720,
"Bitrate": 400,
"Codec": "H.264",
"Fps": 25,
"Gop": 250,
"Profile": "high"
},
"Audio": {
"Bitrate": 64,
"Codec": "AAC",
"Channels": 2,
"Samplerate": "44100"
}
}]
VidAuth
When you play a privately encrypted HLS or MP4 video using ApsaraVideo VOD VidAuth, if the video also contains streams with other encryption types or non-encrypted transcoded streams, you can set the video encryption type to AliyunVoDEncryption to play only the privately encrypted stream.
VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set this parameter to AliyunVoDEncryption, only privately encrypted video streams are returned.
vidAuth.setPlayConfig(vidPlayerConfigGen);
vidAuth.setVid("your_video_id");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The PlayAuth, generated by calling the ApsaraVideo VOD GetVideoPlayAuth operation.
vidAuth.setRegion("your_region");// This parameter is deprecated in player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically resolves it. For earlier versions, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidAuth);
VidSts
When you play a privately encrypted HLS or MP4 video using ApsaraVideo VOD VidSts, if the video also contains streams with other encryption types or non-encrypted transcoded streams, you can set the video encryption type to AliyunVoDEncryption to play only the privately encrypted stream.
VidSts vidSts = new VidSts();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set this parameter to AliyunVoDEncryption, only privately encrypted video streams are returned.
vidSts.setPlayConfig(vidPlayerConfigGen);
vidSts.setVid("your_video_id");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To obtain this, call the STS AssumeRole operation.
vidSts.setRegion("your_region");// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidSts);
LiveSts
To play a privately encrypted live stream in HLS or FLV format using the ApsaraVideo Live LiveSts object, you must pass the URL and an STS credential, and set the video encryption type to AliEncryption. The following code provides an example:
-
Create a data source.
You must pass
LiveStsas the playback source.// Create a LiveSts object and set EncryptionType to AliEncryption. LiveSts liveSts = new LiveSts(); liveSts.setUrl("<your live stream url>");// Required. The playback URL of the privately encrypted HLS live stream. liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setSecurityToken("<your STS token>");// Required. The security token. To obtain this, call the STS AssumeRole operation. liveSts.setDomain("<your Domain>");// Required. The streaming domain of the live stream. liveSts.setApp("<your App Name>");// Required. The AppName of the live stream. liveSts.setStream("<your Stream Name>");// Required. The StreamName of the live stream. liveSts.setEncryptionType(LiveSts.LiveEncryptionType.AliEncryption);// Required. Set the encryption type to AliEncryption. liveSts.setRegion("<region of your video>");// Required. The service region, such as cn-shanghai. // Set the playback source. aliPlayer.setDataSource(liveSts); // Prepare for playback. aliPlayer.prepare(); -
Listen for STS invalidation.
During encrypted live playback, the encryption key may be rotated. When a key rotation occurs, the player uses the STS credential to request the new key. You must monitor the validity of the STS credential because an invalid credential will disrupt playback.
mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() { @Override public AliPlayer.Status onVerifySts(StsInfo info) { if(info is valid){ return IPlayer.StsStatus.Valid; } if(a valid STS credential can be obtained){ getSTS(); // This can be asynchronous or synchronous. return IPlayer.StsStatus.Pending; } // If the info is invalid and a new STS credential cannot be obtained, we recommend stopping playback to prevent corrupted video output. mAliyunVodPlayer.stop(); return IPlayer.StsStatus.Invalid; } @Override public AliPlayer.Status onVerifyAuth(VidAuth auth) { return AliPlayer.Status.Valid; } });NoteAfter you successfully obtain a new STS credential, you must call the
updateLiveStsInfomethod to update it. If you fail to obtain a new credential, we recommend stopping playback. If you do not update the STS credential, the player will continue to use the old one to request keys after it expires. If the STS credential becomes invalid, this may cause playback failure or corrupted video output.mAliyunVodPlayer.updateStsInfo(stsInfo);
Alibaba Cloud Video Encryption (license-based private encryption)
Usage notes
HLS videos encrypted with Alibaba Cloud Video Encryption (License-based private encryption) can be played using a URL after transcoding. Before transcoding, bind a license under the same account (Manage License), then set the EncryptType parameter when you create a transcoding template group. Example:
After you create the template, do not modify or save it on the console. Otherwise, the encryption method will be overwritten.
[{
"TranscodeTemplateId": "",
"TemplateName": "740P H.264 HLS local encryption",
"Type": "Normal",
"Container": {
"Format": "m3u8"
},
"TransConfig": {
"IsCheckReso": false,
"IsCheckResoFail": false,
"IsCheckVideoBitrate": false,
"IsCheckVideoBitrateFail": false,
"IsCheckAudioBitrate": false,
"IsCheckAudioBitrateFail": false
},
"Definition": "HD",
"MuxConfig": {
"Segment": {
"Duration": 5
}
},
"EncryptSetting": {
"EncryptType": "AliyunVoDLicenseEncryption"
},
"Video": {
"Height": 720,
"Bitrate": 400,
"Codec": "H.264",
"Fps": 25,
"Gop": 250,
"Profile": "high"
},
"Audio": {
"Bitrate": 64,
"Codec": "AAC",
"Channels": 2,
"Samplerate": "44100"
}
}]
UrlSource
Only Alibaba Cloud Player SDK for Android V6.8.0 and later supports playing license-based privately encrypted MP4 videos using UrlSource. Version V6.17.0 and later supports license-based privately encrypted HLS videos (single-bitrate and adaptive-bitrate).
To play a license-based privately encrypted video in HLS or MP4 format using UrlSource, call the GetPlayInfo operation to obtain the video playback URL. For an MP4 URL, append etavirp_nuyila=1 to the URL before you pass it to the player. You can place this parameter anywhere in the query string. For HLS, you can use the original video URL. Configure the player SDK as you would for a standard video; no extra parameters are required.
Example playback URL 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Example playback URL 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// Playback URL
String playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1";
// Player
UrlSource urlSource = new UrlSource();
urlSource.setUri(playURL);// Required. The playback URL of the video. You can call the GetPlayInfo operation to obtain the URL.
aliPlayer.setDataSource(urlSource);
aliPlayer.prepare();
// Short video player
AliListPlayer aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
// Add a UrlSource
aliyunListPlayer.addUrl(playURL,uid);
aliyunListPlayer.moveTo(uid);
// Preload
MediaLoader mediaLoader = MediaLoader.getInstance();
mediaLoader.load(playURL,"duration");
Standard HLS encryption
VidAuth
When you play a video that uses standard HLS encryption using ApsaraVideo VOD VidAuth, if the video also contains other non-standard HLS encrypted streams or standard transcoded streams, you can set the encryption type to HLSEncryption to play only the standard HLS encrypted stream. The following code provides an example:
If you enabled Rewrite standard HLS encryption M3U8 files, you must call setMtsHlsUriToken to set the user token.
VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen playerConfig = new VidPlayerConfigGen();
playerConfig.setEncryptType(VidPlayerConfigGen.EncryptType.HLSEncryption);// Optional. If you set this parameter to HLSEncryption, only standard HLS encrypted video streams are returned.
playerConfig.setMtsHlsUriToken("token");// Optional. Pass this parameter if you want to validate the MtsHlsUriToken (user token).
vidAuth.setPlayConfig(playerConfig);
vidAuth.setVid("your_video_id");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The PlayAuth, generated by calling the ApsaraVideo VOD GetVideoPlayAuth operation.
vidAuth.setRegion("your_region");// This parameter is deprecated in player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically resolves it. For earlier versions, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidAuth.setAuthTimeout(3600);// Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidAuth);
VidSts
When you play a video that uses standard HLS encryption using ApsaraVideo VOD VidSts, if the video also contains other non-standard HLS encrypted streams or standard transcoded streams, you can set the encryption type to HLSEncryption to play only the standard HLS encrypted stream. The following code provides an example:
If you enabled Rewrite standard HLS encryption M3U8 files, you must call setMtsHlsUriToken to set the user token.
VidSts vidSts = new VidSts();
VidPlayerConfigGen playerConfig = new VidPlayerConfigGen();
VidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.HLSEncryption);//Optional. If you set this parameter to HLSEncryption, only standard HLS encrypted video streams are returned.
playerConfig.setMtsHlsUriToken("token");// Optional. Pass this parameter if you want to validate the MtsHlsUriToken (user token).
vidSts.setPlayConfig(playerConfig);
vidSts.setVid("your_video_id");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To obtain this, call the STS AssumeRole operation.
vidSts.setRegion("your_region");// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600);// Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidSts);
UrlSource
When playing a stream that uses standard HLS encryption with UrlSource, configure the player SDK as you would for a standard video.
We recommend using ApsaraVideo VOD. You can call the GetPlayInfo operation to obtain the video's playback URL and pass it to the player.
If you enabled Rewrite standard HLS encryption M3U8 files, you must append MtsHlsUriToken=<token> to the video URL before you pass it to the player. You can place this parameter anywhere in the query string.
Example original playback URL: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Example URL to pass to the player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
UrlSource urlSource = new UrlSource();
urlSource.setUri("playback_url");// The playback URL of the live or on-demand stream that uses standard HLS encryption.
aliPlayer.setDataSource(urlSource);
Alibaba Cloud DRM encryption
On Android, we recommend using a SurfaceView to ensure proper playback of videos that have a high level of security.
VidSts
First, configure DRM encryption as described in Configure DRM encryption for ApsaraVideo VOD. When you play a DRM-encrypted video using ApsaraVideo VOD VidSts, the configuration is the same as for an unencrypted video. No additional parameters are required.
VidSts vidSts = new VidSts();
vidSts.setVid("your_video_id");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To obtain this, call the STS AssumeRole operation.
vidSts.setRegion("your_region");// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidSts);
LiveSts
First, configure DRM encryption as described in Configure DRM encryption for ApsaraVideo Live. To play a DRM-encrypted live stream using the LiveSts object, you must pass the URL and an STS credential, and set the video encryption type to WideVine_FairPlay. The following code provides an example:
-
Create a data source.
You must pass
LiveStsas the playback source.// Create a LiveSts object and set EncryptionType to WideVine_FairPlay. LiveSts liveSts = new LiveSts(); liveSts.setUrl("<your live stream url>");// Required. The playback URL of the DRM-encrypted HLS live stream. liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setSecurityToken("<your STS token>");// Required. The security token. To obtain this, call the STS AssumeRole operation. liveSts.setDomain("<your Domain>");// Required. The streaming domain of the live stream. liveSts.setApp("<your App Name>");// Required. The AppName of the live stream. liveSts.setStream("<your Stream Name>");// Required. The StreamName of the live stream. liveSts.setEncryptionType(LiveSts.LiveEncryptionType.WideVine_FairPlay);// Required. Set the encryption type to WideVine_FairPlay. liveSts.setRegion("<region of your video>");// Required. The service region, such as cn-shanghai. // Set the playback source. aliPlayer.setDataSource(liveSts); // Prepare for playback. aliPlayer.prepare(); -
Listen for STS invalidation.
During encrypted live playback, the encryption key may be rotated. When a key rotation occurs, the player uses the STS credential to request the new key. You must monitor the validity of the STS credential because an invalid credential will disrupt playback.
mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() { @Override public AliPlayer.Status onVerifySts(StsInfo info) { if(info is valid){ return IPlayer.StsStatus.Valid; } if(a valid STS credential can be obtained){ getSTS(); // This can be asynchronous or synchronous. return IPlayer.StsStatus.Pending; } // If the info is invalid and a new STS credential cannot be obtained, we recommend stopping playback to prevent corrupted video output. mAliyunVodPlayer.stop(); return IPlayer.StsStatus.Invalid; } @Override public AliPlayer.Status onVerifyAuth(VidAuth auth) { return AliPlayer.Status.Valid; } });NoteAfter you successfully obtain a new STS credential, you must call the
updateLiveStsInfomethod to update it. If you fail to obtain a new credential, we recommend stopping playback. If you do not update the STS credential, the player will continue to use the old one to request keys after it expires. If the STS credential becomes invalid, this may cause playback failure or corrupted video output.mAliyunVodPlayer.updateStsInfo(stsInfo);
Third-party DRM encryption
This feature requires player SDK V7.8.0 or later.
UrlSource
-
This feature supports only the Widevine DRM scheme for the HLS and DASH protocols.
-
The VOD Packaging feature is available in the Intelligent Media Service console on the Alibaba Cloud International site only.
When you play a DRM-encrypted video by using the UrlSource method, in addition to the configurations for a normal video, you must also implement the DrmCallback interface to obtain the key information for the video.
// Implement the DrmCallback.requestKey interface to obtain the key by following the documentation of your third-party DRM provider.
// The following example shows how to retrieve a key from PallyCon. For more information, see https://pallycon.com/docs/en/multidrm.
player.setDrmCallback(new DrmCallback() {
@Override
public byte[] requestKey(byte[] data) {
// Request the key information by using an HTTP POST request, as required by the DRM provider.
String licenseUrl = "https://license-global.pallycon.com/ri/licenseManager.do";
String[] header = {
// Replace TOKEN_ID with your own.
"pallycon-customdata-v2: TOKEN_ID"
};
// Avoid blocking this thread for too long.
byte[] response = async_http_post(licenseUrl, header, data);
if (response != null) {
// If the response_format of the token is set to 'original', return the response directly. Otherwise, you must parse the response before returning it.
// For more information, see https://pallycon.com/docs/en/multidrm/license/license-token/#token-json.
// The format and structure of the response can vary significantly between providers. Review it carefully. If the response cannot be used for decryption, the player reports an error through the onError callback.
return response;
} else {
// Handle exceptions. The player calls onError and reports the relevant error.
return null;
}
}
});
iOS
Procedure
Integrate Player SDK for iOS into your application. The steps and sample code are as follows:
-
Integrate Player SDK for iOS.
-
Create a player to load and play videos.
Follow Basic Features. In Step 3. Create a data source, use one of the following methods based on your requirements.
Alibaba Cloud private encryption
VidAuth for VOD
When you play a privately encrypted HLS or MP4 video by using the VidAuth method of ApsaraVideo VOD, if the video also has non-encrypted or standard transcoded streams, set the encryption type to AliyunVoDEncryption to play only the privately encrypted stream.
AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Your video ID"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. You can obtain this credential by calling the GetVideoPlayAuth operation of ApsaraVideo VOD.
authSource.region = @"Your region"; // This parameter is deprecated in Player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically parses it. For SDK versions earlier than 5.5.5.0, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVoDEncryption"]; // Optional. If you set the encryption type to AliyunVoDEncryption, only privately encrypted video streams are returned.
authSource.playConfig = [config generatePlayerConfig];
[self.player setAuthSource:authSource];
VidSts for VOD
When you play a privately encrypted HLS or MP4 video by using the VidSts method of ApsaraVideo VOD, if the video also has non-encrypted or standard transcoded streams, set the encryption type to AliyunVoDEncryption to play only the privately encrypted stream.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Your region"; // Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.vid = @"Your video ID"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The security token. You can obtain this token by calling the AssumeRole operation of STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVoDEncryption"]; // Optional. If you set the encryption type to AliyunVoDEncryption, only privately encrypted video streams are returned.
source.playConfig = [config generatePlayerConfig];
// Set the playback source.
[self.player setStsSource:source];
LiveStsSource for live
To play a privately encrypted live stream in HLS or FLV format by using the LiveStsSource method, you must provide the stream URL and an STS credential, and set the video encryption type to ENCRYPTION_TYPE_ALIVODENCRYPTION. The following code provides an example:
-
Create a data source.
You must pass
AVPLiveStsSourceas the playback source.// Create a LiveSts object and set encryptionType to ENCRYPTION_TYPE_ALIVODENCRYPTION. AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Encrypted live stream URL" accessKeyId:@"Temporary AccessKey ID" accessKeySecret:@"Temporary AccessKey secret" securityToken:@"Security token" region:@"Region value" domain:@"Streaming domain for the URL" app:@"Application name for streaming" stream:@"Stream name for streaming" encryptionType:ENCRYPTION_TYPE_ALIVODENCRYPTION];// Required. Set the encryption type to ENCRYPTION_TYPE_ALIVODENCRYPTION. // Set the playback source. [self.aliPlayer setLiveStsSource:liveStsSource]; ...... // Prepare for playback. [self.aliPlayer prepare]; -
Listen for STS credential invalidation.
During encrypted live playback, the encryption key may be rotated. When this occurs, the player uses the STS credential to request the new key. You must monitor the credential's validity because an invalid credential disrupts playback.
__weak typeof(self) weakSelf = self; [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) { if (info is valid) { return Valid; } if (a valid STS credential can be obtained) { getSTS(); // This can be an asynchronous or synchronous operation. return Pending; } [weakSelf.aliPlayer stop]; return Invalid; }];NoteAfter you obtain a new STS credential, you must call the
updateLiveStsInfomethod to update it. If the attempt to obtain a new credential fails, we recommend that you stop the playback. If you do not update the STS credential, the player attempts to use the expired credential to request the key, which can cause screen artifacts or playback failure.[self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];
Alibaba Cloud license-based private encryption
UrlSource for VOD
Only Player SDK for iOS V6.8.0 and later supports playing license-based privately encrypted MP4 videos by using UrlSource. V6.17.0 and later supports license-based privately encrypted HLS videos with single and adaptive bitrates.
To play a license-based privately encrypted HLS or MP4 video by using the UrlSource method, you can call the GetPlayInfo operation to obtain the playback URL of the video. After you obtain the video URL, you must append the etavirp_nuyila=1 parameter to the URL before passing it to the player. You can place this parameter anywhere in the query string. This parameter is required only for MP4 videos. For HLS videos, you can use the original video URL. The player configuration is the same as that for playing a standard video. No additional parameters are required.
Playback URL Example 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Playback URL example 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// Playback URL
NSString *playURL = @"https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1";
// Player
AliPlayer *player = [[AliPlayer alloc] init];
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:playURL]; // Required. The playback URL of the video. You can call the GetPlayInfo operation to obtain the URL. For MP4 videos, you must append `etavirp_nuyila=1` to the URL. Example: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
[player setUrlSource:urlSource];
[player prepare];
// List player
AliListPlayer *listPlayer = [[AliListPlayer alloc] init];
[listPlayer addUrlSource:playURL uid:UUIDString];
[listPlayer moveTo:@"uid"];
// Preload
AliMedialoader *mediaLoader = [AliMediaLoader shareInstance];
[mediaLoader load:playURL duration:1000];
HLS standard encryption
VidAuth for VOD
When you play a video that is encrypted by using HLS standard encryption with the VidAuth method of ApsaraVideo VOD, if the video also has non-encrypted or standard transcoded streams, set the encryption type to HLSEncryption to play only the stream with HLS standard encryption. The following code provides an example:
If you enabled M3U8 standard encryption rewriting, you must call setHlsUriToken to set the user token.
AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Your video ID"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. You can obtain this credential by calling the GetVideoPlayAuth operation of ApsaraVideo VOD.
authSource.region = @"Your region"; // This parameter is deprecated in Player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically parses it. For SDK versions earlier than 5.5.5.0, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set this parameter to HLSEncryption, only video streams that are encrypted by using HLS standard encryption are returned.
[config setHlsUriToken: @"token"]; // Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
source.playConfig = [config generatePlayerConfig];
// Set the playback source.
[self.player setAuthSource:authSource];
VidSts for VOD
When you play a video that is encrypted by using HLS standard encryption with the VidSts method of ApsaraVideo VOD, if the video also has non-encrypted or standard transcoded streams, set the encryption type to HLSEncryption to play only the stream with HLS standard encryption. The following code provides an example:
If you enabled M3U8 standard encryption rewriting, you must call setHlsUriToken to set the user token.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.vid = @"Your video ID"; // Required. The video ID.
source.region = @"Your region"; // Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.securityToken = @"<yourSecurityToken>"; // Required. The security token. You can obtain this token by calling the AssumeRole operation of STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set this parameter to HLSEncryption, only video streams that are encrypted by using HLS standard encryption are returned.
[config setHlsUriToken: @"token"]; // Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
source.playConfig = [config generatePlayerConfig];
// Set the playback source.
[self.player setStsSource:source];
UrlSource
When using the UrlSource method to play a stream with HLS standard encryption, the player configuration is the same as that for playing a standard video. No additional parameters are required.
We recommend that you use ApsaraVideo VOD. You can call the GetPlayInfo operation to obtain the playback URL of the video and pass the URL to the player.
If you enabled M3U8 standard encryption rewriting, you must append MtsHlsUriToken=<token> to the video URL before you pass it to the player. You can place this parameter anywhere in the query string.
Example of an original playback URL: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Example URL to enter in the player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // The playback URL of the live or on-demand stream with HLS standard encryption.
[self.player setUrlSource:urlSource];
Alibaba Cloud DRM encryption
On the iOS platform, you must make a one-time global call to the setFairPlayCertID method in AliPlayerGlobalSettings before [self.player prepare] to set the certificate ID. You can obtain the certificate ID in ApsaraVideo VOD console > Configuration Management > Media Processing Configuration > DRM Certificate Management.
[AliPlayerGlobalSettings setFairPlayCertID:@"Your certificate ID obtained from the console"];
VidSts for VOD
First, refer to Configure DRM Encryption for VOD to configure DRM encryption. When you play a DRM-encrypted video by using the VidSts method of ApsaraVideo VOD, the configuration is the same as that for playing a standard video. No additional parameters are required.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Your region"; // Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.vid = @"Your video ID"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The security token. You can obtain this token by calling the AssumeRole operation of STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Set the playback source.
[self.player setStsSource:source]
LiveStsSource for live
First, refer to Configure DRM Encryption for Live Streaming to configure DRM encryption. To play a DRM-encrypted live stream by using the LiveStsSource method, you must provide the stream URL and an STS credential, and set the video encryption type to ENCRYPTION_TYPE_FAIRPLAY. The following code provides an example:
-
Create a data source.
You must pass
AVPLiveStsSourceas the playback source.// Create a LiveSts object and set encryptionType to ENCRYPTION_TYPE_FAIRPLAY. AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Encrypted live stream URL" accessKeyId:@"Temporary AccessKey ID" accessKeySecret:@"Temporary AccessKey secret" securityToken:@"Security token" region:@"Region value" domain:@"Streaming domain for the URL" app:@"Application name for streaming" stream:@"Stream name for streaming" encryptionType:ENCRYPTION_TYPE_FAIRPLAY];// Required. Set the encryption type to ENCRYPTION_TYPE_FAIRPLAY. // Set the playback source. [self.aliPlayer setLiveStsSource:liveStsSource]; ...... // Prepare for playback. [self.aliPlayer prepare]; -
Listen for STS credential invalidation.
During encrypted live playback, the encryption key may be rotated. When this occurs, the player uses the STS credential to request the new key. You must monitor the credential's validity because an invalid credential disrupts playback.
__weak typeof(self) weakSelf = self; [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) { if (info is valid){ return Valid; } if(a valid STS credential can be obtained){ getSTS(); // This can be an asynchronous or synchronous operation. return Pending; } [weakSelf.aliPlayer stop]; return Invalid; }];NoteAfter you obtain a new STS credential, you must call the
updateLiveStsInfomethod to update it. If the attempt to obtain a new credential fails, we recommend that you stop the playback. If you do not update the STS credential, the player attempts to use the expired credential to request the key, which can cause screen artifacts or playback failure.[self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];
Third-party DRM encryption
-
This feature requires Player SDK V7.8.0 or later.
-
You must use AppleAVPlayer to play FairPlay-encrypted videos. Before playback starts, call
[self.player setPreferPlayerName:@"AppleAVPlayer"]to switch the player core. When you play videos that are not DRM-encrypted, you must call[self.player setPreferPlayerName:@""]to restore the default core.
UrlSource for FairPlay
-
Only the FairPlay scheme over the HLS protocol is supported.
-
The live packaging feature is available on the ApsaraVideo for Media Processing console on the Alibaba Cloud International site (alibabacloud.com) only.
When you play a DRM-encrypted video by using the UrlSource method, in addition to using the same configuration as for a regular video, you must also implement the AVPDrmDelegate interface to obtain the FairPlay certificate and the video key.
@interface SimplePlayerViewController()<AVPDrmDelegate>
@end
- (void)viewDidLoad {
self.player = [[AliPlayer alloc] init];
self.player.playerView = self.avpPlayerView.playerView;
self.player.drmDelegate = self;
if(the current URL is for a third-party DRM video){
[self.player setPreferPlayerName:@"AppleAVPlayer"];
}
//...
}
// Implement the AVPDrmDelegate.requestCert and requestKey interfaces. Obtain the certificate and key by following the documentation from your third-party DRM provider.
// The following example shows how to obtain a certificate and key from PallyCon. For more information, see https://pallycon.com/docs/en/multidrm.
#pragma mark AVPDrmDelegate
- (NSData *)requestCert:(AliPlayer *)player {
// You can also pre-fetch and cache the certificate to reduce startup latency. If you do, return the cached certificate here.
// If the certificate data is invalid, the player reports an error. You can also check the console for more error information.
// Replace SITE_ID with your own site ID.
const char* url = "https://license.pallycon.com/ri/fpsKeyManager.do?siteId=SITE_ID";
// Request the FairPlay certificate by using an HTTP GET request as required by the DRM provider.
// Avoid blocking this thread for an extended period.
NSData* responseData = [self performAsyncHttpGet:url];
if (!responseData) {
// Handle the exception. The player will report an error.
return nil;
}
// The response data must be Base64-decoded before being returned to the player.
NSString *base64String = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
return [self decodeBase64String:base64String];
}
- (NSData *)requestKey:(AliPlayer *)player data:(NSData *)data {
// Request the key information by using an HTTP POST request as required by the DRM provider.
NSString *urlString = [NSString stringWithFormat:@"https://license-global.pallycon.com/ri/licenseManager.do"];
const char *url = [urlString UTF8String];
// Replace TOKEN_ID with your own token ID.
NSString *headerString = [NSString stringWithFormat:@"pallycon-customdata-v2: TOKEN_ID"];
const char* headers[] = {
[headerString UTF8String]
};
int headerCount = sizeof(headers) / sizeof(headers[0]);
// Avoid blocking this thread for an extended period.
NSData* responseData = [self performAsyncHttpPost:url
headers:headers
headerCount:headerCount
data:data];
if (!responseData) {
// Handle the exception. The player will report an error.
return nil;
}
// If your token's response_format is set to `original`, return the response directly. Otherwise, you must parse the response before returning it.
// For more information, see https://pallycon.com/docs/en/multidrm/license/license-token/#token-json.
// The format and structure of the response can vary significantly among providers. Check the response carefully. If the response cannot be used for decryption, the player reports an error.
return [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}
Flutter client
The Flutter client does not support DRM encryption.
Procedure
Integrate the Flutter player into your application. The steps and sample code are as follows:
-
Integrate the Alibaba Cloud Player SDK for Flutter.
-
Create a player to play videos.
Follow Basic Features. In Step 3. Create a play source, select one of the following methods.
Alibaba Cloud Video Encryption (private encryption)
VidAuth
When playing a privately encrypted HLS or MP4 video with the VidAuth method for ApsaraVideo for VOD, if the video also contains non-encrypted or standard transcoded streams, set the encryption type to AliyunVoDEncryption to play only the privately encrypted stream.
FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption); // Optional. If you set this to AliyunVoDEncryption, only privately encrypted video streams are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidAuth(
vid: "The video ID",
region: "The region ID", // Required. The region where ApsaraVideo for VOD is activated. Default: cn-shanghai.
playAuth: "<yourPlayAuth>", // Required. The PlayAuth. Obtain it by calling the GetVideoPlayAuth operation for ApsaraVideo for VOD.
playConfig: value);
});
VidSts
When playing a privately encrypted HLS or MP4 video with the VidSts method for ApsaraVideo for VOD, if the video also contains non-encrypted or standard transcoded streams, set the encryption type to AliyunVoDEncryption to play only the privately encrypted stream.
FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption); // Optional. If you set this to AliyunVoDEncryption, only privately encrypted video streams are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidSts(
vid: "The video ID",
region: "The region ID",
accessKeyId: "<yourAccessKeyId>",
accessKeySecret: "<yourAccessKeySecret>",
securityToken: "<yourSecurityToken>",
playConfig: value);
});
License-based private encryption
UrlSource
The Flutter player SDK supports license-based private encryption with UrlSource for MP4 videos in v6.8.0 and later, and for HLS videos (single-bitrate and adaptive-bitrate) in v6.17.0 and later.
When you play a video in HLS or MP4 format that is encrypted by using license-based private encryption with UrlSource-based playback, call the Obtain audio or video playback URL operation to obtain the playback URL. You must append etavirp_nuyila=1 to the obtained URL before you pass it to the player. (This parameter is required only for MP4 files. For HLS files, you can use the original video URL directly.) The player SDK configuration is the same as that for a standard video, and no additional parameters are required.
Example playback URL 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Example playback URL 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// Playback URL.
String playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1"
// Create a player instance.
FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
fAliplayer.setUrl(playURL);
fAliplayer.prepare();
// List player.
FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer();
fAliListPlayer.addUrlSource(playURL,uid);
fAliListPlayer.moveTo("uid");
// Preload.
FlutterAliPlayerMediaLoader fAliPlayerMediaLoader = FlutterAliPlayerMediaLoader();
fAliPlayerMediaLoader.load(playURL,"duration");
HLS standard encryption
VidAuth
When playing an HLS standard encrypted video with the VidAuth method for ApsaraVideo for VOD, if the video also contains streams with other encryption types or non-encrypted transcoded streams, you can set the encryption type to HLSEncryption to play only the HLS standard encrypted stream. The following code is an example:
If M3U8 Standard Encryption Rewrite is enabled, you must call setHlsUriToken to pass the user token.
FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption); // Optional. Set to HLSEncryption to return only HLS standard encrypted video streams.
FlutterAliplayer.setHlsUriToken("token"); // Optional. If you need to validate the MtsHlsUriToken, use this parameter to pass the token.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidAuth(
vid: "The video ID",
region: "The region ID", // Required. The region where ApsaraVideo for VOD is activated. Default: cn-shanghai.
playAuth: "<yourPlayAuth>", // Required. The PlayAuth. Obtain it by calling the GetVideoPlayAuth operation for ApsaraVideo for VOD.
playConfig: value);
});
VidSts
When playing an HLS standard encrypted video with the VidSts method for ApsaraVideo for VOD, if the video also contains streams with other encryption types or non-encrypted transcoded streams, you can set the encryption type to HLSEncryption to play only the HLS standard encrypted stream. The following code is an example:
If M3U8 Standard Encryption Rewrite is enabled, you must call setHlsUriToken to pass the user token.
FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption); // Optional. If you set this to AliyunVoDEncryption, only privately encrypted video streams are returned.
FlutterAliplayer.setHlsUriToken("token"); // Optional. If you need to validate the MtsHlsUriToken, use this parameter to pass the token.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidSts(
vid: "The video ID",
region: "The region ID",
accessKeyId: "<yourAccessKeyId>",
accessKeySecret: "<yourAccessKeySecret>",
securityToken: "<yourSecurityToken>",
playConfig: value);
});
UrlSource
When you use the UrlSource method to play a live or on-demand stream with HLS standard encryption, the player SDK configuration is the same as for a standard video.
To obtain the playback URL, we recommend calling the GetPlayInfo operation in ApsaraVideo for VOD.
After M3U8 Standard Encryption Rewrite is enabled, you must append the MtsHlsUriToken=<token> parameter to the playback URL before passing it to the player. This parameter can be placed anywhere in the URL's query string.
Original playback URL example: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Example of a URL to pass to the player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
// Create a player instance.
FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
// The playback URL is for an HLS standard encrypted live or on-demand stream.
fAliplayer.setUrl("The playback URL");
fAliplayer.prepare();
Harmony
Procedure
Integrate the Harmony player into your app. The following sections provide the steps and sample code.
-
Integrate the Alibaba Cloud Player SDK for Harmony.
-
Create a player to play a video.
Follow Basic Features. In Step 3. Set the playback method, select a method based on your requirements.
Proprietary encryption
VidAuth (HLS/MP4)
When you play a proprietarily encrypted HLS or MP4 video from ApsaraVideo VOD with the VidAuth method, if the video also contains other types of encrypted streams or standard transcoded streams, you can set the encryption type to AliyunVoDEncryption to filter and play only the proprietarily encrypted stream.
const vidAuth: VidAuth = new VidAuth()
const vidPlayerConfigGen: VidPlayerConfigGen = new VidPlayerConfigGen()
vidPlayerConfigGen.setEncryptType(EncryptType.AliyunVodEncryption)// Optional. Set the encryption type to `AliyunVoDEncryption` to return only the proprietarily encrypted video streams.
vidAuth.setPlayerConfig(vidPlayerConfigGen)
vidAuth.setVid("Vid information")// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>")// Required. The playback credential. Obtain this by calling the `GetVideoPlayAuth` operation of ApsaraVideo VOD.
vidAuth.setRegion("Region")// Required for player SDKs earlier than v5.5.5.0. This parameter is deprecated in v5.5.5.0 and later because the player automatically resolves the region.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL, in seconds. This value overrides the URL authentication validity period set in the ApsaraVideo VOD console. If this parameter is not set, the default value is 3600. If you set this parameter, ensure the value is greater than the video duration to prevent the playback URL from expiring mid-playback.
aliPlayer.setVidAuthDataSource(vidAuth)
VidSts (HLS/MP4)
When you play a proprietarily encrypted HLS or MP4 video from ApsaraVideo VOD with the VidSts method, if the video also contains other types of encrypted streams or standard transcoded streams, you can set the encryption type to AliyunVoDEncryption to filter and play only the proprietarily encrypted stream.
const vidSts: VidSts = new VidSts()
const vidPlayerConfigGen: VidPlayerConfigGen = new VidPlayerConfigGen()// Optional. Set the encryption type to `AliyunVoDEncryption` to return only the proprietarily encrypted video streams.
vidPlayerConfigGen.setEncryptType(EncryptType.AliyunVodEncryption)
vidSts.setPlayerConfig(vidPlayerConfigGen)
vidSts.setVid("Vid information")// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>")// Required. The AccessKey ID of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>")// Required. The AccessKey Secret of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
vidSts.setSecurityToken("<yourSecurityToken>")// Required. The security token of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
vidSts.setRegion("Region")// Required. The region for ApsaraVideo VOD. Default: `cn-shanghai`.
// vidSts.setAuthTimeout(3600)// Optional. The validity period of the playback URL, in seconds. This value overrides the URL authentication validity period set in the ApsaraVideo VOD console. If this parameter is not set, the default value is 3600. If you set this parameter, ensure the value is greater than the video duration to prevent the playback URL from expiring mid-playback.
aliPlayer.setVidStsDataSource(vidSts)
LiveStsSource (HLS/FLV)
To play a proprietarily encrypted HLS or FLV live stream with the LiveStsSource method, you must provide the playback URL and STS credentials, and set the video encryption type to LiveEncryptionType.AliEncryption.
You must pass LiveSts as the data source.
// Create LiveSts. EncryptionType must be set to AliEncryption.
const liveSts: LiveSts = new LiveSts()
LiveSts.setUrl("<your live stream url>")// Required. The playback URL of the proprietarily encrypted HLS live stream.
LiveSts.setAccessKeyId("<your AccessKey ID>")// Required. The AccessKey ID of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
LiveSts.setAccessKeySecret("<your AccessKey Secret>")// Required. The AccessKey Secret of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
LiveSts.setSecurityToken("<your STS token>")// Required. The security token of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
LiveSts.setDomain("<your Domain>")// Required. The streaming domain of the live stream.
LiveSts.setApp("<your App Name>")// Required. The app name for the live stream.
LiveSts.setStream("<your Stream Name>")// Required. The stream name for the live stream.
LiveSts.setEncryptionType(LiveEncryptionType.AliEncryption)// Required. The encryption type. Must be `AliEncryption`.
LiveSts.setRegion("<region of your video>")// Required. The region, such as `cn-shanghai`.
// Set the data source
aliPlayer.setLiveStsDataSource(LiveSts)
// Prepare for playback
aliPlayer.prepare()
License-based proprietary encryption
UrlSource (HLS/MP4)
When you use UrlSource-based playback for an HLS or MP4 video that is encrypted by using license-based private encryption, call the Obtain audio/video playback URL API to retrieve the playback URL. You must append etavirp_nuyila=1 to the URL before you pass it to the player. This parameter is required only for MP4 videos. For HLS videos, you can use the original video URL directly. The configuration for the ApsaraVideo Player SDK is the same as that for playing a standard video, and no additional parameters are required.
Sample playback URL 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Sample playback URL 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// The playback URL
let playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1"
// The player
let urlSource: UrlSource = new UrlSource()
urlSource.setUri(playURL)
aliPlayer.setUrlDataSource(urlSource)
aliPlayer.prepare();
// Preload
loader: MediaLoader = MediaLoader.getInstance()
mediaLoader.load(playURL,"duration")
HLS standard encryption
VidAuth
When you play a video with HLS standard encryption from ApsaraVideo VOD with the VidAuth method, if the video also contains other types of encrypted streams or standard transcoded streams, you can set the encryption type to HLSEncryption to filter and play only the HLS standard encrypted stream. The following sample code shows how to do this:
After you enable M3U8 Standard Encryption Rewrite, you need to call setMtsHlsUriToken to set the user token.
const vidAuth: VidAuth = new VidAuth()
const vidPlayerConfigGen: VidPlayerConfigGen = new VidPlayerConfigGen()
vidPlayerConfigGen.setMtsHlsUriToken("token")// Optional. Use this parameter to pass the MtsHlsUriToken (user token) if validation is required.
vidPlayerConfigGen.setEncryptType(EncryptType.HLSEncryption)// Optional. Set the encryption type to `HLSEncryption` to return only the HLS standard encrypted video streams.
vidAuth.setPlayerConfig(vidPlayerConfigGen)
vidAuth.setVid("Vid information")// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>")// Required. The playback credential. Obtain this by calling the `GetVideoPlayAuth` operation of ApsaraVideo VOD.
vidAuth.setRegion("Region")// Required for player SDKs earlier than v5.5.5.0. This parameter is deprecated in v5.5.5.0 and later because the player automatically resolves the region.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL, in seconds. This value overrides the URL authentication validity period set in the ApsaraVideo VOD console. If this parameter is not set, the default value is 3600. If you set this parameter, ensure the value is greater than the video duration to prevent the playback URL from expiring mid-playback.
aliPlayer.setVidAuthDataSource(vidAuth)
VidSts
When you play a video with HLS standard encryption from ApsaraVideo VOD with the VidSts method, if the video also contains other types of encrypted streams or standard transcoded streams, you can set the encryption type to HLSEncryption to filter and play only the HLS standard encrypted stream. The following sample code shows how to do this:
If you enable M3U8 Standard Encryption Rewrite, you need to call setMtsHlsUriToken to set the user token.
const vidSts: VidSts = new VidSts()
const vidPlayerConfigGen: VidPlayerConfigGen = new VidPlayerConfigGen()// Optional. Set the encryption type to `HLSEncryption` to return only the HLS standard encrypted video streams.
vidPlayerConfigGen.setMtsHlsUriToken("token")
vidPlayerConfigGen.setEncryptType(EncryptType.HLSEncryption)
vidSts.setPlayerConfig(vidPlayerConfigGen)
vidSts.setVid("Vid information")// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>")// Required. The AccessKey ID of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>")// Required. The AccessKey Secret of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
vidSts.setSecurityToken("<yourSecurityToken>")// Required. The security token of the temporary credential from Security Token Service (STS). To obtain it, call the STS `AssumeRole` operation.
vidSts.setRegion("Region")// Required. The region for ApsaraVideo VOD. Default: `cn-shanghai`.
// vidSts.setAuthTimeout(3600)// Optional. The validity period of the playback URL, in seconds. This value overrides the URL authentication validity period set in the ApsaraVideo VOD console. If this parameter is not set, the default value is 3600. If you set this parameter, ensure the value is greater than the video duration to prevent the playback URL from expiring mid-playback.
aliPlayer.setVidStsDataSource(vidSts)
UrlSource
When playing a live or on-demand stream with HLS standard encryption with UrlSource, the player SDK configuration is the same as for a standard video, and no additional parameters are required.
For videos hosted on ApsaraVideo VOD, call the GetPlayInfo operation to obtain the playback URL.
If you enabled the M3U8 Standard Encryption Rewrite feature, you must append MtsHlsUriToken=<token> to the playback URL before you pass it to the player. The position of this parameter in the query string does not matter.
Original playback URL sample: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Example player URL: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
// The player
let urlSource: UrlSource = new UrlSource()
// The playback URL of a live or on-demand stream with HLS standard encryption.
urlSource.setUri("The playback URL")
aliPlayer.setUrlDataSource(urlSource)
FAQ
Common issues and solutions: Video Encryption FAQ.