Skip to content

Commit

Permalink
perf(Ads): Reduce latency for interstitial to start playing (#7525)
Browse files Browse the repository at this point in the history
Previously we relied on an event triggered by the video itself which was
launched 4 to 60 times per second, which meant that we had an update (in
the worst case) of 250ms. Now we use a timer that is triggered every
25ms, which considerably reduces the delay.

This is important so as not to show anything from the original ad's
live.
  • Loading branch information
avelad authored Oct 31, 2024
1 parent 20ab35a commit 5ee6a4d
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions lib/ads/interstitial_ad_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,25 @@ shaka.ads.InterstitialAdManager = class {
this.lastPlayedAd_ = null;

this.eventManager_.listen(this.baseVideo_, 'timeupdate', () => {
if (this.playingAd_ || this.basePlayer_.isRemotePlayback()) {
if (this.playingAd_ || this.lastTime_ ||
this.basePlayer_.isRemotePlayback()) {
return;
}
this.lastTime_ = this.baseVideo_.currentTime;
const currentInterstitial = this.getCurrentInterstitial_(
/* needPreRoll= */ true, /* numberToSkip= */ 0, this.lastPlayedAd_);
if (currentInterstitial) {
this.setupAd_(currentInterstitial, /* sequenceLength= */ 1,
/* adPosition= */ 1, /* initialTime= */ Date.now());
}
});

/** @private {shaka.util.Timer} */
this.timeUpdateTimer_ = new shaka.util.Timer(() => {
if (this.playingAd_ || !this.lastTime_ ||
this.basePlayer_.isRemotePlayback()) {
return;
}
const needPreRoll = this.lastTime_ == null || this.lastTime_ == 0;
this.lastTime_ = this.baseVideo_.currentTime;
// Remove last played add when the new time is before to the ad time.
if (this.lastPlayedAd_ &&
Expand All @@ -105,12 +120,12 @@ shaka.ads.InterstitialAdManager = class {
this.lastPlayedAd_ = null;
}
const currentInterstitial = this.getCurrentInterstitial_(
needPreRoll, /* numberToSkip= */ 0, this.lastPlayedAd_);
/* needPreRoll= */ false, /* numberToSkip= */ 0, this.lastPlayedAd_);
if (currentInterstitial) {
this.setupAd_(currentInterstitial, /* sequenceLength= */ 1,
/* adPosition= */ 1, /* initialTime= */ Date.now());
}
});
}).tickEvery(/* seconds= */ 0.025);

/** @private {shaka.util.Timer} */
this.pollTimer_ = new shaka.util.Timer(async () => {
Expand Down Expand Up @@ -219,6 +234,10 @@ shaka.ads.InterstitialAdManager = class {
if (this.adContainer_) {
shaka.util.Dom.removeAllChildren(this.adContainer_);
}
if (this.timeUpdateTimer_) {
this.timeUpdateTimer_.stop();
this.timeUpdateTimer_ = null;
}
if (this.pollTimer_) {
this.pollTimer_.stop();
this.pollTimer_ = null;
Expand Down

0 comments on commit 5ee6a4d

Please sign in to comment.