@dolby-optiview/ads-sdk-core 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{DEFAULT_MODE as e,DEFAULT_AD_PRELOAD_MODE as t,DEFAULT_AD_BREAK_CONTENT_RECOVERY as s,DEFAULT_AD_INSERTION_MODE as i,DEFAULT_AD_BREAK_CUT_SAFETY_MARGIN_SEC as r,DEFAULT_DOUBLE_BOX_AUDIO as a,resolveChaining as n,resolveTuneIn as o,resolveBreakWarnings as d,resolvePdtGraceSeconds as l}from"./types/OptiViewAdsConfig";import{SsaiController as h}from"./services/SsaiController";import{resolvePreloadMode as c}from"./services/detectPreloadMode";import{resolveContentRecovery as u}from"./services/detectContentRecovery";import{emitResolvedModeDiagnostics as m}from"./services/resolvedModeDiagnostics";import{isSingleSurfaceWebDevice as p,resolveInsertionMode as g}from"./services/detectInsertionMode";import{ManifestService as k}from"./services/ManifestService";import{BreakScheduler as f,systemClock as y}from"./services/BreakScheduler";import{MetadataCueTracker as S}from"./services/MetadataCueTracker";import{armBreakFromPresentedCue as v,cueAnchorForBreak as A,diagnoseAnvatoCueObserved as C,notedManifestBreakIds as b}from"./services/anvatoCueRuntime";import{AdPlayerController as P}from"./services/AdPlayerController";import{effectiveFormat as w}from"./services/pictureInPicture";import{resolveBreakFormat as B}from"./services/AdBreakSequencer";import{connectPauseAd as T}from"./services/adPlayer/connectPauseAd";import{BreakTransitionTimer as I}from"./services/BreakTransitionTimer";import{LensReporter as R}from"./services/LensReporter";import{CmcdAdReporter as D}from"./services/CmcdAdReporter";import{DiagnosticBuffer as E}from"./diagnostics/DiagnosticBuffer";import{recordEventTimeline as O}from"./diagnostics/recordEventTimeline";import{DIAGNOSTIC_CODES as M}from"./diagnostics/errorCodes";import{SDK_VERSION as L}from"./generated/version";import{playbackErrorContext as x}from"./diagnostics/playbackErrorContext";import{debugLog as G}from"./diagnostics/debugLog";import{AdBreakStatusTracker as H}from"./session/AdBreakStatusTracker";import{BreakLifecycle as F}from"./session/BreakLifecycle";import{SessionStarter as V}from"./session/SessionStarter";import{SessionState as $}from"./session/SessionState";import{LiveStartPushbackController as q}from"./services/LiveStartPushbackController";export class OptiViewAds{static get version(){return L}constructor(h){if(this.contentErrorReloadGuard=null,this.CONTENT_ERROR_RELOAD_GUARD_MS=5e3,this.eventHandlers=new Map,this.diagnosticHandlers=new Set,this.destroyed=!1,this.continueContentDuringBreak=!1,this.state=new $,this.metadataCueTracker=null,this.anvatoObservedLogged=new Set,this.seenManifestBreakIds=new Set,this.player=h.player,this.liveStartPushback=new q(this.player,h.liveStartPushback,{blocked:()=>!this.state.sessionActive||this.state.channelSwitchInFlight||!!this.adPlayerController?.isAdPlaying()||!!this.state.heldImmediatePreRollId,setSeeking:e=>this.breakScheduler?.setStartupSeeking(e),diagnose:(e,t,s)=>this.diagnose(e,t,s)},h.ptsSource),this.debug=h.debug??!1,this.mode=h.mode??e,this.hasExplicitMode=void 0!==h.mode,this.lensReporter=new R((...e)=>this.log(...e)),this.cmcdAdReporter=new D(()=>this.lensReporter.handle,(...e)=>this.log(...e)),this.adBreakStatusTracker=new H({emit:(e,t)=>this.emit(e,t),effectiveFormatOf:e=>this.effectiveFormatOf(e),secondsUntilBreak:e=>this.breakScheduler?.getSecondsUntilBreak(e)??void 0,breakTransitionTimer:()=>this.breakTransitionTimer}),this.onContentSeeked=()=>{const e=this.breakScheduler?.getActiveBreak();if(!e?.controls?.snapback)return;if(this.state.snapbackSeekInFlight)return void(this.state.snapbackSeekInFlight=!1);const t="number"==typeof e.start?e.start:this.player.currentTime;Math.abs(this.player.currentTime-t)<=.5||(this.log("Snapback: seek detected during locked break, snapping back to break start"),this.state.snapbackSeekInFlight=!0,this.player.seek(t))},this.onContentWaiting=()=>{this.adPlayerController?.isAdPlaying()||this.emit("waiting",{type:"waiting",timestamp:Date.now(),source:"content"})},this.onContentPlaying=()=>{this.adPlayerController?.isAdPlaying()||(this.breakScheduler?.markPlaybackStart(),this.breakTransitionTimer?.settle("out-of-break"),!1!==this.pauseAdController?.onResume()?this.emit("playing",{type:"playing",timestamp:Date.now(),source:"content"}):this.player.pause())},this.onContentPause=()=>{this.adPlayerController?.isAdPlaying()||this.breakScheduler?.isAdStartDelayActive()||this.pauseAdController?.onPause()},this.onContentEnded=()=>{this.adPlayerController?.isAdPlaying()||this.breakScheduler?.markPlaybackEnd()},this.onContentError=e=>{this.sessionStarter?.cancelHeldImmediatePreRollOnContentError();const t=this.toPlaybackError(e,"Content playback error");this.diagnose("DA-CONTENT-PLAYBACK-ERROR",t.message,x(e)),this.breakScheduler?.setContentReloading(!0),this.contentErrorReloadGuard&&clearTimeout(this.contentErrorReloadGuard),this.contentErrorReloadGuard=setTimeout(()=>{this.contentErrorReloadGuard=null,this.breakScheduler?.setContentReloading(!1)},this.CONTENT_ERROR_RELOAD_GUARD_MS),this.emit("aderror",{type:"aderror",timestamp:Date.now(),source:"content",error:t})},this.onTimedMetadata=e=>{if(!e)return;const t=e,s=this.metadataCueTracker?.handleCue(t)??!1;C(t,s,this.metadataCueTracker,this.anvatoObservedLogged,this.player.currentTime,(e,t,s)=>this.diagnose(e,t,s)),"presented"===t.phase&&v(t,this.metadataCueTracker,this.breakScheduler)},this.continueContentDuringBreak=h.continueContentDuringBreak??!1,"ssai"===this.mode)return void this.initSsai(h);if(!h.createAdAdapter)throw new Error("[OptiViewAds] createAdAdapter is required. Use the @dolby-optiview/ads-sdk package for a default HLS.js ad player, or supply your own createAdAdapter factory.");this.state.steeredSsaiOptions={maxBitrate:h.maxBitrate,autoplay:h.autoplay??!1,streamActivityMonitorId:h.gam?.streamActivityMonitorId};const w=c(h.adPreload??t),B=h.adBreakContentRecovery??s,O=u(B),M=g(h.adInsertion??i),L=n(h.chaining),G=o(h.tuneIn),N=d(h.breakWarnings),K=l(h.pdtGraceSeconds);"anvatoCue"===h.ptsSource&&(this.metadataCueTracker=new S(this.diagnose.bind(this))),this.diagnosticBuffer=new E(h.diagnostics?.bufferSize),this.breakTransitionTimer=new I(e=>{this.diagnose("DA-BREAK-TRANSITION",`Transition ${e.kind} took ${e.durationMs}ms`,{transition:e.kind,durationMs:e.durationMs,breakId:e.breakId,adPreload:w,adInsertion:M,...e.phases?{phases:e.phases}:{}})}),this.state.configSummary={mode:this.mode,adPreload:w,adBreakContentRecovery:O,adInsertion:M,chaining:{enabled:L.enabled,maxGapSeconds:L.maxGapSeconds},tuneIn:{enabled:G.enabled,minBreakDurationSeconds:G.minBreakDurationSeconds},breakWarnings:{seconds:N.seconds},ptsSource:h.ptsSource??"mediaTime",continueContentDuringBreak:this.continueContentDuringBreak,gam:h.gam?{hasAssetParameters:!1,streamActivityMonitorId:h.gam.streamActivityMonitorId}:void 0},m({adPreload:h.adPreload??t,adInsertion:h.adInsertion??i,adBreakContentRecovery:B},{preloadMode:w,insertionMode:M,contentRecovery:O},(e,t,s)=>this.diagnose(e,t,s)),this.manifestService=new k(this.debug,h.interceptManifestResponse,(e,t,s)=>this.diagnose(e,t,s),h.interceptManifestRequest),this.breakScheduler=new f(this.player,this.debug,L,void 0,G,(e,t,s)=>this.diagnose(e,t,s),N,this.metadataCueTracker,K),this.adPlayerController=new P(h.player,h.container,h.playerContainer,h.createAdAdapter,this.debug,h.gam,w,M,h.adBreakCutSafetyMarginSec??r,h.doubleBoxAudio??a,p("undefined"!=typeof navigator?navigator.userAgent:"","undefined"!=typeof navigator?navigator.maxTouchPoints??0:0),y,O),this.adPlayerController.setTransitionPhaseReporter(this.debug?e=>this.breakTransitionTimer?.phase(e):null),this.adPlayerController.setResumeCueAnchorResolver(e=>A(this.metadataCueTracker,e)),this.adPlayerController.setChainResolver(L.enabled?e=>this.breakScheduler.getChainedSuccessor(e):null),this.adPlayerController.initialize();const _=(e,t)=>void 0===e||void 0===t?{}:{adIndex:e,totalAds:t};this.adPlayerController.setGamEventCallbacks({onAdFirstQuartile:(e,t,s,i)=>{this.emit("adfirstquartile",{type:"adfirstquartile",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,..._(s,i)})},onAdMidpoint:(e,t,s,i)=>{this.emit("admidpoint",{type:"admidpoint",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,..._(s,i)})},onAdThirdQuartile:(e,t,s,i)=>{this.emit("adthirdquartile",{type:"adthirdquartile",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,..._(s,i)})}}),this.adPlayerController.setDiagnoseHandler((e,t,s)=>{this.diagnose(e,t,s)}),this.pauseAdController=T(this.adPlayerController,{debug:this.debug,diagnose:(e,t,s)=>this.diagnose(e,t,s)}),this.adPlayerController.setVolumeChangeCallback((e,t)=>{this.emit("volumechange",{type:"volumechange",timestamp:Date.now(),muted:e,volume:t})}),this.breakLifecycle=new F(this.state,{adPlayerController:this.adPlayerController,breakScheduler:this.breakScheduler,manifestService:this.manifestService,breakTransitionTimer:this.breakTransitionTimer,cmcdAdReporter:this.cmcdAdReporter,adBreakStatusTracker:this.adBreakStatusTracker,emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e),effectiveFormatOf:e=>this.effectiveFormatOf(e),onBreakSettled:()=>this.sessionStarter?.applyPendingChannelSwitch()}),this.sessionStarter=new V(this.state,{player:this.player,debug:this.debug,mode:this.mode,hasExplicitMode:this.hasExplicitMode,continueContentDuringBreak:this.continueContentDuringBreak,startLivePushback:()=>this.liveStartPushback.start(),manifestService:this.manifestService,breakScheduler:this.breakScheduler,adPlayerController:this.adPlayerController,pauseAdController:this.pauseAdController,breakLifecycle:this.breakLifecycle,cmcdAdReporter:this.cmcdAdReporter,lensReporter:this.lensReporter,adBreakStatusTracker:this.adBreakStatusTracker,emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e),endSessionInternal:e=>this.endSessionInternal(e),notedManifestBreakIds:e=>b(e,this.seenManifestBreakIds)});for(const[e,t]of this.contentListeners())this.player.on(e,t);this.log("OptiViewAds SDK initialized")}initSsai(e){if(!e.gam)throw new Error('[OptiViewAds] mode "ssai" requires a gam config.');if(!e.ssai?.networkCode)throw new Error('[OptiViewAds] mode "ssai" requires an ssai config (networkCode).');const t=e.ssai;this.diagnosticBuffer=new E(e.diagnostics?.bufferSize);const s=e.autoplay??!1;this.state.configSummary={mode:this.mode,adPreload:"n/a",adInsertion:"ssai",chaining:{enabled:!1,maxGapSeconds:0},tuneIn:{enabled:!1,minBreakDurationSeconds:0},gam:{networkCode:t.networkCode,hasAssetParameters:!1,streamActivityMonitorId:e.gam.streamActivityMonitorId},ssai:{maxBitrate:e.maxBitrate,autoplay:s},continueContentDuringBreak:this.continueContentDuringBreak},this.state.ssaiController=new h(this.player,{gam:e.gam,ssai:t,maxBitrate:e.maxBitrate,autoplay:s,debug:this.debug},{emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e)}),this.player.on("volumechange",()=>{this.emit("volumechange",{type:"volumechange",timestamp:Date.now(),muted:this.player.muted,volume:this.player.volume})}),this.sessionStarter=new V(this.state,{player:this.player,debug:this.debug,mode:this.mode,hasExplicitMode:this.hasExplicitMode,continueContentDuringBreak:this.continueContentDuringBreak,startLivePushback:()=>this.liveStartPushback.start(),manifestService:this.manifestService,breakScheduler:this.breakScheduler,adPlayerController:this.adPlayerController,pauseAdController:this.pauseAdController,breakLifecycle:this.breakLifecycle,cmcdAdReporter:this.cmcdAdReporter,lensReporter:this.lensReporter,adBreakStatusTracker:this.adBreakStatusTracker,emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e),endSessionInternal:e=>this.endSessionInternal(e),notedManifestBreakIds:e=>b(e,this.seenManifestBreakIds)});for(const[e,t]of this.contentListeners())this.player.on(e,t);this.log("OptiViewAds SDK initialized (SSAI mode)")}contentListeners(){const e=[["seeked",this.onContentSeeked],["waiting",this.onContentWaiting],["playing",this.onContentPlaying],["pause",this.onContentPause],["ended",this.onContentEnded],["error",this.onContentError]];return this.metadataCueTracker&&e.push(["timedmetadata",this.onTimedMetadata]),e}async startSession(e){return this.sessionStarter.startSession(e)}play(){return this.adPlayerController?.isAdPlaying()?(this.log("play() suppressed — ad break is active"),Promise.resolve()):this.player.play()}pause(){this.adPlayerController?.isAdPlaying()?this.log("pause() suppressed — ad break is active"):this.player.pause()}seek(e){if(!this.state.sessionActive)return;const t=this.breakScheduler?.getActiveBreak();t?.controls?.snapback?this.log("seek() suppressed — break has snapback enabled"):(this.breakScheduler?.notifyViewerSeek(),this.player.seek(e))}get muted(){return this.adPlayerController?this.adPlayerController.muted:this.player.muted}set muted(e){this.adPlayerController?this.adPlayerController.muted=e:this.player.muted=e}get volume(){return this.adPlayerController?this.adPlayerController.volume:this.player.volume}set volume(e){this.adPlayerController?this.adPlayerController.volume=e:this.player.volume=e}skipAd(){const e=this.adBreakStatusTracker.activeBreak;if(!this.state.sessionActive||!this.adPlayerController?.isAdPlaying()||!e)return this.log("skipAd() suppressed — no active ad break"),!1;const t=e.controls?.skipOffset;if(null==t)return this.log(`skipAd() suppressed — break '${e.id}' declares no controls.skipOffset`),this.diagnose("DA-AD-SKIP-SUPPRESSED","Skip requested but break declares no skipOffset",{breakId:e.id}),!1;const s=this.adBreakStatusTracker.activeBreakElapsedSec;return s<t?(this.log(`skipAd() suppressed — skipOffset ${t}s not reached (${s}s)`),this.diagnose("DA-AD-SKIP-SUPPRESSED","Skip requested before skipOffset",{breakId:e.id,skipOffset:t,elapsedSec:s}),!1):(this.log(`skipAd() — skipping break '${e.id}' at ${s}s (skipOffset ${t}s)`),this.diagnose("DA-AD-SKIPPED","Break skipped by viewer",{breakId:e.id,skipOffset:t,elapsedSec:s}),this.cmcdAdReporter.onSkipRequested(e.id),this.adPlayerController.skipBreak(),!0)}clickAd(){const e=this.adBreakStatusTracker.activeBreak,t=this.adPlayerController?.currentAdAsset()??null;if(!(this.state.sessionActive&&this.adPlayerController?.isAdPlaying()&&e&&t))return this.log("clickAd() suppressed — no ad on screen"),null;const s=t.interaction?.clickThrough;return this.diagnose("DA-AD-CLICKED","Ad clicked",{breakId:e.id,assetId:t.id,clickThrough:s??""}),this.emit("adclick",{type:"adclick",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,...s?{clickThrough:s}:{}}),s??null}endSession(){this.state.sessionActive&&this.endSessionInternal()}updateAssetParameters(e){if(this.state.sessionActive){if("ssai"===this.mode||this.state.steeredSsaiActive)return this.state.ssaiController.updateAssetParameters(e),void this.log("Asset parameters updated (SSAI)");this.adPlayerController.updateAssetParameters(e),this.log("Asset parameters updated")}else console.warn("[OptiViewAds] updateAssetParameters called but no active session.")}updateAssetParameterMacros(e){if(this.state.sessionActive){if("ssai"===this.mode||this.state.steeredSsaiActive)return this.state.ssaiController.updateAssetParameterMacros(e),void this.log("Asset parameter macros updated (SSAI)");this.adPlayerController.updateAssetParameterMacros(e),this.log("Asset parameter macros updated")}else console.warn("[OptiViewAds] updateAssetParameterMacros called but no active session.")}endSessionInternal(e="end-session"){this.liveStartPushback.stop(),this.state.sessionActive=!1,this.state.sessionGeneration++,this.breakLifecycle?.reportAbandonedBreak(e),"ssai"===this.mode?this.state.ssaiController?.stop():(this.state.steeredSsaiActive&&(this.state.ssaiController?.stop(),delete this.state.ssaiController,this.state.steeredSsaiActive=!1),this.manifestService?.reset(),this.breakScheduler?.stop(),this.breakScheduler?.destroy(),this.adBreakStatusTracker.resetAdBreakStatus(),this.state.pauseAdTickInterval&&(clearInterval(this.state.pauseAdTickInterval),this.state.pauseAdTickInterval=null),this.sessionStarter?.clearHeldImmediatePreRollArm(),this.pauseAdController?.reset(),this.breakTransitionTimer?.reset(),this.adPlayerController?.stopActiveBreak(),this.adPlayerController?.releaseContentHold(),this.adPlayerController?.endGamSession()),this.state.clearSessionIdentity(),this.anvatoObservedLogged.clear(),this.seenManifestBreakIds.clear(),this.cmcdAdReporter.onSessionEnd(),this.lensReporter.endSession(),this.diagnose("DA-SESSION-ENDED","Session ended"),this.log("Session ended")}addEventListener(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}removeEventListener(e,t){const s=this.eventHandlers.get(e);s&&s.delete(t)}emit(e,t){this.recordEventTimeline(t),this.cmcdAdReporter.onEvent(t);const s=this.eventHandlers.get(e);if(s)for(const e of s)try{e(t)}catch(e){this.log("Event handler error:",e)}}recordEventTimeline(e){O(this.diagnosticBuffer,e)}onDiagnostic(e){this.diagnosticHandlers.add(e)}offDiagnostic(e){this.diagnosticHandlers.delete(e)}exportDiagnostics(){const e={...this.state.configSummary,...this.state.manifestOrigin?{manifestOrigin:this.state.manifestOrigin}:{},...this.state.configSummary.ssai&&this.state.stitcherOrigin?{ssai:{...this.state.configSummary.ssai,stitcherOrigin:this.state.stitcherOrigin}}:{}};return{sdkVersion:L,generatedAt:Date.now(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:null,config:e,diagnostics:this.diagnosticBuffer.getAll()}}diagnose(e,t,s){if(this.destroyed)return;const i=M[e],r={ts:Date.now(),level:i?.level??"info",code:e,category:i?.category??"unknown",message:t,...s?{context:s}:{}};this.diagnosticBuffer.record(r);for(const e of this.diagnosticHandlers)try{e(r)}catch(e){this.log("Diagnostic handler error:",e)}this.debug&&G("[OptiViewAds]",e,t,s??"")}isAdPlaying(){return this.adPlayerController?.isAdPlaying()??!1}isPictureInPicture(){return this.adPlayerController?.isPictureInPicture()??!1}getPresentationState(){return{pictureInPicture:this.isPictureInPicture(),showing:this.adPlayerController?.isShowingAd()?"ad":"content",insertion:this.adPlayerController?.currentInsertionMode()??"overlay",windowOwner:this.adPlayerController?.pictureInPictureOwner()??null}}effectiveFormatOf(e){const t=this.adPlayerController?.declaredFormatOf(e)??B(e);return w(t,this.isPictureInPicture())}isSessionActive(){return this.state.sessionActive}getAdBreakStatus(){return this.adBreakStatusTracker.getAdBreakStatus()}destroy(){this.contentErrorReloadGuard&&(clearTimeout(this.contentErrorReloadGuard),this.contentErrorReloadGuard=null);for(const[e,t]of this.contentListeners())this.player.off(e,t);this.state.sessionActive&&this.endSessionInternal("destroy"),this.manifestService?.destroy(),this.pauseAdController?.destroy(),this.adPlayerController?.destroy(),this.state.ssaiController?.stop(),this.lensReporter.destroy(),this.eventHandlers.clear(),this.diagnosticHandlers.clear(),this.destroyed=!0,this.log("Destroyed")}toPlaybackError(e,t){const s=e;if(s&&("number"==typeof s.code||s.message)){const e="number"==typeof s.code?` (code ${s.code})`:"",i=s.message?`: ${s.message}`:"";return new Error(`${t}${e}${i}`)}return new Error(t)}log(...e){this.debug&&G("[OptiViewAds]",...e)}}
1
+ import{DEFAULT_MODE as e,DEFAULT_AD_PRELOAD_MODE as t,DEFAULT_AD_BREAK_CONTENT_RECOVERY as s,DEFAULT_AD_INSERTION_MODE as r,DEFAULT_AD_BREAK_CUT_SAFETY_MARGIN_SEC as i,DEFAULT_DOUBLE_BOX_AUDIO as a,resolveChaining as n,resolveTuneIn as o,resolveBreakWarnings as d,resolvePdtGraceSeconds as l}from"./types/OptiViewAdsConfig";import{SsaiController as h}from"./services/SsaiController";import{resolvePreloadMode as c}from"./services/detectPreloadMode";import{resolveContentRecovery as u}from"./services/detectContentRecovery";import{emitResolvedModeDiagnostics as m}from"./services/resolvedModeDiagnostics";import{isSingleSurfaceWebDevice as p,resolveInsertionMode as g}from"./services/detectInsertionMode";import{ManifestService as k}from"./services/ManifestService";import{BreakScheduler as f,systemClock as y}from"./services/BreakScheduler";import{MetadataCueTracker as S}from"./services/MetadataCueTracker";import{armBreakFromPresentedCue as v,diagnoseAnvatoCueObserved as A,notedManifestBreakIds as C,wireCueResume as b}from"./services/anvatoCueRuntime";import{AdPlayerController as P}from"./services/AdPlayerController";import{effectiveFormat as w}from"./services/pictureInPicture";import{resolveBreakFormat as B}from"./services/AdBreakSequencer";import{connectPauseAd as T}from"./services/adPlayer/connectPauseAd";import{BreakTransitionTimer as I}from"./services/BreakTransitionTimer";import{LensReporter as R}from"./services/LensReporter";import{CmcdAdReporter as D}from"./services/CmcdAdReporter";import{DiagnosticBuffer as E}from"./diagnostics/DiagnosticBuffer";import{recordEventTimeline as O}from"./diagnostics/recordEventTimeline";import{DIAGNOSTIC_CODES as M}from"./diagnostics/errorCodes";import{SDK_VERSION as L}from"./generated/version";import{playbackErrorContext as x}from"./diagnostics/playbackErrorContext";import{debugLog as G}from"./diagnostics/debugLog";import{AdBreakStatusTracker as H}from"./session/AdBreakStatusTracker";import{BreakLifecycle as F}from"./session/BreakLifecycle";import{SessionStarter as V}from"./session/SessionStarter";import{SessionState as $}from"./session/SessionState";import{LiveStartPushbackController as q}from"./services/LiveStartPushbackController";export class OptiViewAds{static get version(){return L}constructor(h){if(this.contentErrorReloadGuard=null,this.CONTENT_ERROR_RELOAD_GUARD_MS=5e3,this.eventHandlers=new Map,this.diagnosticHandlers=new Set,this.destroyed=!1,this.continueContentDuringBreak=!1,this.state=new $,this.metadataCueTracker=null,this.anvatoObservedLogged=new Set,this.seenManifestBreakIds=new Set,this.player=h.player,this.liveStartPushback=new q(this.player,h.liveStartPushback,{blocked:()=>!this.state.sessionActive||this.state.channelSwitchInFlight||!!this.adPlayerController?.isAdPlaying()||!!this.state.heldImmediatePreRollId,setSeeking:e=>this.breakScheduler?.setStartupSeeking(e),diagnose:(e,t,s)=>this.diagnose(e,t,s)},h.ptsSource),this.debug=h.debug??!1,this.mode=h.mode??e,this.hasExplicitMode=void 0!==h.mode,this.lensReporter=new R((...e)=>this.log(...e)),this.cmcdAdReporter=new D(()=>this.lensReporter.handle,(...e)=>this.log(...e)),this.adBreakStatusTracker=new H({emit:(e,t)=>this.emit(e,t),effectiveFormatOf:e=>this.effectiveFormatOf(e),secondsUntilBreak:e=>this.breakScheduler?.getSecondsUntilBreak(e)??void 0,breakTransitionTimer:()=>this.breakTransitionTimer}),this.onContentSeeked=()=>{const e=this.breakScheduler?.getActiveBreak();if(!e?.controls?.snapback)return;if(this.state.snapbackSeekInFlight)return void(this.state.snapbackSeekInFlight=!1);const t="number"==typeof e.start?e.start:this.player.currentTime;Math.abs(this.player.currentTime-t)<=.5||(this.log("Snapback: seek detected during locked break, snapping back to break start"),this.state.snapbackSeekInFlight=!0,this.player.seek(t))},this.onContentWaiting=()=>{this.adPlayerController?.isAdPlaying()||this.emit("waiting",{type:"waiting",timestamp:Date.now(),source:"content"})},this.onContentPlaying=()=>{this.adPlayerController?.isAdPlaying()||(this.breakScheduler?.markPlaybackStart(),this.breakTransitionTimer?.settle("out-of-break"),!1!==this.pauseAdController?.onResume()?this.emit("playing",{type:"playing",timestamp:Date.now(),source:"content"}):this.player.pause())},this.onContentPause=()=>{this.adPlayerController?.isAdPlaying()||this.breakScheduler?.isAdStartDelayActive()||this.pauseAdController?.onPause()},this.onContentEnded=()=>{this.adPlayerController?.isAdPlaying()||this.breakScheduler?.markPlaybackEnd()},this.onContentError=e=>{this.sessionStarter?.cancelHeldImmediatePreRollOnContentError();const t=this.toPlaybackError(e,"Content playback error");this.diagnose("DA-CONTENT-PLAYBACK-ERROR",t.message,x(e)),this.breakScheduler?.setContentReloading(!0),this.contentErrorReloadGuard&&clearTimeout(this.contentErrorReloadGuard),this.contentErrorReloadGuard=setTimeout(()=>{this.contentErrorReloadGuard=null,this.breakScheduler?.setContentReloading(!1)},this.CONTENT_ERROR_RELOAD_GUARD_MS),this.emit("aderror",{type:"aderror",timestamp:Date.now(),source:"content",error:t})},this.onTimedMetadata=e=>{if(!e)return;const t=e,s=this.metadataCueTracker?.handleCue(t)??!1;this.metadataCueTracker&&this.adPlayerController?.ingestStreamClockCue(t),A(t,s,this.metadataCueTracker,this.anvatoObservedLogged,this.player.currentTime,(e,t,s)=>this.diagnose(e,t,s)),"presented"===t.phase&&v(t,this.metadataCueTracker,this.breakScheduler)},this.continueContentDuringBreak=h.continueContentDuringBreak??!1,"ssai"===this.mode)return void this.initSsai(h);if(!h.createAdAdapter)throw new Error("[OptiViewAds] createAdAdapter is required. Use the @dolby-optiview/ads-sdk package for a default HLS.js ad player, or supply your own createAdAdapter factory.");this.state.steeredSsaiOptions={maxBitrate:h.maxBitrate,autoplay:h.autoplay??!1,streamActivityMonitorId:h.gam?.streamActivityMonitorId};const w=c(h.adPreload??t),B=h.adBreakContentRecovery??s,O=u(B),M=g(h.adInsertion??r),L=n(h.chaining),G=o(h.tuneIn),N=d(h.breakWarnings),K=l(h.pdtGraceSeconds);"anvatoCue"===h.ptsSource&&(this.metadataCueTracker=new S(this.diagnose.bind(this))),this.diagnosticBuffer=new E(h.diagnostics?.bufferSize),this.breakTransitionTimer=new I(e=>{this.diagnose("DA-BREAK-TRANSITION",`Transition ${e.kind} took ${e.durationMs}ms`,{transition:e.kind,durationMs:e.durationMs,breakId:e.breakId,adPreload:w,adInsertion:M,...e.phases?{phases:e.phases}:{}})}),this.state.configSummary={mode:this.mode,adPreload:w,adBreakContentRecovery:O,adInsertion:M,chaining:{enabled:L.enabled,maxGapSeconds:L.maxGapSeconds},tuneIn:{enabled:G.enabled,minBreakDurationSeconds:G.minBreakDurationSeconds},breakWarnings:{seconds:N.seconds},ptsSource:h.ptsSource??"mediaTime",continueContentDuringBreak:this.continueContentDuringBreak,gam:h.gam?{hasAssetParameters:!1,streamActivityMonitorId:h.gam.streamActivityMonitorId}:void 0},m({adPreload:h.adPreload??t,adInsertion:h.adInsertion??r,adBreakContentRecovery:B},{preloadMode:w,insertionMode:M,contentRecovery:O},(e,t,s)=>this.diagnose(e,t,s)),this.manifestService=new k(this.debug,h.interceptManifestResponse,(e,t,s)=>this.diagnose(e,t,s),h.interceptManifestRequest),this.breakScheduler=new f(this.player,this.debug,L,void 0,G,(e,t,s)=>this.diagnose(e,t,s),N,this.metadataCueTracker,K),this.adPlayerController=new P(h.player,h.container,h.playerContainer,h.createAdAdapter,this.debug,h.gam,w,M,h.adBreakCutSafetyMarginSec??i,h.doubleBoxAudio??a,p("undefined"!=typeof navigator?navigator.userAgent:"","undefined"!=typeof navigator?navigator.maxTouchPoints??0:0),y,O),this.adPlayerController.setTransitionPhaseReporter(this.debug?e=>this.breakTransitionTimer?.phase(e):null),b(this.adPlayerController,()=>this.metadataCueTracker),this.adPlayerController.setChainResolver(L.enabled?e=>this.breakScheduler.getChainedSuccessor(e):null),this.adPlayerController.initialize();const _=(e,t)=>void 0===e||void 0===t?{}:{adIndex:e,totalAds:t};this.adPlayerController.setGamEventCallbacks({onAdFirstQuartile:(e,t,s,r)=>{this.emit("adfirstquartile",{type:"adfirstquartile",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,..._(s,r)})},onAdMidpoint:(e,t,s,r)=>{this.emit("admidpoint",{type:"admidpoint",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,..._(s,r)})},onAdThirdQuartile:(e,t,s,r)=>{this.emit("adthirdquartile",{type:"adthirdquartile",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,..._(s,r)})}}),this.adPlayerController.setDiagnoseHandler((e,t,s)=>{this.diagnose(e,t,s)}),this.pauseAdController=T(this.adPlayerController,{debug:this.debug,diagnose:(e,t,s)=>this.diagnose(e,t,s)}),this.adPlayerController.setVolumeChangeCallback((e,t)=>{this.emit("volumechange",{type:"volumechange",timestamp:Date.now(),muted:e,volume:t})}),this.breakLifecycle=new F(this.state,{adPlayerController:this.adPlayerController,breakScheduler:this.breakScheduler,manifestService:this.manifestService,breakTransitionTimer:this.breakTransitionTimer,cmcdAdReporter:this.cmcdAdReporter,adBreakStatusTracker:this.adBreakStatusTracker,emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e),effectiveFormatOf:e=>this.effectiveFormatOf(e),onBreakSettled:()=>this.sessionStarter?.applyPendingChannelSwitch()}),this.sessionStarter=new V(this.state,{player:this.player,debug:this.debug,mode:this.mode,hasExplicitMode:this.hasExplicitMode,continueContentDuringBreak:this.continueContentDuringBreak,startLivePushback:()=>this.liveStartPushback.start(),manifestService:this.manifestService,breakScheduler:this.breakScheduler,adPlayerController:this.adPlayerController,pauseAdController:this.pauseAdController,breakLifecycle:this.breakLifecycle,cmcdAdReporter:this.cmcdAdReporter,lensReporter:this.lensReporter,adBreakStatusTracker:this.adBreakStatusTracker,emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e),endSessionInternal:e=>this.endSessionInternal(e),notedManifestBreakIds:e=>C(e,this.seenManifestBreakIds)});for(const[e,t]of this.contentListeners())this.player.on(e,t);this.log("OptiViewAds SDK initialized")}initSsai(e){if(!e.gam)throw new Error('[OptiViewAds] mode "ssai" requires a gam config.');if(!e.ssai?.networkCode)throw new Error('[OptiViewAds] mode "ssai" requires an ssai config (networkCode).');const t=e.ssai;this.diagnosticBuffer=new E(e.diagnostics?.bufferSize);const s=e.autoplay??!1;this.state.configSummary={mode:this.mode,adPreload:"n/a",adInsertion:"ssai",chaining:{enabled:!1,maxGapSeconds:0},tuneIn:{enabled:!1,minBreakDurationSeconds:0},gam:{networkCode:t.networkCode,hasAssetParameters:!1,streamActivityMonitorId:e.gam.streamActivityMonitorId},ssai:{maxBitrate:e.maxBitrate,autoplay:s},continueContentDuringBreak:this.continueContentDuringBreak},this.state.ssaiController=new h(this.player,{gam:e.gam,ssai:t,maxBitrate:e.maxBitrate,autoplay:s,debug:this.debug},{emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e)}),this.player.on("volumechange",()=>{this.emit("volumechange",{type:"volumechange",timestamp:Date.now(),muted:this.player.muted,volume:this.player.volume})}),this.sessionStarter=new V(this.state,{player:this.player,debug:this.debug,mode:this.mode,hasExplicitMode:this.hasExplicitMode,continueContentDuringBreak:this.continueContentDuringBreak,startLivePushback:()=>this.liveStartPushback.start(),manifestService:this.manifestService,breakScheduler:this.breakScheduler,adPlayerController:this.adPlayerController,pauseAdController:this.pauseAdController,breakLifecycle:this.breakLifecycle,cmcdAdReporter:this.cmcdAdReporter,lensReporter:this.lensReporter,adBreakStatusTracker:this.adBreakStatusTracker,emit:(e,t)=>this.emit(e,t),diagnose:(e,t,s)=>this.diagnose(e,t,s),log:(...e)=>this.log(...e),endSessionInternal:e=>this.endSessionInternal(e),notedManifestBreakIds:e=>C(e,this.seenManifestBreakIds)});for(const[e,t]of this.contentListeners())this.player.on(e,t);this.log("OptiViewAds SDK initialized (SSAI mode)")}contentListeners(){const e=[["seeked",this.onContentSeeked],["waiting",this.onContentWaiting],["playing",this.onContentPlaying],["pause",this.onContentPause],["ended",this.onContentEnded],["error",this.onContentError]];return this.metadataCueTracker&&e.push(["timedmetadata",this.onTimedMetadata]),e}async startSession(e){return this.sessionStarter.startSession(e)}play(){return this.adPlayerController?.isAdPlaying()?(this.log("play() suppressed — ad break is active"),Promise.resolve()):this.player.play()}pause(){this.adPlayerController?.isAdPlaying()?this.log("pause() suppressed — ad break is active"):this.player.pause()}seek(e){if(!this.state.sessionActive)return;const t=this.breakScheduler?.getActiveBreak();t?.controls?.snapback?this.log("seek() suppressed — break has snapback enabled"):(this.breakScheduler?.notifyViewerSeek(),this.player.seek(e))}get muted(){return this.adPlayerController?this.adPlayerController.muted:this.player.muted}set muted(e){this.adPlayerController?this.adPlayerController.muted=e:this.player.muted=e}get volume(){return this.adPlayerController?this.adPlayerController.volume:this.player.volume}set volume(e){this.adPlayerController?this.adPlayerController.volume=e:this.player.volume=e}skipAd(){const e=this.adBreakStatusTracker.activeBreak;if(!this.state.sessionActive||!this.adPlayerController?.isAdPlaying()||!e)return this.log("skipAd() suppressed — no active ad break"),!1;const t=e.controls?.skipOffset;if(null==t)return this.log(`skipAd() suppressed — break '${e.id}' declares no controls.skipOffset`),this.diagnose("DA-AD-SKIP-SUPPRESSED","Skip requested but break declares no skipOffset",{breakId:e.id}),!1;const s=this.adBreakStatusTracker.activeBreakElapsedSec;return s<t?(this.log(`skipAd() suppressed — skipOffset ${t}s not reached (${s}s)`),this.diagnose("DA-AD-SKIP-SUPPRESSED","Skip requested before skipOffset",{breakId:e.id,skipOffset:t,elapsedSec:s}),!1):(this.log(`skipAd() — skipping break '${e.id}' at ${s}s (skipOffset ${t}s)`),this.diagnose("DA-AD-SKIPPED","Break skipped by viewer",{breakId:e.id,skipOffset:t,elapsedSec:s}),this.cmcdAdReporter.onSkipRequested(e.id),this.adPlayerController.skipBreak(),!0)}clickAd(){const e=this.adBreakStatusTracker.activeBreak,t=this.adPlayerController?.currentAdAsset()??null;if(!(this.state.sessionActive&&this.adPlayerController?.isAdPlaying()&&e&&t))return this.log("clickAd() suppressed — no ad on screen"),null;const s=t.interaction?.clickThrough;return this.diagnose("DA-AD-CLICKED","Ad clicked",{breakId:e.id,assetId:t.id,clickThrough:s??""}),this.emit("adclick",{type:"adclick",timestamp:Date.now(),break:e,format:this.effectiveFormatOf(e),asset:t,...s?{clickThrough:s}:{}}),s??null}endSession(){this.state.sessionActive&&this.endSessionInternal()}updateAssetParameters(e){if(this.state.sessionActive){if("ssai"===this.mode||this.state.steeredSsaiActive)return this.state.ssaiController.updateAssetParameters(e),void this.log("Asset parameters updated (SSAI)");this.adPlayerController.updateAssetParameters(e),this.log("Asset parameters updated")}else console.warn("[OptiViewAds] updateAssetParameters called but no active session.")}updateAssetParameterMacros(e){if(this.state.sessionActive){if("ssai"===this.mode||this.state.steeredSsaiActive)return this.state.ssaiController.updateAssetParameterMacros(e),void this.log("Asset parameter macros updated (SSAI)");this.adPlayerController.updateAssetParameterMacros(e),this.log("Asset parameter macros updated")}else console.warn("[OptiViewAds] updateAssetParameterMacros called but no active session.")}endSessionInternal(e="end-session"){this.liveStartPushback.stop(),this.state.sessionActive=!1,this.state.sessionGeneration++,this.breakLifecycle?.reportAbandonedBreak(e),"ssai"===this.mode?this.state.ssaiController?.stop():(this.state.steeredSsaiActive&&(this.state.ssaiController?.stop(),delete this.state.ssaiController,this.state.steeredSsaiActive=!1),this.manifestService?.reset(),this.breakScheduler?.stop(),this.breakScheduler?.destroy(),this.adBreakStatusTracker.resetAdBreakStatus(),this.state.pauseAdTickInterval&&(clearInterval(this.state.pauseAdTickInterval),this.state.pauseAdTickInterval=null),this.sessionStarter?.clearHeldImmediatePreRollArm(),this.pauseAdController?.reset(),this.breakTransitionTimer?.reset(),this.adPlayerController?.stopActiveBreak(),this.adPlayerController?.releaseContentHold(),this.adPlayerController?.endGamSession()),this.state.clearSessionIdentity(),this.anvatoObservedLogged.clear(),this.seenManifestBreakIds.clear(),this.cmcdAdReporter.onSessionEnd(),this.lensReporter.endSession(),this.diagnose("DA-SESSION-ENDED","Session ended"),this.log("Session ended")}addEventListener(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}removeEventListener(e,t){const s=this.eventHandlers.get(e);s&&s.delete(t)}emit(e,t){this.recordEventTimeline(t),this.cmcdAdReporter.onEvent(t);const s=this.eventHandlers.get(e);if(s)for(const e of s)try{e(t)}catch(e){this.log("Event handler error:",e)}}recordEventTimeline(e){O(this.diagnosticBuffer,e)}onDiagnostic(e){this.diagnosticHandlers.add(e)}offDiagnostic(e){this.diagnosticHandlers.delete(e)}exportDiagnostics(){const e={...this.state.configSummary,...this.state.manifestOrigin?{manifestOrigin:this.state.manifestOrigin}:{},...this.state.configSummary.ssai&&this.state.stitcherOrigin?{ssai:{...this.state.configSummary.ssai,stitcherOrigin:this.state.stitcherOrigin}}:{}};return{sdkVersion:L,generatedAt:Date.now(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:null,config:e,diagnostics:this.diagnosticBuffer.getAll()}}diagnose(e,t,s){if(this.destroyed)return;const r=M[e],i={ts:Date.now(),level:r?.level??"info",code:e,category:r?.category??"unknown",message:t,...s?{context:s}:{}};this.diagnosticBuffer.record(i);for(const e of this.diagnosticHandlers)try{e(i)}catch(e){this.log("Diagnostic handler error:",e)}this.debug&&G("[OptiViewAds]",e,t,s??"")}isAdPlaying(){return this.adPlayerController?.isAdPlaying()??!1}isPictureInPicture(){return this.adPlayerController?.isPictureInPicture()??!1}getPresentationState(){return{pictureInPicture:this.isPictureInPicture(),showing:this.adPlayerController?.isShowingAd()?"ad":"content",insertion:this.adPlayerController?.currentInsertionMode()??"overlay",windowOwner:this.adPlayerController?.pictureInPictureOwner()??null}}effectiveFormatOf(e){const t=this.adPlayerController?.declaredFormatOf(e)??B(e);return w(t,this.isPictureInPicture())}isSessionActive(){return this.state.sessionActive}getAdBreakStatus(){return this.adBreakStatusTracker.getAdBreakStatus()}destroy(){this.contentErrorReloadGuard&&(clearTimeout(this.contentErrorReloadGuard),this.contentErrorReloadGuard=null);for(const[e,t]of this.contentListeners())this.player.off(e,t);this.state.sessionActive&&this.endSessionInternal("destroy"),this.manifestService?.destroy(),this.pauseAdController?.destroy(),this.adPlayerController?.destroy(),this.state.ssaiController?.stop(),this.lensReporter.destroy(),this.eventHandlers.clear(),this.diagnosticHandlers.clear(),this.destroyed=!0,this.log("Destroyed")}toPlaybackError(e,t){const s=e;if(s&&("number"==typeof s.code||s.message)){const e="number"==typeof s.code?` (code ${s.code})`:"",r=s.message?`: ${s.message}`:"";return new Error(`${t}${e}${r}`)}return new Error(t)}log(...e){this.debug&&G("[OptiViewAds]",...e)}}
@@ -84,6 +84,16 @@ export declare const DIAGNOSTIC_CODES: {
84
84
  readonly level: "warn";
85
85
  readonly summary: "ptsSource: 'anvatoCue' — the adapter's ptsOffset placed an Anvato cue outside its carrying segment's window (more than 0.1s before or 15s after the cue startTime), so the cue's startTime is used instead. Emitted once per cue pts; context: pts, startTime, ptsOffset, mappedTime.";
86
86
  };
87
+ readonly "DA-ANVATO-CUE-END-MATCHED": {
88
+ readonly category: "break";
89
+ readonly level: "info";
90
+ readonly summary: "ptsSource: 'anvatoCue' — the active break's Anvato type=cue_end was observed and its length on the stream clock (cue_end pts minus the break start pts) is within 2s of the break duration. Emitted once per break; context: breakId, mediaTime (where the player reported the cue_end), lengthSec, durationSec.";
91
+ };
92
+ readonly "DA-ANVATO-CUE-END-REJECTED": {
93
+ readonly category: "break";
94
+ readonly level: "warn";
95
+ readonly summary: "ptsSource: 'anvatoCue' — an Anvato type=cue_end was observed for the active break but its stream-clock length differs from the break duration by more than 2s, so it is ignored and the resume keeps its computed target. Emitted once per break; context: breakId, mediaTime, lengthSec, durationSec.";
96
+ };
87
97
  readonly "DA-PRELOAD-FAILED": {
88
98
  readonly category: "preload";
89
99
  readonly level: "warn";
@@ -477,13 +487,48 @@ export declare const DIAGNOSTIC_CODES: {
477
487
  readonly "DA-RESUME-LANDED": {
478
488
  readonly category: "playback";
479
489
  readonly level: "info";
480
- readonly summary: "Where the post-break resume-seek actually landed, measured on the seeked event rather than inferred: context carries breakId, target (the position requested), landed and errorSec (landed - target; negative means the player settled EARLIER than asked). landed is null with a reason when no seeked event arrived, which is normal for a seek to the position the playhead already holds. Report-only: the SDK does not correct the position.";
490
+ readonly summary: "Where the post-break resume-seek actually landed, measured on the seeked event rather than inferred: context carries breakId, target (the position requested), landed and errorSec (landed - target; negative means the player settled EARLIER than asked). errorSec only says whether the SEEK did what it was asked: when the live-window clamp moved the seek, policyTarget is the resume point before the clamp and policyErrorSec (landed - policyTarget) is how far the viewer really is from it. landed is null with a reason when no seeked event arrived, which is normal for a seek to the position the playhead already holds. Report-only: the SDK does not correct the position.";
491
+ };
492
+ readonly "DA-RESUME-PREPARED": {
493
+ readonly category: "playback";
494
+ readonly level: "info";
495
+ readonly summary: "Android, live break that resumes at its end — the paused content was parked exactly on the resume point before the hand-back, so the hand-back only plays (DA-RESUME-SEEK then reports prepared=true and issues no seek). Context carries breakId, target, source (cue_end when the stream's matched type=cue_end was known, else cue+duration) leadMs (how long before the expected hand-back it was parked) and refresh (true when content parked long before the hand-back was seeked onto the same point again, 4.5s before it). A later cue_end parks content again.";
481
496
  };
482
497
  readonly "DA-RESUME-PREPOSITIONED": {
483
498
  readonly category: "playback";
484
499
  readonly level: "info";
485
500
  readonly summary: "The break resumed without a seek: content was moved onto its resume position DURING the break, so the transition needed no jump. Context carries breakId, target, prepositionedTo, landed, shortfallSec and exact. exact=true means it reached the policy target. exact=false means the live window never published those frames, so content was moved as close as exists — the viewer lands short, but arrives already in place rather than via a visible seek at the cut.";
486
501
  };
502
+ readonly "DA-RESUME-PTS-MAP": {
503
+ readonly category: "playback";
504
+ readonly level: "info";
505
+ readonly summary: "ptsSource: 'anvatoCue', iOS/tvOS and web — the live resume point was mapped onto currentTime through the stream's own clock: the Anvato type=beacon tags delivered since the run-up's last seek give the currentTime ↔ stream-clock offset, and the resume point (the matched cue_end, else the cue plus the break duration) is converted with it. Reported when a mapping is first available after a seek and whenever the mapped target moves by 0.1s or more. Context carries breakId, target, landingStreamSec, landingSource (cue_end or cue+duration), offsetSec, beacons (beacons averaged), generation (how often the mapping started over since the session began), currentTime, and computedTarget with deltaSec (target - computedTarget) when a currentTime-based target exists.";
506
+ };
507
+ readonly "DA-RESUME-PTS-REMAP": {
508
+ readonly category: "playback";
509
+ readonly level: "warn";
510
+ readonly summary: "ptsSource: 'anvatoCue', iOS/tvOS and web — a stream beacon disagreed with the currentTime ↔ stream-clock mapping by more than 0.2s, so the player re-anchored currentTime (a variant switch or a buffer restart); the mapping starts over from that beacon and the resume point is mapped again. Reported during the resume run-up and after the hand-back. Context carries breakId, fromOffsetSec, toOffsetSec, deltaSec, currentTime and stage (run-up or after-hand-back).";
511
+ };
512
+ readonly "DA-RESUME-PTS-CORRECTED": {
513
+ readonly category: "playback";
514
+ readonly level: "info";
515
+ readonly summary: "ptsSource: 'anvatoCue', iOS/tvOS and web — once per break at the hand-back, on a stream that carries Anvato beacons: whether the stream clock placed the live resume point, and by how much it moved it. applied=true: streamClockTarget is the resume point mapped through the beacons, correctionSec is streamClockTarget - computedTarget (the currentTime target, cue plus duration), and currentTimeShiftSec is how far the same stream instant moved in currentTime between the pause and the hand-back (negative: it now sits earlier), null when no beacon mapped the stream before the pause. Context also carries breakId, landingSource (cue_end or cue+duration), landingStreamSec, offsetSec, beacons, remaps (DA-RESUME-PTS-REMAP during the break) and cueEndTarget when a cue_end was matched. applied=false with a reason means no beacon arrived after the run-up's last seek, so the cue_end or currentTime target applied.";
516
+ };
517
+ readonly "DA-RESUME-PTS-LANDED": {
518
+ readonly category: "playback";
519
+ readonly level: "info";
520
+ readonly summary: "ptsSource: 'anvatoCue', iOS/tvOS and web — where a stream-clock resume landed, measured on the stream's own clock from the beacons delivered after the hand-back: landedStreamSec is the position content resumed from (resumedAt, the seek landing or the playhead at a seek-free hand-back) converted with that mapping, and errorSec is landedStreamSec - landingStreamSec (negative: content resumed before the stream's resume point, so slate is shown). Context carries breakId, landingStreamSec, landingSource, resumedAt, sinceHandBackSec and, when measured, landedStreamSec, errorSec, offsetSec and beacons; reason when no beacon arrived within 15s. Report-only: the SDK does not correct the position from it.";
521
+ };
522
+ readonly "DA-RESUME-CUE-END": {
523
+ readonly category: "playback";
524
+ readonly level: "info";
525
+ readonly summary: "ptsSource: 'anvatoCue', iOS/tvOS, web and Android — the stream's matched type=cue_end replaced the computed resume target: the slate under the ad ends there, not at cue plus the advertised duration (150.206s for a 150s break on NFL Channel), and the player can remap its timeline while content is held, so the cue_end is reported in the current mapping. Context carries breakId, computedTarget, cueEndTarget, deltaSec (cueEndTarget - computedTarget), stage (hold, playing or hand-back; Android: always hand-back) and corrected (whether an in-buffer correction seek ran). Only a policy that resumes at the break end is replaced; otherwise applied=false and only the delta is reported.";
526
+ };
527
+ readonly "DA-RESUME-CUE-END-LATE": {
528
+ readonly category: "playback";
529
+ readonly level: "info";
530
+ readonly summary: "ptsSource: 'anvatoCue', iOS/tvOS and Android — the break's type=cue_end was matched only after the hand-back. When it is more than 1s ahead of the playhead and buffered, content is seeked forward to it once (corrected=true); content is never seeked backward. Context carries breakId, cueEndTarget, currentTime, deltaSec (cueEndTarget - currentTime) and corrected.";
531
+ };
487
532
  readonly "DA-RESUME-CATCHUP": {
488
533
  readonly category: "playback";
489
534
  readonly level: "info";
@@ -1 +1 @@
1
- export const DIAGNOSTIC_CODES={"DA-SESSION-STARTED":{category:"session",level:"info",summary:"Monetization session started; manifest polling began. context: manifestUrl (stitcherUrl in SSAI mode), reported verbatim."},"DA-SESSION-ENDED":{category:"session",level:"info",summary:"Monetization session ended; polling and scheduling stopped."},"DA-ASSET-PARAMETERS-UPDATED":{category:"session",level:"info",summary:"The break manifest's session-level asset parameters changed; the merged parameters were pushed to the active GAM stream. context: source ('manifest'), keys (parameter names only, never values)."},"DA-MANIFEST-FETCH-FAILED":{category:"manifest",level:"error",summary:"Initial break-manifest fetch failed; the session could not start."},"DA-MANIFEST-POLL-FAILED":{category:"manifest",level:"warn",summary:"A manifest poll failed; the SDK keeps the last good manifest and retries."},"DA-MANIFEST-CHANNEL-CHANGED":{category:"manifest",level:"info",summary:"A polled manifest describes a different ads channel (channelId, GAM identity or timebase changed); the SDK re-aligned its ad setup and resolved delivery mode again while the session and content playback continued. context: previousChannelId, channelId, reason, manifestUrl."},"DA-MANIFEST-INTERCEPT-FAILED":{category:"manifest",level:"warn",summary:"The customer manifest-response interceptor threw; the un-modified parsed manifest was used instead."},"DA-MANIFEST-REQUEST-INTERCEPT-FAILED":{category:"manifest",level:"warn",summary:"The customer manifest-request interceptor threw; the normal network fetch of the original URL was used instead."},"DA-MANIFEST-SIGNATURE-INVALID":{category:"manifest",level:"error",summary:"The break-manifest response failed detached-JWS signature verification (missing/malformed X-Manifest-Signature, unsupported alg, unknown kid, unknown critical param, or signature mismatch); the manifest was rejected and no breaks were scheduled. context: url, reason."},"DA-PDT-MISSING":{category:"playback",level:"warn",summary:"No EXT-X-PROGRAM-DATE-TIME once content is playing (or after the startup backstop window); wallclock-timebase breaks fall back to the system clock."},"DA-ANVATO-CUE-PENDING":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — no Anvato in-stream cue observed yet for a PTS break; the break stays pending until its cue arrives."},"DA-ANVATO-CUE-MATCHED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — a PTS break's start was matched to an observed Anvato cue and scheduled at the cue's media time."},"DA-ANVATO-CUE-ENTERED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — a break was started by the cue reaching the playhead rather than by the scheduler's 250ms tick; context carries the breakId, the cue pts and the media time it fired at, so the two start paths are distinguishable in the field."},"DA-ANVATO-CUE-OBSERVED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — an Anvato break-signaling (type=cue) frame was observed in the stream; context carries the cue's pts, the media time it landed at, whether the tracker recorded it, and the raw payload — so a manifest-PTS vs in-stream-PTS misalignment is observable in the field."},"DA-ANVATO-CUE-SEGMENT-ANCHORED":{category:"break",level:"warn",summary:"ptsSource: 'anvatoCue' — an Anvato emsg cue arrived without a ptsOffset from the adapter, so its break is scheduled at the cue's carrying segment start, which can be up to one segment early. Emitted once per session; context: pts, mediaTime."},"DA-ANVATO-CUE-OFFSET-REJECTED":{category:"break",level:"warn",summary:"ptsSource: 'anvatoCue' — the adapter's ptsOffset placed an Anvato cue outside its carrying segment's window (more than 0.1s before or 15s after the cue startTime), so the cue's startTime is used instead. Emitted once per cue pts; context: pts, startTime, ptsOffset, mappedTime."},"DA-PRELOAD-FAILED":{category:"preload",level:"warn",summary:"Ad preload failed; the asset will be loaded on demand at break start."},"DA-PRELOAD-MODE-RESOLVED":{category:"preload",level:"info",summary:"The configured ad preload mode was resolved for this session; context carries both the configured and the resolved mode."},"DA-PRELOAD-PATH":{category:"preload",level:"info",summary:"The preload path actually taken for a break's ad (parallel buffer / detached prefetch / none) and the creative container (stream vs progressive)."},"DA-BREAK-EARLY-RETURN":{category:"break",level:"info",summary:"The active break was removed from a polled manifest (early return); the break ends immediately and content resumes at break start plus the seconds already played."},"DA-BREAK-WINDOW-ESCAPED":{category:"break",level:"warn",summary:"An active wallclock break outlived its window on the stream clock (ad stall, bogus trigger position, or a re-fired completed break); the SDK ended it and returned to content. context.overrunSec says by how much."},"DA-BREAK-EVENT-UNSUPPORTED":{category:"break",level:"warn",summary:"A break is triggered by a spec event this SDK version does not schedule on this platform (web schedules `start`, `pause` and `end`; Android and iOS do not schedule `end` yet); the break was ignored. context.event names the event."},"DA-BREAK-SUPPRESSED-OVERLAP":{category:"break",level:"warn",summary:"A break was suppressed because an ad was already playing."},"DA-BREAK-TRANSITION":{category:"break",level:"info",summary:"Measured duration of a playback transition into an ad break, between two ads, between chained breaks, or back to content."},"DA-AD-SURFACE-REVEALED":{category:"break",level:"info",summary:"The ad surface became visible: how long it was held back waiting for the ad's first frame, and whether it was revealed because that frame arrived or because the wait timed out."},"DA-PREROLL-CONTENT-HELD":{category:"break",level:"info",summary:"Content playback was held at session start until a pending pre-roll began, so no content is shown before the ad."},"DA-PREROLL-CONTENT-WAIT-TIMEOUT":{category:"break",level:"info",summary:"A pending pre-roll began after content readiness was not reported within the wait timeout."},"DA-PREROLL-CANCELLED-CONTENT-ERROR":{category:"break",level:"warn",summary:"A pending pre-roll was cancelled because the content failed to load before it could begin."},"DA-SHARED-ELEMENT-UNSUPPORTED":{category:"break",level:"warn",summary:"Configured shared-element insertion is unsupported on this platform (non-iPhone/iPod); fell back to overlay insertion."},"DA-SHARED-ELEMENT-RESTORE-FAILED":{category:"playback",level:"error",summary:"Content did not resume after a shared-element break: the reload/seek/play restore failed twice; the viewer is left paused on the handed-back element."},"DA-IMAGE-LOAD-FAILED":{category:"break",level:"warn",summary:"An image (companion, backdrop or image ad) could not be fetched or decoded within the timeout; the break continues without it."},"DA-PIP-TRANSFER-FAILED":{category:"break",level:"warn",summary:"The picture-in-picture window could not be moved between the content and ad elements; the break continues but the viewer may not see the ad in the PiP window."},"DA-PIP-AUTODETECT-UNAVAILABLE":{category:"break",level:"warn",summary:"No Activity could be resolved from the renderer's Context or the overlay's view tree, so picture-in-picture cannot be detected automatically; the host must call OptiViewAds.setPictureInPicture() from Activity.onPictureInPictureModeChanged or breaks will be laid out for a fullscreen surface. Android only."},"DA-CONTENT-ELEMENT-SWAPPED":{category:"break",level:"info",summary:"The content player replaced its <video> element; the SDK re-bound its presentation listeners to the new one."},"DA-PIP-FORMAT-OVERRIDE":{category:"break",level:"info",summary:"The content player is in picture-in-picture, so the break's declared format was overruled and it plays as a single fullscreen ad."},"DA-PIP-ADOPTION-STATE":{category:"break",level:"info",summary:"Native PiP reconciliation deferred or reused a layout/handoff decision. Context carries reason, active, adPlaying, applied, and asset/break IDs when available; this is not evidence that a format override occurred."},"DA-CHAIN-RESOLVER-ERROR":{category:"chaining",level:"warn",summary:"The chained-successor resolver threw; chaining was skipped for this break."},"DA-GAM-NO-ASSET-KEY":{category:"gam",level:"warn",summary:"Retired: the GAM stream identity now comes from the manifest's vendorConfiguration. Kept declared so the code is never reused; see DA-GAM-CONFIG-MISSING."},"DA-GAM-SESSION-FAILED":{category:"gam",level:"error",summary:"The GAM/IMA session failed to initialize; GAM breaks will not serve."},"DA-GAM-CONFIG-RESOLVED":{category:"gam",level:"info",summary:"The GAM stream identity for this session was resolved from the manifest's vendorConfiguration."},"DA-GAM-CONFIG-MISSING":{category:"gam",level:"error",summary:'The break manifest carries no usable "gam" vendorConfiguration entry; GAM assets are skipped.'},"DA-GAM-POD-IDENTITY-MISMATCH":{category:"gam",level:"error",summary:"A GAM pod asset's vendorParameters name a different network code or custom asset key than the stream session was created with; the asset is skipped because the pod request cannot serve."},"DA-GAM-POD-MID-BREAK-END":{category:"gam",level:"warn",summary:"IMA reported the ad break ended before the pod's last ad while pod stream remains; per-ad reporting continues until the pod ends."},"DA-VENDOR-CONFIG-UNKNOWN-TYPE":{category:"manifest",level:"info",summary:"One or more vendorConfiguration entries declare a type this SDK version does not recognise and were ignored."},"DA-CONTENT-PLAYBACK-ERROR":{category:"playback",level:"error",summary:"The content player reported a playback error."},"DA-CONTENT-RESUME-STALLED":{category:"playback",level:"warn",summary:"Content did not resume within the watchdog window after a break that paused it ended; the SDK re-issued play() once. iOS only for now."},"DA-CONTENT-RECOVERY-MODE-RESOLVED":{category:"playback",level:"info",summary:"The resolved post-break content recovery mode for the session (recreate or none); context carries configured and resolved."},"DA-CONTENT-PIPELINE-RECREATED":{category:"playback",level:"info",summary:"The content player's media pipeline was rebuilt at break end before content resumed (recovery mode recreate); context carries breakId, startTime and durationMs."},"DA-CONTENT-PIPELINE-RECREATE-FAILED":{category:"playback",level:"warn",summary:"Rebuilding the content media pipeline at break end failed or timed out — or the adapter does not implement recreateMediaPipeline() (reason 'unsupported-adapter', e.g. a wrapper adapter that does not forward it); the SDK fell back to resuming in place with seek + play; context carries breakId, startTime, reason."},"DA-AD-PLAYBACK-ERROR":{category:"playback",level:"error",summary:"The ad player reported a playback error during a break."},"DA-AD-LOAD-RETRIED":{category:"playback",level:"warn",summary:'The ad player\'s load() had not settled within the retry window of the ad-start budget and the ad element showed no progress (readyState 0, nothing buffered), so a second load() was issued for the same URI; a slow-but-progressing load is not retried. Context carries breakId, assetId, uri, elapsedMs, remainingBudgetMs. A still-stalled retry ends as DA-AD-PLAYBACK-ERROR "Ad load timeout".'},"DA-AD-URI-MISSING":{category:"playback",level:"error",summary:"The ad asset had no usable media URI, VAST tag URL or render surface; reported as CMCD adec."},"DA-AD-MEDIA-LOAD-FAILED":{category:"playback",level:"error",summary:"The ad player could not fetch the ad media (network or HTTP failure); reported as CMCD adec."},"DA-AD-MEDIA-UNSUPPORTED":{category:"playback",level:"error",summary:"The ad player could not decode the ad media or does not support its format; reported as CMCD adec."},"DA-AD-START-TIMEOUT":{category:"playback",level:"error",summary:"The ad did not load, render a first frame or start within its start budget; reported as CMCD adec."},"DA-AD-START-INTERRUPTED":{category:"playback",level:"warn",summary:"The ad element's play() was interrupted by a browser-initiated pause before the ad started (Chromium AbortError, seen on Samsung Tizen); the SDK re-issued play() once. context: breakId, error."},"DA-AD-DURATION-PREPARED":{category:"playback",level:"info",summary:"The ad media for a break was prepared and its real playable duration is now known, BEFORE the first frame. context: breakId, assetId, index, total, preparedDurationSec (the loaded media's own duration — on a GAM pod, the stitched pod's length), declaredDurationSec (what the manifest said about this asset, when it said anything) and breakDurationSec (the slot the break declares). Emitted per asset, so a multi-asset break reports one per asset and the break total is their sum. The three together separate a short break caused by a short POD from one caused by a short request or a late join."},"DA-DELIVERY-MODE-RESOLVED":{category:"session",level:"info",summary:"Delivery mode (sgai/ssai) resolved for the session at start and again on an ads-channel switch from the manifest's delivery rules (or the explicit client config)."},"DA-DELIVERY-MODE-UNKNOWN":{category:"session",level:"warn",summary:"The matching delivery rule carried an unrecognized mode value; sgai is used (forward compatibility)."},"DA-DELIVERY-MODE-OVERRIDDEN":{category:"session",level:"info",summary:"The manifest's delivery rules resolved a different mode, but the explicit client config takes precedence."},"DA-DELIVERY-MODE-CHANGE-IGNORED":{category:"session",level:"warn",summary:"An ordinary manifest poll resolves a different delivery mode; the mode pinned for the session stays in force. An ads-channel switch resolves the mode again."},"DA-SSAI-UNAVAILABLE":{category:"session",level:"error",summary:"The manifest selected ssai delivery but no vendor configuration can provide a stitched stream (no gam entry with an assetKey); at start the session fails, while on a channel switch the session stays in sgai."},"DA-SSAI-SESSION-FAILED":{category:"session",level:"error",summary:"The SSAI session failed to start (IMA stream init, stream id, or stitched-stream load)."},"DA-SSAI-IMA-ERROR":{category:"gam",level:"error",summary:"IMA reported an error during the SSAI stream session."},"DA-INSERTION-TYPE-RESOLVED":{category:"session",level:"info",summary:"Per-session ad insertion type resolved, and whether the integrator set it or left it unset (unset lets the manifest's resumeOffset drive the resume point)."},"DA-RESUME-OFFSET-CLAMPED":{category:"break",level:"info",summary:"The resume offset was shortened to the ad duration actually played, so the break could not skip further than the ads it delivered."},"DA-INSERTION-TYPE-IGNORED-SSAI":{category:"session",level:"warn",summary:"adInsertionType is ignored in SSAI mode; the stitcher controls ad insertion server-side."},"DA-VAST-UNSUPPORTED-FORMAT":{category:"break",level:"warn",summary:"A VAST asset appeared in an unsupported break format; VAST is only supported in single, double, and lshape_ad. The break was skipped."},"DA-ASSET-MACRO-UNKNOWN":{category:"break",level:"warn",summary:"An asset parameter value contained a macro the SDK has no value for (an unknown or unavailable OptiView macro, or a registered customer macro that returned no value); the parameter was still sent, with the macro kept as its literal token. Raised once per parameter key and macro. context: key, macro, breakId, assetId."},"DA-ASSET-PARAMETER-OMITTED":{category:"break",level:"info",summary:"An asset parameter value contained a customer macro that is empty (value `null`), so the parameter was not sent; for GAM `cust_params` only the `&`-separated pair containing the macro was dropped. Raised once per parameter key and macro (per dropped pair for GAM `cust_params`). context: key, macro, pair (GAM `cust_params` only), breakId, assetId."},"DA-VAST-SSAI-UNSUPPORTED":{category:"session",level:"warn",summary:"VAST assets are not supported in SSAI mode (VAST is SGAI-only); the asset was skipped."},"DA-VAST-IMA-ERROR":{category:"gam",level:"error",summary:"Google IMA reported an error while loading or playing a VAST (client-side / CSAI) ad."},"DA-VAST-NO-FILL":{category:"gam",level:"error",summary:"The VAST ad server returned no ad (empty response, no ads after wrappers or no assets); reported as CMCD adec."},"DA-VAST-TIMEOUT":{category:"gam",level:"error",summary:"The VAST response or its media file did not load in time; reported as CMCD adec."},"DA-VAST-MALFORMED":{category:"gam",level:"error",summary:"The VAST response could not be parsed or uses an unsupported VAST version; reported as CMCD adec."},"DA-VAST-REQUEST-FAILED":{category:"gam",level:"error",summary:"The VAST ad request failed (network error, invalid tag URL, wrapper error or too many redirects); reported as CMCD adec."},"DA-VAST-CREATIVE-FAILED":{category:"gam",level:"error",summary:"The VAST creative could not be played (no compatible media file, playback error or trafficking error); reported as CMCD adec."},"DA-VAST-IMA-SDK-MISSING":{category:"gam",level:"error",summary:"The Google IMA client-side SDK (ima3.js) is unavailable; VAST (CSAI) ads cannot be played."},"DA-PAUSE-AD-SHOWN":{category:"break",level:"info",summary:"A pause ad (full-screen image or video) was shown while content is paused."},"DA-PAUSE-AD-DISMISSED":{category:"break",level:"info",summary:"A pause ad was dismissed (content resumed, or the duration cap elapsed)."},"DA-PAUSE-AD-RESUME-ALLOWED":{category:"break",level:"info",summary:"The viewer may now resume content over the shown pause ad: the break's controls.skipOffset elapsed, or (no skipOffset) the ad was watched fully: a video creative ended, an image reached its duration cap or has none. context: breakId."},"DA-PAUSE-AD-RESUME-BLOCKED":{category:"break",level:"info",summary:"Content tried to resume while a pause ad must still be watched (controls.skipOffset not reached, or no skipOffset and the video creative has not ended / the image duration cap has not elapsed); the SDK keeps content paused. context: breakId, elapsedSec, skipOffset."},"DA-PAUSE-AD-DVR-EXPIRED":{category:"break",level:"info",summary:"The viewer paused for longer than the DVR window is deep, so the position they paused at aged out and playback resumed at the live edge instead. context: pinnedPosition, liveEdge."},"DA-PAUSE-AD-NO-ASSET":{category:"break",level:"warn",summary:"A pause break had no usable image or video asset (no first asset, unsupported media type, or no resolvable VAST creative); the pause ad was skipped."},"DA-PAUSE-AD-SSAI-UNSUPPORTED":{category:"session",level:"warn",summary:"Pause ads are SGAI-only and not supported in SSAI mode; the pause break was skipped."},"DA-MANIFEST-POLLED":{category:"manifest",level:"info",summary:"A manifest poll refresh succeeded (cadence follows the manifest polling config)."},"DA-AD-SKIPPED":{category:"playback",level:"info",summary:"The viewer skipped the active ad break (controls.skipOffset honored)."},"DA-AD-SKIP-SUPPRESSED":{category:"playback",level:"info",summary:"A skip request was suppressed (no skipOffset declared, or requested before the offset)."},"DA-AD-CLICKED":{category:"playback",level:"info",summary:"The viewer clicked the ad on screen (adclick emitted)."},"DA-LIVE-START-PUSHBACK":{category:"playback",level:"info",summary:"Initial live playback requested a backward seek to the configured target-duration distance. Context includes enabledBy (config or ptsSource), targetDurationSec, targetDurationSource, initialOffsetSec, initialOffsetTargetDurations, requestedOffsetSec, requestedOffsetTargetDurations, targetOffsetSec, targetOffsetTargetDurations, rewindSec, rewindTargetDurations, target and windowClamped. This is a request, not proof of the landing."},"DA-LIVE-START-PUSHBACK-SKIPPED":{category:"playback",level:"info",summary:"Initial live playback was left unchanged. The reason identifies a disabled adjustment (enabledBy says whether ptsSource or an explicit enabled decided it), an already sufficient offset, missing target duration or seekable range, invalid configuration, or no safe backward target. Available target-duration and offset measurements are included."},"DA-LIVE-START-PUSHBACK-LANDED":{category:"playback",level:"info",summary:"Measured initial-live seek landing. Context includes the requested target and targetDurationSec, landed, errorSec, liveEdgeAtLanding, landedOffsetSec and landedOffsetTargetDurations. A timeout or failed seek reports landed=null, never an inferred success."},"DA-RESUME-SEEK":{category:"playback",level:"info",summary:"Content was resume-seeked to the resolved post-break position (insertion type policy)."},"DA-RESUME-UNADDRESSABLE":{category:"playback",level:"warn",summary:"A break played through the content player (picture-in-picture), so content came back on a reloaded source whose timeline has its own origin, and that source published neither a program-date-time nor a seekable range to re-address the resume point against. Content stays where the reload left it — near the live edge — rather than being seeked to a position that does not exist on the new timeline. Context carries breakId, target (the position on the pre-borrow timeline) and offset."},"DA-RESUME-LANDED":{category:"playback",level:"info",summary:"Where the post-break resume-seek actually landed, measured on the seeked event rather than inferred: context carries breakId, target (the position requested), landed and errorSec (landed - target; negative means the player settled EARLIER than asked). landed is null with a reason when no seeked event arrived, which is normal for a seek to the position the playhead already holds. Report-only: the SDK does not correct the position."},"DA-RESUME-PREPOSITIONED":{category:"playback",level:"info",summary:"The break resumed without a seek: content was moved onto its resume position DURING the break, so the transition needed no jump. Context carries breakId, target, prepositionedTo, landed, shortfallSec and exact. exact=true means it reached the policy target. exact=false means the live window never published those frames, so content was moved as close as exists — the viewer lands short, but arrives already in place rather than via a visible seek at the cut."},"DA-RESUME-CATCHUP":{category:"playback",level:"info",summary:"Content began playing behind the ad to reach its resume point. Context carries breakId, startPos, target, remainingAdSec, publishedEnd and clampedStart — clampedStart true means the stream had not published the ideal start position, so playback began late and the alignment loop must make up the difference (the zero-live-headroom case). Its ABSENCE on a live break that resumed short means catch-up never ran at all, which is a different fault from it running and falling short."},"DA-RESUME-TARGET-CLAMPED":{category:"playback",level:"warn",summary:"The computed resume position sat outside the held live window and was clamped to the nearest end of it; context carries breakId, requested, clamped, shortfallSec and bound — 'end' when the target is ahead of the published edge, 'start' when it is behind the live window start (already evicted) — applied only when the gap is at most half the held window, otherwise DA-RESUME-START-CLAMP-SKIPPED is emitted instead. Distinct from DA-RESUME-OFFSET-CLAMPED, which shortens the OFFSET to the ad seconds actually played."},"DA-RESUME-START-CLAMP-SKIPPED":{category:"playback",level:"info",summary:"The resume target sat behind the element's live seekable start by more than half the held window, which cannot be DVR eviction (the element's seekable range disagrees with the adapter timeline); the target was left unchanged and the engine resolved the seek itself. Context carries breakId, requested, seekableStart, behindSec, windowSec and maxBehindSec."},"DA-RESUME-ALIGN-BLOCKED":{category:"playback",level:"warn",summary:"Resume alignment wanted to move content past the live edge and stood down, because no seek can reach media the stream has not published yet; content is left riding the edge and the break-end clamp places it. Context carries target, requested, safeEnd, shortfallSec and remainingSec. Emitted once per break. A persistent shortfall here means the resume target is further ahead than the feed's published edge — typically the player's view of the edge is stale, not that the seek is wrong."},"DA-CONTINUE-PLAYOUT-BEGIN":{category:"playback",level:"info",summary:"continueContentDuringBreak engaged: content keeps PLAYING through the break, hidden and muted, so no resume seek is needed. Context carries breakId, anchor, breakDurationSec and edgeDistanceSec."},"DA-CONTINUE-PLAYOUT-END":{category:"playback",level:"info",summary:"continueContentDuringBreak reached the cut. Context carries driftSec (content position minus where the break says it should be), maxDriftSec, the corrections applied, rateHonoured (false if the engine drove playbackRate itself) and driftUnrecoverable."},"DA-CONTINUE-PLAYOUT-REFUSED":{category:"playback",level:"info",summary:"continueContentDuringBreak was not used this session, so breaks pause content and resume with a seek as before. Emitted once per session; context carries the reason (disabled, not-replacement, format, shared-element, picture-in-picture, single-decoder) and the break format. Its ABSENCE on an eligible session is the signal the mode engaged."},"DA-CONTINUE-PLAYOUT-QUALITY-UNAVAILABLE":{category:"playback",level:"warn",summary:"Content continues through the replacement break without a video-quality constraint, so the content stream may retain its normal bitrate alongside the ad. Context carries breakId and reason (unsupported when the optional Web adapter method is absent, not-applied when the adapter returned false or could not apply the request)."},"DA-CONTINUE-PLAYOUT-DRIFT":{category:"playback",level:"warn",summary:"Content drifted further from the break timeline than the remaining break can remove within the playback-rate bounds, so part of it is carried into the cut. Context carries driftSec, remainingSec, the rate applied and seekIssued (always false: a corrective seek would be clipped)."},"DA-CONTINUE-PLAYOUT-ABANDONED":{category:"playback",level:"warn",summary:"Content could not be kept playing through the break, so it reverted to the pause-and-resume path mid-break. Context carries breakId, the reason and the driftSec at the moment it converted."},"DA-AD-AV-DESYNC":{category:"playback",level:"warn",summary:"The ad player's audio sink was handed a buffer whose timestamp does not continue the audio it has already been fed, so the media clock had to be re-anchored mid-ad. Video is scheduled off that clock while the audio already queued in the output track keeps draining, so every re-anchor pushes the picture further from the sound actually being heard. Context carries breakId, assetId, expectedSec, actualSec, deltaSec (negative = audio running behind the picture) and positionSec. Seen on server-stitched pods whose per-ad audio and video durations do not match; a single event near the end of a pod is the accumulated total, not an isolated glitch."},"DA-AD-PLAYOUT-SYNC":{category:"playback",level:"info",summary:"Per-break summary of ad playout health, emitted once at break end. Context carries podUri (the resolved ad media, so a stitched pod can be fetched and inspected), desyncEvents, maxDesyncSec, droppedFrames, audioUnderruns, audioFormats and videoFormats (the distinct decoder input formats seen during the break — more than one means the stitched stream changed sample rate or codec mid-pod) and frameOffsetMeanMs (mean video frame processing offset; large negative values mean frames were released late against the audio clock)."},"DA-EVENT":{category:"event",level:"info",summary:"An SDK event, recorded into the diagnostic ring buffer so exportDiagnostics() carries one unified timeline of diagnostics and playback events. Raised to error for aderror. Buffer-only: not dispatched to onDiagnostic handlers, which would duplicate the event stream they already receive."},"DA-BREAK-CONTENT-MASK":{category:"break",level:"warn",summary:"The host's content surface cannot follow view transforms (punch-through SurfaceView, e.g. react-native-video's default), so the two-box format masks the backdrop with a transparent hole over the content box instead of reframing the content view. context: format."},"DA-BREAK-FORMAT-DEGRADED":{category:"break",level:"warn",summary:"Split break reframing degraded: the host supplied no content view or sibling container for the ad."},"DA-BREAK-NO-PLAYABLE-ASSET":{category:"break",level:"warn",summary:"A break had nothing to play, so it never began: no adbreakbegin/adbreakend was emitted, content kept playing, and a public aderror (source ad, carrying the break) reports it. context.reason says why: no-variant (none declared), no-qualifying-variant (variant selection - device targeting + format playability - matched nothing and no downgrade applied), no-assets (the selected variant was empty), or lshape-content-skipped (shared-element insertion cannot render a backdrop). This is the BREAK-level outcome; when a particular variant was passed over for an unrecognised format, DA-BREAK-VARIANT-FORMAT-UNKNOWN names that format alongside it. context: breakId, reason, declaredAssetCount, format."},"DA-BREAK-VARIANT-FORMAT-UNKNOWN":{category:"break",level:"warn",summary:"A break variant declares a format this SDK version does not recognise, so it was passed over during variant selection rather than guessed at - an unknown format is never playable, because rendering it as a fullscreen single would be the most invasive possible misreading. Raised once per skipped variant: a break that still has a playable variant plays it and reports this too, so the skip is never silent, and a break left with nothing also reports DA-BREAK-NO-PLAYABLE-ASSET with reason no-qualifying-variant. An ABSENT format is treated identically to an unrecognised one. context: breakId, format (the raw manifest string; empty when the field was absent)."},"DA-AD-STALLED":{category:"playback",level:"warn",summary:"An ad began playing and then stopped advancing: the playhead did not move for the stall threshold while the ad was meant to be playing. context: assetId, breakId, playbackState, stalledForMs, positionMs, bufferedAheadMs, reason."},"DA-AD-FOREGROUND-RESUMED":{category:"playback",level:"info",summary:"An in-flight ad resumed after the app returned to the foreground; context carries the suspended duration and ad position at resume."},"DA-AD-FOCUS-LOST":{category:"playback",level:"warn",summary:"The overlay ad lost permanent audio focus during an active break; the host player must not reclaim focus while the SDK ad is on screen. context: breakId, transient, reason."},"DA-AD-FOCUS-GRANTED":{category:"playback",level:"info",summary:"The overlay ad was granted media audio focus for the break, so system focus semantics (call, duck, permanent loss) apply to ad playback. context: breakId, cause, alreadyHeld."},"DA-AD-FOCUS-DENIED":{category:"playback",level:"warn",summary:"The platform refused the overlay ad's media audio-focus request, so the break plays with no focus of its own: another app's audio can mix over the ad, and a call can neither duck nor pause it. context: breakId, cause."},"DA-AD-FOCUS-ABANDONED":{category:"playback",level:"info",summary:"The overlay ad gave media audio focus back, so the content player's own focus request finds a clean stack. context: breakId, cause."},"DA-BREAK-ABANDONED":{category:"lifecycle",level:"warn",summary:"A break was still in flight when the session was torn down (endSession, destroy, or a startSession over an active session). context: breakId, cause, phase, unbalancedAdBegin, adIndex, totalAds, assetId."},"DA-RENDERER-UNAVAILABLE":{category:"lifecycle",level:"error",summary:"The renderer could not render a break because a required piece of it was not attached (e.g. no ad player), after the SDK had already emitted adbreakbegin — so the break began and will never end. context: breakId, missing."},"DA-SESSION-STARTING":{category:"session",level:"info",summary:"A step of startSession() was entered: begin, manifest-fetch, gam-init or scheduling. Emitted on entry, so the last one recorded names the step a hung startSession never finished. context: step, manifestUrl, elapsedMs. The URL is reported verbatim; the redacted config summary carries only its origin (config.manifestOrigin)."}};
1
+ export const DIAGNOSTIC_CODES={"DA-SESSION-STARTED":{category:"session",level:"info",summary:"Monetization session started; manifest polling began. context: manifestUrl (stitcherUrl in SSAI mode), reported verbatim."},"DA-SESSION-ENDED":{category:"session",level:"info",summary:"Monetization session ended; polling and scheduling stopped."},"DA-ASSET-PARAMETERS-UPDATED":{category:"session",level:"info",summary:"The break manifest's session-level asset parameters changed; the merged parameters were pushed to the active GAM stream. context: source ('manifest'), keys (parameter names only, never values)."},"DA-MANIFEST-FETCH-FAILED":{category:"manifest",level:"error",summary:"Initial break-manifest fetch failed; the session could not start."},"DA-MANIFEST-POLL-FAILED":{category:"manifest",level:"warn",summary:"A manifest poll failed; the SDK keeps the last good manifest and retries."},"DA-MANIFEST-CHANNEL-CHANGED":{category:"manifest",level:"info",summary:"A polled manifest describes a different ads channel (channelId, GAM identity or timebase changed); the SDK re-aligned its ad setup and resolved delivery mode again while the session and content playback continued. context: previousChannelId, channelId, reason, manifestUrl."},"DA-MANIFEST-INTERCEPT-FAILED":{category:"manifest",level:"warn",summary:"The customer manifest-response interceptor threw; the un-modified parsed manifest was used instead."},"DA-MANIFEST-REQUEST-INTERCEPT-FAILED":{category:"manifest",level:"warn",summary:"The customer manifest-request interceptor threw; the normal network fetch of the original URL was used instead."},"DA-MANIFEST-SIGNATURE-INVALID":{category:"manifest",level:"error",summary:"The break-manifest response failed detached-JWS signature verification (missing/malformed X-Manifest-Signature, unsupported alg, unknown kid, unknown critical param, or signature mismatch); the manifest was rejected and no breaks were scheduled. context: url, reason."},"DA-PDT-MISSING":{category:"playback",level:"warn",summary:"No EXT-X-PROGRAM-DATE-TIME once content is playing (or after the startup backstop window); wallclock-timebase breaks fall back to the system clock."},"DA-ANVATO-CUE-PENDING":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — no Anvato in-stream cue observed yet for a PTS break; the break stays pending until its cue arrives."},"DA-ANVATO-CUE-MATCHED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — a PTS break's start was matched to an observed Anvato cue and scheduled at the cue's media time."},"DA-ANVATO-CUE-ENTERED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — a break was started by the cue reaching the playhead rather than by the scheduler's 250ms tick; context carries the breakId, the cue pts and the media time it fired at, so the two start paths are distinguishable in the field."},"DA-ANVATO-CUE-OBSERVED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — an Anvato break-signaling (type=cue) frame was observed in the stream; context carries the cue's pts, the media time it landed at, whether the tracker recorded it, and the raw payload — so a manifest-PTS vs in-stream-PTS misalignment is observable in the field."},"DA-ANVATO-CUE-SEGMENT-ANCHORED":{category:"break",level:"warn",summary:"ptsSource: 'anvatoCue' — an Anvato emsg cue arrived without a ptsOffset from the adapter, so its break is scheduled at the cue's carrying segment start, which can be up to one segment early. Emitted once per session; context: pts, mediaTime."},"DA-ANVATO-CUE-OFFSET-REJECTED":{category:"break",level:"warn",summary:"ptsSource: 'anvatoCue' — the adapter's ptsOffset placed an Anvato cue outside its carrying segment's window (more than 0.1s before or 15s after the cue startTime), so the cue's startTime is used instead. Emitted once per cue pts; context: pts, startTime, ptsOffset, mappedTime."},"DA-ANVATO-CUE-END-MATCHED":{category:"break",level:"info",summary:"ptsSource: 'anvatoCue' — the active break's Anvato type=cue_end was observed and its length on the stream clock (cue_end pts minus the break start pts) is within 2s of the break duration. Emitted once per break; context: breakId, mediaTime (where the player reported the cue_end), lengthSec, durationSec."},"DA-ANVATO-CUE-END-REJECTED":{category:"break",level:"warn",summary:"ptsSource: 'anvatoCue' — an Anvato type=cue_end was observed for the active break but its stream-clock length differs from the break duration by more than 2s, so it is ignored and the resume keeps its computed target. Emitted once per break; context: breakId, mediaTime, lengthSec, durationSec."},"DA-PRELOAD-FAILED":{category:"preload",level:"warn",summary:"Ad preload failed; the asset will be loaded on demand at break start."},"DA-PRELOAD-MODE-RESOLVED":{category:"preload",level:"info",summary:"The configured ad preload mode was resolved for this session; context carries both the configured and the resolved mode."},"DA-PRELOAD-PATH":{category:"preload",level:"info",summary:"The preload path actually taken for a break's ad (parallel buffer / detached prefetch / none) and the creative container (stream vs progressive)."},"DA-BREAK-EARLY-RETURN":{category:"break",level:"info",summary:"The active break was removed from a polled manifest (early return); the break ends immediately and content resumes at break start plus the seconds already played."},"DA-BREAK-WINDOW-ESCAPED":{category:"break",level:"warn",summary:"An active wallclock break outlived its window on the stream clock (ad stall, bogus trigger position, or a re-fired completed break); the SDK ended it and returned to content. context.overrunSec says by how much."},"DA-BREAK-EVENT-UNSUPPORTED":{category:"break",level:"warn",summary:"A break is triggered by a spec event this SDK version does not schedule on this platform (web schedules `start`, `pause` and `end`; Android and iOS do not schedule `end` yet); the break was ignored. context.event names the event."},"DA-BREAK-SUPPRESSED-OVERLAP":{category:"break",level:"warn",summary:"A break was suppressed because an ad was already playing."},"DA-BREAK-TRANSITION":{category:"break",level:"info",summary:"Measured duration of a playback transition into an ad break, between two ads, between chained breaks, or back to content."},"DA-AD-SURFACE-REVEALED":{category:"break",level:"info",summary:"The ad surface became visible: how long it was held back waiting for the ad's first frame, and whether it was revealed because that frame arrived or because the wait timed out."},"DA-PREROLL-CONTENT-HELD":{category:"break",level:"info",summary:"Content playback was held at session start until a pending pre-roll began, so no content is shown before the ad."},"DA-PREROLL-CONTENT-WAIT-TIMEOUT":{category:"break",level:"info",summary:"A pending pre-roll began after content readiness was not reported within the wait timeout."},"DA-PREROLL-CANCELLED-CONTENT-ERROR":{category:"break",level:"warn",summary:"A pending pre-roll was cancelled because the content failed to load before it could begin."},"DA-SHARED-ELEMENT-UNSUPPORTED":{category:"break",level:"warn",summary:"Configured shared-element insertion is unsupported on this platform (non-iPhone/iPod); fell back to overlay insertion."},"DA-SHARED-ELEMENT-RESTORE-FAILED":{category:"playback",level:"error",summary:"Content did not resume after a shared-element break: the reload/seek/play restore failed twice; the viewer is left paused on the handed-back element."},"DA-IMAGE-LOAD-FAILED":{category:"break",level:"warn",summary:"An image (companion, backdrop or image ad) could not be fetched or decoded within the timeout; the break continues without it."},"DA-PIP-TRANSFER-FAILED":{category:"break",level:"warn",summary:"The picture-in-picture window could not be moved between the content and ad elements; the break continues but the viewer may not see the ad in the PiP window."},"DA-PIP-AUTODETECT-UNAVAILABLE":{category:"break",level:"warn",summary:"No Activity could be resolved from the renderer's Context or the overlay's view tree, so picture-in-picture cannot be detected automatically; the host must call OptiViewAds.setPictureInPicture() from Activity.onPictureInPictureModeChanged or breaks will be laid out for a fullscreen surface. Android only."},"DA-CONTENT-ELEMENT-SWAPPED":{category:"break",level:"info",summary:"The content player replaced its <video> element; the SDK re-bound its presentation listeners to the new one."},"DA-PIP-FORMAT-OVERRIDE":{category:"break",level:"info",summary:"The content player is in picture-in-picture, so the break's declared format was overruled and it plays as a single fullscreen ad."},"DA-PIP-ADOPTION-STATE":{category:"break",level:"info",summary:"Native PiP reconciliation deferred or reused a layout/handoff decision. Context carries reason, active, adPlaying, applied, and asset/break IDs when available; this is not evidence that a format override occurred."},"DA-CHAIN-RESOLVER-ERROR":{category:"chaining",level:"warn",summary:"The chained-successor resolver threw; chaining was skipped for this break."},"DA-GAM-NO-ASSET-KEY":{category:"gam",level:"warn",summary:"Retired: the GAM stream identity now comes from the manifest's vendorConfiguration. Kept declared so the code is never reused; see DA-GAM-CONFIG-MISSING."},"DA-GAM-SESSION-FAILED":{category:"gam",level:"error",summary:"The GAM/IMA session failed to initialize; GAM breaks will not serve."},"DA-GAM-CONFIG-RESOLVED":{category:"gam",level:"info",summary:"The GAM stream identity for this session was resolved from the manifest's vendorConfiguration."},"DA-GAM-CONFIG-MISSING":{category:"gam",level:"error",summary:'The break manifest carries no usable "gam" vendorConfiguration entry; GAM assets are skipped.'},"DA-GAM-POD-IDENTITY-MISMATCH":{category:"gam",level:"error",summary:"A GAM pod asset's vendorParameters name a different network code or custom asset key than the stream session was created with; the asset is skipped because the pod request cannot serve."},"DA-GAM-POD-MID-BREAK-END":{category:"gam",level:"warn",summary:"IMA reported the ad break ended before the pod's last ad while pod stream remains; per-ad reporting continues until the pod ends."},"DA-VENDOR-CONFIG-UNKNOWN-TYPE":{category:"manifest",level:"info",summary:"One or more vendorConfiguration entries declare a type this SDK version does not recognise and were ignored."},"DA-CONTENT-PLAYBACK-ERROR":{category:"playback",level:"error",summary:"The content player reported a playback error."},"DA-CONTENT-RESUME-STALLED":{category:"playback",level:"warn",summary:"Content did not resume within the watchdog window after a break that paused it ended; the SDK re-issued play() once. iOS only for now."},"DA-CONTENT-RECOVERY-MODE-RESOLVED":{category:"playback",level:"info",summary:"The resolved post-break content recovery mode for the session (recreate or none); context carries configured and resolved."},"DA-CONTENT-PIPELINE-RECREATED":{category:"playback",level:"info",summary:"The content player's media pipeline was rebuilt at break end before content resumed (recovery mode recreate); context carries breakId, startTime and durationMs."},"DA-CONTENT-PIPELINE-RECREATE-FAILED":{category:"playback",level:"warn",summary:"Rebuilding the content media pipeline at break end failed or timed out — or the adapter does not implement recreateMediaPipeline() (reason 'unsupported-adapter', e.g. a wrapper adapter that does not forward it); the SDK fell back to resuming in place with seek + play; context carries breakId, startTime, reason."},"DA-AD-PLAYBACK-ERROR":{category:"playback",level:"error",summary:"The ad player reported a playback error during a break."},"DA-AD-LOAD-RETRIED":{category:"playback",level:"warn",summary:'The ad player\'s load() had not settled within the retry window of the ad-start budget and the ad element showed no progress (readyState 0, nothing buffered), so a second load() was issued for the same URI; a slow-but-progressing load is not retried. Context carries breakId, assetId, uri, elapsedMs, remainingBudgetMs. A still-stalled retry ends as DA-AD-PLAYBACK-ERROR "Ad load timeout".'},"DA-AD-URI-MISSING":{category:"playback",level:"error",summary:"The ad asset had no usable media URI, VAST tag URL or render surface; reported as CMCD adec."},"DA-AD-MEDIA-LOAD-FAILED":{category:"playback",level:"error",summary:"The ad player could not fetch the ad media (network or HTTP failure); reported as CMCD adec."},"DA-AD-MEDIA-UNSUPPORTED":{category:"playback",level:"error",summary:"The ad player could not decode the ad media or does not support its format; reported as CMCD adec."},"DA-AD-START-TIMEOUT":{category:"playback",level:"error",summary:"The ad did not load, render a first frame or start within its start budget; reported as CMCD adec."},"DA-AD-START-INTERRUPTED":{category:"playback",level:"warn",summary:"The ad element's play() was interrupted by a browser-initiated pause before the ad started (Chromium AbortError, seen on Samsung Tizen); the SDK re-issued play() once. context: breakId, error."},"DA-AD-DURATION-PREPARED":{category:"playback",level:"info",summary:"The ad media for a break was prepared and its real playable duration is now known, BEFORE the first frame. context: breakId, assetId, index, total, preparedDurationSec (the loaded media's own duration — on a GAM pod, the stitched pod's length), declaredDurationSec (what the manifest said about this asset, when it said anything) and breakDurationSec (the slot the break declares). Emitted per asset, so a multi-asset break reports one per asset and the break total is their sum. The three together separate a short break caused by a short POD from one caused by a short request or a late join."},"DA-DELIVERY-MODE-RESOLVED":{category:"session",level:"info",summary:"Delivery mode (sgai/ssai) resolved for the session at start and again on an ads-channel switch from the manifest's delivery rules (or the explicit client config)."},"DA-DELIVERY-MODE-UNKNOWN":{category:"session",level:"warn",summary:"The matching delivery rule carried an unrecognized mode value; sgai is used (forward compatibility)."},"DA-DELIVERY-MODE-OVERRIDDEN":{category:"session",level:"info",summary:"The manifest's delivery rules resolved a different mode, but the explicit client config takes precedence."},"DA-DELIVERY-MODE-CHANGE-IGNORED":{category:"session",level:"warn",summary:"An ordinary manifest poll resolves a different delivery mode; the mode pinned for the session stays in force. An ads-channel switch resolves the mode again."},"DA-SSAI-UNAVAILABLE":{category:"session",level:"error",summary:"The manifest selected ssai delivery but no vendor configuration can provide a stitched stream (no gam entry with an assetKey); at start the session fails, while on a channel switch the session stays in sgai."},"DA-SSAI-SESSION-FAILED":{category:"session",level:"error",summary:"The SSAI session failed to start (IMA stream init, stream id, or stitched-stream load)."},"DA-SSAI-IMA-ERROR":{category:"gam",level:"error",summary:"IMA reported an error during the SSAI stream session."},"DA-INSERTION-TYPE-RESOLVED":{category:"session",level:"info",summary:"Per-session ad insertion type resolved, and whether the integrator set it or left it unset (unset lets the manifest's resumeOffset drive the resume point)."},"DA-RESUME-OFFSET-CLAMPED":{category:"break",level:"info",summary:"The resume offset was shortened to the ad duration actually played, so the break could not skip further than the ads it delivered."},"DA-INSERTION-TYPE-IGNORED-SSAI":{category:"session",level:"warn",summary:"adInsertionType is ignored in SSAI mode; the stitcher controls ad insertion server-side."},"DA-VAST-UNSUPPORTED-FORMAT":{category:"break",level:"warn",summary:"A VAST asset appeared in an unsupported break format; VAST is only supported in single, double, and lshape_ad. The break was skipped."},"DA-ASSET-MACRO-UNKNOWN":{category:"break",level:"warn",summary:"An asset parameter value contained a macro the SDK has no value for (an unknown or unavailable OptiView macro, or a registered customer macro that returned no value); the parameter was still sent, with the macro kept as its literal token. Raised once per parameter key and macro. context: key, macro, breakId, assetId."},"DA-ASSET-PARAMETER-OMITTED":{category:"break",level:"info",summary:"An asset parameter value contained a customer macro that is empty (value `null`), so the parameter was not sent; for GAM `cust_params` only the `&`-separated pair containing the macro was dropped. Raised once per parameter key and macro (per dropped pair for GAM `cust_params`). context: key, macro, pair (GAM `cust_params` only), breakId, assetId."},"DA-VAST-SSAI-UNSUPPORTED":{category:"session",level:"warn",summary:"VAST assets are not supported in SSAI mode (VAST is SGAI-only); the asset was skipped."},"DA-VAST-IMA-ERROR":{category:"gam",level:"error",summary:"Google IMA reported an error while loading or playing a VAST (client-side / CSAI) ad."},"DA-VAST-NO-FILL":{category:"gam",level:"error",summary:"The VAST ad server returned no ad (empty response, no ads after wrappers or no assets); reported as CMCD adec."},"DA-VAST-TIMEOUT":{category:"gam",level:"error",summary:"The VAST response or its media file did not load in time; reported as CMCD adec."},"DA-VAST-MALFORMED":{category:"gam",level:"error",summary:"The VAST response could not be parsed or uses an unsupported VAST version; reported as CMCD adec."},"DA-VAST-REQUEST-FAILED":{category:"gam",level:"error",summary:"The VAST ad request failed (network error, invalid tag URL, wrapper error or too many redirects); reported as CMCD adec."},"DA-VAST-CREATIVE-FAILED":{category:"gam",level:"error",summary:"The VAST creative could not be played (no compatible media file, playback error or trafficking error); reported as CMCD adec."},"DA-VAST-IMA-SDK-MISSING":{category:"gam",level:"error",summary:"The Google IMA client-side SDK (ima3.js) is unavailable; VAST (CSAI) ads cannot be played."},"DA-PAUSE-AD-SHOWN":{category:"break",level:"info",summary:"A pause ad (full-screen image or video) was shown while content is paused."},"DA-PAUSE-AD-DISMISSED":{category:"break",level:"info",summary:"A pause ad was dismissed (content resumed, or the duration cap elapsed)."},"DA-PAUSE-AD-RESUME-ALLOWED":{category:"break",level:"info",summary:"The viewer may now resume content over the shown pause ad: the break's controls.skipOffset elapsed, or (no skipOffset) the ad was watched fully: a video creative ended, an image reached its duration cap or has none. context: breakId."},"DA-PAUSE-AD-RESUME-BLOCKED":{category:"break",level:"info",summary:"Content tried to resume while a pause ad must still be watched (controls.skipOffset not reached, or no skipOffset and the video creative has not ended / the image duration cap has not elapsed); the SDK keeps content paused. context: breakId, elapsedSec, skipOffset."},"DA-PAUSE-AD-DVR-EXPIRED":{category:"break",level:"info",summary:"The viewer paused for longer than the DVR window is deep, so the position they paused at aged out and playback resumed at the live edge instead. context: pinnedPosition, liveEdge."},"DA-PAUSE-AD-NO-ASSET":{category:"break",level:"warn",summary:"A pause break had no usable image or video asset (no first asset, unsupported media type, or no resolvable VAST creative); the pause ad was skipped."},"DA-PAUSE-AD-SSAI-UNSUPPORTED":{category:"session",level:"warn",summary:"Pause ads are SGAI-only and not supported in SSAI mode; the pause break was skipped."},"DA-MANIFEST-POLLED":{category:"manifest",level:"info",summary:"A manifest poll refresh succeeded (cadence follows the manifest polling config)."},"DA-AD-SKIPPED":{category:"playback",level:"info",summary:"The viewer skipped the active ad break (controls.skipOffset honored)."},"DA-AD-SKIP-SUPPRESSED":{category:"playback",level:"info",summary:"A skip request was suppressed (no skipOffset declared, or requested before the offset)."},"DA-AD-CLICKED":{category:"playback",level:"info",summary:"The viewer clicked the ad on screen (adclick emitted)."},"DA-LIVE-START-PUSHBACK":{category:"playback",level:"info",summary:"Initial live playback requested a backward seek to the configured target-duration distance. Context includes enabledBy (config or ptsSource), targetDurationSec, targetDurationSource, initialOffsetSec, initialOffsetTargetDurations, requestedOffsetSec, requestedOffsetTargetDurations, targetOffsetSec, targetOffsetTargetDurations, rewindSec, rewindTargetDurations, target and windowClamped. This is a request, not proof of the landing."},"DA-LIVE-START-PUSHBACK-SKIPPED":{category:"playback",level:"info",summary:"Initial live playback was left unchanged. The reason identifies a disabled adjustment (enabledBy says whether ptsSource or an explicit enabled decided it), an already sufficient offset, missing target duration or seekable range, invalid configuration, or no safe backward target. Available target-duration and offset measurements are included."},"DA-LIVE-START-PUSHBACK-LANDED":{category:"playback",level:"info",summary:"Measured initial-live seek landing. Context includes the requested target and targetDurationSec, landed, errorSec, liveEdgeAtLanding, landedOffsetSec and landedOffsetTargetDurations. A timeout or failed seek reports landed=null, never an inferred success."},"DA-RESUME-SEEK":{category:"playback",level:"info",summary:"Content was resume-seeked to the resolved post-break position (insertion type policy)."},"DA-RESUME-UNADDRESSABLE":{category:"playback",level:"warn",summary:"A break played through the content player (picture-in-picture), so content came back on a reloaded source whose timeline has its own origin, and that source published neither a program-date-time nor a seekable range to re-address the resume point against. Content stays where the reload left it — near the live edge — rather than being seeked to a position that does not exist on the new timeline. Context carries breakId, target (the position on the pre-borrow timeline) and offset."},"DA-RESUME-LANDED":{category:"playback",level:"info",summary:"Where the post-break resume-seek actually landed, measured on the seeked event rather than inferred: context carries breakId, target (the position requested), landed and errorSec (landed - target; negative means the player settled EARLIER than asked). errorSec only says whether the SEEK did what it was asked: when the live-window clamp moved the seek, policyTarget is the resume point before the clamp and policyErrorSec (landed - policyTarget) is how far the viewer really is from it. landed is null with a reason when no seeked event arrived, which is normal for a seek to the position the playhead already holds. Report-only: the SDK does not correct the position."},"DA-RESUME-PREPARED":{category:"playback",level:"info",summary:"Android, live break that resumes at its end — the paused content was parked exactly on the resume point before the hand-back, so the hand-back only plays (DA-RESUME-SEEK then reports prepared=true and issues no seek). Context carries breakId, target, source (cue_end when the stream's matched type=cue_end was known, else cue+duration) leadMs (how long before the expected hand-back it was parked) and refresh (true when content parked long before the hand-back was seeked onto the same point again, 4.5s before it). A later cue_end parks content again."},"DA-RESUME-PREPOSITIONED":{category:"playback",level:"info",summary:"The break resumed without a seek: content was moved onto its resume position DURING the break, so the transition needed no jump. Context carries breakId, target, prepositionedTo, landed, shortfallSec and exact. exact=true means it reached the policy target. exact=false means the live window never published those frames, so content was moved as close as exists — the viewer lands short, but arrives already in place rather than via a visible seek at the cut."},"DA-RESUME-PTS-MAP":{category:"playback",level:"info",summary:"ptsSource: 'anvatoCue', iOS/tvOS and web — the live resume point was mapped onto currentTime through the stream's own clock: the Anvato type=beacon tags delivered since the run-up's last seek give the currentTime ↔ stream-clock offset, and the resume point (the matched cue_end, else the cue plus the break duration) is converted with it. Reported when a mapping is first available after a seek and whenever the mapped target moves by 0.1s or more. Context carries breakId, target, landingStreamSec, landingSource (cue_end or cue+duration), offsetSec, beacons (beacons averaged), generation (how often the mapping started over since the session began), currentTime, and computedTarget with deltaSec (target - computedTarget) when a currentTime-based target exists."},"DA-RESUME-PTS-REMAP":{category:"playback",level:"warn",summary:"ptsSource: 'anvatoCue', iOS/tvOS and web — a stream beacon disagreed with the currentTime ↔ stream-clock mapping by more than 0.2s, so the player re-anchored currentTime (a variant switch or a buffer restart); the mapping starts over from that beacon and the resume point is mapped again. Reported during the resume run-up and after the hand-back. Context carries breakId, fromOffsetSec, toOffsetSec, deltaSec, currentTime and stage (run-up or after-hand-back)."},"DA-RESUME-PTS-CORRECTED":{category:"playback",level:"info",summary:"ptsSource: 'anvatoCue', iOS/tvOS and web — once per break at the hand-back, on a stream that carries Anvato beacons: whether the stream clock placed the live resume point, and by how much it moved it. applied=true: streamClockTarget is the resume point mapped through the beacons, correctionSec is streamClockTarget - computedTarget (the currentTime target, cue plus duration), and currentTimeShiftSec is how far the same stream instant moved in currentTime between the pause and the hand-back (negative: it now sits earlier), null when no beacon mapped the stream before the pause. Context also carries breakId, landingSource (cue_end or cue+duration), landingStreamSec, offsetSec, beacons, remaps (DA-RESUME-PTS-REMAP during the break) and cueEndTarget when a cue_end was matched. applied=false with a reason means no beacon arrived after the run-up's last seek, so the cue_end or currentTime target applied."},"DA-RESUME-PTS-LANDED":{category:"playback",level:"info",summary:"ptsSource: 'anvatoCue', iOS/tvOS and web — where a stream-clock resume landed, measured on the stream's own clock from the beacons delivered after the hand-back: landedStreamSec is the position content resumed from (resumedAt, the seek landing or the playhead at a seek-free hand-back) converted with that mapping, and errorSec is landedStreamSec - landingStreamSec (negative: content resumed before the stream's resume point, so slate is shown). Context carries breakId, landingStreamSec, landingSource, resumedAt, sinceHandBackSec and, when measured, landedStreamSec, errorSec, offsetSec and beacons; reason when no beacon arrived within 15s. Report-only: the SDK does not correct the position from it."},"DA-RESUME-CUE-END":{category:"playback",level:"info",summary:"ptsSource: 'anvatoCue', iOS/tvOS, web and Android — the stream's matched type=cue_end replaced the computed resume target: the slate under the ad ends there, not at cue plus the advertised duration (150.206s for a 150s break on NFL Channel), and the player can remap its timeline while content is held, so the cue_end is reported in the current mapping. Context carries breakId, computedTarget, cueEndTarget, deltaSec (cueEndTarget - computedTarget), stage (hold, playing or hand-back; Android: always hand-back) and corrected (whether an in-buffer correction seek ran). Only a policy that resumes at the break end is replaced; otherwise applied=false and only the delta is reported."},"DA-RESUME-CUE-END-LATE":{category:"playback",level:"info",summary:"ptsSource: 'anvatoCue', iOS/tvOS and Android — the break's type=cue_end was matched only after the hand-back. When it is more than 1s ahead of the playhead and buffered, content is seeked forward to it once (corrected=true); content is never seeked backward. Context carries breakId, cueEndTarget, currentTime, deltaSec (cueEndTarget - currentTime) and corrected."},"DA-RESUME-CATCHUP":{category:"playback",level:"info",summary:"Content began playing behind the ad to reach its resume point. Context carries breakId, startPos, target, remainingAdSec, publishedEnd and clampedStart — clampedStart true means the stream had not published the ideal start position, so playback began late and the alignment loop must make up the difference (the zero-live-headroom case). Its ABSENCE on a live break that resumed short means catch-up never ran at all, which is a different fault from it running and falling short."},"DA-RESUME-TARGET-CLAMPED":{category:"playback",level:"warn",summary:"The computed resume position sat outside the held live window and was clamped to the nearest end of it; context carries breakId, requested, clamped, shortfallSec and bound — 'end' when the target is ahead of the published edge, 'start' when it is behind the live window start (already evicted) — applied only when the gap is at most half the held window, otherwise DA-RESUME-START-CLAMP-SKIPPED is emitted instead. Distinct from DA-RESUME-OFFSET-CLAMPED, which shortens the OFFSET to the ad seconds actually played."},"DA-RESUME-START-CLAMP-SKIPPED":{category:"playback",level:"info",summary:"The resume target sat behind the element's live seekable start by more than half the held window, which cannot be DVR eviction (the element's seekable range disagrees with the adapter timeline); the target was left unchanged and the engine resolved the seek itself. Context carries breakId, requested, seekableStart, behindSec, windowSec and maxBehindSec."},"DA-RESUME-ALIGN-BLOCKED":{category:"playback",level:"warn",summary:"Resume alignment wanted to move content past the live edge and stood down, because no seek can reach media the stream has not published yet; content is left riding the edge and the break-end clamp places it. Context carries target, requested, safeEnd, shortfallSec and remainingSec. Emitted once per break. A persistent shortfall here means the resume target is further ahead than the feed's published edge — typically the player's view of the edge is stale, not that the seek is wrong."},"DA-CONTINUE-PLAYOUT-BEGIN":{category:"playback",level:"info",summary:"continueContentDuringBreak engaged: content keeps PLAYING through the break, hidden and muted, so no resume seek is needed. Context carries breakId, anchor, breakDurationSec and edgeDistanceSec."},"DA-CONTINUE-PLAYOUT-END":{category:"playback",level:"info",summary:"continueContentDuringBreak reached the cut. Context carries driftSec (content position minus where the break says it should be), maxDriftSec, the corrections applied, rateHonoured (false if the engine drove playbackRate itself) and driftUnrecoverable."},"DA-CONTINUE-PLAYOUT-REFUSED":{category:"playback",level:"info",summary:"continueContentDuringBreak was not used this session, so breaks pause content and resume with a seek as before. Emitted once per session; context carries the reason (disabled, not-replacement, format, shared-element, picture-in-picture, single-decoder) and the break format. Its ABSENCE on an eligible session is the signal the mode engaged."},"DA-CONTINUE-PLAYOUT-QUALITY-UNAVAILABLE":{category:"playback",level:"warn",summary:"Content continues through the replacement break without a video-quality constraint, so the content stream may retain its normal bitrate alongside the ad. Context carries breakId and reason (unsupported when the optional Web adapter method is absent, not-applied when the adapter returned false or could not apply the request)."},"DA-CONTINUE-PLAYOUT-DRIFT":{category:"playback",level:"warn",summary:"Content drifted further from the break timeline than the remaining break can remove within the playback-rate bounds, so part of it is carried into the cut. Context carries driftSec, remainingSec, the rate applied and seekIssued (always false: a corrective seek would be clipped)."},"DA-CONTINUE-PLAYOUT-ABANDONED":{category:"playback",level:"warn",summary:"Content could not be kept playing through the break, so it reverted to the pause-and-resume path mid-break. Context carries breakId, the reason and the driftSec at the moment it converted."},"DA-AD-AV-DESYNC":{category:"playback",level:"warn",summary:"The ad player's audio sink was handed a buffer whose timestamp does not continue the audio it has already been fed, so the media clock had to be re-anchored mid-ad. Video is scheduled off that clock while the audio already queued in the output track keeps draining, so every re-anchor pushes the picture further from the sound actually being heard. Context carries breakId, assetId, expectedSec, actualSec, deltaSec (negative = audio running behind the picture) and positionSec. Seen on server-stitched pods whose per-ad audio and video durations do not match; a single event near the end of a pod is the accumulated total, not an isolated glitch."},"DA-AD-PLAYOUT-SYNC":{category:"playback",level:"info",summary:"Per-break summary of ad playout health, emitted once at break end. Context carries podUri (the resolved ad media, so a stitched pod can be fetched and inspected), desyncEvents, maxDesyncSec, droppedFrames, audioUnderruns, audioFormats and videoFormats (the distinct decoder input formats seen during the break — more than one means the stitched stream changed sample rate or codec mid-pod) and frameOffsetMeanMs (mean video frame processing offset; large negative values mean frames were released late against the audio clock)."},"DA-EVENT":{category:"event",level:"info",summary:"An SDK event, recorded into the diagnostic ring buffer so exportDiagnostics() carries one unified timeline of diagnostics and playback events. Raised to error for aderror. Buffer-only: not dispatched to onDiagnostic handlers, which would duplicate the event stream they already receive."},"DA-BREAK-CONTENT-MASK":{category:"break",level:"warn",summary:"The host's content surface cannot follow view transforms (punch-through SurfaceView, e.g. react-native-video's default), so the two-box format masks the backdrop with a transparent hole over the content box instead of reframing the content view. context: format."},"DA-BREAK-FORMAT-DEGRADED":{category:"break",level:"warn",summary:"Split break reframing degraded: the host supplied no content view or sibling container for the ad."},"DA-BREAK-NO-PLAYABLE-ASSET":{category:"break",level:"warn",summary:"A break had nothing to play, so it never began: no adbreakbegin/adbreakend was emitted, content kept playing, and a public aderror (source ad, carrying the break) reports it. context.reason says why: no-variant (none declared), no-qualifying-variant (variant selection - device targeting + format playability - matched nothing and no downgrade applied), no-assets (the selected variant was empty), or lshape-content-skipped (shared-element insertion cannot render a backdrop). This is the BREAK-level outcome; when a particular variant was passed over for an unrecognised format, DA-BREAK-VARIANT-FORMAT-UNKNOWN names that format alongside it. context: breakId, reason, declaredAssetCount, format."},"DA-BREAK-VARIANT-FORMAT-UNKNOWN":{category:"break",level:"warn",summary:"A break variant declares a format this SDK version does not recognise, so it was passed over during variant selection rather than guessed at - an unknown format is never playable, because rendering it as a fullscreen single would be the most invasive possible misreading. Raised once per skipped variant: a break that still has a playable variant plays it and reports this too, so the skip is never silent, and a break left with nothing also reports DA-BREAK-NO-PLAYABLE-ASSET with reason no-qualifying-variant. An ABSENT format is treated identically to an unrecognised one. context: breakId, format (the raw manifest string; empty when the field was absent)."},"DA-AD-STALLED":{category:"playback",level:"warn",summary:"An ad began playing and then stopped advancing: the playhead did not move for the stall threshold while the ad was meant to be playing. context: assetId, breakId, playbackState, stalledForMs, positionMs, bufferedAheadMs, reason."},"DA-AD-FOREGROUND-RESUMED":{category:"playback",level:"info",summary:"An in-flight ad resumed after the app returned to the foreground; context carries the suspended duration and ad position at resume."},"DA-AD-FOCUS-LOST":{category:"playback",level:"warn",summary:"The overlay ad lost permanent audio focus during an active break; the host player must not reclaim focus while the SDK ad is on screen. context: breakId, transient, reason."},"DA-AD-FOCUS-GRANTED":{category:"playback",level:"info",summary:"The overlay ad was granted media audio focus for the break, so system focus semantics (call, duck, permanent loss) apply to ad playback. context: breakId, cause, alreadyHeld."},"DA-AD-FOCUS-DENIED":{category:"playback",level:"warn",summary:"The platform refused the overlay ad's media audio-focus request, so the break plays with no focus of its own: another app's audio can mix over the ad, and a call can neither duck nor pause it. context: breakId, cause."},"DA-AD-FOCUS-ABANDONED":{category:"playback",level:"info",summary:"The overlay ad gave media audio focus back, so the content player's own focus request finds a clean stack. context: breakId, cause."},"DA-BREAK-ABANDONED":{category:"lifecycle",level:"warn",summary:"A break was still in flight when the session was torn down (endSession, destroy, or a startSession over an active session). context: breakId, cause, phase, unbalancedAdBegin, adIndex, totalAds, assetId."},"DA-RENDERER-UNAVAILABLE":{category:"lifecycle",level:"error",summary:"The renderer could not render a break because a required piece of it was not attached (e.g. no ad player), after the SDK had already emitted adbreakbegin — so the break began and will never end. context: breakId, missing."},"DA-SESSION-STARTING":{category:"session",level:"info",summary:"A step of startSession() was entered: begin, manifest-fetch, gam-init or scheduling. Emitted on entry, so the last one recorded names the step a hung startSession never finished. context: step, manifestUrl, elapsedMs. The URL is reported verbatim; the redacted config summary carries only its origin (config.manifestOrigin)."}};
@@ -2,4 +2,4 @@
2
2
  * SDK version embedded in diagnostic reports.
3
3
  * Stamped from the monorepo lockstep version (lerna.json) by the taxonomy generator.
4
4
  */
5
- export declare const SDK_VERSION = "1.1.0";
5
+ export declare const SDK_VERSION = "1.1.1";
@@ -1 +1 @@
1
- export const SDK_VERSION="1.1.0";
1
+ export const SDK_VERSION="1.1.1";
@@ -1,4 +1,4 @@
1
- import { PlayerAdapter } from '../interfaces/PlayerAdapter';
1
+ import { PlayerAdapter, type TimedMetadataCue } from '../interfaces/PlayerAdapter';
2
2
  import { Asset, Break, BreakFormat, Timebase } from '../types/BreakManifest';
3
3
  import { AdInsertionType, CreateAdAdapter, DoubleBoxAudio, GamConfig } from '../types/OptiViewAdsConfig';
4
4
  import { AssetParameterMacros } from './assetParameterMacros';
@@ -11,6 +11,7 @@ import { type NoPlayableAssetReason } from './AdBreakSequencer';
11
11
  import type { PauseAdResolution } from './PauseAdController';
12
12
  import { type Clock } from './BreakScheduler';
13
13
  import { PauseAdPresenter } from './adPlayer/PauseAdPresenter';
14
+ import type { BreakEndOnStreamClock } from './adPlayer/streamClockResume';
14
15
  /** Creative identity IMA reports for an ad of a GAM pod; absent for other asset kinds. */
15
16
  export interface AdCreativeIdentity {
16
17
  adId?: string | undefined;
@@ -235,6 +236,10 @@ export declare class AdPlayerController {
235
236
  setChainResolver(resolver: ((currentBreakId: string) => Break | null) | null): void;
236
237
  /** {@link ContentResumeCoordinator.setCueAnchorResolver}. */
237
238
  setResumeCueAnchorResolver(resolver: ((breakInfo: Break) => number | null) | null): void;
239
+ /** {@link ContentResumeCoordinator.setCueEndResolver}. */
240
+ setResumeCueEndResolver(resolver: ((breakInfo: Break) => BreakEndOnStreamClock | null) | null): void;
241
+ /** {@link ContentResumeCoordinator.ingestStreamClockCue}. */
242
+ ingestStreamClockCue(cue: TimedMetadataCue): void;
238
243
  /** Only wired by the SDK in debug mode, so production reports keep their shape. */
239
244
  setTransitionPhaseReporter(reporter: ((name: string) => void) | null): void;
240
245
  /** No-op when no reporter is wired or no transition is in flight. */
@@ -1 +1 @@
1
- import{BreakFormat as e,Timebase as t,isPostRollBreak as r}from"../types/BreakManifest";import{DEFAULT_AD_BREAK_CUT_SAFETY_MARGIN_SEC as s,DEFAULT_DOUBLE_BOX_AUDIO as a}from"../types/OptiViewAdsConfig";import{pipOverridesFormat as i,pipSuppressesBackdrop as n}from"./pictureInPicture";import{AdBreakSequencer as o,assetsOfVariant as d,resolveBreakFormat as l}from"./AdBreakSequencer";import{selectVariantDetailed as h}from"./selectVariant";import{debugLog as u}from"../diagnostics/debugLog";import{systemClock as c}from"./BreakScheduler";import{createAdPlayerState as m,invalidateMediaPreload as g}from"./adPlayer/AdPlayerState";import{PauseAdPresenter as P}from"./adPlayer/PauseAdPresenter";import{AssetParameterResolver as y}from"./adPlayer/AssetParameterResolver";import{GamPodBridge as p}from"./adPlayer/GamPodBridge";import{AdStage as A}from"./adPlayer/AdStage";import{AdPreloader as v}from"./adPlayer/AdPreloader";import{PresentationModeTracker as C}from"./adPlayer/PresentationModeTracker";import{SharedElementBreakPlayer as k}from"./adPlayer/SharedElementBreakPlayer";import{ContentResumeCoordinator as f}from"./adPlayer/ContentResumeCoordinator";import{resumeContentAfterBreak as S}from"./adPlayer/ContentRecovery";import{AssetPlayback as B}from"./adPlayer/AssetPlayback";import{BreakSequenceDriver as b}from"./adPlayer/BreakSequenceDriver";import{VariantSelector as E}from"./adPlayer/VariantSelector";import{AdPlayerEvents as F}from"./adPlayer/AdPlayerEvents";import{armPlaybackCutoff as T,clearPlaybackCutoff as M}from"./adPlayer/PlaybackCutoff";import{AdError as R}from"../types/AdError";export class AdPlayerController{get contentPaused(){return this.state.contentPaused}set contentPaused(e){this.state.contentPaused=e}get firstFrameGateActive(){return this.state.firstFrameGateActive}set firstFrameGateActive(e){this.state.firstFrameGateActive=e}get firstFrameGateShown(){return this.state.firstFrameGateShown}set firstFrameGateShown(e){this.state.firstFrameGateShown=e}get firstFrameRejector(){return this.state.firstFrameRejector}set firstFrameRejector(e){this.state.firstFrameRejector=e}get gamEventCallbacks(){return this.gamPodBridge.eventCallbacks}get vastAdManager(){return this.state.vastAdManager}set vastAdManager(e){this.state.vastAdManager=e}get currentBreak(){return this.state.currentBreak}set currentBreak(e){this.state.currentBreak=e}get currentAsset(){return this.state.currentAsset}set currentAsset(e){this.state.currentAsset=e}get callbacks(){return this.state.callbacks}set callbacks(e){this.state.callbacks=e}get isPlaying(){return this.state.isPlaying}set isPlaying(e){this.state.isPlaying=e}get effectiveBreakDurationSec(){return this.state.effectiveBreakDurationSec}set effectiveBreakDurationSec(e){this.state.effectiveBreakDurationSec=e}get adBreakCutSafetyMarginSec(){return this.state.adBreakCutSafetyMarginSec}set adBreakCutSafetyMarginSec(e){this.state.adBreakCutSafetyMarginSec=e}get durationTimer(){return this.state.durationTimer}set durationTimer(e){this.state.durationTimer=e}get adInsertionType(){return this.state.adInsertionType}set adInsertionType(e){this.state.adInsertionType=e}get breakTimebase(){return this.state.breakTimebase}set breakTimebase(e){this.state.breakTimebase=e}constructor(e,t,r,i,n=!1,o,d="parallel",l="overlay",h=s,u=a,S=!1,T=c,M="none"){this.playerContainerCreatedBySDK=!1,this.adMediaContainer=null,this.adPlayer=null,this.adContainer=null,this.companionElement=null,this.staticQuartilesFired=new Set,this.sequencer=null,this.pendingAdError=null,this.preRollHoldActive=!1,this.preRollHoldHandler=null,this.breakContentGateHandler=null,this.destroyed=!1,this.abortingBreak=!1,this.overlayImageEl=null,this.imageAssetTimer=null,this.chainResolver=null,this.transitionPhaseReporter=null,this.chaining=!1,this.diagnoseHandler=null,this.playerContainerOriginalStyle="",this.companionRemoveTimer=null,this.adFadeTimer=null,this.syncing=!1,this.contentVolumeHandler=null,this.adVolumeChangeHandler=null,this.volumeChangeCallback=null,this.stage=null,this.resizeObserver=null,this.contentVideoElement=null,this.contentVideoGeometryHandler=null,this.contentVideoMutationObserver=null,this.resumeGeneration=0,this.singleSurfaceDevice=!1,this.currentSelectedFormat=void 0,this.audioFocus=null,this.state=m(),this.state.playerContainer=r??null,this.clock=T,this.singleSurfaceDevice=S,this.contentPlayer=e,this.adBreakCutSafetyMarginSec=h,this.doubleBoxAudio=u,this.container=t,r&&(this.playerContainer=r),this.createAdAdapter=i,this.debug=n,this.state.gamConfig=o,this.preloadMode=d,this.insertionMode=l,this.pauseAdPresenter=new P({contentPlayer:this.contentPlayer,getStage:()=>this.stage,resolveUri:e=>this.resolveUri(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.assetParameters=new y(this.state,{contentPlayer:this.contentPlayer,container:this.container,getGamStreamManager:()=>this.state.gamStreamManager,getCurrentBreak:()=>this.currentBreak,getEffectiveBreakDuration:()=>this.effectiveBreakDurationSec,diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.gamPodBridge=new p(this.state,{contentPlayer:this.contentPlayer,debug:this.debug,getAdPlayer:()=>this.adPlayer,getAdContainer:()=>this.adContainer,isSharedElement:()=>"shared-element"===this.effectiveInsertionMode(),getCurrentBreak:()=>this.currentBreak,getCurrentAsset:()=>this.currentAsset,getEffectiveBreakDuration:()=>this.effectiveBreakDurationSec,getAdPlayerStreamRemainingSec:()=>this.adPlayerStreamRemainingSec(),emitStep:e=>this.emitStep(e),emitAdStart:(e,t,r,s,a)=>this.callbacks?.onAdStart(e,t,r,s,a),emitAdEnd:(e,t,r,s,a)=>this.callbacks?.onAdEnd(e,t,r,s,a),onAdEnded:()=>this.onAdEnded(),pushAssetParameters:(e,t)=>this.pushAssetParameters(e,t),resolveSessionAdTagParameters:()=>this.assetParameters.resolveSessionAdTagParameters(),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.adStage=new A({contentPlayer:this.contentPlayer,container:this.container,getPlayerContainer:()=>this.playerContainer,setPlayerContainer:e=>{this.playerContainer=e},setPlayerContainerOriginalStyle:e=>{this.playerContainerOriginalStyle=e},onPlayerContainerCreated:()=>{this.playerContainerCreatedBySDK=!0},getStage:()=>this.stage,setStage:e=>{this.stage=e},getContentVideo:()=>this.contentVideoElement,setContentVideo:e=>{this.contentVideoElement=e},getAdContainer:()=>this.adContainer,setAdContainer:e=>{this.adContainer=e},getAdMediaContainer:()=>this.adMediaContainer,setAdMediaContainer:e=>{this.adMediaContainer=e},setAdPlayer:e=>{g(this.state),this.adPlayer=e},createAdAdapter:e=>this.createAdAdapter(e),setupEventListeners:()=>this.setupEventListeners(),resizeVast:()=>this.vastAdManager?.resize(),getVariant:e=>this.getVariant(e),getCurrentBreak:()=>this.currentBreak,resolveUri:e=>this.resolveUri(e),getCompanion:()=>this.companionElement,setCompanion:e=>{this.companionElement=e},getOverlayImage:()=>this.overlayImageEl,setOverlayImage:e=>{this.overlayImageEl=e},getImageAssetTimer:()=>this.imageAssetTimer,setImageAssetTimer:e=>{this.imageAssetTimer=e},isChaining:()=>this.chaining,log:(...e)=>this.log(...e)}),this.preloader=new v({state:this.state,clock:this.clock,adStartBudgetMs:AdPlayerController.AD_START_BUDGET_MS,gamPodAdStartBudgetMs:AdPlayerController.GAM_POD_AD_START_BUDGET_MS,minAdStartBudgetMs:AdPlayerController.MIN_AD_START_BUDGET_MS,debug:this.debug,isPlaying:()=>this.isPlaying,preloadMode:this.preloadMode,effectiveInsertionMode:()=>this.effectiveInsertionMode(),getVariant:e=>this.getVariant(e),getAssets:e=>this.getAssets(e),resolveUri:e=>this.resolveUri(e),resolveAssetUri:(e,t)=>this.resolveAssetUri(e,t),getCompanionVariant:e=>this.getVariant(e),getAdPlayer:()=>this.adPlayer,getAdContainer:()=>this.adContainer,buildVastTagUrl:(e,t)=>this.buildVastTagUrl(e,t),resolveChainedSuccessor:e=>this.resolveChainedSuccessor(e),show:()=>this.show(),reapplyAdContainerLayout:e=>this.reapplyAdContainerLayout(e),getCurrentBreak:()=>this.currentBreak,onBreakVisible:e=>this.callbacks?.onBreakVisible?.(e),onAdError:e=>this.onAdError(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.presentationModes=new C(this.state,{contentPlayer:this.contentPlayer,getAdPlayer:()=>this.adPlayer,insertionMode:this.insertionMode,getCurrentBreak:()=>this.currentBreak,getCurrentFormat:()=>this.currentSelectedFormat,isSharedElementActive:()=>this.state.sharedAdClaimActive,getVariant:e=>this.getVariant(e),isAdPlaying:()=>this.isAdPlaying(),hasCurrentAsset:()=>null!==this.currentAsset,contentSourceIsReloadable:()=>null!==this.sharedElementPlayer.restorableContentSource(),adoptPictureInPictureMidBreak:()=>this.adoptPictureInPictureMidBreak(),restoreLayout:e=>this.restoreLayout(e),applyLayout:e=>this.applyLayout(e),show:()=>this.show(),playAdThroughContentElement:()=>this.sharedElementPlayer.playAdThroughContentElement(),getContentPositionAtBreakStart:()=>this.state.contentPositionAtBreakStart,setContentPositionAtBreakStart:e=>this.resumeCoordinator.reanchorMidBreak(e),gateContentForBreak:()=>this.gateContentForBreak(),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.resumeCoordinator=new f(this.state,{contentPlayer:this.contentPlayer,clock:this.clock,getInsertionMode:()=>this.effectiveInsertionMode(),gateContentForBreak:()=>this.gateContentForBreak(),clearContentGate:e=>this.clearContentGate(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.recoveryDeps={contentPlayer:e,getCallbacks:()=>this.callbacks,preloadMode:d,contentRecovery:M,resumeCoordinator:this.resumeCoordinator,diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)},this.sharedElementPlayer=new k(this.state,{contentPlayer:this.contentPlayer,getAdPlayer:()=>this.adPlayer,resolveAssetUri:(e,t)=>this.resolveAssetUri(e,t),liveEdgeDistanceSec:()=>this.resumeCoordinator.liveEdgeDistanceSec(),rebindContentElementIfSwapped:()=>this.rebindContentElementIfSwapped(),createAdAdapter:(e,t)=>this.createAdAdapter(e,t),reportAdProgress:e=>this.reportAdProgress(e),processTimedMetadata:e=>this.gamPodBridge.processTimedMetadata(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e),clearContentGate:()=>this.clearContentGate(),hide:()=>this.hide(),waitForLiveEdge:e=>this.resumeCoordinator.waitForLiveEdge(e),getVariant:e=>this.getVariant(e),getAssets:e=>this.getAssets(e)}),this.variantSelector=new E(this.state,{getEffectiveInsertionMode:()=>this.effectiveInsertionMode(),singleSurfaceDevice:this.singleSurfaceDevice,preloadMode:this.preloadMode,getIsContentPictureInPicture:()=>this.isContentPictureInPicture(),getIsGamReady:()=>this.isGamReady(),getSupportsParallelBuffering:()=>this.contentPlayer.supportsParallelBuffering,diagnose:(e,t,r)=>this.diagnose(e,t,r)}),this.assetPlayback=new B(this.state,{getAdPlayer:()=>this.adPlayer,getAdContainer:()=>this.adContainer,getAdMediaContainer:()=>this.adMediaContainer,clearStaticQuartiles:()=>this.staticQuartilesFired.clear(),getVariant:e=>this.getVariant(e),getGamEventCallbacks:()=>this.gamEventCallbacks,getSequencer:()=>this.sequencer,debug:this.debug,resolveUri:e=>this.resolveUri(e),buildGamUrl:(e,t)=>this.buildGamUrl(e,t),buildVastTagUrl:(e,t)=>this.buildVastTagUrl(e,t),onAdError:e=>this.onAdError(e),onAdEnded:()=>this.onAdEnded(),drive:e=>this.drive(e),clearOverlayImage:()=>this.clearOverlayImage(),revealFirstFrame:()=>this.preloader.revealFirstFrame(),transferPictureInPictureToAd:()=>this.presentationModes.transferPictureInPictureToAd(),isGamPodAsset:e=>this.isGamPodAsset(e),hasGamIdentityMismatch:e=>this.gamPodBridge.hasIdentityMismatch(e),beginGamPodTracking:e=>this.gamPodBridge.beginGamPodTracking(e),recordAdProgress:e=>this.adPlayerEvents.recordAdProgress(e),reportPhase:e=>this.reportPhase(e),armAdStartBudget:e=>this.armAdStartBudget(e),remainingAdStartBudgetMs:()=>this.remainingAdStartBudgetMs(),loadWithinBudget:(e,t)=>this.loadWithinBudget(e,t),waitForFirstFrame:()=>this.waitForFirstFrame(),getOverlayImage:()=>this.overlayImageEl,setOverlayImage:e=>{this.overlayImageEl=e},getImageAssetTimer:()=>this.imageAssetTimer,setImageAssetTimer:e=>{this.imageAssetTimer=e},getVastPodPosition:()=>this.vastPodPosition,setVastPodPosition:e=>{this.vastPodPosition=e},diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.breakSequenceDriver=new b(this.state,{getChainResolver:()=>this.chainResolver,getEffectiveInsertionMode:()=>this.effectiveInsertionMode(),getVastPodPosition:()=>this.vastPodPosition,setVastPodPosition:e=>{this.vastPodPosition=e},getPendingAdError:()=>this.pendingAdError,setPendingAdError:e=>{this.pendingAdError=e},getChaining:()=>this.chaining,setChaining:e=>{this.chaining=e},isExpandingPodAsset:e=>this.isExpandingPodAsset(e),fallBackToPodLevelReporting:()=>this.fallBackToPodLevelReporting(),resetGamPodTracking:()=>this.resetGamPodTracking(),emitGamPodSteps:e=>this.gamPodBridge.emitGamPodSteps(e),playAsset:(e,t,r)=>this.playAsset(e,t,r),endBreak:()=>this.endBreak(),playBreak:(e,t,r)=>this.playBreak(e,t,r),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.adPlayerEvents=new F(this.state,{getAdPlayer:()=>this.adPlayer,getContentPlayer:()=>this.contentPlayer,getGamEventCallbacks:()=>this.gamEventCallbacks,getSequencer:()=>this.sequencer,getAudioFocus:()=>this.audioFocus,getSyncing:()=>this.syncing,setSyncing:e=>{this.syncing=e},setAdVolumeChangeHandler:e=>{this.adVolumeChangeHandler=e},setContentVolumeHandler:e=>{this.contentVolumeHandler=e},notifyVolumeChange:()=>this.notifyVolumeChange(),onAdEnded:()=>this.onAdEnded(),processTimedMetadata:e=>this.gamPodBridge.processTimedMetadata(e),toAdError:e=>this.toAdError(e),revealFirstFrame:()=>this.revealFirstFrame(),clearFirstFrameResolver:()=>this.preloader.clearFirstFrameResolver(),drive:e=>this.drive(e),setPendingAdError:e=>{this.pendingAdError=e},log:(...e)=>this.log(...e),maybePrepositionContentForResume:()=>"single-decoder"!==this.preloadMode&&this.resumeCoordinator.maybePrepositionContentForResume(),maybeCatchUpContentForResume:e=>"single-decoder"!==this.preloadMode&&this.resumeCoordinator.maybeCatchUpContentForResume(e),getStaticQuartilesFired:()=>this.staticQuartilesFired,onGamPodAdProgress:e=>this.gamPodBridge.onGamPodAdProgress(e)})}setGamEventCallbacks(e){this.gamPodBridge.setEventCallbacks(e)}setDiagnoseHandler(e){this.diagnoseHandler=e}diagnose(e,t,r){this.diagnoseHandler?.(e,t,r)}holdContentForPreRoll(e){if(this.preRollHoldActive)return;const t=this.getVariant(e);t&&this.shouldPauseContent(t.format)&&(this.preRollHoldActive=!0,this.contentPlayer.pause(),this.preRollHoldHandler=()=>{this.preRollHoldActive&&this.contentPlayer.pause()},this.contentPlayer.on("playing",this.preRollHoldHandler),this.diagnose("DA-PREROLL-CONTENT-HELD","Content held at session start until the pending pre-roll begins.",{breakId:e.id}))}releaseContentHold(){this.preRollHoldActive&&(this.preRollHoldActive=!1,this.preRollHoldHandler&&(this.contentPlayer.off("playing",this.preRollHoldHandler),this.preRollHoldHandler=null))}gateContentForBreak(){this.contentPlayer.pause(),this.breakContentGateHandler||(this.breakContentGateHandler=()=>{this.contentPaused&&!this.state.resumeCatchupActive&&this.contentPlayer.pause()},this.contentPlayer.on("playing",this.breakContentGateHandler))}clearContentGate(e=!1){this.resumeCoordinator.endResumeCatchup(e),this.breakContentGateHandler&&(this.contentPlayer.off("playing",this.breakContentGateHandler),this.breakContentGateHandler=null)}setChainResolver(e){this.chainResolver=e}setResumeCueAnchorResolver(e){this.resumeCoordinator.setCueAnchorResolver(e)}setTransitionPhaseReporter(e){this.transitionPhaseReporter=e}reportPhase(e){this.transitionPhaseReporter?.(e)}setBreakResumePolicy(e,t,r=!1){this.adInsertionType=e,this.breakTimebase=t,this.state.continueContentDuringBreak=r,this.state.continueRefusalReported=!1}initialize(){this.adContainer||(this.setupOverlay(),this.presentationModes.setupPictureInPictureTracking(),"adaptive"===this.insertionMode&&this.presentationModes.setupFullscreenTracking())}async startGamSession(e,t){await this.gamPodBridge.startGamSession(e,t)}endGamSession(){this.gamPodBridge.endGamSession()}setSessionAssetParameters(e){this.assetParameters.setSessionAssetParameters(e)}setManifestAssetParameters(e){this.assetParameters.setManifestAssetParameters(e)}updateAssetParameters(e){this.assetParameters.updateAssetParameters(e)}updateAssetParameterMacros(e){this.assetParameters.updateAssetParameterMacros(e)}get updatedAssetParameters(){return this.state.updatedAssetParameters}setSessionAssetParameterMacros(e){this.assetParameters.setSessionAssetParameterMacros(e)}get sessionAssetParameterMacros(){return this.assetParameters.getSessionAssetParameterMacros()}buildVastTagUrl(e,t){return this.assetParameters.buildVastTagUrl(e,t)}pushAssetParameters(e,t){this.assetParameters.pushAssetParameters(e,t)}setupOverlay(){this.adStage.setupOverlay()}isGamPodAsset(e){return this.gamPodBridge.isGamPodAsset(e)}isExpandingPodAsset(e){return this.gamPodBridge.isExpandingPodAsset(e)}fallBackToPodLevelReporting(){this.gamPodBridge.fallBackToPodLevelReporting()}resetGamPodTracking(){this.gamPodBridge.resetGamPodTracking()}emitGamPodSteps(e){this.gamPodBridge.emitGamPodSteps(e)}isGamEnabled(){return this.gamPodBridge.isGamEnabled()}isGamReady(){return this.gamPodBridge.isGamReady()}isOverlayInsertion(){return"overlay"===this.effectiveInsertionMode()}settleAssetProgress(){this.adPlayerEvents.settleAssetProgress()}reportAdProgress(e){this.adPlayerEvents.reportAdProgress(e)}setupEventListeners(){this.adPlayerEvents.setupEventListeners()}async preload(e){return this.preloader.preload(e)}renderLshapeContentBackdrop(e){this.adStage.renderLshapeContentBackdrop(e)}currentInsertionMode(){return this.presentationModes.currentInsertionMode()}effectiveInsertionMode(){return this.presentationModes.effectiveInsertionMode()}isContentPictureInPicture(){return this.presentationModes.isPictureInPicture()}rebindContentElementIfSwapped(){this.presentationModes.rebindContentElementIfSwapped()}teardownFullscreenTracking(){this.presentationModes.teardownFullscreenTracking()}teardownPictureInPictureTracking(){this.presentationModes.teardownPictureInPictureTracking()}isPictureInPicture(){return this.presentationModes.isPictureInPicture()}pictureInPictureOwner(){return this.presentationModes.pictureInPictureOwner()}isShowingAd(){if(!this.isAdPlaying())return!1;const e=this.currentDeclaredFormat();return!n(e,this.isContentPictureInPicture())}currentDeclaredFormat(){return this.currentSelectedFormat??(this.currentBreak?l(this.currentBreak):void 0)}async playBreak(t,s,a){if(this.state.preloadGeneration++,this.resumeGeneration++,!this.sharedElementPlayer.beginSharedActivity())return;this.releaseContentHold(),this.rebindContentElementIfSwapped();const n=a?.effectiveDurationSec??null;this.effectiveBreakDurationSec=null!==n&&n>0?n:null;const d=this.effectiveBreakDurationSec??t.duration;if("shared-element"===this.effectiveInsertionMode())return g(this.state),void await this.sharedElementPlayer.playSharedElementBreak(t,s);if(!this.adPlayer)return void this.log("playBreak called before initialize()");const l=this.getVariant(t);if(!l)return void this.log("No valid variant found for break:",t.id);this.currentBreak=t,this.callbacks=s,this.isPlaying=!0,this.firstFrameGateActive=a?.firstFrameGate??!1,this.firstFrameGateShown=!1;const h=this.continueContentDuringBreakReason(l.format),u=r(t),c=this.shouldPauseContent(l.format)&&"ok"===h&&!u;c||u||this.state.continueRefusalReported||!this.shouldPauseContent(l.format)||(this.state.continueRefusalReported=!0,this.diagnose("DA-CONTINUE-PLAYOUT-REFUSED",`Content will be paused for breaks this session: ${h}`,{reason:h,format:l.format})),this.audioFocus=l.format===e.DOUBLE?this.doubleBoxAudio:c?"ad":null,this.adPlayer&&("content"===this.audioFocus?(this.adPlayer.muted=!0,this.adPlayer.volume=0):(this.adPlayer.muted=this.contentPlayer.muted,this.adPlayer.volume=this.contentPlayer.volume,"ad"===this.audioFocus&&(this.contentPlayer.muted=!0)));const m=this.declaredFormatOf(t);if(this.currentSelectedFormat=m,this.state.pipAdoptedForBreak=i(m,this.isContentPictureInPicture()),this.state.pipAdoptedForBreak&&this.diagnose("DA-PIP-FORMAT-OVERRIDE",`Picture-in-picture: ${m} break plays as single`,{declared:m,effective:e.SINGLE,reason:"picture-in-picture",midBreak:!1}),this.shouldPauseContent(l.format)?(this.resumeCoordinator.captureBreakAnchor(t),c?(this.contentPaused=!1,this.resumeCoordinator.beginContinueContentPlayout()):(this.contentPaused=!0,this.gateContentForBreak())):this.contentPaused=!1,this.applyLayout(l),l.format===e.LSHAPE_CONTENT)return this.renderLshapeContentBackdrop(l),void(d&&d>0?(this.log("Starting duration timer:",d,"seconds"),this.durationTimer=setTimeout(()=>{this.log("Duration timer expired, ending break"),this.endBreak()},1e3*d)):this.endBreak());this.firstFrameGateActive||(this.show(),this.reapplyAdContainerLayout(l));if(0===this.getAssets(t).length)return this.log("No assets in break, ending immediately"),void this.endBreak();{const e=Math.max(0,d||0)+this.adBreakCutSafetyMarginSec;T(this.state,e,()=>{this.log("Break-cut timer expired, ending break"),this.firstFrameRejector?this.onAdError(new R("Break cut before first frame rendered","DA-AD-START-TIMEOUT")):this.sequencer&&this.currentBreak&&this.isPlaying?(this.callbacks?.onBreakCut?.(this.currentBreak),this.drive(this.sequencer.onOutcome({kind:"break-elapsed"}))):this.endBreak()},()=>this.onAdError(new R("Ad playback startup timed out","DA-AD-START-TIMEOUT")))}this.sequencer=new o("overlay",()=>null,this.selectionInputs()),await this.drive(this.sequencer.beginBreak(t)),this.preloadChainedSuccessor(t.id)}get resumeHandoverInMotion(){return this.state.resumeCatchupActive}reapplyAdContainerLayout(e){this.adStage.reapplyAdContainerLayout(e)}adoptPictureInPictureMidBreak(){this.presentationModes.adoptPictureInPictureMidBreak()}async restorePictureInPictureToContent(){await this.presentationModes.restorePictureInPictureToContent()}continueContentDuringBreakReason(e){return this.variantSelector.continueContentDuringBreakReason(e)}shouldPauseContent(t){return t===e.SINGLE||t===e.LSHAPE_AD}selectionInputs(){return this.variantSelector.selectionInputs()}breakNothingToPlayReason(e){return this.variantSelector.breakNothingToPlayReason(e)}unknownVariantFormatsOf(e){return this.variantSelector.unknownVariantFormatsOf(e)}diagnoseUnknownVariantFormats(e){this.variantSelector.diagnoseUnknownVariantFormats(e)}declaredFormatOf(e){const{selected:t,deviceQualified:r}=h(e,this.selectionInputs());return(t??r)?.format??l(e)}getVariant(e){return this.variantSelector.getVariant(e)}applyLayout(e){this.adStage.applyLayout(e)}restoreLayout(e){this.adStage.restoreLayout(e)}getAssets(e){return d(this.getVariant(e))}async playAsset(e,t,r){return this.assetPlayback.playAsset(e,t,r)}clearOverlayImage(){this.adStage.clearOverlayImage()}async showPauseImage(e){return this.pauseAdPresenter.showPauseImage(e)}hidePauseImage(){this.pauseAdPresenter.hidePauseImage()}async drive(e){return this.breakSequenceDriver.drive(e)}emitStep(e){this.breakSequenceDriver.emitStep(e)}async resolveAssetUri(e,t){return this.assetPlayback.resolveAssetUri(e,t)}async buildGamUrl(e,t){return this.gamPodBridge.buildGamUrl(e,t)}resolveUri(e){return this.assetParameters.resolveUri(e)}adPlayerStreamRemainingSec(){return this.assetPlayback.adPlayerStreamRemainingSec()}onAdEnded(){this.currentBreak&&this.isPlaying&&this.sequencer&&(this.settleAssetProgress(),this.drive(this.sequencer.onOutcome({kind:"asset-ended"})))}toAdError(e){return this.assetPlayback.toAdError(e)}onAdError(e){this.adPlayerEvents.onAdError(e)}endBreak(){if(!this.currentBreak)return;this.log("Break ended:",this.currentBreak.id),M(this.state),this.state.gamPodTracker&&this.emitGamPodSteps(this.state.gamPodTracker.finish()),this.resetGamPodTracking(),this.pushAssetParameters(void 0);const e=this.currentBreak,s=this.getVariant(e)?.format;let a=this.abortingBreak?null:this.resolveChainedSuccessor(e.id);if(a){const e=this.breakNothingToPlayReason(a);this.diagnoseUnknownVariantFormats(a),e&&(this.diagnose("DA-BREAK-NO-PLAYABLE-ASSET",`chained break ${a.id} has no playable variant (${e}); it will not begin.`,{breakId:a.id,reason:e}),this.callbacks?.onAdError(a,void 0,new R(`Break ${a.id} has no playable variant (${e})`,"DA-BREAK-NO-PLAYABLE-ASSET")),this.callbacks?.onChainedBreakSkipped?.(a),a=null)}if(a)return void this.advanceToChainedBreak(e,a);if(this.currentSelectedFormat=void 0,this.resumeCoordinator.endContinueContentPlayout(),this.restorePictureInPictureToContent(),this.isPlaying=!1,this.currentBreak=null,this.resumeGeneration++,this.effectiveBreakDurationSec=null,g(this.state),this.preloader.clearWarmedBreaks(),this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.clearFirstFrame("Break ended before first frame"),"ad"===this.audioFocus&&this.adPlayer?(this.contentPlayer.muted=this.adPlayer.muted,this.contentPlayer.volume=this.adPlayer.volume):"content"===this.audioFocus&&this.adPlayer&&(this.adPlayer.muted=this.contentPlayer.muted,this.adPlayer.volume=this.contentPlayer.volume),this.audioFocus=null,this.clearOverlayImage(),this.vastAdManager?.reset(),this.hide(),this.restoreLayout(s),this.adPlayer?.pause(),this.state.sharedAdClaimActive){const t=this.callbacks;return this.sharedElementPlayer.detachSharedAdListeners(),this.abortingBreak=!1,this.state.earlyReturnResumeOffsetSec=null,this.sharedElementPlayer.restoreSharedElementContent(e),void t?.onBreakEnd(e)}const i="recreate"===this.recoveryDeps.contentRecovery&&"function"==typeof this.contentPlayer.recreateMediaPipeline,n="single-decoder"===this.preloadMode||i?this.adPlayer?.unload?.():void 0;if(this.contentPaused&&r(e))this.contentPaused=!1,this.clearContentGate();else if(this.contentPaused){this.contentPaused=!1,this.clearContentGate(this.resumeHandoverInMotion);const r=this.resumeGeneration;S(this.recoveryDeps,{breakInfo:e,earlyReturnOffsetSec:this.state.earlyReturnResumeOffsetSec,isLiveResume:this.breakTimebase===t.WALLCLOCK,released:n,isCurrent:()=>r===this.resumeGeneration})}this.abortingBreak=!1,this.state.earlyReturnResumeOffsetSec=null,this.callbacks?.onBreakEnd(e)}currentAdAsset(){return this.isPlaying?this.currentAsset:null}skipBreak(){this.isPlaying&&(this.log("Skipping break:",this.currentBreak?.id),M(this.state),this.sequencer&&this.currentBreak?this.drive(this.sequencer.onOutcome({kind:"break-elapsed"})):this.endBreak())}abortBreak(e){this.isPlaying&&(this.log("Early return — break removed from manifest:",this.currentBreak?.id),this.state.earlyReturnResumeOffsetSec=Math.max(0,e),this.abortingBreak=!0,M(this.state),this.sequencer&&this.currentBreak?this.drive(this.sequencer.onOutcome({kind:"break-elapsed"})):this.endBreak())}stopActiveBreak(){g(this.state),this.sharedElementPlayer.cancelSharedRestore()&&this.isPlaying&&(this.log("Aborting active break on session end:",this.currentBreak?.id),M(this.state),this.sharedElementPlayer.detachSharedAdListeners(),this.sharedElementPlayer.releaseContentElementAdPlayer(),this.adPlayer?.pause(),this.clearOverlayImage(),this.vastAdManager?.reset(),this.hide(),this.restoreLayout(this.currentBreak?this.getVariant(this.currentBreak)?.format??void 0:void 0),this.isPlaying=!1,this.currentBreak=null,this.currentAsset=null,this.contentPaused=!1,this.clearContentGate(),this.resumeCoordinator.endContinueContentPlayout(),this.effectiveBreakDurationSec=null,this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.clearFirstFrame("Break aborted before first frame"),this.audioFocus=null)}resolveChainedSuccessor(e){return this.breakSequenceDriver.resolveChainedSuccessor(e)}advanceToChainedBreak(e,t){this.breakSequenceDriver.advanceToChainedBreak(e,t)}preloadChainedSuccessor(e){this.preloader.preloadChainedSuccessor(e)}revealFirstFrame(){this.assetPlayback.revealFirstFrame()}armAdStartBudget(e){this.preloader.armAdStartBudget(e)}remainingAdStartBudgetMs(){return this.preloader.remainingAdStartBudgetMs()}loadWithinBudget(e,t){return this.preloader.loadWithinBudget(e,t)}async waitForFirstFrame(){return this.preloader.waitForFirstFrame()}clearFirstFrame(e="Break ended before first frame"){this.preloader.clearFirstFrame(e)}show(){this.adStage.show()}hide(){this.adStage.hide()}isAdPlaying(){return this.isPlaying}get muted(){return"content"===this.audioFocus?this.contentPlayer.muted:"ad"===this.audioFocus?this.adPlayer?this.adPlayer.muted:this.contentPlayer.muted:this.isPlaying&&this.adPlayer?this.adPlayer.muted:this.contentPlayer.muted}set muted(e){if("content"===this.audioFocus)this.contentPlayer.muted=e;else if("ad"===this.audioFocus)this.adPlayer&&(this.adPlayer.muted=e);else{(this.isPlaying&&this.adPlayer?this.adPlayer:this.contentPlayer).muted=e}this.vastAdManager?.setMuted(e),this.notifyVolumeChange()}get volume(){return"content"===this.audioFocus?this.contentPlayer.volume:"ad"===this.audioFocus?this.adPlayer?this.adPlayer.volume:this.contentPlayer.volume:this.isPlaying&&this.adPlayer?this.adPlayer.volume:this.contentPlayer.volume}set volume(e){if("content"===this.audioFocus)this.contentPlayer.volume=e;else if("ad"===this.audioFocus)this.adPlayer&&(this.adPlayer.volume=e);else{(this.isPlaying&&this.adPlayer?this.adPlayer:this.contentPlayer).volume=e}this.vastAdManager?.setVolume(e),this.notifyVolumeChange()}setVolumeChangeCallback(e){this.volumeChangeCallback=e}notifyVolumeChange(){this.volumeChangeCallback?.(this.muted,this.volume)}destroy(){if(this.destroyed)return;if(this.resumeGeneration++,g(this.state),!this.sharedElementPlayer.beginSharedActivity())return;this.destroyed=!0,this.adStage.destroy(),this.resumeCoordinator.cancelResumeLandedProbe(),this.resumeCoordinator.endResumeCatchup(),this.resumeCoordinator.endContinueContentPlayout(),this.state.resumePrepositionSettle&&(clearTimeout(this.state.resumePrepositionSettle),this.state.resumePrepositionSettle=null),this.releaseContentHold(),this.clearContentGate(),this.clearFirstFrame("Controller destroyed before first frame"),this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.resetGamPodTracking(),M(this.state),this.companionRemoveTimer&&(clearTimeout(this.companionRemoveTimer),this.companionRemoveTimer=null),this.adFadeTimer&&(clearTimeout(this.adFadeTimer),this.adFadeTimer=null),this.adPlayer?.pause(),this.clearOverlayImage(),this.pauseAdPresenter.destroy(),this.contentVolumeHandler&&(this.contentPlayer.off("volumechange",this.contentVolumeHandler),this.contentVolumeHandler=null),this.sharedElementPlayer.detachSharedAdListeners(),this.sharedElementPlayer.releaseContentElementAdPlayer(),this.state.pipTransferredToAd=!1,this.teardownFullscreenTracking(),this.teardownPictureInPictureTracking(),this.adVolumeChangeHandler&&this.adPlayer&&this.adPlayer.off("volumechange",this.adVolumeChangeHandler),this.adVolumeChangeHandler=null,this.hide(),this.adStage.destroy(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.contentVideoMutationObserver?.disconnect(),this.contentVideoMutationObserver=null,this.contentVideoElement&&this.contentVideoGeometryHandler&&(this.contentVideoElement.removeEventListener("loadedmetadata",this.contentVideoGeometryHandler),this.contentVideoElement.removeEventListener("resize",this.contentVideoGeometryHandler)),this.contentVideoElement=null,this.contentVideoGeometryHandler=null;const e=this.adStage.restoreContent(this.playerContainerCreatedBySDK,this.playerContainerOriginalStyle);this.companionElement&&this.companionElement.parentElement&&(this.companionElement.parentElement.removeChild(this.companionElement),this.companionElement=null),this.isPlaying=!1,this.currentBreak=null,this.adContainer&&this.adContainer.parentElement&&this.adContainer.parentElement.removeChild(this.adContainer),!e&&this.stage&&this.stage.parentElement&&this.stage.parentElement.removeChild(this.stage),this.stage=null,this.adContainer=null,this.adMediaContainer=null;try{this.adPlayer?.destroy()}catch(e){this.log("Ad player adapter destroy failed (ignored):",e)}this.adPlayer=null,this.callbacks=null,this.gamPodBridge.destroy(),this.vastAdManager?.destroy(),this.vastAdManager=null,this.log("Ad player destroyed")}log(...e){this.debug&&u("[OptiViewAds:AdPlayerController]",...e)}}AdPlayerController.AD_START_BUDGET_MS=5e3,AdPlayerController.GAM_POD_AD_START_BUDGET_MS=1e4,AdPlayerController.MIN_AD_START_BUDGET_MS=3e3;
1
+ import{BreakFormat as e,Timebase as t,isPostRollBreak as r}from"../types/BreakManifest";import{DEFAULT_AD_BREAK_CUT_SAFETY_MARGIN_SEC as s,DEFAULT_DOUBLE_BOX_AUDIO as a}from"../types/OptiViewAdsConfig";import{pipOverridesFormat as i,pipSuppressesBackdrop as n}from"./pictureInPicture";import{AdBreakSequencer as o,assetsOfVariant as d,resolveBreakFormat as l}from"./AdBreakSequencer";import{selectVariantDetailed as h}from"./selectVariant";import{debugLog as u}from"../diagnostics/debugLog";import{systemClock as c}from"./BreakScheduler";import{createAdPlayerState as m,invalidateMediaPreload as g}from"./adPlayer/AdPlayerState";import{PauseAdPresenter as P}from"./adPlayer/PauseAdPresenter";import{AssetParameterResolver as y}from"./adPlayer/AssetParameterResolver";import{GamPodBridge as p}from"./adPlayer/GamPodBridge";import{AdStage as A}from"./adPlayer/AdStage";import{AdPreloader as v}from"./adPlayer/AdPreloader";import{PresentationModeTracker as C}from"./adPlayer/PresentationModeTracker";import{SharedElementBreakPlayer as k}from"./adPlayer/SharedElementBreakPlayer";import{ContentResumeCoordinator as f}from"./adPlayer/ContentResumeCoordinator";import{resumeContentAfterBreak as S}from"./adPlayer/ContentRecovery";import{AssetPlayback as B}from"./adPlayer/AssetPlayback";import{BreakSequenceDriver as E}from"./adPlayer/BreakSequenceDriver";import{VariantSelector as b}from"./adPlayer/VariantSelector";import{AdPlayerEvents as F}from"./adPlayer/AdPlayerEvents";import{armPlaybackCutoff as T,clearPlaybackCutoff as M}from"./adPlayer/PlaybackCutoff";import{AdError as R}from"../types/AdError";export class AdPlayerController{get contentPaused(){return this.state.contentPaused}set contentPaused(e){this.state.contentPaused=e}get firstFrameGateActive(){return this.state.firstFrameGateActive}set firstFrameGateActive(e){this.state.firstFrameGateActive=e}get firstFrameGateShown(){return this.state.firstFrameGateShown}set firstFrameGateShown(e){this.state.firstFrameGateShown=e}get firstFrameRejector(){return this.state.firstFrameRejector}set firstFrameRejector(e){this.state.firstFrameRejector=e}get gamEventCallbacks(){return this.gamPodBridge.eventCallbacks}get vastAdManager(){return this.state.vastAdManager}set vastAdManager(e){this.state.vastAdManager=e}get currentBreak(){return this.state.currentBreak}set currentBreak(e){this.state.currentBreak=e}get currentAsset(){return this.state.currentAsset}set currentAsset(e){this.state.currentAsset=e}get callbacks(){return this.state.callbacks}set callbacks(e){this.state.callbacks=e}get isPlaying(){return this.state.isPlaying}set isPlaying(e){this.state.isPlaying=e}get effectiveBreakDurationSec(){return this.state.effectiveBreakDurationSec}set effectiveBreakDurationSec(e){this.state.effectiveBreakDurationSec=e}get adBreakCutSafetyMarginSec(){return this.state.adBreakCutSafetyMarginSec}set adBreakCutSafetyMarginSec(e){this.state.adBreakCutSafetyMarginSec=e}get durationTimer(){return this.state.durationTimer}set durationTimer(e){this.state.durationTimer=e}get adInsertionType(){return this.state.adInsertionType}set adInsertionType(e){this.state.adInsertionType=e}get breakTimebase(){return this.state.breakTimebase}set breakTimebase(e){this.state.breakTimebase=e}constructor(e,t,r,i,n=!1,o,d="parallel",l="overlay",h=s,u=a,S=!1,T=c,M="none"){this.playerContainerCreatedBySDK=!1,this.adMediaContainer=null,this.adPlayer=null,this.adContainer=null,this.companionElement=null,this.staticQuartilesFired=new Set,this.sequencer=null,this.pendingAdError=null,this.preRollHoldActive=!1,this.preRollHoldHandler=null,this.breakContentGateHandler=null,this.destroyed=!1,this.abortingBreak=!1,this.overlayImageEl=null,this.imageAssetTimer=null,this.chainResolver=null,this.transitionPhaseReporter=null,this.chaining=!1,this.diagnoseHandler=null,this.playerContainerOriginalStyle="",this.companionRemoveTimer=null,this.adFadeTimer=null,this.syncing=!1,this.contentVolumeHandler=null,this.adVolumeChangeHandler=null,this.volumeChangeCallback=null,this.stage=null,this.resizeObserver=null,this.contentVideoElement=null,this.contentVideoGeometryHandler=null,this.contentVideoMutationObserver=null,this.resumeGeneration=0,this.singleSurfaceDevice=!1,this.currentSelectedFormat=void 0,this.audioFocus=null,this.state=m(),this.state.playerContainer=r??null,this.clock=T,this.singleSurfaceDevice=S,this.contentPlayer=e,this.adBreakCutSafetyMarginSec=h,this.doubleBoxAudio=u,this.container=t,r&&(this.playerContainer=r),this.createAdAdapter=i,this.debug=n,this.state.gamConfig=o,this.preloadMode=d,this.insertionMode=l,this.pauseAdPresenter=new P({contentPlayer:this.contentPlayer,getStage:()=>this.stage,resolveUri:e=>this.resolveUri(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.assetParameters=new y(this.state,{contentPlayer:this.contentPlayer,container:this.container,getGamStreamManager:()=>this.state.gamStreamManager,getCurrentBreak:()=>this.currentBreak,getEffectiveBreakDuration:()=>this.effectiveBreakDurationSec,diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.gamPodBridge=new p(this.state,{contentPlayer:this.contentPlayer,debug:this.debug,getAdPlayer:()=>this.adPlayer,getAdContainer:()=>this.adContainer,isSharedElement:()=>"shared-element"===this.effectiveInsertionMode(),getCurrentBreak:()=>this.currentBreak,getCurrentAsset:()=>this.currentAsset,getEffectiveBreakDuration:()=>this.effectiveBreakDurationSec,getAdPlayerStreamRemainingSec:()=>this.adPlayerStreamRemainingSec(),emitStep:e=>this.emitStep(e),emitAdStart:(e,t,r,s,a)=>this.callbacks?.onAdStart(e,t,r,s,a),emitAdEnd:(e,t,r,s,a)=>this.callbacks?.onAdEnd(e,t,r,s,a),onAdEnded:()=>this.onAdEnded(),pushAssetParameters:(e,t)=>this.pushAssetParameters(e,t),resolveSessionAdTagParameters:()=>this.assetParameters.resolveSessionAdTagParameters(),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.adStage=new A({contentPlayer:this.contentPlayer,container:this.container,getPlayerContainer:()=>this.playerContainer,setPlayerContainer:e=>{this.playerContainer=e},setPlayerContainerOriginalStyle:e=>{this.playerContainerOriginalStyle=e},onPlayerContainerCreated:()=>{this.playerContainerCreatedBySDK=!0},getStage:()=>this.stage,setStage:e=>{this.stage=e},getContentVideo:()=>this.contentVideoElement,setContentVideo:e=>{this.contentVideoElement=e},getAdContainer:()=>this.adContainer,setAdContainer:e=>{this.adContainer=e},getAdMediaContainer:()=>this.adMediaContainer,setAdMediaContainer:e=>{this.adMediaContainer=e},setAdPlayer:e=>{g(this.state),this.adPlayer=e},createAdAdapter:e=>this.createAdAdapter(e),setupEventListeners:()=>this.setupEventListeners(),resizeVast:()=>this.vastAdManager?.resize(),getVariant:e=>this.getVariant(e),getCurrentBreak:()=>this.currentBreak,resolveUri:e=>this.resolveUri(e),getCompanion:()=>this.companionElement,setCompanion:e=>{this.companionElement=e},getOverlayImage:()=>this.overlayImageEl,setOverlayImage:e=>{this.overlayImageEl=e},getImageAssetTimer:()=>this.imageAssetTimer,setImageAssetTimer:e=>{this.imageAssetTimer=e},isChaining:()=>this.chaining,log:(...e)=>this.log(...e)}),this.preloader=new v({state:this.state,clock:this.clock,adStartBudgetMs:AdPlayerController.AD_START_BUDGET_MS,gamPodAdStartBudgetMs:AdPlayerController.GAM_POD_AD_START_BUDGET_MS,minAdStartBudgetMs:AdPlayerController.MIN_AD_START_BUDGET_MS,debug:this.debug,isPlaying:()=>this.isPlaying,preloadMode:this.preloadMode,effectiveInsertionMode:()=>this.effectiveInsertionMode(),getVariant:e=>this.getVariant(e),getAssets:e=>this.getAssets(e),resolveUri:e=>this.resolveUri(e),resolveAssetUri:(e,t)=>this.resolveAssetUri(e,t),getCompanionVariant:e=>this.getVariant(e),getAdPlayer:()=>this.adPlayer,getAdContainer:()=>this.adContainer,buildVastTagUrl:(e,t)=>this.buildVastTagUrl(e,t),resolveChainedSuccessor:e=>this.resolveChainedSuccessor(e),show:()=>this.show(),reapplyAdContainerLayout:e=>this.reapplyAdContainerLayout(e),getCurrentBreak:()=>this.currentBreak,onBreakVisible:e=>this.callbacks?.onBreakVisible?.(e),onAdError:e=>this.onAdError(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.presentationModes=new C(this.state,{contentPlayer:this.contentPlayer,getAdPlayer:()=>this.adPlayer,insertionMode:this.insertionMode,getCurrentBreak:()=>this.currentBreak,getCurrentFormat:()=>this.currentSelectedFormat,isSharedElementActive:()=>this.state.sharedAdClaimActive,getVariant:e=>this.getVariant(e),isAdPlaying:()=>this.isAdPlaying(),hasCurrentAsset:()=>null!==this.currentAsset,contentSourceIsReloadable:()=>null!==this.sharedElementPlayer.restorableContentSource(),adoptPictureInPictureMidBreak:()=>this.adoptPictureInPictureMidBreak(),restoreLayout:e=>this.restoreLayout(e),applyLayout:e=>this.applyLayout(e),show:()=>this.show(),playAdThroughContentElement:()=>this.sharedElementPlayer.playAdThroughContentElement(),getContentPositionAtBreakStart:()=>this.state.contentPositionAtBreakStart,setContentPositionAtBreakStart:e=>this.resumeCoordinator.reanchorMidBreak(e),gateContentForBreak:()=>this.gateContentForBreak(),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.resumeCoordinator=new f(this.state,{contentPlayer:this.contentPlayer,clock:this.clock,getInsertionMode:()=>this.effectiveInsertionMode(),gateContentForBreak:()=>this.gateContentForBreak(),clearContentGate:e=>this.clearContentGate(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.recoveryDeps={contentPlayer:e,getCallbacks:()=>this.callbacks,preloadMode:d,contentRecovery:M,resumeCoordinator:this.resumeCoordinator,diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)},this.sharedElementPlayer=new k(this.state,{contentPlayer:this.contentPlayer,getAdPlayer:()=>this.adPlayer,resolveAssetUri:(e,t)=>this.resolveAssetUri(e,t),liveEdgeDistanceSec:()=>this.resumeCoordinator.liveEdgeDistanceSec(),rebindContentElementIfSwapped:()=>this.rebindContentElementIfSwapped(),createAdAdapter:(e,t)=>this.createAdAdapter(e,t),reportAdProgress:e=>this.reportAdProgress(e),processTimedMetadata:e=>this.gamPodBridge.processTimedMetadata(e),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e),clearContentGate:()=>this.clearContentGate(),hide:()=>this.hide(),waitForLiveEdge:e=>this.resumeCoordinator.waitForLiveEdge(e),getVariant:e=>this.getVariant(e),getAssets:e=>this.getAssets(e)}),this.variantSelector=new b(this.state,{getEffectiveInsertionMode:()=>this.effectiveInsertionMode(),singleSurfaceDevice:this.singleSurfaceDevice,preloadMode:this.preloadMode,getIsContentPictureInPicture:()=>this.isContentPictureInPicture(),getIsGamReady:()=>this.isGamReady(),getSupportsParallelBuffering:()=>this.contentPlayer.supportsParallelBuffering,diagnose:(e,t,r)=>this.diagnose(e,t,r)}),this.assetPlayback=new B(this.state,{getAdPlayer:()=>this.adPlayer,getAdContainer:()=>this.adContainer,getAdMediaContainer:()=>this.adMediaContainer,clearStaticQuartiles:()=>this.staticQuartilesFired.clear(),getVariant:e=>this.getVariant(e),getGamEventCallbacks:()=>this.gamEventCallbacks,getSequencer:()=>this.sequencer,debug:this.debug,resolveUri:e=>this.resolveUri(e),buildGamUrl:(e,t)=>this.buildGamUrl(e,t),buildVastTagUrl:(e,t)=>this.buildVastTagUrl(e,t),onAdError:e=>this.onAdError(e),onAdEnded:()=>this.onAdEnded(),drive:e=>this.drive(e),clearOverlayImage:()=>this.clearOverlayImage(),revealFirstFrame:()=>this.preloader.revealFirstFrame(),transferPictureInPictureToAd:()=>this.presentationModes.transferPictureInPictureToAd(),isGamPodAsset:e=>this.isGamPodAsset(e),hasGamIdentityMismatch:e=>this.gamPodBridge.hasIdentityMismatch(e),beginGamPodTracking:e=>this.gamPodBridge.beginGamPodTracking(e),recordAdProgress:e=>this.adPlayerEvents.recordAdProgress(e),reportPhase:e=>this.reportPhase(e),armAdStartBudget:e=>this.armAdStartBudget(e),remainingAdStartBudgetMs:()=>this.remainingAdStartBudgetMs(),loadWithinBudget:(e,t)=>this.loadWithinBudget(e,t),waitForFirstFrame:()=>this.waitForFirstFrame(),getOverlayImage:()=>this.overlayImageEl,setOverlayImage:e=>{this.overlayImageEl=e},getImageAssetTimer:()=>this.imageAssetTimer,setImageAssetTimer:e=>{this.imageAssetTimer=e},getVastPodPosition:()=>this.vastPodPosition,setVastPodPosition:e=>{this.vastPodPosition=e},diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.breakSequenceDriver=new E(this.state,{getChainResolver:()=>this.chainResolver,getEffectiveInsertionMode:()=>this.effectiveInsertionMode(),getVastPodPosition:()=>this.vastPodPosition,setVastPodPosition:e=>{this.vastPodPosition=e},getPendingAdError:()=>this.pendingAdError,setPendingAdError:e=>{this.pendingAdError=e},getChaining:()=>this.chaining,setChaining:e=>{this.chaining=e},isExpandingPodAsset:e=>this.isExpandingPodAsset(e),fallBackToPodLevelReporting:()=>this.fallBackToPodLevelReporting(),resetGamPodTracking:()=>this.resetGamPodTracking(),emitGamPodSteps:e=>this.gamPodBridge.emitGamPodSteps(e),playAsset:(e,t,r)=>this.playAsset(e,t,r),endBreak:()=>this.endBreak(),playBreak:(e,t,r)=>this.playBreak(e,t,r),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.adPlayerEvents=new F(this.state,{getAdPlayer:()=>this.adPlayer,getContentPlayer:()=>this.contentPlayer,getGamEventCallbacks:()=>this.gamEventCallbacks,getSequencer:()=>this.sequencer,getAudioFocus:()=>this.audioFocus,getSyncing:()=>this.syncing,setSyncing:e=>{this.syncing=e},setAdVolumeChangeHandler:e=>{this.adVolumeChangeHandler=e},setContentVolumeHandler:e=>{this.contentVolumeHandler=e},notifyVolumeChange:()=>this.notifyVolumeChange(),onAdEnded:()=>this.onAdEnded(),processTimedMetadata:e=>this.gamPodBridge.processTimedMetadata(e),toAdError:e=>this.toAdError(e),revealFirstFrame:()=>this.revealFirstFrame(),clearFirstFrameResolver:()=>this.preloader.clearFirstFrameResolver(),drive:e=>this.drive(e),setPendingAdError:e=>{this.pendingAdError=e},log:(...e)=>this.log(...e),maybePrepositionContentForResume:()=>"single-decoder"!==this.preloadMode&&this.resumeCoordinator.maybePrepositionContentForResume(),maybeCatchUpContentForResume:e=>"single-decoder"!==this.preloadMode&&this.resumeCoordinator.maybeCatchUpContentForResume(e),getStaticQuartilesFired:()=>this.staticQuartilesFired,onGamPodAdProgress:e=>this.gamPodBridge.onGamPodAdProgress(e)})}setGamEventCallbacks(e){this.gamPodBridge.setEventCallbacks(e)}setDiagnoseHandler(e){this.diagnoseHandler=e}diagnose(e,t,r){this.diagnoseHandler?.(e,t,r)}holdContentForPreRoll(e){if(this.preRollHoldActive)return;const t=this.getVariant(e);t&&this.shouldPauseContent(t.format)&&(this.preRollHoldActive=!0,this.contentPlayer.pause(),this.preRollHoldHandler=()=>{this.preRollHoldActive&&this.contentPlayer.pause()},this.contentPlayer.on("playing",this.preRollHoldHandler),this.diagnose("DA-PREROLL-CONTENT-HELD","Content held at session start until the pending pre-roll begins.",{breakId:e.id}))}releaseContentHold(){this.preRollHoldActive&&(this.preRollHoldActive=!1,this.preRollHoldHandler&&(this.contentPlayer.off("playing",this.preRollHoldHandler),this.preRollHoldHandler=null))}gateContentForBreak(){this.contentPlayer.pause(),this.breakContentGateHandler||(this.breakContentGateHandler=()=>{this.contentPaused&&!this.state.resumeCatchupActive&&this.contentPlayer.pause()},this.contentPlayer.on("playing",this.breakContentGateHandler))}clearContentGate(e=!1){this.resumeCoordinator.endResumeCatchup(e),this.breakContentGateHandler&&(this.contentPlayer.off("playing",this.breakContentGateHandler),this.breakContentGateHandler=null)}setChainResolver(e){this.chainResolver=e}setResumeCueAnchorResolver(e){this.resumeCoordinator.setCueAnchorResolver(e)}setResumeCueEndResolver(e){this.resumeCoordinator.setCueEndResolver(e)}ingestStreamClockCue(e){this.resumeCoordinator.ingestStreamClockCue(e)}setTransitionPhaseReporter(e){this.transitionPhaseReporter=e}reportPhase(e){this.transitionPhaseReporter?.(e)}setBreakResumePolicy(e,t,r=!1){this.adInsertionType=e,this.breakTimebase=t,this.state.continueContentDuringBreak=r,this.state.continueRefusalReported=!1}initialize(){this.adContainer||(this.setupOverlay(),this.presentationModes.setupPictureInPictureTracking(),"adaptive"===this.insertionMode&&this.presentationModes.setupFullscreenTracking())}async startGamSession(e,t){await this.gamPodBridge.startGamSession(e,t)}endGamSession(){this.gamPodBridge.endGamSession()}setSessionAssetParameters(e){this.assetParameters.setSessionAssetParameters(e)}setManifestAssetParameters(e){this.assetParameters.setManifestAssetParameters(e)}updateAssetParameters(e){this.assetParameters.updateAssetParameters(e)}updateAssetParameterMacros(e){this.assetParameters.updateAssetParameterMacros(e)}get updatedAssetParameters(){return this.state.updatedAssetParameters}setSessionAssetParameterMacros(e){this.assetParameters.setSessionAssetParameterMacros(e)}get sessionAssetParameterMacros(){return this.assetParameters.getSessionAssetParameterMacros()}buildVastTagUrl(e,t){return this.assetParameters.buildVastTagUrl(e,t)}pushAssetParameters(e,t){this.assetParameters.pushAssetParameters(e,t)}setupOverlay(){this.adStage.setupOverlay()}isGamPodAsset(e){return this.gamPodBridge.isGamPodAsset(e)}isExpandingPodAsset(e){return this.gamPodBridge.isExpandingPodAsset(e)}fallBackToPodLevelReporting(){this.gamPodBridge.fallBackToPodLevelReporting()}resetGamPodTracking(){this.gamPodBridge.resetGamPodTracking()}emitGamPodSteps(e){this.gamPodBridge.emitGamPodSteps(e)}isGamEnabled(){return this.gamPodBridge.isGamEnabled()}isGamReady(){return this.gamPodBridge.isGamReady()}isOverlayInsertion(){return"overlay"===this.effectiveInsertionMode()}settleAssetProgress(){this.adPlayerEvents.settleAssetProgress()}reportAdProgress(e){this.adPlayerEvents.reportAdProgress(e)}setupEventListeners(){this.adPlayerEvents.setupEventListeners()}async preload(e){return this.preloader.preload(e)}renderLshapeContentBackdrop(e){this.adStage.renderLshapeContentBackdrop(e)}currentInsertionMode(){return this.presentationModes.currentInsertionMode()}effectiveInsertionMode(){return this.presentationModes.effectiveInsertionMode()}isContentPictureInPicture(){return this.presentationModes.isPictureInPicture()}rebindContentElementIfSwapped(){this.presentationModes.rebindContentElementIfSwapped()}teardownFullscreenTracking(){this.presentationModes.teardownFullscreenTracking()}teardownPictureInPictureTracking(){this.presentationModes.teardownPictureInPictureTracking()}isPictureInPicture(){return this.presentationModes.isPictureInPicture()}pictureInPictureOwner(){return this.presentationModes.pictureInPictureOwner()}isShowingAd(){if(!this.isAdPlaying())return!1;const e=this.currentDeclaredFormat();return!n(e,this.isContentPictureInPicture())}currentDeclaredFormat(){return this.currentSelectedFormat??(this.currentBreak?l(this.currentBreak):void 0)}async playBreak(t,s,a){if(this.state.preloadGeneration++,this.resumeGeneration++,!this.sharedElementPlayer.beginSharedActivity())return;this.releaseContentHold(),this.rebindContentElementIfSwapped();const n=a?.effectiveDurationSec??null;this.effectiveBreakDurationSec=null!==n&&n>0?n:null;const d=this.effectiveBreakDurationSec??t.duration;if("shared-element"===this.effectiveInsertionMode())return g(this.state),void await this.sharedElementPlayer.playSharedElementBreak(t,s);if(!this.adPlayer)return void this.log("playBreak called before initialize()");const l=this.getVariant(t);if(!l)return void this.log("No valid variant found for break:",t.id);this.currentBreak=t,this.callbacks=s,this.isPlaying=!0,this.firstFrameGateActive=a?.firstFrameGate??!1,this.firstFrameGateShown=!1;const h=this.continueContentDuringBreakReason(l.format),u=r(t),c=this.shouldPauseContent(l.format)&&"ok"===h&&!u;c||u||this.state.continueRefusalReported||!this.shouldPauseContent(l.format)||(this.state.continueRefusalReported=!0,this.diagnose("DA-CONTINUE-PLAYOUT-REFUSED",`Content will be paused for breaks this session: ${h}`,{reason:h,format:l.format})),this.audioFocus=l.format===e.DOUBLE?this.doubleBoxAudio:c?"ad":null,this.adPlayer&&("content"===this.audioFocus?(this.adPlayer.muted=!0,this.adPlayer.volume=0):(this.adPlayer.muted=this.contentPlayer.muted,this.adPlayer.volume=this.contentPlayer.volume,"ad"===this.audioFocus&&(this.contentPlayer.muted=!0)));const m=this.declaredFormatOf(t);if(this.currentSelectedFormat=m,this.state.pipAdoptedForBreak=i(m,this.isContentPictureInPicture()),this.state.pipAdoptedForBreak&&this.diagnose("DA-PIP-FORMAT-OVERRIDE",`Picture-in-picture: ${m} break plays as single`,{declared:m,effective:e.SINGLE,reason:"picture-in-picture",midBreak:!1}),this.shouldPauseContent(l.format)?(this.resumeCoordinator.captureBreakAnchor(t),c?(this.contentPaused=!1,this.resumeCoordinator.beginContinueContentPlayout()):(this.contentPaused=!0,this.gateContentForBreak())):this.contentPaused=!1,this.applyLayout(l),l.format===e.LSHAPE_CONTENT)return this.renderLshapeContentBackdrop(l),void(d&&d>0?(this.log("Starting duration timer:",d,"seconds"),this.durationTimer=setTimeout(()=>{this.log("Duration timer expired, ending break"),this.endBreak()},1e3*d)):this.endBreak());this.firstFrameGateActive||(this.show(),this.reapplyAdContainerLayout(l));if(0===this.getAssets(t).length)return this.log("No assets in break, ending immediately"),void this.endBreak();{const e=Math.max(0,d||0)+this.adBreakCutSafetyMarginSec;T(this.state,e,()=>{this.log("Break-cut timer expired, ending break"),this.firstFrameRejector?this.onAdError(new R("Break cut before first frame rendered","DA-AD-START-TIMEOUT")):this.sequencer&&this.currentBreak&&this.isPlaying?(this.callbacks?.onBreakCut?.(this.currentBreak),this.drive(this.sequencer.onOutcome({kind:"break-elapsed"}))):this.endBreak()},()=>this.onAdError(new R("Ad playback startup timed out","DA-AD-START-TIMEOUT")))}this.sequencer=new o("overlay",()=>null,this.selectionInputs()),await this.drive(this.sequencer.beginBreak(t)),this.preloadChainedSuccessor(t.id)}get resumeHandoverInMotion(){return this.state.resumeCatchupActive}reapplyAdContainerLayout(e){this.adStage.reapplyAdContainerLayout(e)}adoptPictureInPictureMidBreak(){this.presentationModes.adoptPictureInPictureMidBreak()}async restorePictureInPictureToContent(){await this.presentationModes.restorePictureInPictureToContent()}continueContentDuringBreakReason(e){return this.variantSelector.continueContentDuringBreakReason(e)}shouldPauseContent(t){return t===e.SINGLE||t===e.LSHAPE_AD}selectionInputs(){return this.variantSelector.selectionInputs()}breakNothingToPlayReason(e){return this.variantSelector.breakNothingToPlayReason(e)}unknownVariantFormatsOf(e){return this.variantSelector.unknownVariantFormatsOf(e)}diagnoseUnknownVariantFormats(e){this.variantSelector.diagnoseUnknownVariantFormats(e)}declaredFormatOf(e){const{selected:t,deviceQualified:r}=h(e,this.selectionInputs());return(t??r)?.format??l(e)}getVariant(e){return this.variantSelector.getVariant(e)}applyLayout(e){this.adStage.applyLayout(e)}restoreLayout(e){this.adStage.restoreLayout(e)}getAssets(e){return d(this.getVariant(e))}async playAsset(e,t,r){return this.assetPlayback.playAsset(e,t,r)}clearOverlayImage(){this.adStage.clearOverlayImage()}async showPauseImage(e){return this.pauseAdPresenter.showPauseImage(e)}hidePauseImage(){this.pauseAdPresenter.hidePauseImage()}async drive(e){return this.breakSequenceDriver.drive(e)}emitStep(e){this.breakSequenceDriver.emitStep(e)}async resolveAssetUri(e,t){return this.assetPlayback.resolveAssetUri(e,t)}async buildGamUrl(e,t){return this.gamPodBridge.buildGamUrl(e,t)}resolveUri(e){return this.assetParameters.resolveUri(e)}adPlayerStreamRemainingSec(){return this.assetPlayback.adPlayerStreamRemainingSec()}onAdEnded(){this.currentBreak&&this.isPlaying&&this.sequencer&&(this.settleAssetProgress(),this.drive(this.sequencer.onOutcome({kind:"asset-ended"})))}toAdError(e){return this.assetPlayback.toAdError(e)}onAdError(e){this.adPlayerEvents.onAdError(e)}endBreak(){if(!this.currentBreak)return;this.log("Break ended:",this.currentBreak.id),M(this.state),this.state.gamPodTracker&&this.emitGamPodSteps(this.state.gamPodTracker.finish()),this.resetGamPodTracking(),this.pushAssetParameters(void 0);const e=this.currentBreak,s=this.getVariant(e)?.format;let a=this.abortingBreak?null:this.resolveChainedSuccessor(e.id);if(a){const e=this.breakNothingToPlayReason(a);this.diagnoseUnknownVariantFormats(a),e&&(this.diagnose("DA-BREAK-NO-PLAYABLE-ASSET",`chained break ${a.id} has no playable variant (${e}); it will not begin.`,{breakId:a.id,reason:e}),this.callbacks?.onAdError(a,void 0,new R(`Break ${a.id} has no playable variant (${e})`,"DA-BREAK-NO-PLAYABLE-ASSET")),this.callbacks?.onChainedBreakSkipped?.(a),a=null)}if(a)return void this.advanceToChainedBreak(e,a);if(this.currentSelectedFormat=void 0,this.resumeCoordinator.endContinueContentPlayout(),this.restorePictureInPictureToContent(),this.isPlaying=!1,this.currentBreak=null,this.resumeGeneration++,this.effectiveBreakDurationSec=null,g(this.state),this.preloader.clearWarmedBreaks(),this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.clearFirstFrame("Break ended before first frame"),"ad"===this.audioFocus&&this.adPlayer?(this.contentPlayer.muted=this.adPlayer.muted,this.contentPlayer.volume=this.adPlayer.volume):"content"===this.audioFocus&&this.adPlayer&&(this.adPlayer.muted=this.contentPlayer.muted,this.adPlayer.volume=this.contentPlayer.volume),this.audioFocus=null,this.clearOverlayImage(),this.vastAdManager?.reset(),this.hide(),this.restoreLayout(s),this.adPlayer?.pause(),this.state.sharedAdClaimActive){const t=this.callbacks;return this.sharedElementPlayer.detachSharedAdListeners(),this.abortingBreak=!1,this.state.earlyReturnResumeOffsetSec=null,this.sharedElementPlayer.restoreSharedElementContent(e),void t?.onBreakEnd(e)}const i="recreate"===this.recoveryDeps.contentRecovery&&"function"==typeof this.contentPlayer.recreateMediaPipeline,n="single-decoder"===this.preloadMode||i?this.adPlayer?.unload?.():void 0;if(this.contentPaused&&r(e))this.contentPaused=!1,this.clearContentGate();else if(this.contentPaused){this.contentPaused=!1,this.clearContentGate(this.resumeHandoverInMotion);const r=this.resumeGeneration;S(this.recoveryDeps,{breakInfo:e,earlyReturnOffsetSec:this.state.earlyReturnResumeOffsetSec,isLiveResume:this.breakTimebase===t.WALLCLOCK,released:n,isCurrent:()=>r===this.resumeGeneration})}this.abortingBreak=!1,this.state.earlyReturnResumeOffsetSec=null,this.callbacks?.onBreakEnd(e)}currentAdAsset(){return this.isPlaying?this.currentAsset:null}skipBreak(){this.isPlaying&&(this.log("Skipping break:",this.currentBreak?.id),M(this.state),this.sequencer&&this.currentBreak?this.drive(this.sequencer.onOutcome({kind:"break-elapsed"})):this.endBreak())}abortBreak(e){this.isPlaying&&(this.log("Early return — break removed from manifest:",this.currentBreak?.id),this.state.earlyReturnResumeOffsetSec=Math.max(0,e),this.abortingBreak=!0,M(this.state),this.sequencer&&this.currentBreak?this.drive(this.sequencer.onOutcome({kind:"break-elapsed"})):this.endBreak())}stopActiveBreak(){g(this.state),this.sharedElementPlayer.cancelSharedRestore()&&this.isPlaying&&(this.log("Aborting active break on session end:",this.currentBreak?.id),M(this.state),this.sharedElementPlayer.detachSharedAdListeners(),this.sharedElementPlayer.releaseContentElementAdPlayer(),this.adPlayer?.pause(),this.clearOverlayImage(),this.vastAdManager?.reset(),this.hide(),this.restoreLayout(this.currentBreak?this.getVariant(this.currentBreak)?.format??void 0:void 0),this.isPlaying=!1,this.currentBreak=null,this.currentAsset=null,this.contentPaused=!1,this.clearContentGate(),this.resumeCoordinator.endContinueContentPlayout(),this.effectiveBreakDurationSec=null,this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.clearFirstFrame("Break aborted before first frame"),this.audioFocus=null)}resolveChainedSuccessor(e){return this.breakSequenceDriver.resolveChainedSuccessor(e)}advanceToChainedBreak(e,t){this.breakSequenceDriver.advanceToChainedBreak(e,t)}preloadChainedSuccessor(e){this.preloader.preloadChainedSuccessor(e)}revealFirstFrame(){this.assetPlayback.revealFirstFrame()}armAdStartBudget(e){this.preloader.armAdStartBudget(e)}remainingAdStartBudgetMs(){return this.preloader.remainingAdStartBudgetMs()}loadWithinBudget(e,t){return this.preloader.loadWithinBudget(e,t)}async waitForFirstFrame(){return this.preloader.waitForFirstFrame()}clearFirstFrame(e="Break ended before first frame"){this.preloader.clearFirstFrame(e)}show(){this.adStage.show()}hide(){this.adStage.hide()}isAdPlaying(){return this.isPlaying}get muted(){return"content"===this.audioFocus?this.contentPlayer.muted:"ad"===this.audioFocus?this.adPlayer?this.adPlayer.muted:this.contentPlayer.muted:this.isPlaying&&this.adPlayer?this.adPlayer.muted:this.contentPlayer.muted}set muted(e){if("content"===this.audioFocus)this.contentPlayer.muted=e;else if("ad"===this.audioFocus)this.adPlayer&&(this.adPlayer.muted=e);else{(this.isPlaying&&this.adPlayer?this.adPlayer:this.contentPlayer).muted=e}this.vastAdManager?.setMuted(e),this.notifyVolumeChange()}get volume(){return"content"===this.audioFocus?this.contentPlayer.volume:"ad"===this.audioFocus?this.adPlayer?this.adPlayer.volume:this.contentPlayer.volume:this.isPlaying&&this.adPlayer?this.adPlayer.volume:this.contentPlayer.volume}set volume(e){if("content"===this.audioFocus)this.contentPlayer.volume=e;else if("ad"===this.audioFocus)this.adPlayer&&(this.adPlayer.volume=e);else{(this.isPlaying&&this.adPlayer?this.adPlayer:this.contentPlayer).volume=e}this.vastAdManager?.setVolume(e),this.notifyVolumeChange()}setVolumeChangeCallback(e){this.volumeChangeCallback=e}notifyVolumeChange(){this.volumeChangeCallback?.(this.muted,this.volume)}destroy(){if(this.destroyed)return;if(this.resumeGeneration++,g(this.state),!this.sharedElementPlayer.beginSharedActivity())return;this.destroyed=!0,this.adStage.destroy(),this.resumeCoordinator.cancelResumeLandedProbe(),this.resumeCoordinator.dispose(),this.resumeCoordinator.endResumeCatchup(),this.resumeCoordinator.endContinueContentPlayout(),this.state.resumePrepositionSettle&&(clearTimeout(this.state.resumePrepositionSettle),this.state.resumePrepositionSettle=null),this.releaseContentHold(),this.clearContentGate(),this.clearFirstFrame("Controller destroyed before first frame"),this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.resetGamPodTracking(),M(this.state),this.companionRemoveTimer&&(clearTimeout(this.companionRemoveTimer),this.companionRemoveTimer=null),this.adFadeTimer&&(clearTimeout(this.adFadeTimer),this.adFadeTimer=null),this.adPlayer?.pause(),this.clearOverlayImage(),this.pauseAdPresenter.destroy(),this.contentVolumeHandler&&(this.contentPlayer.off("volumechange",this.contentVolumeHandler),this.contentVolumeHandler=null),this.sharedElementPlayer.detachSharedAdListeners(),this.sharedElementPlayer.releaseContentElementAdPlayer(),this.state.pipTransferredToAd=!1,this.teardownFullscreenTracking(),this.teardownPictureInPictureTracking(),this.adVolumeChangeHandler&&this.adPlayer&&this.adPlayer.off("volumechange",this.adVolumeChangeHandler),this.adVolumeChangeHandler=null,this.hide(),this.adStage.destroy(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.contentVideoMutationObserver?.disconnect(),this.contentVideoMutationObserver=null,this.contentVideoElement&&this.contentVideoGeometryHandler&&(this.contentVideoElement.removeEventListener("loadedmetadata",this.contentVideoGeometryHandler),this.contentVideoElement.removeEventListener("resize",this.contentVideoGeometryHandler)),this.contentVideoElement=null,this.contentVideoGeometryHandler=null;const e=this.adStage.restoreContent(this.playerContainerCreatedBySDK,this.playerContainerOriginalStyle);this.companionElement&&this.companionElement.parentElement&&(this.companionElement.parentElement.removeChild(this.companionElement),this.companionElement=null),this.isPlaying=!1,this.currentBreak=null,this.adContainer&&this.adContainer.parentElement&&this.adContainer.parentElement.removeChild(this.adContainer),!e&&this.stage&&this.stage.parentElement&&this.stage.parentElement.removeChild(this.stage),this.stage=null,this.adContainer=null,this.adMediaContainer=null;try{this.adPlayer?.destroy()}catch(e){this.log("Ad player adapter destroy failed (ignored):",e)}this.adPlayer=null,this.callbacks=null,this.gamPodBridge.destroy(),this.vastAdManager?.destroy(),this.vastAdManager=null,this.log("Ad player destroyed")}log(...e){this.debug&&u("[OptiViewAds:AdPlayerController]",...e)}}AdPlayerController.AD_START_BUDGET_MS=5e3,AdPlayerController.GAM_POD_AD_START_BUDGET_MS=1e4,AdPlayerController.MIN_AD_START_BUDGET_MS=3e3;
@@ -1 +1 @@
1
- import{BreakEvent as e,Timebase as t,getBreakEvent as a,getPostRollDelay as i,getPreRollDelay as r,isEventTrigger as s,isPauseBreak as n}from"../types/BreakManifest";import{DEFAULT_BREAK_WARNINGS as d,DEFAULT_PDT_GRACE_SECONDS as o}from"../types/OptiViewAdsConfig";import{PTS_MATCH_TOLERANCE_SECONDS as l}from"./MetadataCueTracker";import{debugLog as h}from"../diagnostics/debugLog";import{createBreakTimingState as k,getBreakStartTime as c,getCurrentTime as u,secondsUntilBreak as b}from"./breakTiming";import{RewindRearm as g}from"./RewindRearm";export const systemClock={now:()=>Date.now()};export var BreakState;!function(e){e.PENDING="pending",e.CHAINED="chained",e.ACTIVE="active",e.COMPLETED="completed",e.SKIPPED="skipped"}(BreakState||(BreakState={}));export class BreakScheduler{constructor(e,t=!1,a={enabled:!1,maxGapSeconds:0},i=systemClock,r={enabled:!1,minBreakDurationSeconds:0},s=null,n=d,l=null,h=o){this.breaks=new Map,this.timing=k(),this.checkInterval=null,this.onBreakStart=null,this.onBreakApproaching=null,this.onBreakWarning=null,this.onBreakAborted=null,this.abortNotifiedBreakIds=new Set,this.preloadedBreakIds=new Set,this.breakWarnings=d,this.breakWarningFired=new Map,this.completedBreakIds=new Set,this.unsupportedEventBreakIds=new Set,this.playbackEndedAtMs=null,this.anvatoEnteredDiagnosed=new Set,this.retiredBreaks=new Map,this.minSeenTime=null,this.JOIN_DISCRIMINATOR_SLACK_MS=1e3,this.WINDOW_ESCAPE_GRACE_MS=12e3,this.TIMING_TOLERANCE_MS=5e3,this.PRELOAD_AHEAD_SECONDS=8,this.contentReloading=!1,this.startupSeeking=!1,this.player=e,this.debug=t,this.chainingEnabled=a.enabled,this.maxChainGapMs=1e3*Math.max(0,a.maxGapSeconds),this.tuneInEnabled=r.enabled,this.minBreakDurationMs=1e3*Math.max(0,r.minBreakDurationSeconds),this.clock=i,this.diagnose=s,this.breakWarnings=n,this.cueTracker=l;const c=Math.max(0,h);this.timingDeps={player:this.player,clock:this.clock,cueTracker:this.cueTracker,diagnose:this.diagnose,log:(...e)=>this.log(...e),pdtGraceSeconds:c,pdtGraceMs:1e3*c},this.rewind=new g({breaks:this.breaks,retiredBreaks:this.retiredBreaks,completedBreakIds:this.completedBreakIds,preloadedBreakIds:this.preloadedBreakIds,timing:this.timing,clock:this.clock,log:(...e)=>this.log(...e),getBreakStartTime:e=>this.getBreakStartTime(e)})}claimChain(e){if(!this.chainingEnabled)return;let t=this.breaks.get(e)?.break??null;for(;t;){const e=this.findSuccessor(t);if(!e)break;const a=this.breaks.get(e.id);if(!a||a.state!==BreakState.PENDING)break;a.state=BreakState.CHAINED,this.log(`🔗 Break "${e.id}" claimed as chained after "${t.id}"`),t=e}}getChainedSuccessor(e){if(!this.chainingEnabled)return null;const t=this.breaks.get(e)?.break;return t?this.findSuccessor(t,[BreakState.PENDING,BreakState.CHAINED]):null}activateChainedBreak(e){const t=this.breaks.get(e);t&&(t.state=BreakState.ACTIVE)}findSuccessor(e,t=[BreakState.PENDING]){const a=this.getBreakStartTime(e);if(null===a)return null;const i=a+1e3*(e.duration??0);let r=null;for(const s of this.breaks.values()){if(s.break.id===e.id)continue;if(!t.includes(s.state))continue;const n=this.getBreakStartTime(s.break);if(null===n)continue;if(n<=a)continue;const d=n-i;d>this.maxChainGapMs||(d<-this.TIMING_TOLERANCE_MS||(!r||n<r.start)&&(r={break:s.break,start:n}))}return r?.break??null}updateManifest(e){this.timing.timebase=e.timebase,this.rewind.setAdStartDelayMs(1e3*Math.max(0,e.adStartDelay??0));for(const t of e.breaks){if(n(t))continue;if(!this.isSchedulableEvent(t))continue;if(this.completedBreakIds.has(t.id))continue;const e=this.breaks.get(t.id);e?e.state===BreakState.PENDING&&(e.break=t):(this.breaks.set(t.id,{break:t,state:BreakState.PENDING}),this.log(`📅 Break scheduled: "${t.id}" at ${this.describeStart(t)}`))}const t=new Set(e.breaks.map(e=>e.id));for(const[e,a]of this.breaks)t.has(e)||a.state!==BreakState.ACTIVE||this.abortNotifiedBreakIds.has(e)||(this.abortNotifiedBreakIds.add(e),this.log("Break removed from manifest while active (early return):",e),this.diagnose?.("DA-BREAK-EARLY-RETURN","Active break removed from manifest; returning to content early",{breakId:e}),this.onBreakAborted?.(a.break));this.cleanupBreaks(t)}resetForChannelSwitch(e){const t=this.getActiveBreak();for(const e of[...this.breaks.keys()])e!==t?.id&&this.breaks.delete(e);for(const e of[...this.abortNotifiedBreakIds])e!==t?.id&&this.abortNotifiedBreakIds.delete(e);this.completedBreakIds.clear(),this.retiredBreaks.clear(),this.preloadedBreakIds.clear(),this.breakWarningFired.clear(),this.unsupportedEventBreakIds.clear(),this.anvatoEnteredDiagnosed.clear(),this.timing.anvatoPendingDiagnosed.clear(),this.timing.anvatoMatchedDiagnosed.clear(),this.playbackEndedAtMs=null,this.rewind.beginChannel();const a=t?{...e,breaks:e.breaks.filter(e=>e.id!==t.id)}:e;this.updateManifest(a)}isSchedulableEvent(t){return!s(t.start)||t.start.event===e.START||t.start.event===e.END||(this.unsupportedEventBreakIds.has(t.id)||(this.unsupportedEventBreakIds.add(t.id),this.log(`⚠️ Break ignored: "${t.id}" (unsupported event trigger "${t.start.event}")`),this.diagnose?.("DA-BREAK-EVENT-UNSUPPORTED","Break triggered by an event this SDK version does not schedule; the break was ignored",{breakId:t.id,event:t.start.event})),!1)}describeStart(e){const t=r(e);if(null!==t)return t>0?`playback start + ${t}s`:"playback start";const a=i(e);return null!==a?a>0?`playback end + ${a}s`:"playback end":"string"==typeof e.start?new Date(e.start).toLocaleTimeString():String(e.start)}markPlaybackStart(){null!==this.playbackEndedAtMs&&(this.playbackEndedAtMs=null,this.log("Content replayed; pending post-rolls cancelled")),this.rewind.playbackStarted||(this.rewind.markPlaybackStart(this.peekPosition()),this.log("Content playback started at",new Date(this.clock.now()).toISOString()))}markPlaybackEnd(){null===this.playbackEndedAtMs&&(this.playbackEndedAtMs=this.clock.now(),this.log("Content playback ended at",new Date(this.playbackEndedAtMs).toISOString()))}start(e,t,a,i){this.onBreakStart=e,this.onBreakApproaching=t??null,this.onBreakWarning=a??null,this.onBreakAborted=i??null,this.checkInterval&&clearInterval(this.checkInterval),this.checkInterval=setInterval(()=>{this.tick()},250),this.log("Scheduler started")}tick(){this.checkBreaks()}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.onBreakStart=null,this.log("Scheduler stopped")}completeBreak(e){this.completedBreakIds.add(e),this.breakWarningFired.delete(e),this.abortNotifiedBreakIds.delete(e);const t=this.breaks.get(e);t&&(this.log("Break completed and removed:",e),null===a(t.break)&&null===this.cueTracker&&this.retiredBreaks.set(e,t.break),this.breaks.delete(e),this.preloadedBreakIds.delete(e))}setContentReloading(e){this.contentReloading=e,this.rewind.setContentReloading(e||this.startupSeeking)}setStartupSeeking(e){this.startupSeeking=e,this.rewind.setContentReloading(e||this.contentReloading)}notifyResumeSeek(e,t){this.rewind.notifyResumeSeek(e,t)}notifyViewerSeek(){this.rewind.notifyViewerSeek()}cleanupBreaks(e){const t=[];for(const[a,i]of this.breaks)i.state!==BreakState.COMPLETED&&i.state!==BreakState.SKIPPED&&(e.has(a)||i.state===BreakState.ACTIVE)||t.push(a);for(const e of t)this.breaks.delete(e),this.preloadedBreakIds.delete(e),this.breakWarningFired.delete(e)}getActiveBreak(){for(const e of this.breaks.values())if(e.state===BreakState.ACTIVE)return e.break;return null}getSecondsUntilBreak(e){const t=this.breaks.get(e);if(!t||t.state!==BreakState.PENDING)return null;const a=this.getCurrentTime();if(null===a)return null;const i=this.getBreakStartTime(t.break);return null===i?null:b(i,a)}notifyCuePresented(e){if(null===this.cueTracker||this.timing.timebase!==t.PTS)return null;if(!Number.isFinite(e))return null;let a=null;for(const t of this.breaks.values())if(t.state===BreakState.PENDING&&"number"==typeof t.break.start&&!(Math.abs(t.break.start-e)>l)){a=t.break.id;break}if(null===a)return null;const i=this.player.currentTime;this.checkBreaks();const r=this.breaks.get(a);return r&&r.state===BreakState.ACTIVE?this.anvatoEnteredDiagnosed.has(a)?null:(this.anvatoEnteredDiagnosed.add(a),this.log(`🎯 Break "${a}" armed by cue presentation (pts ${e})`),this.diagnose?.("DA-ANVATO-CUE-ENTERED",`Break "${a}" started from the presented cue (pts ${e}) rather than the scheduler tick.`,{breakId:a,pts:e,mediaTimeSec:i}),a):null}checkBreaks(){if(this.startupSeeking)return;const e=this.getCurrentTime();this.rewind.trackPlayedTime(e);const a=this.rewind.isAdStartDelayActive();null!==e&&(this.minSeenTime=null===this.minSeenTime?e:Math.min(this.minSeenTime,e),this.rewind.rearmOnRewind(e));for(const s of this.breaks.values()){if(s.state===BreakState.ACTIVE&&this.timing.timebase===t.WALLCLOCK&&null!==e&&!this.abortNotifiedBreakIds.has(s.break.id)){const t=this.getBreakStartTime(s.break),a=1e3*(s.break.duration??0);null!==t&&a>0&&e>t+a+this.WINDOW_ESCAPE_GRACE_MS&&(this.abortNotifiedBreakIds.add(s.break.id),this.log(`⚠️ Break window escaped: "${s.break.id}" (ended ${Math.round((e-t-a)/1e3)}s ago on the stream clock)`),this.diagnose?.("DA-BREAK-WINDOW-ESCAPED","Active break outlived its wallclock window; returning to content",{breakId:s.break.id,overrunSec:Math.round((e-t-a)/100)/10}),this.onBreakAborted?.(s.break));continue}if(s.state!==BreakState.PENDING)continue;const n=r(s.break);if(null!==n){this.checkPreRollBreak(s,n,a);continue}const d=i(s.break);if(null!==d){this.checkPostRollBreak(s,d,a);continue}if(null===e)continue;if(a)continue;null!==this.cueTracker&&this.timing.timebase===t.PTS&&this.maybePreload(s.break,"manifest arrival — Anvato flow");const o=this.getBreakStartTime(s.break);if(null===o)continue;const l=e-o,h=Math.round(-l/1e3);if(this.checkWarnings(s.break,h),h>0&&h<=15&&h%2==0&&this.log(`⏱️ Break "${s.break.id}" starts in ${h}s`),h>0&&h<=this.PRELOAD_AHEAD_SECONDS&&this.maybePreload(s.break,`${h}s ahead`),l>=0&&l<=this.TIMING_TOLERANCE_MS){const e=Math.max(0,l),t=1e3*(s.break.duration??0)-e;if(t<=0){this.log(`⚠️ Break missed: "${s.break.id}" (ended ${Math.round(-t/1e3)}s ago, inside the start tolerance)`),s.state=BreakState.SKIPPED,null===this.cueTracker&&this.retiredBreaks.set(s.break.id,s.break);break}if(null!==this.minSeenTime&&o<this.minSeenTime-this.JOIN_DISCRIMINATOR_SLACK_MS&&(!this.tuneInEnabled||t<this.minBreakDurationMs)){this.log(`⚠️ Break missed: "${s.break.id}" (joined in progress inside the start tolerance, ${Math.round(t/1e3)}s remaining < tune-in rules)`),s.state=BreakState.SKIPPED,null===this.cueTracker&&this.retiredBreaks.set(s.break.id,s.break);break}this.log(`🎬 BREAK TRIGGERED: "${s.break.id}"`),s.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(s.break,{tuneIn:!1,elapsedSec:e/1e3,remainingSec:t/1e3});break}if(l>this.TIMING_TOLERANCE_MS){const t=o+1e3*(s.break.duration??0)-e;if(this.tuneInEnabled&&t>=this.minBreakDurationMs&&t>0){this.log(`🎬 TUNE-IN BREAK TRIGGERED: "${s.break.id}" (${Math.round(t/1e3)}s remaining)`),s.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(s.break,{tuneIn:!0,elapsedSec:l/1e3,remainingSec:t/1e3});break}this.log(`⚠️ Break missed: "${s.break.id}" (was ${Math.round(l/1e3)}s ago)`),s.state=BreakState.SKIPPED,null===this.cueTracker&&this.retiredBreaks.set(s.break.id,s.break)}}}checkPreRollBreak(e,t,a){if(!this.rewind.playbackStarted)return;const i=1e3*t;if(this.rewind.adStartDelayMs>0&&i<this.rewind.adStartDelayMs)return this.log(`⚠️ Pre-roll skipped: "${e.break.id}" (delay ${t}s < adStartDelay ${this.rewind.adStartDelayMs/1e3}s)`),void(e.state=BreakState.SKIPPED);const r=this.rewind.channelPlayedMs,s=Math.round((i-r)/1e3);s>0&&s<=15&&s%2==0&&this.log(`⏱️ Pre-roll "${e.break.id}" starts in ${s}s`),s>0&&s<=this.PRELOAD_AHEAD_SECONDS&&this.maybePreload(e.break,`pre-roll, ${s}s ahead`),r>=i&&!a&&(this.log(`🎬 PRE-ROLL TRIGGERED: "${e.break.id}"${t>0?` (after ${t}s delay)`:""}`),e.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(e.break,{tuneIn:!1,elapsedSec:0,remainingSec:e.break.duration??0}))}checkPostRollBreak(e,t,a){if(null===this.playbackEndedAtMs)return;const i=1e3*t,r=this.clock.now()-this.playbackEndedAtMs,s=Math.round((i-r)/1e3);s>0&&s<=this.PRELOAD_AHEAD_SECONDS&&this.maybePreload(e.break,`post-roll, ${s}s ahead`),r>=i&&!a&&(this.log(`🎬 POST-ROLL TRIGGERED: "${e.break.id}"${t>0?` (after ${t}s delay)`:""}`),e.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(e.break,{tuneIn:!1,elapsedSec:0,remainingSec:e.break.duration??0}))}isAdStartDelayActive(){return this.rewind.isAdStartDelayActive()}getCurrentTime(){return u(this.timing,this.timingDeps)}maybePreload(e,t){if(this.preloadedBreakIds.has(e.id)||!this.onBreakApproaching)return;this.log(`⏳ Preloading break "${e.id}" (${t})`);!1!==this.onBreakApproaching(e)&&this.preloadedBreakIds.add(e.id)}getBreakStartTime(e){return s(e.start)?null:c(this.timing,this.timingDeps,e)}peekPosition(){if(this.timing.timebase!==t.WALLCLOCK)return 1e3*this.player.currentTime;const e=this.player.programDateTime?.getTime();return void 0===e||isNaN(e)?null:e}destroy(){this.stop(),this.breaks.clear(),this.preloadedBreakIds.clear(),this.completedBreakIds.clear(),this.retiredBreaks.clear(),this.minSeenTime=null,this.unsupportedEventBreakIds.clear(),this.playbackEndedAtMs=null,this.rewind.reset(),this.breakWarningFired.clear(),this.abortNotifiedBreakIds.clear(),this.timing.pdtMissingWarned=!1,this.timing.pdtSeen=!1,this.timing.firstPdtAttemptMs=null,this.timing.playbackStartedAtMs=null,this.timing.anvatoPendingDiagnosed.clear(),this.timing.anvatoMatchedDiagnosed.clear(),this.cueTracker?.clear()}checkWarnings(e,t){if(t<=0||0===this.breakWarnings.seconds.length)return;let a=this.breakWarningFired.get(e.id);a||(a=new Set,this.breakWarningFired.set(e.id,a));for(const i of this.breakWarnings.seconds)a.has(i)||t<=i&&(a.add(i),this.log(`Break warning for "${e.id}" (${t}s <= ${i}s)`),this.onBreakWarning?.(e,i,t))}log(...e){this.debug&&h("[OptiViewAds:BreakScheduler]",...e)}}
1
+ import{BreakEvent as e,Timebase as t,getBreakEvent as a,getPostRollDelay as i,getPreRollDelay as r,isEventTrigger as s,isPauseBreak as n}from"../types/BreakManifest";import{DEFAULT_BREAK_WARNINGS as d,DEFAULT_PDT_GRACE_SECONDS as o}from"../types/OptiViewAdsConfig";import{PTS_MATCH_TOLERANCE_SECONDS as l}from"./MetadataCueTracker";import{debugLog as h}from"../diagnostics/debugLog";import{createBreakTimingState as k,diagnoseAnvatoBreakEnd as c,getBreakStartTime as u,getCurrentTime as b,secondsUntilBreak as g}from"./breakTiming";import{RewindRearm as S}from"./RewindRearm";export const systemClock={now:()=>Date.now()};export var BreakState;!function(e){e.PENDING="pending",e.CHAINED="chained",e.ACTIVE="active",e.COMPLETED="completed",e.SKIPPED="skipped"}(BreakState||(BreakState={}));export class BreakScheduler{constructor(e,t=!1,a={enabled:!1,maxGapSeconds:0},i=systemClock,r={enabled:!1,minBreakDurationSeconds:0},s=null,n=d,l=null,h=o){this.breaks=new Map,this.timing=k(),this.checkInterval=null,this.onBreakStart=null,this.onBreakApproaching=null,this.onBreakWarning=null,this.onBreakAborted=null,this.abortNotifiedBreakIds=new Set,this.preloadedBreakIds=new Set,this.breakWarnings=d,this.breakWarningFired=new Map,this.completedBreakIds=new Set,this.unsupportedEventBreakIds=new Set,this.playbackEndedAtMs=null,this.anvatoEnteredDiagnosed=new Set,this.retiredBreaks=new Map,this.minSeenTime=null,this.JOIN_DISCRIMINATOR_SLACK_MS=1e3,this.WINDOW_ESCAPE_GRACE_MS=12e3,this.TIMING_TOLERANCE_MS=5e3,this.PRELOAD_AHEAD_SECONDS=8,this.contentReloading=!1,this.startupSeeking=!1,this.player=e,this.debug=t,this.chainingEnabled=a.enabled,this.maxChainGapMs=1e3*Math.max(0,a.maxGapSeconds),this.tuneInEnabled=r.enabled,this.minBreakDurationMs=1e3*Math.max(0,r.minBreakDurationSeconds),this.clock=i,this.diagnose=s,this.breakWarnings=n,this.cueTracker=l;const c=Math.max(0,h);this.timingDeps={player:this.player,clock:this.clock,cueTracker:this.cueTracker,diagnose:this.diagnose,log:(...e)=>this.log(...e),pdtGraceSeconds:c,pdtGraceMs:1e3*c},this.rewind=new S({breaks:this.breaks,retiredBreaks:this.retiredBreaks,completedBreakIds:this.completedBreakIds,preloadedBreakIds:this.preloadedBreakIds,timing:this.timing,clock:this.clock,log:(...e)=>this.log(...e),getBreakStartTime:e=>this.getBreakStartTime(e)})}claimChain(e){if(!this.chainingEnabled)return;let t=this.breaks.get(e)?.break??null;for(;t;){const e=this.findSuccessor(t);if(!e)break;const a=this.breaks.get(e.id);if(!a||a.state!==BreakState.PENDING)break;a.state=BreakState.CHAINED,this.log(`🔗 Break "${e.id}" claimed as chained after "${t.id}"`),t=e}}getChainedSuccessor(e){if(!this.chainingEnabled)return null;const t=this.breaks.get(e)?.break;return t?this.findSuccessor(t,[BreakState.PENDING,BreakState.CHAINED]):null}activateChainedBreak(e){const t=this.breaks.get(e);t&&(t.state=BreakState.ACTIVE)}findSuccessor(e,t=[BreakState.PENDING]){const a=this.getBreakStartTime(e);if(null===a)return null;const i=a+1e3*(e.duration??0);let r=null;for(const s of this.breaks.values()){if(s.break.id===e.id)continue;if(!t.includes(s.state))continue;const n=this.getBreakStartTime(s.break);if(null===n)continue;if(n<=a)continue;const d=n-i;d>this.maxChainGapMs||(d<-this.TIMING_TOLERANCE_MS||(!r||n<r.start)&&(r={break:s.break,start:n}))}return r?.break??null}updateManifest(e){this.timing.timebase=e.timebase,this.rewind.setAdStartDelayMs(1e3*Math.max(0,e.adStartDelay??0));for(const t of e.breaks){if(n(t))continue;if(!this.isSchedulableEvent(t))continue;if(this.completedBreakIds.has(t.id))continue;const e=this.breaks.get(t.id);e?e.state===BreakState.PENDING&&(e.break=t):(this.breaks.set(t.id,{break:t,state:BreakState.PENDING}),this.log(`📅 Break scheduled: "${t.id}" at ${this.describeStart(t)}`))}const t=new Set(e.breaks.map(e=>e.id));for(const[e,a]of this.breaks)t.has(e)||a.state!==BreakState.ACTIVE||this.abortNotifiedBreakIds.has(e)||(this.abortNotifiedBreakIds.add(e),this.log("Break removed from manifest while active (early return):",e),this.diagnose?.("DA-BREAK-EARLY-RETURN","Active break removed from manifest; returning to content early",{breakId:e}),this.onBreakAborted?.(a.break));this.cleanupBreaks(t)}resetForChannelSwitch(e){const t=this.getActiveBreak();for(const e of[...this.breaks.keys()])e!==t?.id&&this.breaks.delete(e);for(const e of[...this.abortNotifiedBreakIds])e!==t?.id&&this.abortNotifiedBreakIds.delete(e);this.completedBreakIds.clear(),this.retiredBreaks.clear(),this.preloadedBreakIds.clear(),this.breakWarningFired.clear(),this.unsupportedEventBreakIds.clear(),this.anvatoEnteredDiagnosed.clear(),this.timing.anvatoPendingDiagnosed.clear(),this.timing.anvatoMatchedDiagnosed.clear(),this.timing.anvatoEndDiagnosed.clear(),this.playbackEndedAtMs=null,this.rewind.beginChannel();const a=t?{...e,breaks:e.breaks.filter(e=>e.id!==t.id)}:e;this.updateManifest(a)}isSchedulableEvent(t){return!s(t.start)||t.start.event===e.START||t.start.event===e.END||(this.unsupportedEventBreakIds.has(t.id)||(this.unsupportedEventBreakIds.add(t.id),this.log(`⚠️ Break ignored: "${t.id}" (unsupported event trigger "${t.start.event}")`),this.diagnose?.("DA-BREAK-EVENT-UNSUPPORTED","Break triggered by an event this SDK version does not schedule; the break was ignored",{breakId:t.id,event:t.start.event})),!1)}describeStart(e){const t=r(e);if(null!==t)return t>0?`playback start + ${t}s`:"playback start";const a=i(e);return null!==a?a>0?`playback end + ${a}s`:"playback end":"string"==typeof e.start?new Date(e.start).toLocaleTimeString():String(e.start)}markPlaybackStart(){null!==this.playbackEndedAtMs&&(this.playbackEndedAtMs=null,this.log("Content replayed; pending post-rolls cancelled")),this.rewind.playbackStarted||(this.rewind.markPlaybackStart(this.peekPosition()),this.log("Content playback started at",new Date(this.clock.now()).toISOString()))}markPlaybackEnd(){null===this.playbackEndedAtMs&&(this.playbackEndedAtMs=this.clock.now(),this.log("Content playback ended at",new Date(this.playbackEndedAtMs).toISOString()))}start(e,t,a,i){this.onBreakStart=e,this.onBreakApproaching=t??null,this.onBreakWarning=a??null,this.onBreakAborted=i??null,this.checkInterval&&clearInterval(this.checkInterval),this.checkInterval=setInterval(()=>{this.tick()},250),this.log("Scheduler started")}tick(){this.checkBreaks()}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.onBreakStart=null,this.log("Scheduler stopped")}completeBreak(e){this.completedBreakIds.add(e),this.breakWarningFired.delete(e),this.abortNotifiedBreakIds.delete(e);const t=this.breaks.get(e);t&&(this.log("Break completed and removed:",e),null===a(t.break)&&null===this.cueTracker&&this.retiredBreaks.set(e,t.break),this.breaks.delete(e),this.preloadedBreakIds.delete(e))}setContentReloading(e){this.contentReloading=e,this.rewind.setContentReloading(e||this.startupSeeking)}setStartupSeeking(e){this.startupSeeking=e,this.rewind.setContentReloading(e||this.contentReloading)}notifyResumeSeek(e,t){this.rewind.notifyResumeSeek(e,t)}notifyViewerSeek(){this.rewind.notifyViewerSeek()}cleanupBreaks(e){const t=[];for(const[a,i]of this.breaks)i.state!==BreakState.COMPLETED&&i.state!==BreakState.SKIPPED&&(e.has(a)||i.state===BreakState.ACTIVE)||t.push(a);for(const e of t)this.breaks.delete(e),this.preloadedBreakIds.delete(e),this.breakWarningFired.delete(e)}getActiveBreak(){for(const e of this.breaks.values())if(e.state===BreakState.ACTIVE)return e.break;return null}getSecondsUntilBreak(e){const t=this.breaks.get(e);if(!t||t.state!==BreakState.PENDING)return null;const a=this.getCurrentTime();if(null===a)return null;const i=this.getBreakStartTime(t.break);return null===i?null:g(i,a)}notifyCuePresented(e){if(null===this.cueTracker||this.timing.timebase!==t.PTS)return null;if(!Number.isFinite(e))return null;let a=null;for(const t of this.breaks.values())if(t.state===BreakState.PENDING&&"number"==typeof t.break.start&&!(Math.abs(t.break.start-e)>l)){a=t.break.id;break}if(null===a)return null;const i=this.player.currentTime;this.checkBreaks();const r=this.breaks.get(a);return r&&r.state===BreakState.ACTIVE?this.anvatoEnteredDiagnosed.has(a)?null:(this.anvatoEnteredDiagnosed.add(a),this.log(`🎯 Break "${a}" armed by cue presentation (pts ${e})`),this.diagnose?.("DA-ANVATO-CUE-ENTERED",`Break "${a}" started from the presented cue (pts ${e}) rather than the scheduler tick.`,{breakId:a,pts:e,mediaTimeSec:i}),a):null}checkBreaks(){if(this.startupSeeking)return;const e=this.getCurrentTime();this.rewind.trackPlayedTime(e);const a=this.rewind.isAdStartDelayActive();null!==e&&(this.minSeenTime=null===this.minSeenTime?e:Math.min(this.minSeenTime,e),this.rewind.rearmOnRewind(e));for(const s of this.breaks.values()){if(s.state===BreakState.ACTIVE&&this.timing.timebase===t.WALLCLOCK&&null!==e&&!this.abortNotifiedBreakIds.has(s.break.id)){const t=this.getBreakStartTime(s.break),a=1e3*(s.break.duration??0);null!==t&&a>0&&e>t+a+this.WINDOW_ESCAPE_GRACE_MS&&(this.abortNotifiedBreakIds.add(s.break.id),this.log(`⚠️ Break window escaped: "${s.break.id}" (ended ${Math.round((e-t-a)/1e3)}s ago on the stream clock)`),this.diagnose?.("DA-BREAK-WINDOW-ESCAPED","Active break outlived its wallclock window; returning to content",{breakId:s.break.id,overrunSec:Math.round((e-t-a)/100)/10}),this.onBreakAborted?.(s.break));continue}if(s.state===BreakState.ACTIVE&&this.timing.timebase===t.PTS&&c(this.timing,this.timingDeps,s.break),s.state!==BreakState.PENDING)continue;const n=r(s.break);if(null!==n){this.checkPreRollBreak(s,n,a);continue}const d=i(s.break);if(null!==d){this.checkPostRollBreak(s,d,a);continue}if(null===e)continue;if(a)continue;null!==this.cueTracker&&this.timing.timebase===t.PTS&&this.maybePreload(s.break,"manifest arrival — Anvato flow");const o=this.getBreakStartTime(s.break);if(null===o)continue;const l=e-o,h=Math.round(-l/1e3);if(this.checkWarnings(s.break,h),h>0&&h<=15&&h%2==0&&this.log(`⏱️ Break "${s.break.id}" starts in ${h}s`),h>0&&h<=this.PRELOAD_AHEAD_SECONDS&&this.maybePreload(s.break,`${h}s ahead`),l>=0&&l<=this.TIMING_TOLERANCE_MS){const e=Math.max(0,l),t=1e3*(s.break.duration??0)-e;if(t<=0){this.log(`⚠️ Break missed: "${s.break.id}" (ended ${Math.round(-t/1e3)}s ago, inside the start tolerance)`),s.state=BreakState.SKIPPED,null===this.cueTracker&&this.retiredBreaks.set(s.break.id,s.break);break}if(null!==this.minSeenTime&&o<this.minSeenTime-this.JOIN_DISCRIMINATOR_SLACK_MS&&(!this.tuneInEnabled||t<this.minBreakDurationMs)){this.log(`⚠️ Break missed: "${s.break.id}" (joined in progress inside the start tolerance, ${Math.round(t/1e3)}s remaining < tune-in rules)`),s.state=BreakState.SKIPPED,null===this.cueTracker&&this.retiredBreaks.set(s.break.id,s.break);break}this.log(`🎬 BREAK TRIGGERED: "${s.break.id}"`),s.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(s.break,{tuneIn:!1,elapsedSec:e/1e3,remainingSec:t/1e3});break}if(l>this.TIMING_TOLERANCE_MS){const t=o+1e3*(s.break.duration??0)-e;if(this.tuneInEnabled&&t>=this.minBreakDurationMs&&t>0){this.log(`🎬 TUNE-IN BREAK TRIGGERED: "${s.break.id}" (${Math.round(t/1e3)}s remaining)`),s.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(s.break,{tuneIn:!0,elapsedSec:l/1e3,remainingSec:t/1e3});break}this.log(`⚠️ Break missed: "${s.break.id}" (was ${Math.round(l/1e3)}s ago)`),s.state=BreakState.SKIPPED,null===this.cueTracker&&this.retiredBreaks.set(s.break.id,s.break)}}}checkPreRollBreak(e,t,a){if(!this.rewind.playbackStarted)return;const i=1e3*t;if(this.rewind.adStartDelayMs>0&&i<this.rewind.adStartDelayMs)return this.log(`⚠️ Pre-roll skipped: "${e.break.id}" (delay ${t}s < adStartDelay ${this.rewind.adStartDelayMs/1e3}s)`),void(e.state=BreakState.SKIPPED);const r=this.rewind.channelPlayedMs,s=Math.round((i-r)/1e3);s>0&&s<=15&&s%2==0&&this.log(`⏱️ Pre-roll "${e.break.id}" starts in ${s}s`),s>0&&s<=this.PRELOAD_AHEAD_SECONDS&&this.maybePreload(e.break,`pre-roll, ${s}s ahead`),r>=i&&!a&&(this.log(`🎬 PRE-ROLL TRIGGERED: "${e.break.id}"${t>0?` (after ${t}s delay)`:""}`),e.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(e.break,{tuneIn:!1,elapsedSec:0,remainingSec:e.break.duration??0}))}checkPostRollBreak(e,t,a){if(null===this.playbackEndedAtMs)return;const i=1e3*t,r=this.clock.now()-this.playbackEndedAtMs,s=Math.round((i-r)/1e3);s>0&&s<=this.PRELOAD_AHEAD_SECONDS&&this.maybePreload(e.break,`post-roll, ${s}s ahead`),r>=i&&!a&&(this.log(`🎬 POST-ROLL TRIGGERED: "${e.break.id}"${t>0?` (after ${t}s delay)`:""}`),e.state=BreakState.ACTIVE,this.onBreakStart&&this.onBreakStart(e.break,{tuneIn:!1,elapsedSec:0,remainingSec:e.break.duration??0}))}isAdStartDelayActive(){return this.rewind.isAdStartDelayActive()}getCurrentTime(){return b(this.timing,this.timingDeps)}maybePreload(e,t){if(this.preloadedBreakIds.has(e.id)||!this.onBreakApproaching)return;this.log(`⏳ Preloading break "${e.id}" (${t})`);!1!==this.onBreakApproaching(e)&&this.preloadedBreakIds.add(e.id)}getBreakStartTime(e){return s(e.start)?null:u(this.timing,this.timingDeps,e)}peekPosition(){if(this.timing.timebase!==t.WALLCLOCK)return 1e3*this.player.currentTime;const e=this.player.programDateTime?.getTime();return void 0===e||isNaN(e)?null:e}destroy(){this.stop(),this.breaks.clear(),this.preloadedBreakIds.clear(),this.completedBreakIds.clear(),this.retiredBreaks.clear(),this.minSeenTime=null,this.unsupportedEventBreakIds.clear(),this.playbackEndedAtMs=null,this.rewind.reset(),this.breakWarningFired.clear(),this.abortNotifiedBreakIds.clear(),this.timing.pdtMissingWarned=!1,this.timing.pdtSeen=!1,this.timing.firstPdtAttemptMs=null,this.timing.playbackStartedAtMs=null,this.timing.anvatoPendingDiagnosed.clear(),this.timing.anvatoMatchedDiagnosed.clear(),this.timing.anvatoEndDiagnosed.clear(),this.cueTracker?.clear()}checkWarnings(e,t){if(t<=0||0===this.breakWarnings.seconds.length)return;let a=this.breakWarningFired.get(e.id);a||(a=new Set,this.breakWarningFired.set(e.id,a));for(const i of this.breakWarnings.seconds)a.has(i)||t<=i&&(a.add(i),this.log(`Break warning for "${e.id}" (${t}s <= ${i}s)`),this.onBreakWarning?.(e,i,t))}log(...e){this.debug&&h("[OptiViewAds:BreakScheduler]",...e)}}
@@ -11,6 +11,20 @@ export declare const ID3_IN_EMSG_SCHEME_ID_URIS: readonly string[];
11
11
  export declare function isId3InEmsgScheme(schemeIdUri: string | undefined): boolean;
12
12
  /** Tolerance (seconds) matching a manifest `start` PTS to a cue `pts`; encoder/backend rounding differs sub-millisecond. */
13
13
  export declare const PTS_MATCH_TOLERANCE_SECONDS = 0.005;
14
+ /**
15
+ * Tolerance (seconds) between a break's duration and its stream-signalled length (`cue_end` pts −
16
+ * break start pts). NFL Channel signalled 150.166–150.293s for 150s breaks (splice segments).
17
+ */
18
+ export declare const BREAK_END_LENGTH_TOLERANCE_SECONDS = 2;
19
+ /** The stream's own end of a break: the `type=cue_end` cue matched to it on the stream clock. */
20
+ export interface BreakEndMatch {
21
+ /** Media time (seconds) the `cue_end` was reported at, in the player's mapping at delivery. */
22
+ mediaTime: number;
23
+ /** Break length on the stream clock, `cue_end` pts − break start pts, in seconds. */
24
+ lengthSec: number;
25
+ /** `lengthSec` is within {@link BREAK_END_LENGTH_TOLERANCE_SECONDS} of the break duration. */
26
+ accepted: boolean;
27
+ }
14
28
  /** Anvato marker: GEOB with description "Anvatos" (MIME `application/json` when surfaced) or emsg with the Anvato scheme. */
15
29
  export declare function isAnvatoCue(cue: TimedMetadataCue): boolean;
16
30
  /**
@@ -41,11 +55,23 @@ export declare class MetadataCueTracker {
41
55
  private readonly diagnose?;
42
56
  /** Observed cue `pts` parameter (seconds) → cue media time (seconds). */
43
57
  private mediaTimeByPts;
58
+ /** Observed `type=cue_end` `pts` → media time; the latest delivery wins. */
59
+ private endMediaTimeByPts;
44
60
  private segmentAnchoredDiagnosed;
45
61
  private offsetRejectedPts;
46
62
  constructor(diagnose?: CueTrackerDiagnose | undefined);
47
- /** Ignores non-Anvato cues, non-`type=cue` payloads, and non-finite `pts`. True when a cue was recorded or refreshed. */
63
+ /**
64
+ * Ignores non-Anvato cues, payloads other than `type=cue` / `type=cue_end`, and non-finite `pts`.
65
+ * True when a cue was recorded or refreshed.
66
+ */
48
67
  handleCue(cue: TimedMetadataCue): boolean;
68
+ /**
69
+ * The `cue_end` closest to ending the break that starts at `startPts` and lasts `durationSec`,
70
+ * judged on the stream clock so a player remap cannot move it. The pts difference is read as
71
+ * seconds and as milliseconds; only a length between half and twice the duration is a candidate.
72
+ * Ties resolve to the lower `cue_end` pts. Null when there is no candidate.
73
+ */
74
+ breakEnd(startPts: number, durationSec: number): BreakEndMatch | null;
49
75
  private resolveMediaTime;
50
76
  /**
51
77
  * Media time of the cue matching `pts` within {@link PTS_MATCH_TOLERANCE_SECONDS}, or null.
@@ -1 +1 @@
1
- import{decodeUtf8 as e,parseId3GeobFrames as t}from"../id3/parseId3Geob";export const ANVATO_ID3_DESCRIPTION="Anvatos";export const ANVATO_ID3_MIME_TYPE="application/json";export const ANVATO_EMSG_SCHEME_ID_URI="urn:anvato:es1:052016";export const ID3_IN_EMSG_SCHEME_ID_URIS=["https://aomedia.org/emsg/ID3","https://developer.apple.com/streaming/emsg-id3"];export function isId3InEmsgScheme(e){return void 0!==e&&ID3_IN_EMSG_SCHEME_ID_URIS.includes(e)}export const PTS_MATCH_TOLERANCE_SECONDS=.005;export function isAnvatoCue(e){return"id3"===e.type?"Anvatos"===e.description&&(void 0===e.mimeType||"application/json"===e.mimeType):"emsg"===e.type&&"urn:anvato:es1:052016"===e.schemeIdUri}export function anvatoPayloadFromCue(s){if(isAnvatoCue(s))return s.messageData??null;if("emsg"===s.type&&isId3InEmsgScheme(s.schemeIdUri)&&s.raw)for(const i of t(s.raw))if("Anvatos"===i.description&&"application/json"===i.mimeType)return e(i.data);return null}export function parseAnvatoPayload(e){const t={};for(const i of e.split("&")){if(""===i)continue;const e=i.indexOf("="),n=-1===e?i:i.slice(0,e),o=-1===e?"":i.slice(e+1),r=s(n);r in t||(t[r]=s(o))}return t}function s(e){const t=e.replace(/\+/g," ");try{return decodeURIComponent(t)}catch{return t}}export const PTS_OFFSET_MIN_LEAD_SECONDS=.1;export const PTS_OFFSET_MAX_LAG_SECONDS=15;export class MetadataCueTracker{constructor(e){this.diagnose=e,this.mediaTimeByPts=new Map,this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts=new Set}handleCue(e){if(!Number.isFinite(e.startTime))return!1;const t=anvatoPayloadFromCue(e);if(!t)return!1;const s=parseAnvatoPayload(t);if("cue"!==s.type)return!1;const i=Number(s.pts);return!!Number.isFinite(i)&&(this.mediaTimeByPts.set(i,this.resolveMediaTime(e,i)),!0)}resolveMediaTime(e,t){const s=e.ptsOffset;if("number"!=typeof s||!Number.isFinite(s))return"urn:anvato:es1:052016"!==e.schemeIdUri||this.segmentAnchoredDiagnosed||(this.segmentAnchoredDiagnosed=!0,this.diagnose?.("DA-ANVATO-CUE-SEGMENT-ANCHORED",`Anvato emsg cue pts=${t} has no ptsOffset; scheduling it at its segment start ${e.startTime}s, which can be up to one segment early.`,{pts:t,mediaTime:e.startTime})),e.startTime;const i=t=>t>=e.startTime-.1&&t<=e.startTime+15,n=t+s;if(i(n))return n;const o=t/1e3+s;return i(o)?o:(this.offsetRejectedPts.has(t)||(this.offsetRejectedPts.add(t),this.diagnose?.("DA-ANVATO-CUE-OFFSET-REJECTED",`Anvato cue pts=${t} maps to ${n}s with ptsOffset ${s}, outside its segment window from ${e.startTime}s; using the segment start.`,{pts:t,startTime:e.startTime,ptsOffset:s,mappedTime:n})),e.startTime)}mediaTimeForPts(e){let t=null,s=1/0;for(const i of this.mediaTimeByPts.keys()){const n=Math.abs(i-e);n>.005||(n<s||n===s&&i<t)&&(t=i,s=n)}return null===t?null:this.mediaTimeByPts.get(t)}get size(){return this.mediaTimeByPts.size}clear(){this.mediaTimeByPts.clear(),this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts.clear()}}
1
+ import{decodeUtf8 as e,parseId3GeobFrames as t}from"../id3/parseId3Geob";export const ANVATO_ID3_DESCRIPTION="Anvatos";export const ANVATO_ID3_MIME_TYPE="application/json";export const ANVATO_EMSG_SCHEME_ID_URI="urn:anvato:es1:052016";export const ID3_IN_EMSG_SCHEME_ID_URIS=["https://aomedia.org/emsg/ID3","https://developer.apple.com/streaming/emsg-id3"];export function isId3InEmsgScheme(e){return void 0!==e&&ID3_IN_EMSG_SCHEME_ID_URIS.includes(e)}export const PTS_MATCH_TOLERANCE_SECONDS=.005;export const BREAK_END_LENGTH_TOLERANCE_SECONDS=2;export function isAnvatoCue(e){return"id3"===e.type?"Anvatos"===e.description&&(void 0===e.mimeType||"application/json"===e.mimeType):"emsg"===e.type&&"urn:anvato:es1:052016"===e.schemeIdUri}export function anvatoPayloadFromCue(s){if(isAnvatoCue(s))return s.messageData??null;if("emsg"===s.type&&isId3InEmsgScheme(s.schemeIdUri)&&s.raw)for(const i of t(s.raw))if("Anvatos"===i.description&&"application/json"===i.mimeType)return e(i.data);return null}export function parseAnvatoPayload(e){const t={};for(const i of e.split("&")){if(""===i)continue;const e=i.indexOf("="),n=-1===e?i:i.slice(0,e),o=-1===e?"":i.slice(e+1),r=s(n);r in t||(t[r]=s(o))}return t}function s(e){const t=e.replace(/\+/g," ");try{return decodeURIComponent(t)}catch{return t}}export const PTS_OFFSET_MIN_LEAD_SECONDS=.1;export const PTS_OFFSET_MAX_LAG_SECONDS=15;export class MetadataCueTracker{constructor(e){this.diagnose=e,this.mediaTimeByPts=new Map,this.endMediaTimeByPts=new Map,this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts=new Set}handleCue(e){if(!Number.isFinite(e.startTime))return!1;const t=anvatoPayloadFromCue(e);if(!t)return!1;const s=parseAnvatoPayload(t),i=s.type;if("cue"!==i&&"cue_end"!==i)return!1;const n=Number(s.pts);if(!Number.isFinite(n))return!1;return("cue"===i?this.mediaTimeByPts:this.endMediaTimeByPts).set(n,this.resolveMediaTime(e,n)),!0}breakEnd(e,t){if(!(Number.isFinite(e)&&t>0))return null;let s=null;for(const[i,n]of this.endMediaTimeByPts){const o=i-e;for(const e of[o,o/1e3]){if(e<t/2||e>2*t)continue;const o=Math.abs(e-t);if(null===s||o<s.distance||o===s.distance&&i<s.endPts){s={endPts:i,distance:o,match:{mediaTime:n,lengthSec:e,accepted:o<=2}}}}}return null===s?null:s.match}resolveMediaTime(e,t){const s=e.ptsOffset;if("number"!=typeof s||!Number.isFinite(s))return"urn:anvato:es1:052016"!==e.schemeIdUri||this.segmentAnchoredDiagnosed||(this.segmentAnchoredDiagnosed=!0,this.diagnose?.("DA-ANVATO-CUE-SEGMENT-ANCHORED",`Anvato emsg cue pts=${t} has no ptsOffset; scheduling it at its segment start ${e.startTime}s, which can be up to one segment early.`,{pts:t,mediaTime:e.startTime})),e.startTime;const i=t=>t>=e.startTime-.1&&t<=e.startTime+15,n=t+s;if(i(n))return n;const o=t/1e3+s;return i(o)?o:(this.offsetRejectedPts.has(t)||(this.offsetRejectedPts.add(t),this.diagnose?.("DA-ANVATO-CUE-OFFSET-REJECTED",`Anvato cue pts=${t} maps to ${n}s with ptsOffset ${s}, outside its segment window from ${e.startTime}s; using the segment start.`,{pts:t,startTime:e.startTime,ptsOffset:s,mappedTime:n})),e.startTime)}mediaTimeForPts(e){let t=null,s=1/0;for(const i of this.mediaTimeByPts.keys()){const n=Math.abs(i-e);n>.005||(n<s||n===s&&i<t)&&(t=i,s=n)}return null===t?null:this.mediaTimeByPts.get(t)}get size(){return this.mediaTimeByPts.size}clear(){this.mediaTimeByPts.clear(),this.endMediaTimeByPts.clear(),this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts.clear()}}
@@ -1 +1 @@
1
- export async function resumeContentAfterBreak(e,t){const{breakInfo:r,earlyReturnOffsetSec:n,isLiveResume:i,released:a,isCurrent:o}=t,{contentPlayer:s,preloadMode:d,contentRecovery:l,resumeCoordinator:c,log:u}=e;if(a&&(await Promise.resolve(a).catch(e=>{u("Ad media release failed:",e)}),!o()))return;const m=()=>{i&&setTimeout(()=>e.getCallbacks()?.onContentReloading?.(!1),2e3)},p=async()=>{await s.play().catch(e=>{u("Content resume failed:",e)}).finally(m)};if("recreate"===l){if("function"==typeof s.recreateMediaPipeline)return void await async function(e,t,r){const{breakInfo:n,earlyReturnOffsetSec:i,isLiveResume:a,isCurrent:o}=t,{contentPlayer:s,resumeCoordinator:d,diagnose:l,preloadMode:c}=e,u=s.recreateMediaPipeline;if(!u)return;if("single-decoder"===c&&(await new Promise(e=>setTimeout(e,300)),!o()))return;a&&e.getCallbacks()?.onContentReloading?.(!0);const m=d.resolveResumeTarget(n,i)??s.currentTime,p=()=>"undefined"!=typeof performance?performance.now():Date.now(),f=p(),C=u.call(s,{startTime:m});let E,T=null;try{await Promise.race([C,new Promise((e,t)=>{E=setTimeout(()=>t(new Error("recreateMediaPipeline timed out")),1e4)})])}catch(e){T=e}finally{void 0!==E&&clearTimeout(E)}if(!o())return;if(null===T){const e=Math.round(p()-f);l("DA-CONTENT-PIPELINE-RECREATED",`Content media pipeline rebuilt at ${m}s for break ${n.id} in ${e}ms`,{breakId:n.id,startTime:m,durationMs:e}),d.probeResumeLanding(n.id,m)}else{const e=T instanceof Error?T.message:String(T);l("DA-CONTENT-PIPELINE-RECREATE-FAILED",`Content media pipeline rebuild for break ${n.id} failed (${e}); resuming in place`,{breakId:n.id,startTime:m,reason:e}),d.probeResumeLanding(n.id,m),s.seek(m)}await r()}(e,t,p);u('Content recovery "recreate" requested but the content adapter does not implement recreateMediaPipeline(); resuming in place with seek + play'),e.diagnose("DA-CONTENT-PIPELINE-RECREATE-FAILED",'Content recovery "recreate" requested but the content adapter does not implement recreateMediaPipeline(); resuming in place',{breakId:r.id,startTime:s.currentTime,reason:"unsupported-adapter"})}const f=()=>{o()&&(i&&e.getCallbacks()?.onContentReloading?.(!0),c.applyResumeSeek(r,n),p())};"single-decoder"===d?setTimeout(f,300):f()}
1
+ export async function resumeContentAfterBreak(e,t){const{breakInfo:n,earlyReturnOffsetSec:r,isLiveResume:a,released:i,isCurrent:o}=t,{contentPlayer:s,preloadMode:d,contentRecovery:l,resumeCoordinator:c,log:u}=e;if(i&&(await Promise.resolve(i).catch(e=>{u("Ad media release failed:",e)}),!o()))return;const m=()=>{a&&setTimeout(()=>e.getCallbacks()?.onContentReloading?.(!1),2e3)},p=async()=>{await s.play().catch(e=>{u("Content resume failed:",e)}).finally(m)};if("recreate"===l){if("function"==typeof s.recreateMediaPipeline)return void await async function(e,t,n){const{breakInfo:r,earlyReturnOffsetSec:a,isLiveResume:i,isCurrent:o}=t,{contentPlayer:s,resumeCoordinator:d,diagnose:l,preloadMode:c}=e,u=s.recreateMediaPipeline;if(!u)return;if("single-decoder"===c&&(await new Promise(e=>setTimeout(e,300)),!o()))return;i&&e.getCallbacks()?.onContentReloading?.(!0);const m=d.resolveResumeTarget(r,a)??s.currentTime;d.noteContentReload();const p=()=>"undefined"!=typeof performance?performance.now():Date.now(),f=p(),C=u.call(s,{startTime:m});let E,T=null;try{await Promise.race([C,new Promise((e,t)=>{E=setTimeout(()=>t(new Error("recreateMediaPipeline timed out")),1e4)})])}catch(e){T=e}finally{void 0!==E&&clearTimeout(E)}if(!o())return;if(null===T){const e=Math.round(p()-f);l("DA-CONTENT-PIPELINE-RECREATED",`Content media pipeline rebuilt at ${m}s for break ${r.id} in ${e}ms`,{breakId:r.id,startTime:m,durationMs:e}),d.probeResumeLanding(r.id,m)}else{const e=T instanceof Error?T.message:String(T);l("DA-CONTENT-PIPELINE-RECREATE-FAILED",`Content media pipeline rebuild for break ${r.id} failed (${e}); resuming in place`,{breakId:r.id,startTime:m,reason:e}),d.probeResumeLanding(r.id,m),s.seek(m)}await n()}(e,t,p);u('Content recovery "recreate" requested but the content adapter does not implement recreateMediaPipeline(); resuming in place with seek + play'),e.diagnose("DA-CONTENT-PIPELINE-RECREATE-FAILED",'Content recovery "recreate" requested but the content adapter does not implement recreateMediaPipeline(); resuming in place',{breakId:n.id,startTime:s.currentTime,reason:"unsupported-adapter"})}const f=()=>{o()&&(a&&e.getCallbacks()?.onContentReloading?.(!0),c.applyResumeSeek(n,r),p())};"single-decoder"===d?setTimeout(f,300):f()}
@@ -1,7 +1,8 @@
1
- import type { PlayerAdapter } from '../../interfaces/PlayerAdapter';
1
+ import type { PlayerAdapter, TimedMetadataCue } from '../../interfaces/PlayerAdapter';
2
2
  import type { Break } from '../../types/BreakManifest';
3
3
  import type { Clock } from '../BreakScheduler';
4
4
  import type { AdPlayerState } from './AdPlayerState';
5
+ import { type BreakEndOnStreamClock } from './streamClockResume';
5
6
  export declare const START_CLAMP_MAX_WINDOW_FRACTION = 0.5;
6
7
  export interface ContentResumeCoordinatorDeps {
7
8
  contentPlayer: PlayerAdapter;
@@ -22,7 +23,23 @@ export declare class ContentResumeCoordinator {
22
23
  * the SDK has no cue tracker (every timebase except `ptsSource: 'anvatoCue'`).
23
24
  */
24
25
  private cueAnchorResolver;
26
+ /** The last resolved resume point before the live-window clamp; null when no seek was resolved. */
27
+ private resumePolicyTarget;
28
+ /** The break's matched Anvato `cue_end`; null without a cue tracker or before it is matched. */
29
+ private cueEndResolver;
30
+ private readonly streamClock;
25
31
  constructor(state: AdPlayerState, deps: ContentResumeCoordinatorDeps);
32
+ /**
33
+ * Supply the break's matched Anvato `cue_end` (`ptsSource: 'anvatoCue'`): the stream's own end
34
+ * of the break, used as the resume point in place of the cue plus the duration.
35
+ */
36
+ setCueEndResolver(resolver: ((breakInfo: Break) => BreakEndOnStreamClock | null) | null): void;
37
+ /** Feed a timed-metadata cue; Anvato beacons map currentTime to the stream clock. */
38
+ ingestStreamClockCue(cue: TimedMetadataCue): void;
39
+ /** The content pipeline was rebuilt: its timeline has to be mapped to the stream clock again. */
40
+ noteContentReload(): void;
41
+ /** Stops the stream-clock landing measurement (controller teardown). */
42
+ dispose(): void;
26
43
  /**
27
44
  * Supply the in-stream cue position used to anchor the resume in place of the pause position.
28
45
  *
@@ -60,14 +77,32 @@ export declare class ContentResumeCoordinator {
60
77
  */
61
78
  resumeAnchorCushionSec(): number | null;
62
79
  isPlausibleSeekEnd(end: number): boolean;
80
+ /**
81
+ * Where the run-up steers content: the stream-clock target once beacons since the run-up's last
82
+ * seek map it, else the matched `cue_end`, else the policy's resume point.
83
+ */
63
84
  plannedResumeTarget(breakInfo: Break): number | null;
85
+ /** The policy's resume point from the anchor, ignoring the stream's own clock. */
86
+ computedResumeTarget(breakInfo: Break): number | null;
87
+ /** Replacement resumes at the break end: the only policy the stream's end of the break can serve. */
88
+ resumesAtBreakEnd(breakInfo: Break): boolean;
89
+ private resolvePolicy;
90
+ /** The matched `cue_end`'s currentTime, when the policy resumes at the break end. */
91
+ private cueEndTarget;
64
92
  maybePrepositionContentForResume(): void;
65
93
  maybeCatchUpContentForResume(breakInfo: Break): void;
66
94
  endResumeCatchup(keepPlaying?: boolean): void;
67
95
  get resumeHandoverInMotion(): boolean;
68
96
  resumeAlignSummary(): Record<string, unknown>;
69
97
  cancelResumeLandedProbe(): void;
70
- probeResumeLanding(breakId: string, target: number): void;
98
+ /**
99
+ * Reports where the resume seek landed (`DA-RESUME-LANDED`) on the next `seeked` event.
100
+ *
101
+ * @param target - The position the player was asked to seek to (after any live-window clamp).
102
+ * @param policyTarget - The resume point before the clamp; the landing is also measured against
103
+ * it, because an exact landing on a clamped seek still leaves the viewer short.
104
+ */
105
+ probeResumeLanding(breakId: string, target: number, policyTarget?: number | null): void;
71
106
  waitForLiveEdge(isCurrent?: () => boolean): Promise<number | null>;
72
107
  resetBreakResumeState(): void;
73
108
  beginContinueContentPlayout(): void;
@@ -86,5 +121,10 @@ export declare class ContentResumeCoordinator {
86
121
  * seek is needed (policy says resume in place, or content was already pre-positioned there).
87
122
  */
88
123
  resolveResumeTarget(breakInfo: Break, earlyReturnOffsetSec?: number | null): number | null;
124
+ /**
125
+ * DA-RESUME-CUE-END at the hand-back, when a matched `cue_end` decides the resume without the
126
+ * stream clock (no beacons, or none since the run-up's last seek). Returns its target, or null.
127
+ */
128
+ private reportCueEnd;
89
129
  applyResumeSeek(breakInfo: Break, earlyReturnOffsetSec?: number | null): void;
90
130
  }
@@ -1 +1 @@
1
- import{Timebase as e,isPostRollBreak as t}from"../../types/BreakManifest";import{resolveResumePoint as s}from"../resolveResumePoint";import{ContinueContentPlayout as n}from"./ContinueContentPlayout";import{contentSeekableEnd as i,isPlausibleSeekEnd as a,liveEdgeDistanceSec as r,liveSafeSeekEnd as o,liveSafeSeekStart as u,liveSeekableWindowSec as l,unreachableEdgeSec as d}from"./liveEdge";export const START_CLAMP_MAX_WINDOW_FRACTION=.5;const h=.04,c=e=>Math.round(1e3*e)/1e3;export class ContentResumeCoordinator{constructor(e,t){this.state=e,this.deps=t,this.cueAnchorResolver=null,this.continuePlayout=new n(this.state,{contentPlayer:this.deps.contentPlayer,clock:this.deps.clock,gateContentForBreak:()=>this.deps.gateContentForBreak(),distanceToLiveEdgeSec:()=>this.distanceToLiveEdgeSec(),plannedResumeTarget:e=>this.plannedResumeTarget(e),diagnose:(e,t,s)=>this.deps.diagnose(e,t,s),log:(...e)=>this.deps.log(...e)})}setCueAnchorResolver(e){this.cueAnchorResolver=e}captureBreakAnchor(e){this.resetBreakResumeState();const t=this.cueAnchorResolver?.(e)??null,s=null!==t&&Number.isFinite(t);this.state.contentPositionAtBreakStart=s?t:this.deps.contentPlayer.currentTime,this.state.resumeAnchorIsCue=s,this.state.resumeAnchorSeekableEnd=this.contentSeekableEnd()}reanchorMidBreak(e){this.state.contentPositionAtBreakStart=e,this.state.resumeAnchorIsCue=!1,this.state.resumeAnchorSeekableEnd=this.contentSeekableEnd()}liveEdgeDistanceSec(){return r(this.deps.contentPlayer)}liveSafeSeekEnd(){return o(this.deps.contentPlayer)}liveSafeSeekStart(){return u(this.deps.contentPlayer)}liveSeekableWindowSec(){return l(this.deps.contentPlayer)}contentSeekableEnd(){return i(this.deps.contentPlayer)}resumeAnchorCushionSec(){const e=this.state.resumeAnchorSeekableEnd;return null!==e&&Number.isFinite(e)?c(e-this.state.contentPositionAtBreakStart):null}isPlausibleSeekEnd(e){return a(this.deps.contentPlayer,e)}plannedResumeTarget(e){if(t(e))return null;const n=s({anchor:this.state.contentPositionAtBreakStart,duration:e.duration,adDuration:e.duration,...this.state.adInsertionType?{insertionType:this.state.adInsertionType}:{},..."number"==typeof e.resumeOffset?{resumeOffset:e.resumeOffset}:{}});return n.seek?n.target:null}maybePrepositionContentForResume(){if("shared-element"===this.deps.getInsertionMode())return;if(!this.state.contentPaused||null!==this.state.resumePrepositionedTo)return;if(null!==this.state.resumePrepositionSettle)return;if(this.state.resumeCatchupActive)return;if(Number.isFinite(this.deps.contentPlayer.duration))return;const e=this.state.currentBreak;if(!e)return;const t=this.plannedResumeTarget(e);if(null===t)return;const s=this.contentSeekableEnd();if(null===s)return;const n=this.state.adSecondsPlayedThisBreak+this.state.currentAssetElapsedSec,i=(e.duration??0)-n;let a;if(t<=s)a=t;else{if(!(i<=3))return;a=s}this.deps.log(a===t?`Resume pre-positioning: seeking content to ${t}s during the break (window reaches ${s}s)`:`Resume pre-positioning: window only reaches ${s}s and the ad ends in ${i}s — moving content as close to ${t}s as exists`),this.deps.contentPlayer.seek(a);const r=setTimeout(()=>{this.state.resumePrepositionSettle=null;const e=this.deps.contentPlayer.currentTime;Math.abs(e-a)<=h?(this.state.resumePrepositionedTo=e,this.deps.log(`Resume pre-positioned: content is at ${e}s`)):this.deps.log(`Resume pre-position rejected: asked ${a}s, landed ${e}s — window is short, will retry`)},250);this.state.resumePrepositionSettle=r}maybeCatchUpContentForResume(e){if("shared-element"===this.deps.getInsertionMode())return;if(!this.state.contentPaused||Number.isFinite(this.deps.contentPlayer.duration))return;const t=this.plannedResumeTarget(e);if(null===t)return;const s=this.deps.contentPlayer.currentTime;if(this.state.resumeCatchupActive){const n=(e.duration??0)-(this.state.adSecondsPlayedThisBreak+this.state.currentAssetElapsedSec);if(s>t+1)return this.state.resumeCatchupActive=!1,this.deps.contentPlayer.pause(),this.state.resumePrepositionedTo=this.deps.contentPlayer.currentTime,void this.deps.log(`Resume catch-up halted: content reached ${this.deps.contentPlayer.currentTime}s, past the ${t}s target`);if(n<=30&&n>=1){this.state.resumeAlignTicks+=1;const e=s+n,i=e-t;if(Math.abs(i)>h){const a=s-i,r=this.liveSafeSeekEnd();if(null!==r){const e=r>this.state.lastResumeSafeEnd+.25;e&&Number.isFinite(this.state.lastResumeSafeEnd)&&this.state.resumeSawSteps.push(Math.round(100*(r-this.state.lastResumeSafeEnd))/100),r>this.state.lastResumeSafeEnd&&(this.state.lastResumeSafeEnd=r);const s=r-a;if(s>this.state.resumeBestSawMarginSec&&(this.state.resumeBestSawMarginSec=s),a>r)return void(this.state.resumeAlignBlockedDiagnosed||(this.state.resumeAlignBlockedDiagnosed=!0,this.deps.log(`Resume align waiting: ${a}s is past the published edge ${r}s (${Math.round(1e3*(a-r))}ms short) — rolling until a manifest step brings it in reach`),this.deps.diagnose?.("DA-RESUME-ALIGN-BLOCKED",`Resume alignment cannot reach ${t}s yet: the published edge is ${r}s`,{target:t,requested:a,safeEnd:r,shortfallSec:Math.round(1e3*(a-r))/1e3,remainingSec:n})));if(!e&&this.state.resumeSawSeekDone)return;this.state.resumeSawSeekDone=!0}if(this.state.lastResumeAlignRemainingSec-n<.5)return;this.state.lastResumeAlignRemainingSec=n,this.deps.log(`Resume align: landing ${e}s vs target ${t}s (${Math.round(1e3*i)}ms) — content to ${a}s, ${n}s of ad left`),this.state.resumeAlignCorrectionsMs.push(Math.round(1e3*i)),this.deps.contentPlayer.seek(a)}}return}if(t-s<=h)return;const n=this.state.adSecondsPlayedThisBreak+this.state.currentAssetElapsedSec,i=(e.duration??0)-n;if(i<=0)return;if(i>30)return;const a=this.contentSeekableEnd();if(null===a)return;const r=t-i+.3,o=Math.min(r,a);this.state.resumeCatchupActive=!0,this.state.resumeCatchupRan=!0,this.state.contentMutedBeforeCatchup=this.deps.contentPlayer.muted,this.deps.contentPlayer.muted=!0,this.deps.log(`Resume catch-up: content to ${o}s, playing toward ${t}s with ${i}s of ad left`),this.deps.diagnose?.("DA-RESUME-CATCHUP",`Break ${e.id}: playing content from ${o}s toward ${t}s with ${i}s of ad left`,{breakId:e.id,startPos:o,target:t,remainingAdSec:Math.round(1e3*i)/1e3,publishedEnd:a,clampedStart:o<r}),Math.abs(s-o)>h&&this.deps.contentPlayer.seek(o),this.deps.contentPlayer.play()}endResumeCatchup(e=!1){this.state.resumeCatchupActive&&(this.state.resumeCatchupActive=!1,e||this.deps.contentPlayer.pause()),null!==this.state.contentMutedBeforeCatchup&&(this.deps.contentPlayer.muted=this.state.contentMutedBeforeCatchup,this.state.contentMutedBeforeCatchup=null)}get resumeHandoverInMotion(){return this.state.resumeCatchupActive}resumeAlignSummary(){const e=this.state.resumeAlignCorrectionsMs;return{catchUpRan:this.state.resumeCatchupRan||this.state.resumeCatchupActive||e.length>0||null!==this.state.resumePrepositionedTo,alignCorrections:e.length,placedOnStep:this.state.resumeSawSeekDone,alignTicks:this.state.resumeAlignTicks,sawSteps:this.state.resumeSawSteps.slice(0,12),sawStepCount:this.state.resumeSawSteps.length,bestSawMarginSec:Number.isFinite(this.state.resumeBestSawMarginSec)?Math.round(1e3*this.state.resumeBestSawMarginSec)/1e3:null,alignCorrectionsMs:e.slice(0,12),alignLastErrorMs:e.length?e[e.length-1]:null}}cancelResumeLandedProbe(){const e=this.state.resumeLandedProbe;this.state.resumeLandedProbe=null,e?.()}probeResumeLanding(e,t){this.cancelResumeLandedProbe();let s=!1;const n=(n,i)=>{if(s)return;s=!0,this.cancelResumeLandedProbe();const a=null===n?null:Math.round(1e3*(n-t))/1e3;this.deps.log(null===n?`Resume landing unknown for break ${e} (${i})`:`Resume landed at ${n}s, ${a}s from the ${t}s asked for (break ${e})`),this.deps.diagnose?.("DA-RESUME-LANDED",null===n?`Resume landing for break ${e} could not be measured (${i})`:`Resume for break ${e} landed at ${n}s, ${a}s from the ${t}s requested`,{breakId:e,target:t,landed:n,errorSec:a,...i?{reason:i}:{}})},i=()=>n(this.deps.contentPlayer.currentTime),a=setTimeout(()=>n(null,"no seeked event"),2e3);this.state.resumeLandedProbe=()=>{clearTimeout(a),this.deps.contentPlayer.off("seeked",i)},this.deps.contentPlayer.on("seeked",i)}async waitForLiveEdge(e=()=>!0){for(let t=0;t<20;t++){if(!e())return null;const t=this.deps.contentPlayer.videoElement,s=t?.seekable;if(s&&s.length>0){const e=s.end(s.length-1);if(Number.isFinite(e)&&e>0)return e}if(await new Promise(e=>setTimeout(e,100)),!e())return null}return this.deps.log("shared-element: no seekable range after restore; staying at the live edge"),null}resetBreakResumeState(){this.state.resumeAnchorIsCue=!1,this.state.resumeAnchorSeekableEnd=null,this.state.resumePrepositionedTo=null,this.state.resumeCatchupActive=!1,this.state.resumeCatchupRan=!1,this.state.contentMutedBeforeCatchup=null,this.state.resumeAlignCorrectionsMs=[],this.state.lastResumeAlignRemainingSec=Number.POSITIVE_INFINITY,this.state.resumeAlignBlockedDiagnosed=!1,this.state.lastResumeSafeEnd=Number.NEGATIVE_INFINITY,this.state.resumeSawSeekDone=!1,this.state.resumeBestSawMarginSec=Number.NEGATIVE_INFINITY,this.state.resumeAlignTicks=0,this.state.resumeSawSteps=[],this.state.resumePrepositionSettle&&(clearTimeout(this.state.resumePrepositionSettle),this.state.resumePrepositionSettle=null),this.state.adSecondsPlayedThisBreak=0,this.state.currentAssetElapsedSec=0}beginContinueContentPlayout(){this.continuePlayout.beginContinueContentPlayout()}distanceToLiveEdgeSec(){const e=this.contentSeekableEnd();return null===e?null:c(e-this.deps.contentPlayer.currentTime)}secondsUntilCut(e){return this.continuePlayout.secondsUntilCut(e)}restoreContinueQuality(e){this.continuePlayout.restoreContinueQuality(e)}currentContinueDriftSec(){return this.continuePlayout.currentContinueDriftSec()}abandonContinueContentPlayout(e){this.continuePlayout.abandonContinueContentPlayout(e)}endContinueContentPlayout(){this.continuePlayout.endContinueContentPlayout()}setContinueRate(e){this.continuePlayout.setContinueRate(e)}tickContinueContentPlayout(){this.continuePlayout.tickContinueContentPlayout()}resolveResumeTarget(t,n=null){const i=null!==n,a=this.state.resumeAnchorIsCue&&!i,r=i?n:a?t.duration:this.state.adSecondsPlayedThisBreak,o=s({anchor:this.state.contentPositionAtBreakStart,duration:t.duration,adDuration:r,...i?{}:{insertionType:this.state.adInsertionType},...i?{resumeOffset:n}:"number"==typeof t.resumeOffset?{resumeOffset:t.resumeOffset}:{}});if(o.clamped&&this.deps.diagnose?.("DA-RESUME-OFFSET-CLAMPED",`Resume offset shortened to the ${o.offset}s of ad actually played for break ${t.id}`,{breakId:t.id,offset:o.offset,source:o.source}),!o.seek)return this.deps.log(`Resume: no seek for break ${t.id} (offset 0, ${o.source})`),null;this.deps.log(`Resume-seek to ${o.target}s (offset ${o.offset}s, ${o.source}) for break ${t.id}`);const u=this.resumeAlignSummary(),l=this.liveSafeSeekEnd();this.deps.diagnose?.("DA-RESUME-SEEK",`Resume-seek to ${o.target}s (offset ${o.offset}s, ${o.source}) for break ${t.id}`,{breakId:t.id,target:o.target,offset:o.offset,source:o.source,anchorPosition:this.state.contentPositionAtBreakStart,anchorIsCue:this.state.resumeAnchorIsCue,anchorSeekableEnd:this.state.resumeAnchorSeekableEnd,anchorCushionSec:this.resumeAnchorCushionSec(),safeEnd:l,seekableEndNow:this.contentSeekableEnd(),liveEdge:this.deps.contentPlayer.liveEdge??null,unreachableEdgeSec:d(this.deps.contentPlayer),...u.catchUpRan?u:{}});(this.state.breakTimebase===e.PTS||this.state.breakTimebase===e.MEDIATIME)&&"number"==typeof t.start&&this.state.callbacks?.onContentResumeSeek?.(o.target,t.start+t.duration);let c=o.target,m=0;null!==l&&c>l&&(m=Math.round(1e3*(c-l))/1e3,c=l);let p=m>0?"end":null;const g=this.liveSafeSeekStart();if(null!==g&&c<g){const e=Math.round(1e3*(g-c))/1e3,s=this.liveSeekableWindowSec(),n=null===s?null:.5*s;null!==n&&e<=n?(m=e,c=g,p="start"):(this.deps.log(`Resume-seek: ${o.target}s is ${e}s behind the element's live window start (window ${s}s); not clamping`),this.deps.diagnose?.("DA-RESUME-START-CLAMP-SKIPPED",`Resume target ${o.target}s for break ${t.id} is ${e}s behind the element's seekable start but the gap exceeds half the ${s}s window; left unchanged`,{breakId:t.id,requested:o.target,seekableStart:g,behindSec:e,windowSec:s,maxBehindSec:n,...this.resumeAlignSummary()}))}if(null!==this.state.resumePrepositionedTo&&Math.abs(this.deps.contentPlayer.currentTime-c)<=h){const e=this.deps.contentPlayer.currentTime;return this.deps.log(`Resume: content already at ${e}s for break ${t.id} (pre-positioned during the break)`+(m>0?` — ${m}s short of policy, those frames are not published yet`:"")+" — no seek"),this.deps.diagnose?.("DA-RESUME-PREPOSITIONED",`Break ${t.id} resumed without a seek: content was moved to ${e}s during the break`+(m>0?` (${m}s short of the ${o.target}s policy target)`:""),{breakId:t.id,target:o.target,prepositionedTo:this.state.resumePrepositionedTo,landed:e,shortfallSec:m,exact:0===m,...this.resumeAlignSummary()}),null}return m>0&&(this.deps.log("start"===p?`Resume-seek clamped: ${o.target}s is behind the live window start (already evicted); seeking ${c}s instead (${m}s early)`:`Resume-seek clamped: ${o.target}s is beyond what the stream has published; seeking ${c}s instead (${m}s short)`),this.deps.diagnose?.("DA-RESUME-TARGET-CLAMPED","start"===p?`Resume target ${o.target}s for break ${t.id} is behind the live window start (already evicted); clamped to ${c}s`:`Resume target ${o.target}s for break ${t.id} is beyond the published window; clamped to ${c}s`,{breakId:t.id,requested:o.target,clamped:c,shortfallSec:m,bound:p,...this.resumeAlignSummary()})),c}applyResumeSeek(e,t=null){const s=this.resolveResumeTarget(e,t);null!==s&&(this.probeResumeLanding(e.id,s),this.deps.contentPlayer.seek(s))}}
1
+ import{Timebase as e,isPostRollBreak as t}from"../../types/BreakManifest";import{resolveResumePoint as s}from"../resolveResumePoint";import{ContinueContentPlayout as n}from"./ContinueContentPlayout";import{StreamClockResume as i}from"./streamClockResume";import{contentSeekableEnd as r,isPlausibleSeekEnd as a,liveEdgeDistanceSec as o,liveSafeSeekEnd as u,liveSafeSeekStart as l,liveSeekableWindowSec as d,unreachableEdgeSec as h}from"./liveEdge";export const START_CLAMP_MAX_WINDOW_FRACTION=.5;const c=.04,m=e=>Math.round(1e3*e)/1e3;export class ContentResumeCoordinator{constructor(e,t){this.state=e,this.deps=t,this.cueAnchorResolver=null,this.resumePolicyTarget=null,this.cueEndResolver=null,this.continuePlayout=new n(this.state,{contentPlayer:this.deps.contentPlayer,clock:this.deps.clock,gateContentForBreak:()=>this.deps.gateContentForBreak(),distanceToLiveEdgeSec:()=>this.distanceToLiveEdgeSec(),plannedResumeTarget:e=>this.plannedResumeTarget(e),diagnose:(e,t,s)=>this.deps.diagnose(e,t,s),log:(...e)=>this.deps.log(...e)}),this.streamClock=new i({contentPlayer:this.deps.contentPlayer,diagnose:(e,t,s)=>this.deps.diagnose(e,t,s),activeBreak:()=>this.state.currentBreak,anchorIsCue:()=>this.state.resumeAnchorIsCue,breakEnd:e=>this.cueEndResolver?.(e)??null,computedTarget:e=>this.computedResumeTarget(e),resumesAtBreakEnd:e=>this.resumesAtBreakEnd(e),now:()=>this.deps.clock.now()})}setCueEndResolver(e){this.cueEndResolver=e}ingestStreamClockCue(e){this.streamClock.ingestCue(e)}noteContentReload(){this.streamClock.noteReload()}dispose(){this.streamClock.cancelLanding()}setCueAnchorResolver(e){this.cueAnchorResolver=e}captureBreakAnchor(e){this.resetBreakResumeState();const t=this.cueAnchorResolver?.(e)??null,s=null!==t&&Number.isFinite(t);this.state.contentPositionAtBreakStart=s?t:this.deps.contentPlayer.currentTime,this.state.resumeAnchorIsCue=s,this.state.resumeAnchorSeekableEnd=this.contentSeekableEnd(),this.streamClock.beginBreak()}reanchorMidBreak(e){this.state.contentPositionAtBreakStart=e,this.state.resumeAnchorIsCue=!1,this.state.resumeAnchorSeekableEnd=this.contentSeekableEnd()}liveEdgeDistanceSec(){return o(this.deps.contentPlayer)}liveSafeSeekEnd(){return u(this.deps.contentPlayer)}liveSafeSeekStart(){return l(this.deps.contentPlayer)}liveSeekableWindowSec(){return d(this.deps.contentPlayer)}contentSeekableEnd(){return r(this.deps.contentPlayer)}resumeAnchorCushionSec(){const e=this.state.resumeAnchorSeekableEnd;return null!==e&&Number.isFinite(e)?m(e-this.state.contentPositionAtBreakStart):null}isPlausibleSeekEnd(e){return a(this.deps.contentPlayer,e)}plannedResumeTarget(e){const t=this.computedResumeTarget(e);return null===t?null:this.streamClock.target(e)??this.cueEndTarget(e)??t}computedResumeTarget(e){if(t(e))return null;const s=this.resolvePolicy(e,this.state.contentPositionAtBreakStart);return s.seek?s.target:null}resumesAtBreakEnd(e){if(t(e))return!1;const s=this.resolvePolicy(e,0);return s.seek&&Math.abs(s.offset-(e.duration??0))<.001}resolvePolicy(e,t){return s({anchor:t,duration:e.duration,adDuration:e.duration,...this.state.adInsertionType?{insertionType:this.state.adInsertionType}:{},..."number"==typeof e.resumeOffset?{resumeOffset:e.resumeOffset}:{}})}cueEndTarget(e){if(!this.state.resumeAnchorIsCue||!this.resumesAtBreakEnd(e))return null;const t=this.cueEndResolver?.(e)?.mediaTime;return"number"==typeof t&&Number.isFinite(t)?t:null}maybePrepositionContentForResume(){if("shared-element"===this.deps.getInsertionMode())return;if(!this.state.contentPaused||null!==this.state.resumePrepositionedTo)return;if(null!==this.state.resumePrepositionSettle)return;if(this.state.resumeCatchupActive)return;if(Number.isFinite(this.deps.contentPlayer.duration))return;const e=this.state.currentBreak;if(!e)return;const t=this.plannedResumeTarget(e);if(null===t)return;const s=this.contentSeekableEnd();if(null===s)return;const n=this.state.adSecondsPlayedThisBreak+this.state.currentAssetElapsedSec,i=(e.duration??0)-n;let r;if(t<=s)r=t;else{if(!(i<=3))return;r=s}this.deps.log(r===t?`Resume pre-positioning: seeking content to ${t}s during the break (window reaches ${s}s)`:`Resume pre-positioning: window only reaches ${s}s and the ad ends in ${i}s — moving content as close to ${t}s as exists`),this.streamClock.noteSeek(r),this.streamClock.arm(),this.deps.contentPlayer.seek(r);const a=setTimeout(()=>{this.state.resumePrepositionSettle=null;const e=this.deps.contentPlayer.currentTime;Math.abs(e-r)<=c?(this.state.resumePrepositionedTo=e,this.deps.log(`Resume pre-positioned: content is at ${e}s`)):this.deps.log(`Resume pre-position rejected: asked ${r}s, landed ${e}s — window is short, will retry`)},250);this.state.resumePrepositionSettle=a}maybeCatchUpContentForResume(e){if("shared-element"===this.deps.getInsertionMode())return;if(!this.state.contentPaused||Number.isFinite(this.deps.contentPlayer.duration))return;const t=this.plannedResumeTarget(e);if(null===t)return;const s=this.deps.contentPlayer.currentTime;if(this.state.resumeCatchupActive){const n=(e.duration??0)-(this.state.adSecondsPlayedThisBreak+this.state.currentAssetElapsedSec);if(s>t+1)return this.state.resumeCatchupActive=!1,this.deps.contentPlayer.pause(),this.state.resumePrepositionedTo=this.deps.contentPlayer.currentTime,void this.deps.log(`Resume catch-up halted: content reached ${this.deps.contentPlayer.currentTime}s, past the ${t}s target`);if(n<=30&&n>=1){this.state.resumeAlignTicks+=1;const e=s+n,i=e-t;if(Math.abs(i)>c){const r=s-i,a=this.liveSafeSeekEnd();if(null!==a){const e=a>this.state.lastResumeSafeEnd+.25;e&&Number.isFinite(this.state.lastResumeSafeEnd)&&this.state.resumeSawSteps.push(Math.round(100*(a-this.state.lastResumeSafeEnd))/100),a>this.state.lastResumeSafeEnd&&(this.state.lastResumeSafeEnd=a);const s=a-r;if(s>this.state.resumeBestSawMarginSec&&(this.state.resumeBestSawMarginSec=s),r>a)return void(this.state.resumeAlignBlockedDiagnosed||(this.state.resumeAlignBlockedDiagnosed=!0,this.deps.log(`Resume align waiting: ${r}s is past the published edge ${a}s (${Math.round(1e3*(r-a))}ms short) — rolling until a manifest step brings it in reach`),this.deps.diagnose?.("DA-RESUME-ALIGN-BLOCKED",`Resume alignment cannot reach ${t}s yet: the published edge is ${a}s`,{target:t,requested:r,safeEnd:a,shortfallSec:Math.round(1e3*(r-a))/1e3,remainingSec:n})));if(!e&&this.state.resumeSawSeekDone)return;this.state.resumeSawSeekDone=!0}if(this.state.lastResumeAlignRemainingSec-n<.5)return;this.state.lastResumeAlignRemainingSec=n,this.deps.log(`Resume align: landing ${e}s vs target ${t}s (${Math.round(1e3*i)}ms) — content to ${r}s, ${n}s of ad left`),this.state.resumeAlignCorrectionsMs.push(Math.round(1e3*i)),this.streamClock.noteSeek(r),this.deps.contentPlayer.seek(r)}}return}if(t-s<=c)return;const n=this.state.adSecondsPlayedThisBreak+this.state.currentAssetElapsedSec,i=(e.duration??0)-n;if(i<=0)return;if(i>30)return;const r=this.contentSeekableEnd();if(null===r)return;const a=t-i+.3,o=Math.min(a,r);this.state.resumeCatchupActive=!0,this.state.resumeCatchupRan=!0,this.state.contentMutedBeforeCatchup=this.deps.contentPlayer.muted,this.deps.contentPlayer.muted=!0,this.deps.log(`Resume catch-up: content to ${o}s, playing toward ${t}s with ${i}s of ad left`),this.deps.diagnose?.("DA-RESUME-CATCHUP",`Break ${e.id}: playing content from ${o}s toward ${t}s with ${i}s of ad left`,{breakId:e.id,startPos:o,target:t,remainingAdSec:Math.round(1e3*i)/1e3,publishedEnd:r,clampedStart:o<a}),Math.abs(s-o)>c&&(this.streamClock.noteSeek(o),this.deps.contentPlayer.seek(o)),this.streamClock.arm(),this.deps.contentPlayer.play()}endResumeCatchup(e=!1){this.state.resumeCatchupActive&&(this.state.resumeCatchupActive=!1,e||this.deps.contentPlayer.pause()),null!==this.state.contentMutedBeforeCatchup&&(this.deps.contentPlayer.muted=this.state.contentMutedBeforeCatchup,this.state.contentMutedBeforeCatchup=null)}get resumeHandoverInMotion(){return this.state.resumeCatchupActive}resumeAlignSummary(){const e=this.state.resumeAlignCorrectionsMs;return{catchUpRan:this.state.resumeCatchupRan||this.state.resumeCatchupActive||e.length>0||null!==this.state.resumePrepositionedTo,alignCorrections:e.length,placedOnStep:this.state.resumeSawSeekDone,alignTicks:this.state.resumeAlignTicks,sawSteps:this.state.resumeSawSteps.slice(0,12),sawStepCount:this.state.resumeSawSteps.length,bestSawMarginSec:Number.isFinite(this.state.resumeBestSawMarginSec)?Math.round(1e3*this.state.resumeBestSawMarginSec)/1e3:null,alignCorrectionsMs:e.slice(0,12),alignLastErrorMs:e.length?e[e.length-1]:null}}cancelResumeLandedProbe(){const e=this.state.resumeLandedProbe;this.state.resumeLandedProbe=null,e?.()}probeResumeLanding(e,t,s=null){this.cancelResumeLandedProbe();let n=!1;const i=(i,r)=>{if(n)return;n=!0,this.cancelResumeLandedProbe();const a=null===i?null:Math.round(1e3*(i-t))/1e3,o=null===i||null===s?null:Math.round(1e3*(i-s))/1e3,u=null!==s&&Math.abs(s-t)>=5e-4&&null!==o?`; ${Math.abs(o)}s ${o<0?"before":"after"} the ${s}s resume point`:"";this.deps.log(null===i?`Resume landing unknown for break ${e} (${r})`:`Resume landed at ${i}s, ${a}s from the ${t}s asked for${u} (break ${e})`),this.deps.diagnose?.("DA-RESUME-LANDED",null===i?`Resume landing for break ${e} could not be measured (${r})`:`Resume for break ${e} landed at ${i}s, ${a}s from the ${t}s requested${u}`,{breakId:e,target:t,landed:i,errorSec:a,...null===s?{}:{policyTarget:s,policyErrorSec:o},...r?{reason:r}:{}})},r=()=>{this.streamClock.updateLanding(e,this.deps.contentPlayer.currentTime),i(this.deps.contentPlayer.currentTime)},a=setTimeout(()=>i(null,"no seeked event"),2e3);this.state.resumeLandedProbe=()=>{clearTimeout(a),this.deps.contentPlayer.off("seeked",r)},this.deps.contentPlayer.on("seeked",r)}async waitForLiveEdge(e=()=>!0){for(let t=0;t<20;t++){if(!e())return null;const t=this.deps.contentPlayer.videoElement,s=t?.seekable;if(s&&s.length>0){const e=s.end(s.length-1);if(Number.isFinite(e)&&e>0)return e}if(await new Promise(e=>setTimeout(e,100)),!e())return null}return this.deps.log("shared-element: no seekable range after restore; staying at the live edge"),null}resetBreakResumeState(){this.state.resumeAnchorIsCue=!1,this.state.resumeAnchorSeekableEnd=null,this.state.resumePrepositionedTo=null,this.state.resumeCatchupActive=!1,this.state.resumeCatchupRan=!1,this.state.contentMutedBeforeCatchup=null,this.state.resumeAlignCorrectionsMs=[],this.state.lastResumeAlignRemainingSec=Number.POSITIVE_INFINITY,this.state.resumeAlignBlockedDiagnosed=!1,this.state.lastResumeSafeEnd=Number.NEGATIVE_INFINITY,this.state.resumeSawSeekDone=!1,this.state.resumeBestSawMarginSec=Number.NEGATIVE_INFINITY,this.state.resumeAlignTicks=0,this.state.resumeSawSteps=[],this.state.resumePrepositionSettle&&(clearTimeout(this.state.resumePrepositionSettle),this.state.resumePrepositionSettle=null),this.state.adSecondsPlayedThisBreak=0,this.state.currentAssetElapsedSec=0}beginContinueContentPlayout(){this.continuePlayout.beginContinueContentPlayout()}distanceToLiveEdgeSec(){const e=this.contentSeekableEnd();return null===e?null:m(e-this.deps.contentPlayer.currentTime)}secondsUntilCut(e){return this.continuePlayout.secondsUntilCut(e)}restoreContinueQuality(e){this.continuePlayout.restoreContinueQuality(e)}currentContinueDriftSec(){return this.continuePlayout.currentContinueDriftSec()}abandonContinueContentPlayout(e){this.continuePlayout.abandonContinueContentPlayout(e)}endContinueContentPlayout(){this.continuePlayout.endContinueContentPlayout()}setContinueRate(e){this.continuePlayout.setContinueRate(e)}tickContinueContentPlayout(){this.continuePlayout.tickContinueContentPlayout()}resolveResumeTarget(t,n=null){this.resumePolicyTarget=null;const i=null!==n,r=this.state.resumeAnchorIsCue&&!i,a=i?n:r?t.duration:this.state.adSecondsPlayedThisBreak,o=s({anchor:this.state.contentPositionAtBreakStart,duration:t.duration,adDuration:a,...i?{}:{insertionType:this.state.adInsertionType},...i?{resumeOffset:n}:"number"==typeof t.resumeOffset?{resumeOffset:t.resumeOffset}:{}});if(o.clamped&&this.deps.diagnose?.("DA-RESUME-OFFSET-CLAMPED",`Resume offset shortened to the ${o.offset}s of ad actually played for break ${t.id}`,{breakId:t.id,offset:o.offset,source:o.source}),!o.seek)return this.deps.log(`Resume: no seek for break ${t.id} (offset 0, ${o.source})`),null;const u=this.streamClock.handBackTarget(t,i),l=null!==u||i?null:this.reportCueEnd(t,o.target),d=u??l??o.target;this.resumePolicyTarget=d;const m=this.streamClock.seekBasis(t)??(null!==l?"cue_end":`offset ${o.offset}s, ${o.source}`);this.deps.log(`Resume-seek to ${d}s (${m}) for break ${t.id}`);const p=this.resumeAlignSummary(),g=this.liveSafeSeekEnd();this.deps.diagnose?.("DA-RESUME-SEEK",`Resume-seek to ${d}s (${m}) for break ${t.id}`,{breakId:t.id,target:d,offset:o.offset,source:o.source,...d===o.target?{}:{computedTarget:o.target},...null===l?{}:{cueEndTarget:l},...this.streamClock.seekContext(t,d,o.target),anchorPosition:this.state.contentPositionAtBreakStart,anchorIsCue:this.state.resumeAnchorIsCue,anchorSeekableEnd:this.state.resumeAnchorSeekableEnd,anchorCushionSec:this.resumeAnchorCushionSec(),safeEnd:g,seekableEndNow:this.contentSeekableEnd(),liveEdge:this.deps.contentPlayer.liveEdge??null,unreachableEdgeSec:h(this.deps.contentPlayer),...p.catchUpRan?p:{}}),this.streamClock.reportCorrection(t,d,o.target,i);(this.state.breakTimebase===e.PTS||this.state.breakTimebase===e.MEDIATIME)&&"number"==typeof t.start&&this.state.callbacks?.onContentResumeSeek?.(d,t.start+t.duration);let k=d,S=0;null!==g&&k>g&&(S=Math.round(1e3*(k-g))/1e3,k=g);let f=S>0?"end":null;const P=this.liveSafeSeekStart();if(null!==P&&k<P){const e=Math.round(1e3*(P-k))/1e3,s=this.liveSeekableWindowSec(),n=null===s?null:.5*s;null!==n&&e<=n?(S=e,k=P,f="start"):(this.deps.log(`Resume-seek: ${d}s is ${e}s behind the element's live window start (window ${s}s); not clamping`),this.deps.diagnose?.("DA-RESUME-START-CLAMP-SKIPPED",`Resume target ${d}s for break ${t.id} is ${e}s behind the element's seekable start but the gap exceeds half the ${s}s window; left unchanged`,{breakId:t.id,requested:d,seekableStart:P,behindSec:e,windowSec:s,maxBehindSec:n,...this.resumeAlignSummary()}))}if(null!==this.state.resumePrepositionedTo&&Math.abs(this.deps.contentPlayer.currentTime-k)<=c){const e=this.deps.contentPlayer.currentTime;return this.deps.log(`Resume: content already at ${e}s for break ${t.id} (pre-positioned during the break)`+(S>0?` — ${S}s short of policy, those frames are not published yet`:"")+" — no seek"),this.deps.diagnose?.("DA-RESUME-PREPOSITIONED",`Break ${t.id} resumed without a seek: content was moved to ${e}s during the break`+(S>0?` (${S}s short of the ${d}s policy target)`:""),{breakId:t.id,target:d,prepositionedTo:this.state.resumePrepositionedTo,landed:e,shortfallSec:S,exact:0===S,...this.resumeAlignSummary()}),this.streamClock.armLanding(t,e),null}return S>0&&(this.deps.log("start"===f?`Resume-seek clamped: ${d}s is behind the live window start (already evicted); seeking ${k}s instead (${S}s early)`:`Resume-seek clamped: ${d}s is beyond what the stream has published; seeking ${k}s instead (${S}s short)`),this.deps.diagnose?.("DA-RESUME-TARGET-CLAMPED","start"===f?`Resume target ${d}s for break ${t.id} is behind the live window start (already evicted); clamped to ${k}s`:`Resume target ${d}s for break ${t.id} is beyond the published window; clamped to ${k}s`,{breakId:t.id,requested:d,clamped:k,shortfallSec:S,bound:f,...this.resumeAlignSummary()})),this.streamClock.armLanding(t,k),k}reportCueEnd(e,t){const s=this.state.resumeAnchorIsCue?this.cueEndResolver?.(e):null;if(!s||!Number.isFinite(s.mediaTime))return null;const n=this.resumesAtBreakEnd(e),i=m(s.mediaTime-t);return this.deps.diagnose("DA-RESUME-CUE-END",n?`Break ${e.id}: resuming on the stream's cue_end at ${s.mediaTime}s (${i}s from the computed ${t}s)`:`Break ${e.id}: cue_end at ${s.mediaTime}s not used; the resume policy does not resume at the break end`,{breakId:e.id,computedTarget:t,cueEndTarget:s.mediaTime,deltaSec:i,applied:n,stage:"hand-back",corrected:!1}),n?s.mediaTime:null}applyResumeSeek(e,t=null){const s=this.resolveResumeTarget(e,t);null!==s&&(this.probeResumeLanding(e.id,s,this.resumePolicyTarget),this.streamClock.noteSeek(s),this.deps.contentPlayer.seek(s))}}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The stream's own clock against the content player's currentTime, measured from Anvato
3
+ * `type=beacon` ID3 tags (one every 3s on NFL Channel). The TS twin of the iOS runtime's
4
+ * `StreamClockMapping`.
5
+ *
6
+ * A beacon carries the stream clock in `pts` — the same clock as the break's `cue` and `cue_end` —
7
+ * and is delivered at its position in currentTime, so `pts − startTime` is the mapping in force.
8
+ * Only beacons delivered after the last seek that may have restarted the buffer count:
9
+ * {@link StreamClockMapping.markSeek} starts over. See `docs/ios-live-resume-v2.md` §16.
10
+ */
11
+ export interface StreamClockAnchor {
12
+ /** The beacon's `pts`, in the feed's own unit. */
13
+ raw: number;
14
+ /** Where the player delivered it, in seconds of currentTime. */
15
+ mediaTime: number;
16
+ }
17
+ export type StreamClockUpdate = {
18
+ kind: 'none';
19
+ } | {
20
+ kind: 'mapped';
21
+ offsetSec: number;
22
+ anchors: number;
23
+ } | {
24
+ kind: 'remapped';
25
+ fromSec: number;
26
+ toSec: number;
27
+ };
28
+ /**
29
+ * Beacons are packed into ID3 PES packets, so their delivery alternates by ~0.134s around the `pts`
30
+ * cadence; the mean over the beacons since the last seek cancels that, and parse-time deliveries
31
+ * can arrive out of order, so two delivered in a row need not be neighbours.
32
+ */
33
+ export declare const STREAM_CLOCK_ANCHORS_KEPT = 10;
34
+ /** A mapping from fewer beacons than this still carries part of the packet jitter. */
35
+ export declare const STREAM_CLOCK_SETTLED_ANCHORS = 2;
36
+ /** An offset step beyond this between consecutive beacons is a remap, not packing jitter. */
37
+ export declare const STREAM_CLOCK_REMAP_THRESHOLD_SEC = 0.2;
38
+ /**
39
+ * The feed's `pts` unit from two consecutive beacons: their `pts` advance by ~1000× or ~1× the
40
+ * currentTime between them. Anything else (a seek in between, an out-of-order delivery) says nothing.
41
+ */
42
+ export declare function streamClockUnit(rawDelta: number, mediaDelta: number): number | null;
43
+ export declare class StreamClockMapping {
44
+ /**
45
+ * Raw `pts` units per second: 1000 when the feed's `pts` is milliseconds (NFL Channel), 1 when
46
+ * seconds. Learned once from two beacons' cadence and kept for the session.
47
+ */
48
+ unitsPerSecond: number | null;
49
+ /** Bumped by {@link markSeek}; every anchor belongs to the generation it was delivered in. */
50
+ generation: number;
51
+ private lastBeacon;
52
+ private anchors;
53
+ /** Beacons behind the current mapping (0 before the first one after the last seek). */
54
+ get anchorCount(): number;
55
+ /** A seek that may have restarted the buffer: the mapping must be measured again. */
56
+ markSeek(): void;
57
+ /** Records a beacon; see {@link StreamClockUpdate} for what it did to the mapping. */
58
+ ingestBeacon(raw: number, mediaTime: number): StreamClockUpdate;
59
+ /** Mean `stream − currentTime`, in seconds, over the beacons since the last seek; null before one. */
60
+ get offsetSec(): number | null;
61
+ /** A raw `pts` (a beacon's, a cue's, a break's manifest start) in seconds of the stream clock. */
62
+ streamSeconds(raw: number): number | null;
63
+ /** Where a stream-clock instant is in currentTime under the current mapping. */
64
+ mediaTimeForStreamSeconds(seconds: number): number | null;
65
+ }
@@ -0,0 +1 @@
1
+ export const STREAM_CLOCK_ANCHORS_KEPT=10;export const STREAM_CLOCK_SETTLED_ANCHORS=2;export const STREAM_CLOCK_REMAP_THRESHOLD_SEC=.2;export function streamClockUnit(n,t){if(!(n>0&&t>.5))return null;const e=n/t;return e>800&&e<1250?1e3:e>.8&&e<1.25?1:null}export class StreamClockMapping{constructor(){this.unitsPerSecond=null,this.generation=0,this.lastBeacon=null,this.anchors=[]}get anchorCount(){return this.anchors.length}markSeek(){this.generation+=1,this.anchors=[]}ingestBeacon(n,t){if(!Number.isFinite(n)||!Number.isFinite(t))return{kind:"none"};null===this.unitsPerSecond&&this.lastBeacon&&(this.unitsPerSecond=streamClockUnit(n-this.lastBeacon.raw,t-this.lastBeacon.mediaTime)),this.lastBeacon={raw:n,mediaTime:t};const e=this.unitsPerSecond;if(null===e||this.anchors.some(t=>t.raw===n))return{kind:"none"};const s={raw:n,mediaTime:t},i=n/e-t,r=this.offsetSec;return null!==r&&Math.abs(i-r)>.2?(this.anchors=[s],{kind:"remapped",fromSec:r,toSec:i}):(this.anchors.push(s),this.anchors.length>10&&this.anchors.splice(0,this.anchors.length-10),{kind:"mapped",offsetSec:this.offsetSec??i,anchors:this.anchors.length})}get offsetSec(){const n=this.unitsPerSecond;return null===n||0===this.anchors.length?null:this.anchors.reduce((t,e)=>t+e.raw/n-e.mediaTime,0)/this.anchors.length}streamSeconds(n){return Number.isFinite(n)&&null!==this.unitsPerSecond?n/this.unitsPerSecond:null}mediaTimeForStreamSeconds(n){const t=this.offsetSec;return Number.isFinite(n)&&null!==t?n-t:null}}
@@ -0,0 +1,94 @@
1
+ import type { PlayerAdapter, TimedMetadataCue } from '../../interfaces/PlayerAdapter';
2
+ import type { Break } from '../../types/BreakManifest';
3
+ import { StreamClockMapping } from './streamClockMapping';
4
+ /** The stream's own end of a break, matched to it on the stream clock. */
5
+ export interface BreakEndOnStreamClock {
6
+ /** Where the player delivered the `cue_end`, in seconds of currentTime. */
7
+ mediaTime: number;
8
+ /** `cue_end` pts minus the break's start pts, in seconds. */
9
+ lengthSec: number;
10
+ }
11
+ /** A resume point on the stream clock, and what fixed it. */
12
+ export interface StreamClockLanding {
13
+ seconds: number;
14
+ source: 'cue_end' | 'cue+duration';
15
+ }
16
+ export interface StreamClockResumeDeps {
17
+ contentPlayer: PlayerAdapter;
18
+ diagnose: (code: string, message: string, context?: Record<string, unknown>) => void;
19
+ /** The break being resumed, while one is. */
20
+ activeBreak: () => Break | null;
21
+ /** Whether the break's anchor is its in-stream cue (the stream clock needs the cue's pts). */
22
+ anchorIsCue: () => boolean;
23
+ /** The break's matched `cue_end`, or null. */
24
+ breakEnd: (breakInfo: Break) => BreakEndOnStreamClock | null;
25
+ /** The policy's resume point on the currentTime timeline, ignoring the stream. */
26
+ computedTarget: (breakInfo: Break) => number | null;
27
+ /** Replacement resumes at the break end, the only policy the stream's end of the break can serve. */
28
+ resumesAtBreakEnd: (breakInfo: Break) => boolean;
29
+ /** Wall clock in milliseconds. */
30
+ now: () => number;
31
+ }
32
+ /**
33
+ * Live resume on the stream's own clock (`ptsSource: 'anvatoCue'`), web: the resume point is a
34
+ * stream-clock instant, converted to currentTime with the mapping that beacons parsed since the
35
+ * run-up's last seek measure, and re-mapped on every beacon until the hand-back. The TS twin of
36
+ * the iOS runtime's `OverlayAdRenderer+StreamClock`; see `docs/ios-live-resume-v2.md` §16.
37
+ */
38
+ export declare class StreamClockResume {
39
+ private readonly deps;
40
+ readonly clock: StreamClockMapping;
41
+ /** The run-up made its opening move: from here the stream clock may map the resume point. */
42
+ armed: boolean;
43
+ /** The hand-back resumed on the stream-clock target. */
44
+ applied: boolean;
45
+ private reportedTarget;
46
+ private reportedGeneration;
47
+ private offsetAtBreakStart;
48
+ private remaps;
49
+ private landingCheck;
50
+ private landingTimer;
51
+ constructor(deps: StreamClockResumeDeps);
52
+ /** The stream carries beacons, so its clock places the resume point once the run-up is mapped. */
53
+ get decides(): boolean;
54
+ /** Content paused for a new break: per-break state starts over, the current mapping is the reference. */
55
+ beginBreak(): void;
56
+ /** The run-up's opening move (catch-up start or pre-positioning). */
57
+ arm(): void;
58
+ /** Before an SDK seek: one that may restart the buffer means the mapping is measured again. */
59
+ noteSeek(position: number): void;
60
+ /** The content source was rebuilt (pipeline recreate): its timeline has to be mapped again. */
61
+ noteReload(): void;
62
+ /**
63
+ * Records an Anvato `type=beacon` cue; other cues are ignored. Presentation re-deliveries are
64
+ * skipped: they repeat a cue parsed earlier, possibly before the last seek.
65
+ */
66
+ ingestCue(cue: TimedMetadataCue): void;
67
+ /**
68
+ * The break's resume point on the stream clock: its matched `cue_end`, else the cue plus the
69
+ * break duration. Null for a break that was not cue-matched or before the feed's unit is known.
70
+ */
71
+ landing(breakInfo: Break): StreamClockLanding | null;
72
+ /** The resume point in currentTime under the mapping measured since the run-up's last seek, or null. */
73
+ target(breakInfo: Break): number | null;
74
+ /** The hand-back's stream-clock target, recording whether it applies; null for an early return. */
75
+ handBackTarget(breakInfo: Break, earlyReturn: boolean): number | null;
76
+ /** What DA-RESUME-SEEK's target is based on, when the stream clock decided it. */
77
+ seekBasis(breakInfo: Break): string | null;
78
+ /** The stream-clock fields of DA-RESUME-SEEK; empty unless the hand-back resumes on the stream clock. */
79
+ seekContext(breakInfo: Break, target: number, computed: number): Record<string, unknown>;
80
+ /**
81
+ * DA-RESUME-PTS-CORRECTED, once per break at the hand-back, whenever the stream carries beacons:
82
+ * how far the stream clock moved the resume point from the currentTime target, or why it did not.
83
+ */
84
+ reportCorrection(breakInfo: Break, target: number, computed: number, earlyReturn: boolean): void;
85
+ /** Arms the landing measurement when the hand-back resumed on the stream clock. */
86
+ armLanding(breakInfo: Break, resumedAt: number): void;
87
+ /** The landing probe measured where the hand-back seek really landed. */
88
+ updateLanding(breakId: string, landed: number): void;
89
+ cancelLanding(): void;
90
+ private reportTarget;
91
+ /** DA-RESUME-PTS-LANDED: where content resumed, on the stream clock, against the resume point. */
92
+ private finishLanding;
93
+ private bufferedState;
94
+ }
@@ -0,0 +1 @@
1
+ import{anvatoPayloadFromCue as e,parseAnvatoPayload as t}from"../MetadataCueTracker";import{STREAM_CLOCK_SETTLED_ANCHORS as n,StreamClockMapping as s}from"./streamClockMapping";const r=e=>Math.round(1e3*e)/1e3;export class StreamClockResume{constructor(e){this.deps=e,this.clock=new s,this.armed=!1,this.applied=!1,this.reportedTarget=null,this.reportedGeneration=null,this.offsetAtBreakStart=null,this.remaps=0,this.landingCheck=null,this.landingTimer=null}get decides(){return null!==this.clock.unitsPerSecond}beginBreak(){this.cancelLanding(),this.armed=!1,this.applied=!1,this.reportedTarget=null,this.reportedGeneration=null,this.remaps=0,this.offsetAtBreakStart=this.clock.offsetSec}arm(){this.armed=!0}noteSeek(e){!0!==this.bufferedState(e)&&this.clock.markSeek()}noteReload(){this.clock.markSeek()}ingestCue(n){if("presented"===n.phase||!Number.isFinite(n.startTime))return;const s=e(n);if(!s)return;const i=t(s);if("beacon"!==i.type)return;const a=Number(i.pts);if(!Number.isFinite(a)||""===i.pts)return;const c=this.clock.ingestBeacon(a,n.startTime),o=this.deps.activeBreak();"remapped"===c.kind&&(o&&(this.remaps+=1),(this.armed||this.landingCheck)&&this.deps.diagnose("DA-RESUME-PTS-REMAP",`currentTime moved ${r(c.toSec-c.fromSec)}s against the stream clock; the resume point is mapped again`,{breakId:o?.id??this.landingCheck?.breakId??"",fromOffsetSec:r(c.fromSec),toOffsetSec:r(c.toSec),deltaSec:r(c.toSec-c.fromSec),currentTime:r(this.deps.contentPlayer.currentTime),stage:this.landingCheck?"after-hand-back":"run-up"})),o&&this.armed&&this.reportTarget(o),this.finishLanding(!1)}landing(e){const t=e.start;if(!this.deps.anchorIsCue()||"number"!=typeof t)return null;const n=this.clock.streamSeconds(t);if(null===n)return null;const s=this.deps.breakEnd(e);return s&&Number.isFinite(s.lengthSec)&&s.lengthSec>0?{seconds:n+s.lengthSec,source:"cue_end"}:{seconds:n+(e.duration??0),source:"cue+duration"}}target(e){if(!this.armed||!this.deps.resumesAtBreakEnd(e))return null;const t=this.landing(e);return t?this.clock.mediaTimeForStreamSeconds(t.seconds):null}handBackTarget(e,t){const n=t?null:this.target(e);return this.applied=null!==n,n}seekBasis(e){const t=this.applied?this.landing(e):null;return t?`on the stream clock, ${t.source}`:null}seekContext(e,t,n){const s=this.applied?this.landing(e):null,i=this.clock.offsetSec;return s&&null!==i?{streamClockTarget:r(t),computedTarget:n,landingStreamSec:r(s.seconds),landingSource:s.source,streamClockOffsetSec:r(i),streamClockBeacons:this.clock.anchorCount}:{}}reportCorrection(e,t,n,s){if(s||!this.armed||!this.decides)return;const i={breakId:e.id,applied:this.applied,computedTarget:n,remaps:this.remaps},a=this.deps.breakEnd(e);a&&(i.cueEndTarget=a.mediaTime);const c=this.applied?this.landing(e):null,o=this.clock.offsetSec;if(!c||null===o)return i.reason="no beacon since the run-up's last seek",void this.deps.diagnose("DA-RESUME-PTS-CORRECTED",`Break ${e.id}: no beacon since the run-up's last seek; the stream clock did not place the resume`,i);const d=r(t-n),l=null===this.offsetAtBreakStart?null:r(this.offsetAtBreakStart-o);Object.assign(i,{streamClockTarget:r(t),correctionSec:d,currentTimeShiftSec:l,landingSource:c.source,landingStreamSec:r(c.seconds),offsetSec:r(o),beacons:this.clock.anchorCount}),this.deps.diagnose("DA-RESUME-PTS-CORRECTED",`Break ${e.id}: the stream clock placed the resume at ${r(t)}s (${c.source}), ${d}s from the currentTime target ${n}s`+(null===l?"":`; currentTime moved ${l}s against the stream during the break`),i)}armLanding(e,t){const n=this.applied?this.landing(e):null;n&&(this.cancelLanding(),this.landingCheck={breakId:e.id,landing:n,resumedAt:t,handBackAtMs:this.deps.now()},this.landingTimer=setTimeout(()=>this.finishLanding(!0),15e3))}updateLanding(e,t){this.landingCheck?.breakId===e&&Number.isFinite(t)&&(this.landingCheck.resumedAt=t)}cancelLanding(){this.landingTimer&&clearTimeout(this.landingTimer),this.landingTimer=null,this.landingCheck=null}reportTarget(e){const t=this.landing(e),n=this.target(e),s=this.clock.offsetSec;if(!t||null===n||null===s)return;const i=this.clock.generation;if(i===this.reportedGeneration&&null!==this.reportedTarget&&Math.abs(n-this.reportedTarget)<.1)return;this.reportedTarget=n,this.reportedGeneration=i;const a=this.deps.computedTarget(e),c={breakId:e.id,target:r(n),landingStreamSec:r(t.seconds),landingSource:t.source,offsetSec:r(s),beacons:this.clock.anchorCount,generation:i,currentTime:r(this.deps.contentPlayer.currentTime)};null!==a&&(c.computedTarget=a,c.deltaSec=r(n-a)),this.deps.diagnose("DA-RESUME-PTS-MAP",`Break ${e.id}: resume point (${t.source}) maps to ${r(n)}s`+(null===a?"":` (${r(n-a)}s from the computed ${a}s)`),c)}finishLanding(e){const t=this.landingCheck;if(!t)return;const s=(this.deps.now()-t.handBackAtMs)/1e3,i={breakId:t.breakId,landingStreamSec:r(t.landing.seconds),landingSource:t.landing.source,resumedAt:r(t.resumedAt),sinceHandBackSec:r(s)},a=this.clock.offsetSec;if(null===a){if(!e)return;return this.cancelLanding(),i.reason="no beacon after the hand-back",void this.deps.diagnose("DA-RESUME-PTS-LANDED",`Resume landing for break ${t.breakId} could not be measured on the stream clock (no beacon)`,i)}if(!e&&this.clock.anchorCount<n&&s<6)return;this.cancelLanding();const c=t.resumedAt+a,o=r(c-t.landing.seconds);Object.assign(i,{landedStreamSec:r(c),errorSec:o,offsetSec:r(a),beacons:this.clock.anchorCount}),this.deps.diagnose("DA-RESUME-PTS-LANDED",`Resume for break ${t.breakId} landed ${Math.abs(o)}s ${o<0?"before":"after"} the stream's resume point (${t.landing.source})`,i)}bufferedState(e){const t=this.deps.contentPlayer.videoElement?.buffered;if(!t||!Number.isFinite(e))return null;for(let n=0;n<t.length;n++)if(e>=t.start(n)&&e<t.end(n))return!0;return!1}}
@@ -2,12 +2,24 @@ import type { TimedMetadataCue } from '../interfaces/PlayerAdapter';
2
2
  import { MetadataCueTracker } from './MetadataCueTracker';
3
3
  import type { BreakScheduler } from './BreakScheduler';
4
4
  import type { Break } from '../types/BreakManifest';
5
+ import type { BreakEndOnStreamClock } from './adPlayer/streamClockResume';
6
+ import type { AdPlayerController } from './AdPlayerController';
5
7
  /**
6
8
  * The media time of the in-stream cue that matched `breakInfo`, for anchoring the content resume;
7
9
  * null when there is no cue tracker (every timebase except `ptsSource: 'anvatoCue'`), when the
8
10
  * break carries no numeric PTS start, or when no cue has been observed for it.
9
11
  */
10
12
  export declare function cueAnchorForBreak(metadataCueTracker: MetadataCueTracker | null, breakInfo: Break): number | null;
13
+ /**
14
+ * The break's `cue_end` when one was matched to it on the stream clock and its length is accepted
15
+ * (within tolerance of the duration); null otherwise.
16
+ */
17
+ export declare function cueEndForBreak(metadataCueTracker: MetadataCueTracker | null, breakInfo: Break): BreakEndOnStreamClock | null;
18
+ /**
19
+ * Anchor the content resume on the break's in-stream cue and end it on the stream's `cue_end`,
20
+ * both read from the session's tracker (null when `ptsSource` is not `'anvatoCue'`).
21
+ */
22
+ export declare function wireCueResume(controller: AdPlayerController, tracker: () => MetadataCueTracker | null): void;
11
23
  export declare function armBreakFromPresentedCue(cue: TimedMetadataCue, metadataCueTracker: MetadataCueTracker | null, breakScheduler: BreakScheduler | undefined): void;
12
24
  export declare function notedManifestBreakIds(manifest: {
13
25
  breaks: Array<{
@@ -1 +1 @@
1
- import{isAnvatoCue as e,parseAnvatoPayload as t}from"./MetadataCueTracker";export function cueAnchorForBreak(e,t){const r=t.start;return e&&"number"==typeof r&&Number.isFinite(r)?e.mediaTimeForPts(r):null}export function armBreakFromPresentedCue(r,s,n){if(!s||!n||!e(r))return;const a=t(r.messageData??"");if("cue"!==a.type)return;const i=Number(a.pts);Number.isFinite(i)&&n.notifyCuePresented(i)}export function notedManifestBreakIds(e,t){const r=[];for(const s of e.breaks)t.has(s.id)||(t.add(s.id),r.push(s.id));return r}export function diagnoseAnvatoCueObserved(r,s,n,a,i,o){if(!n||!e(r))return;const u=r.messageData??"",d=t(u);if("cue"!==d.type)return;const c=`${r.startTime}|${u}`;if(a.has(c))return;a.add(c);const m=Number(d.pts);o("DA-ANVATO-CUE-OBSERVED",`Anvato cue observed: pts=${d.pts} at media time ${r.startTime}s`,{pts:Number.isFinite(m)?m:d.pts,mediaTime:r.startTime,playheadSec:i,recorded:s,payload:u.slice(0,300)})}
1
+ import{isAnvatoCue as e,parseAnvatoPayload as t}from"./MetadataCueTracker";export function cueAnchorForBreak(e,t){const r=t.start;return e&&"number"==typeof r&&Number.isFinite(r)?e.mediaTimeForPts(r):null}export function cueEndForBreak(e,t){const r=t.start;if(!e||"number"!=typeof r||!Number.isFinite(r))return null;const n=e.breakEnd(r,t.duration);return n?.accepted?{mediaTime:n.mediaTime,lengthSec:n.lengthSec}:null}export function wireCueResume(e,t){e.setResumeCueAnchorResolver(e=>cueAnchorForBreak(t(),e)),e.setResumeCueEndResolver(e=>cueEndForBreak(t(),e))}export function armBreakFromPresentedCue(r,n,s){if(!n||!s||!e(r))return;const o=t(r.messageData??"");if("cue"!==o.type)return;const i=Number(o.pts);Number.isFinite(i)&&s.notifyCuePresented(i)}export function notedManifestBreakIds(e,t){const r=[];for(const n of e.breaks)t.has(n.id)||(t.add(n.id),r.push(n.id));return r}export function diagnoseAnvatoCueObserved(r,n,s,o,i,u){if(!s||!e(r))return;const a=r.messageData??"",c=t(a);if("cue"!==c.type)return;const d=`${r.startTime}|${a}`;if(o.has(d))return;o.add(d);const m=Number(c.pts);u("DA-ANVATO-CUE-OBSERVED",`Anvato cue observed: pts=${c.pts} at media time ${r.startTime}s`,{pts:Number.isFinite(m)?m:c.pts,mediaTime:r.startTime,playheadSec:i,recorded:n,payload:a.slice(0,300)})}
@@ -25,6 +25,8 @@ export interface BreakTimingState {
25
25
  anvatoPendingDiagnosed: Set<string>;
26
26
  /** Break ids for which DA-ANVATO-CUE-MATCHED has been emitted (one-shot). */
27
27
  anvatoMatchedDiagnosed: Set<string>;
28
+ /** Break ids whose `cue_end` was judged (DA-ANVATO-CUE-END-MATCHED or -REJECTED, one-shot). */
29
+ anvatoEndDiagnosed: Set<string>;
28
30
  }
29
31
  export declare function createBreakTimingState(): BreakTimingState;
30
32
  export interface BreakTimingDeps {
@@ -57,4 +59,9 @@ export declare function getBreakStartTime(state: BreakTimingState, deps: BreakTi
57
59
  * Null while no matching cue was observed; pending and first match are each diagnosed once.
58
60
  */
59
61
  export declare function resolveAnvatoStartTime(state: BreakTimingState, deps: BreakTimingDeps, breakInfo: Break, startPts: number): number | null;
62
+ /**
63
+ * Judge the active PTS break's `type=cue_end` once: matched when its stream-clock length is
64
+ * within tolerance of the duration, rejected otherwise. Nothing until a candidate is observed.
65
+ */
66
+ export declare function diagnoseAnvatoBreakEnd(state: BreakTimingState, deps: BreakTimingDeps, breakInfo: Break): void;
60
67
  export declare function secondsUntilBreak(breakStartTime: number, currentTime: number): number;
@@ -1 +1 @@
1
- import{Timebase as t}from"../types/BreakManifest";export const PDT_PLAYBACK_SETTLE_MS=1e3;export function createBreakTimingState(){return{timebase:t.WALLCLOCK,pdtMissingWarned:!1,pdtSeen:!1,firstPdtAttemptMs:null,playbackStartedAtMs:null,anvatoPendingDiagnosed:new Set,anvatoMatchedDiagnosed:new Set}}export function getCurrentTime(e,a){if(e.timebase!==t.WALLCLOCK)return 1e3*a.player.currentTime;const n=a.player.programDateTime;if(n){const t=n.getTime();if(!isNaN(t))return e.pdtSeen=!0,t}if(e.pdtSeen)return null;const r=a.clock.now();null===e.firstPdtAttemptMs&&(e.firstPdtAttemptMs=r),null===e.playbackStartedAtMs&&a.player.currentTime>0&&(e.playbackStartedAtMs=r);const s=null!==e.playbackStartedAtMs&&r-e.playbackStartedAtMs>=1e3,i=r-e.firstPdtAttemptMs>=a.pdtGraceMs;return s||i?(warnPdtMissing(e,a,s),r):null}export function warnPdtMissing(t,e,a){if(t.pdtMissingWarned)return;t.pdtMissingWarned=!0;const n=a?"content is playing and exposes none":`none appeared within ${e.pdtGraceSeconds}s`;e.log(`No Program Date Time on wallclock stream (${n}); falling back to the system clock`),e.diagnose?.("DA-PDT-MISSING",`No EXT-X-PROGRAM-DATE-TIME available (${n}); wallclock-timebase breaks are matched against the system clock instead of the stream position.`,{graceSeconds:e.pdtGraceSeconds,playbackStarted:a})}export function getBreakStartTime(e,a,n){if(e.timebase===t.WALLCLOCK){if("string"!=typeof n.start)return a.log("Invalid break start for wallclock timebase:",n.start),null;const t=new Date(n.start);return isNaN(t.getTime())?(a.log("Invalid break start date:",n.start),null):t.getTime()}return"number"!=typeof n.start?(a.log(`Invalid break start for ${e.timebase} timebase:`,n.start),null):a.cueTracker&&e.timebase===t.PTS?resolveAnvatoStartTime(e,a,n,n.start):1e3*n.start}export function resolveAnvatoStartTime(t,e,a,n){const r=e.cueTracker.mediaTimeForPts(n);return null===r?(t.anvatoPendingDiagnosed.has(a.id)||(t.anvatoPendingDiagnosed.add(a.id),e.log(`⌛ Break "${a.id}" awaiting Anvato cue for PTS ${n}`),e.diagnose?.("DA-ANVATO-CUE-PENDING",`No Anvato cue observed for break "${a.id}" (pts ${n}); break stays pending.`,{breakId:a.id,pts:n})),null):(t.anvatoMatchedDiagnosed.has(a.id)||(t.anvatoMatchedDiagnosed.add(a.id),e.log(`🎯 Break "${a.id}" matched Anvato cue: pts ${n} → ${r}s`),e.diagnose?.("DA-ANVATO-CUE-MATCHED",`Anvato cue matched for break "${a.id}": pts ${n} plays at media time ${r}s.`,{breakId:a.id,pts:n,mediaTime:r})),1e3*r)}export function secondsUntilBreak(t,e){const a=Math.round((t-e)/1e3);return a>0?a:0}
1
+ import{Timebase as e}from"../types/BreakManifest";export const PDT_PLAYBACK_SETTLE_MS=1e3;export function createBreakTimingState(){return{timebase:e.WALLCLOCK,pdtMissingWarned:!1,pdtSeen:!1,firstPdtAttemptMs:null,playbackStartedAtMs:null,anvatoPendingDiagnosed:new Set,anvatoMatchedDiagnosed:new Set,anvatoEndDiagnosed:new Set}}export function getCurrentTime(t,a){if(t.timebase!==e.WALLCLOCK)return 1e3*a.player.currentTime;const n=a.player.programDateTime;if(n){const e=n.getTime();if(!isNaN(e))return t.pdtSeen=!0,e}if(t.pdtSeen)return null;const r=a.clock.now();null===t.firstPdtAttemptMs&&(t.firstPdtAttemptMs=r),null===t.playbackStartedAtMs&&a.player.currentTime>0&&(t.playbackStartedAtMs=r);const i=null!==t.playbackStartedAtMs&&r-t.playbackStartedAtMs>=1e3,s=r-t.firstPdtAttemptMs>=a.pdtGraceMs;return i||s?(warnPdtMissing(t,a,i),r):null}export function warnPdtMissing(e,t,a){if(e.pdtMissingWarned)return;e.pdtMissingWarned=!0;const n=a?"content is playing and exposes none":`none appeared within ${t.pdtGraceSeconds}s`;t.log(`No Program Date Time on wallclock stream (${n}); falling back to the system clock`),t.diagnose?.("DA-PDT-MISSING",`No EXT-X-PROGRAM-DATE-TIME available (${n}); wallclock-timebase breaks are matched against the system clock instead of the stream position.`,{graceSeconds:t.pdtGraceSeconds,playbackStarted:a})}export function getBreakStartTime(t,a,n){if(t.timebase===e.WALLCLOCK){if("string"!=typeof n.start)return a.log("Invalid break start for wallclock timebase:",n.start),null;const e=new Date(n.start);return isNaN(e.getTime())?(a.log("Invalid break start date:",n.start),null):e.getTime()}return"number"!=typeof n.start?(a.log(`Invalid break start for ${t.timebase} timebase:`,n.start),null):a.cueTracker&&t.timebase===e.PTS?resolveAnvatoStartTime(t,a,n,n.start):1e3*n.start}export function resolveAnvatoStartTime(e,t,a,n){const r=t.cueTracker.mediaTimeForPts(n);return null===r?(e.anvatoPendingDiagnosed.has(a.id)||(e.anvatoPendingDiagnosed.add(a.id),t.log(`⌛ Break "${a.id}" awaiting Anvato cue for PTS ${n}`),t.diagnose?.("DA-ANVATO-CUE-PENDING",`No Anvato cue observed for break "${a.id}" (pts ${n}); break stays pending.`,{breakId:a.id,pts:n})),null):(e.anvatoMatchedDiagnosed.has(a.id)||(e.anvatoMatchedDiagnosed.add(a.id),t.log(`🎯 Break "${a.id}" matched Anvato cue: pts ${n} → ${r}s`),t.diagnose?.("DA-ANVATO-CUE-MATCHED",`Anvato cue matched for break "${a.id}": pts ${n} plays at media time ${r}s.`,{breakId:a.id,pts:n,mediaTime:r})),1e3*r)}export function diagnoseAnvatoBreakEnd(e,t,a){if(null===t.cueTracker||"number"!=typeof a.start)return;if(e.anvatoEndDiagnosed.has(a.id))return;const n=t.cueTracker.breakEnd(a.start,a.duration);if(null===n)return;e.anvatoEndDiagnosed.add(a.id);const r={breakId:a.id,mediaTime:n.mediaTime,lengthSec:n.lengthSec,durationSec:a.duration};n.accepted?(t.log(`Break "${a.id}" end signalled at media time ${n.mediaTime}s`),t.diagnose?.("DA-ANVATO-CUE-END-MATCHED",`Anvato cue_end matched for break "${a.id}": the stream ends it at media time ${n.mediaTime}s (${n.lengthSec}s on the stream clock).`,r)):t.diagnose?.("DA-ANVATO-CUE-END-REJECTED",`Anvato cue_end for break "${a.id}" signals ${n.lengthSec}s, not the ${a.duration}s duration; it is ignored.`,r)}export function secondsUntilBreak(e,t){const a=Math.round((e-t)/1e3);return a>0?a:0}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dolby-optiview/ads-sdk-core",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "OptiView Ads SDK Core - Player-agnostic ad insertion",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",