stormcloud-video-player 0.8.18 → 0.8.20

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.
Files changed (48) hide show
  1. package/README.md +67 -83
  2. package/dist/stormcloud-vp.min.js +1 -1
  3. package/lib/index.cjs +686 -353
  4. package/lib/index.cjs.map +1 -1
  5. package/lib/index.d.cts +1 -1
  6. package/lib/index.d.ts +1 -1
  7. package/lib/index.js +686 -353
  8. package/lib/index.js.map +1 -1
  9. package/lib/player/AdBreakOrchestrator.cjs +11 -11
  10. package/lib/player/AdBreakOrchestrator.cjs.map +1 -1
  11. package/lib/player/AdBreakOrchestrator.d.cts +4 -4
  12. package/lib/player/{VmapManager.cjs → AdConfigManager.cjs} +561 -217
  13. package/lib/player/AdConfigManager.cjs.map +1 -0
  14. package/lib/player/{VmapManager.d.cts → AdConfigManager.d.cts} +3 -3
  15. package/lib/player/AdPreloadPool.d.cts +1 -1
  16. package/lib/player/AdTimingService.d.cts +1 -1
  17. package/lib/player/HlsEngine.d.cts +1 -1
  18. package/lib/player/PlayerControls.d.cts +1 -1
  19. package/lib/player/Scte35CueManager.d.cts +1 -1
  20. package/lib/player/Scte35Parser.d.cts +1 -1
  21. package/lib/player/StormcloudVideoPlayer.cjs +686 -353
  22. package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
  23. package/lib/player/StormcloudVideoPlayer.d.cts +2 -2
  24. package/lib/player/playerTypes.d.cts +1 -1
  25. package/lib/players/HlsPlayer.cjs +686 -353
  26. package/lib/players/HlsPlayer.cjs.map +1 -1
  27. package/lib/players/HlsPlayer.d.cts +1 -1
  28. package/lib/players/index.cjs +686 -353
  29. package/lib/players/index.cjs.map +1 -1
  30. package/lib/sdk/hlsAdPlayer.cjs +5 -4
  31. package/lib/sdk/hlsAdPlayer.cjs.map +1 -1
  32. package/lib/sdk/hlsAdPlayer.d.cts +1 -1
  33. package/lib/types-BAP8n5mE.d.cts +126 -0
  34. package/lib/ui/StormcloudVideoPlayer.cjs +686 -353
  35. package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
  36. package/lib/ui/StormcloudVideoPlayer.d.cts +1 -1
  37. package/lib/utils/ctvVastSignals.cjs +103 -33
  38. package/lib/utils/ctvVastSignals.cjs.map +1 -1
  39. package/lib/utils/ctvVastSignals.d.cts +1 -13
  40. package/lib/utils/tracking.d.cts +1 -1
  41. package/lib/utils/vastEnvironmentSignals.cjs +450 -0
  42. package/lib/utils/vastEnvironmentSignals.cjs.map +1 -0
  43. package/lib/utils/vastEnvironmentSignals.d.cts +16 -0
  44. package/lib/utils/vastMacros.cjs +347 -25
  45. package/lib/utils/vastMacros.cjs.map +1 -1
  46. package/lib/utils/vastMacros.d.cts +3 -1
  47. package/package.json +1 -1
  48. package/lib/player/VmapManager.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/ubuntu24-new/Dev/stormcloud-vp/lib/player/AdBreakOrchestrator.cjs","../../src/player/AdBreakOrchestrator.ts","../../src/utils/mqttConfig.ts","../../src/utils/mqttClient.ts","../../src/utils/tracking.ts","../../src/player/PlayerControls.ts"],"names":["desc","__create","Object","create","__defProp","defineProperty","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__getProtoOf","getPrototypeOf","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","to","from","except","key","call","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","AdBreakOrchestrator","DEFAULT_MQTT_CONFIG","username","password","mqttConfig","import_mqtt","LOG","AdBreakOrchestrator_exports","enabled","brokerAddress","brokerPort","wsPort","topicPrefix","qos","isMQTTEnabled","brokerUrl","buildPlayerTopic","licenseKey","channel","require","client","status","initMQTTClient","url","buildMQTTBrokerUrl","clientId","random","toString","reconnectPeriod","connectTimeout","Math","slice","mqtt","connect","keepalive","clean","queueQoSZero","console","warn","err","on","info","message","ensureMQTTClient","publishMQTT","topic","payload","cachedBrowserId","screen","window","navigator","ua","userAgent","platform","vendor","memory","deviceMemory","hardwareConcurrency","screenInfo","width","height","availWidth","availHeight","orientation","type","pixelDepth","deviceType","brand","os","model","isSmartTV","isAndroid","isWebView","isWebApp","includes","webosMatch","match","tizenMatch","tvMatch","trim","test","maxTouchPoints","androidModelMatch","outerHeight","outerWidth","matchMedia","matches","standalone","angle","substring","domain","location","hostname","origin","path","pathname","language","languages","join","cookieEnabled","doNotTrack","referrer","document","visibilityState","getBrowserID","clientInfo","crypto","fingerprintString","encodedData","utf8","buffer","i","hashBuffer","hashHex","hash","char","fallbackHash","timestamp","JSON","stringify","subtle","digest","Uint8Array","TextEncoder","encode","unescape","encodeURIComponent","length","buildPlayerMetricEvent","context","flags","input_stream_type","publishTracking","ad_played_count","sendHeartbeat","metricEvent","charCodeAt","Array","map","b","padStart","abs","Date","now","padEnd","canPublish","Boolean","playerId","captureAt","getClientInfo","toISOString","player_id","device_type","toLowerCase","ad_loaded","adLoaded","ad_detect","adDetect","capture_at","inputStreamType","body","sendAdLoadedTracking","adLoadedInfo","error","sendAdImpressionTracking","adImpressionInfo","events","ad_url","adUrl","heartbeatData","getAdAudioVolume","adPlayer","getOriginalMutedState","getOriginalVolume","host","timing","preloadPool","vmap","cueManager","placeholder","inAdBreak","showAds","isShowingPlaceholder","adDetectSentForCurrentBreak","continuousFetchingActive","adRequestQueue","adPodQueue","maxPlaceholderDurationMs","debug","config","debugAdTiming","attachImaEventListeners","getAdPlayer","source","adIndex","currentAdIndex","catch","recordPlayedAdDuration","remaining","getRemainingAdMs","consecutiveFailures","log","queuedUrls","hasTimeToStartAnotherAd","tryNextAvailableAdWithRateLimit","handleAdPodComplete","errorPayload","errorMessage","errorCode","code","continuousFetchLoopRunning","vastErrorCode","cause","innerError","causeMessage","String","handleAdFailure","clearAdFailsafeTimer","clearAdRequestWatchdog","activeAdRequestToken","resetGamNoFillCounter","expectedAdBreakDurationMs","getAdBreakEndWallClockMs","scheduleAdStopAtBreakBoundary","setAdVolume","hidePlaceholder","video","muted","newAdPlayer","createAdPlayer","continueLiveStreamDuringAds","recreateAdController","shouldShowPlaceholder","show","preservedMutedState","preservedVolumeState","destroy","shouldContinueLiveStreamDuringAds","setAdPlayer","initialize","updateOriginalMutedState","showPlaceholder","clearPendingAdBreak","prefetchTimerId","clearTimeout","pendingAdBreak","podAssignedByPrefetch","handleAdStart","scheduled","tags","baseVastUrl","adBreakDurationMs","mode","currentMuted","currentVolume","firstAdUrl","usePreloadedAd","preloadedController","preloaded","firstAdUrlArray","preservedMuted","preservedVolume","adVolume","fallbackPreloaded","ap","fallbackError","findCurrentOrNextBreak","currentTime","consumedVmapBreakIds","add","getAdBreakKey","selectVastTagsForBreak","apiVastTagUrl","_marker","durationSeconds","durationMs","isLiveStream","failedVastUrls","clear","temporaryFailureUrls","isLoopRunning","totalAdRequestsInBreak","beginNewAdPod","volume","adBreakPlayedDurationMs","totalAdsInBreak","vastUrl","adController","vastUrls","shift","generateVastUrls","ensureLoadedAdFitsBudget","rejectLoadedAdForDuration","startContinuousFetching","resume","active","preloadPoolLoop","play","markAdStarted","enforceGlobalRateLimit","lastAdRequestTime","requestAds","startPreloadPool","getPreloadedAd","swapToPreloadedAdPlayer","isTemporaryAdError","set"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iGA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AInD,YAAYjH,KAAKC,GAAA;2DACtD,IAAI,IAAA,CAAK6C,KAAA,EAAO;yCACdvJ,QAAQoK,GAAA,CAAI","sourcesContent":["\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator_exports = {};\n__export(AdBreakOrchestrator_exports, {\n AdBreakOrchestrator: () => AdBreakOrchestrator\n});\nmodule.exports = __toCommonJS(AdBreakOrchestrator_exports);\n\n// src/utils/mqttConfig.ts\nvar DEFAULT_MQTT_CONFIG = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1\n};\nvar mqttConfig = { ...DEFAULT_MQTT_CONFIG };\nfunction isMQTTEnabled() {\n return mqttConfig.enabled;\n}\nfunction buildMQTTBrokerUrl() {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\nfunction buildPlayerTopic(licenseKey, channel) {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n\n// src/utils/mqttClient.ts\nvar import_mqtt = __toESM(require(\"mqtt\"), 1);\nvar LOG = \"[StormcloudVideoPlayer][MQTT]\";\nvar client = null;\nvar status = \"disconnected\";\nfunction initMQTTClient() {\n if (client || !isMQTTEnabled()) return;\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n try {\n client = import_mqtt.default.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5e3,\n connectTimeout: 1e4,\n queueQoSZero: false\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting\\u2026`);\n });\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\nfunction ensureMQTTClient() {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\nfunction publishMQTT(topic, payload) {\n if (!isMQTTEnabled()) {\n return false;\n }\n ensureMQTTClient();\n if (!client) {\n return false;\n }\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\n// src/utils/tracking.ts\nvar cachedBrowserId = null;\nfunction getClientInfo() {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = navigator.deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: screen?.orientation?.type || \"\",\n pixelDepth: screen?.pixelDepth\n };\n let deviceType = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim() : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"NetCast\") || ua.includes(\"LG\"))) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n if (ua.includes(\"Android\") && (maxTouchPoints === 0 || ua.includes(\"Google TV\") || ua.includes(\"XiaoMi\"))) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n isWebApp = window.matchMedia(\"(display-mode: standalone)\").matches || window.navigator.standalone === true || window.screen?.orientation?.angle !== void 0;\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState\n };\n}\nasync function getBrowserID(clientInfo) {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n const fingerprintString = JSON.stringify(clientInfo);\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n let encodedData;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashHex = Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\nfunction canPublish(licenseKey) {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\nasync function buildPlayerMetricEvent(context = {}, flags = {}) {\n const clientInfo = getClientInfo();\n const playerId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? (/* @__PURE__ */ new Date()).toISOString();\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...context.inputStreamType ? { input_stream_type: context.inputStreamType } : {}\n };\n}\nfunction publishTracking(licenseKey, channel, body) {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\nasync function sendAdLoadedTracking(licenseKey, adLoadedInfo, context = {}) {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\nasync function sendAdImpressionTracking(licenseKey, adImpressionInfo, context = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp\n });\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp\n }\n ]\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\nasync function sendHeartbeat(licenseKey, context = {}, flags = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n\n// src/player/PlayerControls.ts\nfunction getAdAudioVolume(adPlayer) {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator = class {\n constructor(host, timing, preloadPool, vmap, cueManager, placeholder) {\n this.inAdBreak = false;\n this.showAds = false;\n this.isShowingPlaceholder = false;\n this.adDetectSentForCurrentBreak = false;\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.adRequestQueue = [];\n this.adPodQueue = [];\n this.maxPlaceholderDurationMs = 5e3;\n this.pendingAdBreak = null;\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.vmap = vmap;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n get debug() {\n return !!this.host.config.debugAdTiming;\n }\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n attachImaEventListeners() {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n this.timing.consecutiveFailures = 0;\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload) => {\n let errorMessage = \"Ad playback failed\";\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : cause.message || String(cause);\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n if (!this.inAdBreak) {\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n recreateAdController() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n clearPendingAdBreak() {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = void 0;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = void 0;\n this.vmap.podAssignedByPrefetch = false;\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n async handleAdStart(_marker) {\n const scheduled = this.vmap.findCurrentOrNextBreak(\n this.host.video.currentTime * 1e3\n );\n if (scheduled) {\n this.vmap.consumedVmapBreakIds.add(this.vmap.getAdBreakKey(scheduled));\n }\n const tags = this.vmap.selectVastTagsForBreak(scheduled);\n let baseVastUrl;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.vmap.apiVastTagUrl) {\n baseVastUrl = this.vmap.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n const adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled?.durationMs;\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n if (this.vmap.podAssignedByPrefetch) {\n this.vmap.podAssignedByPrefetch = false;\n } else {\n this.vmap.beginNewAdPod();\n }\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n let firstAdUrl;\n let usePreloadedAd = false;\n let preloadedController;\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n this.attachImaEventListeners();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n preloadedController.resume();\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n await preloadedController.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n await adPlayer.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n swapToPreloadedAdPlayer(preloadedController) {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n startContinuousFetching(baseVastUrl) {\n if (!this.continuousFetchingActive) {\n return;\n }\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n async continuousFetchLoop(baseVastUrl) {\n const epoch = this.timing.adBreakEpoch;\n while (this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise((resolve) => setTimeout(resolve, 1e3));\n continue;\n }\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n continue;\n }\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n this.adRequestQueue.push(newAdUrl);\n const generationDelay = this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, this.timing.consecutiveFailures), 5e3) : 500;\n await new Promise((resolve) => setTimeout(resolve, generationDelay));\n }\n this.continuousFetchLoopRunning = false;\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n stopContinuousFetching() {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.placeholder.hide();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n async tryNextAvailableAdWithRateLimit() {\n if (!this.inAdBreak) {\n return;\n }\n const epoch = this.timing.adBreakEpoch;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n return this.tryNextAvailableAd(0);\n }\n async tryNextAvailableAd(retryCount = 0) {\n if (!this.inAdBreak) {\n return;\n }\n const remaining = this.timing.getRemainingAdMs();\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n this.timing.cleanupTemporaryFailures();\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(preloaded.adController);\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n if (!this.isShowingPlaceholder && remaining > 1e3) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n async playSingleAd(vastTagUrl) {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n this.recreateAdController();\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.timing.clearAdRequestWatchdog();\n if (this.timing.activeAdRequestToken !== requestToken) return;\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(playError)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = error?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n async showPlaceholderAndWaitForAds() {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n if (waitTime < 1e3) {\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n if (!this.inAdBreak) return;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n handleAdPodComplete() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n this.timing.resetForBreakEnd();\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n this.adRequestQueue = [];\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = void 0;\n this.cueManager.scheduledScte35BreakKey = void 0;\n this.adPodQueue = [];\n this.showAds = false;\n this.host.getAdPlayer().stop().catch(() => {\n });\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {\n });\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {\n });\n }\n }\n handleAdFailure() {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AdBreakOrchestrator\n});\n","import type {\n StormcloudVideoPlayerConfig,\n Scte35Marker,\n AdController,\n} from \"../types\";\nimport {\n sendAdLoadedTracking,\n sendAdImpressionTracking,\n} from \"../utils/tracking\";\nimport type { AdTimingService } from \"./AdTimingService\";\nimport type { AdPreloadPool } from \"./AdPreloadPool\";\nimport type { VmapManager } from \"./VmapManager\";\nimport type { Scte35CueManager } from \"./Scte35CueManager\";\nimport type { PlaceholderLayer } from \"./PlaceholderLayer\";\nimport { getAdAudioVolume } from \"./PlayerControls\";\n\nexport interface AdBreakOrchestratorHost {\n readonly config: StormcloudVideoPlayerConfig;\n readonly video: HTMLVideoElement;\n getAdPlayer(): AdController;\n setAdPlayer(player: AdController): void;\n createAdPlayer(continueLiveStreamDuringAds: boolean): AdController;\n shouldContinueLiveStreamDuringAds(): boolean;\n generateVastUrls(baseUrl: string, count: number): string[];\n}\n\nexport class AdBreakOrchestrator {\n inAdBreak = false;\n showAds: boolean = false;\n isShowingPlaceholder: boolean = false;\n adDetectSentForCurrentBreak: boolean = false;\n\n private continuousFetchingActive: boolean = false;\n private continuousFetchLoopRunning = false;\n adRequestQueue: string[] = [];\n adPodQueue: string[] = [];\n private readonly maxPlaceholderDurationMs: number = 5000;\n\n pendingAdBreak: {\n marker: Scte35Marker;\n detectedAtFragmentSn?: number;\n vastUrls: string[];\n isFetching: boolean;\n fetchStartTime?: number;\n } | null = null;\n prefetchTimerId: number | undefined;\n\n private readonly host: AdBreakOrchestratorHost;\n private readonly timing: AdTimingService;\n private readonly preloadPool: AdPreloadPool;\n private readonly vmap: VmapManager;\n private readonly cueManager: Scte35CueManager;\n private readonly placeholder: PlaceholderLayer;\n\n constructor(\n host: AdBreakOrchestratorHost,\n timing: AdTimingService,\n preloadPool: AdPreloadPool,\n vmap: VmapManager,\n cueManager: Scte35CueManager,\n placeholder: PlaceholderLayer\n ) {\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.vmap = vmap;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n\n private get debug(): boolean {\n return !!this.host.config.debugAdTiming;\n }\n\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n\n attachImaEventListeners(): void {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n this.timing.consecutiveFailures = 0;\n\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload?: any) => {\n let errorMessage = \"Ad playback failed\";\n\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : (cause.message || String(cause));\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n\n if (!this.inAdBreak) {\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n\n recreateAdController(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n\n clearPendingAdBreak(): void {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = undefined;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = undefined;\n this.vmap.podAssignedByPrefetch = false;\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n\n async handleAdStart(_marker: Scte35Marker): Promise<void> {\n const scheduled = this.vmap.findCurrentOrNextBreak(\n this.host.video.currentTime * 1000\n );\n if (scheduled) {\n this.vmap.consumedVmapBreakIds.add(this.vmap.getAdBreakKey(scheduled));\n }\n const tags = this.vmap.selectVastTagsForBreak(scheduled);\n\n let baseVastUrl: string;\n\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.vmap.apiVastTagUrl) {\n baseVastUrl = this.vmap.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n\n const adBreakDurationMs =\n _marker.durationSeconds != null\n ? _marker.durationSeconds * 1000\n : scheduled?.durationMs;\n\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n\n if (this.vmap.podAssignedByPrefetch) {\n this.vmap.podAssignedByPrefetch = false;\n } else {\n this.vmap.beginNewAdPod();\n }\n\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n\n if (\n this.timing.expectedAdBreakDurationMs == null &&\n adBreakDurationMs != null\n ) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n\n let firstAdUrl: string | undefined;\n let usePreloadedAd = false;\n let preloadedController: AdController | undefined;\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n\n this.attachImaEventListeners();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n\n preloadedController.resume();\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n await preloadedController.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n\n await adPlayer.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n\n private swapToPreloadedAdPlayer(preloadedController: AdController): void {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n\n private startContinuousFetching(baseVastUrl: string): void {\n if (!this.continuousFetchingActive) {\n return;\n }\n\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n\n private async continuousFetchLoop(baseVastUrl: string): Promise<void> {\n const epoch = this.timing.adBreakEpoch;\n while (\n this.continuousFetchingActive &&\n this.inAdBreak &&\n epoch === this.timing.adBreakEpoch\n ) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n continue;\n }\n\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise(resolve => setTimeout(resolve, 500));\n continue;\n }\n\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n\n this.adRequestQueue.push(newAdUrl);\n\n const generationDelay = this.timing.consecutiveFailures > 0\n ? Math.min(1000 * Math.pow(2, this.timing.consecutiveFailures), 5000)\n : 500;\n await new Promise(resolve => setTimeout(resolve, generationDelay));\n }\n\n this.continuousFetchLoopRunning = false;\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n\n stopContinuousFetching(): void {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n\n this.placeholder.hide();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n\n async tryNextAvailableAdWithRateLimit(): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const epoch = this.timing.adBreakEpoch;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n\n return this.tryNextAvailableAd(0);\n }\n\n private async tryNextAvailableAd(retryCount: number = 0): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const remaining = this.timing.getRemainingAdMs();\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n this.timing.cleanupTemporaryFailures();\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(preloaded.adController);\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n\n if (!nextAdUrl) continue;\n\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2000) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise(resolve => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n\n if (!this.isShowingPlaceholder && remaining > 1000) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n\n async playSingleAd(vastTagUrl: string): Promise<void> {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n\n this.recreateAdController();\n\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.timing.clearAdRequestWatchdog();\n\n if (this.timing.activeAdRequestToken !== requestToken) return;\n\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(playError as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = (error as Error)?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n\n private async showPlaceholderAndWaitForAds(): Promise<void> {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n\n if (waitTime < 1000) {\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n\n for (let i = 0; i < maxChecks; i++) {\n await new Promise(resolve => setTimeout(resolve, checkInterval));\n\n if (!this.inAdBreak) return;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n\n handleAdPodComplete(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n\n this.timing.resetForBreakEnd();\n\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n\n this.adRequestQueue = [];\n\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = undefined;\n this.cueManager.scheduledScte35BreakKey = undefined;\n this.adPodQueue = [];\n this.showAds = false;\n\n this.host.getAdPlayer().stop().catch(() => {});\n\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {});\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {});\n }\n }\n\n handleAdFailure(): void {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n}\n","export const MQTT_CA_CERT_FILE = \"src/certs/emqxsl-ca.crt\";\n\nexport type MQTTConfig = {\n enabled: boolean;\n brokerAddress: string;\n brokerPort: number;\n wsPort: number;\n username: string;\n password: string;\n topicPrefix: string;\n qos: 0 | 1 | 2;\n brokerUrl?: string;\n};\n\nexport const DEFAULT_MQTT_CONFIG: MQTTConfig = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1,\n};\n\nexport const mqttConfig: MQTTConfig = { ...DEFAULT_MQTT_CONFIG };\n\nexport function applyMQTTConfig(overrides: Partial<MQTTConfig>): void {\n Object.assign(mqttConfig, overrides);\n}\n\nexport function isMQTTEnabled(): boolean {\n return mqttConfig.enabled;\n}\n\nexport function buildMQTTBrokerUrl(): string {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\n\nexport function buildPlayerTopic(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\"\n): string {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n","import mqtt from \"mqtt\";\nimport type { MqttClient } from \"mqtt\";\nimport {\n applyMQTTConfig,\n buildMQTTBrokerUrl,\n isMQTTEnabled,\n mqttConfig,\n} from \"./mqttConfig\";\nimport type { MQTTConfig } from \"./mqttConfig\";\n\nconst LOG = \"[StormcloudVideoPlayer][MQTT]\";\n\nexport type MQTTStatus = \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n\nlet client: MqttClient | null = null;\nlet status: MQTTStatus = \"disconnected\";\n\nexport function getMQTTStatus(): MQTTStatus {\n return status;\n}\n\nexport function isMQTTConnected(): boolean {\n return status === \"connected\" && client !== null && client.connected;\n}\n\nexport function isMQTTConfigured(): boolean {\n return isMQTTEnabled();\n}\n\nexport function configureMQTT(overrides: Partial<MQTTConfig>): void {\n applyMQTTConfig(overrides);\n disconnectMQTT();\n}\n\nexport function initMQTTClient(): void {\n if (client || !isMQTTEnabled()) return;\n\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n\n try {\n client = mqtt.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5000,\n connectTimeout: 10_000,\n queueQoSZero: false,\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting…`);\n });\n\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\n\nexport function ensureMQTTClient(): void {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\n\nexport function publishMQTT(\n topic: string,\n payload: Record<string, unknown>\n): boolean {\n if (!isMQTTEnabled()) {\n return false;\n }\n\n ensureMQTTClient();\n\n if (!client) {\n return false;\n }\n\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\nexport function disconnectMQTT(): void {\n if (client) {\n client.end(true);\n client = null;\n status = \"disconnected\";\n }\n}\n","import type {\n ClientInfo,\n AdDetectInfo,\n AdLoadedInfo,\n AdImpressionInfo,\n PlayerAnalyticsContext,\n} from \"../types\";\nimport { buildPlayerTopic, isMQTTEnabled } from \"./mqttConfig\";\nimport { ensureMQTTClient, publishMQTT } from \"./mqttClient\";\n\nlet cachedBrowserId: string | null = null;\n\nexport function getClientInfo(): ClientInfo {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = (navigator as any).deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: (screen?.orientation as any)?.type || \"\",\n pixelDepth: screen?.pixelDepth,\n };\n\n let deviceType: \"tv\" | \"mobile\" | \"tablet\" | \"desktop\" = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch\n ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim()\n : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))\n ) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"NetCast\") || ua.includes(\"LG\"))\n ) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n\n if (\n ua.includes(\"Android\") &&\n (maxTouchPoints === 0 ||\n ua.includes(\"Google TV\") ||\n ua.includes(\"XiaoMi\"))\n ) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n\n isWebApp =\n window.matchMedia(\"(display-mode: standalone)\").matches ||\n (window.navigator as any).standalone === true ||\n window.screen?.orientation?.angle !== undefined;\n\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState,\n };\n}\n\nexport async function getBrowserID(clientInfo: ClientInfo): Promise<string> {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n\n const fingerprintString = JSON.stringify(clientInfo);\n\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n\n let encodedData: BufferSource;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashHex = Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\n\ntype PlayerMetricFlags = {\n adLoaded?: boolean;\n adDetect?: boolean;\n captureAt?: string;\n};\n\nfunction canPublish(licenseKey: string | undefined): licenseKey is string {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\n\nasync function buildPlayerMetricEvent(\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<Record<string, unknown>> {\n const clientInfo = getClientInfo();\n const playerId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? new Date().toISOString();\n\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...(context.inputStreamType\n ? { input_stream_type: context.inputStreamType }\n : {}),\n };\n}\n\nfunction publishTracking(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\",\n body: Record<string, unknown>\n): void {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\n\nexport async function sendInitialTracking(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n adLoaded: false,\n adDetect: false,\n });\n\n publishTracking(licenseKey, \"metrics\", {\n events: [metricEvent],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\n\nexport async function sendAdDetectTracking(\n licenseKey: string | undefined,\n adDetectInfo: AdDetectInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adDetect: true,\n captureAt: adDetectInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdLoadedTracking(\n licenseKey: string | undefined,\n adLoadedInfo: AdLoadedInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdImpressionTracking(\n licenseKey: string | undefined,\n adImpressionInfo: AdImpressionInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp,\n });\n\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp,\n },\n ],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\n\nexport async function sendHeartbeat(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n","import type { AdController } from \"../types\";\n\nexport function getAdAudioVolume(adPlayer: AdController): number {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\nexport function toggleMute(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (adPlayer.isAdPlaying()) {\n const newMutedState = !adPlayer.getOriginalMutedState();\n const restoreVolume = adPlayer.getOriginalVolume() || 1;\n\n adPlayer.updateOriginalMutedState(newMutedState, video.volume);\n adPlayer.setAdVolume(newMutedState ? 0 : restoreVolume);\n\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:\",\n newMutedState\n );\n }\n } else {\n video.muted = !video.muted;\n adPlayer.updateOriginalMutedState(video.muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", video.muted);\n }\n }\n}\n\nexport function toggleFullscreen(\n video: HTMLVideoElement,\n debug: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container\n .requestFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document\n .exitFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n}\n\nexport function isMuted(\n video: HTMLVideoElement,\n adPlayer: AdController\n): boolean {\n if (adPlayer.isAdPlaying()) {\n return adPlayer.getOriginalMutedState();\n }\n return video.muted;\n}\n\nexport function setMuted(\n video: HTMLVideoElement,\n adPlayer: AdController,\n muted: boolean,\n debug: boolean\n): void {\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying && muted === video.muted) {\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] setMuted reflective update during ad ignored\",\n { muted }\n );\n }\n return;\n }\n\n video.muted = muted;\n\n if (adPlaying) {\n adPlayer.updateOriginalMutedState(muted, video.volume);\n adPlayer.setAdVolume(muted ? 0 : 1);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied during ad\", {\n muted,\n });\n }\n return;\n }\n\n adPlayer.updateOriginalMutedState(muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n}\n\nexport function setVolume(\n video: HTMLVideoElement,\n adPlayer: AdController,\n volume: number,\n debug: boolean\n): void {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying) {\n adPlayer.setAdVolume(clampedVolume);\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume,\n });\n }\n } else {\n video.volume = clampedVolume;\n video.muted = clampedVolume === 0;\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n}\n\nexport function getVolume(\n video: HTMLVideoElement,\n adPlayer: AdController\n): number {\n const adPlaying = adPlayer.isAdPlaying();\n if (adPlaying) {\n return adPlayer.getAdVolume();\n }\n return video.volume;\n}\n\nexport function isFullscreen(): boolean {\n return !!document.fullscreenElement;\n}\n\nexport function resizePlayer(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n\n if (adPlayer && adPlayer.isAdPlaying()) {\n const width = video.clientWidth || 640;\n const height = video.clientHeight || 480;\n\n if (debug) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n\n adPlayer.resize(width, height);\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/ubuntu24-new/Dev/stormcloud-vp/lib/player/AdBreakOrchestrator.cjs","../../src/player/AdBreakOrchestrator.ts","../../src/utils/mqttConfig.ts","../../src/utils/mqttClient.ts","../../src/utils/tracking.ts","../../src/player/PlayerControls.ts"],"names":["desc","__create","Object","create","__defProp","defineProperty","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__getProtoOf","getPrototypeOf","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","to","from","except","key","call","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","AdBreakOrchestrator","DEFAULT_MQTT_CONFIG","username","password","mqttConfig","import_mqtt","LOG","AdBreakOrchestrator_exports","enabled","brokerAddress","brokerPort","wsPort","topicPrefix","qos","isMQTTEnabled","brokerUrl","buildPlayerTopic","licenseKey","channel","require","client","status","initMQTTClient","url","buildMQTTBrokerUrl","clientId","random","toString","reconnectPeriod","connectTimeout","Math","slice","mqtt","connect","keepalive","clean","queueQoSZero","console","warn","err","on","info","message","ensureMQTTClient","publishMQTT","topic","payload","cachedBrowserId","screen","window","navigator","ua","userAgent","platform","vendor","memory","deviceMemory","hardwareConcurrency","screenInfo","width","height","availWidth","availHeight","orientation","type","pixelDepth","deviceType","brand","os","model","isSmartTV","isAndroid","isWebView","isWebApp","includes","webosMatch","match","tizenMatch","tvMatch","trim","test","maxTouchPoints","androidModelMatch","outerHeight","outerWidth","matchMedia","matches","standalone","angle","substring","domain","location","hostname","origin","path","pathname","language","languages","join","cookieEnabled","doNotTrack","referrer","document","visibilityState","getBrowserID","clientInfo","crypto","fingerprintString","encodedData","utf8","buffer","i","hashBuffer","hashHex","hash","char","fallbackHash","timestamp","JSON","stringify","subtle","digest","Uint8Array","TextEncoder","encode","unescape","encodeURIComponent","length","buildPlayerMetricEvent","context","flags","input_stream_type","publishTracking","ad_played_count","sendHeartbeat","metricEvent","charCodeAt","Array","map","b","padStart","abs","Date","now","padEnd","canPublish","Boolean","playerId","captureAt","getClientInfo","toISOString","player_id","device_type","toLowerCase","ad_loaded","adLoaded","ad_detect","adDetect","capture_at","inputStreamType","body","sendAdLoadedTracking","adLoadedInfo","error","sendAdImpressionTracking","adImpressionInfo","events","ad_url","adUrl","heartbeatData","getAdAudioVolume","adPlayer","getOriginalMutedState","getOriginalVolume","host","timing","preloadPool","adConfig","cueManager","placeholder","inAdBreak","showAds","isShowingPlaceholder","adDetectSentForCurrentBreak","continuousFetchingActive","adRequestQueue","adPodQueue","maxPlaceholderDurationMs","debug","config","debugAdTiming","attachImaEventListeners","getAdPlayer","source","adIndex","currentAdIndex","catch","recordPlayedAdDuration","remaining","getRemainingAdMs","consecutiveFailures","log","queuedUrls","hasTimeToStartAnotherAd","tryNextAvailableAdWithRateLimit","handleAdPodComplete","errorPayload","errorMessage","errorCode","code","continuousFetchLoopRunning","vastErrorCode","cause","innerError","causeMessage","String","handleAdFailure","clearAdFailsafeTimer","clearAdRequestWatchdog","activeAdRequestToken","resetGamNoFillCounter","expectedAdBreakDurationMs","getAdBreakEndWallClockMs","scheduleAdStopAtBreakBoundary","setAdVolume","hidePlaceholder","video","muted","newAdPlayer","createAdPlayer","continueLiveStreamDuringAds","recreateAdController","shouldShowPlaceholder","show","preservedMutedState","preservedVolumeState","destroy","shouldContinueLiveStreamDuringAds","setAdPlayer","initialize","updateOriginalMutedState","showPlaceholder","clearPendingAdBreak","prefetchTimerId","clearTimeout","pendingAdBreak","podAssignedByPrefetch","handleAdStart","scheduled","tags","baseVastUrl","adBreakDurationMs","mode","currentMuted","currentVolume","firstAdUrl","usePreloadedAd","preloadedController","preloaded","firstAdUrlArray","preservedMuted","preservedVolume","adVolume","fallbackPreloaded","ap","fallbackError","findCurrentOrNextBreak","currentTime","consumedVmapBreakIds","add","getAdBreakKey","selectVastTagsForBreak","apiVastTagUrl","_marker","durationSeconds","durationMs","isLiveStream","failedVastUrls","clear","temporaryFailureUrls","isLoopRunning","totalAdRequestsInBreak","beginNewAdPod","volume","adBreakPlayedDurationMs","totalAdsInBreak","vastUrl","adController","vastUrls","shift","generateVastUrls","ensureLoadedAdFitsBudget","rejectLoadedAdForDuration","startContinuousFetching","resume","active","preloadPoolLoop","play","markAdStarted","enforceGlobalRateLimit","lastAdRequestTime","requestAds","startPreloadPool","getPreloadedAd","swapToPreloadedAdPlayer","isTemporaryAdError","set"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iGAeiEA,UAFxD,EAAA,0BAAA,gBASP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YArBEC,SAAWC,IAAAA,GAAOC,MAAM;QACxBC,YAAYF,OAAOG,cAAc;IACrC,EAAIC,mBAAmBJ,OAAOK,wBAAwB;IACtD,EAAIC,EAAAA,CAAAA,aAAAA,CAAAA,GAAoBN,OAAOO,GAAAA,CAAAA,SAAAA,IAAAA,CAAAA,CAAmB,IAAA;QAC9CC,IAAAA,GAAAA,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,KAAK,IAAA,CAAK1F,IAAA,CAAKkB,WAAA;4CACrB;;;;;8DAAMwE,GAAGiC,IAAA;;;0CAAT,CAAA,CAAA,gBAAA;4CACA,IAAA,CAAK1H,MAAA,CAAO2H,aAAA;8CAEZ,IAAI,IAAA,CAAK3H,IACP,EADO,CAAO8C,CACd,CAAK9C,MAAA,CAAOgD,KAAA,OAAAA,IADE,IAA6B,GAC/BA,KADuC,IAAA,CAAKhD,KAC5C,CAD4C,CAAO+C,EACnD,OAAA,IAAA,CAAA,UADmD,IACnD,CAAA,CADiF,KACjF,CADuF,CACvF,0BAAA,OAAA,IAAA,CAAA,MAAA,CAAA,mBAAA,2BACd,EAAA,GAAA,IAAA;wBAAA,YAAA,qBAAA,IAAA,CAAA,cAAA;oBAAA,IAAA,CAAA;4CAGA0C,GAAGxC,WAAA,CAAYsC;4CAEf,OAAA,IAAA,IAAA,CAAA,MAAA,CAAA,sBAAA,EAAA;;;;4CACOG;4CACP,IAAI,IAAA,CAAK7E,EAAAA,GAAA,CAAA,CAAO;kDACdvJ,MAAAA,EAAQC,IAAA,CAAK,sDAAsDmO;4CACrE;;;;;;;;;gCAKN,IAAI,IAAA,CAAK1F,MAAA,CAAOkI,aAAAA,KAAA,CAAmB9I,QAAiB;oCAClD,IAAA,CAAKY,MAAA,CAAOwG,oBAAA,CAAqB2B,GAAA,CAAInD,YAAYjH,KAAKC,GAAA;2DACtD,IAAI,IAAA,CAAK6C,KAAA,EAAO;yCACdvJ,QAAQoK,GAAA,CAAI","sourcesContent":["\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator_exports = {};\n__export(AdBreakOrchestrator_exports, {\n AdBreakOrchestrator: () => AdBreakOrchestrator\n});\nmodule.exports = __toCommonJS(AdBreakOrchestrator_exports);\n\n// src/utils/mqttConfig.ts\nvar DEFAULT_MQTT_CONFIG = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1\n};\nvar mqttConfig = { ...DEFAULT_MQTT_CONFIG };\nfunction isMQTTEnabled() {\n return mqttConfig.enabled;\n}\nfunction buildMQTTBrokerUrl() {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\nfunction buildPlayerTopic(licenseKey, channel) {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n\n// src/utils/mqttClient.ts\nvar import_mqtt = __toESM(require(\"mqtt\"), 1);\nvar LOG = \"[StormcloudVideoPlayer][MQTT]\";\nvar client = null;\nvar status = \"disconnected\";\nfunction initMQTTClient() {\n if (client || !isMQTTEnabled()) return;\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n try {\n client = import_mqtt.default.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5e3,\n connectTimeout: 1e4,\n queueQoSZero: false\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting\\u2026`);\n });\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\nfunction ensureMQTTClient() {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\nfunction publishMQTT(topic, payload) {\n if (!isMQTTEnabled()) {\n return false;\n }\n ensureMQTTClient();\n if (!client) {\n return false;\n }\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\n// src/utils/tracking.ts\nvar cachedBrowserId = null;\nfunction getClientInfo() {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = navigator.deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: screen?.orientation?.type || \"\",\n pixelDepth: screen?.pixelDepth\n };\n let deviceType = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim() : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"NetCast\") || ua.includes(\"LG\"))) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n if (ua.includes(\"Android\") && (maxTouchPoints === 0 || ua.includes(\"Google TV\") || ua.includes(\"XiaoMi\"))) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n isWebApp = window.matchMedia(\"(display-mode: standalone)\").matches || window.navigator.standalone === true || window.screen?.orientation?.angle !== void 0;\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState\n };\n}\nasync function getBrowserID(clientInfo) {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n const fingerprintString = JSON.stringify(clientInfo);\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n let encodedData;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashHex = Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\nfunction canPublish(licenseKey) {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\nasync function buildPlayerMetricEvent(context = {}, flags = {}) {\n const clientInfo = getClientInfo();\n const playerId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? (/* @__PURE__ */ new Date()).toISOString();\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...context.inputStreamType ? { input_stream_type: context.inputStreamType } : {}\n };\n}\nfunction publishTracking(licenseKey, channel, body) {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\nasync function sendAdLoadedTracking(licenseKey, adLoadedInfo, context = {}) {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\nasync function sendAdImpressionTracking(licenseKey, adImpressionInfo, context = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp\n });\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp\n }\n ]\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\nasync function sendHeartbeat(licenseKey, context = {}, flags = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n\n// src/player/PlayerControls.ts\nfunction getAdAudioVolume(adPlayer) {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator = class {\n constructor(host, timing, preloadPool, adConfig, cueManager, placeholder) {\n this.inAdBreak = false;\n this.showAds = false;\n this.isShowingPlaceholder = false;\n this.adDetectSentForCurrentBreak = false;\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.adRequestQueue = [];\n this.adPodQueue = [];\n this.maxPlaceholderDurationMs = 5e3;\n this.pendingAdBreak = null;\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.adConfig = adConfig;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n get debug() {\n return !!this.host.config.debugAdTiming;\n }\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n attachImaEventListeners() {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n this.timing.consecutiveFailures = 0;\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload) => {\n let errorMessage = \"Ad playback failed\";\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : cause.message || String(cause);\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n if (!this.inAdBreak) {\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n recreateAdController() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n clearPendingAdBreak() {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = void 0;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = void 0;\n this.adConfig.podAssignedByPrefetch = false;\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n async handleAdStart(_marker) {\n const scheduled = this.adConfig.findCurrentOrNextBreak(\n this.host.video.currentTime * 1e3\n );\n if (scheduled) {\n this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));\n }\n const tags = this.adConfig.selectVastTagsForBreak(scheduled);\n let baseVastUrl;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.adConfig.apiVastTagUrl) {\n baseVastUrl = this.adConfig.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n const adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled?.durationMs;\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n if (this.adConfig.podAssignedByPrefetch) {\n this.adConfig.podAssignedByPrefetch = false;\n } else {\n this.adConfig.beginNewAdPod();\n }\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n let firstAdUrl;\n let usePreloadedAd = false;\n let preloadedController;\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n this.attachImaEventListeners();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n preloadedController.resume();\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n await preloadedController.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n await adPlayer.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n swapToPreloadedAdPlayer(preloadedController) {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n startContinuousFetching(baseVastUrl) {\n if (!this.continuousFetchingActive) {\n return;\n }\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n async continuousFetchLoop(baseVastUrl) {\n const epoch = this.timing.adBreakEpoch;\n while (this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise((resolve) => setTimeout(resolve, 1e3));\n continue;\n }\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n continue;\n }\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n this.adRequestQueue.push(newAdUrl);\n const generationDelay = this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, this.timing.consecutiveFailures), 5e3) : 500;\n await new Promise((resolve) => setTimeout(resolve, generationDelay));\n }\n this.continuousFetchLoopRunning = false;\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n stopContinuousFetching() {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.placeholder.hide();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n async tryNextAvailableAdWithRateLimit() {\n if (!this.inAdBreak) {\n return;\n }\n const epoch = this.timing.adBreakEpoch;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n return this.tryNextAvailableAd(0);\n }\n async tryNextAvailableAd(retryCount = 0) {\n if (!this.inAdBreak) {\n return;\n }\n const remaining = this.timing.getRemainingAdMs();\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n this.timing.cleanupTemporaryFailures();\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(preloaded.adController);\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n if (!this.isShowingPlaceholder && remaining > 1e3) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n async playSingleAd(vastTagUrl) {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n this.recreateAdController();\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.timing.clearAdRequestWatchdog();\n if (this.timing.activeAdRequestToken !== requestToken) return;\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(playError)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = error?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n async showPlaceholderAndWaitForAds() {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n if (waitTime < 1e3) {\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n if (!this.inAdBreak) return;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n handleAdPodComplete() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n this.timing.resetForBreakEnd();\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n this.adRequestQueue = [];\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = void 0;\n this.cueManager.scheduledScte35BreakKey = void 0;\n this.adPodQueue = [];\n this.showAds = false;\n this.host.getAdPlayer().stop().catch(() => {\n });\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {\n });\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {\n });\n }\n }\n handleAdFailure() {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AdBreakOrchestrator\n});\n","import type {\n StormcloudVideoPlayerConfig,\n Scte35Marker,\n AdController,\n} from \"../types\";\nimport {\n sendAdLoadedTracking,\n sendAdImpressionTracking,\n} from \"../utils/tracking\";\nimport type { AdTimingService } from \"./AdTimingService\";\nimport type { AdPreloadPool } from \"./AdPreloadPool\";\nimport type { AdConfigManager } from \"./AdConfigManager\";\nimport type { Scte35CueManager } from \"./Scte35CueManager\";\nimport type { PlaceholderLayer } from \"./PlaceholderLayer\";\nimport { getAdAudioVolume } from \"./PlayerControls\";\n\nexport interface AdBreakOrchestratorHost {\n readonly config: StormcloudVideoPlayerConfig;\n readonly video: HTMLVideoElement;\n getAdPlayer(): AdController;\n setAdPlayer(player: AdController): void;\n createAdPlayer(continueLiveStreamDuringAds: boolean): AdController;\n shouldContinueLiveStreamDuringAds(): boolean;\n generateVastUrls(baseUrl: string, count: number): string[];\n}\n\nexport class AdBreakOrchestrator {\n inAdBreak = false;\n showAds: boolean = false;\n isShowingPlaceholder: boolean = false;\n adDetectSentForCurrentBreak: boolean = false;\n\n private continuousFetchingActive: boolean = false;\n private continuousFetchLoopRunning = false;\n adRequestQueue: string[] = [];\n adPodQueue: string[] = [];\n private readonly maxPlaceholderDurationMs: number = 5000;\n\n pendingAdBreak: {\n marker: Scte35Marker;\n detectedAtFragmentSn?: number;\n vastUrls: string[];\n isFetching: boolean;\n fetchStartTime?: number;\n } | null = null;\n prefetchTimerId: number | undefined;\n\n private readonly host: AdBreakOrchestratorHost;\n private readonly timing: AdTimingService;\n private readonly preloadPool: AdPreloadPool;\n private readonly adConfig: AdConfigManager;\n private readonly cueManager: Scte35CueManager;\n private readonly placeholder: PlaceholderLayer;\n\n constructor(\n host: AdBreakOrchestratorHost,\n timing: AdTimingService,\n preloadPool: AdPreloadPool,\n adConfig: AdConfigManager,\n cueManager: Scte35CueManager,\n placeholder: PlaceholderLayer\n ) {\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.adConfig = adConfig;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n\n private get debug(): boolean {\n return !!this.host.config.debugAdTiming;\n }\n\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n\n attachImaEventListeners(): void {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n this.timing.consecutiveFailures = 0;\n\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload?: any) => {\n let errorMessage = \"Ad playback failed\";\n\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : (cause.message || String(cause));\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n\n if (!this.inAdBreak) {\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n\n recreateAdController(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n\n clearPendingAdBreak(): void {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = undefined;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = undefined;\n this.adConfig.podAssignedByPrefetch = false;\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n\n async handleAdStart(_marker: Scte35Marker): Promise<void> {\n const scheduled = this.adConfig.findCurrentOrNextBreak(\n this.host.video.currentTime * 1000\n );\n if (scheduled) {\n this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));\n }\n const tags = this.adConfig.selectVastTagsForBreak(scheduled);\n\n let baseVastUrl: string;\n\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.adConfig.apiVastTagUrl) {\n baseVastUrl = this.adConfig.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n\n const adBreakDurationMs =\n _marker.durationSeconds != null\n ? _marker.durationSeconds * 1000\n : scheduled?.durationMs;\n\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n\n if (this.adConfig.podAssignedByPrefetch) {\n this.adConfig.podAssignedByPrefetch = false;\n } else {\n this.adConfig.beginNewAdPod();\n }\n\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n\n if (\n this.timing.expectedAdBreakDurationMs == null &&\n adBreakDurationMs != null\n ) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n\n let firstAdUrl: string | undefined;\n let usePreloadedAd = false;\n let preloadedController: AdController | undefined;\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n\n this.attachImaEventListeners();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n\n preloadedController.resume();\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n await preloadedController.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n\n await adPlayer.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n\n private swapToPreloadedAdPlayer(preloadedController: AdController): void {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n\n private startContinuousFetching(baseVastUrl: string): void {\n if (!this.continuousFetchingActive) {\n return;\n }\n\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n\n private async continuousFetchLoop(baseVastUrl: string): Promise<void> {\n const epoch = this.timing.adBreakEpoch;\n while (\n this.continuousFetchingActive &&\n this.inAdBreak &&\n epoch === this.timing.adBreakEpoch\n ) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n continue;\n }\n\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise(resolve => setTimeout(resolve, 500));\n continue;\n }\n\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n\n this.adRequestQueue.push(newAdUrl);\n\n const generationDelay = this.timing.consecutiveFailures > 0\n ? Math.min(1000 * Math.pow(2, this.timing.consecutiveFailures), 5000)\n : 500;\n await new Promise(resolve => setTimeout(resolve, generationDelay));\n }\n\n this.continuousFetchLoopRunning = false;\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n\n stopContinuousFetching(): void {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n\n this.placeholder.hide();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n\n async tryNextAvailableAdWithRateLimit(): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const epoch = this.timing.adBreakEpoch;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n\n return this.tryNextAvailableAd(0);\n }\n\n private async tryNextAvailableAd(retryCount: number = 0): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const remaining = this.timing.getRemainingAdMs();\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n this.timing.cleanupTemporaryFailures();\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(preloaded.adController);\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n\n if (!nextAdUrl) continue;\n\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2000) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise(resolve => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n\n if (!this.isShowingPlaceholder && remaining > 1000) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n\n async playSingleAd(vastTagUrl: string): Promise<void> {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n\n this.recreateAdController();\n\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.timing.clearAdRequestWatchdog();\n\n if (this.timing.activeAdRequestToken !== requestToken) return;\n\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(playError as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = (error as Error)?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n\n private async showPlaceholderAndWaitForAds(): Promise<void> {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n\n if (waitTime < 1000) {\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n\n for (let i = 0; i < maxChecks; i++) {\n await new Promise(resolve => setTimeout(resolve, checkInterval));\n\n if (!this.inAdBreak) return;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n\n handleAdPodComplete(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n\n this.timing.resetForBreakEnd();\n\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n\n this.adRequestQueue = [];\n\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = undefined;\n this.cueManager.scheduledScte35BreakKey = undefined;\n this.adPodQueue = [];\n this.showAds = false;\n\n this.host.getAdPlayer().stop().catch(() => {});\n\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {});\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {});\n }\n }\n\n handleAdFailure(): void {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n}\n","export const MQTT_CA_CERT_FILE = \"src/certs/emqxsl-ca.crt\";\n\nexport type MQTTConfig = {\n enabled: boolean;\n brokerAddress: string;\n brokerPort: number;\n wsPort: number;\n username: string;\n password: string;\n topicPrefix: string;\n qos: 0 | 1 | 2;\n brokerUrl?: string;\n};\n\nexport const DEFAULT_MQTT_CONFIG: MQTTConfig = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1,\n};\n\nexport const mqttConfig: MQTTConfig = { ...DEFAULT_MQTT_CONFIG };\n\nexport function applyMQTTConfig(overrides: Partial<MQTTConfig>): void {\n Object.assign(mqttConfig, overrides);\n}\n\nexport function isMQTTEnabled(): boolean {\n return mqttConfig.enabled;\n}\n\nexport function buildMQTTBrokerUrl(): string {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\n\nexport function buildPlayerTopic(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\"\n): string {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n","import mqtt from \"mqtt\";\nimport type { MqttClient } from \"mqtt\";\nimport {\n applyMQTTConfig,\n buildMQTTBrokerUrl,\n isMQTTEnabled,\n mqttConfig,\n} from \"./mqttConfig\";\nimport type { MQTTConfig } from \"./mqttConfig\";\n\nconst LOG = \"[StormcloudVideoPlayer][MQTT]\";\n\nexport type MQTTStatus = \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n\nlet client: MqttClient | null = null;\nlet status: MQTTStatus = \"disconnected\";\n\nexport function getMQTTStatus(): MQTTStatus {\n return status;\n}\n\nexport function isMQTTConnected(): boolean {\n return status === \"connected\" && client !== null && client.connected;\n}\n\nexport function isMQTTConfigured(): boolean {\n return isMQTTEnabled();\n}\n\nexport function configureMQTT(overrides: Partial<MQTTConfig>): void {\n applyMQTTConfig(overrides);\n disconnectMQTT();\n}\n\nexport function initMQTTClient(): void {\n if (client || !isMQTTEnabled()) return;\n\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n\n try {\n client = mqtt.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5000,\n connectTimeout: 10_000,\n queueQoSZero: false,\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting…`);\n });\n\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\n\nexport function ensureMQTTClient(): void {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\n\nexport function publishMQTT(\n topic: string,\n payload: Record<string, unknown>\n): boolean {\n if (!isMQTTEnabled()) {\n return false;\n }\n\n ensureMQTTClient();\n\n if (!client) {\n return false;\n }\n\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\nexport function disconnectMQTT(): void {\n if (client) {\n client.end(true);\n client = null;\n status = \"disconnected\";\n }\n}\n","import type {\n ClientInfo,\n AdDetectInfo,\n AdLoadedInfo,\n AdImpressionInfo,\n PlayerAnalyticsContext,\n} from \"../types\";\nimport { buildPlayerTopic, isMQTTEnabled } from \"./mqttConfig\";\nimport { ensureMQTTClient, publishMQTT } from \"./mqttClient\";\n\nlet cachedBrowserId: string | null = null;\n\nexport function getClientInfo(): ClientInfo {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = (navigator as any).deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: (screen?.orientation as any)?.type || \"\",\n pixelDepth: screen?.pixelDepth,\n };\n\n let deviceType: \"tv\" | \"mobile\" | \"tablet\" | \"desktop\" = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch\n ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim()\n : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))\n ) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"NetCast\") || ua.includes(\"LG\"))\n ) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n\n if (\n ua.includes(\"Android\") &&\n (maxTouchPoints === 0 ||\n ua.includes(\"Google TV\") ||\n ua.includes(\"XiaoMi\"))\n ) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n\n isWebApp =\n window.matchMedia(\"(display-mode: standalone)\").matches ||\n (window.navigator as any).standalone === true ||\n window.screen?.orientation?.angle !== undefined;\n\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState,\n };\n}\n\nexport async function getBrowserID(clientInfo: ClientInfo): Promise<string> {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n\n const fingerprintString = JSON.stringify(clientInfo);\n\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n\n let encodedData: BufferSource;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashHex = Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\n\ntype PlayerMetricFlags = {\n adLoaded?: boolean;\n adDetect?: boolean;\n captureAt?: string;\n};\n\nfunction canPublish(licenseKey: string | undefined): licenseKey is string {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\n\nasync function buildPlayerMetricEvent(\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<Record<string, unknown>> {\n const clientInfo = getClientInfo();\n const playerId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? new Date().toISOString();\n\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...(context.inputStreamType\n ? { input_stream_type: context.inputStreamType }\n : {}),\n };\n}\n\nfunction publishTracking(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\",\n body: Record<string, unknown>\n): void {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\n\nexport async function sendInitialTracking(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n adLoaded: false,\n adDetect: false,\n });\n\n publishTracking(licenseKey, \"metrics\", {\n events: [metricEvent],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\n\nexport async function sendAdDetectTracking(\n licenseKey: string | undefined,\n adDetectInfo: AdDetectInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adDetect: true,\n captureAt: adDetectInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdLoadedTracking(\n licenseKey: string | undefined,\n adLoadedInfo: AdLoadedInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdImpressionTracking(\n licenseKey: string | undefined,\n adImpressionInfo: AdImpressionInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp,\n });\n\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp,\n },\n ],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\n\nexport async function sendHeartbeat(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n","import type { AdController } from \"../types\";\n\nexport function getAdAudioVolume(adPlayer: AdController): number {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\nexport function toggleMute(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (adPlayer.isAdPlaying()) {\n const newMutedState = !adPlayer.getOriginalMutedState();\n const restoreVolume = adPlayer.getOriginalVolume() || 1;\n\n adPlayer.updateOriginalMutedState(newMutedState, video.volume);\n adPlayer.setAdVolume(newMutedState ? 0 : restoreVolume);\n\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:\",\n newMutedState\n );\n }\n } else {\n video.muted = !video.muted;\n adPlayer.updateOriginalMutedState(video.muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", video.muted);\n }\n }\n}\n\nexport function toggleFullscreen(\n video: HTMLVideoElement,\n debug: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container\n .requestFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document\n .exitFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n}\n\nexport function isMuted(\n video: HTMLVideoElement,\n adPlayer: AdController\n): boolean {\n if (adPlayer.isAdPlaying()) {\n return adPlayer.getOriginalMutedState();\n }\n return video.muted;\n}\n\nexport function setMuted(\n video: HTMLVideoElement,\n adPlayer: AdController,\n muted: boolean,\n debug: boolean\n): void {\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying && muted === video.muted) {\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] setMuted reflective update during ad ignored\",\n { muted }\n );\n }\n return;\n }\n\n video.muted = muted;\n\n if (adPlaying) {\n adPlayer.updateOriginalMutedState(muted, video.volume);\n adPlayer.setAdVolume(muted ? 0 : 1);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied during ad\", {\n muted,\n });\n }\n return;\n }\n\n adPlayer.updateOriginalMutedState(muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n}\n\nexport function setVolume(\n video: HTMLVideoElement,\n adPlayer: AdController,\n volume: number,\n debug: boolean\n): void {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying) {\n adPlayer.setAdVolume(clampedVolume);\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume,\n });\n }\n } else {\n video.volume = clampedVolume;\n video.muted = clampedVolume === 0;\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n}\n\nexport function getVolume(\n video: HTMLVideoElement,\n adPlayer: AdController\n): number {\n const adPlaying = adPlayer.isAdPlaying();\n if (adPlaying) {\n return adPlayer.getAdVolume();\n }\n return video.volume;\n}\n\nexport function isFullscreen(): boolean {\n return !!document.fullscreenElement;\n}\n\nexport function resizePlayer(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n\n if (adPlayer && adPlayer.isAdPlaying()) {\n const width = video.clientWidth || 640;\n const height = video.clientHeight || 480;\n\n if (debug) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n\n adPlayer.resize(width, height);\n }\n}\n"]}