-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_backup_script.js
More file actions
1432 lines (1248 loc) · 51.6 KB
/
_backup_script.js
File metadata and controls
1432 lines (1248 loc) · 51.6 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
const socket = window.socket || io('/', {
transports: ['polling']
})
// keep a global reference to avoid redeclaration errors if script loads twice
window.socket = socket
const videoGrid = document.getElementById('video-grid')
// Determine room id: prefer server-provided, else extract last URL segment as in client
const ROOM_ID = (function() {
if (window.ROOM_ID) return window.ROOM_ID
const pathSegments = window.location.pathname.split('/').filter(s => s)
const urlRoomId = pathSegments[pathSegments.length - 1]
const isValidRoomId = urlRoomId && !['room','video','home'].includes(urlRoomId)
return isValidRoomId ? urlRoomId : 'default-room'
})()
console.log('Viewinter frontend (backend/public/script.js) starting — ROOM_ID:', ROOM_ID, 'URL:', window.location.href)
let myPeer
let myPeerInitialized = false
let myStream
const peers = {}
let pendingUsers = []
let myVAD = null
let isTranscriptionEnabled = false
let myUserName = `User${Math.floor(Math.random() * 10000)}`
let myUserId = null
let myTargetLanguage = '' // Target language for translation
const videoContainers = new Map() // Map userId -> container element
// Anime4K low-resolution decision threshold (only enhance if both width and height are <= these)
const ANIME4K_LOW_RES_THRESHOLD = { maxWidth: 480, maxHeight: 360 }
function isVideoLowResolution(videoEl) {
const w = videoEl?.videoWidth || videoEl?.clientWidth || 0
const h = videoEl?.videoHeight || videoEl?.clientHeight || 0
if (!w || !h) return null // unknown yet (metadata not loaded)
return (w <= ANIME4K_LOW_RES_THRESHOLD.maxWidth && h <= ANIME4K_LOW_RES_THRESHOLD.maxHeight)
}
// Global Anime4K state shared across functions
let globalAnimeState = {
enabled: false,
streams: new Map(), // userId -> { worker, workerReady, loopId, shuttingDown, sizeLocked }
shaderLoaded: false,
// Track per-user auto-disable cooldowns so we don't immediately re-enable a stream that was just auto-disabled
disabledCooldowns: new Map()
}
// Logging utility
function log(category, message, data = null) {
const timestamp = new Date().toISOString().split('T')[1].slice(0, -1)
const logMessage = `[${timestamp}] [${category}] ${message}`
console.log(logMessage, data || '')
// Also log to UI status panel
const statusLog = document.getElementById('status-log')
if (statusLog) {
const logEntry = document.createElement('div')
logEntry.textContent = `${timestamp.split('.')[0]} ${category}: ${message}`
statusLog.insertBefore(logEntry, statusLog.firstChild)
// Keep only last 10 entries
while (statusLog.children.length > 10) {
statusLog.removeChild(statusLog.lastChild)
}
}
}
// Configure ONNX Runtime for VAD
if (typeof ort !== 'undefined') {
ort.env.wasm.wasmPaths = '/ort/'
log('INIT', 'ONNX Runtime configured with WASM paths')
}
// Anime4K worker and shader cache (per script2 reference)
const anime4kShaderCandidates = [
'/ported_shaders/upscale_cnn_x2_s.frag',
'/ported_shaders/anime4k-webgl.frag'
]
let anime4kShaderCode = null
let anime4kLoadedPath = null
async function ensureShaderLoaded() {
if (anime4kShaderCode) return anime4kShaderCode
let lastErr = null
for (const p of anime4kShaderCandidates) {
try {
const res = await fetch(p)
if (res.ok) {
anime4kShaderCode = await res.text()
anime4kLoadedPath = p
console.info('Loaded Anime4K shader from', p)
try { setStatus(`Shader loaded: ${p}`, 'info') } catch (e) {}
return anime4kShaderCode
} else {
lastErr = new Error(`Failed to fetch shader ${p}: ${res.status} ${res.statusText}`)
}
} catch (err) {
lastErr = err
}
}
try { setStatus('Failed to load any Anime4K shader', 'error') } catch (e) {}
throw lastErr || new Error('No Anime4K shader candidates found')
}
// Utility: set a short status message shown in UI
function setStatus(msg, level = 'info') {
const el = document.getElementById('status-bar')
if (el) {
el.textContent = msg
el.classList.remove('info','error')
el.classList.add(level)
}
console.log('STATUS:', msg)
}
// Test TURN server connectivity
function testTurnServer(turnConfig) {
return new Promise((resolve, reject) => {
console.log('Testing TURN config:', turnConfig)
const pc = new RTCPeerConnection({ iceServers: [turnConfig] })
let gotRelay = false
pc.onicecandidate = (e) => {
if (e.candidate) {
console.log('Test ICE candidate:', e.candidate.type, e.candidate.protocol, e.candidate.address)
if (e.candidate.type === 'relay') {
console.log('TURN server is working! Got relay candidate:', e.candidate)
console.log('✅ TURN server is working! Got relay candidate:', e.candidate)
try { setStatus('TURN server working (relay candidate obtained)', 'info') } catch(e){}
gotRelay = true
pc.close()
resolve('TURN server working - relay candidate obtained')
}
}
}
pc.onicegatheringstatechange = () => {
console.log('Test ICE gathering state:', pc.iceGatheringState)
if (pc.iceGatheringState === 'complete') {
pc.close()
if (!gotRelay) {
try { setStatus('TURN server did not produce relay candidates', 'error') } catch(e){}
reject('TURN server not producing relay candidates - may be blocked or auth failed')
}
}
}
// Create a dummy data channel to trigger ICE gathering
pc.createDataChannel('test')
pc.createOffer().then(offer => pc.setLocalDescription(offer))
// Timeout after 10 seconds
setTimeout(() => {
if (!gotRelay) {
pc.close()
try { setStatus('TURN server test timeout - likely blocked by firewall/network', 'error') } catch(e){}
reject('TURN server test timeout - likely blocked by firewall/network')
}
}, 10000)
})
}
async function initializePeer() {
console.log('\n╔════════════════════════════════════════╗')
console.log('║ INITIALIZING PEER CONNECTION ║')
console.log('╚════════════════════════════════════════╗')
try {
console.log('⏳ Waiting for socket connection...')
await new Promise((resolve) => {
if (socket && socket.connected) return resolve()
socket.on('connect', resolve)
// fallback resolve after 5s to avoid hanging forever
setTimeout(resolve, 5000)
})
console.log('✅ Socket connected or timed out, fetching TURN credentials...')
const res = await fetch('https://octopus-app-ubcv5.ondigitalocean.app/api/turn-credentials')
const data = await res.json()
console.log('✅ Got TURN credentials:', (data.iceServers || []).length, 'servers')
(data.iceServers || []).forEach((s, idx) => console.log(` [${idx}] ${s.urls}`))
const turnServers = (data.iceServers || []).filter(s => s.urls && s.urls.some(u => u.includes('turn')))
if (turnServers.length > 0) {
console.log('Testing TURN server connectivity...')
testTurnServer(turnServers[0]).then(result => console.log('TURN server test result:', result)).catch(err => console.warn('TURN server test failed:', err))
} else {
console.warn('NO TURN servers found in ICE config!')
}
myPeer = new Peer({
host: 'octopus-app-ubcv5.ondigitalocean.app',
path: '/peerjs',
secure: true,
config: {
iceServers: data.iceServers
}
})
setupPeerListeners()
await startMedia()
} catch (err) {
console.error('❌ Failed to initialize peer with TURN:', err)
console.log('⚠️ Falling back to peer without TURN credentials')
myPeer = new Peer({
host: 'octopus-app-ubcv5.ondigitalocean.app',
path: '/peerjs',
secure: true
})
setupPeerListeners()
await startMedia()
}
}
initializePeer()
function setupPeerListeners() {
myPeer.on('open', id => {
myPeerInitialized = true
myUserId = id
log('PEER', `My peer ID assigned: ${id}`)
log('SOCKET', `Joining room: ${ROOM_ID}`)
socket.emit('join-room', ROOM_ID, id, myUserName)
// If users joined while we were not ready, process them now
if (pendingUsers.length > 0 && myStream) {
processPendingUsers()
}
})
myPeer.on('error', err => {
console.error('PeerJS error:', err)
})
}
function startMedia() {
const myVideo = document.createElement('video')
myVideo.muted = true
pendingUsers = pendingUsers || [] // Ensure pendingUsers array exists (managed globally)
console.log('Starting media access...')
// Handle initial list of users already in room
socket.on('room-users', users => {
console.log('Users already in room:', users)
if (myStream && users.length > 0) {
users.forEach(userId => {
console.log('Connecting to existing user:', userId)
connectToNewUser(userId, myStream)
})
} else if (users.length > 0) {
// Merge into pending users to call after we get our stream
pendingUsers = Array.from(new Set([...(pendingUsers || []), ...users]))
console.log('Stored pending users to call after getting stream:', pendingUsers)
}
})
// Set up user-connected listener BEFORE getting media
socket.on('user-connected', userId => {
console.log('User connected:', userId)
if (!myPeerInitialized) {
console.log('Peer not initialized yet, queuing user:', userId)
if (!pendingUsers.includes(userId)) pendingUsers.push(userId)
return
}
if (myStream) {
connectToNewUser(userId, myStream)
} else {
console.log('Waiting for local stream before connecting, queuing user:', userId)
if (!pendingUsers.includes(userId)) pendingUsers.push(userId)
}
})
socket.on('user-disconnected', userId => {
console.log('User disconnected:', userId)
if (peers[userId]) {
console.log('Closing peer connection and removing video for:', userId)
peers[userId].close()
delete peers[userId]
}
// Remove the video container from videoContainers Map
const containerData = videoContainers.get(userId)
if (containerData) {
console.log('Removing video container for:', userId)
containerData.container.remove()
videoContainers.delete(userId)
} else {
// Fallback: try to find and remove by video element
const videoElements = document.querySelectorAll('video')
videoElements.forEach(video => {
if (video.dataset.userId === userId) {
console.log('Removing video element (fallback) for:', userId)
const container = video.closest('.video-container')
if (container) {
container.remove()
} else {
video.remove()
}
}
})
}
})
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(stream => {
console.log('Got local stream')
myStream = stream
addVideoStream(myVideo, stream)
// Broadcast username to room
if (myUserId) {
socket.emit('update-username', {
roomId: ROOM_ID,
userId: myUserId,
userName: myUserName
})
log('USER', `Broadcasted initial username: ${myUserName}`)
}
// Auto-enable transcription
isTranscriptionEnabled = true
updateTranscriptionButton(true)
initializeVAD()
log('TRANSCRIPTION', 'Auto-enabled transcription after getting stream')
// Call any users who were in the room before we got our stream
if (pendingUsers.length > 0) {
console.log('Calling pending users:', pendingUsers)
processPendingUsers()
}
myPeer.on('call', call => {
console.log('Receiving call from:', call.peer)
call.answer(stream)
const video = document.createElement('video')
video.dataset.userId = call.peer
// Monitor connection state for incoming calls too
if (call.peerConnection) {
console.log('Setting up peerConnection event handlers for incoming call from', call.peer)
console.log('Initial ICE connection state (incoming):', call.peerConnection.iceConnectionState)
console.log('Initial connection state (incoming):', call.peerConnection.connectionState)
call.peerConnection.oniceconnectionstatechange = () => {
const state = call.peerConnection.iceConnectionState
console.log(`🔄 ICE connection state with ${call.peer}:`, state)
if (state === 'failed' || state === 'disconnected') {
console.error(`Connection ${state} with ${call.peer}`)
} else if (state === 'connected' || state === 'completed') {
console.log(`Successfully connected to ${call.peer}!`)
}
}
call.peerConnection.onconnectionstatechange = () => {
console.log(`🔄 Peer connection state with ${call.peer}:`, call.peerConnection.connectionState)
}
} else {
console.error('No peerConnection object for incoming call from', call.peer)
}
call.on('stream', userVideoStream => {
console.log('Received remote stream from:', call.peer)
// Check if we already have a video for this user
const existingVideo = document.querySelector(`video[data-user-id="${call.peer}"]`)
if (existingVideo) {
console.log('Already have video element for', call.peer, '- skipping duplicate')
return
}
addVideoStream(video, userVideoStream)
})
call.on('close', () => {
console.log('Incoming call closed with:', call.peer)
video.remove()
})
call.on('error', err => {
console.error('Incoming call error with', call.peer, ':', err)
})
peers[call.peer] = call
})
}).catch(err => {
console.error('Media access error:', err)
})
}
function connectToNewUser(userId, stream) {
console.log('Calling user:', userId)
const call = myPeer.call(userId, stream)
if (!call) {
console.error('Failed to create call - PeerJS may be disconnected')
return
}
const video = document.createElement('video')
// Monitor connection state
if (call.peerConnection) {
console.log('Setting up peerConnection event handlers for', userId)
console.log('Initial ICE connection state:', call.peerConnection.iceConnectionState)
console.log('Initial connection state:', call.peerConnection.connectionState)
call.peerConnection.oniceconnectionstatechange = () => {
const state = call.peerConnection.iceConnectionState
console.log(`🔄 ICE connection state with ${userId}:`, state)
if (state === 'failed' || state === 'disconnected') {
console.error(`Connection ${state} with ${userId}, relay may not be working`)
} else if (state === 'connected' || state === 'completed') {
console.log(`Successfully connected to ${userId}!`)
}
}
call.peerConnection.onconnectionstatechange = () => {
console.log(`🔄 Peer connection state with ${userId}:`, call.peerConnection.connectionState)
}
} else {
console.error('No peerConnection object for', userId)
call.peerConnection.onicecandidate = (event) => {
if (event.candidate) {
const c = event.candidate
console.log(`ICE candidate for ${userId}:`, c.type, c.protocol, c.address || 'no-address')
if (c.type === 'relay') {
console.log('🎉 RELAY (TURN) CANDIDATE FOUND!', c)
}
} else {
console.log(`ICE candidate gathering complete for ${userId}`)
}
}
call.peerConnection.onicegatheringstatechange = () => {
console.log(`ICE gathering state with ${userId}:`, call.peerConnection.iceGatheringState)
}
}
call.on('stream', userVideoStream => {
console.log('Received stream from new user:', userId)
// Check if we already have a video for this user
const existingVideo = document.querySelector(`video[data-user-id="${userId}"]`)
if (existingVideo) {
console.log('Already have video element for', userId, '- skipping duplicate')
return
}
video.dataset.userId = userId // Tag video with user ID for cleanup
addVideoStream(video, userVideoStream)
})
call.on('close', () => {
console.log('Call closed with:', userId)
const container = video.closest('.stream-container')
if (container) container.remove()
else video.remove()
})
call.on('error', err => {
console.error('Call error with', userId, ':', err)
})
peers[userId] = call
}
function processPendingUsers() {
if (pendingUsers.length === 0) return
console.log('Processing pending users:', pendingUsers)
const usersToConnect = [...pendingUsers]
pendingUsers = []
usersToConnect.forEach((userId) => {
if (myStream) {
console.log('Connecting to pending user:', userId)
connectToNewUser(userId, myStream)
} else {
console.warn('No local stream available to connect to pending user:', userId)
}
})
}
// --- Anime4K per-remote helpers ---
async function enableAnimeForUser(userId) {
if (!userId || userId === 'local') return
// Respect a short cooldown after auto-disable to avoid immediate re-enable
const cooldownUntil = globalAnimeState.disabledCooldowns.get(userId)
if (cooldownUntil && cooldownUntil > Date.now()) {
log('ANIME4K', `Skipping enable for ${userId} due to cooldown`, { cooldownUntil })
return
}
if (globalAnimeState.streams.has(userId)) return // already enabled for this user
const entry = videoContainers.get(userId)
if (!entry) {
console.warn('No container found for user to enable Anime4K:', userId)
return
}
const videoEl = entry.container.querySelector('video')
if (!videoEl) {
console.warn('No video element found for', userId)
return
}
// Decide whether to enhance based on resolution. If unknown (no metadata), wait for it.
const lowRes = isVideoLowResolution(videoEl)
if (lowRes === false) {
log('ANIME4K', `Skipping Anime4K for ${userId} - resolution too high`, { width: videoEl.videoWidth, height: videoEl.videoHeight })
return
} else if (lowRes === null) {
// Wait for metadata to decide
videoEl.addEventListener('loadedmetadata', () => {
const decided = isVideoLowResolution(videoEl)
if (decided) {
// Re-call the enable function to continue flow now that resolution is known
enableAnimeForUser(userId)
} else {
log('ANIME4K', `Skipping Anime4K for ${userId} after metadata - not low-res`, { width: videoEl.videoWidth, height: videoEl.videoHeight })
}
}, { once: true })
return
}
try {
await ensureShaderLoaded()
} catch (err) {
log('ANIME4K', 'Failed to load shader', err)
return
}
const worker = new Worker('/anime4kWorker.js')
const state = { worker, workerReady: false, loopId: null, shuttingDown: false, sizeLocked: false }
globalAnimeState.streams.set(userId, state)
worker.postMessage({ type: 'load-shader', shaderCode: anime4kShaderCode })
const canvas = entry.container.querySelector('canvas')
const ctx = canvas.getContext('2d')
worker.onmessage = e => {
const msg = e.data
if (msg.type === 'shader-ready') {
state.workerReady = true
log('ANIME4K', `Worker ready for ${userId}`)
} else if (msg.type === 'frame' && msg.bitmap) {
// Ignore frames while we're shutting down for this user to avoid race conditions
if (state.shuttingDown) { try { msg.bitmap.close && msg.bitmap.close() } catch(_) {} ; return }
try {
const dpr = window.devicePixelRatio || 1
const displayW = canvas.clientWidth || window.innerWidth || 640
const displayH = canvas.clientHeight || window.innerHeight || 480
const targetW = Math.max(1, Math.floor(displayW * dpr))
const targetH = Math.max(1, Math.floor(displayH * dpr))
if (canvas.width !== targetW || canvas.height !== targetH) {
canvas.width = targetW
canvas.height = targetH
}
ctx.clearRect(0, 0, canvas.width, canvas.height)
try { ctx.setTransform(1,0,0,1,0,0) } catch(e) {}
ctx.imageSmoothingEnabled = true
const bitmapW = msg.bitmap.width
const bitmapH = msg.bitmap.height
// If the source grows beyond the low-res threshold while Anime4K is active, auto-disable for that user
if (bitmapW > ANIME4K_LOW_RES_THRESHOLD.maxWidth || bitmapH > ANIME4K_LOW_RES_THRESHOLD.maxHeight) {
log('ANIME4K', `Detected higher-resolution frame for ${userId}; auto-disabling Anime4K for this user`, { bitmapW, bitmapH })
// Prevent additional frames from being processed while we disable
state.shuttingDown = true
try { msg.bitmap.close && msg.bitmap.close() } catch(_) {}
// set a short cooldown to prevent immediate re-enable
globalAnimeState.disabledCooldowns.set(userId, Date.now() + 5000)
// call handler synchronously to avoid transient layout expansion from a processed frame
try { handleAutoDisable(userId, { reason: 'high-res-detected', bitmapW, bitmapH }) } catch (e) { console.warn('handleAutoDisable error', e) }
return
}
// If not set yet, record initial bitmap size and compute fixed scale to keep framing stable
if (!state.initialBitmapW || !state.initialBitmapH) {
state.initialBitmapW = bitmapW
state.initialBitmapH = bitmapH
state.fixedScale = Math.min(canvas.width / state.initialBitmapW, canvas.height / state.initialBitmapH)
state.fixedScale = Math.max(0.01, Math.min(10, state.fixedScale))
// Lock container's aspect ratio to the source so enabling Anime4K doesn't change visible shape
try {
if (entry && entry.container && !state.aspectLocked) {
// Capture current size and lock the container to the pixel size so turning Anime4K on doesn't expand the layout
const rect = entry.container.getBoundingClientRect()
// Disable transition while we set explicit sizes to avoid animated jumps
entry.container.style.transition = 'none'
// Lock explicit width/height (not min sizes) so the grid cell keeps the current box and doesn't reflow
entry.container.style.width = Math.round(rect.width) + 'px'
entry.container.style.height = Math.round(rect.height) + 'px'
entry.container.style.boxSizing = 'border-box'
// Also set stream container to center content and hide overflow so canvas is centered
const sc = entry.container.querySelector('.stream-container')
if (sc) {
sc.style.display = 'flex'
sc.style.alignItems = 'center'
sc.style.justifyContent = 'center'
sc.style.overflow = 'hidden'
}
// Keep aspect ratio as a hint (helps maintain proportions) and mark as size-locked
entry.container.style.aspectRatio = `${state.initialBitmapW} / ${state.initialBitmapH}`
state.aspectLocked = true
state.sizeLocked = true
log('ANIME4K', `Locked container width/height and aspect ratio for ${userId}`, { w: state.initialBitmapW, h: state.initialBitmapH, rect })
}
} catch (e) {
console.warn('Failed to set aspect ratio/min-size for', userId, e)
}
} else if (bitmapW !== state.initialBitmapW || bitmapH !== state.initialBitmapH) {
// Source resolution changed while still within low-res range; update fixedScale and locked aspect/min sizes
log('ANIME4K', `Source resolution changed for ${userId}; updating scale`, { prevW: state.initialBitmapW, prevH: state.initialBitmapH, bitmapW, bitmapH })
state.initialBitmapW = bitmapW
state.initialBitmapH = bitmapH
state.fixedScale = Math.min(canvas.width / state.initialBitmapW, canvas.height / state.initialBitmapH)
state.fixedScale = Math.max(0.01, Math.min(10, state.fixedScale))
try {
const rect = entry.container.getBoundingClientRect()
// Update explicit width/height to keep visible size steady when source resolution changes
entry.container.style.width = Math.round(rect.width) + 'px'
entry.container.style.height = Math.round(rect.height) + 'px'
entry.container.style.boxSizing = 'border-box'
if (state.aspectLocked) entry.container.style.aspectRatio = `${state.initialBitmapW} / ${state.initialBitmapH}`
state.sizeLocked = true
} catch (e) {
console.warn('Failed updating locked sizes for', userId, e)
}
}
// Use fixedScale based on initial bitmap so later higher-res frames don't cause zoom changes
const drawW = Math.max(1, Math.floor(state.initialBitmapW * state.fixedScale))
const drawH = Math.max(1, Math.floor(state.initialBitmapH * state.fixedScale))
const offsetX = Math.floor((canvas.width - drawW) / 2)
const offsetY = Math.floor((canvas.height - drawH) / 2)
try {
ctx.save()
ctx.imageSmoothingQuality = 'high'
ctx.translate(0, canvas.height)
ctx.scale(1, -1)
// Scale the incoming bitmap to the fixed draw size to preserve stable framing
ctx.drawImage(msg.bitmap, 0, 0, bitmapW, bitmapH, offsetX, canvas.height - offsetY - drawH, drawW, drawH)
ctx.restore()
} catch (e) {
ctx.drawImage(msg.bitmap, 0, 0, bitmapW, bitmapH, offsetX, offsetY, drawW, drawH)
}
} catch (err) {
console.warn('Failed drawing worker frame for', userId, err)
}
try { msg.bitmap.close && msg.bitmap.close() } catch(_) {}
} else if (msg.type === 'log') {
log('ANIME4K', msg.message)
} else if (msg.type === 'error') {
console.error('Anime4K worker error for', userId, msg.message)
}
}
// Prepare display: show canvas and hide remote video
if (canvas) {
canvas.style.display = 'block'
canvas.style.width = '100%'
canvas.style.height = '100%'
canvas.style.objectFit = 'contain'
canvas.style.objectPosition = 'center center'
}
if (videoEl) videoEl.style.display = 'none'
// Add a small transition to prevent jarring resize when locking min sizes
try { entry.container.style.transition = 'min-width 150ms ease, min-height 150ms ease' } catch(e) {}
// Start capture loop
const capture = document.createElement('canvas')
const cctx = capture.getContext('2d')
const loop = async () => {
if (!state.workerReady) {
state.loopId = requestAnimationFrame(loop)
return
}
try {
const w = videoEl.videoWidth || videoEl.clientWidth || 320
const h = videoEl.videoHeight || videoEl.clientHeight || 240
if (!w || !h) { state.loopId = requestAnimationFrame(loop); return }
capture.width = w
capture.height = h
cctx.drawImage(videoEl, 0, 0, capture.width, capture.height)
const img = cctx.getImageData(0, 0, capture.width, capture.height)
state.worker.postMessage({
type: 'frame',
buffer: img.data.buffer,
inputWidth: capture.width,
inputHeight: capture.height,
outputWidth: capture.width,
outputHeight: capture.height,
passes: 1
}, [img.data.buffer])
} catch (err) {
console.warn('Failed to send frame to worker for', userId, err)
}
state.loopId = requestAnimationFrame(loop)
}
state.loopId = requestAnimationFrame(loop)
}
function disableAnimeForUser(userId) {
const state = globalAnimeState.streams.get(userId)
const entry = videoContainers.get(userId)
if (!state) return
// Prevent any queued frames from being processed and clear size lock marker
state.shuttingDown = true
state.sizeLocked = false
if (state.loopId) cancelAnimationFrame(state.loopId)
try { state.worker.terminate() } catch (e) {}
// remove from active streams map now
globalAnimeState.streams.delete(userId)
// Restore canvas/video visibility
if (entry) {
const canvas = entry.container.querySelector('canvas')
const videoEl = entry.container.querySelector('video')
if (canvas) canvas.style.display = 'none'
if (videoEl) {
videoEl.style.display = 'block'
videoEl.style.width = '100%'
videoEl.style.height = '100%'
videoEl.style.objectFit = 'contain'
videoEl.style.objectPosition = 'center center'
}
// Restore container aspect ratio and min-size if we had locked it earlier
try {
if (state && state.aspectLocked) {
// Disable transition to avoid lingering animated shrink that causes cropping
entry.container.style.transition = 'none'
// Force the container to release any locked pixels (set explicit zeroes)
entry.container.style.minWidth = '0'
entry.container.style.minHeight = '0'
entry.container.style.aspectRatio = 'auto'
entry.container.style.width = ''
entry.container.style.height = ''
const sc = entry.container.querySelector('.stream-container')
if (sc) {
sc.style.display = ''
sc.style.alignItems = ''
sc.style.justifyContent = ''
sc.style.overflow = ''
}
// Force reflow so the browser recomputes layout immediately
/* eslint-disable no-unused-expressions */ void entry.container.offsetHeight /* eslint-enable no-unused-expressions */
// Additional resets to fully release layout anchors
entry.container.style.minWidth = '0'
entry.container.style.minHeight = '0'
entry.container.style.maxWidth = ''
entry.container.style.maxHeight = ''
entry.container.style.width = ''
entry.container.style.height = ''
entry.container.style.boxSizing = ''
// Try to ensure the video can resize naturally: clear inline size on the video and replay
try {
if (videoEl) {
videoEl.style.width = ''
videoEl.style.height = ''
videoEl.style.objectFit = 'contain'
// small play/pause cycle can force re-evaluation in some browsers
videoEl.pause();
videoEl.play().catch(() => {})
}
} catch(e) { console.warn('Error resetting video element styles for', userId, e) }
// As a final aggressive layout reset, perform a clone-and-replace of the outer container to force immediate reflow
try {
const parent = entry.container.parentNode
if (parent) {
const next = entry.container.nextSibling
const label = entry.userLabel
const subtitle = entry.subtitleOverlay
// Create a shallow clone of the container (no children) and move the children into it to preserve media nodes/events
const fresh = entry.container.cloneNode(false)
while (entry.container.firstChild) {
fresh.appendChild(entry.container.firstChild)
}
if (next) parent.insertBefore(fresh, next)
else parent.appendChild(fresh)
parent.removeChild(entry.container)
// Update our stored reference to the new container
entry.container = fresh
videoContainers.set(userId, { container: fresh, userLabel: label, subtitleOverlay: subtitle })
// Force a synchronous reflow
void fresh.offsetHeight
}
} catch (e) {
console.warn('Failed replacing container for', userId, e)
}
// Clear transition setting to restore normal behavior
entry.container.style.transition = ''
state.aspectLocked = false
log('ANIME4K', `Fully restored layout for ${userId}`)
}
} catch (e) {
console.warn('Failed restoring aspect ratio/min-size for', userId, e)
}
}
}
// Handle auto-disable of Anime4K for a single user (e.g., stream became high-res)
function handleAutoDisable(userId, info = {}) {
const entry = videoContainers.get(userId)
const state = globalAnimeState.streams.get(userId)
log('ANIME4K', `Auto-disabling Anime4K for ${userId}`, info)
if (!entry) return
// Show a temporary badge to indicate auto-disable reason
try {
const notice = document.createElement('div')
notice.className = 'anime4k-auto-disabled'
notice.textContent = info.reason === 'high-res-detected' ? 'Upscale paused (high-res)' : 'Upscale paused'
notice.style.position = 'absolute'
notice.style.top = '8px'
notice.style.left = '8px'
notice.style.padding = '6px 8px'
notice.style.background = 'rgba(0,0,0,0.6)'
notice.style.color = '#fff'
notice.style.borderRadius = '6px'
notice.style.fontSize = '12px'
notice.style.zIndex = '60'
entry.container.appendChild(notice)
setTimeout(() => { try { notice.remove() } catch(e){} }, 2600)
} catch (e) { console.warn('Failed to show auto-disable notice for', userId, e) }
// Mark cooldown to avoid immediate re-enable
try { globalAnimeState.disabledCooldowns.set(userId, Date.now() + 5000) } catch(e){}
// Use the same disable path so behavior matches manual disable
try {
// If we still have state, set shuttingDown and clear any sizeLocked flag to ensure consistent behavior
if (state) {
state.shuttingDown = true
state.sizeLocked = false
}
disableAnimeForUser(userId)
// Force grid relayout to ensure sizing matches manual-disable flow
try {
const g = document.getElementById('video-grid')
if (g) {
g.style.display = 'none'
/* force reflow */ void g.offsetHeight
g.style.display = ''
}
} catch (e) { console.warn('Failed forcing grid relayout during auto-disable', userId, e) }
} catch (e) {
console.warn('Error during auto-disable for', userId, e)
}
}
function addVideoStream(video, stream, opts = {}) {
log('VIDEO', 'Adding video stream to grid', { tracks: stream.getTracks().length, streamId: stream.id })
console.log('Adding video stream to grid, tracks:', stream.getTracks().length)
// Outer wrapper for stream and overlays
const outerContainer = document.createElement('div')
outerContainer.className = 'video-container'
// Ensure outer container fills grid cell
outerContainer.style.width = '100%'
outerContainer.style.height = '100%'
outerContainer.style.display = 'block'
const userLabel = document.createElement('div')
userLabel.className = 'user-label'
const subtitleOverlay = document.createElement('div')
subtitleOverlay.className = 'subtitle-overlay'
subtitleOverlay.style.zIndex = '40'
userLabel.style.zIndex = '41'
// Only show a badge for local preview; remove 'Participant' label for remotes
const badgeLabel = opts.isLocal ? 'You' : ''
video.srcObject = stream
video.playsInline = true
// Mute by default to allow autoplay in most browsers; users can unmute manually
video.muted = true
if (opts.isLocal) video.dataset.userId = 'local'
// Inner stream container (video + overlays)
const streamContainer = document.createElement('div')
streamContainer.className = 'stream-container'
// Make the stream container fill its parent's area so absolutely positioned media covers it
streamContainer.style.position = 'relative'
streamContainer.style.width = '100%'
streamContainer.style.height = '100%'
const badge = document.createElement('div')
badge.className = 'stream-badge is-off'
badge.textContent = badgeLabel
badge.style.zIndex = '30'
if (!opts.isLocal) {
// hide badge and toggle for remote streams (remove "Participant" / "Remote" text)
badge.style.display = 'none'
}
const toggle = document.createElement('button')
toggle.className = 'stream-toggle'
toggle.textContent = 'Anime4K: Off'
// Hide per-stream toggle for remotes (global control handles them)
if (!opts.isLocal) {
toggle.style.display = 'none'
}
// Hide local controls that would otherwise overlap the preview
if (opts.isLocal) {
toggle.style.display = 'none'
}
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.style.position = 'absolute'
canvas.style.top = '0'
canvas.style.left = '0'
canvas.style.width = '100%'
canvas.style.height = '100%'
canvas.style.objectFit = 'contain'
canvas.style.display = 'none'
canvas.style.zIndex = '2'
// keep video visually behind overlays
video.style.zIndex = '1'
// append controls and media to the inner stream container
streamContainer.appendChild(canvas)
streamContainer.appendChild(video)
streamContainer.appendChild(badge)
streamContainer.appendChild(toggle)
// Ensure local video uses contain and is centered to prevent top-cropping
if (opts.isLocal) {
video.style.objectFit = 'contain'
video.style.objectPosition = 'center center'
video.style.width = '100%'
video.style.height = '100%'
badge.style.display = 'none'
} else {
// For remote streams, also prevent crop and center the content
video.style.objectFit = 'contain'
video.style.objectPosition = 'center center'
}
video.addEventListener('loadedmetadata', () => {
log('VIDEO', 'Video metadata loaded, attempting to play')
video.play().then(() => {
log('VIDEO', 'Video playing successfully')
}).catch(err => {
log('VIDEO', 'Video play failed', err)
})
})
// assemble and append outer wrapper
// Put overlays inside the stream container so they overlay the media correctly
streamContainer.appendChild(userLabel)
streamContainer.appendChild(subtitleOverlay)
outerContainer.appendChild(streamContainer)
const parentSlot = opts.isLocal ? document.getElementById('local-preview-slot') : null
if (parentSlot && opts.isLocal) {
// Ensure wrapper fills the slot so percentage-based children size correctly
outerContainer.style.width = '100%'
outerContainer.style.height = '100%'
outerContainer.style.display = 'block'
outerContainer.style.boxSizing = 'border-box'
parentSlot.appendChild(outerContainer)