The secure download feature of ApsaraVideo Player SDK encrypts videos downloaded to your local device. Encrypted videos can be played only by using the key file generated from the app that you specified, which prevents malicious playback or distribution.
For all feature-related code and implementation details in this topic, we recommend that you refer to the API-Example demo project and adapt the code based on best practices.
For specific implementations, refer to the source code of the Video Download and Offline Playback module in API-Example-Android and API-Example-iOS.
Overview
ApsaraVideo VOD supports video download to mobile devices for offline playback in two modes:
-
Secure download (recommended): Videos that are downloaded in this mode are encrypted by Alibaba Cloud and can be decrypted only with key files. Videos can be played only using ApsaraVideo Player.
-
Normal download: Videos that are downloaded in this mode are not encrypted by Alibaba Cloud and can be copied and played using any player. Exercise caution when you use the normal download mode.
Secure download ensures that downloaded videos are encrypted. Encrypted videos can be played only by the app that you specified when you generated the key file in the ApsaraVideo VOD console. Compared with normal download, secure download better protects the copyright of downloaded videos and is recommended for most scenarios.
Limits
-
To use the secure download feature, you must integrate ApsaraVideo Player SDK.
-
ApsaraVideo Player SDK supports secure download based on only VidSts and VidAuth.
-
Videos downloaded in secure download mode are encrypted on the local device and can be played only in ApsaraVideo Player SDK on the app that you specified.
Prerequisites
-
The download feature is enabled and Download Mode is set to Secure Download in the ApsaraVideo VOD console. For more information, see Enable secure download.
-
ApsaraVideo Player SDK is integrated. For more information, see Quick integration of ApsaraVideo Player for Android or Quick integration of ApsaraVideo Player for iOS.
-
The video is encrypted using Alibaba Cloud proprietary cryptography or HLS encryption.
Key Android implementation
Secure download settings
-
Configure the encrypted verification file to enable secure downloads.
Configure the key file generated in the ApsaraVideo VOD console in ApsaraVideo Player SDK. The key file is used to encrypt and decrypt videos for download and playback. For more information about how to generate a key file, see Secure download.
NoteMake sure that the information in the key file matches the app information that you specified. Otherwise, video download fails.
We recommend that you configure this only once in the Application. The following is an example:
PrivateService.initService(getApplicationContext(), "Path to encryptedApp.dat file"); // We recommend storing the encryptedApp.dat verification file on the phone and setting its local file path here. -
Create and set downloader.
Create a downloader using AliDownloaderFactory. Example:
AliMediaDownloader mAliDownloader = null; ...... // Create downloader. mAliDownloader = AliDownloaderFactory.create(getApplicationContext()); // Configure download save path. mAliDownloader.setSaveDir("Save folder path"); -
Set event listeners.
The downloader provides multiple event listeners. Example:
-
Prepare download source.
Prepare the download source using the
preparemethod. Download sources support VidSts and VidAuth methods. Examples:-
VidSts
// Create VidSts VidSts aliyunVidSts = new VidSts(); aliyunVidSts.setVid("Vid information"); // Video ID (VideoId). aliyunVidSts.setAccessKeyId("<yourAccessKeyId>"); // AccessKey ID of the temporary STS AccessKey pair, generated by calling the AssumeRole operation of the Security Token Service (STS). aliyunVidSts.setAccessKeySecret("<yourAccessKeySecret>"); // AccessKey secret of the temporary STS AccessKey pair, generated by calling the AssumeRole operation of the Security Token Service (STS). aliyunVidSts.setSecurityToken("<yourSecurityToken>"); // Security Token Service (STS) token, generated by calling the AssumeRole operation of the Security Token Service (STS). aliyunVidSts.setRegion("region"); // The region of the video-on-demand (VOD) service. Default value: cn-shanghai. // If you have enabled HLS encryption parameter pass-through in the VOD console and the default parameter name is MtsHlsUriToken, // you must set the config and pass it into the vid, as shown below. // If you have not enabled HLS encryption parameter pass-through in the VOD console, skip the following code. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); aliyunVidSts.setPlayerConfig(vidConfig); // Prepare the download source mAliDownloader.prepare(aliyunVidSts) -
VidAuth
// Create VidAuth. VidAuth vidAuth = new VidAuth(); vidAuth.setVid("Vid info");// Video ID. vidAuth.setPlayAuth("<yourPlayAuth>");// Playback credential, generated by calling VOD GetVideoPlayAuth API. vidAuth.setRegion("Access region");// For player SDK version 5.5.5.0 and later, this parameter is deprecated and not required; the player automatically parses the region. For versions before 5.5.5.0, this parameter is required; VOD access region default is cn-shanghai. // If you enabled HLS standard encryption parameter pass-through in VOD console with default parameter name MtsHlsUriToken, set config and pass it to vid as follows. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); vidAuth.setPlayerConfig(config); // Prepare download source. mAliDownloader.prepare(vidAuth);
Note-
Source file format matches the downloaded file format; changing it is not supported.
-
If you enabled HLS standard encryption parameter pass-through in VOD console with default parameter name MtsHlsUriToken, see HLS standard encryption parameter pass-through, then set the MtsHlsUriToken value in the VOD source as shown above.
-
-
After successful preparation, select download item and start download.
After successful preparation, the
OnPreparedListenermethod is called. The returned TrackInfo contains information such as video stream definition. Select one Track for download. Example:public void onPrepared(MediaInfo mediaInfo) { // Download item prepared successfully. List<TrackInfo> trackInfos = mediaInfo.getTrackInfos(); // For example: download the first TrackInfo. mAliDownloader.selectItem(trackInfos.get(0).getIndex()); // Start download. mAliDownloader.start(); } -
(Optional) Update download source.
To prevent VidSts and VidAuth expiration, you can update the download source information and start downloading. Example:
// Update download source. mAliDownloader.updateSource(VidSts); // Start download. mAliDownloader.start(); -
After download success or failure, release downloader.
After download success, call
releasein theonCompletionoronErrorcallback to release the downloader. Example:mAliDownloader.stop(); mAliDownloader.release(); -
Optional: Delete downloaded files.
You can delete downloaded files during or after download. Example:
// Delete file via object. mAliDownloader.deleteFile(); // Delete via static method; returns 0 if successful. AliDownloaderFactory.deleteFile("Path to download folder","Video ID","Video format","Downloaded video index");
Play downloaded videos
Downloaded videos can be played only by using playback URLs in ApsaraVideo Player SDK. To play a downloaded video, perform the following steps:
-
After download completion, get the absolute path of the video file.
String path = mAliDownloader.getFilePath(); -
Set the absolute path via VOD UrlSource for playback.
UrlSource urlSource = new UrlSource(); urlSource.setUri("Playback address");// Set absolute path of downloaded video. aliPlayer.setDataSource(urlSource);
Key iOS implementation
Secure download settings
-
Configure the encrypted verification file to enable secure downloads.
Configure the key file generated in the ApsaraVideo VOD console in ApsaraVideo Player SDK. The key file is used to encrypt and decrypt videos for download and playback. For more information about how to generate a key file, see Secure download.
NoteMake sure that the information in the key file matches the app information that you specified. Otherwise, video download fails.
We recommend that you configure this setting only once per application. The following is an example:
NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"]; [AliPrivateService initKey:encrptyFilePath]; Create and set up the downloader.
Example:
AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init]; [downloader setSaveDirectory:self.downLoadPath]; [downloader setDelegate:self];Set event listeners.
The download object provides multiple listeners.
-(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info { // The download item is successfully prepared. } -(void)onError:(AliMediaDownloader *)downloader errorModel:(AVPErrorModel *)errorModel { // A download error occurred. } -(void)onDownloadingProgress:(AliMediaDownloader *)downloader percentage:(int)percent { // Download progress percentage. } -(void)onProcessingProgress:(AliMediaDownloader *)downloader percentage:(int)percent { // Processing progress percentage. } -(void)onCompletion:(AliMediaDownloader *)downloader { // The download is successful. }Prepare the download source.
Call the
preparemethod to prepare a download source. Supported source types include VidStsSource and VidAuthSource. Examples follow:VidSts
// Create VidSts. AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init]; stsSource.region = @"Access region"; // The access region of ApsaraVideo VOD. The default is cn-shanghai. stsSource.vid = @"Vid information"; // The video ID (VideoId). stsSource.securityToken = @"<yourSecurityToken>"; // The STS security token. You need to call the AssumeRole operation of STS to generate it. stsSource.accessKeySecret = @"<yourAccessKeySecret>"; // The AccessKey secret of the temporary STS AccessKey pair. You need to call the AssumeRole operation of STS to generate it. stsSource.accessKeyId = @"<yourAccessKeyId>"; // The AccessKey ID of the temporary STS AccessKey pair. You need to call the AssumeRole operation of STS to generate it. // If you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHlsUriToken, you need to set the config and pass it into the vid. See below. // If you have not enabled HLS standard encryption parameter pass-through in the VOD console, you do not need to integrate the following code. VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init]; [vp setHlsUriToken:yourMtsHlsUriToken]; stsSource.playConfig = [vp generatePlayerConfig]; // Prepare the download source. [downloader prepareWithVid:stsSource];VidAuth
// Create VidAuth. AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init]; authSource.vid = @"Vid information"; // The video ID (VideoId). authSource.playAuth = @"<yourPlayAuth>"; // The playback credential. You need to call the GetVideoPlayAuth operation of ApsaraVideo VOD to generate it. authSource.region = @"Access region"; // For player SDK V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region. The player will automatically parse the region. For player SDK versions earlier than 5.5.5.0, this parameter is required. The access region of ApsaraVideo VOD. The default is cn-shanghai. // If you have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is MtsHlsUriToken, you need to set the config and pass it into the vid. See below. // If you have not enabled HLS standard encryption parameter pass-through in the VOD console, you do not need to integrate the following code. VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init]; [vp setHlsUriToken:yourMtsHlsUriToken]; authSource.playConfig = [vp generatePlayerConfig]; // Prepare the download source. [downloader prepareWithVid:authSource];
NoteIf you enable parameter pass-through for HLS encryption in the ApsaraVideo VOD console, the default parameter is MtsHIsUriToken. For more information, see Parameter pass-through for HLS encryption. Then, set the MtsHIsUriToken value to the ApsaraVideo VOD source by following the preceding code.
Select a download item.
After preparation succeeds, the
onPreparedmethod is called. The returned TrackInfo includes information such as the definition of each video stream. Select a track to download. The following is an example:-(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info { NSArray<AVPTrackInfo*>* tracks = info.tracks; // For example, download the first TrackInfo. [downloader selectTrack:[tracks objectAtIndex:0].trackIndex]; }Update the download source and start the download.
VidSts or VidAuth may expire before the download. Therefore, we recommend updating the download source before you start the download.
// Update the download source. [downloader updateWithVid:vidSource] // Start the download. [downloader start];After the download succeeds or fails, release the downloader.
After the download succeeds, invoke
destroyto release the downloader.[self.downloader destroy]; self.downloader = nil;
Play downloaded videos
Downloaded videos can be played only by using playback URLs in ApsaraVideo Player SDK. To play a downloaded video, perform the following steps:
-
Obtain the absolute path of the downloaded video file.
NoteWe recommend that you generate the absolute path of a downloaded video file as follows: obtain the custom storage path and file name from
downloadedFilePath, retrieve the sandbox directory, and then concatenate them.NSString *downloadedFilePath = downloader.downloadedFilePath; -
Use a VOD UrlSource to set the absolute path for playback.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:downloadedFilePath]; [self.player setUrlSource:urlSource];