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.
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:
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.
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.
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.
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.
Use the Metal framework for rendering
ApsaraVideo Player SDK for iOS allows you to use the Metal framework to render videos.
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:
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];
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]; }
Add subtitles.
[self.player addExtSubtitle:URL];
Switch subtitles.
[self.player selectExtSubtitle: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.
}
}
H.265 adaptive playback
If you have configured a secondary H.264 stream and hardware decoding of the H.265 stream fails, the system automatically plays the secondary H.264 stream. If you do not configure a secondary stream, soft decoding is automatically used for H.265 playback when hardware decoding fails.
This feature is available only after you enable adaptive playback. Adaptive playback is a value-added service. To activate value-added services, submit a request on Yida.
The adaptive playback service provides the following features: dynamic data issuing of hardware decoded data and automatic H.264 switching.
If you do not activate the adaptive playback service, the player SDK can still automatically use software decoding when hardware decoding fails.
The following sample code describes how to configure a secondary stream:
// Create a map on the application layer to store the primary stream URLs and secondary stream URLs as key-value pairs. The system queries the corresponding secondary URL based on the primary stream URL during switching.
NSString* getBackupUrlCallback(AVPBizScene scene, AVPCodecType codecType, NSString* oriurl){
NSMutableDictionary *globalMap = [AliPlayerViewController getGlobalBackupUrlMap];
NSString *backupUrl = globalMap[oriurl];
return backupUrl;
}
[AliPlayerGlobalSettings setAdaptiveDecoderGetBackupURLCallback:getBackupUrlCallback];
Adaptive bitrate streaming
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 provides an example on 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();
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.
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];
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 loading 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:
// Query the configuration information.
AVPConfig *config = [self.player getConfig];
// Specify 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 loading 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];
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 improve playback performance. For more information, see Configure large cache.
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
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
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;
}
}
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.
Set up the PiP delegate to receive event callbacks.
[self.player setPictureinPictureDelegate:self];
Configure the PiP delegate.
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;
NoteYou 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.
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]; } }
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]; } } }
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; }
NoteThis 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]; }
Configure an alternative RTS URL
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];
Enable RTS playback degradation
If you enable the RTS playback degradation feature but your browser does not support RTS or stream pulling over RTS fails, the system automatically plays the stream by using the default HLS URL. Sample code:
// 1 indicates that the RTS playback degradation feature is enabled and 0 indicates that the RTS playback degradation feature is disabled. Hardware decoding is enabled by default.
[AliPlayerGlobalSettings setOption:ALLOW_PRE_RENDER valueInt:1];
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.
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]:
Backend decoding
The backend decoding feature is supported for ApsaraVideo Player SDK V6.12.0 and later. After you enable this feature, the system can decode and play videos and send callbacks on the backend. Sample code:
// 1 indicates that backend decoding is enabled and 0 indicates that backend decoding is not enabled. Default value: 0.
[self.player setOption:ALLOW_DECODE_BACKGROUND valueInt:1];
Performance
Configure pre-rendering
ApsaraVideo Player SDK for iOS supports pre-rendering of the first frame before the playback starts. Sample code:
[player setOption:ALLOW_PRE_RENDER valueInt:1];
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 video preload 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 point in 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 point in 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];
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 URLhttp://****.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 URLhttp(s)://xxxxx.m3u8?aaaa
but not the key URLhttp(s)://yyyyy?bbbb
in thesetCacheUrlHashCallback
callback.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
andhttp://****.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 URLhttp://****.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 authentication information. If a video is not completely cached, the player sends a URL signing request by using the cached authentication information when you play the uncached video content. If the validity period of the signed URL is 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];
Use the default cache path
The following sample code describes how to configure AliPlayerGlobalSettings
to use the default cache path.
[AliPlayerGlobalSettings enableLocalCache:true];
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:
Enable the global local caching feature.
By default, the video preload feature is disabled. To use this feature, you must enable it. You can call
enableLocalCache
in theAliPlayerGlobalSettings
class to enable local caching. For more information about the sample code, see the Enable local caching section of the Advanced features topic.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.
Enable large cache. Sample code:
[AliPlayerGlobalSettings enableBufferToLocalCache:true];
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.
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:
[AliPlayerGlobalSettings enableNetworkBalance:false];
Enable the local caching feature. For more information, see the Configure local caching section of this topic.
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];
Configure the AliMediaLoader instance.
NoteIf you call
prepare
inplayer
andmediaLoader.load
at the same time, an Application Not Responding (ANR) error may occur. This is because the system must traverse all local files for both operations. We recommend that you start loading after theonPrepared
callback is fired inplayer
.// 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
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.
Preloading of multi-bitrate HLS videos
You can preload videos in the same definition as the current video stream when you call the listPlayer
method during the playback of multi-bitrate HLS videos. You can use different preloading modes based on your business requirements.
Query 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.
ApsaraVideo Player SDK provides 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.
The enhanced HTTPDNS feature is supported in ApsaraVideo Player SDK V6.7.0 or later. To use the enhanced HTTPDNS feature in ApsaraVideo Player SDK V6.7.0 to V6.11.0, submit a ticket or contact your Alibaba Cloud account manager. If you use ApsaraVideo Player SDK V6.12.0 or later, the enhanced HTTPDNS feature is enabled by default and no application is required.
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];
// Optional. Add an HTTPDNS pre-resolved domain name.
[[AliDomainProcessor shareInstance] addPreResolveDomain:@"player.***alicdn.com"];
HTTP/2
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:
[AliPlayerGlobalSettings setUseHttp2:true];
Create TCP connections before playback requests are initiated over HTTP
You can create Transmission Control Protocol (TCP) connections before playback requests are initiated over HTTP. This reduces the waiting time, ensures the timeliness and consistency of video playback, improves the user experience, and optimizes the usage of network and system resources. Sample code:
// Specify the domain parameter in the host[:port] format. Separate multiple domain names with semicolons (;). The port parameter is optional.
// Specify global settings.
// Add or delete TCP connections. If you specify an empty string, no TCP connections are created.
[AliPlayerGlobalSettings setOption:SET_PRE_CONNECT_DOMAIN value: @"domain1;domain2"];
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
(Optional) Configure the security file for encryption verification. You must configure the security file only when you use the secure download mode.
NoteMake 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];
Create and set a video downloader.
Sample code:
AliMediaDownloader *downloader = [[AliMediaDownloader alloc] init]; [downloader setSaveDirectory:self.downLoadPath]; [downloader setDelegate:self];
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. }
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];
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]; }
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];
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 Android 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.