@kangsicj/nexussync 1.2.0 → 1.3.0

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.2.0-7C4DFF?style=for-the-badge)](./CHANGELOG.md)
7
+ [![Version](https://img.shields.io/badge/version-1.3.0-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)
@@ -61,7 +61,7 @@ Draw a quick circle around that actor and it glows on everyone's screen — on t
61
61
  <td valign="top">
62
62
 
63
63
  ### 🧠 Live AI subtitles
64
- No subtitles on that video? Turn on live speech recognition with translation into your language, with a glossary for names and terms so characters are always spelled right.
64
+ No subtitles on that video? Pick your language, choose **video sound** and press Start — NexusSync listens to the video itself and writes live, translated subtitles, with a glossary so names are always spelled right.
65
65
 
66
66
  </td>
67
67
  </tr>
@@ -74,6 +74,7 @@ No subtitles on that video? Turn on live speech recognition with translation int
74
74
  - **Make it yours** — pick your name and colour; your bubbles and doodles wear it on every screen.
75
75
  - **Calm, never jumpy** — phones going to sleep, slow Wi-Fi or a player restarting on its own never pause the whole room.
76
76
  - **No accidental pauses** — tapping the chat, a doodle or a reaction never nudges the video for anyone.
77
+ - **No ad interruptions** — ad boxes and links laid over the video are hidden while you watch, and ad pop-ups opened by a tap on the player are stopped.
77
78
  - **Invisible until needed** — the ⚙️ button appears only next to real videos, never on ordinary pages.
78
79
  - **Private rooms** — everything you share in a room is end-to-end encrypted; only people with the PIN can join.
79
80
 
@@ -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.2.0
11
+ // @version 1.3.0
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 *://*/*
@@ -24,6 +24,7 @@
24
24
  // @grant GM.getValue
25
25
  // @grant GM.listValues
26
26
  // @grant GM.xmlHttpRequest
27
+ // @grant unsafeWindow
27
28
  // @connect translate.googleapis.com
28
29
  // @connect nexussync-dd5b4-default-rtdb.asia-southeast1.firebasedatabase.app
29
30
  // @connect api.openai.com
@@ -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.2.0
11
+ // @version 1.3.0
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 *://*/*
@@ -24,6 +24,7 @@
24
24
  // @grant GM.getValue
25
25
  // @grant GM.listValues
26
26
  // @grant GM.xmlHttpRequest
27
+ // @grant unsafeWindow
27
28
  // @connect translate.googleapis.com
28
29
  // @connect nexussync-dd5b4-default-rtdb.asia-southeast1.firebasedatabase.app
29
30
  // @connect api.openai.com
@@ -42,12 +43,12 @@
42
43
 
43
44
  // The version of the code that is actually running (the manager's metadata can lag
44
45
  // behind when an old copy is still installed).
45
- const NXU_VERSION = '1.2.0';
46
+ const NXU_VERSION = '1.3.0';
46
47
  // Rank used by the one-instance guard below and to tell newer builds apart in a room.
47
48
  // It is independent of the public version (1.0.0 is the first public release, after
48
49
  // private builds that reached ranks up to 10.2.0), so every older copy still installed
49
50
  // steps aside instead of this release.
50
- const NXU_RANK = '11.2.0';
51
+ const NXU_RANK = '11.3.0';
51
52
  const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
52
53
  // App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
53
54
  const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
@@ -173,7 +174,7 @@
173
174
  'nxu_idle_timeout', 'nxu_sub_size', 'nxu_sub_opacity', 'nxu_sub_position', 'nxu_speaker_language',
174
175
  'nxu_subtitle_language', 'nxu_audio_mode', 'nxu_translation_provider', 'nxu_stt_local_first',
175
176
  'nxu_smart_speech_locale', 'nxu_fab_pos', 'nxu_asr_provider', 'nxu_key_openai', 'nxu_key_anthropic', 'nxu_key_groq', 'nxu_key_deepl',
176
- 'nxu_model_openai', 'nxu_model_anthropic', 'nxu_cinema_ambient', 'nxu_cinema_fit', 'nxu_cc_remaining', 'nxu_cinema_controls', 'nxu_nickname', 'nxu_color', 'nxu_quick_replies', 'nxu_chat_translate', 'nxu_sync_offset', 'nxu_cover_band', 'nxu_cover_marks', 'nxu_travel', 'nxu_auto_next', 'nxu_auto_cinema_sites', 'nxu_glossary', 'nxu_panel_size_chat-panel', 'nxu_panel_size_sub-log-panel', 'nxu_panel_size_debug-panel', 'nxu_panel_size_trans-modal', 'nxu_cinema_rotate', 'nxu_rotate_denied_' + HOST
177
+ 'nxu_model_openai', 'nxu_model_anthropic', 'nxu_cinema_ambient', 'nxu_cinema_fit', 'nxu_cc_remaining', 'nxu_cinema_controls', 'nxu_nickname', 'nxu_color', 'nxu_quick_replies', 'nxu_chat_translate', 'nxu_sync_offset', 'nxu_cover_band', 'nxu_cover_marks', 'nxu_travel', 'nxu_auto_next', 'nxu_auto_cinema_sites', 'nxu_ad_guard', 'nxu_glossary', 'nxu_panel_size_chat-panel', 'nxu_panel_size_sub-log-panel', 'nxu_panel_size_debug-panel', 'nxu_panel_size_trans-modal', 'nxu_cinema_rotate', 'nxu_rotate_denied_' + HOST
177
178
  ]);
178
179
 
179
180
  // ───────────────────────── Cross-origin HTTP (GM xhr first, fetch fallback)
@@ -485,9 +486,31 @@
485
486
  return w * h;
486
487
  }
487
488
 
489
+ // Vibration. Android: the Vibration API. iPhone/iPad have no Vibration API; Safari 18+
490
+ // gives a light tap when a switch control is toggled, which works inside a tap only.
491
+ let _hapticSwitch = null;
488
492
  function triggerHaptic(type = 'light') {
489
- if (!navigator.vibrate) return;
490
- try { navigator.vibrate(type === 'heavy' ? [100, 50, 100] : 15); } catch (_) { }
493
+ if (navigator.vibrate) {
494
+ try { navigator.vibrate(type === 'heavy' ? [100, 50, 100] : 15); } catch (_) { }
495
+ return;
496
+ }
497
+ if (!IS_IOS) return;
498
+ try {
499
+ if (!_hapticSwitch || !_hapticSwitch.isConnected) {
500
+ const label = document.createElement('label');
501
+ label.setAttribute('aria-hidden', 'true');
502
+ label.style.cssText = 'position:fixed;left:-9999px;top:0;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none;';
503
+ const input = document.createElement('input');
504
+ input.type = 'checkbox';
505
+ input.setAttribute('switch', '');
506
+ input.tabIndex = -1;
507
+ label.appendChild(input);
508
+ (document.body || document.documentElement).appendChild(label);
509
+ _hapticSwitch = label;
510
+ }
511
+ const pulses = type === 'heavy' ? 3 : 1;
512
+ for (let i = 0; i < pulses; i++) setTimeout(() => { try { _hapticSwitch.click(); } catch (_) { } }, i * 110);
513
+ } catch (_) { }
491
514
  }
492
515
 
493
516
  function generateUserColor(id) {
@@ -624,7 +647,7 @@
624
647
  travelBack: 'Back in the room', travelMoved: 'Moved to “{title}” · tap to go together', travelGoing: 'Going together…',
625
648
  chatTrOn: 'Auto-translate: on', chatTrOff: 'Auto-translate: off', chatTrShowOrig: 'Tap to see the original', chatTrShowTr: 'Tap to see the translation', chatTrFrom: 'Translated from {lang}',
626
649
  inkClosing: 'Closing soon — move or tap to keep drawing',
627
- modeSitePlayer: 'Site player in use', modeNexusPlayer: 'NexusSync player in use', modeSiteHint: 'Change subtitles or the server in the site’s player, then switch.', modeSiteHintAuto: 'Cinema started by itself. Pick subtitles or a server in the site’s player first if needed, then switch.', modeNexusHint: 'Everything is controlled by NexusSync. The site’s own settings are one tap away.', modeUseNexus: 'Use NexusSync player', modeUseSite: 'Use site player', autoCinemaStopSite: 'No auto-cinema on this site', autoCinemaOnSite: 'Auto-cinema on for {site}', autoCinemaOffSite: 'Auto-cinema off for {site}', autoCinemaBtnOn: 'Auto-cinema: on (this site)', autoCinemaBtnOff: 'Auto-cinema: off (this site)', ccPip: 'Picture-in-Picture (keep watching in a small window)', nextEpTitle: 'Up next', nextEpGo: 'Next episode', nextEpCancel: 'Stay on this episode', nextEpGoing: 'Next episode…', talkMenu: 'Chat', inkMenu: 'Quick sketch', quickEdit: 'Edit quick replies', quickEditHint: 'Separate with |', quickReset: 'Back to the default replies', save: 'Save',
650
+ modeSitePlayer: 'Site player in use', modeNexusPlayer: 'NexusSync player in use', modeSiteHint: 'Change subtitles or the server in the site’s player, then switch.', modeSiteHintAuto: 'Cinema started by itself. Pick subtitles or a server in the site’s player first if needed, then switch.', modeNexusHint: 'Everything is controlled by NexusSync. The site’s own settings are one tap away.', modeUseNexus: 'Use NexusSync player', modeUseSite: 'Use site player', autoCinemaStopSite: 'No auto-cinema on this site', autoCinemaOnSite: 'Auto-cinema on for {site}', autoCinemaOffSite: 'Auto-cinema off for {site}', autoCinemaBtnOn: 'Auto-cinema: on (this site)', autoCinemaBtnOff: 'Auto-cinema: off (this site)', adGuardOn: 'Ad guard: on', adGuardOff: 'Ad guard: off', adGuardHid: 'Hid an ad / link laid over the video', adGuardPopup: 'Stopped an ad pop-up', ccPip: 'Picture-in-Picture (keep watching in a small window)', nextEpTitle: 'Up next', nextEpGo: 'Next episode', nextEpCancel: 'Stay on this episode', nextEpGoing: 'Next episode…', talkMenu: 'Chat', inkMenu: 'Quick sketch', quickEdit: 'Edit quick replies', quickEditHint: 'Separate with |', quickReset: 'Back to the default replies', save: 'Save',
628
651
  talkTitle: 'Chat bubble', talkPlaceholder: 'Say something…', talkReplyTo: '↩ Reply to {name}', talkClose: 'Close', talkSend: 'Send', talkFull: 'Open the chat history (every message so far)', talkHistory: 'History',
629
652
  inkTitle: 'Quick sketch (fades away)', inkHint: 'Draw on the screen — it fades in a few seconds', inkDone: 'Done', inkBubble: 'is sketching on the screen — tap to draw back',
630
653
  you: 'You', roomBuffering: '⏳ {name} is loading… everyone waits', roomResume: '▶️ Everyone is ready — playing together', roomRate: '⏩ Speed {rate}x synced',
@@ -648,17 +671,28 @@
648
671
  subtitleLanguage: 'Translate subtitles to', audioSource: 'Audio source', audioAuto: 'Auto (video audio when possible + mic)', audioMic: 'Microphone only',
649
672
  audioMedia: 'Video / tab audio only', audioDual: 'Microphone + video audio',
650
673
  audioHelp: 'Auto listens to the page video directly when the browser allows it, otherwise through the microphone (turn the speaker volume up).',
674
+ heardSound: 'What to listen to', srcMedia: '🎬 Video sound (recommended)', srcMic: '🎤 Microphone',
675
+ srcMediaHelp: 'Listens to the video itself — no speakers needed. If the browser asks what to share, pick this tab and turn on “Share tab audio”.',
676
+ srcMicHelp: 'Listens through the microphone: play the video out loud through the speakers (not headphones).',
677
+ srcIosHelp: 'On iPhone and iPad, Safari can only listen through the microphone — play the video through the speaker.',
678
+ videoLanguage: 'Language spoken in the video', subtitleLanguageReq: 'Subtitle language (required)', chooseLanguage: '— Choose a language —',
679
+ subPickLanguage: 'Choose the subtitle language first.', subAskMic: '🎤 Tap “Allow” when the browser asks for the microphone.',
680
+ subAskTab: '🎬 Choose this tab and turn on “Share tab audio”, then press Share.',
681
+ subMicBlockedSite: 'This site does not allow the microphone — listening to the video sound instead.',
682
+ subMicBlockedNoMedia: 'This site does not allow the microphone, and the video sound cannot be captured here.',
683
+ subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
684
+ subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
651
685
  subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
652
686
  advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
653
687
  providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
654
688
  localFirst: 'Prefer on-device speech recognition', localFirstHelp: 'Uses the offline speech model when the browser has it installed.',
655
689
  hotkeyHelp: 'Shortcuts: Alt+Shift+T subtitles · Alt+Shift+C cinema · Alt+Shift+N menu · in cinema: Space, ←/→, ↑/↓, M, F',
656
- subStart: 'Start subtitles', subStop: 'Stop subtitles', subStarting: 'Starting…', subStatusIdle: 'Ready. Press Start, then allow microphone access if asked.',
690
+ subStart: 'Start subtitles', subStop: 'Stop subtitles', subStarting: 'Starting…', subStatusIdle: 'Ready. Choose the languages, then press Start.',
657
691
  subStatusStarting: 'Preparing audio input…', subListening: 'Listening', auto: 'Auto', inputMic: 'mic', inputMedia: 'video audio',
658
692
  engineLocal: 'on-device', engineOnline: 'online', translation: 'Translation', recognition: 'Recognition', speaker: 'Speaker', time: 'Time', confidence: 'Confidence',
659
693
  speakerMic: 'Mic', speakerMedia: 'Video', speakerMixed: 'Mixed',
660
694
  subOn: '🎙️ AI subtitles ON', subOff: '🔇 AI subtitles OFF', subUnsupported: 'This browser has no speech recognition. Use Chrome, Edge or Safari.',
661
- subNeedsHttps: 'Subtitles need a secure (https) page.', subMicDenied: '🎙️ Microphone access was blocked. Allow it in the site settings and try again.',
695
+ subNeedsHttps: 'Subtitles need a secure (https) page.', subMicDenied: '🎤 Microphone access is off. Click the 🔒 icon left of the address bar, set Microphone to “Allow”, then try again.',
662
696
  subMicUnavailable: '🎙️ No audio input available.', subNoMic: '🎙️ No microphone found.', subServiceBlocked: 'The speech service is not available in this browser.',
663
697
  subNetworkFailed: 'Speech service unreachable. Check the connection and start again.', subLangUnsupported: 'This language is not supported for recognition.',
664
698
  subStalled: 'Speech recognition keeps failing. Please start again.', subWebAudioUnavailable: 'Video audio unavailable here — using the microphone.',
@@ -707,7 +741,7 @@
707
741
  travelBack: '방에 다시 연결했어요', travelMoved: '「{title}」(으)로 이동했어요 · 눌러서 같이 가기', travelGoing: '같이 이동하는 중…',
708
742
  chatTrOn: '자동 번역 켜짐', chatTrOff: '자동 번역 꺼짐', chatTrShowOrig: '눌러서 원문 보기', chatTrShowTr: '눌러서 번역 보기', chatTrFrom: '{lang}에서 번역됨',
709
743
  inkClosing: '곧 닫혀요 — 계속 그리려면 움직이거나 눌러 주세요',
710
- modeSitePlayer: '사이트 플레이어 사용 중', modeNexusPlayer: 'NexusSync 플레이어 사용 중', modeSiteHint: '자막이나 서버는 사이트 플레이어에서 바꾼 뒤 전환하세요.', modeSiteHintAuto: '시네마 모드가 자동으로 켜졌어요. 필요하면 사이트 플레이어에서 자막·서버를 먼저 고른 뒤 전환하세요.', modeNexusHint: 'NexusSync가 모든 조작을 맡아요. 사이트 설정은 한 번 탭으로 돌아갈 수 있어요.', modeUseNexus: 'NexusSync 플레이어로', modeUseSite: '사이트 플레이어로', autoCinemaStopSite: '이 사이트는 자동 시네마 끄기', autoCinemaOnSite: '{site}에서 자동 시네마 켜짐', autoCinemaOffSite: '{site}에서 자동 시네마 꺼짐', autoCinemaBtnOn: '자동 시네마: 켬 (이 사이트)', autoCinemaBtnOff: '자동 시네마: 끔 (이 사이트)', ccPip: 'PiP (작은 창으로 계속 보기)', nextEpTitle: '다음 화', nextEpGo: '다음 화 보기', nextEpCancel: '이번 화에 머물기', nextEpGoing: '다음 화로 이동하는 중…', talkMenu: '말풍선 채팅', inkMenu: '잠깐 그리기', quickEdit: '빠른 답장 편집', quickEditHint: '| 로 구분', quickReset: '기본 답장으로', save: '저장',
744
+ modeSitePlayer: '사이트 플레이어 사용 중', modeNexusPlayer: 'NexusSync 플레이어 사용 중', modeSiteHint: '자막이나 서버는 사이트 플레이어에서 바꾼 뒤 전환하세요.', modeSiteHintAuto: '시네마 모드가 자동으로 켜졌어요. 필요하면 사이트 플레이어에서 자막·서버를 먼저 고른 뒤 전환하세요.', modeNexusHint: 'NexusSync가 모든 조작을 맡아요. 사이트 설정은 한 번 탭으로 돌아갈 수 있어요.', modeUseNexus: 'NexusSync 플레이어로', modeUseSite: '사이트 플레이어로', autoCinemaStopSite: '이 사이트는 자동 시네마 끄기', autoCinemaOnSite: '{site}에서 자동 시네마 켜짐', autoCinemaOffSite: '{site}에서 자동 시네마 꺼짐', autoCinemaBtnOn: '자동 시네마: 켬 (이 사이트)', autoCinemaBtnOff: '자동 시네마: 끔 (이 사이트)', adGuardOn: '광고 가리기: 켬', adGuardOff: '광고 가리기: 끔', adGuardHid: '영상 위에 덮인 광고·링크를 숨겼어요', adGuardPopup: '광고 팝업을 막았어요', ccPip: 'PiP (작은 창으로 계속 보기)', nextEpTitle: '다음 화', nextEpGo: '다음 화 보기', nextEpCancel: '이번 화에 머물기', nextEpGoing: '다음 화로 이동하는 중…', talkMenu: '말풍선 채팅', inkMenu: '잠깐 그리기', quickEdit: '빠른 답장 편집', quickEditHint: '| 로 구분', quickReset: '기본 답장으로', save: '저장',
711
745
  talkTitle: '말풍선 채팅', talkPlaceholder: '메시지 보내기…', talkReplyTo: '↩ {name} 님에게 답장', talkClose: '닫기', talkSend: '보내기', talkFull: '지금까지의 대화 기록 전체 보기', talkHistory: '대화 기록',
712
746
  inkTitle: '잠깐 그리기 (몇 초 뒤 사라짐)', inkHint: '화면에 그려 보세요 — 몇 초 뒤 사라져요', inkDone: '완료', inkBubble: '님이 화면에 그리고 있어요 — 탭해서 같이 그리기',
713
747
  you: '나', roomBuffering: '⏳ {name} 기기 로딩 중… 모두 잠시 대기', roomResume: '▶️ 모두 준비됨 — 함께 재생합니다', roomRate: '⏩ {rate}배속 동기화',
@@ -731,17 +765,28 @@
731
765
  subtitleLanguage: '자막 번역 언어', audioSource: '오디오 입력', audioAuto: '자동 (가능하면 영상 소리 + 마이크)', audioMic: '마이크만',
732
766
  audioMedia: '영상/탭 소리만', audioDual: '마이크 + 영상 소리',
733
767
  audioHelp: '자동은 브라우저가 허용하면 페이지 영상 소리를 직접 듣고, 아니면 마이크로 듣습니다 (스피커 볼륨을 높여 주세요).',
768
+ heardSound: '들을 소리', srcMedia: '🎬 영상 소리 (권장)', srcMic: '🎤 마이크',
769
+ srcMediaHelp: '영상 소리를 직접 들어요. 브라우저가 공유할 화면을 물으면 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
770
+ srcMicHelp: '마이크로 들어요. 영상 소리를 이어폰이 아닌 스피커로 크게 틀어 주세요.',
771
+ srcIosHelp: '아이폰·아이패드의 Safari는 마이크로만 들을 수 있어요. 영상을 스피커로 재생해 주세요.',
772
+ videoLanguage: '영상 속 언어', subtitleLanguageReq: '자막 언어 (필수)', chooseLanguage: '— 언어를 선택하세요 —',
773
+ subPickLanguage: '먼저 자막 언어를 선택해 주세요.', subAskMic: '🎤 브라우저가 마이크 권한을 물으면 “허용”을 눌러 주세요.',
774
+ subAskTab: '🎬 이 탭을 고르고 “탭 오디오 공유”를 켠 뒤 공유를 눌러 주세요.',
775
+ subMicBlockedSite: '이 사이트는 마이크 사용을 막아 두었어요. 영상 소리로 들을게요.',
776
+ subMicBlockedNoMedia: '이 사이트는 마이크 사용을 막아 두었고, 영상 소리도 받을 수 없어요.',
777
+ subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
778
+ subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
734
779
  subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
735
780
  advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
736
781
  providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
737
782
  localFirst: '기기 내 음성 인식 우선', localFirstHelp: '브라우저에 오프라인 음성 모델이 설치되어 있으면 사용합니다.',
738
783
  hotkeyHelp: '단축키: Alt+Shift+T 자막 · Alt+Shift+C 시네마 · Alt+Shift+N 메뉴 · 시네마 중: Space, ←/→, ↑/↓, M, F',
739
- subStart: '자막 시작', subStop: '자막 중지', subStarting: '시작하는 중…', subStatusIdle: '준비됨. 시작을 누르고, 요청되면 마이크 권한을 허용하세요.',
784
+ subStart: '자막 시작', subStop: '자막 중지', subStarting: '시작하는 중…', subStatusIdle: '준비됨. 언어를 고른 뒤 시작을 누르세요.',
740
785
  subStatusStarting: '오디오 입력 준비 중…', subListening: '듣는 중', auto: '자동', inputMic: '마이크', inputMedia: '영상 소리',
741
786
  engineLocal: '기기 내', engineOnline: '온라인', translation: '번역', recognition: '인식', speaker: '화자', time: '시간', confidence: '신뢰도',
742
787
  speakerMic: '마이크', speakerMedia: '영상', speakerMixed: '혼합',
743
788
  subOn: '🎙️ AI 자막 켜짐', subOff: '🔇 AI 자막 꺼짐', subUnsupported: '이 브라우저는 음성 인식을 지원하지 않습니다. Chrome, Edge, Safari를 사용하세요.',
744
- subNeedsHttps: '자막은 보안(https) 페이지에서만 동작합니다.', subMicDenied: '🎙️ 마이크 권한이 차단되었습니다. 사이트 설정에서 허용한 뒤 다시 시도하세요.',
789
+ subNeedsHttps: '자막은 보안(https) 페이지에서만 동작합니다.', subMicDenied: '🎤 마이크 권한이 꺼져 있어요. 주소창 왼쪽 🔒(사이트 정보)에서 마이크를 “허용”으로 바꾼 뒤 다시 눌러 주세요.',
745
790
  subMicUnavailable: '🎙️ 사용할 수 있는 오디오 입력이 없습니다.', subNoMic: '🎙️ 마이크를 찾을 수 없습니다.', subServiceBlocked: '이 브라우저에서는 음성 인식 서비스를 사용할 수 없습니다.',
746
791
  subNetworkFailed: '음성 인식 서버에 연결할 수 없습니다. 연결을 확인하고 다시 시작하세요.', subLangUnsupported: '이 언어는 음성 인식을 지원하지 않습니다.',
747
792
  subStalled: '음성 인식이 계속 실패합니다. 다시 시작해 주세요.', subWebAudioUnavailable: '이 페이지에서는 영상 소리를 직접 받을 수 없어 마이크를 사용합니다.',
@@ -2202,14 +2247,21 @@
2202
2247
  // ── settings & language helpers
2203
2248
  _settings() {
2204
2249
  return {
2205
- audioMode: STORE.get('nxu_audio_mode', 'auto'),
2250
+ audioMode: this._audioMode(),
2206
2251
  provider: STORE.get('nxu_translation_provider', 'auto'),
2207
2252
  localFirst: STORE.get('nxu_stt_local_first', true) !== false
2208
2253
  };
2209
2254
  },
2255
+ // Two sources only: the video's own sound (default) or the microphone. Older saved
2256
+ // values (auto / dual) mean "video sound". iPhone/iPad Safari can only use the mic.
2257
+ _audioMode() {
2258
+ if (this._isAppleMobile()) return 'mic';
2259
+ return STORE.get('nxu_audio_mode', 'media') === 'mic' ? 'mic' : 'media';
2260
+ },
2261
+ // The subtitle language is always chosen by the user (no guessing): empty until set.
2210
2262
  loadLanguageSettings() {
2211
- const out = baseLang(STORE.get('nxu_subtitle_language', '') || defaultOutputLanguage());
2212
- this.outLang = LANG_BY_CODE.has(out) ? out : defaultOutputLanguage();
2263
+ const out = baseLang(STORE.get('nxu_subtitle_language', '') || '');
2264
+ this.outLang = out && LANG_BY_CODE.has(out) ? out : '';
2213
2265
  const saved = STORE.get('nxu_speaker_language', '');
2214
2266
  this.inLang = this._localeFor(saved) || this._defaultSpeakerLocale();
2215
2267
  },
@@ -2354,11 +2406,66 @@
2354
2406
  if (!audio.length) throw new Error('no audio was shared');
2355
2407
  return new MediaStream(audio);
2356
2408
  },
2409
+ // Is the microphone switched off for this page by the site itself (Permissions-Policy)?
2410
+ // Then the browser refuses at once, without ever asking the user.
2411
+ _micBlockedByPolicy() {
2412
+ try {
2413
+ const pp = document.permissionsPolicy || document.featurePolicy;
2414
+ return !!(pp && typeof pp.allowsFeature === 'function' && !pp.allowsFeature('microphone'));
2415
+ } catch (_) { return false; }
2416
+ },
2417
+ async _micPermissionState() {
2418
+ try { return (await withTimeout(navigator.permissions.query({ name: 'microphone' }), 800)).state || 'unknown'; } catch (_) { return 'unknown'; }
2419
+ },
2420
+ // Does a captured stream carry any sound? Cross-origin or protected media gives a
2421
+ // track of pure digital silence. Only judged while the video is audibly playing.
2422
+ async _hasSignal(stream) {
2423
+ const v = STATE.video;
2424
+ if (!v || v.paused || v.muted || !(v.volume > 0) || typeof v.captureStream !== 'function') return true;
2425
+ const Ctx = window.AudioContext || window.webkitAudioContext;
2426
+ if (!Ctx) return true;
2427
+ let ctx = null;
2428
+ try {
2429
+ ctx = new Ctx();
2430
+ const src = ctx.createMediaStreamSource(stream);
2431
+ const an = ctx.createAnalyser();
2432
+ an.fftSize = 512;
2433
+ src.connect(an);
2434
+ if (ctx.state === 'suspended') { try { await ctx.resume(); } catch (_) { } }
2435
+ const buf = new Float32Array(an.fftSize);
2436
+ let peak = 0;
2437
+ for (let i = 0; i < 12 && peak < 0.0008; i++) {
2438
+ await new Promise(r => setTimeout(r, 120));
2439
+ an.getFloatTimeDomainData(buf);
2440
+ for (let j = 0; j < buf.length; j++) { const x = Math.abs(buf[j]); if (x > peak) peak = x; }
2441
+ }
2442
+ return peak >= 0.0008;
2443
+ } catch (_) { return true; } finally { try { ctx?.close(); } catch (_) { } }
2444
+ },
2445
+ // The video's own sound: the element itself when it gives real audio, otherwise (on a
2446
+ // computer) the tab's audio, which the browser lets the user share in one dialog.
2447
+ async _captureMediaAudio(token) {
2448
+ let web = this._captureElementAudio();
2449
+ if (web && !(await this._hasSignal(web))) {
2450
+ web.getTracks().forEach(tr => tr.stop());
2451
+ web = null;
2452
+ logDebug('AI Sub: the video element gives no sound here (protected or cross-origin media).', 'info');
2453
+ }
2454
+ if (web) { this._webFromElement = true; return web; }
2455
+ if (token !== this._startToken) return null;
2456
+ if (this._isAppleMobile() || this._isAndroid() || !navigator.mediaDevices?.getDisplayMedia) return null;
2457
+ showToast(t('subAskTab'));
2458
+ try { return await this._captureDisplayAudio(); } catch (err) {
2459
+ logDebug('AI Sub: tab audio not shared: ' + (err.message || err.name), 'warn');
2460
+ return null;
2461
+ }
2462
+ },
2357
2463
  async _startAudioCapture(token) {
2358
2464
  this._stopAudioCapture();
2359
- const mode = this._settings().audioMode;
2465
+ const mode = this._audioMode();
2360
2466
  this.audioMode = mode;
2361
2467
  this._webFromElement = false;
2468
+ this._micMixed = false;
2362
2469
  this._mediaPeak = 0;
2363
2470
  this._trackSince = 0;
2364
2471
  this._levels = { mic: 0, media: 0 };
@@ -2369,36 +2476,36 @@
2369
2476
  this.captureMode = 'ios-mic';
2370
2477
  return;
2371
2478
  }
2479
+ const stopAll = (...streams) => streams.forEach(st => st?.getTracks().forEach(tr => tr.stop()));
2480
+ const policyBlocked = this._micBlockedByPolicy();
2372
2481
  let web = null, mic = null;
2373
- if (mode === 'auto' || mode === 'media' || mode === 'dual') {
2374
- web = this._captureElementAudio();
2375
- if (web) this._webFromElement = true;
2376
- else if (mode !== 'auto') {
2377
- try { web = await this._captureDisplayAudio(); } catch (err) {
2378
- logDebug('AI Sub: tab audio unavailable: ' + (err.message || err.name), 'warn');
2379
- if (mode === 'media') showToast(t('subWebAudioUnavailable'));
2380
- }
2482
+ if (mode === 'media' || policyBlocked) {
2483
+ if (policyBlocked && mode === 'mic') showToast(t('subMicBlockedSite'));
2484
+ web = await this._captureMediaAudio(token);
2485
+ if (token !== this._startToken) { stopAll(web); throw new Error('cancelled'); }
2486
+ if (!web && policyBlocked) { const e = new Error('microphone blocked by the site'); e.name = 'PolicyBlocked'; throw e; }
2487
+ }
2488
+ // The microphone is asked for explicitly (so the permission prompt shows up right
2489
+ // away): always in mic mode, as the fallback when the video sound is unavailable,
2490
+ // and alongside video sound for browser recognition, which may still need it.
2491
+ if (!policyBlocked && (!web || this._useWebSpeech)) {
2492
+ if (!web && (await this._micPermissionState()) === 'prompt') showToast(t('subAskMic'));
2493
+ try {
2494
+ // Echo cancellation would erase the very speaker sound we want to hear.
2495
+ mic = await this._requestMic(!web);
2496
+ } catch (err) {
2497
+ if (!web) throw err;
2498
+ logDebug('AI Sub: microphone unavailable, using the video sound only.', 'info');
2381
2499
  }
2382
2500
  }
2383
- if (token !== this._startToken) { web?.getTracks().forEach(tr => tr.stop()); throw new Error('cancelled'); }
2384
- const trackRecognition = !!web && this._supportsTrackInput();
2385
- try {
2386
- mic = await this._requestMic(!trackRecognition);
2387
- } catch (err) {
2388
- if (!web) throw err;
2389
- logDebug('AI Sub: microphone unavailable, using media audio only.', 'warn');
2390
- }
2391
- if (token !== this._startToken) {
2392
- [web, mic].forEach(s => s?.getTracks().forEach(tr => tr.stop()));
2393
- throw new Error('cancelled');
2394
- }
2501
+ if (token !== this._startToken) { stopAll(web, mic); throw new Error('cancelled'); }
2502
+ if (mode === 'media' && !web && mic) showToast(t('subUsingMicFallback'));
2395
2503
  this.mediaStream = mic;
2396
2504
  this.webMediaStream = web;
2397
- const prefix = mode === 'auto' ? 'auto-' : '';
2398
- this.captureMode = web && mic && mode !== 'media' ? prefix + 'dual' : web ? prefix + 'media' : 'mic';
2505
+ this.captureMode = web ? 'media' : 'mic';
2399
2506
 
2400
2507
  const AudioCtx = window.AudioContext || window.webkitAudioContext;
2401
- const micForMix = mode === 'media' && web ? null : mic;
2508
+ const micForMix = web ? null : mic;
2402
2509
  if (!AudioCtx || (!micForMix && !web)) return;
2403
2510
  try {
2404
2511
  let ctx;
@@ -2432,7 +2539,8 @@
2432
2539
  connect(web, 'media');
2433
2540
  this.audioContext = ctx;
2434
2541
  this.audioNodes = nodes;
2435
- this.recognitionAudioStream = web ? dest.stream : null;
2542
+ // Recognition hears exactly this mix (video sound, or the echo-free microphone).
2543
+ this.recognitionAudioStream = dest.stream;
2436
2544
  this._levelTimer = setInterval(() => { if (!document.hidden) this._refreshLevels(); }, 400);
2437
2545
  } catch (err) {
2438
2546
  logDebug('AI Sub: audio analysis unavailable: ' + (err.message || err.name), 'info');
@@ -2629,6 +2737,9 @@
2629
2737
  if (!this.active) return;
2630
2738
  if (!document.hidden) this._checkAudio();
2631
2739
  if (!this.active) return;
2740
+ // The user stopped sharing the tab's audio from the browser's bar.
2741
+ const shared = this.webMediaStream && !this._webFromElement ? this.webMediaStream.getAudioTracks() : [];
2742
+ if (shared.length && shared.every(tr => tr.readyState === 'ended')) { this.stop(t('subTabShareEnded')); return; }
2632
2743
  if (!this._useWebSpeech) { updateAIBtnUX(); return; }
2633
2744
  const now = Date.now();
2634
2745
  if (!this._restartTimer && !this._waitOnline && now - this._lastEventAt > 25000) {
@@ -2640,11 +2751,14 @@
2640
2751
  this._scheduleRestart('watchdog', 100, true);
2641
2752
  } else if (this._recognitionInput === 'track' && !this._trackDisabled && this._trackSince && (
2642
2753
  // Captured video audio is silent (e.g. cross-origin media) while the video plays,
2643
- (now - this._trackSince > 6000 && this._mediaPeak < 0.003 && STATE.video && !STATE.video.paused && !STATE.video.muted && STATE.video.volume > 0) ||
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) ||
2644
2755
  // or sound is present but the engine never returns words from the track.
2645
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; }
2646
2759
  this._trackDisabled = true;
2647
- logDebug('AI Sub: captured video audio unusable, switching to microphone input.', 'warn');
2760
+ logDebug('AI Sub: captured audio unusable, switching to the recognizer’s own microphone.', 'warn');
2761
+ if (!this._micMixed) showToast(t('subUsingMicFallback'));
2648
2762
  this._preparePlaybackMic();
2649
2763
  this._destroyRecognizer();
2650
2764
  this._createRecognizer();
@@ -2652,6 +2766,27 @@
2652
2766
  }
2653
2767
  updateAIBtnUX();
2654
2768
  },
2769
+ _mixInMic() {
2770
+ const ctx = this.audioContext, nodes = this.audioNodes;
2771
+ if (!this.mediaStream || !ctx || !nodes?.mix) return false;
2772
+ try {
2773
+ const src = ctx.createMediaStreamSource(this.mediaStream);
2774
+ const an = ctx.createAnalyser();
2775
+ an.fftSize = 512;
2776
+ an.smoothingTimeConstant = 0.3;
2777
+ src.connect(an);
2778
+ src.connect(nodes.mix);
2779
+ nodes.list.push(src, an);
2780
+ nodes.analysers.mic = an;
2781
+ this._micMixed = true;
2782
+ this._preparePlaybackMic();
2783
+ this._trackSince = Date.now();
2784
+ this.captureMode = 'mic';
2785
+ showToast(t('subUsingMicFallback'));
2786
+ logDebug('AI Sub: the video sound is silent here, listening through the microphone.', 'warn');
2787
+ return true;
2788
+ } catch (_) { return false; }
2789
+ },
2655
2790
  _preparePlaybackMic() {
2656
2791
  const track = this.mediaStream?.getAudioTracks?.()[0];
2657
2792
  if (!track || typeof track.applyConstraints !== 'function') return;
@@ -3389,6 +3524,8 @@
3389
3524
  },
3390
3525
  async start({ silent = false } = {}) {
3391
3526
  if (this.state !== 'idle') return;
3527
+ this.loadLanguageSettings();
3528
+ if (!this.outLang) { this._askLanguage(); return; }
3392
3529
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
3393
3530
  this._cloud = AI.asrProvider() !== 'browser' && !!(window.AudioContext || window.webkitAudioContext);
3394
3531
  // With cloud recognition on iPhone/iPad, Safari's own recognizer stays off
@@ -3398,7 +3535,6 @@
3398
3535
  if (window.isSecureContext === false) { showToast(t('subNeedsHttps')); return; }
3399
3536
  const token = ++this._startToken;
3400
3537
  this.state = 'starting';
3401
- this.loadLanguageSettings();
3402
3538
  this._resetRuntime();
3403
3539
  this._abortCtrl = new AbortController();
3404
3540
  this._syncUI();
@@ -3412,7 +3548,7 @@
3412
3548
  this._syncUI();
3413
3549
  const denied = err?.name === 'NotAllowedError' || err?.name === 'SecurityError';
3414
3550
  logDebug('AI Sub: audio input failed: ' + (err?.message || err?.name), 'error');
3415
- showToast(t(denied ? 'subMicDenied' : 'subMicUnavailable'));
3551
+ showToast(t(err?.name === 'PolicyBlocked' ? 'subMicBlockedNoMedia' : err?.name === 'NotFoundError' ? 'subNoMic' : denied ? 'subMicDenied' : 'subMicUnavailable'));
3416
3552
  return;
3417
3553
  }
3418
3554
  if (token !== this._startToken) return;
@@ -3493,6 +3629,19 @@
3493
3629
  if (wasActive && message) showToast(message);
3494
3630
  if (wasActive) logDebug('AI Sub stopped.', 'info');
3495
3631
  },
3632
+ // No subtitle language yet: open the settings with the language picker highlighted.
3633
+ _askLanguage() {
3634
+ showToast(t('subPickLanguage'));
3635
+ const modal = shadow?.getElementById('trans-modal');
3636
+ if (modal && modal.style.display !== 'flex') openPanel(modal);
3637
+ const sel = shadow?.getElementById('stt-out');
3638
+ if (sel) {
3639
+ sel.classList.remove('need');
3640
+ void sel.offsetWidth;
3641
+ sel.classList.add('need');
3642
+ try { sel.focus({ preventScroll: true }); } catch (_) { }
3643
+ }
3644
+ },
3496
3645
  toggle() {
3497
3646
  if (this.state === 'idle') this.start();
3498
3647
  else this.stop(t('subOff'));
@@ -3509,7 +3658,7 @@
3509
3658
  updateAIBtnUX();
3510
3659
  },
3511
3660
  setOutputLanguage(value) {
3512
- this.outLang = LANG_BY_CODE.has(value) ? value : 'en';
3661
+ this.outLang = value && LANG_BY_CODE.has(value) ? value : '';
3513
3662
  this._recentQueued = [];
3514
3663
  if (this.active) this._warmBrowserTranslator(baseLang(this._recognitionLanguage()), this.outLang);
3515
3664
  updateAIBtnUX();
@@ -6308,10 +6457,26 @@
6308
6457
  const label = text => createEl('div', 'field-label', text);
6309
6458
  const help = text => createEl('div', 'trans-help', text);
6310
6459
  const speakerSelect = createSelect('stt-in', LANGS.map(l => ({ value: l.locale, label: l.label })));
6311
- const subtitleSelect = createSelect('stt-out', LANGS.map(l => ({ value: l.code, label: l.label })));
6312
- const audioSelect = createSelect('stt-audio-mode', [
6313
- { value: 'auto', label: t('audioAuto') }, { value: 'mic', label: t('audioMic') },
6314
- { value: 'media', label: t('audioMedia') }, { value: 'dual', label: t('audioDual') }]);
6460
+ const subtitleSelect = createSelect('stt-out', [{ value: '', label: t('chooseLanguage') }, ...LANGS.map(l => ({ value: l.code, label: l.label }))]);
6461
+ // What to listen to: two clear choices instead of a list of capture modes.
6462
+ const ios = TRANSLATOR._isAppleMobile();
6463
+ const sourceRow = createEl('div', 'seg', '', { id: 'stt-source', role: 'radiogroup' });
6464
+ const srcMedia = createEl('button', 'seg-btn', t('srcMedia'), { type: 'button', 'data-mode': 'media', role: 'radio' });
6465
+ const srcMic = createEl('button', 'seg-btn', t('srcMic'), { type: 'button', 'data-mode': 'mic', role: 'radio' });
6466
+ const sourceHelp = help('');
6467
+ sourceRow.append(srcMedia, srcMic);
6468
+ const paintSource = () => {
6469
+ const mode = TRANSLATOR._audioMode();
6470
+ [srcMedia, srcMic].forEach(b => { const on = b.dataset.mode === mode; b.classList.toggle('on', on); b.setAttribute('aria-checked', String(on)); });
6471
+ srcMedia.disabled = ios;
6472
+ sourceHelp.textContent = ios ? t('srcIosHelp') : mode === 'mic' ? t('srcMicHelp') : t('srcMediaHelp');
6473
+ };
6474
+ [srcMedia, srcMic].forEach(b => b.addEventListener('click', () => {
6475
+ if (b.disabled || TRANSLATOR._audioMode() === b.dataset.mode) return;
6476
+ STORE.set('nxu_audio_mode', b.dataset.mode);
6477
+ paintSource();
6478
+ TRANSLATOR.restart('audio source changed');
6479
+ }));
6315
6480
  const positionSelect = createSelect('stt-position', [{ value: 'video', label: t('posVideo') }, { value: 'screen', label: t('posScreen') }]);
6316
6481
  const asrSelect = createSelect('stt-asr-provider', [
6317
6482
  { value: 'browser', label: t('asrBrowser') }, { value: 'openai', label: t('asrOpenAI') },
@@ -6388,17 +6553,17 @@
6388
6553
  const advanced = createEl('div', 'ai-advanced-body');
6389
6554
  const offlineBtn = createEl('button', 'btn subtle', '⬇️ ' + t('offlineDownload'));
6390
6555
  offlineBtn.onclick = () => TRANSLATOR.downloadOfflineModels();
6391
- advanced.append(label(t('glossary')), glossaryInput, help(t('glossaryHelp')), label(t('aiKeys')), keyRows, help(t('aiKeysHelp')), modelRow('anthropic', 'claude-haiku-4-5'), modelRow('openai', 'gpt-4.1-mini'),
6556
+ advanced.append(label(t('translationEngine')), providerSelect, engineHint,
6557
+ label(t('asrEngine')), asrSelect,
6558
+ label(t('subPosition')), positionSelect,
6559
+ label(t('glossary')), glossaryInput, help(t('glossaryHelp')), label(t('aiKeys')), keyRows, help(t('aiKeysHelp')), modelRow('anthropic', 'claude-haiku-4-5'), modelRow('openai', 'gpt-4.1-mini'),
6392
6560
  help(t('modelHelp')), localRow, help(t('localFirstHelp')), offlineBtn, help(t('offlineHelp')));
6393
6561
  details.append(createEl('summary', '', t('advanced')), advanced);
6394
6562
 
6395
6563
  body.append(
6396
- label(t('speakerLanguage')), speakerSelect, help(t('speakerHelp')),
6397
- label(t('subtitleLanguage')), subtitleSelect,
6398
- label(t('audioSource')), audioSelect, help(t('audioHelp')),
6399
- label(t('asrEngine')), asrSelect,
6400
- label(t('translationEngine')), providerSelect, engineHint,
6401
- label(t('subPosition')), positionSelect,
6564
+ label(t('heardSound')), sourceRow, sourceHelp,
6565
+ label(t('videoLanguage')), speakerSelect,
6566
+ label(t('subtitleLanguageReq')), subtitleSelect,
6402
6567
  sizeRow, opacityRow,
6403
6568
  details,
6404
6569
  createEl('div', 'ai-status', t('subStatusIdle'), { id: 'nxu-ai-status' }),
@@ -6407,8 +6572,8 @@
6407
6572
  );
6408
6573
 
6409
6574
  speakerSelect.value = TRANSLATOR._recognitionLanguage();
6410
- subtitleSelect.value = TRANSLATOR.outLang;
6411
- audioSelect.value = STORE.get('nxu_audio_mode', 'auto');
6575
+ subtitleSelect.value = TRANSLATOR.outLang || '';
6576
+ paintSource();
6412
6577
  positionSelect.value = STORE.get('nxu_sub_position', 'video');
6413
6578
  providerSelect.value = STORE.get('nxu_translation_provider', 'auto');
6414
6579
  asrSelect.value = STORE.get('nxu_asr_provider', 'browser');
@@ -6418,8 +6583,12 @@
6418
6583
  opacitySlider.value = SUB_PREFS.opacity; opacityVal.textContent = SUB_PREFS.opacity + '%';
6419
6584
 
6420
6585
  speakerSelect.addEventListener('change', () => { STORE.set('nxu_speaker_language', speakerSelect.value); TRANSLATOR.setSpeakerLanguage(speakerSelect.value); });
6421
- subtitleSelect.addEventListener('change', () => { STORE.set('nxu_subtitle_language', subtitleSelect.value); TRANSLATOR.setOutputLanguage(subtitleSelect.value); });
6422
- audioSelect.addEventListener('change', () => { STORE.set('nxu_audio_mode', audioSelect.value); TRANSLATOR.restart('audio source changed'); });
6586
+ subtitleSelect.addEventListener('change', () => {
6587
+ if (!subtitleSelect.value) return;
6588
+ subtitleSelect.classList.remove('need');
6589
+ STORE.set('nxu_subtitle_language', subtitleSelect.value);
6590
+ TRANSLATOR.setOutputLanguage(subtitleSelect.value);
6591
+ });
6423
6592
  positionSelect.addEventListener('change', () => { STORE.set('nxu_sub_position', positionSelect.value); SUB_LAYOUT.schedule(); });
6424
6593
  providerSelect.addEventListener('change', () => { STORE.set('nxu_translation_provider', providerSelect.value); TRANSLATOR._cache.clear(); TRANSLATOR._llmHistory = []; refreshEngineHint(); });
6425
6594
  asrSelect.addEventListener('change', () => { STORE.set('nxu_asr_provider', asrSelect.value); refreshEngineHint(); TRANSLATOR.restart('recognition engine changed'); });
@@ -6574,6 +6743,12 @@
6574
6743
  .trans-check { width:18px; height:18px; accent-color:var(--accent); }
6575
6744
  .trans-help { font-size:11px; line-height:1.45; color:rgba(255,255,255,0.55); }
6576
6745
  .trans-help.center { text-align:center; margin-top:4px; }
6746
+ .seg { display:flex; gap:6px; }
6747
+ .seg-btn { flex:1; min-height:38px; padding:8px 6px; border-radius:10px; border:1px solid rgba(255,255,255,0.16); background:rgba(255,255,255,0.06); color:inherit; font:inherit; font-size:13px; font-weight:700; cursor:pointer; }
6748
+ .seg-btn.on { background:rgba(124,77,255,0.38); border-color:rgba(160,130,255,0.95); }
6749
+ .seg-btn:disabled { opacity:0.4; cursor:default; }
6750
+ .trans-select.need { outline:2px solid #ffca28; outline-offset:1px; animation:nxNeed 0.9s ease 3; }
6751
+ @keyframes nxNeed { 50% { outline-color:transparent; } }
6577
6752
  .range-row { display:flex; align-items:center; gap:8px; font-size:12px; margin-top:6px; }
6578
6753
  .range-row input { flex:1; accent-color:var(--accent); }
6579
6754
  .range-val { min-width:42px; text-align:right; color:rgba(255,255,255,0.7); }
@@ -6733,7 +6908,9 @@
6733
6908
  /* together */
6734
6909
  .react-sep { width:1px; align-self:stretch; background:rgba(255,255,255,0.18); margin:2px 2px; }
6735
6910
  .nexus-container.nx-shake { animation:nxShake 0.5s ease; }
6736
- @keyframes nxShake { 15% { transform:translateX(-5px); } 30% { transform:translateX(5px); } 45% { transform:translateX(-4px); } 60% { transform:translateX(3px); } 80% { transform:translateX(-1px); } }
6911
+ /* "translate", not "transform": the container is turned 90° with transform in iPhone
6912
+ landscape view, and animating transform briefly put it back upright. */
6913
+ @keyframes nxShake { 15% { translate:-6px 0; } 30% { translate:6px 0; } 45% { translate:-5px 0; } 60% { translate:4px 0; } 80% { translate:-2px 0; } 100% { translate:0 0; } }
6737
6914
  .nx-ping-catcher { position:absolute; inset:0; z-index:2100; pointer-events:auto; cursor:crosshair; background:rgba(0,0,0,0.12); }
6738
6915
  .nx-ping-hint { position:absolute; top:calc(16px + env(safe-area-inset-top, 0px)); left:50%; transform:translateX(-50%); background:rgba(0,0,0,0.75); color:#fff; padding:8px 16px; border-radius:999px; font-size:13px; font-weight:700; white-space:nowrap; }
6739
6916
  .nx-ping { position:absolute; z-index:2050; width:0; height:0; pointer-events:none; }
@@ -6956,6 +7133,9 @@
6956
7133
  }
6957
7134
  shadow = host.attachShadow({ mode: 'open' });
6958
7135
  UI_GUARD.install(host, shadow);
7136
+ // Taps on NexusSync's own controls stop here: many video sites open an ad tab
7137
+ // ("speed test", pop-unders) from a click listener on the whole page.
7138
+ ['click', 'dblclick', 'auxclick', 'contextmenu', 'mousedown', 'pointerdown', 'touchstart'].forEach(type => host.addEventListener(type, (e) => e.stopPropagation()));
6959
7139
  if (!SUPPORTS_TOP_LAYER) {
6960
7140
  // Without the top layer, paint order decides between equal z-indexes: stay last.
6961
7141
  new MutationObserver(() => {
@@ -7005,6 +7185,11 @@
7005
7185
  const btnCinema = mk('nxu-cinema', '🍿 ' + t('cinema'), t('cinemaTitle'));
7006
7186
  const btnAutoCinema = mk('nxu-auto-cinema', '');
7007
7187
  btnAutoCinema.classList.add('subtle');
7188
+ const btnAdGuard = mk('nxu-ad-guard', '');
7189
+ btnAdGuard.classList.add('subtle');
7190
+ const paintAdGuard = () => { const on = AD_GUARD.enabled(); btnAdGuard.textContent = '🛡️ ' + t(on ? 'adGuardOn' : 'adGuardOff'); btnAdGuard.classList.toggle('active', on); };
7191
+ paintAdGuard();
7192
+ btnAdGuard.onclick = () => { STORE.set('nxu_ad_guard', !AD_GUARD.enabled()); paintAdGuard(); showToast('🛡️ ' + t(AD_GUARD.enabled() ? 'adGuardOn' : 'adGuardOff')); };
7008
7193
  const btnPiP = mk('nxu-pip', '📺 PiP');
7009
7194
  const btnRate = mk('nxu-rate', '⏩ 1x', t('rateTitle'));
7010
7195
  // Talking happens in speech bubbles and quick ink now: the menu opens those directly
@@ -7118,7 +7303,7 @@
7118
7303
  toast.setAttribute('role', 'status');
7119
7304
 
7120
7305
  // Sketching and chat live in the reaction bar (🖍️ 💬); the menu does not repeat them.
7121
- dock.append(btnFindMedia, btnLink, btnInvite, btnSyncStatus, btnCinema, btnAutoCinema, btnPiP, btnRate, btnBookmark, btnTranslate, btnSubLog, btnDebug, btnHideSite);
7306
+ dock.append(btnFindMedia, btnLink, btnInvite, btnSyncStatus, btnCinema, btnAutoCinema, btnAdGuard, btnPiP, btnRate, btnBookmark, btnTranslate, btnSubLog, btnDebug, btnHideSite);
7122
7307
  uiWrapper.append(dock, reactPill, fab);
7123
7308
  nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, toast, debugPanel);
7124
7309
  shadow.appendChild(nexusContainer);
@@ -8205,6 +8390,97 @@
8205
8390
  }
8206
8391
  };
8207
8392
 
8393
+ // ───────────────────────── Ad guard
8394
+ // While a video is being watched, links and ad boxes that sites lay over the picture
8395
+ // ("speed test", "download", sponsor banners) are hidden, and new tabs a site tries to
8396
+ // open to another website right after a tap on the player are stopped.
8397
+ const AD_GUARD = {
8398
+ RX_AD: /(speed\s*test|speedtest|속도\s*(측정|테스트)|광고|advert|sponsor|click\s*here|download\s*now|install\s*now|casino|betting|vpn|지금\s*(설치|다운|확인)|무료\s*(다운|설치)|바로가기)/i,
8399
+ RX_CONTROL: /(control|vjs-|jw-|plyr|shaka|ytp-|caption|subtitle|cue|track|progress|seek|volume|menu|setting|spinner|loading|poster|time|title|nxu)/i,
8400
+ hidden: new WeakSet(),
8401
+ _count: 0,
8402
+ _toasted: false,
8403
+ _blockedPopups: 0,
8404
+ enabled() { return STORE.get('nxu_ad_guard', true) !== false; },
8405
+ _watching() { const v = STATE.video; return !!v && v.isConnected && !v.paused && !v.ended && v.readyState >= 2; },
8406
+ _otherOrigin(href) { try { const u = new URL(href, location.href); return /^https?:$/.test(u.protocol) && u.origin !== location.origin; } catch (_) { return false; } },
8407
+ _adLike(el) {
8408
+ if (el.tagName === 'IFRAME') {
8409
+ if (VIDEO_DETECTOR.frameReports.has(el)) return false; // the player itself
8410
+ return this._otherOrigin(el.src || '');
8411
+ }
8412
+ const link = el.matches('a[href]') ? el : el.querySelector?.('a[href]');
8413
+ const outLink = !!link && this._otherOrigin(link.href) && !/^(#|javascript:)/i.test(link.getAttribute('href') || '');
8414
+ const text = (el.textContent || '').trim().slice(0, 200);
8415
+ const clicky = outLink || el.matches('a, [onclick]') || getComputedStyle(el).cursor === 'pointer';
8416
+ if (outLink && (link.target === '_blank' || this.RX_AD.test(text) || el.querySelector('img, iframe'))) return true;
8417
+ return clicky && this.RX_AD.test(text);
8418
+ },
8419
+ scan() {
8420
+ if (!this.enabled() || !this._watching()) return;
8421
+ const v = STATE.video;
8422
+ const r = v.getBoundingClientRect();
8423
+ if (r.width < 240 || r.height < 135) return;
8424
+ const seen = new Set();
8425
+ for (const fx of [0.15, 0.5, 0.85]) for (const fy of [0.15, 0.5, 0.85]) {
8426
+ const x = r.left + r.width * fx, y = r.top + r.height * fy;
8427
+ if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) continue;
8428
+ let stack;
8429
+ try { stack = document.elementsFromPoint(x, y); } catch (_) { continue; }
8430
+ for (const el of stack) {
8431
+ if (el === v || el.contains(v)) break; // reached the picture
8432
+ if (seen.has(el) || this.hidden.has(el) || el.closest('#nxu-host') || el.id === 'nxu-host') continue;
8433
+ seen.add(el);
8434
+ // Climb to the whole overlay box (but never to something holding the video).
8435
+ let box = el;
8436
+ while (box.parentElement && !box.parentElement.contains(v) && box.parentElement !== document.body) box = box.parentElement;
8437
+ if (this.hidden.has(box)) continue;
8438
+ const sig = `${box.id} ${typeof box.className === 'string' ? box.className : ''}`;
8439
+ if (this.RX_CONTROL.test(sig)) continue;
8440
+ const br = box.getBoundingClientRect();
8441
+ if (br.width * br.height > r.width * r.height * 0.92 && !box.querySelector?.('a[href], iframe')) continue; // likely the player's own click layer
8442
+ if (!this._adLike(box) && !this._adLike(el)) continue;
8443
+ this.hide(box);
8444
+ }
8445
+ }
8446
+ },
8447
+ hide(el) {
8448
+ this.hidden.add(el);
8449
+ el.setAttribute('data-nxu-adguard', '');
8450
+ el.style.setProperty('display', 'none', 'important');
8451
+ this._count++;
8452
+ logDebug('Ad guard: hid an overlay on the video (' + (el.tagName || '') + ')', 'info');
8453
+ if (!this._toasted && IS_TOP) { this._toasted = true; showToast('🛡️ ' + t('adGuardHid')); }
8454
+ if (!IS_TOP) FRAME.postToParent({ type: 'NXU_ACTIVITY' });
8455
+ },
8456
+ // window.open from the page while watching: a tab to another website opened right after
8457
+ // a tap on the player is almost always an ad (pop-under). Same-site windows still open.
8458
+ installPopupGuard() {
8459
+ const W = typeof unsafeWindow !== 'undefined' && unsafeWindow ? unsafeWindow : null;
8460
+ if (!W || typeof W.open !== 'function' || W.__nxuPopupGuard) return;
8461
+ const orig = W.open;
8462
+ const self = this;
8463
+ try {
8464
+ W.__nxuPopupGuard = true;
8465
+ W.open = function (url, ...rest) {
8466
+ try {
8467
+ const busy = self.enabled() && (self._watching() || STATE.isCinema || STATE.handshakeVerified);
8468
+ const recentTap = Date.now() - ((STATE._lastPlayerGesture && STATE._lastPlayerGesture.at) || 0) < 2000;
8469
+ if (busy && recentTap && url && self._otherOrigin(String(url))) {
8470
+ self._blockedPopups++;
8471
+ logDebug('Ad guard: stopped a pop-up to ' + String(url).slice(0, 80), 'warn');
8472
+ if (IS_TOP) showToast('🛡️ ' + t('adGuardPopup'));
8473
+ return null;
8474
+ }
8475
+ } catch (_) { }
8476
+ return orig.apply(this, [url, ...rest]);
8477
+ };
8478
+ } catch (_) { }
8479
+ }
8480
+ };
8481
+ AD_GUARD.installPopupGuard();
8482
+ setInterval(() => { try { AD_GUARD.scan(); } catch (_) { } }, 1500);
8483
+
8208
8484
  // ───────────────────────── Automatic cinema
8209
8485
  // Opening a page that is all about one video (an episode, a movie — not a feed with many
8210
8486
  // posts) switches to cinema mode as soon as the video is ready. It keeps the site's own
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangsicj/nexussync",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
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",