@scalemule/gallop 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2886 +0,0 @@
1
- import { EventEmitter } from './chunk-SQPWH6EI.js';
2
- import Hls from 'hls.js';
3
-
4
- // src/constants.ts
5
- var DEFAULT_THEME = {
6
- colorPrimary: "#635bff",
7
- colorSecondary: "#8b5cf6",
8
- colorText: "#ffffff",
9
- colorBackground: "rgba(24, 24, 32, 0.92)",
10
- colorBuffered: "rgba(255, 255, 255, 0.22)",
11
- colorProgress: "#635bff",
12
- controlBarBackground: "rgba(0, 0, 0, 0.65)",
13
- controlBarHeight: "44px",
14
- borderRadius: "8px",
15
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
16
- fontSize: "13px",
17
- iconSize: "22px"
18
- };
19
- var DEFAULT_CONFIG = {
20
- autoplay: false,
21
- loop: false,
22
- muted: false,
23
- aspectRatio: "16:9",
24
- apiBaseUrl: "https://api.scalemule.com"
25
- };
26
- var SPEED_PRESETS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
27
- var SEEK_STEP = 5;
28
- var SEEK_STEP_LARGE = 10;
29
- var VOLUME_STEP = 0.05;
30
- var CONTROLS_HIDE_DELAY = 3e3;
31
- var DOUBLE_TAP_DELAY = 300;
32
- var HLS_DEFAULT_CONFIG = {
33
- maxBufferLength: 30,
34
- maxMaxBufferLength: 60,
35
- startLevel: -1,
36
- capLevelToPlayerSize: true,
37
- progressive: true
38
- };
39
-
40
- // src/core/PlayerState.ts
41
- var VALID_TRANSITIONS = {
42
- idle: ["loading"],
43
- loading: ["ready", "error"],
44
- ready: ["playing", "paused", "error"],
45
- playing: ["paused", "buffering", "ended", "error", "loading"],
46
- paused: ["playing", "buffering", "ended", "error", "loading"],
47
- buffering: ["playing", "paused", "error", "ended"],
48
- ended: ["playing", "loading", "idle"],
49
- error: ["loading", "idle"]
50
- };
51
- var PlayerState = class {
52
- constructor(onChange) {
53
- this._status = "idle";
54
- this.onChange = onChange;
55
- }
56
- get status() {
57
- return this._status;
58
- }
59
- transition(next) {
60
- if (next === this._status) return false;
61
- const allowed = VALID_TRANSITIONS[this._status];
62
- if (!allowed.includes(next)) {
63
- return false;
64
- }
65
- const prev = this._status;
66
- this._status = next;
67
- this.onChange?.(next, prev);
68
- return true;
69
- }
70
- reset() {
71
- const prev = this._status;
72
- this._status = "idle";
73
- if (prev !== "idle") {
74
- this.onChange?.("idle", prev);
75
- }
76
- }
77
- get isPlaying() {
78
- return this._status === "playing";
79
- }
80
- get isPaused() {
81
- return this._status === "paused";
82
- }
83
- get isBuffering() {
84
- return this._status === "buffering";
85
- }
86
- get isEnded() {
87
- return this._status === "ended";
88
- }
89
- };
90
- var HLSJSEngine = class {
91
- constructor(auth, hlsConfigOverrides) {
92
- this.hls = null;
93
- this.video = null;
94
- this.levels = [];
95
- this.listeners = /* @__PURE__ */ new Map();
96
- this.statsTimer = null;
97
- this.apiKey = auth?.apiKey;
98
- this.embedToken = auth?.embedToken;
99
- this.hlsConfigOverrides = hlsConfigOverrides;
100
- }
101
- load(url, videoElement) {
102
- this.destroy();
103
- this.video = videoElement;
104
- let sourceOrigin = null;
105
- try {
106
- sourceOrigin = new URL(url, window.location.href).origin;
107
- } catch {
108
- }
109
- const config = {
110
- ...HLS_DEFAULT_CONFIG,
111
- ...this.hlsConfigOverrides
112
- };
113
- if (this.apiKey || this.embedToken) {
114
- const apiKey = this.apiKey;
115
- const embedToken = this.embedToken;
116
- config.xhrSetup = (xhr, requestUrl) => {
117
- try {
118
- const u = new URL(requestUrl, url);
119
- const isTrustedOrigin = sourceOrigin !== null && u.origin === sourceOrigin;
120
- if (apiKey && isTrustedOrigin) {
121
- xhr.setRequestHeader("X-API-Key", apiKey);
122
- } else if (embedToken && isTrustedOrigin) {
123
- u.searchParams.set("token", embedToken);
124
- xhr.open("GET", u.toString(), true);
125
- }
126
- } catch {
127
- }
128
- };
129
- }
130
- this.hls = new Hls(config);
131
- this.hls.on(Hls.Events.MANIFEST_PARSED, (_event, data) => {
132
- this.levels = data.levels.map((level, index) => ({
133
- index,
134
- height: level.height,
135
- width: level.width,
136
- bitrate: level.bitrate,
137
- label: `${level.height}p`,
138
- active: index === this.hls.currentLevel
139
- }));
140
- this.fire("qualitylevels", this.levels);
141
- });
142
- this.hls.on(Hls.Events.LEVEL_SWITCHED, (_event, data) => {
143
- this.levels = this.levels.map((level) => ({
144
- ...level,
145
- active: level.index === data.level
146
- }));
147
- const activeLevel = this.levels[data.level];
148
- if (activeLevel) {
149
- this.fire("qualitychange", activeLevel);
150
- }
151
- this.fireStats({
152
- kind: "level_switch",
153
- level: data.level,
154
- bandwidthEstimate: this.hls?.bandwidthEstimate
155
- });
156
- });
157
- this.hls.on(Hls.Events.ERROR, (_event, data) => {
158
- this.fireStats({
159
- kind: "hls_error",
160
- fatal: data.fatal,
161
- errorType: data.type,
162
- errorDetails: data.details,
163
- bandwidthEstimate: this.hls?.bandwidthEstimate
164
- });
165
- if (data.fatal) {
166
- switch (data.type) {
167
- case Hls.ErrorTypes.NETWORK_ERROR:
168
- this.hls.startLoad();
169
- break;
170
- case Hls.ErrorTypes.MEDIA_ERROR:
171
- this.hls.recoverMediaError();
172
- break;
173
- default:
174
- this.fire("error", {
175
- code: data.type,
176
- message: data.details || "Fatal playback error"
177
- });
178
- break;
179
- }
180
- }
181
- });
182
- this.hls.on(Hls.Events.FRAG_BUFFERED, (_event, data) => {
183
- this.fire("buffering", false);
184
- const stats = data ?? {};
185
- const loadStart = stats.stats?.loading?.start ?? 0;
186
- const loadEnd = stats.stats?.loading?.end ?? 0;
187
- this.fireStats({
188
- kind: "fragment",
189
- bandwidthEstimate: this.hls?.bandwidthEstimate,
190
- fragmentDuration: stats.frag?.duration,
191
- fragmentSizeBytes: stats.stats?.total,
192
- fragmentLoadMs: loadEnd > loadStart ? loadEnd - loadStart : void 0
193
- });
194
- });
195
- this.hls.on(Hls.Events.FRAG_LOADED, (_event, data) => {
196
- const response = data.networkDetails;
197
- if (response && typeof response.getResponseHeader === "function") {
198
- this.fireStats({
199
- kind: "fragment",
200
- cdnNode: response.getResponseHeader("X-Amz-Cf-Pop") || response.getResponseHeader("X-Edge-Location") || void 0,
201
- cdnCacheStatus: response.getResponseHeader("X-Cache") || void 0,
202
- cdnRequestID: response.getResponseHeader("X-Amz-Cf-Id") || void 0,
203
- bandwidthEstimate: this.hls?.bandwidthEstimate
204
- });
205
- }
206
- });
207
- this.hls.loadSource(url);
208
- this.hls.attachMedia(videoElement);
209
- this.statsTimer = setInterval(() => {
210
- if (!this.video) return;
211
- const v = this.video;
212
- if (typeof v.getVideoPlaybackQuality === "function") {
213
- const quality = v.getVideoPlaybackQuality();
214
- this.fireStats({
215
- kind: "periodic",
216
- droppedFrames: quality.droppedVideoFrames,
217
- totalFrames: quality.totalVideoFrames,
218
- bandwidthEstimate: this.hls?.bandwidthEstimate
219
- });
220
- } else if (typeof v.webkitDroppedFrameCount === "number") {
221
- this.fireStats({
222
- kind: "periodic",
223
- droppedFrames: v.webkitDroppedFrameCount,
224
- bandwidthEstimate: this.hls?.bandwidthEstimate
225
- });
226
- }
227
- }, 1e4);
228
- }
229
- destroy() {
230
- if (this.statsTimer) {
231
- clearInterval(this.statsTimer);
232
- this.statsTimer = null;
233
- }
234
- if (this.hls) {
235
- this.hls.destroy();
236
- this.hls = null;
237
- }
238
- this.video = null;
239
- this.levels = [];
240
- }
241
- getQualityLevels() {
242
- return this.levels;
243
- }
244
- setQualityLevel(index) {
245
- if (this.hls) {
246
- this.hls.currentLevel = index;
247
- }
248
- }
249
- getCurrentQuality() {
250
- return this.hls?.currentLevel ?? -1;
251
- }
252
- isAutoQuality() {
253
- return this.hls?.autoLevelEnabled ?? true;
254
- }
255
- setAutoQuality() {
256
- if (this.hls) {
257
- this.hls.currentLevel = -1;
258
- }
259
- }
260
- on(event, callback) {
261
- if (!this.listeners.has(event)) {
262
- this.listeners.set(event, /* @__PURE__ */ new Set());
263
- }
264
- this.listeners.get(event).add(callback);
265
- }
266
- off(event, callback) {
267
- this.listeners.get(event)?.delete(callback);
268
- }
269
- fire(event, ...args) {
270
- const set = this.listeners.get(event);
271
- if (!set) return;
272
- for (const cb of set) {
273
- cb(...args);
274
- }
275
- }
276
- fireStats(stats) {
277
- this.fire("stats", { ...stats, statsSource: "hlsjs" });
278
- }
279
- };
280
-
281
- // src/engine/NativeHLSEngine.ts
282
- var NativeHLSEngine = class {
283
- constructor() {
284
- this.video = null;
285
- this.listeners = /* @__PURE__ */ new Map();
286
- this.statsTimer = null;
287
- this.lastResourceIndex = 0;
288
- this.sourceHost = null;
289
- }
290
- load(url, videoElement) {
291
- this.destroy();
292
- this.video = videoElement;
293
- try {
294
- const parsed = new URL(url, window.location.href);
295
- this.sourceHost = parsed.host;
296
- } catch {
297
- this.sourceHost = null;
298
- }
299
- videoElement.src = url;
300
- videoElement.addEventListener("loadedmetadata", () => {
301
- this.fire("qualitylevels", []);
302
- });
303
- videoElement.addEventListener("error", () => {
304
- const err = videoElement.error;
305
- this.fire("error", {
306
- code: `MEDIA_ERR_${err?.code ?? 0}`,
307
- message: err?.message ?? "Native playback error"
308
- });
309
- });
310
- this.statsTimer = setInterval(() => {
311
- this.scavengeStats();
312
- }, 1e4);
313
- }
314
- destroy() {
315
- if (this.statsTimer) {
316
- clearInterval(this.statsTimer);
317
- this.statsTimer = null;
318
- }
319
- if (this.video) {
320
- this.video.removeAttribute("src");
321
- this.video.load();
322
- this.video = null;
323
- }
324
- }
325
- scavengeStats() {
326
- if (!this.video) return;
327
- const v = this.video;
328
- let droppedFrames;
329
- let totalFrames;
330
- if (typeof v.getVideoPlaybackQuality === "function") {
331
- const q = v.getVideoPlaybackQuality();
332
- droppedFrames = q.droppedVideoFrames;
333
- totalFrames = q.totalVideoFrames;
334
- } else if (typeof v.webkitDroppedFrameCount === "number") {
335
- droppedFrames = v.webkitDroppedFrameCount;
336
- }
337
- if (typeof performance !== "undefined" && typeof performance.getEntriesByType === "function") {
338
- const resources = performance.getEntriesByType("resource");
339
- for (let i = this.lastResourceIndex; i < resources.length; i++) {
340
- const res = resources[i];
341
- if (!this.isVideoFragment(res.name)) continue;
342
- const isCrossOrigin = this.sourceHost !== null && !res.name.includes(window.location.host);
343
- const taoAvailable = !isCrossOrigin || res.transferSize > 0 || res.responseStart > 0;
344
- this.fire("stats", {
345
- kind: "fragment",
346
- statsSource: "native_resource_timing",
347
- fragmentLoadMs: Math.round(res.duration),
348
- fragmentSizeBytes: taoAvailable && res.transferSize > 0 ? res.transferSize : void 0,
349
- bandwidthEstimate: taoAvailable && res.transferSize > 0 && res.duration > 0 ? Math.round(res.transferSize * 8 / (res.duration / 1e3)) : void 0,
350
- taoAvailable
351
- });
352
- }
353
- this.lastResourceIndex = resources.length;
354
- }
355
- this.fire("stats", {
356
- kind: "periodic",
357
- statsSource: "native_resource_timing",
358
- droppedFrames,
359
- totalFrames
360
- });
361
- }
362
- isVideoFragment(url) {
363
- if (this.sourceHost) {
364
- try {
365
- const parsed = new URL(url, window.location.href);
366
- if (parsed.host !== this.sourceHost) return false;
367
- } catch {
368
- return false;
369
- }
370
- }
371
- const path = url.split("?")[0];
372
- return path.endsWith(".ts") || path.endsWith(".m4s") || path.endsWith(".m4v") || path.includes("/seg-") || path.includes("/segment");
373
- }
374
- getQualityLevels() {
375
- return [];
376
- }
377
- setQualityLevel(_index) {
378
- }
379
- getCurrentQuality() {
380
- return -1;
381
- }
382
- isAutoQuality() {
383
- return true;
384
- }
385
- setAutoQuality() {
386
- }
387
- on(event, callback) {
388
- if (!this.listeners.has(event)) {
389
- this.listeners.set(event, /* @__PURE__ */ new Set());
390
- }
391
- this.listeners.get(event).add(callback);
392
- }
393
- off(event, callback) {
394
- this.listeners.get(event)?.delete(callback);
395
- }
396
- fire(event, ...args) {
397
- const set = this.listeners.get(event);
398
- if (!set) return;
399
- for (const cb of set) {
400
- cb(...args);
401
- }
402
- }
403
- };
404
-
405
- // src/utils/device.ts
406
- function supportsNativeHLS() {
407
- if (typeof document === "undefined") return false;
408
- const video = document.createElement("video");
409
- return video.canPlayType("application/vnd.apple.mpegurl") !== "";
410
- }
411
- function supportsFullscreen() {
412
- if (typeof document === "undefined") return false;
413
- const el2 = document.documentElement;
414
- return !!(el2.requestFullscreen || el2.webkitRequestFullscreen);
415
- }
416
-
417
- // src/engine/engineFactory.ts
418
- function createEngine(auth, hlsConfig) {
419
- const authOpts = typeof auth === "string" ? { apiKey: auth } : auth ?? {};
420
- if (Hls.isSupported()) {
421
- return new HLSJSEngine(authOpts, hlsConfig);
422
- }
423
- if (supportsNativeHLS()) {
424
- return new NativeHLSEngine();
425
- }
426
- throw new Error("HLS playback is not supported in this browser");
427
- }
428
-
429
- // src/api/ScaleMuleClient.ts
430
- var ScaleMuleClient = class {
431
- constructor(optionsOrKey, baseUrl) {
432
- if (typeof optionsOrKey === "string") {
433
- this.apiKey = optionsOrKey;
434
- this.baseUrl = (baseUrl ?? DEFAULT_CONFIG.apiBaseUrl).replace(/\/$/, "");
435
- } else {
436
- this.apiKey = optionsOrKey.apiKey;
437
- this.embedToken = optionsOrKey.embedToken;
438
- this.baseUrl = (optionsOrKey.baseUrl ?? DEFAULT_CONFIG.apiBaseUrl).replace(/\/$/, "");
439
- }
440
- }
441
- buildUrl(path) {
442
- const url = new URL(`${this.baseUrl}${path}`);
443
- if (this.embedToken) {
444
- url.searchParams.set("token", this.embedToken);
445
- }
446
- return url.toString();
447
- }
448
- getHeaders() {
449
- const headers = { "Accept": "application/json" };
450
- if (this.apiKey) {
451
- headers["X-API-Key"] = this.apiKey;
452
- }
453
- return headers;
454
- }
455
- async getVideoMetadata(videoId) {
456
- const path = this.embedToken ? `/v1/videos/embed/${videoId}/metadata` : `/v1/videos/${videoId}`;
457
- const response = await fetch(this.buildUrl(path), {
458
- headers: this.getHeaders()
459
- });
460
- if (!response.ok) {
461
- const text = await response.text().catch(() => "");
462
- throw new Error(`Failed to load video ${videoId}: ${response.status} ${text}`);
463
- }
464
- const data = await response.json();
465
- return {
466
- id: data.id,
467
- title: data.title ?? "",
468
- duration: data.duration ?? 0,
469
- poster: data.poster_url ?? data.thumbnail_url,
470
- playlistUrl: data.playlist_url,
471
- qualities: (data.qualities ?? []).map((q, i) => ({
472
- index: i,
473
- height: q.height,
474
- width: q.width,
475
- bitrate: q.bitrate,
476
- label: `${q.height}p`,
477
- active: false
478
- }))
479
- };
480
- }
481
- async trackPlayback(videoId, payload, options) {
482
- const path = this.embedToken ? `/v1/videos/embed/${videoId}/track` : `/v1/videos/${videoId}/track`;
483
- const response = await fetch(this.buildUrl(path), {
484
- method: "POST",
485
- headers: {
486
- ...this.getHeaders(),
487
- "Content-Type": "application/json"
488
- },
489
- body: JSON.stringify(payload),
490
- keepalive: options?.keepalive ?? false
491
- });
492
- if (!response.ok) {
493
- const text = await response.text().catch(() => "");
494
- throw new Error(`Failed to track playback for ${videoId}: ${response.status} ${text}`);
495
- }
496
- }
497
- };
498
-
499
- // src/ui/IconSet.ts
500
- var stroke = (d) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${d}</svg>`;
501
- var fill = (d) => `<svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${d}</svg>`;
502
- var Icons = {
503
- play: fill('<path d="M6.906 4.537A.6.6 0 0 0 6 5.053v13.894a.6.6 0 0 0 .906.516l11.723-6.947a.6.6 0 0 0 0-1.032L6.906 4.537Z"/>'),
504
- pause: fill('<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>'),
505
- volumeHigh: stroke('<path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>'),
506
- volumeLow: stroke('<path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>'),
507
- volumeMuted: stroke('<path d="M11 5L6 9H2v6h4l5 4V5z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/>'),
508
- fullscreen: stroke('<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>'),
509
- fullscreenExit: stroke('<path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/>'),
510
- settings: stroke('<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>'),
511
- chevronLeft: stroke('<polyline points="15 18 9 12 15 6"/>'),
512
- check: stroke('<polyline points="20 6 9 17 4 12"/>')
513
- };
514
-
515
- // src/utils/dom.ts
516
- function el(tag, attrs, children) {
517
- const element = document.createElement(tag);
518
- if (attrs) {
519
- for (const [key, value] of Object.entries(attrs)) {
520
- element.setAttribute(key, value);
521
- }
522
- }
523
- return element;
524
- }
525
- function svgIcon(svgContent, className) {
526
- const wrapper = document.createElement("span");
527
- wrapper.className = "gallop-icon";
528
- wrapper.innerHTML = svgContent;
529
- wrapper.setAttribute("aria-hidden", "true");
530
- return wrapper;
531
- }
532
-
533
- // src/ui/ProgressBar.ts
534
- var ProgressBar = class {
535
- constructor(player) {
536
- this.dragging = false;
537
- this.onMouseDown = (e) => {
538
- e.preventDefault();
539
- this.dragging = true;
540
- this.seekToPosition(e.clientX);
541
- const onMove = (ev) => this.seekToPosition(ev.clientX);
542
- const onUp = () => {
543
- this.dragging = false;
544
- document.removeEventListener("mousemove", onMove);
545
- document.removeEventListener("mouseup", onUp);
546
- };
547
- document.addEventListener("mousemove", onMove);
548
- document.addEventListener("mouseup", onUp);
549
- };
550
- this.onTouchStart = (e) => {
551
- e.preventDefault();
552
- this.dragging = true;
553
- const touch = e.touches[0];
554
- this.seekToPosition(touch.clientX);
555
- const onMove = (ev) => this.seekToPosition(ev.touches[0].clientX);
556
- const onEnd = () => {
557
- this.dragging = false;
558
- document.removeEventListener("touchmove", onMove);
559
- document.removeEventListener("touchend", onEnd);
560
- };
561
- document.addEventListener("touchmove", onMove);
562
- document.addEventListener("touchend", onEnd);
563
- };
564
- this.player = player;
565
- this.element = document.createElement("div");
566
- this.element.className = "gallop-progress-container";
567
- this.bar = document.createElement("div");
568
- this.bar.className = "gallop-progress-bar";
569
- this.buffered = document.createElement("div");
570
- this.buffered.className = "gallop-progress-buffered";
571
- this.played = document.createElement("div");
572
- this.played.className = "gallop-progress-played";
573
- this.thumb = document.createElement("div");
574
- this.thumb.className = "gallop-progress-thumb";
575
- this.bar.appendChild(this.buffered);
576
- this.bar.appendChild(this.played);
577
- this.bar.appendChild(this.thumb);
578
- this.element.appendChild(this.bar);
579
- this.element.addEventListener("mousedown", this.onMouseDown);
580
- this.element.addEventListener("touchstart", this.onTouchStart, { passive: false });
581
- }
582
- update(currentTime, duration, bufferedRanges) {
583
- if (this.dragging || !duration) return;
584
- const pct = currentTime / duration * 100;
585
- this.played.style.width = `${pct}%`;
586
- this.thumb.style.left = `${pct}%`;
587
- if (bufferedRanges.length > 0) {
588
- const bufferedEnd = bufferedRanges.end(bufferedRanges.length - 1);
589
- this.buffered.style.width = `${bufferedEnd / duration * 100}%`;
590
- }
591
- }
592
- seekToPosition(clientX) {
593
- const rect = this.bar.getBoundingClientRect();
594
- const pct = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
595
- const time = pct * this.player.duration;
596
- this.player.seek(time);
597
- this.played.style.width = `${pct * 100}%`;
598
- this.thumb.style.left = `${pct * 100}%`;
599
- }
600
- destroy() {
601
- this.element.removeEventListener("mousedown", this.onMouseDown);
602
- this.element.removeEventListener("touchstart", this.onTouchStart);
603
- }
604
- };
605
-
606
- // src/ui/VolumeControl.ts
607
- var VolumeControl = class {
608
- constructor(player) {
609
- this.onSliderMouseDown = (e) => {
610
- e.preventDefault();
611
- e.stopPropagation();
612
- this.setVolumeFromX(e.clientX);
613
- const onMove = (ev) => this.setVolumeFromX(ev.clientX);
614
- const onUp = () => {
615
- document.removeEventListener("mousemove", onMove);
616
- document.removeEventListener("mouseup", onUp);
617
- };
618
- document.addEventListener("mousemove", onMove);
619
- document.addEventListener("mouseup", onUp);
620
- };
621
- this.player = player;
622
- this.element = document.createElement("div");
623
- this.element.className = "gallop-volume";
624
- this.muteBtn = document.createElement("button");
625
- this.muteBtn.className = "gallop-btn";
626
- this.muteBtn.setAttribute("aria-label", "Mute");
627
- this.iconHigh = svgIcon(Icons.volumeHigh);
628
- this.iconLow = svgIcon(Icons.volumeLow);
629
- this.iconMuted = svgIcon(Icons.volumeMuted);
630
- this.muteBtn.appendChild(this.iconHigh);
631
- this.muteBtn.addEventListener("click", (e) => {
632
- e.stopPropagation();
633
- player.toggleMute();
634
- });
635
- this.sliderWrap = document.createElement("div");
636
- this.sliderWrap.className = "gallop-volume-slider-wrap";
637
- this.slider = document.createElement("div");
638
- this.slider.className = "gallop-volume-slider";
639
- this.fill = document.createElement("div");
640
- this.fill.className = "gallop-volume-fill";
641
- this.fill.style.width = `${player.volume * 100}%`;
642
- this.slider.appendChild(this.fill);
643
- this.sliderWrap.appendChild(this.slider);
644
- this.element.appendChild(this.muteBtn);
645
- this.element.appendChild(this.sliderWrap);
646
- this.slider.addEventListener("mousedown", this.onSliderMouseDown);
647
- }
648
- update(volume, muted) {
649
- const effectiveVolume = muted ? 0 : volume;
650
- this.fill.style.width = `${effectiveVolume * 100}%`;
651
- this.muteBtn.innerHTML = "";
652
- if (muted || volume === 0) {
653
- this.muteBtn.appendChild(this.iconMuted.cloneNode(true));
654
- } else if (volume < 0.5) {
655
- this.muteBtn.appendChild(this.iconLow.cloneNode(true));
656
- } else {
657
- this.muteBtn.appendChild(this.iconHigh.cloneNode(true));
658
- }
659
- }
660
- setVolumeFromX(clientX) {
661
- const rect = this.slider.getBoundingClientRect();
662
- const pct = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
663
- this.player.volume = pct;
664
- if (this.player.muted && pct > 0) {
665
- this.player.muted = false;
666
- }
667
- }
668
- destroy() {
669
- this.slider.removeEventListener("mousedown", this.onSliderMouseDown);
670
- }
671
- };
672
-
673
- // src/utils/time.ts
674
- function formatTime(seconds) {
675
- if (!isFinite(seconds) || seconds < 0) return "0:00";
676
- const h = Math.floor(seconds / 3600);
677
- const m = Math.floor(seconds % 3600 / 60);
678
- const s = Math.floor(seconds % 60);
679
- if (h > 0) {
680
- return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
681
- }
682
- return `${m}:${s.toString().padStart(2, "0")}`;
683
- }
684
- function clamp(value, min, max) {
685
- return Math.min(Math.max(value, min), max);
686
- }
687
-
688
- // src/ui/TimeDisplay.ts
689
- var TimeDisplay = class {
690
- constructor() {
691
- this.currentTime = 0;
692
- this.duration = 0;
693
- this.element = document.createElement("span");
694
- this.element.className = "gallop-time";
695
- this.render();
696
- }
697
- update(currentTime, duration) {
698
- this.currentTime = currentTime;
699
- this.duration = duration;
700
- this.render();
701
- }
702
- render() {
703
- this.element.textContent = `${formatTime(this.currentTime)} / ${formatTime(this.duration)}`;
704
- }
705
- };
706
-
707
- // src/ui/SettingsMenu.ts
708
- var SettingsMenu = class {
709
- constructor(player) {
710
- this.currentView = "main";
711
- this.qualityLevels = [];
712
- this.player = player;
713
- this.button = document.createElement("button");
714
- this.button.className = "gallop-btn";
715
- this.button.setAttribute("aria-label", "Settings");
716
- this.button.appendChild(svgIcon(Icons.settings));
717
- this.button.addEventListener("click", (e) => {
718
- e.stopPropagation();
719
- this.toggle();
720
- });
721
- this.element = document.createElement("div");
722
- this.element.className = "gallop-settings-menu";
723
- this.element.hidden = true;
724
- this.element.addEventListener("click", (e) => e.stopPropagation());
725
- this.renderMain();
726
- }
727
- setQualityLevels(levels) {
728
- this.qualityLevels = levels;
729
- if (this.currentView === "quality") {
730
- this.renderQuality();
731
- } else if (this.currentView === "main") {
732
- this.renderMain();
733
- }
734
- }
735
- toggle() {
736
- if (this.element.hidden) {
737
- this.currentView = "main";
738
- this.renderMain();
739
- this.element.hidden = false;
740
- } else {
741
- this.element.hidden = true;
742
- }
743
- }
744
- close() {
745
- this.element.hidden = true;
746
- this.currentView = "main";
747
- }
748
- renderMain() {
749
- this.element.innerHTML = "";
750
- const qualityItem = this.createItem("Quality", this.getQualityLabel());
751
- qualityItem.addEventListener("click", () => {
752
- this.currentView = "quality";
753
- this.renderQuality();
754
- });
755
- const speedItem = this.createItem("Speed", this.getSpeedLabel());
756
- speedItem.addEventListener("click", () => {
757
- this.currentView = "speed";
758
- this.renderSpeed();
759
- });
760
- this.element.appendChild(qualityItem);
761
- this.element.appendChild(speedItem);
762
- }
763
- renderQuality() {
764
- this.element.innerHTML = "";
765
- const header = this.createHeader("Quality");
766
- this.element.appendChild(header);
767
- const autoItem = this.createSelectItem(
768
- "Auto",
769
- this.player.isAutoQuality()
770
- );
771
- autoItem.addEventListener("click", () => {
772
- this.player.setAutoQuality();
773
- this.close();
774
- });
775
- this.element.appendChild(autoItem);
776
- const sorted = [...this.qualityLevels].sort((a, b) => b.height - a.height);
777
- for (const level of sorted) {
778
- const item = this.createSelectItem(
779
- level.label,
780
- !this.player.isAutoQuality() && level.index === this.player.getCurrentQuality()
781
- );
782
- item.addEventListener("click", () => {
783
- this.player.setQualityLevel(level.index);
784
- this.close();
785
- });
786
- this.element.appendChild(item);
787
- }
788
- }
789
- renderSpeed() {
790
- this.element.innerHTML = "";
791
- const header = this.createHeader("Speed");
792
- this.element.appendChild(header);
793
- for (const speed of SPEED_PRESETS) {
794
- const label = speed === 1 ? "Normal" : `${speed}x`;
795
- const item = this.createSelectItem(label, this.player.playbackRate === speed);
796
- item.addEventListener("click", () => {
797
- this.player.playbackRate = speed;
798
- this.close();
799
- });
800
- this.element.appendChild(item);
801
- }
802
- }
803
- createItem(label, value) {
804
- const item = document.createElement("div");
805
- item.className = "gallop-settings-item";
806
- const labelEl = document.createElement("span");
807
- labelEl.textContent = label;
808
- const valueEl = document.createElement("span");
809
- valueEl.className = "gallop-settings-value";
810
- valueEl.textContent = value;
811
- item.appendChild(labelEl);
812
- item.appendChild(valueEl);
813
- return item;
814
- }
815
- createSelectItem(label, active) {
816
- const item = document.createElement("div");
817
- item.className = "gallop-settings-item" + (active ? " gallop-settings-item-active" : "");
818
- if (active) {
819
- item.appendChild(svgIcon(Icons.check));
820
- } else {
821
- const spacer = document.createElement("span");
822
- spacer.className = "gallop-icon";
823
- item.appendChild(spacer);
824
- }
825
- const labelEl = document.createElement("span");
826
- labelEl.textContent = label;
827
- item.appendChild(labelEl);
828
- return item;
829
- }
830
- createHeader(title) {
831
- const header = document.createElement("div");
832
- header.className = "gallop-settings-header";
833
- header.appendChild(svgIcon(Icons.chevronLeft));
834
- const text = document.createElement("span");
835
- text.textContent = title;
836
- header.appendChild(text);
837
- header.addEventListener("click", () => {
838
- this.currentView = "main";
839
- this.renderMain();
840
- });
841
- return header;
842
- }
843
- getQualityLabel() {
844
- if (this.player.isAutoQuality()) {
845
- const current2 = this.player.getCurrentQuality();
846
- const level2 = this.qualityLevels.find((l) => l.index === current2);
847
- return level2 ? `Auto (${level2.height}p)` : "Auto";
848
- }
849
- const current = this.player.getCurrentQuality();
850
- const level = this.qualityLevels.find((l) => l.index === current);
851
- return level?.label ?? "Auto";
852
- }
853
- getSpeedLabel() {
854
- const rate = this.player.playbackRate;
855
- return rate === 1 ? "Normal" : `${rate}x`;
856
- }
857
- };
858
-
859
- // src/ui/Controls.ts
860
- var Controls = class {
861
- constructor(player, wrapper) {
862
- this.fullscreenBtn = null;
863
- this.hideTimer = null;
864
- this.onActivity = () => {
865
- this.showControls();
866
- this.startHideTimer();
867
- };
868
- this.player = player;
869
- this.wrapper = wrapper;
870
- this.element = document.createElement("div");
871
- this.element.className = "gallop-controls";
872
- this.playIcon = svgIcon(Icons.play);
873
- this.pauseIcon = svgIcon(Icons.pause);
874
- this.fsEnterIcon = svgIcon(Icons.fullscreen);
875
- this.fsExitIcon = svgIcon(Icons.fullscreenExit);
876
- this.progressBar = new ProgressBar(player);
877
- const row = document.createElement("div");
878
- row.className = "gallop-controls-row";
879
- this.playPauseBtn = document.createElement("button");
880
- this.playPauseBtn.className = "gallop-btn";
881
- this.playPauseBtn.setAttribute("aria-label", "Play");
882
- this.playPauseBtn.appendChild(this.playIcon.cloneNode(true));
883
- this.playPauseBtn.addEventListener("click", (e) => {
884
- e.stopPropagation();
885
- player.togglePlay();
886
- });
887
- row.appendChild(this.playPauseBtn);
888
- this.timeDisplay = new TimeDisplay();
889
- row.appendChild(this.timeDisplay.element);
890
- row.appendChild(this.progressBar.element);
891
- this.volumeControl = new VolumeControl(player);
892
- row.appendChild(this.volumeControl.element);
893
- this.settingsMenu = new SettingsMenu(player);
894
- const settingsWrap = document.createElement("div");
895
- settingsWrap.style.position = "relative";
896
- settingsWrap.appendChild(this.settingsMenu.element);
897
- settingsWrap.appendChild(this.settingsMenu.button);
898
- row.appendChild(settingsWrap);
899
- if (supportsFullscreen()) {
900
- this.fullscreenBtn = document.createElement("button");
901
- this.fullscreenBtn.className = "gallop-btn";
902
- this.fullscreenBtn.setAttribute("aria-label", "Fullscreen");
903
- this.fullscreenBtn.appendChild(this.fsEnterIcon.cloneNode(true));
904
- this.fullscreenBtn.addEventListener("click", (e) => {
905
- e.stopPropagation();
906
- player.toggleFullscreen();
907
- });
908
- row.appendChild(this.fullscreenBtn);
909
- }
910
- this.element.appendChild(row);
911
- this.bindEvents();
912
- this.startHideTimer();
913
- }
914
- bindEvents() {
915
- this.player.on("timeupdate", ({ currentTime, duration }) => {
916
- this.timeDisplay.update(currentTime, duration);
917
- this.progressBar.update(currentTime, duration, this.player.buffered);
918
- });
919
- this.player.on("volumechange", ({ volume, muted }) => {
920
- this.volumeControl.update(volume, muted);
921
- });
922
- this.player.on("play", () => this.updatePlayPause(true));
923
- this.player.on("pause", () => this.updatePlayPause(false));
924
- this.player.on("ended", () => this.updatePlayPause(false));
925
- this.player.on("qualitylevels", ({ levels }) => {
926
- this.settingsMenu.setQualityLevels(levels);
927
- });
928
- this.player.on("fullscreenchange", ({ isFullscreen }) => {
929
- if (this.fullscreenBtn) {
930
- this.fullscreenBtn.innerHTML = "";
931
- this.fullscreenBtn.appendChild(
932
- isFullscreen ? this.fsExitIcon.cloneNode(true) : this.fsEnterIcon.cloneNode(true)
933
- );
934
- }
935
- });
936
- this.wrapper.addEventListener("mousemove", this.onActivity);
937
- this.wrapper.addEventListener("mouseenter", this.onActivity);
938
- this.wrapper.addEventListener("mouseleave", () => this.hideControls());
939
- this.wrapper.addEventListener("click", (e) => {
940
- if (e.target === this.player.getVideoElement() || e.target === this.wrapper) {
941
- this.player.togglePlay();
942
- this.settingsMenu.close();
943
- }
944
- });
945
- }
946
- updatePlayPause(playing) {
947
- this.playPauseBtn.innerHTML = "";
948
- this.playPauseBtn.appendChild(
949
- playing ? this.pauseIcon.cloneNode(true) : this.playIcon.cloneNode(true)
950
- );
951
- this.playPauseBtn.setAttribute("aria-label", playing ? "Pause" : "Play");
952
- }
953
- showControls() {
954
- this.element.classList.remove("gallop-controls-hidden");
955
- this.wrapper.style.cursor = "";
956
- }
957
- hideControls() {
958
- if (this.hideTimer) {
959
- clearTimeout(this.hideTimer);
960
- this.hideTimer = null;
961
- }
962
- this.element.classList.add("gallop-controls-hidden");
963
- this.wrapper.style.cursor = "none";
964
- }
965
- startHideTimer() {
966
- if (this.hideTimer) clearTimeout(this.hideTimer);
967
- this.hideTimer = setTimeout(() => this.hideControls(), CONTROLS_HIDE_DELAY);
968
- }
969
- destroy() {
970
- if (this.hideTimer) clearTimeout(this.hideTimer);
971
- this.progressBar.destroy();
972
- this.volumeControl.destroy();
973
- this.wrapper.removeEventListener("mousemove", this.onActivity);
974
- }
975
- };
976
-
977
- // src/ui/BigPlayButton.ts
978
- var BigPlayButton = class {
979
- constructor(onClick) {
980
- this.element = document.createElement("button");
981
- this.element.className = "gallop-big-play";
982
- this.element.setAttribute("aria-label", "Play");
983
- this.element.appendChild(svgIcon(Icons.play));
984
- this.element.addEventListener("click", (e) => {
985
- e.stopPropagation();
986
- onClick();
987
- });
988
- }
989
- setVisible(visible) {
990
- this.element.hidden = !visible;
991
- }
992
- };
993
-
994
- // src/ui/LoadingSpinner.ts
995
- var LoadingSpinner = class {
996
- constructor() {
997
- this.element = document.createElement("div");
998
- this.element.className = "gallop-spinner";
999
- this.element.hidden = true;
1000
- this.element.setAttribute("role", "status");
1001
- this.element.setAttribute("aria-label", "Loading");
1002
- const ring = document.createElement("div");
1003
- ring.className = "gallop-spinner-ring";
1004
- this.element.appendChild(ring);
1005
- }
1006
- setVisible(visible) {
1007
- this.element.hidden = !visible;
1008
- }
1009
- };
1010
-
1011
- // src/ui/ErrorOverlay.ts
1012
- var ErrorOverlay = class {
1013
- constructor(onRetry) {
1014
- this.element = document.createElement("div");
1015
- this.element.className = "gallop-error";
1016
- this.element.hidden = true;
1017
- this.messageEl = document.createElement("div");
1018
- this.messageEl.className = "gallop-error-message";
1019
- this.messageEl.textContent = "An error occurred during playback.";
1020
- this.element.appendChild(this.messageEl);
1021
- const retryBtn = document.createElement("button");
1022
- retryBtn.className = "gallop-error-retry";
1023
- retryBtn.textContent = "Retry";
1024
- retryBtn.addEventListener("click", (e) => {
1025
- e.stopPropagation();
1026
- onRetry();
1027
- });
1028
- this.element.appendChild(retryBtn);
1029
- }
1030
- setVisible(visible) {
1031
- this.element.hidden = !visible;
1032
- }
1033
- setMessage(message) {
1034
- this.messageEl.textContent = message;
1035
- }
1036
- };
1037
-
1038
- // src/ui/PosterImage.ts
1039
- var PosterImage = class {
1040
- constructor() {
1041
- this.element = document.createElement("div");
1042
- this.element.className = "gallop-poster";
1043
- this.element.hidden = true;
1044
- }
1045
- show(url) {
1046
- this.element.style.backgroundImage = `url("${url.replace(/"/g, '\\"')}")`;
1047
- this.element.hidden = false;
1048
- }
1049
- hide() {
1050
- this.element.hidden = true;
1051
- }
1052
- };
1053
-
1054
- // src/ui/ContextMenu.ts
1055
- var ContextMenu = class {
1056
- constructor(wrapper, pageUrl) {
1057
- this.wrapper = wrapper;
1058
- this.onHide = null;
1059
- this.handleContextMenu = (e) => {
1060
- e.preventDefault();
1061
- e.stopPropagation();
1062
- const rect = this.wrapper.getBoundingClientRect();
1063
- let x = e.clientX - rect.left;
1064
- let y = e.clientY - rect.top;
1065
- this.element.hidden = false;
1066
- const menuRect = this.element.getBoundingClientRect();
1067
- if (x + menuRect.width > rect.width) {
1068
- x = rect.width - menuRect.width - 4;
1069
- }
1070
- if (y + menuRect.height > rect.height) {
1071
- y = rect.height - menuRect.height - 4;
1072
- }
1073
- this.element.style.left = `${Math.max(4, x)}px`;
1074
- this.element.style.top = `${Math.max(4, y)}px`;
1075
- };
1076
- this.handleDocumentClick = () => {
1077
- this.hide();
1078
- };
1079
- this.handleDocumentContext = (e) => {
1080
- if (!this.wrapper.contains(e.target)) {
1081
- this.hide();
1082
- }
1083
- };
1084
- const resolvedUrl = pageUrl || window.location.href;
1085
- this.items = [
1086
- {
1087
- label: "About ScaleMule Gallop",
1088
- action: () => {
1089
- window.open("https://www.scalemule.com/gallop", "_blank", "noopener");
1090
- }
1091
- },
1092
- {
1093
- label: "Report a problem",
1094
- action: () => {
1095
- const encoded = encodeURIComponent(resolvedUrl);
1096
- window.open(
1097
- `https://www.scalemule.com/gallop/report?url=${encoded}`,
1098
- "_blank",
1099
- "noopener"
1100
- );
1101
- }
1102
- },
1103
- {
1104
- label: "Copy link",
1105
- action: () => {
1106
- navigator.clipboard?.writeText(resolvedUrl).catch(() => {
1107
- const input = document.createElement("input");
1108
- input.value = resolvedUrl;
1109
- document.body.appendChild(input);
1110
- input.select();
1111
- document.execCommand("copy");
1112
- document.body.removeChild(input);
1113
- });
1114
- }
1115
- }
1116
- ];
1117
- this.element = el("div", { class: "gallop-context-menu" });
1118
- this.element.hidden = true;
1119
- for (const item of this.items) {
1120
- const row = el("div", { class: "gallop-context-menu-item" });
1121
- row.textContent = item.label;
1122
- row.addEventListener("click", (e) => {
1123
- e.stopPropagation();
1124
- item.action();
1125
- this.hide();
1126
- });
1127
- this.element.appendChild(row);
1128
- }
1129
- this.wrapper.addEventListener("contextmenu", this.handleContextMenu);
1130
- document.addEventListener("click", this.handleDocumentClick);
1131
- document.addEventListener("contextmenu", this.handleDocumentContext);
1132
- }
1133
- hide() {
1134
- this.element.hidden = true;
1135
- }
1136
- destroy() {
1137
- this.wrapper.removeEventListener("contextmenu", this.handleContextMenu);
1138
- document.removeEventListener("click", this.handleDocumentClick);
1139
- document.removeEventListener("contextmenu", this.handleDocumentContext);
1140
- this.element.remove();
1141
- }
1142
- };
1143
-
1144
- // src/theme/ThemeManager.ts
1145
- var PROP_MAP = {
1146
- colorPrimary: "--gallop-color-primary",
1147
- colorSecondary: "--gallop-color-secondary",
1148
- colorText: "--gallop-color-text",
1149
- colorBackground: "--gallop-color-background",
1150
- colorBuffered: "--gallop-color-buffered",
1151
- colorProgress: "--gallop-color-progress",
1152
- controlBarBackground: "--gallop-control-bar-bg",
1153
- controlBarHeight: "--gallop-control-bar-height",
1154
- borderRadius: "--gallop-border-radius",
1155
- fontFamily: "--gallop-font-family",
1156
- fontSize: "--gallop-font-size",
1157
- iconSize: "--gallop-icon-size"
1158
- };
1159
- var ThemeManager = class {
1160
- constructor(theme) {
1161
- this.theme = theme;
1162
- }
1163
- apply(element) {
1164
- for (const [key, cssVar] of Object.entries(PROP_MAP)) {
1165
- const value = this.theme[key];
1166
- if (value) {
1167
- element.style.setProperty(cssVar, value);
1168
- }
1169
- }
1170
- }
1171
- update(overrides, element) {
1172
- this.theme = { ...this.theme, ...overrides };
1173
- this.apply(element);
1174
- }
1175
- };
1176
-
1177
- // src/input/KeyboardManager.ts
1178
- var KeyboardManager = class {
1179
- constructor(player) {
1180
- this.player = player;
1181
- this.handler = (e) => {
1182
- const wrapper = player.getWrapperElement();
1183
- if (!wrapper.contains(document.activeElement) && document.activeElement !== wrapper) {
1184
- return;
1185
- }
1186
- const tag = e.target?.tagName;
1187
- if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
1188
- switch (e.key) {
1189
- case " ":
1190
- case "k":
1191
- e.preventDefault();
1192
- player.togglePlay();
1193
- break;
1194
- case "ArrowLeft":
1195
- e.preventDefault();
1196
- player.seekBackward(SEEK_STEP);
1197
- break;
1198
- case "ArrowRight":
1199
- e.preventDefault();
1200
- player.seekForward(SEEK_STEP);
1201
- break;
1202
- case "j":
1203
- e.preventDefault();
1204
- player.seekBackward(SEEK_STEP_LARGE);
1205
- break;
1206
- case "l":
1207
- e.preventDefault();
1208
- player.seekForward(SEEK_STEP_LARGE);
1209
- break;
1210
- case "ArrowUp":
1211
- e.preventDefault();
1212
- player.volume = Math.min(1, player.volume + VOLUME_STEP);
1213
- break;
1214
- case "ArrowDown":
1215
- e.preventDefault();
1216
- player.volume = Math.max(0, player.volume - VOLUME_STEP);
1217
- break;
1218
- case "m":
1219
- e.preventDefault();
1220
- player.toggleMute();
1221
- break;
1222
- case "f":
1223
- e.preventDefault();
1224
- player.toggleFullscreen();
1225
- break;
1226
- case "0":
1227
- case "Home":
1228
- e.preventDefault();
1229
- player.seek(0);
1230
- break;
1231
- case "End":
1232
- e.preventDefault();
1233
- player.seek(player.duration);
1234
- break;
1235
- case "1":
1236
- case "2":
1237
- case "3":
1238
- case "4":
1239
- case "5":
1240
- case "6":
1241
- case "7":
1242
- case "8":
1243
- case "9": {
1244
- e.preventDefault();
1245
- const pct = parseInt(e.key) / 10;
1246
- player.seek(player.duration * pct);
1247
- break;
1248
- }
1249
- case "<":
1250
- e.preventDefault();
1251
- this.cycleSpeed(-1);
1252
- break;
1253
- case ">":
1254
- e.preventDefault();
1255
- this.cycleSpeed(1);
1256
- break;
1257
- }
1258
- };
1259
- document.addEventListener("keydown", this.handler);
1260
- }
1261
- cycleSpeed(direction) {
1262
- const speeds = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
1263
- const current = this.player.playbackRate;
1264
- const idx = speeds.indexOf(current);
1265
- const next = idx + direction;
1266
- if (next >= 0 && next < speeds.length) {
1267
- this.player.playbackRate = speeds[next];
1268
- }
1269
- }
1270
- destroy() {
1271
- document.removeEventListener("keydown", this.handler);
1272
- }
1273
- };
1274
-
1275
- // src/input/TouchManager.ts
1276
- var TouchManager = class {
1277
- constructor(player, wrapper) {
1278
- this.lastTapTime = 0;
1279
- this.lastTapX = 0;
1280
- this.tapTimeout = null;
1281
- this.player = player;
1282
- this.wrapper = wrapper;
1283
- this.handler = (e) => {
1284
- const target = e.target;
1285
- if (target.closest(".gallop-controls") || target.closest(".gallop-big-play")) {
1286
- return;
1287
- }
1288
- const touch = e.changedTouches[0];
1289
- const now = Date.now();
1290
- const timeDiff = now - this.lastTapTime;
1291
- if (timeDiff < DOUBLE_TAP_DELAY) {
1292
- if (this.tapTimeout) {
1293
- clearTimeout(this.tapTimeout);
1294
- this.tapTimeout = null;
1295
- }
1296
- const rect = wrapper.getBoundingClientRect();
1297
- const x = touch.clientX - rect.left;
1298
- const halfWidth = rect.width / 2;
1299
- if (x < halfWidth) {
1300
- player.seekBackward(SEEK_STEP_LARGE);
1301
- } else {
1302
- player.seekForward(SEEK_STEP_LARGE);
1303
- }
1304
- } else {
1305
- this.tapTimeout = setTimeout(() => {
1306
- player.togglePlay();
1307
- this.tapTimeout = null;
1308
- }, DOUBLE_TAP_DELAY);
1309
- }
1310
- this.lastTapTime = now;
1311
- this.lastTapX = touch.clientX;
1312
- };
1313
- wrapper.addEventListener("touchend", this.handler);
1314
- }
1315
- destroy() {
1316
- this.wrapper.removeEventListener("touchend", this.handler);
1317
- if (this.tapTimeout) clearTimeout(this.tapTimeout);
1318
- }
1319
- };
1320
-
1321
- // src/theme/styles.ts
1322
- var PLAYER_STYLES = `
1323
- /* ===== Gallop Player \u2014 ScaleMule Video Player ===== */
1324
-
1325
- /* --- Foundation --- */
1326
- .gallop-player {
1327
- position: relative;
1328
- width: 100%;
1329
- max-width: 100%;
1330
- background: #000;
1331
- overflow: hidden;
1332
- border-radius: var(--gallop-border-radius, 8px);
1333
- font-family: var(--gallop-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif);
1334
- font-size: var(--gallop-font-size, 13px);
1335
- color: #fff;
1336
- user-select: none;
1337
- -webkit-user-select: none;
1338
- outline: none;
1339
- line-height: 1.4;
1340
- }
1341
-
1342
- .gallop-player * {
1343
- box-sizing: border-box;
1344
- }
1345
-
1346
- .gallop-player.gallop-fullscreen {
1347
- border-radius: 0;
1348
- width: 100vw;
1349
- height: 100vh;
1350
- max-width: none;
1351
- aspect-ratio: auto !important;
1352
- }
1353
-
1354
- .gallop-video {
1355
- display: block;
1356
- width: 100%;
1357
- height: 100%;
1358
- object-fit: contain;
1359
- }
1360
-
1361
- /* --- Icon base --- */
1362
- .gallop-icon {
1363
- display: inline-flex;
1364
- align-items: center;
1365
- justify-content: center;
1366
- width: var(--gallop-icon-size, 22px);
1367
- height: var(--gallop-icon-size, 22px);
1368
- flex-shrink: 0;
1369
- }
1370
- .gallop-icon svg {
1371
- width: 100%;
1372
- height: 100%;
1373
- }
1374
-
1375
- /* ===================================================
1376
- BIG PLAY BUTTON \u2014 Signature rounded-rect with gradient
1377
- =================================================== */
1378
- .gallop-big-play {
1379
- position: absolute;
1380
- top: 50%;
1381
- left: 50%;
1382
- transform: translate(-50%, -50%);
1383
- width: 104px;
1384
- height: 72px;
1385
- background: var(--gallop-color-primary, #635bff);
1386
- border: none;
1387
- border-radius: 18px;
1388
- cursor: pointer;
1389
- display: flex;
1390
- align-items: center;
1391
- justify-content: center;
1392
- color: #fff;
1393
- opacity: 0.92;
1394
- transition: opacity 0.25s, transform 0.25s, box-shadow 0.25s;
1395
- z-index: 4;
1396
- padding: 0;
1397
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
1398
- }
1399
-
1400
- .gallop-big-play:hover {
1401
- opacity: 1;
1402
- transform: translate(-50%, -50%) scale(1.06);
1403
- box-shadow: 0 6px 28px rgba(0, 0, 0, 0.4);
1404
- }
1405
-
1406
- .gallop-big-play .gallop-icon {
1407
- width: 40px;
1408
- height: 40px;
1409
- margin-left: 4px;
1410
- filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.15));
1411
- }
1412
-
1413
- .gallop-big-play[hidden] {
1414
- display: none;
1415
- }
1416
-
1417
- /* When controls are visible during pause, dim the big play button slightly */
1418
- .gallop-player[data-status="paused"] .gallop-big-play {
1419
- opacity: 0.85;
1420
- }
1421
-
1422
- /* ===================================================
1423
- LOADING SPINNER \u2014 Brand-colored ring
1424
- =================================================== */
1425
- .gallop-spinner {
1426
- position: absolute;
1427
- top: 50%;
1428
- left: 50%;
1429
- transform: translate(-50%, -50%);
1430
- width: 48px;
1431
- height: 48px;
1432
- z-index: 3;
1433
- }
1434
- .gallop-spinner[hidden] { display: none; }
1435
-
1436
- .gallop-spinner-ring {
1437
- width: 100%;
1438
- height: 100%;
1439
- border: 3px solid rgba(255, 255, 255, 0.15);
1440
- border-top-color: var(--gallop-color-primary, #635bff);
1441
- border-radius: 50%;
1442
- animation: gallop-spin 0.8s linear infinite;
1443
- }
1444
-
1445
- @keyframes gallop-spin {
1446
- to { transform: rotate(360deg); }
1447
- }
1448
-
1449
- /* ===================================================
1450
- POSTER IMAGE
1451
- =================================================== */
1452
- .gallop-poster {
1453
- position: absolute;
1454
- inset: 0;
1455
- z-index: 2;
1456
- background-size: cover;
1457
- background-position: center;
1458
- background-repeat: no-repeat;
1459
- transition: opacity 0.4s ease;
1460
- }
1461
- .gallop-poster[hidden] { display: none; }
1462
-
1463
- /* ===================================================
1464
- ERROR OVERLAY
1465
- =================================================== */
1466
- .gallop-error {
1467
- position: absolute;
1468
- inset: 0;
1469
- z-index: 5;
1470
- background: rgba(0, 0, 0, 0.88);
1471
- display: flex;
1472
- flex-direction: column;
1473
- align-items: center;
1474
- justify-content: center;
1475
- gap: 16px;
1476
- }
1477
- .gallop-error[hidden] { display: none; }
1478
-
1479
- .gallop-error-message {
1480
- font-size: 15px;
1481
- color: rgba(255, 255, 255, 0.75);
1482
- text-align: center;
1483
- max-width: 80%;
1484
- }
1485
-
1486
- .gallop-error-retry {
1487
- padding: 10px 28px;
1488
- background: var(--gallop-color-primary, #635bff);
1489
- color: #fff;
1490
- border: none;
1491
- border-radius: 10px;
1492
- font-size: 14px;
1493
- font-weight: 500;
1494
- cursor: pointer;
1495
- transition: transform 0.2s, box-shadow 0.2s;
1496
- }
1497
- .gallop-error-retry:hover {
1498
- transform: scale(1.04);
1499
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
1500
- }
1501
-
1502
- /* ===================================================
1503
- CONTROL BAR \u2014 Floating rounded pill
1504
- =================================================== */
1505
- .gallop-controls {
1506
- position: absolute;
1507
- bottom: 10px;
1508
- left: 10px;
1509
- right: 10px;
1510
- z-index: 10;
1511
- background: var(--gallop-control-bar-bg, rgba(0, 0, 0, 0.65));
1512
- border-radius: 22px;
1513
- padding: 0;
1514
- opacity: 1;
1515
- transition: opacity 0.35s ease;
1516
- backdrop-filter: blur(12px);
1517
- -webkit-backdrop-filter: blur(12px);
1518
- }
1519
-
1520
- /* Hide controls during active playback (not paused/idle/ready/ended) */
1521
- .gallop-player:not(:hover):not(:focus-within):not([data-status="paused"]):not([data-status="idle"]):not([data-status="ready"]):not([data-status="ended"]) .gallop-controls.gallop-controls-hidden {
1522
- opacity: 0;
1523
- pointer-events: none;
1524
- }
1525
-
1526
- /* Also hide big play button during active playback when controls hidden */
1527
- .gallop-player:not(:hover):not(:focus-within)[data-status="playing"] .gallop-big-play {
1528
- opacity: 0;
1529
- pointer-events: none;
1530
- transition: opacity 0.35s ease;
1531
- }
1532
-
1533
- .gallop-controls-row {
1534
- display: flex;
1535
- align-items: center;
1536
- gap: 6px;
1537
- height: var(--gallop-control-bar-height, 44px);
1538
- padding: 0 6px 0 8px;
1539
- }
1540
-
1541
- /* --- Control Buttons --- */
1542
- .gallop-btn {
1543
- background: none;
1544
- border: none;
1545
- color: rgba(255, 255, 255, 0.9);
1546
- cursor: pointer;
1547
- padding: 6px;
1548
- border-radius: 6px;
1549
- display: flex;
1550
- align-items: center;
1551
- justify-content: center;
1552
- transition: background 0.15s, color 0.15s, transform 0.15s;
1553
- position: relative;
1554
- }
1555
- .gallop-btn:hover {
1556
- background: rgba(255, 255, 255, 0.12);
1557
- color: #fff;
1558
- transform: scale(1.05);
1559
- }
1560
-
1561
- /* ===================================================
1562
- PROGRESS BAR \u2014 Thick, bold, TikTok-inspired
1563
- =================================================== */
1564
- .gallop-progress-container {
1565
- flex: 1;
1566
- min-width: 0;
1567
- padding: 0;
1568
- cursor: pointer;
1569
- display: flex;
1570
- align-items: center;
1571
- }
1572
-
1573
- .gallop-progress-bar {
1574
- position: relative;
1575
- width: 100%;
1576
- height: 4px;
1577
- background: rgba(255, 255, 255, 0.2);
1578
- border-radius: 2px;
1579
- transition: height 0.15s ease;
1580
- }
1581
-
1582
- .gallop-progress-container:hover .gallop-progress-bar {
1583
- height: 6px;
1584
- }
1585
-
1586
- .gallop-progress-buffered {
1587
- position: absolute;
1588
- left: 0;
1589
- top: 0;
1590
- height: 100%;
1591
- background: rgba(255, 255, 255, 0.22);
1592
- border-radius: 2px;
1593
- pointer-events: none;
1594
- }
1595
-
1596
- .gallop-progress-played {
1597
- position: absolute;
1598
- left: 0;
1599
- top: 0;
1600
- height: 100%;
1601
- background: var(--gallop-color-progress, var(--gallop-color-primary, #635bff));
1602
- border-radius: 2px;
1603
- pointer-events: none;
1604
- }
1605
-
1606
- .gallop-progress-thumb {
1607
- position: absolute;
1608
- top: 50%;
1609
- width: 12px;
1610
- height: 12px;
1611
- background: #fff;
1612
- border: 2px solid var(--gallop-color-primary, #635bff);
1613
- border-radius: 50%;
1614
- transform: translate(-50%, -50%);
1615
- opacity: 0;
1616
- transition: opacity 0.15s, transform 0.15s;
1617
- pointer-events: none;
1618
- }
1619
-
1620
- .gallop-progress-container:hover .gallop-progress-thumb {
1621
- opacity: 1;
1622
- transform: translate(-50%, -50%) scale(1.1);
1623
- }
1624
-
1625
- /* ===================================================
1626
- VOLUME
1627
- =================================================== */
1628
- .gallop-volume {
1629
- display: flex;
1630
- align-items: center;
1631
- gap: 4px;
1632
- }
1633
-
1634
- .gallop-volume-slider-wrap {
1635
- width: 0;
1636
- overflow: hidden;
1637
- transition: width 0.2s ease;
1638
- }
1639
- .gallop-volume:hover .gallop-volume-slider-wrap,
1640
- .gallop-volume-slider-wrap.gallop-volume-expanded {
1641
- width: 64px;
1642
- }
1643
-
1644
- .gallop-volume-slider {
1645
- width: 64px;
1646
- height: 4px;
1647
- background: rgba(255, 255, 255, 0.18);
1648
- border-radius: 2px;
1649
- position: relative;
1650
- cursor: pointer;
1651
- }
1652
- .gallop-volume-fill {
1653
- position: absolute;
1654
- left: 0;
1655
- top: 0;
1656
- height: 100%;
1657
- background: rgba(255, 255, 255, 0.85);
1658
- border-radius: 2px;
1659
- pointer-events: none;
1660
- }
1661
-
1662
- /* ===================================================
1663
- TIME DISPLAY
1664
- =================================================== */
1665
- .gallop-time {
1666
- font-size: 12px;
1667
- color: rgba(255, 255, 255, 0.85);
1668
- white-space: nowrap;
1669
- font-variant-numeric: tabular-nums;
1670
- min-width: 40px;
1671
- letter-spacing: 0.02em;
1672
- }
1673
-
1674
- /* Spacer */
1675
- .gallop-spacer { flex: 1; }
1676
-
1677
- /* ===================================================
1678
- SETTINGS MENU
1679
- =================================================== */
1680
- .gallop-settings-menu {
1681
- position: absolute;
1682
- bottom: 100%;
1683
- right: 0;
1684
- margin-bottom: 8px;
1685
- min-width: 200px;
1686
- background: var(--gallop-color-background, rgba(24, 24, 32, 0.92));
1687
- border-radius: 12px;
1688
- padding: 6px 0;
1689
- backdrop-filter: blur(16px);
1690
- -webkit-backdrop-filter: blur(16px);
1691
- z-index: 20;
1692
- max-height: 300px;
1693
- overflow-y: auto;
1694
- border: 1px solid rgba(255, 255, 255, 0.08);
1695
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
1696
- }
1697
- .gallop-settings-menu[hidden] { display: none; }
1698
-
1699
- .gallop-settings-header {
1700
- display: flex;
1701
- align-items: center;
1702
- gap: 8px;
1703
- padding: 8px 14px;
1704
- font-size: 13px;
1705
- font-weight: 600;
1706
- border-bottom: 1px solid rgba(255, 255, 255, 0.08);
1707
- cursor: pointer;
1708
- color: rgba(255, 255, 255, 0.9);
1709
- }
1710
- .gallop-settings-header .gallop-icon {
1711
- width: 18px;
1712
- height: 18px;
1713
- }
1714
-
1715
- .gallop-settings-item {
1716
- display: flex;
1717
- align-items: center;
1718
- justify-content: space-between;
1719
- padding: 8px 16px;
1720
- cursor: pointer;
1721
- transition: background 0.12s;
1722
- font-size: 13px;
1723
- gap: 12px;
1724
- color: rgba(255, 255, 255, 0.8);
1725
- }
1726
- .gallop-settings-item:hover {
1727
- background: rgba(255, 255, 255, 0.08);
1728
- }
1729
-
1730
- .gallop-settings-item-active .gallop-icon {
1731
- color: var(--gallop-color-primary, #635bff);
1732
- }
1733
-
1734
- .gallop-settings-value {
1735
- color: rgba(255, 255, 255, 0.5);
1736
- font-size: 12px;
1737
- }
1738
-
1739
- /* ===================================================
1740
- CONTEXT MENU
1741
- =================================================== */
1742
- .gallop-context-menu {
1743
- position: absolute;
1744
- z-index: 30;
1745
- min-width: 180px;
1746
- background: var(--gallop-color-background, rgba(24, 24, 32, 0.94));
1747
- border-radius: 10px;
1748
- padding: 4px 0;
1749
- backdrop-filter: blur(16px);
1750
- -webkit-backdrop-filter: blur(16px);
1751
- border: 1px solid rgba(255, 255, 255, 0.08);
1752
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45);
1753
- }
1754
- .gallop-context-menu[hidden] { display: none; }
1755
-
1756
- .gallop-context-menu-item {
1757
- padding: 9px 14px;
1758
- font-size: 13px;
1759
- color: rgba(255, 255, 255, 0.85);
1760
- cursor: pointer;
1761
- transition: background 0.12s;
1762
- white-space: nowrap;
1763
- }
1764
- .gallop-context-menu-item:hover {
1765
- background: rgba(255, 255, 255, 0.08);
1766
- }
1767
-
1768
- /* ===================================================
1769
- GALLOP BRANDING WATERMARK
1770
- =================================================== */
1771
- .gallop-brand {
1772
- position: absolute;
1773
- top: 12px;
1774
- right: 12px;
1775
- z-index: 6;
1776
- display: flex;
1777
- align-items: center;
1778
- gap: 5px;
1779
- padding: 4px 10px;
1780
- background: rgba(0, 0, 0, 0.35);
1781
- border-radius: 6px;
1782
- backdrop-filter: blur(8px);
1783
- -webkit-backdrop-filter: blur(8px);
1784
- opacity: 0;
1785
- transition: opacity 0.35s ease;
1786
- pointer-events: none;
1787
- font-size: 11px;
1788
- font-weight: 600;
1789
- letter-spacing: 0.04em;
1790
- color: rgba(255, 255, 255, 0.7);
1791
- text-transform: uppercase;
1792
- }
1793
-
1794
- .gallop-brand-dot {
1795
- width: 6px;
1796
- height: 6px;
1797
- border-radius: 50%;
1798
- background: var(--gallop-color-primary, #635bff);
1799
- flex-shrink: 0;
1800
- }
1801
-
1802
- /* Show branding on hover */
1803
- .gallop-player:hover .gallop-brand,
1804
- .gallop-player:focus-within .gallop-brand,
1805
- .gallop-player[data-status="paused"] .gallop-brand,
1806
- .gallop-player[data-status="idle"] .gallop-brand,
1807
- .gallop-player[data-status="ready"] .gallop-brand,
1808
- .gallop-player[data-status="ended"] .gallop-brand {
1809
- opacity: 1;
1810
- pointer-events: auto;
1811
- }
1812
- `;
1813
-
1814
- // src/analytics/AnalyticsCollector.ts
1815
- var DEFAULTS = {
1816
- flushIntervalMs: 3e3,
1817
- maxBatchSize: 20,
1818
- maxQueueSize: 300,
1819
- progressIntervalSeconds: 10
1820
- };
1821
- var AnalyticsCollector = class {
1822
- constructor(options) {
1823
- this.queue = [];
1824
- this.flushTimer = null;
1825
- this.flushing = false;
1826
- this.destroyed = false;
1827
- this.playRequestedAtMs = null;
1828
- this.ttffMs = null;
1829
- this.firstFrameSeen = false;
1830
- this.lastProgressPosition = 0;
1831
- this.maxPositionSeen = 0;
1832
- this.watchedSeconds = 0;
1833
- this.lastHeartbeatPosition = 0;
1834
- this.bufferStartedAtMs = null;
1835
- this.totalBufferMs = 0;
1836
- this.startupQuality = null;
1837
- this.qualitySwitches = 0;
1838
- this.lastQuality = null;
1839
- this.lastEngineStats = null;
1840
- this.cdnNode = null;
1841
- this.cdnCacheStatus = null;
1842
- this.cdnRequestID = null;
1843
- this.initialDroppedFrames = null;
1844
- this.droppedFrames = 0;
1845
- this.isVisible = true;
1846
- this.observer = null;
1847
- this.onPlay = () => this.handlePlay();
1848
- this.onPause = () => this.handlePause();
1849
- this.onEnded = () => this.handleEnded();
1850
- this.onSeeked = ({ time }) => this.handleSeeked(time);
1851
- this.onTimeUpdate = ({ currentTime }) => this.handleTimeUpdate(currentTime);
1852
- this.onBuffering = ({ isBuffering }) => this.handleBuffering(isBuffering);
1853
- this.onQualityChange = ({ level }) => this.handleQualityChange(level);
1854
- this.onError = ({ code, message }) => this.handleError(code, message);
1855
- this.onVisibilityChange = () => {
1856
- if (document.visibilityState === "hidden") {
1857
- this.enqueue("pause", this.player.currentTime, { event_subtype: "document_hidden" }, true);
1858
- void this.flush(true);
1859
- }
1860
- };
1861
- this.onPageHide = () => {
1862
- this.enqueue("pause", this.player.currentTime, { event_subtype: "pagehide" }, true);
1863
- void this.flush(true);
1864
- };
1865
- this.client = options.client;
1866
- this.player = options.player;
1867
- this.videoId = options.videoId;
1868
- this.config = options.config ?? {};
1869
- this.sessionId = this.config.sessionId ?? createSessionId();
1870
- this.bind();
1871
- this.start();
1872
- this.initVisibilityTracking();
1873
- }
1874
- setVideoId(videoId) {
1875
- this.videoId = videoId;
1876
- }
1877
- onEngineStats(stats) {
1878
- this.lastEngineStats = stats;
1879
- if (stats.cdnNode) this.cdnNode = stats.cdnNode;
1880
- if (stats.cdnCacheStatus) this.cdnCacheStatus = stats.cdnCacheStatus;
1881
- if (stats.cdnRequestID) this.cdnRequestID = stats.cdnRequestID;
1882
- if (stats.kind === "periodic" && stats.droppedFrames !== void 0) {
1883
- if (this.initialDroppedFrames === null) {
1884
- this.initialDroppedFrames = stats.droppedFrames;
1885
- } else {
1886
- this.droppedFrames = stats.droppedFrames - this.initialDroppedFrames;
1887
- }
1888
- }
1889
- }
1890
- trackEvent(eventType, timestampSeconds, metadata = {}, urgent = false) {
1891
- this.enqueue(eventType, timestampSeconds, metadata, urgent);
1892
- }
1893
- async destroy() {
1894
- if (this.destroyed) return;
1895
- if (this.observer) {
1896
- this.observer.disconnect();
1897
- this.observer = null;
1898
- }
1899
- this.unbind();
1900
- if (this.bufferStartedAtMs !== null) {
1901
- const durationMs = Date.now() - this.bufferStartedAtMs;
1902
- this.totalBufferMs += Math.max(0, durationMs);
1903
- this.bufferStartedAtMs = null;
1904
- }
1905
- this.enqueue("pause", this.player.currentTime, { event_subtype: "destroy" }, true);
1906
- await this.flush(true);
1907
- if (this.flushTimer) {
1908
- clearInterval(this.flushTimer);
1909
- this.flushTimer = null;
1910
- }
1911
- this.destroyed = true;
1912
- }
1913
- bind() {
1914
- this.player.on("play", this.onPlay);
1915
- this.player.on("pause", this.onPause);
1916
- this.player.on("ended", this.onEnded);
1917
- this.player.on("seeked", this.onSeeked);
1918
- this.player.on("timeupdate", this.onTimeUpdate);
1919
- this.player.on("buffering", this.onBuffering);
1920
- this.player.on("qualitychange", this.onQualityChange);
1921
- this.player.on("error", this.onError);
1922
- if (typeof document !== "undefined") {
1923
- document.addEventListener("visibilitychange", this.onVisibilityChange);
1924
- }
1925
- if (typeof window !== "undefined") {
1926
- window.addEventListener("pagehide", this.onPageHide);
1927
- }
1928
- }
1929
- unbind() {
1930
- this.player.off("play", this.onPlay);
1931
- this.player.off("pause", this.onPause);
1932
- this.player.off("ended", this.onEnded);
1933
- this.player.off("seeked", this.onSeeked);
1934
- this.player.off("timeupdate", this.onTimeUpdate);
1935
- this.player.off("buffering", this.onBuffering);
1936
- this.player.off("qualitychange", this.onQualityChange);
1937
- this.player.off("error", this.onError);
1938
- if (typeof document !== "undefined") {
1939
- document.removeEventListener("visibilitychange", this.onVisibilityChange);
1940
- }
1941
- if (typeof window !== "undefined") {
1942
- window.removeEventListener("pagehide", this.onPageHide);
1943
- }
1944
- }
1945
- start() {
1946
- this.flushTimer = setInterval(() => {
1947
- void this.flush(false);
1948
- }, this.config.flushIntervalMs ?? DEFAULTS.flushIntervalMs);
1949
- }
1950
- handlePlay() {
1951
- this.playRequestedAtMs = Date.now();
1952
- this.enqueue("play", this.player.currentTime);
1953
- }
1954
- handlePause() {
1955
- this.enqueue("pause", this.player.currentTime);
1956
- void this.flush(false);
1957
- }
1958
- handleEnded() {
1959
- this.enqueue("complete", this.player.currentTime, {
1960
- completion_ratio: safeRatio(this.player.currentTime, this.player.duration)
1961
- }, true);
1962
- void this.flush(false);
1963
- }
1964
- handleSeeked(time) {
1965
- this.lastProgressPosition = time;
1966
- this.maxPositionSeen = Math.max(this.maxPositionSeen, time);
1967
- this.enqueue("seek", time);
1968
- }
1969
- handleTimeUpdate(currentTime) {
1970
- if (!Number.isFinite(currentTime)) {
1971
- return;
1972
- }
1973
- if (!this.firstFrameSeen && this.playRequestedAtMs !== null) {
1974
- this.firstFrameSeen = true;
1975
- this.ttffMs = Math.max(0, Date.now() - this.playRequestedAtMs);
1976
- }
1977
- if (this.lastProgressPosition > 0) {
1978
- const delta = currentTime - this.lastProgressPosition;
1979
- if (delta > 0 && delta < 5) {
1980
- this.watchedSeconds += delta;
1981
- }
1982
- }
1983
- this.lastProgressPosition = currentTime;
1984
- this.maxPositionSeen = Math.max(this.maxPositionSeen, currentTime);
1985
- const progressInterval = this.config.progressIntervalSeconds ?? DEFAULTS.progressIntervalSeconds;
1986
- if (Math.abs(currentTime - this.lastHeartbeatPosition) >= progressInterval) {
1987
- this.lastHeartbeatPosition = currentTime;
1988
- this.enqueue("play", currentTime, { event_subtype: "heartbeat" });
1989
- }
1990
- }
1991
- initVisibilityTracking() {
1992
- if (this.config.trackVisibility === false || typeof IntersectionObserver === "undefined") {
1993
- return;
1994
- }
1995
- this.observer = new IntersectionObserver((entries) => {
1996
- const entry = entries[0];
1997
- if (entry) {
1998
- const wasVisible = this.isVisible;
1999
- this.isVisible = entry.isIntersecting;
2000
- if (wasVisible !== this.isVisible) {
2001
- this.enqueue("play", this.player.currentTime, {
2002
- event_subtype: "visibility_change",
2003
- is_visible: this.isVisible,
2004
- intersection_ratio: round(entry.intersectionRatio, 3)
2005
- });
2006
- }
2007
- }
2008
- }, { threshold: [0, 0.25, 0.5, 0.75, 1] });
2009
- const el2 = this.player.getWrapperElement();
2010
- if (el2) {
2011
- this.observer.observe(el2);
2012
- }
2013
- }
2014
- handleBuffering(isBuffering) {
2015
- if (isBuffering) {
2016
- if (this.bufferStartedAtMs !== null) return;
2017
- this.bufferStartedAtMs = Date.now();
2018
- this.enqueue("buffer", this.player.currentTime, { buffering_state: "start" });
2019
- return;
2020
- }
2021
- if (this.bufferStartedAtMs === null) return;
2022
- const durationMs = Math.max(0, Date.now() - this.bufferStartedAtMs);
2023
- this.totalBufferMs += durationMs;
2024
- this.bufferStartedAtMs = null;
2025
- this.enqueue("buffer", this.player.currentTime, {
2026
- buffering_state: "end",
2027
- buffering_duration_ms: Math.round(durationMs)
2028
- });
2029
- }
2030
- handleQualityChange(level) {
2031
- const label = level.label || `${level.height}p`;
2032
- if (!this.startupQuality) {
2033
- this.startupQuality = label;
2034
- }
2035
- if (this.lastQuality && this.lastQuality !== label) {
2036
- this.qualitySwitches += 1;
2037
- }
2038
- this.lastQuality = label;
2039
- this.enqueue("play", this.player.currentTime, {
2040
- event_subtype: "quality_change",
2041
- quality_label: label,
2042
- quality_bitrate: level.bitrate,
2043
- quality_height: level.height,
2044
- quality_width: level.width
2045
- });
2046
- }
2047
- handleError(code, message) {
2048
- this.enqueue("error", this.player.currentTime, {
2049
- error_code: code,
2050
- error_message: message,
2051
- error_classification: classifyError(code, this.lastEngineStats)
2052
- }, true);
2053
- void this.flush(false);
2054
- }
2055
- enqueue(eventType, timestampSeconds, metadata = {}, urgent = false) {
2056
- if (!this.videoId) {
2057
- return;
2058
- }
2059
- const quality = this.resolveQuality();
2060
- const payload = {
2061
- session_id: this.sessionId,
2062
- event_type: eventType,
2063
- timestamp_seconds: Number.isFinite(timestampSeconds) ? round(timestampSeconds, 3) : void 0,
2064
- quality: quality ?? void 0,
2065
- metadata: this.buildMetadata(metadata)
2066
- };
2067
- this.queue.push(payload);
2068
- const maxQueue = this.config.maxQueueSize ?? DEFAULTS.maxQueueSize;
2069
- if (this.queue.length > maxQueue) {
2070
- this.queue.splice(0, this.queue.length - maxQueue);
2071
- }
2072
- if (this.config.debug) {
2073
- console.debug("[Gallop analytics] queued event", payload);
2074
- }
2075
- if (urgent) {
2076
- void this.flush(false);
2077
- }
2078
- }
2079
- async flush(keepalive) {
2080
- if (this.flushing || this.queue.length === 0) {
2081
- return;
2082
- }
2083
- this.flushing = true;
2084
- const maxBatchSize = this.config.maxBatchSize ?? DEFAULTS.maxBatchSize;
2085
- try {
2086
- while (this.queue.length > 0) {
2087
- const batch = this.queue.splice(0, maxBatchSize);
2088
- for (let i = 0; i < batch.length; i++) {
2089
- try {
2090
- await this.client.trackPlayback(this.videoId, batch[i], { keepalive });
2091
- } catch (err) {
2092
- if (this.config.debug) {
2093
- console.warn("[Gallop analytics] failed to send event", { event: batch[i], err });
2094
- }
2095
- this.queue.unshift(...batch.slice(i));
2096
- return;
2097
- }
2098
- }
2099
- }
2100
- } finally {
2101
- this.flushing = false;
2102
- }
2103
- }
2104
- buildMetadata(overrides) {
2105
- const watchSeconds = round(this.watchedSeconds, 3);
2106
- const currentTime = round(this.player.currentTime, 3);
2107
- const duration = round(this.player.duration, 3);
2108
- const rebufferRatio = safeRatio(this.totalBufferMs / 1e3, this.watchedSeconds);
2109
- const buffered = this.player.buffered;
2110
- let bufferDepth = 0;
2111
- for (let i = 0; i < buffered.length; i++) {
2112
- if (currentTime >= buffered.start(i) && currentTime <= buffered.end(i)) {
2113
- bufferDepth = buffered.end(i) - currentTime;
2114
- break;
2115
- }
2116
- }
2117
- const metadata = {
2118
- ...this.config.metadata ?? {},
2119
- ...overrides,
2120
- current_time_seconds: currentTime,
2121
- duration_seconds: duration,
2122
- watched_seconds: watchSeconds,
2123
- max_position_seconds: round(this.maxPositionSeen, 3),
2124
- watch_through_ratio: safeRatio(this.maxPositionSeen, this.player.duration),
2125
- completion_ratio: safeRatio(this.player.currentTime, this.player.duration),
2126
- ttff_ms: this.ttffMs,
2127
- total_buffer_ms: Math.round(this.totalBufferMs),
2128
- rebuffer_ratio: rebufferRatio,
2129
- buffer_depth_seconds: round(bufferDepth, 3),
2130
- quality_switches: this.qualitySwitches,
2131
- startup_quality: this.startupQuality,
2132
- dropped_frames: this.droppedFrames,
2133
- is_visible: this.isVisible,
2134
- cdn_node: this.cdnNode,
2135
- cdn_cache_status: this.cdnCacheStatus,
2136
- cdn_request_id: this.cdnRequestID,
2137
- playback_rate: this.player.playbackRate,
2138
- muted: this.player.muted,
2139
- volume: round(this.player.volume, 3),
2140
- status: this.player.status,
2141
- viewport_width: typeof window !== "undefined" ? window.innerWidth : void 0,
2142
- viewport_height: typeof window !== "undefined" ? window.innerHeight : void 0,
2143
- device_pixel_ratio: typeof window !== "undefined" ? window.devicePixelRatio : void 0,
2144
- hls_bandwidth_estimate_bps: this.lastEngineStats?.bandwidthEstimate,
2145
- hls_stats_kind: this.lastEngineStats?.kind,
2146
- hls_level: this.lastEngineStats?.level,
2147
- hls_fragment_duration: this.lastEngineStats?.fragmentDuration,
2148
- hls_fragment_size_bytes: this.lastEngineStats?.fragmentSizeBytes,
2149
- hls_fragment_load_ms: this.lastEngineStats?.fragmentLoadMs,
2150
- hls_error_type: this.lastEngineStats?.errorType,
2151
- hls_error_details: this.lastEngineStats?.errorDetails,
2152
- hls_error_fatal: this.lastEngineStats?.fatal,
2153
- stats_source: this.lastEngineStats?.statsSource,
2154
- tao_available: this.lastEngineStats?.taoAvailable
2155
- };
2156
- if (this.config.includeNetworkInfo ?? true) {
2157
- const networkInfo = getNetworkInfo();
2158
- metadata.connection_effective_type = networkInfo.effectiveType;
2159
- metadata.connection_downlink_mbps = networkInfo.downlink;
2160
- metadata.connection_rtt_ms = networkInfo.rtt;
2161
- metadata.connection_save_data = networkInfo.saveData;
2162
- }
2163
- if (this.config.includeDeviceInfo ?? true) {
2164
- metadata.user_agent = typeof navigator !== "undefined" ? navigator.userAgent : void 0;
2165
- metadata.language = typeof navigator !== "undefined" ? navigator.language : void 0;
2166
- metadata.platform = typeof navigator !== "undefined" ? navigator.platform : void 0;
2167
- metadata.device_memory_gb = typeof navigator !== "undefined" ? navigator.deviceMemory : void 0;
2168
- metadata.hardware_concurrency = typeof navigator !== "undefined" ? navigator.hardwareConcurrency : void 0;
2169
- metadata.screen_width = typeof screen !== "undefined" ? screen.width : void 0;
2170
- metadata.screen_height = typeof screen !== "undefined" ? screen.height : void 0;
2171
- }
2172
- return removeUndefined(metadata);
2173
- }
2174
- resolveQuality() {
2175
- const active = this.player.getQualityLevels().find((level) => level.active);
2176
- if (active) {
2177
- return active.label || `${active.height}p`;
2178
- }
2179
- if (this.lastQuality) {
2180
- return this.lastQuality;
2181
- }
2182
- const currentIndex = this.player.getCurrentQuality();
2183
- if (currentIndex >= 0) {
2184
- return `level_${currentIndex}`;
2185
- }
2186
- return null;
2187
- }
2188
- };
2189
- function getNetworkInfo() {
2190
- if (typeof navigator === "undefined") {
2191
- return {};
2192
- }
2193
- const connection = navigator.connection;
2194
- if (!connection) {
2195
- return {};
2196
- }
2197
- return {
2198
- effectiveType: connection.effectiveType,
2199
- downlink: connection.downlink,
2200
- rtt: connection.rtt,
2201
- saveData: connection.saveData
2202
- };
2203
- }
2204
- function classifyError(code, stats) {
2205
- const lowered = code.toLowerCase();
2206
- if (lowered.includes("network") || stats?.errorType?.toLowerCase().includes("network")) {
2207
- return "network";
2208
- }
2209
- if (lowered.includes("media") || stats?.errorType?.toLowerCase().includes("media")) {
2210
- return "media";
2211
- }
2212
- return "unknown";
2213
- }
2214
- function createSessionId() {
2215
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
2216
- return crypto.randomUUID();
2217
- }
2218
- return `sess_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
2219
- }
2220
- function round(value, digits) {
2221
- if (!Number.isFinite(value)) {
2222
- return 0;
2223
- }
2224
- const factor = 10 ** digits;
2225
- return Math.round(value * factor) / factor;
2226
- }
2227
- function safeRatio(numerator, denominator) {
2228
- if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator <= 0) {
2229
- return 0;
2230
- }
2231
- return round(numerator / denominator, 4);
2232
- }
2233
- function removeUndefined(metadata) {
2234
- return Object.fromEntries(
2235
- Object.entries(metadata).filter(([, value]) => value !== void 0)
2236
- );
2237
- }
2238
-
2239
- // src/utils/csp.ts
2240
- function resolveNonce(explicitNonce) {
2241
- if (explicitNonce) return explicitNonce;
2242
- if (typeof document !== "undefined" && document.currentScript instanceof HTMLScriptElement && document.currentScript.nonce) {
2243
- return document.currentScript.nonce;
2244
- }
2245
- if (typeof document !== "undefined") {
2246
- const el2 = document.querySelector("script[nonce], style[nonce]");
2247
- if (el2) {
2248
- return el2.nonce || el2.getAttribute("nonce") || void 0;
2249
- }
2250
- }
2251
- return void 0;
2252
- }
2253
- function detectCSPFailure(styleEl, onFailure) {
2254
- if (typeof document === "undefined") return;
2255
- const violationHandler = (e) => {
2256
- if (e.blockedURI === "inline" || e.violatedDirective.startsWith("style-src")) {
2257
- onFailure(`CSP blocked style injection: ${e.violatedDirective}`);
2258
- cleanup();
2259
- }
2260
- };
2261
- document.addEventListener("securitypolicyviolation", violationHandler);
2262
- requestAnimationFrame(() => {
2263
- const testEl = styleEl.parentElement?.querySelector(".gallop-player");
2264
- if (testEl) {
2265
- const computed = getComputedStyle(testEl);
2266
- if (computed.position === "static") {
2267
- onFailure("CSP may have blocked style injection (computed style mismatch)");
2268
- cleanup();
2269
- }
2270
- }
2271
- });
2272
- setTimeout(() => {
2273
- if (!styleEl.sheet) {
2274
- onFailure("Style sheet not applied (sheet is null)");
2275
- cleanup();
2276
- }
2277
- }, 100);
2278
- const cleanup = () => {
2279
- document.removeEventListener("securitypolicyviolation", violationHandler);
2280
- };
2281
- setTimeout(cleanup, 2e3);
2282
- }
2283
-
2284
- // src/debug/DebugOverlay.ts
2285
- var DebugOverlay = class {
2286
- constructor(parent, config, getDiagnostics) {
2287
- this.parent = parent;
2288
- this.config = config;
2289
- this.getDiagnostics = getDiagnostics;
2290
- this.isExpanded = false;
2291
- this.container = document.createElement("div");
2292
- this.container.className = "gallop-debug-overlay";
2293
- this.container.setAttribute("aria-hidden", "true");
2294
- this.container.style.cssText = `
2295
- position: absolute;
2296
- top: 10px;
2297
- right: 10px;
2298
- z-index: 9999;
2299
- background: rgba(0, 0, 0, 0.8);
2300
- color: #00ff00;
2301
- font-family: monospace;
2302
- font-size: 10px;
2303
- padding: 5px;
2304
- border-radius: 3px;
2305
- pointer-events: auto;
2306
- max-width: 300px;
2307
- max-height: 80%;
2308
- overflow-y: auto;
2309
- border: 1px solid #333;
2310
- `;
2311
- this.contentEl = document.createElement("div");
2312
- this.container.appendChild(this.contentEl);
2313
- const toggleBtn = document.createElement("div");
2314
- toggleBtn.textContent = "[DEBUG]";
2315
- toggleBtn.style.cursor = "pointer";
2316
- toggleBtn.onclick = () => this.toggle();
2317
- this.container.insertBefore(toggleBtn, this.contentEl);
2318
- this.parent.appendChild(this.container);
2319
- this.update();
2320
- setInterval(() => this.update(), 1e3);
2321
- }
2322
- toggle() {
2323
- this.isExpanded = !this.isExpanded;
2324
- this.container.setAttribute("aria-hidden", (!this.isExpanded).toString());
2325
- if (this.isExpanded) {
2326
- this.container.setAttribute("role", "log");
2327
- } else {
2328
- this.container.removeAttribute("role");
2329
- }
2330
- this.update();
2331
- }
2332
- update() {
2333
- if (!this.isExpanded) {
2334
- this.contentEl.innerHTML = "";
2335
- this.container.style.width = "auto";
2336
- return;
2337
- }
2338
- const diag = this.getDiagnostics();
2339
- const html = `
2340
- <div style="margin-top: 5px; border-top: 1px solid #444; padding-top: 5px;">
2341
- <strong>System</strong><br>
2342
- v: ${this.config.version}<br>
2343
- mode: ${this.config.mode}<br>
2344
- engine: ${this.config.engineType}<br>
2345
- nonce: ${this.config.nonceStatus}<br>
2346
- csp: ${this.config.cspStatus}<br>
2347
- conn: ${this.config.connectionState || "n/a"}<br>
2348
- </div>
2349
- <div style="margin-top: 5px; border-top: 1px solid #444; padding-top: 5px;">
2350
- <strong>Performance</strong><br>
2351
- bitrate: ${(diag.bitrate / 1e6).toFixed(2)} Mbps<br>
2352
- buffer: ${diag.bufferLength.toFixed(1)}s<br>
2353
- fps: ${diag.fps}<br>
2354
- dropped: ${diag.droppedFrames}<br>
2355
- </div>
2356
- <div style="margin-top: 5px; border-top: 1px solid #444; padding-top: 5px;">
2357
- <button onclick="navigator.clipboard.writeText(JSON.stringify(window.GallopDiagnostics))" style="font-size: 9px; cursor: pointer;">
2358
- Copy JSON Diagnostics
2359
- </button>
2360
- </div>
2361
- `;
2362
- this.contentEl.innerHTML = html;
2363
- window.GallopDiagnostics = diag;
2364
- }
2365
- destroy() {
2366
- this.container.remove();
2367
- }
2368
- };
2369
-
2370
- // src/version.ts
2371
- var GALLOP_VERSION = "0.0.1";
2372
-
2373
- // src/core/GallopPlayerCore.ts
2374
- var GallopPlayerCore = class extends EventEmitter {
2375
- constructor(container, config = {}) {
2376
- super();
2377
- this.engine = null;
2378
- this.client = null;
2379
- this.controls = null;
2380
- this.bigPlayButton = null;
2381
- this.loadingSpinner = null;
2382
- this.errorOverlay = null;
2383
- this.posterImage = null;
2384
- this.contextMenu = null;
2385
- this.keyboardManager = null;
2386
- this.touchManager = null;
2387
- this.analyticsCollector = null;
2388
- this.styleEl = null;
2389
- this.debugOverlay = null;
2390
- this.cspStatus = "pending";
2391
- this.nonceStatus = "none";
2392
- this.destroyed = false;
2393
- this.engineStats = null;
2394
- this.container = container;
2395
- this.config = config;
2396
- this.state = new PlayerState((status) => {
2397
- this.emit("statuschange", { status });
2398
- this.updateUIState();
2399
- });
2400
- this.themeManager = new ThemeManager({ ...DEFAULT_THEME, ...config.theme });
2401
- if (config.apiKey || config.embedToken) {
2402
- this.client = new ScaleMuleClient({
2403
- apiKey: config.apiKey,
2404
- embedToken: config.embedToken,
2405
- baseUrl: config.apiBaseUrl
2406
- });
2407
- }
2408
- this.createDOM();
2409
- this.bindVideoEvents();
2410
- if (config.controls !== false) {
2411
- this.mountUI();
2412
- }
2413
- if (config.keyboard !== false) {
2414
- this.keyboardManager = new KeyboardManager(this);
2415
- }
2416
- if (config.touch !== false) {
2417
- this.touchManager = new TouchManager(this, this.wrapper);
2418
- }
2419
- this.initializeAnalytics();
2420
- if (this.config.debug) {
2421
- this.initializeDebugOverlay();
2422
- }
2423
- if (config.videoId && this.client) {
2424
- void this.loadVideoById(config.videoId);
2425
- } else if (config.src) {
2426
- void this.loadSource(config.src);
2427
- }
2428
- }
2429
- // --- DOM Setup ---
2430
- createDOM() {
2431
- this.styleEl = document.createElement("style");
2432
- const nonce = resolveNonce(this.config.nonce);
2433
- if (nonce) {
2434
- this.styleEl.nonce = nonce;
2435
- this.nonceStatus = this.config.nonce ? "explicit" : "auto";
2436
- }
2437
- this.styleEl.textContent = PLAYER_STYLES;
2438
- this.container.appendChild(this.styleEl);
2439
- detectCSPFailure(this.styleEl, (msg) => {
2440
- this.cspStatus = "blocked";
2441
- this.emit("error", { code: "CSP_BLOCKED", message: msg });
2442
- });
2443
- if (this.cspStatus === "pending") {
2444
- this.cspStatus = "applied";
2445
- }
2446
- this.wrapper = document.createElement("div");
2447
- this.wrapper.className = "gallop-player";
2448
- this.wrapper.setAttribute("tabindex", "0");
2449
- this.themeManager.apply(this.wrapper);
2450
- const aspectRatio = this.config.aspectRatio ?? DEFAULT_CONFIG.aspectRatio;
2451
- const [w, h] = aspectRatio.split(":").map(Number);
2452
- if (w && h) {
2453
- this.wrapper.style.aspectRatio = `${w} / ${h}`;
2454
- }
2455
- this.video = document.createElement("video");
2456
- this.video.className = "gallop-video";
2457
- this.video.playsInline = true;
2458
- this.video.preload = "metadata";
2459
- if (this.config.muted ?? DEFAULT_CONFIG.muted) {
2460
- this.video.muted = true;
2461
- }
2462
- if (this.config.loop ?? DEFAULT_CONFIG.loop) {
2463
- this.video.loop = true;
2464
- }
2465
- this.wrapper.appendChild(this.video);
2466
- this.container.appendChild(this.wrapper);
2467
- }
2468
- mountUI() {
2469
- this.posterImage = new PosterImage();
2470
- this.wrapper.appendChild(this.posterImage.element);
2471
- this.bigPlayButton = new BigPlayButton(() => this.togglePlay());
2472
- this.wrapper.appendChild(this.bigPlayButton.element);
2473
- this.loadingSpinner = new LoadingSpinner();
2474
- this.wrapper.appendChild(this.loadingSpinner.element);
2475
- this.errorOverlay = new ErrorOverlay(() => this.retry());
2476
- this.wrapper.appendChild(this.errorOverlay.element);
2477
- this.controls = new Controls(this, this.wrapper);
2478
- this.wrapper.appendChild(this.controls.element);
2479
- this.contextMenu = new ContextMenu(this.wrapper, this.config.pageUrl);
2480
- this.wrapper.appendChild(this.contextMenu.element);
2481
- const brand = document.createElement("div");
2482
- brand.className = "gallop-brand";
2483
- const dot = document.createElement("span");
2484
- dot.className = "gallop-brand-dot";
2485
- brand.appendChild(dot);
2486
- brand.appendChild(document.createTextNode("Gallop"));
2487
- this.wrapper.appendChild(brand);
2488
- if (this.config.poster) {
2489
- this.posterImage.show(this.config.poster);
2490
- }
2491
- }
2492
- bindVideoEvents() {
2493
- const v = this.video;
2494
- v.addEventListener("play", () => {
2495
- this.state.transition("playing");
2496
- this.emit("play");
2497
- });
2498
- v.addEventListener("pause", () => {
2499
- if (!this.state.isEnded) {
2500
- this.state.transition("paused");
2501
- this.emit("pause");
2502
- }
2503
- });
2504
- v.addEventListener("ended", () => {
2505
- this.state.transition("ended");
2506
- this.emit("ended");
2507
- });
2508
- v.addEventListener("timeupdate", () => {
2509
- this.emit("timeupdate", {
2510
- currentTime: v.currentTime,
2511
- duration: v.duration
2512
- });
2513
- });
2514
- v.addEventListener("volumechange", () => {
2515
- this.emit("volumechange", {
2516
- volume: v.volume,
2517
- muted: v.muted
2518
- });
2519
- });
2520
- v.addEventListener("waiting", () => {
2521
- this.state.transition("buffering");
2522
- this.emit("buffering", { isBuffering: true });
2523
- });
2524
- v.addEventListener("playing", () => {
2525
- this.state.transition("playing");
2526
- this.emit("buffering", { isBuffering: false });
2527
- });
2528
- v.addEventListener("canplay", () => {
2529
- if (this.state.status === "loading") {
2530
- this.state.transition("ready");
2531
- this.emit("ready");
2532
- if (this.config.autoplay ?? DEFAULT_CONFIG.autoplay) {
2533
- this.play();
2534
- }
2535
- }
2536
- });
2537
- v.addEventListener("error", () => {
2538
- const err = v.error;
2539
- this.state.transition("error");
2540
- this.emit("error", {
2541
- code: `MEDIA_ERR_${err?.code ?? 0}`,
2542
- message: err?.message ?? "Playback error"
2543
- });
2544
- });
2545
- v.addEventListener("ratechange", () => {
2546
- this.emit("ratechange", { rate: v.playbackRate });
2547
- });
2548
- }
2549
- // --- Loading ---
2550
- async loadVideoById(videoId) {
2551
- if (!this.client) {
2552
- this.emit("error", { code: "NO_API_KEY", message: "API key required to load video by ID" });
2553
- return;
2554
- }
2555
- this.state.transition("loading");
2556
- this.analyticsCollector?.setVideoId(videoId);
2557
- try {
2558
- const metadata = await this.client.getVideoMetadata(videoId);
2559
- if (metadata.poster && this.posterImage) {
2560
- this.posterImage.show(metadata.poster);
2561
- }
2562
- this.loadSource(metadata.playlistUrl);
2563
- } catch (err) {
2564
- this.state.transition("error");
2565
- this.emit("error", {
2566
- code: "API_ERROR",
2567
- message: err instanceof Error ? err.message : "Failed to load video"
2568
- });
2569
- }
2570
- }
2571
- loadSource(url) {
2572
- this.state.transition("loading");
2573
- try {
2574
- this.engine?.destroy();
2575
- this.engine = createEngine(
2576
- { apiKey: this.config.apiKey, embedToken: this.config.embedToken },
2577
- this.config.hlsConfig
2578
- );
2579
- this.engine.on("qualitylevels", (levels) => {
2580
- this.emit("qualitylevels", { levels });
2581
- });
2582
- this.engine.on("qualitychange", (level) => {
2583
- this.emit("qualitychange", { level });
2584
- });
2585
- this.engine.on("error", (err) => {
2586
- const e = err;
2587
- this.state.transition("error");
2588
- this.emit("error", e);
2589
- });
2590
- this.engine.on("stats", (stats) => {
2591
- const s = stats;
2592
- this.engineStats = s;
2593
- this.analyticsCollector?.onEngineStats(s);
2594
- this.emit("enginestats", { stats: s });
2595
- });
2596
- this.engine.load(url, this.video);
2597
- if (this.config.startTime) {
2598
- this.video.currentTime = this.config.startTime;
2599
- }
2600
- return Promise.resolve();
2601
- } catch (err) {
2602
- this.state.transition("error");
2603
- this.emit("error", {
2604
- code: "ENGINE_ERROR",
2605
- message: err instanceof Error ? err.message : "Failed to initialize player"
2606
- });
2607
- return Promise.reject(err);
2608
- }
2609
- }
2610
- // --- Diagnostics & Debug ---
2611
- getDiagnostics() {
2612
- return {
2613
- version: GALLOP_VERSION,
2614
- mode: "inline",
2615
- engineType: this.engine?.constructor.name || "none",
2616
- bitrate: this.engineStats?.bandwidthEstimate || 0,
2617
- bufferLength: this.getBufferLength(),
2618
- fps: this.engineStats?.totalFrames || 0,
2619
- // Simplified
2620
- droppedFrames: this.engineStats?.droppedFrames || 0,
2621
- totalFrames: this.engineStats?.totalFrames || 0,
2622
- status: this.state.status,
2623
- isMuted: this.video.muted,
2624
- volume: this.video.volume,
2625
- playbackRate: this.video.playbackRate,
2626
- currentTime: this.video.currentTime,
2627
- duration: this.video.duration,
2628
- nonceStatus: this.nonceStatus,
2629
- cspStatus: this.cspStatus
2630
- };
2631
- }
2632
- getBufferLength() {
2633
- const time = this.video.currentTime;
2634
- const buffered = this.video.buffered;
2635
- for (let i = 0; i < buffered.length; i++) {
2636
- if (time >= buffered.start(i) && time <= buffered.end(i)) {
2637
- return buffered.end(i) - time;
2638
- }
2639
- }
2640
- return 0;
2641
- }
2642
- async query(key) {
2643
- switch (key) {
2644
- case "currentTime":
2645
- return this.video.currentTime;
2646
- case "duration":
2647
- return this.video.duration;
2648
- case "volume":
2649
- return this.video.volume;
2650
- case "muted":
2651
- return this.video.muted;
2652
- case "playbackRate":
2653
- return this.video.playbackRate;
2654
- case "status":
2655
- return this.state.status;
2656
- case "isFullscreen":
2657
- return this.isFullscreen;
2658
- case "currentQuality":
2659
- return this.getCurrentQuality();
2660
- case "qualityLevels":
2661
- return this.getQualityLevels();
2662
- case "diagnostics":
2663
- return this.getDiagnostics();
2664
- default:
2665
- return Promise.reject(new Error(`Unknown query key: ${key}`));
2666
- }
2667
- }
2668
- initializeDebugOverlay() {
2669
- const diag = this.getDiagnostics();
2670
- this.debugOverlay = new DebugOverlay(
2671
- this.wrapper,
2672
- {
2673
- version: diag.version,
2674
- mode: diag.mode,
2675
- engineType: diag.engineType,
2676
- nonceStatus: diag.nonceStatus,
2677
- cspStatus: diag.cspStatus
2678
- },
2679
- () => this.getDiagnostics()
2680
- );
2681
- }
2682
- retry() {
2683
- if (this.config.videoId && this.client) {
2684
- void this.loadVideoById(this.config.videoId);
2685
- } else if (this.config.src) {
2686
- void this.loadSource(this.config.src);
2687
- }
2688
- }
2689
- // --- Playback Controls ---
2690
- async play() {
2691
- try {
2692
- this.posterImage?.hide();
2693
- await this.video.play();
2694
- } catch (err) {
2695
- if (err instanceof Error) {
2696
- if (err.name === "NotAllowedError") {
2697
- this.analyticsCollector?.trackEvent("error", this.currentTime, {
2698
- event_subtype: "autoplay_blocked",
2699
- error_code: "AUTOPLAY_BLOCKED",
2700
- error_message: err.message
2701
- });
2702
- }
2703
- if (err.name !== "AbortError") {
2704
- this.emit("error", { code: "PLAY_FAILED", message: err.message });
2705
- }
2706
- }
2707
- }
2708
- }
2709
- pause() {
2710
- this.video.pause();
2711
- return Promise.resolve();
2712
- }
2713
- togglePlay() {
2714
- if (this.video.paused || this.video.ended) {
2715
- return this.play();
2716
- } else {
2717
- return this.pause();
2718
- }
2719
- }
2720
- seek(time) {
2721
- const t = clamp(time, 0, this.duration);
2722
- this.video.currentTime = t;
2723
- this.emit("seeked", { time: t });
2724
- return Promise.resolve();
2725
- }
2726
- seekForward(seconds = 5) {
2727
- void this.seek(this.currentTime + seconds);
2728
- }
2729
- seekBackward(seconds = 5) {
2730
- void this.seek(this.currentTime - seconds);
2731
- }
2732
- // --- Volume ---
2733
- get volume() {
2734
- return this.video.volume;
2735
- }
2736
- set volume(v) {
2737
- this.video.volume = clamp(v, 0, 1);
2738
- }
2739
- get muted() {
2740
- return this.video.muted;
2741
- }
2742
- set muted(m) {
2743
- this.video.muted = m;
2744
- }
2745
- toggleMute() {
2746
- this.video.muted = !this.video.muted;
2747
- }
2748
- // --- Time ---
2749
- get currentTime() {
2750
- return this.video.currentTime;
2751
- }
2752
- get duration() {
2753
- return this.video.duration || 0;
2754
- }
2755
- get paused() {
2756
- return this.video.paused;
2757
- }
2758
- get buffered() {
2759
- return this.video.buffered;
2760
- }
2761
- // --- Quality ---
2762
- getQualityLevels() {
2763
- return this.engine?.getQualityLevels() ?? [];
2764
- }
2765
- setQualityLevel(index) {
2766
- this.engine?.setQualityLevel(index);
2767
- return Promise.resolve();
2768
- }
2769
- setAutoQuality() {
2770
- this.engine?.setAutoQuality();
2771
- return Promise.resolve();
2772
- }
2773
- isAutoQuality() {
2774
- return this.engine?.isAutoQuality() ?? true;
2775
- }
2776
- getCurrentQuality() {
2777
- return this.engine?.getCurrentQuality() ?? -1;
2778
- }
2779
- // --- Playback Rate ---
2780
- get playbackRate() {
2781
- return this.video.playbackRate;
2782
- }
2783
- set playbackRate(rate) {
2784
- if (SPEED_PRESETS.includes(rate)) {
2785
- this.video.playbackRate = rate;
2786
- }
2787
- }
2788
- // --- Fullscreen ---
2789
- async toggleFullscreen() {
2790
- const fsEl = document.fullscreenElement ?? document.webkitFullscreenElement;
2791
- if (fsEl) {
2792
- await this.exitFullscreen();
2793
- } else {
2794
- await this.enterFullscreen();
2795
- }
2796
- }
2797
- async enterFullscreen() {
2798
- const el2 = this.wrapper;
2799
- try {
2800
- if (el2.requestFullscreen) {
2801
- await el2.requestFullscreen();
2802
- } else if (el2.webkitRequestFullscreen) {
2803
- await el2.webkitRequestFullscreen();
2804
- }
2805
- this.wrapper.classList.add("gallop-fullscreen");
2806
- this.emit("fullscreenchange", { isFullscreen: true });
2807
- } catch {
2808
- }
2809
- }
2810
- async exitFullscreen() {
2811
- const doc = document;
2812
- try {
2813
- if (document.exitFullscreen) {
2814
- await document.exitFullscreen();
2815
- } else if (doc.webkitExitFullscreen) {
2816
- await doc.webkitExitFullscreen();
2817
- }
2818
- this.wrapper.classList.remove("gallop-fullscreen");
2819
- this.emit("fullscreenchange", { isFullscreen: false });
2820
- } catch {
2821
- }
2822
- }
2823
- get isFullscreen() {
2824
- const fsEl = document.fullscreenElement ?? document.webkitFullscreenElement;
2825
- return fsEl === this.wrapper;
2826
- }
2827
- // --- State ---
2828
- get status() {
2829
- return this.state.status;
2830
- }
2831
- getVideoElement() {
2832
- return this.video;
2833
- }
2834
- getWrapperElement() {
2835
- return this.wrapper;
2836
- }
2837
- // --- UI Updates ---
2838
- updateUIState() {
2839
- const status = this.state.status;
2840
- this.bigPlayButton?.setVisible(status === "idle" || status === "ready" || status === "paused" || status === "ended");
2841
- this.loadingSpinner?.setVisible(status === "loading" || status === "buffering");
2842
- this.errorOverlay?.setVisible(status === "error");
2843
- if (status === "playing") {
2844
- this.posterImage?.hide();
2845
- }
2846
- this.wrapper.setAttribute("data-status", status);
2847
- }
2848
- // --- Cleanup ---
2849
- destroy() {
2850
- if (this.destroyed) return;
2851
- this.destroyed = true;
2852
- this.keyboardManager?.destroy();
2853
- this.touchManager?.destroy();
2854
- this.contextMenu?.destroy();
2855
- this.controls?.destroy();
2856
- void this.analyticsCollector?.destroy();
2857
- this.engine?.destroy();
2858
- this.state.reset();
2859
- this.emit("destroy");
2860
- this.removeAllListeners();
2861
- this.wrapper.remove();
2862
- this.styleEl?.remove();
2863
- }
2864
- initializeAnalytics() {
2865
- const analyticsConfig = this.config.analytics;
2866
- const enabled = analyticsConfig?.enabled ?? true;
2867
- if (!enabled || !this.client) {
2868
- return;
2869
- }
2870
- const videoId = analyticsConfig?.videoId ?? this.config.videoId;
2871
- if (!videoId) {
2872
- if (analyticsConfig?.debug) {
2873
- console.warn("[Gallop analytics] disabled: no videoId available");
2874
- }
2875
- return;
2876
- }
2877
- this.analyticsCollector = new AnalyticsCollector({
2878
- client: this.client,
2879
- player: this,
2880
- videoId,
2881
- config: analyticsConfig
2882
- });
2883
- }
2884
- };
2885
-
2886
- export { GALLOP_VERSION, GallopPlayerCore };