@brandbrigade/ott-bb-player 1.0.69 → 1.1.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/README.md +122 -270
- package/dist/OTTPlayer.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,358 +1,210 @@
|
|
|
1
1
|
# OTT-BB-Player
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Table of Contents
|
|
6
|
-
|
|
7
|
-
- [Overview](#Overview)
|
|
8
|
-
- [Installation](#installation)
|
|
9
|
-
- [HowTo](#HowTo)
|
|
10
|
-
- [Example](#example)
|
|
11
|
-
- [Changelog](#changelog)
|
|
12
|
-
|
|
13
|
-
## Overview
|
|
14
|
-
|
|
15
|
-
The SDK allows to augment targeted ads on top of DRM1 stream, providing that the same content is/was augmetned by BrandBrigade and the augmentation metadata is stored in the BrandBrigade cloud Smart-Feed, and providing that the stream contains embeded timecodes that match in a frame-accurate manner the timecode embedded in the smart feed.
|
|
3
|
+
BrandBrigade OTT Player SDK for targeted ad augmentation on live streams.
|
|
16
4
|
|
|
17
5
|
## Installation
|
|
18
6
|
|
|
19
|
-
To install My Project, follow these steps:
|
|
20
|
-
|
|
21
|
-
1. Login into npmjs repo if you are not logged in
|
|
22
|
-
|
|
23
|
-
```bash
|
|
24
|
-
npm login
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
2. Use npm to install the package
|
|
28
|
-
|
|
29
7
|
```bash
|
|
30
|
-
npm install @brandbrigade/ott-bb-player
|
|
8
|
+
npm install @brandbrigade/ott-bb-player
|
|
31
9
|
```
|
|
32
10
|
|
|
33
|
-
##
|
|
11
|
+
## Usage
|
|
34
12
|
|
|
35
13
|
### Initialization
|
|
36
14
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
4. A channel name: The programmatic emulation channel to demonstrate the targeted ad
|
|
47
|
-
|
|
48
|
-
```
|
|
49
|
-
bbPlayer = new BB.OTTPlayer(
|
|
50
|
-
video, //Video Tag
|
|
51
|
-
30000/1001, // frame rate
|
|
52
|
-
{ gameId:<game id>,//game id
|
|
53
|
-
augmentation:{“channelName”:”nba”}});//channel name
|
|
15
|
+
```javascript
|
|
16
|
+
const bbPlayer = new BB.OTTPlayer(
|
|
17
|
+
videoElement,
|
|
18
|
+
frameRate, // e.g., 30000/1001 for 29.97 fps
|
|
19
|
+
{
|
|
20
|
+
gameId: 'game_identifier',
|
|
21
|
+
augmentation: { channelName: 'channel_name' }
|
|
22
|
+
}
|
|
23
|
+
);
|
|
54
24
|
```
|
|
55
25
|
|
|
56
|
-
##
|
|
26
|
+
## API Reference
|
|
57
27
|
|
|
58
|
-
|
|
59
|
-
A test page hosted on the BB server can be accessed [here](http://bb-ott-player.s3-website-us-east-1.amazonaws.com/demo/node_modules/@brandbrigade/ott-bb-player/sample.html)
|
|
28
|
+
### Event Integration
|
|
60
29
|
|
|
61
|
-
|
|
30
|
+
#### `onNewMetadata(event)`
|
|
31
|
+
Forward MediaKind metadata events containing timecode information.
|
|
62
32
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
```
|
|
69
|
-
var config = {
|
|
70
|
-
"url":"https://injecto-streams.s3-accelerate.amazonaws.com/hls_fileTest_tmp/index_test.m3u8",
|
|
71
|
-
"gameId":"“arena_nba_BB_test_Lakers_long”,
|
|
72
|
-
"channel":"nba"
|
|
73
|
-
};
|
|
33
|
+
```javascript
|
|
34
|
+
wmcMgr.addEventListener(wmcEvents.AMC_EVENT_PLAYER_METADATA, (event) => {
|
|
35
|
+
bbPlayer.onNewMetadata(event);
|
|
36
|
+
});
|
|
74
37
|
```
|
|
75
38
|
|
|
76
|
-
|
|
39
|
+
#### `onNewSegment(event)`
|
|
40
|
+
Forward MediaKind segment playback events for synchronization.
|
|
77
41
|
|
|
42
|
+
```javascript
|
|
43
|
+
wmcMgr.addEventListener(wmcEvents.AMC_EVENT_PLAYER_SEGMENT_PLAYBACK, (event) => {
|
|
44
|
+
bbPlayer.onNewSegment(event);
|
|
45
|
+
});
|
|
78
46
|
```
|
|
79
|
-
function onNewMetadata(eventObj) {
|
|
80
|
-
bbPlayer.onNewMetadata(eventObj)
|
|
81
|
-
};
|
|
82
|
-
function onNewSegment(eventObj) {
|
|
83
|
-
bbPlayer.onNewSegment(eventObj);
|
|
84
|
-
};
|
|
85
|
-
wmcMgr.addEventListener(wmcEvents.AMC_EVENT_PLAYER_METADATA, onNewMetadata);
|
|
86
|
-
wmcMgr.addEventListener(wmcEvents.AMC_EVENT_PLAYER_SEGMENT_PLAYBACK, onNewSegment);
|
|
87
|
-
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
### Control
|
|
91
47
|
|
|
92
|
-
|
|
48
|
+
#### `onAdEvent(eventType)`
|
|
49
|
+
Notify player of ad events to pause/resume augmentation.
|
|
93
50
|
|
|
51
|
+
```javascript
|
|
52
|
+
bbPlayer.onAdEvent('start'); // Pause augmentation during ad
|
|
53
|
+
bbPlayer.onAdEvent('end'); // Resume augmentation after ad
|
|
94
54
|
```
|
|
95
|
-
bbPlayer.Toggle({true|false});
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
## Changelog
|
|
99
|
-
|
|
100
|
-
### Version 1.0.0
|
|
101
|
-
|
|
102
|
-
Initial version
|
|
103
|
-
|
|
104
|
-
### Version 1.0.1
|
|
105
|
-
|
|
106
|
-
Initial version
|
|
107
|
-
|
|
108
|
-
### Version 1.0.2
|
|
109
|
-
|
|
110
|
-
Initial version
|
|
111
|
-
|
|
112
|
-
### Version 1.0.3
|
|
113
|
-
|
|
114
|
-
Added readme.md
|
|
115
|
-
|
|
116
|
-
### Version 1.0.4
|
|
117
|
-
|
|
118
|
-
Added support of 59.94 streams
|
|
119
|
-
|
|
120
|
-
Added interface functions to get sync timecodes from MK MetadataEvents
|
|
121
|
-
|
|
122
|
-
### Version 1.0.5
|
|
123
|
-
|
|
124
|
-
Added support of Safari on Mac
|
|
125
|
-
|
|
126
|
-
### Version 1.0.6
|
|
127
|
-
|
|
128
|
-
Enabled support of Safari on Mac
|
|
129
|
-
|
|
130
|
-
### Version 1.0.7
|
|
131
|
-
|
|
132
|
-
Fixed Safari issue.
|
|
133
|
-
Improved Chrome rendering
|
|
134
|
-
|
|
135
|
-
### Version 1.0.8
|
|
136
|
-
|
|
137
|
-
Added usage of TimeCodesSync service
|
|
138
|
-
|
|
139
|
-
### Version 1.0.9
|
|
140
|
-
|
|
141
|
-
Bug fix
|
|
142
|
-
|
|
143
|
-
### Version 1.0.10
|
|
144
|
-
|
|
145
|
-
Bug fix
|
|
146
|
-
|
|
147
|
-
### Version 1.0.11
|
|
148
|
-
|
|
149
|
-
Bug fix
|
|
150
|
-
|
|
151
|
-
### Version 1.0.12
|
|
152
|
-
|
|
153
|
-
All is packed to one file
|
|
154
|
-
|
|
155
|
-
### Version 1.0.13
|
|
156
|
-
|
|
157
|
-
Chrome on MK REF App support
|
|
158
|
-
|
|
159
|
-
### Version 1.0.14
|
|
160
|
-
|
|
161
|
-
Safari on MK REF App support
|
|
162
55
|
|
|
163
|
-
###
|
|
56
|
+
### Control Methods
|
|
164
57
|
|
|
165
|
-
|
|
58
|
+
#### `toggle(enabled)`
|
|
59
|
+
Enable or disable augmentation rendering.
|
|
166
60
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
### Version 1.0.17
|
|
172
|
-
|
|
173
|
-
Improvements
|
|
174
|
-
|
|
175
|
-
### Version 1.0.18
|
|
176
|
-
|
|
177
|
-
Improvements
|
|
178
|
-
|
|
179
|
-
### Version v1.0.19
|
|
180
|
-
|
|
181
|
-
Chrome-Mac support
|
|
182
|
-
|
|
183
|
-
### Version v1.0.20
|
|
184
|
-
|
|
185
|
-
Improvements### Version v1.0.21
|
|
186
|
-
test26
|
|
187
|
-
|
|
188
|
-
### Version v1.0.22
|
|
189
|
-
|
|
190
|
-
test26
|
|
191
|
-
|
|
192
|
-
### Version v1.0.23
|
|
193
|
-
|
|
194
|
-
test_v_1.0.23
|
|
195
|
-
|
|
196
|
-
### Version v1.0.24
|
|
197
|
-
|
|
198
|
-
test
|
|
199
|
-
|
|
200
|
-
### Version v1.0.25
|
|
201
|
-
|
|
202
|
-
test
|
|
203
|
-
|
|
204
|
-
### Version v1.0.26
|
|
205
|
-
|
|
206
|
-
test
|
|
207
|
-
|
|
208
|
-
### Version v1.0.27
|
|
209
|
-
|
|
210
|
-
test
|
|
211
|
-
|
|
212
|
-
### Version v1.0.28
|
|
213
|
-
|
|
214
|
-
test
|
|
215
|
-
|
|
216
|
-
### Version v1.0.29
|
|
217
|
-
|
|
218
|
-
test
|
|
219
|
-
|
|
220
|
-
### Version v1.0.30
|
|
221
|
-
|
|
222
|
-
test
|
|
223
|
-
|
|
224
|
-
### Version v1.0.31
|
|
225
|
-
|
|
226
|
-
test
|
|
61
|
+
```javascript
|
|
62
|
+
bbPlayer.toggle(true); // Enable
|
|
63
|
+
bbPlayer.toggle(false); // Disable
|
|
64
|
+
```
|
|
227
65
|
|
|
228
|
-
|
|
66
|
+
#### `setMediaInfo(mediaInfo)`
|
|
67
|
+
Update media stream information (fps, bitrate).
|
|
229
68
|
|
|
230
|
-
|
|
69
|
+
```javascript
|
|
70
|
+
bbPlayer.setMediaInfo({ fps: 29.97, bitrate: 5000000 });
|
|
71
|
+
```
|
|
231
72
|
|
|
232
|
-
|
|
73
|
+
#### `setFps(fps)`
|
|
74
|
+
Update frame rate independently.
|
|
233
75
|
|
|
234
|
-
|
|
76
|
+
```javascript
|
|
77
|
+
bbPlayer.setFps(29.97);
|
|
78
|
+
```
|
|
235
79
|
|
|
236
|
-
###
|
|
80
|
+
### Asset Override Methods
|
|
237
81
|
|
|
238
|
-
|
|
82
|
+
#### `setAd(source, placeholder?)`
|
|
83
|
+
Override ad creative at runtime. Accepts URL, Blob, or ImageBitmap.
|
|
239
84
|
|
|
240
|
-
|
|
85
|
+
```javascript
|
|
86
|
+
bbPlayer.setAd('https://example.com/ad.png', 'brand_name');
|
|
87
|
+
bbPlayer.setAd(adBlob);
|
|
88
|
+
bbPlayer.setAd(imageBitmap);
|
|
89
|
+
```
|
|
241
90
|
|
|
242
|
-
|
|
91
|
+
#### `setLED(source)`
|
|
92
|
+
Override LED board creative. Accepts URL, Blob, or ImageBitmap.
|
|
243
93
|
|
|
244
|
-
|
|
94
|
+
```javascript
|
|
95
|
+
bbPlayer.setLED('https://example.com/led.png');
|
|
96
|
+
bbPlayer.setLED(ledBlob);
|
|
97
|
+
bbPlayer.setLED(imageBitmap);
|
|
98
|
+
```
|
|
245
99
|
|
|
246
|
-
|
|
100
|
+
#### `setGameParams(gameParams)`
|
|
101
|
+
Manually override game parameters (offsets, bucket info).
|
|
102
|
+
|
|
103
|
+
```javascript
|
|
104
|
+
bbPlayer.setGameParams({
|
|
105
|
+
bucketName: 'game-bucket',
|
|
106
|
+
offsets: [{ frame: 0, offset: 0, timecode: '00:00:00:00' }],
|
|
107
|
+
startZip: 'start.zip',
|
|
108
|
+
endZip: 'end.zip',
|
|
109
|
+
customerId: 'customer_id',
|
|
110
|
+
customerName: 'Customer Name'
|
|
111
|
+
});
|
|
112
|
+
```
|
|
247
113
|
|
|
248
|
-
###
|
|
114
|
+
### Event Subscription
|
|
249
115
|
|
|
250
|
-
|
|
116
|
+
#### `on(eventName, listener)`
|
|
117
|
+
Subscribe to player events.
|
|
251
118
|
|
|
252
|
-
|
|
119
|
+
```javascript
|
|
120
|
+
bbPlayer.on('augmentationStatusChanged', (event) => {
|
|
121
|
+
console.log('Status:', event.detail);
|
|
122
|
+
});
|
|
123
|
+
```
|
|
253
124
|
|
|
254
|
-
|
|
125
|
+
#### `off(eventName, listener)`
|
|
126
|
+
Unsubscribe from player events.
|
|
255
127
|
|
|
256
|
-
|
|
128
|
+
```javascript
|
|
129
|
+
bbPlayer.off('augmentationStatusChanged', listener);
|
|
130
|
+
```
|
|
257
131
|
|
|
258
|
-
|
|
132
|
+
### Lifecycle
|
|
259
133
|
|
|
260
|
-
|
|
134
|
+
#### `destroy()`
|
|
135
|
+
Cleanup and dispose of player instance. Terminates workers, removes event listeners, and frees resources.
|
|
261
136
|
|
|
262
|
-
|
|
137
|
+
```javascript
|
|
138
|
+
bbPlayer.destroy();
|
|
139
|
+
```
|
|
263
140
|
|
|
264
|
-
|
|
141
|
+
## Platform Support
|
|
265
142
|
|
|
266
|
-
|
|
143
|
+
- Chrome (Mac, Windows)
|
|
267
144
|
|
|
268
|
-
### Version v1.0.47
|
|
269
145
|
|
|
270
|
-
|
|
146
|
+
## Changelog
|
|
271
147
|
|
|
272
|
-
|
|
148
|
+
**Version v1.0.47** - OTT Web rebuild, supports Chrome Mac
|
|
273
149
|
|
|
274
|
-
Fixed augmentation size bug,
|
|
150
|
+
**Version v1.0.49** - Fixed augmentation size bug,
|
|
275
151
|
Updated configurations
|
|
276
152
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
Fixed multiple instances of OTT Player,
|
|
153
|
+
**Version v1.0.50** - Fixed multiple instances of OTT Player,
|
|
280
154
|
Applied SetInterval in Adepter,
|
|
281
155
|
Added OTTActions support
|
|
282
156
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
Adapter, Downloader and Decoder Settings added to global player options
|
|
157
|
+
**Version v1.0.52** - Adapter, Downloader and Decoder Settings added to global player options
|
|
286
158
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
More debug metrix added,
|
|
159
|
+
**Version v1.0.53** - More debug metrix added,
|
|
290
160
|
Pixel tickers color changed to dark gray
|
|
291
161
|
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
Pattern tracking based renderer calls implemented
|
|
162
|
+
**Version v1.0.55** - Pattern tracking based renderer calls implemented
|
|
295
163
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
Added support for Windows Chrome,
|
|
164
|
+
**Version v1.0.57** - Added support for Windows Chrome,
|
|
299
165
|
Updated logging
|
|
300
166
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
Improve support for Windows Chrome
|
|
167
|
+
**Version v1.0.58** - Improve support for Windows Chrome
|
|
304
168
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
Logging to Datadog Enabled
|
|
169
|
+
**Version v1.0.59** - Logging to Datadog Enabled
|
|
308
170
|
Minor improvements
|
|
309
171
|
|
|
310
|
-
|
|
311
|
-
|
|
172
|
+
**Version v1.0.60** -
|
|
312
173
|
- Game parameters are now fetched every 10 seconds.
|
|
313
174
|
- After seeking, if new metadata with a relevant timecode is not received, the augmentation will stop.
|
|
314
175
|
- Fixed an issue where the timecode exceeds 24 hours.
|
|
315
176
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
WebGL Quad rendering optimization
|
|
177
|
+
**Version v1.0.61** - WebGL Quad rendering optimization
|
|
319
178
|
Added error logging in case of the missing JSON in zip
|
|
320
179
|
|
|
321
|
-
|
|
180
|
+
**Version v1.0.62** - Minor Update
|
|
322
181
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
### Version v1.0.63
|
|
326
|
-
|
|
327
|
-
Added setMediaInfo(mediaInfo: { fps?: number; bitrate?: number }) for communication with MK
|
|
182
|
+
**Version v1.0.63** - Added setMediaInfo(mediaInfo: { fps?: number; bitrate?: number }) for communication with MK
|
|
328
183
|
Added logging metrics to backend
|
|
329
184
|
Hardcoded BurkerKing logo to be replaced by campaigns
|
|
330
185
|
Dev tests of Firefox support
|
|
331
186
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
Added Beacon Evenst
|
|
187
|
+
**Version v1.0.64** - Added Beacon Evenst
|
|
335
188
|
Added onAdEvent
|
|
336
189
|
Ad campaings connected
|
|
337
190
|
Added internal metrics logging to cloud
|
|
338
191
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
Added global augmentation status to beacon events
|
|
192
|
+
**Version v1.0.65** - Added global augmentation status to beacon events
|
|
342
193
|
Console logs cleared
|
|
343
194
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
Minor fixes
|
|
347
|
-
|
|
348
|
-
### Version v1.0.67
|
|
195
|
+
**Version v1.0.66** - Minor fixes
|
|
349
196
|
|
|
350
|
-
Killswitch status is now checked on game params headers instead of zip headers
|
|
197
|
+
**Version v1.0.67** - Killswitch status is now checked on game params headers instead of zip headers
|
|
351
198
|
Added metrics for zip fetch as URL parameters
|
|
352
199
|
Implemented a zip fetch retry mechanism while there is still time to fetch them
|
|
353
200
|
Added OTTPlayer off method to unsubscribe from player events
|
|
354
201
|
Implemented destroy method to properly dispose OTTPlayer instances
|
|
355
202
|
|
|
356
|
-
|
|
203
|
+
**Version v1.0.68** - Zip download logic fixed
|
|
357
204
|
|
|
358
|
-
|
|
205
|
+
**Version v1.1.00** -
|
|
206
|
+
- Add banchmarking
|
|
207
|
+
- Add Lifecicle management
|
|
208
|
+
- Add status overlay
|
|
209
|
+
- Fix toggle(flag: boolean)
|
|
210
|
+
- Update onAdEvent(eventType: 'start' | 'end') logic
|
package/dist/OTTPlayer.js
CHANGED
|
@@ -491,10 +491,10 @@ void main(){
|
|
|
491
491
|
|
|
492
492
|
}
|
|
493
493
|
|
|
494
|
-
`,s=this.createShader(this.gl.VERTEX_SHADER,r),i=this.createShader(this.gl.FRAGMENT_SHADER,n);this.program=this.createProgram(s,i),this.gl.useProgram(this.program),this.positionLoc=this.gl.getAttribLocation(this.program,"a_position"),this.texCoordLoc=this.gl.getAttribLocation(this.program,"a_texCoord"),this.resolutionLoc=this.gl.getUniformLocation(this.program,"u_resolution"),this.videoSizeLoc=this.gl.getUniformLocation(this.program,"u_videoSize"),this.textureLoc=this.gl.getUniformLocation(this.program,"u_image"),this.positionBuffer=this.gl.createBuffer(),this.texCoordBuffer=this.gl.createBuffer(),this.videoTexture=this.gl.createTexture(),this.fbo=this.gl.createFramebuffer(),this.outTex=this.gl.createTexture(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,this.OUT_WIDTH,0,0,this.OUT_HEIGHT,0,this.OUT_HEIGHT,this.OUT_WIDTH,0,this.OUT_WIDTH,this.OUT_HEIGHT]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.positionLoc),this.gl.vertexAttribPointer(this.positionLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.texCoordLoc),this.gl.vertexAttribPointer(this.texCoordLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.outTex),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.OUT_WIDTH,this.OUT_HEIGHT,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.outTex,0)}createShader(e,r){const n=this.gl.createShader(e);if(this.gl.shaderSource(n,r),this.gl.compileShader(n),!this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)){const s=this.gl.getShaderInfoLog(n);throw this.gl.deleteShader(n),new Error("Shader compile failed: "+s)}return n}createProgram(e,r){const n=this.gl.createProgram();if(this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),!this.gl.getProgramParameter(n,this.gl.LINK_STATUS)){const s=this.gl.getProgramInfoLog(n);throw this.gl.deleteProgram(n),new Error("Program link failed: "+s)}return this.gl.detachShader(n,e),this.gl.detachShader(n,r),this.gl.deleteShader(e),this.gl.deleteShader(r),n}decode(e){const r=e.videoWidth|0,n=e.videoHeight|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}decodeFromImageBitmap(e){const r=e.width|0,n=e.height|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}dispose(){this.videoTexture&&this.gl.deleteTexture(this.videoTexture),this.outTex&&this.gl.deleteTexture(this.outTex),this.fbo&&this.gl.deleteFramebuffer(this.fbo),this.positionBuffer&&this.gl.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&this.gl.deleteBuffer(this.texCoordBuffer),this.program&&this.gl.deleteProgram(this.program)}}const pe=class pe{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecodeSet=!1,this.firstFrameTimecode=[0,0,0,0,0],this.firstVideoFrameCallbackFired=!1,this.isMKAdPlaying=!1,this.loggerTimeoutStart=0,this.loggerTimeout=1e4,this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=100,this.resumedAt=0,this.SKIP_PROCESSING_AFTER_RESUME_MS=1e3,this.afData={counter:0,lastTimestamp:0,previousTimestamp:0,lastMetadataNow:0,timeFromLastRVFC:0,animationFPS:0,playerTimeOffset:0,lastPlayerTimeFromSync:0,lastCalculatedPlayerTimeVideoFrame:0,lastCalculatedPlayerTimeFraction:0,previousCalculatedPlayerTimeFraction:2},this.vfcData={counter:0,lastTimestamp:0,previousTimestamp:0,timeFromLastRAF:0,videoFPS:0,lastFrameMetadata:null,lastFrameMetadataNow:0,storedMetadata:[],timePerformanceNowToExpectedDisplayTime:0,timeRVFCnowToExpectedDisplayTime:0,mediaTimeOffset:0,lastMediaTimeFromSync:0,lastCalculatedMediaTimeVideoFrame:0},this.siData={counter:0,lastTimestamp:0,lastOffset:0,timeFromLastRAF:0,timeFromLastRVFC:0,lastSeenRAFCount:0,lastSeenRVFCCount:0,isRAFSeen:!1,isRVFCSeen:!1,isVideoPaused:!0,workingFps:0,refreshRate:0,RVFCmissed:0,RVFCframeExpected:0,expectedRefreshRate:0,avgExpectedRefreshRate:0,newRefreshRateFrames:0,expectedFPS:0,newFPSFrames:0,RVFCpattern:[],isRVFCpatternDetected:!1,patternTracking:[],patternTrackingIndex:-1,patternNextValue:-1,possibilityTracking:[],previousPossibilityValue:-1,lastCallback:null,lastCalculatedFrame:0,lastRendererFrameSent:0,lastMessageSent:"",compensationMode:!1,compensationCounter:0,frameCorrection:0,determineFramesIntervals:[],determineAFIntervals:[],expectedDisplayTimeReminder:0,animationFramesToDisplayTime:0},this.tcTimeStamp=0,this.timecode_offset=0,this.burnedLastTcKey=-1,this.sampleBurnedFrame=async()=>{var r;if(!(!this.OTTPlayer||!this.video)&&!(this.video.videoWidth===0||this.video.videoHeight===0)&&this.gl2Decoder)try{let n=await createImageBitmap(this.video);const s=this.gl2Decoder.decodeFromImageBitmap(n);if(!s){try{n.close()}catch{}return}const i=this.parseTcKey(s);if(i<=this.burnedLastTcKey){try{n.close()}catch{}return}this.burnedLastTcKey=i,this.metrics&&this.metrics.updateMetric("Last sent timecode",s),(r=this.OTTPlayer.clocker)==null||r.callRendererWorkerWithFrame(n,s),n=void 0}catch(n){this.logger.error("[Adapter] sampleBurnedFrame error: "+n)}},this.onAnimationFrame=r=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.previousTimestamp=this.afData.lastTimestamp,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=r,this.afData.timeFromLastRVFC=this.afData.lastTimestamp-this.vfcData.lastTimestamp,this.afData.animationFPS=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.siData.lastCallback=="RAF"&&this.siData.RVFCmissed++,this.siData.lastCallback="RAF";const n=(this.video.currentTime-this.syncPoint.playerTime)*(6e4/1001);this.afData.lastPlayerTimeFromSync=n;const s=Math.floor(n)+this.syncPoint.frame;this.afData.playerTimeOffset=L.calculateCurrentOffset(s,this.OTTPlayer.gameParams.offsets);let i=s-this.afData.playerTimeOffset;if(i<0&&(i+=5178816),i++,this.afData.lastCalculatedPlayerTimeVideoFrame=i,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=n-Math.floor(n),this.metrics)try{this.metrics.updateMetric("RAF calls",this.afData.counter),this.metrics.updateMetric("Last player time",this.video.currentTime.toFixed(4)),this.metrics.updateMetric("Last player time frame",this.afData.lastCalculatedPlayerTimeVideoFrame),this.metrics.updateMetric("Last player time fraction",this.afData.lastCalculatedPlayerTimeFraction.toFixed(4)),this.metrics.updateMetric("Last player time double frame",this.afData.lastPlayerTimeFromSync.toFixed(5)),this.metrics.updateMetric("AF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("VF ExpDispTime - AF metadata now",(this.afData.lastTimestamp-this.vfcData.lastFrameMetadata.expectedDisplayTime).toFixed(3)),this.metrics.updateMetric("Last RAF call",this.afData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("RAF - RVFC dif",this.afData.timeFromLastRVFC.toFixed(2))}catch(o){this.options&&_(this.options,"Adapter")&&console.error(o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(r,n)=>{if(this.firstVideoFrameCallbackFired||(this.firstVideoFrameCallbackFired=!0,this.logger.info("[Adapter] First video frame callback fired"),console.log("[Adapter] First video frame callback fired")),this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame);return}this.vfcData.counter++,this.vfcData.previousTimestamp=this.vfcData.lastTimestamp,this.vfcData.lastTimestamp=performance.now(),this.vfcData.timeFromLastRAF=this.vfcData.lastTimestamp-this.afData.lastTimestamp,this.siData.RVFCmissed=0,this.vfcData.videoFPS=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.siData.lastCallback="RVFC";const s=(n.mediaTime-this.syncPoint.playerTime)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=s;const i=Math.floor(s+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=L.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let o=i-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=n,this.vfcData.storedMetadata.push(n),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timePerformanceNowToExpectedDisplayTime=n.expectedDisplayTime-this.vfcData.lastTimestamp,this.vfcData.timeRVFCnowToExpectedDisplayTime=n.expectedDisplayTime-r,this.vfcData.lastFrameMetadataNow=r,this.metrics&&(this.metrics.updateMetric("MediaTime",n.mediaTime),this.metrics.updateMetric("MediaTimeWithSync",i),this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",n.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(n.presentationTime-r).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",n.presentedFrames),this.metrics.updateMetric("Metadata processing duration",n.processingDuration),this.metrics.updateMetric("Last media time double frame",this.vfcData.lastMediaTimeFromSync.toFixed(5)),this.metrics.updateMetric("VF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("RVFC to expected display time",this.vfcData.timeRVFCnowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Performance Now to expected display time",this.vfcData.timePerformanceNowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Last RVFC call",this.vfcData.lastTimestamp.toFixed(2))),this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,s,i,o;if(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;this.siData.counter===0&&this.logger.info("didStartAugmentation"),this.siData.counter++,this.siData.isVideoPaused=this.video.paused,this.siData.isRAFSeen=this.siData.lastSeenRAFCount==this.afData.counter,this.siData.isRVFCSeen=this.siData.lastSeenRVFCCount==this.vfcData.counter,this.siData.lastTimestamp=performance.now(),this.siData.timeFromLastRAF=this.siData.lastTimestamp-this.afData.lastTimestamp,this.siData.timeFromLastRVFC=this.siData.lastTimestamp-this.vfcData.lastTimestamp,this.siData.lastSeenRAFCount=this.afData.counter,this.siData.lastSeenRVFCCount=this.vfcData.counter,this.siData.workingFps=this.OTTPlayer.clocker.videoFPScalculator.getFPS(),this.siData.refreshRate=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS();const r=this.siData.lastTimestamp;if(this.OTTPlayer.statusOverlay&&r-this.lastStatusUpdate>this.STATUS_UPDATE_INTERVAL&&(this.updateStatusOverlay(),this.lastStatusUpdate=r),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const a={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:((s=this.OTTPlayer.gameParams)==null?void 0:s.bucketName)||"",offsets:((i=this.OTTPlayer.gameParams)==null?void 0:i.offsets)||[],customerId:((o=this.OTTPlayer.gameParams)==null?void 0:o.customerId)||""};this.OTTPlayer.clocker.callAdapterWorker(a)}},this.determineFrameUpdateChromeMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>4?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),this.siData.newRefreshRateFrames=0),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=1,c=5;if(this.debugControls){const d=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(d)||(o=d);const l=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(l)||(a=l);const u=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(u)||(c=u)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+a),c):this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateChromeWin=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=2,c=!1;if(this.debugControls){const u=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(u)||(o=u);const f=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(f)||(a=f),parseInt(this.debugControls.getValue("Timeout time"),10),this.debugControls.getValue("Video Captur Card Mode")==="true"&&(c=!0)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),c&&(o+=1);const d=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length,l=(d+this.siData.RVFCpattern.length-1)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[d]){let u=0;c&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame&&this.siData.RVFCpattern[l]&&(u=2),this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+u+a)}}},this.determineFrameUpdateSifariMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS||(this.siData.expectedRefreshRate&&this.siData.expectedFPS&&(this.expectedRefreshRateCalculator.addFrameDuration(1/this.siData.refreshRate),this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),Math.abs(this.siData.expectedRefreshRate-this.siData.avgExpectedRefreshRate)>3&&this.siData.newRefreshRateFrames++,Math.abs(this.siData.expectedFPS-this.siData.workingFps)>3&&this.siData.newFPSFrames++,(this.siData.newRefreshRateFrames>10||this.siData.newFPSFrames>10)&&(this.siData.newRefreshRateFrames=0,this.siData.expectedRefreshRate=0,this.siData.newFPSFrames=0,this.siData.expectedFPS=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))return;const r=Math.abs(this.siData.refreshRate-this.siData.workingFps)<2?8:20,n=1e3,s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((h,m)=>m-h),i=2,o=s[0],a=s[1],c=o-a,d=1e3/this.afData.animationFPS,l=Math.round(d/4+.1),u=this.vfcData.timeRVFCnowToExpectedDisplayTime;if(this.siData.isRVFCSeen)this.metrics;else{const h=(-u-l)/d,m=Math.ceil(h),g=(Math.round(h)-h)*d,S=Math.abs(g)<=i,E=g<=0?m-1:m+1,A=Math.abs(-u-l)<=i;if(this.metrics&&(this.metrics.updateMetric("Is Smoothing Needed",S),this.metrics.updateMetric("Is More Than Border",m),this.metrics.updateMetric("Is Smoothed",E)),S&&!A){const w=Math.min(m,E),R=Math.max(m,E);this.metrics&&this.metrics.updateMetric("Pssblty next index",""+w+" "+R),this.siData.possibilityTracking[this.siData.possibilityTracking.length-w]=2,this.siData.possibilityTracking[this.siData.possibilityTracking.length-R]=1}else S&&A&&(this.metrics&&this.metrics.updateMetric("Pssblty next index","min"),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]=1,this.siData.possibilityTracking.push(2),this.siData.possibilityTracking.push(3));if(-u<l)this.siData.expectedDisplayTimeReminder=-u;else if(c>d&&-u-(c-d)<=l)this.siData.expectedDisplayTimeReminder=-u-(c-d);else{let w=-u-c,R=0,v=this.siData.determineFramesIntervals.length-1;for(let F=this.siData.determineAFIntervals.length-1;F>=0&&(v--,!(this.siData.determineAFIntervals[F]>d&&w-(this.siData.determineAFIntervals[F]-d)<=l||w<=l||this.siData.determineFramesIntervals[v].includes("vf")&&this.siData.workingFps<40));F--)w-=this.siData.determineAFIntervals[F],R+=1;if(this.siData.patternTracking.length<R+1){this.siData.patternTracking=[!0];for(let F=0;F<R;F++)this.siData.patternTracking.push(!1)}else this.siData.patternTracking[this.siData.patternTracking.length-1-R]=!0;this.siData.animationFramesToDisplayTime=R}}if(this.siData.isRAFSeen||(this.siData.expectedDisplayTimeReminder?(this.siData.expectedDisplayTimeReminder-l,this.siData.expectedDisplayTimeReminder+c<=l?(this.siData.patternTracking.push(!0),this.siData.animationFramesToDisplayTime=0):(this.siData.patternTracking[this.siData.patternTracking.length-1]=!0,this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime=1),this.siData.expectedDisplayTimeReminder=0):(this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime+=1),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]==3?this.siData.possibilityTracking.pop():this.siData.possibilityTracking.push(0)),this.siData.patternTracking.length>n&&this.siData.patternTracking.shift(),this.siData.possibilityTracking.length>n&&this.siData.possibilityTracking.shift(),!this.siData.isRVFCpatternDetected){const h=this.siData.patternTracking;for(let m=1;m*r<=h.length;m++){for(let g=0;g+m*r<=h.length;g++){let S=!0;for(let b=0;b<r-1;b++){const E=h.slice(g+b*m,g+(b+1)*m),A=h.slice(g+(b+1)*m,g+(b+2)*m);if(!E.every((w,R)=>w===A[R])){S=!1;break}}if(S){const b=h.slice(g,g+m),E=b.every(R=>!R),A=b.every(R=>R),w=this.afData.animationFPS-this.vfcData.videoFPS;if(E||A&&w>5)continue;this.siData.RVFCpattern=b,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected){this.siData.expectedRefreshRate=this.siData.refreshRate,this.siData.expectedFPS=this.siData.workingFps;break}}}if(this.siData.RVFCpattern.length>0){const h=this.siData.RVFCpattern,m=this.siData.patternTracking;let g=-1;for(let S=m.length-h.length*5;S>=0;S--){let b=!0;for(let E=0;E<h.length*5;E++)if(h[E%h.length]!==m[S+E]){b=!1;break}if(b){g=S;break}}if(g>=0){const S=(m.length-g)%h.length,b=h[S];this.siData.patternTrackingIndex=S,this.siData.patternNextValue=b?1:0}if(m.length>=h.length*5){m.slice(m.length-h.length*5);let S=0,b=0;for(let E=0;E+h.length<=m.length;E++)m.slice(E,E+h.length).every((w,R)=>w===h[R])?(S++,b=Math.max(b,S),E+=h.length-1):S=0;b<6&&(this.siData.isRVFCpatternDetected=!1)}}const f=[];for(let h=1;h<=3;h++)f.push(this.siData.possibilityTracking[this.siData.possibilityTracking.length-this.siData.RVFCpattern.length*h]);const p=Math.max(...f);if(this.metrics){let h="";if(this.siData.isRAFSeen?h="vf: "+c.toFixed(0):h="af: "+c.toFixed(0),this.siData.determineFramesIntervals.push(h),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),!this.siData.isRAFSeen){const m=this.afData.lastTimestamp-this.afData.previousTimestamp;this.siData.determineAFIntervals.push(m),this.siData.determineAFIntervals.length>10&&this.siData.determineAFIntervals.shift()}this.siData.isRVFCSeen||this.metrics.updateMetric("Last AF to VF time",(this.vfcData.lastTimestamp-this.afData.lastTimestamp).toFixed(0)),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("AF frames intervals",this.siData.determineAFIntervals.map(m=>m.toFixed(0)).join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.map(m=>m?1:0).slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Pssblty found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pssblty array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pssblty tracking",this.siData.possibilityTracking.slice(this.siData.possibilityTracking.length>100?this.siData.possibilityTracking.length-100:0).join("")),this.metrics.updateMetric("Pssblty next value",p),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate.toFixed(5)),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(5)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames),this.metrics.updateMetric("AF To Display Time",this.siData.animationFramesToDisplayTime),this.metrics.updateMetric("Call Renderer Reached",!1)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let h=0,m=0;if(this.debugControls){const S=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(S)||(h=S);const b=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(b)||(m=b),parseInt(this.debugControls.getValue("Timeout time"),10)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset}));const g=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length+h)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[g]||p){const S=Math.ceil(this.siData.animationFramesToDisplayTime/this.siData.RVFCpattern.length)+1,b=this.siData.RVFCpattern.map(ke=>ke?1:0).join("").repeat(S),E=(this.siData.RVFCpattern.length-this.siData.patternTrackingIndex)%this.siData.RVFCpattern.length,A=b.slice(0,E==0?-this.siData.RVFCpattern.length:-E);let w=0;const R=this.siData.possibilityTracking.length-1-this.siData.animationFramesToDisplayTime;A[A.length-1-this.siData.animationFramesToDisplayTime]=="0"&&this.siData.possibilityTracking[R]==1&&(w=-1);const v=this.siData.animationFramesToDisplayTime+w,F=v<=0?"":A.slice(-v);let De=F.split("").filter(ke=>ke==="1").length*Math.round(60/this.siData.workingFps);this.siData.workingFps<40&&(De+=1),this.siData.compensationMode&&!(p==2||this.siData.previousPossibilityValue==2)&&(this.siData.compensationCounter=1,this.siData.compensationMode=!1),this.siData.compensationCounter==1?this.siData.possibilityTracking.slice(-5).every(ke=>ke===0)&&(this.siData.compensationCounter-=.1):this.siData.compensationCounter>0&&this.siData.compensationCounter<1&&(this.siData.compensationCounter=Math.max(this.siData.compensationCounter-.1,0)),p==1?this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m-1,this.siData.compensationCounter):p==2&&this.siData.previousPossibilityValue==1?this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter):this.siData.RVFCpattern[g]&&((p==2||this.siData.previousPossibilityValue==2)&&Math.abs(this.afData.animationFPS-this.siData.workingFps)<5&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m?(this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter),this.siData.compensationMode=!0):this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m,this.siData.compensationCounter)),this.metrics&&(this.metrics.updateMetric("Call Renderer Reached",!0),this.metrics.updateMetric("Is Smoothing Needed",this.siData.compensationMode),this.metrics.updateMetric("Correction",De),this.metrics.updateMetric("Compensation Counter",this.siData.compensationCounter),this.metrics.updateMetric("Repeated Pattern",b),this.metrics.updateMetric("Trimmed Pattern",A),this.metrics.updateMetric("Sliced Pattern",F),this.metrics.updateMetric("AF To Display Time Correction",w)),this.siData.previousPossibilityValue=p}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateFirefoxMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const n=5,s=1e3;if(!this.siData.isRVFCSeen){const i=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(i<=0&&this.siData.patternTracking.length<=1-i){this.siData.patternTracking=[!0];for(let o=0;o<1-i;o++)this.siData.patternTracking.push(!1)}else i<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+i]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>s&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const i=this.siData.patternTracking;for(let o=1;o*n<=i.length;o++){for(let a=0;a+o*n<=i.length;a++){let c=!0;for(let d=0;d<n-1;d++){const l=i.slice(a+d*o,a+(d+1)*o),u=i.slice(a+(d+1)*o,a+(d+2)*o);if(!l.every((f,p)=>f===u[p])){c=!1;break}}if(c){const d=i.slice(a,a+o),l=d.every(p=>!p),u=d.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(l||u&&f>5)continue;this.siData.RVFCpattern=d,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const i=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-i.length;c>=0;c--){let d=!0;for(let l=0;l<i.length;l++)if(i[l]!==o[c+l]){d=!1;break}if(d){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,d=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=d?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,d=0;for(let l=0;l+i.length<=o.length;l++)o.slice(l,l+i.length).every((f,p)=>f===i[p])?(c++,d=Math.max(d,c),l+=i.length-1):c=0;d<5&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((d,l)=>l-d),o=i[0],a=i[1],c=o-a;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(c.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let i=0,o=1;if(this.debugControls){const a=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(a)||(i=a);const c=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(c)||(o=c),parseInt(this.debugControls.getValue("Timeout time"),10)}if(this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+i)%this.siData.RVFCpattern.length]){let a=this.vfcData.lastCalculatedMediaTimeVideoFrame+o;a==this.siData.lastRendererFrameSent&&(a+=2),this.callRenderer(a)}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.callRenderer=(r,n)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=r,this.metrics&&this.metrics.updateMetric("Last sent frame",r);const s=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",s.toFixed(2));const i=L.fromFrames(r,6e4/1001);this.renderAugmentation(i,n)},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(r,n)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const s=L.toStr(r);this.siData.lastMessageSent=s,this.options&&_(this.options,"Adapter")&&console.log(`Rendering augmentation for timecode: ${s} , ${r}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",s),this.OTTPlayer.clocker.callRendererWorker(s,n)},this.onVideoSeeked=()=>{this.firstFrameTimecode=[0,0,0,0,0],this.firstFrameTimecodeSet=!1},this.clearAugmentation=r=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const n=r?L.toStr(r):void 0;this.options&&_(this.options,"Adapter")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(n,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.benchmark=new pn(e.options.BENCHMARK_DURATION_SECONDS),this.options&&_(this.options,"Adapter")&&console.log("Adapter is initialized",this.OTTPlayer),this.video=e.video,this.debug=this.options.debug?this.options.debug.on:!1,this.expectedRefreshRateCalculator=new nt(20),I.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(I.isChromeWin())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeWin;else{I.isSafariMac(),I.isFirefoxMac(),this.platformSpecificFrameUpdate=()=>{},this.logger.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),console.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),this.platformSupported=!1;return}if(this.debug){this.metrics=new jt;const r=this.metrics.createContainer(),n=this.metrics.createContainer(),s=this.metrics.createContainer(),i=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),d=this.metrics.createContainer(),l=this.metrics.createContainer(),u=this.metrics.createContainer(),f=this.metrics.createContainer(),p=this.metrics.createContainer(),h=this.metrics.createContainer(),m=this.metrics.createContainer(),g=this.metrics.createContainer(),S=this.metrics.createContainer();this.metrics.createMetric("tcTimeStamp",r),this.metrics.createMetric("timecodeOffset",r),this.metrics.createMetric("firstFrameTimecode",r),this.metrics.createMetric("frame",n),this.metrics.createMetric("playerTime",n),this.metrics.createMetric("stringTime",n),this.metrics.createMetric("lastUpdate",n),this.metrics.createMetric("MediaTime",s),this.metrics.createMetric("MediaTimeWithSync",s),this.metrics.createMetric("RAF calls",i),this.metrics.createMetric("RVFC calls",i),this.metrics.createMetric("RVFC missed",i),this.metrics.createMetric("Last sent frame",i),this.metrics.createMetric("Last sent timecode",i),this.metrics.createMetric("Last metadata media time",o),this.metrics.createMetric("Last player time",o),this.metrics.createMetric("RVFC to expected display time",o),this.metrics.createMetric("Performance Now to expected display time",o),this.metrics.createMetric("Last metadata media time frame",a),this.metrics.createMetric("Last player time frame",a),this.metrics.createMetric("Last player time fraction",a),this.metrics.createMetric("Last media time double frame",c),this.metrics.createMetric("Last player time double frame",c),this.metrics.createMetric("Compensation Counter",c),this.metrics.createMetric("AF metadata now - perf.now()",d),this.metrics.createMetric("VF metadata now - perf.now()",d),this.metrics.createMetric("VF ExpDispTime - AF metadata now",d),this.metrics.createMetric("Time to presentation time",l),this.metrics.createMetric("Metadata presented frames",l),this.metrics.createMetric("Metadata processing duration",l),this.metrics.createMetric("FPS",u),this.metrics.createMetric("Refresh rate",u),this.metrics.createMetric("Last RAF call",u),this.metrics.createMetric("Last RVFC call",u),this.metrics.createMetric("RAF - RVFC dif",u),this.metrics.createMetric("Determine frames intervals",f),this.metrics.createMetric("Last AF to VF time",p),this.metrics.createMetric("AF frames intervals",p),this.metrics.createMetric("Expected Refresh Rate",h),this.metrics.createMetric("Avg Expected Refresh Rate",h),this.metrics.createMetric("New Refresh Rate Frames",h),this.metrics.createMetric("AF To Display Time",h),this.metrics.createMetric("AF To Display Time Correction",h),this.metrics.createMetric("Call Renderer Reached",h),this.metrics.createMetric("Is Smoothing Needed",m),this.metrics.createMetric("Is More Than Border",m),this.metrics.createMetric("Is Smoothed",m),this.metrics.createMetric("Correction",m),this.metrics.createMetric("Repeated Pattern",m),this.metrics.createMetric("Trimmed Pattern",m),this.metrics.createMetric("Sliced Pattern",m),this.metrics.createMetric("Pattern found",g),this.metrics.createMetric("Pattern array",g),this.metrics.createMetric("Pattern tracking",g),this.metrics.createMetric("Pattern next index",g),this.metrics.createMetric("Pattern next value",g),this.metrics.createMetric("Pssblty found",S),this.metrics.createMetric("Pssblty array",S),this.metrics.createMetric("Pssblty tracking",S),this.metrics.createMetric("Pssblty next index",S),this.metrics.createMetric("Pssblty next value",S),this.debugControls=new un;const b=this.debugControls.createContainer(),E=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,b),this.debugControls.createInput("Window End (ms)",-11,b),this.debugControls.createSelect("Pattern offset",{"-5":-5,"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4,5:5},"0",b),this.debugControls.createCheckbox("Video Captur Card Mode",!1,b),I.isChromeWin()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"2",E):I.isSafariMac()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"0",E):this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",E),this.debugControls.createSelect("Timeout time",{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20},"5",E)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}isVideoFpsSupported(e){return e>pe.MIN_SUPPORTED_FPS&&e<=pe.MAX_SUPPORTED_FPS}setupAdapter(){const e=this.video;if(this.options.BURNED_TIMECODES_MODE){this.startBurnedPipeline();return}if(this.debug){const r=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(r);const n=r.getAvailableVideoQualities(),s={};n.forEach(a=>{s[a.label]=a.id});const i=a=>{r.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(i);this.debugControls.createSelect("videoQuality",s,n[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}startBurnedPipeline(){this.gl2Decoder=new mn,this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33)}stopBurnedPipeline(){this.burnedIntervalId&&(window.clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0),this.gl2Decoder&&(this.gl2Decoder.dispose(),this.gl2Decoder=void 0),this.burnedLastTcKey=-1}parseTcKey(e){const r=e.split("_");if(r.length<4)return-1;const n=parseInt(r[0],10)||0,s=parseInt(r[1],10)||0,i=parseInt(r[2],10)||0,o=parseInt(r[3],10)||0,a=r.length>=5&&r[4]==="1"?1:0;return((n*3600+s*60+i)*60+o)*2+a}updateStatusOverlay(){var i,o,a;const e=this.OTTPlayer.statusOverlay;e.updateMetric("support","browser",this.platformSupported,`${this.options.browserName} on ${this.options.platform}`),e.updateMetric("support","pattern",this.siData.isRVFCpatternDetected,this.siData.isRVFCpatternDetected?this.siData.RVFCpattern.map(c=>c?"1":"0").join("").slice(0,20):"Detecting...");const r=((i=this.OTTPlayer.clocker)==null?void 0:i.videoFPScalculator.getPerciseFPS())||0,n=this.isVideoFpsSupported(r);e.updateMetric("support","fps",n,r>0?`${r.toFixed(2)} fps`:"Detecting..."),e.updateMetric("support","game_params",!!this.OTTPlayer.gameParams),e.updateMetric("support","mk_ads",!this.isMKAdPlaying,this.isMKAdPlaying?"Ad in progress":"No ads"),this.syncPoint?e.updateMetric("timecode","sync_point",!0,this.syncPoint.stringTime):e.updateMetric("timecode","sync_point",!1,"Not set");const s=this.benchmark.test({gameParams:!!this.OTTPlayer.gameParams,browserSupported:this.platformSupported,patternDetected:this.siData.isRVFCpatternDetected,fpsSupported:n,noMKAdsPlaying:!this.isMKAdPlaying,syncPointSet:!!this.syncPoint});s.shouldClear&&(this.options&&_(this.options,"Adapter")&&console.log("[Benchmark] Failed - clearing augmentation. Reasons:",(o=s.failedConditions)==null?void 0:o.join(", ")),this.clearAugmentation()),e.updateMetric("benchmark","status",s.state,s.state==="TESTING"?`Stability test: ${s.remainingSeconds}s`:s.state==="FAILED"?`Failed: ${(a=s.failedConditions)==null?void 0:a.join(", ")}`:"Stable")}onNewSegmentForMetadata(e){if(!this.firstFrameTimecodeSet){const a=performance.now();a-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=a,this.logger.error("[Adapter] First frame timecode of the recieved segment not set")),console.error("[Adapter] First frame timecode of the recieved segment not set");return}const r=fn(this.firstFrameTimecode,6e4/1001);if(!e.mimeType.includes("video"))return;const n=hn(this.firstFrameTimecode,!0,!0);this.options&&_(this.options,"Adapter")&&console.log("New segment ("+e.url+"): "+n+" ("+r+") playing at "+e.playbackTime);const s=e.playbackTime;s-this.playbackTimeDelta,this.playbackTimeDelta=s;const i=e.wallClockTime/1e3;if(i-this.wallClockTimeDelta,this.wallClockTimeDelta=i,e.dateTime instanceof Date){const a=e.dateTime.getTime()/1e3;a-this.dateTimeDelta,this.dateTimeDelta=a}const o={frame:r,playerTime:s,stringTime:n,lastUpdate:performance.now()};this.syncPoint=o,this.metrics&&(this.metrics.updateMetric("frame",o.frame),this.metrics.updateMetric("playerTime",o.playerTime),this.metrics.updateMetric("stringTime",o.stringTime),this.metrics.updateMetric("lastUpdate",o.lastUpdate)),this.options&&_(this.options,"Adapter")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||I.isSafariMac()){console.log("onNewMetadata: ",e);let r=!1;if(e.metadata.messageData)r=this.processTimedMetadata(e.metadata.messageData,e.metadata.presentationTime);else if(e.metadata.frames&&e.metadata.frames.length&&e.metadata.frames[0].key&&e.metadata.frames[0].key.toLowerCase()==="priv"){const n=e.metadata.frames.filter(s=>s.info&&s.info.toLowerCase().includes("ntc"));if(n.length){const s=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;r=this.processTimedMetadata(s,e.metadata.presentationTime)}}if(r&&(e.metadata.id==0||I.isSafariMac()&&this.timecode_offset==0)){e.metadata.presentationTime*1e3,this.logger.setAttributes({id3_metadata:this.tcTimeStamp-this.timecode_offset});const n=new Date(this.tcTimeStamp-this.timecode_offset);let s=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const i=s%1;let o=1;i==.5&&(s=Math.floor(s),o=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(s),o==1?0:1],this.logger.setAttributes({segment_first_frame_timecode:this.firstFrameTimecode}),this.firstFrameTimecodeSet||this.logger.info(`[Adapter] Segment first frame timecode set: ${this.firstFrameTimecode}`),this.firstFrameTimecodeSet=!0,console.log("First frame timecode reciesved at: ",new Date().toISOString()),console.log("First frame timecode: ",this.firstFrameTimecode),console.log("video.currentTime: ",this.video.currentTime),console.log("video.currentTime to UTC: ",new Date(this.video.currentTime*1e3).toISOString()),this.metrics&&(this.metrics.updateMetric("tcTimeStamp",this.tcTimeStamp),this.metrics.updateMetric("timecodeOffset",this.timecode_offset),this.metrics.updateMetric("firstFrameTimecode",this.firstFrameTimecode.join(",")))}}}onAdEvent(e){this.options&&_(this.options,"Adapter")&&console.log(`MK Ad event: ${e}`),this.isMKAdPlaying=e==="start"}parseId3Tag(e,r){console.log("Parsing ID3 tag: ",r);const n=e.exec(r);return n&&n[1]?n[1]:null}processTimedMetadata(e,r){if(e&&e.includes("www.mediakind.com/NTC")){let n=!1;const s=/tc__[\s\S]{4}(\d+)/,i=this.parseId3Tag(s,e);i?(this.tcTimeStamp=new Date(parseInt(i)).getTime(),console.log(`NewTcTimeStamp: ${this.tcTimeStamp}`),n=!0):console.log("tcTimeStamp not found.");const o=/offs[\s\S]{4}(\d+)/,a=this.parseId3Tag(o,e);return a?(this.timecode_offset=parseInt(a)/90,console.log(`New Extracted offset: ${this.timecode_offset}`),n=!0):console.log("offset not found."),n}return!1}pause(){this.animationFrameLoopId&&(cancelAnimationFrame(this.animationFrameLoopId),this.animationFrameLoopId=void 0),this.videoFrameCallbackLoopId&&(this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.videoFrameCallbackLoopId=void 0),this.burnedIntervalId&&(clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0)}resume(){this.resumedAt=performance.now(),this.options&&_(this.options,"Adapter")&&console.log("[Adapter] Resumed - skipping expensive processing for",this.SKIP_PROCESSING_AFTER_RESUME_MS,"ms"),this.siData.patternTracking=[],this.siData.possibilityTracking=[],this.siData.determineFramesIntervals=[],this.siData.determineAFIntervals=[],this.siData.isRVFCpatternDetected=!1,this.siData.RVFCpattern=[],this.siData.expectedRefreshRate=0,this.siData.expectedFPS=0,this.siData.newRefreshRateFrames=0,this.siData.newFPSFrames=0,this.animationFrameLoopId||(this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame)),this.videoFrameCallbackLoopId||(this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame)),this.options.BURNED_TIMECODES_MODE&&!this.burnedIntervalId&&(this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33))}delete(){this.options.BURNED_TIMECODES_MODE&&this.stopBurnedPipeline(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.intervalLoopId&&clearInterval(this.intervalLoopId),this.metrics&&this.metrics.delete(),this.debugControls&&this.debugControls.delete()}};pe.MIN_SUPPORTED_FPS=20,pe.MAX_SUPPORTED_FPS=40;let it=pe;class q{constructor(e,r){this.size=1,this.positionElement=()=>{let s=0,i=0;this.corner=="left-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i}px`):this.corner=="right-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i}px`)},this.video=r,this.container=r.parentElement,this.corner=e;const n=document.createElement("div");n.style.position="absolute",n.style.width=`${this.size}px`,n.style.height=`${this.size}px`,n.style.transition="background-color 0s",n.style.zIndex="100000",this.element=n,this.container.appendChild(n),this.positionElement()}getRandomColor(){const n=Math.floor(Math.random()*11)+0;return`rgb(${n},${n},${n})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new q("left-top",e),new q("right-top",e),new q("right-bottom",e),new q("left-bottom",e)]}static updateAll(e){e.forEach(r=>r.update())}static deleteAll(e){e.forEach(r=>r.delete())}}const C={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},M=console,X={};Object.keys(C).forEach(t=>{X[t]=M[t]});const ge="Datadog Browser SDK:",D={debug:X.debug.bind(M,ge),log:X.log.bind(M,ge),info:X.info.bind(M,ge),warn:X.warn.bind(M,ge),error:X.error.bind(M,ge)},ot="https://docs.datadoghq.com",Yt=`${ot}/real_user_monitoring/browser/troubleshooting`,Fe="More details:";function qt(t,e){return(...r)=>{try{return t(...r)}catch(n){D.error(e,n)}}}function Le(t){return t!==0&&Math.random()*100<=t}function gn(t){return yn(t)&&t>=0&&t<=100}function yn(t){return typeof t=="number"}const ye=1e3,K=60*ye,Xt=60*K,_n=365*(24*Xt);function _e(){return new Date().getTime()}function G(){return _e()}function Pe(){return performance.now()}function V(){return{relative:Pe(),timeStamp:G()}}function bn(){return{relative:0,timeStamp:Kt()}}function vn(t,e){return e-t}function Tn(t,e){return t+e}function Sn(t){return t-Kt()}let at;function Kt(){return at===void 0&&(at=performance.timing.navigationStart),at}const B=1024,Jt=1024*B,En=/[^\u0000-\u007F]/;function ct(t){return En.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function xn(t){return{...t}}function Zt(t,e){return Object.keys(t).some(r=>t[r]===e)}function be(t){return Object.keys(t).length===0}function H(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function oe(t,e){const r=H();let n;return r.Zone&&typeof r.Zone.__symbol__=="function"&&(n=t[r.Zone.__symbol__(e)]),n||(n=t[e]),n}let Oe,Qt=!1;function wn(t){Oe=t}function An(t){Qt=t}function Rn(t,e,r){const n=r.value;r.value=function(...s){return(Oe?x(n):n).apply(this,s)}}function x(t){return function(){return ve(t,this,arguments)}}function ve(t,e,r){try{return t.apply(e,r)}catch(n){Cn(n)}}function Cn(t){if(lt(t),Oe)try{Oe(t)}catch(e){lt(e)}}function lt(...t){Qt&&D.error("[MONITOR]",...t)}function Te(t,e){return oe(H(),"setTimeout")(x(t),e)}function er(t){oe(H(),"clearTimeout")(t)}function dt(t,e){return oe(H(),"setInterval")(x(t),e)}function tr(t){oe(H(),"clearInterval")(t)}class k{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(r=>e!==r),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(r=>r(e))}}function rr(...t){return new k(e=>{const r=t.map(n=>n.subscribe(s=>e.notify(s)));return()=>r.forEach(n=>n.unsubscribe())})}function nr(t,e,r){let n=!1,s,i;return{throttled:(...o)=>{if(n){s=o;return}t(...o),n=!0,i=Te(()=>{s&&t(...s),n=!1,s=void 0},e)},cancel:()=>{er(i),n=!1,s=void 0}}}function W(){}function j(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\w-]+)\s*=\s*([^;]+)/g;function Dn(t,e){for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r){if(r[1]===e)return r[2]}else break}}function kn(t){const e=new Map;for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r)e.set(r[1],r[2]);else break}return e}function Un(t,e,r=""){const n=t.charCodeAt(e-1),i=n>=55296&&n<=56319?e+1:e;return t.length<=i?t:`${t.slice(0,i)}${r}`}function Fn(){return Ln()===0}let Me;function Ln(){return Me??(Me=Pn())}function Pn(t=window){var e;const r=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(r)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(r)&&!/chrome|android/i.test(r)?1:2}function Se(t,e,r=0,n){const s=new Date;s.setTime(s.getTime()+r);const i=`expires=${s.toUTCString()}`,o=n&&n.crossSite?"none":"strict",a=n&&n.domain?`;domain=${n.domain}`:"",c=n&&n.secure?";secure":"",d=n&&n.partitioned?";partitioned":"";document.cookie=`${t}=${e};${i};path=/;samesite=${o}${a}${c}${d}`}function ut(t){return Dn(document.cookie,t)}let ht;function J(t){return ht||(ht=kn(document.cookie)),ht.get(t)}function sr(t,e){Se(t,"",0,e)}function On(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${j()}`,r="test";Se(e,r,K,t);const n=ut(e)===r;return sr(e,t),n}catch(e){return D.error(e),!1}}let ft;function In(){if(ft===void 0){const t=`dd_site_test_${j()}`,e="test",r=window.location.hostname.split(".");let n=r.pop();for(;r.length&&!ut(t);)n=`${r.pop()}.${n}`,Se(t,e,ye,{domain:n});sr(t,{domain:n}),ft=n}return ft}const ae="_dd_s";function Be(t){return Object.values(t)}function Mn(t){return Object.entries(t)}const pt=4*Xt,ir=15*K,Bn=_n,Ee={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},or=/^([a-zA-Z]+)=([a-z0-9-]+)$/,mt="&";function Nn(t){return!!t&&(t.indexOf(mt)!==-1||or.test(t))}const zn="1";function Z(t,e){const r={isExpired:zn};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?r.anonymousId=t==null?void 0:t.anonymousId:r.anonymousId=j()),r}function Ne(t){return be(t)}function ar(t){return!Ne(t)}function ze(t){return t.isExpired!==void 0||!$n(t)}function $n(t){return(t.created===void 0||_e()-Number(t.created)<pt)&&(t.expire===void 0||_e()<Number(t.expire))}function cr(t){t.expire=String(_e()+ir)}function gt(t){return Mn(t).map(([e,r])=>e==="anonymousId"?`aid=${r}`:`${e}=${r}`).join(mt)}function lr(t){const e={};return Nn(t)&&t.split(mt).forEach(r=>{const n=or.exec(r);if(n!==null){const[,s,i]=n;s==="aid"?e.anonymousId=i:e[s]=i}}),e}const Gn="_dd",Vn="_dd_r",Hn="_dd_l",Wn="rum",jn="logs";function Yn(t){if(!J(ae)){const r=J(Gn),n=J(Vn),s=J(Hn),i={};r&&(i.id=r),s&&/^[01]$/.test(s)&&(i[jn]=s),n&&/^[012]$/.test(n)&&(i[Wn]=n),ar(i)&&(cr(i),t.persistSession(i))}}function dr(t){const e=Zn(t);return On(e)?{type:Ee.COOKIE,cookieOptions:e}:void 0}function qn(t,e){const r={isLockEnabled:Fn(),persistSession:Xn(e),retrieveSession:Jn,expireSession:n=>Kn(e,n,t)};return Yn(r),r}function Xn(t){return e=>{Se(ae,gt(e),ir,t)}}function Kn(t,e,r){const n=Z(e,r);Se(ae,gt(n),r.trackAnonymousUser?Bn:pt,t)}function Jn(){const t=ut(ae);return lr(t)}function Zn(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=In()),e}const Qn="_dd_test_";function ur(){try{const t=j(),e=`${Qn}${t}`;localStorage.setItem(e,t);const r=localStorage.getItem(e);return localStorage.removeItem(e),t===r?{type:Ee.LOCAL_STORAGE}:void 0}catch{return}}function es(t){return{isLockEnabled:!1,persistSession:hr,retrieveSession:ts,expireSession:e=>rs(e,t)}}function hr(t){localStorage.setItem(ae,gt(t))}function ts(){const t=localStorage.getItem(ae);return lr(t)}function rs(t,e){hr(Z(t,e))}const ns=10,ss=100,fr=[];let $e;function Q(t,e,r=0){var n;const{isLockEnabled:s,persistSession:i,expireSession:o}=e,a=f=>i({...f,lock:d}),c=()=>{const f=e.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if($e||($e=t),t!==$e){fr.push(t);return}if(s&&r>=ss){pr(e);return}let d,l=c();if(s){if(l.lock){Ge(t,e,r);return}if(d=j(),a(l.session),l=c(),l.lock!==d){Ge(t,e,r);return}}let u=t.process(l.session);if(s&&(l=c(),l.lock!==d)){Ge(t,e,r);return}if(u&&(ze(u)?o(u):(cr(u),s?a(u):i(u))),s&&!(u&&ze(u))){if(l=c(),l.lock!==d){Ge(t,e,r);return}i(l.session),u=l.session}(n=t.after)===null||n===void 0||n.call(t,u||l.session),pr(e)}function Ge(t,e,r){Te(()=>{Q(t,e,r+1)},ns)}function pr(t){$e=void 0;const e=fr.shift();e&&Q(e,t)}const mr=ye;function is(t){switch(t.sessionPersistence){case Ee.COOKIE:return dr(t);case Ee.LOCAL_STORAGE:return ur();case void 0:{let e=dr(t);return!e&&t.allowFallbackToLocalStorage&&(e=ur()),e}default:D.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function os(t,e,r,n){const s=new k,i=new k,o=new k,a=t.type===Ee.COOKIE?qn(e,t.cookieOptions):es(e),{expireSession:c}=a,d=dt(h,mr);let l;g();const{throttled:u,cancel:f}=nr(()=>{Q({process:v=>{if(Ne(v))return;const F=m(v);return S(F),F},after:v=>{ar(v)&&!b()&&w(v),l=v}},a)},mr);function p(){Q({process:v=>b()?m(v):void 0},a)}function h(){Q({process:v=>ze(v)?Z(v,e):void 0,after:m},a)}function m(v){return ze(v)&&(v=Z(v,e)),b()&&(E(v)?A():(o.notify({previousState:l,newState:v}),l=v)),v}function g(){Q({process:v=>{if(Ne(v))return Z(v,e)},after:v=>{l=v}},a)}function S(v){if(Ne(v))return!1;const{trackingType:F,isTracked:Mt}=n(v[r]);v[r]=F,delete v.isExpired,Mt&&!v.id&&(v.id=j(),v.created=String(_e()))}function b(){return l[r]!==void 0}function E(v){return l.id!==v.id||l[r]!==v[r]}function A(){l=Z(l,e),i.notify()}function w(v){l=v,s.notify()}function R(v){Q({process:F=>({...F,...v}),after:m},a)}return{expandOrRenewSession:u,expandSession:p,getSession:()=>l,renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o,restartSession:g,expire:()=>{f(),c(l),m(Z(l,e))},stop:()=>{tr(d)},updateSessionState:R}}const yt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function as(t){const e=new k;return{tryToInit(r){t||(t=r)},update(r){t=r,e.notify()},isGranted(){return t===yt.GRANTED},observable:e}}function ee(t,e,r){if(typeof t!="object"||t===null)return JSON.stringify(t);const n=ce(Object.prototype),s=ce(Array.prototype),i=ce(Object.getPrototypeOf(t)),o=ce(t);try{return JSON.stringify(t,e,r)}catch{return"<error: unable to serialize object>"}finally{n(),s(),i(),o()}}function ce(t){const e=t,r=e.toJSON;return r?(delete e.toJSON,()=>{e.toJSON=r}):W}function _t(t){return cs(t,location.href).href}function cs(t,e){const r=ls();if(r)try{return e!==void 0?new r(t,e):new r(t)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${ee({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let n=document;const s=n.createElement("a");if(e!==void 0){n=document.implementation.createHTMLDocument("");const i=n.createElement("base");i.href=e,n.head.appendChild(i),n.body.appendChild(s)}return s.href=t,s}const gr=URL;let Ve;function ls(){if(Ve===void 0)try{Ve=new gr("http://test/path").href==="http://test/path"}catch{Ve=!1}return Ve?gr:void 0}const ds="datad0g.com",us="dd0g-gov.com",le="datadoghq.com",hs="ddog-gov.com",fs="pci.browser-intake-datadoghq.com",ps=["ddsource","ddtags"];function xe(t,e,r){const n=ms(t,e);return{build(s,i){const o=ys(t,e,r,s,i);return n(o)},urlPrefix:n(""),trackType:e}}function ms(t,e){const r=`/api/v2/${e}`,n=t.proxy;if(typeof n=="string"){const i=_t(n);return o=>`${i}?ddforward=${encodeURIComponent(`${r}?${o}`)}`}if(typeof n=="function")return i=>n({path:r,parameters:i});const s=gs(e,t);return i=>`https://${s}${r}?${i}`}function gs(t,e){const{site:r=le,internalAnalyticsSubdomain:n}=e;if(t==="logs"&&e.usePciIntake&&r===le)return fs;if(n&&r===le)return`${n}.${le}`;if(r===us)return`http-intake.logs.${r}`;const s=r.split("."),i=s.pop();return`browser-intake-${s.join("-")}.${i}`}function ys({clientToken:t,internalAnalyticsSubdomain:e},r,n,s,{retry:i,encoding:o}){const a=["sdk_version:6.5.0",`api:${s}`].concat(n);i&&a.push(`retry_count:${i.count}`,`retry_after:${i.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${t}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return o&&c.push(`dd-evp-encoding=${o}`),r==="rum"&&c.push(`batch_time=${G()}`),e&&c.reverse(),c.join("&")}const _s=200;function bs(t){const{env:e,service:r,version:n,datacenter:s}=t,i=[];return e&&i.push(He("env",e)),r&&i.push(He("service",r)),n&&i.push(He("version",n)),s&&i.push(He("datacenter",s)),i}function He(t,e){const r=_s-t.length-1;(e.length>r||vs(e))&&D.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${Fe} ${ot}/getting_started/tagging/#defining-tags`);const n=e.replace(/,/g,"_");return`${t}:${n}`}function vs(t){return Ts()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function Ts(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function Ss(t){const e=t.site||le,r=bs(t),n=Es(t,r);return{replica:xs(t,r),site:e,...n}}function Es(t,e){return{logsEndpointBuilder:xe(t,"logs",e),rumEndpointBuilder:xe(t,"rum",e),sessionReplayEndpointBuilder:xe(t,"replay",e)}}function xs(t,e){if(!t.replica)return;const r={...t,site:le,clientToken:t.replica.clientToken},n={logsEndpointBuilder:xe(r,"logs",e),rumEndpointBuilder:xe(r,"rum",e)};return{applicationId:t.replica.applicationId,...n}}function ws(t){return ps.every(e=>t.includes(e))}function bt(t,e){return t!=null&&typeof t!="string"?(D.error(`${e} must be defined as a string`),!1):!0}function As(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(D.error(`Site should be a valid Datadog site. ${Fe} ${ot}/getting_started/site/.`),!1):!0}function We(t,e){return t!==void 0&&!gn(t)?(D.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function Rs(t){var e,r,n,s,i,o;if(!t||!t.clientToken){D.error("Client Token is not configured, we will not send any data.");return}if(!(!As(t.site)||!We(t.sessionSampleRate,"Session")||!We(t.telemetrySampleRate,"Telemetry")||!We(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!We(t.telemetryUsageSampleRate,"Telemetry Usage")||!bt(t.version,"Version")||!bt(t.env,"Env")||!bt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Zt(yt,t.trackingConsent)){D.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&qt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:is(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(r=t.telemetrySampleRate)!==null&&r!==void 0?r:20,telemetryConfigurationSampleRate:(n=t.telemetryConfigurationSampleRate)!==null&&n!==void 0?n:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(i=t.trackingConsent)!==null&&i!==void 0?i:yt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*B,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ye,batchMessagesLimit:50,messageBytesLimit:256*B,...Ss(t)}}}function Cs(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var vt;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(vt||(vt={}));const yr=new Set;function Ds(t){Array.isArray(t)&&ks(t.filter(e=>Zt(vt,e)))}function ks(t){t.forEach(e=>{yr.add(e)})}function Us(){return yr}const we="?";function N(t){const e=[];let r=Tt(t,"stack");const n=String(t);return r&&r.startsWith(n)&&(r=r.slice(n.length)),r&&r.split(`
|
|
494
|
+
`,s=this.createShader(this.gl.VERTEX_SHADER,r),i=this.createShader(this.gl.FRAGMENT_SHADER,n);this.program=this.createProgram(s,i),this.gl.useProgram(this.program),this.positionLoc=this.gl.getAttribLocation(this.program,"a_position"),this.texCoordLoc=this.gl.getAttribLocation(this.program,"a_texCoord"),this.resolutionLoc=this.gl.getUniformLocation(this.program,"u_resolution"),this.videoSizeLoc=this.gl.getUniformLocation(this.program,"u_videoSize"),this.textureLoc=this.gl.getUniformLocation(this.program,"u_image"),this.positionBuffer=this.gl.createBuffer(),this.texCoordBuffer=this.gl.createBuffer(),this.videoTexture=this.gl.createTexture(),this.fbo=this.gl.createFramebuffer(),this.outTex=this.gl.createTexture(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,this.OUT_WIDTH,0,0,this.OUT_HEIGHT,0,this.OUT_HEIGHT,this.OUT_WIDTH,0,this.OUT_WIDTH,this.OUT_HEIGHT]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.positionLoc),this.gl.vertexAttribPointer(this.positionLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.texCoordLoc),this.gl.vertexAttribPointer(this.texCoordLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.outTex),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.OUT_WIDTH,this.OUT_HEIGHT,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.outTex,0)}createShader(e,r){const n=this.gl.createShader(e);if(this.gl.shaderSource(n,r),this.gl.compileShader(n),!this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)){const s=this.gl.getShaderInfoLog(n);throw this.gl.deleteShader(n),new Error("Shader compile failed: "+s)}return n}createProgram(e,r){const n=this.gl.createProgram();if(this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),!this.gl.getProgramParameter(n,this.gl.LINK_STATUS)){const s=this.gl.getProgramInfoLog(n);throw this.gl.deleteProgram(n),new Error("Program link failed: "+s)}return this.gl.detachShader(n,e),this.gl.detachShader(n,r),this.gl.deleteShader(e),this.gl.deleteShader(r),n}decode(e){const r=e.videoWidth|0,n=e.videoHeight|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}decodeFromImageBitmap(e){const r=e.width|0,n=e.height|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}dispose(){this.videoTexture&&this.gl.deleteTexture(this.videoTexture),this.outTex&&this.gl.deleteTexture(this.outTex),this.fbo&&this.gl.deleteFramebuffer(this.fbo),this.positionBuffer&&this.gl.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&this.gl.deleteBuffer(this.texCoordBuffer),this.program&&this.gl.deleteProgram(this.program)}}const pe=class pe{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecodeSet=!1,this.firstFrameTimecode=[0,0,0,0,0],this.firstVideoFrameCallbackFired=!1,this.isMKAdPlaying=!1,this.loggerTimeoutStart=0,this.loggerTimeout=1e4,this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=100,this.resumedAt=0,this.SKIP_PROCESSING_AFTER_RESUME_MS=1e3,this.afData={counter:0,lastTimestamp:0,previousTimestamp:0,lastMetadataNow:0,timeFromLastRVFC:0,animationFPS:0,playerTimeOffset:0,lastPlayerTimeFromSync:0,lastCalculatedPlayerTimeVideoFrame:0,lastCalculatedPlayerTimeFraction:0,previousCalculatedPlayerTimeFraction:2},this.vfcData={counter:0,lastTimestamp:0,previousTimestamp:0,timeFromLastRAF:0,videoFPS:0,lastFrameMetadata:null,lastFrameMetadataNow:0,storedMetadata:[],timePerformanceNowToExpectedDisplayTime:0,timeRVFCnowToExpectedDisplayTime:0,mediaTimeOffset:0,lastMediaTimeFromSync:0,lastCalculatedMediaTimeVideoFrame:0},this.siData={counter:0,lastTimestamp:0,lastOffset:0,timeFromLastRAF:0,timeFromLastRVFC:0,lastSeenRAFCount:0,lastSeenRVFCCount:0,isRAFSeen:!1,isRVFCSeen:!1,isVideoPaused:!0,workingFps:0,refreshRate:0,RVFCmissed:0,RVFCframeExpected:0,expectedRefreshRate:0,avgExpectedRefreshRate:0,newRefreshRateFrames:0,expectedFPS:0,newFPSFrames:0,RVFCpattern:[],isRVFCpatternDetected:!1,patternTracking:[],patternTrackingIndex:-1,patternNextValue:-1,possibilityTracking:[],previousPossibilityValue:-1,lastCallback:null,lastCalculatedFrame:0,lastRendererFrameSent:0,lastMessageSent:"",compensationMode:!1,compensationCounter:0,frameCorrection:0,determineFramesIntervals:[],determineAFIntervals:[],expectedDisplayTimeReminder:0,animationFramesToDisplayTime:0},this.tcTimeStamp=0,this.timecode_offset=0,this.burnedLastTcKey=-1,this.sampleBurnedFrame=async()=>{var r;if(!(!this.OTTPlayer||!this.video)&&!(this.video.videoWidth===0||this.video.videoHeight===0)&&this.gl2Decoder)try{let n=await createImageBitmap(this.video);const s=this.gl2Decoder.decodeFromImageBitmap(n);if(!s){try{n.close()}catch{}return}const i=this.parseTcKey(s);if(i<=this.burnedLastTcKey){try{n.close()}catch{}return}this.burnedLastTcKey=i,this.metrics&&this.metrics.updateMetric("Last sent timecode",s),(r=this.OTTPlayer.clocker)==null||r.callRendererWorkerWithFrame(n,s),n=void 0}catch(n){this.logger.error("[Adapter] sampleBurnedFrame error: "+n)}},this.onAnimationFrame=r=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.previousTimestamp=this.afData.lastTimestamp,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=r,this.afData.timeFromLastRVFC=this.afData.lastTimestamp-this.vfcData.lastTimestamp,this.afData.animationFPS=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.siData.lastCallback=="RAF"&&this.siData.RVFCmissed++,this.siData.lastCallback="RAF";const n=(this.video.currentTime-this.syncPoint.playerTime)*(6e4/1001);this.afData.lastPlayerTimeFromSync=n;const s=Math.floor(n)+this.syncPoint.frame;this.afData.playerTimeOffset=L.calculateCurrentOffset(s,this.OTTPlayer.gameParams.offsets);let i=s-this.afData.playerTimeOffset;if(i<0&&(i+=5178816),i++,this.afData.lastCalculatedPlayerTimeVideoFrame=i,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=n-Math.floor(n),this.metrics)try{this.metrics.updateMetric("RAF calls",this.afData.counter),this.metrics.updateMetric("Last player time",this.video.currentTime.toFixed(4)),this.metrics.updateMetric("Last player time frame",this.afData.lastCalculatedPlayerTimeVideoFrame),this.metrics.updateMetric("Last player time fraction",this.afData.lastCalculatedPlayerTimeFraction.toFixed(4)),this.metrics.updateMetric("Last player time double frame",this.afData.lastPlayerTimeFromSync.toFixed(5)),this.metrics.updateMetric("AF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("VF ExpDispTime - AF metadata now",(this.afData.lastTimestamp-this.vfcData.lastFrameMetadata.expectedDisplayTime).toFixed(3)),this.metrics.updateMetric("Last RAF call",this.afData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("RAF - RVFC dif",this.afData.timeFromLastRVFC.toFixed(2))}catch(o){this.options&&_(this.options,"Adapter")&&console.error(o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(r,n)=>{if(this.firstVideoFrameCallbackFired||(this.firstVideoFrameCallbackFired=!0,this.logger.info("[Adapter] First video frame callback fired"),console.log("[Adapter] First video frame callback fired")),this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame);return}this.vfcData.counter++,this.vfcData.previousTimestamp=this.vfcData.lastTimestamp,this.vfcData.lastTimestamp=performance.now(),this.vfcData.timeFromLastRAF=this.vfcData.lastTimestamp-this.afData.lastTimestamp,this.siData.RVFCmissed=0,this.vfcData.videoFPS=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.siData.lastCallback="RVFC";const s=(n.mediaTime-this.syncPoint.playerTime)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=s;const i=Math.floor(s+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=L.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let o=i-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=n,this.vfcData.storedMetadata.push(n),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timePerformanceNowToExpectedDisplayTime=n.expectedDisplayTime-this.vfcData.lastTimestamp,this.vfcData.timeRVFCnowToExpectedDisplayTime=n.expectedDisplayTime-r,this.vfcData.lastFrameMetadataNow=r,this.metrics&&(this.metrics.updateMetric("MediaTime",n.mediaTime),this.metrics.updateMetric("MediaTimeWithSync",i),this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",n.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(n.presentationTime-r).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",n.presentedFrames),this.metrics.updateMetric("Metadata processing duration",n.processingDuration),this.metrics.updateMetric("Last media time double frame",this.vfcData.lastMediaTimeFromSync.toFixed(5)),this.metrics.updateMetric("VF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("RVFC to expected display time",this.vfcData.timeRVFCnowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Performance Now to expected display time",this.vfcData.timePerformanceNowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Last RVFC call",this.vfcData.lastTimestamp.toFixed(2))),this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,s,i,o;if(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;this.siData.counter===0&&this.logger.info("didStartAugmentation"),this.siData.counter++,this.siData.isVideoPaused=this.video.paused,this.siData.isRAFSeen=this.siData.lastSeenRAFCount==this.afData.counter,this.siData.isRVFCSeen=this.siData.lastSeenRVFCCount==this.vfcData.counter,this.siData.lastTimestamp=performance.now(),this.siData.timeFromLastRAF=this.siData.lastTimestamp-this.afData.lastTimestamp,this.siData.timeFromLastRVFC=this.siData.lastTimestamp-this.vfcData.lastTimestamp,this.siData.lastSeenRAFCount=this.afData.counter,this.siData.lastSeenRVFCCount=this.vfcData.counter,this.siData.workingFps=this.OTTPlayer.clocker.videoFPScalculator.getFPS(),this.siData.refreshRate=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS();const r=this.siData.lastTimestamp;if(this.OTTPlayer.statusOverlay&&r-this.lastStatusUpdate>this.STATUS_UPDATE_INTERVAL&&(this.updateStatusOverlay(),this.lastStatusUpdate=r),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const a={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:((s=this.OTTPlayer.gameParams)==null?void 0:s.bucketName)||"",offsets:((i=this.OTTPlayer.gameParams)==null?void 0:i.offsets)||[],customerId:((o=this.OTTPlayer.gameParams)==null?void 0:o.customerId)||""};this.OTTPlayer.clocker.callAdapterWorker(a)}},this.determineFrameUpdateChromeMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>4?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),this.siData.newRefreshRateFrames=0),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=1,c=5;if(this.debugControls){const d=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(d)||(o=d);const l=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(l)||(a=l);const u=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(u)||(c=u)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+a),c):this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateChromeWin=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=2,c=!1;if(this.debugControls){const u=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(u)||(o=u);const f=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(f)||(a=f),parseInt(this.debugControls.getValue("Timeout time"),10),this.debugControls.getValue("Video Captur Card Mode")==="true"&&(c=!0)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),c&&(o+=1);const d=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length,l=(d+this.siData.RVFCpattern.length-1)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[d]){let u=0;c&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame&&this.siData.RVFCpattern[l]&&(u=2),this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+u+a)}}},this.determineFrameUpdateSifariMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS||(this.siData.expectedRefreshRate&&this.siData.expectedFPS&&(this.expectedRefreshRateCalculator.addFrameDuration(1/this.siData.refreshRate),this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),Math.abs(this.siData.expectedRefreshRate-this.siData.avgExpectedRefreshRate)>3&&this.siData.newRefreshRateFrames++,Math.abs(this.siData.expectedFPS-this.siData.workingFps)>3&&this.siData.newFPSFrames++,(this.siData.newRefreshRateFrames>10||this.siData.newFPSFrames>10)&&(this.siData.newRefreshRateFrames=0,this.siData.expectedRefreshRate=0,this.siData.newFPSFrames=0,this.siData.expectedFPS=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))return;const r=Math.abs(this.siData.refreshRate-this.siData.workingFps)<2?8:20,n=1e3,s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((h,m)=>m-h),i=2,o=s[0],a=s[1],c=o-a,d=1e3/this.afData.animationFPS,l=Math.round(d/4+.1),u=this.vfcData.timeRVFCnowToExpectedDisplayTime;if(this.siData.isRVFCSeen)this.metrics;else{const h=(-u-l)/d,m=Math.ceil(h),g=(Math.round(h)-h)*d,S=Math.abs(g)<=i,E=g<=0?m-1:m+1,A=Math.abs(-u-l)<=i;if(this.metrics&&(this.metrics.updateMetric("Is Smoothing Needed",S),this.metrics.updateMetric("Is More Than Border",m),this.metrics.updateMetric("Is Smoothed",E)),S&&!A){const w=Math.min(m,E),R=Math.max(m,E);this.metrics&&this.metrics.updateMetric("Pssblty next index",""+w+" "+R),this.siData.possibilityTracking[this.siData.possibilityTracking.length-w]=2,this.siData.possibilityTracking[this.siData.possibilityTracking.length-R]=1}else S&&A&&(this.metrics&&this.metrics.updateMetric("Pssblty next index","min"),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]=1,this.siData.possibilityTracking.push(2),this.siData.possibilityTracking.push(3));if(-u<l)this.siData.expectedDisplayTimeReminder=-u;else if(c>d&&-u-(c-d)<=l)this.siData.expectedDisplayTimeReminder=-u-(c-d);else{let w=-u-c,R=0,v=this.siData.determineFramesIntervals.length-1;for(let F=this.siData.determineAFIntervals.length-1;F>=0&&(v--,!(this.siData.determineAFIntervals[F]>d&&w-(this.siData.determineAFIntervals[F]-d)<=l||w<=l||this.siData.determineFramesIntervals[v].includes("vf")&&this.siData.workingFps<40));F--)w-=this.siData.determineAFIntervals[F],R+=1;if(this.siData.patternTracking.length<R+1){this.siData.patternTracking=[!0];for(let F=0;F<R;F++)this.siData.patternTracking.push(!1)}else this.siData.patternTracking[this.siData.patternTracking.length-1-R]=!0;this.siData.animationFramesToDisplayTime=R}}if(this.siData.isRAFSeen||(this.siData.expectedDisplayTimeReminder?(this.siData.expectedDisplayTimeReminder-l,this.siData.expectedDisplayTimeReminder+c<=l?(this.siData.patternTracking.push(!0),this.siData.animationFramesToDisplayTime=0):(this.siData.patternTracking[this.siData.patternTracking.length-1]=!0,this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime=1),this.siData.expectedDisplayTimeReminder=0):(this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime+=1),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]==3?this.siData.possibilityTracking.pop():this.siData.possibilityTracking.push(0)),this.siData.patternTracking.length>n&&this.siData.patternTracking.shift(),this.siData.possibilityTracking.length>n&&this.siData.possibilityTracking.shift(),!this.siData.isRVFCpatternDetected){const h=this.siData.patternTracking;for(let m=1;m*r<=h.length;m++){for(let g=0;g+m*r<=h.length;g++){let S=!0;for(let b=0;b<r-1;b++){const E=h.slice(g+b*m,g+(b+1)*m),A=h.slice(g+(b+1)*m,g+(b+2)*m);if(!E.every((w,R)=>w===A[R])){S=!1;break}}if(S){const b=h.slice(g,g+m),E=b.every(R=>!R),A=b.every(R=>R),w=this.afData.animationFPS-this.vfcData.videoFPS;if(E||A&&w>5)continue;this.siData.RVFCpattern=b,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected){this.siData.expectedRefreshRate=this.siData.refreshRate,this.siData.expectedFPS=this.siData.workingFps;break}}}if(this.siData.RVFCpattern.length>0){const h=this.siData.RVFCpattern,m=this.siData.patternTracking;let g=-1;for(let S=m.length-h.length*5;S>=0;S--){let b=!0;for(let E=0;E<h.length*5;E++)if(h[E%h.length]!==m[S+E]){b=!1;break}if(b){g=S;break}}if(g>=0){const S=(m.length-g)%h.length,b=h[S];this.siData.patternTrackingIndex=S,this.siData.patternNextValue=b?1:0}if(m.length>=h.length*5){m.slice(m.length-h.length*5);let S=0,b=0;for(let E=0;E+h.length<=m.length;E++)m.slice(E,E+h.length).every((w,R)=>w===h[R])?(S++,b=Math.max(b,S),E+=h.length-1):S=0;b<6&&(this.siData.isRVFCpatternDetected=!1)}}const f=[];for(let h=1;h<=3;h++)f.push(this.siData.possibilityTracking[this.siData.possibilityTracking.length-this.siData.RVFCpattern.length*h]);const p=Math.max(...f);if(this.metrics){let h="";if(this.siData.isRAFSeen?h="vf: "+c.toFixed(0):h="af: "+c.toFixed(0),this.siData.determineFramesIntervals.push(h),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),!this.siData.isRAFSeen){const m=this.afData.lastTimestamp-this.afData.previousTimestamp;this.siData.determineAFIntervals.push(m),this.siData.determineAFIntervals.length>10&&this.siData.determineAFIntervals.shift()}this.siData.isRVFCSeen||this.metrics.updateMetric("Last AF to VF time",(this.vfcData.lastTimestamp-this.afData.lastTimestamp).toFixed(0)),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("AF frames intervals",this.siData.determineAFIntervals.map(m=>m.toFixed(0)).join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.map(m=>m?1:0).slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Pssblty found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pssblty array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pssblty tracking",this.siData.possibilityTracking.slice(this.siData.possibilityTracking.length>100?this.siData.possibilityTracking.length-100:0).join("")),this.metrics.updateMetric("Pssblty next value",p),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate.toFixed(5)),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(5)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames),this.metrics.updateMetric("AF To Display Time",this.siData.animationFramesToDisplayTime),this.metrics.updateMetric("Call Renderer Reached",!1)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let h=0,m=0;if(this.debugControls){const S=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(S)||(h=S);const b=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(b)||(m=b),parseInt(this.debugControls.getValue("Timeout time"),10)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset}));const g=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length+h)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[g]||p){const S=Math.ceil(this.siData.animationFramesToDisplayTime/this.siData.RVFCpattern.length)+1,b=this.siData.RVFCpattern.map(ke=>ke?1:0).join("").repeat(S),E=(this.siData.RVFCpattern.length-this.siData.patternTrackingIndex)%this.siData.RVFCpattern.length,A=b.slice(0,E==0?-this.siData.RVFCpattern.length:-E);let w=0;const R=this.siData.possibilityTracking.length-1-this.siData.animationFramesToDisplayTime;A[A.length-1-this.siData.animationFramesToDisplayTime]=="0"&&this.siData.possibilityTracking[R]==1&&(w=-1);const v=this.siData.animationFramesToDisplayTime+w,F=v<=0?"":A.slice(-v);let De=F.split("").filter(ke=>ke==="1").length*Math.round(60/this.siData.workingFps);this.siData.workingFps<40&&(De+=1),this.siData.compensationMode&&!(p==2||this.siData.previousPossibilityValue==2)&&(this.siData.compensationCounter=1,this.siData.compensationMode=!1),this.siData.compensationCounter==1?this.siData.possibilityTracking.slice(-5).every(ke=>ke===0)&&(this.siData.compensationCounter-=.1):this.siData.compensationCounter>0&&this.siData.compensationCounter<1&&(this.siData.compensationCounter=Math.max(this.siData.compensationCounter-.1,0)),p==1?this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m-1,this.siData.compensationCounter):p==2&&this.siData.previousPossibilityValue==1?this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter):this.siData.RVFCpattern[g]&&((p==2||this.siData.previousPossibilityValue==2)&&Math.abs(this.afData.animationFPS-this.siData.workingFps)<5&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m?(this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter),this.siData.compensationMode=!0):this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m,this.siData.compensationCounter)),this.metrics&&(this.metrics.updateMetric("Call Renderer Reached",!0),this.metrics.updateMetric("Is Smoothing Needed",this.siData.compensationMode),this.metrics.updateMetric("Correction",De),this.metrics.updateMetric("Compensation Counter",this.siData.compensationCounter),this.metrics.updateMetric("Repeated Pattern",b),this.metrics.updateMetric("Trimmed Pattern",A),this.metrics.updateMetric("Sliced Pattern",F),this.metrics.updateMetric("AF To Display Time Correction",w)),this.siData.previousPossibilityValue=p}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateFirefoxMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const n=5,s=1e3;if(!this.siData.isRVFCSeen){const i=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(i<=0&&this.siData.patternTracking.length<=1-i){this.siData.patternTracking=[!0];for(let o=0;o<1-i;o++)this.siData.patternTracking.push(!1)}else i<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+i]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>s&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const i=this.siData.patternTracking;for(let o=1;o*n<=i.length;o++){for(let a=0;a+o*n<=i.length;a++){let c=!0;for(let d=0;d<n-1;d++){const l=i.slice(a+d*o,a+(d+1)*o),u=i.slice(a+(d+1)*o,a+(d+2)*o);if(!l.every((f,p)=>f===u[p])){c=!1;break}}if(c){const d=i.slice(a,a+o),l=d.every(p=>!p),u=d.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(l||u&&f>5)continue;this.siData.RVFCpattern=d,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const i=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-i.length;c>=0;c--){let d=!0;for(let l=0;l<i.length;l++)if(i[l]!==o[c+l]){d=!1;break}if(d){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,d=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=d?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,d=0;for(let l=0;l+i.length<=o.length;l++)o.slice(l,l+i.length).every((f,p)=>f===i[p])?(c++,d=Math.max(d,c),l+=i.length-1):c=0;d<5&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((d,l)=>l-d),o=i[0],a=i[1],c=o-a;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(c.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let i=0,o=1;if(this.debugControls){const a=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(a)||(i=a);const c=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(c)||(o=c),parseInt(this.debugControls.getValue("Timeout time"),10)}if(this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+i)%this.siData.RVFCpattern.length]){let a=this.vfcData.lastCalculatedMediaTimeVideoFrame+o;a==this.siData.lastRendererFrameSent&&(a+=2),this.callRenderer(a)}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.callRenderer=(r,n)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=r,this.metrics&&this.metrics.updateMetric("Last sent frame",r);const s=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",s.toFixed(2));const i=L.fromFrames(r,6e4/1001);this.renderAugmentation(i,n)},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(r,n)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const s=L.toStr(r);this.siData.lastMessageSent=s,this.options&&_(this.options,"Adapter")&&console.log(`Rendering augmentation for timecode: ${s} , ${r}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",s),this.OTTPlayer.clocker.callRendererWorker(s,n)},this.onVideoSeeked=()=>{this.firstFrameTimecode=[0,0,0,0,0],this.firstFrameTimecodeSet=!1,this.isMKAdPlaying&&(this.options&&_(this.options,"Adapter")&&console.log("[Adapter] Resetting MK ad state after seek/scrub"),this.isMKAdPlaying=!1)},this.clearAugmentation=r=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const n=r?L.toStr(r):void 0;this.options&&_(this.options,"Adapter")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(n,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.benchmark=new pn(e.options.BENCHMARK_DURATION_SECONDS),this.options&&_(this.options,"Adapter")&&console.log("Adapter is initialized",this.OTTPlayer),this.video=e.video,this.debug=this.options.debug?this.options.debug.on:!1,this.expectedRefreshRateCalculator=new nt(20),I.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(I.isChromeWin())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeWin;else{I.isSafariMac(),I.isFirefoxMac(),this.platformSpecificFrameUpdate=()=>{},this.logger.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),console.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),this.platformSupported=!1;return}if(this.debug){this.metrics=new jt;const r=this.metrics.createContainer(),n=this.metrics.createContainer(),s=this.metrics.createContainer(),i=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),d=this.metrics.createContainer(),l=this.metrics.createContainer(),u=this.metrics.createContainer(),f=this.metrics.createContainer(),p=this.metrics.createContainer(),h=this.metrics.createContainer(),m=this.metrics.createContainer(),g=this.metrics.createContainer(),S=this.metrics.createContainer();this.metrics.createMetric("tcTimeStamp",r),this.metrics.createMetric("timecodeOffset",r),this.metrics.createMetric("firstFrameTimecode",r),this.metrics.createMetric("frame",n),this.metrics.createMetric("playerTime",n),this.metrics.createMetric("stringTime",n),this.metrics.createMetric("lastUpdate",n),this.metrics.createMetric("MediaTime",s),this.metrics.createMetric("MediaTimeWithSync",s),this.metrics.createMetric("RAF calls",i),this.metrics.createMetric("RVFC calls",i),this.metrics.createMetric("RVFC missed",i),this.metrics.createMetric("Last sent frame",i),this.metrics.createMetric("Last sent timecode",i),this.metrics.createMetric("Last metadata media time",o),this.metrics.createMetric("Last player time",o),this.metrics.createMetric("RVFC to expected display time",o),this.metrics.createMetric("Performance Now to expected display time",o),this.metrics.createMetric("Last metadata media time frame",a),this.metrics.createMetric("Last player time frame",a),this.metrics.createMetric("Last player time fraction",a),this.metrics.createMetric("Last media time double frame",c),this.metrics.createMetric("Last player time double frame",c),this.metrics.createMetric("Compensation Counter",c),this.metrics.createMetric("AF metadata now - perf.now()",d),this.metrics.createMetric("VF metadata now - perf.now()",d),this.metrics.createMetric("VF ExpDispTime - AF metadata now",d),this.metrics.createMetric("Time to presentation time",l),this.metrics.createMetric("Metadata presented frames",l),this.metrics.createMetric("Metadata processing duration",l),this.metrics.createMetric("FPS",u),this.metrics.createMetric("Refresh rate",u),this.metrics.createMetric("Last RAF call",u),this.metrics.createMetric("Last RVFC call",u),this.metrics.createMetric("RAF - RVFC dif",u),this.metrics.createMetric("Determine frames intervals",f),this.metrics.createMetric("Last AF to VF time",p),this.metrics.createMetric("AF frames intervals",p),this.metrics.createMetric("Expected Refresh Rate",h),this.metrics.createMetric("Avg Expected Refresh Rate",h),this.metrics.createMetric("New Refresh Rate Frames",h),this.metrics.createMetric("AF To Display Time",h),this.metrics.createMetric("AF To Display Time Correction",h),this.metrics.createMetric("Call Renderer Reached",h),this.metrics.createMetric("Is Smoothing Needed",m),this.metrics.createMetric("Is More Than Border",m),this.metrics.createMetric("Is Smoothed",m),this.metrics.createMetric("Correction",m),this.metrics.createMetric("Repeated Pattern",m),this.metrics.createMetric("Trimmed Pattern",m),this.metrics.createMetric("Sliced Pattern",m),this.metrics.createMetric("Pattern found",g),this.metrics.createMetric("Pattern array",g),this.metrics.createMetric("Pattern tracking",g),this.metrics.createMetric("Pattern next index",g),this.metrics.createMetric("Pattern next value",g),this.metrics.createMetric("Pssblty found",S),this.metrics.createMetric("Pssblty array",S),this.metrics.createMetric("Pssblty tracking",S),this.metrics.createMetric("Pssblty next index",S),this.metrics.createMetric("Pssblty next value",S),this.debugControls=new un;const b=this.debugControls.createContainer(),E=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,b),this.debugControls.createInput("Window End (ms)",-11,b),this.debugControls.createSelect("Pattern offset",{"-5":-5,"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4,5:5},"0",b),this.debugControls.createCheckbox("Video Captur Card Mode",!1,b),I.isChromeWin()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"2",E):I.isSafariMac()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"0",E):this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",E),this.debugControls.createSelect("Timeout time",{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20},"5",E)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}isVideoFpsSupported(e){return e>pe.MIN_SUPPORTED_FPS&&e<=pe.MAX_SUPPORTED_FPS}setupAdapter(){const e=this.video;if(this.options.BURNED_TIMECODES_MODE){this.startBurnedPipeline();return}if(this.debug){const r=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(r);const n=r.getAvailableVideoQualities(),s={};n.forEach(a=>{s[a.label]=a.id});const i=a=>{r.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(i);this.debugControls.createSelect("videoQuality",s,n[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}startBurnedPipeline(){this.gl2Decoder=new mn,this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33)}stopBurnedPipeline(){this.burnedIntervalId&&(window.clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0),this.gl2Decoder&&(this.gl2Decoder.dispose(),this.gl2Decoder=void 0),this.burnedLastTcKey=-1}parseTcKey(e){const r=e.split("_");if(r.length<4)return-1;const n=parseInt(r[0],10)||0,s=parseInt(r[1],10)||0,i=parseInt(r[2],10)||0,o=parseInt(r[3],10)||0,a=r.length>=5&&r[4]==="1"?1:0;return((n*3600+s*60+i)*60+o)*2+a}updateStatusOverlay(){var i,o,a;const e=this.OTTPlayer.statusOverlay;e.updateMetric("support","browser",this.platformSupported,`${this.options.browserName} on ${this.options.platform}`),e.updateMetric("support","pattern",this.siData.isRVFCpatternDetected,this.siData.isRVFCpatternDetected?this.siData.RVFCpattern.map(c=>c?"1":"0").join("").slice(0,20):"Detecting...");const r=((i=this.OTTPlayer.clocker)==null?void 0:i.videoFPScalculator.getPerciseFPS())||0,n=this.isVideoFpsSupported(r);e.updateMetric("support","fps",n,r>0?`${r.toFixed(2)} fps`:"Detecting..."),e.updateMetric("support","game_params",!!this.OTTPlayer.gameParams),e.updateMetric("support","mk_ads",!this.isMKAdPlaying,this.isMKAdPlaying?"Ad in progress":"No ads"),this.syncPoint?e.updateMetric("timecode","sync_point",!0,this.syncPoint.stringTime):e.updateMetric("timecode","sync_point",!1,"Not set");const s=this.benchmark.test({gameParams:!!this.OTTPlayer.gameParams,browserSupported:this.platformSupported,patternDetected:this.siData.isRVFCpatternDetected,fpsSupported:n,noMKAdsPlaying:!this.isMKAdPlaying,syncPointSet:!!this.syncPoint});s.shouldClear&&(this.options&&_(this.options,"Adapter")&&console.log("[Benchmark] Failed - clearing augmentation. Reasons:",(o=s.failedConditions)==null?void 0:o.join(", ")),this.clearAugmentation()),e.updateMetric("benchmark","status",s.state,s.state==="TESTING"?`Stability test: ${s.remainingSeconds}s`:s.state==="FAILED"?`Failed: ${(a=s.failedConditions)==null?void 0:a.join(", ")}`:"Stable")}onNewSegmentForMetadata(e){if(!this.firstFrameTimecodeSet){const a=performance.now();a-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=a,this.logger.error("[Adapter] First frame timecode of the recieved segment not set")),console.error("[Adapter] First frame timecode of the recieved segment not set");return}const r=fn(this.firstFrameTimecode,6e4/1001);if(!e.mimeType.includes("video"))return;const n=hn(this.firstFrameTimecode,!0,!0);this.options&&_(this.options,"Adapter")&&console.log("New segment ("+e.url+"): "+n+" ("+r+") playing at "+e.playbackTime);const s=e.playbackTime;s-this.playbackTimeDelta,this.playbackTimeDelta=s;const i=e.wallClockTime/1e3;if(i-this.wallClockTimeDelta,this.wallClockTimeDelta=i,e.dateTime instanceof Date){const a=e.dateTime.getTime()/1e3;a-this.dateTimeDelta,this.dateTimeDelta=a}const o={frame:r,playerTime:s,stringTime:n,lastUpdate:performance.now()};this.syncPoint=o,this.metrics&&(this.metrics.updateMetric("frame",o.frame),this.metrics.updateMetric("playerTime",o.playerTime),this.metrics.updateMetric("stringTime",o.stringTime),this.metrics.updateMetric("lastUpdate",o.lastUpdate)),this.options&&_(this.options,"Adapter")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||I.isSafariMac()){console.log("onNewMetadata: ",e);let r=!1;if(e.metadata.messageData)r=this.processTimedMetadata(e.metadata.messageData,e.metadata.presentationTime);else if(e.metadata.frames&&e.metadata.frames.length&&e.metadata.frames[0].key&&e.metadata.frames[0].key.toLowerCase()==="priv"){const n=e.metadata.frames.filter(s=>s.info&&s.info.toLowerCase().includes("ntc"));if(n.length){const s=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;r=this.processTimedMetadata(s,e.metadata.presentationTime)}}if(r&&(e.metadata.id==0||I.isSafariMac()&&this.timecode_offset==0)){e.metadata.presentationTime*1e3,this.logger.setAttributes({id3_metadata:this.tcTimeStamp-this.timecode_offset});const n=new Date(this.tcTimeStamp-this.timecode_offset);let s=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const i=s%1;let o=1;i==.5&&(s=Math.floor(s),o=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(s),o==1?0:1],this.logger.setAttributes({segment_first_frame_timecode:this.firstFrameTimecode}),this.firstFrameTimecodeSet||this.logger.info(`[Adapter] Segment first frame timecode set: ${this.firstFrameTimecode}`),this.firstFrameTimecodeSet=!0,console.log("First frame timecode reciesved at: ",new Date().toISOString()),console.log("First frame timecode: ",this.firstFrameTimecode),console.log("video.currentTime: ",this.video.currentTime),console.log("video.currentTime to UTC: ",new Date(this.video.currentTime*1e3).toISOString()),this.metrics&&(this.metrics.updateMetric("tcTimeStamp",this.tcTimeStamp),this.metrics.updateMetric("timecodeOffset",this.timecode_offset),this.metrics.updateMetric("firstFrameTimecode",this.firstFrameTimecode.join(",")))}}}onAdEvent(e){this.options&&_(this.options,"Adapter")&&console.log(`MK Ad event: ${e}`),this.isMKAdPlaying=e==="start"}parseId3Tag(e,r){console.log("Parsing ID3 tag: ",r);const n=e.exec(r);return n&&n[1]?n[1]:null}processTimedMetadata(e,r){if(e&&e.includes("www.mediakind.com/NTC")){let n=!1;const s=/tc__[\s\S]{4}(\d+)/,i=this.parseId3Tag(s,e);i?(this.tcTimeStamp=new Date(parseInt(i)).getTime(),console.log(`NewTcTimeStamp: ${this.tcTimeStamp}`),n=!0):console.log("tcTimeStamp not found.");const o=/offs[\s\S]{4}(\d+)/,a=this.parseId3Tag(o,e);return a?(this.timecode_offset=parseInt(a)/90,console.log(`New Extracted offset: ${this.timecode_offset}`),n=!0):console.log("offset not found."),n}return!1}pause(){this.animationFrameLoopId&&(cancelAnimationFrame(this.animationFrameLoopId),this.animationFrameLoopId=void 0),this.videoFrameCallbackLoopId&&(this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.videoFrameCallbackLoopId=void 0),this.burnedIntervalId&&(clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0)}resume(){this.resumedAt=performance.now(),this.options&&_(this.options,"Adapter")&&console.log("[Adapter] Resumed - skipping expensive processing for",this.SKIP_PROCESSING_AFTER_RESUME_MS,"ms"),this.siData.patternTracking=[],this.siData.possibilityTracking=[],this.siData.determineFramesIntervals=[],this.siData.determineAFIntervals=[],this.siData.isRVFCpatternDetected=!1,this.siData.RVFCpattern=[],this.siData.expectedRefreshRate=0,this.siData.expectedFPS=0,this.siData.newRefreshRateFrames=0,this.siData.newFPSFrames=0,this.animationFrameLoopId||(this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame)),this.videoFrameCallbackLoopId||(this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame)),this.options.BURNED_TIMECODES_MODE&&!this.burnedIntervalId&&(this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33))}delete(){this.options.BURNED_TIMECODES_MODE&&this.stopBurnedPipeline(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.intervalLoopId&&clearInterval(this.intervalLoopId),this.metrics&&this.metrics.delete(),this.debugControls&&this.debugControls.delete()}};pe.MIN_SUPPORTED_FPS=20,pe.MAX_SUPPORTED_FPS=40;let it=pe;class q{constructor(e,r){this.size=1,this.positionElement=()=>{let s=0,i=0;this.corner=="left-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i}px`):this.corner=="right-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i}px`)},this.video=r,this.container=r.parentElement,this.corner=e;const n=document.createElement("div");n.style.position="absolute",n.style.width=`${this.size}px`,n.style.height=`${this.size}px`,n.style.transition="background-color 0s",n.style.zIndex="100000",this.element=n,this.container.appendChild(n),this.positionElement()}getRandomColor(){const n=Math.floor(Math.random()*11)+0;return`rgb(${n},${n},${n})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new q("left-top",e),new q("right-top",e),new q("right-bottom",e),new q("left-bottom",e)]}static updateAll(e){e.forEach(r=>r.update())}static deleteAll(e){e.forEach(r=>r.delete())}}const C={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},M=console,X={};Object.keys(C).forEach(t=>{X[t]=M[t]});const ge="Datadog Browser SDK:",D={debug:X.debug.bind(M,ge),log:X.log.bind(M,ge),info:X.info.bind(M,ge),warn:X.warn.bind(M,ge),error:X.error.bind(M,ge)},ot="https://docs.datadoghq.com",Yt=`${ot}/real_user_monitoring/browser/troubleshooting`,Fe="More details:";function qt(t,e){return(...r)=>{try{return t(...r)}catch(n){D.error(e,n)}}}function Le(t){return t!==0&&Math.random()*100<=t}function gn(t){return yn(t)&&t>=0&&t<=100}function yn(t){return typeof t=="number"}const ye=1e3,K=60*ye,Xt=60*K,_n=365*(24*Xt);function _e(){return new Date().getTime()}function G(){return _e()}function Pe(){return performance.now()}function V(){return{relative:Pe(),timeStamp:G()}}function bn(){return{relative:0,timeStamp:Kt()}}function vn(t,e){return e-t}function Tn(t,e){return t+e}function Sn(t){return t-Kt()}let at;function Kt(){return at===void 0&&(at=performance.timing.navigationStart),at}const B=1024,Jt=1024*B,En=/[^\u0000-\u007F]/;function ct(t){return En.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function xn(t){return{...t}}function Zt(t,e){return Object.keys(t).some(r=>t[r]===e)}function be(t){return Object.keys(t).length===0}function H(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function oe(t,e){const r=H();let n;return r.Zone&&typeof r.Zone.__symbol__=="function"&&(n=t[r.Zone.__symbol__(e)]),n||(n=t[e]),n}let Oe,Qt=!1;function wn(t){Oe=t}function An(t){Qt=t}function Rn(t,e,r){const n=r.value;r.value=function(...s){return(Oe?x(n):n).apply(this,s)}}function x(t){return function(){return ve(t,this,arguments)}}function ve(t,e,r){try{return t.apply(e,r)}catch(n){Cn(n)}}function Cn(t){if(lt(t),Oe)try{Oe(t)}catch(e){lt(e)}}function lt(...t){Qt&&D.error("[MONITOR]",...t)}function Te(t,e){return oe(H(),"setTimeout")(x(t),e)}function er(t){oe(H(),"clearTimeout")(t)}function dt(t,e){return oe(H(),"setInterval")(x(t),e)}function tr(t){oe(H(),"clearInterval")(t)}class k{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(r=>e!==r),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(r=>r(e))}}function rr(...t){return new k(e=>{const r=t.map(n=>n.subscribe(s=>e.notify(s)));return()=>r.forEach(n=>n.unsubscribe())})}function nr(t,e,r){let n=!1,s,i;return{throttled:(...o)=>{if(n){s=o;return}t(...o),n=!0,i=Te(()=>{s&&t(...s),n=!1,s=void 0},e)},cancel:()=>{er(i),n=!1,s=void 0}}}function W(){}function j(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\w-]+)\s*=\s*([^;]+)/g;function Dn(t,e){for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r){if(r[1]===e)return r[2]}else break}}function kn(t){const e=new Map;for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r)e.set(r[1],r[2]);else break}return e}function Un(t,e,r=""){const n=t.charCodeAt(e-1),i=n>=55296&&n<=56319?e+1:e;return t.length<=i?t:`${t.slice(0,i)}${r}`}function Fn(){return Ln()===0}let Me;function Ln(){return Me??(Me=Pn())}function Pn(t=window){var e;const r=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(r)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(r)&&!/chrome|android/i.test(r)?1:2}function Se(t,e,r=0,n){const s=new Date;s.setTime(s.getTime()+r);const i=`expires=${s.toUTCString()}`,o=n&&n.crossSite?"none":"strict",a=n&&n.domain?`;domain=${n.domain}`:"",c=n&&n.secure?";secure":"",d=n&&n.partitioned?";partitioned":"";document.cookie=`${t}=${e};${i};path=/;samesite=${o}${a}${c}${d}`}function ut(t){return Dn(document.cookie,t)}let ht;function J(t){return ht||(ht=kn(document.cookie)),ht.get(t)}function sr(t,e){Se(t,"",0,e)}function On(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${j()}`,r="test";Se(e,r,K,t);const n=ut(e)===r;return sr(e,t),n}catch(e){return D.error(e),!1}}let ft;function In(){if(ft===void 0){const t=`dd_site_test_${j()}`,e="test",r=window.location.hostname.split(".");let n=r.pop();for(;r.length&&!ut(t);)n=`${r.pop()}.${n}`,Se(t,e,ye,{domain:n});sr(t,{domain:n}),ft=n}return ft}const ae="_dd_s";function Be(t){return Object.values(t)}function Mn(t){return Object.entries(t)}const pt=4*Xt,ir=15*K,Bn=_n,Ee={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},or=/^([a-zA-Z]+)=([a-z0-9-]+)$/,mt="&";function Nn(t){return!!t&&(t.indexOf(mt)!==-1||or.test(t))}const zn="1";function Z(t,e){const r={isExpired:zn};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?r.anonymousId=t==null?void 0:t.anonymousId:r.anonymousId=j()),r}function Ne(t){return be(t)}function ar(t){return!Ne(t)}function ze(t){return t.isExpired!==void 0||!$n(t)}function $n(t){return(t.created===void 0||_e()-Number(t.created)<pt)&&(t.expire===void 0||_e()<Number(t.expire))}function cr(t){t.expire=String(_e()+ir)}function gt(t){return Mn(t).map(([e,r])=>e==="anonymousId"?`aid=${r}`:`${e}=${r}`).join(mt)}function lr(t){const e={};return Nn(t)&&t.split(mt).forEach(r=>{const n=or.exec(r);if(n!==null){const[,s,i]=n;s==="aid"?e.anonymousId=i:e[s]=i}}),e}const Gn="_dd",Vn="_dd_r",Hn="_dd_l",Wn="rum",jn="logs";function Yn(t){if(!J(ae)){const r=J(Gn),n=J(Vn),s=J(Hn),i={};r&&(i.id=r),s&&/^[01]$/.test(s)&&(i[jn]=s),n&&/^[012]$/.test(n)&&(i[Wn]=n),ar(i)&&(cr(i),t.persistSession(i))}}function dr(t){const e=Zn(t);return On(e)?{type:Ee.COOKIE,cookieOptions:e}:void 0}function qn(t,e){const r={isLockEnabled:Fn(),persistSession:Xn(e),retrieveSession:Jn,expireSession:n=>Kn(e,n,t)};return Yn(r),r}function Xn(t){return e=>{Se(ae,gt(e),ir,t)}}function Kn(t,e,r){const n=Z(e,r);Se(ae,gt(n),r.trackAnonymousUser?Bn:pt,t)}function Jn(){const t=ut(ae);return lr(t)}function Zn(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=In()),e}const Qn="_dd_test_";function ur(){try{const t=j(),e=`${Qn}${t}`;localStorage.setItem(e,t);const r=localStorage.getItem(e);return localStorage.removeItem(e),t===r?{type:Ee.LOCAL_STORAGE}:void 0}catch{return}}function es(t){return{isLockEnabled:!1,persistSession:hr,retrieveSession:ts,expireSession:e=>rs(e,t)}}function hr(t){localStorage.setItem(ae,gt(t))}function ts(){const t=localStorage.getItem(ae);return lr(t)}function rs(t,e){hr(Z(t,e))}const ns=10,ss=100,fr=[];let $e;function Q(t,e,r=0){var n;const{isLockEnabled:s,persistSession:i,expireSession:o}=e,a=f=>i({...f,lock:d}),c=()=>{const f=e.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if($e||($e=t),t!==$e){fr.push(t);return}if(s&&r>=ss){pr(e);return}let d,l=c();if(s){if(l.lock){Ge(t,e,r);return}if(d=j(),a(l.session),l=c(),l.lock!==d){Ge(t,e,r);return}}let u=t.process(l.session);if(s&&(l=c(),l.lock!==d)){Ge(t,e,r);return}if(u&&(ze(u)?o(u):(cr(u),s?a(u):i(u))),s&&!(u&&ze(u))){if(l=c(),l.lock!==d){Ge(t,e,r);return}i(l.session),u=l.session}(n=t.after)===null||n===void 0||n.call(t,u||l.session),pr(e)}function Ge(t,e,r){Te(()=>{Q(t,e,r+1)},ns)}function pr(t){$e=void 0;const e=fr.shift();e&&Q(e,t)}const mr=ye;function is(t){switch(t.sessionPersistence){case Ee.COOKIE:return dr(t);case Ee.LOCAL_STORAGE:return ur();case void 0:{let e=dr(t);return!e&&t.allowFallbackToLocalStorage&&(e=ur()),e}default:D.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function os(t,e,r,n){const s=new k,i=new k,o=new k,a=t.type===Ee.COOKIE?qn(e,t.cookieOptions):es(e),{expireSession:c}=a,d=dt(h,mr);let l;g();const{throttled:u,cancel:f}=nr(()=>{Q({process:v=>{if(Ne(v))return;const F=m(v);return S(F),F},after:v=>{ar(v)&&!b()&&w(v),l=v}},a)},mr);function p(){Q({process:v=>b()?m(v):void 0},a)}function h(){Q({process:v=>ze(v)?Z(v,e):void 0,after:m},a)}function m(v){return ze(v)&&(v=Z(v,e)),b()&&(E(v)?A():(o.notify({previousState:l,newState:v}),l=v)),v}function g(){Q({process:v=>{if(Ne(v))return Z(v,e)},after:v=>{l=v}},a)}function S(v){if(Ne(v))return!1;const{trackingType:F,isTracked:Mt}=n(v[r]);v[r]=F,delete v.isExpired,Mt&&!v.id&&(v.id=j(),v.created=String(_e()))}function b(){return l[r]!==void 0}function E(v){return l.id!==v.id||l[r]!==v[r]}function A(){l=Z(l,e),i.notify()}function w(v){l=v,s.notify()}function R(v){Q({process:F=>({...F,...v}),after:m},a)}return{expandOrRenewSession:u,expandSession:p,getSession:()=>l,renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o,restartSession:g,expire:()=>{f(),c(l),m(Z(l,e))},stop:()=>{tr(d)},updateSessionState:R}}const yt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function as(t){const e=new k;return{tryToInit(r){t||(t=r)},update(r){t=r,e.notify()},isGranted(){return t===yt.GRANTED},observable:e}}function ee(t,e,r){if(typeof t!="object"||t===null)return JSON.stringify(t);const n=ce(Object.prototype),s=ce(Array.prototype),i=ce(Object.getPrototypeOf(t)),o=ce(t);try{return JSON.stringify(t,e,r)}catch{return"<error: unable to serialize object>"}finally{n(),s(),i(),o()}}function ce(t){const e=t,r=e.toJSON;return r?(delete e.toJSON,()=>{e.toJSON=r}):W}function _t(t){return cs(t,location.href).href}function cs(t,e){const r=ls();if(r)try{return e!==void 0?new r(t,e):new r(t)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${ee({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let n=document;const s=n.createElement("a");if(e!==void 0){n=document.implementation.createHTMLDocument("");const i=n.createElement("base");i.href=e,n.head.appendChild(i),n.body.appendChild(s)}return s.href=t,s}const gr=URL;let Ve;function ls(){if(Ve===void 0)try{Ve=new gr("http://test/path").href==="http://test/path"}catch{Ve=!1}return Ve?gr:void 0}const ds="datad0g.com",us="dd0g-gov.com",le="datadoghq.com",hs="ddog-gov.com",fs="pci.browser-intake-datadoghq.com",ps=["ddsource","ddtags"];function xe(t,e,r){const n=ms(t,e);return{build(s,i){const o=ys(t,e,r,s,i);return n(o)},urlPrefix:n(""),trackType:e}}function ms(t,e){const r=`/api/v2/${e}`,n=t.proxy;if(typeof n=="string"){const i=_t(n);return o=>`${i}?ddforward=${encodeURIComponent(`${r}?${o}`)}`}if(typeof n=="function")return i=>n({path:r,parameters:i});const s=gs(e,t);return i=>`https://${s}${r}?${i}`}function gs(t,e){const{site:r=le,internalAnalyticsSubdomain:n}=e;if(t==="logs"&&e.usePciIntake&&r===le)return fs;if(n&&r===le)return`${n}.${le}`;if(r===us)return`http-intake.logs.${r}`;const s=r.split("."),i=s.pop();return`browser-intake-${s.join("-")}.${i}`}function ys({clientToken:t,internalAnalyticsSubdomain:e},r,n,s,{retry:i,encoding:o}){const a=["sdk_version:6.5.0",`api:${s}`].concat(n);i&&a.push(`retry_count:${i.count}`,`retry_after:${i.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${t}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return o&&c.push(`dd-evp-encoding=${o}`),r==="rum"&&c.push(`batch_time=${G()}`),e&&c.reverse(),c.join("&")}const _s=200;function bs(t){const{env:e,service:r,version:n,datacenter:s}=t,i=[];return e&&i.push(He("env",e)),r&&i.push(He("service",r)),n&&i.push(He("version",n)),s&&i.push(He("datacenter",s)),i}function He(t,e){const r=_s-t.length-1;(e.length>r||vs(e))&&D.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${Fe} ${ot}/getting_started/tagging/#defining-tags`);const n=e.replace(/,/g,"_");return`${t}:${n}`}function vs(t){return Ts()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function Ts(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function Ss(t){const e=t.site||le,r=bs(t),n=Es(t,r);return{replica:xs(t,r),site:e,...n}}function Es(t,e){return{logsEndpointBuilder:xe(t,"logs",e),rumEndpointBuilder:xe(t,"rum",e),sessionReplayEndpointBuilder:xe(t,"replay",e)}}function xs(t,e){if(!t.replica)return;const r={...t,site:le,clientToken:t.replica.clientToken},n={logsEndpointBuilder:xe(r,"logs",e),rumEndpointBuilder:xe(r,"rum",e)};return{applicationId:t.replica.applicationId,...n}}function ws(t){return ps.every(e=>t.includes(e))}function bt(t,e){return t!=null&&typeof t!="string"?(D.error(`${e} must be defined as a string`),!1):!0}function As(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(D.error(`Site should be a valid Datadog site. ${Fe} ${ot}/getting_started/site/.`),!1):!0}function We(t,e){return t!==void 0&&!gn(t)?(D.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function Rs(t){var e,r,n,s,i,o;if(!t||!t.clientToken){D.error("Client Token is not configured, we will not send any data.");return}if(!(!As(t.site)||!We(t.sessionSampleRate,"Session")||!We(t.telemetrySampleRate,"Telemetry")||!We(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!We(t.telemetryUsageSampleRate,"Telemetry Usage")||!bt(t.version,"Version")||!bt(t.env,"Env")||!bt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Zt(yt,t.trackingConsent)){D.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&qt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:is(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(r=t.telemetrySampleRate)!==null&&r!==void 0?r:20,telemetryConfigurationSampleRate:(n=t.telemetryConfigurationSampleRate)!==null&&n!==void 0?n:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(i=t.trackingConsent)!==null&&i!==void 0?i:yt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*B,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ye,batchMessagesLimit:50,messageBytesLimit:256*B,...Ss(t)}}}function Cs(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var vt;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(vt||(vt={}));const yr=new Set;function Ds(t){Array.isArray(t)&&ks(t.filter(e=>Zt(vt,e)))}function ks(t){t.forEach(e=>{yr.add(e)})}function Us(){return yr}const we="?";function N(t){const e=[];let r=Tt(t,"stack");const n=String(t);return r&&r.startsWith(n)&&(r=r.slice(n.length)),r&&r.split(`
|
|
495
495
|
`).forEach(s=>{const i=Ps(s)||Is(s)||Bs(s)||$s(s);i&&(!i.func&&i.line&&(i.func=we),e.push(i))}),{message:Tt(t,"message"),name:Tt(t,"name"),stack:e}}const _r="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)",de="(?::(\\d+))",Fs=new RegExp(`^\\s*at (.*?) ?\\(${_r}${de}?${de}?\\)?\\s*$`,"i"),Ls=new RegExp(`\\((\\S*)${de}${de}\\)`);function Ps(t){const e=Fs.exec(t);if(!e)return;const r=e[2]&&e[2].indexOf("native")===0,n=e[2]&&e[2].indexOf("eval")===0,s=Ls.exec(e[2]);return n&&s&&(e[2]=s[1],e[3]=s[2],e[4]=s[3]),{args:r?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||we,line:e[3]?+e[3]:void 0,url:r?void 0:e[2]}}const Os=new RegExp(`^\\s*at ?${_r}${de}?${de}??\\s*$`,"i");function Is(t){const e=Os.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:we,line:e[2]?+e[2]:void 0,url:e[1]}}const Ms=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function Bs(t){const e=Ms.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||we,line:+e[3],url:e[2]}}const Ns=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,zs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function $s(t){const e=Ns.exec(t);if(!e)return;const r=e[3]&&e[3].indexOf(" > eval")>-1,n=zs.exec(e[3]);return r&&n&&(e[3]=n[1],e[4]=n[2],e[5]=void 0),{args:e[2]?e[2].split(","):[],column:e[5]?+e[5]:void 0,func:e[1]||we,line:e[4]?+e[4]:void 0,url:e[3]}}function Tt(t,e){if(typeof t!="object"||!t||!(e in t))return;const r=t[e];return typeof r=="string"?r:void 0}function Gs(t,e,r,n){const s=[{url:e,column:n,line:r}],{name:i,message:o}=Hs(t);return{name:i,message:o,stack:s}}const Vs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;function Hs(t){let e,r;return{}.toString.call(t)==="[object String]"&&([,e,r]=Vs.exec(t)),{name:e,message:r}}function je(t){const r=new Error(t);r.name="HandlingStack";let n;return ve(()=>{const s=N(r);s.stack=s.stack.slice(2),n=te(s)}),n}function te(t){let e=br(t);return t.stack.forEach(r=>{const n=r.func==="?"?"<anonymous>":r.func,s=r.args&&r.args.length>0?`(${r.args.join(", ")})`:"",i=r.line?`:${r.line}`:"",o=r.line&&r.column?`:${r.column}`:"";e+=`
|
|
496
496
|
at ${n}${s} @ ${r.url}${i}${o}`}),e}function br(t){return`${t.name||"Error"}: ${t.message}`}function re(t,e,r,{computeHandlingStack:n}={}){let s=t[e];if(typeof s!="function")if(e in t&&e.startsWith("on"))s=W;else return{stop:W};let i=!1;const o=function(){if(i)return s.apply(this,arguments);const a=Array.from(arguments);let c;ve(r,null,[{target:this,parameters:a,onPostCall:l=>{c=l},handlingStack:n?je("instrumented method"):void 0}]);const d=s.apply(this,a);return c&&ve(c,null,[d]),d};return t[e]=o,{stop:()=>{i=!0,t[e]===o&&(t[e]=s)}}}const Ws=220*B,js="$",Ys=3;function z(t,e=Ws){const r=ce(Object.prototype),n=ce(Array.prototype),s=[],i=new WeakMap,o=St(t,js,void 0,s,i),a=JSON.stringify(o);let c=a?a.length:0;if(c>e){xt(e,"discarded",t);return}for(;s.length>0&&c<e;){const d=s.shift();let l=0;if(Array.isArray(d.source))for(let u=0;u<d.source.length;u++){const f=St(d.source[u],d.path,u,s,i);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=l,l=1,c>e){xt(e,"truncated",t);break}d.target[u]=f}else for(const u in d.source)if(Object.prototype.hasOwnProperty.call(d.source,u)){const f=St(d.source[u],d.path,u,s,i);if(f!==void 0&&(c+=JSON.stringify(f).length+l+u.length+Ys,l=1),c>e){xt(e,"truncated",t);break}d.target[u]=f}}return r(),n(),o}function St(t,e,r,n,s){const i=Ks(t);if(!i||typeof i!="object")return qs(i);const o=Et(i);if(o!=="[Object]"&&o!=="[Array]"&&o!=="[Error]")return o;const a=t;if(s.has(a))return`[Reference seen at ${s.get(a)}]`;const c=r!==void 0?`${e}.${r}`:e,d=Array.isArray(i)?[]:{};return s.set(a,c),n.push({source:i,target:d,path:c}),d}function qs(t){return typeof t=="bigint"?`[BigInt] ${t.toString()}`:typeof t=="function"?`[Function] ${t.name||"unknown"}`:typeof t=="symbol"?`[Symbol] ${t.description||t.toString()}`:t}function Et(t){try{if(t instanceof Event)return Xs(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const r=Object.prototype.toString.call(t).match(/\[object (.*)\]/);if(r&&r[1])return`[${r[1]}]`}catch{}return"[Unserializable]"}function Xs(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?Et(t.currentTarget):null,target:t.target?Et(t.target):null}}function Ks(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function xt(t,e,r){D.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,r)}const vr="No stack, consider using an instance of Error";function Tr({stackTrace:t,originalError:e,handlingStack:r,componentStack:n,startClocks:s,nonErrorPrefix:i,source:o,handling:a}){const c=Y(e),d=Js(t,c,i,e),l=Zs(c,t)?te(t):vr,u=c?xr(e,o):void 0,f=t?t.name:void 0,p=Sr(e),h=Er(e);return{startClocks:s,source:o,handling:a,handlingStack:r,componentStack:n,originalError:e,type:f,message:d,stack:l,causes:u,fingerprint:p,context:h}}function Js(t,e,r,n){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${r} ${ee(z(n))}`}function Zs(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function Sr(t){return Y(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function Er(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Qs(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function Y(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function xr(t,e){let r=t;const n=[];for(;Y(r==null?void 0:r.cause)&&n.length<10;){const s=N(r.cause);n.push({message:r.cause.message,source:e,type:s==null?void 0:s.name,stack:te(s)}),r=r.cause}return n.length?n:void 0}const P={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function ei(t){const e=(s,i)=>{const o=Tr({stackTrace:s,originalError:i,startClocks:V(),nonErrorPrefix:"Uncaught",source:P.SOURCE,handling:"unhandled"});t.notify(o)},{stop:r}=ti(e),{stop:n}=ri(e);return{stop:()=>{r(),n()}}}function ti(t){return re(window,"onerror",({parameters:[e,r,n,s,i]})=>{let o;Y(i)?o=N(i):o=Gs(e,r,n,s),t(o,i??e)})}function ri(t){return re(window,"onunhandledrejection",({parameters:[e]})=>{const r=e.reason||"Empty reason",n=N(r);t(n,r)})}function ni(t){const e={version:"6.5.0",onReady(r){r()},...t};return Object.defineProperty(e,"_setDebug",{get(){return An},enumerable:!1}),e}function si(t,e,r){const n=t[e];n&&!n.q&&n.version&&D.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=r,n&&n.q&&n.q.forEach(s=>qt(s,"onReady callback threw an error:")())}function wr(t,e){e.silentMultipleInit||D.error(`${t} is already initialized.`)}function ne(t,e,r,n,s){return wt(t,e,[r],n,s)}function wt(t,e,r,n,{once:s,capture:i,passive:o}={}){const a=x(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(s&&u(),n(f))}),c=o?{capture:i,passive:o}:i,d=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=oe(d,"addEventListener");r.forEach(f=>l.call(e,f,a,c));function u(){const f=oe(d,"removeEventListener");r.forEach(p=>f.call(e,p,a,c))}return{stop:u}}const Ye={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ii(t,e){const r=[];e.includes(Ye.cspViolation)&&r.push(ai(t));const n=e.filter(s=>s!==Ye.cspViolation);return n.length&&r.push(oi(n)),rr(...r)}function oi(t){return new k(e=>{if(!window.ReportingObserver)return;const r=x((s,i)=>s.forEach(o=>e.notify(ci(o)))),n=new window.ReportingObserver(r,{types:t,buffered:!0});return n.observe(),()=>{n.disconnect()}})}function ai(t){return new k(e=>{const{stop:r}=ne(t,document,"securitypolicyviolation",n=>{e.notify(li(n))});return r})}function ci(t){const{type:e,body:r}=t;return Ar({type:r.id,message:`${e}: ${r.message}`,originalError:t,stack:Rr(r.id,r.message,r.sourceFile,r.lineNumber,r.columnNumber)})}function li(t){const e=`'${t.blockedURI}' blocked by '${t.effectiveDirective}' directive`;return Ar({type:t.effectiveDirective,message:`${Ye.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:Rr(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${Un(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function Ar(t){return{startClocks:V(),source:P.REPORT,handling:"unhandled",...t}}function Rr(t,e,r,n,s){return r?te({name:t,message:e,stack:[{func:"?",url:r,line:n??void 0,column:s??void 0}]}):void 0}function Cr(t,e){const r=window.__ddBrowserSdkExtensionCallback;r&&r({type:t,payload:e})}function Dr(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function qe(t,e,r=di()){if(e===void 0)return t;if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const s=e.flags||[e.global?"g":"",e.ignoreCase?"i":"",e.multiline?"m":"",e.sticky?"y":"",e.unicode?"u":""].join("");return new RegExp(e.source,s)}if(r.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const s=Array.isArray(t)?t:[];for(let i=0;i<e.length;++i)s[i]=qe(s[i],e[i],r);return s}const n=Dr(t)==="object"?t:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=qe(n[s],e[s],r));return n}function kr(t){return qe(void 0,t)}function ue(...t){let e;for(const r of t)r!=null&&(e=qe(e,r));return e}function di(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(r){const n=e.has(r);return n||e.add(r),n}}}const t=[];return{hasAlreadyBeenSeen(e){const r=t.indexOf(e)>=0;return r||t.push(e),r}}}function ui(){var t;const e=window.navigator;return{status:e.onLine?"connected":"not_connected",interfaces:e.connection&&e.connection.type?[e.connection.type]:void 0,effective_type:(t=e.connection)===null||t===void 0?void 0:t.effectiveType}}function hi(t){const e=new Set;return t.forEach(r=>e.add(r)),Array.from(e)}function Ur(t,e){const r=t.indexOf(e);r>=0&&t.splice(r,1)}const fi=500;function Fr(){const t=[];return{add:s=>{t.push(s)>fi&&t.splice(0,1)},remove:s=>{Ur(t,s)},drain:s=>{t.forEach(i=>i(s)),t.length=0}}}const se={log:"log",configuration:"configuration",usage:"usage"},pi=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],mi=[hs];let Lr=Fr(),he=t=>{Lr.add(()=>he(t))};function gi(t,e){let r;const n=new k,s=new Set,i=!mi.includes(e.site)&&Le(e.telemetrySampleRate),o={[se.log]:i,[se.configuration]:i&&Le(e.telemetryConfigurationSampleRate),[se.usage]:i&&Le(e.telemetryUsageSampleRate)},a=yi();he=d=>{const l=ee(d);if(o[d.type]&&s.size<e.maxTelemetryEventsPerPage&&!s.has(l)){const u=c(t,d,a);n.notify(u),Cr("telemetry",u),s.add(l)}},wn(Or);function c(d,l,u){return ue({type:"telemetry",date:G(),service:d,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ue(l,{runtime_env:u,connectivity:ui(),sdk_setup:"npm"}),experimental_features:Array.from(Us())},r!==void 0?r():{})}return{setContextProvider:d=>{r=d},observable:n,enabled:i}}function yi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function _i(){Lr.drain()}function bi(t){return t.site===ds}function Pr(t,e){lt(C.debug,t,e),he({type:se.log,message:t,status:"debug",...e})}function Or(t,e){he({type:se.log,status:"error",...Si(t),...e})}function vi(t){he({type:se.configuration,configuration:t})}function Ti(t){he({type:se.usage,usage:t})}function Si(t){if(Y(t)){const e=N(t);return{error:{kind:e.name,stack:te(Ei(e))},message:e.message}}return{error:{stack:vr},message:`Uncaught ${ee(t)}`}}function Ei(t){return t.stack=t.stack.filter(e=>!e.url||pi.some(r=>e.url.startsWith(r))),t}const Ae=1/0,xi=K;let Re=null;const Xe=new Set;function wi(){Xe.forEach(t=>t())}function Ai({expireDelay:t,maxEntries:e}){let r=[];const n=[];Re||(Re=dt(()=>wi(),xi));const s=()=>{const p=Pe()-t;for(;r.length>0&&r[r.length-1].endTime<p;){const h=r.pop();h&&n.push(h.startTime)}};Xe.add(s);function i(p,h){const m={value:p,startTime:h,endTime:Ae,remove:()=>{Ur(r,m)},close:g=>{m.endTime=g}};return e&&r.length>=e&&r.pop(),r.unshift(m),m}function o(p=Ae,h={returnInactive:!1}){for(const m of r)if(m.startTime<=p){if(h.returnInactive||p<=m.endTime)return m.value;break}}function a(p){const h=r[0];h&&h.endTime===Ae&&h.close(p)}function c(p=Ae,h=0){const m=Tn(p,h);return r.filter(g=>g.startTime<=m&&p<=g.endTime).map(g=>g.value)}function d(){return r.map(({startTime:p,endTime:h,value:m})=>({startTime:p,endTime:h===Ae?"Infinity":h,value:m}))}function l(){return n}function u(){r=[]}function f(){Xe.delete(s),Xe.size===0&&Re&&(tr(Re),Re=null)}return{add:i,find:o,closeActive:a,findAll:c,reset:u,stop:f,getAllEntries:d,getDeletedEntries:l}}const Ri=K,Ci=pt;function Di(t,e,r,n){const s=new k,i=new k,o=os(t.sessionStoreStrategyType,t,e,r),a=Ai({expireDelay:Ci});o.renewObservable.subscribe(()=>{a.add(c(),Pe()),s.notify()}),o.expireObservable.subscribe(()=>{i.notify(),a.closeActive(Pe())}),o.expandOrRenewSession(),a.add(c(),bn().relative),n.observable.subscribe(()=>{n.isGranted()?o.expandOrRenewSession():o.expire()}),ki(t,()=>{n.isGranted()&&o.expandOrRenewSession()}),Ui(t,()=>o.expandSession()),Fi(t,()=>o.restartSession());function c(){return{id:o.getSession().id,trackingType:o.getSession()[e],isReplayForced:!!o.getSession().forcedReplay,anonymousId:o.getSession().anonymousId}}return{findSession:(d,l)=>a.find(d,l),renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o.sessionStateUpdateObservable,expire:o.expire,updateSessionState:o.updateSessionState}}function ki(t,e){wt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function Ui(t,e){const r=()=>{document.visibilityState==="visible"&&e()};ne(t,document,"visibilitychange",r),dt(r,Ri)}function Fi(t,e){ne(t,window,"resume",e,{capture:!0})}function Ir(t){return t>=500}function Li(t){try{return t.clone()}catch{return}}const Pi=80*B,Oi=32,Mr=3*Jt,Ii=K,Br=ye;function Nr(t,e,r,n,s){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?$r(t,e,r,{onSuccess:()=>Gr(0,e,r,n,s),onFailure:()=>{e.queuedPayloads.enqueue(t),zr(e,r,n,s)}}):e.queuedPayloads.enqueue(t)}function zr(t,e,r,n){t.transportStatus===2&&Te(()=>{const s=t.queuedPayloads.first();$r(s,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Br,Gr(1,t,e,r,n)},onFailure:()=>{t.currentBackoffTime=Math.min(Ii,t.currentBackoffTime*2),zr(t,e,r,n)}})},t.currentBackoffTime)}function $r(t,e,r,{onSuccess:n,onFailure:s}){e.bandwidthMonitor.add(t),r(t,i=>{e.bandwidthMonitor.remove(t),Mi(i)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:i.status},s()):(e.transportStatus=0,n())})}function Gr(t,e,r,n,s){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(s({message:`Reached max ${n} events size queued for upload: ${Mr/Jt}MiB`,source:P.AGENT,startClocks:V()}),e.queueFullReported=!0);const i=e.queuedPayloads;for(e.queuedPayloads=Vr();i.size()>0;)Nr(i.dequeue(),e,r,n,s)}function Mi(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Ir(t.status))}function Bi(){return{transportStatus:0,currentBackoffTime:Br,bandwidthMonitor:Ni(),queuedPayloads:Vr(),queueFullReported:!1}}function Vr(){const t=[];return{bytesCount:0,enqueue(e){this.isFull()||(t.push(e),this.bytesCount+=e.bytesCount)},first(){return t[0]},dequeue(){const e=t.shift();return e&&(this.bytesCount-=e.bytesCount),e},size(){return t.length},isFull(){return this.bytesCount>=Mr}}}function Ni(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Pi&&this.ongoingRequestCount<Oi},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function zi(t,e,r){const n=Bi(),s=(i,o)=>Vi(t,e,i,o);return{send:i=>{Nr(i,n,s,t.trackType,r)},sendOnExit:i=>{$i(t,e,i)}}}function $i(t,e,r){if(!!navigator.sendBeacon&&r.bytesCount<e)try{const i=t.build("beacon",r);if(navigator.sendBeacon(i,r.data))return}catch(i){Gi(i)}const s=t.build("xhr",r);At(s,r.data)}let Hr=!1;function Gi(t){Hr||(Hr=!0,Or(t))}function Vi(t,e,r,n){if(Hi()&&r.bytesCount<e){const i=t.build("fetch",r);fetch(i,{method:"POST",body:r.data,keepalive:!0,mode:"cors"}).then(x(o=>n==null?void 0:n({status:o.status,type:o.type})),x(()=>{const o=t.build("xhr",r);At(o,r.data,n)}))}else{const i=t.build("xhr",r);At(i,r.data,n)}}function Hi(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function At(t,e,r){const n=new XMLHttpRequest;n.open("POST",t,!0),e instanceof Blob&&n.setRequestHeader("Content-Type",e.type),ne({allowUntrustedEvents:!0},n,"loadend",()=>{r==null||r({status:n.status})},{once:!0}),n.send(e)}function Rt(){const t=Wi();if(t)return{getCapabilities(){var e;return JSON.parse(((e=t.getCapabilities)===null||e===void 0?void 0:e.call(t))||"[]")},getPrivacyLevel(){var e;return(e=t.getPrivacyLevel)===null||e===void 0?void 0:e.call(t)},getAllowedWebViewHosts(){return JSON.parse(t.getAllowedWebViewHosts())},send(e,r,n){const s=n?{id:n}:void 0;t.send(JSON.stringify({eventType:e,event:r,view:s}))}}}function Ke(t){var e;t===void 0&&(t=(e=H().location)===null||e===void 0?void 0:e.hostname);const r=Rt();return!!r&&r.getAllowedWebViewHosts().some(n=>t===n||t.endsWith(`.${n}`))}function Wi(){return H().DatadogEventBridge}const Je={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function ji(t){return new k(e=>{const{stop:r}=wt(t,window,["visibilitychange","freeze"],s=>{s.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:Je.HIDDEN}):s.type==="freeze"&&e.notify({reason:Je.FROZEN})},{capture:!0}),n=ne(t,window,"beforeunload",()=>{e.notify({reason:Je.UNLOADING})}).stop;return()=>{r(),n()}})}function Yi(t){return Be(Je).includes(t)}function qi({encoder:t,request:e,flushController:r,messageBytesLimit:n}){let s={};const i=r.flushObservable.subscribe(u=>l(u));function o(u,f,p){r.notifyBeforeAddMessage(f),p!==void 0?(s[p]=u,r.notifyAfterAddMessage()):t.write(t.isEmpty?u:`
|
|
497
497
|
${u}`,h=>{r.notifyAfterAddMessage(h-f)})}function a(u){return u!==void 0&&s[u]!==void 0}function c(u){const f=s[u];delete s[u];const p=t.estimateEncodedBytesCount(f);r.notifyAfterRemoveMessage(p)}function d(u,f){const p=ee(u),h=t.estimateEncodedBytesCount(p);if(h>=n){D.warn(`Discarded a message whose size was bigger than the maximum allowed size ${n}KB. ${Fe} ${Yt}/#technical-limitations`);return}a(f)&&c(f),o(p,h,f)}function l(u){const f=Be(s).join(`
|
|
498
498
|
`);s={};const p=Yi(u.reason),h=p?e.sendOnExit:e.send;if(p&&t.isAsync){const m=t.finishSync();m.outputBytesCount&&h(Wr(m));const g=[m.pendingData,f].filter(Boolean).join(`
|
|
499
499
|
`);g&&h({data:g,bytesCount:ct(g)})}else f&&t.write(t.isEmpty?f:`
|
|
500
|
-
${f}`),t.finish(m=>{h(Wr(m))})}return{flushController:r,add:d,upsert:d,stop:i.unsubscribe}}function Wr(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function Xi({messagesLimit:t,bytesLimit:e,durationLimit:r,pageExitObservable:n,sessionExpireObservable:s}){const i=n.subscribe(h=>l(h.reason)),o=s.subscribe(()=>l("session_expire")),a=new k(()=>()=>{i.unsubscribe(),o.unsubscribe()});let c=0,d=0;function l(h){if(d===0)return;const m=d,g=c;d=0,c=0,p(),a.notify({reason:h,messagesCount:m,bytesCount:g})}let u;function f(){u===void 0&&(u=Te(()=>{l("duration_limit")},r))}function p(){er(u),u=void 0}return{flushObservable:a,get messagesCount(){return d},notifyBeforeAddMessage(h){c+h>=e&&l("bytes_limit"),d+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,d>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,d-=1,d===0&&p()}}}function jr(t,e,r,n,s,i,o=qi){const a=d(t,e),c=r&&d(t,r);function d(l,{endpoint:u,encoder:f}){return o({encoder:f,request:zi(u,l.batchBytesLimit,n),flushController:Xi({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:i}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,u=!0){a.add(l),c&&u&&c.add(r.transformMessage?r.transformMessage(l):l)},upsert:(l,u)=>{a.upsert(l,u),c&&c.upsert(r.transformMessage?r.transformMessage(l):l,u)},stop:()=>{a.stop(),c&&c.stop()}}}function Ze(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(r,n){const s=ct(r);e+=s,t+=r,n&&n(s)},finish(r){r(this.finishSync())},finishSync(){const r={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,r},estimateEncodedBytesCount(r){return r.length}}}class Ki{constructor(){this.callbacks={}}notify(e,r){const n=this.callbacks[e];n&&n.forEach(s=>s(r))}subscribe(e,r){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(r),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(n=>r!==n)}}}}function Ji(t,e,r){let n=0,s=!1;return{isLimitReached(){if(n===0&&Te(()=>{n=0},K),n+=1,n<=e||s)return s=!1,!1;if(n===e+1){s=!0;try{r({message:`Reached max number of ${t}s by minute: ${e}`,source:P.AGENT,startClocks:V()})}finally{s=!1}}return!0}}}let Ct;const Dt=new WeakMap;function Zi(t){return Ct||(Ct=Qi(t)),Ct}function Qi(t){return new k(e=>{const{stop:r}=re(XMLHttpRequest.prototype,"open",eo),{stop:n}=re(XMLHttpRequest.prototype,"send",i=>{to(i,t,e)},{computeHandlingStack:!0}),{stop:s}=re(XMLHttpRequest.prototype,"abort",ro);return()=>{r(),n(),s()}})}function eo({target:t,parameters:[e,r]}){Dt.set(t,{state:"open",method:String(e).toUpperCase(),url:_t(String(r))})}function to({target:t,handlingStack:e},r,n){const s=Dt.get(t);if(!s)return;const i=s;i.state="start",i.startClocks=V(),i.isAborted=!1,i.xhr=t,i.handlingStack=e;let o=!1;const{stop:a}=re(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(d(),a(),o)return;o=!0;const l=s;l.state="complete",l.duration=vn(i.startClocks.timeStamp,G()),l.status=t.status,n.notify(xn(l))},{stop:d}=ne(r,t,"loadend",c);n.notify(i)}function ro({target:t}){const e=Dt.get(t);e&&(e.isAborted=!0)}let kt;function Yr(){return kt||(kt=no()),kt}function no(){return new k(t=>{if(!window.fetch)return;const{stop:e}=re(window,"fetch",r=>so(r,t),{computeHandlingStack:!0});return e})}function so({parameters:t,onPostCall:e,handlingStack:r},n){const[s,i]=t;let o=i&&i.method;o===void 0&&s instanceof Request&&(o=s.method);const a=o!==void 0?String(o).toUpperCase():"GET",c=s instanceof Request?s.url:_t(String(s)),d=V(),l={state:"start",init:i,input:s,method:a,startClocks:d,url:c,handlingStack:r};n.notify(l),t[0]=l.input,t[1]=l.init,e(u=>io(n,u,l))}function io(t,e,r){const n=r;function s(i){n.state="resolve",Object.assign(n,i),t.notify(n)}e.then(x(i=>{s({response:i,responseType:i.type,status:i.status,isAborted:!1})}),x(i=>{var o,a;s({status:0,isAborted:((a=(o=n.init)===null||o===void 0?void 0:o.signal)===null||a===void 0?void 0:a.aborted)||i instanceof DOMException&&i.code===DOMException.ABORT_ERR,error:i})}))}let Ut={};function oo(t){const e=t.map(r=>(Ut[r]||(Ut[r]=ao(r)),Ut[r]));return rr(...e)}function ao(t){return new k(e=>{const r=M[t];return M[t]=(...n)=>{r.apply(console,n);const s=je("console error");ve(()=>{e.notify(co(n,t,s))})},()=>{M[t]=r}})}function co(t,e,r){const n=t.map(i=>lo(i)).join(" ");let s;if(e===C.error){const i=t.find(Y);s={stack:i?te(N(i)):void 0,fingerprint:Sr(i),causes:i?xr(i,"console"):void 0,startClocks:V(),message:n,source:P.CONSOLE,handling:"handled",handlingStack:r,context:Er(i)}}return{api:e,message:n,error:s,handlingStack:r}}function lo(t){return typeof t=="string"?z(t):Y(t)?br(N(t)):ee(z(t),void 0,2)}function uo(t){const e=Dr(t)==="object";return e||D.error("Unsupported context:",t),e}function Ft(t,e,r){const n={...t};for(const[s,{required:i,type:o}]of Object.entries(e))o==="string"&&s in n&&(n[s]=String(n[s])),i&&!(s in t)&&D.warn(`The property ${s} of ${r} is required; context will not be sent to the intake.`);return n}function Qe(t="",{customerDataTracker:e,propertiesConfig:r={}}={}){let n={};const s=new k,i={getContext:()=>kr(n),setContext:o=>{uo(o)?(n=z(Ft(o,r,t)),e==null||e.updateCustomerData(n)):i.clearContext(),s.notify()},setContextProperty:(o,a)=>{n=z(Ft({...n,[o]:a},r,t)),e==null||e.updateCustomerData(n),s.notify()},removeContextProperty:o=>{delete n[o],e==null||e.updateCustomerData(n),Ft(n,r,t),s.notify()},clearContext:()=>{n={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return i}const ho="_dd_c",fo=[];function Lt(t,e,r,n){const s=po(r,n);fo.push(ne(t,window,"storage",({key:d})=>{s===d&&o()})),e.changeObservable.subscribe(a);const i=ue(c(),e.getContext());be(i)||e.setContext(i);function o(){e.setContext(c())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function c(){const d=localStorage.getItem(s);return d?JSON.parse(d):{}}}function po(t,e){return`${ho}_${t}_${e}`}const mo=3*B,go=16*B,yo=200;function _o(t=2){const e=new Map;let r=!1;function n(s=0){if(r||t===0)return;const i=t===2?mo:go;let o=s;e.forEach(a=>{o+=a.getBytesCount()}),o>i&&(bo(i),r=!0)}return{createDetachedTracker:()=>{const s=qr(()=>n(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,qr(n)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,n())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function qr(t){let e=0;const{throttled:r,cancel:n}=nr(i=>{e=ct(ee(i)),t()},yo),s=()=>{n(),e=0};return{updateCustomerData:i=>{be(i)?s():r(i)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{n()}}}function bo(t){D.warn(`Customer data exceeds the recommended ${t/B}KiB threshold. ${Fe} ${Yt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function vo(t,e,r){const n=t.getReader(),s=[];let i=0;o();function o(){n.read().then(x(c=>{if(c.done){a();return}s.push(c.value),i+=c.value.length,i>r.bytesLimit?a():o()}),x(c=>e(c)))}function a(){n.cancel().catch(W);let c,d;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(i);let u=0;s.forEach(f=>{l.set(f,u),u+=f.length})}c=l.slice(0,r.bytesLimit),d=l.length>r.bytesLimit}e(void 0,c,d)}}const To="datadog-synthetics-public-id",So="datadog-synthetics-result-id",Eo="datadog-synthetics-injects-rum";function Xr(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(Eo))}function xo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(To);return typeof t=="string"?t:void 0}function wo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||J(So);return typeof t=="string"?t:void 0}function et(t,e,r){const n=r.getHandler(),s=Array.isArray(n)?n:[n];return Kr[t]>=Kr[r.getLevel()]&&s.includes(e)}const T={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Kr={[T.ok]:0,[T.debug]:1,[T.info]:2,[T.notice]:4,[T.warn]:5,[T.error]:6,[T.critical]:7,[T.alert]:8,[T.emerg]:9};function tt(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var Ao=function(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i};const Ce={console:"console",http:"http",silent:"silent"},Ro=Object.keys(T);let O=class{constructor(e,r,n,s=Ce.http,i=T.debug,o={}){this.handleLogStrategy=e,this.handlerType=s,this.level=i,this.contextManager=Qe("logger",{customerDataTracker:r}),this.contextManager.setContext(o),n&&this.contextManager.setContextProperty("logger",{name:n})}logImplementation(e,r,n=T.info,s,i){const o=z(r);let a;if(s!=null){const c=Tr({stackTrace:Y(s)?N(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:P.LOGGER,handling:"handled",startClocks:V()});a=ue({error:tt(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:z(e),context:a,status:n},this,i)}log(e,r,n=T.info,s){let i;et(n,Ce.http,this)&&(i=je("log")),this.logImplementation(e,r,n,s,i)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,r){this.contextManager.setContextProperty(e,r)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};Ao([Rn],O.prototype,"logImplementation",null),O.prototype.ok=$(T.ok),O.prototype.debug=$(T.debug),O.prototype.info=$(T.info),O.prototype.notice=$(T.notice),O.prototype.warn=$(T.warn),O.prototype.error=$(T.error),O.prototype.critical=$(T.critical),O.prototype.alert=$(T.alert),O.prototype.emerg=$(T.emerg);function $(t){return function(e,r,n){let s;et(t,Ce.http,this)&&(s=je("log")),this.logImplementation(e,r,t,n,s)}}function Co(t,e,r){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:r.getContext()}}const Do=32*B;function ko(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&D.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Rs(t),r=Jr(t.forwardConsoleLogs,Be(C),"Forward Console Logs"),n=Jr(t.forwardReports,Be(Ye),"Forward Reports");if(!(!e||!r||!n))return t.forwardErrorsToLogs&&!r.includes(C.error)&&r.push(C.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:r,forwardReports:n,requestErrorResponseLengthLimit:Do,...e}}function Jr(t,e,r){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(n=>e.includes(n)))){D.error(`${r} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:hi(t)}function Uo(t){const e=Cs(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Fo(t,e,r){const n=Fr();let s,i;const o=e.observable.subscribe(a);function a(){if(!i||!s||!e.isGranted())return;o.unsubscribe();const c=r(s,i);n.drain(c)}return{init(c){if(!c){D.error("Missing configuration");return}if(Ds(c.enableExperimentalFeatures),Ke()&&(c=Lo(c)),s=c,i){wr("DD_LOGS",c);return}const d=ko(c);d&&(i=d,Yr().subscribe(W),e.tryToInit(d.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:W,handleLog(c,d,l,u=t(),f=G()){n.add(p=>p.handleLog(c,d,l,u,f))}}}function Lo(t){return{...t,clientToken:"empty"}}const Pt="logs";function Po(t){const e=_o(),r=Qe("global context",{customerDataTracker:e.getOrCreateTracker(2)}),n=Qe("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=Qe("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=as();function o(){return Co(r,n,s)}let a=Fo(o,i,(l,u)=>{l.storeContextsAcrossPages&&(Lt(u,r,Pt,2),Lt(u,n,Pt,1),Lt(u,s,Pt,4));const f=t(l,u,o,i);return a=Oo(l,f),f});const c={},d=new O((...l)=>a.handleLog(...l),e.createDetachedTracker());return ni({logger:d,init:x(l=>a.init(l)),setTrackingConsent:x(l=>{i.update(l),Ti({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:x(()=>r.getContext()),setGlobalContext:x(l=>r.setContext(l)),setGlobalContextProperty:x((l,u)=>r.setContextProperty(l,u)),removeGlobalContextProperty:x(l=>r.removeContextProperty(l)),clearGlobalContext:x(()=>r.clearContext()),createLogger:x((l,u={})=>(c[l]=new O((...f)=>a.handleLog(...f),e.createDetachedTracker(),z(l),u.handler,u.level,z(u.context)),c[l])),getLogger:x(l=>c[l]),getInitConfiguration:x(()=>kr(a.initConfiguration)),getInternalContext:x(l=>a.getInternalContext(l)),setUser:x(n.setContext),getUser:x(n.getContext),setUserProperty:x(n.setContextProperty),removeUserProperty:x(n.removeContextProperty),clearUser:x(n.clearContext),setAccount:x(s.setContext),getAccount:x(s.getContext),setAccountProperty:x(s.setContextProperty),removeAccountProperty:x(s.removeContextProperty),clearAccount:x(s.clearContext)})}function Oo(t,e){return{init:r=>{wr("DD_LOGS",r)},initConfiguration:t,...e}}const Io="logs";function Mo(t,e){const r=Di(t,Io,n=>No(t,n),e);return{findTrackedSession:(n,s={returnInactive:!1})=>{const i=r.findSession(n,s);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:r.expireObservable}}function Bo(t){const r=Zr(t)==="1"?{}:void 0;return{findTrackedSession:()=>r,expireObservable:new k}}function Zr(t){return Le(t.sessionSampleRate)?"1":"0"}function No(t,e){const r=zo(e)?e:Zr(t);return{trackingType:r,isTracked:r==="1"}}function zo(t){return t==="0"||t==="1"}let Qr=!1;function rt(t){const e=window;if(Xr()){const n=r(e.DD_RUM_SYNTHETICS);return!n&&!Qr&&(Qr=!0,Pr("Logs sent before RUM is injected by the synthetics worker",{testId:xo(),resultId:wo()})),n}return r(e.DD_RUM);function r(n){if(n&&n.getInternalContext)return n.getInternalContext(t)}}function $o(t,e,r,n,s){const i=Ro.concat(["custom"]),o={};i.forEach(a=>{o[a]=Ji(a,e.eventRateLimiterThreshold,s)}),r.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:d=void 0,domainContext:l})=>{var u,f;const p=Sn(a.date),h=t.findTrackedSession(p);if(!t.findTrackedSession(p,{returnInactive:!0}))return;const g=d||n();let S;!be(g.account)&&g.account.id&&(S=g.account),h&&h.anonymousId&&!g.user.anonymous_id&&(g.user.anonymous_id=h.anonymousId);const b=ue({service:e.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:be(g.user)?void 0:g.user,account:S,view:g.view},g.context,rt(p),a,c);((u=e.beforeSend)===null||u===void 0?void 0:u.call(e,b,l))===!1||b.origin!==P.AGENT&&((f=o[b.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||r.notify(1,b)})}const Go={[C.log]:T.info,[C.debug]:T.debug,[C.info]:T.info,[C.warn]:T.warn,[C.error]:T.error};function Vo(t,e){const r=oo(t.forwardConsoleLogs).subscribe(n=>{var s;const i={rawLogsEvent:{date:G(),message:n.message,origin:P.CONSOLE,error:n.error&&tt(n.error),status:Go[n.api]},messageContext:(s=n.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:n.handlingStack}};e.notify(0,i)});return{stop:()=>{r.unsubscribe()}}}function Ho(t,e){const r=ii(t,t.forwardReports).subscribe(n=>{let s=n.message,i;const o=n.originalError.type==="deprecation"?T.warn:T.error;o===T.error?i=tt(n):n.stack&&(s+=` Found in ${Qs(n.stack)}`),e.notify(0,{rawLogsEvent:{date:G(),message:s,origin:P.REPORT,error:i,status:o}})});return{stop:()=>{r.unsubscribe()}}}function Wo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=Zi(t).subscribe(i=>{i.state==="complete"&&s("xhr",i)}),n=Yr().subscribe(i=>{i.state==="resolve"&&s("fetch",i)});function s(i,o){!ws(o.url)&&(Xo(o)||Ir(o.status))&&("xhr"in o?jo(o.xhr,t,a):o.response?qo(o.response,t,a):o.error&&Yo(o.error,t,a));function a(c){const d={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${Ko(i)} error ${o.method} ${o.url}`,date:o.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:o.method,status_code:o.status,url:o.url},status:T.error,origin:P.NETWORK},domainContext:d})}}return{stop:()=>{r.unsubscribe(),n.unsubscribe()}}}function jo(t,e,r){typeof t.response=="string"?r(Ot(t.response,e)):r(t.response)}function Yo(t,e,r){r(Ot(te(N(t)),e))}function qo(t,e,r){const n=Li(t);!n||!n.body?r():window.TextDecoder?Jo(n.body,e.requestErrorResponseLengthLimit,(s,i)=>{r(s?`Unable to retrieve response: ${s}`:i)}):n.text().then(x(s=>r(Ot(s,e))),x(s=>r(`Unable to retrieve response: ${s}`)))}function Xo(t){return t.status===0&&t.responseType!=="opaque"}function Ot(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function Ko(t){return t==="xhr"?"XHR":"Fetch"}function Jo(t,e,r){vo(t,(n,s,i)=>{if(n)r(n);else{let o=new TextDecoder().decode(s);i&&(o+="..."),r(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function Zo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=new k,{stop:n}=ei(r),s=r.subscribe(i=>{e.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:tt(i),origin:P.SOURCE,status:T.error},messageContext:i.context})});return{stop:()=>{n(),s.unsubscribe()}}}const Qo=Ki;function ea(t){function e(r,n,s,i,o){const a=ue(n.getContext(),r.context);if(et(r.status,Ce.console,n)&&ra(r,a),et(r.status,Ce.http,n)){const c={rawLogsEvent:{date:o||G(),message:r.message,status:r.status,origin:P.LOGGER},messageContext:a,savedCommonContext:i};s&&(c.domainContext={handlingStack:s}),t.notify(0,c)}}return{handleLog:e}}const ta={[T.ok]:C.debug,[T.debug]:C.debug,[T.info]:C.info,[T.notice]:C.info,[T.warn]:C.warn,[T.error]:C.error,[T.critical]:C.error,[T.alert]:C.error,[T.emerg]:C.error};function ra({status:t,message:e},r){X[ta[t]].call(M,e,r)}function na(t,e,r,n,s){const i=jr(t,{endpoint:t.logsEndpointBuilder,encoder:Ze()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);return e.subscribe(1,o=>{i.add(o)}),i}function sa(t){const e=Rt();t.subscribe(1,r=>{e.send("log",r)})}function ia(t){return{get:e=>{const r=t.findTrackedSession(e);if(r)return{session_id:r.id}}}}function oa(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:P.AGENT,status:T.error}}),Pr("Error reported to customer",{"error.message":e.message})}}function aa(t,e,r,n,s){const i=gi("browser-logs-sdk",e);i.setContextProvider(()=>{var a,c,d,l,u,f;return{application:{id:(a=rt())===null||a===void 0?void 0:a.application_id},session:{id:(c=s.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(d=rt())===null||d===void 0?void 0:d.view)===null||l===void 0?void 0:l.id},action:{id:(f=(u=rt())===null||u===void 0?void 0:u.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ke()){const a=Rt(),c=i.observable.subscribe(d=>a.send("internal_telemetry",d));o.push(()=>c.unsubscribe())}else{const a=jr(e,{endpoint:e.rumEndpointBuilder,encoder:Ze()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);o.push(()=>a.stop());const c=i.observable.subscribe(d=>a.add(d,bi(e)));o.push(()=>c.unsubscribe())}return _i(),vi(Uo(t)),{telemetry:i,stop:()=>{o.forEach(a=>a())}}}function ca(t,e,r,n){const s=new Qo,i=[];s.subscribe(1,f=>Cr("logs",f));const o=oa(s),a=ji(e),c=e.sessionStoreStrategyType&&!Ke()&&!Xr()?Mo(e,n):Bo(e),{stop:d}=aa(t,e,o,a,c);i.push(()=>d()),Wo(e,s),Zo(e,s),Vo(e,s),Ho(e,s);const{handleLog:l}=ea(s);if($o(c,e,s,r,o),Ke())sa(s);else{const{stop:f}=na(e,s,o,a,c);i.push(()=>f())}const u=ia(c);return{handleLog:l,getInternalContext:u.get,stop:()=>{i.forEach(f=>f())}}}const fe=Po(ca);si(H(),"DD_LOGS",fe);const y=class y{constructor(e){this.listenerMap=new Map,y.options=e,this.isLoggingOn=e.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const r="bb_logger_mac_uuid";let n=localStorage.getItem(r);n||(n=crypto.randomUUID(),localStorage.setItem(r,n)),y.tracking.mac=n,y.tracking.dev=`${e.platform}_${e.browserName}`,y.beatHandle||(y.options&&_(y.options,"Logger")&&console.log("[Logger] Starting tracking beat"),y.beatHandle=window.setInterval(y.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}addEventListener(e,r){const n=s=>r(s);this.listenerMap.set(r,{eventName:e,wrappedListener:n}),this.eventTarget.addEventListener(e,n)}removeEventListener(e,r){const n=this.listenerMap.get(r);n&&n.eventName===e&&(this.eventTarget.removeEventListener(e,n.wrappedListener),this.listenerMap.delete(r))}removeAllEventListeners(){for(const[e,{eventName:r,wrappedListener:n}]of this.listenerMap)this.eventTarget.removeEventListener(r,n);this.listenerMap.clear()}setAttributes(e){y.processAttributes(e);for(const r in e)fe.logger.setContextProperty(r,e[r])}info(e,r){e==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(r==null?void 0:r.url)||""}),e==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(r==null?void 0:r.isEnabled)||!0}),e==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",r),e==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",r),e==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",r),r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.info(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending info: ",e))}error(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.error(e,r),y.tracking.err_time=Date.now().toFixed(0),y.tracking.err_desc=e+(r?` - ${JSON.stringify(r)}`:""),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending error: ",e))}warn(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.warn(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){if(!y.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{y.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}catch(r){console.error("[Logger] Error posting message:",r)}}static info(e,r){y.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:r})}static error(e,r){y.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:r})}static warn(e,r){y.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:r})}static processAttributes(e){if(e.player_version&&(y.tracking.sdk=e.player_version),e.media_id&&(y.tracking.gid=e.media_id),e.game_id&&(y.tracking.buc=e.game_id),e.bb_session_id&&(y.tracking.sid=e.bb_session_id,y.options&&_(y.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",y.tracking.sid)),e.last_timecode){const n=L.fromStr(e.last_timecode);y.tracking.tc=n.print(),y.lastTimecodeMillis=n.totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))}e.last_offset&&(y.tracking.off=e.last_offset),e.last_loading_zip&&(y.tracking.zip=e.last_loading_zip+".zip",y.lastZipMillis=L.fromStr(e.last_loading_zip).totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(y.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(y.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([r,n])=>n!==0&&n!=="").map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`).join("&")}emit(e,r){const n=new CustomEvent(e,{detail:r});this.eventTarget.dispatchEvent(n)}};y.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},y.lastTimecodeMillis=0,y.lastZipMillis=0,y.flushTracking=()=>{const e=Date.now().toFixed(0);y.tracking.now=e;const n=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${y.objectToQuery(y.tracking)}`;y.options&&_(y.options,"Logger")&&console.log("[Logger] Flushing tracking data:",n),fetch(n,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),y.tracking.err_desc="",y.tracking.err_time=""};let It=y;const la={env:"prod",urlConfigURL:"https://db8igqxlbvayn.cloudfront.net/url_config.json",gameBaseURL:"https://db8igqxlbvayn.cloudfront.net",zipBaseURL:"https://db8igqxlbvayn.cloudfront.net",adsBaseURL:"https://dwu3k7rrxk5s3.cloudfront.net",LOG_TO_DATADOG:!0,SEND_METRICS:!0,BURNED_TIMECODES_MODE:!1,RENDER_LED:!0,DRAW_TIMESTAMP_WEBGL:!1,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:10,DOWNLOADER_ZIP_LENGTH_SECONDS:2,ZIP_BUFFER_READY_THRESHOLD:5,ZIP_BUFFER_FADEOUT_THRESHOLD:1,BENCHMARK_DURATION_SECONDS:10,DECODER_UPDATE_FREQUENCY:30,DECODER_FRAME_BATCH_SIZE:3,DECODER_LEAD_TIME_MILLIS:180,PERFORMANCE_TRACKING_INTERVAL:1e3,BUCKET_SUBFOLDER_PATH:"manifests/59.94/",debug:{on:!1,showAugmentationStatus:!1,logOTTPlayer:!1,logClocker:!1,logDownloader:!1,logDecoder:!1,logRenderer:!1,logFetcher:!1,logAdapter:!1,logAds:!1,logLogger:!1,logErrors:!1,trackPerformance:!1}},da="https://identity-qa.nba.com/qa/auth";class ua{constructor(e){this.cookies=[],this.xToken=null,this.authInProgress=!1,this.OTTPlayer=e,this.options=e.options,this.logger=e.logger}async fetchNBAToken(e,r){const n=this.options.authIdentityUrl||da;_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Fetching JWT from: ${n}`);const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r})});if(!s.ok){const o=await s.text().catch(()=>"");throw new Error(`NBA auth request failed: ${s.status} ${s.statusText} - ${o}`)}const i=await s.json().catch(()=>null);if(!i||!i.data||!i.data.jwt)throw new Error("NBA auth response was invalid or missing JWT token");return i.data.jwt}async loginAndGetCookies(e){try{const r=this.options.authNbaToken,n=this.options.authEmail,s=this.options.authPassword;if(!r&&(!n||!s))return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] No credentials or NBA token provided, skipping authentication"),[];const i=this.options.zipBaseURL;if(!i)return console.warn("[CloudFrontAuth] No zipBaseURL configured, cannot authenticate"),[];if(this.lastGameId===e&&this.cookies.length>0)return _(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] ✓ Using cached cookies for gameId=${e}`),this.cookies;if(this.authInProgress)return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ⏳ Auth already in progress, waiting..."),await this.waitForAuth(),this.cookies;this.authInProgress=!0,this.lastGameId=e,console.log(`[CloudFrontAuth] 🔐 Starting authentication for gameId=${e}`),console.log(`[CloudFrontAuth] CloudFront URL: ${i}`);let o;r?(o=r,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using provided NBA token")):this.xToken?(o=this.xToken,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using existing x-token")):(o=await this.fetchNBAToken(n,s),_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Got JWT token from NBA Identity"));const a=`${i}/auth/${encodeURIComponent(e)}`;console.log(`[CloudFrontAuth] Fetching cookies from: ${a}`);const c=await fetch(a,{method:"GET",credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(!c.ok&&c.status!==204)throw new Error(`Failed to fetch cookies: ${c.status} ${c.statusText}`);_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auth endpoint status: ${c.status}`);const d=c.headers.get("x-token");d&&(this.xToken=d,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Received fresh x-token"));const l=c.headers.get("set-cookie");return l?this.cookies=l.split(",").map(u=>u.trim()):this.cookies=["browser-managed-httponly-cookies"],console.log("[CloudFrontAuth] ✅ Successfully authenticated"),console.log("[CloudFrontAuth] Note: Cookies are HttpOnly and managed by browser automatically"),this.logger.info("didAuthenticateCloudFront",{gameId:e,cookieCount:this.cookies.length,hasXToken:!!this.xToken}),this.scheduleCookieRefresh(e),this.cookies}catch(r){return console.error("[CloudFrontAuth] ❌ Authentication failed:",r),this.logger.error("[CloudFrontAuth] Authentication failed",{error:r.message||r}),this.xToken=null,[]}finally{this.authInProgress=!1}}async waitForAuth(){return new Promise(e=>{const r=setInterval(()=>{this.authInProgress||(clearInterval(r),e())},100)})}scheduleCookieRefresh(e){this.cookieRefreshTimer&&window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=window.setTimeout(()=>{_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auto-refreshing cookies and x-token for gameId=${e}`),this.loginAndGetCookies(e)},7*60*60*1e3)}getCookies(){return this.cookies}getXToken(){return this.xToken}isAuthenticated(){return this.cookies.length>0}destroy(){this.cookies=[],this.xToken=null,this.lastGameId=void 0,this.cookieRefreshTimer&&(window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=void 0)}}class ha{constructor(e){this.groups=new Map,this.isVisible=!0,this.lastFrameTime=0,this.TARGET_FPS=60,this.FRAME_INTERVAL=1e3/this.TARGET_FPS,this.canvas=document.createElement("canvas"),this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0",this.canvas.style.pointerEvents="none",this.canvas.style.zIndex="3001",this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight,this.canvas.style.width="100%",this.canvas.style.height="100%",this.ctx=this.canvas.getContext("2d"),e.appendChild(this.canvas),this.initializeGroups(),this.startRenderLoop(),this.setupResizeObserver(e)}initializeGroups(){this.groups.set("support",{title:"Basic Augmentation Support",metrics:new Map([["game_params",{value:!1}],["browser",{value:!1,detail:""}],["pattern",{value:!1,detail:""}],["fps",{value:!1,detail:""}],["mk_ads",{value:!1,detail:""}]])}),this.groups.set("timecode",{title:"TimeCode Status",metrics:new Map([["sync_point",{value:!1,detail:""}],["consistency",{value:!1,detail:""}]])}),this.groups.set("benchmark",{title:"",metrics:new Map([["status",{value:"FAILED",detail:""}]])}),this.groups.set("switches",{title:"Augmentation Switches",metrics:new Map([["killswitch_web",{value:!1}],["killswitch_local",{value:!1}],["isLive",{value:!1}],["render_state",{value:"OFF"}]])}),this.groups.set("data",{title:"Augmentation Data Presence",metrics:new Map([["zip_buffer",{value:!1,detail:"0.0s"}],["stream_data",{value:!1}],["ads",{value:!1}],["render_data",{value:!1}],["alpha_mask",{value:!1}],["placeholders",{value:!1}],["processing_size",{value:!1}]])}),this.groups.set("health",{title:"Player Components Health",metrics:new Map([["decoder",{value:!1,detail:""}],["webgl",{value:!1,detail:""}]])})}updateMetric(e,r,n,s){const i=this.groups.get(e);i&&i.metrics.set(r,{value:n,detail:s})}startRenderLoop(){const e=r=>{r-this.lastFrameTime>=this.FRAME_INTERVAL&&(this.isVisible&&this.draw(),this.lastFrameTime=r),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}setupResizeObserver(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight}),this.resizeObserver.observe(e))}draw(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);const e=12,r=e+3,n=10,s=15,i=10;this.ctx.font=`${e}px monospace`,this.ctx.textBaseline="top";let o=i;this.groups.forEach((c,d)=>{var l;if(d==="benchmark"){const u=c.metrics.get("status");if(u){const f=u.value;let p,h;f==="PASSED"?(p="rgba(0,255,136,0.8)",h="STABILITY TEST: PASSED"):f==="TESTING"?(p="rgba(255,170,0,0.8)",h=`STABILITY TEST: TESTING${u.detail?" ("+((l=u.detail.split(":")[1])==null?void 0:l.trim())+")":""}`):(p="rgba(255,51,51,0.8)",h="STABILITY TEST: FAILED"),this.ctx.fillStyle=p,this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(h,i+5,o+4),this.ctx.font=`${e}px monospace`,o+=25}return}this.ctx.fillStyle="rgba(0,0,0,0.7)",this.ctx.fillRect(i,o,300,r+2),this.ctx.fillStyle="#fff",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(c.title,i+5,o+1),this.ctx.font=`${e}px monospace`,o+=r+4,c.metrics.forEach((u,f)=>{const p=this.getColorForValue(u.value),h=this.formatValue(u.value);this.ctx.fillStyle="rgba(0,0,0,0.5)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle=p,this.ctx.beginPath(),this.ctx.arc(i+s+5,o+r/2,3,0,Math.PI*2),this.ctx.fill(),this.ctx.fillStyle="#fff";const m=f.replace(/_/g," ");this.ctx.fillText(`${m}: ${h}`,i+s+15,o+1),o+=r,u.detail&&(this.ctx.fillStyle="rgba(0,0,0,0.4)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle="#aaa",this.ctx.fillText(` ${u.detail}`,i+s+15,o+1),o+=r)}),o+=n});const a=this.isAugmentationReady();this.ctx.fillStyle=a?"rgba(0,255,136,0.8)":"rgba(255,51,51,0.8)",this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(`AUGMENTATION: ${a?"READY":"NOT READY"}`,i+5,o+4),this.ctx.font=`${e}px monospace`}formatValue(e){return typeof e=="boolean"?e?"OK":"NO":e==="PASSED"?"PASSED":e==="TESTING"?"TESTING":e==="FAILED"?"FAILED":e}getColorForValue(e){return typeof e=="boolean"?e?"#00ff88":"#ff3333":e==="ON"||e==="FADE_IN"?"#00ff88":e==="FADE_OUT"?"#ffaa00":e==="PASSED"?"#00ff88":e==="TESTING"?"#ffaa00":"#ff3333"}isAugmentationReady(){var u,f,p,h,m,g,S,b,E,A;const e=this.groups.get("support"),r=this.groups.get("switches"),n=this.groups.get("data"),s=this.groups.get("health"),i=this.groups.get("benchmark");if(!e||!r||!n||!s||!i)return!1;const o=((u=e.metrics.get("game_params"))==null?void 0:u.value)===!0&&((f=e.metrics.get("browser"))==null?void 0:f.value)===!0&&((p=e.metrics.get("pattern"))==null?void 0:p.value)===!0&&((h=e.metrics.get("fps"))==null?void 0:h.value)===!0&&((m=e.metrics.get("mk_ads"))==null?void 0:m.value)===!0,a=((g=r.metrics.get("killswitch_web"))==null?void 0:g.value)===!0&&((S=r.metrics.get("killswitch_local"))==null?void 0:S.value)===!0&&(((b=r.metrics.get("render_state"))==null?void 0:b.value)==="ON"||((E=r.metrics.get("render_state"))==null?void 0:E.value)==="FADE_IN"),c=Array.from(n.metrics.values()).every(w=>w.value===!0),d=Array.from(s.metrics.values()).every(w=>w.value===!0),l=((A=i.metrics.get("status"))==null?void 0:A.value)==="PASSED";return o&&a&&c&&d&&l}toggle(){this.isVisible=!this.isVisible,this.isVisible||this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}pause(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}resume(){this.animationFrameId||this.startRenderLoop()}delete(){this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.resizeObserver&&this.resizeObserver.disconnect(),this.canvas.remove()}}class en{constructor(e,r,n,s){this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.handleVisibilityChange=()=>{document.hidden?this.onTabHidden():this.onTabVisible()},this.fetchGameParams=async()=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId),this.options.OVERRIDE_GAME_PARAMS){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Using OVERRIDE_GAME_PARAMS from configuration");const d=this.options.OVERRIDE_GAME_PARAMS;if(this.options.BURNED_TIMECODES_MODE){this.gameParams=d;return}if(d.hasOwnProperty("bucketName")&&d.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:d.bucketName,customer_name:d.customerName,customer_id:d.customerId}),this.gameParams){const l=JSON.stringify(this.gameParams),u=JSON.stringify(d);l!==u&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:d})}else this.logger.info("didFetchGameInfo",d);this.gameParams=d,this.cloudFrontAuth&&d.bucketName&&this.cloudFrontAuth.loginAndGetCookies(d.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",d.bucketName)}).catch(l=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",l)});return}else throw new Error(`OVERRIDE_GAME_PARAMS for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}let o;const a=`${this.options.gameBaseURL}/${this.options.gameId}.json`;if(_(this.options,"OTTPlayer")&&console.log(`Fetching GameParams from ${a}`),this.options.SEND_METRICS?o=await fetch(a,{headers:{"X-Platform":"Web"},cache:"no-store"}):o=await fetch(a,{cache:"no-store"}),!o.ok){const d=`Unable to fetch game params for ${this.options.gameId}. HTTP error. Status: ${o.status}`;this.logger.error("[OTTPlayer] Failed to fetch game params",{status:o.status,gameId:this.options.gameId}),_(this.options,"Errors")&&console.error(`[OTTPlayer] ${d}`),this.destroy();return}const c=await o.json();if(this.options.BURNED_TIMECODES_MODE){this.gameParams=c;return}if(this.handleOttActions(o,c),c.hasOwnProperty("bucketName")&&c.hasOwnProperty("offsets"))o=c;else throw new Error(`Game params for ${this.options.gameId} not found in JSON`);if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const d=JSON.stringify(this.gameParams),l=JSON.stringify(o);d!==l&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",this.gameParams);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(d=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",d)})}catch(o){this.logger.error("[OTTPlayer] Error fetching game params",{error:o}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",o)}this.fetchGameParamsTimeoutId=window.setTimeout(()=>this.fetchGameParams(),1e4)},this.setGameParams=o=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Overriding game params"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),this.options.BURNED_TIMECODES_MODE){this.gameParams=o;return}if(o.hasOwnProperty("bucketName")&&o.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const a=JSON.stringify(this.gameParams),c=JSON.stringify(o);a!==c&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",o);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(a=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",a)});return}else throw new Error(`Game params for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}catch(a){this.logger.error("[OTTPlayer] Error overriding game params",{error:a}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error overriding game params:",a)}};const i="OTTPlayer_v1.0.69";console.log(`%c${i}`,"font-size: 16px; font-weight: bold; color: blue;"),this.video=e,this.options={...n,...la,platform:I.getCurrentPlatform(),browserName:I.getBrowserName(),augmentation:{channelName:"nba"}},this.options.browserName==="Firefox"&&(this.options.DECODER_LEAD_TIME_MILLIS=300),_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Starting fetchUrlConfig"),this.fetchUrlConfig(s),this.logger=new It(this.options),this.logger.setAttributes({player_version:i,bb_session_id:crypto.randomUUID()}),this.logger.info("didGetConfiguration",{...n,fps:r}),tn(this.options,s).then(()=>{var o;if(this.logger.setAttributes({media_id:this.options.gameId}),window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(a=>{a.destroy()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(a=>{a.terminate()}),this.cloudFrontAuth=new ua(this),this.clocker=new dn(this),this.adapter=new it(this),this.ottActions={toggle:{ios:!0,android:!0,web:!0,local:this.options.enabled}},(o=this.options.debug)!=null&&o.showAugmentationStatus){const a=this.options.CANVAS_CONTAINER||this.video.parentElement;a&&(this.statusOverlay=new ha(a))}this.RUN_PIXEL_TICKERS&&(this.pixelTickers=q.createInAllCorners(this.video)),this.applyImageOverridesFromOptions(),this.flushPendingOverrides(),this.fetchGameParams(),window.BB.playerInstances.push(this),document.addEventListener("visibilitychange",this.handleVisibilityChange)})}onNewMetadata(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewMetadata(e)}onNewSegment(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewSegmentForMetadata(e)}onAdEvent(e){console.log(`[OTTPlayer] onAdEvent: ${e}`),!(!this.adapter||this.options.BURNED_TIMECODES_MODE)&&this.adapter.onAdEvent(e)}async fetchUrlConfig(e){try{if(!this.options.urlConfigURL){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] No urlConfigURL provided, skipping URL config fetch");return}_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Fetching URL config from:",this.options.urlConfigURL);const r=await fetch(this.options.urlConfigURL);if(!r.ok)throw new Error(`Failed to fetch URL config: ${r.status} ${r.statusText}`);const n=await r.json();if(!n||typeof n!="object")throw new Error("Invalid URL config structure: not an object");const s=this.options.env;if(!n[s])throw new Error(`Environment '${s}' not found in URL config`);const i=n[s];if(!i.gameBaseUrl||!i.zipBaseUrl||!i.adsBaseUrl)throw new Error(`Missing required URLs in environment '${s}' config`);e!=null&&e.gameBaseURL||(this.options.gameBaseURL=i.gameBaseUrl),e!=null&&e.zipBaseURL||(this.options.zipBaseURL=i.zipBaseUrl),e!=null&&e.adsBaseURL||(this.options.adsBaseURL=i.adsBaseUrl),_(this.options,"OTTPlayer")&&(console.log("[OTTPlayer] URL config loaded successfully for environment:",s),console.log("[OTTPlayer] Updated URLs:",{gameBaseURL:this.options.gameBaseURL,zipBaseURL:this.options.zipBaseURL,adsBaseURL:this.options.adsBaseURL}))}catch(r){_(this.options,"OTTPlayer")&&(console.warn("[OTTPlayer] Failed to fetch URL config:",r),console.log("[OTTPlayer] Using default URLs from options"))}}handleOttActions(e,r){if(!this.clocker||this.options.BURNED_TIMECODES_MODE)return;const n=e.headers.get("x-tgi-ott-actions");let s;if(n?s=JSON.parse(n):s={toggle:{ios:!0,android:!0,web:!0}},!this.ottActions||this.ottActions.toggle.web!==s.toggle.web||s.toggle[r.customerId]!==void 0&&(this.ottActions.toggle[r.customerId]===void 0||this.ottActions.toggle[r.customerId]!==s.toggle[r.customerId])||s.toggle[r.customerId]===void 0&&this.ottActions.toggle[r.customerId]!==void 0){const o=s.toggle[r.customerId]!==void 0?s.toggle[r.customerId]&&s.toggle.web:s.toggle.web;this.ottActions&&this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:o}),s.toggle.local=this.options.enabled,this.ottActions=s,console.warn("[OTTPlayer] ottActions",s)}}toggle(e){this.options.enabled=e,this.ottActions&&(this.ottActions.toggle.local=e,this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:e}))}setFps(e){this.fps=e}setMediaInfo(e){e.fps&&this.setFps(e.fps),e.bitrate&&(this.bitrate=e.bitrate)}setAd(e,r){if(typeof e=="string"){let n;try{n=new URL(e,document.baseURI).toString()}catch(s){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid ad URL passed to setAd",e,s);return}fetch(n,{cache:"no-store"}).then(s=>s.blob()).then(async s=>{if(!this.clocker){this.pendingAdBlob=s,this.pendingAdPlaceholder=r;return}this.clocker.setAdBlob(s,r)}).catch(s=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch ad image from URL in setAd",n,s)});return}if(!this.clocker){if(e instanceof Blob)this.pendingAdBlob=e;else{if(this.pendingAdBitmap)try{this.pendingAdBitmap.close()}catch{}this.pendingAdBitmap=e}this.pendingAdPlaceholder=r;return}if(e instanceof Blob){this.clocker.setAdBlob(e,r);return}else this.clocker.setAdImage(e,r)}setLED(e){if(typeof e=="string"){let r;try{r=new URL(e,document.baseURI).toString()}catch(n){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid LED URL passed to setLED",e,n);return}fetch(r,{cache:"no-store"}).then(n=>n.blob()).then(n=>{if(!this.clocker){this.pendingLEDBlob=n;return}this.clocker.setLEDBlob(n)}).catch(n=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch LED image from URL in setLED",r,n)});return}if(!this.clocker){if(e instanceof Blob)this.pendingLEDBlob=e;else{if(this.pendingLEDBitmap)try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=e}return}e instanceof Blob?this.clocker.setLEDBlob(e):this.clocker.setLEDImage(e)}async applyImageOverridesFromOptions(){try{const e=[];this.options.OVERRIDE_AD&&e.push(this.applySingleOverride(this.options.OVERRIDE_AD,"ad")),this.options.OVERRIDE_LED&&e.push(this.applySingleOverride(this.options.OVERRIDE_LED,"led")),await Promise.all(e)}catch(e){_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to apply image overrides",e)}}async applySingleOverride(e,r){let n;if(typeof e=="string")try{const s=new URL(e,document.baseURI).toString();n=await(await fetch(s,{cache:"no-store"})).blob()}catch(s){_(this.options,"Errors")&&console.error(`[OTTPlayer] Failed to fetch override ${r} from URL`,e,s);return}else n=e;if(n){if(!this.clocker){r==="ad"?this.pendingAdBlob=n:this.pendingLEDBlob=n;return}r==="ad"?this.clocker.setAdBlob(n):this.clocker.setLEDBlob(n)}}flushPendingOverrides(){if(this.clocker){if(this.pendingAdBitmap){const e=this.pendingAdBitmap;this.pendingAdBitmap=void 0,this.clocker.setAdImage(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}else if(this.pendingAdBlob){const e=this.pendingAdBlob;this.pendingAdBlob=void 0,this.clocker.setAdBlob(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}if(this.pendingLEDBitmap){const e=this.pendingLEDBitmap;this.pendingLEDBitmap=void 0,this.clocker.setLEDImage(e)}else if(this.pendingLEDBlob){const e=this.pendingLEDBlob;this.pendingLEDBlob=void 0,this.clocker.setLEDBlob(e)}}}onTabHidden(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab hidden - pausing all components"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(e=this.clocker)==null||e.pause(),(r=this.adapter)==null||r.pause(),(n=this.statusOverlay)==null||n.pause()}onTabVisible(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab visible - resuming all components"),(e=this.clocker)==null||e.resume(),(r=this.adapter)==null||r.resume(),(n=this.statusOverlay)==null||n.resume(),this.fetchGameParams()}on(e,r){this.logger.addEventListener(e,r)}off(e,r){this.logger.removeEventListener(e,r)}destroy(){var r;document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(r=this.clocker)==null||r.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),this.cloudFrontAuth&&(this.cloudFrontAuth.destroy(),this.cloudFrontAuth=void 0),this.statusOverlay&&(this.statusOverlay.delete(),this.statusOverlay=void 0),q.deleteAll(this.pixelTickers),this.pixelTickers=[],this.logger.removeAllEventListeners();const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:en,playerInstances:[],workerInstances:[]},en});
|
|
500
|
+
${f}`),t.finish(m=>{h(Wr(m))})}return{flushController:r,add:d,upsert:d,stop:i.unsubscribe}}function Wr(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function Xi({messagesLimit:t,bytesLimit:e,durationLimit:r,pageExitObservable:n,sessionExpireObservable:s}){const i=n.subscribe(h=>l(h.reason)),o=s.subscribe(()=>l("session_expire")),a=new k(()=>()=>{i.unsubscribe(),o.unsubscribe()});let c=0,d=0;function l(h){if(d===0)return;const m=d,g=c;d=0,c=0,p(),a.notify({reason:h,messagesCount:m,bytesCount:g})}let u;function f(){u===void 0&&(u=Te(()=>{l("duration_limit")},r))}function p(){er(u),u=void 0}return{flushObservable:a,get messagesCount(){return d},notifyBeforeAddMessage(h){c+h>=e&&l("bytes_limit"),d+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,d>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,d-=1,d===0&&p()}}}function jr(t,e,r,n,s,i,o=qi){const a=d(t,e),c=r&&d(t,r);function d(l,{endpoint:u,encoder:f}){return o({encoder:f,request:zi(u,l.batchBytesLimit,n),flushController:Xi({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:i}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,u=!0){a.add(l),c&&u&&c.add(r.transformMessage?r.transformMessage(l):l)},upsert:(l,u)=>{a.upsert(l,u),c&&c.upsert(r.transformMessage?r.transformMessage(l):l,u)},stop:()=>{a.stop(),c&&c.stop()}}}function Ze(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(r,n){const s=ct(r);e+=s,t+=r,n&&n(s)},finish(r){r(this.finishSync())},finishSync(){const r={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,r},estimateEncodedBytesCount(r){return r.length}}}class Ki{constructor(){this.callbacks={}}notify(e,r){const n=this.callbacks[e];n&&n.forEach(s=>s(r))}subscribe(e,r){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(r),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(n=>r!==n)}}}}function Ji(t,e,r){let n=0,s=!1;return{isLimitReached(){if(n===0&&Te(()=>{n=0},K),n+=1,n<=e||s)return s=!1,!1;if(n===e+1){s=!0;try{r({message:`Reached max number of ${t}s by minute: ${e}`,source:P.AGENT,startClocks:V()})}finally{s=!1}}return!0}}}let Ct;const Dt=new WeakMap;function Zi(t){return Ct||(Ct=Qi(t)),Ct}function Qi(t){return new k(e=>{const{stop:r}=re(XMLHttpRequest.prototype,"open",eo),{stop:n}=re(XMLHttpRequest.prototype,"send",i=>{to(i,t,e)},{computeHandlingStack:!0}),{stop:s}=re(XMLHttpRequest.prototype,"abort",ro);return()=>{r(),n(),s()}})}function eo({target:t,parameters:[e,r]}){Dt.set(t,{state:"open",method:String(e).toUpperCase(),url:_t(String(r))})}function to({target:t,handlingStack:e},r,n){const s=Dt.get(t);if(!s)return;const i=s;i.state="start",i.startClocks=V(),i.isAborted=!1,i.xhr=t,i.handlingStack=e;let o=!1;const{stop:a}=re(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(d(),a(),o)return;o=!0;const l=s;l.state="complete",l.duration=vn(i.startClocks.timeStamp,G()),l.status=t.status,n.notify(xn(l))},{stop:d}=ne(r,t,"loadend",c);n.notify(i)}function ro({target:t}){const e=Dt.get(t);e&&(e.isAborted=!0)}let kt;function Yr(){return kt||(kt=no()),kt}function no(){return new k(t=>{if(!window.fetch)return;const{stop:e}=re(window,"fetch",r=>so(r,t),{computeHandlingStack:!0});return e})}function so({parameters:t,onPostCall:e,handlingStack:r},n){const[s,i]=t;let o=i&&i.method;o===void 0&&s instanceof Request&&(o=s.method);const a=o!==void 0?String(o).toUpperCase():"GET",c=s instanceof Request?s.url:_t(String(s)),d=V(),l={state:"start",init:i,input:s,method:a,startClocks:d,url:c,handlingStack:r};n.notify(l),t[0]=l.input,t[1]=l.init,e(u=>io(n,u,l))}function io(t,e,r){const n=r;function s(i){n.state="resolve",Object.assign(n,i),t.notify(n)}e.then(x(i=>{s({response:i,responseType:i.type,status:i.status,isAborted:!1})}),x(i=>{var o,a;s({status:0,isAborted:((a=(o=n.init)===null||o===void 0?void 0:o.signal)===null||a===void 0?void 0:a.aborted)||i instanceof DOMException&&i.code===DOMException.ABORT_ERR,error:i})}))}let Ut={};function oo(t){const e=t.map(r=>(Ut[r]||(Ut[r]=ao(r)),Ut[r]));return rr(...e)}function ao(t){return new k(e=>{const r=M[t];return M[t]=(...n)=>{r.apply(console,n);const s=je("console error");ve(()=>{e.notify(co(n,t,s))})},()=>{M[t]=r}})}function co(t,e,r){const n=t.map(i=>lo(i)).join(" ");let s;if(e===C.error){const i=t.find(Y);s={stack:i?te(N(i)):void 0,fingerprint:Sr(i),causes:i?xr(i,"console"):void 0,startClocks:V(),message:n,source:P.CONSOLE,handling:"handled",handlingStack:r,context:Er(i)}}return{api:e,message:n,error:s,handlingStack:r}}function lo(t){return typeof t=="string"?z(t):Y(t)?br(N(t)):ee(z(t),void 0,2)}function uo(t){const e=Dr(t)==="object";return e||D.error("Unsupported context:",t),e}function Ft(t,e,r){const n={...t};for(const[s,{required:i,type:o}]of Object.entries(e))o==="string"&&s in n&&(n[s]=String(n[s])),i&&!(s in t)&&D.warn(`The property ${s} of ${r} is required; context will not be sent to the intake.`);return n}function Qe(t="",{customerDataTracker:e,propertiesConfig:r={}}={}){let n={};const s=new k,i={getContext:()=>kr(n),setContext:o=>{uo(o)?(n=z(Ft(o,r,t)),e==null||e.updateCustomerData(n)):i.clearContext(),s.notify()},setContextProperty:(o,a)=>{n=z(Ft({...n,[o]:a},r,t)),e==null||e.updateCustomerData(n),s.notify()},removeContextProperty:o=>{delete n[o],e==null||e.updateCustomerData(n),Ft(n,r,t),s.notify()},clearContext:()=>{n={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return i}const ho="_dd_c",fo=[];function Lt(t,e,r,n){const s=po(r,n);fo.push(ne(t,window,"storage",({key:d})=>{s===d&&o()})),e.changeObservable.subscribe(a);const i=ue(c(),e.getContext());be(i)||e.setContext(i);function o(){e.setContext(c())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function c(){const d=localStorage.getItem(s);return d?JSON.parse(d):{}}}function po(t,e){return`${ho}_${t}_${e}`}const mo=3*B,go=16*B,yo=200;function _o(t=2){const e=new Map;let r=!1;function n(s=0){if(r||t===0)return;const i=t===2?mo:go;let o=s;e.forEach(a=>{o+=a.getBytesCount()}),o>i&&(bo(i),r=!0)}return{createDetachedTracker:()=>{const s=qr(()=>n(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,qr(n)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,n())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function qr(t){let e=0;const{throttled:r,cancel:n}=nr(i=>{e=ct(ee(i)),t()},yo),s=()=>{n(),e=0};return{updateCustomerData:i=>{be(i)?s():r(i)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{n()}}}function bo(t){D.warn(`Customer data exceeds the recommended ${t/B}KiB threshold. ${Fe} ${Yt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function vo(t,e,r){const n=t.getReader(),s=[];let i=0;o();function o(){n.read().then(x(c=>{if(c.done){a();return}s.push(c.value),i+=c.value.length,i>r.bytesLimit?a():o()}),x(c=>e(c)))}function a(){n.cancel().catch(W);let c,d;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(i);let u=0;s.forEach(f=>{l.set(f,u),u+=f.length})}c=l.slice(0,r.bytesLimit),d=l.length>r.bytesLimit}e(void 0,c,d)}}const To="datadog-synthetics-public-id",So="datadog-synthetics-result-id",Eo="datadog-synthetics-injects-rum";function Xr(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(Eo))}function xo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(To);return typeof t=="string"?t:void 0}function wo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||J(So);return typeof t=="string"?t:void 0}function et(t,e,r){const n=r.getHandler(),s=Array.isArray(n)?n:[n];return Kr[t]>=Kr[r.getLevel()]&&s.includes(e)}const T={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Kr={[T.ok]:0,[T.debug]:1,[T.info]:2,[T.notice]:4,[T.warn]:5,[T.error]:6,[T.critical]:7,[T.alert]:8,[T.emerg]:9};function tt(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var Ao=function(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i};const Ce={console:"console",http:"http",silent:"silent"},Ro=Object.keys(T);let O=class{constructor(e,r,n,s=Ce.http,i=T.debug,o={}){this.handleLogStrategy=e,this.handlerType=s,this.level=i,this.contextManager=Qe("logger",{customerDataTracker:r}),this.contextManager.setContext(o),n&&this.contextManager.setContextProperty("logger",{name:n})}logImplementation(e,r,n=T.info,s,i){const o=z(r);let a;if(s!=null){const c=Tr({stackTrace:Y(s)?N(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:P.LOGGER,handling:"handled",startClocks:V()});a=ue({error:tt(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:z(e),context:a,status:n},this,i)}log(e,r,n=T.info,s){let i;et(n,Ce.http,this)&&(i=je("log")),this.logImplementation(e,r,n,s,i)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,r){this.contextManager.setContextProperty(e,r)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};Ao([Rn],O.prototype,"logImplementation",null),O.prototype.ok=$(T.ok),O.prototype.debug=$(T.debug),O.prototype.info=$(T.info),O.prototype.notice=$(T.notice),O.prototype.warn=$(T.warn),O.prototype.error=$(T.error),O.prototype.critical=$(T.critical),O.prototype.alert=$(T.alert),O.prototype.emerg=$(T.emerg);function $(t){return function(e,r,n){let s;et(t,Ce.http,this)&&(s=je("log")),this.logImplementation(e,r,t,n,s)}}function Co(t,e,r){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:r.getContext()}}const Do=32*B;function ko(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&D.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Rs(t),r=Jr(t.forwardConsoleLogs,Be(C),"Forward Console Logs"),n=Jr(t.forwardReports,Be(Ye),"Forward Reports");if(!(!e||!r||!n))return t.forwardErrorsToLogs&&!r.includes(C.error)&&r.push(C.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:r,forwardReports:n,requestErrorResponseLengthLimit:Do,...e}}function Jr(t,e,r){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(n=>e.includes(n)))){D.error(`${r} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:hi(t)}function Uo(t){const e=Cs(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Fo(t,e,r){const n=Fr();let s,i;const o=e.observable.subscribe(a);function a(){if(!i||!s||!e.isGranted())return;o.unsubscribe();const c=r(s,i);n.drain(c)}return{init(c){if(!c){D.error("Missing configuration");return}if(Ds(c.enableExperimentalFeatures),Ke()&&(c=Lo(c)),s=c,i){wr("DD_LOGS",c);return}const d=ko(c);d&&(i=d,Yr().subscribe(W),e.tryToInit(d.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:W,handleLog(c,d,l,u=t(),f=G()){n.add(p=>p.handleLog(c,d,l,u,f))}}}function Lo(t){return{...t,clientToken:"empty"}}const Pt="logs";function Po(t){const e=_o(),r=Qe("global context",{customerDataTracker:e.getOrCreateTracker(2)}),n=Qe("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=Qe("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=as();function o(){return Co(r,n,s)}let a=Fo(o,i,(l,u)=>{l.storeContextsAcrossPages&&(Lt(u,r,Pt,2),Lt(u,n,Pt,1),Lt(u,s,Pt,4));const f=t(l,u,o,i);return a=Oo(l,f),f});const c={},d=new O((...l)=>a.handleLog(...l),e.createDetachedTracker());return ni({logger:d,init:x(l=>a.init(l)),setTrackingConsent:x(l=>{i.update(l),Ti({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:x(()=>r.getContext()),setGlobalContext:x(l=>r.setContext(l)),setGlobalContextProperty:x((l,u)=>r.setContextProperty(l,u)),removeGlobalContextProperty:x(l=>r.removeContextProperty(l)),clearGlobalContext:x(()=>r.clearContext()),createLogger:x((l,u={})=>(c[l]=new O((...f)=>a.handleLog(...f),e.createDetachedTracker(),z(l),u.handler,u.level,z(u.context)),c[l])),getLogger:x(l=>c[l]),getInitConfiguration:x(()=>kr(a.initConfiguration)),getInternalContext:x(l=>a.getInternalContext(l)),setUser:x(n.setContext),getUser:x(n.getContext),setUserProperty:x(n.setContextProperty),removeUserProperty:x(n.removeContextProperty),clearUser:x(n.clearContext),setAccount:x(s.setContext),getAccount:x(s.getContext),setAccountProperty:x(s.setContextProperty),removeAccountProperty:x(s.removeContextProperty),clearAccount:x(s.clearContext)})}function Oo(t,e){return{init:r=>{wr("DD_LOGS",r)},initConfiguration:t,...e}}const Io="logs";function Mo(t,e){const r=Di(t,Io,n=>No(t,n),e);return{findTrackedSession:(n,s={returnInactive:!1})=>{const i=r.findSession(n,s);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:r.expireObservable}}function Bo(t){const r=Zr(t)==="1"?{}:void 0;return{findTrackedSession:()=>r,expireObservable:new k}}function Zr(t){return Le(t.sessionSampleRate)?"1":"0"}function No(t,e){const r=zo(e)?e:Zr(t);return{trackingType:r,isTracked:r==="1"}}function zo(t){return t==="0"||t==="1"}let Qr=!1;function rt(t){const e=window;if(Xr()){const n=r(e.DD_RUM_SYNTHETICS);return!n&&!Qr&&(Qr=!0,Pr("Logs sent before RUM is injected by the synthetics worker",{testId:xo(),resultId:wo()})),n}return r(e.DD_RUM);function r(n){if(n&&n.getInternalContext)return n.getInternalContext(t)}}function $o(t,e,r,n,s){const i=Ro.concat(["custom"]),o={};i.forEach(a=>{o[a]=Ji(a,e.eventRateLimiterThreshold,s)}),r.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:d=void 0,domainContext:l})=>{var u,f;const p=Sn(a.date),h=t.findTrackedSession(p);if(!t.findTrackedSession(p,{returnInactive:!0}))return;const g=d||n();let S;!be(g.account)&&g.account.id&&(S=g.account),h&&h.anonymousId&&!g.user.anonymous_id&&(g.user.anonymous_id=h.anonymousId);const b=ue({service:e.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:be(g.user)?void 0:g.user,account:S,view:g.view},g.context,rt(p),a,c);((u=e.beforeSend)===null||u===void 0?void 0:u.call(e,b,l))===!1||b.origin!==P.AGENT&&((f=o[b.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||r.notify(1,b)})}const Go={[C.log]:T.info,[C.debug]:T.debug,[C.info]:T.info,[C.warn]:T.warn,[C.error]:T.error};function Vo(t,e){const r=oo(t.forwardConsoleLogs).subscribe(n=>{var s;const i={rawLogsEvent:{date:G(),message:n.message,origin:P.CONSOLE,error:n.error&&tt(n.error),status:Go[n.api]},messageContext:(s=n.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:n.handlingStack}};e.notify(0,i)});return{stop:()=>{r.unsubscribe()}}}function Ho(t,e){const r=ii(t,t.forwardReports).subscribe(n=>{let s=n.message,i;const o=n.originalError.type==="deprecation"?T.warn:T.error;o===T.error?i=tt(n):n.stack&&(s+=` Found in ${Qs(n.stack)}`),e.notify(0,{rawLogsEvent:{date:G(),message:s,origin:P.REPORT,error:i,status:o}})});return{stop:()=>{r.unsubscribe()}}}function Wo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=Zi(t).subscribe(i=>{i.state==="complete"&&s("xhr",i)}),n=Yr().subscribe(i=>{i.state==="resolve"&&s("fetch",i)});function s(i,o){!ws(o.url)&&(Xo(o)||Ir(o.status))&&("xhr"in o?jo(o.xhr,t,a):o.response?qo(o.response,t,a):o.error&&Yo(o.error,t,a));function a(c){const d={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${Ko(i)} error ${o.method} ${o.url}`,date:o.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:o.method,status_code:o.status,url:o.url},status:T.error,origin:P.NETWORK},domainContext:d})}}return{stop:()=>{r.unsubscribe(),n.unsubscribe()}}}function jo(t,e,r){typeof t.response=="string"?r(Ot(t.response,e)):r(t.response)}function Yo(t,e,r){r(Ot(te(N(t)),e))}function qo(t,e,r){const n=Li(t);!n||!n.body?r():window.TextDecoder?Jo(n.body,e.requestErrorResponseLengthLimit,(s,i)=>{r(s?`Unable to retrieve response: ${s}`:i)}):n.text().then(x(s=>r(Ot(s,e))),x(s=>r(`Unable to retrieve response: ${s}`)))}function Xo(t){return t.status===0&&t.responseType!=="opaque"}function Ot(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function Ko(t){return t==="xhr"?"XHR":"Fetch"}function Jo(t,e,r){vo(t,(n,s,i)=>{if(n)r(n);else{let o=new TextDecoder().decode(s);i&&(o+="..."),r(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function Zo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=new k,{stop:n}=ei(r),s=r.subscribe(i=>{e.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:tt(i),origin:P.SOURCE,status:T.error},messageContext:i.context})});return{stop:()=>{n(),s.unsubscribe()}}}const Qo=Ki;function ea(t){function e(r,n,s,i,o){const a=ue(n.getContext(),r.context);if(et(r.status,Ce.console,n)&&ra(r,a),et(r.status,Ce.http,n)){const c={rawLogsEvent:{date:o||G(),message:r.message,status:r.status,origin:P.LOGGER},messageContext:a,savedCommonContext:i};s&&(c.domainContext={handlingStack:s}),t.notify(0,c)}}return{handleLog:e}}const ta={[T.ok]:C.debug,[T.debug]:C.debug,[T.info]:C.info,[T.notice]:C.info,[T.warn]:C.warn,[T.error]:C.error,[T.critical]:C.error,[T.alert]:C.error,[T.emerg]:C.error};function ra({status:t,message:e},r){X[ta[t]].call(M,e,r)}function na(t,e,r,n,s){const i=jr(t,{endpoint:t.logsEndpointBuilder,encoder:Ze()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);return e.subscribe(1,o=>{i.add(o)}),i}function sa(t){const e=Rt();t.subscribe(1,r=>{e.send("log",r)})}function ia(t){return{get:e=>{const r=t.findTrackedSession(e);if(r)return{session_id:r.id}}}}function oa(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:P.AGENT,status:T.error}}),Pr("Error reported to customer",{"error.message":e.message})}}function aa(t,e,r,n,s){const i=gi("browser-logs-sdk",e);i.setContextProvider(()=>{var a,c,d,l,u,f;return{application:{id:(a=rt())===null||a===void 0?void 0:a.application_id},session:{id:(c=s.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(d=rt())===null||d===void 0?void 0:d.view)===null||l===void 0?void 0:l.id},action:{id:(f=(u=rt())===null||u===void 0?void 0:u.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ke()){const a=Rt(),c=i.observable.subscribe(d=>a.send("internal_telemetry",d));o.push(()=>c.unsubscribe())}else{const a=jr(e,{endpoint:e.rumEndpointBuilder,encoder:Ze()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);o.push(()=>a.stop());const c=i.observable.subscribe(d=>a.add(d,bi(e)));o.push(()=>c.unsubscribe())}return _i(),vi(Uo(t)),{telemetry:i,stop:()=>{o.forEach(a=>a())}}}function ca(t,e,r,n){const s=new Qo,i=[];s.subscribe(1,f=>Cr("logs",f));const o=oa(s),a=ji(e),c=e.sessionStoreStrategyType&&!Ke()&&!Xr()?Mo(e,n):Bo(e),{stop:d}=aa(t,e,o,a,c);i.push(()=>d()),Wo(e,s),Zo(e,s),Vo(e,s),Ho(e,s);const{handleLog:l}=ea(s);if($o(c,e,s,r,o),Ke())sa(s);else{const{stop:f}=na(e,s,o,a,c);i.push(()=>f())}const u=ia(c);return{handleLog:l,getInternalContext:u.get,stop:()=>{i.forEach(f=>f())}}}const fe=Po(ca);si(H(),"DD_LOGS",fe);const y=class y{constructor(e){this.listenerMap=new Map,y.options=e,this.isLoggingOn=e.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const r="bb_logger_mac_uuid";let n=localStorage.getItem(r);n||(n=crypto.randomUUID(),localStorage.setItem(r,n)),y.tracking.mac=n,y.tracking.dev=`${e.platform}_${e.browserName}`,y.beatHandle||(y.options&&_(y.options,"Logger")&&console.log("[Logger] Starting tracking beat"),y.beatHandle=window.setInterval(y.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}addEventListener(e,r){const n=s=>r(s);this.listenerMap.set(r,{eventName:e,wrappedListener:n}),this.eventTarget.addEventListener(e,n)}removeEventListener(e,r){const n=this.listenerMap.get(r);n&&n.eventName===e&&(this.eventTarget.removeEventListener(e,n.wrappedListener),this.listenerMap.delete(r))}removeAllEventListeners(){for(const[e,{eventName:r,wrappedListener:n}]of this.listenerMap)this.eventTarget.removeEventListener(r,n);this.listenerMap.clear()}setAttributes(e){y.processAttributes(e);for(const r in e)fe.logger.setContextProperty(r,e[r])}info(e,r){e==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(r==null?void 0:r.url)||""}),e==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(r==null?void 0:r.isEnabled)||!0}),e==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",r),e==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",r),e==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",r),r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.info(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending info: ",e))}error(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.error(e,r),y.tracking.err_time=Date.now().toFixed(0),y.tracking.err_desc=e+(r?` - ${JSON.stringify(r)}`:""),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending error: ",e))}warn(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.warn(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){if(!y.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{y.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}catch(r){console.error("[Logger] Error posting message:",r)}}static info(e,r){y.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:r})}static error(e,r){y.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:r})}static warn(e,r){y.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:r})}static processAttributes(e){if(e.player_version&&(y.tracking.sdk=e.player_version),e.media_id&&(y.tracking.gid=e.media_id),e.game_id&&(y.tracking.buc=e.game_id),e.bb_session_id&&(y.tracking.sid=e.bb_session_id,y.options&&_(y.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",y.tracking.sid)),e.last_timecode){const n=L.fromStr(e.last_timecode);y.tracking.tc=n.print(),y.lastTimecodeMillis=n.totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))}e.last_offset&&(y.tracking.off=e.last_offset),e.last_loading_zip&&(y.tracking.zip=e.last_loading_zip+".zip",y.lastZipMillis=L.fromStr(e.last_loading_zip).totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(y.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(y.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([r,n])=>n!==0&&n!=="").map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`).join("&")}emit(e,r){const n=new CustomEvent(e,{detail:r});this.eventTarget.dispatchEvent(n)}};y.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},y.lastTimecodeMillis=0,y.lastZipMillis=0,y.flushTracking=()=>{const e=Date.now().toFixed(0);y.tracking.now=e;const n=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${y.objectToQuery(y.tracking)}`;y.options&&_(y.options,"Logger")&&console.log("[Logger] Flushing tracking data:",n),fetch(n,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),y.tracking.err_desc="",y.tracking.err_time=""};let It=y;const la={env:"prod",urlConfigURL:"https://db8igqxlbvayn.cloudfront.net/url_config.json",gameBaseURL:"https://db8igqxlbvayn.cloudfront.net",zipBaseURL:"https://db8igqxlbvayn.cloudfront.net",adsBaseURL:"https://dwu3k7rrxk5s3.cloudfront.net",LOG_TO_DATADOG:!0,SEND_METRICS:!0,BURNED_TIMECODES_MODE:!1,RENDER_LED:!0,DRAW_TIMESTAMP_WEBGL:!1,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:10,DOWNLOADER_ZIP_LENGTH_SECONDS:2,ZIP_BUFFER_READY_THRESHOLD:5,ZIP_BUFFER_FADEOUT_THRESHOLD:1,BENCHMARK_DURATION_SECONDS:10,DECODER_UPDATE_FREQUENCY:30,DECODER_FRAME_BATCH_SIZE:3,DECODER_LEAD_TIME_MILLIS:180,PERFORMANCE_TRACKING_INTERVAL:1e3,BUCKET_SUBFOLDER_PATH:"manifests/59.94/",debug:{on:!1,showAugmentationStatus:!1,logOTTPlayer:!1,logClocker:!1,logDownloader:!1,logDecoder:!1,logRenderer:!1,logFetcher:!1,logAdapter:!1,logAds:!1,logLogger:!1,logErrors:!1,trackPerformance:!1}},da="https://identity-qa.nba.com/qa/auth";class ua{constructor(e){this.cookies=[],this.xToken=null,this.authInProgress=!1,this.OTTPlayer=e,this.options=e.options,this.logger=e.logger}async fetchNBAToken(e,r){const n=this.options.authIdentityUrl||da;_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Fetching JWT from: ${n}`);const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r})});if(!s.ok){const o=await s.text().catch(()=>"");throw new Error(`NBA auth request failed: ${s.status} ${s.statusText} - ${o}`)}const i=await s.json().catch(()=>null);if(!i||!i.data||!i.data.jwt)throw new Error("NBA auth response was invalid or missing JWT token");return i.data.jwt}async loginAndGetCookies(e){try{const r=this.options.authNbaToken,n=this.options.authEmail,s=this.options.authPassword;if(!r&&(!n||!s))return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] No credentials or NBA token provided, skipping authentication"),[];const i=this.options.zipBaseURL;if(!i)return console.warn("[CloudFrontAuth] No zipBaseURL configured, cannot authenticate"),[];if(this.lastGameId===e&&this.cookies.length>0)return _(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] ✓ Using cached cookies for gameId=${e}`),this.cookies;if(this.authInProgress)return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ⏳ Auth already in progress, waiting..."),await this.waitForAuth(),this.cookies;this.authInProgress=!0,this.lastGameId=e,console.log(`[CloudFrontAuth] 🔐 Starting authentication for gameId=${e}`),console.log(`[CloudFrontAuth] CloudFront URL: ${i}`);let o;r?(o=r,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using provided NBA token")):this.xToken?(o=this.xToken,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using existing x-token")):(o=await this.fetchNBAToken(n,s),_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Got JWT token from NBA Identity"));const a=`${i}/auth/${encodeURIComponent(e)}`;console.log(`[CloudFrontAuth] Fetching cookies from: ${a}`);const c=await fetch(a,{method:"GET",credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(!c.ok&&c.status!==204)throw new Error(`Failed to fetch cookies: ${c.status} ${c.statusText}`);_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auth endpoint status: ${c.status}`);const d=c.headers.get("x-token");d&&(this.xToken=d,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Received fresh x-token"));const l=c.headers.get("set-cookie");return l?this.cookies=l.split(",").map(u=>u.trim()):this.cookies=["browser-managed-httponly-cookies"],console.log("[CloudFrontAuth] ✅ Successfully authenticated"),console.log("[CloudFrontAuth] Note: Cookies are HttpOnly and managed by browser automatically"),this.logger.info("didAuthenticateCloudFront",{gameId:e,cookieCount:this.cookies.length,hasXToken:!!this.xToken}),this.scheduleCookieRefresh(e),this.cookies}catch(r){return console.error("[CloudFrontAuth] ❌ Authentication failed:",r),this.logger.error("[CloudFrontAuth] Authentication failed",{error:r.message||r}),this.xToken=null,[]}finally{this.authInProgress=!1}}async waitForAuth(){return new Promise(e=>{const r=setInterval(()=>{this.authInProgress||(clearInterval(r),e())},100)})}scheduleCookieRefresh(e){this.cookieRefreshTimer&&window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=window.setTimeout(()=>{_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auto-refreshing cookies and x-token for gameId=${e}`),this.loginAndGetCookies(e)},7*60*60*1e3)}getCookies(){return this.cookies}getXToken(){return this.xToken}isAuthenticated(){return this.cookies.length>0}destroy(){this.cookies=[],this.xToken=null,this.lastGameId=void 0,this.cookieRefreshTimer&&(window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=void 0)}}class ha{constructor(e){this.groups=new Map,this.isVisible=!0,this.lastFrameTime=0,this.TARGET_FPS=60,this.FRAME_INTERVAL=1e3/this.TARGET_FPS,this.canvas=document.createElement("canvas"),this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0",this.canvas.style.pointerEvents="none",this.canvas.style.zIndex="3001",this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight,this.canvas.style.width="100%",this.canvas.style.height="100%",this.ctx=this.canvas.getContext("2d"),e.appendChild(this.canvas),this.initializeGroups(),this.startRenderLoop(),this.setupResizeObserver(e)}initializeGroups(){this.groups.set("support",{title:"Basic Augmentation Support",metrics:new Map([["game_params",{value:!1}],["browser",{value:!1,detail:""}],["pattern",{value:!1,detail:""}],["fps",{value:!1,detail:""}],["mk_ads",{value:!1,detail:""}]])}),this.groups.set("timecode",{title:"TimeCode Status",metrics:new Map([["sync_point",{value:!1,detail:""}],["consistency",{value:!1,detail:""}]])}),this.groups.set("benchmark",{title:"",metrics:new Map([["status",{value:"FAILED",detail:""}]])}),this.groups.set("switches",{title:"Augmentation Switches",metrics:new Map([["killswitch_web",{value:!1}],["killswitch_local",{value:!1}],["isLive",{value:!1}],["render_state",{value:"OFF"}]])}),this.groups.set("data",{title:"Augmentation Data Presence",metrics:new Map([["zip_buffer",{value:!1,detail:"0.0s"}],["stream_data",{value:!1}],["ads",{value:!1}],["render_data",{value:!1}],["alpha_mask",{value:!1}],["placeholders",{value:!1}],["processing_size",{value:!1}]])}),this.groups.set("health",{title:"Player Components Health",metrics:new Map([["decoder",{value:!1,detail:""}],["webgl",{value:!1,detail:""}]])})}updateMetric(e,r,n,s){const i=this.groups.get(e);i&&i.metrics.set(r,{value:n,detail:s})}startRenderLoop(){const e=r=>{r-this.lastFrameTime>=this.FRAME_INTERVAL&&(this.isVisible&&this.draw(),this.lastFrameTime=r),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}setupResizeObserver(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight}),this.resizeObserver.observe(e))}draw(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);const e=12,r=e+3,n=10,s=15,i=10;this.ctx.font=`${e}px monospace`,this.ctx.textBaseline="top";let o=i;this.groups.forEach((c,d)=>{var l;if(d==="benchmark"){const u=c.metrics.get("status");if(u){const f=u.value;let p,h;f==="PASSED"?(p="rgba(0,255,136,0.8)",h="STABILITY TEST: PASSED"):f==="TESTING"?(p="rgba(255,170,0,0.8)",h=`STABILITY TEST: TESTING${u.detail?" ("+((l=u.detail.split(":")[1])==null?void 0:l.trim())+")":""}`):(p="rgba(255,51,51,0.8)",h="STABILITY TEST: FAILED"),this.ctx.fillStyle=p,this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(h,i+5,o+4),this.ctx.font=`${e}px monospace`,o+=25}return}this.ctx.fillStyle="rgba(0,0,0,0.7)",this.ctx.fillRect(i,o,300,r+2),this.ctx.fillStyle="#fff",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(c.title,i+5,o+1),this.ctx.font=`${e}px monospace`,o+=r+4,c.metrics.forEach((u,f)=>{const p=this.getColorForValue(u.value),h=this.formatValue(u.value);this.ctx.fillStyle="rgba(0,0,0,0.5)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle=p,this.ctx.beginPath(),this.ctx.arc(i+s+5,o+r/2,3,0,Math.PI*2),this.ctx.fill(),this.ctx.fillStyle="#fff";const m=f.replace(/_/g," ");this.ctx.fillText(`${m}: ${h}`,i+s+15,o+1),o+=r,u.detail&&(this.ctx.fillStyle="rgba(0,0,0,0.4)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle="#aaa",this.ctx.fillText(` ${u.detail}`,i+s+15,o+1),o+=r)}),o+=n});const a=this.isAugmentationReady();this.ctx.fillStyle=a?"rgba(0,255,136,0.8)":"rgba(255,51,51,0.8)",this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(`AUGMENTATION: ${a?"READY":"NOT READY"}`,i+5,o+4),this.ctx.font=`${e}px monospace`}formatValue(e){return typeof e=="boolean"?e?"OK":"NO":e==="PASSED"?"PASSED":e==="TESTING"?"TESTING":e==="FAILED"?"FAILED":e}getColorForValue(e){return typeof e=="boolean"?e?"#00ff88":"#ff3333":e==="ON"||e==="FADE_IN"?"#00ff88":e==="FADE_OUT"?"#ffaa00":e==="PASSED"?"#00ff88":e==="TESTING"?"#ffaa00":"#ff3333"}isAugmentationReady(){var u,f,p,h,m,g,S,b,E,A;const e=this.groups.get("support"),r=this.groups.get("switches"),n=this.groups.get("data"),s=this.groups.get("health"),i=this.groups.get("benchmark");if(!e||!r||!n||!s||!i)return!1;const o=((u=e.metrics.get("game_params"))==null?void 0:u.value)===!0&&((f=e.metrics.get("browser"))==null?void 0:f.value)===!0&&((p=e.metrics.get("pattern"))==null?void 0:p.value)===!0&&((h=e.metrics.get("fps"))==null?void 0:h.value)===!0&&((m=e.metrics.get("mk_ads"))==null?void 0:m.value)===!0,a=((g=r.metrics.get("killswitch_web"))==null?void 0:g.value)===!0&&((S=r.metrics.get("killswitch_local"))==null?void 0:S.value)===!0&&(((b=r.metrics.get("render_state"))==null?void 0:b.value)==="ON"||((E=r.metrics.get("render_state"))==null?void 0:E.value)==="FADE_IN"),c=Array.from(n.metrics.values()).every(w=>w.value===!0),d=Array.from(s.metrics.values()).every(w=>w.value===!0),l=((A=i.metrics.get("status"))==null?void 0:A.value)==="PASSED";return o&&a&&c&&d&&l}toggle(){this.isVisible=!this.isVisible,this.isVisible||this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}pause(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}resume(){this.animationFrameId||this.startRenderLoop()}delete(){this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.resizeObserver&&this.resizeObserver.disconnect(),this.canvas.remove()}}class en{constructor(e,r,n,s){this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.handleVisibilityChange=()=>{document.hidden?this.onTabHidden():this.onTabVisible()},this.fetchGameParams=async()=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId),this.options.OVERRIDE_GAME_PARAMS){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Using OVERRIDE_GAME_PARAMS from configuration");const d=this.options.OVERRIDE_GAME_PARAMS;if(this.options.BURNED_TIMECODES_MODE){this.gameParams=d;return}if(d.hasOwnProperty("bucketName")&&d.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:d.bucketName,customer_name:d.customerName,customer_id:d.customerId}),this.gameParams){const l=JSON.stringify(this.gameParams),u=JSON.stringify(d);l!==u&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:d})}else this.logger.info("didFetchGameInfo",d);this.gameParams=d,this.cloudFrontAuth&&d.bucketName&&this.cloudFrontAuth.loginAndGetCookies(d.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",d.bucketName)}).catch(l=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",l)});return}else throw new Error(`OVERRIDE_GAME_PARAMS for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}let o;const a=`${this.options.gameBaseURL}/${this.options.gameId}.json`;if(_(this.options,"OTTPlayer")&&console.log(`Fetching GameParams from ${a}`),this.options.SEND_METRICS?o=await fetch(a,{headers:{"X-Platform":"Web"},cache:"no-store"}):o=await fetch(a,{cache:"no-store"}),!o.ok){const d=`Unable to fetch game params for ${this.options.gameId}. HTTP error. Status: ${o.status}`;this.logger.error("[OTTPlayer] Failed to fetch game params",{status:o.status,gameId:this.options.gameId}),_(this.options,"Errors")&&console.error(`[OTTPlayer] ${d}`),this.destroy();return}const c=await o.json();if(this.options.BURNED_TIMECODES_MODE){this.gameParams=c;return}if(this.handleOttActions(o,c),c.hasOwnProperty("bucketName")&&c.hasOwnProperty("offsets"))o=c;else throw new Error(`Game params for ${this.options.gameId} not found in JSON`);if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const d=JSON.stringify(this.gameParams),l=JSON.stringify(o);d!==l&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",this.gameParams);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(d=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",d)})}catch(o){this.logger.error("[OTTPlayer] Error fetching game params",{error:o}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",o)}this.fetchGameParamsTimeoutId=window.setTimeout(()=>this.fetchGameParams(),1e4)},this.setGameParams=o=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Overriding game params"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),this.options.BURNED_TIMECODES_MODE){this.gameParams=o;return}if(o.hasOwnProperty("bucketName")&&o.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const a=JSON.stringify(this.gameParams),c=JSON.stringify(o);a!==c&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",o);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(a=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",a)});return}else throw new Error(`Game params for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}catch(a){this.logger.error("[OTTPlayer] Error overriding game params",{error:a}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error overriding game params:",a)}};const i="OTTPlayer_v1.1.0";console.log(`%c${i}`,"font-size: 16px; font-weight: bold; color: blue;"),this.video=e,this.options={...n,...la,platform:I.getCurrentPlatform(),browserName:I.getBrowserName(),augmentation:{channelName:"nba"}},this.options.browserName==="Firefox"&&(this.options.DECODER_LEAD_TIME_MILLIS=300),_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Starting fetchUrlConfig"),this.fetchUrlConfig(s),this.logger=new It(this.options),this.logger.setAttributes({player_version:i,bb_session_id:crypto.randomUUID()}),this.logger.info("didGetConfiguration",{...n,fps:r}),tn(this.options,s).then(()=>{var o;if(this.logger.setAttributes({media_id:this.options.gameId}),window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(a=>{a.destroy()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(a=>{a.terminate()}),this.cloudFrontAuth=new ua(this),this.clocker=new dn(this),this.adapter=new it(this),this.ottActions={toggle:{ios:!0,android:!0,web:!0,local:this.options.enabled}},(o=this.options.debug)!=null&&o.showAugmentationStatus){const a=this.options.CANVAS_CONTAINER||this.video.parentElement;a&&(this.statusOverlay=new ha(a))}this.RUN_PIXEL_TICKERS&&(this.pixelTickers=q.createInAllCorners(this.video)),this.applyImageOverridesFromOptions(),this.flushPendingOverrides(),this.fetchGameParams(),window.BB.playerInstances.push(this),document.addEventListener("visibilitychange",this.handleVisibilityChange)})}onNewMetadata(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewMetadata(e)}onNewSegment(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewSegmentForMetadata(e)}onAdEvent(e){console.log(`[OTTPlayer] onAdEvent: ${e}`),!(!this.adapter||this.options.BURNED_TIMECODES_MODE)&&this.adapter.onAdEvent(e)}async fetchUrlConfig(e){try{if(!this.options.urlConfigURL){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] No urlConfigURL provided, skipping URL config fetch");return}_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Fetching URL config from:",this.options.urlConfigURL);const r=await fetch(this.options.urlConfigURL);if(!r.ok)throw new Error(`Failed to fetch URL config: ${r.status} ${r.statusText}`);const n=await r.json();if(!n||typeof n!="object")throw new Error("Invalid URL config structure: not an object");const s=this.options.env;if(!n[s])throw new Error(`Environment '${s}' not found in URL config`);const i=n[s];if(!i.gameBaseUrl||!i.zipBaseUrl||!i.adsBaseUrl)throw new Error(`Missing required URLs in environment '${s}' config`);e!=null&&e.gameBaseURL||(this.options.gameBaseURL=i.gameBaseUrl),e!=null&&e.zipBaseURL||(this.options.zipBaseURL=i.zipBaseUrl),e!=null&&e.adsBaseURL||(this.options.adsBaseURL=i.adsBaseUrl),_(this.options,"OTTPlayer")&&(console.log("[OTTPlayer] URL config loaded successfully for environment:",s),console.log("[OTTPlayer] Updated URLs:",{gameBaseURL:this.options.gameBaseURL,zipBaseURL:this.options.zipBaseURL,adsBaseURL:this.options.adsBaseURL}))}catch(r){_(this.options,"OTTPlayer")&&(console.warn("[OTTPlayer] Failed to fetch URL config:",r),console.log("[OTTPlayer] Using default URLs from options"))}}handleOttActions(e,r){if(!this.clocker||this.options.BURNED_TIMECODES_MODE)return;const n=e.headers.get("x-tgi-ott-actions");let s;if(n?s=JSON.parse(n):s={toggle:{ios:!0,android:!0,web:!0}},!this.ottActions||this.ottActions.toggle.web!==s.toggle.web||s.toggle[r.customerId]!==void 0&&(this.ottActions.toggle[r.customerId]===void 0||this.ottActions.toggle[r.customerId]!==s.toggle[r.customerId])||s.toggle[r.customerId]===void 0&&this.ottActions.toggle[r.customerId]!==void 0){const o=s.toggle[r.customerId]!==void 0?s.toggle[r.customerId]&&s.toggle.web:s.toggle.web;this.ottActions&&this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:o}),s.toggle.local=this.options.enabled,this.ottActions=s,console.warn("[OTTPlayer] ottActions",s)}}toggle(e){this.options.enabled=e,this.ottActions&&(this.ottActions.toggle.local=e,this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:e}))}setFps(e){this.fps=e}setMediaInfo(e){e.fps&&this.setFps(e.fps),e.bitrate&&(this.bitrate=e.bitrate)}setAd(e,r){if(typeof e=="string"){let n;try{n=new URL(e,document.baseURI).toString()}catch(s){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid ad URL passed to setAd",e,s);return}fetch(n,{cache:"no-store"}).then(s=>s.blob()).then(async s=>{if(!this.clocker){this.pendingAdBlob=s,this.pendingAdPlaceholder=r;return}this.clocker.setAdBlob(s,r)}).catch(s=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch ad image from URL in setAd",n,s)});return}if(!this.clocker){if(e instanceof Blob)this.pendingAdBlob=e;else{if(this.pendingAdBitmap)try{this.pendingAdBitmap.close()}catch{}this.pendingAdBitmap=e}this.pendingAdPlaceholder=r;return}if(e instanceof Blob){this.clocker.setAdBlob(e,r);return}else this.clocker.setAdImage(e,r)}setLED(e){if(typeof e=="string"){let r;try{r=new URL(e,document.baseURI).toString()}catch(n){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid LED URL passed to setLED",e,n);return}fetch(r,{cache:"no-store"}).then(n=>n.blob()).then(n=>{if(!this.clocker){this.pendingLEDBlob=n;return}this.clocker.setLEDBlob(n)}).catch(n=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch LED image from URL in setLED",r,n)});return}if(!this.clocker){if(e instanceof Blob)this.pendingLEDBlob=e;else{if(this.pendingLEDBitmap)try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=e}return}e instanceof Blob?this.clocker.setLEDBlob(e):this.clocker.setLEDImage(e)}async applyImageOverridesFromOptions(){try{const e=[];this.options.OVERRIDE_AD&&e.push(this.applySingleOverride(this.options.OVERRIDE_AD,"ad")),this.options.OVERRIDE_LED&&e.push(this.applySingleOverride(this.options.OVERRIDE_LED,"led")),await Promise.all(e)}catch(e){_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to apply image overrides",e)}}async applySingleOverride(e,r){let n;if(typeof e=="string")try{const s=new URL(e,document.baseURI).toString();n=await(await fetch(s,{cache:"no-store"})).blob()}catch(s){_(this.options,"Errors")&&console.error(`[OTTPlayer] Failed to fetch override ${r} from URL`,e,s);return}else n=e;if(n){if(!this.clocker){r==="ad"?this.pendingAdBlob=n:this.pendingLEDBlob=n;return}r==="ad"?this.clocker.setAdBlob(n):this.clocker.setLEDBlob(n)}}flushPendingOverrides(){if(this.clocker){if(this.pendingAdBitmap){const e=this.pendingAdBitmap;this.pendingAdBitmap=void 0,this.clocker.setAdImage(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}else if(this.pendingAdBlob){const e=this.pendingAdBlob;this.pendingAdBlob=void 0,this.clocker.setAdBlob(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}if(this.pendingLEDBitmap){const e=this.pendingLEDBitmap;this.pendingLEDBitmap=void 0,this.clocker.setLEDImage(e)}else if(this.pendingLEDBlob){const e=this.pendingLEDBlob;this.pendingLEDBlob=void 0,this.clocker.setLEDBlob(e)}}}onTabHidden(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab hidden - pausing all components"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(e=this.clocker)==null||e.pause(),(r=this.adapter)==null||r.pause(),(n=this.statusOverlay)==null||n.pause()}onTabVisible(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab visible - resuming all components"),(e=this.clocker)==null||e.resume(),(r=this.adapter)==null||r.resume(),(n=this.statusOverlay)==null||n.resume(),this.fetchGameParams()}on(e,r){this.logger.addEventListener(e,r)}off(e,r){this.logger.removeEventListener(e,r)}destroy(){var r;document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(r=this.clocker)==null||r.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),this.cloudFrontAuth&&(this.cloudFrontAuth.destroy(),this.cloudFrontAuth=void 0),this.statusOverlay&&(this.statusOverlay.delete(),this.statusOverlay=void 0),q.deleteAll(this.pixelTickers),this.pixelTickers=[],this.logger.removeAllEventListeners();const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:en,playerInstances:[],workerInstances:[]},en});
|