Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1745 lines (1554 loc) · 81.4 KB
/
Copy pathapp.js
File metadata and controls
1745 lines (1554 loc) · 81.4 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
/* LIVE PARTY v5.0 */
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-app.js";
import { getDatabase, ref, set, get, push, onValue, onChildAdded, remove, onDisconnect }
from "https://www.gstatic.com/firebasejs/11.5.0/firebase-database.js";
const firebaseConfig = { apiKey: "AIzaSyBGnFw13ko0b4KAs7plpFmHlg0GohowElA", authDomain: "webrtc-cd5af.firebaseapp.com", databaseURL: "https://webrtc-cd5af-default-rtdb.asia-southeast1.firebasedatabase.app", projectId: "webrtc-cd5af" };
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const cfAppId = 'e6be1e8812248470630854d4277238af';
const cfAppSecret = '3f671947386a7bf692d8326e509e3797be3c37c295337c98a6414d563c0bfeb3';
const turnId = '86014ad259cbd5b3dbef1f0867bbe15b';
async function fetchIceServers() {
// NOTE: Cloudflare TURN requires a valid Key ID and Secret.
// We've moved this to only fire when needed to avoid distracting 401 errors on load.
if (window._turnLoaded) return;
try {
const res = await fetch(`https://rtc.live.cloudflare.com/v1/turn/keys/${turnId}/credentials/generate-ice-servers`, {
method: "POST", headers: { "Authorization": `Bearer ${cfAppSecret}`, "Content-Type": "application/json" },
body: JSON.stringify({ ttl: 86400 })
});
if (res.status === 401) {
console.warn("Cloudflare TURN: Unauthorized (401). Falling back to Google/Apple STUN.");
return;
}
const data = await res.json();
if (data.iceServers) {
servers.iceServers = [...servers.iceServers, ...data.iceServers];
logStatus("Cloudflare optimized routes enabled.");
window._turnLoaded = true;
}
} catch (e) {}
}
fetchIceServers(); // Start pre-fetching ICE servers immediately for Jio/Airtel compatibility
const servers = {
iceServers: [
{ urls: ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302", "stun:stun2.l.google.com:19302"] },
{ urls: ["stun:stun.cloudflare.com:3478", "stun:iphone-ice.apple.com:3478"] }
],
iceCandidatePoolSize: 10,
bundlePolicy: "max-bundle"
};
class RealtimeApp {
constructor(appId, basePath = 'https://rtc.live.cloudflare.com/v1') { this.prefixPath = `${basePath}/apps/${appId}`; }
async sendRequest(url, body, method = 'POST') {
const res = await fetch(url, { method, mode: 'cors', headers: { 'content-type': 'application/json', Authorization: `Bearer ${cfAppSecret}` }, body: JSON.stringify(body) });
return await res.json();
}
checkErrors(result, tracksCount = 0) {
if (result.errorCode) throw new Error(result.errorDescription);
for (let i = 0; i < tracksCount; i++) if (result.tracks[i].errorCode) throw new Error(`tracks[${i}]: ${result.tracks[i].errorDescription}`);
}
async newSession(offerSDP) {
const res = await this.sendRequest(`${this.prefixPath}/sessions/new`, { sessionDescription: { type: 'offer', sdp: offerSDP } });
this.checkErrors(res); this.sessionId = res.sessionId; return res;
}
async newTracks(trackObjects, offerSDP = null) {
const body = { tracks: trackObjects };
if (offerSDP) body.sessionDescription = { type: 'offer', sdp: offerSDP };
const res = await this.sendRequest(`${this.prefixPath}/sessions/${this.sessionId}/tracks/new`, body);
this.checkErrors(res, trackObjects.length); return res;
}
async sendAnswerSDP(answer) {
const res = await this.sendRequest(`${this.prefixPath}/sessions/${this.sessionId}/renegotiate`, { sessionDescription: { type: 'answer', sdp: answer } }, 'PUT');
this.checkErrors(res);
}
async renegotiate() {
const pc = isHost ? screenPcMap["host_cf"] : viewerPc;
if (!pc) return;
logStatus("Starting Renegotiation/ICE Restart...");
const offer = await pc.createOffer({ iceRestart: true });
const mungedSdp = applyCodecPreferences(offer.sdp);
await pc.setLocalDescription({ type: 'offer', sdp: mungedSdp });
const res = await this.sendRequest(`${this.prefixPath}/sessions/${this.sessionId}/renegotiate`, { sessionDescription: { type: 'offer', sdp: mungedSdp } }, 'PUT');
this.checkErrors(res);
await pc.setRemoteDescription(new RTCSessionDescription(res.sessionDescription));
logStatus("Renegotiation complete.");
}
}
const RES_MAP = {
"2160p": { width: 3840, height: 2160 },
"1440p": { width: 2560, height: 1440 },
"1080p": { width: 1920, height: 1080 },
"720p": { width: 1280, height: 720 },
"480p": { width: 854, height: 480 },
"360p": { width: 640, height: 360 },
"240p": { width: 426, height: 240 },
"144p": { width: 256, height: 144 }
};
/* STATE */
let localStream = null, roomId = "", isHost = false, myName = "", sessionType = "party";
let screenPcMap = {}, viewerPc = null;
let connectedViewers = {}, pendingViewers = {};
let statsInterval = null, timerInterval = null, startTime = 0, prevBytesStat = 0;
let firebaseUnsubs = [], bgAudioSet = false, iceRestartCount = 0;
let audioCtx = null, movieNode = null, duckingActive = false;
let myVoiceStream = null, voicePcs = {}, silenceLoop = null;
let cfApp = null, myCfSessionId = null, myCfTrackNames = {};
let movieGainNode = null, hostInfo = null;
let reconnectToken = localStorage.getItem("nova_reconnect_token") || Math.random().toString(36).substring(2, 10);
localStorage.setItem("nova_reconnect_token", reconnectToken);
let approvedTokens = {}; // Host: stores vid -> token
let typingUsers = {};
let typingStopTimer = null;
let typingWriteTimer = null;
let typingActive = false;
let typingLastWrite = 0;
const MAX_ICE_RESTARTS = 3;
const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
let wakeLock = null;
async function requestWakeLock() {
try { if ('wakeLock' in navigator) { wakeLock = await navigator.wakeLock.request('screen'); logStatus("WakeLock active"); } } catch (_) { }
}
function gestureUnlock() {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if (audioCtx.state === "suspended") audioCtx.resume();
const osc = audioCtx.createOscillator();
const g = audioCtx.createGain();
g.gain.value = 0; osc.connect(g); g.connect(audioCtx.destination);
osc.start(); osc.stop(audioCtx.currentTime + 0.1);
const bg = document.getElementById("bgAudio"), sl = document.getElementById("silenceLoop");
if (bg) { bg.play().catch(() => { }); bg.pause(); }
if (sl) { sl.play().catch(() => { }); sl.pause(); }
requestWakeLock();
logStatus("Audio & WakeLock unlocked.");
}
function logIce(pc, label) { pc.onicegatheringstatechange = () => console.log(`[ICE ${label}] gather:${pc.iceGatheringState}`); pc.oniceconnectionstatechange = () => console.log(`[ICE ${label}] ice:${pc.iceConnectionState}`); }
function logCandidate(c, label) { if (!c) return; const t = c.candidate?.match(/typ (\w+)/)?.[1] || '?'; console.log(`[ICE ${label}] ${t}|${c.candidate?.substring(0, 60)}`); }
window.toggleNoHeat = (on) => {
document.body.classList.toggle('no-heat', on);
localStorage.setItem('no_heat_mode', on);
// Update UI Elements
const mainBtn = document.getElementById('noHeatBtnMain');
const quickBtn = document.getElementById('noHeatBtnQuick');
const toggle = document.getElementById('noHeatToggle');
if (toggle) toggle.checked = on;
if (on) {
if (window._dynamicActive) window.toggleDynamic();
if (mainBtn) mainBtn.style.background = "#339933 !important";
if (mainBtn) mainBtn.querySelector('.material-symbols-outlined').style.color = "#000";
showToast("🔋 No-Heat Mode Active: Green/Black");
} else {
if (mainBtn) mainBtn.style.background = "#000 !important";
if (mainBtn) mainBtn.querySelector('.material-symbols-outlined').style.color = "#339933";
showToast("✨ Premium Effects Restored");
}
};
/* HELPERS */
function playProceduralSound(type) {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain); gain.connect(ctx.destination);
if (type === "join") { osc.type = "sine"; osc.frequency.setValueAtTime(440, ctx.currentTime); osc.frequency.exponentialRampToValueAtTime(880, ctx.currentTime + 0.2); gain.gain.setValueAtTime(0.1, ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.5); }
else { osc.type = "sine"; osc.frequency.setValueAtTime(880, ctx.currentTime); osc.frequency.exponentialRampToValueAtTime(440, ctx.currentTime + 0.2); gain.gain.setValueAtTime(0.1, ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.5); }
osc.start(); osc.stop(ctx.currentTime + 0.5);
} catch (_) { }
}
function esc(s) { return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }
function startSilenceLoop() {
if (silenceLoop) return;
try {
const audio = document.getElementById("silenceLoop");
if (!audio) return;
// True silent WAV (44 bytes, 1 sample, 16-bit PCM, value=0) — zero humming
const silentWav = "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=";
audio.src = silentWav;
audio.loop = true;
audio.volume = 0; // absolute zero — no hum possible
audio.play().then(() => {
silenceLoop = { audio };
logStatus("Silence keep-alive active (silent WAV).");
}).catch(() => {});
} catch (e) { }
}
function stopSilenceLoop() {
if (silenceLoop) {
try { silenceLoop.audio.pause(); silenceLoop.audio.src = ""; } catch (e) { }
silenceLoop = null;
}
}
function nameToHsl(n) { let h = 0; for (const c of String(n)) h = c.charCodeAt(0) + ((h << 5) - h); return `hsl(${Math.abs(h) % 360},65%,48%)`; }
function getChatName() {
return document.getElementById("userName")?.value.trim() || (isHost ? "Host" : "Viewer");
}
function getTypingId() {
return window._myVid || (isHost ? "host" : reconnectToken);
}
function getTypingRef() {
if (!roomId) return null;
return ref(db, `rooms/${roomId}/typing/${getTypingId()}`);
}
function renderTypingStatus() {
const now = Date.now();
const activeNames = Object.entries(typingUsers)
.filter(([id, data]) => id !== getTypingId() && data?.name && now - (data.ts || 0) < 6000)
.map(([, data]) => data.name);
const uniqueNames = [...new Set(activeNames)].slice(0, 3);
const text = uniqueNames.length === 0
? ""
: uniqueNames.length === 1
? `${uniqueNames[0]} is typing...`
: uniqueNames.length === 2
? `${uniqueNames[0]} and ${uniqueNames[1]} are typing...`
: `${uniqueNames[0]}, ${uniqueNames[1]} and ${uniqueNames.length - 2} more are typing...`;
const markup = text ? `<span class="typing-label">${esc(text)}</span><span class="typing-dots" aria-hidden="true"><span></span><span></span><span></span></span>` : "";
["chatTypingStatus", "fsChatTypingStatus"].forEach(id => {
const el = document.getElementById(id);
if (!el) return;
if (!text) {
el.hidden = true;
el.innerHTML = "";
return;
}
el.hidden = false;
el.innerHTML = markup;
});
}
async function publishTypingState(active) {
const typingRef = getTypingRef();
if (!typingRef) return;
if (!active) {
typingActive = false;
typingLastWrite = 0;
clearTimeout(typingWriteTimer);
clearTimeout(typingStopTimer);
try { await remove(typingRef); } catch (_) { }
return;
}
const now = Date.now();
if (now - typingLastWrite < 700 && typingActive) return;
typingActive = true;
typingLastWrite = now;
try {
await set(typingRef, { name: getChatName(), ts: now });
onDisconnect(typingRef).remove();
} catch (_) { }
}
function stopLocalTyping() {
clearTimeout(typingStopTimer);
clearTimeout(typingWriteTimer);
publishTypingState(false);
}
function handleChatTyping(sourceEl) {
const val = sourceEl?.value?.trim?.() || "";
if (!val) {
stopLocalTyping();
return;
}
publishTypingState(true);
clearTimeout(typingStopTimer);
typingStopTimer = setTimeout(() => {
const chatVal = document.getElementById("chatInput")?.value.trim() || document.getElementById("fsChatInput")?.value.trim() || "";
if (!chatVal) stopLocalTyping();
}, 1500);
}
function startTypingListener() {
if (!roomId) return;
const unsub = onValue(ref(db, `rooms/${roomId}/typing`), snap => {
typingUsers = snap.val() || {};
renderTypingStatus();
});
firebaseUnsubs.push(unsub);
}
/* ===== COUPLE FEATURES ===== */
// Reaction sounds via Web Audio
function playReactionSound(emoji) {
try {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if (audioCtx.state === 'suspended') audioCtx.resume();
const ctx = audioCtx;
const freqMap = { '❤️':880, '💕':1047, '😍':783, '🎉':1319, '✨':1046, '🔥':220, '😂':523, '👍':659, '🍿':440, '😮':587, '💀':196, '👏':330 };
const freq = freqMap[emoji] || 523;
const o = ctx.createOscillator(); const g = ctx.createGain();
o.connect(g); g.connect(ctx.destination);
o.type = ['❤️','💕','😍'].includes(emoji) ? 'sine' : 'triangle';
o.frequency.value = freq;
g.gain.setValueAtTime(0.2, ctx.currentTime);
g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4);
o.start(); o.stop(ctx.currentTime + 0.4);
} catch(_) {}
}
// Heartbeat – sends to Firebase, both screens show heart
window.sendHeartbeat = async () => {
if (!roomId) return showToast('⚠️ Join a room first');
const icon = document.getElementById('heartbeatIcon');
if (icon) { icon.classList.add('heartbeat-anim'); setTimeout(() => icon.classList.remove('heartbeat-anim'), 700); }
await set(ref(db, `rooms/${roomId}/heartbeat`), { from: myName, ts: Date.now() });
window._showHeartWave?.();
playReactionSound('❤️');
};
// Drifted Off – sends notification to partner
window.sendDriftedOff = async () => {
if (!roomId) return;
await set(ref(db, `rooms/${roomId}/signals/driftedOff`), { from: myName, ts: Date.now() });
showToast('🌙 Your partner has been notified');
};
// Apply ambient glow to video wrap when streaming
function setAmbientGlow(on) {
const wrap = document.getElementById('videoWrap');
if (wrap) wrap.classList.toggle('streaming', on);
}
// Set cursor style based on role
function applyRoleCursor() {
document.body.classList.remove('host-cursor', 'viewer-cursor');
if (isHost) document.body.classList.add('host-cursor');
else document.body.classList.add('viewer-cursor');
}
// Show session buttons after joining
function showSessionButtons() {
['drawToggleToolbar', 'drawToggleToolbarFS'].forEach(id => {
const el = document.getElementById(id);
if (el) el.style.display = 'flex';
});
// Host-only Tools
if (isHost) {
['changeScreenBtn', 'quickResSelect', 'quickResSelectFS', 'refreshBtn'].forEach(id => {
const el = document.getElementById(id);
if (el) el.style.display = 'flex';
});
}
}
// Hide session buttons when leaving
function hideSessionButtons() {
['drawToggleToolbar', 'drawToggleToolbarFS', 'changeScreenBtn', 'quickResSelect', 'quickResSelectFS', 'refreshBtn'].forEach(id => {
const el = document.getElementById(id);
if (el) el.style.display = 'none';
});
}
// Announce mood to Firebase at session start
async function publishMood() {
if (!roomId || !window._currentMood) return;
const mood = window._currentMood;
await set(ref(db, `rooms/${roomId}/mood`), { ...mood, name: myName });
// Update panel mood bar
const bar = document.getElementById('moodBar');
const moodEl = document.getElementById('moodEmoji');
const labelEl = document.getElementById('moodLabel');
if (bar) { bar.style.display = 'flex'; }
if (moodEl) moodEl.textContent = mood.emoji;
if (labelEl) labelEl.textContent = mood.label;
}
// Listen to partner's mood
function listenMood() {
onValue(ref(db, `rooms/${roomId}/mood`), snap => {
const m = snap.val(); if (!m || m.name === myName) return;
const bar = document.getElementById('moodBar');
if (bar) bar.style.display = 'flex';
document.getElementById('moodEmoji').textContent = m.emoji;
document.getElementById('moodLabel').textContent = `${m.label} (${m.name})`;
});
}
// Listen to heartbeat events
function listenHeartbeat() {
onValue(ref(db, `rooms/${roomId}/heartbeat`), snap => {
const h = snap.val(); if (!h || h.from === myName) return;
window._showHeartWave?.();
playReactionSound('❤️');
});
}
// Listen to stream status for pause/resume
function listenStreamStatus() {
onValue(ref(db, `rooms/${roomId}/signals/streamStatus`), snap => {
const s = snap.val(); if (!s) return;
const overlay = document.getElementById('waitOverlay');
if (overlay) {
if (s.active === false && !isHost) {
overlay.style.display = 'flex';
document.getElementById('waitOverlayTitle').textContent = "Waiting for Host";
document.getElementById('waitOverlaySub').textContent = "Host has paused screen sharing. Stay tuned.";
} else if (s.active === true) {
overlay.style.display = 'none';
}
}
});
}
// Time capsule – save session on leave
function saveTimeCapsule() {
if (!roomId || !startTime) return;
const dur = Math.floor((Date.now() - startTime) / 60000);
const capsule = { roomId, date: new Date().toLocaleDateString(), duration: dur + ' min', mood: window._currentMood?.label || '—', role: isHost ? 'Host' : 'Viewer' };
const prev = JSON.parse(localStorage.getItem('saath_memories') || '[]');
prev.unshift(capsule); if (prev.length > 20) prev.pop();
localStorage.setItem('saath_memories', JSON.stringify(prev));
if (dur >= 2) showToast(`✨ ${dur} min together saved in memories!`);
}
window.handleScreenEnd = () => {
if (!isHost) return;
const overlay = document.getElementById('waitOverlay');
if (overlay) {
overlay.style.display = 'flex';
document.getElementById('waitOverlayTitle').textContent = "Screen Share Paused";
document.getElementById('waitOverlaySub').textContent = "Click 'Change Screen' below to resume sharing.";
}
if (roomId && db) set(ref(db, `rooms/${roomId}/signals/streamStatus`), { active: false, ts: Date.now() });
};
// Bootstrap draw + secret note listeners for both host and viewer
function bootstrapCoupleFeatures() {
const helpers = { set, ref, onValue, onChildAdded, push };
window._myName = myName;
window._startDrawListener?.(roomId, db, helpers);
window._startThemeSyncListener?.(roomId, db, helpers);
listenHeartbeat();
listenMood();
listenStreamStatus();
publishMood();
applyRoleCursor();
showSessionButtons();
}
window.logStatus = msg => {
const c = document.getElementById("logBox");
if (c) c.innerHTML = `<div>${new Date().toLocaleTimeString()} - ${esc(msg)}</div>` + c.innerHTML;
if (window._pipWin && window._pipWin.document) {
const pipStats = window._pipWin.document.getElementById("pip-stats");
if (pipStats) pipStats.innerHTML = `<div>${new Date().toLocaleTimeString()} - ${esc(msg)}</div>` + pipStats.innerHTML;
}
};
function logStatus(msg) {
console.log(`[STATUS] ${msg}`);
const log = document.getElementById("connLog");
if (log) {
const el = document.createElement("div");
el.textContent = `[${new Date().toLocaleTimeString([], { hour12: false, minute: '2-digit', second: '2-digit' })}] ${msg}`;
log.appendChild(el); log.scrollTop = log.scrollHeight;
if (log.children.length > 50) log.children[0].remove();
}
}
function mungerPreferH264(sdp) {
const lines = sdp.split("\r\n"); let videoIdx = -1;
for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith("m=video ")) { videoIdx = i; break; } }
if (videoIdx === -1) return sdp;
const mLine = lines[videoIdx].split(" "); const payloads = mLine.slice(3);
let h264Payloads = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith("a=rtpmap:") && lines[i].toLowerCase().includes("h264")) {
const p = lines[i].split(":")[1].split(" ")[0]; if (payloads.includes(p)) h264Payloads.push(p);
}
}
if (!h264Payloads.length) return sdp;
const others = payloads.filter(p => !h264Payloads.includes(p));
mLine.splice(3, mLine.length - 3, ...h264Payloads, ...others);
lines[videoIdx] = mLine.join(" "); return lines.join("\r\n");
}
/* MIC MANAGEMENT */
let micMeterInterval = null;
async function refreshAudioDevices() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const micSelect = document.getElementById("micSelect");
if (!micSelect) return;
const prev = micSelect.value; micSelect.innerHTML = "";
devices.filter(d => d.kind === "audioinput").forEach(d => {
const opt = document.createElement("option"); opt.value = d.deviceId; opt.textContent = d.label || `Mic ${micSelect.length + 1}`;
micSelect.appendChild(opt);
});
if (prev && [...micSelect.options].some(o => o.value === prev)) micSelect.value = prev;
} catch (_) { }
}
function getMicConstraints() {
const devId = document.getElementById("micSelect")?.value;
const echo = document.getElementById("micEcho")?.checked ?? true;
const noise = document.getElementById("micNoise")?.checked ?? true;
const agc = document.getElementById("micAGC")?.checked ?? true;
const con = { audio: { echoCancellation: echo, noiseSuppression: noise, autoGainControl: agc } };
if (devId) con.audio.deviceId = { exact: devId };
return con;
}
window.refreshMicMeter = async () => {
if (micMeterInterval) { clearInterval(micMeterInterval); micMeterInterval = null; }
const fill = document.getElementById("micMeterFill"); if (fill) fill.style.width = "0%";
try {
const stream = await navigator.mediaDevices.getUserMedia(getMicConstraints());
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const source = ctx.createMediaStreamSource(stream);
const analyzer = ctx.createAnalyser(); analyzer.fftSize = 256;
source.connect(analyzer);
const data = new Uint8Array(analyzer.frequencyBinCount);
micMeterInterval = setInterval(() => {
analyzer.getByteFrequencyData(data);
const vol = data.reduce((a, b) => a + b, 0) / data.length;
if (fill) fill.style.width = Math.min(100, vol * 2) + "%";
}, 100);
// Cleanup after 5s or when tab changes
setTimeout(() => { clearInterval(micMeterInterval); stream.getTracks().forEach(t => t.stop()); ctx.close(); if (fill) fill.style.width = "0%"; }, 5000);
} catch (_) { }
};
// Trigger device list on load WITHOUT requesting permission immediately
navigator.mediaDevices.addEventListener("devicechange", refreshAudioDevices);
refreshAudioDevices(); // Only enumerates, doesn't prompt
/* STABILITY HELPERS */
function mungerPreferOpus(sdp) {
const lines = sdp.split("\r\n");
let audioIdx = -1;
for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith("m=audio ")) { audioIdx = i; break; } }
if (audioIdx === -1) return sdp;
// ULTRA-FIDELITY: 510kbps Stereo (Max Opus Specs) for original-quality music and movies
let newSdp = sdp.replace(/a=fmtp:(\d+) (.*)/g, (m, p1, p2) => {
if (sdp.includes("a=rtpmap:" + p1 + " opus/48000")) {
return `a=fmtp:${p1} minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1;maxaveragebitrate=510000`;
}
return m;
});
return newSdp;
}
function mungerPreferVP9(sdp) {
const lines = sdp.split("\r\n");
let videoIdx = -1;
for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith("m=video ")) { videoIdx = i; break; } }
if (videoIdx === -1) return sdp;
const mLine = lines[videoIdx].split(" ");
const payloads = mLine.slice(3);
let vp9Payloads = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith("a=rtpmap:") && lines[i].toLowerCase().includes("vp9")) {
const p = lines[i].split(":")[1].split(" ")[0];
if (payloads.includes(p)) vp9Payloads.push(p);
}
}
if (!vp9Payloads.length) return sdp;
const otherPayloads = payloads.filter(p => !vp9Payloads.includes(p));
mLine.splice(3, mLine.length - 3, ...vp9Payloads, ...otherPayloads);
lines[videoIdx] = mLine.join(" ");
return lines.join("\r\n");
}
function mungerPreferAV1(sdp) {
const lines = sdp.split("\r\n");
let videoIdx = -1;
for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith("m=video ")) { videoIdx = i; break; } }
if (videoIdx === -1) return sdp;
const mLine = lines[videoIdx].split(" ");
const payloads = mLine.slice(3);
let av1Payloads = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith("a=rtpmap:") && lines[i].toLowerCase().includes("av1")) {
const p = lines[i].split(":")[1].split(" ")[0];
if (payloads.includes(p)) av1Payloads.push(p);
}
}
if (!av1Payloads.length) return sdp;
const others = payloads.filter(p => !av1Payloads.includes(p));
mLine.splice(3, mLine.length - 3, ...av1Payloads, ...others);
lines[videoIdx] = mLine.join(" ");
return lines.join("\r\n");
}
function mungerPreferH265(sdp) {
const lines = sdp.split("\r\n");
let videoIdx = -1;
for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith("m=video ")) { videoIdx = i; break; } }
if (videoIdx === -1) return sdp;
const mLine = lines[videoIdx].split(" ");
const payloads = mLine.slice(3);
let h265Payloads = [];
for (let i = 0; i < lines.length; i++) {
// Chrome uses H265 or HEVC in rtpmap
if (lines[i].startsWith("a=rtpmap:") && (lines[i].toLowerCase().includes("h265") || lines[i].toLowerCase().includes("hevc"))) {
const p = lines[i].split(":")[1].split(" ")[0];
if (payloads.includes(p)) h265Payloads.push(p);
}
}
if (!h265Payloads.length) return sdp;
const others = payloads.filter(p => !h265Payloads.includes(p));
mLine.splice(3, mLine.length - 3, ...h265Payloads, ...others);
lines[videoIdx] = mLine.join(" ");
return lines.join("\r\n");
}
function applyCodecPreferences(sdp) {
let res = mungerPreferOpus(sdp);
const codec = document.getElementById("preferredCodec")?.value || "h264";
if (codec === "av1") res = mungerPreferAV1(res);
else if (codec === "h265") res = mungerPreferH265(res);
else if (codec === "vp9") res = mungerPreferVP9(res);
else res = mungerPreferH264(res);
return res;
}
/* UI */
const scrollChat = () => { const c = document.getElementById("chatMessages"); if (c) { requestAnimationFrame(() => { c.scrollTop = c.scrollHeight; setTimeout(() => { c.scrollTop = c.scrollHeight; }, 100); }); } };
function showToast(msg) { const t = document.getElementById("toast"); if (!t) return; t.textContent = msg; t.classList.add("show"); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove("show"), 3500); }
function addSystemMsg(text) { const c = document.getElementById("chatMessages"); if (!c) return; const el = document.createElement("div"); el.className = "chat-system"; el.textContent = text; c.appendChild(el); scrollChat(); }
function addFloatingChatMsg(sender, text) {
const overlay = document.getElementById("fullscreenChatOverlay"); if (!overlay) return;
const el = document.createElement("div"); el.className = "fs-chat-msg";
el.innerHTML = `<b>${esc(sender)}</b> ${esc(text)}`; overlay.appendChild(el);
el.addEventListener("animationend", () => el.remove(), { once: true });
}
window.shareRoom = () => { const r = document.getElementById("roomId")?.value.trim() || roomId; if (!r) return showToast("⚠️ Start a session first"); const url = `${location.origin}${location.pathname}?room=${encodeURIComponent(r)}`; if (navigator.share) { navigator.share({ title: "Join my Watch Party! 🍿", url }).catch(() => { }); } else { navigator.clipboard?.writeText(url).then(() => showToast("🔗 Link copied!")).catch(() => showToast(url)); } };
function updateConnStatus(state) { const dot = document.getElementById("connDot"), label = document.getElementById("connLabel"); if (!dot || !label) return; dot.classList.remove("connected", "connecting", "live"); if (state === "connected") { dot.classList.add("connected"); label.textContent = "CONNECTED"; } else if (state === "connecting") { dot.classList.add("connecting"); label.textContent = "CONNECTING..."; } else { label.textContent = "DISCONNECTED"; } }
function changeActionBtns(mode) { const c = document.getElementById("actionBtns"); if (!c) return; if (mode === "session") { c.innerHTML = `<button class="btn-action end" onclick="leaveCall()"><span class="material-symbols-outlined">stop_circle</span> Leave Session</button>`; } else { c.innerHTML = `<button class="btn-action host" onclick="confirmHost()"><span class="material-symbols-outlined">cast</span> Start Host Session</button><button class="btn-action join" onclick="confirmJoin()"><span class="material-symbols-outlined">login</span> Join Watch Party</button>`; } }
/* PEOPLE TAB */
function renderPeopleTab() {
const c = document.getElementById("peopleList"); if (!c) return;
let html = "";
const pending = Object.entries(pendingViewers);
if (isHost && pending.length > 0) { html += `<div class="ppl-section">⏳ Waiting to Join</div>`; for (const [vid, d] of pending) { const col = nameToHsl(d.name); html += `<div class="ppl-item pending-item"><div class="ppl-av" style="background:${col}">${d.name[0].toUpperCase()}</div><div class="ppl-name">${esc(d.name)}</div><div class="ppl-btns"><button class="pa-btn approve" onclick="approveViewer('${vid}','${esc(d.name)}')"><span class="material-symbols-outlined">check</span></button><button class="pa-btn deny" onclick="denyViewer('${vid}','${esc(d.name)}')"><span class="material-symbols-outlined">close</span></button></div></div>`; } }
html += `<div class="ppl-section">👥 In Session</div>`;
// Show "You"
const colMe = nameToHsl(myName || "User");
const myRole = isHost ? "HOST" : "YOU";
html += `<div class="ppl-item"><div class="ppl-av" style="background:${colMe}">${(myName || "U")[0].toUpperCase()}</div><div class="ppl-name">${esc(myName || "User")} <span class="role-badge">${myRole}</span></div></div>`;
// Show Host if someone else is hosting
if (!isHost && hostInfo && hostInfo.name !== myName) {
const colHost = nameToHsl(hostInfo.name);
html += `<div class="ppl-item"><div class="ppl-av" style="background:${colHost}">${hostInfo.name[0].toUpperCase()}</div><div class="ppl-name">${esc(hostInfo.name)} <span class="role-badge">HOST</span></div></div>`;
}
const connectedArr = Object.entries(connectedViewers);
for (const [vid, p] of connectedArr) {
if (p.name === myName) continue;
const col = nameToHsl(p.name);
html += `<div class="ppl-item"><div class="ppl-av" style="background:${col}">${p.name[0].toUpperCase()}</div><div class="ppl-name">${esc(p.name)}</div>${isHost ? `<button class="pa-btn kick" onclick="kickViewer('${vid}','${esc(p.name)}')"><span class="material-symbols-outlined">person_remove</span></button>` : ""}</div>`;
}
if (!html) html = `<div class="ppl-empty"><span class="material-symbols-outlined">group</span><p>No one yet</p></div>`;
c.innerHTML = html;
const badge = document.getElementById("peopleBadge"); if (badge) { badge.textContent = pending.length; badge.style.display = pending.length > 0 ? "flex" : "none"; }
if (window._pipWin && window._pipWin.document) {
const pipPpl = window._pipWin.document.getElementById("pip-ppl");
if (pipPpl) pipPpl.innerHTML = html;
}
}
window.approveViewer = async (vid, name) => {
const token = pendingViewers[vid]?.token;
if (token) approvedTokens[vid] = token;
await set(ref(db, `rooms/${roomId}/waitroom/${vid}/status`), "approved");
delete pendingViewers[vid];
renderPeopleTab();
};
window.denyViewer = async (vid, name) => { await set(ref(db, `rooms/${roomId}/waitroom/${vid}/status`), "denied"); setTimeout(() => remove(ref(db, `rooms/${roomId}/waitroom/${vid}`)), 3000); delete pendingViewers[vid]; renderPeopleTab(); showToast(`✗ ${name} declined`); };
window.kickViewer = async (vid, name) => { await set(ref(db, `rooms/${roomId}/viewers/${vid}/kicked`), true); setTimeout(() => remove(ref(db, `rooms/${roomId}/viewers/${vid}`)), 2000); try { screenPcMap[vid]?.close(); } catch (_) { } delete screenPcMap[vid]; delete connectedViewers[vid]; renderPeopleTab(); showToast(`👢 ${name} removed`); };
window.muteAllViewers = async () => { if (!isHost || !roomId) return; await set(ref(db, `rooms/${roomId}/muteAll`), Date.now()); showToast("🤫 Muted all viewers"); };
window.applyBitrateNow = () => { logStatus("Bitrate dynamically managed by Cloudflare SFU."); };
window.pushHostSettings = () => {
if (!isHost || !roomId) return;
const sRes = document.getElementById("scrResS")?.value || "1080p";
const sFps = document.getElementById("scrFpsS")?.value || "30";
const sCodec = document.getElementById("preferredCodec")?.value || "h264";
const sDel = document.getElementById("streamDelaySlider")?.value || "0.05";
set(ref(db, `rooms/${roomId}/settings`), { quality: sRes, fps: sFps, codec: sCodec, bitrate: "Auto", delay: sDel, type: sessionType });
};
window.setMode = (m) => {
sessionType = m;
document.getElementById("modalMode").value = m;
document.getElementById("modeParty").style.background = m === 'party' ? 'var(--accent-dim)' : 'var(--surface)';
document.getElementById("modeParty").style.borderColor = m === 'party' ? 'var(--accent)' : 'var(--glass-border)';
document.getElementById("modeBroadcast").style.background = m === 'broadcast' ? 'var(--accent-dim)' : 'var(--surface)';
document.getElementById("modeBroadcast").style.borderColor = m === 'broadcast' ? 'var(--accent)' : 'var(--glass-border)';
document.getElementById("micOptionHost").style.display = m === 'broadcast' ? 'none' : 'flex';
};
window.replaceScreenShareBtn = async () => {
if (!isHost || !roomId) return;
const resStr = document.getElementById("scrResS")?.value || "1080p", fpsStr = document.getElementById("scrFpsS")?.value || "30";
const { width, height } = RES_MAP[resStr] || RES_MAP["1080p"], fps = parseInt(fpsStr) || 30;
const con = { video: { width: { ideal: width }, height: { ideal: height }, frameRate: { ideal: fps, max: fps } }, audio: { channelCount: 2, sampleRate: 48000, autoGainControl: false, echoCancellation: false, noiseSuppression: false } };
let newStream;
try { newStream = await navigator.mediaDevices.getDisplayMedia(con); }
catch { con.audio = true; try { newStream = await navigator.mediaDevices.getDisplayMedia(con); } catch { con.audio = false; newStream = await navigator.mediaDevices.getDisplayMedia(con); } }
if (!newStream) return;
const vt = newStream.getVideoTracks()[0]; if (vt && "contentHint" in vt) vt.contentHint = "detail";
// Stop old tracks
if (localStream) { localStream.getTracks().forEach(t => t.stop()); }
localStream = newStream;
const video = document.getElementById("remoteVideo"); video.srcObject = localStream;
vt.onended = () => window.handleScreenEnd();
// Hide wait overlay and notify viewers
const overlay = document.getElementById('waitOverlay');
if (overlay) overlay.style.display = 'none';
if (roomId && db) set(ref(db, `rooms/${roomId}/signals/streamStatus`), { active: true, ts: Date.now() });
// Replace tracks and apply bitrate
Object.values(screenPcMap).forEach(async pc => {
const senders = pc.getSenders();
for (const track of localStream.getTracks()) {
const sender = senders.find(s => s.track && s.track.kind === track.kind);
if (sender) await sender.replaceTrack(track);
else pc.addTransceiver(track, { direction: 'sendonly' });
}
await optimizeHostSender(pc);
});
// Update Firebase host metadata with STABLE NAMES (already movie-v/movie-a)
set(ref(db, `rooms/${roomId}/host`), {
name: myName,
created: Date.now(),
cfSessionId: cfApp.sessionId,
cfTrackVideo: "movie-v",
cfTrackAudio: "movie-a",
role: 'host'
});
showToast("🔄 Quality updated & audio stabilized");
};
/* CAPTURE */
async function captureScreen() {
const resStr = document.getElementById("scrRes")?.value || "1080p", fpsStr = document.getElementById("scrFps")?.value || "30";
const { width, height } = RES_MAP[resStr] || RES_MAP["1080p"], fps = parseInt(fpsStr) || 30;
const con = {
video: {
width: { ideal: width },
height: { ideal: height },
frameRate: { ideal: fps, max: fps },
displaySurface: "monitor"
},
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
channelCount: 2,
sampleRate: 48000,
suppressLocalAudioPlayback: false
},
systemAudio: "include" // Modern hint for system audio
};
try {
// Attempt with system audio inclusion
localStream = await navigator.mediaDevices.getDisplayMedia(con);
} catch (e) {
console.warn("Screen capture with audio failed, retrying without audio hint", e);
delete con.systemAudio;
try { localStream = await navigator.mediaDevices.getDisplayMedia(con); }
catch { con.audio = false; localStream = await navigator.mediaDevices.getDisplayMedia(con); }
}
// Mix Mic if enabled (only if not in broadcast mode)
if (document.getElementById("modalHostMic")?.checked && sessionType !== 'broadcast') {
try {
const micStream = await navigator.mediaDevices.getUserMedia(getMicConstraints());
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const dest = ctx.createMediaStreamDestination();
const existingAudioTracks = localStream.getAudioTracks();
if (existingAudioTracks.length > 0) {
const source1 = ctx.createMediaStreamSource(new MediaStream([existingAudioTracks[0]]));
source1.connect(dest);
}
const source2 = ctx.createMediaStreamSource(micStream);
source2.connect(dest);
const mixedTrack = dest.stream.getAudioTracks()[0];
// Do NOT stop existing tracks since source1 needs them flowing!
existingAudioTracks.forEach(t => localStream.removeTrack(t));
localStream.addTrack(mixedTrack);
localStream._micStream = micStream; // store to stop later
} catch (e) { console.warn("Mic capture failed", e); }
}
const vt = localStream.getVideoTracks()[0]; if (vt && "contentHint" in vt) vt.contentHint = "detail";
vt.onended = () => window.handleScreenEnd();
// Initial overlay clear
const overlay = document.getElementById('waitOverlay');
if (overlay) overlay.style.display = 'none';
if (roomId && db) set(ref(db, `rooms/${roomId}/signals/streamStatus`), { active: true, ts: Date.now() });
const video = document.getElementById("remoteVideo"); video.srcObject = localStream; video.muted = true;
return localStream;
}
/* OPTIMIZE SENDER */
async function optimizeHostSender(pc, vid = null) {
// Use a high cap to allow auto-bitrate to scale up, while prioritizing FPS
let mbps = 25;
const fps = parseInt(document.getElementById("scrFps")?.value || "30") || 30;
for (const s of pc.getSenders()) {
if (!s.track) continue;
const p = s.getParameters();
if (s.track.kind === "video") {
if (!p.encodings?.length || p.encodings.length < 3) continue;
// PRIORITIZE FPS (Smoothness) over resolution
p.degradationPreference = "maintain-framerate";
// High Layer (Layer 2)
p.encodings[2].maxBitrate = mbps * 1_000_000;
p.encodings[2].maxFramerate = fps;
p.encodings[2].networkPriority = "high";
p.encodings[2].priority = "high";
// Mid Layer (Layer 1)
p.encodings[1].maxBitrate = 2_500_000;
p.encodings[1].scaleResolutionDownBy = 2.0;
// Low Layer (Layer 0) - starting from 144p
p.encodings[0].maxBitrate = 500_000;
p.encodings[0].scaleResolutionDownBy = 4.0;
} else if (s.track.kind === "audio") {
if (!p.encodings?.length) p.encodings = [{}];
p.encodings[0].networkPriority = "high";
p.encodings[0].priority = "high";
}
try { await s.setParameters(p); } catch (e) { console.warn("Failed to set parameters", e); }
}
logStatus(`FPS Priority Active: Target ${fps} FPS (Auto-Bitrate)`);
}
/* HOST */
window.confirmHost = async () => {
gestureUnlock();
roomId = document.getElementById("roomId").value.trim(); myName = document.getElementById("userName").value.trim() || "Host";
if (!roomId) { roomId = Math.random().toString(36).substr(2, 8).toUpperCase(); document.getElementById("roomId").value = roomId; }
sessionType = document.getElementById("modalMode")?.value || "party";
logStatus(`Host session starting (${sessionType} mode)...`);
try { await captureScreen(); } catch { logStatus("Capture canceled"); return showToast("⚠️ Screen share cancelled"); }
isHost = true;
logStatus("Screen captured successfully");
window._myVid = "host";
startSilenceLoop();
document.getElementById("noSignal").classList.add("hidden");
document.getElementById("liveBadge").style.display = "flex";
document.getElementById("sourceTag").style.display = ""; document.getElementById("sourceTag").textContent = "HOSTING";
updateConnStatus("connected"); changeActionBtns("session");
hostInfo = { name: myName, role: 'host' };
document.getElementById("hostOnlySettings")?.style.removeProperty("display");
document.getElementById("lowDataGroup") && (document.getElementById("lowDataGroup").style.display = "none");
if (sessionType === "broadcast") {
document.getElementById("micBtnMain").style.display = "none";
document.getElementById("micBtnChat").style.display = "none";
}
window.switchTab("chat"); renderPeopleTab();
setAmbientGlow(true);
bootstrapCoupleFeatures();
_reconnectAttempt = 0; _startConnPoll();
// Add pre-show countdown button
const hostBtns = document.getElementById("hostOnlySettings");
if (hostBtns && !document.getElementById('countdownTriggerBtn')) {
const cb = document.createElement('button');
cb.id = 'countdownTriggerBtn'; cb.className = 'btn-action'; cb.style.cssText = 'background:rgba(201,75,123,0.1);border-color:rgba(201,75,123,0.3);color:var(--accent);font-size:12px;height:34px;margin-bottom:10px;';
cb.innerHTML = '<span class="material-symbols-outlined" style="font-size:16px;">movie</span> Pre-Show Countdown';
cb.onclick = () => { startPreShowCountdown(5); };
hostBtns.prepend(cb);
}
cfApp = new RealtimeApp(cfAppId);
const pc = new RTCPeerConnection(servers);
screenPcMap["host_cf"] = pc; // Keep reference to cleanup later
pc.ontrack = e => {
const track = e.track;
if (track.kind === "audio") {
logStatus(`Host received Voice track: ${track.id}`);
const au = document.createElement("audio");
au.id = `voice_${track.id}`;
au.autoplay = true;
au.srcObject = new MediaStream([track]);
document.body.appendChild(au);
track.onended = () => { if (au.parentNode) au.parentNode.removeChild(au); };
track.onmute = () => { if (au.parentNode) au.parentNode.removeChild(au); };
}
};
let localTransceivers = [];
if (localStream) {
localStream.getTracks().forEach(track => {
localTransceivers.push(pc.addTransceiver(track, { direction: "sendonly" }));
});
}
const offer1 = await pc.createOffer();
const munged1 = applyCodecPreferences(offer1.sdp);
await pc.setLocalDescription({ type: 'offer', sdp: munged1 });
const newSessionResult = await cfApp.newSession(munged1);
await pc.setRemoteDescription(new RTCSessionDescription(newSessionResult.sessionDescription));
await new Promise((resolve, reject) => {
pc.addEventListener('iceconnectionstatechange', ev => {
if (pc.iceConnectionState === 'connected') resolve();
});
setTimeout(resolve, 5000); // safety fallback
});
logStatus("Cloudflare SFU Host Session Created.");
myCfSessionId = cfApp.sessionId;
let trackObjects = localTransceivers.map(t => {
const isVid = t.sender.track.kind === 'video';
return { location: 'local', mid: t.mid, trackName: isVid ? "movie-v" : "movie-a" };
});
const offer2 = await pc.createOffer();
const munged2 = applyCodecPreferences(offer2.sdp);
await pc.setLocalDescription({ type: 'offer', sdp: munged2 });
const newLocalTracksResult = await cfApp.newTracks(trackObjects, munged2);
await pc.setRemoteDescription(new RTCSessionDescription(newLocalTracksResult.sessionDescription));
logStatus("Tracks published to Cloudflare SFU.");
const roomRef = ref(db, `rooms/${roomId}`);
logStatus(`Registering host in room: ${roomId}`);
await set(ref(db, `rooms/${roomId}/host`), {
name: myName,
created: Date.now(),
cfSessionId: myCfSessionId,
cfTrackVideo: "movie-v",
cfTrackAudio: "movie-a",
role: 'host',
mood: window._currentMood?.label || 'Movie Night'
}).catch(e => logStatus(`Firebase Error: ${e.message}`));
onDisconnect(roomRef).remove();
// Waitroom UI
const unsubW = onChildAdded(ref(db, `rooms/${roomId}/waitroom`), snap => {
const vid = snap.key, data = snap.val(); if (!data || !vid || data.status) return;
// Auto-Accept logic for network reconnections
if (data.token && Object.values(approvedTokens).includes(data.token)) {
logStatus(`Auto-approving reconnection for ${data.name}`);
set(ref(db, `rooms/${roomId}/waitroom/${vid}/status`), "approved");
// Update approvedTokens with new vid
Object.keys(approvedTokens).forEach(k => { if (approvedTokens[k] === data.token) delete approvedTokens[k]; });
approvedTokens[vid] = data.token;
return;
}
logStatus(`Approval request from: ${data.name || "Viewer"}`);
pendingViewers[vid] = { name: data.name || "Viewer", token: data.token };
renderPeopleTab(); showToast(`🔔 ${data.name} wants to join`); window.switchTab("people");
});
// Voice Pull Listener
const unsubVoice = onChildAdded(ref(db, `rooms/${roomId}/voice`), async snap => {
const peerVid = snap.key; if (peerVid === window._myVid || !snap.val()) return;
pullVoiceTracks(snap.val().cfSessionId, snap.val().trackName, pc);
});