-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.html
More file actions
2156 lines (1911 loc) · 94.3 KB
/
player.html
File metadata and controls
2156 lines (1911 loc) · 94.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NeverPause Player</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&family=Rajdhani:wght@400;600;700&display=swap"
rel="stylesheet">
<style>
:root {
--bg: #2C333D;
--accent: #FDFDF7;
--border: #6B7280;
--text: #FFFFFF;
--text-dim: #D1D5DB;
--mono: 'JetBrains Mono', monospace;
--display: 'Inter Tight', sans-serif;
/* CONFIGURATION */
--tier-labels-visibility: block;
/* Set to 'none' to hide "Original", "Blur Fuerte", etc. */
/* Status colors */
--perfect: #FDFDF7;
--good: #D1D5DB;
--medium: #6B7280;
--bad: #4B5563;
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0
}
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&family=Inter+Tight:wght@700&family=JetBrains+Mono&display=swap');
html,
body {
width: 100%;
height: 100%;
background: #000;
overflow: hidden;
font-family: var(--display);
color: var(--text);
-webkit-font-smoothing: antialiased
}
#player-shell {
position: relative;
width: 100%;
height: 100%;
background: #000;
display: flex;
flex-direction: column
}
#view-area {
position: relative;
flex: 1;
overflow: hidden;
background: #000;
cursor: pointer;
}
/* Corner Brackets implementation */
.bracket {
position: absolute;
width: 12px;
height: 12px;
border: 1px solid var(--accent);
pointer-events: none;
z-index: 25;
opacity: 0.6;
animation: breath-slow 4s ease-in-out infinite;
}
.bracket-tl {
top: 24px;
left: 24px;
border-right: none;
border-bottom: none;
}
.bracket-tr {
top: 24px;
right: 24px;
border-left: none;
border-bottom: none;
}
.bracket-bl {
bottom: 24px;
left: 24px;
border-right: none;
border-top: none;
}
.bracket-br {
bottom: 24px;
right: 24px;
border-left: none;
border-top: none;
}
@keyframes breath-slow {
0%,
100% {
opacity: 0.2;
transform: scale(1);
}
50% {
opacity: 0.8;
transform: scale(1.05);
}
}
#tier-badge {
display: var(--tier-labels-visibility) !important;
position: absolute;
top: 24px;
left: 50%;
transform: translateX(-50%);
font-family: var(--mono);
font-size: .55rem;
padding: 2px 12px;
background: rgba(44, 51, 61, 0.8);
border: 1px solid var(--border);
z-index: 30;
letter-spacing: .2em;
pointer-events: none;
color: var(--text-dim) !important;
text-transform: uppercase;
}
#powered-badge {
position: absolute;
bottom: 80px;
/* Offset to sit above the absolute controls bar */
right: 24px;
font-family: var(--mono);
font-size: .65rem;
font-weight: 700;
color: var(--text);
opacity: 0.8;
z-index: 50;
text-decoration: none;
text-transform: uppercase;
letter-spacing: 0.15em;
transition: opacity 0.4s ease, transform 0.3s ease, background 0.2s;
background: rgba(20, 24, 30, 0.85);
padding: 8px 16px 8px 14px;
border: 1px solid rgba(255, 255, 255, 0.4);
border-left: 3px solid var(--accent);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6);
pointer-events: auto;
backdrop-filter: blur(12px);
}
#powered-badge:hover {
opacity: 1 !important;
background: var(--bg);
transform: translateY(-2px);
border-color: var(--accent);
}
#canvas-l2,
#canvas-l3,
#stream-video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain;
}
#center-icon {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
font-size: 3rem;
opacity: 0;
pointer-events: none;
z-index: 30;
color: var(--accent);
}
#center-icon.flash {
animation: icon-flash .5s cubic-bezier(0.2, 0.8, 0.2, 1) forwards
}
@keyframes icon-flash {
0% {
opacity: 0.8;
transform: translate(-50%, -50%) scale(.8)
}
100% {
opacity: 0;
transform: translate(-50%, -50%) scale(1.5)
}
}
#caching-overlay {
position: absolute;
inset: 0;
background: rgba(44, 51, 61, 0.95);
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 24px;
z-index: 40;
backdrop-filter: blur(10px)
}
#caching-overlay .cl {
font-family: var(--mono);
font-size: .6rem;
color: var(--border);
letter-spacing: .25em;
text-transform: uppercase;
}
#caching-overlay .cp {
font-family: var(--display);
font-size: 4rem;
font-weight: 700;
color: var(--accent);
line-height: 1
}
#controls-wrap {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 60%, transparent 100%);
border-top: 1px solid rgba(255, 255, 255, 0.1);
z-index: 100;
transition: transform 0.4s ease, opacity 0.4s ease;
}
/* ── ACTIVITY TRACKING ── */
.idle {
cursor: none !important;
}
.idle #controls-wrap {
transform: translateY(10px);
opacity: 0;
pointer-events: none;
}
.idle #powered-badge,
.idle #tier-badge,
.idle .bracket {
opacity: 0 !important;
}
/* Ensure badge is visible when NOT idle, even if JS hasn't touched it yet
Wait, JS handles logic, but let's make it easier to see in dev. */
#powered-badge.force-show {
opacity: 1 !important;
pointer-events: auto;
}
#seek-wrap {
padding: 0;
height: 24px;
/* Large touch target */
display: flex;
align-items: center;
background: transparent;
position: absolute;
top: -12px;
/* Center the 24px wrap over the 1px border */
left: 0;
right: 0;
z-index: 100;
cursor: pointer;
}
#seek-bar {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 4px;
/* Slightly thicker for visibility */
background: transparent;
outline: none;
margin: 0;
transition: height 0.2s;
}
/* The visual track is handled by a background gradient on the input or a pseudo-element.
We'll use a gradient on the input but make it 2px visually using a background-size trick or just 4px.
Let's go with 4px for better mobile visibility while keeping it sleek. */
#seek-bar {
background: linear-gradient(to right,
var(--accent) 0%, var(--accent) var(--played, 0%),
var(--border) var(--played, 0%), var(--border) var(--buffered, 0%),
rgba(255, 255, 255, 0.05) var(--buffered, 0%), rgba(255, 255, 255, 0.05) 100%);
}
#seek-wrap:hover #seek-bar,
#seek-bar:active {
height: 6px;
}
/* Minimalist Thumb */
#seek-bar::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 2px;
height: 16px;
background: var(--accent);
cursor: pointer;
box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
border: none;
}
#seek-bar::-moz-range-thumb {
width: 2px;
height: 16px;
background: var(--accent);
cursor: pointer;
box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
border: none;
}
#controls-bar {
height: 56px;
display: flex;
align-items: center;
padding: 0 24px;
gap: 20px
}
.icon-btn {
background: none;
border: none;
color: var(--text-dim);
cursor: pointer;
padding: 8px;
display: flex;
align-items: center;
justify-content: center;
transition: all .3s;
}
.icon-btn:hover {
color: var(--accent);
transform: translateY(-1px);
}
.icon-btn svg {
width: 18px;
height: 18px;
fill: currentColor
}
#time-display {
font-family: var(--mono);
font-size: .6rem;
color: var(--border);
letter-spacing: .1em;
}
.spacer {
flex: 1
}
#vol-wrap {
display: flex;
align-items: center;
gap: 12px
}
#vol-slider {
-webkit-appearance: none;
appearance: none;
width: 60px;
height: 1px;
background: var(--border);
cursor: pointer;
outline: none
}
#vol-slider::-webkit-slider-thumb {
-webkit-appearance: none;
width: 6px;
height: 6px;
background: var(--accent);
border-radius: 50%;
}
#tier-pill {
display: var(--tier-labels-visibility) !important;
font-family: var(--mono);
font-size: .55rem;
color: var(--border) !important;
letter-spacing: .1em;
text-transform: uppercase;
}
#cache-dots {
display: flex;
gap: 8px;
align-items: center
}
.c-dot {
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--border);
transition: all .5s
}
.c-dot.ready,
.c-dot.cached {
background: #00ff88;
box-shadow: 0 0 10px rgba(0, 255, 136, 0.5);
}
.c-dot.loading {
animation: pulse 1s ease-in-out infinite;
background: var(--accent);
}
.c-dot.failed {
background: #ff4466;
box-shadow: 0 0 8px rgba(255, 68, 102, 0.4);
}
@keyframes pulse {
0%,
100% {
opacity: .2
}
50% {
opacity: 1
}
}
#net-meter {
width: 40px;
height: 1px;
background: var(--border);
overflow: hidden;
}
#net-fill {
height: 100%;
width: 0%;
background: var(--accent);
transition: width .5s
}
#loading-screen {
position: absolute;
inset: 0;
background: var(--bg);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 32px;
z-index: 100
}
.l-title {
font-family: var(--display);
font-size: 1rem;
font-weight: 700;
color: var(--text);
letter-spacing: .4em;
text-transform: uppercase
}
.spinner {
width: 32px;
height: 32px;
border: 1px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 1s linear infinite
}
.l-sub {
font-family: var(--mono);
font-size: .6rem;
color: var(--border);
letter-spacing: .2em;
text-transform: uppercase
}
#error-screen {
position: absolute;
inset: 0;
background: var(--bg);
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 110;
padding: 40px;
text-align: center
}
.e-msg {
font-family: var(--mono);
font-size: .7rem;
color: var(--text-dim);
letter-spacing: .05em;
max-width: 300px;
line-height: 1.8;
}
:fullscreen #player-shell,
:-webkit-full-screen #player-shell {
width: 100vw;
height: 100vh
}
/* Ensure smooth transitions for all UI elements */
#tier-badge,
.bracket {
transition: opacity 0.4s ease;
}
#controls-bar {
background: var(--bg);
}
</style>
</head>
<body>
<div id="player-shell">
<div id="loading-screen">
<div class="l-title">NeverPause</div>
<div class="spinner"></div>
<div class="l-sub" id="load-sub">Initializing Player...</div>
</div>
<div id="error-screen">
<div class="e-msg" id="error-msg"></div>
</div>
<div id="view-area" class="tier-original">
<div class="bracket bracket-tl"></div>
<div class="bracket bracket-tr"></div>
<div class="bracket bracket-bl"></div>
<div class="bracket bracket-br"></div>
<canvas id="canvas-l3" class="layer-back"></canvas>
<canvas id="canvas-l2" class="layer-back"></canvas>
<video id="stream-video" class="layer-front" playsinline muted preload="auto"></video>
<div id="tier-badge">Playback Stable</div>
<div id="center-icon">▶</div>
<div id="caching-overlay">
<div class="cl" id="cache-label">Loading Quality Track...</div>
<div class="cp" id="overlay-percent">0%</div>
</div>
<div id="sub-container"
style="position:absolute;bottom:80px;left:0;right:0;text-align:center;pointer-events:none;z-index:45;font-family:var(--display);font-size:1.2rem;color:#fff;text-shadow:1px 1px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 0 2px 4px rgba(0,0,0,0.8);line-height:1.4;">
</div>
<a href="https://google.com" target="_blank" id="powered-badge">Powered by NeverPause</a>
</div>
<audio id="audio-el" style="display:none"></audio>
<div id="controls-wrap">
<div id="seek-wrap">
<input type="range" id="seek-bar" min="0" max="100" step="0.01" value="0">
</div>
<div id="controls-bar">
<button class="icon-btn" id="play-btn" title="Play/Pause (Space)">
<svg id="play-icon" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z" />
</svg>
</button>
<span id="time-display">0:00 / 0:00</span>
<div class="spacer"></div>
<div id="net-meter">
<div id="net-fill"></div>
</div>
<div id="tier-pill">Original</div>
<div id="cache-dots">
<div class="c-dot loading" id="dot-l2" title="L2"></div>
<div class="c-dot loading" id="dot-l3" title="L3"></div>
</div>
<div id="vol-wrap">
<button class="icon-btn" id="mute-btn" title="Mute (M)">
<svg id="vol-icon" viewBox="0 0 24 24">
<path
d="M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" />
</svg>
</button>
<input type="range" id="vol-slider" min="0" max="1" step="0.01" value="1">
</div>
<button class="icon-btn" id="fs-btn" title="Fullscreen (F)">
<svg id="fs-icon" viewBox="0 0 24 24">
<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
</svg>
</button>
</div>
</div>
</div>
<script>
'use strict';
// ═══════════════════════════════════════════════════════════════════════════
// NeverPause PLAYER — WebCodecs + IndexedDB edition
//
// Storage: IndexedDB stores L2/L3 blobs across sessions.
// On first load: download + store. On reload: read from IDB (<100ms).
//
// Video: L2/L3 → WebCodecs (VideoDecoder) → <canvas>
// Original/L1 → <video> element (stream)
//
// Audio: WebAudioTrack (AudioContext) — seek latency <1ms
//
// Offline: navigator.onLine + 'offline' event → INSTANT switch (<16ms)
// No waiting for health probe timeout
// ═══════════════════════════════════════════════════════════════════════════
const HAS_WEBCODECS = typeof VideoDecoder !== 'undefined';
const IDB_NAME = 'video-resilience';
const IDB_STORE = 'blobs';
const IDB_VERSION = 1;
const TIER_RANK = { original: 3, l1: 2, l2: 1, l3: 0 };
const TIER_META = {
original: { label: 'Original', color: 'var(--perfect)', css: 'tier-original' },
l1: { label: 'Standard', color: 'var(--good)', css: 'tier-l1' },
l2: { label: 'Medium', color: 'var(--medium)', css: 'tier-l2' },
l3: { label: 'Basic', color: 'var(--bad)', css: 'tier-l3' },
};
const THRESHOLDS = { original: 2000, l1: 800, l2: 150 };
// ── DOM ───────────────────────────────────────────────────────────────────────
const canvasL2 = document.getElementById('canvas-l2');
const ctxL2 = canvasL2.getContext('2d', { alpha: false, desynchronized: true });
const canvasL3 = document.getElementById('canvas-l3');
const ctxL3 = canvasL3.getContext('2d', { alpha: false, desynchronized: true });
const streamVid = document.getElementById('stream-video');
const audioEl = document.getElementById('audio-el');
const viewArea = document.getElementById('view-area');
const tierBadge = document.getElementById('tier-badge');
const centerIcon = document.getElementById('center-icon');
const cachingOvl = document.getElementById('caching-overlay');
const cacheLabel = document.getElementById('cache-label');
const overlayPct = document.getElementById('overlay-percent');
const seekBar = document.getElementById('seek-bar');
const timeDisplay = document.getElementById('time-display');
const playBtn = document.getElementById('play-btn');
const playIcon = document.getElementById('play-icon');
const muteBtn = document.getElementById('mute-btn');
const volIcon = document.getElementById('vol-icon');
const volSlider = document.getElementById('vol-slider');
const fsBtn = document.getElementById('fs-btn');
const fsIcon = document.getElementById('fs-icon');
const netFill = document.getElementById('net-fill');
const tierPill = document.getElementById('tier-pill');
const dotL2 = document.getElementById('dot-l2');
const dotL3 = document.getElementById('dot-l3');
const loadScreen = document.getElementById('loading-screen');
const loadSub = document.getElementById('load-sub');
const errorScreen = document.getElementById('error-screen');
const errorMsg = document.getElementById('error-msg');
const poweredBadge = document.getElementById('powered-badge');
// ── State ─────────────────────────────────────────────────────────────────────
let instructions = null;
let baseURL = '';
let activeTier = 'original';
let isPlaying = false;
let isLooping = false;
let isMuted = false;
let isFullscreen = false;
let isSeeking = false;
let lastDragPct = null;
let duration = 0;
let switching = false; // prevents concurrent switchToTier calls
let probeEnabled = true; // skip bandwidth probes during quality transitions
let badgeTimeout = null;
let telStat = { started: false, buffers: 0, switches: 0, lastBuf: 0 };
const Telemetry = (() => {
return {
record: async (type, data) => {
// Public Standalone implementation: emit tracking events to console
// console.log('[Telemetry Record]', type, data);
}
};
})();
let bwSamples = [];
let healthScore = 10000;
const EWMA_A = 0.35;
let goodTicks = 0;
let lastUpgradeTime = 0; // last time we went up in quality
let lastSwitchTime = 0; // throttle any switch cycle
const UPGRADE_COOLDOWN_MS = 5000;
const MIN_SWITCH_INTERVAL_MS = 3000;
let l3Track = null;
let l2Track = null;
let audioTrack = null;
let _seekFrameExpected = false;
let _seekVersion = 0;
let _seekInFlight = false;
let _seekPending = null;
const DBG = true;
function dbg(...a) { if (DBG) console.log('[AR seek]', ...a); }
// postMessage API — lets any parent page (same or cross-origin) listen to player events
// and send commands. This is the entire external interface for embedders.
function emit(type, detail = {}) {
if (window._suppressNextEmit) {
// Only suppress play/pause to avoid interfering with timeupdate, etc.
if (type === 'play' || type === 'pause') {
window._suppressNextEmit = false;
return;
}
}
const msg = { source: 'video-resilience-player', type, ...detail };
try { window.parent.postMessage(msg, '*'); } catch { }
}
function mu(p) { return p.startsWith('http') ? p : `${baseURL}/${p}`; }
function showError(m) { loadScreen.style.display = 'none'; errorScreen.style.display = 'flex'; errorMsg.textContent = m; }
// ═══════════════════════════════════════════════════════════════════════════
// INDEXEDDB — stores Uint8Array blobs keyed by URL
// ═══════════════════════════════════════════════════════════════════════════
let idb = null;
async function idbOpen() {
return new Promise((res, rej) => {
const req = indexedDB.open(IDB_NAME, IDB_VERSION);
req.onupgradeneeded = e => e.target.result.createObjectStore(IDB_STORE);
req.onsuccess = e => res(e.target.result);
req.onerror = e => rej(e.target.error);
});
}
async function idbGet(key) {
return new Promise((res, rej) => {
if (!idb) return res(null);
const tx = idb.transaction(IDB_STORE, 'readonly');
const req = tx.objectStore(IDB_STORE).get(key);
req.onsuccess = e => {
const data = e.target.result;
if (!data) return res(null);
// TTL: 2 days (172,800,000 ms)
if (!data.ts || Date.now() - data.ts > 172800000) {
idbDelete(key);
return res(null);
}
res(data.blob);
};
req.onerror = e => rej(e.target.error);
});
}
async function idbPut(key, value) {
return new Promise((res, rej) => {
if (!idb) return res();
const tx = idb.transaction(IDB_STORE, 'readwrite');
const req = tx.objectStore(IDB_STORE).put({ blob: value, ts: Date.now() }, key);
req.onsuccess = () => res();
req.onerror = e => rej(e.target.error);
});
}
async function idbDelete(key) {
if (!idb) return;
const tx = idb.transaction(IDB_STORE, 'readwrite');
tx.objectStore(IDB_STORE).delete(key);
}
async function idbCleanup() {
if (!idb) return;
const tx = idb.transaction(IDB_STORE, 'readwrite');
const store = tx.objectStore(IDB_STORE);
const req = store.openCursor();
req.onsuccess = e => {
const cursor = e.target.result;
if (cursor) {
const data = cursor.value;
if (data && (!data.ts || Date.now() - data.ts > 172800000)) {
cursor.delete();
}
cursor.continue();
}
};
}
// ═══════════════════════════════════════════════════════════════════════════
// EBML DEMUXER — parses WebM in RAM, builds keyframe index
// ═══════════════════════════════════════════════════════════════════════════
class EBMLDemuxer {
constructor(buf) {
this.buf = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
this.view = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);
this.pos = 0;
}
readVINT() {
const b = this.buf[this.pos];
if (!b) throw new Error('bad vint');
const len = Math.clz32(b) - 24 + 1;
let val = b & (0xFF >> len);
for (let i = 1; i < len; i++) val = val * 256 + this.buf[this.pos + i];
this.pos += len;
return val;
}
readID() {
const b = this.buf[this.pos];
const len = Math.clz32(b) - 24 + 1;
let id = 0;
for (let i = 0; i < len; i++) id = (id << 8) | this.buf[this.pos + i];
this.pos += len;
return id >>> 0;
}
readUint(len) {
let v = 0;
for (let i = 0; i < len; i++) v = v * 256 + this.buf[this.pos++];
return v;
}
readFloat(len) {
const off = this.pos; this.pos += len;
return len === 4 ? this.view.getFloat32(off, false)
: len === 8 ? this.view.getFloat64(off, false) : 0;
}
readString(len) {
const s = String.fromCharCode(...this.buf.slice(this.pos, this.pos + len));
this.pos += len; return s.replace(/\0/g, '').trim();
}
_skipToID(target) {
while (this.pos < this.buf.length - 8) {
const s = this.pos;
try { if (this.readID() === target) return; this.pos = s + 1; }
catch { this.pos = s + 1; }
}
}
parse() {
const r = { codecId: '', codecPrivate: null, timecodeScale: 1000000, duration: 0, keyframes: [], clusters: [] };
this._skipToID(0x18538067);
this.readVINT();
while (this.pos < this.buf.length - 4) {
const id = this.readID(), sz = this.readVINT(), end = this.pos + sz;
if (id === 0x1549A966) this._info(r, end);
else if (id === 0x1654AE6B) this._tracks(r, end);
else if (id === 0x1F43B675) this._cluster(r, this.pos - this._vlen(sz) - this._ilen(id), sz);
else this.pos = end;
if (this.pos >= this.buf.length) break;
}
r.keyframes.sort((a, b) => a.ts - b.ts);
return r;
}
_vlen(v) { return v < 0x80 ? 1 : v < 0x4000 ? 2 : v < 0x200000 ? 3 : v < 0x10000000 ? 4 : 8; }
_ilen(id) { return id <= 0xFF ? 1 : id <= 0xFFFF ? 2 : id <= 0xFFFFFF ? 3 : 4; }
_info(r, end) {
while (this.pos < end) {
const id = this.readID(), sz = this.readVINT();
if (id === 0x2AD7B1) r.timecodeScale = this.readUint(sz);
else if (id === 0x4489) r.duration = this.readFloat(sz);
else this.pos += sz;
}
r.duration = r.duration * r.timecodeScale / 1e6;
}
_tracks(r, end) {
while (this.pos < end) {
const id = this.readID(), sz = this.readVINT(), el = this.pos + sz;
if (id === 0xAE) this._trackEntry(r, el);
else this.pos = el;
}
}
_trackEntry(r, end) {
let type = 0, codec = '', priv = null;
while (this.pos < end) {
const id = this.readID(), sz = this.readVINT();
if (id === 0x83) type = this.readUint(sz);
else if (id === 0x86) codec = this.readString(sz);
else if (id === 0x63A2) { priv = this.buf.slice(this.pos, this.pos + sz); this.pos += sz; }
else this.pos += sz;
}
if (type === 1 && !r.codecId) { r.codecId = codec; r.codecPrivate = priv; }
}
// AV1: container keyframe flag is unreliable with libaom realtime mode.
// Read the OBU bitstream — SEQUENCE_HEADER OBU (type=1) = real keyframe.
_isAV1Key(off, len) {
const end = off + len;
let p = off;
while (p < end - 1) {
const hdr = this.buf[p++];
if (hdr & 0x80) break;
const type = (hdr >> 3) & 0xF;
const ext = (hdr >> 2) & 1;
const hasSize = (hdr >> 1) & 1;
if (ext) p++;
let obuSz = 0;
if (hasSize) {
let sh = 0;
while (p < end) { const b = this.buf[p++]; obuSz |= (b & 0x7F) << sh; if (!(b & 0x80)) break; sh += 7; }
} else obuSz = end - p;
if (type === 1) return true; // SEQUENCE_HEADER
if (type === 3 || type === 6) {
if (p < end) {
const fb = this.buf[p];
if (!((fb >> 7) & 1)) return ((fb >> 5) & 3) === 0; // frame_type===KEY_FRAME
}
return false;
}
p += obuSz;
}
return false;
}
_cluster(r, clOff, clSz) {
const end = Math.min(this.pos + clSz, this.buf.length);
let clTs = 0;
const blocks = [];
const isAV1 = r.codecId.startsWith('V_AV1');
while (this.pos < end - 2) {
const id = this.readID(), sz = this.readVINT(), el = this.pos + sz;
if (el > this.buf.length) { this.pos = end; break; }
if (id === 0xE7) {
clTs = this.readUint(sz);
} else if (id === 0xA3) {
// SimpleBlock
this.readVINT(); // trackNum
const relTs = this.view.getInt16(this.pos, false); this.pos += 2;
const flags = this.buf[this.pos++];
const dOff = this.pos, dLen = el - this.pos;
this.pos = el;
const ts = (clTs + relTs) * r.timecodeScale / 1e6;
const key = isAV1 ? this._isAV1Key(dOff, dLen) : !!(flags & 0x80);
blocks.push({ ts, offset: dOff, length: dLen, keyframe: key });
if (key) r.keyframes.push({ ts, clusterIdx: r.clusters.length });
} else if (id === 0xA0) {
// BlockGroup
this._blockGroup(r, el, clTs, blocks, isAV1);
this.pos = el;
} else {
this.pos = el;
}
}
this.pos = end;
r.clusters.push({ ts: clTs * r.timecodeScale / 1e6, offset: clOff, length: clSz, blocks });
}
_blockGroup(r, end, clTs, blocks, isAV1) {
let bd = null, hasRef = false;
while (this.pos < end) {
const id = this.readID(), sz = this.readVINT(), el = this.pos + sz;
if (id === 0xA1) {
this.readVINT(); // trackNum
const relTs = this.view.getInt16(this.pos, false); this.pos += 2;
this.pos++; // flags
bd = { relTs, dOff: this.pos, dLen: el - this.pos };
this.pos = el;
} else if (id === 0xFB) { hasRef = true; this.pos = el; }
else this.pos = el;
}
if (!bd) return;
const ts = (clTs + bd.relTs) * r.timecodeScale / 1e6; // timecodeScale applied in _cluster
const key = isAV1 ? this._isAV1Key(bd.dOff, bd.dLen) : !hasRef;
blocks.push({ ts, offset: bd.dOff, length: bd.dLen, keyframe: key });
if (key) r.keyframes.push({ ts, clusterIdx: r.clusters.length });
}
}
// ═══════════════════════════════════════════════════════════════════════════
// WebCodecsTrack
// ═══════════════════════════════════════════════════════════════════════════
class WebCodecsTrack {