@dolby-optiview/ads-sdk-core 1.0.0-beta.3 → 1.0.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/OptiViewAds.d.ts +3 -3
- package/dist/generated/diagnosticCodes.d.ts +5 -0
- package/dist/generated/diagnosticCodes.js +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/services/AdPlayerController.d.ts +1 -3
- package/dist/services/AdPlayerController.js +1 -1
- package/dist/services/SsaiController.js +1 -1
- package/dist/services/adPlayer/AdPlayerState.d.ts +8 -1
- package/dist/services/adPlayer/AdPlayerState.js +1 -1
- package/dist/services/adPlayer/AdPreloader.d.ts +2 -1
- package/dist/services/adPlayer/AdPreloader.js +1 -1
- package/dist/services/adPlayer/AssetParameterResolver.d.ts +2 -1
- package/dist/services/adPlayer/AssetParameterResolver.js +1 -1
- package/dist/services/adPlayer/AssetPlayback.d.ts +1 -1
- package/dist/services/adPlayer/AssetPlayback.js +1 -1
- package/dist/services/adPlayer/BreakSequenceDriver.d.ts +1 -1
- package/dist/services/adPlayer/BreakSequenceDriver.js +1 -1
- package/dist/services/adPlayer/ContentResumeCoordinator.d.ts +1 -1
- package/dist/services/adPlayer/ContentResumeCoordinator.js +1 -1
- package/dist/services/adPlayer/SharedElementBreakPlayer.d.ts +11 -2
- package/dist/services/adPlayer/SharedElementBreakPlayer.js +1 -1
- package/dist/services/assetParameterMacroTable.js +1 -1
- package/dist/services/assetParameterMacros.d.ts +16 -6
- package/dist/services/assetParameterMacros.js +1 -1
- package/dist/types/OptiViewAdsConfig.d.ts +13 -9
- package/package.json +1 -1
package/dist/OptiViewAds.d.ts
CHANGED
|
@@ -129,9 +129,9 @@ export declare class OptiViewAds {
|
|
|
129
129
|
* @category Lifecycle */
|
|
130
130
|
updateAssetParameters(params: Record<string, string>): void;
|
|
131
131
|
/**
|
|
132
|
-
* Merge per-name macro updates; `null`
|
|
133
|
-
* Active GAM targeting is re-resolved via `replaceAdTagParameters()
|
|
134
|
-
* new values on the next request without re-requesting an already loaded ad.
|
|
132
|
+
* Merge per-name macro updates; `null` marks a name empty, `undefined` unregisters it, and
|
|
133
|
+
* other names stay unchanged. Active GAM targeting is re-resolved via `replaceAdTagParameters()`;
|
|
134
|
+
* VAST URLs use new values on the next request without re-requesting an already loaded ad.
|
|
135
135
|
* @category Lifecycle */
|
|
136
136
|
updateAssetParameterMacros(macros: AssetParameterMacroUpdates): void;
|
|
137
137
|
private endSessionInternal;
|
|
@@ -289,6 +289,11 @@ export declare const DIAGNOSTIC_CODES: {
|
|
|
289
289
|
readonly level: "warn";
|
|
290
290
|
readonly 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.";
|
|
291
291
|
};
|
|
292
|
+
readonly "DA-ASSET-PARAMETER-OMITTED": {
|
|
293
|
+
readonly category: "break";
|
|
294
|
+
readonly level: "info";
|
|
295
|
+
readonly 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.";
|
|
296
|
+
};
|
|
292
297
|
readonly "DA-VAST-SSAI-UNSUPPORTED": {
|
|
293
298
|
readonly category: "session";
|
|
294
299
|
readonly level: "warn";
|
|
@@ -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-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-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-AD-PLAYBACK-ERROR":{category:"playback",level:"error",summary:"The ad player reported a playback error during a break."},"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-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-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-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-RESUME-SEEK":{category:"playback",level:"info",summary:"Content was resume-seeked to the resolved post-break position (insertion type policy)."},"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 inside the engine's minimum live offset and was clamped to the closest position the engine will hold; context carries breakId, requested, clamped and shortfallSec. Distinct from DA-RESUME-OFFSET-CLAMPED, which shortens the OFFSET to the ad seconds actually played."},"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-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-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-AD-PLAYBACK-ERROR":{category:"playback",level:"error",summary:"The ad player reported a playback error during a break."},"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-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-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-RESUME-SEEK":{category:"playback",level:"info",summary:"Content was resume-seeked to the resolved post-break position (insertion type policy)."},"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 inside the engine's minimum live offset and was clamped to the closest position the engine will hold; context carries breakId, requested, clamped and shortfallSec. Distinct from DA-RESUME-OFFSET-CLAMPED, which shortens the OFFSET to the ad seconds actually played."},"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 +1 @@
|
|
|
1
|
-
export const SDK_VERSION="1.0.0-beta.
|
|
1
|
+
export const SDK_VERSION="1.0.0-beta.5";
|
|
@@ -120,8 +120,6 @@ export declare class AdPlayerController {
|
|
|
120
120
|
private abortingBreak;
|
|
121
121
|
private overlayImageEl;
|
|
122
122
|
private imageAssetTimer;
|
|
123
|
-
private get preloadedBreakId();
|
|
124
|
-
private set preloadedBreakId(value);
|
|
125
123
|
private chainResolver;
|
|
126
124
|
private transitionPhaseReporter;
|
|
127
125
|
private chaining;
|
|
@@ -452,7 +450,7 @@ export declare class AdPlayerController {
|
|
|
452
450
|
/**
|
|
453
451
|
* Pausing the ad media is what stops its audio — removing the overlay from the DOM does not
|
|
454
452
|
* reliably stop a playing element. Unlike {@link endBreak} it does not resume content: the
|
|
455
|
-
* caller owns the content lifecycle once the session is ending.
|
|
453
|
+
* caller owns the content lifecycle once the session is ending. Cancels pending restores even when idle.
|
|
456
454
|
*/
|
|
457
455
|
stopActiveBreak(): void;
|
|
458
456
|
private resolveChainedSuccessor;
|
|
@@ -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 a,DEFAULT_DOUBLE_BOX_AUDIO as s}from"../types/OptiViewAdsConfig";import{pipOverridesFormat as i,pipSuppressesBackdrop as n}from"./pictureInPicture";import{AdBreakSequencer as o,assetsOfVariant as l,resolveBreakFormat as d}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}from"./adPlayer/AdPlayerState";import{PauseAdPresenter as g}from"./adPlayer/PauseAdPresenter";import{AssetParameterResolver as P}from"./adPlayer/AssetParameterResolver";import{GamPodBridge as y}from"./adPlayer/GamPodBridge";import{AdStage as p}from"./adPlayer/AdStage";import{AdPreloader as A}from"./adPlayer/AdPreloader";import{PresentationModeTracker as C}from"./adPlayer/PresentationModeTracker";import{SharedElementBreakPlayer as k}from"./adPlayer/SharedElementBreakPlayer";import{ContentResumeCoordinator as v}from"./adPlayer/ContentResumeCoordinator";import{AssetPlayback as f}from"./adPlayer/AssetPlayback";import{BreakSequenceDriver as S}from"./adPlayer/BreakSequenceDriver";import{VariantSelector as B}from"./adPlayer/VariantSelector";import{AdPlayerEvents as E}from"./adPlayer/AdPlayerEvents";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 preloadedBreakId(){return this.state.preloadedBreakId}set preloadedBreakId(e){this.state.preloadedBreakId=e}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,l="parallel",d="overlay",h=a,u=s,b=!1,T=c){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.RESUME_GUARD_RELEASE_GRACE_MS=2e3,this.SINGLE_DECODER_RESUME_DELAY_MS=300,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.singleSurfaceDevice=!1,this.currentSelectedFormat=void 0,this.audioFocus=null,this.state=m(),this.state.playerContainer=r??null,this.clock=T,this.singleSurfaceDevice=b,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=l,this.insertionMode=d,this.pauseAdPresenter=new g({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 P(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 y(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,a,s)=>this.callbacks?.onAdStart(e,t,r,a,s),emitAdEnd:(e,t,r,a,s)=>this.callbacks?.onAdEnd(e,t,r,a,s),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 p({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=>{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 A({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.state.contentPositionAtBreakStart=e},gateContentForBreak:()=>this.gateContentForBreak(),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e)}),this.resumeCoordinator=new v(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.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),diagnose:(e,t,r)=>this.diagnose(e,t,r),log:(...e)=>this.log(...e),clearContentGate:()=>this.clearContentGate(),hide:()=>this.hide(),waitForLiveEdge:()=>this.resumeCoordinator.waitForLiveEdge(),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 f(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),beginGamPodTracking:e=>this.beginGamPodTracking(e),recordAdProgress:e=>this.adPlayerEvents.recordAdProgress(e),reportPhase:e=>this.reportPhase(e),armAdStartBudget:e=>this.armAdStartBudget(e),remainingAdStartBudgetMs:()=>this.remainingAdStartBudgetMs(),loadWithinBudget:e=>this.loadWithinBudget(e),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 S(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 E(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:()=>this.resumeCoordinator.maybePrepositionContentForResume(),maybeCatchUpContentForResume:e=>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}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)}beginGamPodTracking(e){this.gamPodBridge.beginGamPodTracking(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?d(this.currentBreak):void 0)}async playBreak(t,a,s){this.releaseContentHold(),this.rebindContentElementIfSwapped(),this.sharedElementPlayer.clearSharedRestoreWatchdog();const n=s?.effectiveDurationSec??null;this.effectiveBreakDurationSec=null!==n&&n>0?n:null;const l=this.effectiveBreakDurationSec??t.duration;if("shared-element"===this.effectiveInsertionMode())return void await this.sharedElementPlayer.playSharedElementBreak(t,a);if(!this.adPlayer)return void this.log("playBreak called before initialize()");const d=this.getVariant(t);if(!d)return void this.log("No valid variant found for break:",t.id);this.currentBreak=t,this.callbacks=a,this.isPlaying=!0,this.firstFrameGateActive=s?.firstFrameGate??!1,this.firstFrameGateShown=!1;const h=this.continueContentDuringBreakReason(d.format),u=r(t),c=this.shouldPauseContent(d.format)&&"ok"===h&&!u;c||u||this.state.continueRefusalReported||!this.shouldPauseContent(d.format)||(this.state.continueRefusalReported=!0,this.diagnose("DA-CONTINUE-PLAYOUT-REFUSED",`Content will be paused for breaks this session: ${h}`,{reason:h,format:d.format})),this.audioFocus=d.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(d.format)?(this.state.contentPositionAtBreakStart=this.contentPlayer.currentTime,this.resumeCoordinator.resetBreakResumeState(),c?(this.contentPaused=!1,this.resumeCoordinator.beginContinueContentPlayout()):(this.contentPaused=!0,this.gateContentForBreak())):this.contentPaused=!1,this.applyLayout(d),d.format===e.LSHAPE_CONTENT)return this.renderLshapeContentBackdrop(d),void(l&&l>0?(this.log("Starting duration timer:",l,"seconds"),this.durationTimer=setTimeout(()=>{this.log("Duration timer expired, ending break"),this.endBreak()},1e3*l)):this.endBreak());this.firstFrameGateActive||(this.show(),this.reapplyAdContainerLayout(d));if(0===this.getAssets(t).length)return this.log("No assets in break, ending immediately"),void this.endBreak();{const e=Math.max(0,l||0)+this.adBreakCutSafetyMarginSec;this.log("Starting break-cut timer:",e,"seconds"),this.durationTimer=setTimeout(()=>{this.log("Break-cut timer expired, ending break"),this.firstFrameRejector?this.onAdError(new Error("Break cut before first frame rendered")):this.sequencer&&this.currentBreak&&this.isPlaying?(this.callbacks?.onBreakCut?.(this.currentBreak),this.drive(this.sequencer.onOutcome({kind:"break-elapsed"}))):this.endBreak()},1e3*e)}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??d(e)}getVariant(e){return this.variantSelector.getVariant(e)}applyLayout(e){this.adStage.applyLayout(e)}restoreLayout(e){this.adStage.restoreLayout(e)}getAssets(e){return l(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),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),this.state.gamPodTracker&&this.emitGamPodSteps(this.state.gamPodTracker.finish()),this.resetGamPodTracking(),this.pushAssetParameters(void 0);const e=this.currentBreak,a=this.getVariant(e)?.format;let s=this.abortingBreak?null:this.resolveChainedSuccessor(e.id);if(s){const e=this.breakNothingToPlayReason(s);this.diagnoseUnknownVariantFormats(s),e&&(this.diagnose("DA-BREAK-NO-PLAYABLE-ASSET",`chained break ${s.id} has no playable variant (${e}); it will not begin.`,{breakId:s.id,reason:e}),this.callbacks?.onAdError(s,void 0,new Error(`Break ${s.id} has no playable variant (${e})`)),this.callbacks?.onChainedBreakSkipped?.(s),s=null)}if(s)this.advanceToChainedBreak(e,s);else{if(this.currentSelectedFormat=void 0,this.resumeCoordinator.endContinueContentPlayout(),this.restorePictureInPictureToContent(),this.isPlaying=!1,this.currentBreak=null,this.effectiveBreakDurationSec=null,this.preloadedBreakId=null,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(a),this.adPlayer?.pause(),this.state.sharedAdClaimActive)return this.sharedElementPlayer.detachSharedAdListeners(),this.sharedElementPlayer.restoreSharedElementContent(e),this.abortingBreak=!1,this.state.earlyReturnResumeOffsetSec=null,void this.callbacks?.onBreakEnd(e);if("single-decoder"===this.preloadMode&&this.adPlayer?.unload?.(),this.contentPaused&&r(e))this.contentPaused=!1,this.clearContentGate();else if(this.contentPaused){this.contentPaused=!1,this.clearContentGate(this.resumeHandoverInMotion);const r=this.state.earlyReturnResumeOffsetSec,a=this.breakTimebase===t.WALLCLOCK,s=()=>{a&&this.callbacks?.onContentReloading?.(!0),this.resumeCoordinator.applyResumeSeek(e,r),this.contentPlayer.play().catch(e=>{this.log("Content resume failed:",e)}).finally(()=>{a&&setTimeout(()=>this.callbacks?.onContentReloading?.(!1),this.RESUME_GUARD_RELEASE_GRACE_MS)})};"single-decoder"===this.preloadMode?setTimeout(s,this.SINGLE_DECODER_RESUME_DELAY_MS):s()}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),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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,this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),this.sequencer&&this.currentBreak?this.drive(this.sequencer.onOutcome({kind:"break-elapsed"})):this.endBreak())}stopActiveBreak(){this.isPlaying&&(this.log("Aborting active break on session end:",this.currentBreak?.id),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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){return this.preloader.loadWithinBudget(e)}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.adStage.destroy(),this.resumeCoordinator.cancelResumeLandedProbe(),this.resumeCoordinator.endResumeCatchup(),this.resumeCoordinator.endContinueContentPlayout(),this.state.resumePrepositionSettle&&(clearTimeout(this.state.resumePrepositionSettle),this.state.resumePrepositionSettle=null),this.sharedElementPlayer.clearSharedRestoreWatchdog(),this.releaseContentHold(),this.clearContentGate(),this.clearFirstFrame("Controller destroyed before first frame"),this.firstFrameGateActive=!1,this.firstFrameGateShown=!1,this.resetGamPodTracking(),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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.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,this.playerContainerCreatedBySDK)for(;this.playerContainer.firstChild;)this.container.appendChild(this.playerContainer.firstChild);else this.container.appendChild(this.playerContainer),this.playerContainer.style.cssText=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),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 l,resolveBreakFormat as d}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{AssetPlayback as S}from"./adPlayer/AssetPlayback";import{BreakSequenceDriver as B}from"./adPlayer/BreakSequenceDriver";import{VariantSelector as E}from"./adPlayer/VariantSelector";import{AdPlayerEvents as b}from"./adPlayer/AdPlayerEvents";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,l="parallel",d="overlay",h=s,u=a,T=!1,F=c){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.RESUME_GUARD_RELEASE_GRACE_MS=2e3,this.SINGLE_DECODER_RESUME_DELAY_MS=300,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.singleSurfaceDevice=!1,this.currentSelectedFormat=void 0,this.audioFocus=null,this.state=m(),this.state.playerContainer=r??null,this.clock=F,this.singleSurfaceDevice=T,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=l,this.insertionMode=d,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.state.contentPositionAtBreakStart=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.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),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 S(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),beginGamPodTracking:e=>this.beginGamPodTracking(e),recordAdProgress:e=>this.adPlayerEvents.recordAdProgress(e),reportPhase:e=>this.reportPhase(e),armAdStartBudget:e=>this.armAdStartBudget(e),remainingAdStartBudgetMs:()=>this.remainingAdStartBudgetMs(),loadWithinBudget:e=>this.loadWithinBudget(e),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 b(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:()=>this.resumeCoordinator.maybePrepositionContentForResume(),maybeCatchUpContentForResume:e=>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}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)}beginGamPodTracking(e){this.gamPodBridge.beginGamPodTracking(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?d(this.currentBreak):void 0)}async playBreak(t,s,a){if(this.state.preloadGeneration++,!this.sharedElementPlayer.beginSharedActivity())return;this.releaseContentHold(),this.rebindContentElementIfSwapped();const n=a?.effectiveDurationSec??null;this.effectiveBreakDurationSec=null!==n&&n>0?n:null;const l=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 d=this.getVariant(t);if(!d)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(d.format),u=r(t),c=this.shouldPauseContent(d.format)&&"ok"===h&&!u;c||u||this.state.continueRefusalReported||!this.shouldPauseContent(d.format)||(this.state.continueRefusalReported=!0,this.diagnose("DA-CONTINUE-PLAYOUT-REFUSED",`Content will be paused for breaks this session: ${h}`,{reason:h,format:d.format})),this.audioFocus=d.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(d.format)?(this.state.contentPositionAtBreakStart=this.contentPlayer.currentTime,this.resumeCoordinator.resetBreakResumeState(),c?(this.contentPaused=!1,this.resumeCoordinator.beginContinueContentPlayout()):(this.contentPaused=!0,this.gateContentForBreak())):this.contentPaused=!1,this.applyLayout(d),d.format===e.LSHAPE_CONTENT)return this.renderLshapeContentBackdrop(d),void(l&&l>0?(this.log("Starting duration timer:",l,"seconds"),this.durationTimer=setTimeout(()=>{this.log("Duration timer expired, ending break"),this.endBreak()},1e3*l)):this.endBreak());this.firstFrameGateActive||(this.show(),this.reapplyAdContainerLayout(d));if(0===this.getAssets(t).length)return this.log("No assets in break, ending immediately"),void this.endBreak();{const e=Math.max(0,l||0)+this.adBreakCutSafetyMarginSec;this.log("Starting break-cut timer:",e,"seconds"),this.durationTimer=setTimeout(()=>{this.log("Break-cut timer expired, ending break"),this.firstFrameRejector?this.onAdError(new Error("Break cut before first frame rendered")):this.sequencer&&this.currentBreak&&this.isPlaying?(this.callbacks?.onBreakCut?.(this.currentBreak),this.drive(this.sequencer.onOutcome({kind:"break-elapsed"}))):this.endBreak()},1e3*e)}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??d(e)}getVariant(e){return this.variantSelector.getVariant(e)}applyLayout(e){this.adStage.applyLayout(e)}restoreLayout(e){this.adStage.restoreLayout(e)}getAssets(e){return l(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),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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 Error(`Break ${a.id} has no playable variant (${e})`)),this.callbacks?.onChainedBreakSkipped?.(a),a=null)}if(a)this.advanceToChainedBreak(e,a);else{if(this.currentSelectedFormat=void 0,this.resumeCoordinator.endContinueContentPlayout(),this.restorePictureInPictureToContent(),this.isPlaying=!1,this.currentBreak=null,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)}if("single-decoder"===this.preloadMode&&this.adPlayer?.unload?.(),this.contentPaused&&r(e))this.contentPaused=!1,this.clearContentGate();else if(this.contentPaused){this.contentPaused=!1,this.clearContentGate(this.resumeHandoverInMotion);const r=this.state.earlyReturnResumeOffsetSec,s=this.breakTimebase===t.WALLCLOCK,a=()=>{s&&this.callbacks?.onContentReloading?.(!0),this.resumeCoordinator.applyResumeSeek(e,r),this.contentPlayer.play().catch(e=>{this.log("Content resume failed:",e)}).finally(()=>{s&&setTimeout(()=>this.callbacks?.onContentReloading?.(!1),this.RESUME_GUARD_RELEASE_GRACE_MS)})};"single-decoder"===this.preloadMode?setTimeout(a,this.SINGLE_DECODER_RESUME_DELAY_MS):a()}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),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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,this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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){return this.preloader.loadWithinBudget(e)}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(g(this.state),this.sharedElementPlayer.beginSharedActivity()){if(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(),this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null),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.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,this.playerContainerCreatedBySDK)for(;this.playerContainer.firstChild;)this.container.appendChild(this.playerContainer.firstChild);else this.container.appendChild(this.playerContainer),this.playerContainer.style.cssText=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),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{applyAssetParameterMacros as e,omitBreakScopedParameters as t}from"./assetParameterMacros";import{buildAssetParameterMacroTable as a}from"./assetParameterMacroTable";import{resolveAssetParameters as s}from"./resolveAssetParameters";import{AssetType as r,MediaType as i,BreakFormat as o}from"../types/BreakManifest";import{GamStreamManager as n}from"./GamStreamManager";import{resolveBreakFormat as m}from"./AdBreakSequencer";import{buildStitcherMasterUrl as d}from"./StitcherUrlBuilder";export class SsaiController{constructor(e,t,a){this.player=e,this.options=t,this.callbacks=a,this.gamStreamManager=null,this.breakCounter=0,this.adIndexInBreak=0,this.currentBreak=null,this.currentAsset=null,this.customerMacros={},this.onTimedMetadata=e=>{if(!e)return;const t=e;this.gamStreamManager?.processTimedMetadata(t)}}async start(e){const t=this.player.videoElement;if(!t)throw new Error("SSAI mode requires a content PlayerAdapter that exposes a videoElement (for IMA DAI).");if(!e.customAssetKey)throw new Error("SSAI mode requires a customAssetKey in startSession().");this.sessionConfigParameters=e.assetParameters,this.updatedParameters=void 0,this.manifestParameters=void 0,this.customerMacros={...e.assetParameterMacros};const a=new n(t,void 0,this.options.debug);a.setCallbacks(this.buildGamCallbacks()),this.gamStreamManager=a,await a.initialize({networkCode:this.options.ssai.networkCode,customAssetKey:e.customAssetKey,adTagParameters:this.resolveAdTagParameters(),streamActivityMonitorId:this.options.gam.streamActivityMonitorId});const s=a.getStreamId();if(!s)throw new Error("SSAI mode: IMA DAI session did not return a stream id.");const r=d({stitcherUrl:e.stitcherUrl,streamId:s,maxBitrate:this.options.maxBitrate});this.callbacks.log("SSAI stitched master URL:",r),this.player.on("timedmetadata",this.onTimedMetadata),await this.player.load(r),this.options.autoplay&&await this.player.play()}async startSteered(e,t,a){const s=this.player.videoElement;if(!s)throw new Error("SSAI mode requires a content PlayerAdapter that exposes a videoElement (for IMA DAI).");this.sessionConfigParameters=t,this.updatedParameters=void 0,this.manifestParameters=e.assetParameters,this.customerMacros={...a};const r=new n(s,void 0,this.options.debug);r.setCallbacks(this.buildGamCallbacks()),this.gamStreamManager=r;const i=await r.initializeLiveStream({assetKey:e.assetKey,networkCode:e.networkCode,adTagParameters:this.resolveAdTagParameters(),streamActivityMonitorId:this.options.gam.streamActivityMonitorId});this.callbacks.log("SSAI full-service DAI stream URL:",i),this.player.on("timedmetadata",this.onTimedMetadata),await this.player.load(i),this.options.autoplay&&await this.player.play()}resolveAdTagParameters(){const r=s(this.sessionConfigParameters,this.updatedParameters,this.manifestParameters,void 0),i=e(t(r),a({customerMacros:this.customerMacros,element:this.player.videoElement??null,breakDurationSec:void 0}));for(const{key:e,macro:t}of i.unresolved)this.callbacks.diagnose("DA-ASSET-MACRO-UNKNOWN",`Asset parameter '${e}' sent with literal macro '${t}': the macro has no value.`,{key:e,macro:t});return i.params}updateAssetParameters(e){this.updatedParameters=e,this.gamStreamManager?.replaceAdTagParameters(this.resolveAdTagParameters()??{})}updateAssetParameterMacros(e){const t={...this.customerMacros};for(const[a,s]of Object.entries(e))
|
|
1
|
+
import{applyAssetParameterMacros as e,omitBreakScopedParameters as t}from"./assetParameterMacros";import{buildAssetParameterMacroTable as a}from"./assetParameterMacroTable";import{resolveAssetParameters as s}from"./resolveAssetParameters";import{AssetType as r,MediaType as i,BreakFormat as o}from"../types/BreakManifest";import{GamStreamManager as n}from"./GamStreamManager";import{resolveBreakFormat as m}from"./AdBreakSequencer";import{buildStitcherMasterUrl as d}from"./StitcherUrlBuilder";export class SsaiController{constructor(e,t,a){this.player=e,this.options=t,this.callbacks=a,this.gamStreamManager=null,this.breakCounter=0,this.adIndexInBreak=0,this.currentBreak=null,this.currentAsset=null,this.customerMacros={},this.onTimedMetadata=e=>{if(!e)return;const t=e;this.gamStreamManager?.processTimedMetadata(t)}}async start(e){const t=this.player.videoElement;if(!t)throw new Error("SSAI mode requires a content PlayerAdapter that exposes a videoElement (for IMA DAI).");if(!e.customAssetKey)throw new Error("SSAI mode requires a customAssetKey in startSession().");this.sessionConfigParameters=e.assetParameters,this.updatedParameters=void 0,this.manifestParameters=void 0,this.customerMacros={...e.assetParameterMacros};const a=new n(t,void 0,this.options.debug);a.setCallbacks(this.buildGamCallbacks()),this.gamStreamManager=a,await a.initialize({networkCode:this.options.ssai.networkCode,customAssetKey:e.customAssetKey,adTagParameters:this.resolveAdTagParameters(),streamActivityMonitorId:this.options.gam.streamActivityMonitorId});const s=a.getStreamId();if(!s)throw new Error("SSAI mode: IMA DAI session did not return a stream id.");const r=d({stitcherUrl:e.stitcherUrl,streamId:s,maxBitrate:this.options.maxBitrate});this.callbacks.log("SSAI stitched master URL:",r),this.player.on("timedmetadata",this.onTimedMetadata),await this.player.load(r),this.options.autoplay&&await this.player.play()}async startSteered(e,t,a){const s=this.player.videoElement;if(!s)throw new Error("SSAI mode requires a content PlayerAdapter that exposes a videoElement (for IMA DAI).");this.sessionConfigParameters=t,this.updatedParameters=void 0,this.manifestParameters=e.assetParameters,this.customerMacros={...a};const r=new n(s,void 0,this.options.debug);r.setCallbacks(this.buildGamCallbacks()),this.gamStreamManager=r;const i=await r.initializeLiveStream({assetKey:e.assetKey,networkCode:e.networkCode,adTagParameters:this.resolveAdTagParameters(),streamActivityMonitorId:this.options.gam.streamActivityMonitorId});this.callbacks.log("SSAI full-service DAI stream URL:",i),this.player.on("timedmetadata",this.onTimedMetadata),await this.player.load(i),this.options.autoplay&&await this.player.play()}resolveAdTagParameters(){const r=s(this.sessionConfigParameters,this.updatedParameters,this.manifestParameters,void 0),i=e(t(r),a({customerMacros:this.customerMacros,element:this.player.videoElement??null,breakDurationSec:void 0}),"gam");for(const{key:e,macro:t}of i.unresolved)this.callbacks.diagnose("DA-ASSET-MACRO-UNKNOWN",`Asset parameter '${e}' sent with literal macro '${t}': the macro has no value.`,{key:e,macro:t});for(const{key:e,macro:t,pair:a}of i.omitted)this.callbacks.diagnose("DA-ASSET-PARAMETER-OMITTED",`Asset parameter '${e}' not sent: macro '${t}' is empty.`,{key:e,macro:t,...void 0!==a?{pair:a}:{}});return i.params}updateAssetParameters(e){this.updatedParameters=e,this.gamStreamManager?.replaceAdTagParameters(this.resolveAdTagParameters()??{})}updateAssetParameterMacros(e){const t={...this.customerMacros};for(const[a,s]of Object.entries(e))void 0===s?delete t[a]:t[a]=s;this.customerMacros=t,this.callbacks.diagnose("DA-ASSET-PARAMETERS-UPDATED","Asset parameter macros updated.",{source:"macros",keys:Object.keys(e).sort()}),this.gamStreamManager?.replaceAdTagParameters(this.resolveAdTagParameters()??{})}get sessionAssetParameterMacros(){return{...this.customerMacros}}setManifestAssetParameters(e){(function(e,t){e&&0===Object.keys(e).length&&(e=void 0);t&&0===Object.keys(t).length&&(t=void 0);if(e===t)return!0;if(!e||!t)return!1;const a=Object.keys(e);return a.length===Object.keys(t).length&&a.every(a=>e[a]===t[a])})(this.manifestParameters,e)||(this.manifestParameters=e,this.gamStreamManager&&(this.gamStreamManager.replaceAdTagParameters(this.resolveAdTagParameters()??{}),this.callbacks.diagnose("DA-ASSET-PARAMETERS-UPDATED","Manifest asset parameters changed; IMA targeting updated.",{source:"manifest",keys:Object.keys(e??{}).sort()})))}stop(){this.player.off("timedmetadata",this.onTimedMetadata),this.gamStreamManager?.destroy(),this.gamStreamManager=null,this.sessionConfigParameters=void 0,this.updatedParameters=void 0,this.manifestParameters=void 0,this.customerMacros={},this.currentBreak=null,this.currentAsset=null,this.breakCounter=0,this.adIndexInBreak=0}buildGamCallbacks(){return{onAdBreakStarted:()=>{this.breakCounter+=1,this.adIndexInBreak=0,this.currentBreak=this.synthBreak(`ssai-break-${this.breakCounter}`),this.callbacks.emit("adbreakbegin",{type:"adbreakbegin",timestamp:Date.now(),break:this.currentBreak,format:m(this.currentBreak),elapsedSec:0,remainingSec:this.currentBreak.duration})},onAdStarted:e=>{const t=this.ensureBreak(),a=this.adIndexInBreak;this.adIndexInBreak+=1,this.currentAsset=this.synthAsset(`${t.id}-ad-${this.adIndexInBreak}`),this.callbacks.emit("adbegin",{type:"adbegin",timestamp:Date.now(),break:t,format:m(t),asset:this.currentAsset,adIndex:a,totalAds:0,...void 0!==e?.adPosition&&Number.isInteger(e.adPosition)&&e.adPosition>=1?{podPosition:e.adPosition}:{}})},onAdFirstQuartile:()=>this.emitQuartile("adfirstquartile"),onAdMidpoint:()=>this.emitQuartile("admidpoint"),onAdThirdQuartile:()=>this.emitQuartile("adthirdquartile"),onAdComplete:()=>{const e=this.ensureBreak(),t=this.currentAsset??this.synthAsset(`${e.id}-ad`);this.callbacks.emit("adend",{type:"adend",timestamp:Date.now(),break:e,format:m(e),asset:t,adIndex:Math.max(0,this.adIndexInBreak-1),totalAds:0}),this.currentAsset=null},onAdBreakEnded:()=>{const e=this.ensureBreak();this.callbacks.emit("adbreakend",{type:"adbreakend",timestamp:Date.now(),break:e,format:m(e)}),this.currentBreak=null,this.currentAsset=null},onError:e=>{this.callbacks.diagnose("DA-SSAI-IMA-ERROR",e),this.callbacks.emit("aderror",{type:"aderror",timestamp:Date.now(),source:"ad",...this.currentBreak?{break:this.currentBreak,format:m(this.currentBreak)}:{},...this.currentAsset?{asset:this.currentAsset}:{},error:new Error(e)})}}}emitQuartile(e){const t=this.ensureBreak(),a=this.currentAsset??this.synthAsset(`${t.id}-ad`);this.callbacks.emit(e,{type:e,timestamp:Date.now(),break:t,format:m(t),asset:a})}ensureBreak(){return this.currentBreak||(this.breakCounter+=1,this.currentBreak=this.synthBreak(`ssai-break-${this.breakCounter}`)),this.currentBreak}synthBreak(e){return{id:e,start:this.player.currentTime,duration:0,variant:{format:o.SINGLE,assets:[]}}}synthAsset(e){return{id:e,type:r.STATIC,mediaType:i.VIDEO,uri:""}}}
|
|
@@ -85,7 +85,13 @@ export interface AdPlayerState {
|
|
|
85
85
|
resumeLandedProbe: (() => void) | null;
|
|
86
86
|
adSecondsPlayedThisBreak: number;
|
|
87
87
|
currentAssetElapsedSec: number;
|
|
88
|
-
|
|
88
|
+
preparedMedia: {
|
|
89
|
+
breakId: string;
|
|
90
|
+
assetId: string;
|
|
91
|
+
uri: string;
|
|
92
|
+
player: PlayerAdapter;
|
|
93
|
+
} | null;
|
|
94
|
+
preloadGeneration: number;
|
|
89
95
|
firstFrameGateActive: boolean;
|
|
90
96
|
firstFrameGateShown: boolean;
|
|
91
97
|
firstFrameResolver: (() => void) | null;
|
|
@@ -95,4 +101,5 @@ export interface AdPlayerState {
|
|
|
95
101
|
adStartBudgetMs: number;
|
|
96
102
|
vastAdManager: VastAdManager | null;
|
|
97
103
|
}
|
|
104
|
+
export declare function invalidateMediaPreload(state: AdPlayerState): number;
|
|
98
105
|
export declare function createAdPlayerState(): AdPlayerState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createAdPlayerState(){return{currentBreak:null,currentAsset:null,isPlaying:!1,contentPaused:!1,callbacks:null,durationTimer:null,effectiveBreakDurationSec:null,adInsertionType:void 0,breakTimebase:null,adBreakCutSafetyMarginSec:0,detectedDeviceType:void 0,sessionAssetParameters:void 0,updatedAssetParameters:void 0,manifestAssetParameters:void 0,sessionAssetParameterMacros:{},pushedAssetParameters:null,gamStreamManager:null,gamPodMode:"none",gamPodTracker:null,gamPodAsset:null,earlyGamPodAdStart:null,withheldPodAdBegin:null,gamConfig:void 0,gamInitPromise:null,currentGamIdentity:void 0,playerContainer:null,stage:null,contentVideoElement:null,adContainer:null,adMediaContainer:null,adPlayer:null,companionElement:null,overlayImageEl:null,isContentFullscreen:!1,trackedContentVideo:null,fullscreenEnterHandler:null,fullscreenExitHandler:null,contentPictureInPicture:!1,pipTransferredToAd:!1,pipAdoptedForBreak:!1,sharedAdClaimActive:!1,savedContentSrc:null,savedContentTime:0,savedContentLive:!1,savedContentEdgeDistance:null,earlyReturnResumeOffsetSec:null,contentPositionAtBreakStart:0,resumePrepositionedTo:null,resumePrepositionSettle:null,resumeCatchupActive:!1,lastResumeAlignRemainingSec:Number.POSITIVE_INFINITY,resumeAlignBlockedDiagnosed:!1,lastResumeSafeEnd:Number.NEGATIVE_INFINITY,resumeSawSeekDone:!1,resumeBestSawMarginSec:Number.NEGATIVE_INFINITY,resumeAlignTicks:0,resumeSawSteps:[],continueContentDuringBreak:!1,continueQualityOverrideApplied:!1,continueContentDuringBreakActive:!1,keepContentPlayingHandler:null,continuePlayoutStartWallMs:0,continuePlayoutTicker:null,continueRateWritten:null,continueRateWrittenAtMs:0,continueRateHonoured:!0,continueMaxAbsDriftSec:0,continueCorrections:[],continueDriftUnrecoverable:!1,continueRefusalReported:!1,contentMutedBeforeCatchup:null,resumeAlignCorrectionsMs:[],resumeLandedProbe:null,adSecondsPlayedThisBreak:0,currentAssetElapsedSec:0,
|
|
1
|
+
export function invalidateMediaPreload(e){return e.preparedMedia=null,++e.preloadGeneration}export function createAdPlayerState(){return{currentBreak:null,currentAsset:null,isPlaying:!1,contentPaused:!1,callbacks:null,durationTimer:null,effectiveBreakDurationSec:null,adInsertionType:void 0,breakTimebase:null,adBreakCutSafetyMarginSec:0,detectedDeviceType:void 0,sessionAssetParameters:void 0,updatedAssetParameters:void 0,manifestAssetParameters:void 0,sessionAssetParameterMacros:{},pushedAssetParameters:null,gamStreamManager:null,gamPodMode:"none",gamPodTracker:null,gamPodAsset:null,earlyGamPodAdStart:null,withheldPodAdBegin:null,gamConfig:void 0,gamInitPromise:null,currentGamIdentity:void 0,playerContainer:null,stage:null,contentVideoElement:null,adContainer:null,adMediaContainer:null,adPlayer:null,companionElement:null,overlayImageEl:null,isContentFullscreen:!1,trackedContentVideo:null,fullscreenEnterHandler:null,fullscreenExitHandler:null,contentPictureInPicture:!1,pipTransferredToAd:!1,pipAdoptedForBreak:!1,sharedAdClaimActive:!1,savedContentSrc:null,savedContentTime:0,savedContentLive:!1,savedContentEdgeDistance:null,earlyReturnResumeOffsetSec:null,contentPositionAtBreakStart:0,resumePrepositionedTo:null,resumePrepositionSettle:null,resumeCatchupActive:!1,lastResumeAlignRemainingSec:Number.POSITIVE_INFINITY,resumeAlignBlockedDiagnosed:!1,lastResumeSafeEnd:Number.NEGATIVE_INFINITY,resumeSawSeekDone:!1,resumeBestSawMarginSec:Number.NEGATIVE_INFINITY,resumeAlignTicks:0,resumeSawSteps:[],continueContentDuringBreak:!1,continueQualityOverrideApplied:!1,continueContentDuringBreakActive:!1,keepContentPlayingHandler:null,continuePlayoutStartWallMs:0,continuePlayoutTicker:null,continueRateWritten:null,continueRateWrittenAtMs:0,continueRateHonoured:!0,continueMaxAbsDriftSec:0,continueCorrections:[],continueDriftUnrecoverable:!1,continueRefusalReported:!1,contentMutedBeforeCatchup:null,resumeAlignCorrectionsMs:[],resumeLandedProbe:null,adSecondsPlayedThisBreak:0,currentAssetElapsedSec:0,preparedMedia:null,preloadGeneration:0,firstFrameGateActive:!1,firstFrameGateShown:!1,firstFrameResolver:null,firstFrameRejector:null,firstFrameTimeout:null,adStartDeadlineMs:null,adStartBudgetMs:0,vastAdManager:null}}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PlayerAdapter } from '../../interfaces/PlayerAdapter';
|
|
2
2
|
import { Asset, Break, BreakVariant, StaticAsset, VastAsset } from '../../types/BreakManifest';
|
|
3
3
|
import type { ResolvedPreloadMode } from '../detectPreloadMode';
|
|
4
|
-
import type
|
|
4
|
+
import { type AdPlayerState } from './AdPlayerState';
|
|
5
5
|
import type { Clock } from '../BreakScheduler';
|
|
6
6
|
export interface AdPreloaderDeps {
|
|
7
7
|
state: AdPlayerState;
|
|
@@ -38,6 +38,7 @@ export declare class AdPreloader {
|
|
|
38
38
|
private classifyCreative;
|
|
39
39
|
private diagnosePreloadPath;
|
|
40
40
|
preload(breakInfo: Break): Promise<void>;
|
|
41
|
+
private ownsPreload;
|
|
41
42
|
preloadVastAsset(asset: VastAsset, breakInfo: Break): Promise<void>;
|
|
42
43
|
preloadChainedSuccessor(currentBreakId: string): void;
|
|
43
44
|
clearWarmedBreaks(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AssetType as e,BreakFormat as t,MediaType as s,Vendor as a,isVastAsset as i,isVendorAsset as r}from"../../types/BreakManifest";import{AUX_FETCH_TIMEOUT_MS as d,fetchWithTimeout as o}from"../fetchWithTimeout";import{resolveVastAdmission as n}from"../resolveVastAdmission";import{isImaCsaiSdkAvailable as p,VastAdManager as l}from"../VastAdManager";export class AdPreloader{constructor(e){this.deps=e,this.warmedBreakIds=new Set}classifyCreative(e){const t=(e.split(/[?#]/)[0]??"").toLowerCase();return t.endsWith(".m3u8")||t.endsWith(".mpd")?"stream":/\.(mp4|m4v|m4a|webm|mov|ogg|ogv|mp3)$/.test(t)?"progressive":"unknown"}diagnosePreloadPath(e,t,s){const a=this.classifyCreative(t);this.deps.diagnose("DA-PRELOAD-PATH",`Ad preload path: ${s} (${a} creative)`,{breakId:e,adPreload:this.deps.preloadMode,path:s,creative:a})}async preload(a){if(this.deps.isPlaying())return void this.deps.log("Preload skipped: ad already playing");if("none"===this.deps.preloadMode){const t=this.deps.getAssets(a)[0],s=t&&t.type===e.STATIC?this.deps.resolveUri(t.uri)??"":"";return this.diagnosePreloadPath(a.id,s,"none"),void this.deps.log('Preload skipped: adPreload "none"')}if("shared-element"===this.deps.effectiveInsertionMode()){const s=this.deps.getVariant(a);if(s&&s.format!==t.LSHAPE_CONTENT){const t=this.deps.getAssets(a)[0];if(t&&t.type===e.STATIC){const e=this.deps.resolveUri(t.uri);e&&await this.warmCache([e])}}return}const
|
|
1
|
+
import{AssetType as e,BreakFormat as t,MediaType as s,Vendor as a,isVastAsset as i,isVendorAsset as r}from"../../types/BreakManifest";import{AUX_FETCH_TIMEOUT_MS as d,fetchWithTimeout as o}from"../fetchWithTimeout";import{resolveVastAdmission as n}from"../resolveVastAdmission";import{isImaCsaiSdkAvailable as p,VastAdManager as l}from"../VastAdManager";import{invalidateMediaPreload as h}from"./AdPlayerState";export class AdPreloader{constructor(e){this.deps=e,this.warmedBreakIds=new Set}classifyCreative(e){const t=(e.split(/[?#]/)[0]??"").toLowerCase();return t.endsWith(".m3u8")||t.endsWith(".mpd")?"stream":/\.(mp4|m4v|m4a|webm|mov|ogg|ogv|mp3)$/.test(t)?"progressive":"unknown"}diagnosePreloadPath(e,t,s){const a=this.classifyCreative(t);this.deps.diagnose("DA-PRELOAD-PATH",`Ad preload path: ${s} (${a} creative)`,{breakId:e,adPreload:this.deps.preloadMode,path:s,creative:a})}async preload(a){if(this.deps.isPlaying())return void this.deps.log("Preload skipped: ad already playing");const r=h(this.deps.state),d=this.deps.getAdPlayer();if("none"===this.deps.preloadMode){const t=this.deps.getAssets(a)[0],s=t&&t.type===e.STATIC?this.deps.resolveUri(t.uri)??"":"";return this.diagnosePreloadPath(a.id,s,"none"),void this.deps.log('Preload skipped: adPreload "none"')}if("shared-element"===this.deps.effectiveInsertionMode()){const s=this.deps.getVariant(a);if(s&&s.format!==t.LSHAPE_CONTENT){const t=this.deps.getAssets(a)[0];if(t&&t.type===e.STATIC){const e=this.deps.resolveUri(t.uri);e&&await this.warmCache([e])}}return}const o=this.deps.getAssets(a);if(0===o.length)return void this.deps.log("No assets to preload");this.preloadCompanion(a);const n=this.deps.getVariant(a);if(n?.format===t.LSHAPE_CONTENT)return;if(o[0].mediaType===s.IMAGE){const e=await this.deps.resolveAssetUri(o[0],a.duration);if(e){(new Image).src=e,this.deps.log("Preloading overlay image:",e)}return}if(i(o[0]))return void await this.preloadVastAsset(o[0],a);const p=await this.deps.resolveAssetUri(o[0],a.duration);if(p){if(d&&this.ownsPreload(r,d))if("single-decoder"!==this.deps.preloadMode){this.deps.log("Preloading ad (parallel):",p),this.diagnosePreloadPath(a.id,p,"parallel");try{if(await d.load(p),!this.ownsPreload(r,d))return;this.deps.state.preparedMedia={breakId:a.id,assetId:o[0].id,uri:p,player:d},this.deps.log("Preload complete for break:",a.id)}catch(e){this.deps.log("Preload failed (will load on demand):",e)}}else{if(this.deps.log("Preloading ad (single-decoder, detached):",p),this.diagnosePreloadPath(a.id,p,"single-decoder"),await this.warmCache([p]),!this.ownsPreload(r,d))return;try{await(d.preload?.(p))}catch(e){this.deps.log("Detached prefetch failed (will load on demand):",e)}}}else this.deps.log("No valid URI for preload")}ownsPreload(e,t){return e===this.deps.state.preloadGeneration&&!this.deps.isPlaying()&&t===this.deps.getAdPlayer()}async preloadVastAsset(e,s){const a=this.deps.getVariant(s),i=a?.format??t.SINGLE;if(!n({format:i,ssai:!1}).admitted)return void this.deps.log("VAST preload skipped: format not supported",i);if(!p())return void this.deps.log("VAST preload skipped: IMA client-side SDK unavailable");const r=this.deps.getAdPlayer(),d=this.deps.getAdContainer();if(!r||!d)return void this.deps.log("VAST preload skipped: ad player not initialized");const o=r.videoElement;if(!o)return void this.deps.log("VAST preload skipped: no ad video element");const h=this.deps.buildVastTagUrl(e,s);if(h){this.deps.state.vastAdManager||(this.deps.state.vastAdManager=new l(d,o,this.deps.debug)),this.deps.log("Preloading VAST asset via IMA CSAI:",h);try{await this.deps.state.vastAdManager.preloadVast(h,{muted:r.muted}),this.deps.log("VAST preload complete for break:",s.id)}catch(t){const a=t instanceof Error?t:new Error(String(t));this.deps.log("VAST preload failed (will load on demand):",a.message),this.deps.diagnose("DA-PRELOAD-FAILED",a.message,{breakId:s.id,assetId:e.id})}}else this.deps.log("No valid VAST tag URL for preload")}preloadChainedSuccessor(e){const t=this.deps.resolveChainedSuccessor(e);t&&this.preloadNext(t)}clearWarmedBreaks(){this.warmedBreakIds.clear()}async preloadNext(s){if(this.warmedBreakIds.has(s.id))return;this.preloadCompanion(s);const a=this.deps.getVariant(s);if(!a||a.format===t.LSHAPE_CONTENT)return;const i=this.deps.getAssets(s)[0];if(!i||i.type!==e.STATIC)return void this.deps.log("Chained successor first asset not static; skipping media warm:",s.id);const r=this.deps.resolveUri(i.uri);if(r){this.warmedBreakIds.add(s.id),this.deps.log("Warming chained successor media:",s.id,r),await this.warmCache([r]);try{await(this.deps.getAdPlayer()?.preload?.(r))}catch(e){this.deps.log("Chained prefetch failed (will load on demand):",e)}}}revealFirstFrame(){if(!this.deps.state.firstFrameGateActive||this.deps.state.firstFrameGateShown)return;const e=this.deps.getCurrentBreak();if(!e)return;this.deps.state.firstFrameGateShown=!0,this.deps.show();const t=this.deps.getVariant(e);t&&this.deps.reapplyAdContainerLayout(t),this.deps.onBreakVisible(e)}armAdStartBudget(e){const t=1e3*((this.deps.state.effectiveBreakDurationSec??this.deps.state.currentBreak?.duration??0)+this.deps.state.adBreakCutSafetyMarginSec),s=r(e)&&e.vendor===a.GAM?this.deps.gamPodAdStartBudgetMs:this.deps.adStartBudgetMs,i=Math.max(Math.min(t-100,s),this.deps.minAdStartBudgetMs);this.deps.state.adStartBudgetMs=i,this.deps.state.adStartDeadlineMs=this.deps.clock.now()+i}remainingAdStartBudgetMs(){return Math.max(0,(this.deps.state.adStartDeadlineMs??this.deps.clock.now())-this.deps.clock.now())}loadWithinBudget(e){const t=this.deps.state.preloadGeneration;return new Promise((s,a)=>{const i=setTimeout(()=>{t===this.deps.state.preloadGeneration&&this.deps.onAdError(new Error("Ad load timeout")),s(!1)},this.remainingAdStartBudgetMs());e.then(()=>{clearTimeout(i),s(!0)},e=>{clearTimeout(i),a(e instanceof Error?e:new Error(String(e)))})})}async waitForFirstFrame(){return new Promise((e,t)=>{this.deps.state.firstFrameResolver=()=>{this.clearFirstFrameResolver(),e()},this.deps.state.firstFrameRejector=e=>{this.clearFirstFrameResolver(),t(e)},this.deps.state.firstFrameTimeout=setTimeout(()=>{this.deps.onAdError(new Error("First frame timeout"))},this.remainingAdStartBudgetMs())})}clearFirstFrame(e="Break ended before first frame"){if(this.deps.state.adStartDeadlineMs=null,this.deps.state.adStartBudgetMs=0,this.deps.state.firstFrameTimeout&&(clearTimeout(this.deps.state.firstFrameTimeout),this.deps.state.firstFrameTimeout=null),this.deps.state.firstFrameRejector){const t=this.deps.state.firstFrameRejector;this.deps.state.firstFrameResolver=null,this.deps.state.firstFrameRejector=null,t(new Error(e))}}clearFirstFrameResolver(){this.deps.state.adStartDeadlineMs=null,this.deps.state.adStartBudgetMs=0,this.deps.state.firstFrameTimeout&&(clearTimeout(this.deps.state.firstFrameTimeout),this.deps.state.firstFrameTimeout=null),this.deps.state.firstFrameResolver=null,this.deps.state.firstFrameRejector=null}preloadCompanion(s){const a=this.deps.getCompanionVariant(s);if(!a)return;if(a.format===t.LSHAPE_CONTENT){const t=a.assets[0];if(!t||t.type!==e.STATIC)return;const s=this.deps.resolveUri(t.uri);if(!s)return;return(new Image).src=s,void this.deps.log("Preloading lshape_content backdrop:",s)}if(a.format!==t.DOUBLE&&a.format!==t.LSHAPE_AD)return;const i=a.assets[0]?.companion;if(!i||i.type!==e.STATIC)return;const r=this.deps.resolveUri(i.uri);if(!r)return;(new Image).src=r,this.deps.log("Preloading companion:",r)}async warmCache(e){"function"==typeof fetch&&await Promise.allSettled(e.map(e=>o(e,{mode:"no-cors"},d).catch(()=>{})))}}
|
|
@@ -27,7 +27,8 @@ export declare class AssetParameterResolver {
|
|
|
27
27
|
/**
|
|
28
28
|
* Substitute the `$` macros in an effective (already layered) parameter map.
|
|
29
29
|
* Precedence per macro name: session macros, then the built-ins; a customer
|
|
30
|
-
* macro
|
|
30
|
+
* macro returning `undefined` falls through to the built-in, while `null`
|
|
31
|
+
* marks the parameter empty.
|
|
31
32
|
* Every unresolved macro is sent literally and reported as
|
|
32
33
|
* `DA-ASSET-MACRO-UNKNOWN`.
|
|
33
34
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isVendorAsset as e}from"../../types/BreakManifest";import{appendQueryParameters as s,applyAssetParameterMacros as t,omitBreakScopedParameters as a}from"../assetParameterMacros";import{buildAssetParameterMacroTable as r}from"../assetParameterMacroTable";import{resolveAssetParameters as i}from"../resolveAssetParameters";import{detectDeviceType as o}from"../detectDeviceType";import{resolveTargetedUri as n}from"../resolveTargetedUri";function
|
|
1
|
+
import{isVendorAsset as e}from"../../types/BreakManifest";import{appendQueryParameters as s,applyAssetParameterMacros as t,omitBreakScopedParameters as a}from"../assetParameterMacros";import{buildAssetParameterMacroTable as r}from"../assetParameterMacroTable";import{resolveAssetParameters as i}from"../resolveAssetParameters";import{detectDeviceType as o}from"../detectDeviceType";import{resolveTargetedUri as n}from"../resolveTargetedUri";function m(e,s){if(e&&0===Object.keys(e).length&&(e=void 0),s&&0===Object.keys(s).length&&(s=void 0),e===s)return!0;if(!e||!s)return!1;const t=Object.keys(e);return t.length===Object.keys(s).length&&t.every(t=>e[t]===s[t])}export class AssetParameterResolver{constructor(e,s){this.state=e,this.deps=s}setSessionAssetParameters(e){this.state.sessionAssetParameters=e}setManifestAssetParameters(s){if(m(this.state.manifestAssetParameters,s))return;if(this.state.manifestAssetParameters=s,!this.deps.getGamStreamManager()?.isInitialized())return void this.deps.log("Manifest asset parameters stored before GAM initialization");const t=this.state.gamPodAsset;this.pushAssetParameters(t&&e(t)?t.assetParameters:void 0,t?.id),this.deps.diagnose("DA-ASSET-PARAMETERS-UPDATED","Manifest asset parameters changed; IMA targeting updated.",{source:"manifest",keys:Object.keys(s??{}).sort()})}updateAssetParameters(e){this.state.updatedAssetParameters=e,this.deps.getGamStreamManager()?.isInitialized()?this.pushAssetParameters(void 0):this.deps.log("updateAssetParameters: GAM not initialized, stored for VAST only")}updateAssetParameterMacros(e){const s={...this.state.sessionAssetParameterMacros};for(const[t,a]of Object.entries(e))void 0===a?delete s[t]:s[t]=a;this.state.sessionAssetParameterMacros=s,this.deps.diagnose("DA-ASSET-PARAMETERS-UPDATED","Asset parameter macros updated.",{source:"macros",keys:Object.keys(e).sort()}),this.deps.getGamStreamManager()?.isInitialized()?this.pushAssetParameters(void 0):this.deps.log("updateAssetParameterMacros: GAM not initialized, stored for VAST only")}setSessionAssetParameterMacros(e){this.state.sessionAssetParameterMacros={...e}}getSessionAssetParameterMacros(){return{...this.state.sessionAssetParameterMacros}}resolveAssetParameterMacros(e,s,i,o,n){const m="session"===i?a(e):e,d=t(m,r({customerMacros:this.state.sessionAssetParameterMacros,element:this.deps.container,breakDurationSec:"session"===i?void 0:s}),o);for(const{key:e,macro:s}of d.unresolved)this.deps.diagnose("DA-ASSET-MACRO-UNKNOWN",`Asset parameter '${e}' sent with literal macro '${s}': the macro has no value.`,{...n,key:e,macro:s});for(const{key:e,macro:s,pair:t}of d.omitted)this.deps.diagnose("DA-ASSET-PARAMETER-OMITTED",`Asset parameter '${e}' not sent: macro '${s}' is empty.`,{...n,key:e,macro:s,...void 0!==t?{pair:t}:{}});return d.params}resolveSessionAdTagParameters(){const e=i(this.state.sessionAssetParameters,this.state.updatedAssetParameters,this.state.manifestAssetParameters,void 0);return this.resolveAssetParameterMacros(e,void 0,"session","gam",{breakId:void 0,assetId:void 0})}buildVastTagUrl(e,t){const a=this.resolveUri(e.uri);if(!a)return null;const r=i(this.state.sessionAssetParameters,this.state.updatedAssetParameters,this.state.manifestAssetParameters,e.assetParameters),o=e.duration??this.deps.getEffectiveBreakDuration()??t.duration,n=this.resolveAssetParameterMacros(r,o,"break","vast",{breakId:t.id,assetId:e.id});return s(a,n)}pushAssetParameters(e,s){const t=this.deps.getGamStreamManager();if(!t?.isInitialized())return;const a=this.deps.getCurrentBreak(),r=i(this.state.sessionAssetParameters,this.state.updatedAssetParameters,this.state.manifestAssetParameters,e),o=this.resolveAssetParameterMacros(r,this.deps.getEffectiveBreakDuration()??a?.duration,"break","gam",{breakId:a?.id,assetId:s});null!==this.state.pushedAssetParameters&&m(this.state.pushedAssetParameters,o)||(this.state.pushedAssetParameters=o,t.replaceAdTagParameters(o??{}))}resolveUri(e){return void 0===this.state.detectedDeviceType&&(this.state.detectedDeviceType=o()),n(e,this.state.detectedDeviceType)}}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PlayerAdapter } from '../../interfaces/PlayerAdapter';
|
|
2
2
|
import { Asset, Break, BreakVariant, StaticAsset, VastAsset, VendorAsset } from '../../types/BreakManifest';
|
|
3
3
|
import type { AdBreakSequencer, AdBreakTransition } from '../AdBreakSequencer';
|
|
4
|
-
import type
|
|
4
|
+
import { type AdPlayerState } from './AdPlayerState';
|
|
5
5
|
export interface AssetPlaybackDeps {
|
|
6
6
|
getAdPlayer: () => PlayerAdapter | null;
|
|
7
7
|
getAdContainer: () => HTMLDivElement | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AssetType as e,BreakFormat as t,Vendor as s,MediaType as r,isVastAsset as a}from"../../types/BreakManifest";import{resolveVastAdmission as i}from"../resolveVastAdmission";import{VastAdManager as
|
|
1
|
+
import{AssetType as e,BreakFormat as t,Vendor as s,MediaType as r,isVastAsset as a}from"../../types/BreakManifest";import{resolveVastAdmission as i}from"../resolveVastAdmission";import{VastAdManager as n,isImaCsaiSdkAvailable as d}from"../VastAdManager";import{invalidateMediaPreload as o}from"./AdPlayerState";export class AssetPlayback{constructor(e,t){this.state=e,this.deps=t}get currentBreak(){return this.state.currentBreak}async playAsset(e,t,s){const i=this.currentBreak,n=this.deps.getAdPlayer();if(!i||!n)return;const d=this.state.preparedMedia,h=o(this.state),l=()=>this.state.preloadGeneration===h&&this.currentBreak===i&&this.deps.getAdPlayer()===n;if(this.state.currentAsset=e,this.state.currentAssetElapsedSec=0,this.deps.clearStaticQuartiles(),this.deps.clearOverlayImage(),this.deps.log("Playing asset:",e.id,"type:",e.type,"index:",t),a(e))return void this.playVastAsset(e,t,s);if(e.mediaType===r.IMAGE)return void await this.playImageAsset(e,t,s);const c=await this.resolveAssetUri(e,this.state.effectiveBreakDurationSec??i.duration);if(!l())return;if(!c)return void this.deps.onAdError(new Error("No valid URI for asset"));this.deps.log("Resolved URI:",c),this.deps.reportPhase("uri-resolved");const p=i.id;try{this.deps.armAdStartBudget(e);if(0===t&&d?.breakId===p&&d.assetId===e.id&&d.uri===c&&d.player===n)this.deps.reportPhase("load-skipped-preloaded");else{if(this.deps.reportPhase("load-start"),!await this.deps.loadWithinBudget(n.load(c))||!l())return;this.deps.reportPhase("load-resolved")}const r=n.videoElement;if(r&&(r.style.cssText="display:block;width:100%;height:100%;object-fit:contain;"),this.deps.reportPhase("play-called"),this.state.firstFrameGateActive&&!this.state.firstFrameGateShown){const e=this.deps.waitForFirstFrame();await this.playRetryingInterruption(n,p),await e}else{let e=null;const t=await Promise.race([this.playRetryingInterruption(n,p).then(()=>!0),new Promise(t=>{e=setTimeout(()=>t(!1),this.deps.remainingAdStartBudgetMs())})]);if(e&&clearTimeout(e),!l())return;if(!t)return void this.deps.onAdError(new Error(`Ad did not start within ${this.state.adStartBudgetMs}ms ad-start budget`))}if(!l())return;this.state.adStartDeadlineMs=null,this.state.adStartBudgetMs=0,this.deps.transferPictureInPictureToAd();const a=this.deps.getSequencer();a?(this.deps.isGamPodAsset(e)&&this.deps.beginGamPodTracking(e),await this.deps.drive(a.onOutcome({kind:"asset-started"}))):this.state.callbacks?.onAdStart(this.currentBreak,e,t,s)}catch(e){if(!l())return;if(this.state.firstFrameGateActive&&null===this.state.firstFrameResolver)return;this.deps.onAdError(e instanceof Error?e:new Error(String(e)))}}async playRetryingInterruption(e,t){const s=this.state.preloadGeneration;try{await e.play()}catch(r){if(s!==this.state.preloadGeneration||!function(e){return"AbortError"===e?.name}(r)||!this.isStartingBreak(t))throw r;this.deps.diagnose("DA-AD-START-INTERRUPTED","Ad play() was interrupted by a browser-initiated pause before the ad started; play() re-issued once.",{breakId:t,error:r instanceof Error?r.message:String(r)}),this.deps.reportPhase("play-retried"),await e.play()}}isStartingBreak(e){return this.state.isPlaying&&this.state.currentBreak?.id===e}playVastAsset(e,s,r){if(!this.currentBreak||!this.deps.getAdPlayer())return;const a=this.deps.getVariant(this.currentBreak)?.format??t.SINGLE,o=i({format:a,ssai:!1});if(!o.admitted)return this.deps.diagnose(o.diagnostic??"DA-VAST-UNSUPPORTED-FORMAT",`VAST asset '${e.id}' is not supported in '${a}' breaks (single/double/lshape_ad only); skipping.`,{breakId:this.currentBreak.id,assetId:e.id,format:a}),void this.deps.onAdError(new Error(`VAST not supported in ${a} format`));if(!d())return this.deps.diagnose("DA-VAST-IMA-SDK-MISSING","Google IMA client-side SDK (ima3.js) is unavailable; cannot play VAST ad.",{breakId:this.currentBreak.id,assetId:e.id}),void this.deps.onAdError(new Error("IMA client-side SDK (ima3.js) not available"));const h=this.deps.buildVastTagUrl(e,this.currentBreak);if(!h)return void this.deps.onAdError(new Error("No valid VAST tag URL for asset"));const l=this.deps.getAdPlayer(),c=l?.videoElement,p=this.deps.getAdContainer();if(!p||!c||!l)return void this.deps.onAdError(new Error("VAST playout requires an ad container and ad video element"));this.deps.revealFirstFrame(),c.style.cssText="display:block;width:100%;height:100%;object-fit:contain;",this.state.vastAdManager||(this.state.vastAdManager=new n(p,c,this.deps.debug)),this.state.vastAdManager.setCallbacks({onAdStarted:t=>{if(!this.currentBreak)return;this.deps.setVastPodPosition(t);const a=this.deps.getSequencer();a?this.deps.drive(a.onOutcome({kind:"asset-started"})):this.state.callbacks?.onAdStart(this.currentBreak,e,s,r,{podPosition:t})},onAdProgress:(t,s)=>{this.currentBreak&&(this.deps.recordAdProgress(t),this.state.callbacks?.onAdTimeUpdate(this.currentBreak,e,t,s))},onAdFirstQuartile:()=>{this.currentBreak&&this.deps.getGamEventCallbacks().onAdFirstQuartile?.(this.currentBreak,e)},onAdMidpoint:()=>{this.currentBreak&&this.deps.getGamEventCallbacks().onAdMidpoint?.(this.currentBreak,e)},onAdThirdQuartile:()=>{this.currentBreak&&this.deps.getGamEventCallbacks().onAdThirdQuartile?.(this.currentBreak,e)}}),this.deps.log("Playing VAST asset via IMA CSAI:",h);(this.state.vastAdManager.hasPreloadedManager()?(this.state.vastAdManager.setMuted(l.muted),this.state.vastAdManager.startPreloaded()):this.state.vastAdManager.playVast(h,{muted:l.muted})).then(()=>{this.deps.onAdEnded()},t=>{const s=t instanceof Error?t:new Error(String(t)),r=/ima3\.js|client-side SDK/i.test(s.message)?"DA-VAST-IMA-SDK-MISSING":"DA-VAST-IMA-ERROR";this.deps.diagnose(r,s.message,{...this.currentBreak?{breakId:this.currentBreak.id}:{},assetId:e.id}),this.deps.onAdError(s)})}async playImageAsset(e,t,s){const r=this.currentBreak,a=this.deps.getAdMediaContainer();if(!r||!a)return;const i=this.state.effectiveBreakDurationSec??r.duration,n=await this.resolveAssetUri(e,i);if(!n)return void this.deps.onAdError(new Error("No valid URI for asset"));const d=document.createElement("img");d.className="dolby-overlay-image",d.style.cssText="display:block;width:100%;height:100%;object-fit:contain;",this.deps.setOverlayImage(d);const o=e.duration??i;d.onload=()=>{if(this.deps.getOverlayImage()!==d||!this.currentBreak)return;const r=this.deps.getSequencer();r?this.deps.drive(r.onOutcome({kind:"asset-started"})):this.state.callbacks?.onAdStart(this.currentBreak,e,t,s),o>0?this.deps.setImageAssetTimer(setTimeout(()=>this.onImageAssetEnded(),1e3*o)):this.onImageAssetEnded()},d.onerror=()=>{this.deps.getOverlayImage()===d&&this.deps.onAdError(new Error(`Overlay image failed to load: ${n}`))},d.src=n,a.appendChild(d)}onImageAssetEnded(){const e=this.deps.getSequencer();if(!this.currentBreak||!this.state.isPlaying||!e)return;const t=this.deps.getImageAssetTimer();t&&(clearTimeout(t),this.deps.setImageAssetTimer(null)),this.deps.drive(e.onOutcome({kind:"asset-ended"}))}async resolveAssetUri(t,r){switch(t.type){case e.STATIC:return this.deps.resolveUri(t.uri);case e.VENDOR:{const e=t;return e.vendor===s.GAM?await this.deps.buildGamUrl(e,r):(this.deps.log("Unsupported vendor:",e.vendor),null)}default:return this.deps.log("Unsupported asset type:",t.type),null}}adPlayerStreamRemainingSec(){const e=this.deps.getAdPlayer();if(!e)return 0;const{duration:t,currentTime:s}=e;if(!Number.isFinite(t)||t<=0)return 0;if(!Number.isFinite(s)||s<0)return 0;const r=t-s;return r>0?r:0}revealFirstFrame(){this.deps.revealFirstFrame()}toAdError(e){const t=e;if(t&&("number"==typeof t.code||t.message)){const e="number"==typeof t.code?` (code ${t.code})`:"",s=t.message?`: ${t.message}`:"";return new Error(`Ad playback error${e}${s}`)}return new Error("Ad playback error")}}
|
|
@@ -2,7 +2,7 @@ import type { Asset, Break } from '../../types/BreakManifest';
|
|
|
2
2
|
import type { AdPlayerCallbacks, PlayBreakOptions } from '../AdPlayerController';
|
|
3
3
|
import type { AdBreakAction, AdBreakStep, AdBreakTransition, EffectiveInsertionMode } from '../AdBreakSequencer';
|
|
4
4
|
import type { GamPodAdStep } from '../GamPodAdTracker';
|
|
5
|
-
import type
|
|
5
|
+
import { type AdPlayerState } from './AdPlayerState';
|
|
6
6
|
export interface BreakSequenceDriverDeps {
|
|
7
7
|
getChainResolver: () => ((currentBreakId: string) => Break | null) | null;
|
|
8
8
|
getEffectiveInsertionMode: () => EffectiveInsertionMode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export class BreakSequenceDriver{constructor(e,t){this.state=e,this.deps=t}async drive(e){for(const t of e.noPlayableAsset??[])this.deps.diagnose("DA-BREAK-NO-PLAYABLE-ASSET",`break ${t.breakId} had no playable ad (${t.reason}); it began and ended without an ad.`,{breakId:t.breakId,reason:t.reason,declaredAssetCount:t.declaredAssetCount,...void 0!==t.format?{format:t.format}:{}});for(const t of e.steps)this.emitStep(t);await this.performAction(e.action)}emitStep(e){if(this.state.currentBreak)switch(e.type){case"adbreakbegin":case"adbreakend":return;case"adbegin":return this.deps.isExpandingPodAsset(e.asset)?void("pending"===this.state.gamPodMode&&(this.state.withheldPodAdBegin=e)):void(void 0!==this.deps.getVastPodPosition()?(this.state.callbacks?.onAdStart(this.state.currentBreak,e.asset,e.adIndex,e.totalAds,{podPosition:this.deps.getVastPodPosition()}),this.deps.setVastPodPosition(void 0)):this.state.callbacks?.onAdStart(this.state.currentBreak,e.asset,e.adIndex,e.totalAds));case"adend":if(this.settlePodAdEnd(e))return;return this.state.callbacks?.onAdEnd(this.state.currentBreak,e.asset,e.adIndex,e.totalAds),void this.deps.resetGamPodTracking();case"aderror":{this.deps.isExpandingPodAsset(e.asset)&&(this.state.withheldPodAdBegin=null,this.state.gamPodTracker?.sawAnyAd&&this.emitGamPodSteps(this.state.gamPodTracker.finish()));const t=this.deps.getPendingAdError()??new Error("Ad playback error");return this.deps.setPendingAdError(null),void this.state.callbacks?.onAdError(this.state.currentBreak,e.asset,t)}}}settlePodAdEnd(e){return!!this.deps.isExpandingPodAsset(e.asset)&&(this.state.gamPodTracker?.sawAnyAd?(this.emitGamPodSteps(this.state.gamPodTracker.finish()),this.deps.resetGamPodTracking(),!0):(this.deps.fallBackToPodLevelReporting(),!1))}async performAction(e){switch(e.kind){case"play-asset":return void await this.deps.playAsset(e.asset,e.index,e.total);case"end-break":return void this.deps.endBreak();default:return}}emitGamPodSteps(e){this.deps.emitGamPodSteps(e)}resolveChainedSuccessor(e){const t=this.deps.getChainResolver();if(!t)return null;if("shared-element"===this.deps.getEffectiveInsertionMode())return null;try{return t(e)}catch(e){return this.deps.log("Chain resolver error:",e),null}}advanceToChainedBreak(
|
|
1
|
+
import{invalidateMediaPreload as e}from"./AdPlayerState";export class BreakSequenceDriver{constructor(e,t){this.state=e,this.deps=t}async drive(e){for(const t of e.noPlayableAsset??[])this.deps.diagnose("DA-BREAK-NO-PLAYABLE-ASSET",`break ${t.breakId} had no playable ad (${t.reason}); it began and ended without an ad.`,{breakId:t.breakId,reason:t.reason,declaredAssetCount:t.declaredAssetCount,...void 0!==t.format?{format:t.format}:{}});for(const t of e.steps)this.emitStep(t);await this.performAction(e.action)}emitStep(e){if(this.state.currentBreak)switch(e.type){case"adbreakbegin":case"adbreakend":return;case"adbegin":return this.deps.isExpandingPodAsset(e.asset)?void("pending"===this.state.gamPodMode&&(this.state.withheldPodAdBegin=e)):void(void 0!==this.deps.getVastPodPosition()?(this.state.callbacks?.onAdStart(this.state.currentBreak,e.asset,e.adIndex,e.totalAds,{podPosition:this.deps.getVastPodPosition()}),this.deps.setVastPodPosition(void 0)):this.state.callbacks?.onAdStart(this.state.currentBreak,e.asset,e.adIndex,e.totalAds));case"adend":if(this.settlePodAdEnd(e))return;return this.state.callbacks?.onAdEnd(this.state.currentBreak,e.asset,e.adIndex,e.totalAds),void this.deps.resetGamPodTracking();case"aderror":{this.deps.isExpandingPodAsset(e.asset)&&(this.state.withheldPodAdBegin=null,this.state.gamPodTracker?.sawAnyAd&&this.emitGamPodSteps(this.state.gamPodTracker.finish()));const t=this.deps.getPendingAdError()??new Error("Ad playback error");return this.deps.setPendingAdError(null),void this.state.callbacks?.onAdError(this.state.currentBreak,e.asset,t)}}}settlePodAdEnd(e){return!!this.deps.isExpandingPodAsset(e.asset)&&(this.state.gamPodTracker?.sawAnyAd?(this.emitGamPodSteps(this.state.gamPodTracker.finish()),this.deps.resetGamPodTracking(),!0):(this.deps.fallBackToPodLevelReporting(),!1))}async performAction(e){switch(e.kind){case"play-asset":return void await this.deps.playAsset(e.asset,e.index,e.total);case"end-break":return void this.deps.endBreak();default:return}}emitGamPodSteps(e){this.deps.emitGamPodSteps(e)}resolveChainedSuccessor(e){const t=this.deps.getChainResolver();if(!t)return null;if("shared-element"===this.deps.getEffectiveInsertionMode())return null;try{return t(e)}catch(e){return this.deps.log("Chain resolver error:",e),null}}advanceToChainedBreak(t,s){this.deps.log(`Chaining: "${t.id}" -> "${s.id}" (overlay held, content stays paused)`),this.state.currentBreak=null,this.state.effectiveBreakDurationSec=null,e(this.state);const a=this.state.callbacks;a?.onBreakEnd(t),a?.onChainedBreakBegin?.(s),a&&(this.deps.setChaining(!0),this.deps.playBreak(s,a).finally(()=>{this.deps.setChaining(!1)}))}}
|
|
@@ -29,7 +29,7 @@ export declare class ContentResumeCoordinator {
|
|
|
29
29
|
resumeAlignSummary(): Record<string, unknown>;
|
|
30
30
|
cancelResumeLandedProbe(): void;
|
|
31
31
|
probeResumeLanding(breakId: string, target: number): void;
|
|
32
|
-
waitForLiveEdge(): Promise<number | null>;
|
|
32
|
+
waitForLiveEdge(isCurrent?: () => boolean): Promise<number | null>;
|
|
33
33
|
resetBreakResumeState(): void;
|
|
34
34
|
beginContinueContentPlayout(): void;
|
|
35
35
|
distanceToLiveEdgeSec(): number | null;
|
|
@@ -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}from"./liveEdge";const u=.04;export class ContentResumeCoordinator{constructor(e,t){this.state=e,this.deps=t,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)})}liveEdgeDistanceSec(){return r(this.deps.contentPlayer)}liveSafeSeekEnd(){return o(this.deps.contentPlayer)}contentSeekableEnd(){return i(this.deps.contentPlayer)}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)<=u?(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)>u){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<=u)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.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)>u&&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.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(){for(let e=0;e<20;e++){const e=this.deps.contentPlayer.videoElement,t=e?.seekable;if(t&&t.length>0){const e=t.end(t.length-1);if(Number.isFinite(e)&&e>0)return e}await new Promise(e=>setTimeout(e,100))}return this.deps.log("shared-element: no seekable range after restore; staying at the live edge"),null}resetBreakResumeState(){this.state.resumePrepositionedTo=null,this.state.resumeCatchupActive=!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:(t=e-this.deps.contentPlayer.currentTime,Math.round(1e3*t)/1e3);var t}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()}applyResumeSeek(t,n=null){const i=null!==n,a=i?n:this.state.adSecondsPlayedThisBreak,r=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(r.clamped&&this.deps.diagnose?.("DA-RESUME-OFFSET-CLAMPED",`Resume offset shortened to the ${r.offset}s of ad actually played for break ${t.id}`,{breakId:t.id,offset:r.offset,source:r.source}),!r.seek)return void this.deps.log(`Resume: no seek for break ${t.id} (offset 0, ${r.source})`);this.deps.log(`Resume-seek to ${r.target}s (offset ${r.offset}s, ${r.source}) for break ${t.id}`),this.deps.diagnose?.("DA-RESUME-SEEK",`Resume-seek to ${r.target}s (offset ${r.offset}s, ${r.source}) for break ${t.id}`,{breakId:t.id,target:r.target,offset:r.offset,source:r.source});(this.state.breakTimebase===e.PTS||this.state.breakTimebase===e.MEDIATIME)&&"number"==typeof t.start&&this.state.callbacks?.onContentResumeSeek?.(r.target,t.start+t.duration);const o=this.liveSafeSeekEnd();let d=r.target,l=0;if(null!==o&&d>o&&(l=Math.round(1e3*(d-o))/1e3,d=o),null!==this.state.resumePrepositionedTo&&Math.abs(this.deps.contentPlayer.currentTime-d)<=u){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)`+(l>0?` — ${l}s short of policy, those frames are not published yet`:"")+" — no seek"),void this.deps.diagnose?.("DA-RESUME-PREPOSITIONED",`Break ${t.id} resumed without a seek: content was moved to ${e}s during the break`+(l>0?` (${l}s short of the ${r.target}s policy target)`:""),{breakId:t.id,target:r.target,prepositionedTo:this.state.resumePrepositionedTo,landed:e,shortfallSec:l,exact:0===l,...this.resumeAlignSummary()})}l>0&&(this.deps.log(`Resume-seek clamped: ${r.target}s is beyond what the stream has published; seeking ${d}s instead (${l}s short)`),this.deps.diagnose?.("DA-RESUME-TARGET-CLAMPED",`Resume target ${r.target}s for break ${t.id} is beyond the published window; clamped to ${d}s`,{breakId:t.id,requested:r.target,clamped:d,shortfallSec:l,...this.resumeAlignSummary()})),this.probeResumeLanding(t.id,d),this.deps.contentPlayer.seek(d)}}
|
|
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}from"./liveEdge";const u=.04;export class ContentResumeCoordinator{constructor(e,t){this.state=e,this.deps=t,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)})}liveEdgeDistanceSec(){return r(this.deps.contentPlayer)}liveSafeSeekEnd(){return o(this.deps.contentPlayer)}contentSeekableEnd(){return i(this.deps.contentPlayer)}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)<=u?(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)>u){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<=u)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.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)>u&&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.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.resumePrepositionedTo=null,this.state.resumeCatchupActive=!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:(t=e-this.deps.contentPlayer.currentTime,Math.round(1e3*t)/1e3);var t}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()}applyResumeSeek(t,n=null){const i=null!==n,a=i?n:this.state.adSecondsPlayedThisBreak,r=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(r.clamped&&this.deps.diagnose?.("DA-RESUME-OFFSET-CLAMPED",`Resume offset shortened to the ${r.offset}s of ad actually played for break ${t.id}`,{breakId:t.id,offset:r.offset,source:r.source}),!r.seek)return void this.deps.log(`Resume: no seek for break ${t.id} (offset 0, ${r.source})`);this.deps.log(`Resume-seek to ${r.target}s (offset ${r.offset}s, ${r.source}) for break ${t.id}`),this.deps.diagnose?.("DA-RESUME-SEEK",`Resume-seek to ${r.target}s (offset ${r.offset}s, ${r.source}) for break ${t.id}`,{breakId:t.id,target:r.target,offset:r.offset,source:r.source});(this.state.breakTimebase===e.PTS||this.state.breakTimebase===e.MEDIATIME)&&"number"==typeof t.start&&this.state.callbacks?.onContentResumeSeek?.(r.target,t.start+t.duration);const o=this.liveSafeSeekEnd();let d=r.target,l=0;if(null!==o&&d>o&&(l=Math.round(1e3*(d-o))/1e3,d=o),null!==this.state.resumePrepositionedTo&&Math.abs(this.deps.contentPlayer.currentTime-d)<=u){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)`+(l>0?` — ${l}s short of policy, those frames are not published yet`:"")+" — no seek"),void this.deps.diagnose?.("DA-RESUME-PREPOSITIONED",`Break ${t.id} resumed without a seek: content was moved to ${e}s during the break`+(l>0?` (${l}s short of the ${r.target}s policy target)`:""),{breakId:t.id,target:r.target,prepositionedTo:this.state.resumePrepositionedTo,landed:e,shortfallSec:l,exact:0===l,...this.resumeAlignSummary()})}l>0&&(this.deps.log(`Resume-seek clamped: ${r.target}s is beyond what the stream has published; seeking ${d}s instead (${l}s short)`),this.deps.diagnose?.("DA-RESUME-TARGET-CLAMPED",`Resume target ${r.target}s for break ${t.id} is beyond the published window; clamped to ${d}s`,{breakId:t.id,requested:r.target,clamped:d,shortfallSec:l,...this.resumeAlignSummary()})),this.probeResumeLanding(t.id,d),this.deps.contentPlayer.seek(d)}}
|
|
@@ -14,7 +14,7 @@ export interface SharedElementBreakPlayerDeps {
|
|
|
14
14
|
log: (...args: unknown[]) => void;
|
|
15
15
|
clearContentGate: () => void;
|
|
16
16
|
hide: () => void;
|
|
17
|
-
waitForLiveEdge: () => Promise<number | null>;
|
|
17
|
+
waitForLiveEdge: (isCurrent?: () => boolean) => Promise<number | null>;
|
|
18
18
|
getVariant: (breakInfo: Break) => {
|
|
19
19
|
format: string;
|
|
20
20
|
} | null;
|
|
@@ -30,6 +30,9 @@ export declare class SharedElementBreakPlayer {
|
|
|
30
30
|
private sharedAdTimeUpdateHandler;
|
|
31
31
|
private sharedAdFirstFrameTimer;
|
|
32
32
|
private sharedRestoreWatchdog;
|
|
33
|
+
private sharedRestore;
|
|
34
|
+
private sharedRestoreGeneration;
|
|
35
|
+
private sharedActivityGeneration;
|
|
33
36
|
constructor(state: AdPlayerState, deps: SharedElementBreakPlayerDeps);
|
|
34
37
|
sharedElementAdPlayer(): PlayerAdapter | null;
|
|
35
38
|
private sharedAdStep;
|
|
@@ -48,7 +51,13 @@ export declare class SharedElementBreakPlayer {
|
|
|
48
51
|
playSharedElementBreak(breakInfo: Break, callbacks: AdPlayerCallbacks): Promise<void>;
|
|
49
52
|
onSharedElementAdEnded(): void;
|
|
50
53
|
restoreSharedElementContent(breakInfo?: Break | null): void;
|
|
54
|
+
private runSharedRestore;
|
|
55
|
+
private ownsSharedRestoreAttempt;
|
|
56
|
+
private reloadAndResume;
|
|
57
|
+
private finishSharedRestore;
|
|
58
|
+
private endSharedRestoreReloading;
|
|
51
59
|
private armSharedRestoreWatchdog;
|
|
52
|
-
|
|
60
|
+
beginSharedActivity(): boolean;
|
|
61
|
+
cancelSharedRestore(): boolean;
|
|
53
62
|
restorableContentSource(): string | null;
|
|
54
63
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BreakFormat as e,isPostRollBreak as t}from"../../types/BreakManifest";export class SharedElementBreakPlayer{constructor(e,t){this.state=e,this.deps=t,this.contentElementAdPlayer=null,this.sharedAdSource=null,this.sharedAdEndedHandler=null,this.sharedAdTimeUpdateHandler=null,this.sharedAdFirstFrameTimer=null,this.sharedRestoreWatchdog=null}sharedElementAdPlayer(){const e=this.deps.contentPlayer.videoElement;if(!e)return null;if(this.contentElementAdPlayer?.videoElement===e)return this.contentElementAdPlayer;this.releaseContentElementAdPlayer();const t=this.deps.createAdAdapter(document.createElement("div"),e);return t.videoElement!==e?(this.deps.log("shared-element: createAdAdapter ignored the content element; falling back to the content player for ad playback"),t.destroy(),null):(this.contentElementAdPlayer=t,t)}async sharedAdStep(e,t,s){try{await s()}catch(s){const a=t.videoElement,n=s instanceof Error?s.message:String(s);throw new Error(`shared-element ${e} failed: ${n} (readyState=${a?.readyState??"-"} paused=${a?.paused??"-"} networkState=${a?.networkState??"-"})`,{cause:s})}}clearSharedAdFirstFrameWatchdog(){this.sharedAdFirstFrameTimer&&(clearTimeout(this.sharedAdFirstFrameTimer),this.sharedAdFirstFrameTimer=null)}armSharedAdFirstFrameWatchdog(e,t){this.clearSharedAdFirstFrameWatchdog(),this.sharedAdFirstFrameTimer=setTimeout(()=>{if(this.sharedAdFirstFrameTimer=null,!this.state.isPlaying||!this.state.currentBreak)return;const s=e.videoElement,a=this.deps.contentPlayer.videoElement,n=s?.currentSrc??"",r=`readyState=${s?.readyState??"-"} networkState=${s?.networkState??"-"} paused=${s?.paused??"-"} connected=${s?.isConnected??"-"} srcKind=${n.startsWith("blob:")?"blob":n?"url":"none"} sameElementAsContentPlayer=${String(s===a)}`;this.deps.log(`shared-element: no first frame within ${t}ms (${r})`),this.deps.diagnose("DA-AD-PLAYBACK-ERROR",`the ad never rendered a frame on the content element within ${t}ms`,{breakId:this.state.currentBreak.id,detail:r});const d=this.state.currentAsset;d&&this.state.callbacks?.onAdError(this.state.currentBreak,d,new Error(`shared-element ad produced no frames within ${t}ms (${r})`)),this.onSharedElementAdEnded()},t)}attachSharedAdListeners(e){this.sharedAdSource=e,this.sharedAdEndedHandler=()=>this.onSharedElementAdEnded(),e.on("ended",this.sharedAdEndedHandler),this.sharedAdTimeUpdateHandler=()=>{this.sharedAdFirstFrameTimer&&e.currentTime>0&&this.clearSharedAdFirstFrameWatchdog(),this.deps.reportAdProgress(e)},e.on("timeupdate",this.sharedAdTimeUpdateHandler)}detachSharedAdListeners(){const e=this.sharedAdSource??this.deps.contentPlayer;this.sharedAdSource=null,this.state.sharedAdClaimActive=!1,this.clearSharedAdFirstFrameWatchdog(),this.sharedAdTimeUpdateHandler&&(e.off("timeupdate",this.sharedAdTimeUpdateHandler),this.sharedAdTimeUpdateHandler=null),this.sharedAdEndedHandler&&(e.off("ended",this.sharedAdEndedHandler),this.sharedAdEndedHandler=null)}async releaseContentElementFromContentEngine(){if(this.deps.contentPlayer.releaseMediaElement)try{await this.deps.contentPlayer.releaseMediaElement()}catch(e){this.deps.log("shared-element: the content engine did not release the element:",e)}}releaseContentElementAdPlayer(){if(this.contentElementAdPlayer){try{this.contentElementAdPlayer.destroy()}catch(e){this.deps.log("shared-element: releasing the ad player on the content element failed:",e)}this.contentElementAdPlayer=null}}async playAdThroughContentElement(){const e=this.state.currentAsset,t=this.state.currentBreak;if(!e||!t)return;const s=this.state.effectiveBreakDurationSec??t.duration,a=await this.deps.resolveAssetUri(e,s);if(!a)return void this.deps.log("shared-element: no URI for the running ad; leaving it on the ad element");const n=this.deps.getAdPlayer()?.currentTime??0;this.state.savedContentSrc=this.restorableContentSource(),this.state.savedContentTime=this.deps.contentPlayer.currentTime,this.state.savedContentLive=!Number.isFinite(this.deps.contentPlayer.duration),this.state.savedContentEdgeDistance=this.state.savedContentLive?this.deps.liveEdgeDistanceSec():null,this.state.sharedAdClaimActive=!0,await this.releaseContentElementFromContentEngine(),this.deps.rebindContentElementIfSwapped();const r=this.sharedElementAdPlayer()??this.deps.contentPlayer;try{this.deps.getAdPlayer()?.pause(),this.deps.clearContentGate(),await r.load(a),this.attachSharedAdListeners(r),n>0&&r.seek(n),await r.play(),this.deps.hide(),this.deps.log("shared-element: the ad now plays through the content element")}catch(e){this.deps.log("shared-element: could not move the ad onto the content element:",e),this.state.sharedAdClaimActive=!1,this.state.savedContentSrc=null,this.state.savedContentEdgeDistance=null}}async playSharedElementBreak(t,s){const a=this.deps.getVariant(t);if(!a)return this.deps.log("shared-element: no valid variant, skipping break:",t.id),void s.onBreakEnd(t);if(a.format===e.LSHAPE_CONTENT)return this.deps.log("shared-element: skipping lshape_content break (no fullscreen video asset):",t.id),void s.onBreakEnd(t);const n=this.deps.getAssets(t)[0];if(!n)return this.deps.log("shared-element: no asset to play, skipping break:",t.id),void s.onBreakEnd(t);a.format!==e.SINGLE&&this.deps.log(`shared-element: downgrading ${a.format} to a single fullscreen ad:`,t.id),this.state.currentBreak=t,this.state.currentAsset=n,this.state.callbacks=s,this.state.isPlaying=!0;const r=this.state.effectiveBreakDurationSec??t.duration,d=await this.deps.resolveAssetUri(n,r);if(!d)return this.deps.log("shared-element: no valid URI, skipping break:",t.id),this.state.isPlaying=!1,this.state.currentBreak=null,this.state.currentAsset=null,void s.onBreakEnd(t);this.state.savedContentSrc=this.restorableContentSource(),this.state.savedContentTime=this.deps.contentPlayer.currentTime,this.state.savedContentLive=!Number.isFinite(this.deps.contentPlayer.duration),this.state.savedContentEdgeDistance=this.state.savedContentLive?this.deps.liveEdgeDistanceSec():null,this.state.sharedAdClaimActive=!0,await this.releaseContentElementFromContentEngine(),this.deps.rebindContentElementIfSwapped();const i=this.sharedElementAdPlayer()??this.deps.contentPlayer;if(r&&r>0){const e=r+this.state.adBreakCutSafetyMarginSec;this.state.durationTimer=setTimeout(()=>{this.deps.log("shared-element: break-cut timer expired, ending break"),this.state.isPlaying&&this.state.currentBreak&&this.state.callbacks?.onBreakCut?.(this.state.currentBreak),this.onSharedElementAdEnded()},1e3*e)}try{this.deps.clearContentGate(),await this.sharedAdStep("load",i,()=>i.load(d)),this.attachSharedAdListeners(i),this.armSharedAdFirstFrameWatchdog(i,Math.max(Math.min(1e3*(r??0)-100,5e3),3e3)),await this.sharedAdStep("play",i,()=>i.play()),this.state.callbacks?.onAdStart(t,n,0,1)}catch(e){this.deps.log("shared-element: ad playback failed:",e),this.state.callbacks?.onAdError(t,n,e instanceof Error?e:new Error(String(e))),this.onSharedElementAdEnded()}}onSharedElementAdEnded(){if(!this.state.isPlaying||!this.state.currentBreak)return;const e=this.state.currentBreak,t=this.state.currentAsset;this.detachSharedAdListeners(),this.state.durationTimer&&(clearTimeout(this.state.durationTimer),this.state.durationTimer=null),this.state.isPlaying=!1,this.state.currentBreak=null,t&&this.state.callbacks?.onAdEnd(e,t,0,1),this.state.currentAsset=null,this.restoreSharedElementContent(e),this.state.callbacks?.onBreakEnd(e)}restoreSharedElementContent(e){const s=this.state.savedContentSrc,a=this.state.savedContentTime,n=this.state.savedContentLive,r=this.state.savedContentEdgeDistance;if(this.state.savedContentSrc=null,this.state.savedContentEdgeDistance=null,!s)return this.deps.log("shared-element: no saved content source to restore"),void this.releaseContentElementAdPlayer();e&&"number"==typeof e.start&&this.state.callbacks?.onContentResumeSeek?.(n?this.deps.contentPlayer.currentTime:a,e.start+e.duration),this.state.callbacks?.onContentReloading?.(!0);const d=!!e&&t(e),i=async()=>{if(await this.deps.contentPlayer.load(s),n){if(!d&&null!==r&&r>0){const e=await this.deps.waitForLiveEdge();if(null!==e){const t=Math.max(e-r,0);this.deps.log(`shared-element: live resume ${r.toFixed(2)}s behind the edge (${t.toFixed(2)}s)`),this.deps.contentPlayer.seek(t)}}}else this.deps.contentPlayer.seek(a);d||await this.deps.contentPlayer.play()};i().catch(async t=>{this.deps.log("shared-element: content restore failed, retrying once:",t);try{await i()}catch(t){this.deps.diagnose("DA-SHARED-ELEMENT-RESTORE-FAILED",`Content did not resume after the shared-element break: ${t instanceof Error?t.message:String(t)}`,{breakId:e?.id,live:n,attempts:2})}}).finally(()=>{this.state.contentPaused=!1,this.deps.clearContentGate(),this.releaseContentElementAdPlayer(),this.deps.rebindContentElementIfSwapped(),this.state.callbacks?.onContentReloading?.(!1),d||this.armSharedRestoreWatchdog(e)})}armSharedRestoreWatchdog(e){this.sharedRestoreWatchdog&&clearTimeout(this.sharedRestoreWatchdog);const t=this.deps.contentPlayer.currentTime;this.sharedRestoreWatchdog=setTimeout(()=>{this.sharedRestoreWatchdog=null;const s=this.deps.contentPlayer.currentTime-t;(this.deps.contentPlayer.paused||s<1)&&(this.deps.diagnose("DA-CONTENT-RESUME-STALLED",`Content did not resume within 5s of the shared-element restore (paused: ${this.deps.contentPlayer.paused}, advanced: ${s.toFixed(1)}s); nudging play()`,{breakId:e?.id??"?",paused:this.deps.contentPlayer.paused,advancedSec:s}),this.deps.contentPlayer.play().catch(e=>{this.deps.log("shared-element: watchdog play() nudge failed:",e)}))},5e3)}clearSharedRestoreWatchdog(){this.sharedRestoreWatchdog&&(clearTimeout(this.sharedRestoreWatchdog),this.sharedRestoreWatchdog=null)}restorableContentSource(){const e=this.deps.contentPlayer.sourceUrl;if(e&&!e.startsWith("blob:"))return e;const t=this.deps.contentPlayer.videoElement,s=t?.currentSrc||t?.src||"";return s.length>0&&!s.startsWith("blob:")?s:null}}
|
|
1
|
+
import{BreakFormat as e,isPostRollBreak as t}from"../../types/BreakManifest";export class SharedElementBreakPlayer{constructor(e,t){this.state=e,this.deps=t,this.contentElementAdPlayer=null,this.sharedAdSource=null,this.sharedAdEndedHandler=null,this.sharedAdTimeUpdateHandler=null,this.sharedAdFirstFrameTimer=null,this.sharedRestoreWatchdog=null,this.sharedRestore=null,this.sharedRestoreGeneration=0,this.sharedActivityGeneration=0}sharedElementAdPlayer(){const e=this.deps.contentPlayer.videoElement;if(!e)return null;if(this.contentElementAdPlayer?.videoElement===e)return this.contentElementAdPlayer;this.releaseContentElementAdPlayer();const t=this.deps.createAdAdapter(document.createElement("div"),e);return t.videoElement!==e?(this.deps.log("shared-element: createAdAdapter ignored the content element; falling back to the content player for ad playback"),t.destroy(),null):(this.contentElementAdPlayer=t,t)}async sharedAdStep(e,t,s){try{await s()}catch(s){const a=t.videoElement,n=s instanceof Error?s.message:String(s);throw new Error(`shared-element ${e} failed: ${n} (readyState=${a?.readyState??"-"} paused=${a?.paused??"-"} networkState=${a?.networkState??"-"})`,{cause:s})}}clearSharedAdFirstFrameWatchdog(){this.sharedAdFirstFrameTimer&&(clearTimeout(this.sharedAdFirstFrameTimer),this.sharedAdFirstFrameTimer=null)}armSharedAdFirstFrameWatchdog(e,t){this.clearSharedAdFirstFrameWatchdog(),this.sharedAdFirstFrameTimer=setTimeout(()=>{if(this.sharedAdFirstFrameTimer=null,!this.state.isPlaying||!this.state.currentBreak)return;const s=e.videoElement,a=this.deps.contentPlayer.videoElement,n=s?.currentSrc??"",r=`readyState=${s?.readyState??"-"} networkState=${s?.networkState??"-"} paused=${s?.paused??"-"} connected=${s?.isConnected??"-"} srcKind=${n.startsWith("blob:")?"blob":n?"url":"none"} sameElementAsContentPlayer=${String(s===a)}`;this.deps.log(`shared-element: no first frame within ${t}ms (${r})`),this.deps.diagnose("DA-AD-PLAYBACK-ERROR",`the ad never rendered a frame on the content element within ${t}ms`,{breakId:this.state.currentBreak.id,detail:r});const i=this.state.currentAsset;i&&this.state.callbacks?.onAdError(this.state.currentBreak,i,new Error(`shared-element ad produced no frames within ${t}ms (${r})`)),this.onSharedElementAdEnded()},t)}attachSharedAdListeners(e){this.sharedAdSource=e,this.sharedAdEndedHandler=()=>this.onSharedElementAdEnded(),e.on("ended",this.sharedAdEndedHandler),this.sharedAdTimeUpdateHandler=()=>{this.sharedAdFirstFrameTimer&&e.currentTime>0&&this.clearSharedAdFirstFrameWatchdog(),this.deps.reportAdProgress(e)},e.on("timeupdate",this.sharedAdTimeUpdateHandler)}detachSharedAdListeners(){const e=this.sharedAdSource??this.deps.contentPlayer;this.sharedAdSource=null,this.state.sharedAdClaimActive=!1,this.clearSharedAdFirstFrameWatchdog(),this.sharedAdTimeUpdateHandler&&(e.off("timeupdate",this.sharedAdTimeUpdateHandler),this.sharedAdTimeUpdateHandler=null),this.sharedAdEndedHandler&&(e.off("ended",this.sharedAdEndedHandler),this.sharedAdEndedHandler=null)}async releaseContentElementFromContentEngine(){if(this.deps.contentPlayer.releaseMediaElement)try{await this.deps.contentPlayer.releaseMediaElement()}catch(e){this.deps.log("shared-element: the content engine did not release the element:",e)}}releaseContentElementAdPlayer(){const e=this.contentElementAdPlayer;if(e){this.contentElementAdPlayer=null;try{e.destroy()}catch(e){this.deps.log("shared-element: releasing the ad player on the content element failed:",e)}}}async playAdThroughContentElement(){const e=this.state.currentAsset,t=this.state.currentBreak;if(!e||!t)return;const s=this.state.effectiveBreakDurationSec??t.duration,a=await this.deps.resolveAssetUri(e,s);if(!a)return void this.deps.log("shared-element: no URI for the running ad; leaving it on the ad element");const n=this.deps.getAdPlayer()?.currentTime??0;this.state.savedContentSrc=this.restorableContentSource(),this.state.savedContentTime=this.deps.contentPlayer.currentTime,this.state.savedContentLive=!Number.isFinite(this.deps.contentPlayer.duration),this.state.savedContentEdgeDistance=this.state.savedContentLive?this.deps.liveEdgeDistanceSec():null,this.state.sharedAdClaimActive=!0,await this.releaseContentElementFromContentEngine(),this.deps.rebindContentElementIfSwapped();const r=this.sharedElementAdPlayer()??this.deps.contentPlayer;try{this.deps.getAdPlayer()?.pause(),this.deps.clearContentGate(),await r.load(a),this.attachSharedAdListeners(r),n>0&&r.seek(n),await r.play(),this.deps.hide(),this.deps.log("shared-element: the ad now plays through the content element")}catch(e){this.deps.log("shared-element: could not move the ad onto the content element:",e),this.state.sharedAdClaimActive=!1,this.state.savedContentSrc=null,this.state.savedContentEdgeDistance=null}}async playSharedElementBreak(t,s){const a=this.deps.getVariant(t);if(!a)return this.deps.log("shared-element: no valid variant, skipping break:",t.id),void s.onBreakEnd(t);if(a.format===e.LSHAPE_CONTENT)return this.deps.log("shared-element: skipping lshape_content break (no fullscreen video asset):",t.id),void s.onBreakEnd(t);const n=this.deps.getAssets(t)[0];if(!n)return this.deps.log("shared-element: no asset to play, skipping break:",t.id),void s.onBreakEnd(t);a.format!==e.SINGLE&&this.deps.log(`shared-element: downgrading ${a.format} to a single fullscreen ad:`,t.id),this.state.currentBreak=t,this.state.currentAsset=n,this.state.callbacks=s,this.state.isPlaying=!0;const r=this.state.effectiveBreakDurationSec??t.duration,i=await this.deps.resolveAssetUri(n,r);if(!i)return this.deps.log("shared-element: no valid URI, skipping break:",t.id),this.state.isPlaying=!1,this.state.currentBreak=null,this.state.currentAsset=null,void s.onBreakEnd(t);this.state.savedContentSrc=this.restorableContentSource(),this.state.savedContentTime=this.deps.contentPlayer.currentTime,this.state.savedContentLive=!Number.isFinite(this.deps.contentPlayer.duration),this.state.savedContentEdgeDistance=this.state.savedContentLive?this.deps.liveEdgeDistanceSec():null,this.state.sharedAdClaimActive=!0,await this.releaseContentElementFromContentEngine(),this.deps.rebindContentElementIfSwapped();const d=this.sharedElementAdPlayer()??this.deps.contentPlayer;if(r&&r>0){const e=r+this.state.adBreakCutSafetyMarginSec;this.state.durationTimer=setTimeout(()=>{this.deps.log("shared-element: break-cut timer expired, ending break"),this.state.isPlaying&&this.state.currentBreak&&this.state.callbacks?.onBreakCut?.(this.state.currentBreak),this.onSharedElementAdEnded()},1e3*e)}try{this.deps.clearContentGate(),await this.sharedAdStep("load",d,()=>d.load(i)),this.attachSharedAdListeners(d),this.armSharedAdFirstFrameWatchdog(d,Math.max(Math.min(1e3*(r??0)-100,5e3),3e3)),await this.sharedAdStep("play",d,()=>d.play()),this.state.callbacks?.onAdStart(t,n,0,1)}catch(e){this.deps.log("shared-element: ad playback failed:",e),this.state.callbacks?.onAdError(t,n,e instanceof Error?e:new Error(String(e))),this.onSharedElementAdEnded()}}onSharedElementAdEnded(){if(!this.state.isPlaying||!this.state.currentBreak)return;const e=this.state.currentBreak,t=this.state.currentAsset,s=this.state.callbacks,a=this.sharedRestoreGeneration;this.detachSharedAdListeners(),this.state.durationTimer&&(clearTimeout(this.state.durationTimer),this.state.durationTimer=null),this.state.isPlaying=!1,this.state.currentBreak=null,this.state.currentAsset=null,t&&s?.onAdEnd(e,t,0,1),a===this.sharedRestoreGeneration&&this.restoreSharedElementContent(e),s?.onBreakEnd(e)}restoreSharedElementContent(e){const s=this.state.savedContentSrc;if(!s){if(this.sharedRestore)return;return this.deps.log("shared-element: no saved content source to restore"),void this.releaseContentElementAdPlayer()}if(!this.beginSharedActivity())return;const a=this.state.savedContentTime,n=this.state.savedContentLive,r=this.state.savedContentEdgeDistance,i=this.state.callbacks;this.state.savedContentSrc=null,this.state.savedContentEdgeDistance=null;const d={src:s,time:a,live:n,edgeDistance:r,breakInfo:e,postRoll:!!e&&t(e),onContentReloading:i?.onContentReloading?.bind(i),adPlayer:this.contentElementAdPlayer,reloading:!1,cleanedUp:!1,cancelled:!1,finishingActivity:null,attempt:null};this.sharedRestore=d,e&&"number"==typeof e.start&&i?.onContentResumeSeek?.(n?this.deps.contentPlayer.currentTime:a,e.start+e.duration),this.sharedRestore===d&&(d.reloading=!0,d.onContentReloading?.(!0),this.sharedRestore===d&&this.runSharedRestore(d))}async runSharedRestore(e){for(let t=1;t<=2;t++){const s={phase:"load",deadline:performance.now()+5e3,settle:null};e.attempt=s;const a=await new Promise(t=>{const a=setTimeout(()=>s.settle?.("timeout"),5e3);s.settle=e=>{s.settle&&(s.settle=null,clearTimeout(a),t(e))},this.reloadAndResume(e,s).then(()=>s.settle?.("success"),()=>s.settle?.("rejection"))});if(this.sharedRestore!==e||e.attempt!==s)return;if("success"===a||"cancelled"===a)break;if(2===t?this.deps.diagnose("DA-SHARED-ELEMENT-RESTORE-FAILED",`Content did not resume after the shared-element break: ${s.phase} ${a}`,{breakId:e.breakInfo?.id,live:e.live,attempts:t,phase:s.phase,reason:a}):this.deps.log(`shared-element: content restore ${s.phase} ${a}, retrying once`),this.sharedRestore!==e||e.attempt!==s)return}this.finishSharedRestore(e,!0)}ownsSharedRestoreAttempt(e,t){return!(this.sharedRestore!==e||e.attempt!==t||!t.settle)&&(performance.now()<t.deadline||(t.settle("timeout"),!1))}async reloadAndResume(e,t){const{src:s,time:a,live:n,edgeDistance:r,postRoll:i}=e,d=()=>this.ownsSharedRestoreAttempt(e,t);if(d()&&(await this.deps.contentPlayer.load(s),d())){if(n){if(!i&&null!==r&&r>0){t.phase="live-edge";const e=await this.deps.waitForLiveEdge(d);if(!d())return;if(null!==e){const s=Math.max(e-r,0);if(this.deps.log(`shared-element: live resume ${r.toFixed(2)}s behind the edge (${s.toFixed(2)}s)`),!d())return;t.phase="seek",this.deps.contentPlayer.seek(s)}}}else t.phase="seek",this.deps.contentPlayer.seek(a);d()&&!i&&(t.phase="play",await this.deps.contentPlayer.play(),d())}}finishSharedRestore(e,t){this.sharedRestore===e&&(null===e.finishingActivity?(e.finishingActivity=this.sharedActivityGeneration,e.cleanedUp||(this.state.contentPaused=!1,this.contentElementAdPlayer===e.adPlayer&&this.releaseContentElementAdPlayer(),this.sharedRestore===e&&this.deps.clearContentGate(),this.sharedRestore===e&&this.deps.rebindContentElementIfSwapped(),e.cleanedUp=!0),this.endSharedRestoreReloading(e),e.finishingActivity=null,this.sharedRestore===e&&(!t||e.cancelled||e.postRoll?this.sharedRestore=null:this.armSharedRestoreWatchdog(e))):e.finishingActivity!==this.sharedActivityGeneration&&(this.endSharedRestoreReloading(e),this.sharedRestore===e&&(this.sharedRestore=null)))}endSharedRestoreReloading(e){e.reloading&&(e.reloading=!1,e.onContentReloading?.(!1))}armSharedRestoreWatchdog(e){const t=this.deps.contentPlayer.currentTime;this.sharedRestoreWatchdog=setTimeout(()=>{if(this.sharedRestore!==e)return;this.sharedRestoreWatchdog=null;const s=this.deps.contentPlayer.currentTime-t;(this.deps.contentPlayer.paused||s<1)&&(this.deps.diagnose("DA-CONTENT-RESUME-STALLED",`Content did not resume within 5s of the shared-element restore (paused: ${this.deps.contentPlayer.paused}, advanced: ${s.toFixed(1)}s); nudging play()`,{breakId:e.breakInfo?.id??"?",paused:this.deps.contentPlayer.paused,advancedSec:s}),this.sharedRestore===e&&this.deps.contentPlayer.play().catch(()=>{this.sharedRestore===e&&this.deps.log("shared-element: watchdog play() nudge failed")}))},5e3)}beginSharedActivity(){return this.sharedActivityGeneration++,this.cancelSharedRestore()}cancelSharedRestore(){const e=this.sharedActivityGeneration;this.sharedRestoreGeneration++,this.sharedRestoreWatchdog&&(clearTimeout(this.sharedRestoreWatchdog),this.sharedRestoreWatchdog=null);const t=this.sharedRestore;return t&&(t.cancelled=!0,t.attempt?.settle?.("cancelled"),this.finishSharedRestore(t,!1)),e===this.sharedActivityGeneration}restorableContentSource(){const e=this.deps.contentPlayer.sourceUrl;if(e&&!e.startsWith("blob:"))return e;const t=this.deps.contentPlayer.videoElement,s=t?.currentSrc||t?.src||"";return s.length>0&&!s.startsWith("blob:")?s:null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{OPTIVIEW_ASSET_PARAMETER_MACROS as e,resolveAssetParameterMacro as r}from"./assetParameterMacros";export function buildAssetParameterMacroTable(t){const
|
|
1
|
+
import{OPTIVIEW_ASSET_PARAMETER_MACROS as e,resolveAssetParameterMacro as r}from"./assetParameterMacros";export function buildAssetParameterMacroTable(t){const n={};for(const r of Object.values(e))n[r]=()=>{switch(r){case e.USER_AGENT:return"undefined"!=typeof navigator?navigator.userAgent:void 0;case e.PLAYER_WIDTH:return t.element?String(Math.round(t.element.clientWidth)):void 0;case e.PLAYER_HEIGHT:return t.element?String(Math.round(t.element.clientHeight)):void 0;case e.BREAK_DURATION_MS:return void 0===t.breakDurationSec?void 0:String(Math.round(1e3*t.breakDurationSec));case e.BREAK_DURATION_SECONDS:return void 0===t.breakDurationSec?void 0:String(t.breakDurationSec);default:return}};for(const e of Object.keys(t.customerMacros)){const o=n[e];n[e]=()=>{const n=r(t.customerMacros[e]);return void 0===n?o?.():n}}return n}
|
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
* `unresolved` (the caller diagnoses `DA-ASSET-MACRO-UNKNOWN`).
|
|
17
17
|
* 3. Any other unresolved token is kept literally, since it may be a vendor
|
|
18
18
|
* macro the ad server itself expands, and is not reported.
|
|
19
|
+
* 4. A macro resolving to `null` omits its parameter; GAM `cust_params` drops only
|
|
20
|
+
* the `&`-separated pair containing the macro.
|
|
19
21
|
*
|
|
20
22
|
* Matching is case-sensitive. Who fills the macro table is platform glue: the
|
|
21
23
|
* runtime puts the customer's registered macros in front of the built-in
|
|
@@ -31,13 +33,14 @@ export declare const OPTIVIEW_ASSET_PARAMETER_MACROS: {
|
|
|
31
33
|
readonly BREAK_DURATION_SECONDS: '$OPTIVIEW_BREAK_DURATION_SECONDS$';
|
|
32
34
|
};
|
|
33
35
|
export type AssetParameterMacroScope = 'session' | 'break';
|
|
36
|
+
export type AssetParameterTarget = 'gam' | 'vast';
|
|
34
37
|
export declare const OPTIVIEW_ASSET_PARAMETER_MACRO_SCOPES: Record<string, AssetParameterMacroScope>;
|
|
35
|
-
/** A macro's replacement text, or `undefined` when no value is available. @category Manifest Customization */
|
|
36
|
-
export type AssetParameterMacroValue = string | undefined;
|
|
38
|
+
/** A macro's replacement text, `null` when the parameter is empty, or `undefined` when no value is available. @category Manifest Customization */
|
|
39
|
+
export type AssetParameterMacroValue = string | null | undefined;
|
|
37
40
|
/**
|
|
38
41
|
* A customer macro: a fixed value, or a callback invoked with no arguments
|
|
39
|
-
* right before the URL is built. `
|
|
40
|
-
* through to the built-ins.
|
|
42
|
+
* right before the URL is built. `null` omits parameters that use the macro;
|
|
43
|
+
* `undefined` means "no value" and falls through to the built-ins.
|
|
41
44
|
* @category Manifest Customization */
|
|
42
45
|
export type AssetParameterMacro = AssetParameterMacroValue | (() => AssetParameterMacroValue);
|
|
43
46
|
/** Customer-registered macros, keyed by the full token (`'$CUSTOM_MACRO$'`). @category Manifest Customization */
|
|
@@ -54,12 +57,19 @@ export interface UnresolvedAssetParameterMacro {
|
|
|
54
57
|
macro: string;
|
|
55
58
|
}
|
|
56
59
|
export interface AppliedAssetParameters {
|
|
57
|
-
/** The substituted map, or `undefined` when the input was empty. */
|
|
60
|
+
/** The substituted map, or `undefined` when the input was empty or every key was omitted. */
|
|
58
61
|
params: Record<string, string> | undefined;
|
|
59
62
|
/** Unresolved macros, ordered by sorted parameter key and scan order. */
|
|
60
63
|
unresolved: UnresolvedAssetParameterMacro[];
|
|
64
|
+
/** Omitted parameters, ordered by sorted parameter key, then cust_params pair order. */
|
|
65
|
+
omitted: OmittedAssetParameter[];
|
|
61
66
|
}
|
|
62
|
-
export
|
|
67
|
+
export interface OmittedAssetParameter {
|
|
68
|
+
key: string;
|
|
69
|
+
macro: string;
|
|
70
|
+
pair?: string;
|
|
71
|
+
}
|
|
72
|
+
export declare function applyAssetParameterMacros(params: Record<string, string> | undefined, macros: AssetParameterMacroTable, target: AssetParameterTarget): AppliedAssetParameters;
|
|
63
73
|
/**
|
|
64
74
|
* Append `params` to `url` as `key=value` query parameters, before any
|
|
65
75
|
* `#fragment`, reusing an existing `?`. Keys are sorted so the three cores
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const OPTIVIEW_MACRO_PREFIX="$OPTIVIEW_";export const OPTIVIEW_ASSET_PARAMETER_MACROS={USER_AGENT:"$OPTIVIEW_USER_AGENT$",PLAYER_WIDTH:"$OPTIVIEW_PLAYER_WIDTH$",PLAYER_HEIGHT:"$OPTIVIEW_PLAYER_HEIGHT$",BREAK_DURATION_MS:"$OPTIVIEW_BREAK_DURATION_MS$",BREAK_DURATION_SECONDS:"$OPTIVIEW_BREAK_DURATION_SECONDS$"};export const OPTIVIEW_ASSET_PARAMETER_MACRO_SCOPES={[OPTIVIEW_ASSET_PARAMETER_MACROS.USER_AGENT]:"session",[OPTIVIEW_ASSET_PARAMETER_MACROS.PLAYER_WIDTH]:"session",[OPTIVIEW_ASSET_PARAMETER_MACROS.PLAYER_HEIGHT]:"session",[OPTIVIEW_ASSET_PARAMETER_MACROS.BREAK_DURATION_MS]:"break",[OPTIVIEW_ASSET_PARAMETER_MACROS.BREAK_DURATION_SECONDS]:"break"};export function omitBreakScopedParameters(e){if(!e)return;const t=Object.fromEntries(Object.entries(e).filter(([,e])=>!Object.entries(OPTIVIEW_ASSET_PARAMETER_MACRO_SCOPES).some(([t,
|
|
1
|
+
export const OPTIVIEW_MACRO_PREFIX="$OPTIVIEW_";export const OPTIVIEW_ASSET_PARAMETER_MACROS={USER_AGENT:"$OPTIVIEW_USER_AGENT$",PLAYER_WIDTH:"$OPTIVIEW_PLAYER_WIDTH$",PLAYER_HEIGHT:"$OPTIVIEW_PLAYER_HEIGHT$",BREAK_DURATION_MS:"$OPTIVIEW_BREAK_DURATION_MS$",BREAK_DURATION_SECONDS:"$OPTIVIEW_BREAK_DURATION_SECONDS$"};export const OPTIVIEW_ASSET_PARAMETER_MACRO_SCOPES={[OPTIVIEW_ASSET_PARAMETER_MACROS.USER_AGENT]:"session",[OPTIVIEW_ASSET_PARAMETER_MACROS.PLAYER_WIDTH]:"session",[OPTIVIEW_ASSET_PARAMETER_MACROS.PLAYER_HEIGHT]:"session",[OPTIVIEW_ASSET_PARAMETER_MACROS.BREAK_DURATION_MS]:"break",[OPTIVIEW_ASSET_PARAMETER_MACROS.BREAK_DURATION_SECONDS]:"break"};export function omitBreakScopedParameters(e){if(!e)return;const t=Object.fromEntries(Object.entries(e).filter(([,e])=>!Object.entries(OPTIVIEW_ASSET_PARAMETER_MACRO_SCOPES).some(([t,o])=>"break"===o&&e.includes(t))));return Object.keys(t).length>0?t:void 0}export function resolveAssetParameterMacro(e){return"function"==typeof e?e():e}export function applyAssetParameterMacros(o,n,r){const s=o??{},E={},i=[],_=[];for(const o of Object.keys(s).sort()){if("gam"===r&&"cust_params"===o){const e=t(s[o],n);void 0!==e.value&&(E[o]=e.value),_.push(...e.omitted.map(({macro:e,pair:t})=>({key:o,macro:e,pair:t}))),i.push(...e.unresolved.map(e=>({key:o,macro:e})));continue}const A=e(s[o],n);void 0===A.omittedBy?(E[o]=A.value,i.push(...A.unresolved.map(e=>({key:o,macro:e})))):_.push({key:o,macro:A.omittedBy})}return{params:Object.keys(E).length>0?E:void 0,unresolved:i,omitted:_}}function e(e,t){let o="",r=0;const s=[],E=new Set;for(;r<e.length;){const i=e.indexOf("$",r);if(-1===i){o+=e.slice(r);break}o+=e.slice(r,i);const _=n(e,i);if(void 0===_){o+="$",r=i+1;continue}const A=t[_]?.();if(null===A)return{value:"",unresolved:[],omittedBy:_};void 0!==A?o+=A:(o+=_,!_.startsWith("$OPTIVIEW_")&&!(_ in t)||E.has(_)||(s.push(_),E.add(_))),r=i+_.length}return{value:o,unresolved:s}}function t(t,o){const n=[],r=[],s=[];for(const E of t.split("&")){const t=e(E,o);void 0===t.omittedBy?(n.push(t.value),r.push(...t.unresolved)):s.push({macro:t.omittedBy,pair:E})}return{value:n.length>0?n.join("&"):void 0,unresolved:r,omitted:s}}function o(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"||e>="0"&&e<="9"||"_"===e}function n(e,t){let n=t+1;for(;n<e.length&&o(e[n]);)n++;return n>t+1&&"$"===e[n]?e.slice(t,n+1):void 0}export function appendQueryParameters(e,t){const o=t??{},n=Object.keys(o).sort();if(0===n.length)return e;if(/^data:/i.test(e))return e;const r=n.map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),s=e.indexOf("#"),E=-1===s?e:e.slice(0,s),i=-1===s?"":e.slice(s),_=E.includes("?")?E.endsWith("?")||E.endsWith("&")?"":"&":"?";return`${E}${_}${r}${i}`}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { PlayerAdapter } from '../interfaces/PlayerAdapter';
|
|
2
|
-
import {
|
|
2
|
+
import { AssetParameterMacro, AssetParameterMacros } from '../services/assetParameterMacros';
|
|
3
3
|
import { BreakManifest } from './BreakManifest';
|
|
4
4
|
/**
|
|
5
5
|
* Factory for a custom ad player: create media elements inside the supplied container
|
|
@@ -380,11 +380,14 @@ export interface SessionConfig {
|
|
|
380
380
|
* `{ '$CUSTOM_TEAM$': () => currentTeam() }`. Every `$NAME$` token inside a
|
|
381
381
|
* manifest / session / update value is replaced when the ad request is built,
|
|
382
382
|
* so `"$OPTIVIEW_PLAYER_WIDTH$x$OPTIVIEW_PLAYER_HEIGHT$"` becomes `"1920x1080"`.
|
|
383
|
-
* Customer macros are consulted before the built-in `$OPTIVIEW_*` set, so a
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
383
|
+
* Customer macros are consulted before the built-in `$OPTIVIEW_*` set, so a built-in can be
|
|
384
|
+
* overridden. A string replaces the token. `null` omits the parameter; for GAM `cust_params`,
|
|
385
|
+
* only the containing pair is dropped and the key is omitted if no pair remains. For VAST,
|
|
386
|
+
* the whole `cust_params` parameter is omitted. `undefined` leaves an unresolved token literal
|
|
387
|
+
* and sends the parameter. `DA-ASSET-MACRO-UNKNOWN` reports
|
|
388
|
+
* unresolved built-in or registered macros; `DA-ASSET-PARAMETER-OMITTED` reports null omissions.
|
|
389
|
+
* Other unresolved `$NAME$` tokens stay literal without a diagnostic. `$` without a closing `$`
|
|
390
|
+
* is unchanged.
|
|
388
391
|
* Callbacks are evaluated per ad request and cleared when the session ends.
|
|
389
392
|
* Session-scoped parameters are sent to IMA DAI with
|
|
390
393
|
* built-in and customer macros resolved; break-duration macros are omitted.
|
|
@@ -394,10 +397,11 @@ export interface SessionConfig {
|
|
|
394
397
|
assetParameterMacros?: AssetParameterMacros;
|
|
395
398
|
}
|
|
396
399
|
/**
|
|
397
|
-
* Per-name update for {@link SessionConfig.assetParameterMacros}
|
|
398
|
-
* `null`
|
|
400
|
+
* Per-name update for {@link SessionConfig.assetParameterMacros}. A value or callback replaces the
|
|
401
|
+
* macro; `null` marks it empty (parameters that use it are not sent); `undefined` removes the
|
|
402
|
+
* customer macro so the macro table's unresolved or built-in fall-through behavior applies again.
|
|
399
403
|
* @category Configuration */
|
|
400
|
-
export type AssetParameterMacroUpdates = Record<string,
|
|
404
|
+
export type AssetParameterMacroUpdates = Record<string, AssetParameterMacro | undefined>;
|
|
401
405
|
/**
|
|
402
406
|
* Per-session configuration for `mode: 'ssai'`: keyed on the stitched master URL instead of a
|
|
403
407
|
* manifest URL. The SDK appends `stream_id`, `max_bitrate` and extra params and never rebuilds the path.
|