stormcloud-video-player 0.2.36 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -2226,6 +2226,9 @@ var StormcloudVideoPlayer = class {
2226
2226
  this.activeAdRequestToken = null;
2227
2227
  this.adRequestWatchdogToken = null;
2228
2228
  this.adFailsafeToken = null;
2229
+ this.fetchedAdDurations = /* @__PURE__ */ new Map();
2230
+ this.targetAdBreakDurationMs = null;
2231
+ this.isAdaptiveMode = false;
2229
2232
  initializePolyfills();
2230
2233
  const browserOverrides = getBrowserConfigOverrides();
2231
2234
  this.config = { ...config, ...browserOverrides };
@@ -3032,7 +3035,7 @@ var StormcloudVideoPlayer = class {
3032
3035
  }
3033
3036
  }
3034
3037
  async fetchAdConfiguration() {
3035
- var _a, _b, _c;
3038
+ var _a, _b, _c, _d, _e, _f, _g;
3036
3039
  const vastMode = this.config.vastMode || "default";
3037
3040
  if (this.config.debugAdTiming) {
3038
3041
  console.log("[StormcloudVideoPlayer] VAST mode:", vastMode);
@@ -3103,6 +3106,16 @@ var StormcloudVideoPlayer = class {
3103
3106
  );
3104
3107
  }
3105
3108
  }
3109
+ const numberAds = (_g = (_f = (_e = (_d = data.response) == null ? void 0 : _d.options) == null ? void 0 : _e.vast) == null ? void 0 : _f.cue_tones) == null ? void 0 : _g.number_ads;
3110
+ if (numberAds != null && numberAds > 0) {
3111
+ this.apiNumberAds = numberAds;
3112
+ if (this.config.debugAdTiming) {
3113
+ console.log(
3114
+ "[StormcloudVideoPlayer] Number of ads per break from API:",
3115
+ this.apiNumberAds
3116
+ );
3117
+ }
3118
+ }
3106
3119
  }
3107
3120
  getCurrentAdIndex() {
3108
3121
  return this.currentAdIndex;
@@ -3110,6 +3123,27 @@ var StormcloudVideoPlayer = class {
3110
3123
  getTotalAdsInBreak() {
3111
3124
  return this.totalAdsInBreak;
3112
3125
  }
3126
+ generateVastUrlsWithCorrelators(baseUrl, count) {
3127
+ const urls = [];
3128
+ for (let i = 0; i < count; i++) {
3129
+ try {
3130
+ const url = new URL(baseUrl);
3131
+ const timestamp = Date.now();
3132
+ const random = Math.floor(Math.random() * 1e6);
3133
+ const uniqueCorrelator = `${timestamp}${random}${i}`;
3134
+ url.searchParams.set("correlator", uniqueCorrelator);
3135
+ urls.push(url.toString());
3136
+ } catch (error) {
3137
+ console.warn(
3138
+ "[StormcloudVideoPlayer] Failed to parse VAST URL:",
3139
+ baseUrl,
3140
+ error
3141
+ );
3142
+ urls.push(`${baseUrl}${baseUrl.includes("?") ? "&" : "?"}correlator=${Date.now()}${i}`);
3143
+ }
3144
+ }
3145
+ return urls;
3146
+ }
3113
3147
  isAdPlaying() {
3114
3148
  return this.inAdBreak && this.ima.isAdPlaying();
3115
3149
  }
@@ -3148,7 +3182,52 @@ var StormcloudVideoPlayer = class {
3148
3182
  const tags = this.selectVastTagsForBreak(scheduled);
3149
3183
  let vastTagUrls = [];
3150
3184
  if (this.apiVastTagUrl) {
3151
- vastTagUrls = [this.apiVastTagUrl];
3185
+ let numberOfAds = 1;
3186
+ if (this.isLiveStream) {
3187
+ const adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled == null ? void 0 : scheduled.durationMs;
3188
+ if (adBreakDurationMs != null && adBreakDurationMs > 0) {
3189
+ this.isAdaptiveMode = true;
3190
+ this.targetAdBreakDurationMs = adBreakDurationMs;
3191
+ this.fetchedAdDurations.clear();
3192
+ numberOfAds = 2;
3193
+ if (this.config.debugAdTiming) {
3194
+ console.log(
3195
+ `[ADAPTIVE-POD] \u{1F4FA} LIVE MODE (ADAPTIVE): Target duration=${adBreakDurationMs}ms | Starting with ${numberOfAds} ads, will fetch actual durations and add more dynamically`
3196
+ );
3197
+ }
3198
+ } else {
3199
+ if (this.config.debugAdTiming) {
3200
+ console.warn(
3201
+ "[DEBUG-POD] \u26A0\uFE0F LIVE MODE: No duration available, defaulting to 1 ad"
3202
+ );
3203
+ }
3204
+ }
3205
+ } else {
3206
+ this.isAdaptiveMode = false;
3207
+ this.targetAdBreakDurationMs = null;
3208
+ this.fetchedAdDurations.clear();
3209
+ if (this.apiNumberAds && this.apiNumberAds > 1) {
3210
+ numberOfAds = this.apiNumberAds;
3211
+ if (this.config.debugAdTiming) {
3212
+ console.log(
3213
+ `[DEBUG-POD] \u{1F3AC} VOD MODE (FIXED): Using number_ads=${numberOfAds} from API`
3214
+ );
3215
+ }
3216
+ }
3217
+ }
3218
+ if (numberOfAds > 1) {
3219
+ vastTagUrls = this.generateVastUrlsWithCorrelators(
3220
+ this.apiVastTagUrl,
3221
+ numberOfAds
3222
+ );
3223
+ if (this.config.debugAdTiming) {
3224
+ console.log(
3225
+ `[DEBUG-POD] \u{1F504} Generated ${vastTagUrls.length} initial VAST URLs with unique correlators`
3226
+ );
3227
+ }
3228
+ } else {
3229
+ vastTagUrls = [this.apiVastTagUrl];
3230
+ }
3152
3231
  } else if (tags && tags.length > 0) {
3153
3232
  vastTagUrls = tags;
3154
3233
  } else {
@@ -3198,7 +3277,8 @@ var StormcloudVideoPlayer = class {
3198
3277
  console.log("[DEBUG-POD] \u26A0\uFE0F No ads in pod");
3199
3278
  return;
3200
3279
  }
3201
- await new Promise((resolve) => setTimeout(resolve, 500));
3280
+ const waitTime = this.isAdaptiveMode ? 1500 : 500;
3281
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
3202
3282
  const firstPreloaded = this.findNextPreloadedAd();
3203
3283
  if (!firstPreloaded) {
3204
3284
  console.log("[DEBUG-POD] \u26A0\uFE0F No preloaded ads after wait, trying first ad");
@@ -3567,6 +3647,89 @@ var StormcloudVideoPlayer = class {
3567
3647
  }
3568
3648
  return mediaUrls;
3569
3649
  }
3650
+ async fetchVastDuration(vastTagUrl) {
3651
+ var _a;
3652
+ try {
3653
+ const response = await fetch(vastTagUrl, { mode: "cors" });
3654
+ if (!response.ok) {
3655
+ if (this.config.debugAdTiming) {
3656
+ console.warn(
3657
+ `[ADAPTIVE-POD] Failed to fetch VAST: ${response.status}`
3658
+ );
3659
+ }
3660
+ return null;
3661
+ }
3662
+ const xmlText = await response.text();
3663
+ const parser = new DOMParser();
3664
+ const xmlDoc = parser.parseFromString(xmlText, "text/xml");
3665
+ const durationText = (_a = xmlDoc.querySelector("Duration")) == null ? void 0 : _a.textContent;
3666
+ if (!durationText) {
3667
+ if (this.config.debugAdTiming) {
3668
+ console.warn("[ADAPTIVE-POD] No Duration element found in VAST");
3669
+ }
3670
+ return null;
3671
+ }
3672
+ const durationParts = durationText.split(":");
3673
+ const durationSeconds = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + parseInt(durationParts[2] || "0", 10);
3674
+ return durationSeconds;
3675
+ } catch (error) {
3676
+ if (this.config.debugAdTiming) {
3677
+ console.warn(
3678
+ `[ADAPTIVE-POD] Error fetching VAST duration from ${vastTagUrl}:`,
3679
+ error
3680
+ );
3681
+ }
3682
+ return null;
3683
+ }
3684
+ }
3685
+ calculateAdditionalAdsNeeded() {
3686
+ if (!this.isAdaptiveMode || this.targetAdBreakDurationMs === null) {
3687
+ return 0;
3688
+ }
3689
+ let totalFetchedDurationMs = 0;
3690
+ for (const duration of this.fetchedAdDurations.values()) {
3691
+ totalFetchedDurationMs += duration * 1e3;
3692
+ }
3693
+ const remainingTimeMs = this.targetAdBreakDurationMs - totalFetchedDurationMs;
3694
+ if (remainingTimeMs <= 0) {
3695
+ if (this.config.debugAdTiming) {
3696
+ console.log(
3697
+ `[ADAPTIVE-POD] \u2705 Target duration reached: ${totalFetchedDurationMs}ms / ${this.targetAdBreakDurationMs}ms`
3698
+ );
3699
+ }
3700
+ return 0;
3701
+ }
3702
+ const fetchedCount = this.fetchedAdDurations.size;
3703
+ const averageDurationMs = fetchedCount > 0 ? totalFetchedDurationMs / fetchedCount : 30 * 1e3;
3704
+ const additionalAds = Math.ceil(remainingTimeMs / averageDurationMs);
3705
+ if (this.config.debugAdTiming) {
3706
+ console.log(
3707
+ `[ADAPTIVE-POD] \u{1F4CA} Need ${additionalAds} more ads | Fetched: ${totalFetchedDurationMs}ms / Target: ${this.targetAdBreakDurationMs}ms | Remaining: ${remainingTimeMs}ms | Avg duration: ${averageDurationMs}ms`
3708
+ );
3709
+ }
3710
+ return additionalAds;
3711
+ }
3712
+ async addAdaptiveAdsToQueue() {
3713
+ if (!this.isAdaptiveMode || !this.apiVastTagUrl) {
3714
+ return;
3715
+ }
3716
+ const additionalAds = this.calculateAdditionalAdsNeeded();
3717
+ if (additionalAds <= 0) {
3718
+ return;
3719
+ }
3720
+ const newUrls = this.generateVastUrlsWithCorrelators(
3721
+ this.apiVastTagUrl,
3722
+ additionalAds
3723
+ );
3724
+ if (this.config.debugAdTiming) {
3725
+ console.log(
3726
+ `[ADAPTIVE-POD] \u{1F504} Adding ${newUrls.length} additional VAST URLs to queue (will be preloaded sequentially)`
3727
+ );
3728
+ }
3729
+ this.adPodAllUrls.push(...newUrls);
3730
+ this.adPodQueue.push(...newUrls);
3731
+ this.totalAdsInBreak += newUrls.length;
3732
+ }
3570
3733
  async preloadMediaFile(mediaUrl) {
3571
3734
  if (this.preloadedMediaUrls.has(mediaUrl)) {
3572
3735
  return;
@@ -3611,31 +3774,82 @@ var StormcloudVideoPlayer = class {
3611
3774
  if (this.adPodAllUrls.length === 0) {
3612
3775
  return;
3613
3776
  }
3614
- if (this.config.debugAdTiming) {
3615
- console.log(
3616
- `[StormcloudVideoPlayer] Starting parallel preload of ${this.adPodAllUrls.length} ads`
3617
- );
3618
- }
3619
- const preloadPromises = this.adPodAllUrls.map(
3620
- (vastTagUrl) => this.preloadSingleAd(vastTagUrl).catch((error) => {
3621
- if (this.config.debugAdTiming) {
3622
- console.warn(
3623
- `[StormcloudVideoPlayer] Preload failed for ${vastTagUrl}:`,
3624
- error
3625
- );
3777
+ if (this.isAdaptiveMode) {
3778
+ if (this.config.debugAdTiming) {
3779
+ console.log(
3780
+ `[ADAPTIVE-POD] Starting sequential preload of ${this.adPodAllUrls.length} initial ads`
3781
+ );
3782
+ }
3783
+ const processedUrls = /* @__PURE__ */ new Set();
3784
+ while (true) {
3785
+ const nextUrl = this.adPodAllUrls.find((url) => !processedUrls.has(url));
3786
+ if (!nextUrl) {
3787
+ break;
3626
3788
  }
3627
- })
3628
- );
3629
- await Promise.all(preloadPromises);
3630
- if (this.config.debugAdTiming) {
3631
- console.log(
3632
- `[StormcloudVideoPlayer] Background preloading completed for all ads`
3789
+ processedUrls.add(nextUrl);
3790
+ try {
3791
+ await this.preloadSingleAd(nextUrl);
3792
+ } catch (error) {
3793
+ if (this.config.debugAdTiming) {
3794
+ console.warn(
3795
+ `[ADAPTIVE-POD] Preload failed for ${nextUrl}:`,
3796
+ error
3797
+ );
3798
+ }
3799
+ }
3800
+ if (this.calculateAdditionalAdsNeeded() === 0) {
3801
+ if (this.config.debugAdTiming) {
3802
+ console.log(
3803
+ `[ADAPTIVE-POD] \u2705 Target duration reached, stopping preload`
3804
+ );
3805
+ }
3806
+ break;
3807
+ }
3808
+ }
3809
+ if (this.config.debugAdTiming) {
3810
+ console.log(
3811
+ `[ADAPTIVE-POD] Sequential preloading completed (${processedUrls.size} ads preloaded)`
3812
+ );
3813
+ }
3814
+ } else {
3815
+ if (this.config.debugAdTiming) {
3816
+ console.log(
3817
+ `[StormcloudVideoPlayer] Starting parallel preload of ${this.adPodAllUrls.length} ads`
3818
+ );
3819
+ }
3820
+ const preloadPromises = this.adPodAllUrls.map(
3821
+ (vastTagUrl) => this.preloadSingleAd(vastTagUrl).catch((error) => {
3822
+ if (this.config.debugAdTiming) {
3823
+ console.warn(
3824
+ `[StormcloudVideoPlayer] Preload failed for ${vastTagUrl}:`,
3825
+ error
3826
+ );
3827
+ }
3828
+ })
3633
3829
  );
3830
+ await Promise.all(preloadPromises);
3831
+ if (this.config.debugAdTiming) {
3832
+ console.log(
3833
+ `[StormcloudVideoPlayer] Background preloading completed for all ads`
3834
+ );
3835
+ }
3634
3836
  }
3635
3837
  }
3636
3838
  async preloadSingleAd(vastTagUrl) {
3637
3839
  if (!vastTagUrl) return;
3638
3840
  try {
3841
+ if (this.isAdaptiveMode && !this.fetchedAdDurations.has(vastTagUrl)) {
3842
+ const duration = await this.fetchVastDuration(vastTagUrl);
3843
+ if (duration !== null) {
3844
+ this.fetchedAdDurations.set(vastTagUrl, duration);
3845
+ if (this.config.debugAdTiming) {
3846
+ console.log(
3847
+ `[ADAPTIVE-POD] \u2713 Fetched ad duration: ${duration}s (${this.fetchedAdDurations.size} ads fetched so far)`
3848
+ );
3849
+ }
3850
+ await this.addAdaptiveAdsToQueue();
3851
+ }
3852
+ }
3639
3853
  if (this.ima.preloadAds && !this.ima.hasPreloadedAd(vastTagUrl)) {
3640
3854
  if (!this.preloadingAdUrls.has(vastTagUrl)) {
3641
3855
  if (this.config.debugAdTiming) {