ApsaraVideo Player SDK provides the secure download feature. Videos that are downloaded to your local device in this mode are encrypted. You can play the encrypted videos only using the key file generated from the app that you specified. Secure download protects your videos from malicious playback or distribution. This topic describes how to use ApsaraVideo Player SDK for Android and iOS to securely download videos.
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, you can use the solutions described in this topic and refer to the source code of the Video Download and Offline Playback module in the corresponding API-Example-Android and API-Example-iOS.
Overview
ApsaraVideo VOD supports video download to mobile devices for offline playback. The normal download and secure download modes are supported. The following content describes the differences between the two modes:
Secure download (recommended): Videos that are downloaded in this mode are encrypted by Alibaba Cloud. You must use key files to decrypt the videos before you play them. 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 videos that you download are encrypted. You can play the encrypted videos only using the app that you specified when you generate the key file in the ApsaraVideo VOD console. Compared with the normal download mode, the secure download mode is more reliable and suitable to protect the copyright of downloaded videos. In most cases, we recommend that you use the secure download mode.
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 that are downloaded using the secure download mode are encrypted on the local device and can be played only based on playback URLs 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(), "File path where encryptedApp.dat is located"); // We recommend storing the encryptedApp.dat file on the phone and then setting the local file path of the encryption file hereCreate and set up the downloader.
You can create a downloader using AliDownloaderFactory. The following code is an example:
AliMediaDownloader mAliDownloader = null; ...... // Create the downloader mAliDownloader = AliDownloaderFactory.create(getApplicationContext()); // Configure the save path for the download mAliDownloader.setSaveDir("Save folder address");Set listeners.
The downloader provides multiple event listeners. The following code is an example:
Prepare the download source.
You can use the
preparemethod to prepare the download source. The download source supports VidSts and VidAuth methods. The following code is an example:VidSts
// Create a VidSts object. VidSts aliyunVidSts = new VidSts(); aliyunVidSts.setVid("your_video_id"); // The video ID. aliyunVidSts.setAccessKeyId("<yourAccessKeyId>"); // The AccessKey ID of the temporary STS token. To obtain the token, you must call the AssumeRole operation of STS. aliyunVidSts.setAccessKeySecret("<yourAccessKeySecret>"); // The AccessKey secret of the temporary STS token. To obtain the token, you must call the AssumeRole operation of STS. aliyunVidSts.setSecurityToken("<yourSecurityToken>"); // The security token. To obtain the token, you must call the AssumeRole operation of STS. aliyunVidSts.setRegion("your_region_id"); // The ID of the region where VOD is activated. Default value: cn-shanghai. // If you enabled HLS encryption with parameter pass-through in the VOD console and the default parameter name is MtsHlsUriToken, you must set the config parameter and pass it to the VidSts object. For more information, see the following code. // If you did not enable HLS encryption with parameter pass-through in the VOD console, you do not need to integrate the following code. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); aliyunVidSts.setPlayerConfig(vidConfig); // Prepare the download source. mAliDownloader.prepare(aliyunVidSts);VidAuth
// Create a VidAuth object. VidAuth vidAuth = new VidAuth(); vidAuth.setVid("Your Video ID");// The video ID (VideoId). vidAuth.setPlayAuth("<yourPlayAuth>");// The playback credential. You must call the GetVideoPlayAuth operation of the VOD service to generate the credential. vidAuth.setRegion("The region");// For player SDKs V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region because the player automatically parses the region. For player SDKs earlier than V5.5.5.0, this parameter is required. It specifies the region where the VOD service is activated. The default value is cn-shanghai. // If you enable pass-through of HLS encryption parameters in the VOD console and the default parameter name is MtsHlsUriToken, you must set the config and pass it to the VidAuth object. For more information, see the following code. VidPlayerConfigGen vidConfig = new VidPlayerConfigGen(); vidConfig.setMtsHlsUriToken("<yourMtsHlsUriToken>"); vidAuth.setPlayerConfig(vidConfig); // Prepare the download source. mAliDownloader.prepare(vidAuth);
NoteThe source file format and the output download file format are the same and cannot be changed.
If you enable HLS standard encryption parameter pass-through in the VOD console, the default parameter name is MtsHIsUriToken. For more information, see HLS standard encryption parameter pass-through. In this case, you must set the MtsHIsUriToken value in the VOD source as shown in the code above.
After the preparation is successful, select a download item and start the download.
After the preparation is successful, the
OnPreparedListenermethod is called. The returned TrackInfo object contains information such as the definition of each video stream. You can select a Track to download. The following code is an example:public void onPrepared(MediaInfo mediaInfo) { // Successfully prepared the download item List<TrackInfo> trackInfos = mediaInfo.getTrackInfos(); // For example, download the first TrackInfo mAliDownloader.selectItem(trackInfos.get(0).getIndex()); // Start the download mAliDownloader.start(); }(Optional) Update the download source.
To prevent VidSts and VidAuth from expiring, you can also update the download source information before you start the download. The following code is an example:
// Update the download source mAliDownloader.updateSource(VidSts); // Start the download mAliDownloader.start();After the download succeeds or fails, release the downloader.
After the download is complete, you can call
releasein theonCompletionoronErrorcallback to release the downloader. The following code is an example:mAliDownloader.stop(); mAliDownloader.release();Optional: Delete the downloaded files.
During or after the download, you can delete the downloaded files. The following code is an example:
// Delete the file through the object mAliDownloader.deleteFile(); // Delete through a static method. If successful, it returns 0 AliDownloaderFactory.deleteFile("Path of the download folder to be deleted", "Video ID", "Video format", "Index of the downloaded video");
Play downloaded videos
Videos that are downloaded can be played only based on playback URLs in ApsaraVideo Player SDK. To play a downloaded video, perform the following steps:
After the download is complete, obtain the absolute path of the video file.
String path = mAliDownloader.getFilePath();Set the absolute path for playback using the UrlSource method.
UrlSource urlSource = new UrlSource(); urlSource.setUri("Playback URL");// Set the absolute path of the 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 downloader provides multiple event listeners. The following code provides an example:
-(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.
You can use the
preparemethod to prepare the download source. Both VidSts and VidAuth methods are supported. The following code provides an example:VidSts
// Create VidSts. AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init]; stsSource.region = @"Access region"; // The access region of ApsaraVideo VOD. Default is cn-shanghai. stsSource.vid = @"Vid information"; // The video ID. stsSource.securityToken = @"<yourSecurityToken>"; // The STS token. You need to call the AssumeRole API operation of STS to generate it. stsSource.accessKeySecret = @"<yourAccessKeySecret>"; // The AccessKey secret of the temporary STS AccessKey pair. You need to call the AssumeRole API operation of STS to generate it. stsSource.accessKeyId = @"<yourAccessKeyId>"; // The AccessKey ID of the temporary STS AccessKey pair. You need to call the AssumeRole API 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, as shown 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. authSource.playAuth = @"<yourPlayAuth>"; // The playback credential. You need to call the GetVideoPlayAuth API operation of ApsaraVideo VOD to generate it. authSource.region = @"Access region"; // For player SDKs V5.5.5.0 and later, this parameter is deprecated. You do not need to set the region; the player will automatically parse it. For player SDKs earlier than V5.5.5.0, this parameter is required. The access region of ApsaraVideo VOD, 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, as shown 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 have enabled HLS standard encryption parameter pass-through in the VOD console, and the default parameter name is `MtsHIsUriToken` (for more information, see HLS standard encryption parameter pass-through), please set the `MtsHIsUriToken` value into the VOD source as shown in the code above.
After successful preparation, select a download item.
After the preparation is successful, the
onPreparedmethod is called back. The returned `TrackInfo` contains information such as the definition of each video stream. You can 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, download the first TrackInfo. [downloader selectTrack:[tracks objectAtIndex:0].trackIndex]; }Update the download source and start the download.
To prevent VidSts and VidAuth from expiring, we recommend that you update the download 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];After the download succeeds or fails, release the downloader.
After the download is successful, you can call
destroyto release the downloader.[self.downloader destroy]; self.downloader = nil;
Play downloaded videos
Videos that are downloaded can be played only based on 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 by performing the following steps: obtain the custom storage path and file name from
downloadedFilePath, retrieve the sandbox directory, and then concatenate the custom storage path, file name, and sandbox directory.NSString *downloadedFilePath = downloader.downloadedFilePath;You can use the VOD UrlSource to set an absolute path for playback.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:downloadedFilePath]; [self.player setUrlSource:urlSource];