Secure download
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);
NoteSource 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);
Videos downloaded by using the playAuth method contain only a single video stream at the definition that you selected during download. After the video is downloaded, you cannot switch to a different definition. If you need a video at a different definition, you must download the corresponding version again.
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 configure the downloader.
The following code provides an example:
AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init]; [downloader setSaveDirectory:self.downLoadPath]; [downloader setDelegate:self];Set event listeners.
The downloader supports multiple event listeners. The following code provides an example:
-(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info { // A download item is successfully prepared. } -(void)onError:(AliMediaDownloader *)downloader errorModel:(AVPErrorModel *)errorModel { // An error occurred during download. } -(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 the download source. VidSts and VidAuth sources are supported. The following code provides an example:VidSts
// Create a VidSts source. AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init]; stsSource.region = @"your_region"; // Your ApsaraVideo VOD service region. Default value: cn-shanghai. stsSource.vid = @"your_video_id"; // The video ID. stsSource.securityToken = @"<yourSecurityToken>"; // The STS security token. To get this token, call the STS AssumeRole operation. stsSource.accessKeySecret = @"<yourAccessKeySecret>"; // The AccessKey secret of the temporary STS credential. To get this secret, call the STS AssumeRole operation. stsSource.accessKeyId = @"<yourAccessKeyId>"; // The AccessKey ID of the temporary STS credential. To get this ID, call the STS AssumeRole operation. // If you have enabled parameter pass-through for HLS encryption in the ApsaraVideo VOD console // and the default parameter name is MtsHlsUriToken, you must set the config and pass it to the VidSts source. // If this feature is not enabled, you can skip the following code. VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init]; [vp setHlsUriToken:yourMtsHlsUriToken]; stsSource.playConfig = [vp generatePlayerConfig]; // Prepare the download source. [downloader prepareWithVid:stsSource];VidAuth
// Create a VidAuth source. AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init]; authSource.vid = @"your_video_id"; // The video ID. authSource.playAuth = @"<yourPlayAuth>"; // The playback credential. To get this credential, call the ApsaraVideo VOD GetVideoPlayAuth operation. authSource.region = @"your_region"; // Deprecated in ApsaraVideo Player SDK V5.5.5.0 and later because the player automatically parses the region. // Required for earlier versions. // Your ApsaraVideo VOD service region. Default value: cn-shanghai. // If you have enabled parameter pass-through for HLS encryption in the ApsaraVideo VOD console // and the default parameter name is MtsHlsUriToken, you must set the config and pass it to the VidAuth source. // If this feature is not enabled, you can skip 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 and the default parameter name is MtsHlsUriToken, you must set the MtsHlsUriToken value in the download source as shown in the code above. For more information, see parameter pass-through for HLS encryption.
Select a video track after the source is prepared.
After the download source is prepared, the
onPreparedmethod is called. ThemediaInfoparameter of the callback contains information about each available video track, such as video quality. Select a track to download. The following code provides an example:-(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info { NSArray<AVPTrackInfo*>* tracks = info.tracks; // For example, to download the first track: [downloader selectTrack:[tracks objectAtIndex:0].trackIndex]; }Update the download source and start the download.
To prevent VidSts and VidAuth credentials from expiring, we recommend updating the source information before you start the download. The following code provides an example:
// Update the download source. [downloader updateWithVid:vidSource] // Start the download. [downloader start];Release the downloader after the download completes or fails.
Call the
destroymethod to 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];
Videos downloaded by using the playAuth method contain only a single video stream at the definition that you selected during download. After the video is downloaded, you cannot switch to a different definition. If you need a video at a different definition, you must download the corresponding version again.