Notification system

Updated at:

The Notification System is the inter-component communication infrastructure of AliPlayerKit. It uses a Notification Dispatcher and Delegate protocol pattern to dispatch information, such as internal player state changes, gesture interactions, and slot operations, to all observers. This pattern completely decouples the player controller, UI slots, and policies.

Concepts

What is the notification system?

The Notification System is the multicast notification dispatch mechanism within PlayerKit. Each Dispatcher manages a group of weakly referenced observers. It defines callback interfaces through a corresponding Delegate protocol. Observers only need to implement the methods they are interested in to receive notifications.

Core features:

  • Multicast dispatch: Each Dispatcher supports registering multiple observers. Notifications are broadcast to all registered observers.

  • Weak reference management: Observers are stored as weak references using NSHashTable. They are automatically cleaned up after the object is released.

  • Instance-level isolation: Each AliPlayerController holds an independent Dispatcher instance. Notifications from different player instances do not interfere with each other.

  • Exception isolation: Each observer call is wrapped in a @try/@catch block. An exception in one observer does not affect other observers.

Problems solved

Problem

Solution with the notification system

High coupling due to direct dependencies between components

Communication through Delegate protocols removes direct references between components.

Disordered notifications with multiple player instances

Each controller holds an independent Dispatcher instance, providing natural isolation.

Mixing of UI and business logic

Downward dispatch of state notifications separates responsibilities.

Subscriber leaks

Weak references managed by NSHashTable ensure observers are automatically cleaned up after they are released.

Core architecture

The PlayerKit notification system consists of three groups of Dispatcher and Delegate protocols:

┌───────────────────────────────────────────────────────────────────┐
│                     AliPlayerController                            │
│                                                                   │
│  ┌─────────────────────────────────┐                              │
│  │ PlayerNotificationDispatcher    │──▶ PlayerNotificationDelegate │
│  └─────────────────────────────────┘                              │
│                                                                   │
│  ┌─────────────────────────────────┐                              │
│  │ GestureNotificationDispatcher   │──▶ GestureNotificationDelegate│
│  └─────────────────────────────────┘                              │
│                                                                   │
│  ┌─────────────────────────────────┐                              │
│  │ SlotActionNotificationDispatcher│──▶ SlotActionNotificationDele.│
│  └─────────────────────────────────┘                              │
└───────────────────────────────────────────────────────────────────┘
        │                   │                    │
        ▼                   ▼                    ▼
   [Observer A]        [Observer B]         [Observer C]
   (Slot/Strategy)     (Slot/Strategy)      (Slot/Strategy)

Dispatcher

Delegate protocol

Responsibility

Access method

PlayerNotificationDispatcher

PlayerNotificationDelegate

Core player notifications: state, progress, errors, snapshots, full screen, control bar, loading, display mode, and tracks.

Through the controller's addNotificationDelegate:

GestureNotificationDispatcher

GestureNotificationDelegate

Gesture notifications: single tap, long press, brightness slide, and volume slide.

Injected into built-in slots by SlotHostLayout.

SlotActionNotificationDispatcher

SlotActionNotificationDelegate

Slot action notifications: settings menu, playback speed panel, and quality panel.

Injected into built-in slots by SlotHostLayout.

Note

AliPlayerController only exposes the registration entry point for PlayerNotificationDelegate (addNotificationDelegate: / removeNotificationDelegate:). GestureNotificationDispatcher and SlotActionNotificationDispatcher are part of the internal communication mechanism for slots. They are automatically injected by SlotHostLayout during slot construction and are not exposed externally.

The three Dispatcher groups

PlayerNotificationDispatcher

The core player notification dispatcher. It is responsible for dispatching information, such as player state changes, progress updates, and error notifications, to all observers.

Core properties and methods:

Interface

Description

playerId

The unique identifier of the player that is the source of the notification (NSString, read/write). It is written by the controller after configuring the MediaPlayer.

addObserver:

Adds an observer that conforms to PlayerNotificationDelegate (weak reference, adding duplicates has no effect).

removeObserver:

Removes the specified observer (has no effect if not registered).

removeAllObservers

Removes all observers.

notifyObservers:

Dispatches a notification block to all observers.

notifyObservers:withBlock:

Dispatches only to observers that implement the specified selector (selector filtering).

observerCount

Returns the number of current active observers.

Convenience dispatch methods (called internally by the controller):

Method

Trigger scenario

dispatchDidChangeState:

Player state changes.

dispatchDidPreparedWithDuration:

Preparation is complete.

dispatchDidRenderFirstFrame

First frame is rendered.

dispatchDidCompletion

Playback is complete.

dispatchDidUpdatePosition:duration:bufferedPosition:

Progress is updated.

dispatchDidEncounterError:

An error occurs.

dispatchDidCaptureScreenImage:

Snapshot is complete.

dispatchDidChangeVideoWidth:height:

Video dimensions change.

dispatchFullscreenChanged:

Full-screen state changes.

dispatchDidLoadingBegin

Buffering starts.

dispatchDidLoadingEnd

Buffering ends.

dispatchDidUpdateLoadingProgress:

Buffering progress is updated.

dispatchDidChangeMirrorMode:

Mirror mode changes.

dispatchDidChangeScaleMode:

Scaling mode changes.

dispatchDidChangeRotateMode:

Rotation mode changes.

dispatchDidTrackReady:

Track information is ready.

dispatchDidTrackChanged:

Track switching is complete.

Note

PlayerNotificationDelegate defines 18 @optional callback methods, but the Dispatcher provides 17 convenience dispatch methods. The playerDidChangeControlsVisible: notification is dispatched by GestureControlSlot using the generic notifyObservers:withBlock: method, instead of a dedicated convenience method.

GestureNotificationDispatcher

The gesture notification dispatcher. It is created and held by GestureControlSlot. After a gesture is recognized, it dispatches semantic information about the gesture to all observers.

Core methods:

Interface

Description

addObserver:

Adds an observer that conforms to GestureNotificationDelegate.

removeObserver:

Removes the specified observer.

removeAllObservers

Removes all observers.

notifyObservers:

Dispatches a notification block to all observers.

observerCount

Returns the number of current active observers.

Features:

  • Callback parameters focus on the data required for display, such as brightness or volume percentage, rather than the raw coordinate information of the gesture.

  • Injected by SlotHostLayout into slots that need to respond to gestures, such as TopBarSlot, BottomBarSlot, and CenterDisplaySlot, during slot construction.

SlotActionNotificationDispatcher

The slot action notification dispatcher. It is created and managed by SlotHostLayout. It is used to decouple direct method calls between slots, such as when TopBarSlot or BottomBarSlot triggers SettingMenuSlot.

Core methods:

Interface

Description

addObserver:

Adds an observer that conforms to SlotActionNotificationDelegate.

removeObserver:

Removes the specified observer.

removeAllObservers

Removes all observers.

notifyObservers:

Asynchronously dispatches a notification block to all observers.

observerCount

Returns the number of current active observers.

Features: Unlike other Dispatchers, SlotActionNotificationDispatcher always dispatches notifications asynchronously using dispatch_async(dispatch_get_main_queue(), ...). This avoids UI freezes that can be caused by performing heavy UI operations synchronously within the button event handling chain.

Usage

Register through the controller (recommended)

AliPlayerController provides convenience methods to register PlayerNotificationDelegate observers. This is the most common way to subscribe:

@interface MyViewController () <PlayerNotificationDelegate>
@property (nonatomic, strong) AliPlayerController *controller;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.controller = [[AliPlayerController alloc] init];

    // Register as a notification observer
    [self.controller addNotificationDelegate:self];

    // Configure and attach the player...
    [self.controller configure:model];
    [self.playerView attach:self.controller];
}

- (void)dealloc {
    // Explicitly remove the observer.
    [self.controller removeNotificationDelegate:self];
    [self.controller destroy];
}

#pragma mark - PlayerNotificationDelegate

- (void)playerDidChangeState:(PlayerState)state {
    // Update the play/pause button state
}

- (void)playerDidUpdateCurrentPosition:(NSInteger)position
                              duration:(NSInteger)duration
                      bufferedPosition:(NSInteger)bufferedPosition {
    // Update the progress bar
}

- (void)playerDidEncounterError:(NSError *)error {
    // Display an error message
}

@end

Controller registration entry points:

Method

Description

addNotificationDelegate:

Adds an observer that conforms to the PlayerNotificationDelegate protocol. The observer is held by a weak reference.

removeNotificationDelegate:

Removes a previously added notification observer.

Note

Observers are stored as weak references using NSHashTable. They are automatically removed from the list when the observer object is released. However, you should explicitly call removeNotificationDelegate: in your observer's dealloc method to ensure prompt cleanup.

Internal slot communication (advanced)

GestureNotificationDispatcher and SlotActionNotificationDispatcher are part of the internal communication mechanism for slots. They are provided to built-in slots by SlotHostLayout through property injection during slot construction.

If a custom slot needs to receive gesture or slot action notifications, declare the corresponding Dispatcher property. SlotHostLayout will inject it for use:

@interface MyCustomSlot : UIView <SlotProtocol, GestureNotificationDelegate, SlotActionNotificationDelegate>

@property (nonatomic, weak, nullable) GestureNotificationDispatcher *gestureDispatcher;
@property (nonatomic, weak, nullable) SlotActionNotificationDispatcher *slotActionDispatcher;

@end

@implementation MyCustomSlot

- (void)setGestureDispatcher:(GestureNotificationDispatcher *)gestureDispatcher {
    if (_gestureDispatcher) {
        [_gestureDispatcher removeObserver:self];
    }
    _gestureDispatcher = gestureDispatcher;
    if (_gestureDispatcher) {
        [_gestureDispatcher addObserver:self];
    }
}

- (void)setSlotActionDispatcher:(SlotActionNotificationDispatcher *)slotActionDispatcher {
    if (_slotActionDispatcher) {
        [_slotActionDispatcher removeObserver:self];
    }
    _slotActionDispatcher = slotActionDispatcher;
    if (_slotActionDispatcher) {
        [_slotActionDispatcher addObserver:self];
    }
}

#pragma mark - GestureNotificationDelegate

- (void)gestureDidSingleTap {
    // Toggle control bar visibility on single tap
}

- (void)gestureDidUpdateVolumeWithPercent:(CGFloat)currentPercent {
    // Display the volume adjustment UI
}

#pragma mark - SlotActionNotificationDelegate

- (void)slotDidRequestToggleSettingMenu {
    // Respond to the request to toggle the settings menu
}

@end
Note

GestureNotificationDispatcher is created and held by GestureControlSlot (a readonly property). SlotActionNotificationDispatcher is created and held by SlotHostLayout. The Dispatcher properties of a slot are declared as weak and are automatically injected by SlotHostLayout when rebuildSlots is called.

Complete code example

The following example shows how a complete playback page subscribes to player notifications:

@interface PlayerPageViewController () <PlayerNotificationDelegate>
@property (nonatomic, strong) AliPlayerView *playerView;
@property (nonatomic, strong) AliPlayerController *controller;
@end

@implementation PlayerPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.playerView = [[AliPlayerView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.playerView];

    self.controller = [[AliPlayerController alloc] init];

    // Register as a notification observer
    [self.controller addNotificationDelegate:self];

    VideoSource *source = [VideoSource vidAuthSourceWithVid:@"vid" playAuth:@"auth"];
    AliPlayerModel *model = [[AliPlayerModel alloc] initWithVideoSource:source];
    [self.controller configure:model];
    [self.playerView attach:self.controller];
}

- (void)dealloc {
    [self.controller removeNotificationDelegate:self];
    [self.controller destroy];
}

#pragma mark - PlayerNotificationDelegate

- (void)playerDidChangeState:(PlayerState)state {
    NSLog(@"Player state changed: %ld", (long)state);
}

- (void)playerDidPreparedWithDuration:(NSInteger)duration {
    NSLog(@"Preparation complete, total duration: %ld ms", (long)duration);
}

- (void)playerDidRenderFirstFrame {
    // Hide the thumbnail
}

- (void)playerDidCompletion {
    // Show the replay button
}

- (void)playerDidUpdateCurrentPosition:(NSInteger)position
                              duration:(NSInteger)duration
                      bufferedPosition:(NSInteger)bufferedPosition {
    // Update the progress bar
}

- (void)playerDidChangeFullscreen:(BOOL)isFullscreen {
    // Update the layout for full-screen/non-full-screen mode
}

- (void)playerDidChangeControlsVisible:(BOOL)visible {
    // Sync control bar visibility
}

- (void)playerDidEncounterError:(NSError *)error {
    NSLog(@"Playback error: %@", error.localizedDescription);
}

@end
Note

The PlayerKitUsages/UsageNotificationSystem module provides a complete example of how to use the notification system. It shows how to register a PlayerNotificationDelegate observer and receive real-time notifications for player state changes, progress updates, and more.

List of notifications

PlayerNotificationDelegate (18 @optional methods)

Playback state notifications

Method

Triggered when

Parameter description

playerDidChangeState:

The player state transitions.

state — The new PlayerState enumeration value.

playerDidPreparedWithDuration:

The player finishes preparation.

duration — The total duration of the media in milliseconds.

playerDidRenderFirstFrame

The first frame of the video is rendered.

—

playerDidCompletion

Playback reaches the end of the media.

—

Playback progress notifications

Method

Triggered when

Parameter description

playerDidUpdateCurrentPosition:duration:bufferedPosition:

Called periodically during playback.

position — The current position in ms. duration — The total duration in ms. bufferedPosition — The buffered position in ms.

Error notifications

Method

Triggered when

Parameter description

playerDidEncounterError:

A playback error occurs.

error — An NSError object.

Snapshot notifications

Method

Triggered when

Parameter description

playerDidCompleteSnapshot:

A snapshot is completed.

image — The captured UIImage. It is nil on failure.

Video dimension notifications

Method

Triggered when

Parameter description

playerDidChangeVideoWidth:height:

The video dimensions change.

width/height — The original dimensions of the video in pixels.

Full-screen and control bar notifications

Method

Triggered when

Parameter description

playerDidChangeFullscreen:

The full-screen transition is complete.

isFullscreen — Indicates whether the player is in full-screen mode.

playerDidChangeControlsVisible:

The visibility of the control bar changes.

visible — Indicates whether the control bar should be visible.

Note

The playerDidChangeControlsVisible: notification is triggered by a single-tap gesture in GestureControlSlot or by the auto-hide timer. All control bars that need to synchronize their visibility should implement this method. This prevents state inconsistencies that can result from independent toggling.

Loading notifications

Method

Triggered when

Parameter description

playerDidLoadingBegin

Network stuttering occurs or the buffer is insufficient.

—

playerDidLoadingEnd

There is enough buffered data to resume playback.

—

playerDidUpdateLoadingProgress:

The buffering progress changes.

progress — A float value from 0 to 100.

Display mode notifications

Method

Triggered when

Parameter description

playerDidChangeMirrorMode:

The mirror mode changes.

mirrorMode — The new MirrorMode.

playerDidChangeScaleMode:

The scaling mode changes.

scaleMode — The new ScaleMode.

playerDidChangeRotateMode:

The rotation mode changes.

rotateMode — The new RotateMode.

Track notifications

Method

Triggered when

Parameter description

playerDidTrackReady:

The available track information is ready.

tracks — An NSArray<TrackQuality *>.

playerDidTrackChanged:

Track switching is complete.

quality — The TrackQuality after the switch.

GestureNotificationDelegate (7 @optional methods)

Method

Triggered when

Parameter description

gestureDidSingleTap

A single-tap gesture is triggered.

—

gestureDidBeginLongPress

A long-press gesture starts (playback speed is activated).

—

gestureDidEndLongPress

A long-press gesture ends (playback speed is restored).

—

gestureDidUpdateBrightnessWithPercent:

A vertical drag on the left side is updated.

currentPercent — The brightness value, from 0.0 to 1.0.

gestureDidEndBrightnessAdjust

A vertical drag on the left side ends.

—

gestureDidUpdateVolumeWithPercent:

A vertical drag on the right side is updated.

currentPercent — The volume level, from 0.0 to 1.0.

gestureDidEndVolumeAdjust

A vertical drag on the right side ends.

—

SlotActionNotificationDelegate (3 @optional methods)

Method

Triggered when

Parameter description

slotDidRequestToggleSettingMenu

The Settings button in TopBarSlot is clicked.

—

slotDidRequestShowSpeedPanel

The Playback Speed button in BottomBarSlot is clicked.

—

slotDidRequestShowQualityPanel

The Quality button in BottomBarSlot is clicked.

—

Note

All notifications from SlotActionNotificationDelegate are dispatched asynchronously using dispatch_async(dispatch_get_main_queue(), ...). This ensures they execute in the next run loop and avoids UI issues caused by synchronous execution within the button event handling chain.

Instance-level isolation mechanism

Design principle

In scenarios with multiple player instances, such as vertical scrolling in short videos or Picture-in-Picture (PiP), notifications from different players must not interfere with each other. PlayerKit achieves notification isolation at the instance level rather than through global filtering.

Isolation method

Each AliPlayerController holds an independent PlayerNotificationDispatcher instance. After an observer registers with a controller's Dispatcher, it only receives notifications from that controller:

┌── AliPlayerController (A) ──┐     ┌── AliPlayerController (B) ──┐
│  PlayerNotificationDispatcher │     │  PlayerNotificationDispatcher │
│  ├── Observer 1               │     │  ├── Observer 3               │
│  └── Observer 2               │     │  └── Observer 4               │
└───────────────────────────────┘     └───────────────────────────────┘

Observers 1 and 2 only receive notifications from Controller A
Observers 3 and 4 only receive notifications from Controller B

Key design points:

  • No need for a global EventBus or to manually check the playerId in callbacks.

  • The PlayerNotificationDispatcher.playerId property is used to inform observers of the source identifier of a notification, not for filtering.

  • Registration provides isolation, and unregistering disconnects the observer.

// Notifications from controllerA are only dispatched to observers registered with A
[controllerA addNotificationDelegate:slotA];  // slotA only receives notifications from A
[controllerB addNotificationDelegate:slotB];  // slotB only receives notifications from B

Developing custom observers

Implement the Delegate protocol

Implement the required Delegate protocol. You only need to implement the methods you are interested in, as all methods are @optional:

@interface MyAnalyticsObserver : NSObject <PlayerNotificationDelegate>
@end

@implementation MyAnalyticsObserver

- (void)playerDidChangeState:(PlayerState)state {
    [self trackStateChange:state];
}

- (void)playerDidEncounterError:(NSError *)error {
    [self reportError:error];
}

- (void)playerDidCompletion {
    [self trackPlaybackComplete];
}

@end

Register and unregister

// Create the observer
MyAnalyticsObserver *observer = [[MyAnalyticsObserver alloc] init];

// Register: Use the controller's convenience entry point
[controller addNotificationDelegate:observer];

// Unregister: Explicitly remove
[controller removeNotificationDelegate:observer];
Note

Although the NSHashTable weak reference automatically cleans up after the observer is released, you should explicitly call removeNotificationDelegate: to ensure prompt cleanup. This avoids receiving unexpected notifications in the brief time window before the observer is released.

Thread safety mechanism

Feature

Description

Observer storage

Stored as weak references using NSHashTable weakObjectsHashTable.

List access

Protected by a serial dispatch queue (dispatch_queue_t) for thread safety.

Callback thread

Notifications are always dispatched on the main thread. For SlotActionNotificationDispatcher, this is the asynchronous main thread.

Exception isolation

Each observer call is wrapped in a @try/@catch block. An exception in one observer does not affect other observers.

Duplicate additions

Adding the same observer multiple times has no effect.

Safe for no-ops

Removing an unregistered observer has no effect.

Dispatch flow:

PlayerNotificationDispatcher / GestureNotificationDispatcher:
    dispatch method call
        → Get a snapshot of observers within the serial queue (thread-safe)
        → Call observer callbacks one by one on the main thread
        → Wrap each call in @try/@catch (exception isolation)

SlotActionNotificationDispatcher:
    notifyObservers: call
        → Get a snapshot of observers within the serial queue (thread-safe)
        → Dispatch asynchronously with dispatch_async(dispatch_get_main_queue(), ...)
        → Call observer callbacks one by one in the next run loop
        → Wrap each call in @try/@catch (exception isolation)

API quick reference

Dispatcher class

Class

Key methods

Description

PlayerNotificationDispatcher

addObserver: / removeObserver: / removeAllObservers / notifyObservers: / notifyObservers:withBlock:

Player notification dispatcher. Includes a playerId property and supports dispatch with selector filtering.

GestureNotificationDispatcher

addObserver: / removeObserver: / removeAllObservers / notifyObservers:

Gesture notification dispatcher.

SlotActionNotificationDispatcher

addObserver: / removeObserver: / removeAllObservers / notifyObservers:

Slot action notification dispatcher (asynchronous dispatch).

Delegate protocols

Protocol

Number of methods

Scope of responsibility

PlayerNotificationDelegate

18 @optional methods

Playback state, progress, errors, snapshots, full screen, control bar, loading, display mode, and tracks.

GestureNotificationDelegate

7 @optional methods

Single tap, long press, brightness adjustment, and volume adjustment.

SlotActionNotificationDelegate

3 @optional methods

Settings menu toggle, playback speed panel, and quality panel.

Controller protocol

Method

Description

addNotificationDelegate:

Registers a PlayerNotificationDelegate observer (weak reference).

removeNotificationDelegate:

Removes a PlayerNotificationDelegate observer.

Common Dispatcher methods

Method

Description

addObserver:

Adds an observer (weak reference, adding duplicates has no effect).

removeObserver:

Removes the specified observer (has no effect if not registered).

removeAllObservers

Clears all observers.

notifyObservers:

Dispatches a notification block to all observers.

observerCount

Returns the number of current active observers.

PlayerNotificationDispatcher-specific methods

Method

Description

notifyObservers:withBlock:

Dispatches only to observers that implement the specified selector (selector filtering).

17 convenience methods, such as dispatchDidChangeState:

Conveniently monitor player status, progress, errors, screenshots, full screen, loading, display mode, and tracks.