@kangsicj/nexussync 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <br>
6
6
 
7
- [![Version](https://img.shields.io/badge/version-1.3.0-7C4DFF?style=for-the-badge)](./CHANGELOG.md)
7
+ [![Version](https://img.shields.io/badge/version-1.3.1-7C4DFF?style=for-the-badge)](./CHANGELOG.md)
8
8
  [![Tampermonkey](https://img.shields.io/badge/Tampermonkey-PC%20%C2%B7%20Android-00485B?style=for-the-badge&logo=tampermonkey&logoColor=white)](https://www.tampermonkey.net/)
9
9
  [![iOS Safari](https://img.shields.io/badge/Userscripts-iPhone%20%C2%B7%20iPad-0A84FF?style=for-the-badge&logo=safari&logoColor=white)](https://apps.apple.com/app/userscripts/id1463298887)
10
10
  [![Sponsor](https://img.shields.io/badge/Fairy-Sponsor-FF6FB5?style=for-the-badge&logo=githubsponsors&logoColor=white)](https://fairy.hada.io/@jinny)
@@ -71,6 +71,7 @@ No subtitles on that video? Pick your language, choose **video sound** and press
71
71
 
72
72
  - **Next episode, together** — move on to the next episode and you stay in the room; friends follow with one tap. Near the end, an *Up next* card counts down and opens it for you.
73
73
  - **Cinema by itself** — open a page with one movie or episode and it switches to cinema as soon as the video is ready, keeping the site's player so you can still pick subtitles or a server. Turn it off per site.
74
+ - **See who's here** — everyone in the room is listed by name and colour, with a 💤 when someone's screen is off.
74
75
  - **Make it yours** — pick your name and colour; your bubbles and doodles wear it on every screen.
75
76
  - **Calm, never jumpy** — phones going to sleep, slow Wi-Fi or a player restarting on its own never pause the whole room.
76
77
  - **No accidental pauses** — tapping the chat, a doodle or a reaction never nudges the video for anyone.
@@ -8,7 +8,7 @@
8
8
  // @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
9
9
  // @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
10
10
  // @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
11
- // @version 1.3.0
11
+ // @version 1.3.1
12
12
  // @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
13
13
  // @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
14
14
  // @match *://*/*
@@ -8,7 +8,7 @@
8
8
  // @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
9
9
  // @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
10
10
  // @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
11
- // @version 1.3.0
11
+ // @version 1.3.1
12
12
  // @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
13
13
  // @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
14
14
  // @match *://*/*
@@ -43,12 +43,12 @@
43
43
 
44
44
  // The version of the code that is actually running (the manager's metadata can lag
45
45
  // behind when an old copy is still installed).
46
- const NXU_VERSION = '1.3.0';
46
+ const NXU_VERSION = '1.3.1';
47
47
  // Rank used by the one-instance guard below and to tell newer builds apart in a room.
48
48
  // It is independent of the public version (1.0.0 is the first public release, after
49
49
  // private builds that reached ranks up to 10.2.0), so every older copy still installed
50
50
  // steps aside instead of this release.
51
- const NXU_RANK = '11.3.0';
51
+ const NXU_RANK = '11.3.1';
52
52
  const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
53
53
  // App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
54
54
  const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
@@ -322,7 +322,7 @@
322
322
  const bool = v => v === undefined || typeof v === 'boolean';
323
323
  switch (data.type) {
324
324
  case 'NXU_VIDEO_FOUND':
325
- return num(data.videoW) && num(data.videoH) && (num(data.duration) || data.duration === undefined) && bool(data.paused) && bool(data.playing);
325
+ return num(data.videoW) && num(data.videoH) && (num(data.duration) || data.duration === undefined) && bool(data.paused) && bool(data.playing) && bool(data.live);
326
326
  case 'NXU_VIDEO_LOST':
327
327
  case 'NXU_ACTIVITY':
328
328
  case 'NXU_CINEMA_EXIT_REQ':
@@ -330,7 +330,7 @@
330
330
  return true;
331
331
  case 'NXU_VIDEO_EVENT':
332
332
  return ['play', 'pause', 'seeked', 'ratechange', 'timeupdate', 'waiting', 'canplay', 'volume'].includes(data.event) &&
333
- num(data.currentTime) && num(data.playbackRate) && typeof data.paused === 'boolean' && str(data.remoteEventId);
333
+ num(data.currentTime) && num(data.playbackRate) && typeof data.paused === 'boolean' && str(data.remoteEventId) && bool(data.live);
334
334
  case 'NXU_FULLSCREEN_STATE':
335
335
  return typeof data.active === 'boolean';
336
336
  case 'NXU_HOTKEY':
@@ -682,6 +682,8 @@
682
682
  subMicBlockedNoMedia: 'This site does not allow the microphone, and the video sound cannot be captured here.',
683
683
  subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
684
684
  subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
685
+ subHearVideo: '🎧 Listening to the video', subHearMic: '🎧 Listening through the microphone', subVideoSilent: '🔇 No sound reaches the subtitles from this video',
686
+ subIssueNet: '⚠️ Speech service connection is unstable — retrying', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
685
687
  subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
686
688
  advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
687
689
  providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
@@ -705,7 +707,7 @@
705
707
  noVideo: '⚠️ No video detected', noPlayingVideo: '⚠️ No playing video found', pipUnsupported: '⚠️ Picture-in-Picture not supported', pipBlocked: '⚠️ Picture-in-Picture was blocked',
706
708
  mediaFound: '✅ Media detected', mediaNotFound: '🔎 No media yet — start the video and try again',
707
709
  canvasOn: '🎨 Canvas ON', canvasOff: '🎨 Canvas OFF', canvasViewOnly: '🎨 Canvas (view only)', nothingToUndo: '↩️ Nothing to undo', undo: 'Undo (Ctrl+Z)',
708
- pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching',
710
+ pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching', meTag: '(me)', whoViewer: 'watching only', whoAway: 'away (screen off or another tab)', whoOldVer: 'different version — please update', whoTitle: 'Watching together',
709
711
  shieldTitle: 'Connected', shieldText: 'Tap to enable synchronized playback in this tab.', shieldButton: 'START SYNC ▶️',
710
712
  menuCinema: 'Toggle cinema mode', menuSubtitles: 'Start / stop AI subtitles', menuShowButton: 'Show / hide the NexusSync button on this site'
711
713
  },
@@ -776,6 +778,8 @@
776
778
  subMicBlockedNoMedia: '이 사이트는 마이크 사용을 막아 두었고, 영상 소리도 받을 수 없어요.',
777
779
  subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
778
780
  subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
781
+ subHearVideo: '🎧 영상 소리 듣는 중', subHearMic: '🎧 마이크로 듣는 중', subVideoSilent: '🔇 이 영상의 소리가 자막에 전달되지 않아요',
782
+ subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
779
783
  subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
780
784
  advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
781
785
  providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
@@ -799,7 +803,7 @@
799
803
  noVideo: '⚠️ 감지된 영상이 없습니다', noPlayingVideo: '⚠️ 재생 중인 영상이 없습니다', pipUnsupported: '⚠️ PiP를 지원하지 않습니다', pipBlocked: '⚠️ PiP가 차단되었습니다',
800
804
  mediaFound: '✅ 미디어 감지됨', mediaNotFound: '🔎 아직 미디어가 없습니다 — 영상을 재생한 뒤 다시 시도하세요',
801
805
  canvasOn: '🎨 캔버스 켜짐', canvasOff: '🎨 캔버스 꺼짐', canvasViewOnly: '🎨 캔버스 (보기 전용)', nothingToUndo: '↩️ 되돌릴 내용이 없습니다', undo: '되돌리기 (Ctrl+Z)',
802
- pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중',
806
+ pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람',
803
807
  shieldTitle: '연결됨', shieldText: '눌러서 이 탭의 동기화 재생을 활성화하세요.', shieldButton: '동기화 시작 ▶️',
804
808
  menuCinema: '시네마 모드 켜기/끄기', menuSubtitles: 'AI 자막 시작/중지', menuShowButton: '이 사이트에서 NexusSync 버튼 표시/숨기기'
805
809
  }
@@ -1126,6 +1130,7 @@
1126
1130
  [class*="mask" i], [class*="volume" i], [class*="settings" i], [class*="menu" i], [class*="tooltip" i], [class*="watermark" i], .jw-display, .xgplayer-start, .fp-ui, .art-layers, .art-notice):not(video):not(.nxu-cinema-fill):not(.nxu-keep):not([class*="caption" i]):not([class*="subtitle" i]):not([class*="text-track" i]):not([class*="cue" i]):not([class*="sub-" i]):not([class*="danmaku" i]) {
1127
1131
  visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
1128
1132
  .nxu-site-ui-off :is([class*="caption" i], [class*="subtitle" i], [class*="text-track" i], [class*="cue" i], [class*="danmaku" i]) { visibility: visible !important; }
1133
+ .nxu-site-ui-off .nxu-site-hide { visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
1129
1134
  .nxu-cue-mirror { position: absolute !important; left: calc(50% + var(--nxu-cue-shift, 0px)) !important; right: auto !important; top: auto !important; bottom: var(--nxu-cue-bottom, 6%) !important; transform: translateX(-50%) !important;
1130
1135
  width: var(--nxu-cue-width, 90%) !important; max-width: 96% !important; height: auto !important; margin: 0 !important; padding: 0 !important; border: 0 !important; background: none !important;
1131
1136
  flex-direction: column !important; align-items: center !important; gap: 3px !important; z-index: 2147483646 !important; transition: bottom 0.3s ease !important; pointer-events: none !important; visibility: visible !important; opacity: 1 !important; }
@@ -1383,6 +1388,7 @@
1383
1388
  for (let n = video.parentElement; n && n !== root; n = n.parentElement) n.classList.add('nxu-keep');
1384
1389
  }
1385
1390
  root.classList.toggle('nxu-site-ui-off', hide);
1391
+ this._structuralHide(root, video, hide);
1386
1392
  if (video) {
1387
1393
  if (hide && video.hasAttribute('controls')) { video.dataset.nxuControls = '1'; video.removeAttribute('controls'); }
1388
1394
  else if (!hide && video.dataset.nxuControls) { video.setAttribute('controls', ''); delete video.dataset.nxuControls; }
@@ -1396,7 +1402,53 @@
1396
1402
  } catch (_) { }
1397
1403
  }
1398
1404
  },
1405
+ // Players built from utility classes (Tailwind and the like) have no "control" in
1406
+ // their class names, so the site's bar stayed visible behind ours. Structurally: in the
1407
+ // player, everything beside the video's own chain of wrappers that holds controls
1408
+ // (buttons, sliders, icons, links) or is an empty overlay is hidden; text-only layers
1409
+ // (the site's subtitles) stay. Re-checked when the player redraws its controls.
1410
+ _structuralHide(root, video, hide) {
1411
+ const undo = () => {
1412
+ (this._hidden || []).forEach(n => n.classList.remove('nxu-site-hide'));
1413
+ this._hidden = [];
1414
+ this._hideObs?.disconnect();
1415
+ this._hideObs = null;
1416
+ };
1417
+ if (!hide || !root || !video || root === video) { undo(); return; }
1418
+ const run = () => {
1419
+ const chain = new Set();
1420
+ for (let n = video; n && n !== root; n = n.parentElement) chain.add(n);
1421
+ const hidden = [];
1422
+ const CTRL = 'button, input, select, [role="button"], [role="slider"], [role="menu"], [role="menuitem"], svg, a[href], [tabindex]';
1423
+ for (let n = video; n && n !== root; n = n.parentElement) {
1424
+ const parent = n.parentElement;
1425
+ if (!parent) break;
1426
+ for (const child of parent.children) {
1427
+ if (chain.has(child) || child === video || child.tagName === 'VIDEO' || child.tagName === 'CANVAS' && child.width > 200) continue;
1428
+ if (/^(nxu|nexus)/i.test(child.id || '') || [...child.classList].some(c => c.startsWith('nxu-') && c !== 'nxu-site-hide')) continue;
1429
+ if (child.tagName === 'TRACK' || child.tagName === 'SOURCE' || child.tagName === 'STYLE' || child.tagName === 'SCRIPT') continue;
1430
+ const interactive = child.matches(CTRL) || !!child.querySelector(CTRL);
1431
+ const text = (child.textContent || '').trim();
1432
+ // Text without any control: most likely the site's own subtitles.
1433
+ if (!interactive && text) continue;
1434
+ child.classList.add('nxu-site-hide');
1435
+ hidden.push(child);
1436
+ }
1437
+ }
1438
+ (this._hidden || []).forEach(n => { if (!hidden.includes(n)) n.classList.remove('nxu-site-hide'); });
1439
+ this._hidden = hidden;
1440
+ };
1441
+ run();
1442
+ if (!this._hideObs || this._hideObsRoot !== root) {
1443
+ this._hideObs?.disconnect();
1444
+ let timer = 0;
1445
+ this._hideObs = new MutationObserver(() => { if (!timer) timer = setTimeout(() => { timer = 0; if (root.classList.contains('nxu-site-ui-off')) run(); }, 250); });
1446
+ this._hideObs.observe(root, { childList: true, subtree: true });
1447
+ this._hideObsRoot = root;
1448
+ }
1449
+ },
1399
1450
  _releaseSiteUi(root, video) {
1451
+ this._structuralHide(root, video, false);
1400
1452
  root?.classList.remove('nxu-site-ui-off');
1401
1453
  try { root?.querySelectorAll('.nxu-keep').forEach(n => n.classList.remove('nxu-keep')); } catch (_) { }
1402
1454
  if (video?.dataset.nxuControls) { video.setAttribute('controls', ''); delete video.dataset.nxuControls; }
@@ -2444,7 +2496,14 @@
2444
2496
  },
2445
2497
  // The video's own sound: the element itself when it gives real audio, otherwise (on a
2446
2498
  // computer) the tab's audio, which the browser lets the user share in one dialog.
2499
+ _liveTab() {
2500
+ const st = this._sharedTab;
2501
+ return st && st.getAudioTracks().some(tr => tr.readyState === 'live') ? st : null;
2502
+ },
2447
2503
  async _captureMediaAudio(token) {
2504
+ // A tab the user already shared keeps working across restarts (no new dialog).
2505
+ const tab = this._liveTab();
2506
+ if (tab) return tab;
2448
2507
  let web = this._captureElementAudio();
2449
2508
  if (web && !(await this._hasSignal(web))) {
2450
2509
  web.getTracks().forEach(tr => tr.stop());
@@ -2455,7 +2514,7 @@
2455
2514
  if (token !== this._startToken) return null;
2456
2515
  if (this._isAppleMobile() || this._isAndroid() || !navigator.mediaDevices?.getDisplayMedia) return null;
2457
2516
  showToast(t('subAskTab'));
2458
- try { return await this._captureDisplayAudio(); } catch (err) {
2517
+ try { return (this._sharedTab = await this._captureDisplayAudio()); } catch (err) {
2459
2518
  logDebug('AI Sub: tab audio not shared: ' + (err.message || err.name), 'warn');
2460
2519
  return null;
2461
2520
  }
@@ -2493,6 +2552,9 @@
2493
2552
  try {
2494
2553
  // Echo cancellation would erase the very speaker sound we want to hear.
2495
2554
  mic = await this._requestMic(!web);
2555
+ // With the video sound in hand the microphone was only needed for the
2556
+ // permission; it is not kept open (no recording light, no audio ducking).
2557
+ if (web) { stopAll(mic); mic = null; this._micGranted = true; }
2496
2558
  } catch (err) {
2497
2559
  if (!web) throw err;
2498
2560
  logDebug('AI Sub: microphone unavailable, using the video sound only.', 'info');
@@ -2541,7 +2603,7 @@
2541
2603
  this.audioNodes = nodes;
2542
2604
  // Recognition hears exactly this mix (video sound, or the echo-free microphone).
2543
2605
  this.recognitionAudioStream = dest.stream;
2544
- this._levelTimer = setInterval(() => { if (!document.hidden) this._refreshLevels(); }, 400);
2606
+ this._levelTimer = setInterval(() => { if (!document.hidden) { this._refreshLevels(); this._updateListenChip(); } }, 400);
2545
2607
  } catch (err) {
2546
2608
  logDebug('AI Sub: audio analysis unavailable: ' + (err.message || err.name), 'info');
2547
2609
  }
@@ -2550,6 +2612,7 @@
2550
2612
  clearInterval(this._levelTimer);
2551
2613
  this._levelTimer = null;
2552
2614
  [this.mediaStream, this.webMediaStream, this.recognitionAudioStream].forEach(stream => {
2615
+ if (stream && stream === this._sharedTab) return; // released only on a real stop
2553
2616
  try { stream?.getTracks().forEach(tr => tr.stop()); } catch (_) { }
2554
2617
  });
2555
2618
  this.mediaStream = this.webMediaStream = this.recognitionAudioStream = null;
@@ -2686,8 +2749,12 @@
2686
2749
  },
2687
2750
  _touch() { this._lastEventAt = Date.now(); },
2688
2751
  _liveTrack() {
2689
- const track = this.recognitionAudioStream?.getAudioTracks?.()[0];
2690
- return track && track.readyState === 'live' ? track : null;
2752
+ const pick = s => { const tr = s?.getAudioTracks?.()[0]; return tr && tr.readyState === 'live' ? tr : null; };
2753
+ // The recognizer listens to the captured source track itself (the video's own
2754
+ // audio track, or the echo-free microphone), as browsers document and test it; the
2755
+ // mixed stream is used only once the microphone was added to a silent video sound.
2756
+ if (this._micMixed) return pick(this.recognitionAudioStream) || pick(this.mediaStream);
2757
+ return pick(this.webMediaStream) || pick(this.mediaStream) || pick(this.recognitionAudioStream);
2691
2758
  },
2692
2759
  _startSession(reason) {
2693
2760
  if (!this.active) return;
@@ -2751,11 +2818,14 @@
2751
2818
  this._scheduleRestart('watchdog', 100, true);
2752
2819
  } else if (this._recognitionInput === 'track' && !this._trackDisabled && this._trackSince && (
2753
2820
  // Captured video audio is silent (e.g. cross-origin media) while the video plays,
2754
- (this.webMediaStream && !this._micMixed && now - this._trackSince > 6000 && this._mediaPeak < 0.003 && STATE.video && !STATE.video.paused && !STATE.video.muted && STATE.video.volume > 0) ||
2755
- // or sound is present but the engine never returns words from the track.
2756
- (now - this._trackSince > 12000 && this._lastResultAt < this._trackSince && Math.max(this._levels.media, this._levels.mic) >= SPEECH_LEVEL))) {
2757
- // First try: keep feeding the recognizer, now from the echo-free microphone.
2758
- if (this.webMediaStream && !this._micMixed && this._mixInMic()) { updateAIBtnUX(); return; }
2821
+ (this._mediaSilent() && !this._micMixed) ||
2822
+ // or (microphone track only) sound is present but the engine never returns
2823
+ // words from the track. Never judged on the video sound: music, effects or a
2824
+ // long quiet scene are no reason to give up on it.
2825
+ (!this.webMediaStream && this.captureMode === 'mic' && now - this._trackSince > 40000 && this._lastResultAt < this._trackSince && this._levels.mic >= SPEECH_LEVEL))) {
2826
+ // Silent video sound: keep feeding the recognizer, from the echo-free microphone,
2827
+ // and offer the tab's sound (one tap) in the subtitle area.
2828
+ if (this.webMediaStream) { if (!this._micMixing) this._mixInMic(); updateAIBtnUX(); return; }
2759
2829
  this._trackDisabled = true;
2760
2830
  logDebug('AI Sub: captured audio unusable, switching to the recognizer’s own microphone.', 'warn');
2761
2831
  if (!this._micMixed) showToast(t('subUsingMicFallback'));
@@ -2764,12 +2834,24 @@
2764
2834
  this._createRecognizer();
2765
2835
  this._scheduleRestart('track-fallback', 150, true);
2766
2836
  }
2837
+ this._updateListenChip();
2767
2838
  updateAIBtnUX();
2768
2839
  },
2769
- _mixInMic() {
2840
+ // The video is audibly playing but the captured sound has stayed digitally silent.
2841
+ _mediaSilent() {
2842
+ const v = STATE.video;
2843
+ return !!(this.webMediaStream && this._trackSince && Date.now() - this._trackSince > 6000 && this._mediaPeak < 0.003
2844
+ && v && !v.paused && !v.muted && v.volume > 0);
2845
+ },
2846
+ async _mixInMic() {
2770
2847
  const ctx = this.audioContext, nodes = this.audioNodes;
2771
- if (!this.mediaStream || !ctx || !nodes?.mix) return false;
2848
+ if (this._micMixed || this._micMixing || !ctx || !nodes?.mix) return false;
2849
+ this._micMixing = true;
2772
2850
  try {
2851
+ if (!this.mediaStream) {
2852
+ try { this.mediaStream = await this._requestMic(true); } catch (_) { return false; }
2853
+ if (!this.active || this.audioContext !== ctx) { this.mediaStream.getTracks().forEach(tr => tr.stop()); this.mediaStream = null; return false; }
2854
+ }
2773
2855
  const src = ctx.createMediaStreamSource(this.mediaStream);
2774
2856
  const an = ctx.createAnalyser();
2775
2857
  an.fftSize = 512;
@@ -2782,10 +2864,64 @@
2782
2864
  this._preparePlaybackMic();
2783
2865
  this._trackSince = Date.now();
2784
2866
  this.captureMode = 'mic';
2867
+ if (this._useWebSpeech && this.active) {
2868
+ // Listen to the mix (video + microphone) from now on.
2869
+ this._destroyRecognizer();
2870
+ this._createRecognizer();
2871
+ this._scheduleRestart('mic-mixed', 150, true);
2872
+ }
2785
2873
  showToast(t('subUsingMicFallback'));
2786
2874
  logDebug('AI Sub: the video sound is silent here, listening through the microphone.', 'warn');
2787
2875
  return true;
2788
- } catch (_) { return false; }
2876
+ } catch (_) { return false; } finally { this._micMixing = false; }
2877
+ },
2878
+ // One tap in the subtitle area: listen to this tab's sound instead (needs the tap,
2879
+ // because the browser only opens its sharing dialog for a user action).
2880
+ async shareTabAudio() {
2881
+ if (!this.active || !navigator.mediaDevices?.getDisplayMedia) return;
2882
+ try {
2883
+ const st = await this._captureDisplayAudio();
2884
+ try { this._sharedTab?.getTracks().forEach(tr => tr.stop()); } catch (_) { }
2885
+ this._sharedTab = st;
2886
+ this._trackDisabled = false;
2887
+ await this.restart('tab audio shared');
2888
+ } catch (err) {
2889
+ logDebug('AI Sub: tab audio not shared: ' + (err.message || err.name), 'warn');
2890
+ showToast(t('subTabNotShared'));
2891
+ }
2892
+ },
2893
+ _canShareTab() {
2894
+ return !this._isAppleMobile() && !this._isAndroid() && !!navigator.mediaDevices?.getDisplayMedia && !this._liveTab();
2895
+ },
2896
+ // A small "listening" chip: shows that sound is arriving (level meter), and when the
2897
+ // video's sound cannot be heard, says so with a one-tap way to connect the tab sound.
2898
+ _updateListenChip() {
2899
+ const overlay = shadow?.getElementById('nxu-subtitle-overlay');
2900
+ if (!overlay) return;
2901
+ let chip = overlay.querySelector('.sub-listen');
2902
+ if (!this.active) { chip?.remove(); return; }
2903
+ if (!chip) {
2904
+ chip = createEl('div', 'sub-listen');
2905
+ const btn = createEl('button', 'sub-listen-btn', t('subShareTab'), { type: 'button' });
2906
+ btn.addEventListener('click', (e) => { e.stopPropagation(); this.shareTabAudio(); });
2907
+ const meter = createEl('span', 'sub-listen-meter');
2908
+ meter.appendChild(createEl('i'));
2909
+ chip.append(createEl('span', 'sub-listen-text'), meter, btn);
2910
+ overlay.prepend(chip);
2911
+ }
2912
+ const wantedVideo = this.audioMode === 'media' && this.captureMode !== 'ios-mic';
2913
+ const silent = this._mediaSilent();
2914
+ const fellBack = wantedVideo && !this.webMediaStream;
2915
+ const offer = (silent || fellBack) && this._canShareTab();
2916
+ const showing = !!(shadow.getElementById('nxu-final-slot')?.childElementCount || shadow.getElementById('nxu-interim-slot')?.childElementCount);
2917
+ chip.classList.toggle('hide', showing && !offer);
2918
+ chip.classList.toggle('warn', silent);
2919
+ chip.classList.toggle('warn', silent || !!this._issue);
2920
+ if (this._issue) chip.classList.remove('hide');
2921
+ chip.querySelector('.sub-listen-text').textContent = this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
2922
+ const level = Math.max(this._levels.media || 0, this._levels.mic || 0);
2923
+ chip.querySelector('.sub-listen-meter i').style.width = Math.min(100, Math.round(level * 400)) + '%';
2924
+ chip.querySelector('.sub-listen-btn').style.display = offer ? '' : 'none';
2789
2925
  },
2790
2926
  _preparePlaybackMic() {
2791
2927
  const track = this.mediaStream?.getAudioTracks?.()[0];
@@ -2807,6 +2943,7 @@
2807
2943
  this._networkErrors = 0;
2808
2944
  this._networkRetryMs = 0;
2809
2945
  this._audioCaptureErrors = 0;
2946
+ this._issue = '';
2810
2947
  const finals = [];
2811
2948
  const interim = [];
2812
2949
  let confidence = null;
@@ -2971,11 +3108,21 @@
2971
3108
  }
2972
3109
  return;
2973
3110
  case 'audio-capture':
3111
+ if (this._recognitionInput === 'track' && !this._trackDisabled) {
3112
+ // The engine could not read the captured track: let it use its own input.
3113
+ this._trackDisabled = true;
3114
+ logDebug('AI Sub: the speech engine could not read the captured audio, using its own input.', 'warn');
3115
+ this._destroyRecognizer();
3116
+ this._createRecognizer();
3117
+ this._scheduleRestart('track-capture-error', 200, true);
3118
+ return;
3119
+ }
2974
3120
  if (++this._audioCaptureErrors >= 3) { this.stop(t('subNoMic')); return; }
2975
3121
  this._networkRetryMs = 1000;
2976
3122
  return;
2977
3123
  case 'network': {
2978
3124
  this._networkErrors++;
3125
+ this._issue = this._networkErrors >= 2 ? 'net' : '';
2979
3126
  if (this._networkErrors >= 12) { this.stop(t('subNetworkFailed')); return; }
2980
3127
  if (navigator.onLine === false) { this._waitOnline = true; return; }
2981
3128
  this._networkRetryMs = Math.min(15000, Math.max(800, (this._networkRetryMs || 600) * 1.7));
@@ -3501,6 +3648,7 @@
3501
3648
  this._networkErrors = 0;
3502
3649
  this._networkRetryMs = 0;
3503
3650
  this._audioCaptureErrors = 0;
3651
+ this._issue = '';
3504
3652
  this._sessionFailures = 0;
3505
3653
  this._trackDisabled = false;
3506
3654
  this._waitOnline = false;
@@ -3571,6 +3719,7 @@
3571
3719
  clearInterval(this._watchdogTimer);
3572
3720
  this._watchdogTimer = setInterval(() => this._watchdog(), 4000);
3573
3721
  this.getOverlay();
3722
+ this._updateListenChip();
3574
3723
  SUB_LAYOUT.schedule();
3575
3724
  this._syncUI();
3576
3725
  if (!silent) showToast(t('subOn'));
@@ -3617,6 +3766,9 @@
3617
3766
  this._restoreAppleSession();
3618
3767
  this._resetRuntime();
3619
3768
  if (!keepOverlay) {
3769
+ try { this._sharedTab?.getTracks().forEach(tr => tr.stop()); } catch (_) { }
3770
+ this._sharedTab = null;
3771
+ shadow?.getElementById('nxu-subtitle-overlay')?.querySelector('.sub-listen')?.remove();
3620
3772
  const overlay = shadow?.getElementById('nxu-subtitle-overlay');
3621
3773
  if (overlay) {
3622
3774
  overlay.style.opacity = '0';
@@ -5440,7 +5592,24 @@
5440
5592
  shieldUntil: 0,
5441
5593
  noteTap() { this.tapAt = Date.now(); },
5442
5594
  noteType() { this.typeAt = Date.now(); },
5443
- shield(ms = 650) { this.shieldUntil = Math.max(this.shieldUntil, Date.now() + ms); },
5595
+ shield(ms = 650) { this.shieldUntil = Math.max(this.shieldUntil, Date.now() + ms); this._arm(); },
5596
+ // The page-wide click swallower is attached only while the shield is up (a permanent
5597
+ // non-passive touch listener on the window slows every tap and scroll on phones).
5598
+ _types: ['click', 'dblclick', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'touchstart', 'touchend'],
5599
+ _arm() {
5600
+ if (!this._swallow) return;
5601
+ if (!this._armed) {
5602
+ this._armed = true;
5603
+ this._types.forEach(type => window.addEventListener(type, this._swallow, { capture: true, passive: false }));
5604
+ }
5605
+ clearTimeout(this._disarmTimer);
5606
+ const left = this.shieldUntil - Date.now();
5607
+ this._disarmTimer = setTimeout(() => {
5608
+ if (Date.now() < this.shieldUntil) { this._arm(); return; }
5609
+ this._armed = false;
5610
+ this._types.forEach(type => window.removeEventListener(type, this._swallow, { capture: true }));
5611
+ }, Math.max(50, left + 60));
5612
+ },
5444
5613
  accidental() {
5445
5614
  const now = Date.now();
5446
5615
  if (now - (STATE._ownControlAt || 0) < 900) return false;
@@ -5458,7 +5627,8 @@
5458
5627
  if (e.cancelable) e.preventDefault();
5459
5628
  e.stopImmediatePropagation();
5460
5629
  };
5461
- ['click', 'dblclick', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'touchstart', 'touchend'].forEach(type => window.addEventListener(type, swallow, { capture: true, passive: false }));
5630
+ this._swallow = swallow;
5631
+ if (Date.now() < this.shieldUntil) this._arm();
5462
5632
  }
5463
5633
  };
5464
5634
 
@@ -5797,19 +5967,61 @@
5797
5967
  hud._hideTimer = setTimeout(() => { hud.style.display = 'none'; }, 8000);
5798
5968
  }
5799
5969
 
5970
+ // Who is here, for display: me first, then by name, each with their own colour and a
5971
+ // small mark for "watching only", "away" (screen off / other tab) and an outdated version.
5972
+ function roomRoster() {
5973
+ const safeColor = c => (/^#[0-9a-f]{3,8}$/i.test(String(c || '')) ? c : '#7c4dff');
5974
+ const list = Object.entries(STATE.presenceMap || {}).map(([uid, p]) => {
5975
+ const self = uid === STATE.userId;
5976
+ return {
5977
+ uid, self,
5978
+ name: self ? (STATE.nickname || t('you')) : (p?.nick || 'ID:' + String(uid).slice(0, 3)),
5979
+ color: safeColor(self ? STATE.color : p?.color),
5980
+ viewer: self ? !!STATE.isViewer : !!p?.viewer,
5981
+ away: !self && !!p?.hid,
5982
+ oldVer: !self && !!(p?.v && p.v !== NXU_VERSION)
5983
+ };
5984
+ });
5985
+ list.sort((a, b) => (b.self - a.self) || a.name.localeCompare(b.name));
5986
+ return list;
5987
+ }
5988
+ function renderRoster(box, max = 4) {
5989
+ const list = roomRoster();
5990
+ const sig = max + '|' + list.map(m => [m.uid, m.name, m.color, m.viewer, m.away, m.oldVer].join(',')).join(';');
5991
+ if (box._rosterSig === sig) return list;
5992
+ box._rosterSig = sig;
5993
+ box.replaceChildren();
5994
+ list.slice(0, max).forEach(m => {
5995
+ const chip = createEl('span', 'nx-who' + (m.away ? ' away' : '') + (m.self ? ' me' : ''));
5996
+ const dot = createEl('i', 'nx-who-dot');
5997
+ dot.style.background = m.color;
5998
+ chip.append(dot, createEl('span', 'nx-who-name', m.name + (m.self && STATE.nickname ? ' ' + t('meTag') : '')));
5999
+ if (m.viewer) chip.append(createEl('span', 'nx-who-tag', '👀'));
6000
+ if (m.away) chip.append(createEl('span', 'nx-who-tag', '💤'));
6001
+ if (m.oldVer) chip.append(createEl('span', 'nx-who-tag', '⚠️'));
6002
+ chip.title = [m.name, m.viewer && t('whoViewer'), m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
6003
+ box.appendChild(chip);
6004
+ });
6005
+ if (list.length > max) box.appendChild(createEl('span', 'nx-who more', '+' + (list.length - max)));
6006
+ box.title = t('whoTitle') + ' (' + list.length + ')';
6007
+ return list;
6008
+ }
6009
+
5800
6010
  function updatePresenceUI() {
5801
6011
  if (!shadow) return;
5802
6012
  let pill = shadow.getElementById('nxu-presence-pill');
5803
6013
  if (!pill && uiElements.uiWrapper) {
5804
6014
  pill = createEl('div', 'presence-pill');
5805
6015
  pill.id = 'nxu-presence-pill';
6016
+ pill.setAttribute('role', 'button');
6017
+ // Tap: the full list (everyone, one per line) ↔ the short row of names.
6018
+ pill.addEventListener('click', (e) => { e.stopPropagation(); pill.classList.toggle('open'); updatePresenceUI(); });
5806
6019
  uiElements.uiWrapper.appendChild(pill);
5807
6020
  }
5808
6021
  if (!pill) return;
5809
6022
  const entries = Object.values(STATE.presenceMap);
5810
6023
  if (entries.length && STATE.role !== 'IDLE') {
5811
- pill.textContent = '👥 ' + t('watching', { n: entries.length });
5812
- pill.title = entries.map(e => e.nick || e.role || '').filter(Boolean).join(', ');
6024
+ renderRoster(pill, pill.classList.contains('open') ? 50 : 3);
5813
6025
  pill.style.display = '';
5814
6026
  } else {
5815
6027
  pill.style.display = 'none';
@@ -5824,11 +6036,11 @@
5824
6036
 
5825
6037
  function currentMediaInfo() {
5826
6038
  if (STATE.video) {
5827
- return { kind: 'video', el: STATE.video, time: STATE.video.currentTime, duration: STATE.video.duration, paused: STATE.video.paused };
6039
+ return { kind: 'video', el: STATE.video, time: STATE.video.currentTime, duration: STATE.video.duration, paused: STATE.video.paused, live: VIDEO_DETECTOR.isLive(STATE.video) };
5828
6040
  }
5829
6041
  if (STATE.cinemaIframe) {
5830
6042
  const rep = VIDEO_DETECTOR.frameReports.get(STATE.cinemaIframe) || {};
5831
- return { kind: 'iframe', el: STATE.cinemaIframe, time: STATE.lastCinemaTime || 0, duration: rep.duration, paused: rep.paused !== false };
6043
+ return { kind: 'iframe', el: STATE.cinemaIframe, time: STATE.lastCinemaTime || 0, duration: rep.duration, paused: rep.paused !== false, live: !!rep.live };
5832
6044
  }
5833
6045
  return null;
5834
6046
  }
@@ -6296,12 +6508,21 @@
6296
6508
  panel.style.top = Math.max(12, Math.min(initTop + dy, getH() - panel.offsetHeight - 12)) + 'px';
6297
6509
  };
6298
6510
  const onUp = () => { dragging = false; };
6299
- handle.addEventListener('mousedown', onDown);
6300
- handle.addEventListener('touchstart', onDown, { passive: true });
6301
- window.addEventListener('mousemove', onMove);
6302
- window.addEventListener('touchmove', onMove, { passive: false });
6303
- window.addEventListener('mouseup', onUp);
6304
- window.addEventListener('touchend', onUp);
6511
+ // Page-wide move/up listeners exist only while dragging: a permanent non-passive
6512
+ // touchmove on the window makes every scroll and tap on the page wait for script,
6513
+ // which felt sluggish on iPhone.
6514
+ const listen = (on) => {
6515
+ const m = on ? 'addEventListener' : 'removeEventListener';
6516
+ window[m]('mousemove', onMove);
6517
+ window[m]('touchmove', onMove, { passive: false });
6518
+ window[m]('mouseup', finish);
6519
+ window[m]('touchend', finish);
6520
+ window[m]('touchcancel', finish);
6521
+ };
6522
+ const finish = (e) => { listen(false); onUp(e); };
6523
+ const begin = (e) => { onDown(e); if (dragging) listen(true); };
6524
+ handle.addEventListener('mousedown', begin);
6525
+ handle.addEventListener('touchstart', begin, { passive: true });
6305
6526
  }
6306
6527
 
6307
6528
  function updateSmartPosition(wrapper, fab, dock, reactPill) {
@@ -6409,12 +6630,21 @@
6409
6630
  STORE.set('nxu_fab_pos', { x: parseFloat(wrapper.style.left) / Math.max(1, w - 48), y: parseFloat(wrapper.style.top) / Math.max(1, h - 48) });
6410
6631
  }
6411
6632
  };
6412
- handle.addEventListener('mousedown', onDown);
6413
- handle.addEventListener('touchstart', onDown, { passive: true });
6414
- window.addEventListener('mousemove', onMove);
6415
- window.addEventListener('touchmove', onMove, { passive: false });
6416
- window.addEventListener('mouseup', onUp);
6417
- window.addEventListener('touchend', onUp);
6633
+ // Page-wide move/up listeners exist only while dragging: a permanent non-passive
6634
+ // touchmove on the window makes every scroll and tap on the page wait for script,
6635
+ // which felt sluggish on iPhone.
6636
+ const listen = (on) => {
6637
+ const m = on ? 'addEventListener' : 'removeEventListener';
6638
+ window[m]('mousemove', onMove);
6639
+ window[m]('touchmove', onMove, { passive: false });
6640
+ window[m]('mouseup', finish);
6641
+ window[m]('touchend', finish);
6642
+ window[m]('touchcancel', finish);
6643
+ };
6644
+ const finish = (e) => { listen(false); onUp(e); };
6645
+ const begin = (e) => { onDown(e); if (dragging) listen(true); };
6646
+ handle.addEventListener('mousedown', begin);
6647
+ handle.addEventListener('touchstart', begin, { passive: true });
6418
6648
 
6419
6649
  const restore = () => {
6420
6650
  const saved = STORE.get('nxu_fab_pos', null);
@@ -6649,6 +6879,13 @@
6649
6879
  #ui-wrapper.ui-idle.touch-peek .fab { pointer-events:auto !important; }
6650
6880
  #ui-wrapper.ui-idle.touch-peek > :not(.fab) { visibility:hidden !important; }
6651
6881
  button { font-family:inherit; }
6882
+ button, [role="button"], .seg-btn, .cc-btn, .react-btn { touch-action:manipulation; -webkit-tap-highlight-color:transparent; }
6883
+ /* Touch devices: no backdrop blur. Blurring what lies behind a menu over a playing
6884
+ video is redone every frame and was the main cause of sluggish taps on iPhone. */
6885
+ @media (hover:none) and (pointer:coarse) {
6886
+ *, *::before, *::after { -webkit-backdrop-filter:none !important; backdrop-filter:none !important; }
6887
+ .nexus-container.nexus-container { --glass:rgba(20,25,30,0.5); --glass-strong:rgba(18,22,28,0.66); }
6888
+ }
6652
6889
  .fab { pointer-events:auto; position:absolute; width:48px; height:48px; border-radius:50%; background:var(--glass); border:1px solid rgba(255,255,255,0.22); color:#fff; cursor:grab; font-size:22px;
6653
6890
  backdrop-filter:blur(12px); -webkit-backdrop-filter:blur(12px); box-shadow:0 4px 15px rgba(0,0,0,0.35); display:flex; align-items:center; justify-content:center; user-select:none; touch-action:none; z-index:101; padding:0; }
6654
6891
  .fab.menu-open { background:var(--glass-active); border-color:rgba(0,230,118,0.5); }
@@ -6675,7 +6912,16 @@
6675
6912
  .nx-spark { position:absolute; font-size:13px; pointer-events:none; transform:translate(-50%,-50%); opacity:0; animation:nxSpark .7s cubic-bezier(.2,.7,.3,1) both; z-index:2100; }
6676
6913
  @keyframes nxSpark { 0% { opacity:1; transform:translate(-50%,-50%) scale(.6); } 100% { opacity:0; transform:translate(calc(-50% + var(--dx)), calc(-50% + var(--dy))) scale(1.05) rotate(var(--rot)); } }
6677
6914
  @media (prefers-reduced-motion: reduce) { .react-btn.pop, .react-btn.pop::after, .nx-spark { animation:none !important; } }
6678
- .presence-pill { position:absolute; font-size:11px; padding:3px 8px; border-radius:99px; background:rgba(0,0,0,0.6); color:#e0e0e0; white-space:nowrap; pointer-events:auto; }
6915
+ .presence-pill { position:absolute; display:flex; gap:3px; align-items:center; font-size:11px; padding:3px 4px; border-radius:99px; background:rgba(0,0,0,0.45); color:#e0e0e0; white-space:nowrap; pointer-events:auto; cursor:pointer; max-width:min(78vw, 360px); overflow:hidden; }
6916
+ .presence-pill.open { flex-direction:column; align-items:stretch; border-radius:12px; padding:5px; max-height:50vh; overflow:auto; }
6917
+ .nx-who { display:inline-flex; align-items:center; gap:4px; padding:2px 7px 2px 5px; border-radius:99px; background:rgba(255,255,255,0.1); font-size:11.5px; font-weight:600; line-height:1.3; max-width:140px; color:rgba(255,255,255,0.92); text-shadow:0 1px 2px rgba(0,0,0,0.6); }
6918
+ .presence-pill.open .nx-who { max-width:none; }
6919
+ .nx-who.me { background:rgba(255,255,255,0.18); }
6920
+ .nx-who.away { opacity:0.55; }
6921
+ .nx-who.more { padding:2px 7px; }
6922
+ .nx-who-dot { flex:none; width:8px; height:8px; border-radius:50%; box-shadow:0 0 5px currentColor; }
6923
+ .nx-who-name { overflow:hidden; text-overflow:ellipsis; }
6924
+ .nx-who-tag { font-size:10px; }
6679
6925
  .dock { position:absolute; background:var(--glass-strong); border-radius:16px; padding:10px; display:flex; flex-direction:column; gap:6px; pointer-events:none; opacity:0; border:1px solid rgba(255,255,255,0.1);
6680
6926
  transition:opacity 0.25s ease, transform 0.25s ease; box-shadow:0 10px 30px rgba(0,0,0,0.35); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); z-index:90; overflow-y:auto; text-shadow:0 1px 2px rgba(0,0,0,0.8); overflow-x:hidden; width:clamp(150px, 40vw, 190px); width:clamp(150px, 40cqw, 190px); }
6681
6927
  .dock.open { opacity:1; pointer-events:auto; border-color:rgba(0,230,118,0.3); }
@@ -6944,6 +7190,12 @@
6944
7190
  .shield-title { font-size:21px; font-weight:800; margin-bottom:12px; }
6945
7191
  .shield-text { opacity:0.8; margin-bottom:18px; line-height:1.45; font-size:14px; }
6946
7192
  .shield-btn { font-size:17px; padding:14px; }
7193
+ .sub-listen { display:flex; align-items:center; gap:7px; padding:4px 6px 4px 10px; border-radius:99px; background:rgba(0,0,0,0.45); color:rgba(255,255,255,0.88); font-size:12px; font-weight:600; text-shadow:0 1px 2px rgba(0,0,0,0.7); pointer-events:auto; transition:opacity 0.3s ease; }
7194
+ .sub-listen.hide { opacity:0; pointer-events:none; }
7195
+ .sub-listen.warn { background:rgba(120,60,0,0.6); }
7196
+ .sub-listen-meter { width:38px; height:5px; border-radius:3px; background:rgba(255,255,255,0.18); overflow:hidden; }
7197
+ .sub-listen-meter i { display:block; height:100%; width:0; background:#40c4ff; transition:width 0.35s ease; }
7198
+ .sub-listen-btn { border:0; border-radius:99px; padding:4px 10px; background:#7c4dff; color:#fff; font:inherit; font-size:12px; font-weight:700; cursor:pointer; }
6947
7199
  .sub-overlay-container { position:absolute; bottom:11%; left:50%; transform:translateX(-50%); width:clamp(280px, 90vw, 880px); width:clamp(280px, 90cqw, 880px); display:flex; flex-direction:column; align-items:center; gap:6px; transition:opacity 0.3s ease; z-index:70; user-select:none; }
6948
7200
  .sub-overlay-container.anchored { transition:opacity 0.3s ease; }
6949
7201
  .sub-slot { width:100%; display:flex; flex-direction:column; align-items:center; gap:6px; transition:opacity 0.25s ease; }
@@ -7009,7 +7261,7 @@
7009
7261
  .cc-title { color:#fff; font-size:15px; font-weight:700; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; text-shadow:0 1px 3px rgba(0,0,0,0.8); }
7010
7262
  .cc-room { display:none; align-items:center; gap:6px; font-size:12px; font-weight:600; color:rgba(255,255,255,0.85); text-shadow:0 1px 2px rgba(0,0,0,0.8); }
7011
7263
  .cc-room.show { display:flex; }
7012
- .cc-room::before { content:''; width:7px; height:7px; border-radius:50%; background:var(--cc-accent); box-shadow:0 0 6px var(--cc-accent); }
7264
+ .cc-room { flex-wrap:wrap; gap:4px; }
7013
7265
  .cc-bottom { bottom:0; padding:0 calc(14px + env(safe-area-inset-right, 0px)) calc(8px + env(safe-area-inset-bottom, 0px)) calc(14px + env(safe-area-inset-left, 0px)); }
7014
7266
  .cc-center { top:50%; display:none; justify-content:center; align-items:center; gap:clamp(28px, 10vw, 72px); transform:translateY(-50%); pointer-events:none; }
7015
7267
  .cinema-chrome.touch:not(.site-mode) .cc-center { display:flex; }
@@ -8176,6 +8428,10 @@
8176
8428
  this._canvas = createEl('canvas', 'nx-ink');
8177
8429
  container.appendChild(this._canvas);
8178
8430
  this._ctx = this._canvas.getContext('2d');
8431
+ if (!this._onResize) {
8432
+ this._onResize = () => { if (this.strokes.size) this._kick(); };
8433
+ window.addEventListener('resize', this._onResize, { passive: true });
8434
+ }
8179
8435
  }
8180
8436
  const dpr = Math.min(2, window.devicePixelRatio || 1);
8181
8437
  const w = container.clientWidth, h = container.clientHeight;
@@ -8193,6 +8449,10 @@
8193
8449
  ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
8194
8450
  const now = Date.now();
8195
8451
  const g = SOCIAL._picture();
8452
+ // Points are converted to screen positions once and reused while the picture's
8453
+ // geometry stays the same (before: every point of every stroke, every frame).
8454
+ const sig = (g ? [g.cx, g.cy, g.cw, g.ch, g.cos, g.sin].map(n => Math.round(n * 100)).join(',') : '') + '|' + window.innerWidth + 'x' + window.innerHeight + '|' + (typeof ROTATE !== 'undefined' ? ROTATE.deg || 0 : 0);
8455
+ let animate = false, wakeIn = Infinity;
8196
8456
  const toUi = ([u, v], ref) => {
8197
8457
  let x, y;
8198
8458
  if (ref === 'pic' && g) {
@@ -8206,7 +8466,11 @@
8206
8466
  const alpha = s.live ? 1 : age < this.HOLD_MS ? 1 : 1 - (age - this.HOLD_MS) / this.FADE_MS;
8207
8467
  if (alpha <= 0) { this.strokes.delete(id); continue; }
8208
8468
  if (s.pts.length < 1) continue;
8209
- const pts = s.pts.map(p => toUi(p, s.ref));
8469
+ if (s._sig !== sig) { s._sig = sig; s._ui = []; }
8470
+ while (s._ui.length < s.pts.length) s._ui.push(toUi(s.pts[s._ui.length], s.ref));
8471
+ const pts = s._ui;
8472
+ if (s.live || age < 400 || age >= this.HOLD_MS) animate = true;
8473
+ else wakeIn = Math.min(wakeIn, this.HOLD_MS - age);
8210
8474
  const path = () => {
8211
8475
  ctx.beginPath();
8212
8476
  ctx.moveTo(pts[0].x, pts[0].y);
@@ -8218,24 +8482,33 @@
8218
8482
  if (pts.length > 1) ctx.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y);
8219
8483
  };
8220
8484
  ctx.save();
8221
- ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
8485
+ const a = Math.max(0, Math.min(1, alpha));
8222
8486
  ctx.lineCap = 'round'; ctx.lineJoin = 'round';
8223
- // Neon: a soft glow in the colour, then a bright core.
8224
- ctx.shadowColor = s.color; ctx.shadowBlur = 16;
8225
- ctx.strokeStyle = s.color; ctx.lineWidth = s.w + 3;
8487
+ // Neon look without shadowBlur (a blur per stroke per frame is what made quick
8488
+ // sketching lag): a wide translucent halo, the colour, then a bright core.
8489
+ ctx.globalAlpha = a * 0.28;
8490
+ ctx.strokeStyle = s.color; ctx.lineWidth = s.w + 10;
8491
+ path(); ctx.stroke();
8492
+ ctx.globalAlpha = a;
8493
+ ctx.lineWidth = s.w + 2.5;
8226
8494
  path(); ctx.stroke();
8227
- ctx.shadowBlur = 0;
8228
8495
  ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.lineWidth = Math.max(1.5, s.w * 0.4);
8229
8496
  path(); ctx.stroke();
8230
8497
  // A sparkle at the tip while it is being drawn.
8231
8498
  if (s.live || age < 400) {
8232
8499
  const tip = pts[pts.length - 1];
8233
- ctx.fillStyle = '#fff'; ctx.shadowColor = s.color; ctx.shadowBlur = 18;
8234
- ctx.beginPath(); ctx.arc(tip.x, tip.y, s.w * 0.9, 0, Math.PI * 2); ctx.fill();
8500
+ ctx.globalAlpha = a * 0.35; ctx.fillStyle = s.color;
8501
+ ctx.beginPath(); ctx.arc(tip.x, tip.y, s.w * 1.9, 0, Math.PI * 2); ctx.fill();
8502
+ ctx.globalAlpha = a; ctx.fillStyle = '#fff';
8503
+ ctx.beginPath(); ctx.arc(tip.x, tip.y, s.w * 0.8, 0, Math.PI * 2); ctx.fill();
8235
8504
  }
8236
8505
  ctx.restore();
8237
8506
  }
8238
- if (this.strokes.size) this._kick();
8507
+ // Redraw every frame only while something moves (drawing, the tip sparkle, fading);
8508
+ // finished strokes simply stay on the canvas until their fade begins.
8509
+ clearTimeout(this._wakeTimer);
8510
+ if (animate) this._kick();
8511
+ else if (wakeIn < Infinity) this._wakeTimer = setTimeout(() => this._kick(), wakeIn + 5);
8239
8512
  },
8240
8513
  active() { return !!this._catcher?.isConnected; },
8241
8514
  start() {
@@ -8532,7 +8805,8 @@
8532
8805
  if (!info) return false;
8533
8806
  const r = info.el.getBoundingClientRect();
8534
8807
  if (r.width < Math.min(420, window.innerWidth * 0.6)) return false;
8535
- return Number.isFinite(info.duration) && info.duration >= 90;
8808
+ // A movie or episode — or a live channel (endless, or a short moving window).
8809
+ return !!info.live || (Number.isFinite(info.duration) && info.duration >= 90);
8536
8810
  },
8537
8811
  tick() {
8538
8812
  if (!IS_TOP || STATE.retired || STATE.isCinema || STATE.pendingCinema || document.hidden) return;
@@ -10500,9 +10774,9 @@
10500
10774
  e.spinnerLabel.textContent = roomWait
10501
10775
  ? (room.sourceDeviceId === STATE.userId ? t('ccWaitSelf') : t('ccWaitPeer', { name: participantName(room.sourceDeviceId) }))
10502
10776
  : '';
10503
- const peers = STATE.handshakeVerified ? Math.max(1, Object.keys(STATE.presenceMap || {}).length) : 0;
10777
+ const peers = STATE.handshakeVerified ? Object.keys(STATE.presenceMap || {}).length : 0;
10504
10778
  e.room.classList.toggle('show', peers > 0);
10505
- if (peers) e.room.textContent = t('ccWatching', { n: peers });
10779
+ if (peers) renderRoster(e.room, 4);
10506
10780
 
10507
10781
  e.seek.style.visibility = duration ? '' : 'hidden';
10508
10782
  if (!this._scrubbing) {
@@ -10795,7 +11069,7 @@
10795
11069
  if (!inUse && this.isClipLike(v)) return false;
10796
11070
  if (v === STATE.video && v.readyState >= 1) return true;
10797
11071
  const dur = v.duration;
10798
- if (Number.isFinite(dur) && dur > 0 && dur < 8) return false;
11072
+ if (Number.isFinite(dur) && dur > 0 && dur < 8 && !this.isLive(v)) return false;
10799
11073
  if (+style.opacity === 0) return false;
10800
11074
  const rect = v.getBoundingClientRect();
10801
11075
  // Parked off-page (preloaded ads, hidden players): left of / above the document.
@@ -10810,12 +11084,22 @@
10810
11084
  // video (gifv, 움짤, hero backgrounds) or a short muted autoplay clip without controls
10811
11085
  // (feed previews, many video ads). Unmuting or adding controls makes it media again
10812
11086
  // (volumechange triggers a rescan).
11087
+ // A live stream: endless, or a moving window (HLS players report the window's few
11088
+ // seconds as the "duration", and the playable range no longer starts at 0).
11089
+ isLive(v) {
11090
+ try {
11091
+ if (!v) return false;
11092
+ if (v.duration === Infinity || v._nxuLive) return true;
11093
+ const s = v.seekable;
11094
+ return !!(s && s.length && s.start(0) > 0.5 && !v.loop);
11095
+ } catch (_) { return false; }
11096
+ },
10813
11097
  isClipLike(v) {
10814
11098
  const silent = v.muted || v.volume === 0;
10815
11099
  if (!silent || v.controls || v.hasAttribute('data-nxu-user-played')) return false;
10816
11100
  if (v.loop) return true;
10817
11101
  const dur = v.duration;
10818
- if (dur === Infinity) return false; // live stream
11102
+ if (this.isLive(v)) return false; // live stream (a TV channel)
10819
11103
  // Silent short clips without controls (previews, ads, animated clips) — unless the
10820
11104
  // user started them; long silent videos (muted players) still count.
10821
11105
  return Number.isNaN(dur) || (dur > 0 && dur < 60);
@@ -10885,7 +11169,23 @@
10885
11169
  return score;
10886
11170
  },
10887
11171
 
11172
+ // HLS live players start the stream at 0 and grow the "duration" as segments arrive:
11173
+ // a duration that keeps growing while it plays marks a live channel.
11174
+ _watchLive(v) {
11175
+ if (v._nxuLiveWatch) return;
11176
+ v._nxuLiveWatch = true;
11177
+ let last = v.duration;
11178
+ v.addEventListener('durationchange', () => {
11179
+ const d = v.duration;
11180
+ if (Number.isFinite(d) && Number.isFinite(last) && d > last + 0.5 && d - last < 120 && !v._nxuLive) {
11181
+ v._nxuLive = true;
11182
+ this.scheduleScan(30);
11183
+ }
11184
+ last = d;
11185
+ });
11186
+ },
10888
11187
  _videoInfo(v) {
11188
+ this._watchLive(v);
10889
11189
  const playing = !!(v.isConnected && !v.paused && !v.ended && v.readyState >= 2);
10890
11190
  let score = this._scoreRect(rectInTop(v), playing);
10891
11191
  if (!v.ended) score += 500;
@@ -11037,11 +11337,11 @@
11037
11337
  msg = {
11038
11338
  type: 'NXU_VIDEO_FOUND', videoW: v.videoWidth || 0, videoH: v.videoHeight || 0,
11039
11339
  duration: Number.isFinite(v.duration) ? v.duration : null, paused: !!v.paused,
11040
- playing: !v.paused && !v.ended && v.readyState >= 2
11340
+ playing: !v.paused && !v.ended && v.readyState >= 2, live: this.isLive(v)
11041
11341
  };
11042
11342
  } else if (STATE.cinemaIframe) {
11043
11343
  const rep = this.frameReports.get(STATE.cinemaIframe) || {};
11044
- msg = { type: 'NXU_VIDEO_FOUND', videoW: rep.w || 0, videoH: rep.h || 0, duration: Number.isFinite(rep.duration) ? rep.duration : null, paused: rep.paused !== false, playing: !!rep.playing };
11344
+ msg = { type: 'NXU_VIDEO_FOUND', videoW: rep.w || 0, videoH: rep.h || 0, duration: Number.isFinite(rep.duration) ? rep.duration : null, paused: rep.paused !== false, playing: !!rep.playing, live: !!rep.live };
11045
11345
  }
11046
11346
  if (msg) {
11047
11347
  const sig = JSON.stringify(msg);
@@ -11079,7 +11379,7 @@
11079
11379
  FRAME.postToParent({
11080
11380
  type: 'NXU_VIDEO_EVENT', event: evt,
11081
11381
  currentTime: video.currentTime, paused: video.paused, playbackRate: RATE.base(video),
11082
- duration: Number.isFinite(video.duration) ? video.duration : null,
11382
+ duration: Number.isFinite(video.duration) ? video.duration : null, live: this.isLive(video),
11083
11383
  volume: video.volume, muted: video.muted, buffered: bufferedEnd(video),
11084
11384
  remoteEventId: Date.now() < (video._nxuRemoteUntil || 0) && String(video._nxuRemoteKinds || '').split(' ').includes(evt) ? video._nxuRemoteEventId : null,
11085
11385
  userGesture
@@ -11165,7 +11465,7 @@
11165
11465
  case 'NXU_VIDEO_FOUND':
11166
11466
  this._watchFrameBox(ifr);
11167
11467
  this.frameReports.set(ifr, {
11168
- w: data.videoW, h: data.videoH, duration: data.duration, paused: data.paused !== false,
11468
+ w: data.videoW, h: data.videoH, duration: data.duration, live: !!data.live, paused: data.paused !== false,
11169
11469
  playing: !!data.playing, currentTime: this.frameReports.get(ifr)?.currentTime || 0, ts: Date.now()
11170
11470
  });
11171
11471
  if (isTarget && !IS_TOP) this._reportUp();
@@ -11191,6 +11491,7 @@
11191
11491
  rep.playing = !data.paused && !rep.waiting;
11192
11492
  rep.currentTime = data.currentTime;
11193
11493
  if (Number.isFinite(data.duration)) rep.duration = data.duration;
11494
+ if (typeof data.live === 'boolean') rep.live = data.live;
11194
11495
  rep.ts = Date.now();
11195
11496
  this.frameReports.set(ifr, rep);
11196
11497
  // A frame we are not using yet started playing: it may be the real player.
@@ -11427,8 +11728,10 @@
11427
11728
  });
11428
11729
 
11429
11730
  // Genuine user gestures distinguish user playback from site auto-resume.
11731
+ // On window (capture): the earliest listener, so a page that stops the event in its own
11732
+ // handler (many players do for Space) cannot hide the gesture.
11430
11733
  ['pointerdown', 'mousedown', 'touchstart', 'keydown'].forEach(type => {
11431
- document.addEventListener(type, () => { if (!MEDIA_SAFE._simulatingKey) STATE._lastUserGestureTs = Date.now(); }, { capture: true, passive: true });
11734
+ window.addEventListener(type, (e) => { if (!MEDIA_SAFE._simulatingKey && e.isTrusted !== false) STATE._lastUserGestureTs = Date.now(); }, { capture: true, passive: true });
11432
11735
  });
11433
11736
  // What the user clicked/tapped (a scroll never produces a click): tells a video the user
11434
11737
  // started apart from autoplay previews that start while scrolling a feed.
@@ -11459,6 +11762,36 @@
11459
11762
  }
11460
11763
  };
11461
11764
 
11765
+ // Space bar = play / pause for the room's video, wherever the keyboard focus is.
11766
+ // Often the page itself cannot do it: the player sits in another site's frame (keys go
11767
+ // to the top page), or the focus stayed on a NexusSync button (Space would press that
11768
+ // button). The page gets the first chance; if the video did not change, we toggle it.
11769
+ const SPACE_KEY = {
11770
+ handle(e, target) {
11771
+ if (e.code !== 'Space' || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return false;
11772
+ const info = currentMediaInfo();
11773
+ if (!info) return false;
11774
+ const host = shadow?.host;
11775
+ const inUi = !!host && (typeof e.composedPath === 'function' ? e.composedPath().includes(host) : false);
11776
+ // A frame player cannot hear the key, and a focused NexusSync button must not be pressed.
11777
+ if (inUi || info.kind === 'iframe') {
11778
+ e.preventDefault();
11779
+ e.stopPropagation();
11780
+ if (!e.repeat) { applyMediaCommand('toggle'); STATE._ownControlAt = Date.now(); }
11781
+ try { if (inUi && target && typeof target.blur === 'function' && target.tagName === 'BUTTON') target.blur(); } catch (_) { }
11782
+ return true;
11783
+ }
11784
+ if (e.repeat || STATE.role === 'IDLE') return false;
11785
+ const before = info.paused, el = info.el;
11786
+ clearTimeout(this._timer);
11787
+ this._timer = setTimeout(() => {
11788
+ const now = currentMediaInfo();
11789
+ if (now && now.el === el && now.paused === before) applyMediaCommand('toggle');
11790
+ }, 320);
11791
+ return false;
11792
+ }
11793
+ };
11794
+
11462
11795
  document.addEventListener('keydown', (e) => {
11463
11796
  // Our own simulated key (player fallback) and page-generated keys are not shortcuts.
11464
11797
  if (STATE.retired || MEDIA_SAFE._simulatingKey || !e.isTrusted) return;
@@ -11476,6 +11809,7 @@
11476
11809
  }
11477
11810
  if (isEditableTarget(target) && !(isPlayerSlider(target) && STATE.isCinema)) return;
11478
11811
  if (STATE.isCinema && (IS_TOP || STATE.video) && CINEMA_UI.handleKey(e)) return;
11812
+ if (IS_TOP && SPACE_KEY.handle(e, target)) return;
11479
11813
  if (e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && HOTKEYS.map[e.code]) {
11480
11814
  e.preventDefault();
11481
11815
  e.stopPropagation();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangsicj/nexussync",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Watch-together userscript: media sync, cinema mode, live AI subtitles, chat bubbles and quick ink for Tampermonkey and iOS Userscripts.",
5
5
  "keywords": [
6
6
  "userscript",