@dolby-optiview/ads-sdk-core 1.1.0 → 1.2.0
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 +8 -4
- package/dist/OptiViewAds.js +1 -1
- package/dist/OptiViewAdsExternalVendors.d.ts +47 -0
- package/dist/OptiViewAdsExternalVendors.js +1 -0
- package/dist/generated/diagnosticCodes.d.ts +118 -3
- package/dist/generated/diagnosticCodes.js +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/id3/index.d.ts +1 -0
- package/dist/id3/index.js +1 -1
- package/dist/id3/parseId3TextFrames.d.ts +8 -0
- package/dist/id3/parseId3TextFrames.js +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/dist/interfaces/PlayerAdapter.d.ts +5 -0
- package/dist/services/AdBreakSequencer.js +1 -1
- package/dist/services/AdPlayerController.d.ts +8 -1
- package/dist/services/AdPlayerController.js +1 -1
- package/dist/services/BreakScheduler.d.ts +31 -56
- package/dist/services/BreakScheduler.js +1 -1
- package/dist/services/BreakSchedulerTypes.d.ts +55 -0
- package/dist/services/BreakSchedulerTypes.js +1 -0
- package/dist/services/ExternalVendorConfigurationTracker.d.ts +13 -0
- package/dist/services/ExternalVendorConfigurationTracker.js +1 -0
- package/dist/services/GamStreamManager.d.ts +6 -0
- package/dist/services/GamStreamManager.js +1 -1
- package/dist/services/ImaMetadataDeduplicator.d.ts +5 -0
- package/dist/services/ImaMetadataDeduplicator.js +1 -0
- package/dist/services/MetadataCueTracker.d.ts +27 -1
- package/dist/services/MetadataCueTracker.js +1 -1
- package/dist/services/SsaiController.d.ts +2 -0
- package/dist/services/SsaiController.js +1 -1
- package/dist/services/adPlayer/AdPlayerEvents.js +1 -1
- package/dist/services/adPlayer/AdPlayerState.d.ts +13 -0
- package/dist/services/adPlayer/AdPlayerState.js +1 -1
- package/dist/services/adPlayer/AdPreloader.js +1 -1
- package/dist/services/adPlayer/AdStage.d.ts +7 -3
- package/dist/services/adPlayer/AdStage.js +1 -1
- package/dist/services/adPlayer/AssetParameterResolver.d.ts +2 -0
- package/dist/services/adPlayer/AssetParameterResolver.js +1 -1
- package/dist/services/adPlayer/AssetPlayback.js +1 -1
- package/dist/services/adPlayer/ContentRecovery.js +1 -1
- package/dist/services/adPlayer/ContentResumeCoordinator.d.ts +50 -3
- package/dist/services/adPlayer/ContentResumeCoordinator.js +1 -1
- package/dist/services/adPlayer/GamPodBridge.js +1 -1
- package/dist/services/adPlayer/SharedElementBreakPlayer.js +1 -1
- package/dist/services/adPlayer/VariantSelector.js +1 -1
- package/dist/services/adPlayer/pdtClockResume.d.ts +57 -0
- package/dist/services/adPlayer/pdtClockResume.js +1 -0
- package/dist/services/adPlayer/streamClockMapping.d.ts +65 -0
- package/dist/services/adPlayer/streamClockMapping.js +1 -0
- package/dist/services/adPlayer/streamClockResume.d.ts +94 -0
- package/dist/services/adPlayer/streamClockResume.js +1 -0
- package/dist/services/anvatoCueRuntime.d.ts +12 -0
- package/dist/services/anvatoCueRuntime.js +1 -1
- package/dist/services/assetParameterMacros.d.ts +0 -1
- package/dist/services/assetParameterMacros.js +1 -1
- package/dist/services/breakTiming.d.ts +9 -0
- package/dist/services/breakTiming.js +1 -1
- package/dist/services/channelSwitch.d.ts +3 -1
- package/dist/services/channelSwitch.js +1 -1
- package/dist/services/detectDeviceType.d.ts +7 -2
- package/dist/services/detectDeviceType.js +1 -1
- package/dist/services/diagnosticReport.d.ts +3 -0
- package/dist/services/diagnosticReport.js +1 -0
- package/dist/services/externalVendorConfigurationGetter.d.ts +12 -0
- package/dist/services/externalVendorConfigurationGetter.js +1 -0
- package/dist/services/matchTargeting.d.ts +19 -0
- package/dist/services/matchTargeting.js +1 -0
- package/dist/services/resolveDeliveryMode.d.ts +3 -1
- package/dist/services/resolveDeliveryMode.js +1 -1
- package/dist/services/resolveExternalVendorConfigurations.d.ts +20 -0
- package/dist/services/resolveExternalVendorConfigurations.js +1 -0
- package/dist/services/resolveGamVendorConfiguration.js +1 -1
- package/dist/services/resolveResumeClamp.d.ts +42 -0
- package/dist/services/resolveResumeClamp.js +1 -0
- package/dist/services/resolveTargetedUri.d.ts +2 -1
- package/dist/services/resolveTargetedUri.js +1 -1
- package/dist/services/selectVariant.d.ts +4 -0
- package/dist/services/selectVariant.js +1 -1
- package/dist/services/toPlaybackError.d.ts +1 -0
- package/dist/services/toPlaybackError.js +1 -0
- package/dist/services/wallclockBreakWindow.d.ts +41 -0
- package/dist/services/wallclockBreakWindow.js +1 -0
- package/dist/session/BreakLifecycle.d.ts +2 -0
- package/dist/session/BreakLifecycle.js +1 -1
- package/dist/session/SessionStarter.d.ts +6 -1
- package/dist/session/SessionStarter.js +1 -1
- package/dist/session/SessionState.d.ts +1 -0
- package/dist/session/SessionState.js +1 -1
- package/dist/types/BreakManifest.d.ts +39 -1
- package/dist/types/BreakManifest.js +1 -1
- package/dist/types/Events.d.ts +16 -1
- package/dist/types/ExternalVendorConfiguration.d.ts +5 -0
- package/dist/types/ExternalVendorConfiguration.js +1 -0
- package/dist/types/OptiViewAdsConfig.d.ts +2 -1
- package/package.json +1 -1
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { BreakManifest } from '../types/BreakManifest';
|
|
2
|
+
import type { ExternalVendorConfigurationsResult } from './resolveExternalVendorConfigurations';
|
|
3
|
+
import type { ExternalVendorConfiguration } from './resolveExternalVendorConfigurations';
|
|
4
|
+
import type { ExternalVendorConfigurationChangeEvent } from '../types/Events';
|
|
5
|
+
export declare class ExternalVendorConfigurationTracker {
|
|
6
|
+
private readonly emit;
|
|
7
|
+
private templates;
|
|
8
|
+
constructor(emit: (provider: string) => void);
|
|
9
|
+
get entries(): ExternalVendorConfiguration[];
|
|
10
|
+
adopt(manifest: BreakManifest): ExternalVendorConfigurationsResult;
|
|
11
|
+
reset(): void;
|
|
12
|
+
}
|
|
13
|
+
export declare function createExternalVendorConfigurationTracker(emit: (event: ExternalVendorConfigurationChangeEvent) => void): ExternalVendorConfigurationTracker;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{changedExternalVendorProviders as e,resolveExternalVendorConfigurations as t}from"./resolveExternalVendorConfigurations";export class ExternalVendorConfigurationTracker{constructor(e){this.emit=e,this.templates=[]}get entries(){return this.templates.map(e=>({provider:e.provider,assetParameters:{...e.assetParameters}}))}adopt(r){const n=t(r),o=e(this.templates,n.entries);this.templates=n.entries;for(const e of o)this.emit(e);return n}reset(){this.templates=[]}}export function createExternalVendorConfigurationTracker(e){return new ExternalVendorConfigurationTracker(t=>e({type:"externalvendorconfigurationchange",provider:t,timestamp:Date.now()}))}
|
|
@@ -12,7 +12,9 @@ export interface GamAdEventCallbacks {
|
|
|
12
12
|
onAdMidpoint?: () => void;
|
|
13
13
|
onAdThirdQuartile?: () => void;
|
|
14
14
|
onError?: (message: string) => void;
|
|
15
|
+
onDuplicateMetadata?: (startTime: number) => void;
|
|
15
16
|
}
|
|
17
|
+
export declare const GAM_DUPLICATE_METADATA_DIAGNOSTIC_MESSAGE = "The stream carries the same ad marker more than once at the same time (for example in both the audio and video renditions of an fMP4 stream); the duplicate was not passed to IMA, so each ad event fires once. Reported once per stream session.";
|
|
16
18
|
/** Configuration for GamStreamManager initialization. */
|
|
17
19
|
export interface GamStreamConfig {
|
|
18
20
|
networkCode: string;
|
|
@@ -37,6 +39,9 @@ export declare class GamStreamManager {
|
|
|
37
39
|
private initPromise;
|
|
38
40
|
private debug;
|
|
39
41
|
private callbacks;
|
|
42
|
+
private metadataDeduplicator;
|
|
43
|
+
private markerTextDeduplicator;
|
|
44
|
+
private duplicateMetadataReported;
|
|
40
45
|
constructor(videoElement: HTMLVideoElement, adUiContainer?: HTMLElement | undefined, debug?: boolean);
|
|
41
46
|
/** Set callbacks for ad events. */
|
|
42
47
|
setCallbacks(callbacks: GamAdEventCallbacks): void;
|
|
@@ -57,6 +62,7 @@ export declare class GamStreamManager {
|
|
|
57
62
|
replaceAdTagParameters(params: Record<string, string>): void;
|
|
58
63
|
/** Forward a timed-metadata marker to IMA for SSAI ad tracking. Prefers raw ID3 bytes (IMA parses them itself). */
|
|
59
64
|
processTimedMetadata(cue: TimedMetadataCue): void;
|
|
65
|
+
private acceptMetadata;
|
|
60
66
|
/** Build a pod manifest URL with the current streamId. Throws if not initialized. */
|
|
61
67
|
buildPodUrl(podId: string, durationSeconds: number, params: GamVendorParameters): string;
|
|
62
68
|
/** Reset before starting a new playback session. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildGamPodUrl as t}from"./GamPodUrlBuilder";import{debugLog as e}from"../diagnostics/debugLog";export class GamStreamManager{constructor(t,e,
|
|
1
|
+
import{buildGamPodUrl as t}from"./GamPodUrlBuilder";import{debugLog as e}from"../diagnostics/debugLog";import{ImaMetadataDeduplicator as a}from"./ImaMetadataDeduplicator";import{parseId3TextFrames as i}from"../id3/parseId3TextFrames";export const GAM_DUPLICATE_METADATA_DIAGNOSTIC_MESSAGE="The stream carries the same ad marker more than once at the same time (for example in both the audio and video renditions of an fMP4 stream); the duplicate was not passed to IMA, so each ad event fires once. Reported once per stream session.";export class GamStreamManager{constructor(t,e,i=!1){this.videoElement=t,this.adUiContainer=e,this.streamManager=null,this.streamId=null,this.config=null,this.initPromise=null,this.callbacks={},this.metadataDeduplicator=new a,this.markerTextDeduplicator=new a,this.duplicateMetadataReported=!1,this.debug=i}setCallbacks(t){this.callbacks=t}isImaSdkAvailable(){return"undefined"!=typeof google&&void 0!==google.ima&&void 0!==google.ima.dai&&void 0!==google.ima.dai.api}async initialize(t){return this.streamManager&&this.reset(),this.config=t,this.initPromise=this.doInitialize(),this.initPromise}async initializeLiveStream(t){if(this.streamManager&&this.reset(),!this.isImaSdkAvailable())throw new Error('Google IMA DAI SDK not found. Include <script src="https://imasdk.googleapis.com/js/sdkloader/ima3_dai.js"><\/script> in your page.');const e=this.adUiContainer||this.videoElement.parentElement||document.body;this.streamManager=new google.ima.dai.api.StreamManager(this.videoElement,e);const a=new google.ima.dai.api.LiveStreamRequest;return a.assetKey=t.assetKey,a.format="hls",t.networkCode&&(a.networkCode=t.networkCode),t.adTagParameters&&(a.adTagParameters=t.adTagParameters),t.streamActivityMonitorId&&(a.streamActivityMonitorId=t.streamActivityMonitorId),new Promise((e,i)=>{this.setupEventListeners(void 0,i,t=>e(t)),this.log(`Requesting live stream for asset: ${t.assetKey}`),this.streamManager.requestStream(a)})}async doInitialize(){if(!this.isImaSdkAvailable())throw new Error('Google IMA DAI SDK not found. Include <script src="https://imasdk.googleapis.com/js/sdkloader/ima3_dai.js"><\/script> in your page.');if(!this.config)throw new Error("GamStreamManager config not set");this.log("Initializing IMA StreamManager...");const t=this.adUiContainer||this.videoElement.parentElement||document.body;this.streamManager=new google.ima.dai.api.StreamManager(this.videoElement,t);const e=new google.ima.dai.api.PodStreamRequest;return e.networkCode=this.config.networkCode,e.customAssetKey=this.config.customAssetKey,e.format="hls",this.config.adTagParameters&&(e.adTagParameters=this.config.adTagParameters),this.config.streamActivityMonitorId&&(e.streamActivityMonitorId=this.config.streamActivityMonitorId),new Promise((t,a)=>{this.setupEventListeners(t,a),this.log(`Requesting stream for network: ${this.config.networkCode}, asset: ${this.config.customAssetKey}`),this.streamManager.requestStream(e)})}setupEventListeners(t,e,a){if(!this.streamManager)return;const i=google.ima.dai.api.StreamEvent.Type;this.streamManager.addEventListener(i.STREAM_INITIALIZED,e=>{const a=e.getStreamData();this.streamId=a.streamId,this.log(`Stream initialized, streamId: ${this.streamId}`),t?.()}),this.streamManager.addEventListener(i.LOADED,t=>{const e=t.getStreamData();this.streamId=e.streamId,e.url&&(this.log(`Stream loaded, url: ${e.url}`),a?.(e.url))}),this.streamManager.addEventListener(i.AD_BREAK_STARTED,()=>{this.log("Ad break started"),this.callbacks.onAdBreakStarted?.()}),this.streamManager.addEventListener(i.AD_BREAK_ENDED,()=>{this.log("Ad break ended"),this.callbacks.onAdBreakEnded?.()}),this.streamManager.addEventListener(i.STARTED,t=>{const e=function(t){const e=t.getAd?.();if(!e)return;const a=e.getAdPodInfo?.();return{adPosition:a?.getAdPosition(),totalAds:a?.getTotalAds(),adId:e.getAdId?.(),creativeId:e.getCreativeId?.(),duration:e.getDuration?.()}}(t);this.log(`Ad started (ad ${e?.adPosition??"?"} of ${e?.totalAds??"?"})`),this.callbacks.onAdStarted?.(e)}),this.streamManager.addEventListener(i.COMPLETE,()=>{this.log("Ad complete"),this.callbacks.onAdComplete?.()}),this.streamManager.addEventListener(i.FIRST_QUARTILE,()=>{this.log("Ad first quartile"),this.callbacks.onAdFirstQuartile?.()}),this.streamManager.addEventListener(i.MIDPOINT,()=>{this.log("Ad midpoint"),this.callbacks.onAdMidpoint?.()}),this.streamManager.addEventListener(i.THIRD_QUARTILE,()=>{this.log("Ad third quartile"),this.callbacks.onAdThirdQuartile?.()}),this.streamManager.addEventListener(i.ERROR,t=>{const a=t.getStreamData().errorMessage||"Unknown IMA error";this.log(`IMA error: ${a}`),e?.(new Error(`IMA stream initialization failed: ${a}`)),this.callbacks.onError?.(a)})}getStreamId(){return this.streamId}isInitialized(){return null!==this.streamId}replaceAdTagParameters(t){this.streamManager&&this.streamId?(this.streamManager.replaceAdTagParameters(t),this.log("Ad tag parameters replaced")):this.log("replaceAdTagParameters called but stream not initialized — ignoring")}processTimedMetadata(t){if(!this.streamManager)return;if(t.raw&&t.raw.length>0){if("presented"===t.phase)return;if(!this.acceptMetadata(`id3:${Array.from(t.raw).join(",")}`,t.startTime))return;const e=i(t.raw);if(e.length>0&&!this.markerTextDeduplicator.accept(`marker:${e.join("\0")}`,t.startTime))return;return void this.streamManager.processMetadata("ID3",t.raw,t.startTime)}if("parsed"===t.phase)return;const e=t.frames?.TXXX??t.messageData;if(t.frames&&Object.keys(t.frames).length>0){if(!this.acceptMetadata(`txt:${JSON.stringify(t.frames)}`,t.startTime))return;if(void 0!==e&&!this.markerTextDeduplicator.accept(`marker:${e}`,t.startTime))return;this.streamManager.onTimedMetadata(t.frames)}else if(t.messageData){if(!this.acceptMetadata(`txt:${t.messageData}`,t.startTime))return;if(!this.markerTextDeduplicator.accept(`marker:${t.messageData}`,t.startTime))return;this.streamManager.onTimedMetadata({TXXX:t.messageData})}}acceptMetadata(t,e){return!!this.metadataDeduplicator.accept(t,e)||(this.duplicateMetadataReported||(this.duplicateMetadataReported=!0,this.callbacks.onDuplicateMetadata?.(e)),!1)}buildPodUrl(e,a,i){if(!this.streamId)throw new Error("GamStreamManager not initialized. Call initialize() first.");const r=t(e,i,this.streamId,a);return this.log(`Built pod URL: ${r}`),r}reset(){this.streamManager&&this.streamManager.reset(),this.streamId=null,this.initPromise=null,this.streamManager=null,this.metadataDeduplicator.reset(),this.markerTextDeduplicator.reset(),this.duplicateMetadataReported=!1,this.log("Stream manager reset")}destroy(){this.reset(),this.config=null,this.callbacks={}}log(t){this.debug&&e(`[GamStreamManager] ${t}`)}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class ImaMetadataDeduplicator{constructor(){this.entries=[]}accept(e,t){if(!Number.isFinite(t))return!0;return!this.entries.some(s=>s.key===e&&Math.abs(s.time-t)<=.5)&&(this.entries.push({key:e,time:t}),this.entries.length>64&&this.entries.shift(),!0)}reset(){this.entries=[]}}
|
|
@@ -11,6 +11,20 @@ export declare const ID3_IN_EMSG_SCHEME_ID_URIS: readonly string[];
|
|
|
11
11
|
export declare function isId3InEmsgScheme(schemeIdUri: string | undefined): boolean;
|
|
12
12
|
/** Tolerance (seconds) matching a manifest `start` PTS to a cue `pts`; encoder/backend rounding differs sub-millisecond. */
|
|
13
13
|
export declare const PTS_MATCH_TOLERANCE_SECONDS = 0.005;
|
|
14
|
+
/**
|
|
15
|
+
* Tolerance (seconds) between a break's duration and its stream-signalled length (`cue_end` pts −
|
|
16
|
+
* break start pts). NFL Channel signalled 150.166–150.293s for 150s breaks (splice segments).
|
|
17
|
+
*/
|
|
18
|
+
export declare const BREAK_END_LENGTH_TOLERANCE_SECONDS = 2;
|
|
19
|
+
/** The stream's own end of a break: the `type=cue_end` cue matched to it on the stream clock. */
|
|
20
|
+
export interface BreakEndMatch {
|
|
21
|
+
/** Media time (seconds) the `cue_end` was reported at, in the player's mapping at delivery. */
|
|
22
|
+
mediaTime: number;
|
|
23
|
+
/** Break length on the stream clock, `cue_end` pts − break start pts, in seconds. */
|
|
24
|
+
lengthSec: number;
|
|
25
|
+
/** `lengthSec` is within {@link BREAK_END_LENGTH_TOLERANCE_SECONDS} of the break duration. */
|
|
26
|
+
accepted: boolean;
|
|
27
|
+
}
|
|
14
28
|
/** Anvato marker: GEOB with description "Anvatos" (MIME `application/json` when surfaced) or emsg with the Anvato scheme. */
|
|
15
29
|
export declare function isAnvatoCue(cue: TimedMetadataCue): boolean;
|
|
16
30
|
/**
|
|
@@ -41,11 +55,23 @@ export declare class MetadataCueTracker {
|
|
|
41
55
|
private readonly diagnose?;
|
|
42
56
|
/** Observed cue `pts` parameter (seconds) → cue media time (seconds). */
|
|
43
57
|
private mediaTimeByPts;
|
|
58
|
+
/** Observed `type=cue_end` `pts` → media time; the latest delivery wins. */
|
|
59
|
+
private endMediaTimeByPts;
|
|
44
60
|
private segmentAnchoredDiagnosed;
|
|
45
61
|
private offsetRejectedPts;
|
|
46
62
|
constructor(diagnose?: CueTrackerDiagnose | undefined);
|
|
47
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* Ignores non-Anvato cues, payloads other than `type=cue` / `type=cue_end`, and non-finite `pts`.
|
|
65
|
+
* True when a cue was recorded or refreshed.
|
|
66
|
+
*/
|
|
48
67
|
handleCue(cue: TimedMetadataCue): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* The `cue_end` closest to ending the break that starts at `startPts` and lasts `durationSec`,
|
|
70
|
+
* judged on the stream clock so a player remap cannot move it. The pts difference is read as
|
|
71
|
+
* seconds and as milliseconds; only a length between half and twice the duration is a candidate.
|
|
72
|
+
* Ties resolve to the lower `cue_end` pts. Null when there is no candidate.
|
|
73
|
+
*/
|
|
74
|
+
breakEnd(startPts: number, durationSec: number): BreakEndMatch | null;
|
|
49
75
|
private resolveMediaTime;
|
|
50
76
|
/**
|
|
51
77
|
* Media time of the cue matching `pts` within {@link PTS_MATCH_TOLERANCE_SECONDS}, or null.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeUtf8 as e,parseId3GeobFrames as t}from"../id3/parseId3Geob";export const ANVATO_ID3_DESCRIPTION="Anvatos";export const ANVATO_ID3_MIME_TYPE="application/json";export const ANVATO_EMSG_SCHEME_ID_URI="urn:anvato:es1:052016";export const ID3_IN_EMSG_SCHEME_ID_URIS=["https://aomedia.org/emsg/ID3","https://developer.apple.com/streaming/emsg-id3"];export function isId3InEmsgScheme(e){return void 0!==e&&ID3_IN_EMSG_SCHEME_ID_URIS.includes(e)}export const PTS_MATCH_TOLERANCE_SECONDS=.005;export function isAnvatoCue(e){return"id3"===e.type?"Anvatos"===e.description&&(void 0===e.mimeType||"application/json"===e.mimeType):"emsg"===e.type&&"urn:anvato:es1:052016"===e.schemeIdUri}export function anvatoPayloadFromCue(s){if(isAnvatoCue(s))return s.messageData??null;if("emsg"===s.type&&isId3InEmsgScheme(s.schemeIdUri)&&s.raw)for(const i of t(s.raw))if("Anvatos"===i.description&&"application/json"===i.mimeType)return e(i.data);return null}export function parseAnvatoPayload(e){const t={};for(const i of e.split("&")){if(""===i)continue;const e=i.indexOf("="),n=-1===e?i:i.slice(0,e),o=-1===e?"":i.slice(e+1),r=s(n);r in t||(t[r]=s(o))}return t}function s(e){const t=e.replace(/\+/g," ");try{return decodeURIComponent(t)}catch{return t}}export const PTS_OFFSET_MIN_LEAD_SECONDS=.1;export const PTS_OFFSET_MAX_LAG_SECONDS=15;export class MetadataCueTracker{constructor(e){this.diagnose=e,this.mediaTimeByPts=new Map,this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts=new Set}handleCue(e){if(!Number.isFinite(e.startTime))return!1;const t=anvatoPayloadFromCue(e);if(!t)return!1;const s=parseAnvatoPayload(t);if("cue"!==
|
|
1
|
+
import{decodeUtf8 as e,parseId3GeobFrames as t}from"../id3/parseId3Geob";export const ANVATO_ID3_DESCRIPTION="Anvatos";export const ANVATO_ID3_MIME_TYPE="application/json";export const ANVATO_EMSG_SCHEME_ID_URI="urn:anvato:es1:052016";export const ID3_IN_EMSG_SCHEME_ID_URIS=["https://aomedia.org/emsg/ID3","https://developer.apple.com/streaming/emsg-id3"];export function isId3InEmsgScheme(e){return void 0!==e&&ID3_IN_EMSG_SCHEME_ID_URIS.includes(e)}export const PTS_MATCH_TOLERANCE_SECONDS=.005;export const BREAK_END_LENGTH_TOLERANCE_SECONDS=2;export function isAnvatoCue(e){return"id3"===e.type?"Anvatos"===e.description&&(void 0===e.mimeType||"application/json"===e.mimeType):"emsg"===e.type&&"urn:anvato:es1:052016"===e.schemeIdUri}export function anvatoPayloadFromCue(s){if(isAnvatoCue(s))return s.messageData??null;if("emsg"===s.type&&isId3InEmsgScheme(s.schemeIdUri)&&s.raw)for(const i of t(s.raw))if("Anvatos"===i.description&&"application/json"===i.mimeType)return e(i.data);return null}export function parseAnvatoPayload(e){const t={};for(const i of e.split("&")){if(""===i)continue;const e=i.indexOf("="),n=-1===e?i:i.slice(0,e),o=-1===e?"":i.slice(e+1),r=s(n);r in t||(t[r]=s(o))}return t}function s(e){const t=e.replace(/\+/g," ");try{return decodeURIComponent(t)}catch{return t}}export const PTS_OFFSET_MIN_LEAD_SECONDS=.1;export const PTS_OFFSET_MAX_LAG_SECONDS=15;export class MetadataCueTracker{constructor(e){this.diagnose=e,this.mediaTimeByPts=new Map,this.endMediaTimeByPts=new Map,this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts=new Set}handleCue(e){if(!Number.isFinite(e.startTime))return!1;const t=anvatoPayloadFromCue(e);if(!t)return!1;const s=parseAnvatoPayload(t),i=s.type;if("cue"!==i&&"cue_end"!==i)return!1;const n=Number(s.pts);if(!Number.isFinite(n))return!1;return("cue"===i?this.mediaTimeByPts:this.endMediaTimeByPts).set(n,this.resolveMediaTime(e,n)),!0}breakEnd(e,t){if(!(Number.isFinite(e)&&t>0))return null;let s=null;for(const[i,n]of this.endMediaTimeByPts){const o=i-e;for(const e of[o,o/1e3]){if(e<t/2||e>2*t)continue;const o=Math.abs(e-t);if(null===s||o<s.distance||o===s.distance&&i<s.endPts){s={endPts:i,distance:o,match:{mediaTime:n,lengthSec:e,accepted:o<=2}}}}}return null===s?null:s.match}resolveMediaTime(e,t){const s=e.ptsOffset;if("number"!=typeof s||!Number.isFinite(s))return"urn:anvato:es1:052016"!==e.schemeIdUri||this.segmentAnchoredDiagnosed||(this.segmentAnchoredDiagnosed=!0,this.diagnose?.("DA-ANVATO-CUE-SEGMENT-ANCHORED",`Anvato emsg cue pts=${t} has no ptsOffset; scheduling it at its segment start ${e.startTime}s, which can be up to one segment early.`,{pts:t,mediaTime:e.startTime})),e.startTime;const i=t=>t>=e.startTime-.1&&t<=e.startTime+15,n=t+s;if(i(n))return n;const o=t/1e3+s;return i(o)?o:(this.offsetRejectedPts.has(t)||(this.offsetRejectedPts.add(t),this.diagnose?.("DA-ANVATO-CUE-OFFSET-REJECTED",`Anvato cue pts=${t} maps to ${n}s with ptsOffset ${s}, outside its segment window from ${e.startTime}s; using the segment start.`,{pts:t,startTime:e.startTime,ptsOffset:s,mappedTime:n})),e.startTime)}mediaTimeForPts(e){let t=null,s=1/0;for(const i of this.mediaTimeByPts.keys()){const n=Math.abs(i-e);n>.005||(n<s||n===s&&i<t)&&(t=i,s=n)}return null===t?null:this.mediaTimeByPts.get(t)}get size(){return this.mediaTimeByPts.size}clear(){this.mediaTimeByPts.clear(),this.endMediaTimeByPts.clear(),this.segmentAnchoredDiagnosed=!1,this.offsetRejectedPts.clear()}}
|
|
@@ -3,6 +3,7 @@ import type { AssetParameterMacroUpdates, GamConfig, SsaiConfig, SsaiSessionConf
|
|
|
3
3
|
import type { StitchedStreamVendor } from './resolveDeliveryMode';
|
|
4
4
|
import { AssetParameterMacros } from './assetParameterMacros';
|
|
5
5
|
import type { OptiViewAdsEventMap, OptiViewAdsEventType } from '../types/Events';
|
|
6
|
+
import type { ExternalVendorConfiguration } from './resolveExternalVendorConfigurations';
|
|
6
7
|
/** Org-level options the SSAI controller needs from the SDK config. */
|
|
7
8
|
export interface SsaiControllerOptions {
|
|
8
9
|
gam: GamConfig;
|
|
@@ -45,6 +46,7 @@ export declare class SsaiController {
|
|
|
45
46
|
startSteered(vendor: StitchedStreamVendor, sessionConfigParameters?: Record<string, string>, macros?: AssetParameterMacros): Promise<void>;
|
|
46
47
|
private resolveAdTagParameters;
|
|
47
48
|
updateAssetParameters(params: Record<string, string>): void;
|
|
49
|
+
resolveExternalVendorConfiguration(entry: ExternalVendorConfiguration): ExternalVendorConfiguration;
|
|
48
50
|
updateAssetParameterMacros(macros: AssetParameterMacroUpdates): void;
|
|
49
51
|
get sessionAssetParameterMacros(): AssetParameterMacros;
|
|
50
52
|
setManifestAssetParameters(params: Record<string, string> | undefined): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{objectEntries as e}from"./runtimeObject";import{applyAssetParameterMacros as t
|
|
1
|
+
import{objectEntries as e}from"./runtimeObject";import{applyAssetParameterMacros 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{GAM_DUPLICATE_METADATA_DIAGNOSTIC_MESSAGE as n,GamStreamManager as m}from"./GamStreamManager";import{resolveBreakFormat as d}from"./AdBreakSequencer";import{buildStitcherMasterUrl as c}from"./StitcherUrlBuilder";import{resolveExternalVendorParameters as h}from"./resolveExternalVendorConfigurations";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 m(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=c({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 m(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 e=s(this.sessionConfigParameters,this.updatedParameters,this.manifestParameters,void 0),r=t(e,a({customerMacros:this.customerMacros,element:this.player.videoElement??null,breakDurationSec:void 0}),"gam");for(const{key:e,macro:t}of r.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 r.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 r.params}updateAssetParameters(e){this.updatedParameters=e,this.gamStreamManager?.replaceAdTagParameters(this.resolveAdTagParameters()??{})}resolveExternalVendorConfiguration(e){const t=h(e,s(this.sessionConfigParameters,this.updatedParameters,void 0,void 0),a({customerMacros:this.customerMacros,element:this.player.videoElement??null,breakDurationSec:void 0}));for(const{key:e,macro:a}of t.unresolved)this.callbacks.diagnose("DA-ASSET-MACRO-UNKNOWN",`Asset parameter '${e}' sent with literal macro '${a}': the macro has no value.`,{key:e,macro:a});for(const{key:e,macro:a}of t.omitted)this.callbacks.diagnose("DA-ASSET-PARAMETER-OMITTED",`Asset parameter '${e}' not sent: macro '${a}' is empty.`,{key:e,macro:a});return t.configuration}updateAssetParameterMacros(t){const a={...this.customerMacros};for(const[s,r]of e(t))void 0===r?delete a[s]:a[s]=r;this.customerMacros=a,this.callbacks.diagnose("DA-ASSET-PARAMETERS-UPDATED","Asset parameter macros updated.",{source:"macros",keys:Object.keys(t).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:d(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:d(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"),onDuplicateMetadata:e=>{this.callbacks.diagnose("DA-GAM-DUPLICATE-METADATA",n,{...this.currentAsset?{assetId:this.currentAsset.id}:{},startTime:e})},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:d(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:d(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:d(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:d(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:""}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AssetType as t}from"../../types/BreakManifest";export class AdPlayerEvents{constructor(t,e){this.state=t,this.deps=e}recordAdProgress(t){!Number.isFinite(t)||t<=0||(this.deps.onGamPodAdProgress(t),t>this.state.currentAssetElapsedSec&&(this.state.currentAssetElapsedSec=t))}settleAssetProgress(){let t=this.state.currentAssetElapsedSec;if(t<=0){const e=this.state.currentAsset?.duration;"number"==typeof e&&Number.isFinite(e)&&e>0&&(t=e)}this.state.adSecondsPlayedThisBreak+=t,this.state.currentAssetElapsedSec=0}reportAdProgress(e){if(this.state.isPlaying&&this.state.currentBreak&&this.state.currentAsset&&(this.recordAdProgress(e.currentTime),this.deps.maybePrepositionContentForResume(),this.state.currentBreak&&this.deps.maybeCatchUpContentForResume(this.state.currentBreak),this.state.callbacks?.onAdTimeUpdate(this.state.currentBreak,this.state.currentAsset,e.currentTime,e.duration),this.state.currentAsset.type===t.STATIC&&e.duration>0)){const t=e.currentTime/e.duration,s=this.deps.getStaticQuartilesFired(),r=this.deps.getGamEventCallbacks();t>=.25&&!s.has("first")&&(s.add("first"),r.onAdFirstQuartile?.(this.state.currentBreak,this.state.currentAsset)),t>=.5&&!s.has("mid")&&(s.add("mid"),r.onAdMidpoint?.(this.state.currentBreak,this.state.currentAsset)),t>=.75&&!s.has("third")&&(s.add("third"),r.onAdThirdQuartile?.(this.state.currentBreak,this.state.currentAsset))}}setupEventListeners(){const t=this.deps.getAdPlayer();if(!t)return;t.on("ended",()=>{this.deps.onAdEnded()}),t.on("timedmetadata",t=>{t&&this.deps.processTimedMetadata(t)}),t.on("error",t=>{this.onAdError(this.deps.toAdError(t))}),t.on("timeupdate",()=>this.reportAdProgress(t)),t.on("waiting",()=>{this.state.isPlaying&&this.state.currentBreak&&this.state.currentAsset&&this.state.callbacks?.onAdWaiting(this.state.currentBreak,this.state.currentAsset)}),t.on("playing",()=>{if(this.state.isPlaying&&this.state.currentBreak&&this.state.currentAsset&&!t.paused){if(this.state.startPlaybackCutoff?.(),this.state.firstFrameResolver)return this.deps.revealFirstFrame(),this.state.firstFrameResolver(),void this.state.callbacks?.onAdPlaying(this.state.currentBreak,this.state.currentAsset);this.state.callbacks?.onAdPlaying(this.state.currentBreak,this.state.currentAsset)}});const e=()=>{const t=this.deps.getAdPlayer();if(this.deps.getSyncing()||!t)return;const e=this.deps.getAudioFocus();e?"ad"===e?this.deps.notifyVolumeChange():(this.deps.setSyncing(!0),t.muted=!0,t.volume=0,this.deps.setSyncing(!1)):this.state.isPlaying&&(this.deps.setSyncing(!0),this.deps.getContentPlayer().muted=t.muted,this.deps.getContentPlayer().volume=t.volume,this.deps.setSyncing(!1),this.deps.notifyVolumeChange())};this.deps.setAdVolumeChangeHandler(e),t.on("volumechange",e);const s=()=>{const t=this.deps.getAdPlayer();if(this.deps.getSyncing()||!t)return;const e=this.deps.getAudioFocus();e?"content"===e?this.deps.notifyVolumeChange():(this.deps.setSyncing(!0),this.deps.getContentPlayer().muted=!0,this.deps.setSyncing(!1)):(this.deps.setSyncing(!0),t.muted=this.deps.getContentPlayer().muted,t.volume=this.deps.getContentPlayer().volume,this.deps.setSyncing(!1),this.deps.notifyVolumeChange())};this.deps.setContentVolumeHandler(s),this.deps.getContentPlayer().on("volumechange",s)}onAdError(t){const e=this.deps.getSequencer();if(this.state.
|
|
1
|
+
import{AssetType as t}from"../../types/BreakManifest";export class AdPlayerEvents{constructor(t,e){this.state=t,this.deps=e}recordAdProgress(t){!Number.isFinite(t)||t<=0||(this.deps.onGamPodAdProgress(t),t>this.state.currentAssetElapsedSec&&(this.state.currentAssetElapsedSec=t))}settleAssetProgress(){let t=this.state.currentAssetElapsedSec;if(t<=0){const e=this.state.currentAsset?.duration;"number"==typeof e&&Number.isFinite(e)&&e>0&&(t=e)}this.state.adSecondsPlayedThisBreak+=t,this.state.currentAssetElapsedSec=0}reportAdProgress(e){if(this.state.isPlaying&&this.state.currentBreak&&this.state.currentAsset&&(this.recordAdProgress(e.currentTime),this.deps.maybePrepositionContentForResume(),this.state.currentBreak&&this.deps.maybeCatchUpContentForResume(this.state.currentBreak),this.state.callbacks?.onAdTimeUpdate(this.state.currentBreak,this.state.currentAsset,e.currentTime,e.duration),this.state.currentAsset.type===t.STATIC&&e.duration>0)){const t=e.currentTime/e.duration,s=this.deps.getStaticQuartilesFired(),r=this.deps.getGamEventCallbacks();t>=.25&&!s.has("first")&&(s.add("first"),r.onAdFirstQuartile?.(this.state.currentBreak,this.state.currentAsset)),t>=.5&&!s.has("mid")&&(s.add("mid"),r.onAdMidpoint?.(this.state.currentBreak,this.state.currentAsset)),t>=.75&&!s.has("third")&&(s.add("third"),r.onAdThirdQuartile?.(this.state.currentBreak,this.state.currentAsset))}}setupEventListeners(){const t=this.deps.getAdPlayer();if(!t)return;t.on("ended",()=>{this.deps.onAdEnded()}),t.on("timedmetadata",t=>{t&&this.deps.processTimedMetadata(t)}),t.on("error",t=>{this.onAdError(this.deps.toAdError(t))}),t.on("timeupdate",()=>this.reportAdProgress(t)),t.on("waiting",()=>{this.state.isPlaying&&this.state.currentBreak&&this.state.currentAsset&&this.state.callbacks?.onAdWaiting(this.state.currentBreak,this.state.currentAsset)}),t.on("playing",()=>{if(this.state.isPlaying&&this.state.currentBreak&&this.state.currentAsset&&!t.paused){if(this.state.startPlaybackCutoff?.(),this.state.firstFrameResolver)return this.deps.revealFirstFrame(),this.state.firstFrameResolver(),void this.state.callbacks?.onAdPlaying(this.state.currentBreak,this.state.currentAsset);this.state.callbacks?.onAdPlaying(this.state.currentBreak,this.state.currentAsset)}});const e=()=>{const t=this.deps.getAdPlayer();if(this.deps.getSyncing()||!t)return;const e=this.deps.getAudioFocus();e?"ad"===e?this.deps.notifyVolumeChange():(this.deps.setSyncing(!0),t.muted=!0,t.volume=0,this.deps.setSyncing(!1)):this.state.isPlaying&&(this.deps.setSyncing(!0),this.deps.getContentPlayer().muted=t.muted,this.deps.getContentPlayer().volume=t.volume,this.deps.setSyncing(!1),this.deps.notifyVolumeChange())};this.deps.setAdVolumeChangeHandler(e),t.on("volumechange",e);const s=()=>{const t=this.deps.getAdPlayer();if(this.deps.getSyncing()||!t)return;const e=this.deps.getAudioFocus();e?"content"===e?this.deps.notifyVolumeChange():(this.deps.setSyncing(!0),this.deps.getContentPlayer().muted=!0,this.deps.setSyncing(!1)):(this.deps.setSyncing(!0),t.muted=this.deps.getContentPlayer().muted,t.volume=this.deps.getContentPlayer().volume,this.deps.setSyncing(!1),this.deps.notifyVolumeChange())};this.deps.setContentVolumeHandler(s),this.deps.getContentPlayer().on("volumechange",s)}onAdError(t){const e=this.deps.getSequencer(),s=this.state.currentBreak;if(!s||!e)return;const r=this.state.preloadGeneration,i=this.state.erroredAsset;if(i?.breakInfo!==s||i.generation!==r){if(this.state.erroredAsset={breakInfo:s,generation:r},this.state.firstFrameRejector){const e=this.state.firstFrameRejector;this.deps.clearFirstFrameResolver(),e(t)}this.deps.log("Ad error:",t.message),this.deps.setPendingAdError(t),this.deps.drive(e.onOutcome({kind:"asset-errored"}))}else this.deps.log("Ignoring further ad error for the same asset:",t.message)}}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Asset, Break, DeviceType, Timebase } from '../../types/BreakManifest';
|
|
2
|
+
import type { DeviceProfile } from '../matchTargeting';
|
|
2
3
|
import type { AdInsertionType } from '../../types/OptiViewAdsConfig';
|
|
3
4
|
import type { AdPlayerCallbacks } from '../AdPlayerController';
|
|
4
5
|
import type { AdBreakStep } from '../AdBreakSequencer';
|
|
@@ -22,6 +23,7 @@ export interface AdPlayerState {
|
|
|
22
23
|
breakTimebase: Timebase | null;
|
|
23
24
|
adBreakCutSafetyMarginSec: number;
|
|
24
25
|
detectedDeviceType: DeviceType | undefined;
|
|
26
|
+
detectedDeviceProfile?: DeviceProfile | undefined;
|
|
25
27
|
sessionAssetParameters: Record<string, string> | undefined;
|
|
26
28
|
updatedAssetParameters: Record<string, string> | undefined;
|
|
27
29
|
manifestAssetParameters: Record<string, string> | undefined;
|
|
@@ -63,6 +65,12 @@ export interface AdPlayerState {
|
|
|
63
65
|
* whether the content under the ad is known slate of exactly the advertised duration.
|
|
64
66
|
*/
|
|
65
67
|
resumeAnchorIsCue: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* Whether this break's anchor is the content time of the manifest start, placed through the
|
|
70
|
+
* stream's Program Date Time (`wallclock` timebase) — like a cue, a stream-clock anchor under
|
|
71
|
+
* which the content for the whole advertised duration is the stream's own break.
|
|
72
|
+
*/
|
|
73
|
+
resumeAnchorIsPdt: boolean;
|
|
66
74
|
/**
|
|
67
75
|
* The seekable end as the engine reported it at break start, captured with the anchor so the
|
|
68
76
|
* two are comparable. Their difference is the cushion the resume has to work with: a playhead
|
|
@@ -106,6 +114,11 @@ export interface AdPlayerState {
|
|
|
106
114
|
player: PlayerAdapter;
|
|
107
115
|
} | null;
|
|
108
116
|
preloadGeneration: number;
|
|
117
|
+
/** The break + asset generation that already reported an error; later errors for it are dropped. */
|
|
118
|
+
erroredAsset: {
|
|
119
|
+
breakInfo: Break;
|
|
120
|
+
generation: number;
|
|
121
|
+
} | null;
|
|
109
122
|
firstFrameGateActive: boolean;
|
|
110
123
|
firstFrameGateShown: boolean;
|
|
111
124
|
firstFrameResolver: (() => void) | null;
|
|
@@ -1 +1 @@
|
|
|
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,startPlaybackCutoff: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,resumeAnchorIsCue:!1,resumeAnchorSeekableEnd:null,resumePrepositionedTo:null,resumePrepositionSettle:null,resumeCatchupActive:!1,resumeCatchupRan:!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
|
+
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,startPlaybackCutoff: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,resumeAnchorIsCue:!1,resumeAnchorIsPdt:!1,resumeAnchorSeekableEnd:null,resumePrepositionedTo:null,resumePrepositionSettle:null,resumeCatchupActive:!1,resumeCatchupRan:!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,erroredAsset:null,firstFrameGateActive:!1,firstFrameGateShown:!1,firstFrameResolver:null,firstFrameRejector:null,firstFrameTimeout:null,adStartDeadlineMs:null,adStartBudgetMs:0,vastAdManager:null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AssetType as e,BreakFormat as t,MediaType as s,Vendor as
|
|
1
|
+
import{AssetType as e,BreakFormat as t,MediaType as s,Vendor as a,isVastAsset as r,isVendorAsset as i}from"../../types/BreakManifest";import{AUX_FETCH_TIMEOUT_MS as d,fetchWithTimeout as o}from"../fetchWithTimeout";import{resolveVastAdmission as n}from"../resolveVastAdmission";import{isImaCsaiSdkAvailable as l,VastAdManager as p}from"../VastAdManager";import{invalidateMediaPreload as h}from"./AdPlayerState";import{AdError as m}from"../../types/AdError";export const AD_LOAD_RETRY_AFTER_MS=2e3;export function adLoadShowsNoProgress(e){return!e||0===e.readyState&&0===e.buffered.length}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 i=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(r(o[0]))return void await this.preloadVastAsset(o[0],a);const l=await this.deps.resolveAssetUri(o[0],a.duration);if(l){if(d&&this.ownsPreload(i,d))if("single-decoder"!==this.deps.preloadMode){this.deps.log("Preloading ad (parallel):",l),this.diagnosePreloadPath(a.id,l,"parallel");try{if(await d.load(l),!this.ownsPreload(i,d))return;this.deps.state.preparedMedia={breakId:a.id,assetId:o[0].id,uri:l,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):",l),this.diagnosePreloadPath(a.id,l,"single-decoder"),await this.warmCache([l]),!this.ownsPreload(i,d))return;try{await(d.preload?.(l))}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),r=a?.format??t.SINGLE;if(!n({format:r,ssai:!1}).admitted)return void this.deps.log("VAST preload skipped: format not supported",r);if(!l())return void this.deps.log("VAST preload skipped: IMA client-side SDK unavailable");const i=this.deps.getAdPlayer(),d=this.deps.getAdContainer();if(!i||!d)return void this.deps.log("VAST preload skipped: ad player not initialized");const o=i.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 p(d,o,this.deps.debug)),this.deps.log("Preloading VAST asset via IMA CSAI:",h);try{await this.deps.state.vastAdManager.preloadVast(h,{muted:i.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 r=this.deps.getAssets(s)[0];if(!r||r.type!==e.STATIC)return void this.deps.log("Chained successor first asset not static; skipping media warm:",s.id);const i=this.deps.resolveUri(r.uri);if(i){this.warmedBreakIds.add(s.id),this.deps.log("Warming chained successor media:",s.id,i),await this.warmCache([i]);try{await(this.deps.getAdPlayer()?.preload?.(i))}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=i(e)&&e.vendor===a.GAM?this.deps.gamPodAdStartBudgetMs:this.deps.adStartBudgetMs,r=Math.max(Math.min(t-100,s),this.deps.minAdStartBudgetMs);this.deps.state.adStartBudgetMs=r,this.deps.state.adStartDeadlineMs=this.deps.clock.now()+r}remainingAdStartBudgetMs(){return Math.max(0,(this.deps.state.adStartDeadlineMs??this.deps.clock.now())-this.deps.clock.now())}loadWithinBudget(e,t){const s=this.deps.state.preloadGeneration,a=this.remainingAdStartBudgetMs(),r=this.deps.clock.now();return new Promise((i,d)=>{let o=!1,n=!1;const l=e=>{o||(o=!0,clearTimeout(p),null!==h&&clearTimeout(h),e.ok?i(!0):d(e.error))},p=setTimeout(()=>{s===this.deps.state.preloadGeneration&&this.deps.onAdError(new m("Ad load timeout","DA-AD-START-TIMEOUT")),o||(o=!0,null!==h&&clearTimeout(h),i(!1))},a);let h=null;a>2e3&&(h=setTimeout(()=>{if(o||s!==this.deps.state.preloadGeneration)return;const a=this.deps.clock.now()-r,i=this.deps.getAdPlayer()?.videoElement;adLoadShowsNoProgress(i)?(n=!0,this.deps.log(`Ad load for ${t.assetId} stalled after ${a}ms; retrying once`),this.deps.diagnose("DA-AD-LOAD-RETRIED",`Ad load for ${t.assetId} in break ${t.breakId} had not settled after ${a}ms; issued a second load()`,{breakId:t.breakId,assetId:t.assetId,uri:t.uri,elapsedMs:a,remainingBudgetMs:this.remainingAdStartBudgetMs()}),e().then(()=>l({ok:!0}),e=>l({ok:!1,error:e}))):this.deps.log(`Ad load for ${t.assetId} still pending after ${a}ms but the element is progressing (readyState=${i?.readyState}, buffered=${i?.buffered.length}); no retry`)},2e3)),e().then(()=>l({ok:!0}),e=>{n||l({ok:!1,error: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 m("First frame timeout","DA-AD-START-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 r=a.assets[0]?.companion;if(!r||r.type!==e.STATIC)return;const i=this.deps.resolveUri(r.uri);if(!i)return;(new Image).src=i,this.deps.log("Preloading companion:",i)}async warmCache(e){"function"==typeof fetch&&await Promise.allSettled(e.map(e=>o(e,{mode:"no-cors"},d).catch(()=>{})))}}
|
|
@@ -31,15 +31,15 @@ export interface AdStageDeps {
|
|
|
31
31
|
isChaining: () => boolean;
|
|
32
32
|
log: (...args: unknown[]) => void;
|
|
33
33
|
}
|
|
34
|
-
/** Owns the overlay stage geometry, break layout
|
|
34
|
+
/** Owns the overlay stage geometry, break layout and companions. The content/ad switch is a cut; only the layout reflow glides. */
|
|
35
35
|
export declare class AdStage {
|
|
36
36
|
private readonly deps;
|
|
37
37
|
private contentVideoGeometryHandler;
|
|
38
38
|
private contentVideoMutationObserver;
|
|
39
39
|
private resizeObserver;
|
|
40
40
|
private resizePoll;
|
|
41
|
-
|
|
42
|
-
private
|
|
41
|
+
/** Layout whose box currently holds the content; `null` while the content is full-size. */
|
|
42
|
+
private contentLayout;
|
|
43
43
|
private preparedLease;
|
|
44
44
|
private unsubscribeGeometry;
|
|
45
45
|
constructor(deps: AdStageDeps);
|
|
@@ -54,6 +54,10 @@ export declare class AdStage {
|
|
|
54
54
|
applyLayout(variant: BreakVariant): void;
|
|
55
55
|
restoreLayout(format?: BreakFormat): void;
|
|
56
56
|
renderCompanion(assets: AssetWithCompanion[], cssText: string): void;
|
|
57
|
+
/** Shows `img` as the stage companion and retires the previous one, cross-fading between them. */
|
|
58
|
+
private installCompanion;
|
|
59
|
+
/** Removes that specific companion element at once (a cut, like the ad surface). */
|
|
60
|
+
private retireCompanion;
|
|
57
61
|
clearOverlayImage(): void;
|
|
58
62
|
show(): void;
|
|
59
63
|
hide(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getPreparedPresentation as e}from"./PreparedPresentation";import{AssetType as t,BreakFormat as s}from"../../types/BreakManifest";const i=16/9;export class AdStage{constructor(e){this.deps=e,this.contentVideoGeometryHandler=null,this.contentVideoMutationObserver=null,this.resizeObserver=null,this.resizePoll=null,this.companionRemoveTimer=null,this.adFadeTimer=null,this.preparedLease=null,this.unsubscribeGeometry=null}setupOverlay(){const t=e(this.deps.container);if(t){const e=this.deps.getPlayerContainer();if(e&&e!==t.playerContainer)throw new Error("The prepared content container cannot be replaced");this.preparedLease=t.acquire(),this.deps.setStage(this.preparedLease.stage),this.deps.setPlayerContainer(this.preparedLease.playerContainer),this.unsubscribeGeometry=this.preparedLease.subscribe(()=>this.deps.resizeVast());try{this.setupMediaLayer()}catch(e){const t=this.deps.getAdContainer();throw t?.parentNode?.removeChild(t),this.deps.setAdContainer(null),this.deps.setAdMediaContainer(null),this.unsubscribeGeometry?.(),this.preparedLease.release(),e}return}const s=window.getComputedStyle(this.deps.container);"static"!==s.position&&""!==s.position||(this.deps.container.style.position="relative"),this.deps.setStage(document.createElement("div"));const i=this.deps.getStage();if(!i)return;if(i.className="dolby-stage",i.style.cssText="position:absolute;overflow:hidden;",this.deps.container.appendChild(i),this.contentVideoGeometryHandler=()=>this.refreshStageGeometry(),"undefined"!=typeof MutationObserver&&(this.contentVideoMutationObserver=new MutationObserver(()=>{(this.deps.contentPlayer.videoElement??null)!==this.deps.getContentVideo()&&this.refreshStageGeometry()}),this.contentVideoMutationObserver.observe(this.deps.container,{childList:!0,subtree:!0})),"undefined"!=typeof ResizeObserver)this.resizeObserver=new ResizeObserver(()=>this.refreshStageGeometry()),this.resizeObserver.observe(this.deps.container);else{let e=this.deps.container.getBoundingClientRect();this.resizePoll=setInterval(()=>{const t=this.deps.container.getBoundingClientRect();t.width===e.width&&t.height===e.height||(e=t,this.refreshStageGeometry())},250)}if(this.refreshStageGeometry(),this.deps.getPlayerContainer()){const e=this.deps.getPlayerContainer();if(!e)return;i.appendChild(e)}else{const e=document.createElement("div"),t=Array.from(this.deps.container.childNodes).filter(e=>e!==i);for(const s of t)e.appendChild(s);i.appendChild(e),this.deps.setPlayerContainer(e),this.deps.onPlayerContainerCreated()}const o=this.deps.getPlayerContainer();o&&(this.deps.setPlayerContainerOriginalStyle(o.style.cssText),o.style.cssText="position:absolute;top:0;left:0;right:0;bottom:0;transition:top 0.3s ease-in-out,left 0.3s ease-in-out,right 0.3s ease-in-out,bottom 0.3s ease-in-out,opacity 0.3s ease-in-out;",this.setupMediaLayer())}setupMediaLayer(){const e=this.deps.getStage();if(!e)throw new Error("An ads presentation stage is required");this.deps.setAdContainer(document.createElement("div"));const t=this.deps.getAdContainer();if(!t)return;t.className="dolby-ad-container",t.style.cssText="display:none;position:absolute;top:0;left:0;right:0;bottom:0;z-index:100;background:#000;",this.deps.setAdMediaContainer(document.createElement("div"));const s=this.deps.getAdMediaContainer();s&&(s.style.cssText="display:block;width:100%;height:100%;",t.appendChild(s),e.appendChild(t),this.deps.setAdPlayer(this.deps.createAdAdapter(s)),this.deps.setupEventListeners(),this.deps.log("Ad player overlay initialized"))}refreshStageGeometry(){this.rebindContentVideoGeometryListener(),this.updateStageGeometry(),this.deps.resizeVast()}rebindContentVideoGeometryListener(){const e=this.deps.contentPlayer.videoElement??null,t=e&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener?e:null;t!==this.deps.getContentVideo()&&(this.deps.getContentVideo()&&this.contentVideoGeometryHandler&&(this.deps.getContentVideo()?.removeEventListener("loadedmetadata",this.contentVideoGeometryHandler),this.deps.getContentVideo()?.removeEventListener("resize",this.contentVideoGeometryHandler)),this.deps.setContentVideo(t),t&&this.contentVideoGeometryHandler&&(t.addEventListener("loadedmetadata",this.contentVideoGeometryHandler),t.addEventListener("resize",this.contentVideoGeometryHandler)))}updateStageGeometry(){const e=this.deps.getStage();if(!e)return;const{width:t,height:s}=this.deps.container.getBoundingClientRect();if(0===t||0===s)return;const i=this.getContentAspectRatio();let o,n;t/s>i?(n=s,o=s*i):(o=t,n=t/i);const r=(s-n)/2,a=(t-o)/2;e.style.width=`${o}px`,e.style.height=`${n}px`,e.style.top=`${r}px`,e.style.left=`${a}px`}getContentAspectRatio(){const e=this.deps.contentPlayer.videoElement;if(!e)return i;const{videoWidth:t,videoHeight:s}=e;return!Number.isFinite(t)||!Number.isFinite(s)||t<=0||s<=0?i:t/s}renderLshapeContentBackdrop(e){const s=e.assets[0];if(!s||s.type!==t.STATIC)return;const i=this.deps.resolveUri(s.uri);if(!i)return;const o=document.createElement("img");o.className="dolby-companion",o.src=i,o.style.cssText="position:absolute;top:0;left:0;right:0;bottom:0;z-index:99;object-fit:cover;width:100%;height:100%;opacity:0;transition:opacity 0.3s ease-in-out;";const n=this.deps.getStage();n&&(n.appendChild(o),this.deps.setCompanion(o),requestAnimationFrame(()=>{const e=this.deps.getCompanion();e&&(e.style.opacity="1")}),this.deps.log("Rendered lshape_content backdrop:",i))}reapplyAdContainerLayout(e){const t=this.deps.getAdContainer();if(t){switch(e.format){case s.LSHAPE_AD:t.style.position="absolute",t.style.top="5%",t.style.left="5%",t.style.right="30%",t.style.bottom="30%",t.style.width="",t.style.height="",t.style.zIndex="100";break;case s.DOUBLE:t.style.position="absolute",t.style.top="26.04%",t.style.left="51.04%",t.style.right="1.04%",t.style.bottom="26.04%",t.style.width="",t.style.height="",t.style.zIndex="100"}this.deps.log("reapplyAdContainerLayout: re-stamped adContainer CSS for format:",e.format)}}applyLayout(e){const t=this.deps.getAdContainer(),i=this.deps.getPlayerContainer();if(!t||!i)return;const o="transition:top 0.3s ease-in-out,left 0.3s ease-in-out,right 0.3s ease-in-out,bottom 0.3s ease-in-out,opacity 0.3s ease-in-out;";switch(e.format){case s.SINGLE:t.style.cssText="display:none;opacity:0;position:absolute;top:0;left:0;right:0;bottom:0;z-index:100;background:#000;transition:opacity 0.3s ease-in-out;";break;case s.DOUBLE:i.style.cssText=`position:absolute;top:26.04%;left:1.04%;right:51.04%;bottom:26.04%;z-index:101;${o}`,t.style.cssText="display:none;opacity:0;position:absolute;top:26.04%;left:51.04%;right:1.04%;bottom:26.04%;z-index:100;background:#000;transition:opacity 0.3s ease-in-out;",this.renderCompanion(e.assets,"position:absolute;top:0;left:0;right:0;bottom:0;z-index:99;object-fit:cover;width:100%;height:100%;opacity:0;transition:opacity 0.3s ease-in-out;");break;case s.LSHAPE_AD:i.style.cssText=`position:absolute;top:5%;left:5%;right:30%;bottom:30%;z-index:101;opacity:0;${o}`,t.style.cssText="display:none;opacity:0;position:absolute;top:5%;left:5%;right:30%;bottom:30%;z-index:100;background:#000;transition:opacity 0.3s ease-in-out;",this.renderCompanion(e.assets,"position:absolute;top:0;left:0;right:0;bottom:0;z-index:99;object-fit:cover;width:100%;height:100%;opacity:0;transition:opacity 0.3s ease-in-out;");break;case s.LSHAPE_CONTENT:i.style.top="5%",i.style.left="5%",i.style.right="30%",i.style.bottom="30%",i.style.zIndex="101";break;case s.OVERLAY:{const s=e,i=e=>void 0!==e?100*e+"%":"auto",o=i(s.position.top),n=i(s.position.bottom),r=i(s.position.left),a=i(s.position.right),d=100*s.size.width+"%",l=100*s.size.height+"%",p=s.opacity??1;t.style.cssText=`display:none;position:absolute;top:${o};bottom:${n};left:${r};right:${a};width:${d};height:${l};z-index:100;opacity:${p};`;break}default:t.style.cssText="display:none;position:absolute;top:0;left:0;right:0;bottom:0;z-index:100;background:#000;"}}restoreLayout(e){if(this.preparedLease&&!this.preparedLease.isActive())return;const t=e===s.DOUBLE||e===s.LSHAPE_AD||e===s.LSHAPE_CONTENT,i=this.deps.getPlayerContainer();if(!i)return;i.style.cssText="position:absolute;top:0;left:0;right:0;bottom:0;"+(t?"z-index:101;":"")+"transition:top 0.3s ease-in-out,left 0.3s ease-in-out,right 0.3s ease-in-out,bottom 0.3s ease-in-out,opacity 0.3s ease-in-out;",this.companionRemoveTimer&&clearTimeout(this.companionRemoveTimer);const o=this.deps.getCompanion();o&&(o.style.opacity="0"),this.companionRemoveTimer=setTimeout(()=>{const e=this.deps.getCompanion();e?.parentElement&&(e.parentElement.removeChild(e),this.deps.setCompanion(null)),this.companionRemoveTimer=null;const s=this.deps.getPlayerContainer();t&&s&&(s.style.zIndex="")},300)}renderCompanion(e,s){const i=e[0]?.companion;if(!i)return;const o=i.type===t.STATIC?this.deps.resolveUri(i.uri):null;if(!o)return;const n=document.createElement("img");n.className="dolby-companion",n.src=o,n.style.cssText=s;const r=this.deps.getStage();r&&(r.appendChild(n),this.deps.setCompanion(n),requestAnimationFrame(()=>{const e=this.deps.getCompanion();e&&(e.style.opacity="1")}))}clearOverlayImage(){const e=this.deps.getImageAssetTimer();e&&(clearTimeout(e),this.deps.setImageAssetTimer(null));const t=this.deps.getOverlayImage();t?.parentElement&&t.parentElement.removeChild(t),this.deps.setOverlayImage(null)}show(){const e=this.deps.getAdContainer();if(!e)return;this.adFadeTimer&&(clearTimeout(this.adFadeTimer),this.adFadeTimer=null);const t=this.deps.getCurrentBreak(),i=t?this.deps.getVariant(t):null;e.style.display="block",i?.format!==s.OVERLAY&&(this.deps.isChaining()?e.style.opacity="1":(e.style.opacity="0",requestAnimationFrame(()=>{const e=this.deps.getAdContainer();e&&(e.style.opacity="1")})))}hide(){const e=this.deps.getAdContainer();if(!e)return;const t=this.deps.getCurrentBreak(),i=t?this.deps.getVariant(t):null;i?.format!==s.OVERLAY?(e.style.opacity="0",this.adFadeTimer=setTimeout(()=>{const e=this.deps.getAdContainer();e&&(e.style.display="none"),this.adFadeTimer=null},300)):e.style.display="none"}restoreContent(e,t){if(this.releasePreparedPresentation())return!0;const s=this.deps.getPlayerContainer();if(!s)return!1;if(e)for(;s.firstChild;)this.deps.container.appendChild(s.firstChild);else this.deps.container.appendChild(s),s.style.cssText=t;return!1}releasePreparedPresentation(){return!!this.preparedLease&&(this.unsubscribeGeometry?.(),this.unsubscribeGeometry=null,this.preparedLease.release(),!0)}destroy(){this.unsubscribeGeometry?.(),this.unsubscribeGeometry=null;const e=this.deps.getContentVideo();e&&this.contentVideoGeometryHandler&&(e.removeEventListener("loadedmetadata",this.contentVideoGeometryHandler),e.removeEventListener("resize",this.contentVideoGeometryHandler)),this.contentVideoMutationObserver?.disconnect(),this.resizeObserver?.disconnect(),null!==this.resizePoll&&clearInterval(this.resizePoll),this.resizePoll=null,this.contentVideoMutationObserver=null,this.resizeObserver=null,this.contentVideoGeometryHandler=null,this.companionRemoveTimer&&clearTimeout(this.companionRemoveTimer),this.adFadeTimer&&clearTimeout(this.adFadeTimer)}}
|
|
1
|
+
import{getPreparedPresentation as e}from"./PreparedPresentation";import{AssetType as t,BreakFormat as s}from"../../types/BreakManifest";const i=16/9;export class AdStage{constructor(e){this.deps=e,this.contentVideoGeometryHandler=null,this.contentVideoMutationObserver=null,this.resizeObserver=null,this.resizePoll=null,this.contentLayout=null,this.preparedLease=null,this.unsubscribeGeometry=null}setupOverlay(){const t=e(this.deps.container);if(t){const e=this.deps.getPlayerContainer();if(e&&e!==t.playerContainer)throw new Error("The prepared content container cannot be replaced");this.preparedLease=t.acquire(),this.deps.setStage(this.preparedLease.stage),this.deps.setPlayerContainer(this.preparedLease.playerContainer),this.unsubscribeGeometry=this.preparedLease.subscribe(()=>this.deps.resizeVast());try{this.setupMediaLayer()}catch(e){const t=this.deps.getAdContainer();throw t?.parentNode?.removeChild(t),this.deps.setAdContainer(null),this.deps.setAdMediaContainer(null),this.unsubscribeGeometry?.(),this.preparedLease.release(),e}return}const s=window.getComputedStyle(this.deps.container);"static"!==s.position&&""!==s.position||(this.deps.container.style.position="relative"),this.deps.setStage(document.createElement("div"));const i=this.deps.getStage();if(!i)return;if(i.className="dolby-stage",i.style.cssText="position:absolute;overflow:hidden;",this.deps.container.appendChild(i),this.contentVideoGeometryHandler=()=>this.refreshStageGeometry(),"undefined"!=typeof MutationObserver&&(this.contentVideoMutationObserver=new MutationObserver(()=>{(this.deps.contentPlayer.videoElement??null)!==this.deps.getContentVideo()&&this.refreshStageGeometry()}),this.contentVideoMutationObserver.observe(this.deps.container,{childList:!0,subtree:!0})),"undefined"!=typeof ResizeObserver)this.resizeObserver=new ResizeObserver(()=>this.refreshStageGeometry()),this.resizeObserver.observe(this.deps.container);else{let e=this.deps.container.getBoundingClientRect();this.resizePoll=setInterval(()=>{const t=this.deps.container.getBoundingClientRect();t.width===e.width&&t.height===e.height||(e=t,this.refreshStageGeometry())},250)}if(this.refreshStageGeometry(),this.deps.getPlayerContainer()){const e=this.deps.getPlayerContainer();if(!e)return;i.appendChild(e)}else{const e=document.createElement("div"),t=Array.from(this.deps.container.childNodes).filter(e=>e!==i);for(const s of t)e.appendChild(s);i.appendChild(e),this.deps.setPlayerContainer(e),this.deps.onPlayerContainerCreated()}const n=this.deps.getPlayerContainer();n&&(this.deps.setPlayerContainerOriginalStyle(n.style.cssText),n.style.cssText="position:absolute;top:0;left:0;right:0;bottom:0;transition:top 0.3s ease-in-out,left 0.3s ease-in-out,right 0.3s ease-in-out,bottom 0.3s ease-in-out;",this.setupMediaLayer())}setupMediaLayer(){const e=this.deps.getStage();if(!e)throw new Error("An ads presentation stage is required");this.deps.setAdContainer(document.createElement("div"));const t=this.deps.getAdContainer();if(!t)return;t.className="dolby-ad-container",t.style.cssText="display:none;position:absolute;top:0;left:0;right:0;bottom:0;z-index:100;background:#000;",this.deps.setAdMediaContainer(document.createElement("div"));const s=this.deps.getAdMediaContainer();if(!s)return;s.style.cssText="display:block;width:100%;height:100%;",t.appendChild(s),e.appendChild(t);const i=this.deps.createAdAdapter(s);i!==this.deps.contentPlayer&&i.prepareForAdPlayback?.(),this.deps.setAdPlayer(i),this.deps.setupEventListeners(),this.deps.log("Ad player overlay initialized")}refreshStageGeometry(){this.rebindContentVideoGeometryListener(),this.updateStageGeometry(),this.deps.resizeVast()}rebindContentVideoGeometryListener(){const e=this.deps.contentPlayer.videoElement??null,t=e&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener?e:null;t!==this.deps.getContentVideo()&&(this.deps.getContentVideo()&&this.contentVideoGeometryHandler&&(this.deps.getContentVideo()?.removeEventListener("loadedmetadata",this.contentVideoGeometryHandler),this.deps.getContentVideo()?.removeEventListener("resize",this.contentVideoGeometryHandler)),this.deps.setContentVideo(t),t&&this.contentVideoGeometryHandler&&(t.addEventListener("loadedmetadata",this.contentVideoGeometryHandler),t.addEventListener("resize",this.contentVideoGeometryHandler)))}updateStageGeometry(){const e=this.deps.getStage();if(!e)return;const{width:t,height:s}=this.deps.container.getBoundingClientRect();if(0===t||0===s)return;const i=this.getContentAspectRatio();let n,o;t/s>i?(o=s,n=s*i):(n=t,o=t/i);const r=(s-o)/2,a=(t-n)/2;e.style.width=`${n}px`,e.style.height=`${o}px`,e.style.top=`${r}px`,e.style.left=`${a}px`}getContentAspectRatio(){const e=this.deps.contentPlayer.videoElement;if(!e)return i;const{videoWidth:t,videoHeight:s}=e;return!Number.isFinite(t)||!Number.isFinite(s)||t<=0||s<=0?i:t/s}renderLshapeContentBackdrop(e){const s=e.assets[0];if(!s||s.type!==t.STATIC)return;const i=this.deps.resolveUri(s.uri);if(!i)return;const n=document.createElement("img");n.className="dolby-companion",n.src=i,n.style.cssText="position:absolute;top:0;left:0;right:0;bottom:0;z-index:99;object-fit:cover;width:100%;height:100%;opacity:0;";const o=this.deps.getStage();o&&(this.installCompanion(n,o),this.deps.log("Rendered lshape_content backdrop:",i))}reapplyAdContainerLayout(e){const t=this.deps.getAdContainer();if(t){switch(e.format){case s.LSHAPE_AD:t.style.position="absolute",t.style.top="5%",t.style.left="5%",t.style.right="30%",t.style.bottom="30%",t.style.width="",t.style.height="",t.style.zIndex="100";break;case s.DOUBLE:t.style.position="absolute",t.style.top="26.04%",t.style.left="51.04%",t.style.right="1.04%",t.style.bottom="26.04%",t.style.width="",t.style.height="",t.style.zIndex="100"}this.deps.log("reapplyAdContainerLayout: re-stamped adContainer CSS for format:",e.format)}}applyLayout(e){const t=this.deps.getAdContainer(),i=this.deps.getPlayerContainer();if(!t||!i)return;const n="transition:top 0.3s ease-in-out,left 0.3s ease-in-out,right 0.3s ease-in-out,bottom 0.3s ease-in-out;";switch(e.format){case s.SINGLE:this.contentLayout&&(i.style.opacity="0"),t.style.cssText="display:none;opacity:0;position:absolute;top:0;left:0;right:0;bottom:0;z-index:100;background:#000;";break;case s.DOUBLE:i.style.cssText=`position:absolute;top:26.04%;left:1.04%;right:51.04%;bottom:26.04%;z-index:101;${n}`,t.style.cssText="display:none;opacity:0;position:absolute;top:26.04%;left:51.04%;right:1.04%;bottom:26.04%;z-index:100;background:#000;",this.renderCompanion(e.assets,"position:absolute;top:0;left:0;right:0;bottom:0;z-index:99;object-fit:cover;width:100%;height:100%;opacity:0;"),this.contentLayout=e.format;break;case s.LSHAPE_AD:i.style.cssText=`position:absolute;top:5%;left:5%;right:30%;bottom:30%;z-index:101;opacity:0;${n}`,t.style.cssText="display:none;opacity:0;position:absolute;top:5%;left:5%;right:30%;bottom:30%;z-index:100;background:#000;",this.renderCompanion(e.assets,"position:absolute;top:0;left:0;right:0;bottom:0;z-index:99;object-fit:cover;width:100%;height:100%;opacity:0;"),this.contentLayout=e.format;break;case s.LSHAPE_CONTENT:i.style.top="5%",i.style.left="5%",i.style.right="30%",i.style.bottom="30%",i.style.zIndex="101",this.contentLayout=e.format;break;case s.OVERLAY:{const s=e,i=e=>void 0!==e?100*e+"%":"auto",n=i(s.position.top),o=i(s.position.bottom),r=i(s.position.left),a=i(s.position.right),d=100*s.size.width+"%",l=100*s.size.height+"%",p=s.opacity??1;t.style.cssText=`display:none;position:absolute;top:${n};bottom:${o};left:${r};right:${a};width:${d};height:${l};z-index:100;opacity:${p};`;break}default:t.style.cssText="display:none;position:absolute;top:0;left:0;right:0;bottom:0;z-index:100;background:#000;"}}restoreLayout(e){if(this.preparedLease&&!this.preparedLease.isActive())return;const t=this.deps.getPlayerContainer();if(!t)return;const i=function(e){return e===s.DOUBLE||e===s.LSHAPE_AD||e===s.LSHAPE_CONTENT}(e)||null!==this.contentLayout;this.contentLayout=null,t.style.cssText="position:absolute;top:0;left:0;right:0;bottom:0;"+(i?"z-index:101;":"")+"transition:top 0.3s ease-in-out,left 0.3s ease-in-out,right 0.3s ease-in-out,bottom 0.3s ease-in-out;";const n=this.deps.getCompanion();n&&(this.deps.setCompanion(null),this.retireCompanion(n)),i&&(t.style.zIndex="")}renderCompanion(e,s){const i=e[0]?.companion;if(!i)return;const n=i.type===t.STATIC?this.deps.resolveUri(i.uri):null;if(!n)return;const o=document.createElement("img");o.className="dolby-companion",o.src=n,o.style.cssText=s;const r=this.deps.getStage();r&&this.installCompanion(o,r)}installCompanion(e,t){const s=this.deps.getCompanion();t.appendChild(e),this.deps.setCompanion(e),e.style.opacity="1",s&&s!==e&&this.retireCompanion(s)}retireCompanion(e){e.parentElement?.removeChild(e)}clearOverlayImage(){const e=this.deps.getImageAssetTimer();e&&(clearTimeout(e),this.deps.setImageAssetTimer(null));const t=this.deps.getOverlayImage();t?.parentElement&&t.parentElement.removeChild(t),this.deps.setOverlayImage(null)}show(){const e=this.deps.getAdContainer();if(!e)return;const t=this.deps.getCurrentBreak(),i=t?this.deps.getVariant(t):null;e.style.display="block",i?.format!==s.OVERLAY&&(e.style.opacity="1")}hide(){const e=this.deps.getAdContainer();e&&(e.style.opacity="0",e.style.display="none")}restoreContent(e,t){if(this.releasePreparedPresentation())return!0;const s=this.deps.getPlayerContainer();if(!s)return!1;if(e)for(;s.firstChild;)this.deps.container.appendChild(s.firstChild);else this.deps.container.appendChild(s),s.style.cssText=t;return!1}releasePreparedPresentation(){return!!this.preparedLease&&(this.unsubscribeGeometry?.(),this.unsubscribeGeometry=null,this.preparedLease.release(),!0)}destroy(){this.unsubscribeGeometry?.(),this.unsubscribeGeometry=null;const e=this.deps.getContentVideo();e&&this.contentVideoGeometryHandler&&(e.removeEventListener("loadedmetadata",this.contentVideoGeometryHandler),e.removeEventListener("resize",this.contentVideoGeometryHandler)),this.contentVideoMutationObserver?.disconnect(),this.resizeObserver?.disconnect(),null!==this.resizePoll&&clearInterval(this.resizePoll),this.resizePoll=null,this.contentVideoMutationObserver=null,this.resizeObserver=null,this.contentVideoGeometryHandler=null,this.contentLayout=null}}
|
|
@@ -4,6 +4,7 @@ import { AssetParameterMacros } from '../assetParameterMacros';
|
|
|
4
4
|
import type { GamStreamManager } from '../GamStreamManager';
|
|
5
5
|
import type { AdPlayerState } from './AdPlayerState';
|
|
6
6
|
import type { AssetParameterMacroUpdates } from '../../types/OptiViewAdsConfig';
|
|
7
|
+
import type { ExternalVendorConfiguration } from '../resolveExternalVendorConfigurations';
|
|
7
8
|
export interface AssetParameterResolverDeps {
|
|
8
9
|
contentPlayer: PlayerAdapter;
|
|
9
10
|
container: HTMLElement;
|
|
@@ -24,6 +25,7 @@ export declare class AssetParameterResolver {
|
|
|
24
25
|
updateAssetParameterMacros(macros: AssetParameterMacroUpdates): void;
|
|
25
26
|
setSessionAssetParameterMacros(macros: AssetParameterMacros | undefined): void;
|
|
26
27
|
getSessionAssetParameterMacros(): AssetParameterMacros;
|
|
28
|
+
resolveExternalVendorConfiguration(entry: ExternalVendorConfiguration): ExternalVendorConfiguration;
|
|
27
29
|
/**
|
|
28
30
|
* Substitute the `$` macros in an effective (already layered) parameter map.
|
|
29
31
|
* Precedence per macro name: session macros, then the built-ins; a customer
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isVendorAsset as e}from"../../types/BreakManifest";import{appendQueryParameters as s,applyAssetParameterMacros as t
|
|
1
|
+
import{isVendorAsset as e}from"../../types/BreakManifest";import{appendQueryParameters as s,applyAssetParameterMacros as t}from"../assetParameterMacros";import{buildAssetParameterMacroTable as a}from"../assetParameterMacroTable";import{objectEntries as r}from"../runtimeObject";import{resolveAssetParameters as i}from"../resolveAssetParameters";import{detectDeviceProfile as o}from"../detectDeviceType";import{resolveTargetedUri as n}from"../resolveTargetedUri";import{resolveExternalVendorParameters as d}from"../resolveExternalVendorConfigurations";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 r(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}}resolveExternalVendorConfiguration(e){const s=d(e,i(this.state.sessionAssetParameters,this.state.updatedAssetParameters,void 0,void 0),a({customerMacros:this.state.sessionAssetParameterMacros,element:this.deps.container,breakDurationSec:void 0}));for(const{key:e,macro:t}of s.unresolved)this.deps.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}of s.omitted)this.deps.diagnose("DA-ASSET-PARAMETER-OMITTED",`Asset parameter '${e}' not sent: macro '${t}' is empty.`,{key:e,macro:t});return s.configuration}resolveAssetParameterMacros(e,s,r,i,o){const n=t(e,a({customerMacros:this.state.sessionAssetParameterMacros,element:this.deps.container,breakDurationSec:"session"===r?void 0:s}),i);for(const{key:e,macro:s}of n.unresolved)this.deps.diagnose("DA-ASSET-MACRO-UNKNOWN",`Asset parameter '${e}' sent with literal macro '${s}': the macro has no value.`,{...o,key:e,macro:s});for(const{key:e,macro:s,pair:t}of n.omitted)this.deps.diagnose("DA-ASSET-PARAMETER-OMITTED",`Asset parameter '${e}' not sent: macro '${s}' is empty.`,{...o,key:e,macro:s,...void 0!==t?{pair:t}:{}});return n.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){if(void 0===this.state.detectedDeviceProfile){const e=o();void 0!==this.state.detectedDeviceType?e.deviceType=this.state.detectedDeviceType:this.state.detectedDeviceType=e.deviceType,this.state.detectedDeviceProfile=e}return n(e,this.state.detectedDeviceProfile??this.state.detectedDeviceType,e=>this.deps.diagnose(e.code,`Targeting ${e.field} was rejected.`,{field:e.field,...void 0===e.value?{}:{value:e.value}}))}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AssetType as e,BreakFormat as t,Vendor as s,MediaType as r,isVastAsset as i}from"../../types/BreakManifest";import{AdError as a}from"../../types/AdError";import{resolveVastAdmission as d}from"../resolveVastAdmission";import{classifyMediaError as n,toClassifiedAdError as o}from"./classifyMediaError";import{VastAdManager as h,isImaCsaiSdkAvailable as p}from"../VastAdManager";import{invalidateMediaPreload as c}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 d=this.currentBreak,n=this.deps.getAdPlayer();if(!d||!n)return;const h=this.state.preparedMedia,p=c(this.state),l=()=>this.state.preloadGeneration===p&&this.currentBreak===d&&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),i(e))return void this.playVastAsset(e,t,s);if(e.mediaType===r.IMAGE)return void await this.playImageAsset(e,t,s);const u=await this.resolveAssetUri(e,this.state.effectiveBreakDurationSec??d.duration);if(!l())return;if(!u)return void this.deps.onAdError(this.missingUriError(e));this.deps.log("Resolved URI:",u),this.deps.reportPhase("uri-resolved");const A=d.id;try{this.deps.armAdStartBudget(e);if(0===t&&h?.breakId===A&&h.assetId===e.id&&h.uri===u&&h.player===n)this.deps.reportPhase("load-skipped-preloaded");else{if(this.deps.reportPhase("load-start"),!await this.deps.loadWithinBudget(()=>n.load(u),{breakId:A,assetId:e.id,uri:u})||!l())return;this.deps.reportPhase("load-resolved")}this.reportPreparedDuration(n,d,e,t,s);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,A),await e}else{let e=null;const t=await Promise.race([this.playRetryingInterruption(n,A).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 a(`Ad did not start within ${this.state.adStartBudgetMs}ms ad-start budget`,"DA-AD-START-TIMEOUT"))}if(!l())return;this.state.adStartDeadlineMs=null,this.state.adStartBudgetMs=0,this.deps.transferPictureInPictureToAd();const i=this.deps.getSequencer();i?(this.deps.isGamPodAsset(e)&&this.deps.beginGamPodTracking(e),await this.deps.drive(i.onOutcome({kind:"asset-started"}))):this.state.callbacks?.onAdStart(this.currentBreak,e,t,s)}catch(e){if(!l())return;
|
|
1
|
+
import{AssetType as e,BreakFormat as t,Vendor as s,MediaType as r,isVastAsset as i}from"../../types/BreakManifest";import{AdError as a}from"../../types/AdError";import{resolveVastAdmission as d}from"../resolveVastAdmission";import{classifyMediaError as n,toClassifiedAdError as o}from"./classifyMediaError";import{VastAdManager as h,isImaCsaiSdkAvailable as p}from"../VastAdManager";import{invalidateMediaPreload as c}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 d=this.currentBreak,n=this.deps.getAdPlayer();if(!d||!n)return;const h=this.state.preparedMedia,p=c(this.state),l=()=>this.state.preloadGeneration===p&&this.currentBreak===d&&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),i(e))return void this.playVastAsset(e,t,s);if(e.mediaType===r.IMAGE)return void await this.playImageAsset(e,t,s);const u=await this.resolveAssetUri(e,this.state.effectiveBreakDurationSec??d.duration);if(!l())return;if(!u)return void this.deps.onAdError(this.missingUriError(e));this.deps.log("Resolved URI:",u),this.deps.reportPhase("uri-resolved");const A=d.id;try{this.deps.armAdStartBudget(e);if(0===t&&h?.breakId===A&&h.assetId===e.id&&h.uri===u&&h.player===n)this.deps.reportPhase("load-skipped-preloaded");else{if(this.deps.reportPhase("load-start"),!await this.deps.loadWithinBudget(()=>n.load(u),{breakId:A,assetId:e.id,uri:u})||!l())return;this.deps.reportPhase("load-resolved")}this.reportPreparedDuration(n,d,e,t,s);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,A),await e}else{let e=null;const t=await Promise.race([this.playRetryingInterruption(n,A).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 a(`Ad did not start within ${this.state.adStartBudgetMs}ms ad-start budget`,"DA-AD-START-TIMEOUT"))}if(!l())return;this.state.adStartDeadlineMs=null,this.state.adStartBudgetMs=0,this.deps.transferPictureInPictureToAd();const i=this.deps.getSequencer();i?(this.deps.isGamPodAsset(e)&&this.deps.beginGamPodTracking(e),await this.deps.drive(i.onOutcome({kind:"asset-started"}))):this.state.callbacks?.onAdStart(this.currentBreak,e,t,s)}catch(e){if(!l())return;this.deps.onAdError(o(e))}}reportPreparedDuration(e,t,s,r,i){const a=e.duration;if(!Number.isFinite(a)||a<=0)return;const d=s.duration;this.deps.diagnose("DA-AD-DURATION-PREPARED",`Ad media for break ${t.id} prepared: ${a}s of playable ad`,{breakId:t.id,assetId:s.id,index:r,total:i,preparedDurationSec:a,..."number"==typeof d?{declaredDurationSec:d}:{},breakDurationSec:this.state.effectiveBreakDurationSec??t.duration})}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 i=this.deps.getVariant(this.currentBreak)?.format??t.SINGLE,n=d({format:i,ssai:!1});if(!n.admitted)return this.deps.diagnose(n.diagnostic??"DA-VAST-UNSUPPORTED-FORMAT",`VAST asset '${e.id}' is not supported in '${i}' breaks (single/double/lshape_ad only); skipping.`,{breakId:this.currentBreak.id,assetId:e.id,format:i}),void this.deps.onAdError(new a(`VAST not supported in ${i} format`,n.diagnostic??"DA-VAST-UNSUPPORTED-FORMAT"));if(!p())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 a("IMA client-side SDK (ima3.js) not available","DA-VAST-IMA-SDK-MISSING"));const o=this.deps.buildVastTagUrl(e,this.currentBreak);if(!o)return void this.deps.onAdError(new a("No valid VAST tag URL for asset","DA-AD-URI-MISSING"));const c=this.deps.getAdPlayer(),l=c?.videoElement,u=this.deps.getAdContainer();if(!u||!l||!c)return void this.deps.onAdError(new a("VAST playout requires an ad container and ad video element","DA-AD-URI-MISSING"));this.deps.revealFirstFrame(),l.style.cssText="display:block;width:100%;height:100%;object-fit:contain;",this.state.vastAdManager||(this.state.vastAdManager=new h(u,l,this.deps.debug)),this.state.vastAdManager.setCallbacks({onAdStarted:t=>{if(!this.currentBreak)return;this.state.startPlaybackCutoff?.(),this.deps.setVastPodPosition(t);const i=this.deps.getSequencer();i?this.deps.drive(i.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:",o);(this.state.vastAdManager.hasPreloadedManager()?(this.state.vastAdManager.setMuted(c.muted),this.state.vastAdManager.startPreloaded()):this.state.vastAdManager.playVast(o,{muted:c.muted})).then(()=>{this.deps.onAdEnded()},t=>{const s=t instanceof Error?t.message:String(t),r=/ima3\.js|client-side SDK/i.test(s)?"DA-VAST-IMA-SDK-MISSING":"DA-VAST-IMA-ERROR",i=t instanceof a?t:new a(s,r);this.deps.diagnose(r,s,{...this.currentBreak?{breakId:this.currentBreak.id}:{},assetId:e.id}),this.deps.onAdError(i)})}async playImageAsset(e,t,s){const r=this.currentBreak,i=this.deps.getAdMediaContainer();if(!r||!i)return;const d=this.state.effectiveBreakDurationSec??r.duration,n=await this.resolveAssetUri(e,d);if(!n)return void this.deps.onAdError(this.missingUriError(e));const o=document.createElement("img");o.className="dolby-overlay-image",o.style.cssText="display:block;width:100%;height:100%;object-fit:contain;",this.deps.setOverlayImage(o);const h=e.duration??d;o.onload=()=>{if(this.deps.getOverlayImage()!==o||!this.currentBreak)return;this.state.startPlaybackCutoff?.();const r=this.deps.getSequencer();r?this.deps.drive(r.onOutcome({kind:"asset-started"})):this.state.callbacks?.onAdStart(this.currentBreak,e,t,s),h>0?this.deps.setImageAssetTimer(setTimeout(()=>this.onImageAssetEnded(),1e3*h)):this.onImageAssetEnded()},o.onerror=()=>{this.deps.getOverlayImage()===o&&this.deps.onAdError(new a(`Overlay image failed to load: ${n}`,"DA-IMAGE-LOAD-FAILED"))},o.src=n,i.appendChild(o)}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,s=n(e);if(t&&("number"==typeof t.code||t.message)){const e="number"==typeof t.code?` (code ${t.code})`:"",r=t.message?`: ${t.message}`:"";return new a(`Ad playback error${e}${r}`,s)}return new a("Ad playback error",s)}missingUriError(e){return this.deps.hasGamIdentityMismatch(e)?new a("GAM pod asset identity does not match the stream session","DA-GAM-POD-IDENTITY-MISMATCH"):new a("No valid URI for asset","DA-AD-URI-MISSING")}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function resumeContentAfterBreak(e,t){const{breakInfo:
|
|
1
|
+
export async function resumeContentAfterBreak(e,t){const{breakInfo:n,earlyReturnOffsetSec:r,isLiveResume:a,released:i,isCurrent:o}=t,{contentPlayer:s,preloadMode:d,contentRecovery:l,resumeCoordinator:c,log:u}=e;if(i&&(await Promise.resolve(i).catch(e=>{u("Ad media release failed:",e)}),!o()))return;const m=()=>{a&&setTimeout(()=>e.getCallbacks()?.onContentReloading?.(!1),2e3)},p=async()=>{await s.play().catch(e=>{u("Content resume failed:",e)}).finally(m)};if("recreate"===l){if("function"==typeof s.recreateMediaPipeline)return void await async function(e,t,n){const{breakInfo:r,earlyReturnOffsetSec:a,isLiveResume:i,isCurrent:o}=t,{contentPlayer:s,resumeCoordinator:d,diagnose:l,preloadMode:c}=e,u=s.recreateMediaPipeline;if(!u)return;if("single-decoder"===c&&(await new Promise(e=>setTimeout(e,300)),!o()))return;i&&e.getCallbacks()?.onContentReloading?.(!0);const m=d.resolveResumeTarget(r,a)??s.currentTime;d.noteContentReload();const p=()=>"undefined"!=typeof performance?performance.now():Date.now(),f=p(),C=u.call(s,{startTime:m});let E,T=null;try{await Promise.race([C,new Promise((e,t)=>{E=setTimeout(()=>t(new Error("recreateMediaPipeline timed out")),1e4)})])}catch(e){T=e}finally{void 0!==E&&clearTimeout(E)}if(!o())return;if(null===T){const e=Math.round(p()-f);l("DA-CONTENT-PIPELINE-RECREATED",`Content media pipeline rebuilt at ${m}s for break ${r.id} in ${e}ms`,{breakId:r.id,startTime:m,durationMs:e}),d.probeResumeLanding(r.id,m)}else{const e=T instanceof Error?T.message:String(T);l("DA-CONTENT-PIPELINE-RECREATE-FAILED",`Content media pipeline rebuild for break ${r.id} failed (${e}); resuming in place`,{breakId:r.id,startTime:m,reason:e}),d.probeResumeLanding(r.id,m),s.seek(m)}await n()}(e,t,p);u('Content recovery "recreate" requested but the content adapter does not implement recreateMediaPipeline(); resuming in place with seek + play'),e.diagnose("DA-CONTENT-PIPELINE-RECREATE-FAILED",'Content recovery "recreate" requested but the content adapter does not implement recreateMediaPipeline(); resuming in place',{breakId:n.id,startTime:s.currentTime,reason:"unsupported-adapter"})}const f=()=>{o()&&(a&&e.getCallbacks()?.onContentReloading?.(!0),c.applyResumeSeek(n,r),p())};"single-decoder"===d?setTimeout(f,300):f()}
|