@kangsicj/nexussync 1.6.6 → 1.6.8

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
@@ -32,11 +32,11 @@
32
32
  | Chat | Floating speech bubbles, quick replies, automatic translation of incoming messages, exportable history |
33
33
  | Drawing and reactions | Strokes anchored to the video frame on every screen; emoji bursts; 3-2-1 countdown |
34
34
  | Cover | Hides the picture on all screens for a few seconds; audio and subtitles continue; replays the cover on rewind |
35
- | AI subtitles | Transcribes video audio into translated live subtitles; glossary for names; bring-your-own API key |
35
+ | AI subtitles | Transcribes video audio into translated live subtitles; free offline Whisper on PC (downloaded on request), the browser's engine, or your own API key; glossary for names |
36
36
  | Subtitles | Video tracks, local files or OpenSubtitles; up to 3 tracks at once |
37
37
  | Timing sync | Aligns two different releases of the same film (offset by manual mark or automatic detection) |
38
- | Next episode | Room persists across episodes; *Up next* countdown |
39
- | Privacy | End-to-end encrypted rooms, PIN to join, rooms deleted after everyone leaves |
38
+ | Next episode | Room persists across episodes; *Up next* countdown; sleep timer (pause after 15/30/60 min or at the end of the episode) |
39
+ | Privacy | End-to-end encrypted rooms, PIN or invite link to join, rooms deleted after everyone leaves |
40
40
 
41
41
  ## Installation
42
42
 
@@ -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.6.6
11
+ // @version 1.6.8
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.6.6
11
+ // @version 1.6.8
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 *://*/*
@@ -46,12 +46,12 @@
46
46
 
47
47
  // The version of the code that is actually running (the manager's metadata can lag
48
48
  // behind when an old copy is still installed).
49
- const NXU_VERSION = '1.6.6';
49
+ const NXU_VERSION = '1.6.8';
50
50
  // Rank used by the one-instance guard below and to tell newer builds apart in a room.
51
51
  // It is independent of the public version (1.0.0 is the first public release, after
52
52
  // private builds that reached ranks up to 10.2.0), so every older copy still installed
53
53
  // steps aside instead of this release.
54
- const NXU_RANK = '11.6.6';
54
+ const NXU_RANK = '11.6.8';
55
55
  const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
56
56
  // App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
57
57
  const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
@@ -64,6 +64,76 @@
64
64
  return 0;
65
65
  };
66
66
 
67
+ // ── Offline Whisper helper. Speech recognition with the open-source Whisper model runs
68
+ // in a hidden frame on NexusSync's own package page on jsDelivr: many sites forbid the
69
+ // background worker it needs (their security policy), that page does not, and the page
70
+ // keeps the downloaded model for later visits. The copy of this script inside that frame
71
+ // does nothing else.
72
+ if (!IS_TOP && location.hostname === 'cdn.jsdelivr.net' && location.hash.startsWith('#nxu-whisper=')) {
73
+ const token = location.hash.slice('#nxu-whisper='.length);
74
+ const LIB = 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1/dist/transformers.min.js';
75
+ const WORKER_SRC = `
76
+ let T = null, asr = null, key = '';
77
+ const post = (m) => self.postMessage(m);
78
+ let chain = Promise.resolve();
79
+ self.onmessage = (e) => { const m = e.data; chain = chain.then(() => handle(m)).catch(() => { }); };
80
+ async function handle(m) {
81
+ try {
82
+ if (m.type === 'load') {
83
+ if (!T) {
84
+ T = await import(m.lib); T.env.allowLocalModels = false; T.env.useBrowserCache = true;
85
+ const onnx = T.env.backends.onnx;
86
+ try { onnx.wasm.numThreads = 1; } catch (_) { }
87
+ // The runtime build that is tested with this library (one file pair, same CDN).
88
+ const ver = (onnx.versions && onnx.versions.web) || m.ort;
89
+ try { onnx.wasm.wasmPaths = { mjs: 'https://cdn.jsdelivr.net/npm/onnxruntime-web@' + ver + '/dist/ort-wasm-simd-threaded.jsep.mjs', wasm: 'https://cdn.jsdelivr.net/npm/onnxruntime-web@' + ver + '/dist/ort-wasm-simd-threaded.jsep.wasm' }; } catch (_) { }
90
+ }
91
+ const want = m.repo + '|' + m.device;
92
+ if (asr && key === want) { post({ type: 'ready', id: m.id, device: m.device }); return; }
93
+ if (asr) { try { await asr.dispose?.(); } catch (_) { } asr = null; }
94
+ const progress = (p) => { if (p && (p.status === 'progress' || p.status === 'progress_total')) post({ type: 'progress', id: m.id, file: p.file || '', loaded: p.loaded || 0, total: p.total || 0, all: p.status === 'progress_total' }); };
95
+ asr = await T.pipeline('automatic-speech-recognition', m.repo, { device: m.device, dtype: m.dtype, progress_callback: progress });
96
+ key = want;
97
+ post({ type: 'ready', id: m.id, device: m.device });
98
+ } else if (m.type === 'run') {
99
+ if (!asr) throw new Error('model not loaded');
100
+ const out = await asr(m.audio, { language: m.lang || null, task: 'transcribe', chunk_length_s: 30 });
101
+ post({ type: 'text', id: m.id, text: String((out && out.text) || '').trim() });
102
+ }
103
+ } catch (err) { post({ type: 'error', id: m.id, message: String((err && err.message) || err) }); }
104
+ }`;
105
+ let worker = null, parentOrigin = '*';
106
+ const send = (m) => { try { window.parent.postMessage(Object.assign({ nxuWhisper: token }, m), parentOrigin); } catch (_) { } };
107
+ const getWorker = () => {
108
+ if (worker) return worker;
109
+ worker = new Worker(URL.createObjectURL(new Blob([WORKER_SRC], { type: 'text/javascript' })), { type: 'module' });
110
+ worker.onmessage = (e) => send(e.data);
111
+ worker.onerror = (e) => send({ type: 'error', message: 'worker: ' + (e.message || 'failed') });
112
+ return worker;
113
+ };
114
+ const cacheHas = async (urls) => {
115
+ try { const c = await caches.open('transformers-cache'); for (const u of urls) if (!(await c.match(u))) return false; return true; } catch (_) { return false; }
116
+ };
117
+ window.addEventListener('message', async (e) => {
118
+ const m = e.data;
119
+ if (!m || m.nxuWhisper !== token || e.source !== window.parent) return;
120
+ parentOrigin = e.origin || '*';
121
+ try {
122
+ if (m.cmd === 'status') send({ type: 'status', id: m.id, cached: await cacheHas(m.urls || []), gpu: !!navigator.gpu, f16: navigator.gpu ? await navigator.gpu.requestAdapter().then(a => !!a && a.features.has('shader-f16')).catch(() => false) : false });
123
+ else if (m.cmd === 'load') getWorker().postMessage({ type: 'load', id: m.id, lib: LIB, ort: '1.31.0-dev.20260914-8d85527a0', repo: m.repo, device: m.device, dtype: m.dtype });
124
+ else if (m.cmd === 'run') getWorker().postMessage({ type: 'run', id: m.id, audio: m.audio, lang: m.lang }, [m.audio.buffer]);
125
+ else if (m.cmd === 'remove') {
126
+ const c = await caches.open('transformers-cache');
127
+ for (const req of await c.keys()) if (req.url.includes('/' + m.repo + '/')) await c.delete(req);
128
+ if (worker) { worker.terminate(); worker = null; }
129
+ send({ type: 'removed', id: m.id });
130
+ }
131
+ } catch (err) { send({ type: 'error', id: m.id, message: String(err && err.message || err) }); }
132
+ });
133
+ send({ type: 'hello' });
134
+ return;
135
+ }
136
+
67
137
  // ── One instance per page, across userscript sandboxes (shared DOM marker).
68
138
  // The flag is per build, so an older build that ran first cannot stop this one (the
69
139
  // shared DOM marker below decides which build stays).
@@ -628,6 +698,7 @@
628
698
  const I18N = {
629
699
  en: {
630
700
  asrEngine: 'Speech recognition engine', asrBrowser: 'Browser built-in (free)', asrOpenAI: 'OpenAI gpt-4o-mini-transcribe (fast, accurate)', asrOpenAIHQ: 'OpenAI gpt-4o-transcribe (best accuracy)',
701
+ asrLocal: 'Whisper offline (this PC, free, no key)', whisperModel_base: 'Whisper base · fast · {mb} MB', whisperModel_small: 'Whisper small · more accurate, slower · {mb} MB', whisperModel_turbo: 'Whisper large-v3 turbo · best · {mb} MB · needs a graphics card (WebGPU)', whisperDownload: 'Download ({mb} MB)', whisperRemove: 'Remove', whisperChecking: 'Checking…', whisperReady: 'Ready (offline)', whisperDownloading: 'Downloading the model — only this once on this site, then it works offline.', whisperDone: 'Offline Whisper is ready', whisperFailed: 'The Whisper download failed — check the connection and try again', whisperHelp: 'Open-source speech recognition that runs on this PC: nothing is sent anywhere, no key needed. Downloaded once per site, then it works offline.', whisperReadyHelp: 'Recognition runs on this PC. Bigger models are more accurate but need a faster PC.', whisperNeedsGpu: 'Needs a graphics card', whisperGpuHelp: 'This model needs WebGPU with 16-bit support, which this browser or PC does not offer. Pick base or small.', whisperBlocked: 'Not available here', whisperBlockedHelp: 'The helper NexusSync needs could not start here (blocked by the site, or the userscript manager does not run in frames). Allow it to run in frames, or use another site.', whisperBlockedHere: '⚠️ Offline Whisper cannot start on this site — using the browser engine.',
631
702
  asrGroq: 'Groq Whisper large-v3 turbo (very fast)', providerClaude: 'Claude (context-aware, most natural)', providerGPT: 'GPT (context-aware)', providerDeepL: 'DeepL',
632
703
  engineHelp: 'AI engines (OpenAI, Claude, Groq, DeepL) use your own API key and give the best accuracy; without a key the free engines are used.',
633
704
  aiNeedKey: 'Enter the {names} API key under Advanced — until then the free engine is used.', aiKeys: 'API keys', aiTest: 'Test',
@@ -676,6 +747,7 @@
676
747
  hiddenOnSite: '🙈 ⚙️ button hidden on this site · turn it back on in Settings or with Alt+Shift+N', shownOnSite: '⚙️ Button shown on this site',
677
748
  roomChat: 'Room Chat', chatLog: 'Chat history', chatCleared: '🧹 Chat history cleared', nickname: 'Nickname (optional)', chatPlaceholder: 'Message…', newMessages: 'New', latest: 'Latest',
678
749
  subHistory: 'Subtitle History', export: 'Export', clear: 'Clear', logCleared: '🧹 Subtitle history cleared', logExported: '💾 Subtitle history exported',
750
+ inviteLink: 'Invite link', inviteLinkCopied: 'Invite link copied — send it to your friend', inviteShareText: 'Watch with me on NexusSync', invitedHint: 'You were invited — tap Join.', sleepTitle: 'Sleep timer', sleepNone: 'Off', sleepMin: '{n} min', sleepEnd: 'End of this episode', sleepSet: 'Pauses in {n} min', sleepEndSet: 'Pauses at the end of this episode', sleepOff: 'Sleep timer off', sleepLeft: '{n} min left', sleepSoon: 'Pausing in 10 seconds (sleep timer)', sleepDone: 'Paused by the sleep timer. Good night!',
679
751
  createRoom: 'Create a room', copyPin: 'Copy PIN', enterPin: 'Enter PIN', joinRoom: 'Join Room', viewerMode: 'Viewer mode (follow without controlling)',
680
752
  aiSubSettings: 'AI Subtitles', debugConsole: 'Debug Console', uiHide: 'Auto-hide', keepOpen: 'Keep open',
681
753
  bmLibrary: 'Bookmarks', bmAddHere: 'Bookmark this moment', bmSearch: 'Search bookmarks', bmEmpty: 'No bookmarks yet. Tap “Bookmark this moment” while watching.', bmLive: 'LIVE', bmOpening: '📌 Opening the bookmark…', bmJumped: '📌 Back to {time}', bmLiveOpened: '🔴 Playing the live stream', bmDelete: 'Delete', bmThisPage: 'this page', bmCopy: 'Copy link', bmCopied: '📋 Link copied',
@@ -714,7 +786,7 @@
714
786
  subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
715
787
  subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
716
788
  subHearVideo: '🎧 Listening to the video', subHearMic: '🎧 Listening through the microphone', subVideoSilent: '🔇 No sound reaches the subtitles from this video',
717
- subNoWords: '⚠️ The speech engine hears sound but returns no words here. Add a free Groq key in AI Sub → Advanced to use AI recognition instead.', subNoWordsEdge: '⚠️ Edge’s speech engine hears the video but returns no words. Use Chrome, or add a free Groq key in AI Sub → Advanced (works in Edge).', subNoWordsKey: '⚠️ The browser’s speech engine returns no words here — switching to AI recognition with your key.',
789
+ subNoWords: '⚠️ The speech engine hears sound but returns no words here. In AI Sub → Advanced, pick “Whisper offline” (free, runs on this PC) or add a free Groq key.', subNoWordsEdge: '⚠️ Edge’s speech engine hears the video but returns no words. In AI Sub → Advanced, pick “Whisper offline” (free, runs on this PC), use Chrome, or add a free Groq key.', subNoWordsKey: '⚠️ The browser’s speech engine returns no words here — switching to AI recognition with your key.',
718
790
  subDiagCopy: 'Copy a problem report', subDiagCopied: '🔬 Report copied — paste it in your message', subDiagInDebug: '🔬 Report written to the debug console (Settings → Advanced → Debug)',
719
791
  subNoTrackInput: '⚠️ This browser’s speech engine cannot listen to the video sound directly — it only hears the microphone (play the sound through speakers, not headphones), or add a free Groq key in AI Sub → Advanced.', subIssueNoTrack: 'The speech engine only hears the microphone here', subNoService: '⚠️ This browser has no working speech recognition service (it works in Chrome). Add a free Groq or an OpenAI key in AI Sub → Advanced to use AI recognition instead.', subNoServiceKey: '⚠️ This browser has no working speech recognition service — switching to AI recognition with your key.',
720
792
  subIssueNet: '⚠️ Speech service connection is unstable — retrying', subIssueNoResult: '⚠️ Sound arrives but no words are recognised', subSiteBlocksSpeech: 'This site does not allow the browser’s speech recognition. Add an OpenAI or Groq key (AI subtitles → Advanced) to use AI subtitles here.', subSiteBlocksSpeechKey: 'This site blocks the browser’s speech recognition — switching to cloud recognition with your key.', subTryMic: '🎤 Listen through the mic', subTryKey: '🔑 Use an AI recognition key', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
@@ -747,6 +819,7 @@
747
819
  },
748
820
  ko: {
749
821
  asrEngine: '음성 인식 엔진', asrBrowser: '브라우저 내장 (무료)', asrOpenAI: 'OpenAI gpt-4o-mini-transcribe (빠르고 정확)', asrOpenAIHQ: 'OpenAI gpt-4o-transcribe (최고 정확도)',
822
+ asrLocal: 'Whisper 오프라인 (이 PC, 무료, 키 없음)', whisperModel_base: 'Whisper base · 빠름 · {mb}MB', whisperModel_small: 'Whisper small · 더 정확, 느림 · {mb}MB', whisperModel_turbo: 'Whisper large-v3 turbo · 최고 · {mb}MB · 그래픽카드(WebGPU) 필요', whisperDownload: '다운로드 ({mb}MB)', whisperRemove: '삭제', whisperChecking: '확인 중…', whisperReady: '준비됨 (오프라인)', whisperDownloading: '모델을 받는 중이에요 — 이 사이트에서는 이번 한 번만 받고, 이후엔 오프라인으로 동작해요.', whisperDone: '오프라인 Whisper 준비 완료', whisperFailed: 'Whisper 다운로드에 실패했어요 — 연결을 확인하고 다시 시도해 주세요', whisperHelp: '이 PC에서 직접 돌아가는 오픈소스 음성 인식이에요. 어디에도 보내지 않고 키도 필요 없어요. 사이트마다 한 번 받으면 이후엔 오프라인으로 동작해요.', whisperReadyHelp: '음성 인식이 이 PC에서 돌아가요. 큰 모델일수록 정확하지만 더 빠른 PC가 필요해요.', whisperNeedsGpu: '그래픽카드 필요', whisperGpuHelp: '이 모델은 16비트를 지원하는 WebGPU가 필요한데, 이 브라우저나 PC에서는 쓸 수 없어요. base나 small을 골라 주세요.', whisperBlocked: '여기서는 쓸 수 없음', whisperBlockedHelp: 'NexusSync가 쓰는 도우미가 여기서 시작되지 못했어요 (사이트가 막았거나, 유저스크립트 관리자가 프레임 안에서 실행되지 않아요). 프레임 안 실행을 허용하거나 다른 사이트에서 써 주세요.', whisperBlockedHere: '⚠️ 이 사이트에서는 오프라인 Whisper를 시작할 수 없어 브라우저 엔진을 써요.',
750
823
  asrGroq: 'Groq Whisper large-v3 turbo (매우 빠름)', providerClaude: 'Claude (문맥 이해, 가장 자연스러움)', providerGPT: 'GPT (문맥 이해)', providerDeepL: 'DeepL',
751
824
  engineHelp: 'AI 엔진(OpenAI·Claude·Groq·DeepL)은 본인 API 키로 동작하며 정확도가 가장 높습니다. 키가 없으면 무료 엔진을 사용합니다.',
752
825
  aiNeedKey: '고급 설정에서 {names} API 키를 입력하세요 — 그전까지는 무료 엔진을 사용합니다.', aiKeys: 'API 키', aiTest: '확인',
@@ -795,6 +868,7 @@
795
868
  hiddenOnSite: '🙈 이 사이트에서 ⚙️ 버튼을 숨겼어요 · 설정이나 Alt+Shift+N으로 다시 켤 수 있어요', shownOnSite: '⚙️ 이 사이트에서 버튼 표시',
796
869
  roomChat: '방 채팅', chatLog: '채팅 기록', chatCleared: '🧹 채팅 기록을 지웠어요', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
797
870
  subHistory: '자막 기록', export: '내보내기', clear: '지우기', logCleared: '🧹 자막 기록을 지웠습니다', logExported: '💾 자막 기록을 저장했습니다',
871
+ inviteLink: '초대 링크', inviteLinkCopied: '초대 링크를 복사했어요 — 친구에게 보내 주세요', inviteShareText: 'NexusSync로 같이 봐요', invitedHint: '초대받았어요 — 참가를 누르세요.', sleepTitle: '취침 타이머', sleepNone: '끄기', sleepMin: '{n}분', sleepEnd: '이번 화 끝나면', sleepSet: '{n}분 뒤 일시정지해요', sleepEndSet: '이번 화가 끝나면 일시정지해요', sleepOff: '취침 타이머를 껐어요', sleepLeft: '{n}분 남음', sleepSoon: '10초 뒤 일시정지해요 (취침 타이머)', sleepDone: '취침 타이머로 일시정지했어요. 잘 자요!',
798
872
  createRoom: '방 만들기', copyPin: 'PIN 복사', enterPin: 'PIN 입력', joinRoom: '방 참여', viewerMode: '시청자 모드 (조작 없이 따라보기)',
799
873
  aiSubSettings: 'AI 자막', debugConsole: '디버그 콘솔', uiHide: '자동 숨김', keepOpen: '고정',
800
874
  bmLibrary: '북마크', bmAddHere: '지금 장면 북마크', bmSearch: '북마크 검색', bmEmpty: '아직 북마크가 없어요. 보는 중에 “지금 장면 북마크”를 눌러 보세요.', bmLive: '라이브', bmOpening: '📌 북마크를 여는 중…', bmJumped: '📌 {time}(으)로 돌아왔어요', bmLiveOpened: '🔴 라이브 방송을 바로 재생해요', bmDelete: '삭제', bmThisPage: '이 페이지', bmCopy: '링크 복사', bmCopied: '📋 링크를 복사했어요',
@@ -833,7 +907,7 @@
833
907
  subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
834
908
  subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
835
909
  subHearVideo: '🎧 영상 소리 듣는 중', subHearMic: '🎧 마이크로 듣는 중', subVideoSilent: '🔇 이 영상의 소리가 자막에 전달되지 않아요',
836
- subNoWords: '⚠️ 음성 인식이 소리는 듣지만 말을 알아듣지 못하고 있어요. AI 자막 → 고급에서 무료 Groq 키를 넣으면 AI 인식으로 쓸 수 있어요.', subNoWordsEdge: '⚠️ Edge의 음성 인식이 영상 소리를 받지만 말을 알아듣지 못하고 있어요. Chrome을 쓰거나, AI 자막 → 고급에서 무료 Groq 키를 넣어 주세요 (Edge에서도 동작해요).', subNoWordsKey: '⚠️ 브라우저 음성 인식이 말을 알아듣지 못해 입력한 키로 AI 인식을 시작해요.',
910
+ subNoWords: '⚠️ 음성 인식이 소리는 듣지만 말을 알아듣지 못하고 있어요. AI 자막 → 고급에서 “Whisper 오프라인”(무료, 이 PC에서 동작)을 고르거나 무료 Groq 키를 넣어 주세요.', subNoWordsEdge: '⚠️ Edge의 음성 인식이 영상 소리를 받지만 말을 알아듣지 못하고 있어요. AI 자막 → 고급에서 “Whisper 오프라인”(무료, 이 PC에서 동작)을 고르거나, Chrome을 쓰거나, 무료 Groq 키를 넣어 주세요.', subNoWordsKey: '⚠️ 브라우저 음성 인식이 말을 알아듣지 못해 입력한 키로 AI 인식을 시작해요.',
837
911
  subDiagCopy: '문제 진단 보고서 복사', subDiagCopied: '🔬 진단 보고서를 복사했어요 — 메시지에 붙여 넣어 주세요', subDiagInDebug: '🔬 진단 보고서를 디버그 콘솔에 남겼어요 (설정 → 고급 → 디버그)',
838
912
  subNoTrackInput: '⚠️ 이 브라우저의 음성 인식은 영상 소리를 직접 듣지 못하고 마이크로만 들어요. 이어폰 대신 스피커로 소리를 내거나, AI 자막 → 고급에서 무료 Groq 키를 넣어 주세요.', subIssueNoTrack: '이 브라우저는 마이크로만 들을 수 있어요', subNoService: '⚠️ 이 브라우저에는 동작하는 음성 인식 서비스가 없어요 (Chrome에서는 동작해요). AI 자막 → 고급에서 무료 Groq 키나 OpenAI 키를 넣으면 AI 인식으로 쓸 수 있어요.', subNoServiceKey: '⚠️ 이 브라우저에는 동작하는 음성 인식 서비스가 없어 입력한 키로 AI 인식을 시작해요.',
839
913
  subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subSiteBlocksSpeech: '이 사이트는 브라우저 음성 인식을 막아 두었어요. AI 자막 → 고급에서 OpenAI 또는 Groq 키를 넣으면 여기서도 쓸 수 있어요.', subSiteBlocksSpeechKey: '이 사이트는 브라우저 음성 인식을 막아 두어서, 넣어 둔 키로 클라우드 인식으로 바꿀게요.', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
@@ -1361,8 +1435,11 @@
1361
1435
  else (doc.body || doc.documentElement).appendChild(layer);
1362
1436
  root.classList.add('nxu-ambient-on');
1363
1437
  this._matchLayerZ(layer, root);
1364
- const gap = lite ? 180 : 60; // ms between samples (≈5.5 / 16 per second)
1365
- const blend = lite ? 0.4 : 0.2; // share of the new frame: the glow eases between scenes
1438
+ // Reading a video frame is the costly part (it was almost all of cinema's CPU time at
1439
+ // 16 a second). Six a second with a stronger blend looks the same: the glow eases
1440
+ // between scenes anyway, and a cut still shows within a fraction of a second.
1441
+ const gap = lite ? 220 : 160; // ms between samples (≈4.5 / 6 per second)
1442
+ const blend = lite ? 0.45 : 0.35; // share of the new frame
1366
1443
  let last = 0, drawn = false, visible = true;
1367
1444
  const draw = (hard) => {
1368
1445
  if (!visible || doc.hidden || video.readyState < 2 || !video.videoWidth) return;
@@ -3064,7 +3141,10 @@
3064
3141
  // Plenty of sound but not a single word back: try the other ways of feeding the
3065
3142
  // engine on its own first, then say so, with a one-tap way out.
3066
3143
  if (this._useWebSpeech && !this._cloud && this._rescueNoWords()) { updateAIBtnUX(); return; }
3067
- if (this._useWebSpeech && !this._issue && (this._soundMs > 15000 || (this._diag.empty || 0) >= 10) && (this._lastResultAt || 0) < (this._startedAt || 0) && (this._cloud || this._rescueStage >= 3)) {
3144
+ const lastStepTried = this._rescueStage >= 3 && Date.now() - (this._stageAt || 0) >= 10000
3145
+ && ((this._stageSoundMs || 0) >= 10000 || (this._diag.empty || 0) - (this._stageEmpty || 0) >= 6);
3146
+ if (this._useWebSpeech && !this._issue && (this._soundMs > 15000 || (this._diag.empty || 0) >= 10) && (this._lastResultAt || 0) < (this._startedAt || 0) && (this._cloud || lastStepTried)) {
3147
+ if (this._feedFromMemory) STORE.set(this._feedKey(), ''); // it no longer works: start fresh next time
3068
3148
  this._issue = 'noresult';
3069
3149
  if (!this._cloud && !this._toldNoWords) {
3070
3150
  this._toldNoWords = true;
@@ -3080,6 +3160,33 @@
3080
3160
  this._updateListenChip();
3081
3161
  updateAIBtnUX();
3082
3162
  },
3163
+ // Which way of feeding the speech engine gave words in this browser last time. Some
3164
+ // engines (Edge) answer a captured track with empty results for minutes; once a rescue
3165
+ // step has worked, the next start begins there instead of waiting through the others.
3166
+ _feedKey() {
3167
+ const ua = navigator.userAgent || '';
3168
+ return 'nxu_ai_feed_' + (/\bEdg\//.test(ua) ? 'edge' : /\bOPR\//.test(ua) ? 'opera' : /\bWhale\//.test(ua) ? 'whale' : /SamsungBrowser/.test(ua) ? 'samsung' : /Firefox\//.test(ua) ? 'firefox' : 'chrome');
3169
+ },
3170
+ _applyFeedMemory() {
3171
+ this._feedSaved = false;
3172
+ this._feedFromMemory = '';
3173
+ if (this._cloud || this._isAppleMobile()) return;
3174
+ const feed = STORE.get(this._feedKey(), '');
3175
+ if (feed === 'mix') { this._useMixTrack = true; this._rescueStage = 2; }
3176
+ else if (feed === 'mic') { this._trackDisabled = true; this._rescueStage = 3; }
3177
+ else return;
3178
+ this._stageAt = Date.now(); this._stageSoundMs = 0; this._stageEmpty = 0;
3179
+ this._feedFromMemory = feed;
3180
+ logDebug('AI Sub: starting with ' + (feed === 'mix' ? 'the Web Audio copy of the sound' : 'the engine’s own microphone') + ' (it gave words last time in this browser).', 'info');
3181
+ },
3182
+ _rememberFeed() {
3183
+ if (this._feedSaved || this._cloud) return;
3184
+ this._feedSaved = true;
3185
+ const feed = this._trackDisabled ? 'mic' : this._useMixTrack ? 'mix' : '';
3186
+ if ((STORE.get(this._feedKey(), '') || '') === feed) return;
3187
+ STORE.set(this._feedKey(), feed);
3188
+ if (feed) logDebug('AI Sub: words came with ' + (feed === 'mix' ? 'the Web Audio copy' : 'the own microphone') + '; next time this browser starts that way.', 'success');
3189
+ },
3083
3190
  // Sound keeps arriving but the speech engine returns no words (some Chrome builds take
3084
3191
  // a captured track and then never answer, or the on-device model hears nothing).
3085
3192
  // Each step is tried for about ten seconds of sound: online recognition instead of
@@ -3249,6 +3356,7 @@
3249
3356
  if (!anyWords) { this._diag.empty = (this._diag.empty || 0) + 1; return; }
3250
3357
  this._diag.words = (this._diag.words || 0) + 1;
3251
3358
  this._lastResultAt = Date.now();
3359
+ this._rememberFeed();
3252
3360
  this._networkErrors = 0;
3253
3361
  this._networkRetryMs = 0;
3254
3362
  this._audioCaptureErrors = 0;
@@ -4028,6 +4136,7 @@
4028
4136
  const token = ++this._startToken;
4029
4137
  this.state = 'starting';
4030
4138
  this._resetRuntime();
4139
+ this._applyFeedMemory();
4031
4140
  this._abortCtrl = new AbortController();
4032
4141
  this._syncUI();
4033
4142
  try {
@@ -4094,7 +4203,7 @@
4094
4203
  'video: ' + (v ? (v.paused ? 'paused' : 'playing') + (v.muted ? ', muted' : '') + ', volume ' + Math.round((v.volume || 0) * 100) + '%' : (STATE.cinemaIframe || STATE.frameMedia ? 'in a frame' : 'none')) + ' · sound from: ' + (this._sharedTab && this.webMediaStream === this._sharedTab ? 'shared tab' : this._webFromElement ? 'video element' : this.captureMode) + ' · video sound peak: ' + (this._mediaPeak || 0).toFixed(4),
4095
4204
  'levels: video ' + Math.round((this._levels?.media || 0) * 400) + ' · mic ' + Math.round((this._levels?.mic || 0) * 400),
4096
4205
  'engine events: sound ' + this._diag.sound + ' · results ' + this._diag.results + ' (with words ' + (this._diag.words || 0) + ', empty ' + (this._diag.empty || 0) + ')' + (this._diag.lastText ? ' · last heard "' + this._diag.lastText + '"' : '') + ' · last error ' + (this._diag.err || '-') + ' · network errors ' + (this._networkErrors || 0),
4097
- 'issue: ' + (this._issue || '-')
4206
+ 'issue: ' + (this._issue || '-') + ' · started with: ' + (this._feedFromMemory || 'video track') + ' · remembered for this browser: ' + (STORE.get(this._feedKey(), '') || '-') + ' · running ' + Math.round((Date.now() - (this._startedAt || Date.now())) / 1000) + ' s'
4098
4207
  ];
4099
4208
  return lines.join('\n');
4100
4209
  },
@@ -4110,7 +4219,7 @@
4110
4219
  this._cloud = false;
4111
4220
  CLOUD_ASR.stop();
4112
4221
  const bad = err?.status === 401 || err?.status === 403;
4113
- showToast(t(bad ? 'aiKeyInvalid' : 'cloudAsrFallback'));
4222
+ showToast(t(err?.code === 'helper' ? 'whisperBlockedHere' : bad ? 'aiKeyInvalid' : 'cloudAsrFallback'));
4114
4223
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
4115
4224
  if (SR && this.active && !this.recognizer) {
4116
4225
  this._useWebSpeech = true;
@@ -4652,6 +4761,7 @@
4652
4761
  key(name) { return String(STORE.get('nxu_key_' + name, '') || '').trim(); },
4653
4762
  asrProvider() {
4654
4763
  const p = STORE.get('nxu_asr_provider', 'browser');
4764
+ if (p === 'local' && LOCAL_WHISPER.available() && STORE.get('nxu_whisper_ready_' + LOCAL_WHISPER.model(), false)) return p;
4655
4765
  if ((p === 'openai' || p === 'openai-hq') && this.key('openai')) return p;
4656
4766
  if (p === 'groq' && this.key('groq')) return p;
4657
4767
  return 'browser';
@@ -4664,6 +4774,7 @@
4664
4774
  return ['auto', 'browser', 'device', 'google', 'openai', 'anthropic', 'deepl'].includes(p) ? p : 'auto';
4665
4775
  },
4666
4776
  asrModel(p = this.asrProvider()) {
4777
+ if (p === 'local') return 'whisper-' + LOCAL_WHISPER.model() + ' (offline)';
4667
4778
  if (p === 'groq') return 'whisper-large-v3-turbo';
4668
4779
  if (p === 'openai-hq') return 'gpt-4o-transcribe';
4669
4780
  return 'gpt-4o-mini-transcribe';
@@ -4844,6 +4955,93 @@
4844
4955
  // Raw audio is resampled to 16 kHz mono; an adaptive energy detector cuts it at natural
4845
4956
  // pauses (with 300 ms pre-roll so first syllables are kept) and each utterance is sent
4846
4957
  // as a small WAV clip. Results are released strictly in speaking order.
4958
+ // Offline speech recognition with the open-source Whisper model (transformers.js, run by
4959
+ // the hidden helper frame above). PC only, downloaded once when the user asks for it.
4960
+ const LOCAL_WHISPER = {
4961
+ HELPER: 'https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@1.6.4/package.json',
4962
+ MODELS: {
4963
+ base: { repo: 'onnx-community/whisper-base', mb: 73, device: 'wasm', dtype: { encoder_model: 'q8', decoder_model_merged: 'q8' } },
4964
+ small: { repo: 'onnx-community/whisper-small', mb: 237, device: 'wasm', dtype: { encoder_model: 'q8', decoder_model_merged: 'q8' } },
4965
+ turbo: { repo: 'onnx-community/whisper-large-v3-turbo', mb: 536, device: 'webgpu', gpu: true, dtype: { encoder_model: 'q4f16', decoder_model_merged: 'q4f16' } }
4966
+ },
4967
+ _frame: null, _token: '', _ready: null, _n: 0, _wait: new Map(), _loaded: '', _gpu: null, _queue: 0,
4968
+ available() { return !IS_IOS && !/Android/i.test(navigator.userAgent) && typeof Worker === 'function'; },
4969
+ model() { const m = STORE.get('nxu_whisper_model', 'base'); return this.MODELS[m] ? m : 'base'; },
4970
+ files(id) {
4971
+ const M = this.MODELS[id], base = `https://huggingface.co/${M.repo}/resolve/main/`;
4972
+ const sfx = (d) => (d === 'q8' ? '_quantized' : d === 'fp32' ? '' : '_' + d);
4973
+ return ['config.json', 'tokenizer.json', `onnx/encoder_model${sfx(M.dtype.encoder_model)}.onnx`, `onnx/decoder_model_merged${sfx(M.dtype.decoder_model_merged)}.onnx`].map(f => base + f);
4974
+ },
4975
+ _connect() {
4976
+ if (this._ready) return this._ready;
4977
+ this._ready = new Promise((resolve, reject) => {
4978
+ this._token = Math.random().toString(36).slice(2) + Date.now().toString(36);
4979
+ const f = document.createElement('iframe');
4980
+ f.src = this.HELPER + '#nxu-whisper=' + this._token;
4981
+ f.setAttribute('allow', 'webgpu');
4982
+ f.setAttribute('aria-hidden', 'true');
4983
+ f.tabIndex = -1;
4984
+ f.style.cssText = 'position:fixed;width:1px;height:1px;left:-10px;top:-10px;border:0;opacity:0;pointer-events:none;';
4985
+ const timer = setTimeout(() => { this._ready = null; f.remove(); reject(Object.assign(new Error('helper frame did not answer'), { code: 'helper' })); }, 12000);
4986
+ const onMsg = (e) => {
4987
+ const m = e.data;
4988
+ if (!m || m.nxuWhisper !== this._token || e.source !== f.contentWindow) return;
4989
+ if (m.type === 'hello') { clearTimeout(timer); resolve(f); return; }
4990
+ const w = this._wait.get(m.id);
4991
+ if (!w) return;
4992
+ if (m.type === 'progress') { w.progress?.(m); return; }
4993
+ this._wait.delete(m.id);
4994
+ if (m.type === 'error') w.reject(new Error(m.message || 'whisper failed'));
4995
+ else w.resolve(m);
4996
+ };
4997
+ window.addEventListener('message', onMsg);
4998
+ (document.body || document.documentElement).appendChild(f);
4999
+ this._frame = f;
5000
+ });
5001
+ return this._ready;
5002
+ },
5003
+ async _call(msg, { progress = null, transfer = [], timeout = 0 } = {}) {
5004
+ const f = await this._connect();
5005
+ const id = ++this._n;
5006
+ return new Promise((resolve, reject) => {
5007
+ const timer = timeout ? setTimeout(() => { this._wait.delete(id); reject(new Error('whisper timed out')); }, timeout) : 0;
5008
+ this._wait.set(id, { resolve: (v) => { clearTimeout(timer); resolve(v); }, reject: (e) => { clearTimeout(timer); reject(e); }, progress });
5009
+ f.contentWindow.postMessage(Object.assign({ nxuWhisper: this._token, id }, msg), 'https://cdn.jsdelivr.net', transfer);
5010
+ });
5011
+ },
5012
+ async status(id = this.model()) {
5013
+ const r = await this._call({ cmd: 'status', urls: this.files(id) }, { timeout: 15000 });
5014
+ this._gpu = { gpu: r.gpu, f16: r.f16 };
5015
+ return r;
5016
+ },
5017
+ canRun(id = this.model()) { return !this.MODELS[id].gpu || !!(this._gpu && this._gpu.f16); },
5018
+ // Downloads (first time) and loads the model; progress gets 0..1.
5019
+ async load(id = this.model(), progress = null) {
5020
+ const M = this.MODELS[id];
5021
+ if (this._loaded === id) return true;
5022
+ const seen = new Map();
5023
+ await this._call({ cmd: 'load', repo: M.repo, device: M.device, dtype: M.dtype }, {
5024
+ progress: (p) => {
5025
+ if (!progress) return;
5026
+ if (p.all && p.total) { progress(p.loaded / p.total); return; }
5027
+ if (p.file && p.total) { seen.set(p.file, [p.loaded, p.total]); let a = 0, b = 0; seen.forEach(([l, t]) => { a += l; b += t; }); progress(Math.min(1, a / Math.max(b, M.mb * 1048576 * 0.9))); }
5028
+ }
5029
+ });
5030
+ this._loaded = id;
5031
+ return true;
5032
+ },
5033
+ async remove(id = this.model()) { await this._call({ cmd: 'remove', repo: this.MODELS[id].repo }, { timeout: 20000 }); if (this._loaded === id) this._loaded = ''; },
5034
+ async transcribe(samples, lang) {
5035
+ if (this._queue > 3) { logDebug('AI Sub: offline Whisper is behind; skipping a line to catch up.', 'warn'); return ''; }
5036
+ this._queue++;
5037
+ try {
5038
+ await this.load();
5039
+ const r = await this._call({ cmd: 'run', audio: samples, lang: lang || '' }, { transfer: [samples.buffer], timeout: 120000 });
5040
+ return String(r.text || '').trim();
5041
+ } finally { this._queue--; }
5042
+ }
5043
+ };
5044
+
4847
5045
  const CLOUD_ASR = {
4848
5046
  RATE: 16000,
4849
5047
  FRAME: 320, // 20 ms
@@ -4980,13 +5178,17 @@
4980
5178
  const seconds = (frames.length * 0.02).toFixed(1);
4981
5179
  let text = '';
4982
5180
  try {
4983
- text = await AI.transcribe(this._wav(frames), { lang: baseLang(TRANSLATOR._recognitionLanguage()), prompt: [glossaryTerms().join(', '), TRANSLATOR._cloudPrompt].filter(Boolean).join('. '), signal: ctrl.signal });
5181
+ if (AI.asrProvider() === 'local') {
5182
+ const pcm = new Float32Array(frames.reduce((n, f) => n + f.length, 0));
5183
+ let o = 0; for (const f of frames) { pcm.set(f, o); o += f.length; }
5184
+ text = await LOCAL_WHISPER.transcribe(pcm, baseLang(TRANSLATOR._recognitionLanguage()));
5185
+ } else text = await AI.transcribe(this._wav(frames), { lang: baseLang(TRANSLATOR._recognitionLanguage()), prompt: [glossaryTerms().join(', '), TRANSLATOR._cloudPrompt].filter(Boolean).join('. '), signal: ctrl.signal });
4984
5186
  this._failures = 0;
4985
5187
  } catch (err) {
4986
5188
  if (err?.name === 'AbortError' || !this.active) return;
4987
5189
  this._failures++;
4988
5190
  logDebug(`AI Sub: cloud speech recognition failed (${err.message}${err.detail ? ': ' + err.detail : ''}).`, 'warn');
4989
- if (err.status === 401 || err.status === 403 || this._failures >= 4) TRANSLATOR.cloudAsrFailed(err);
5191
+ if (err.status === 401 || err.status === 403 || err.code === 'helper' || this._failures >= 4) TRANSLATOR.cloudAsrFailed(err);
4990
5192
  } finally {
4991
5193
  this._inflight.delete(ctrl);
4992
5194
  }
@@ -7891,8 +8093,65 @@
7891
8093
  }));
7892
8094
  const positionSelect = createSelect('stt-position', [{ value: 'video', label: t('posVideo') }, { value: 'screen', label: t('posScreen') }]);
7893
8095
  const asrSelect = createSelect('stt-asr-provider', [
7894
- { value: 'browser', label: t('asrBrowser') }, { value: 'openai', label: t('asrOpenAI') },
8096
+ { value: 'browser', label: t('asrBrowser') },
8097
+ ...(LOCAL_WHISPER.available() ? [{ value: 'local', label: t('asrLocal') }] : []),
8098
+ { value: 'openai', label: t('asrOpenAI') },
7895
8099
  { value: 'openai-hq', label: t('asrOpenAIHQ') }, { value: 'groq', label: t('asrGroq') }]);
8100
+ // Offline Whisper: pick a model, download it once (explicitly), remove it again.
8101
+ const whisperBox = createEl('div', 'whisper-box');
8102
+ const whisperModel = createSelect('stt-whisper-model', Object.keys(LOCAL_WHISPER.MODELS).map(id => ({ value: id, label: t('whisperModel_' + id, { mb: LOCAL_WHISPER.MODELS[id].mb }) })));
8103
+ whisperModel.value = LOCAL_WHISPER.model();
8104
+ const whisperBtn = createEl('button', 'btn subtle', '', { type: 'button', id: 'nxu-whisper-btn' });
8105
+ const whisperDel = createEl('button', 'btn subtle', '🗑️ ' + t('whisperRemove'), { type: 'button', id: 'nxu-whisper-del' });
8106
+ const whisperInfo = createEl('div', 'trans-help', '', { id: 'nxu-whisper-info' });
8107
+ const whisperRow = createEl('div', 'nx-btn-row');
8108
+ whisperRow.append(whisperBtn, whisperDel);
8109
+ whisperBox.append(whisperModel, whisperRow, whisperInfo);
8110
+ const paintWhisper = async () => {
8111
+ const id = whisperModel.value;
8112
+ whisperBox.style.display = asrSelect.value === 'local' ? '' : 'none';
8113
+ if (asrSelect.value !== 'local') return;
8114
+ whisperBtn.disabled = true; whisperDel.style.display = 'none';
8115
+ whisperBtn.textContent = '⏳ ' + t('whisperChecking');
8116
+ try {
8117
+ const st = await LOCAL_WHISPER.status(id);
8118
+ STORE.set('nxu_whisper_ready_' + id, !!st.cached);
8119
+ if (!LOCAL_WHISPER.canRun(id)) { whisperBtn.textContent = '⚠️ ' + t('whisperNeedsGpu'); whisperInfo.textContent = t('whisperGpuHelp'); return; }
8120
+ whisperBtn.disabled = !!st.cached;
8121
+ whisperBtn.textContent = st.cached ? '✓ ' + t('whisperReady') : '⬇️ ' + t('whisperDownload', { mb: LOCAL_WHISPER.MODELS[id].mb });
8122
+ whisperDel.style.display = st.cached ? '' : 'none';
8123
+ whisperInfo.textContent = t(st.cached ? 'whisperReadyHelp' : 'whisperHelp');
8124
+ } catch (err) {
8125
+ whisperBtn.textContent = '⚠️ ' + t('whisperBlocked');
8126
+ whisperInfo.textContent = t('whisperBlockedHelp');
8127
+ }
8128
+ };
8129
+ whisperModel.addEventListener('change', () => { STORE.set('nxu_whisper_model', whisperModel.value); paintWhisper(); if (AI.asrProvider() === 'local') TRANSLATOR.restart('whisper model changed'); });
8130
+ whisperBtn.onclick = async (ev) => {
8131
+ ev.stopPropagation();
8132
+ const id = whisperModel.value;
8133
+ whisperBtn.disabled = true;
8134
+ whisperBtn.textContent = '⬇️ 0%';
8135
+ whisperInfo.textContent = t('whisperDownloading');
8136
+ try {
8137
+ await LOCAL_WHISPER.load(id, (f) => { whisperBtn.textContent = '⬇️ ' + Math.round(f * 100) + '%'; });
8138
+ STORE.set('nxu_whisper_ready_' + id, true);
8139
+ showToast('✓ ' + t('whisperDone'));
8140
+ logDebug('Offline Whisper (' + id + ') downloaded and ready.', 'success');
8141
+ if (TRANSLATOR.active) TRANSLATOR.restart('whisper ready');
8142
+ } catch (err) {
8143
+ logDebug('Offline Whisper download failed: ' + err.message, 'error');
8144
+ showToast('⚠️ ' + t('whisperFailed'));
8145
+ }
8146
+ paintWhisper();
8147
+ };
8148
+ whisperDel.onclick = async (ev) => {
8149
+ ev.stopPropagation();
8150
+ try { await LOCAL_WHISPER.remove(whisperModel.value); } catch (_) { }
8151
+ STORE.set('nxu_whisper_ready_' + whisperModel.value, false);
8152
+ if (AI.asrProvider() !== 'local' && TRANSLATOR.active) TRANSLATOR.restart('whisper removed');
8153
+ paintWhisper();
8154
+ };
7896
8155
  const providerSelect = createSelect('stt-translation-provider', [
7897
8156
  { value: 'auto', label: t('providerAuto') }, { value: 'anthropic', label: t('providerClaude') }, { value: 'openai', label: t('providerGPT') },
7898
8157
  { value: 'deepl', label: t('providerDeepL') }, { value: 'device', label: t('providerDevice') }, { value: 'google', label: t('providerGoogle') }, { value: 'browser', label: t('providerBrowser') }]);
@@ -7977,7 +8236,7 @@
7977
8236
  const offlineBtn = createEl('button', 'btn subtle', '⬇️ ' + t('offlineDownload'));
7978
8237
  offlineBtn.onclick = () => TRANSLATOR.downloadOfflineModels();
7979
8238
  advanced.append(label(t('translationEngine')), providerSelect, engineHint,
7980
- label(t('asrEngine')), asrSelect,
8239
+ label(t('asrEngine')), asrSelect, whisperBox,
7981
8240
  label(t('subPosition')), positionSelect,
7982
8241
  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'),
7983
8242
  help(t('modelHelp')), localRow, help(t('localFirstHelp')), offlineBtn, help(t('offlineHelp')));
@@ -8001,6 +8260,8 @@
8001
8260
  positionSelect.value = STORE.get('nxu_sub_position', 'video');
8002
8261
  providerSelect.value = STORE.get('nxu_translation_provider', 'auto');
8003
8262
  asrSelect.value = STORE.get('nxu_asr_provider', 'browser');
8263
+ if (!asrSelect.value) asrSelect.value = 'browser';
8264
+ paintWhisper();
8004
8265
  refreshEngineHint();
8005
8266
  localCheck.checked = STORE.get('nxu_stt_local_first', true) !== false;
8006
8267
  sizeSlider.value = SUB_PREFS.size; sizeVal.textContent = SUB_PREFS.size + 'px';
@@ -8015,7 +8276,7 @@
8015
8276
  });
8016
8277
  positionSelect.addEventListener('change', () => { STORE.set('nxu_sub_position', positionSelect.value); SUB_LAYOUT.schedule(); });
8017
8278
  providerSelect.addEventListener('change', () => { STORE.set('nxu_translation_provider', providerSelect.value); TRANSLATOR._cache.clear(); TRANSLATOR._llmHistory = []; refreshEngineHint(); });
8018
- asrSelect.addEventListener('change', () => { STORE.set('nxu_asr_provider', asrSelect.value); refreshEngineHint(); TRANSLATOR.restart('recognition engine changed'); });
8279
+ asrSelect.addEventListener('change', () => { STORE.set('nxu_asr_provider', asrSelect.value); refreshEngineHint(); paintWhisper(); TRANSLATOR.restart('recognition engine changed'); });
8019
8280
  localCheck.addEventListener('change', () => STORE.set('nxu_stt_local_first', !!localCheck.checked));
8020
8281
  sizeSlider.addEventListener('input', () => {
8021
8282
  STORE.set('nxu_sub_size', +sizeSlider.value);
@@ -8819,6 +9080,13 @@
8819
9080
  pinDisplay.style.display = 'none';
8820
9081
  const pinCopyBtn = createEl('button', 'btn subtle', '📋 ' + t('copyPin'));
8821
9082
  pinCopyBtn.style.display = 'none';
9083
+ // An invite link: this page with the PIN; opened by someone with NexusSync, the join
9084
+ // window comes up with the PIN filled in (one tap). Same secret as telling the PIN.
9085
+ const pinLinkBtn = createEl('button', 'btn subtle', '🔗 ' + t('inviteLink'), { type: 'button', id: 'nxu-invite-link' });
9086
+ pinLinkBtn.style.display = 'none';
9087
+ new MutationObserver(() => { pinLinkBtn.style.display = pinCopyBtn.style.display; }).observe(pinCopyBtn, { attributes: true, attributeFilter: ['style'] });
9088
+ const pinRow = createEl('div', 'nx-btn-row');
9089
+ pinRow.append(pinCopyBtn, pinLinkBtn);
8822
9090
  const guestInput = createEl('input', 'pin-input', '', { placeholder: t('enterPin'), maxlength: '6', type: 'text', inputmode: 'numeric', pattern: '[0-9]*', autocomplete: 'off' });
8823
9091
  guestInput.addEventListener('keydown', e => { if (e.key === 'Enter') connectBtn.click(); });
8824
9092
  const connectBtn = createEl('button', 'btn primary', '🚀 ' + t('joinRoom'));
@@ -8829,7 +9097,7 @@
8829
9097
  pinError.setAttribute('role', 'alert');
8830
9098
  guestInput.addEventListener('input', () => { pinError.textContent = ''; guestInput.classList.remove('bad'); });
8831
9099
  const pinHint = createEl('div', 'pin-hint');
8832
- manualBody.append(hostBtn, pinHint, pinDisplay, pinCopyBtn, createEl('hr', 'divider'), guestInput, pinError, connectBtn, viewerRow);
9100
+ manualBody.append(hostBtn, pinHint, pinDisplay, pinRow, createEl('hr', 'divider'), guestInput, pinError, connectBtn, viewerRow);
8833
9101
  manualModal.append(manualHeader, manualBody);
8834
9102
 
8835
9103
  // AI subtitles settings
@@ -9056,6 +9324,22 @@
9056
9324
  else fallback();
9057
9325
  };
9058
9326
 
9327
+ pinLinkBtn.onclick = async () => {
9328
+ const pin = pinDisplay.textContent;
9329
+ if (!/^\d{6}$/.test(pin)) return;
9330
+ const link = location.href.split('#')[0] + '#nxu-join=' + pin;
9331
+ try {
9332
+ if (IS_TOUCH && navigator.share) { await navigator.share({ title: 'NexusSync', text: t('inviteShareText'), url: link }); return; }
9333
+ await navigator.clipboard.writeText(link);
9334
+ showToast('🔗 ' + t('inviteLinkCopied'));
9335
+ } catch (err) {
9336
+ if (err?.name === 'AbortError') return;
9337
+ const ta = document.createElement('textarea'); ta.value = link; document.body.appendChild(ta); ta.select();
9338
+ try { document.execCommand('copy'); showToast('🔗 ' + t('inviteLinkCopied')); } catch (_) { }
9339
+ ta.remove();
9340
+ }
9341
+ };
9342
+
9059
9343
  // Invite more people (any participant): a new PIN for the same room.
9060
9344
  btnInvite.onclick = async () => {
9061
9345
  if (!STATE.handshakeVerified && STATE.role !== 'HOST') return;
@@ -9182,6 +9466,18 @@
9182
9466
  updateDockMenuState();
9183
9467
  installFullscreenRedirect();
9184
9468
  logDebug(`NexusSync v${NXU_VERSION} ready.`, 'success');
9469
+ // Opened from an invite link: the join window with the PIN filled in.
9470
+ const invited = IS_TOP && /^#nxu-join=(\d{6})$/.exec(location.hash || '');
9471
+ if (invited) {
9472
+ try { history.replaceState(history.state, '', location.href.split('#')[0]); } catch (_) { }
9473
+ if (!STATE.handshakeVerified && STATE.role !== 'HOST') {
9474
+ openPanel(manualModal);
9475
+ guestInput.value = invited[1];
9476
+ pinHint.textContent = t('invitedHint');
9477
+ setTimeout(() => connectBtn.focus(), 200);
9478
+ logDebug('Opened from an invite link; the PIN is filled in.', 'info');
9479
+ }
9480
+ }
9185
9481
  if (MANAGER_VERSION && MANAGER_VERSION !== NXU_VERSION) logDebug(`Userscript manager reports v${MANAGER_VERSION} (loader or stale metadata); running code is v${NXU_VERSION}.`, 'info');
9186
9482
  }
9187
9483
 
@@ -10762,6 +11058,49 @@
10762
11058
  // button. Near the end of an episode in cinema mode a small card offers it, and when the
10763
11059
  // episode ends it counts down and moves on (in a room: everyone is invited along, and
10764
11060
  // this device comes back into the same room on the next page).
11061
+ // 😴 Sleep timer: pauses after a while or at the end of this episode (and then does not
11062
+ // start the next one). The pause goes to everyone in the room like any pause.
11063
+ const SLEEP = {
11064
+ at: 0, endOfEp: false, _warned: false,
11065
+ set(minutes) {
11066
+ this.endOfEp = minutes === 'end';
11067
+ this.at = typeof minutes === 'number' && minutes > 0 ? Date.now() + minutes * 60000 : 0;
11068
+ this._warned = false;
11069
+ if (minutes) showToast('😴 ' + (this.endOfEp ? t('sleepEndSet') : t('sleepSet', { n: minutes })));
11070
+ else showToast('😴 ' + t('sleepOff'));
11071
+ },
11072
+ active() { return this.endOfEp || this.at > 0; },
11073
+ label() {
11074
+ if (this.endOfEp) return t('sleepEnd');
11075
+ if (!this.at) return '';
11076
+ const m = Math.max(0, Math.ceil((this.at - Date.now()) / 60000));
11077
+ return t('sleepLeft', { n: m });
11078
+ },
11079
+ blocksNext() { return this.endOfEp; },
11080
+ _fire() {
11081
+ const info = currentMediaInfo();
11082
+ if (info?.el && !info.el.paused) { try { info.el.pause(); } catch (_) { } }
11083
+ showToast('😴 ' + t('sleepDone'));
11084
+ logDebug('Sleep timer: paused.', 'info');
11085
+ this.at = 0; this.endOfEp = false; this._warned = false;
11086
+ },
11087
+ tick() {
11088
+ if (!this.active()) return;
11089
+ if (this.at) {
11090
+ const left = this.at - Date.now();
11091
+ if (left <= 10000 && !this._warned) { this._warned = true; showToast('😴 ' + t('sleepSoon')); }
11092
+ if (left <= 0) this._fire();
11093
+ return;
11094
+ }
11095
+ const info = currentMediaInfo();
11096
+ if (!info || !Number.isFinite(info.duration) || info.duration < 60) return;
11097
+ const left = info.duration - info.time;
11098
+ if (left <= 10 && left > 1.2 && !this._warned) { this._warned = true; showToast('😴 ' + t('sleepSoon')); }
11099
+ if (left <= 1.2 || (info.kind === 'video' && info.el.ended)) this._fire();
11100
+ }
11101
+ };
11102
+ setInterval(() => { try { SLEEP.tick(); } catch (_) { } }, 1000);
11103
+
10765
11104
  const NEXT_EP = {
10766
11105
  _card: null,
10767
11106
  _target: null,
@@ -10859,7 +11198,7 @@
10859
11198
  requestAnimationFrame(() => card.classList.add('in'));
10860
11199
  }
10861
11200
  this._card.querySelector('.nx-next-l').textContent = target.label && target.label.length > 2 ? target.label : t('nextEpGo');
10862
- if (ended && !this._count && this.enabled()) {
11201
+ if (ended && !this._count && this.enabled() && !SLEEP.blocksNext()) {
10863
11202
  let left = 8;
10864
11203
  const ring = this._card.querySelector('.nx-next-ring');
10865
11204
  this._card.classList.add('counting');
@@ -12514,11 +12853,18 @@
12514
12853
  menu.dataset.kind = 'rate';
12515
12854
  if (!open) return;
12516
12855
  const current = currentPlaybackRate();
12856
+ const sleepItem = (label, value, sel) => {
12857
+ const b = createEl('button', sel ? 'sel' : '', label, { type: 'button', role: 'menuitemradio' });
12858
+ b.onclick = (ev) => { ev.stopPropagation(); SLEEP.set(value); this.toggleRateMenu(false); this._poke(); };
12859
+ return b;
12860
+ };
12517
12861
  menu.replaceChildren(createEl('div', 'cc-menu-title', t('ccSpeed')), ...[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map(r => {
12518
12862
  const item = createEl('button', Math.abs(r - current) < 0.01 ? 'sel' : '', r === 1 ? t('ccNormal') : `${r}x`, { type: 'button', role: 'menuitemradio' });
12519
12863
  item.onclick = () => { setSharedRate(r); this.toggleRateMenu(false); this._poke(); };
12520
12864
  return item;
12521
- }));
12865
+ }), createEl('div', 'cc-menu-title', '😴 ' + t('sleepTitle') + (SLEEP.active() ? ' · ' + SLEEP.label() : '')),
12866
+ sleepItem(t('sleepNone'), 0, !SLEEP.active()), sleepItem(t('sleepMin', { n: 15 }), 15, false), sleepItem(t('sleepMin', { n: 30 }), 30, false),
12867
+ sleepItem(t('sleepMin', { n: 60 }), 60, false), sleepItem(t('sleepEnd'), 'end', SLEEP.endOfEp));
12522
12868
  resetIdleTimer(true);
12523
12869
  },
12524
12870
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangsicj/nexussync",
3
- "version": "1.6.6",
3
+ "version": "1.6.8",
4
4
  "description": "Watch-together userscript: media sync, cinema mode, live AI subtitles, chat bubbles and quick ink for Violentmonkey, Tampermonkey and iOS Userscripts.",
5
5
  "keywords": [
6
6
  "userscript",