All Products
Search
Document Center

ApsaraVideo VOD:Play encrypted videos

Last Updated:Nov 27, 2025

ApsaraVideo VOD and ApsaraVideo Live provide multiple video encryption methods that you can use with the ApsaraVideo Player SDK to decrypt and play videos. This method effectively prevents hotlinking, illegal downloads, and unauthorized distribution of your video content. This topic describes how to use the ApsaraVideo Player SDK to play videos that are encrypted using Alibaba Cloud proprietary encryption, HLS encryption, or Digital Rights Management (DRM) encryption.

Introduction to video encryption

ApsaraVideo VOD provides a comprehensive content security mechanism to prevent hotlinking, illegal downloads, and unauthorized distribution of video content. This security mechanism includes measures such as access control, URL signing, remote authentication, video encryption, and secure downloads.

For more information about security mechanisms such as access control, URL signing, and remote authentication, see Overview of video security. This topic focuses on playing videos that use three types of encryption. The following table describes the three encryption types.

Security mechanism

Security method

Features

Security level

Ease of use

Video encryption

Alibaba Cloud proprietary encryption

A cloud-native video encryption solution that uses a proprietary encryption algorithm and ensures secure transmission.

High

Low. Requires simple configuration and integration with ApsaraVideo Player.

HLS encryption

A universal HTTP Live Streaming (HLS) encryption solution that uses AES-128 to encrypt content. It is compatible with all HLS players, but the key can be easily stolen.

High

High. You must build your own key management and token issuance services and ensure secure transmission.

Commercial DRM

Native support for Apple FairPlay and Google Widevine. It provides a high level of security and meets the requirements of most copyright content providers.

High

High. Billed based on the number of license requests. For third-party DRM encryption, see the billing standards of the third-party service. Requires integration with ApsaraVideo Player SDK.

ApsaraVideo Player SDK compatibility for encrypted playback

Note
  1. Before you use the ApsaraVideo Player SDK for web to play encrypted videos, you must understand its compatibility with different browsers and encryption features. For example, the ApsaraVideo Player SDK for web supports playing videos that use proprietary encryption on mainstream mobile browsers. For more information, see Browser compatibility and Feature compatibility. ✔️ indicates that the feature is supported, and ❌ indicates that the feature is not supported.

  2. You can download the latest version of the ApsaraVideo Player SDK to ensure feature compatibility. For more information, see SDK overview.

  3. Note: The container format for HLS is M3U8.

Terminal

Playback method

Proprietary encryption (HLS)

License-based proprietary encryption (HLS)

License-based proprietary encryption (MP4)

Proprietary encryption (Live FLV)

HLS encryption

Alibaba Cloud DRM encryption

Third-party DRM encryption

Web

VOD UrlSource

✔️

✔️

VOD VidAuth

✔️

✔️

VOD VidSts

✔️

✔️

Live UrlSource

✔️

✔️

Live LiveStsSource

✔️

✔️

✔️

Native (iOS/Android/Flutter)

VOD UrlSource

✔️

✔️

Requires SDK V6.17.0 or later.

✔️

Requires SDK V6.8.0 or later.

✔️

✔️

Requires SDK V7.8.0 or later. Flutter is not supported.

VOD VidAuth

✔️

✔️

✔️

VOD VidSts

✔️

✔️

✔️

✔️

Flutter is not supported.

Live UrlSource

✔️

✔️

Requires SDK V7.8.0 or later. Flutter is not supported.

Live LiveStsSource

✔️

✔️

✔️

✔️

Flutter is not supported.

Encryption methods

Alibaba Cloud proprietary encryption

Alibaba Cloud proprietary encryption encrypts video data. Even if a video is downloaded locally, the video remains encrypted. This method effectively prevents malicious redistribution, leaks, and hotlinking. For more information, see Alibaba Cloud proprietary encryption.

The ApsaraVideo Player SDK encapsulates the decryption logic and server-side interactions. You can implement encrypted playback at a low cost by configuring encrypted transcoding and integrating the player.

Important
  • Alibaba Cloud proprietary encryption is a free service, but it requires video transcoding. Fees are incurred for transcoding operations. For more information about billing, see Media transcoding billing.

Configure proprietary encryption

For more information about the procedure and configurations for Alibaba Cloud proprietary encryption, see How to use.

Limits

Alibaba Cloud proprietary encryption supports HLS, FLV, and MP4 videos. You can play these encrypted videos only using the ApsaraVideo Player. On the web, only HLS playback is supported. On native clients, playback in all formats is supported.

Alibaba Cloud license-based proprietary encryption

Alibaba Cloud license-based proprietary encryption builds on proprietary encryption to ensure playback security. It accelerates playback startup by allowing direct playback from an encrypted video URL. This method is suitable for short videos and short video series.

Important
  • Alibaba Cloud license-based proprietary encryption is a free service, but it requires video transcoding. Fees are incurred for transcoding operations. For more information about billing, see Media transcoding billing.

Configure proprietary encryption

For more information about the procedure and configurations for Alibaba Cloud proprietary encryption, see How to use.

Limits

Alibaba Cloud license-based proprietary encryption supports HLS and MP4 videos. You can play these encrypted videos only using the ApsaraVideo Player.

HLS encryption

HLS encryption uses AES-128 to encrypt video content. It is compatible with all HLS players, including self-developed or open-source players. This method provides high flexibility but also has a higher barrier to entry and lower security. For more information, see HLS encryption.

Important

HLS encryption is a free service, but it requires video transcoding. Fees are incurred for transcoding operations. For more information about billing, see Media transcoding billing.

Configure HLS encryption

For more information about the procedure and configurations for HLS encryption, see Integration procedure.

Limits

HLS encryption is compatible with various HLS players. You can choose your own player. This topic uses the ApsaraVideo Player as an example to show how to play HLS-encrypted videos. The ApsaraVideo Player supports token passing. Alibaba Cloud CDN dynamically adjusts the decryption URI in the HLS file and includes the user token for your business to authenticate.

Alibaba Cloud DRM encryption

ApsaraVideo VOD supports industry-standard DRM encryption. This feature allows for one-stop management of copyrighted videos and is compatible with Widevine and FairPlay solutions. For more information, see DRM encryption.

Important

DRM encryption is implemented through transcoding. Fees are incurred only for transcoding when the video is output. No DRM encryption fees are generated at this stage. DRM encryption fees are incurred when a terminal requests to play a DRM-encrypted video. The playback client is billed based on the number of license requests for the video. For more information about billing, see DRM billing.

Configure DRM encryption

You can enable DRM encryption in the ApsaraVideo Live and ApsaraVideo VOD consoles. For more information, see Configure DRM encryption for live streaming and Configure DRM encryption for VOD.

Limits

Videos encrypted with DRM can be played only using the ApsaraVideo Player.

Third-party DRM encryption

ApsaraVideo VOD supports industry-standard DRM encryption. It provides end-to-end support from video production in Intelligent Media Services and third-party DRM encryption to decryption and playback with the ApsaraVideo Player SDK.

Important

DRM encryption is implemented through transcoding. Fees are incurred only for transcoding when the video is output. No DRM encryption fees are generated at this stage. DRM encryption fees are incurred when a terminal requests to play a DRM-encrypted video. The playback client is billed based on the number of license requests for the video. For more information about billing, see DRM billing.

Configure DRM encryption

You can enable this feature in the Intelligent Media Services console. For more information, see Live packaging and VOD packaging.

Web

Note
  • Before you use the ApsaraVideo Player SDK for web, you must understand its compatibility with different browsers and its support for playing videos that use Alibaba Cloud proprietary encryption. The details are as follows:

  • For security reasons, you cannot use real encrypted videos for debugging with Alibaba Cloud proprietary encryption.

Procedure

You can embed the ApsaraVideo Player in your webpage to play videos.

  1. For more information about how to import the ApsaraVideo Player SDK for web into your page, see Quick integration.

  2. Select an encryption method and start playback.

    You can embed the ApsaraVideo Player SDK for web in your webpage to play videos. The following code provides an example.

Alibaba Cloud proprietary encryption

Proprietary encrypted playback - VOD VidAuth playback (HLS)

When you play a proprietary encrypted video using the VOD VidAuth method, you must set the encryptType parameter to 1 to enable proprietary encryption. This is not required for playing regular 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 encrypted 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. You can obtain the video ID in the ApsaraVideo VOD console. Go to Media Assets > Audio/Video. Example: 1e067a2831b641db90d570b6480f****.
                playauth : '<your PlayAuth>',// Required. You can call the GetVideoPlayAuth operation to obtain the value of this parameter.
                encryptType: 1, // Required. Set this parameter to 1 to play a proprietary encrypted stream. You do not need to set this parameter in other cases.
                playConfig:{EncryptType:'AliyunVoDEncryption'}, // Specify this parameter if your output M3U8 stream contains other non-proprietary encrypted streams.
                // authTimeout: 7200, // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set in the ApsaraVideo VOD console. If you do not set this parameter, the default value 7200 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 playback is complete.
              },function(player){
                console.log('The player is created.')
             });
          </script>
      </body>
  </html>

Proprietary encrypted playback - Live LiveStsSource playback (HLS)

To play a proprietary encrypted video using the LiveStsSource method, you must pass the URL and STS temporary credentials. For more information about how to generate STS temporary credentials, see Obtain an STS token. The following code provides an example.

<!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 encrypted 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%',
               isLive: true, // Set to true for live streaming.
               source: '<your live stream url>',// Required. The playback URL of the proprietary encrypted HLS live stream.
               accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
               accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
               securityToken: '<your STS token>',// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
               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 live stream.
               regionId: '<region of your video>',// Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
             },function(player){
               console.log('The player is created.')
            });
         </script>
     </body>
 </html>
Note
  • To support proprietary encrypted VOD playback on browsers for iOS versions earlier than 17.1, you must deploy an additional player plugin script. The steps are as follows:

    How it works: Proprietary encryption for iOS versions earlier than 17.1 requires an additional plugin that uses Service Worker technology. Because of browser security policies, a website can only access service worker scripts that are from the same origin as the website. Therefore, you must deploy the player plugin script to the same domain as your website.

    1. Download the script from the following URL: https://g.alicdn.com/apsara-media-box/imp-web-player/<version number>/aliplayer-worker-min.js

    2. Deploy the script. For example, if your website for playing proprietary encrypted videos is https://www.aliyun.com/a/b.html, you must deploy the script to https://www.aliyun.com/a/aliplayer-worker-min.js. This means the script must be in the same directory as the current website.

    3. Pass this URL when you initialize the player:

      new Aliplayer({
        // ...Other parameters
        swScriptURL: 'https://www.aliyun.com/a/aliplayer-worker-min.js' // Enter the full URL of the plugin script. Make sure that this URL is accessible.
      })

    Note: Make sure that the player version and the plugin version are the same.

  • If your webpage runs in a custom-packaged iOS application, such as a uni-app application, you must add your website domain to WKAppBoundDomains in the application's Info.plist file. This enables the Service Worker feature in WKWebView. For more information, see App-Bound Domains.

HLS encryption

HLS encrypted playback - VOD VidAuth playback

When you play an HLS-encrypted video using the VOD VidAuth method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

let player = new Aliplayer({
   id:'J_prismPlayer',
   vid:'<your video ID>', // Required. The audio or video ID. Example: 1e067a2831b641db90d570b6480f****.
   playauth:'<your PlayAuth>', // Required. The audio or video playback credential.
   playConfig: { // Optional.
     MtsHlsUriToken: '', // Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
     EncryptType: 'HLSEncryption', // Optional. If you set the encryption type to HLSEncryption, only HLS-encrypted video streams are returned.
   },
 });

HLS encrypted playback - VOD VidSts playback

When you play an HLS-encrypted video using the VOD VidSts method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

let player = new Aliplayer({
   id: 'J_prismPlayer',
   vid : '<your video ID>', // Required. You can obtain the audio or video ID in the console (Media Assets > Audio/Video) or by calling a server-side API operation (SearchMedia) after the audio or video is uploaded. Example: 1e067a2831b641db90d570b6480f****.
   accessKeyId: '<your AccessKey ID>', // Required. The AccessKey ID of the temporary STS token, which is returned when the STS token is generated.
   securityToken: '<your STS token>', // Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
   accessKeySecret: '<your AccessKey Secret>', // Required. The AccessKey secret of the temporary STS token, which is returned when the STS token is generated.
   region: '<region of your video>', // Required. The region where the media asset is located, such as cn-shanghai, eu-central-1, or ap-southeast-1.
   playConfig: { // Optional.
     MtsHlsUriToken: '', // Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
     EncryptType: 'HLSEncryption', // Optional. If you set the encryption type to HLSEncryption, only HLS-encrypted video streams are returned.
   },
 };

HLS encrypted playback - UrlSource playback

When you play an HLS-encrypted video using the live or VOD UrlSource method, the configuration is the same as for playing a regular video. No extra parameters are required.

  let player = new Aliplayer({
    id:'J_prismPlayer',
    source:'<your play URL>', // The playback URL, which can be a live or VOD URL.
    isLive: true, // Specifies whether it is a live stream.
  });

DRM encryption

DRM encrypted playback - VOD VidSts playback

When you play a DRM-encrypted video using the VOD VidSts method, you must set the isDrm parameter to true to enable DRM encryption. This is not required for playing regular 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 DRM encrypted 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%',
               isDrm: true,
               vid: '<your video ID>',// Required. You can obtain the video ID in the ApsaraVideo VOD console. Go to Media Assets > Audio/Video. Example: 1e067a2831b641db90d570b6480f****.
               accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
               securityToken: '<your STS token>',// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
               accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
               region: '<region of your video>', // Required. The region where the media asset is located, such as cn-shanghai, eu-central-1, or ap-southeast-1.
               certId: '<your certificate ID>', // Required for playback on Apple devices. This parameter is used to request an Apple certificate. You can obtain it from the ApsaraVideo VOD or ApsaraVideo Live console based on your DRM encryption implementation.
               // authTimeout: 7200, // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set in the ApsaraVideo VOD console. If you do not set this parameter, the default value 7200 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 playback is complete.
             },function(player){
               console.log('The player is created.')
            });
         </script>
     </body>
 </html>

DRM encrypted playback - Live LiveStsSource playback

To play a DRM-encrypted video using the LiveStsSource method, you must pass the URL and STS temporary credentials. For more information about how to generate STS temporary credentials, see Obtain an STS token. The following code provides an example.

<!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 encrypted 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%',
               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 temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
               securityToken: '<your STS token>',// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
               accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
               region: '<region of your video>', // Required. The service region where the media asset is located, such as cn-shanghai, eu-central-1, or ap-southeast-1.
               certId: '<your certificate ID>', // Required for playback on Apple devices. This parameter is used to request an Apple certificate. You can obtain it from the ApsaraVideo VOD or ApsaraVideo Live console based on your DRM encryption implementation.
             },function(player){
               console.log('The player is created.')
            });
         </script>
     </body>
 </html>

Android

Procedure

You can quickly integrate the ApsaraVideo Player for Android into your application to play videos. The steps and sample code are as follows:

  1. Integrate the ApsaraVideo Player SDK for Android.

    For more information, see Integrate the SDK.

  2. Create a player to play the video.

    For the steps on creating a player, see Basic Features. In Step 3. Create DataSource, select one of the following methods to create the data source based on your requirements.

Alibaba Cloud proprietary encryption

Note

You can play HLS videos that are encrypted using Alibaba Cloud proprietary cryptography by URL-based playback after you create a transcoding template and transcode the videos. Before transcoding, you must bind a license in the same account. For more information, see Manage licenses. Then, you can use the EncryptType parameter to create a transcoding template group. An example is as follows:

Important

After the template is created, you cannot modify or save it in the console. Otherwise, the encryption method is overwritten.

[{
        "TranscodeTemplateId": "",
	"TemplateName": "740PH264HLS_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"
	}
}]

Proprietary encrypted playback - VOD VidAuth playback (HLS + MP4)

When you play a proprietary encrypted HLS or MP4 video using the VOD VidAuth method, you can set the video encryption type to AliyunVoDEncryption to filter for proprietary encrypted streams if the video also has other types of encrypted streams or regular transcoded streams.

VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
vidAuth.setPlayConfig(vidPlayerConfigGen);
vidAuth.setVid("Vid info");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The playback credential. You can call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate this credential.
vidAuth.setRegion("Region");// This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 and later. You do not need to set the region. The player automatically parses the region. For earlier versions, this parameter is required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.
aliPlayer.setDataSource(vidAuth);

Proprietary encrypted playback - VOD VidSts playback (HLS + MP4)

When you play a proprietary encrypted HLS or MP4 video using the VOD VidSts method, you can set the video encryption type to AliyunVoDEncryption to filter for proprietary encrypted streams if the video also has other types of encrypted streams or regular transcoded streams.

VidSts vidSts = new VidSts();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
vidSts.setPlayConfig(vidPlayerConfigGen);
vidSts.setVid("Vid info");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
vidSts.setRegion("Region");// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.
aliPlayer.setDataSource(vidSts);

Proprietary encrypted playback - Live LiveStsSource playback (HLS + FLV)

To play a proprietary encrypted HLS or FLV video using the LiveStsSource method, you must pass the URL and STS credentials, and set the video encryption type to AliEncryption. The following code provides an example.

  1. Create a data source.

    You must pass AVPLiveStsSource as 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 proprietary encrypted HLS live stream.
    liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
    liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
    liveSts.setSecurityToken("<your STS token>");// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
    liveSts.setDomain("<your Domain>");// Required. The streaming domain for 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();
  2. Listen for STS token invalidation.

    During encrypted live playback, the encryption key may be changed. When the key is changed, the latest key is requested using STS. You need to listen for whether the STS token is valid. An invalid token affects the playback of the encrypted live stream.

    mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() {
    		@Override
        public AliPlayer.Status onVerifySts(StsInfo info) {
            // Replace the following pseudocode with your own implementation.
            if(info is valid){
                return IPlayer.StsStatus.Valid;
            }
    
            // Replace the following pseudocode with your own implementation.
            if(a new valid STS can be obtained){
                obtainSTS(); // This can be an asynchronous or synchronous call.
                return IPlayer.StsStatus.Pending;
            }
            // If the info is invalid and you cannot obtain the latest STS, we recommend that you stop the playback to prevent display errors.
            mAliyunVodPlayer.stop();
            return IPlayer.StsStatus.Invalid;
        }
    
        @Override
        public AliPlayer.Status onVerifyAuth(VidAuth auth) {
            return AliPlayer.Status.Valid;
        }
    });
    Note

    After you retrieve the STS token, you must call the updateLiveStsInfo method to update the STS information. If the token fails to be retrieved, we recommend that you stop the playback. If you do not update the STS information, the player continues to use the previous STS token to retrieve the key after a timeout. If the STS token is invalid, screen tearing or playback failure may occur.

    mAliyunVodPlayer.updateStsInfo(stsInfo);

Alibaba Cloud license-based proprietary encryption

Note

HLS videos that are encrypted with Alibaba Cloud license-based proprietary encryption can be played back using a URL after they are transcoded using a transcoding template. Before transcoding, you must attach a license under the same account. For more information, see Manage Licenses. Then, you can use the EncryptType parameter to create a transcoding template group, as shown in the following example:

Important

After the template is created, you cannot modify or save it in the console. Otherwise, the encryption method is overwritten.

[{
        "TranscodeTemplateId": "",
	"TemplateName": "740PH264HLS_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"
	}
}]

License-based proprietary encrypted playback - VOD UrlSource playback (HLS + MP4)

Note

ApsaraVideo Player SDK for Android V6.8.0 and later supports playing license-based proprietary encrypted MP4 videos using the VOD UrlSource method. V6.17.0 and later supports license-based proprietary encrypted HLS videos (single and multiple bitrates).

To play a license-based proprietary encrypted HLS or MP4 video using the VOD UrlSource method, you can call the GetPlayInfo operation to obtain the playback URL. Before you pass the URL to the player, you must append etavirp_nuyila=1 to the end of the URL. The position of the parameter does not matter. This is required only for MP4 videos. For HLS videos, you can use the original URL. The player SDK configuration is the same as for playing a regular video. No extra 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

// 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 video URL.
aliPlayer.setDataSource(urlSource);
aliPlayer.prepare();

// Short video player
AliListPlayer aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
// Add a UrlSource playback source.
aliyunListPlayer.addUrl(playURL,uid);
aliyunListPlayer.moveTo(uid);

//Preload
MediaLoader mediaLoader = MediaLoader.getInstance();
mediaLoader.load(playURL,"duration");

HLS encryption

HLS encrypted playback - VOD VidAuth playback

When you play an HLS-encrypted video using the VOD VidAuth method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

Important

After you enable M3U8 encryption and rewrite, 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 the encryption type to HLSEncryption, only HLS-encrypted video streams are returned.
playerConfig.setMtsHlsUriToken("token");// Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
vidAuth.setPlayConfig(playerConfig);
vidAuth.setVid("Vid info");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The playback credential. You can call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate this credential.
vidAuth.setRegion("Region");// This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 and later. You do not need to set the region. The player automatically parses the region. For earlier versions, this parameter is required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
// vidAuth.setAuthTimeout(3600);// Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.
aliPlayer.setDataSource(vidAuth);

HLS encrypted playback - VOD VidSts playback

When you play an HLS-encrypted video using the VOD VidSts method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

Important

After you enable M3U8 encryption and rewrite, 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 the encryption type to HLSEncryption, only HLS-encrypted video streams are returned.
playerConfig.setMtsHlsUriToken("token");// Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
vidSts.setPlayConfig(playerConfig);
vidSts.setVid("Vid info");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
vidSts.setRegion("Region");// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
// vidSts.setAuthTimeout(3600);// Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.
aliPlayer.setDataSource(vidSts);

HLS encrypted playback - UrlSource playback

When you play an HLS-encrypted video using the live or VOD UrlSource method, the player SDK configuration is the same as for playing a regular video. No extra 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 it to the player.

Important

After you enable M3U8 encryption and rewrite, you must append MtsHlsUriToken=<token> to the end of the obtained URL (position does not matter) before passing it to the player.

Sample original playback URL: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.

Sample URL to input 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 HLS-encrypted live or VOD stream.
        aliPlayer.setDataSource(urlSource);

Alibaba Cloud DRM encryption

Note

On Android, we recommend that you use SurfaceView for playback to ensure that high-security videos can be played properly.

DRM encrypted playback - VOD VidSts playback

For more information about how to configure DRM encryption, see Configure DRM encryption for VOD. When you play a DRM-encrypted video using the VOD VidSts method, the configuration is the same as for playing a regular video. No extra parameters are required.

VidSts vidSts = new VidSts();
        vidSts.setVid("Vid info");// Required. The video ID.
        vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
        vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
        vidSts.setSecurityToken("<yourSecurityToken>");// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
        vidSts.setRegion("Region");// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
        // vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.
        aliPlayer.setDataSource(vidSts);

DRM encrypted playback - Live LiveStsSource playback

For more information about how to configure DRM encryption, see Configure DRM encryption for live streaming. To play a DRM-encrypted video using the LiveStsSource method, you must pass the URL and STS credentials, and set the video encryption type to WideVine_FairPlay. The following code provides an example.

  1. Create a data source.

    You must pass AVPLiveStsSource as 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 token. You can call the AssumeRole operation of STS to generate this ID.
    liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
    liveSts.setSecurityToken("<your STS token>");// Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
    liveSts.setDomain("<your Domain>");// Required. The streaming domain for 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();
  2. Listen for STS token invalidation.

    During encrypted live playback, the encryption key may be changed. When the key is changed, the latest key is requested using STS. You need to listen for whether the STS token is valid. An invalid token affects the playback of the encrypted live stream.

    mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() {
    		@Override
        public AliPlayer.Status onVerifySts(StsInfo info) {
            if(info can be used){
                return IPlayer.StsStatus.Valid;
            }
    
            if(a valid STS can be obtained){
                Obtain STS();// Can be asynchronous or synchronous.
                return IPlayer.StsStatus.Pending;
            }
            // If the info is invalid and a new STS cannot be obtained, we recommend stopping playback to prevent screen tearing.
            mAliyunVodPlayer.stop();
            return IPlayer.StsStatus.Invalid;
        }
    
        @Override
        public AliPlayer.Status onVerifyAuth(VidAuth auth) {
            return AliPlayer.Status.Valid;
        }
    });
    Note

    After you retrieve the STS token, you must call the updateLiveStsInfo method to update the STS information. If the token fails to be retrieved, we recommend that you stop the playback. If you do not update the STS information, the player continues to use the previous STS token to retrieve the key after a timeout. If the STS token is invalid, screen tearing or playback failure may occur.

    mAliyunVodPlayer.updateStsInfo(stsInfo);

Third-party DRM encryption

Note

This feature requires ApsaraVideo Player SDK V7.8.0 or later.

Third-party DRM (Widevine) encrypted playback - VOD UrlSource/Live UrlSource playback

Note
  • Only the Widevine solution for HLS and DASH is supported.

For more information about how to configure DRM encryption, see VOD packaging. When you play a DRM-encrypted video using the UrlSource method, the configuration is the same as for playing a regular video. However, you must also implement the DrmCallback interface to obtain the key information for the video.

// Implement the DrmCallback.requestKey interface and obtain the key by referring to the documentation of the third-party DRM provider.
// The following code provides an example of how to obtain a key from PallyCon. For more information, see https://pallycon.com/docs/en/multidrm.

player.setDrmCallback(new DrmCallback() {
    @Override
    public byte[] requestKey(byte[] data) {
        // Send an HTTP POST request to obtain the key information as required by the DRM provider.
        String licenseUrl = "https://license-global.pallycon.com/ri/licenseManager.do";
        String[] header = {
            // Replace TOKEN_ID with your own token ID.
            "pallycon-customdata-v2: TOKEN_ID"
        };

        // Avoid occupying this thread for too long.
        byte[] response = async_http_post(licenseUrl, header, data);
        if (response != null) {
            // If the response_format of your token is set to original, return the response directly. Otherwise, you need to 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 vary greatly among different providers. Check carefully. If the response cannot be used for decryption, the player will report an error.
            return response;
        } else {
            // Handle exceptions. The player will report an error.
            return null;
        }
    }
});

iOS

Procedure

You can quickly integrate the ApsaraVideo Player for iOS into your application to play videos. The steps and sample code are as follows:

  1. Integrate the ApsaraVideo Player SDK for iOS.

    For more information, see Integrate the SDK.

  2. Create a player to preload and play or load a video.

    For more information about creating a player, see Basic features. In Step 3. Create a data source, you can create the data source in one of the following ways.

Alibaba Cloud proprietary encryption

Proprietary encrypted playback - VOD VidAuth (HLS + MP4)

When you play a proprietary encrypted HLS or MP4 video using the VOD VidAuth method, you can set the video encryption type to AliyunVoDEncryption to filter for proprietary encrypted streams if the video also has other types of encrypted streams or regular transcoded streams.

AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Vid info"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. You can call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate this credential.
authSource.region = @"Region"; // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 and later. You do not need to set the region. The player automatically parses the region. For earlier versions, this parameter is required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.

//Build the config using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVoDEncryption"]; // Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
authSource.playConfig = [config generatePlayerConfig]; 
[self.player setAuthSource:authSource];

Proprietary encrypted playback - VOD VidSts (HLS + MP4)

When you play a proprietary encrypted HLS or MP4 video using the VOD VidSts method, you can set the video encryption type to AliyunVoDEncryption to filter for proprietary encrypted streams if the video also has other types of encrypted streams or regular transcoded streams.

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Region"; // Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
source.vid = @"Vid info"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.

//Build the config using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVoDEncryption"]; // Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
source.playConfig = [config generatePlayerConfig]; 

//Set the playback source.
[self.player setStsSource:source];

Proprietary encrypted playback - Live LiveStsSource (HLS + FLV)

To play a proprietary encrypted HLS or FLV video using the LiveStsSource method, you must pass the URL and STS credentials, and set the video encryption type to ENCRYPTION_TYPE_ALIVODENCRYPTION. The following code provides an example.

  1. Create a data source.

    You must pass AVPLiveStsSource as the playback source.

    // Create a LiveSts object and set encryptionType to ENCRYPTION_TYPE_ALIVODENCRYPTION.
    AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Encrypted live URL" 
                                                                accessKeyId:@"Temporary AK ID" 
                                                                accessKeySecret:@"Temporary AK secret" 
                                                                securityToken:@"Security token" 
                                                                region:@"Region value" 
                                                                domain:@"URL streaming domain" 
                                                                app:@"Streaming application name" 
                                                                stream:@"Streaming stream name" 
                                                                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];
  2. Listen for STS token invalidation.

    During encrypted live playback, the encryption key may be changed. When the key is changed, the latest key is requested using STS. You need to listen for whether the STS token is valid. An invalid token affects the playback of the encrypted live stream.

     __weak typeof(self) weakSelf = self;
    [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) {
        if (info can be used) {
            return Valid;
        }
        if(a valid STS can be obtained){
            Obtain STS();// Can be asynchronous or synchronous.
            return Pending;
        }
        [weakSelf.aliPlayer stop];
        return Invalid;
    }];
    Note

    After you retrieve the STS token, you must call the updateLiveStsInfo method to update the STS information. If the token fails to be retrieved, we recommend that you stop the playback. If you do not update the STS information, the player continues to use the previous STS token to retrieve the key after a timeout. If the STS token is invalid, screen tearing or playback failure may occur.

    [self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];

Alibaba Cloud license-based proprietary encryption

License-based proprietary encrypted playback - VOD UrlSource playback (HLS + MP4)

Note

ApsaraVideo Player SDK for iOS V6.8.0 and later supports playing license-based proprietary encrypted MP4 videos using the VOD UrlSource method. V6.17.0 and later supports license-based proprietary encrypted HLS videos (single and multiple bitrates).

To play a license-based proprietary encrypted HLS or MP4 video using the VOD UrlSource method, you can call the GetPlayInfo operation to obtain the playback URL. Before you pass the URL to the player, you must append etavirp_nuyila=1 to the end of the URL. The position of the parameter does not matter. This is required only for MP4 videos. For HLS videos, you can use the original URL. The player SDK configuration is the same as for playing a regular video. No extra 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

//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 video URL. You must append etavirp_nuyila=1 to the end of the obtained URL (for MP4 only) before passing it to the player. 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 encryption

HLS encrypted playback - VOD VidAuth playback

When you play an HLS-encrypted video using the VOD VidAuth method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

Important

After you enable M3U8 encryption and rewrite, you must call setHlsUriToken to set the user token.

AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Vid info"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. You can call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate this credential.
authSource.region = @"Region"; // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 and later. You do not need to set the region. The player automatically parses the region. For earlier versions, this parameter is required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.

//Build the config using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set the encryption type to HLSEncryption, only HLS-encrypted video streams 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];

HLS encrypted playback - VOD VidSts playback

When you play an HLS-encrypted video using the VOD VidSts method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

Important

After you enable M3U8 encryption and rewrite, you must call setHlsUriToken to set the user token.

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.vid = @"Vid info"; // Required. The video ID.
source.region = @"Region"; // Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.

//Build the config using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set the encryption type to HLSEncryption, only HLS-encrypted video streams 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];

HLS encrypted playback - UrlSource playback

When you play an HLS-encrypted video using the live or VOD UrlSource method, the player SDK configuration is the same as for playing a regular video. No extra 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 it to the player.

Important

After you enable M3U8 encryption and rewrite, you must append MtsHlsUriToken=<token> to the end of the obtained URL (position does not matter) before passing it to the player.

Sample original playback URL: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.

Sample URL to input to the player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.

AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // The playback URL of the HLS-encrypted live or VOD stream.
[self.player setUrlSource:urlSource];

Alibaba Cloud DRM encryption

Note

On iOS, you must call the setFairPlayCertID method in AliPlayerGlobalSettings once globally before you call [self.player prepare] to set the certificate ID. You can obtain the certificate ID in the ApsaraVideo VOD console by choosing Configuration Management > Media Processing > DRM Certificate Management.

 [AliPlayerGlobalSettings setFairPlayCertID:@"Certificate ID obtained from the console"];

DRM encrypted playback - VOD VidSts playback

For more information about how to configure DRM encryption, see Configure DRM encryption for VOD. When you play a DRM-encrypted video using the VOD VidSts method, the configuration is the same as for playing a regular video. No extra parameters are required.

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Region"; // Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
source.vid = @"Vid info"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The STS token. You can call the AssumeRole operation of STS to generate this token.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS token. You can call the AssumeRole operation of STS to generate this secret.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS token. You can call the AssumeRole operation of STS to generate this ID.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overwrites the validity period of URL signing that is set 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 playback is complete.
 //Set the playback source.
 [self.player setStsSource:source]

DRM encrypted playback - Live LiveStsSource playback

For more information about how to configure DRM encryption, see Configure DRM encryption for live streaming. To play a DRM-encrypted video using the LiveStsSource method, you must pass the URL and STS credentials, and set the video encryption type to ENCRYPTION_TYPE_FAIRPLAY. The following code provides an example.

  1. Create a data source.

    You must pass AVPLiveStsSource as the playback source.

    // Create a LiveSts object and set encryptionType to ENCRYPTION_TYPE_FAIRPLAY.
    AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Encrypted live URL" 
                                                                accessKeyId:@"Temporary AK ID" 
                                                                accessKeySecret:@"Temporary AK secret" 
                                                                securityToken:@"Security token" 
                                                                region:@"Region value" 
                                                                domain:@"URL streaming domain" 
                                                                app:@"Streaming application name" 
                                                                stream:@"Streaming stream name" 
                                                                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];

  2. Listen for STS token invalidation.

    During encrypted live playback, the encryption key may be changed. When the key is changed, the latest key is requested using STS. You need to listen for whether the STS token is valid. An invalid token affects the playback of the encrypted live stream.

     __weak typeof(self) weakSelf = self;
    [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) {
        if (info can be used){
            return Valid;
        }
        if(a valid STS can be obtained){
            Obtain STS();// Can be asynchronous or synchronous.
            return Pending;
        }
        [weakSelf.aliPlayer stop];
        return Invalid;
    }];
    Note

    After you retrieve the STS token, you must call the updateLiveStsInfo method to update the STS information. If the token fails to be retrieved, we recommend that you stop the playback. If you do not update the STS information, the player continues to use the previous STS token to retrieve the key after a timeout. If the STS token is invalid, screen tearing or playback failure may occur.

    [self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];

Third-party DRM encryption

Note
  • This feature requires ApsaraVideo Player SDK V7.8.0 or later.

  • You must use AppleAVPlayer to play FairPlay-encrypted videos. Before playback starts, you can call [self.player setPreferPlayerName:@"AppleAVPlayer"] to switch the kernel. To play non-DRM encrypted videos, you can call [self.player setPreferPlayerName:@""] to restore the default kernel.

Third-party DRM (Fairplay) encrypted playback - VOD UrlSource/Live UrlSource playback

Note
  • Only the FairPlay solution for HLS is supported.

For more information about how to configure DRM encryption, see Live packaging. When you play a DRM-encrypted video using the UrlSource method, the configuration is the same as for playing a regular video. However, you must also implement the AVPDrmDelegate interface to obtain the FairPlay certificate and 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 a third-party DRM video){
        [self.player setPreferPlayerName:@"AppleAVPlayer"];
    }
    //...
}

// Implement the AVPDrmDelegate.requestCert and requestKey interfaces, and obtain the certificate and key by referring to the documentation of the third-party DRM provider.
// The following code provides an example of 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 request and cache the certificate in advance. In this case, just return the cached certificate to reduce playback startup time.
    // If the certificate data is incorrect, the player will report 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";

    // Send an HTTP GET request for the configured FairPlay certificate as required by the DRM provider.
    // Avoid occupying this thread for too long.
    NSData* responseData = [self performAsyncHttpGet:url];
    if (!responseData) {
        // Handle exceptions. The player will report an error.
        return nil;
    }
    
    // The returned data needs to 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 {
    // Send an HTTP POST request to obtain the key information 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 occupying this thread for too long.
    NSData* responseData = [self performAsyncHttpPost:url
                                             headers:headers
                                         headerCount:headerCount
                                                data:data];
    if (!responseData) {
        // Handle exceptions. The player will report an error.
        return nil;
    }

    // If the response_format of your token is set to original, return the response directly. Otherwise, you need to 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 vary greatly among different providers. Check carefully. If the response cannot be used for decryption, the player will report an error.
    return [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}

Flutter

Note

DRM encryption is not supported in Flutter.

Procedure

You can quickly integrate the ApsaraVideo Player for Flutter into your application to play videos. The steps and sample code are as follows:

  1. Integrate the ApsaraVideo Player SDK for Flutter.

    For more information, see Integrate the SDK.

  2. Create a player to play the video.

    For more information about how to create a player, see Basic features. For Step 3. Create a playback source, you can create the source in one of the following ways as needed.

Alibaba Cloud proprietary encryption

Proprietary encrypted playback - VOD VidAuth (HLS + MP4)

When you play a proprietary encrypted HLS or MP4 video using the VOD VidAuth method, you can set the video encryption type to AliyunVoDEncryption to filter for proprietary encrypted streams if the video also has other types of encrypted streams or regular transcoded streams.

FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidAuth(
              vid: "Vid info",
              region: "Region",// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
              playAuth: "<yourPlayAuth>",// Required. The playback credential. You can call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate this credential.
              playConfig: value);
});

Proprietary encrypted playback - VOD VidSts (HLS + MP4)

When you play a proprietary encrypted HLS or MP4 video using the VOD VidSts method, you can set the video encryption type to AliyunVoDEncryption to filter for proprietary encrypted streams if the video also has other types of encrypted streams or regular transcoded streams.

FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidSts(
              vid: "Vid info",
              region: "Region",
              accessKeyId: "<yourAccessKeyId>",
              accessKeySecret: "<yourAccessKeySecret>",
              securityToken: "<yourSecurityToken>",
              playConfig: value);
        });

Alibaba Cloud license-based proprietary encryption

License-based proprietary encrypted playback - VOD UrlSource playback (HLS + MP4)

Note

ApsaraVideo Player SDK for Flutter V6.8.0 and later supports playing license-based proprietary encrypted MP4 videos using the VOD UrlSource method. V6.17.0 and later supports license-based proprietary encrypted HLS videos (single and multiple bitrates).

To play a license-based proprietary encrypted HLS or MP4 video using the VOD UrlSource method, you can call the GetPlayInfo operation to obtain the playback URL. Before you pass the URL to the player, you must append etavirp_nuyila=1 to the end of the URL. The position of the parameter does not matter. This is required only for MP4 videos. For HLS videos, you can use the original URL. The player SDK configuration is the same as for playing a regular video. No extra 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

//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 encryption

HLS encrypted playback - VOD VidAuth playback

When you play an HLS-encrypted video using the VOD VidAuth method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

Important

After you enable M3U8 encryption and rewrite, you must call setHlsUriToken to set the user token.

FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption);// Optional. If you set the encryption type to HLSEncryption, only HLS-encrypted video streams are returned.
FlutterAliplayer.setHlsUriToken("token");// Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidAuth(
              vid: "Vid info",
              region: "Region",// Required. The region where ApsaraVideo VOD is activated. The default value is cn-shanghai.
              playAuth: "<yourPlayAuth>",// Required. The playback credential. You can call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate this credential.
              playConfig: value);
});

HLS encrypted playback - VOD VidSts playback

When you play an HLS-encrypted video using the VOD VidSts method, you can set the video encryption type to HLSEncryption to filter for HLS-encrypted streams if the video also has other types of encrypted streams or regular transcoded streams. The following code provides an example.

Important

After you enable M3U8 encryption and rewrite, you must call setHlsUriToken to set the user token.

FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption);// Optional. If you set the encryption type to AliyunVoDEncryption, only proprietary encrypted video streams are returned.
FlutterAliplayer.setHlsUriToken("token");// Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
FlutterAliplayer.generatePlayerConfig().then((value) {
          this.fAliplayer.setVidSts(
              vid: "Vid info",
              region: "Region",
              accessKeyId: "<yourAccessKeyId>",
              accessKeySecret: "<yourAccessKeySecret>",
              securityToken: "<yourSecurityToken>",
              playConfig: value);
        });

HLS encrypted playback - UrlSource playback

When you play an HLS-encrypted video using the live or VOD UrlSource method, the player SDK configuration is the same as for playing a regular video. No extra 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 it to the player.

Important

After you enable M3U8 encryption and rewrite, you must append MtsHlsUriToken=<token> to the end of the obtained URL (position does not matter) before passing it to the player.

Sample original playback URL: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.

Sample URL to input to the player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.

//Create a player instance.
FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
//The playback URL of the HLS-encrypted live or VOD stream.
fAliplayer.setUrl("Playback URL");
fAliplayer.prepare();

FAQ

For more information about common issues and solutions for video encryption, see FAQ about video encryption.

References