This topic describes the advanced features of ApsaraVideo Player SDK for Windows and provides the sample code.
Configure video playback
Configure external subtitles
ApsaraVideo Player SDK for Windows allows you to add and switch external subtitles. Only subtitle files in the .srt format are supported. Sample code:
- Create a control to display subtitles. You must create different views for subtitles in different formats.
mSubtitleLabelPtr = new QLabel(QString(""), this); mSubtitleLabelPtr->setParent(this);
- Configure listeners for subtitles.
// Listens to the callback for adding an external subtitle. void AlivcLivePlayerMainDlg::onSubtitleExtAdded(AliPlayer *player, int64_t trackIndex, const char *URL) { emit SgnAddExtSubtitle((qint64) trackIndex); } // Listens to the callback for displaying the subtitle. void AlivcLivePlayerMainDlg::onSubtitleShow(AliPlayer *player, int64_t trackIndex, int64_t subtitleId, const char *subtitle) { emit SgnUpdateSubtitle(QString::fromStdString(subtitle), true); } // Listens to the callback for hiding the subtitle. void AlivcLivePlayerMainDlg::onSubtitleHide(AliPlayer *player, int64_t trackIndex, int64_t subtitleId) { emit SgnUpdateSubtitle(QString(""), false); }
- Add subtitles.
mPlayerPtr->addExtSubtitle("url");
- Switch subtitles.
mPlayerPtr->selectExtSubtitle(trackIndex, true);
Enable audio-only playback
AVPConfig *config = mPlayerPtr->getConfig();
config->mDisableVideo = true;
mPlayerPtr->setConfig(config);
Adaptive bitrate streaming
prepare
method is called, call getMediaInfo
to obtain the stream information that is indicated by TrackInfo
. Sample code:AVPMediaInfo info = mPlayerPtr->getMediaInfo();
for (int i = 0; i < info.trackCount; i++) {
AVPTrackInfo *track = info.tracks[i];
}
selectTrack
to switch to the required bitrate. If you specify SELECT_AVPTRACK_TYPE_VIDEO_AUTO in the method, adaptive bitrate streaming is enabled. Sample code:// Switch the bitrate.
mPlayerPtr->selectTrack(trackIndex);
// Switch to the adaptive bitrate.
mPlayerPtr->selectTrack(SELECT_AVPTRACK_TYPE_VIDEO_AUTO);
onTrackChanged
method returns the switching result. Sample code:void AlivcLivePlayerMainDlg::onTrackChanged(AliPlayer *player, AVPTrackInfo *info)
{
if (info->trackType == AVPTRACK_TYPE_VIDEO) {
// video changed
}
// etc
}
Capture snapshots
snapShot
operation to capture video snapshots. The player saves the captured snapshots in the ARGB32 format. You can obtain the information about the captured snapshots after the onSnapshotImageBuffer
callback is invoked. Sample code:// Capture a snapshot of the current video image.
mPlayerPtr->snapshot();
// Configure the callback for snapshot capture.
void AlivcLivePlayerMainDlg::onSnapshotImageBuffer(AliPlayer *player, int width, int height, unsigned char *pARGBBuffer)
{
QString savePath = "save path";
QImage snapshot(pARGBBuffer, width, height, QImage::Format_ARGB32);
snapshot.save(savePath);
}
Configure video preview
ApsaraVideo Player SDK for Windows allows you to configure the preview feature in ApsaraVideo VOD. This feature supports VidAuth and VidSts sources. We recommend that you use VidAuth for playback. For more information about how to configure and use the preview feature, see Configure the preview feature.
setPreviewTime
operation in VidPlayerConfigGenerator
to specify the preview duration. After you specify the preview duration, ApsaraVideo Player SDK for Windows allows you to preview a video for the specified duration instead of the whole video. The following sample code provides an example. In this example, VidSts is used.VidPlayerConfigGenerator playConfigGen;
playConfigGen.setPreviewTime(10);
AVPVidStsSource vidSource;
vidSource.initWithVid(Video ID,
"accessKeyId",
"accessKeySecret",
"Security token",
"Access region ID",
playConfigGen.generatePlayerConfig());
mPlayerPtr->setSource(vidSource);
Set the referer
AVPConfig
class for you to set the request referer. You can use the referer together with a referer whitelist or blacklist configured in the ApsaraVideo VOD console to implement access control. Sample code:// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the referer.
pConfig->referer = referer;
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
Specify the user agent
// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Specify the user agent.
pConfig->userAgent = userAgent;
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
Specify the network timeout period and number of retries
AVPConfig
class for you to set the network timeout period and number of retries. Sample code:// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the network timeout period. Unit: milliseconds.
pConfig->networkTimeout = 5000;
// Specify the maximum number of retries upon a network timeout. The retry interval equals the timeout period specified by the NetworkTimeout parameter. The networkRetryCount parameter specifies the maximum number of retries. A value of 0 indicates zero retry. The application determines the maximum number of retries. Default value: 2.
pConfig->networkRetryCount = 2;
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
- If you set the networkRetryCount parameter to a value other than 0, the player retries playback when the player starts to load data due to a network error. The maximum number of retries is equal to the value of the networkRetryCount parameter. The retry interval is equal to the value of the networkTimeout parameter.
- If loading persists after the maximum number of retries is reached, a callback is invoked by the onError event. In this case, AVPErrorModel.code returns ERROR_LOADING_TIMEOUT.
- If you set the networkRetryCount parameter to 0, a callback is invoked by the onPlayerEvent event when a network timeout occurs. In this case, eventWithString returns EVENT_PLAYER_NETWORK_RETRY. To resolve the issue, you can call the reload method provided by ApsaraVideo Player SDK to reload network packets or perform other operations based on your business requirements.
Control the buffer and latency
AVPConfig
class to allow you to configure buffer settings and latency settings. Sample code:// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the maximum latency. This parameter is valid only for live streaming. If the latency exceeds the maximum limit, ApsaraVideo Player SDK synchronizes frames to ensure that the latency does not exceed the limit.
pConfig->maxDelayTime = 5000;
// Set the maximum buffer duration. Unit: milliseconds. This parameter specifies the maximum buffer duration for the player to load data at a time.
pConfig->maxBufferDuration = 50000;
// Set the peak buffer duration. Unit: milliseconds. This parameter specifies the peak buffer duration. After the peak buffer duration elapses, the player stops loading data when the network conditions are poor.
pConfig->highBufferDuration = 3000;
// Set the startup buffer duration Unit: milliseconds. A smaller value indicates a shorter startup buffer duration. In this case, the player starts to load data sooner after the playback starts.
pConfig->startBufferDuration = 500;
// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
Configure HTTP headers
AVPConfig
class for you to configure HTTP headers for the player. Sample code:// Obtain the configuration information.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Configure the header.
pConfig->headerCount = 1;
pConfig->httpHeaders = new char *[pConfig->headerCount];
// Configure a host when you use Alibaba Cloud HTTPDNS.
pConfig->httpHeaders[0] = strdup("Host:example.com");
....// Configure other settings.
// Configure the settings for the player.
mPlayerPtr->setConfig(pConfig);
Configure the performance
Configure local caching
AVPCacheConfig mCacheConfig;
// Enable the local caching feature.
mCacheConfig.enable = true;
// Specify the maximum duration of a single cached file. Files whose duration exceeds the upper limit are not cached.
mCacheConfig.maxDuration = 100;
// Specify the maximum size of the cache directory. If the total size of cached files in the cache directory exceeds the upper limit, the earliest cached files are overwritten.
mCacheConfig.maxSizeMB = 200;
// Set the cache directory to the directory required by your application.
mCacheConfig.path = strdup("please use your cache path here");
// Configure the cache settings for the player.
mPlayerPtr->setCacheConfig(&mCacheConfig);
You must call setCacheConfig to use cached files. Cached files are used in the following scenarios:- If you enable the loop playback feature, the player automatically replays a video by using the cached video file each time the playback is complete.
- After you cache a video and create a player to play the video, the new player plays the video by using the cached video file. Important The player uses information such as the video ID from online requests to find cached files for video ID-based playback.
- If you use UrlSource for video playback and the playback URL is in the HLS format, the player does not cache the video during playback. If the playback URL is in other formats, the player caches videos during playback based on your configuration.
- If you use VidAuth or VidSts for playback, the player caches videos during playback based on your configuration.
- A video is cached after the player reads all video data. Caching fails if the
stop
method is called or theonError
callback is invoked before the player reads all video data. - In-buffer seeking does not affect the caching result. Seeking to a position outside the buffer may cause a caching failure.
- If the security file does not match the application information, the video caching fails.
- You can check the caching result from the
onPlayerEvent
callback.EVENT_PLAYER_CACHE_SUCCESS
indicates that the video is cached andEVENT_PLAYER_CACHE_ERROR
indicates that the video is not cached.
Configure video download
- Normal download
Videos that are downloaded in normal download mode are not encrypted by Alibaba Cloud and can be played by third-party players.
- Secure download
Videos that are downloaded in secure download mode are encrypted by Alibaba Cloud. You can only use ApsaraVideo Player to play these videos.
Usage notes
- You can download only videos that are played based on VidSts or VidAuth.
- To use the video download feature, you must enable the feature and configure the download mode in the ApsaraVideo VOD console. For more information, see Configure download settings.
- Resumable download is supported.
Procedure
- Optional:Configure the security file for encryption verification. You must configure the security file only when you use the secure download mode. Note Make sure that the information in the security file for encryption verification matches the application information. Otherwise, the video download fails.
If you use the secure download mode, you must configure the key file generated in the ApsaraVideo VOD console in ApsaraVideo Player SDK. The key file is used to decrypt and verify the video for download and playback. For more information about how to generate the key file, see Secure download.
You need to configure the key file only once. Sample code:InitPrivateService(fileContentBuffer, fileLength);
- Create and configure a downloader. Sample code:
mMediaDownloader = AliMediaDownloader::CreateMediaDownloader(); mMediaDownloader->setListener(new AVDListenerImpl); mMediaDownloader->setSaveDirectory("saveDir");
- Prepare the download source. You can call the
prepare
method to prepare the download source. VidSts and VidAuth are supported as download sources. We recommend that you use VidAuth sources. The following sample code provides an example In this example, VidSts is used.AVPVidStsSource vidSource; vidSource.initWithVid("Video ID", "accessKeyId", "accessKeySecret", "Security token", "Access region ID", nullptr); mMediaDownloader->prepareWithVid(&vidSource);
- Select the content that you want to download from the prepared download source. After the download source is prepared, a callback is invoked by the
onPrepared
event. The value of the TrackInfo parameter indicates the information about video tracks such as video definitions. Select a track to download. Sample code:void YourClass::onPrepared(AliMediaDownloader *downloader, AVPMediaInfo *mediaInfo) { AVPTrackInfo *track = mediaInfo->tracks[0]; mMediaDownloader->selectTrack(track->trackIndex); }
- Update the download source and start the download. VidSts or VidAuth may expire before the download. Therefore, we recommend that you update the download source before you start the download. Sample code:
mMediaDownloader->updateWithVid(&vidSource); mMediaDownloader->start();
- Release the download object after the download succeeds or fails. Release the download object after the download succeeds. Sample code:
delete mMediaDownloader; mMediaDownloader = nullptr;