All Products
Search
Document Center

ApsaraVideo VOD:Advanced features

Last Updated:Mar 14, 2024

This topic describes the advanced features of ApsaraVideo Player SDK for iOS and provides sample code. For more information about the features, see API operations for ApsaraVideo Player SDK for iOS.

Configure playback

Enable list playback for short videos

ApsaraVideo Player SDK for iOS provides a full-fledged list playback feature for short videos. The SDK uses features such as preloading to minimize the startup time of short videos. We recommend that you do not enable this feature for long videos.

Procedure

  1. Create a player.

    Create an AliListPlayer object. Sample code:

    self.listPlayer = [[AliListPlayer alloc] init];
    [listPlayer setTraceID:@"xxxxxx"];  // TraceID indicates the unique identifier of the device or the user. In most cases, the value is the International Mobile Equipment Identity (IMEI) or the Identifier for Advertisers (IDFA) of the device.

  2. Optional. Configure listeners.

    Listeners are optional when you create a short video list player. If you do not configure listeners, you cannot receive notifications of events related to the player, such as the failure and progress of the playback. We recommend that you configure listeners as needed.

    You can configure multiple listeners for your player. We recommend that you configure the following listeners: onPlayerEvent and onError.

    /**
     @brief The callback for an invalid delegate.
     @param player The pointer of the player.
     @param errorModel The description of player errors. For more information, see AliVcPlayerErrorModel.
     */
    - (void)onError:(AliPlayer*)player errorModel:(AVPErrorModel *)errorModel {
        // Indicates that an error occurred and the playback is stopped.
    }
    /**
     @brief The callback for player events.
     @param player The pointer of the player.
     @param eventType The event type of the player. This parameter is similar to the AVPEventType parameter.
     */
    -(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
        switch (eventType) {
            case AVPEventPrepareDone: {
                // The preparation is complete.
            }
                break;
            case AVPEventAutoPlayStart:
                // The autoplay starts.
                break;
            case AVPEventFirstRenderedStart:
                // The first frame appears.
                break;
            case AVPEventCompletion:
                // The playback is complete.
                break;
            case AVPEventLoadingStart:
                // The buffering starts.
                break;
            case AVPEventLoadingEnd:
                // The buffering is complete.
                break;
            case AVPEventSeekEnd:
                // The seeking is complete.
                break;
            case AVPEventLoopingStart:
                // The loop playback starts.
                break;
            default:
                break;
        }
    }
    /**
     @brief The callback for the current playback position.
     @param player The pointer of the player.
     @param position The current playback position.
     */
    - (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position {
        // Updates the playback progress.
    }
    /**
     @brief The callback for the buffer position.
     @param player The pointer of the player.
     @ param position The current buffer position.
     */
    - (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position {
        // Updates the buffering progress.
    }
    /**
     @brief The callback for obtaining the track information.
     @param player The pointer of the player.
     @param info The array of track information. For more information, see AVPTrackInfo.
     */
    - (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info {
        // Obtains information about different bitrates.
    }
    /**
     @brief The callback for displaying the subtitle.
     @param player The pointer of the player.
     @param index The index number of the subtitle.
     @param subtitle The string of the subtitle.
     */
    - (void)onSubtitleShow:(AliPlayer*)player index:(int)index subtitle:(NSString *)subtitle {
        // Obtains the subtitle for display.
    }
    /**
     @brief The callback for hiding the subtitle.
     @param player The pointer of the player.
     @param index The index number of the subtitle.
     */
    - (void)onSubtitleHide:(AliPlayer*)player index:(int)index {
        // Hides the subtitles.
    }
    /**
     @brief The callback for snapshot capture.
     @param player The pointer of the player.
     @param image The image.
     */
    - (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
        // Previews and saves the snapshot.
    }
    /**
     @brief track The callback that indicates the track is switched.
     @param player The pointer of the player.
     @param info The information about the track after the switching is complete. For more information, see AVPTrackInfo.
     */
    - (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info {
        // Notifies the result of track switching.
    }
    //...
  3. Specify the number of videos that you want to preload.

    You can specify the number of videos that you want to preload based on your business requirements. This way, the startup time can be decreased. Sample code:

    // Specify the number of videos that you want to preload. The total number of loaded videos is equal to one plus twice the specified number. 
    self.listplyer.preloadCount = 2;
  4. Add or remove multiple playback sources.

    List playback supports the VidSts and UrlSource playback sources. Url indicates the playback URL. vid indicates the audio or video ID. Sample code:

    • Url: The playback URL can be the URL of an audio file or a video file in ApsaraVideo VOD or on a third-party video-on-demand (VOD) platform.

      You can call the GetPlayInfo operation to obtain the playback URL of an audio file or a video file in ApsaraVideo VOD. We recommend that you use ApsaraVideo VOD SDKs to obtain media playback URLs. This frees you from complex signature calculations. For more information about the GetPlayInfo operation, visit OpenAPI Explorer.

    • Vid: The audio or video ID. To obtain the ID, log on to the ApsaraVideo VOD console and choose Media Files > Audio/Video in the left-side navigation pane. Alternatively, you can call the SearchMedia operation.

    // Add a VidSts playback source.
    [self.listPlayer addVidSource:videoId uid:UUIDString];
    // Add a UrlSource playback source.
    [self.listPlayer addUrlSource:URL uid:UUIDString];
    // Remove a playback source.
    [self.listPlayer removeSource:UUIDString];
    Note
    • VidAuth is not supported for list playback.

    • The uid parameter indicates the unique ID of a video. You can use the unique ID to identify videos. Videos that have the same unique ID are considered the same. If the player plays a video that is not the one you specified, check whether you specify the same ID for multiple videos. You can set the unique ID to any string that you prefer.

  5. Configure the UI view.

    If the playback source contains video images, you must configure the UI view to display the video images in the player. Sample code:

    self.listPlayer.playerView = self.simplePlayScrollView.playView;
  6. Play the video source.

    After you add one or more playback sources, call moveTo to play the content from the specified playback source. Sample code:

    // Call moveTo for UrlSource playback sources.
    - (BOOL) moveTo:(NSString*)uid;
    // Call moveTo for VidSts playback sources. If you want to use VidSts playback sources, you must obtain the STS token and AccessKey pair in advance. For more information, see Create a RAM role and grant temporary access permissions to the role by using STS. 
    - (BOOL) moveTo:(NSString*)uid accId:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
  7. Play the previous or next video in the list.

    After you call moveTo to play a video, you can call moveToPrev to play the previous video or call moveToNext to play the next video. Sample code:

    UrlSource

    // Play the next video. 
    - (BOOL) moveToNext;
    // Play the previous video. 
    - (BOOL) moveToPre;

    VidSts

    // Play the next video. 
    - (BOOL) moveToNext:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
    // Play the previous video. 
    - (BOOL) moveToPre:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
  8. Optional. Enable the pre-rendering feature to ensure smooth video switching.

    Note

    The pre-rendering feature is supported only in ApsaraVideo Player SDK for iOS V5.5.2.0 or later. You must enable local caching to use this feature. For more information, see Configure local caching.

    The getPreRenderPlayer and moveToNextWithPrerendered operations are provided in ApsaraVideo Player SDK for iOS V5.5.2.0 or later to improve the smoothness of video switching. The following section describes how to use the operations when you integrate different versions of ApsaraVideo Player SDK for iOS.

    ApsaraVideo Player SDK for iOS V5.5.2.0 or later integrated

    Use getPreRenderPlayer. Sample code:

    AliPlayer *prePlayer = [self.listPlayer getPreRenderPlayer];
    if (prePlayer != nil) {
        prePlayer.autoPlay = YES;
            prePlayer.playerView  = playerView;
            [prePlayer prepare];
    
      [self.listPlayer moveToNextWithPrerendered];
    }

    ApsaraVideo Player SDK for iOS updated from an earlier version to V5.5.2.0 or later

    You must modify the code in the earlier version of ApsaraVideo Player SDK for iOS. The following section describes how to modify the code.

    1. Create a render view.

      • If you use UIScrollView to manage render views, you must configure playerView for every playback source. Then, specify playerView when you call moveToNext and moveToPre.

      • If you use UITableView to manage render views, we recommend that you create cells based on your business requirements and configure playerView in each cell.

    2. Modify the logic for switching video sources.

      In ApsaraVideo Player SDK for iOS V5.5.2.0 or later, preRenderPlayer is added. You must configure separate logic for playerView. The logic of the moveToNext operation is different from that of the moveToPre operation. Sample code:

      • moveToNext

        // Check whether prePlayer exists before you call moveToNext.
        AliPlayer *prePlayer = [self.listPlayer getPreRenderPlayer];
        if (prePlayer) {
            prePlayer.autoPlay = YES;
            prePlayer.playerView = playerView;
            [prePlayer prepare];
        } else {
            self.listPlayer.playerView = playerView;
        }
        
        if (prePlayer) {
        [self.listPlayer moveToNextWithPrerendered];
        } else {
        [self.listPlayer moveToNext];
        }
      • moveToPre

        // Configure playerView before you call moveToPre.
        [self.listPlayer getCurrentPlayer].playerView = playerView;
        [self.listPlayer moveToPre];
    3. Optional. Modify the logic of playlist playback.

      You can modify the logic of playlist playback to start the playback of the next video when half of the view of the next video is displayed. Listen to the UIScrollViewDelegate callback to start the playback of the next video when half of the view of the next video is displayed. Then, configure the global parameter currentIndex to change the index file after the video is switched. Sample code:

      - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
      CGFloat offsetY = scrollView.contentOffset.y;
      if (offsetY < 0) {
      return;
      }
      
      NSInteger index = lroundf(offsetY/[UIScreen mainScreen].bundle.size.height);
      if (self.currentIndex != index) {
      if (offsetY - CGRectGetMinY(currentPlayView.frame) >= [UIScreen mainScreen].bundle.size.height / 2.0) {
      self.currentIndex = index;
      // Call moveToNext.
      } else if (CGRectGetMinY(currentPlayView.frame) - offsetY >= [UIScreen mainScreen].bundle.size.height / 2.0) {
      self.currentIndex = index;
      // Call moveToPre.
      }
      }
      }

Play videos that have transparency configurations

Description

ApsaraVideo Player SDK supports rendering of videos with alpha channels to play dynamic gift videos with a transparent background. This way, you can view the dynamic effects of gifts without blocking the live video content when someone is streaming. This significantly improves the viewing and interactive experience.

Limits

You can use ApsaraVideo MediaBox SDK V6.8.0 or later and ApsaraVideo Player SDK V6.9.0 or later to render videos with transparency.

Benefits

You can use MP4 videos with transparency as gift effects. This improves the performance of dynamic effects and video compatibility, reduces the video size, and simplifies development. This also optimizes the viewing experience of the gift effects and improves user experience. Using MP4 videos with transparency as gift effects has the following benefits:

  1. Higher video quality: You can use MP4 videos to display the dynamic gift effects in the original quality, such as the original image details and colors. Compared with other video formats such as APN or IXD, MP4 can display the dynamic effect in the original quality intended by the designers.

  2. Smaller video size: Compared with other video formats such as APNG or IXD, MP4 reduces file sizes in a more efficient way. This accelerates loading and reduces the consumption of network bandwidth.

  3. Better compatibility: MP4 is a general video format that is widely supported on various devices and browsers. You can play MP4 videos that are used as gift effects on mainstream devices.

  4. Higher development efficiency: The solution of using MP4 videos as gift effects requires simple development. Instead of studying and developing complex parsing and rendering logic, developers can focus on the implementation of other features to improve development efficiency.

Sample code

The setAlphaRenderMode operation is added. You can call this operation to specify the alpha channel position of the video material. For example, you can place the alpha channel at the top, bottom, left side, or right side of the video material. By default, the value is set to None.

Note
  • The alpha channel position of the material must be the same as that you specified when you call the setAlphaRenderMode operation.

  • The size of the player view must be proportional to the resolution of the material.

/**
 @brief The rendering mode of the alpha channel. You can place the alpha channel at the top, bottom, left side, or right side of the video material. By default, the value is set to None.
 @see AVPAlphaRenderMode
 */
/****
 @brief Set a rendering mode. Support alpha at right, left, top and bottom. Default value is none.
 @see AVPAlphaRenderMode
 */
@property(nonatomic) AVPAlphaRenderMode alphaRenderMode;
//--------------Configure the view-------------
// Specify clearColor for the view.
@property (weak, nonatomic) IBOutlet UIView *mediaPlayerView;
[self.aliplayerview setBackgroundColor:UIColor.clearColor];

//-----------Configure AliPlayer-----------
// Set the alpha mode.
[self.aliplayer setAlphaRenderMode:AVP_RENDERMODE_ALPHA_AT_LEFT];
// Specify the material that corresponds to the alpha mode.
AVPUrlSource *source = [[AVPUrlSource alloc] urlWithString:@"https://alivc-player.oss-cn-shanghai.aliyuncs.com/video/%E4%B8%9A%E5%8A%A1%E9%9C%80%E6%B1%82%E6%A0%B7%E6%9C%AC/alpha%E9%80%9A%E9%81%93/alpha_left.mp4"];
[self.aliplayer setUrlSource:source];

// Optional. If a connection error occurs when the playback of videos in a player instance is complete, you can clear the view.
#pragma mark -- AVPDelegate
- (void)onPlayerEvent:(AliPlayer *)player eventType:(AVPEventType)eventType {
    switch (eventType) {
        case AVPEventCompletion:
        {
            [player clearScreen];
        }
            break;
        //...
    }
}

[self.aliplayer setAutoPlay: YES];
[self.aliplayer prepare];

Use the Metal framework for rendering

ApsaraVideo Player SDK for iOS allows you to use the Metal framework to render videos.

Note

You can use the Metal framework to set the background color, scaling mode, and picture-in-picture (PiP) feature.

Sample code

/**
 @ brief The video rendering type. 0 specifies the default renderer and 1 specifies the mixed renderer. Default value: 0.
 */
/****
 @brief video renderType, 0 means default render; 1 means mixed render.
 */
@property(nonatomic, assign) int videoRenderType;

Example

AVPConfig *config = [self.player getConfig];
// Use the Metal framework to render videos.
config.videoRenderType = 1;
[self.player setConfig:config];
[self.player prepare];

Configure external subtitles

ApsaraVideo Player SDK for iOS allows you to add, turn on, and turn off external subtitles that are in the SubRip Subtitle (SRT) format, SubStation Alpha (SSA) format, Advanced SubStation Alpha (ASS) format, or Web Video Text Track (WebVTT) format. Sample code:

  1. Create a view that displays the subtitles.

    You must create different views for subtitles in different formats.

    // Initialize the custom subTitleLabel view.
    UILabel *subTitleLabel = [[UILabel alloc] initWithFrame:frame];
    // Add the subTitleLabel view to a custom superView, which is the parent view of the custom user interface.
    [superView addSubview:subTitleLabel];
  2. Configure listeners for subtitles.

    // The callback is invoked when an external subtitle is added.
    - (void)onSubtitleExtAdded:(AliPlayer*)player trackIndex:(int)trackIndex URL:(NSString *)URL {}
    // The callback is invoked when the subtitle header information is obtained.
    - (void)onSubtitleHeader:(AliPlayer *)player trackIndex:(int)trackIndex Header:(NSString *)header{}
    // The callback is invoked when the subtitle is displayed.
    - (void)onSubtitleShow:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID subtitle:(NSString *)subtitle {
     subTitleLabel.text =subtitle;
     subTitleLabel.tag =subtitleID;
    }
    // The callback is invoked when the subtitle is hid.
    - (void)onSubtitleHide:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID{
      [subTitleLabel removeFromSuperview];
    }
  3. Add subtitles.

    [self.playeraddExtSubtitle:URL];
  4. Switch subtitles.

    [self.playerselectExtSubtitle:trackIndexenable:YES];

Enable audio-only playback

You can disable the display of video images to enable audio-only playback. Before you call the prepare method, configure the PlayerConfig class.

AVPConfig *config = [self.player getConfig];
config.disableVideo = YES;
[self.player setConfig:config];

Switch between hardware decoding and software decoding

ApsaraVideo Player SDK for iOS supports hardware decoding based on the H.264 standard and H.265 standard. You can call enableHardwareDecoder to enable or disable the hardware decoding feature. By default, hardware decoding is enabled. If hardware decoding fails to be initialized, software decoding is automatically used to ensure video playback. Sample code:

// Enable hardware decoding. By default, hardware decoding is enabled.
self.player.enableHardwareDecoder = YES;

If you switch hardware decoding to software decoding, the onPlayerEvent callback is invoked. Sample code:

-(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description {
    if (eventWithString == EVENT_SWITCH_TO_SOFTWARE_DECODER) {
        // Switch to software decoding.
    }
}

Adaptive bitrate streaming

Note
  • You can transcode videos to HTTP Live Streaming (HLS) adaptive bitrate streams by using ApsaraVideo VOD transcoding template groups. For more information, see Implement adaptive bitrate streaming in ApsaraVideo VOD.

  • If you use Vid-based playback for adaptive bitrate streams that are transcoded by ApsaraVideo VOD, you must specify AUTO as the default playback definition. This way, the player can obtain and play adaptive bitrate streams. If you do not specify AUTO as the default playback definition, the player automatically plays video streams in low definition. For more information about the playback order based on video definitions, see FAQ about video resolution. The following sample code describes how to specify the default playback definition for VidAuth-based playback:

    AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
    authSource.definitions = @"AUTO";

ApsaraVideo Player SDK for iOS supports adaptive bitrate streaming of HLS video streams and Dynamic Adaptive Streaming over HTTP (DASH) video streams. After the prepare method is called, call getMediaInfo to obtain the bitrate information that is indicated by TrackInfo. Sample code:

AVPMediaInfo *info = [self.player getMediaInfo];
NSArray<AVPTrackInfo*>* tracks = info.tracks;

During the playback, you can call the selectTrack method 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 to the required bitrate.
[self.player selectTrack:track.trackIndex];
// Enable adaptive bitrate streaming.
[self.player selectTrack:SELECT_AVPTRACK_TYPE_VIDEO_AUTO];

The onTrackChanged callback returns the switching result. Sample code:

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

Manage snapshot jobs

ApsaraVideo Player SDK for iOS provides the snapshot method to allow you to capture snapshots from videos. When you capture a snapshot, the player saves the source data of the video image to be captured and converts the source data to a bitmap. After the snapshot is captured, you can invoke the onCaptureScreen callback to obtain the bitmap. Sample code:

// Configure the callback for snapshot capture.
- (void)onCaptureScreen:(AliPlayer *)player image:(UIImage *)image {
    // Process the snapshot.
}
// Capture a snapshot of the current video image.
aliyunVodPlayer.snapshot();
Note

A snapshot does not contain the UI.

Configure video preview

ApsaraVideo Player SDK for iOS integrates specific configurations of ApsaraVideo VOD to support previews of videos. Only VidSts sources and VidAuth sources can be previewed. We recommend that you preview only VidAuth sources in ApsaraVideo VOD. For more information about how to configure and use the preview feature, see Configure the preview feature.

After you enable the preview feature, you can call setPreviewTime in the VidPlayerConfigGen class to specify the preview duration. The following sample code provides a VidSts-based example:

AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
....
VidPlayerConfigGenerator* vp = [[VidPlayerConfigGenerator alloc] init];
[vp setPreviewTime:20];// Set the preview duration to 20s.
source.playConfig = [vp generatePlayerConfig];// Configure the settings for the player.
...

After you specify the preview duration, ApsaraVideo Player SDK for iOS allows you to preview a video for the specified duration instead of the whole video.

Note

You can use VidPlayerConfigGen to set the request parameters that are supported by the server. For more information, see Request parameters.

Set the referer

ApsaraVideo Player SDK for iOS provides the 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 *config = [self.player getConfig];
// Set the referer.
config.referer = referer;
....// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];

Specify the User-Agent

ApsaraVideo Player SDK for iOS provides the AVPConfig class to allow you to specify the User-Agent header. After you specify the User-Agent header, the player contains the user agent information in its requests. Sample code:

// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Specify the User-Agent header.
config.userAgent = userAgent;
....// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];

Specify the network timeout period and number of retries

ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to specify the network timeout period and number of retries. Sample code:

// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the network timeout period. Unit: milliseconds.
config.networkTimeout = 5000;
// Specify the maximum number of retries that can be performed after a network timeout occurs. The retry interval is equal to the timeout period that is specified for the NetworkTimeout parameter. The NetworkRetryCount parameter specifies the number of retries. A value of 0 indicates no retry. The application determines the number of retries. Default value: 2.
config.networkRetryCount = 2;
....// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];
Note
  • 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 method. In this case, ERROR_LOADING_TIMEOUT is returned for AVPErrorModel.code.

  • If you set the networkRetryCount parameter to 0, a callback is invoked by the onPlayerEvent method when a network timeout occurs. In this case, EVENT_PLAYER_NETWORK_RETRY is returned for eventWithString. To resolve the issue, you can call the reload method of ApsaraVideo Player SDK for iOS to reload network packets or perform other operations as required.

Control the buffer and latency.

Buffer control is important for a player. You can reduce the startup duration and improve playback smoothness by using proper configurations. ApsaraVideo Player SDK for iOS provides the AVPConfig class for you to configure buffer and latency settings. Sample code:

// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Set the maximum latency. Note: 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. 
config.maxDelayTime = 5000;
// Specify the maximum buffer duration. Unit: milliseconds. This parameter specifies the maximum buffer duration for the player to load data at a time. 
config.maxBufferDuration = 50000;
// Specify the peak buffer duration. Unit: milliseconds. This parameter specifies the peak buffer duration. After the peak buffer duration elapses, the player stops loading data if the network conditions are poor. 
config.highBufferDuration = 3000;
// Set the startup buffer duration Unit: milliseconds. A smaller value indicates a shorter startup buffer duration. In this case, the player may enter the loading status soon after the playback starts. 
config.startBufferDuration = 500;
// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];
Important
  • Make sure that the value of the startBufferDuration parameter is not greater than the value of the highBufferDuration parameter. Make sure that the value of the highBufferDuration parameter is not greater than the value of the maxBufferDuration parameter.

  • When mMaxBufferDuration is greater than 5 minutes, the peak buffer duration is set to 5 minutes to prevent memory exceptions that occur due to excessive buffer size. When mMaxBufferDuration is greater than 50,000 ms (50 seconds), you can enable large cache to reduce the memory usage and further improve playback performance. For more information, see Advanced features.

Configure HTTP headers

ApsaraVideo Player SDK for iOS provides the AVPConfig class to allow you to add HTTP headers to requests. Sample code:

// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Define a header.
NSMutableArray *httpHeaders = [[NSMutableArray alloc] init];
// Configure a host when you use Alibaba Cloud HTTPDNS. 
[httpHeaders addObject:@"Host:example.com"];
// Configure the headers.
config.httpHeaders = httpHeaders;
....// Configure other settings.
// Configure the settings for the player.
[self.player setConfig:config];

Configure PiP

Note
  • You can use the picture-in-picture (PiP) feature only when you use ApsaraVideo Player V5.4.9.0 or later on devices that run iOS 15 or later.

  • You can use ApsaraVideo Player SDK for iOS of a version earlier than V5.5.2.0 to call specific methods to enable or disable the PiP feature and specify whether to play videos in a floating window when the application is switched to the background. ApsaraVideo Player SDK for iOS V5.5.2.0 or later supports delegate settings for the PiP feature. This allows you to configure custom settings for the PiP feature.

  • You must enable the PiP feature on your iPhone for the PiP settings to take effect. Choose Settings > General > Picture in Picture to enable the PiP feature.

Enable the PiP feature

After the PiP feature is enabled, the video is played in a floating window when the application is switched to the background. When the application is switched to the foreground, the video is played in the application window. You can call setPictureInPictureEnable to enable the PiP feature. Before you enable the PiP feature, make sure that the player is prepared. AVPEventPrepareDone indicates that the player is prepared. Sample code:

- (void)onPlayerEvent:(AliPlayer *)player eventType:(AVPEventType)eventType {
    switch (eventType) {
        case AVPEventPrepareDone:
        {
            [self.player setPictureInPictureEnable:YES];
        }
            break;
        default:
            break;
    }
}
Note

If you want to stop the playback, you must call setPictureInPictureEnable to disable the PiP feature and then call stop.

Set the PiP delegate

The following sample code provides an example on how to pause, play, fast forward, fast backward, and replay videos in PiP mode and the interactions between the floating window and the player view. For more information about how to configure the PiP delegate, see the header file AliPlayerPictureInPictureDelegate.h of AliyunPlayer.framework in the directory of the demo for ApsaraVideo Player SDK for iOS. For more information about how to download the demo, see SDK overview and download.

  1. Set up the PiP delegate to receive event callbacks.

    [self.player setPictureinPictureDelegate:self];
  2. Configure the PiP delegate.

    1. Add a global variable to manage the status change of the player.

      // Listen for the PiP pause event.
      @property (nonatomic, assign) BOOL isPipPaused;
      // Listen for newStatus to determine whether the playback status of the player is changed.
      @property (nonatomic, assign) AVPStatus currentPlayerStatus;
      // Configure the PiP controller in the callback that indicates the PiP feature is enabled. Set the controller to nil before you end the playback in PiP mode. We recommend that you configure the PiP controller.
      @property (nonatomic, weak) AVPictureInPictureController *pipController;
      // Listen for the playback progress event. Set currentPosition to the position that is returned in the callback of the current playback progress.
      @property(nonatomic, assign) int64_t currentPosition;
      Note

      You must use the weak or assign modifier for pipController. If you use the assign modifier, make sure that you set the correct variables to null.

    2. Update the status of the PiP controller when you listen for the onPlayerStatusChanged event.

      - (void)onPlayerStatusChanged:(AliPlayer*)player oldStatus:(AVPStatus)oldStatus newStatus:(AVPStatus)newStatus {
          self.currentPlayerStatus = newStatus;
      
        if (_pipController) {
           [self.pipController invalidatePlaybackState];
         }
      }
    3. Update the status of the PiP controller when you listen for the onPlayerEvent event.

      - (void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
          if (eventType == AVPEventCompletion) {
            if (_pipController) {
             self.isPipPaused = YES; // Pause the playback in PiP mode after the playback ends.
             [self.pipController invalidatePlaybackState];
          }
        } else if (eventType == AVPEventSeekEnd) {
          // The seeking is complete.
            if (_pipController) {
             [self.pipController invalidatePlaybackState];
          }
        }
      }
    4. Configure listeners.

      • Listen to the callback returned when the playback in PiP mode is about to start.

        /**
         @ brief The callback returned when the playback in PiP mode starts.
         @param pictureInPictureController indicates the PiP controller.
         */
        - (void)pictureInPictureControllerWillStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController {
            if (!_pipController) {
             self.pipController = pictureInPictureController;
          }
            self.isPipPaused = !(self.currentPlayerStatus == AVPStatusStarted);
          [pictureInPictureController invalidatePlaybackState];
        }
      • Listen to the callback returned when the playback in PiP mode is about to stop.

        /**
         @ brief The callback returned when the playback in PiP mode is about to stop.
         @param pictureInPictureController indicates the PiP controller.
         */
        - (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController {
            self.isPipPaused = NO;
          [pictureInPictureController invalidatePlaybackState];
        }
      • Listen to the callback returned after the playback in PiP mode stops and use the delegate to enable the player UI.

        /**
         @ brief The callback returned after the playback in PiP mode stops.
         @param pictureInPictureController indicates the PiP controller.
         @ param Set completionHandler to YES to stop playback in PiP mode and enable the player UI.
         */
        - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL restored))completionHandler {
            if (_pipController) {
              _pipController = nil;
          }
          completionHandler(YES);
        }
      • Listen to the callback of the duration limits of videos that can be played in PiP mode.

        /**
         @ brief The callback of the duration limits of videos that can be played in PiP mode.
         @param pictureInPictureController indicates the PiP controller.
         @ return The duration limits of videos that can be played in PiP mode.
         */
         - (CMTimeRange)pictureInPictureControllerTimeRangeForPlayback:(nonnull AVPictureInPictureController *)pictureInPictureController layerTime:(CMTime)layerTime{
            Float64 current64 = CMTimeGetSeconds(layerTime);
        
            Float64 start;
            Float64 end;
        
            if (currentPosition <= self.player.duration) {
                double curPostion = self.currentPosition / 1000.0;
                double duration = self.player.duration / 1000.0;
                double interval = duration - curPostion;
                start = current64 - curPostion;
                end = current64 + interval;
                CMTime t1 = CMTimeMakeWithSeconds(start, layerTime.timescale);
                CMTime t2 = CMTimeMakeWithSeconds(end, layerTime.timescale);
                return CMTimeRangeFromTimeToTime(t1, t2);
            } else {
                return CMTimeRangeMake(kCMTimeNegativeInfinity, kCMTimePositiveInfinity);
            }
        }
      • Listen to the callback returned when the status of playback in PiP mode is changed.

        /**
         @ brief The callback returned when the status of playback in PiP mode is changed. The UI changes when the playback status changes.
         @param pictureInPictureController indicates the PiP controller.
         @ return The playback status in PiP mode.
         */
        - (BOOL)pictureInPictureControllerIsPlaybackPaused:(nonnull AVPictureInPictureController *)pictureInPictureController{
            return self.isPipPaused;
        }
        Note

        This callback is invoked before a video enters the PiP mode. The video enters the PiP mode only when false is returned in the callback.

      • Listen to the callback returned when a fast forward or fast backward operation is performed during playback in PiP mode and synchronize the playback progress to the player.

        /**
         @ brief The callback returned when a fast forward or fast backward operation is performed during playback in PiP mode.
         @param pictureInPictureController indicates the PiP controller.
         @ param skipInterval indicates the interval by which the video is skipped forward or backward.
         @ param Call completionHandler to end the fast forward or fast backward operation.
         */
         - (void)pictureInPictureController:(nonnull AVPictureInPictureController *)pictureInPictureController skipByInterval:(CMTime)skipInterval completionHandler:(nonnull void (^)(void))completionHandler {
            int64_t skipTime = skipInterval.value / skipInterval.timescale;
            int64_t skipPosition = self.currentPosition + skipTime * 1000;
            if (skipPosition < 0) {
                skipPosition = 0;
            } else if (skipPosition > self.player.duration) {
                skipPosition = self.player.duration;
            }
            [self.player seekToTime:skipPosition seekMode:AVP_SEEKMODE_INACCURATE];
            [pictureInPictureController invalidatePlaybackState];
        }
      • Listen to the callback returned when the playback in PiP mode is paused or started.

        /**
         @ brief The callback that is returned when the playback in PiP mode is paused or started.
         @param pictureInPictureController indicates the PiP controller.
         @ param playing indicates whether the video is being played in PiP mode.
         */
        - (void)pictureInPictureController:(nonnull AVPictureInPictureController *)pictureInPictureController setPlaying:(BOOL)playing {
            if (!playing){
              [self.player pause];
              self.isPipPaused = YES;
            } else {
              // If you want to replay a video after the playback ends, run the following code that starts with if.
              if (self.currentPlayerStatus == AVPStatusCompletion) {
                 [self.player seekToTime:0 seekMode:AVP_SEEKMODE_ACCURATE];
              }
        
              [self.player start];
              self.isPipPaused = NO;
          }
          [pictureInPictureController invalidatePlaybackState];
        }

RTS playback degradation

Playback degradation is supported by Real-Time streaming (RTS). You can specify an alternative RTS URL, such as a playback URL in the HLS or FLV format. If stream pulling over RTS fails, the video specified in this URL is automatically played.

// Specify downgradeUrl.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:downgradeUrl];
// Optional. Configure playback degradation.
AVPConfig *config = [self.player getConfig];
// Specify an alternative RTS URL.
[self.player enableDowngrade:urlSource config:config];

Switch between left and right audio channels

outputAudioChannel specifies the output audio channel. You can switch between the left and right audio channels only if the input file contains two audio channels. If the input file contains only one audio channel, the outputAudioChannel configuration is invalid.

Note

The following output audio channel settings affect audio rendering and Pulse-Code Modulation (PCM) data callback.

// Specify AVPOutputAudioChannel to switch the audio channel. Default value: AVP_AUDIO_CHANNEL_NONE.
// Specify AVP_AUDIO_CHANNEL_NONE to use the audio channel settings of the input file.
// Specify AVP_AUDIO_CHANNEL_LEFT to use the left audio channel for playback.
// Specify AVP_AUDIO_CHANNEL_RIGHT to use the right audio channel for playback.
self.aliplayer.outputAudioChannel = AVP_AUDIO_CHANNEL_NONE;

Set the background color of the player

You can set the background color of the player when you use ApsaraVideo Player SDK for iOS. The following content describes how to set the background color of the player and provides sample code:

Methods

/**
 @ brief Set the background color of the video.
 @param color  the color
 */
/****
 @brief Set video background color
 @param color  the color
 */
-(void) setVideoBackgroundColor:(UIColor *)color;

Sample code

// The value must be an 8-bit hexadecimal string, in which every 2 characters indicate a factor in the following sequence: R (red), G (green), B (blue), and A (alpha transparency).
// For example, 0x00ff00ff indicates green.
[aliPlayer setVideoBackgroundColor:0x00ff00ff]

Specify a domain name for vidAuth-based playback

You can specify parameters such as the domain name when you use vidAuth for playback. For more information about the parameters, see GetPlayInfo. The following content describes how to specify a domain name for vidAuth-based playback and provides sample code:

Methods

/**
 @brief Play videos based on the VID and playAuth. For more information, visit https://www.alibabacloud.com/help/en/vod/user-guide/use-playback-credentials-to-play-videos.
 @param source The playback source type is AVPVidAuthSource.
 @see AVPVidAuthSource
 */
- (void)setAuthSource:(AVPVidAuthSource*)source;

Sample code

Specify the playDomain parameter when you call addVidPlayerConfigByStringValue in VidPlayerConfigGenerator.

VidPlayerConfigGenerator* gen = [[VidPlayerConfigGenerator alloc]init];
// Specify the playDomain parameter. For more information, visit https://www.alibabacloud.com/help/en/vod/developer-reference/api-vod-2017-03-21-getplayinfo.
//https://www.alibabacloud.com/help/zh/vod/developer-reference/api-vod-2017-03-21-getplayinfo
[gen addVidPlayerConfigByStringValue:@"playDomain" value: @"com.xxx.xxx"];
[source setPlayConfig:[gen generatePlayerConfig]];
[self.player setAuthSource:source]:

Performance

Configure local caching

ApsaraVideo Player SDK for iOS allows you to cache videos during playback. This reduces the startup time, accelerates the seeking process, reduces the playback latency, and saves your traffic during loop playback.

Enable local caching

By default, the local caching feature is disabled. To use this feature, you must enable it. You can call enableLocalCache in the AliPlayerGlobalSettings class to enable local caching. Sample code:

/**
 * Enable local caching. After this feature is enabled, a media file is cached on your device. 
 * @param enable: specifies whether to enable the video preload feature. Valid values: true and false. true indicates that the local caching feature is enabled and false indicates that the local caching feature is disabled. Default value: false. 
 * @param maxBufferMemoryKB: This parameter is deprecated in V5.4.7.1 and later. 
 * @param localCacheDir: Required. The directory of the cached file, which is an absolute path. 
 */
[AliPlayerGlobalSettings enableLocalCache:true maxBufferMemoryKB:1024 localCacheDir:@""];

/**
 @brief Configure settings for clearing cached files. 
 @ param expireMin: This parameter is deprecated in V5.4.7.1 and later. 
 @param maxCapacityMB: the maximum cache size. Unit: MB. By default, the maximum size of cached data is 20 GB. If the specified maximum size is exceeded, the system deletes cached files based on the time when the file is cached until the size of the cached data is less than or equal to the specified maximum size. During this process, the system preferentially deletes the earliest files that are cached. 
 @param freeStorageMB: the minimum idle space of the disk. Unit: MB. Default value: 0. If the idle space of the disk is less than the specified minimum space, the system deletes cached files based on the time when the file is cached until the idle space of the disk is greater than or equal to the specified minimum space. During this process, the system preferentially deletes the earliest files that are cached. 
 */
[AliPlayerGlobalSettings setCacheFileClearConfig:0 maxCapacityMB:0 freeStorageMB:0];

/**
 * Obtain the callback for the URL hash value of the video file and use it as the unique ID of the URL. 
 */

// You must run the function and set the function pointer to setCacheUrlHashCallback.
static NSString *CaheUrlHashHandle(NSString *url) {
    return @"xxx";
}

[AliPlayerGlobalSettings setCacheUrlHashCallback:&CaheUrlHashHandle];
Note
  • If the playback URL of a video file contains authentication parameters, the values of the authentication parameters change during the local caching and playback of the video file. You can call the setCacheUrlHashCallback operation to calculate the MD5 hash value after you remove the authentication parameters. For example, http://****.mp4?aaa is the playback URL of a video file that contains authentication parameters. In this case, the URL http://****.mp4 is used to calculate the MD5 hash value when the video file is loaded. However, if you calculate the MD5 hash value after you remove the authentication parameters in the key URL of an encrypted M3U8 video, the playback fails because different videos are hit by the same key URL. Solution: Remove the authentication parameters only from the playback URL http(s)://xxxxx.m3u8?aaaa but not the key URL http(s)://yyyyy?bbbb in the setCacheUrlHashCallback callback.进阶功能-本地缓存.png

  • If your server supports HTTP and HTTPS and a video file can be specified by using two URLs with the same elements but different protocols, you can remove the protocol header of the URLs or use the URL with the HTTP protocol to calculate the MD5 hash value. Examples:

    • If the playback URLs of a video file are https://****.mp4 and http://****.mp4, the MD5 hash value is calculated by using ****.mp4 when the video file is loaded.

    • If the playback URL of the video file is https://****.mp4, the MD5 hash value is calculated by using the URL http://****.mp4 when the video file is loaded.

  • For ApsaraVideo Player SDK V5.5.4.0 or later, if you want to play an HLS stream whose playback URL contains authentication parameters, configure AVPConfig.enableStrictAuthMode to specify authentication modes. By default, AVPConfig.enableStrictAuthMode is set to false. Valid values of AVPConfig.enableStrictAuthMode:

    • false: caches the video content and performs authentication. If a video is not completely cached, the player sends a URL signing request by using the authentication information about the cached content when you play the uncached video content. If the validity period of the signed URL is too short, playback errors occur.

    • true: performs authentication and does not cache video content. URL signing is required for every playback. No network connections lead to playback failures.

Enable or disable local caching for a single URL

You can disable local caching for a single URL in player config. Sample code:

// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Configure whether to enable local caching for the playback URL. Default value: true. When local caching is enabled in AliPlayerGlobalSettings and the value of this parameter is true, the local caching for the URL takes effect. If the value of this parameter is false, the local caching for the URL is disabled. 
config.enableLocalCache = false;
....// Configure other settings.

// Configure the settings for the player.
[self.player setConfig:config];

Configure large cache

You can set the maximum buffer duration to cache video data in the memory during playback, which improves the playback performance and experience. If the maximum buffer duration is set too large, the buffer consumes excessive memory. You can use the large cache feature to cache video in files, which reduces memory usage and further improves player performance.

When mMaxBufferDuration is greater than 50,000 ms, you can enable local caching to automatically trigger large cache. Perform the following steps:

  1. Enable the global local caching feature.

    By default, the local caching feature is disabled. To use this feature, you must enable it. You can call enableLocalCache in the AliPlayerGlobalSettings class to enable local caching. For more information about the sample code, see the Enable local caching section of the Advanced features topic.

  2. Enable local caching for a URL.

    For more information about the sample code, see Enable or disable local caching for a single URL in Configure local caching.

Configure video preload

ApsaraVideo Player SDK for iOS supports video preload, which is an upgrade of the local caching feature. The video preload feature allows you to specify the maximum size of memory that can be occupied by cached videos. This helps reduce the startup duration.

The video preload feature has the following limits:

  • You can preload only one MP4, MP3, FLV, or HLS file at a time.

  • You can preload only one file that is played based on the URL. You cannot preload VidAuth or VidSts sources.

Note

By default, network resource scheduling is enabled when you use ApsaraVideo Player SDK for iOS to preload videos. This ensures the quality of the video that is being played. If network resource scheduling is enabled, the preload request is sent only after the buffered content of the video that is being played reaches a specific limit. You can disable network resource scheduling if you want to manage the real-time preload requests. Sample code:

[AliPlayerGlobalSettingsenableNetworkBalance:false];
  1. Enable the local caching feature. For more information, see Advanced features.

  2. Obtain an AliMediaLoader instance.

    The AliMediaLoader instance is a singleton object. You can create only one AliMediaLoader instance regardless of the number of times for which you obtain the instance.

    [AliMediaLoader shareInstance];
  3. Configure the AliMediaLoader instance.

    // Configure listeners and start to load video files. 
    // url: the URL of the video file.  duration: the loading duration. Unit: milliseconds. 
    [[AliMediaLoader shareInstance] load:obj.url duration:1000];
    // Configure a callback delegate.
    [[AliMediaLoader shareInstance] setAliMediaLoaderStatusDelegate:self];
    
    @protocol AliMediaLoaderStatusDelegate <NSObject>
    @optional
    
    /**
     @brief The callback that is invoked when an error occurs.
     @ param url The URL.
     @param code The error code.
     @ param msg The error description.
     */
    - (void)onError:(NSString *)url code:(int64_t)code msg:(NSString *)msg;
    
    /**
     @ brief The callback that is invoked when the loading is complete.
     @ param url The URL.
     */
    - (void)onCompleted:(NSString *)url;
    
    /**
     @ brief The callback that is invoked when the loading is canceled.
     @ param url The URL.
     */
    - (void)onCanceled:(NSString *)url;
    
    @end
  4. Optional: Delete the loaded video files.

    You can delete the loaded video files to reduce occupied space. ApsaraVideo Player SDK for iOS does not provide a method to delete the loaded video files. You must delete the video files in the corresponding directory in your application.

Dynamic preloading

The dynamic preloading feature allows you to manage cache of the video that is being played and videos that are preloaded. You can also control the number of videos that can be preloaded. This helps maintain a balance between playback experience and cost.

Show code

// Enable the dynamic preloading feature and use the default configurations.
[self.listPlayer setScene:AVP_SHORT_VIDEO];

// Configure the baseline preload duration.
// Set the preload duration to 1,000 milliseconds.
AVPPreloadConfig *config = [[AVPPreloadConfig alloc] init];
config.preloadDuration = 1000;
[self.listPlayer updatePreloadConfig:config];

Configure the number of videos that can be preloaded. Forward and backward are supported.
// 1 specifies the number of videos that can be preloaded forwards and 3 specifies the number of videos that can be preloaded backwards.
[self.listPlayer setPreloadCount:1 nextCount:3];

// Configure the decreasing offset for dynamic preloading.
[self.listPlayer enableStrategy:AVP_STRATEGY_DYNAMIC_PRELOAD enable:true];
[self.listPlayer setStrategyParam:AVP_STRATEGY_DYNAMIC_PRELOAD strategyParam:@"{\"algorithm\": \"sub\",\"offset\": \"200\"}"];

Obtain the download speed

ApsaraVideo Player SDK for iOS allows you to query the download speed of specified videos. The callback invoked by the onCurrentDownloadSpeed method returns the download speed. Sample code:

- (void)onCurrentDownloadSpeed:(AliPlayer *)player speed:(int64_t)speed{
  intspeed_=speed;
}

Configure the network

HTTPDNS

The HTTPDNS feature uses the DNS resolution technology to send domain name resolution requests to the specific HTTPDNS server and obtain the resolution results in a quick and stable manner. This prevents DNS hijacking.

You can use one of the following HTTPDNS features based on your business requirements.

Type

Description

Standard HTTPDNS

Provide HTTPDNS services for various domain names.

Enhanced HTTPDNS

Provide HTTPDNS services for domain names that are accelerated by Alibaba Cloud CDN. You can use the enhanced HTTPDNS feature to implement precise scheduling and ensure that the real-time domain resolution results immediately take effect. This improves the network performance.

Note

To use the enhanced HTTPDNS feature, submit a request on Yida or contact your account manager.

Sample code for using the standard HTTPDNS feature

// Enable the standard HTTPDNS feature.
[AliPlayerGlobalSettings enableHttpDns:YES];
// Optional. Add an HTTPDNS pre-resolved domain name.
[[AliDomainProcessor shareInstance] addPreResolveDomain:@"player.***cdn.com"];

Sample code for using the enhanced HTTPDNS feature

You can use the enhanced HTTPDNS feature only for accelerated domain names. Before you use the feature, make sure that an accelerated domain name is added and configured. For more information about how to add and configure a domain name for CDN to ApsaraVideo VOD, see Add a domain name for CDN. For more information about accelerated domain names, see What is Alibaba Cloud CDN?.

// Enable the enhanced HTTPDNS feature.
[AliPlayerGlobalSettings enableEnhancedHttpDns:YES];
// Required. Add and configure a domain name for CDN. Make sure that the domain name can provide online services. 
[[AliDomainProcessor shareInstance] addEnhancedHttpDnsDomain:@"player.***alicdn.com"];
// Optional. Add an HTTPDNS pre-resolved domain name.
[[AliDomainProcessor shareInstance] addPreResolveDomain:@"player.***alicdn.com"];

Configure the priority of HTTPDNS

You can configure the priority levels of HTTPDNS and local DNS. Standard HTTPDNS and enhanced HTTPDNS are supported.

// SET_DNS_PRIORITY_LOCAL_FIRST specifies the priority of HTTPDNS.
// YES indicates that local DNS takes precedence and NO indicates that HTTPDNS takes precedence.
[AliPlayerGlobalSettings setOption:SET_DNS_PRIORITY_LOCAL_FIRST valueInt:NO];

HTTP/2

Note

By default, HTTP/2 is enabled for ApsaraVideo Player SDK for iOS V5.5.0.0 and later.

ApsaraVideo Player SDK for iOS supports HTTP/2. You can enable HTTP/2 to implement multiplexing of requests. This prevents head-of-line (HOL) blocking and improves playback performance. Sample code:

[AliPlayerGlobalSettingssetUseHttp2:true];

HTTP/3

Note
  • In 2022, Internet Engineering Task Force (IETF) published HTTP/3 as a proposed standard. ApsaraVideo Player SDK for iOS supports only IETF Quick UDP Internet Connections (QUIC) h3-v1. Google QUIC is not supported.

  • If the playback times out or fails after you enable HTTP/3, requests are automatically sent over HTTP/2.

HTTP/3 is supported in ApsaraVideo Player SDK for iOS. To enable HTTP/3 for an accelerated domain name, submit a request on Yida. Then, you can play videos that are stored in ApsaraVideo VOD over HTTP/3 by using the accelerated domain name. You can also configure ApsaraVideo Player to access playback URLs over HTTP/3 to better respond to poor network conditions. Sample code:

// Obtain the configuration information.
AVPConfig *config = [self.player getConfig];
// Send requests over HTTP/3.
config.enableHttp3 = YES;
....// Configure other settings.
// Apply the configurations to the player.
[self.player setConfig:config];

Configure video download

ApsaraVideo Player SDK for iOS allows you to download videos to local devices for offline playback. The normal download and secure download modes are supported.

  • 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 cannot use third-party players to play the downloaded videos. You can use only ApsaraVideo Player to play them.

Usage notes

  • You can only download 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

  1. (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.

    We recommend that you configure the key file only once. Sample code:

    NSString *encrptyFilePath = [[NSBundle mainBundle] pathForResource:@"encryptedApp" ofType:@"dat"];
    [AliPrivateService initKey:encrptyFilePath];
  2. Create and set a video downloader.

    Sample code:

    AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init];
    [downloader setSaveDirectory:self.downLoadPath];
    [downloader setDelegate:self];
  3. Configure listeners.

    The download object provides multiple listeners. Sample code:

    -(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info {
        // The listener for the preparation of the content to be downloaded.
    }
    -(void)onError:(AliMediaDownloader *)downloader errorModel:(AVPErrorModel *)errorModel {
        // The listener for a download error.
    }
    -(void)onDownloadingProgress:(AliMediaDownloader *)downloader percentage:(int)percent {
        // The listener for the download progress in percentage.
    }
    -(void)onProcessingProgress:(AliMediaDownloader *)downloader percentage:(int)percent {
        // The listener for the processing progress in percentage.
    }
    -(void)onCompletion:(AliMediaDownloader *)downloader {
        // The listener for a successful download.
    }
  4. Prepare the download source.

    You can call the prepare method to prepare a download source. AVPVidStsSource and AVPVidAuthSource are supported. Sample code:

    • VidSts

      // Create the VidSts download source.
      AVPVidStsSource* stsSource = [[AVPVidStsSource alloc] init];
      stsSource.region = @"Access region"; // The region in which ApsaraVideo VOD is activated. Default value: cn-shanghai. 
      stsSource.vid = @"Video ID"; // The ID of the video. 
      stsSource.securityToken = @"<Your security token>"; // The STS token. To generate an STS token, call the AssumeRole operation in STS. 
      stsSource.accessKeySecret = @"<Your AccessKey secret>"; // The AccessKey secret that is generated when the temporary STS token is issued. To generate the AccessKey secret, call the AssumeRole operation in STS. 
      stsSource.accessKeyId = @"<Your AccessKey ID>"; // The AccessKey ID that is generated when the temporary STS token is issued. To generate the AccessKey ID, call the AssumeRole operation in STS. 
      // Prepare the download source.
      [downloader prepareWithVid:stsSource];
    • VidAuth

      // Add the VidAuth download source.
      AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
      authSource.vid = @"Video ID";// The ID of the video. 
      authSource.playAuth = @"<Your playback credential>"; // The playback credential. To obtain the playback credential, call the GetVideoPlayAuth operation in ApsaraVideo VOD. 
      authSource.region = @"Access region"; // This parameter is deprecated in ApsaraVideo Player SDK V5.5.5.0 or later. If you use ApsaraVideo Player SDK V5.5.5.0 or later, the player automatically parses the region information. If you use ApsaraVideo Player SDK V5.5.5.0 or earlier, this parameter is required. Specify the ID of the region in which ApsaraVideo VOD is activated for this parameter. Default value: cn-shanghai. 
      // Prepare the download source.
      [downloader prepareWithVid:authSource];
  5. 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 method. The value of the TrackInfo parameter indicates the information about video tracks such as video definitions. Select a track to download. Sample code:

    -(void)onPrepared:(AliMediaDownloader *)downloader mediaInfo:(AVPMediaInfo *)info {
        NSArray<AVPTrackInfo*>* tracks = info.tracks;
        // In this example, download the content of the first track.
        [downloader selectTrack:[tracks objectAtIndex:0].trackIndex];
    }
  6. 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:

    // Update the download source.
    [downloader updateWithVid:vidSource]
    // Start the download.
    [downloader start];
  7. Release the downloader after the download succeeds or fails.

    After the download succeeds, call the destroy method to release the downloader.

    [self.downloader destroy];
    self.downloader = nil;

Play encrypted videos

ApsaraVideo Player SDK for iOS allows you to play on-demand videos encrypted based on HLS encryption, Alibaba Cloud proprietary cryptography, or digital rights management (DRM) encryption. The SDK allows you to play live streams encrypted only based on DRM encryption. For more information about how to play encrypted videos, see Play an encrypted video.

Configure Native RTS SDK

You can integrate ApsaraVideo Player SDK for iOS with Native RTS SDK to use the Real-Time Streaming (RTS) feature. For more information, see Native RTS SDK for iOS.

References