@codenkay/video-nsgplayer-core 5.2.0 → 5.3.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/CHANGELOG.md +12 -0
- package/README.md +2 -0
- package/dist/index.cjs +583 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +306 -4
- package/dist/index.d.ts +306 -4
- package/dist/index.js +568 -21
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -12,9 +12,13 @@ var PlayerErrorCode = /* @__PURE__ */ ((PlayerErrorCode2) => {
|
|
|
12
12
|
PlayerErrorCode2["PLAYBACK_ERROR"] = "PLAYBACK_ERROR";
|
|
13
13
|
PlayerErrorCode2["UNSUPPORTED_BROWSER"] = "UNSUPPORTED_BROWSER";
|
|
14
14
|
PlayerErrorCode2["AUTOPLAY_BLOCKED"] = "AUTOPLAY_BLOCKED";
|
|
15
|
+
PlayerErrorCode2["PLATFORM_IN_USE"] = "PLATFORM_IN_USE";
|
|
16
|
+
PlayerErrorCode2["PLAYBACK_NOT_READY"] = "PLAYBACK_NOT_READY";
|
|
15
17
|
PlayerErrorCode2["UNKNOWN"] = "UNKNOWN";
|
|
16
18
|
return PlayerErrorCode2;
|
|
17
19
|
})(PlayerErrorCode || {});
|
|
20
|
+
var PLATFORM_IN_USE = "PLATFORM_IN_USE";
|
|
21
|
+
var PLAYBACK_NOT_READY = "PLAYBACK_NOT_READY";
|
|
18
22
|
function createPlayerError(code, message, options) {
|
|
19
23
|
return {
|
|
20
24
|
code,
|
|
@@ -147,7 +151,7 @@ var AuthManager = class {
|
|
|
147
151
|
// src/config/defaults.ts
|
|
148
152
|
var PLAYBACK_RATES = [0.5, 0.75, 1, 1.25, 1.5, 2];
|
|
149
153
|
var DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS = 45e3;
|
|
150
|
-
var PACKAGE_VERSION = "5.
|
|
154
|
+
var PACKAGE_VERSION = "5.3.0";
|
|
151
155
|
var DEFAULT_PLAYER_BEHAVIOR = {
|
|
152
156
|
autoplay: true,
|
|
153
157
|
startMuted: true,
|
|
@@ -249,7 +253,8 @@ var SKIP_DEEP_SCAN_KEYS = /* @__PURE__ */ new Set([
|
|
|
249
253
|
"refreshsource",
|
|
250
254
|
"keyproxyurlbuilder",
|
|
251
255
|
"mediaproxyurlbuilder",
|
|
252
|
-
"getkeyaccesstoken"
|
|
256
|
+
"getkeyaccesstoken",
|
|
257
|
+
"onnativeauthupdate"
|
|
253
258
|
]);
|
|
254
259
|
var SECRET_SCAN_MAX_DEPTH = 32;
|
|
255
260
|
function isPlainObject(value) {
|
|
@@ -336,7 +341,10 @@ function mergePlayerConfig(partial) {
|
|
|
336
341
|
mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder,
|
|
337
342
|
keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder,
|
|
338
343
|
getKeyAccessToken: partial?.streaming?.getKeyAccessToken,
|
|
339
|
-
keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures
|
|
344
|
+
keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures,
|
|
345
|
+
useAppexHlsProfile: partial?.streaming?.useAppexHlsProfile,
|
|
346
|
+
nativeSessionMode: partial?.streaming?.nativeSessionMode,
|
|
347
|
+
onNativeAuthUpdate: partial?.streaming?.onNativeAuthUpdate
|
|
340
348
|
},
|
|
341
349
|
logging: { ...DEFAULT_PLAYER_CONFIG.logging, ...partial?.logging },
|
|
342
350
|
debug: { ...DEFAULT_PLAYER_CONFIG.debug, ...partial?.debug },
|
|
@@ -811,6 +819,26 @@ function isSameOriginHttpUrl(value, baseOrigin) {
|
|
|
811
819
|
}
|
|
812
820
|
}
|
|
813
821
|
|
|
822
|
+
// src/config/hlsProfiles.ts
|
|
823
|
+
function hlsConfig(isLive = false) {
|
|
824
|
+
return {
|
|
825
|
+
maxBufferLength: isLive ? 24 : 60,
|
|
826
|
+
maxMaxBufferLength: isLive ? 40 : 120,
|
|
827
|
+
maxBufferSize: 32 * 1024 * 1024,
|
|
828
|
+
backBufferLength: 30,
|
|
829
|
+
startLevel: 0,
|
|
830
|
+
abrEwmaDefaultEstimate: 5e5,
|
|
831
|
+
abrBandWidthFactor: 0.7,
|
|
832
|
+
abrBandWidthUpFactor: 0.55,
|
|
833
|
+
maxStarvationDelay: 2,
|
|
834
|
+
lowLatencyMode: false,
|
|
835
|
+
liveSyncDurationCount: 4,
|
|
836
|
+
liveMaxLatencyDurationCount: 8,
|
|
837
|
+
maxLiveSyncPlaybackRate: 1.1
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
var appexHlsConfig = hlsConfig;
|
|
841
|
+
|
|
814
842
|
// src/streaming/authParamsLoader.ts
|
|
815
843
|
var ENC_KEY_PATH_RE = /enc\.key$/i;
|
|
816
844
|
var BUILTIN_LOADER_NAMES = /* @__PURE__ */ new Set(["XhrLoader", "FetchLoader"]);
|
|
@@ -1360,7 +1388,7 @@ var HlsEngine = class {
|
|
|
1360
1388
|
const {
|
|
1361
1389
|
videoEl,
|
|
1362
1390
|
authParams,
|
|
1363
|
-
hlsConfig,
|
|
1391
|
+
hlsConfig: hlsConfig2,
|
|
1364
1392
|
callbacks,
|
|
1365
1393
|
videoId,
|
|
1366
1394
|
keyProxyUrlBuilder,
|
|
@@ -1373,8 +1401,8 @@ var HlsEngine = class {
|
|
|
1373
1401
|
getKeyAccessToken,
|
|
1374
1402
|
keyProxyMaxFailures: this.options.keyProxyMaxFailures
|
|
1375
1403
|
});
|
|
1376
|
-
const enableWorker =
|
|
1377
|
-
if (
|
|
1404
|
+
const enableWorker = hlsConfig2.enableWorker && !isGeckoBrowser();
|
|
1405
|
+
if (hlsConfig2.enableWorker && !enableWorker) {
|
|
1378
1406
|
this.options.logger.warn(
|
|
1379
1407
|
"Disabling hls.js worker on Firefox to avoid MSE bufferAppendError"
|
|
1380
1408
|
);
|
|
@@ -1383,17 +1411,19 @@ var HlsEngine = class {
|
|
|
1383
1411
|
this.hls = new Hls({
|
|
1384
1412
|
enableWorker,
|
|
1385
1413
|
// LL mode on short encrypted VOD drives aggressive ABR thrash → MSE errors.
|
|
1386
|
-
lowLatencyMode:
|
|
1387
|
-
backBufferLength:
|
|
1388
|
-
maxBufferLength:
|
|
1389
|
-
maxMaxBufferLength:
|
|
1390
|
-
maxBufferSize:
|
|
1414
|
+
lowLatencyMode: hlsConfig2.lowLatencyMode,
|
|
1415
|
+
backBufferLength: hlsConfig2.backBufferLength,
|
|
1416
|
+
maxBufferLength: hlsConfig2.maxBufferLength,
|
|
1417
|
+
maxMaxBufferLength: hlsConfig2.maxMaxBufferLength,
|
|
1418
|
+
maxBufferSize: hlsConfig2.maxBufferSize,
|
|
1391
1419
|
startPosition: typeof startPosition === "number" && startPosition > 0 ? startPosition : -1,
|
|
1392
1420
|
// A first-fragment bandwidth probe on short encrypted VODs truncates
|
|
1393
1421
|
// the body and immediately hops levels. ABR itself stays on hls.js
|
|
1394
1422
|
// defaults so a long VOD is not held on the lowest rung.
|
|
1395
1423
|
testBandwidth: false,
|
|
1396
1424
|
startLevel: -1,
|
|
1425
|
+
// Opt-in Appextech profile (buffers, ABR, live sync). Wins for its keys.
|
|
1426
|
+
...this.options.useAppexHlsProfile ? appexHlsConfig(Boolean(this.options.isLive)) : {},
|
|
1397
1427
|
loader
|
|
1398
1428
|
});
|
|
1399
1429
|
this.hls.attachMedia(videoEl);
|
|
@@ -1432,7 +1462,7 @@ var HlsEngine = class {
|
|
|
1432
1462
|
}
|
|
1433
1463
|
handleHlsError(Hls, data) {
|
|
1434
1464
|
if (this.destroyed) return;
|
|
1435
|
-
const { callbacks, hlsConfig } = this.options;
|
|
1465
|
+
const { callbacks, hlsConfig: hlsConfig2 } = this.options;
|
|
1436
1466
|
const status = data.response?.code;
|
|
1437
1467
|
const authFailure = isAuthHttpStatus(status);
|
|
1438
1468
|
if (data.details === Hls.ErrorDetails.KEY_LOAD_ERROR) {
|
|
@@ -1464,7 +1494,7 @@ var HlsEngine = class {
|
|
|
1464
1494
|
}
|
|
1465
1495
|
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
|
|
1466
1496
|
this.networkRecoveryCount += 1;
|
|
1467
|
-
if (this.networkRecoveryCount <=
|
|
1497
|
+
if (this.networkRecoveryCount <= hlsConfig2.fatalRecoveryLimit) {
|
|
1468
1498
|
if (authFailure) {
|
|
1469
1499
|
callbacks.onAuthRecoveryNeeded?.("fatal_network");
|
|
1470
1500
|
}
|
|
@@ -1474,7 +1504,7 @@ var HlsEngine = class {
|
|
|
1474
1504
|
}
|
|
1475
1505
|
if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
|
|
1476
1506
|
this.mediaRecoveryCount += 1;
|
|
1477
|
-
if (this.mediaRecoveryCount >
|
|
1507
|
+
if (this.mediaRecoveryCount > hlsConfig2.fatalRecoveryLimit) {
|
|
1478
1508
|
callbacks.onFatalError?.(data.details || "Fatal HLS error");
|
|
1479
1509
|
return;
|
|
1480
1510
|
}
|
|
@@ -1572,12 +1602,43 @@ var HlsEngine = class {
|
|
|
1572
1602
|
});
|
|
1573
1603
|
}
|
|
1574
1604
|
updateAuthParams() {
|
|
1575
|
-
if (this.supportMode
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1605
|
+
if (this.supportMode !== "native" || !this.options.videoEl) return;
|
|
1606
|
+
if (this.options.nativeSessionMode) {
|
|
1607
|
+
void this.updateNativeAuthParams(this.options.authParams.toRecord());
|
|
1608
|
+
return;
|
|
1609
|
+
}
|
|
1610
|
+
const time = this.options.videoEl.currentTime;
|
|
1611
|
+
const wasPaused = this.options.videoEl.paused;
|
|
1612
|
+
this.options.videoEl.src = this.playbackRequestUrl(this.options.playbackUrl);
|
|
1613
|
+
this.options.videoEl.currentTime = time;
|
|
1614
|
+
if (!wasPaused) void this.options.videoEl.play();
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Native HLS: apply new auth parameters without replacing `video.src`.
|
|
1618
|
+
*
|
|
1619
|
+
* With `nativeSessionMode`, `onNativeAuthUpdate` receives the params and the
|
|
1620
|
+
* current request URL so the BFF session/cookie can be renewed; the element
|
|
1621
|
+
* keeps playing. Without it this method is a no-op unless a callback exists,
|
|
1622
|
+
* because rewriting `video.src` would restart the stream (use
|
|
1623
|
+
* `updateAuthParams()` for that reload path).
|
|
1624
|
+
*
|
|
1625
|
+
* Returns true when a callback handled the update.
|
|
1626
|
+
*/
|
|
1627
|
+
async updateNativeAuthParams(params) {
|
|
1628
|
+
if (this.destroyed || this.supportMode !== "native") return false;
|
|
1629
|
+
const callback = this.options.onNativeAuthUpdate;
|
|
1630
|
+
if (!callback) return false;
|
|
1631
|
+
try {
|
|
1632
|
+
await callback({
|
|
1633
|
+
params,
|
|
1634
|
+
url: this.playbackRequestUrl(this.options.playbackUrl)
|
|
1635
|
+
});
|
|
1636
|
+
return true;
|
|
1637
|
+
} catch (error) {
|
|
1638
|
+
this.options.logger.warn(
|
|
1639
|
+
error instanceof Error ? `Native auth update failed: ${error.message}` : "Native auth update failed"
|
|
1640
|
+
);
|
|
1641
|
+
return false;
|
|
1581
1642
|
}
|
|
1582
1643
|
}
|
|
1583
1644
|
playbackRequestUrl(playbackUrl) {
|
|
@@ -1898,6 +1959,10 @@ function createVideoPlayer(options) {
|
|
|
1898
1959
|
getKeyAccessToken: config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
|
|
1899
1960
|
keyProxyMaxFailures: config.streaming.keyProxyMaxFailures,
|
|
1900
1961
|
hlsConfig: config.streaming.hls,
|
|
1962
|
+
useAppexHlsProfile: config.streaming.useAppexHlsProfile,
|
|
1963
|
+
isLive: isLiveStream,
|
|
1964
|
+
nativeSessionMode: config.streaming.nativeSessionMode,
|
|
1965
|
+
onNativeAuthUpdate: config.streaming.onNativeAuthUpdate,
|
|
1901
1966
|
logger,
|
|
1902
1967
|
callbacks: {
|
|
1903
1968
|
onStateChange: (s) => {
|
|
@@ -2231,7 +2296,10 @@ function createVideoPlayer(options) {
|
|
|
2231
2296
|
mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder ?? config.streaming.mediaProxyUrlBuilder,
|
|
2232
2297
|
keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder ?? config.streaming.keyProxyUrlBuilder,
|
|
2233
2298
|
getKeyAccessToken: partial?.streaming?.getKeyAccessToken ?? config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
|
|
2234
|
-
keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures
|
|
2299
|
+
keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures,
|
|
2300
|
+
useAppexHlsProfile: partial?.streaming?.useAppexHlsProfile ?? config.streaming.useAppexHlsProfile,
|
|
2301
|
+
nativeSessionMode: partial?.streaming?.nativeSessionMode ?? config.streaming.nativeSessionMode,
|
|
2302
|
+
onNativeAuthUpdate: partial?.streaming?.onNativeAuthUpdate ?? config.streaming.onNativeAuthUpdate
|
|
2235
2303
|
},
|
|
2236
2304
|
logging: { ...config.logging, ...partial?.logging },
|
|
2237
2305
|
debug: { ...config.debug, ...partial?.debug },
|
|
@@ -2252,7 +2320,472 @@ function createVideoPlayer(options) {
|
|
|
2252
2320
|
};
|
|
2253
2321
|
return api;
|
|
2254
2322
|
}
|
|
2323
|
+
|
|
2324
|
+
// src/captions/restoreSubtitleSelection.ts
|
|
2325
|
+
var SDK_SUBTITLE_TRACK_SELECTOR = "track[data-sample-subtitle],track[data-appextech-subtitle]";
|
|
2326
|
+
function restoreSubtitleSelection(video, language) {
|
|
2327
|
+
const nodes = video.querySelectorAll(
|
|
2328
|
+
SDK_SUBTITLE_TRACK_SELECTOR
|
|
2329
|
+
);
|
|
2330
|
+
for (const node of Array.from(nodes)) {
|
|
2331
|
+
const selected = Boolean(language) && node.srclang === language;
|
|
2332
|
+
node.default = selected;
|
|
2333
|
+
if (node.track) node.track.mode = selected ? "showing" : "disabled";
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
// src/student/StudentLeaseClient.ts
|
|
2338
|
+
var STUDENT_HEARTBEAT_INTERVAL_MS = 15e3;
|
|
2339
|
+
var STUDENT_REQUEST_TIMEOUT_MS = 1e4;
|
|
2340
|
+
var STUDENT_NOT_READY_MAX_ATTEMPTS = 20;
|
|
2341
|
+
var STUDENT_NOT_READY_RETRY_DELAY_MS = 3e3;
|
|
2342
|
+
var STUDENT_NOT_READY_DEADLINE_MS = 6e4;
|
|
2343
|
+
var WATERMARK_MIN_DELAY_MS = 3e4;
|
|
2344
|
+
var WATERMARK_JITTER_MS = 60001;
|
|
2345
|
+
var WATERMARK_VISIBLE_MS = 5e3;
|
|
2346
|
+
var WATERMARK_MAX_LENGTH = 200;
|
|
2347
|
+
var TOKEN_MAX_LENGTH = 16384;
|
|
2348
|
+
var USERID_MAX_LENGTH = 200;
|
|
2349
|
+
var PLATFORM_LABELS = {
|
|
2350
|
+
android: "Android",
|
|
2351
|
+
ios: "iOS",
|
|
2352
|
+
web: "Web"
|
|
2353
|
+
};
|
|
2354
|
+
var StudentLeaseError = class extends Error {
|
|
2355
|
+
constructor(message, details = {}) {
|
|
2356
|
+
super(message);
|
|
2357
|
+
this.name = "StudentLeaseError";
|
|
2358
|
+
this.code = details.code;
|
|
2359
|
+
this.activePlatform = details.activePlatform;
|
|
2360
|
+
this.status = details.status;
|
|
2361
|
+
}
|
|
2362
|
+
};
|
|
2363
|
+
function mapStudentLeaseError(status, payload) {
|
|
2364
|
+
const error = payload && typeof payload === "object" ? payload.error : void 0;
|
|
2365
|
+
const code = typeof error?.code === "string" ? error.code : void 0;
|
|
2366
|
+
const activePlatform = typeof error?.active_platform === "string" ? error.active_platform : void 0;
|
|
2367
|
+
const label = activePlatform ? PLATFORM_LABELS[activePlatform] : void 0;
|
|
2368
|
+
let message = "Student playback authorization unavailable.";
|
|
2369
|
+
if (code === PLAYBACK_NOT_READY) {
|
|
2370
|
+
message = "Live video is preparing. Please retry shortly.";
|
|
2371
|
+
} else if (status === 409 && code === PLATFORM_IN_USE && label) {
|
|
2372
|
+
message = `You are already watching video on ${label}.`;
|
|
2373
|
+
}
|
|
2374
|
+
return new StudentLeaseError(message, { code, activePlatform, status });
|
|
2375
|
+
}
|
|
2376
|
+
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2377
|
+
var StudentLeaseClient = class {
|
|
2378
|
+
constructor(video, config, options = {}) {
|
|
2379
|
+
this.watermarkEl = null;
|
|
2380
|
+
this.active = null;
|
|
2381
|
+
this.version = 0;
|
|
2382
|
+
this.closed = false;
|
|
2383
|
+
this.inFlight = false;
|
|
2384
|
+
this.onEnded = () => {
|
|
2385
|
+
void this.stop();
|
|
2386
|
+
};
|
|
2387
|
+
this.onPageHide = () => {
|
|
2388
|
+
void this.stop();
|
|
2389
|
+
};
|
|
2390
|
+
const origin = new URL(config.baseUrl);
|
|
2391
|
+
if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
|
|
2392
|
+
throw new Error("Use an HTTPS base origin");
|
|
2393
|
+
}
|
|
2394
|
+
const platform = config.platform ?? "web";
|
|
2395
|
+
if (platform !== "web" || typeof config.userId !== "string" || !config.userId.trim() || config.userId.length > USERID_MAX_LENGTH) {
|
|
2396
|
+
throw new Error("userId and web platform are mandatory");
|
|
2397
|
+
}
|
|
2398
|
+
this.video = video;
|
|
2399
|
+
this.config = {
|
|
2400
|
+
baseUrl: origin.origin,
|
|
2401
|
+
userId: config.userId,
|
|
2402
|
+
platform,
|
|
2403
|
+
watermarkText: config.watermarkText,
|
|
2404
|
+
authorizationToken: assertToken(config.authorizationToken)
|
|
2405
|
+
};
|
|
2406
|
+
this.onError = options.onError ?? (() => {
|
|
2407
|
+
});
|
|
2408
|
+
this.fetchImpl = options.fetch ?? ((...args) => globalThis.fetch(...args));
|
|
2409
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
2410
|
+
this.now = options.now ?? Date.now;
|
|
2411
|
+
this.random = options.random ?? Math.random;
|
|
2412
|
+
this.container = options.watermarkContainer === void 0 ? video.parentElement ?? null : options.watermarkContainer;
|
|
2413
|
+
this.createWatermarkElement();
|
|
2414
|
+
video.addEventListener("ended", this.onEnded);
|
|
2415
|
+
if (typeof window !== "undefined") {
|
|
2416
|
+
window.addEventListener("pagehide", this.onPageHide);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
/** Replace the student bearer token (for example after the BFF renews it). */
|
|
2420
|
+
updateAuthorizationToken(value) {
|
|
2421
|
+
this.config.authorizationToken = assertToken(value);
|
|
2422
|
+
}
|
|
2423
|
+
/** True while a lease is held. */
|
|
2424
|
+
get isActive() {
|
|
2425
|
+
return this.active !== null;
|
|
2426
|
+
}
|
|
2427
|
+
/**
|
|
2428
|
+
* Acquire a lease. Retries `PLAYBACK_NOT_READY` up to 20 attempts, 3s apart,
|
|
2429
|
+
* inside a 60s deadline. Rejects with `StudentLeaseError` otherwise
|
|
2430
|
+
* (`PLATFORM_IN_USE` carries `activePlatform`).
|
|
2431
|
+
*/
|
|
2432
|
+
async start(videoId, mediaType = "video") {
|
|
2433
|
+
if (this.closed) throw new Error("Player is closed");
|
|
2434
|
+
await this.stop();
|
|
2435
|
+
const version = this.version;
|
|
2436
|
+
const body = {
|
|
2437
|
+
userid: this.config.userId,
|
|
2438
|
+
platform: this.config.platform,
|
|
2439
|
+
video_id: videoId,
|
|
2440
|
+
media_type: mediaType
|
|
2441
|
+
};
|
|
2442
|
+
if (this.config.watermarkText != null) {
|
|
2443
|
+
body.watermark_text = this.config.watermarkText;
|
|
2444
|
+
}
|
|
2445
|
+
const deadline = this.now() + STUDENT_NOT_READY_DEADLINE_MS;
|
|
2446
|
+
let result;
|
|
2447
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
2448
|
+
if (this.closed || version !== this.version) {
|
|
2449
|
+
throw new Error("Playback request cancelled");
|
|
2450
|
+
}
|
|
2451
|
+
try {
|
|
2452
|
+
result = await this.request(
|
|
2453
|
+
"/student/playback",
|
|
2454
|
+
this.config.authorizationToken,
|
|
2455
|
+
body
|
|
2456
|
+
);
|
|
2457
|
+
break;
|
|
2458
|
+
} catch (error) {
|
|
2459
|
+
const code = error?.code;
|
|
2460
|
+
if (code !== PLAYBACK_NOT_READY || attempt >= STUDENT_NOT_READY_MAX_ATTEMPTS - 1 || this.now() >= deadline) {
|
|
2461
|
+
throw error;
|
|
2462
|
+
}
|
|
2463
|
+
await this.sleep(STUDENT_NOT_READY_RETRY_DELAY_MS);
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
const lease = result?.data?.student_session;
|
|
2467
|
+
if (!lease?.token) throw new Error("Invalid student playback response");
|
|
2468
|
+
if (this.closed || version !== this.version) {
|
|
2469
|
+
await this.request("/student/release", lease.token).catch(() => {
|
|
2470
|
+
});
|
|
2471
|
+
throw new Error("Playback request cancelled");
|
|
2472
|
+
}
|
|
2473
|
+
this.active = { token: lease.token, seq: 0 };
|
|
2474
|
+
this.heartbeatTimer = setInterval(() => {
|
|
2475
|
+
void this.heartbeat();
|
|
2476
|
+
}, STUDENT_HEARTBEAT_INTERVAL_MS);
|
|
2477
|
+
this.scheduleWatermark(
|
|
2478
|
+
typeof lease.watermark_text === "string" ? lease.watermark_text.slice(0, WATERMARK_MAX_LENGTH) : ""
|
|
2479
|
+
);
|
|
2480
|
+
return result.data;
|
|
2481
|
+
}
|
|
2482
|
+
/** Send one heartbeat. On failure the lease is released and `onError` runs. */
|
|
2483
|
+
async heartbeat() {
|
|
2484
|
+
const lease = this.active;
|
|
2485
|
+
if (!lease || this.inFlight) return;
|
|
2486
|
+
this.inFlight = true;
|
|
2487
|
+
try {
|
|
2488
|
+
await this.request("/student/heartbeat", lease.token, {
|
|
2489
|
+
seq: ++lease.seq,
|
|
2490
|
+
playing: true
|
|
2491
|
+
});
|
|
2492
|
+
} catch (error) {
|
|
2493
|
+
if (this.active === lease) {
|
|
2494
|
+
await this.stop();
|
|
2495
|
+
this.onError(toLeaseError(error));
|
|
2496
|
+
}
|
|
2497
|
+
} finally {
|
|
2498
|
+
this.inFlight = false;
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
/**
|
|
2502
|
+
* Show the watermark at random positions every 30-90s for 5s while the video
|
|
2503
|
+
* plays. An empty string clears it. Requires an active lease.
|
|
2504
|
+
*/
|
|
2505
|
+
scheduleWatermark(text) {
|
|
2506
|
+
clearTimeout(this.watermarkTimer);
|
|
2507
|
+
clearTimeout(this.hideTimer);
|
|
2508
|
+
this.hideWatermark();
|
|
2509
|
+
if (!text || !this.active) return;
|
|
2510
|
+
const nextDelay = () => WATERMARK_MIN_DELAY_MS + Math.floor(this.random() * WATERMARK_JITTER_MS);
|
|
2511
|
+
const tick = () => {
|
|
2512
|
+
if (!this.active) return;
|
|
2513
|
+
if (!this.video.paused && !this.video.ended) {
|
|
2514
|
+
this.showWatermark(text);
|
|
2515
|
+
this.hideTimer = setTimeout(
|
|
2516
|
+
() => this.hideWatermark(),
|
|
2517
|
+
WATERMARK_VISIBLE_MS
|
|
2518
|
+
);
|
|
2519
|
+
}
|
|
2520
|
+
this.watermarkTimer = setTimeout(tick, nextDelay());
|
|
2521
|
+
};
|
|
2522
|
+
this.watermarkTimer = setTimeout(tick, nextDelay());
|
|
2523
|
+
}
|
|
2524
|
+
/** Pause the video, stop timers, and release the lease (keepalive). */
|
|
2525
|
+
async stop() {
|
|
2526
|
+
this.version += 1;
|
|
2527
|
+
this.video.pause();
|
|
2528
|
+
const lease = this.active;
|
|
2529
|
+
this.active = null;
|
|
2530
|
+
clearInterval(this.heartbeatTimer);
|
|
2531
|
+
clearTimeout(this.watermarkTimer);
|
|
2532
|
+
clearTimeout(this.hideTimer);
|
|
2533
|
+
this.hideWatermark();
|
|
2534
|
+
if (lease) {
|
|
2535
|
+
await this.request("/student/release", lease.token, {}, true).catch(
|
|
2536
|
+
() => {
|
|
2537
|
+
}
|
|
2538
|
+
);
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
/** Release the lease, remove the overlay, and detach listeners. */
|
|
2542
|
+
async close() {
|
|
2543
|
+
this.closed = true;
|
|
2544
|
+
await this.stop();
|
|
2545
|
+
this.watermarkEl?.remove();
|
|
2546
|
+
this.watermarkEl = null;
|
|
2547
|
+
this.video.removeEventListener("ended", this.onEnded);
|
|
2548
|
+
if (typeof window !== "undefined") {
|
|
2549
|
+
window.removeEventListener("pagehide", this.onPageHide);
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
async request(path, token, body = {}, keepalive = false) {
|
|
2553
|
+
const controller = new AbortController();
|
|
2554
|
+
const timeout = setTimeout(
|
|
2555
|
+
() => controller.abort(),
|
|
2556
|
+
STUDENT_REQUEST_TIMEOUT_MS
|
|
2557
|
+
);
|
|
2558
|
+
try {
|
|
2559
|
+
const response = await this.fetchImpl(this.config.baseUrl + path, {
|
|
2560
|
+
method: "POST",
|
|
2561
|
+
headers: {
|
|
2562
|
+
Authorization: `Bearer ${token}`,
|
|
2563
|
+
"Content-Type": "application/json"
|
|
2564
|
+
},
|
|
2565
|
+
body: JSON.stringify(body),
|
|
2566
|
+
cache: "no-store",
|
|
2567
|
+
credentials: "omit",
|
|
2568
|
+
redirect: "error",
|
|
2569
|
+
signal: controller.signal,
|
|
2570
|
+
keepalive
|
|
2571
|
+
});
|
|
2572
|
+
const result = await response.json().catch(() => ({}));
|
|
2573
|
+
if (!response.ok) throw mapStudentLeaseError(response.status, result);
|
|
2574
|
+
return result;
|
|
2575
|
+
} finally {
|
|
2576
|
+
clearTimeout(timeout);
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
createWatermarkElement() {
|
|
2580
|
+
if (!this.container || typeof document === "undefined") return;
|
|
2581
|
+
const el = document.createElement("div");
|
|
2582
|
+
Object.assign(el.style, {
|
|
2583
|
+
position: "absolute",
|
|
2584
|
+
display: "none",
|
|
2585
|
+
pointerEvents: "none",
|
|
2586
|
+
zIndex: "20",
|
|
2587
|
+
color: "white",
|
|
2588
|
+
background: "rgba(0,0,0,.4)",
|
|
2589
|
+
padding: "4px 8px",
|
|
2590
|
+
font: "14px sans-serif",
|
|
2591
|
+
maxWidth: "90%",
|
|
2592
|
+
overflowWrap: "anywhere"
|
|
2593
|
+
});
|
|
2594
|
+
if (getComputedStyle(this.container).position === "static") {
|
|
2595
|
+
this.container.style.position = "relative";
|
|
2596
|
+
}
|
|
2597
|
+
this.container.append(el);
|
|
2598
|
+
this.watermarkEl = el;
|
|
2599
|
+
}
|
|
2600
|
+
showWatermark(text) {
|
|
2601
|
+
const el = this.watermarkEl;
|
|
2602
|
+
const container = this.container;
|
|
2603
|
+
if (!el || !container) return;
|
|
2604
|
+
el.textContent = text;
|
|
2605
|
+
el.style.display = "block";
|
|
2606
|
+
el.style.left = `${Math.floor(
|
|
2607
|
+
this.random() * Math.max(1, container.clientWidth - el.offsetWidth)
|
|
2608
|
+
)}px`;
|
|
2609
|
+
el.style.top = `${Math.floor(
|
|
2610
|
+
this.random() * Math.max(1, container.clientHeight - el.offsetHeight)
|
|
2611
|
+
)}px`;
|
|
2612
|
+
}
|
|
2613
|
+
hideWatermark() {
|
|
2614
|
+
if (this.watermarkEl) this.watermarkEl.style.display = "none";
|
|
2615
|
+
}
|
|
2616
|
+
};
|
|
2617
|
+
function assertToken(value) {
|
|
2618
|
+
if (typeof value !== "string" || !value || value.length > TOKEN_MAX_LENGTH || /[\r\n]/.test(value)) {
|
|
2619
|
+
throw new Error("Student playback token is required");
|
|
2620
|
+
}
|
|
2621
|
+
return value;
|
|
2622
|
+
}
|
|
2623
|
+
function toLeaseError(error) {
|
|
2624
|
+
if (error instanceof StudentLeaseError) return error;
|
|
2625
|
+
return new StudentLeaseError(
|
|
2626
|
+
error instanceof Error ? error.message : "Student playback authorization unavailable."
|
|
2627
|
+
);
|
|
2628
|
+
}
|
|
2629
|
+
|
|
2630
|
+
// src/analytics/AnalyticsClient.ts
|
|
2631
|
+
var defaultSend = async (url, body, opts) => {
|
|
2632
|
+
const response = await fetch(url, {
|
|
2633
|
+
method: "POST",
|
|
2634
|
+
headers: { "Content-Type": "application/json" },
|
|
2635
|
+
body: JSON.stringify(body),
|
|
2636
|
+
keepalive: opts?.keepalive ?? false
|
|
2637
|
+
});
|
|
2638
|
+
const value = await response.json().catch(() => ({}));
|
|
2639
|
+
if (!response.ok) {
|
|
2640
|
+
throw new Error(
|
|
2641
|
+
value.error ?? "Analytics request failed"
|
|
2642
|
+
);
|
|
2643
|
+
}
|
|
2644
|
+
return value;
|
|
2645
|
+
};
|
|
2646
|
+
var AnalyticsClient = class {
|
|
2647
|
+
constructor(options) {
|
|
2648
|
+
this.options = options;
|
|
2649
|
+
this.session = null;
|
|
2650
|
+
this.watched = 0;
|
|
2651
|
+
this.sequence = 0;
|
|
2652
|
+
this.finished = false;
|
|
2653
|
+
this.destroyed = false;
|
|
2654
|
+
this.lastPosition = 0;
|
|
2655
|
+
this.progressedAt = Number.NEGATIVE_INFINITY;
|
|
2656
|
+
this.onPause = () => {
|
|
2657
|
+
void this.heartbeat(false);
|
|
2658
|
+
};
|
|
2659
|
+
this.onEnded = () => {
|
|
2660
|
+
void this.heartbeat(true);
|
|
2661
|
+
};
|
|
2662
|
+
this.onPageHide = () => {
|
|
2663
|
+
void this.heartbeat(true);
|
|
2664
|
+
};
|
|
2665
|
+
this.send = options.send ?? defaultSend;
|
|
2666
|
+
this.now = options.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
2667
|
+
this.onError = options.onError ?? (() => {
|
|
2668
|
+
});
|
|
2669
|
+
this.lastTime = this.now();
|
|
2670
|
+
this.lastPosition = options.video.currentTime || 0;
|
|
2671
|
+
}
|
|
2672
|
+
/** Total seconds credited as watched so far. */
|
|
2673
|
+
get watchedSeconds() {
|
|
2674
|
+
return this.watched;
|
|
2675
|
+
}
|
|
2676
|
+
/** Session from `analytics/start`, or null before it resolves. */
|
|
2677
|
+
get currentSession() {
|
|
2678
|
+
return this.session;
|
|
2679
|
+
}
|
|
2680
|
+
/**
|
|
2681
|
+
* POST `{origin}/media/{videoKey}/analytics/start` and begin sampling.
|
|
2682
|
+
* Resolves to the session, or null on failure (reported via `onError`).
|
|
2683
|
+
*/
|
|
2684
|
+
async start() {
|
|
2685
|
+
if (this.destroyed) return null;
|
|
2686
|
+
const { video, origin, videoKey, deviceId, platform } = this.options;
|
|
2687
|
+
const url = new URL(
|
|
2688
|
+
`/media/${encodeURIComponent(videoKey)}/analytics/start`,
|
|
2689
|
+
origin
|
|
2690
|
+
).href;
|
|
2691
|
+
const token = typeof this.options.playbackToken === "function" ? this.options.playbackToken() : this.options.playbackToken;
|
|
2692
|
+
video.addEventListener("pause", this.onPause);
|
|
2693
|
+
video.addEventListener("ended", this.onEnded);
|
|
2694
|
+
if (typeof window !== "undefined") {
|
|
2695
|
+
window.addEventListener("pagehide", this.onPageHide);
|
|
2696
|
+
}
|
|
2697
|
+
this.lastTime = this.now();
|
|
2698
|
+
this.lastPosition = video.currentTime || 0;
|
|
2699
|
+
this.sampleTimer = setInterval(
|
|
2700
|
+
() => this.sample(),
|
|
2701
|
+
this.options.sampleIntervalMs ?? 1e3
|
|
2702
|
+
);
|
|
2703
|
+
this.heartbeatTimer = setInterval(
|
|
2704
|
+
() => void this.heartbeat(false),
|
|
2705
|
+
this.options.heartbeatIntervalMs ?? 15e3
|
|
2706
|
+
);
|
|
2707
|
+
try {
|
|
2708
|
+
const value = await this.send(url, {
|
|
2709
|
+
playback_token: token,
|
|
2710
|
+
device_id: deviceId,
|
|
2711
|
+
platform: platform ?? "web"
|
|
2712
|
+
});
|
|
2713
|
+
const session = unwrapSession(value);
|
|
2714
|
+
if (!session) throw new Error("Invalid analytics start response");
|
|
2715
|
+
if (this.destroyed) return null;
|
|
2716
|
+
this.session = session;
|
|
2717
|
+
return session;
|
|
2718
|
+
} catch (error) {
|
|
2719
|
+
this.onError(error);
|
|
2720
|
+
return null;
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
/** Credit elapsed wall time when the video genuinely advanced. */
|
|
2724
|
+
sample() {
|
|
2725
|
+
const { video } = this.options;
|
|
2726
|
+
const now = this.now();
|
|
2727
|
+
const elapsed = Math.min(2, (now - this.lastTime) / 1e3);
|
|
2728
|
+
const advance = video.currentTime - this.lastPosition;
|
|
2729
|
+
const rate = Math.max(1, video.playbackRate || 1);
|
|
2730
|
+
if (!video.paused && !video.seeking && video.readyState >= 2 && advance > 0 && advance <= elapsed * rate + 1) {
|
|
2731
|
+
this.watched += Math.min(
|
|
2732
|
+
elapsed,
|
|
2733
|
+
advance / Math.max(0.1, video.playbackRate || 1)
|
|
2734
|
+
);
|
|
2735
|
+
this.progressedAt = now;
|
|
2736
|
+
}
|
|
2737
|
+
this.lastTime = now;
|
|
2738
|
+
this.lastPosition = video.currentTime;
|
|
2739
|
+
}
|
|
2740
|
+
/**
|
|
2741
|
+
* Send an event heartbeat. `end: true` marks the session finished, sends with
|
|
2742
|
+
* `keepalive`, and suppresses further heartbeats.
|
|
2743
|
+
*/
|
|
2744
|
+
async heartbeat(end = false) {
|
|
2745
|
+
const session = this.session;
|
|
2746
|
+
if (!session || this.finished) return;
|
|
2747
|
+
this.sample();
|
|
2748
|
+
if (end) this.finished = true;
|
|
2749
|
+
const { video, origin } = this.options;
|
|
2750
|
+
const body = {
|
|
2751
|
+
token: session.token,
|
|
2752
|
+
seq: ++this.sequence,
|
|
2753
|
+
watched_seconds: this.watched,
|
|
2754
|
+
playing: !video.paused && !video.ended && !video.seeking && this.now() - this.progressedAt < (this.options.progressWindowMs ?? 5e3),
|
|
2755
|
+
ended: end
|
|
2756
|
+
};
|
|
2757
|
+
try {
|
|
2758
|
+
await this.send(new URL(session.event_url, origin).href, body, {
|
|
2759
|
+
keepalive: true
|
|
2760
|
+
});
|
|
2761
|
+
} catch (error) {
|
|
2762
|
+
this.onError(error);
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
/** Send the final heartbeat (if started) and detach everything. */
|
|
2766
|
+
async destroy() {
|
|
2767
|
+
if (this.destroyed) return;
|
|
2768
|
+
await this.heartbeat(true);
|
|
2769
|
+
this.destroyed = true;
|
|
2770
|
+
clearInterval(this.sampleTimer);
|
|
2771
|
+
clearInterval(this.heartbeatTimer);
|
|
2772
|
+
const { video } = this.options;
|
|
2773
|
+
video.removeEventListener("pause", this.onPause);
|
|
2774
|
+
video.removeEventListener("ended", this.onEnded);
|
|
2775
|
+
if (typeof window !== "undefined") {
|
|
2776
|
+
window.removeEventListener("pagehide", this.onPageHide);
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
};
|
|
2780
|
+
function unwrapSession(value) {
|
|
2781
|
+
const candidate = value && typeof value === "object" && "data" in value ? value.data : value;
|
|
2782
|
+
if (!candidate || typeof candidate !== "object") return null;
|
|
2783
|
+
const { token, event_url } = candidate;
|
|
2784
|
+
if (typeof token !== "string" || typeof event_url !== "string") return null;
|
|
2785
|
+
return candidate;
|
|
2786
|
+
}
|
|
2255
2787
|
export {
|
|
2788
|
+
AnalyticsClient,
|
|
2256
2789
|
AuthManager,
|
|
2257
2790
|
AuthParamsStore,
|
|
2258
2791
|
DEFAULT_CONTROLS,
|
|
@@ -2265,26 +2798,40 @@ export {
|
|
|
2265
2798
|
EventEmitter,
|
|
2266
2799
|
KEY_PROXY_MAX_FAILURES,
|
|
2267
2800
|
PACKAGE_VERSION,
|
|
2801
|
+
PLATFORM_IN_USE,
|
|
2802
|
+
PLAYBACK_NOT_READY,
|
|
2268
2803
|
PLAYBACK_RATES,
|
|
2269
2804
|
PlaybackSourceManager,
|
|
2270
2805
|
PlayerErrorCode,
|
|
2271
2806
|
RefreshManager,
|
|
2807
|
+
SDK_SUBTITLE_TRACK_SELECTOR,
|
|
2272
2808
|
SECRET_SCAN_MAX_DEPTH,
|
|
2809
|
+
STUDENT_HEARTBEAT_INTERVAL_MS,
|
|
2810
|
+
STUDENT_NOT_READY_DEADLINE_MS,
|
|
2811
|
+
STUDENT_NOT_READY_MAX_ATTEMPTS,
|
|
2812
|
+
STUDENT_NOT_READY_RETRY_DELAY_MS,
|
|
2813
|
+
STUDENT_REQUEST_TIMEOUT_MS,
|
|
2814
|
+
StudentLeaseClient,
|
|
2815
|
+
StudentLeaseError,
|
|
2816
|
+
appexHlsConfig,
|
|
2273
2817
|
assertNoSecretsInConfig,
|
|
2274
2818
|
createAuthParamsLoader,
|
|
2275
2819
|
createPlayerError,
|
|
2276
2820
|
createVideoPlayer,
|
|
2277
2821
|
getLiveEdgeTime,
|
|
2822
|
+
hlsConfig,
|
|
2278
2823
|
isAtLiveEdge,
|
|
2279
2824
|
isEncryptionKeyUrl,
|
|
2280
2825
|
isLivePlaylistUrl,
|
|
2281
2826
|
isPlainObject,
|
|
2282
2827
|
isSameOriginHttpUrl,
|
|
2828
|
+
mapStudentLeaseError,
|
|
2283
2829
|
mergePlayerConfig,
|
|
2284
2830
|
redactObject,
|
|
2285
2831
|
redactSensitive,
|
|
2286
2832
|
redactValue,
|
|
2287
2833
|
resolveBuiltinHlsLoader,
|
|
2834
|
+
restoreSubtitleSelection,
|
|
2288
2835
|
rewriteHlsRequestUrl,
|
|
2289
2836
|
seekToLiveEdge,
|
|
2290
2837
|
themeToCssVars
|