Strategy system

Updated at:

The Strategy System is a core architectural design of AliPlayerKit. It uses an event-driven policy mechanism to encapsulate player monitoring, analysis, and optimization logic into independent strategy components. This design decouples business logic, enables reusability, and provides flexible extension.

Concepts

What is a strategy?

A Strategy is an independent unit that encapsulates player business logic. It implements specific business capabilities or custom logic, such as time-to-first-frame (TTFF) statistics, stutter detection, traffic protection, and resume playback.

Core features:

  • Single responsibility: Each strategy focuses on a clear functional goal.

  • Event-driven: A strategy subscribes to player events through the PlayerNotificationDelegate protocol and executes logic in response.

  • Independent and isolated: Strategies are independent and do not interfere with each other. The execution of each strategy is isolated by @try/@catch.

What is the strategy system?

The Strategy System is the architectural mechanism that manages all strategy components. It handles strategy registration, lifecycle management, context injection, event subscription, and runtime state control. This system lets you enable or disable specific strategies as needed. You can also quickly implement custom strategies or completely replace default ones to meet specific business requirements.

Core value

Usage

Description

Benefit

Use default strategies

The player component uses the official default strategies.

Simplifies the integration process and works out-of-the-box.

Custom policy

Implement strategies for specific business requirements.

Meets various custom business requirements.

Use no strategies

Use only the playback feature.

For pure playback scenarios with no logic dependencies.

Architectural benefits:

  • Decoupling: Strategies are separate from the core player logic, ensuring clear responsibilities.

  • Reusability: Strategies can be reused across different player instances.

  • Extensibility: You can customize strategies without modifying the framework.

  • Isolation: Strategies are independent. An exception in one strategy does not affect others.

Features

Core capabilities

Capability

Description

Event-driven

Strategies subscribe to player events by implementing the PlayerNotificationDelegate protocol and execute in response.

Lifecycle management

Manages the start, stop, reset, and destruction of strategies.

Context injection

Strategies can access the player controller, playback model, and state store through StrategyContext.

Factory pattern

Register global strategy factories through StrategyRegistry. The factories are automatically applied to all newly created player instances.

Error isolation

The lifecycle calls of each strategy are isolated by @try/@catch. An exception in one strategy does not affect others.

Built-in strategies

Strategy

Class name

Description

Trigger condition

Time-to-first-frame

FirstFrameStrategy

Measures the time from the PREPARING state to the rendering of the first frame.

Starts automatically when the player prepares.

Stutter detection

StutterDetectStrategy

Detects the number and duration of stutters during playback.

Starts monitoring after the first frame is rendered.

Traffic protection

TrafficProtectionStrategy

Detects cellular network status and notifies of changes.

Triggers when the network status changes.

Note

Built-in strategies are automatically registered when StrategyRegistry is first accessed. When a new AliPlayerController is created, all registered factories are used to instantiate strategies. These strategies are then injected into the controller's StrategyManager using applyToManager:. This process ensures that each controller has its own independent strategy instances.

Time-to-first-frame strategy (FirstFrameStrategy)

Measures the time it takes for the player to render the first frame. The process is divided into three stages:

Stage

Description

Event interval

Preparation stage

Video parsing and network requests.

PREPARING → Prepared

Rendering stage

Decoding and rendering the first frame.

Prepared → FirstFrameRendered

Total time

The complete time-to-first-frame.

PREPARING → FirstFrameRendered

You can retrieve the time data through FirstFrameStrategyDelegate:

@protocol FirstFrameStrategyDelegate <NSObject>
@optional

- (void)firstFrameStrategy:(FirstFrameStrategy *)strategy
       didRenderFirstFrameWithPrepareTime:(NSInteger)prepareTimeMs
                               renderTime:(NSInteger)renderTimeMs
                                totalTime:(NSInteger)totalTimeMs;
@end
FirstFrameStrategy *strategy = [[FirstFrameStrategy alloc] init];
strategy.delegate = self;
[controller.strategyManager registerStrategy:strategy];

Stutter detection strategy (StutterDetectStrategy)

Monitors the Loading state during playback to collect stuttering statistics. Loading that occurs before the first frame is rendered does not count as stuttering.

Metric

Property

Description

Stutter count

stutterCount

The number of times the Loading state occurs (calculated after the first frame).

Total stutter duration

totalStutterDurationMs

The total stutter duration for the entire playback session, in milliseconds.

Stutter threshold

stutterThresholdMs

A duration is considered a stutter only if it exceeds this threshold (default is 0).

You can receive callbacks through StutterDetectStrategyDelegate:

@protocol StutterDetectStrategyDelegate <NSObject>
@optional

/// A stutter is detected.
- (void)stutterDetectStrategy:(StutterDetectStrategy *)strategy
                   didStutter:(NSInteger)durationMs;

/// Analysis at the end of the playback session.
- (void)stutterDetectStrategy:(StutterDetectStrategy *)strategy
            didAnalyzeSession:(NSInteger)stayDurationMs
            validPlayDuration:(NSInteger)validPlayDurationMs
         totalStutterDuration:(NSInteger)totalStutterDurationMs
                 stutterCount:(NSInteger)stutterCount;
@end
// Create a stutter detection strategy (you can specify a threshold).
StutterDetectStrategy *strategy = [[StutterDetectStrategy alloc] initWithThreshold:500];
strategy.delegate = self;
[controller.strategyManager registerStrategy:strategy];

Traffic protection strategy (TrafficProtectionStrategy)

Monitors network status changes and sends a notification when it detects that the device is using a cellular network for video playback. This strategy only performs detection and logging. It does not automatically pause playback.

Scenario

Behavior

Wi-Fi → Cellular network

Notifies through the delegate.

Playback starts on a cellular network

Notifies through the delegate.

Cellular network → Wi-Fi

Notifies through the delegate and resets the prompt flag.

@protocol TrafficProtectionStrategyDelegate <NSObject>
@optional

/// A cellular network is detected.
- (void)trafficProtectionStrategyDidDetectCellularNetwork:(TrafficProtectionStrategy *)strategy;

/// A switch back to a Wi-Fi network is detected.
- (void)trafficProtectionStrategyDidDetectWifiNetwork:(TrafficProtectionStrategy *)strategy;
@end

The application layer can query the current network status through the isOnCellularNetwork property:

TrafficProtectionStrategy *strategy = (TrafficProtectionStrategy *)
    [controller.strategyManager strategyWithName:@"TrafficProtectionStrategy"];
if (strategy.isOnCellularNetwork) {
    // Display a traffic prompt.
}

Usage

Use default strategies (simplest integration)

When you create an AliPlayerController, the default strategies (time-to-first-frame, stutter detection, and traffic protection) are automatically registered:

// Create a controller (default strategies are registered automatically).
AliPlayerController *controller = [[AliPlayerController alloc] init];

// Configure the playback data.
VideoSource *source = [VideoSource vidAuthSourceWithVid:@"vid" playAuth:@"auth"];
AliPlayerModel *model = [[AliPlayerModel alloc] initWithVideoSource:source];
[controller configure:model];

// Attach to a view (strategies start automatically).
[self.playerView attach:controller];

Register a custom strategy

You can register additional strategies on a specific controller:

AliPlayerController *controller = [[AliPlayerController alloc] init];

// Register a time-to-first-frame strategy with a delegate callback.
FirstFrameStrategy *firstFrame = [[FirstFrameStrategy alloc] init];
firstFrame.delegate = self;
[controller.strategyManager registerStrategy:firstFrame];

// Register a stutter detection strategy with a threshold.
StutterDetectStrategy *stutter = [[StutterDetectStrategy alloc] initWithThreshold:200];
stutter.delegate = self;
[controller.strategyManager registerStrategy:stutter];

AliPlayerModel *model = [[AliPlayerModel alloc] initWithVideoSource:videoSource];
[controller configure:model];
[self.playerView attach:controller];

Global registration policy factory

Strategy factories registered with StrategyRegistry are automatically applied to all newly created controllers:

// Register a global strategy in AppDelegate.
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [AliPlayerKit setup];

    // Register a global custom strategy factory.
    [[StrategyRegistry sharedRegistry] addGlobalStrategyFactory:^id<StrategyProtocol>{
        return [[MyAnalyticsStrategy alloc] init];
    }];

    return YES;
}

// All AliPlayerController instances created after this will automatically register this strategy.
Note

Calling StrategyFactory creates a new strategy instance. This ensures that each controller has an independent strategy object and prevents shared state.

Select strategies as needed

// Clear the default strategies (including built-in ones). New controllers will not automatically register any strategies.
[[StrategyRegistry sharedRegistry] clearGlobalStrategies];

// Use only the time-to-first-frame statistics.
[[StrategyRegistry sharedRegistry] addGlobalStrategyFactory:^id<StrategyProtocol>{
    return [[FirstFrameStrategy alloc] init];
}];

// Restore the default built-in strategy configuration.
[[StrategyRegistry sharedRegistry] resetToDefault];

Global vs. local registration

Registration method

Description

Scenarios

Global registration

Register a factory through StrategyRegistry.

General-purpose strategies such as time-to-first-frame statistics and stutter detection.

Local registration

Call strategyManager.registerStrategy: directly.

Business strategies for specific scenarios.

// Global registration: All new controllers load this automatically.
[[StrategyRegistry sharedRegistry] addGlobalStrategyFactory:^id<StrategyProtocol>{
    return [[MyAnalyticsStrategy alloc] init];
}];

// Local registration: Only the current controller loads this.
AliPlayerController *controller = [[AliPlayerController alloc] init];
[controller.strategyManager registerStrategy:[[MySpecialStrategy alloc] init]];
Note

Global registration affects only controllers created after the registration. Existing controllers are not affected. If you register a strategy with the same name as an existing one, the new strategy replaces the existing one.

Custom development

Strategy protocol (StrategyProtocol)

All strategies must conform to StrategyProtocol. This protocol defines the lifecycle contract for a strategy:

@protocol StrategyProtocol <NSObject>

@required

/// The unique name of the strategy. Registering a strategy with the same name replaces the existing instance.
- (NSString *)strategyName;

/// Starts the strategy and attaches the player context.
- (void)strategyDidStart:(StrategyContext *)context;

/// Stops the strategy and detaches the player context.
- (void)strategyDidStop;

/// Resets the strategy, updates the context, and clears the internal state. This is called when the video source is switched.
- (void)strategyDidReset:(StrategyContext *)context;

@end
Note

strategyDidReset: is a @required method. It is called by StrategyManager when the video source is switched on the same controller (by calling configure: again). The strategy must reset its internal counters and temporary state but keep its event subscriptions unchanged.

Strategy context (StrategyContext)

StrategyContext is created and passed in by StrategyManager when a strategy starts. It provides read-only environment information about the player:

@interface StrategyContext : NSObject

/// The associated player controller (weak reference).
@property (nonatomic, weak, readonly) AliPlayerController *controller;

/// The current playback configuration model.
@property (nonatomic, strong, readonly) AliPlayerModel *playerModel;

/// The player state store, which provides a read-only snapshot of the current playback state.
@property (nonatomic, strong, readonly, nullable) PlayerStateStore *stateStore;

- (instancetype)initWithController:(AliPlayerController *)controller
                       playerModel:(AliPlayerModel *)playerModel;

@end
Note

The StrategyContext object becomes invalid after strategyDidStop is called and must not be used. The strategyDidReset: method passes a new context that contains the updated playerModel, which invalidates the old context.

Inherit from BaseStrategy (recommended)

BaseStrategy encapsulates notification subscription management and common lifecycle logic. This allows child classes to focus only on business logic:

@interface BaseStrategy : NSObject <StrategyProtocol, PlayerNotificationDelegate>

/// The strategy context. It is available after strategyDidStart: and is nil after strategyDidStop.
@property (nonatomic, strong, readonly, nullable) StrategyContext *context;

/// A hook method for child classes to reset their internal state. It is called by the base class during strategyDidReset:.
- (void)resetInternalState;

@end

Lifecycle flow:

Stage

Internal behavior of BaseStrategy

strategyDidStart:

Saves the context → Registers as the controller's PlayerNotificationDelegate

strategyDidReset:

Updates the context → Calls the child class's resetInternalState

strategyDidStop

Unregisters PlayerNotificationDelegate → Clears the context

Note

Child classes must override the strategyName method. Otherwise, an exception is thrown. If you override strategyDidStart:, strategyDidStop, or strategyDidReset:, you must call super.

Complete example of a custom strategy

The following is a complete implementation of a playback duration statistics strategy:

@interface PlayDurationStrategy : BaseStrategy

@property (nonatomic, copy, readonly, nullable) void (^onSessionEnd)(NSTimeInterval durationMs);

- (instancetype)initWithCallback:(void (^)(NSTimeInterval durationMs))callback;

@end

@implementation PlayDurationStrategy {
    CFAbsoluteTime _playStartTime;
    NSTimeInterval _totalPlayDuration;
    BOOL _isPlaying;
}

- (instancetype)initWithCallback:(void (^)(NSTimeInterval))callback {
    self = [super init];
    if (self) {
        _onSessionEnd = [callback copy];
    }
    return self;
}

- (NSString *)strategyName {
    return @"PlayDurationStrategy";
}

- (void)resetInternalState {
    _playStartTime = 0;
    _totalPlayDuration = 0;
    _isPlaying = NO;
}

#pragma mark - PlayerNotificationDelegate

- (void)playerDidChangeState:(PlayerState)state {
    switch (state) {
        case PlayerStatePlaying:
            if (!_isPlaying) {
                _isPlaying = YES;
                _playStartTime = CFAbsoluteTimeGetCurrent();
            }
            break;

        case PlayerStatePaused:
            [self accumulateDuration];
            break;

        case PlayerStateCompleted:
        case PlayerStateStopped:
        case PlayerStateError:
            [self accumulateDuration];
            [self reportDuration];
            break;

        default:
            break;
    }
}

#pragma mark - Private

- (void)accumulateDuration {
    if (_isPlaying && _playStartTime > 0) {
        NSTimeInterval delta = (CFAbsoluteTimeGetCurrent() - _playStartTime) * 1000;
        _totalPlayDuration += delta;
        _isPlaying = NO;
        _playStartTime = 0;
    }
}

- (void)reportDuration {
    if (_onSessionEnd && _totalPlayDuration > 0) {
        _onSessionEnd(_totalPlayDuration);
    }
    _totalPlayDuration = 0;
}

@end

Registration and usage:

AliPlayerController *controller = [[AliPlayerController alloc] init];

[controller.strategyManager registerStrategy:
    [[PlayDurationStrategy alloc] initWithCallback:^(NSTimeInterval durationMs) {
        NSLog(@"Playback duration: %.0fms", durationMs);
    }]];

[controller configure:model];
[self.playerView attach:controller];

Implement StrategyProtocol directly (advanced)

Conforming to the protocol directly provides more flexibility, but you must manage event subscriptions yourself:

@interface MyCustomStrategy : NSObject <StrategyProtocol, PlayerNotificationDelegate>
@end

@implementation MyCustomStrategy {
    StrategyContext *_context;
}

- (NSString *)strategyName {
    return @"MyCustomStrategy";
}

- (void)strategyDidStart:(StrategyContext *)context {
    _context = context;
    [context.controller addNotificationDelegate:self];
}

- (void)strategyDidStop {
    [_context.controller removeNotificationDelegate:self];
    _context = nil;
}

- (void)strategyDidReset:(StrategyContext *)context {
    _context = context;
}

#pragma mark - PlayerNotificationDelegate

- (void)playerDidChangeState:(PlayerState)state {
    // Handle state changes.
}

@end
Note

When you implement the protocol directly, you must manually unsubscribe from all events in strategyDidStop. Failure to do so will cause a memory leak. Inheriting from BaseStrategy handles this automatically.

Strategy lifecycle

Lifecycle stages

Lifecycle method

Trigger conditions

Description

registerStrategy:

Manual registration or automatic registration by a global factory.

The strategy is added to the manager and waits to be started. If the manager is already started, the new strategy starts immediately.

strategyDidStart:

StrategyManager.startWithController:playerModel:

Starts the strategy, subscribes to notifications, and initializes resources.

PlayerNotificationDelegate

The controller dispatches notifications.

The strategy processes the received player events.

strategyDidReset:

StrategyManager.resetWithPlayerModel:

Resets the internal state and updates the context (when the video source is switched).

strategyDidStop

StrategyManager.stop or the strategy is unregistered.

Stops the strategy, unsubscribes, and cleans up resources.

destroy

StrategyManager.destroy

Stops all strategies and clears the strategy list.

Lifecycle flow

Create a controller
    ↓
[StrategyRegistry applyToManager:] → Register global strategies
    ↓
[playerView attach:controller]
    ↓
[strategyManager startWithController:playerModel:] → Create StrategyContext
    ↓                                                 → Iterate through strategies and call strategyDidStart:
Strategy is automatically registered as PlayerNotificationDelegate (BaseStrategy)
    ↓
Player notifications are dispatched through NotificationDispatcher → Strategy responds to callback methods
    ↓
Playback content is switched → [controller configure:newModel]
    ↓           → [strategyManager resetWithPlayerModel:] → Update StrategyContext
    ↓                                                      → Iterate through strategies and call strategyDidReset:
    ↓                                                      → BaseStrategy calls resetInternalState
    ↓
[playerView detach] or [controller destroy]
    ↓
[strategyManager stop] → Iterate through strategies and call strategyDidStop
                        → BaseStrategy automatically unregisters NotificationDelegate

Strategy manager (StrategyManager)

StrategyManager is responsible for managing the lifecycle of all strategies. Each AliPlayerController has a single StrategyManager instance.

@interface StrategyManager : NSObject

/// Registers a strategy. A strategy with the same name is replaced. If the manager is started, the new strategy starts immediately.
- (void)registerStrategy:(id<StrategyProtocol>)strategy;

/// Unregisters a strategy by name. If the manager is started, the strategy is stopped before it is removed.
- (void)unregisterStrategyWithName:(NSString *)name;

/// Finds a strategy by name.
- (nullable id<StrategyProtocol>)strategyWithName:(NSString *)name;

/// Starts all strategies. If they are already started, they are stopped and then restarted.
- (void)startWithController:(AliPlayerController *)controller
                playerModel:(AliPlayerModel *)playerModel;

/// Resets all strategies. This is called when the video source is switched. It has no effect if the strategies are not started.
- (void)resetWithPlayerModel:(AliPlayerModel *)playerModel;

/// Stops all strategies. The strategy instances are retained and can be started again.
- (void)stop;

/// Destroys the manager. This stops all strategies and clears the strategy list.
- (void)destroy;

/// The number of currently registered strategies.
@property (nonatomic, assign, readonly) NSUInteger strategyCount;

/// Indicates whether the manager is started.
@property (nonatomic, assign, readonly, getter=isStarted) BOOL started;

@end
Note

All methods must be called on the main thread. The manager does not provide internal thread synchronization. Strategy lifecycle callbacks are executed in the order of registration.

Best practices

Lifecycle management

@implementation MyStrategy

- (void)strategyDidStart:(StrategyContext *)context {
    [super strategyDidStart:context];  // You must call super.
    // Initialize resources.
}

- (void)strategyDidStop {
    // Clean up resources (timers, network listeners, etc.).
    [super strategyDidStop];  // You must call super.
}

- (void)resetInternalState {
    // Reset the internal state to prepare for a new video.
    _count = 0;
    _duration = 0;
}

@end

Event response

BaseStrategy automatically registers as a PlayerNotificationDelegate. Child classes can directly implement the callback methods:

#pragma mark - PlayerNotificationDelegate

- (void)playerDidChangeState:(PlayerState)state {
    // Handle state changes.
}

- (void)playerDidRenderFirstFrame {
    // Handle first frame rendering.
}

- (void)playerDidLoadingBegin {
    // Handle the start of loading.
}

- (void)playerDidLoadingEnd {
    // Handle the end of loading.
}

Access player state

You can access player information through the context (available after strategyDidStart:):

- (void)playerDidChangeState:(PlayerState)state {
    // Get the playback data model.
    AliPlayerModel *model = self.context.playerModel;
    NSString *title = model.videoTitle;

    // Get the player state.
    PlayerStateStore *stateStore = self.context.stateStore;
    long position = stateStore.currentPosition;
    long duration = stateStore.duration;

    // Send a command through the controller.
    [self.context.controller pause];
}

Notes

Scenario

Recommended practice

Reason

Overriding lifecycle methods

You must call super.

The BaseStrategy class manages notification subscriptions through its superclass.

Long-running tasks

Cancel the task in strategyDidStop.

This prevents memory leaks.

Video switching

Reset the state in resetInternalState.

Ensure that the state is correct to prevent outdated data from accumulating.

Accessing the context

Use it after strategyDidStart:.

This ensures that the context is initialized and available.

Network monitoring

Remove the listener in strategyDidStop.

This prevents resource leaks.

Thread safety

Execute all operations on the main thread.

The StrategyManager is not thread-safe.

Common mistakes

// ✗ Incorrect: Accessing the context in the constructor.
- (instancetype)init {
    self = [super init];
    if (self) {
        // The context is nil at this point!
        NSString *title = self.context.playerModel.videoTitle;  // nil
    }
    return self;
}

// ✓ Correct: Access it after strategyDidStart:.
- (void)strategyDidStart:(StrategyContext *)context {
    [super strategyDidStart:context];
    NSString *title = self.context.playerModel.videoTitle;  // Access is normal.
}
// ✗ Incorrect: resetInternalState does not reset all internal states.
- (void)resetInternalState {
    // Forgot to reset _stutterCount, which causes data to accumulate across videos.
}

// ✓ Correct: Reset all internal states.
- (void)resetInternalState {
    _stutterCount = 0;
    _totalDuration = 0;
    _isPlaying = NO;
}
// ✗ Incorrect: Overriding a lifecycle method without calling super.
- (void)strategyDidStart:(StrategyContext *)context {
    // Did not call [super strategyDidStart:context].
    // This prevents the context from being saved and notifications from being subscribed.
}

// ✓ Correct: Always call super.
- (void)strategyDidStart:(StrategyContext *)context {
    [super strategyDidStart:context];
    // Custom initialization.
}

API reference

Core classes

Class/Protocol

Description

StrategyProtocol

The strategy protocol, which defines the lifecycle contract.

BaseStrategy

The base class for strategies. It encapsulates notification subscription management and lifecycle flow.

StrategyManager

The strategy manager. It manages strategy registration, lifecycle, and error isolation.

StrategyContext

The strategy context. It provides read-only environment information about the player.

StrategyRegistry

The global strategy registry. It manages default strategy factories.

StrategyProtocol methods

Method

Required

Description

strategyName

Yes

Returns the strategy name (must be unique).

strategyDidStart:

Yes

Starts the strategy and attaches the context.

strategyDidStop

Yes

Stops the strategy and detaches the context.

strategyDidReset:

Yes

Resets the strategy and updates the context.

BaseStrategy methods

Method/Property

Description

context

The strategy context (available after strategyDidStart:).

resetInternalState

A hook method for child classes to reset their internal state.

StrategyManager methods

Method

Description

registerStrategy:

Registers a strategy (replaces if the name exists, starts immediately if the manager is started).

unregisterStrategyWithName:

Unregisters a strategy by name.

strategyWithName:

Queries for a strategy by name.

startWithController:playerModel:

Starts all strategies.

resetWithPlayerModel:

Resets all strategies.

stop

Stops all strategies.

destroy

Disposal Manager

strategyCount

The number of registered strategies.

started

Indicates whether the manager is started.

StrategyRegistry methods

Method

Description

+sharedRegistry

Gets the global singleton instance.

addGlobalStrategyFactory:

Registers a global strategy factory.

clearGlobalStrategies

Clears all global strategies (including built-in ones).

applyToManager:

Applies global strategies to a specified manager.

resetToDefault

Restores the default built-in strategy configuration.

StrategyContext methods

Property

Type

Description

controller

AliPlayerController * (weak)

Player controller.

playerModel

AliPlayerModel *

Playback configuration model.

stateStore

PlayerStateStore * (nullable)

Player state store (read-only).

Built-in strategies

Strategy

Delegate protocol

Key properties/methods

FirstFrameStrategy

FirstFrameStrategyDelegate

delegate

StutterDetectStrategy

StutterDetectStrategyDelegate

delegate, stutterCount, totalStutterDurationMs, stutterThresholdMs, initWithThreshold:

TrafficProtectionStrategy

TrafficProtectionStrategyDelegate

delegate, isOnCellularNetwork

Example reference

The PlayerKitUsages/UsageStrategySystem module provides a complete example of how to use the strategy system. This example demonstrates the automatic loading of built-in strategies, such as time-to-first-frame, stutter detection, and traffic protection. It also shows how to register a custom ResumePlayStrategy, query the resume position, and clear its data.