Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1387 lines (1246 loc) · 56.3 KB
/
Copy pathapp.js
File metadata and controls
1387 lines (1246 loc) · 56.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
/**
* ASCILINE ENGINE - Pure & Performant Logic
* =========================================
* No decorative animations. Pure WebSocket streaming
* and high-performance canvas rendering.
* Includes an "Invisible Selection Layer" for text selection.
*/
const player = document.getElementById('ascii-player');
const canvas = document.getElementById('ascii-canvas');
const ctx = canvas.getContext('2d');
const statusEl = document.getElementById('status');
const container = document.getElementById('player-container');
const overlay = document.getElementById('play-overlay');
const audioEl = document.getElementById('ascii-audio');
const volumeSlider = document.getElementById('volume-slider');
const playPauseBtn = document.getElementById('play-pause-btn');
const seekBar = document.getElementById('seek-slider');
const timeCurrent = document.getElementById('time-current');
const timeTotal = document.getElementById('time-total');
// Added controls: skip buttons, played fill, and the hover scrub preview
const btnBack = document.getElementById('btn-back');
const btnFwd = document.getElementById('btn-fwd');
const seekPlayed = document.getElementById('seek-played');
const seekWrap = document.querySelector('.seek-wrap');
const seekPreview = document.getElementById('seek-preview');
const seekPreviewImg = document.getElementById('seek-preview-img');
const seekPreviewTime = document.getElementById('seek-preview-time');
const btnCopy = document.getElementById('btn-copy');
const copyTooltip = document.getElementById('copy-tooltip');
let scrubMeta = null; // hover sprite layout from /scrub
let copyFeedbackTimer = null;
function showCopyTooltip(msg) {
if (!copyTooltip) return;
copyTooltip.textContent = msg;
copyTooltip.classList.add('show');
clearTimeout(copyFeedbackTimer);
copyFeedbackTimer = setTimeout(() => {
copyTooltip.classList.remove('show');
}, 1500);
}
function formatTime(seconds) {
if (isNaN(seconds) || seconds < 0) return "00:00";
const m = Math.floor(seconds / 60).toString().padStart(2, '0');
const s = Math.floor(seconds % 60).toString().padStart(2, '0');
return `${m}:${s}`;
}
// ── STATE ──
let state = 'IDLE'; // IDLE | PLAYING | PAUSED
let ws = null;
let bufferReportTimer = null; // periodic backlog report to the server (backpressure)
const frameBuffer = [];
const BUFFER_SIZE = 4;
let codecDecoder = null; // Adaptive codec decoder (codec.js)
let targetFps = 24;
let frameInterval = 1000 / targetFps;
let renderMode = 1;
let pixelMode = false;
let pixelCodec = 'raw';
let readyToRender = false;
let pauseStartTime = 0;
let duration = 0;
let isSeeking = false;
let currentQueueIdx = 0;
let audioOffset = 0;
let isWebcamStream = false; // skips audio-sync gate and locks pause
let renderRequestId = null;
let cancelPlaybackStart = null;
let playbackAttempt = 0;
let audioClockActive = false;
let pendingSeekId = null;
let syncId = null; // null means an older server without clock coordination
let resumeNeedsAudioSeek = false;
// Grid & Dimensions
let gridCols = 0, gridRows = 0;
let charWidth = 0, charHeight = 0;
let xPos = null, yPos = null;
// Pixel Mode (--pixel) — ImageData pixel buffer
let dotImageData = null;
// Selection Layer optimization
const textDecoder = new TextDecoder();
let selectionBuffer = null;
// Timing & Metrics
let lastRenderTime = 0;
let frameCount = 0, currentFps = 0, lastFpsUpdate = 0;
let streamStartTime = 0;
let streamEpoch = 0; // Incremented on every seek/reinit to cancel stale async audio loads
let lastUiUpdateTime = 0;
let lastFormattedTime = "";
const CHAR_LUT = new Array(128);
for (let i = 0; i < 128; i++) CHAR_LUT[i] = String.fromCharCode(i);
// ═══════════════════════════════════════
// CANVAS SETUP
// ═══════════════════════════════════════
function buildCanvas(cols, rows) {
gridCols = cols;
gridRows = rows;
// Sizing and positioning for both layers
const syncSize = (el) => {
el.style.width = container.clientWidth + 'px';
el.style.height = container.clientHeight + 'px';
el.style.objectFit = 'contain';
el.style.position = 'absolute';
el.style.top = '0';
el.style.left = '0';
};
if (pixelMode) {
// ── DOT MODE: 1 canvas pixel = 1 grid cell ──
canvas.width = cols;
canvas.height = rows;
canvas.style.display = 'block';
canvas.style.imageRendering = 'pixelated';
dotImageData = ctx.createImageData(cols, rows);
// Pre-fill alpha channel to 255 (fully opaque)
const d = dotImageData.data;
for (let i = 3; i < d.length; i += 4) d[i] = 255;
syncSize(canvas);
// Hide selection layer — no text to select in dot mode
player.style.display = 'none';
} else {
// ── STANDARD ASCII MODES (1-5) ──
canvas.style.imageRendering = '';
dotImageData = null;
ctx.font = 'bold 8px Courier New';
charWidth = ctx.measureText('M').width;
charHeight = 8;
canvas.width = cols * charWidth;
canvas.height = rows * charHeight;
canvas.style.display = 'block';
// Selection Layer Buffer
selectionBuffer = new Uint8Array((cols + 1) * rows);
for (let r = 0; r < rows; r++) selectionBuffer[r * (cols + 1) + cols] = 10;
syncSize(canvas);
// Selection layer: match canvas object-fit:contain position exactly
const containerW = container.clientWidth;
const containerH = container.clientHeight;
const fitScaleX = containerW / canvas.width;
const fitScaleY = containerH / canvas.height;
const fitScale = Math.min(fitScaleX, fitScaleY);
const renderedW = canvas.width * fitScale;
const renderedH = canvas.height * fitScale;
const offsetX = (containerW - renderedW) / 2;
const offsetY = (containerH - renderedH) / 2;
player.style.width = canvas.width + 'px';
player.style.height = canvas.height + 'px';
player.style.position = 'absolute';
player.style.top = '0';
player.style.left = '0';
player.style.transformOrigin = 'top left';
player.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${fitScale})`;
player.style.fontSize = '8px';
player.style.lineHeight = '8px';
ctx.font = 'bold 8px Courier New';
ctx.textBaseline = 'top';
xPos = new Float32Array(cols);
yPos = new Float32Array(rows);
for (let c = 0; c < cols; c++) xPos[c] = c * charWidth;
for (let r = 0; r < rows; r++) yPos[r] = r * charHeight;
}
applyReliefGrid();
}
// ═══════════════════════════════════════
// STARTUP SYNC LOGIC (VIDEO GATE)
// ═══════════════════════════════════════
function stopRendering() {
if (renderRequestId !== null) cancelAnimationFrame(renderRequestId);
renderRequestId = null;
}
function scheduleRender() {
if (renderRequestId !== null) return;
renderRequestId = requestAnimationFrame(now => {
renderRequestId = null;
renderFrame(now);
});
}
function resetPlaybackStart() {
playbackAttempt++;
if (cancelPlaybackStart) cancelPlaybackStart();
cancelPlaybackStart = null;
readyToRender = false;
stopRendering();
stopBufferReports();
}
function resetFramePipeline() {
frameBuffer.length = 0;
framesInFlight = 0;
playbackMetrics = { decodeMs: 0, decoded: 0, renderMs: 0, rendered: 0,
lateDrops: 0, decodeErrors: 0, latestTime: null };
decodeQueue = Promise.resolve();
codecDecoder = typeof AscilineCodec !== 'undefined' && renderMode > 1 && (!pixelMode || pixelCodec === 'dct')
? AscilineCodec.makeDecoder(pixelMode ? 3 : 4) : null;
}
function loadAudio() {
audioClockActive = false;
if (!audioEl || isWebcamStream) return;
audioEl.pause();
audioEl.src = `/audio?v=${currentQueueIdx}&start=${audioOffset}&t=${Date.now()}&epoch=${streamEpoch}`;
audioEl.volume = volumeSlider ? volumeSlider.value : 1.0;
audioEl.load();
}
const beginRendering = (withAudio = false) => {
if (readyToRender || state !== 'PLAYING' || pendingSeekId !== null) return;
if (cancelPlaybackStart) cancelPlaybackStart();
cancelPlaybackStart = null;
audioClockActive = withAudio;
readyToRender = true;
statusEl.textContent = 'Playing...';
const firstTime = frameBuffer.length ? frameBuffer[0].time : audioOffset;
streamStartTime = performance.now() - (firstTime * 1000.0);
frameCount = 0;
lastRenderTime = performance.now();
lastFpsUpdate = lastRenderTime;
if (playPauseBtn) playPauseBtn.textContent = '❚❚';
if (syncId !== null && ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'playback-ready', requestId: syncId, time: getMasterClock() }));
}
scheduleRender();
startBufferReports();
};
const triggerPlaybackStart = (epochToMatch) => {
if (epochToMatch !== streamEpoch || readyToRender || cancelPlaybackStart ||
state !== 'PLAYING' || pendingSeekId !== null || !frameBuffer.length) return;
if (syncId !== null && frameBuffer.length < BUFFER_SIZE) return;
if (isWebcamStream || !audioEl) {
beginRendering();
return;
}
const attempt = ++playbackAttempt;
const expectedSource = audioEl.src;
const current = () => attempt === playbackAttempt && epochToMatch === streamEpoch && state === 'PLAYING';
const onPlaying = () => {
// This DOM element is reused across seeks. An old queued media event
// must not anchor the new timeline to the previous resource's clock.
if (current() && audioEl.currentSrc === expectedSource &&
audioEl.readyState >= 3 && !audioEl.paused) beginRendering(true);
};
const onUnavailable = () => {
if (!current()) return;
audioEl.pause();
beginRendering(false);
};
// Register once per playback attempt, never once per incoming frame.
// Metadata/readiness alone does not mean the audio clock is running.
const timer = setTimeout(onUnavailable, 2000);
cancelPlaybackStart = () => {
clearTimeout(timer);
audioEl.removeEventListener('playing', onPlaying);
audioEl.removeEventListener('error', onUnavailable);
};
statusEl.textContent = 'Starting audio...';
audioEl.addEventListener('playing', onPlaying);
audioEl.addEventListener('error', onUnavailable);
audioEl.play().then(onPlaying).catch(onUnavailable);
};
// ═══════════════════════════════════════
// STREAM CONTROL
// ═══════════════════════════════════════
function startStream() {
if (state !== 'IDLE') return;
overlay.classList.add('hidden');
statusEl.textContent = 'Connecting...';
statusEl.style.color = 'var(--accent-color)';
connectWebSocket();
}
function connectWebSocket() {
frameBuffer.length = 0;
frameCount = 0;
currentFps = 0;
// Audio is loaded later in INIT handler (Audio Ready Gate).
// Don't preload here — causes race conditions with vol=0 (204 response).
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
ws = new WebSocket(`${protocol}//${location.host}/ws?codec=adaptive&sync=1&pixel_codec=dct-v1`);
ws.binaryType = 'arraybuffer';
ws.onmessage = (event) => {
if (typeof event.data === 'string') {
if (event.data.startsWith('SEEKED:')) {
const parts = event.data.split(':');
const requestId = Number(parts[1]);
if (requestId !== pendingSeekId) return;
pendingSeekId = null;
resumeNeedsAudioSeek = false;
syncId = requestId;
audioOffset = Number(parts[2]);
statusEl.textContent = 'Preparing playback...';
resetFramePipeline();
streamStartTime = performance.now() - audioOffset * 1000;
if (state === 'PAUSED') pauseStartTime = performance.now();
loadAudio();
return;
}
if (event.data.startsWith('Error:')) {
hideToast(); // drop any "fetching..." notice; the fetch failed
statusEl.textContent = event.data;
statusEl.style.color = '#ff0000';
if (ws) ws.close();
setTimeout(() => finishStream(), 3000);
return;
}
if (event.data.startsWith('INIT:')) {
// First INIT means frames are about to flow — drop any
// "fetching..." notification the server sent earlier.
hideToast();
const p = event.data.split(':');
targetFps = parseFloat(p[1]);
frameInterval = 1000 / targetFps;
renderMode = parseInt(p[2]);
pixelMode = (p.length > 5 && parseInt(p[5]) === 1);
pixelCodec = pixelMode && p[11] === 'dct' ? 'dct' : 'raw';
if (btnCopy) {
btnCopy.disabled = pixelMode;
btnCopy.title = pixelMode
? 'Copy text is only available in ASCII modes'
: 'Copy current ASCII frame';
}
const currentQueueIndex = (p.length > 6) ? parseInt(p[6]) : null;
duration = (p.length > 7) ? parseFloat(p[7]) : 0;
const startOffset = (p.length > 8) ? parseFloat(p[8]) : 0;
const isWebcam = (p.length > 9 && parseInt(p[9]) === 1);
isWebcamStream = isWebcam;
syncId = !isWebcam && p.length > 10 ? Number(p[10]) : null;
pendingSeekId = null;
resetPlaybackStart();
currentQueueIdx = currentQueueIndex !== null ? currentQueueIndex : 0;
if (seekBar) {
seekBar.max = duration;
seekBar.value = 0;
}
if (timeTotal) timeTotal.textContent = formatTime(duration);
if (timeCurrent) timeCurrent.textContent = "00:00";
if (seekPlayed) seekPlayed.style.transform = 'scaleX(0)';
if (typeof filterPixelBtn !== 'undefined' && filterPixelBtn) {
filterPixelBtn.dataset.active = pixelMode ? 'true' : 'false';
filterPixelBtn.textContent = pixelMode ? 'ON' : 'OFF';
if (isWebcam) {
filterPixelBtn.disabled = true;
filterPixelBtn.style.opacity = '0.5';
filterPixelBtn.style.cursor = 'not-allowed';
filterPixelBtn.title = 'Pixel mode toggle is disabled during live webcam feed';
} else {
filterPixelBtn.disabled = false;
filterPixelBtn.style.opacity = '1';
filterPixelBtn.style.cursor = 'pointer';
filterPixelBtn.title = '';
}
}
audioOffset = startOffset;
frameBuffer.length = 0;
framesInFlight = 0;
streamEpoch++; // Invalidate any pending audio loads
scrubMeta = null; // reset so new video gets fresh thumbnails
// Lazy-load hover thumbnails: only fetch on first hover
const qIdx = currentQueueIdx;
if (seekWrap && !scrubMeta) {
seekWrap.addEventListener('mouseenter', () => {
if (!scrubMeta) setupScrub(qIdx);
}, { once: true });
}
buildCanvas(parseInt(p[3]), parseInt(p[4]));
// DCT is explicitly negotiated. Each seek/reinit owns a new
// decoder so late results cannot change the new predictor.
resetFramePipeline();
// Sequential decode queue — reset on each new stream so deltas
// never race ahead of keyframes across playlist transitions.
decodeQueue = Promise.resolve();
// ── AUDIO READY GATE ──
// Hold rendering until audio actually starts. Without this, the
// master clock (audioEl.currentTime) snaps forward the moment audio
// loads, making renderFrame think it's behind and draining the whole
// buffer in one go — visible as a sudden freeze on heavy footage.
// The decodeQueue above already prevents delta/keyframe races, so
// restoring the gate does NOT bring back the old startup stutter.
const wasPaused = (state === 'PAUSED');
readyToRender = false;
if (!wasPaused) state = 'PLAYING';
streamStartTime = performance.now() - audioOffset * 1000;
if (wasPaused) pauseStartTime = performance.now();
loadAudio();
// Re-push prefs after INIT — server filter state starts at defaults
// on each new stream, so a restored UI alone would not affect frames.
sendFilters();
return;
}
// STATUS:<CODE>:<human-readable text> — e.g. the server tells us a
// YouTube/ytdlp fetch is starting. MUST return here: any string that
// falls through below is parsed as a Mode-1 text frame.
if (event.data.startsWith('STATUS:')) {
const msgStart = event.data.indexOf(':', 7);
if (msgStart !== -1) showToast(event.data.slice(msgStart + 1), true);
return;
}
// Mode 1: Text Frame with Timestamp
if (pendingSeekId !== null) return;
const text = event.data;
const newlineIdx = text.indexOf('\n');
const frameIndex = parseInt(text.substring(0, newlineIdx));
const frameTime = frameIndex / targetFps;
const frameData = text.substring(newlineIdx + 1);
playbackMetrics.latestTime = frameTime;
frameBuffer.push({ data: frameData, time: frameTime });
triggerPlaybackStart(streamEpoch);
} else {
if (pendingSeekId !== null) return;
// Binary Frames — decoded via adaptive codec (raw/zlib/delta)
if (codecDecoder) {
const epoch = streamEpoch;
const decoder = codecDecoder;
framesInFlight++;
// Chain onto the sequential queue so deltas always patch the
// correct preceding frame, never racing ahead of a keyframe.
decodeQueue = decodeQueue.then(() => {
if (epoch !== streamEpoch) return;
const decodeStarted = performance.now();
return decoder.decode(event.data).then(({ frameIndex, frame }) => {
if (epoch !== streamEpoch) return;
framesInFlight--;
const frameTime = frameIndex / targetFps;
playbackMetrics.decodeMs += performance.now() - decodeStarted;
playbackMetrics.decoded++;
playbackMetrics.latestTime = frameTime;
frameBuffer.push({ data: frame, time: frameTime });
while (frameBuffer.length > BUFFER_SIZE * 5) frameBuffer.shift();
triggerPlaybackStart(epoch);
}).catch(e => {
if (epoch !== streamEpoch) return;
framesInFlight--;
playbackMetrics.decodeErrors++;
console.error("Decode error", e);
});
});
} else {
// Fallback: legacy 4-byte header
const buffer = event.data;
const view = new DataView(buffer);
const frameIndex = view.getUint32(0, false);
const frameTime = frameIndex / targetFps;
const frameData = new Uint8Array(buffer, 4);
playbackMetrics.latestTime = frameTime;
frameBuffer.push({ data: frameData, time: frameTime });
triggerPlaybackStart(streamEpoch);
}
}
while (frameBuffer.length > BUFFER_SIZE * 5) frameBuffer.shift();
};
ws.onopen = () => { statusEl.textContent = 'Buffering...'; };
ws.onclose = (event) => {
if (state === 'PLAYING' || state === 'PAUSED') {
// 1000 = server closed cleanly after finishing the queue. Anything
// else (1006 dropped TCP, 1001/1012 server shutdown) is a real drop.
const ended = event.code === 1000;
if (!ended) showToast('Connection lost.');
statusEl.textContent = ended ? 'Stream Ended.' : 'Connection lost.';
statusEl.style.color = '#888';
if (audioEl) audioEl.pause();
setTimeout(() => finishStream(), 800);
}
};
ws.onerror = () => {
showToast('Connection lost.');
statusEl.textContent = 'Connection Error!';
statusEl.style.color = '#ff0000';
setTimeout(() => finishStream(), 2000);
};
}
// ═══════════════════════════════════════
// RENDER LOOP
// ═══════════════════════════════════════
function renderFrame(now) {
if (state !== 'PLAYING' || !readyToRender) return;
scheduleRender();
const masterClock = getMasterClock();
if (now - lastFpsUpdate >= 1000) {
currentFps = Math.round(frameCount * 1000 / (now - lastFpsUpdate));
frameCount = 0;
lastFpsUpdate = now;
const modes = { 2: '64 Color', 3: '512 Color', 4: '32K Color', 5: '262K Color', 6: '16M Ultra' };
const label = (modes[renderMode] || 'B&W') + (pixelMode ? ' PIXEL' : '');
statusEl.textContent = `FPS: ${currentFps}/${Math.round(targetFps)} | Buf: ${frameBuffer.length} | ${label}`;
}
if (!isSeeking && seekBar) {
if (now - lastUiUpdateTime >= 100) {
seekBar.value = masterClock;
if (seekPlayed && duration) seekPlayed.style.transform = `scaleX(${Math.min(1, masterClock / duration)})`;
lastUiUpdateTime = now;
}
const formattedTime = formatTime(masterClock);
if (timeCurrent && formattedTime !== lastFormattedTime) {
timeCurrent.textContent = formattedTime;
lastFormattedTime = formattedTime;
}
}
if (frameBuffer.length === 0) return;
let frameObj;
if (isWebcamStream) {
// ZERO-LATENCY MODE: Grab the absolute newest frame, trash all older ones.
frameObj = frameBuffer.pop();
frameBuffer.length = 0; // Empty the buffer
} else {
// A/V Sync: Drop frames that are too far behind the master clock (catch up)
while (frameBuffer.length > 0 && frameBuffer[0].time < masterClock - 0.1) {
frameBuffer.shift();
playbackMetrics.lateDrops++;
}
if (frameBuffer.length === 0) return;
// A/V Sync: Wait if the frame is in the future
if (frameBuffer[0].time > masterClock + 0.05) {
return;
}
frameObj = frameBuffer.shift();
}
const frame = frameObj.data;
const renderStarted = performance.now();
frameCount++;
lastRenderTime = now;
if (reliefActive()) {
// 3D view: the frame bytes go to the GPU unchanged; the 2D layers are hidden.
relief.update(frame);
if (typeof frame === 'string') {
player.textContent = frame; // mode 1: keep "copy frame" current
} else if (!pixelMode) {
// Keep the hidden text layer current so "copy frame" still copies this frame.
for (let i = 0, cell = 0; i < frame.length; i += 4, cell++) {
selectionBuffer[Math.floor(cell / gridCols) * (gridCols + 1) + cell % gridCols] = frame[i];
}
player.textContent = textDecoder.decode(selectionBuffer);
}
} else if (pixelMode) {
// ── ZERO-COPY PIXEL MODE ──
// Server sends raw BGR (3 bytes/pixel). We swap B↔R here.
const view = frame; // Already a Uint8Array
const data = dotImageData.data;
// view: [B,G,R, B,G,R, ...] → data: [R,G,B,A, R,G,B,A, ...]
for (let src = 0, dst = 0; src < view.length; src += 3, dst += 4) {
data[dst] = view[src + 2]; // R (from BGR)
data[dst + 1] = view[src + 1]; // G
data[dst + 2] = view[src]; // B
// Alpha already set to 255 in buildCanvas
}
ctx.putImageData(dotImageData, 0, 0);
} else if (renderMode === 1) {
player.style.display = 'block';
player.style.color = '#fff';
player.textContent = frame;
} else {
// ── STANDARD COLOR MODES (2-5): fillText per character ──
const view = frame; // Already a Uint8Array
// 1. Draw Canvas (Background)
ctx.fillStyle = '#050505';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = 'bold 8px Courier New';
ctx.textBaseline = 'top';
let col = 0, row = 0, prevPacked = -1;
for (let idx = 0; idx < view.length; idx += 4) {
const packed = (view[idx+1] << 16) | (view[idx+2] << 8) | view[idx+3];
if (packed !== prevPacked) {
ctx.fillStyle = `rgb(${view[idx+1]},${view[idx+2]},${view[idx+3]})`;
prevPacked = packed;
}
ctx.fillText(CHAR_LUT[view[idx]], xPos[col], yPos[row]);
// Fill Selection Buffer (char code is at view[idx])
selectionBuffer[row * (gridCols + 1) + col] = view[idx];
col++;
if (col >= gridCols) { col = 0; row++; }
}
// 2. Update Selection Layer (Foreground)
player.style.display = 'block';
player.style.color = 'transparent';
player.textContent = textDecoder.decode(selectionBuffer);
}
playbackMetrics.renderMs += performance.now() - renderStarted;
playbackMetrics.rendered++;
playbackMetrics.displayTime = frameObj.time;
}
// ═══════════════════════════════════════
// CLEANUP
// ═══════════════════════════════════════
// ── BACKPRESSURE REPORTING ──
// Tell the server how many frames are currently stuck in the decode pipeline
// (framesInFlight). When it grows, the client is CPU-bound, and the server
// drops frames instead of making us inflate+delta-patch them.
let framesInFlight = 0;
// Epoch-local averages and counters for --debug server diagnostics. Decode time
// excludes waiting for earlier packets; framesInFlight measures that queue.
let playbackMetrics = { decodeMs: 0, decoded: 0, renderMs: 0, rendered: 0,
lateDrops: 0, decodeErrors: 0, latestTime: null };
// Sequential promise chain that serialises async codec decodes so a fast
// Delta never races ahead of a slow Keyframe/ZLIB inflate.
let decodeQueue = Promise.resolve();
function startBufferReports() {
stopBufferReports();
bufferReportTimer = setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN && state === 'PLAYING') {
ws.send(JSON.stringify({
type: 'buffer', depth: framesInFlight,
decodeMs: playbackMetrics.decoded ? playbackMetrics.decodeMs / playbackMetrics.decoded : null,
renderMs: playbackMetrics.rendered ? playbackMetrics.renderMs / playbackMetrics.rendered : null,
lagMs: playbackMetrics.latestTime === null ? null
: Math.max(0, (getMasterClock() - playbackMetrics.latestTime) * 1000),
lateDrops: playbackMetrics.lateDrops,
decodeErrors: playbackMetrics.decodeErrors,
requestId: syncId,
decoded: playbackMetrics.decoded,
rendered: playbackMetrics.rendered,
renderBuffer: frameBuffer.length,
clock: getMasterClock(),
displayTime: playbackMetrics.displayTime ?? null,
hidden: document.hidden === true,
}));
}
}, 250);
}
function stopBufferReports() {
if (bufferReportTimer) { clearInterval(bufferReportTimer); bufferReportTimer = null; }
}
// Unexpected disconnect toast. Lazy-created; safe to call twice (onerror+onclose).
// Pass sticky=true to keep it up until hideToast() (e.g. a fetch in progress).
let toastHideTimer = null;
let toastSticky = false;
function showToast(msg, sticky) {
let el = document.getElementById('connection-toast');
if (!el) {
el = document.createElement('div');
el.id = 'connection-toast';
el.className = 'toast';
el.setAttribute('role', 'status');
el.setAttribute('aria-live', 'polite');
container.appendChild(el);
}
el.textContent = msg;
el.classList.add('show');
toastSticky = !!sticky;
clearTimeout(toastHideTimer);
toastHideTimer = null;
if (!sticky) {
toastHideTimer = setTimeout(() => el.classList.remove('show'), 4000);
}
}
function hideToast() {
clearTimeout(toastHideTimer);
toastHideTimer = null;
toastSticky = false;
const el = document.getElementById('connection-toast');
if (el) el.classList.remove('show');
}
// Clear only a sticky (fetch-in-progress) toast — leaves a transient
// "Connection lost." toast to run out its own timer.
function hideStickyToast() {
if (toastSticky) hideToast();
}
function finishStream() {
resetPlaybackStart();
streamEpoch++;
pendingSeekId = null;
syncId = null;
audioClockActive = false;
resumeNeedsAudioSeek = false;
state = 'IDLE';
stopBufferReports();
hideStickyToast(); // a fetch notice must never outlive the stream
if (ws) { ws.onclose = null; ws.close(); ws = null; }
if (audioEl) { audioEl.pause(); audioEl.src = ''; }
ctx.clearRect(0, 0, canvas.width, canvas.height);
player.textContent = '';
player.style.display = 'none';
container.classList.remove('paused');
overlay.classList.remove('hidden');
statusEl.textContent = 'Ready';
statusEl.style.color = 'rgba(255,255,255,0.6)';
if (playPauseBtn) playPauseBtn.textContent = '▶';
readyToRender = false;
pauseStartTime = 0;
frameBuffer.length = 0;
}
// ═══════════════════════════════════════
// PAUSE / RESUME
// ═══════════════════════════════════════
function togglePause() {
if (isWebcamStream) return; // Can't pause a live broadcast!
if (state === 'PLAYING') {
const pausedAt = getMasterClock();
resumeNeedsAudioSeek = readyToRender && !audioClockActive;
state = 'PAUSED';
resetPlaybackStart();
pauseStartTime = performance.now();
streamStartTime = pauseStartTime - pausedAt * 1000;
if (audioEl && !audioEl.paused) {
audioEl.pause();
}
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'pause', paused: true }));
}
container.classList.add('paused');
if (playPauseBtn) playPauseBtn.textContent = '▶';
statusEl.textContent = '❚❚ PAUSED';
statusEl.style.color = '#888';
} else if (state === 'PAUSED') {
const resumeAt = getMasterClock();
state = 'PLAYING';
resetPlaybackStart();
// Update streamStartTime to account for the pause duration
const pauseDuration = performance.now() - pauseStartTime;
streamStartTime += pauseDuration;
pauseStartTime = 0;
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'pause', paused: false }));
}
container.classList.remove('paused');
statusEl.textContent = 'Resuming...';
statusEl.style.color = 'var(--accent-color)';
// Restart render loop
if (playPauseBtn) playPauseBtn.textContent = '❚❚';
lastRenderTime = performance.now();
lastFpsUpdate = performance.now();
frameCount = 0;
// If autoplay/audio failed earlier, its currentTime may still be zero.
// Reload both tracks at the wall-clock position before trying again.
if (resumeNeedsAudioSeek) doSeek(resumeAt);
else triggerPlaybackStart(streamEpoch);
}
}
if (playPauseBtn) {
playPauseBtn.addEventListener('click', (e) => {
e.stopPropagation();
if (state === 'IDLE') startStream();
else togglePause();
});
}
// Seek to an absolute time. Reuses the live seek (tell the server, then reload
// the audio from that point). Shared by the slider and the skip buttons.
function doSeek(targetSec) {
if (isWebcamStream) return; // Can't seek a live broadcast!
if (!Number.isFinite(targetSec)) return;
if (duration) targetSec = Math.max(0, Math.min(targetSec, duration));
if (seekBar) seekBar.value = targetSec;
if (seekPlayed && duration) seekPlayed.style.transform = `scaleX(${Math.min(1, targetSec / duration)})`;
resetPlaybackStart();
resumeNeedsAudioSeek = false;
statusEl.textContent = 'Seeking...';
streamEpoch++;
resetFramePipeline();
audioClockActive = false;
audioOffset = targetSec;
streamStartTime = performance.now() - targetSec * 1000;
if (state === 'PAUSED') pauseStartTime = performance.now();
if (audioEl) audioEl.pause();
pendingSeekId = syncId !== null ? streamEpoch : null;
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'seek', time: targetSec, requestId: streamEpoch }));
}
// A coordinated server confirms the exact decoded position first. Frames
// arriving before that marker belong to the old timeline and are ignored.
if (pendingSeekId === null) loadAudio();
}
function getMasterClock() {
// audioEl.currentTime is frozen when paused — correct in both states.
// Only fall back to the wall-clock estimate when audio hasn't loaded yet.
if (pendingSeekId !== null) return audioOffset;
if (audioClockActive && audioEl && audioEl.readyState >= 1) return audioEl.currentTime + audioOffset;
if (state === 'PAUSED') return (pauseStartTime - streamStartTime) / 1000.0;
if (!readyToRender) return audioOffset;
return (performance.now() - streamStartTime) / 1000.0;
}
function skip(delta) {
if (state !== 'PLAYING' && state !== 'PAUSED') return;
if (!duration) return;
doSeek(getMasterClock() + delta);
}
// Pull the hover thumbnail sprite for this video (built lazily by the server).
function setupScrub(v) {
scrubMeta = null;
if (seekPreviewImg) seekPreviewImg.style.backgroundImage = '';
fetch('/scrub?v=' + (v || 0) + '&t=' + Date.now()).then(r => r.json()).then(m => {
if (!m || !m.available || !seekPreviewImg) return;
scrubMeta = m;
seekPreviewImg.style.width = m.cellW + 'px';
seekPreviewImg.style.height = m.cellH + 'px';
seekPreviewImg.style.backgroundImage = `url(${m.sprite})`;
seekPreviewImg.style.backgroundSize = (m.gridCols * m.cellW) + 'px ' + (m.gridRows * m.cellH) + 'px';
}).catch(() => {});
}
function onSeekHover(e) {
if (!scrubMeta || !duration || !seekWrap) return;
const rect = seekWrap.getBoundingClientRect();
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
const time = (x / rect.width) * duration;
const idx = Math.max(0, Math.min(Math.floor(time / scrubMeta.interval), scrubMeta.count - 1));
const col = idx % scrubMeta.gridCols, row = Math.floor(idx / scrubMeta.gridCols);
seekPreviewImg.style.backgroundPosition = `-${col * scrubMeta.cellW}px -${row * scrubMeta.cellH}px`;
seekPreviewTime.textContent = formatTime(time);
const half = scrubMeta.cellW / 2;
seekPreview.style.left = Math.max(half, Math.min(x, rect.width - half)) + 'px';
seekPreview.classList.add('show');
}
if (seekBar) {
seekBar.addEventListener('input', () => {
isSeeking = true;
if (timeCurrent) timeCurrent.textContent = formatTime(seekBar.value);
});
seekBar.addEventListener('change', () => {
doSeek(parseFloat(seekBar.value));
isSeeking = false;
});
}
if (btnBack) btnBack.addEventListener('click', (e) => { e.stopPropagation(); skip(-10); });
if (btnFwd) btnFwd.addEventListener('click', (e) => { e.stopPropagation(); skip(10); });
if (btnCopy) {
btnCopy.addEventListener('click', async (e) => {
e.stopPropagation();
if (pixelMode) return;
try {
const rawText = player.textContent || '';
if (!rawText.trim()) {
showCopyTooltip('NO FRAME');
return;
}
if (!navigator.clipboard) {
throw new Error('Clipboard API unavailable (requires secure HTTPS/localhost context)');
}
// 1. Plain text uses untouched LF (\n) to avoid ^M artifacts on Mac/Linux terminals
const plainText = rawText;
// 2. Rich HTML for rich text targets (Google Docs, Word, Notion, email clients)
const escaped = rawText
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
const htmlContent = `<pre style="background-color:#050505;color:#ffffff;font-family:'Courier New',Consolas,monospace;font-size:8px;line-height:8px;letter-spacing:0;white-space:pre;margin:0;padding:8px;display:inline-block;">${escaped}</pre>`;
let copied = false;
if (typeof navigator.clipboard.write === 'function' && typeof window.ClipboardItem !== 'undefined') {
try {
const textBlob = new Blob([plainText], { type: 'text/plain' });
const htmlBlob = new Blob([htmlContent], { type: 'text/html' });
await navigator.clipboard.write([
new ClipboardItem({
'text/plain': textBlob,
'text/html': htmlBlob
})
]);
copied = true;
} catch (_) {
// Fallback to standard writeText if HTML mime is rejected by browser/OS
}
}
if (!copied) {
await navigator.clipboard.writeText(plainText);
}
showCopyTooltip('COPIED!');
} catch (error) {
console.error('Failed to copy ASCII frame:', error);
showCopyTooltip('COPY FAILED');
}
});
}
if (seekWrap) {
seekWrap.addEventListener('mousemove', onSeekHover);
seekWrap.addEventListener('mouseleave', () => { if (seekPreview) seekPreview.classList.remove('show'); });
}
// ── EVENT LISTENERS ──
overlay.addEventListener('click', (e) => {
e.stopPropagation();
startStream();
});
// ── PAUSE TOGGLE (click on player area) ──
container.addEventListener('click', (e) => {
if (e.target.closest('#play-overlay')) return;
if (window.getSelection().toString().length > 0) return;
togglePause();
});
// ── KEYBOARD: Space to pause, Arrows to seek, F for filters ──
document.addEventListener('keydown', (e) => {
if (state === 'PLAYING' || state === 'PAUSED') {
if (e.code === 'Space') {
e.preventDefault();
togglePause();
} else if (e.code === 'ArrowRight') {
e.preventDefault();
btnFwd.click(); // Trigger forward 10s logic
} else if (e.code === 'ArrowLeft') {
e.preventDefault();
btnBack.click(); // Trigger backward 10s logic
}
}
});
const PREF_VOLUME = 'asciline_volume';
const PREF_FILTERS = 'asciline_filters';
if (volumeSlider) {
const savedVol = localStorage.getItem(PREF_VOLUME);
if (savedVol !== null) {
const vol = Math.min(1, Math.max(0, parseFloat(savedVol)));
if (!Number.isNaN(vol)) {
volumeSlider.value = vol;
if (audioEl) audioEl.volume = vol;
}
}
volumeSlider.addEventListener('input', () => {