CuePointMonitor.java
Overview
`CuePointMonitor` is an abstract class designed to monitor video playback progress on a frame-by-frame basis and coordinate advertisement-related actions within a media player leveraging ExoPlayer. It integrates tightly with a finite state machine player (`FsmPlayer`) to manage ad retrieval and ad display based on predefined cue points in video content.
The primary responsibilities of this class are:
Tracking the current playback position relative to cue points and ad call points.
Initiating network calls to fetch ads ahead of reaching the cue points.
Triggering the display of ads exactly at the cue points.
Preventing redundant or repeated ad calls and ad displays using internal safe-check mechanisms.
Providing utility methods to efficiently search cue points with a timing tolerance to accommodate slight playback variations.
`CuePointMonitor` acts as a bridge between playback progress and the FSM controlling ad insertion, ensuring ads are requested and played at correct times without disrupting the user experience.
Class: CuePointMonitor
Package
package com.tubitv.media.fsm.listener;
Dependencies
com.tubitv.media.fsm.Input— Enum representing FSM inputs/triggers.com.tubitv.media.fsm.concrete.AdPlayingStateandVpaidState— States indicating that ads are currently playing.com.tubitv.media.fsm.state_machine.FsmPlayer— The finite state machine player that manages playback states and transitions.com.tubitv.media.helpers.Constants— Contains constants used for logging tags.com.tubitv.media.utilities.ExoPlayerLogger— Utility for logging.
Fields
Field | Type | Description |
|---|---|---|
`TAG` | String | Class tag for logging purposes. |
`RANGE_FACTOR` | long | Tolerance window (1.5 seconds) for approximate cue point matching in binary searches. |
`fsmPlayer` | FsmPlayer | Reference to the FSM player instance for state transitions and cue point updates. |
`safeCheckForAdcall` | boolean | Flag to ensure ad call network requests are triggered only once per cue point. |
`safeCheckForCue` | boolean | Flag to ensure ad display triggers only once per cue point. |
`cuePoints` | long[] | Array of cue point timestamps (in milliseconds) indicating when ads should play. |
`adCallPoints` | long[] | Array of timestamps (milliseconds) for triggering ad network calls, offset ahead of cue points. |
`currentQueuePointPos` | int | Index of the current active cue point being processed, or -1 if none. |
Constructor
public CuePointMonitor(FsmPlayer fsmPlayer)
Parameters:
fsmPlayer— Instance ofFsmPlayerto coordinate FSM transitions.
Description:
Initializes the monitor with a reference to the FSM player.
Public Methods
1. binarySerchWithRange(long[] a, long key) : int
Description:
Performs a binary search on a sorted arrayato find an element approximately matchingkeywithin a tolerance ofRANGE_FACTORmilliseconds.Parameters:
a— Sorted array of long values representing cue points or ad call points.key— The playback position in milliseconds to search for.
Returns:
Index of the matching cue point within range if found.
Otherwise, negative insertion point
-(low + 1)indicating no match.
Usage:
Used internally to detect when playback is near an ad call or cue point, allowing a ±1.5 seconds tolerance.
2. binarySerchExactly(long[] a, long key) : int
Description:
Performs an exact binary search without tolerance on the arrayafor the exactkey.Parameters:
Same as above.
Returns:
Index of exact match or negative insertion point if not found.
Usage:
Secondary utility, not typically used in this class's core logic.
3. abstract int networkingAhead()
Description:
Abstract method that concrete subclasses must implement to specify the offset duration (in milliseconds) to request ads ahead of cue points.Returns:
Number of milliseconds to advance the ad call point before the cue point.
Usage:
Defines how early the system should attempt to fetch ads relative to cue points.
4. void setQuePoints(@Nullable long[] cuePoints)
Description:
Sets the cue points for the current media content and calculates corresponding ad call points.Parameters:
cuePoints— Array of cue point timestamps in milliseconds. May be null to clear the points.
Effect:
Resets internal state (
currentQueuePointPos, safe-check flags).Calculates ad call points by subtracting
networkingAhead()from each cue point (minimum zero).
Example:
long[] cuePoints = {30000, 60000, 90000}; // at 30s, 60s, 90s
cuePointMonitor.setQuePoints(cuePoints);
5. void onMovieProgress(long milliseconds, long durationMillis)
Description:
Called continuously during playback to update the monitor with the current playback position.Parameters:
milliseconds— Current playback position in milliseconds.durationMillis— Total duration of the media (unused internally).
Behavior:
If the FSM player is currently in an ad playing state (
AdPlayingStateorVpaidState), ignores progress updates.Otherwise, checks if an ad network call should be performed ahead of the cue point.
Checks if an ad should be displayed at the current cue point.
Transitions FSM player state accordingly.
Example Usage:
cuePointMonitor.onMovieProgress(currentPositionMs, totalDurationMs);
Protected / Private Methods
1. void preformAdCallIfNecessary(long milliseconds)
Description:
Checks if the current playback position is close to any ad call point and, if allowed by safe checks, triggers the FSM input to make an ad network call.Parameters:
milliseconds— Current playback position.
Behavior:
If within range and
safeCheckForAdcallis true, calls FSM inputMAKE_AD_CALLand updates theAdRetrieverwith the current cue point.Resets
safeCheckForAdcallto false to prevent duplicate calls.If playback moves away from the ad call point range, resets
safeCheckForAdcallto true.
2. void preformShowAdIfNecessary(long milliseconds)
Description:
Checks if the current playback position matches a cue point and, if allowed by safe checks, triggers the FSM input to show ads.Parameters:
milliseconds— Current playback position.
Behavior:
If within range and
safeCheckForCueis true, calls FSM inputSHOW_ADS.Resets
safeCheckForCueto false.Resets
safeCheckForCueto true when playback moves away.
3. boolean isProgressActionable(long[] array, long currentProgress)
Description:
Utility to check if the current playback position is within the trigger range of any point in the given array (cue points or ad call points).Parameters:
array— Array of cue or ad call points.currentProgress— Current playback time.
Returns:
trueif currentProgress is near a point inarray.Updates
currentQueuePointPosto the matched index.falseotherwise and resetscurrentQueuePointPosto -1.
4. long[] getAddCallPoints(long[] cuePoints)
Description:
Calculates ad call points by subtracting thenetworkingAhead()offset from each cue point timestamp, ensuring no negative values.Parameters:
cuePoints— Array of cue points.
Returns:
New array of ad call points.
Usage:
Ensures ad calls happen in advance of cue points to allow ad fetching.
5. void remoteShowedCuePoints()
Description:
Intended to remove cue points that have already triggered ads after ad calls finish.
Note: This method is currently unused.Behavior:
Removes the current cue point from the cue points array, updating the monitor state.
Implementation Detail:
Uses internal helperremoveElementFromArray.
6. long[] removeElementFromArray(long[] array, int keyPos)
Description:
Creates a new array with the element atkeyPosremoved.Parameters:
array— Original array.keyPos— Index of element to remove.
Returns:
New array without the element at
keyPos, ornullif invalid.
Important Implementation Details
Safe Check Flags (
safeCheckForAdcall,safeCheckForCue):
These boolean flags prevent repeated triggering of ad calls or ad displays when playback position remains within the trigger range over multiple frames, ensuring one-time execution per cue point.Binary Search With Range:
ThebinarySearchWithRangemethod extends standard binary search to find elements within a ±RANGE_FACTORwindow, efficiently detecting if playback is "close enough" to a cue point for triggering actions.Cue Points vs. Ad Call Points:
Cue points represent exact timestamps for showing ads. Ad call points are offset earlier bynetworkingAhead()milliseconds to allow the system to request ads ahead of time.FSM Integration:
The monitor never directly controls UI or playback but invokes FSM transitions (MAKE_AD_CALLandSHOW_ADS) to delegate responsibilities, following clean separation of concerns.Abstract
networkingAhead():
Subclasses define how far ahead of cue points ad calls should be made, allowing flexible prefetching strategies.
Interaction with Other Components
FsmPlayer:
The monitor usesfsmPlayerto query current playback state and to send inputs for state transitions related to ads, such asMAKE_AD_CALLandSHOW_ADS.AdRetriever (via
fsmPlayer.updateCuePointForRetriever):
When making an ad call, the monitor updates theAdRetrieverwith the current cue point to fetch appropriate ads.ExoPlayer Playback:
The monitor expects continuous updates on playback progress (onMovieProgress) to evaluate when to trigger ad calls or ad displays.AdPlayingState and VpaidState:
The monitor checks if the player is currently in these ad playback states and suspends triggering actions during ads.
Usage Example
// Subclass defines networkingAhead()
public class MyCuePointMonitor extends CuePointMonitor {
@Override
public int networkingAhead() {
return 5000; // 5 seconds before cue point
}
}
// Usage
FsmPlayer fsmPlayer = ...; // initialized FSM player instance
MyCuePointMonitor monitor = new MyCuePointMonitor(fsmPlayer);
// Set cue points in milliseconds
long[] cuePoints = {30000, 60000, 90000}; // 30s, 60s, 90s
monitor.setQuePoints(cuePoints);
// During playback, call onMovieProgress continuously
long currentPosition = 29500; // e.g., 29.5 seconds
monitor.onMovieProgress(currentPosition, 120000); // total duration 2 minutes
Visual Diagram
classDiagram
class CuePointMonitor {
-static final String TAG
-static final long RANGE_FACTOR
-FsmPlayer fsmPlayer
-boolean safeCheckForAdcall
-boolean safeCheckForCue
-long[] cuePoints
-long[] adCallPoints
-int currentQueuePointPos
+CuePointMonitor(FsmPlayer fsmPlayer)
+static int binarySerchWithRange(long[] a, long key)
+static int binarySerchExactly(long[] a, long key)
#abstract int networkingAhead()
+void setQuePoints(long[] cuePoints)
+void onMovieProgress(long milliseconds, long durationMillis)
-void preformAdCallIfNecessary(long milliseconds)
-void preformShowAdIfNecessary(long milliseconds)
-boolean isProgressActionable(long[] array, long currentProgress)
-long[] getAddCallPoints(long[] cuePoints)
+void remoteShowedCuePoints()
-long[] removeElementFromArray(long[] array, int keyPos)
}
Summary
`CuePointMonitor` is a crucial component for ad insertion in media playback, providing a robust mechanism to detect playback proximity to cue points and coordinate with a finite state machine to fetch and show ads timely. Its design ensures efficiency through binary search with tolerance, safety through trigger flags, and flexibility via an abstract networking ahead parameter. It maintains clear separation of concerns by delegating playback and UI control to other system components while focusing on cue point monitoring logic.