All Products
Search
Document Center

:Advanced features

Last Updated:Jan 28, 2026

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 lets you add and switch external subtitles. Only subtitle files in the .srt format are supported. Sample code:

  1. Create a control to display subtitles.

    You can create different views for subtitles in different formats.

    mSubtitleLabelPtr = new QLabel(QString(""), this);
    mSubtitleLabelPtr->setParent(this);
  2. Configure listeners for subtitles.

    // An external subtitle is added.
    void AlivcLivePlayerMainDlg::onSubtitleExtAdded(AliPlayer *player, int64_t trackIndex, const char *URL)
    {
        emit SgnAddExtSubtitle((qint64) trackIndex);
    }
    // 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);
    }
    // Callback for hiding the subtitle.
    void AlivcLivePlayerMainDlg::onSubtitleHide(AliPlayer *player, int64_t trackIndex, int64_t subtitleId)
    {
        emit SgnUpdateSubtitle(QString(""), false);
    }
  3. Add subtitles.

    mPlayerPtr->addExtSubtitle("url");
  4. Switch subtitles.

    mPlayerPtr->selectExtSubtitle(trackIndex, true);

Enable audio-only playback

To enable audio-only playback, you can disable video playback. You must configure PlayerConfig before you call the prepare method.

AVPConfig *config = mPlayerPtr->getConfig();
config->mDisableVideo = true;
mPlayerPtr->setConfig(config);

Adaptive bitrate streaming

ApsaraVideo Player SDK for Windows supports adaptive bitrate streaming for HTTP Live Streaming (HLS) and Dynamic Adaptive Streaming over HTTP (DASH) video streams. After the prepare method is successfully called, you can call getMediaInfo to obtain information about each stream, which is returned as TrackInfo. Sample code:

AVPMediaInfo info = mPlayerPtr->getMediaInfo();
for (int i = 0; i < info.trackCount; i++) {
     AVPTrackInfo *track = info.tracks[i];
}
Note

HLS and DASH video streams must be packaged using a multi-bitrate transcoding template group. In the ApsaraVideo VOD console, go to Configuration Management > Media Processing > Transcoding Template Groups to configure and generate the required video streams. For more information, see Set video or caption packaging templates.

During playback, you can call the selectTrack method of the player to switch the stream bitrate. If you set the value to SELECT_AVPTRACK_TYPE_VIDEO_AUTO, 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);

The result of the switch is returned in the onTrackChanged listener callback. Sample code:

void AlivcLivePlayerMainDlg::onTrackChanged(AliPlayer *player, AVPTrackInfo *info)
{
    if (info->trackType == AVPTRACK_TYPE_VIDEO) {
        // video changed
    }
    // etc
}

Capture snapshots

You can call the snapShot method of the ApsaraVideo Player SDK for Windows to capture a snapshot of the current video. The snapshot is returned in ARGB32 format through the onSnapshotImageBuffer callback. Sample code:

// Capture a snapshot of the current video frame.
mPlayerPtr->snapshot();
// 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);
}
Important

Snapshots do not include the user interface.

Preview

ApsaraVideo Player SDK for Windows lets you 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 Preview videos.

After you configure the preview feature, call the setPreviewTime method of the VidPlayerConfigGenerator interface to set the preview duration for the player. When you set a preview duration and play a video using the SDK, the server returns only the content for the preview period instead of the full video content. The following sample code shows an example of playback using VidSts:

VidPlayerConfigGenerator playConfigGen;
playConfigGen.setPreviewTime(10);
AVPVidStsSource vidSource;
vidSource.initWithVid("Video ID",
                        "accessKeyId",
                        "accessKeySecret",
                        "Security token",
                        "Region",
                        playConfigGen.generatePlayerConfig());
mPlayerPtr->setSource(vidSource);

Set the referer

ApsaraVideo Player SDK for Windows supports setting a Referer. You can use the Referer with blacklists and whitelists in the console to control access privileges. Use the AVPConfig interface to set the request Referer. Sample code:

// Obtain the configurations.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the Referer.
pConfig->referer = referer;
....// Other settings.
// Set the configurations for the player.
mPlayerPtr->setConfig(pConfig);

Specify the user agent

ApsaraVideo Player SDK for Windows provides AVPConfig to set the request User-Agent (UA). After you set the UA, the player includes the UA information in its requests. Sample code:

// Obtain the configurations.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the User-Agent.
pConfig->userAgent = userAgent;
....// Other settings.
// Set the configurations for the player.
mPlayerPtr->setConfig(pConfig);

Specify the network timeout period and number of retries

ApsaraVideo Player SDK for Windows supports setting the network timeout period and the number of retries. You can use the AVPConfig interface to configure these settings. Sample code:

// Obtain the configurations.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the network timeout period in milliseconds.
pConfig->networkTimeout = 5000;
// Set the number of retries upon a timeout. The retry interval is the value of networkTimeout. If you set networkRetryCount to 0, no retry is performed. The retry policy is determined by the app. Default value: 2.
pConfig->networkRetryCount = 2;
....// Other settings.
// Set the configurations for the player.
mPlayerPtr->setConfig(pConfig);
Note
  • If you set networkRetryCount, the player retries the specified number of times if a network issue causes loading. The interval for each retry is the value of networkTimeout.

  • If the loading state persists after the maximum number of retries is reached, the onError event is triggered. In this case, the value of AVPErrorModel.code is ERROR_LOADING_TIMEOUT.

  • If networkRetryCount is set to 0, the player triggers the onPlayerEvent callback when a network retry times out. The eventWithString parameter is EVENT_PLAYER_NETWORK_RETRY. At this point, you can call the player's reload method to reload the network or perform other actions.

Control the buffer and latency

Cache control is critical for a player. Proper configuration can speed up startup and reduce stuttering. ApsaraVideo Player SDK for Windows provides interfaces in AVPConfig to control the cache and latency. Sample code:

// Obtain the configurations.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// The maximum latency. Note: This parameter is valid only for live streaming. If the latency is high, the SDK performs operations such as frame synchronization to keep the latency within this range.
pConfig->maxDelayTime = 5000;
// The maximum buffer duration in milliseconds. The player loads a maximum of the specified duration of data into the buffer at a time.
pConfig->maxBufferDuration = 50000;
// The high buffer watermark in milliseconds. When the player loads data due to poor network conditions, the loading state ends if the buffered data reaches this duration.
pConfig->highBufferDuration = 3000;
// The startup buffer duration in milliseconds. A smaller value indicates a faster startup. However, the player may enter the loading state soon after playback starts.
pConfig->startBufferDuration = 500;
// Other settings.
// Set the configurations for the player.
mPlayerPtr->setConfig(pConfig);
Important

The three buffer durations must satisfy the following condition: startBufferDuration ≤ highBufferDuration ≤ maxBufferDuration.

Configure HTTP headers

Using the AVPConfig parameter, you can add HTTP header parameters to requests from the player. Sample code:

// Obtain the configurations.
AVPConfig *pConfig = mPlayerPtr->getConfig();
// Set the header.
pConfig->headerCount = 1;
pConfig->httpHeaders = new char *[pConfig->headerCount];
// For example, if you use HTTPDNS, you must set the Host.
pConfig->httpHeaders[0] = strdup("Host:example.com");
....// Other settings.
// Set the configurations for the player.
mPlayerPtr->setConfig(pConfig);

Performance

Local cache

ApsaraVideo Player SDK for Windows provides a local caching feature that lets you cache content during playback. This feature saves data traffic when users play a video repeatedly. To implement this feature, configure AVPCacheConfig for the player before you call the prepare method. Sample code:

AVPCacheConfig mCacheConfig;
// Enable the caching feature.
mCacheConfig.enable = true;
// The maximum duration of a single file that can be cached. Files that exceed this duration are not cached.
mCacheConfig.maxDuration = 100;
// The maximum size of the cache directory. If the size limit is exceeded, the oldest cached files are deleted.
mCacheConfig.maxSizeMB = 200;
// The path of the cache directory. Replace this with the desired path for your app.
mCacheConfig.path = strdup("please use your cache path here");
// Set the cache configurations for the player.
mPlayerPtr->setCacheConfig(&mCacheConfig);

If you have configured setCacheConfig, the cached file is used in the following situations after a video is successfully cached.

  • If loop playback is enabled, the cached file is automatically used for playback starting from the second loop.

  • If you create a new player to play the same resource after the video is successfully cached, the cached file is also automatically used.

    Important

    For VID-based playback, the player uses information such as the video ID (VID) from online requests to locate cached files. Therefore, the player can determine which cached file to use only after it receives information from network requests.

The cache-while-playing feature is subject to the following conditions:

  • For playback using UrlSource, HLS (M3U8) streams are not cached. Other supported formats are cached according to the cache configuration.

  • For playback using VidAuth or VidSts, videos are cached according to the cache configuration.

  • Caching is considered successful only after the player reads all the data. If you call the stop method or an onError event occurs before the download is complete, the caching process fails.

  • Seeking within the cached content does not affect the caching result. Seeking outside the cached content causes the caching process to fail.

  • If the security file is inconsistent with the app information, the caching process fails.

  • The caching result is returned in the onPlayerEvent callback. The callback includes EVENT_PLAYER_CACHE_SUCCESS and EVENT_PLAYER_CACHE_ERROR.

Video download

ApsaraVideo Player SDK for Windows provides a download feature for ApsaraVideo VOD videos. This feature allows users to cache videos locally for offline viewing with ApsaraVideo Player. Two download modes are available: normal download and secure 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

  • The video download feature is supported only for playback using VidSts and VidAuth.

  • To use the video download feature of the player, you must enable and configure the download mode in the ApsaraVideo VOD console. For more information, see Offline download.

  • Resumable download is supported.

Procedure

  1. Optional: Configure the security file for encryption verification. You must configure the security file only when you use the secure download mode.

    Note

    Ensure that the configured encryption and verification file is consistent with the app 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 Enable secure download.

    You need to configure this only once. Sample code:

    InitPrivateService(fileContentBuffer, fileLength);
  2. Create and configure a downloader.

    For example:

    mMediaDownloader = AliMediaDownloader::CreateMediaDownloader();
    mMediaDownloader->setListener(new AVDListenerImpl);
    mMediaDownloader->setSaveDirectory("saveDir");
  3. Prepare the download source.

    Call the prepare method to prepare the download source. Only VidAuth (recommended) and VidSts download sources are supported. The following sample code shows an example of a VidSts download source:

    AVPVidStsSource vidSource;
    vidSource.initWithVid("Video ID",
                          "accessKeyId",
                          "accessKeySecret",
                          "Security token",
                          "Region",
                          nullptr);
    mMediaDownloader->prepareWithVid(&vidSource);
  4. Select the content that you want to download from the prepared download source.

    After the source is prepared, the onPrepared method is triggered. The returned TrackInfo contains information about each video stream, such as the definition. Select a track to download. Sample code:

    void YourClass::onPrepared(AliMediaDownloader *downloader, AVPMediaInfo *mediaInfo) {
        AVPTrackInfo *track = mediaInfo->tracks[0];
        mMediaDownloader->selectTrack(track->trackIndex);
    }
  5. Update the download source and start the download.

    To prevent VidSts and VidAuth from expiring, update the download source information before you start the download. Sample code:

    mMediaDownloader->updateWithVid(&vidSource);
    mMediaDownloader->start();
  6. Release the download object after the download succeeds or fails.

    After the download is successful, release the downloader. Sample code:

    delete mMediaDownloader;
    mMediaDownloader = nullptr;

References

API operations