@kangsicj/nexussync 1.6.13 → 1.6.14

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
@@ -33,9 +33,9 @@
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
35
  | AI subtitles | Transcribes video audio into translated live subtitles; free offline Whisper on PC and phone (downloaded on request; on iPhone the way to hear the video itself without a key), the browser's engine, or your own API key; glossary for names |
36
- | Subtitles | Video tracks, local files or OpenSubtitles; up to 3 tracks at once |
36
+ | Subtitles | Video tracks, local files or OpenSubtitles; up to 3 tracks at once, each in its own colour; your pick is remembered per site for the next episode |
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; sleep timer (pause after 15/30/60 min or at the end of the episode) |
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); continue watching from where you stopped (offered, never forced) |
39
39
  | Privacy | End-to-end encrypted rooms, PIN or invite link to join, rooms deleted after everyone leaves |
40
40
 
41
41
  ## Installation
@@ -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.13
11
+ // @version 1.6.14
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.13
11
+ // @version 1.6.14
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.13';
49
+ const NXU_VERSION = '1.6.14';
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.13';
54
+ const NXU_RANK = '11.6.14';
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=';
@@ -249,7 +249,7 @@ async function handle(m) {
249
249
  'nxu_idle_timeout', 'nxu_sub_size', 'nxu_sub_opacity', 'nxu_sub_position', 'nxu_speaker_language',
250
250
  'nxu_subtitle_language', 'nxu_audio_mode', 'nxu_translation_provider', 'nxu_stt_local_first',
251
251
  'nxu_smart_speech_locale', 'nxu_fab_pos', 'nxu_asr_provider', 'nxu_key_openai', 'nxu_key_anthropic', 'nxu_key_groq', 'nxu_key_deepl',
252
- '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
252
+ '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, 'nxu_resume', 'nxu_resume_on', 'nxu_sub_pick_' + HOST
253
253
  ]);
254
254
 
255
255
  // ───────────────────────── Cross-origin HTTP (GM xhr first, fetch fallback)
@@ -413,7 +413,9 @@ async function handle(m) {
413
413
  case 'NXU_CINEMA':
414
414
  return typeof data.on === 'boolean' && bool(data.ambient) && (data.fit === undefined || ['contain', 'cover', 'fill'].includes(data.fit)) && bool(data.nexus);
415
415
  case 'NXU_MEDIA_CMD':
416
- return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute'].includes(data.action) && num(data.value);
416
+ return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute', 'pip'].includes(data.action) && num(data.value);
417
+ case 'NXU_PIP_STATE':
418
+ return ['on', 'off', 'armed', 'blocked', 'unsupported'].includes(data.state);
417
419
  case 'NXU_SYNC_CMD':
418
420
  return ['play', 'pause', 'rate'].includes(data.cmd) && num(data.time) && num(data.rate) && str(data.eventId) && str(data.action) && num(data.startIn);
419
421
  case 'NXU_TUNE':
@@ -764,7 +766,7 @@ async function handle(m) {
764
766
  tuneSrcSame: '🟢 Same video on every device — kept in step automatically, frame by frame.', tuneSrcDiff: '🟠 Different versions (length differs by {s}) — the timing is found automatically after a little playing, or set it here.', tuneSrcUnknown: 'Waiting for the others’ video…', tuneSrcShifted: '🟠 Same length, but the scenes differ — the timing is lined up automatically while you play, or set it here.', tuneDiffPicture: 'Same time, but the pictures differ', tuneShiftFound: 'Same length but different scenes: timing set to {s} automatically (tap to undo).',
765
767
  tuneSameReset: '⏱ Same video as the others: timing correction removed.', tuneAutoApplied: 'Different version: timing set to {s} automatically (tap to undo).', tuneSuggest: 'Your videos differ by {s}. Tap to line them up.',
766
768
  subMenu: 'Subtitles', xsubOff: 'Off', subTrack: 'From the video', subSearch: '🔎 Find subtitles (OpenSubtitles)', subFile: '📂 Open a subtitle file…', subAi: '🧠 AI live subtitles', subDelay: 'Timing', subLater: 'later', subEarlier: 'earlier', xsubSize: 'Size',
767
- subLoaded: '💬 Subtitles: {name}', subMulti: 'Several subtitles at once — each dot is the colour of its lines on screen; tap one to take it away.', subNone: 'No subtitles found in this video.', subMoreLangs: '🌐 {n} more languages', subSiteOnly: 'This site loads that subtitle only from its own menu — switch to the site controls (top right) and pick it there.', subSuggest: '💬 No subtitles? Find them', subLoadFail: 'Could not load these subtitles.',
769
+ subLoaded: '💬 Subtitles: {name}', subMulti: 'Several subtitles at once — each dot is the colour of its lines on screen; tap one to take it away.', subNone: 'No subtitles found in this video.', subMoreLangs: '🌐 {n} more languages', subRestored: '💬 Subtitles picked again: {name}', resumeFrom: 'Continue from {time}', setResume: 'Offer to continue where I stopped', subSiteOnly: 'This site loads that subtitle only from its own menu — switch to the site controls (top right) and pick it there.', subSuggest: '💬 No subtitles? Find them', subLoadFail: 'Could not load these subtitles.',
768
770
  osTitle: 'Find subtitles', osTmdbLooking: 'Looking up the English title on TMDB…', osTmdbNone: 'No English title found on TMDB — type it yourself if you know it.', osQuery: 'Title (English titles work best)', osSeason: 'Season', osEpisode: 'Episode', osLang: 'Language', osSearch: 'Search', osSearching: 'Searching…', osNone: 'Nothing found. Try the English title, or remove the year.', osError: 'OpenSubtitles did not answer. Try again in a moment.', osDownloads: '{n} downloads', osLoading: 'Loading…', osHint: 'Subtitles come from OpenSubtitles.org and are shown in NexusSync’s own style; use “Timing” in the subtitle menu if they are early or late.',
769
771
  viewMenu: 'Picture', viewAudio: 'Soundtrack', viewBright: 'Brightness', viewBoost: 'Volume boost', viewReset: 'Reset', boostBlocked: 'This video’s sound cannot be boosted here (it comes from another site).',
770
772
  settings: 'Settings', setProfile: 'Profile', setAvatar: 'Avatar', setStatus: 'Status message', setStatusPh: 'e.g. Popcorn ready 🍿', setReactions: 'My reactions',
@@ -783,6 +785,8 @@ async function handle(m) {
783
785
  srcIosHelp: 'Safari\'s built-in engine on iPhone/iPad erases the phone\'s own sound, so it hears only voices in the room. To subtitle the video, pick offline Whisper or Groq/OpenAI as the recognition engine below.',
784
786
  srcIosMediaHelp: 'The video is heard through the microphone with echo cancellation off — keep it playing through the speaker (not earphones) with the volume up.',
785
787
  subIosSpeaker: 'Listening to the video through the microphone — play it through the speaker with the volume up (not earphones).',
788
+ subIssueIos: 'Hears only voices around you',
789
+ subIosEngineCard: 'Safari\'s built-in engine cannot hear this phone\'s own sound, only voices around you. To subtitle the video, use the free offline model (73 MB, downloaded once).', subIosGetWhisper: 'Get the offline model and switch', subIosWhisperFailed: 'The offline model could not start in this app. In AI settings, enter a free Groq key and pick Groq as the recognition engine instead.',
786
790
  subIosEngine: 'Safari\'s engine hears only voices in the room, not this phone\'s own sound. To subtitle the video, choose offline Whisper or Groq in AI settings → recognition engine.',
787
791
  whisperMobileHelp: 'On a phone only the base model is offered; the first line can take a few seconds.',
788
792
  videoLanguage: 'Language spoken in the video', subtitleLanguageReq: 'Subtitle language (required)', chooseLanguage: '— Choose a language —',
@@ -817,7 +821,7 @@ async function handle(m) {
817
821
  pinFormat: '⚠️ Enter the 6-digit PIN', pinLocked: '🔒 Too many attempts. Retry in {s}s.', pinMismatch: '⚠️ Could not join. {n} attempts left.', pinCopied: '📋 PIN copied',
818
822
  syncBlocked: '❌ This site blocks the sync module. Try another page.', roomPlaying: '▶️ Room playing at {time}', roomPaused: '⏸️ Room paused at {time}',
819
823
  bookmarkAdded: '📌 Bookmark added: {time}', bookmarkSynced: '📌 Bookmark synced', jumpedTo: '⏩ Jumped to {time}', jumpToPosition: 'Jump to this position',
820
- noVideo: '⚠️ No video detected', noPlayingVideo: '⚠️ No playing video found', pipUnsupported: '⚠️ Picture-in-Picture not supported', pipBlocked: '⚠️ Picture-in-Picture was blocked',
824
+ noVideo: '⚠️ No video detected', noPlayingVideo: '⚠️ No playing video found', pipUnsupported: '⚠️ Picture-in-Picture not supported', pipBlocked: '⚠️ Picture-in-Picture was blocked', pipTapVideo: '📺 Tap the video once to pop it out',
821
825
  mediaFound: '✅ Media detected', mediaNotFound: '🔎 No media yet — start the video and try again',
822
826
  canvasOn: '🎨 Canvas ON', canvasOff: '🎨 Canvas OFF', canvasViewOnly: '🎨 Canvas (view only)', nothingToUndo: '↩️ Nothing to undo', undo: 'Undo (Ctrl+Z)',
823
827
  pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching', meTag: '(me)', whoViewer: 'watching only', whoAway: 'away (screen off or another tab)', whoOldVer: 'different version — please update', whoTitle: 'Watching together', whoSleeping: 'screen off — still in the room, back when it wakes', whoReconnecting: 'Reconnecting…',
@@ -889,7 +893,7 @@ async function handle(m) {
889
893
  tuneSrcSame: '🟢 모두 같은 영상이에요 — 프레임 단위로 자동으로 맞추고 있어요.', tuneSrcDiff: '🟠 서로 다른 버전이에요 (길이 차이 {s}) — 잠시 재생하면 자동으로 맞추고, 여기서 직접 맞출 수도 있어요.', tuneSrcUnknown: '다른 사람의 영상 정보를 기다리는 중…', tuneSrcShifted: '🟠 길이는 같지만 장면이 달라요 — 재생하는 동안 자동으로 맞추고, 여기서 직접 맞출 수도 있어요.', tuneDiffPicture: '시간은 같지만 화면이 달라요', tuneShiftFound: '길이는 같지만 장면이 달라서 타이밍을 {s} 자동 보정했어요 (누르면 되돌리기).',
890
894
  tuneSameReset: '⏱ 상대와 같은 영상이라 타이밍 보정을 해제했어요.', tuneAutoApplied: '다른 버전이라 타이밍을 {s} 자동 보정했어요 (누르면 되돌리기).', tuneSuggest: '서로 영상 길이가 {s} 달라요. 눌러서 맞춰 보세요.',
891
895
  subMenu: '자막', xsubOff: '끄기', subTrack: '영상에 포함된 자막', subSearch: '🔎 자막 찾기 (OpenSubtitles)', subFile: '📂 자막 파일 열기…', subAi: '🧠 AI 실시간 자막', subDelay: '싱크', subLater: '늦게', subEarlier: '빠르게', xsubSize: '크기',
892
- subLoaded: '💬 자막: {name}', subMulti: '자막 여러 개를 함께 보는 중 — 점 색이 화면 자막 색이에요. 누르면 그 자막만 꺼져요.', subNone: '이 영상에는 포함된 자막이 없어요.', subMoreLangs: '🌐 다른 언어 {n}개 더 보기', subSiteOnly: '이 사이트는 자기 메뉴에서만 이 자막을 불러와요. 오른쪽 위에서 사이트 컨트롤로 바꾼 뒤 거기서 골라 주세요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
896
+ subLoaded: '💬 자막: {name}', subMulti: '자막 여러 개를 함께 보는 중 — 점 색이 화면 자막 색이에요. 누르면 그 자막만 꺼져요.', subNone: '이 영상에는 포함된 자막이 없어요.', subMoreLangs: '🌐 다른 언어 {n}개 더 보기', subRestored: '💬 지난번 자막을 다시 켰어요: {name}', resumeFrom: '{time}부터 이어보기', setResume: '보던 곳부터 이어보기 제안', subSiteOnly: '이 사이트는 자기 메뉴에서만 이 자막을 불러와요. 오른쪽 위에서 사이트 컨트롤로 바꾼 뒤 거기서 골라 주세요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
893
897
  osTitle: '자막 찾기', osTmdbLooking: 'TMDB에서 영어 제목을 찾는 중…', osTmdbNone: 'TMDB에서 영어 제목을 찾지 못했어요 — 알고 있다면 직접 입력하세요.', osQuery: '제목 (영어 제목이 가장 잘 찾아져요)', osSeason: '시즌', osEpisode: '회차', osLang: '언어', osSearch: '검색', osSearching: '찾는 중…', osNone: '찾지 못했어요. 영어 제목으로 바꾸거나 연도를 빼 보세요.', osError: 'OpenSubtitles가 응답하지 않아요. 잠시 후 다시 시도하세요.', osDownloads: '다운로드 {n}회', osLoading: '불러오는 중…', osHint: '자막은 OpenSubtitles.org에서 가져와 NexusSync 스타일로 보여 줘요. 빠르거나 늦으면 자막 메뉴의 “싱크”로 맞추세요.',
894
898
  viewMenu: '화면', viewAudio: '오디오 트랙', viewBright: '밝기', viewBoost: '볼륨 부스트', viewReset: '초기화', boostBlocked: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
895
899
  settings: '설정', setProfile: '프로필', setAvatar: '아바타', setStatus: '상태 메시지', setStatusPh: '예: 팝콘 준비 완료 🍿', setReactions: '내 리액션',
@@ -908,6 +912,8 @@ async function handle(m) {
908
912
  srcIosHelp: '아이폰·아이패드의 Safari 기본 엔진은 휴대폰 자체 소리를 지워서 주변 사람 목소리만 들어요. 영상 자막을 보려면 아래 음성 인식 엔진을 오프라인 Whisper나 Groq/OpenAI로 골라 주세요.',
909
913
  srcIosMediaHelp: '마이크의 에코 제거를 끄고 영상 소리를 들어요. 이어폰 말고 스피커로, 소리를 키워서 재생해 주세요.',
910
914
  subIosSpeaker: '마이크로 영상 소리를 듣고 있어요. 이어폰 말고 스피커로, 소리를 키워서 재생해 주세요.',
915
+ subIssueIos: '주변 목소리만 듣는 중',
916
+ subIosEngineCard: 'Safari 기본 엔진은 이 휴대폰에서 나는 소리는 못 듣고 주변 목소리만 들어요. 영상 자막을 보려면 무료 오프라인 모델(73MB, 한 번만 다운로드)을 쓰세요.', subIosGetWhisper: '오프라인 모델 받고 바로 전환', subIosWhisperFailed: '이 앱에서는 오프라인 모델을 실행할 수 없어요. AI 설정에서 무료 Groq 키를 넣고 음성 인식 엔진을 Groq로 골라 주세요.',
911
917
  subIosEngine: 'Safari 엔진은 이 휴대폰 자체 소리는 못 듣고 주변 목소리만 들어요. 영상 자막은 AI 설정 → 음성 인식 엔진에서 오프라인 Whisper나 Groq를 골라 주세요.',
912
918
  whisperMobileHelp: '휴대폰에서는 base 모델만 쓸 수 있어요. 첫 줄은 몇 초 걸릴 수 있어요.',
913
919
  videoLanguage: '영상 속 언어', subtitleLanguageReq: '자막 언어 (필수)', chooseLanguage: '— 언어를 선택하세요 —',
@@ -942,7 +948,7 @@ async function handle(m) {
942
948
  pinFormat: '⚠️ 6자리 PIN을 입력하세요', pinLocked: '🔒 시도 횟수 초과. {s}초 후 다시 시도하세요.', pinMismatch: '⚠️ 참여하지 못했습니다. {n}회 남음.', pinCopied: '📋 PIN 복사됨',
943
949
  syncBlocked: '❌ 이 사이트는 동기화 모듈을 차단합니다. 다른 페이지에서 시도하세요.', roomPlaying: '▶️ {time}부터 재생 중', roomPaused: '⏸️ {time}에서 일시정지',
944
950
  bookmarkAdded: '📌 북마크 추가: {time}', bookmarkSynced: '📌 북마크 동기화됨', jumpedTo: '⏩ {time}(으)로 이동', jumpToPosition: '이 위치로 이동',
945
- noVideo: '⚠️ 감지된 영상이 없습니다', noPlayingVideo: '⚠️ 재생 중인 영상이 없습니다', pipUnsupported: '⚠️ PiP를 지원하지 않습니다', pipBlocked: '⚠️ PiP가 차단되었습니다',
951
+ noVideo: '⚠️ 감지된 영상이 없습니다', noPlayingVideo: '⚠️ 재생 중인 영상이 없습니다', pipUnsupported: '⚠️ PiP를 지원하지 않습니다', pipBlocked: '⚠️ PiP가 차단되었습니다', pipTapVideo: '📺 영상을 한 번 탭하면 작은 창으로 떠요',
946
952
  mediaFound: '✅ 미디어 감지됨', mediaNotFound: '🔎 아직 미디어가 없습니다 — 영상을 재생한 뒤 다시 시도하세요',
947
953
  canvasOn: '🎨 캔버스 켜짐', canvasOff: '🎨 캔버스 꺼짐', canvasViewOnly: '🎨 캔버스 (보기 전용)', nothingToUndo: '↩️ 되돌릴 내용이 없습니다', undo: '되돌리기 (Ctrl+Z)',
948
954
  pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람', whoSleeping: '화면 꺼짐 — 방에 그대로 있고, 화면이 켜지면 돌아와요', whoReconnecting: '다시 연결하는 중…',
@@ -1788,7 +1794,8 @@ async function handle(m) {
1788
1794
  const why = this._seeThrough(a.video, a.root);
1789
1795
  if (why) { logDebug('Ambient light off for this player: ' + why, 'info'); this._stopAmbient(); this._ambientPaused = true; }
1790
1796
  else { this._matchLayerZ(a.layer, a.root); this._clearBackdrops(a.video, a.root, a.cleared); }
1791
- } else if (this._ambientPaused && this.ambientEnabled() && this.applied.video && this.applied.chain[0]?.root) {
1797
+ } else if (this._ambientPaused && this.ambientEnabled() && this.applied.video && this.applied.chain[0]?.root && Date.now() - (this._ambientTry || 0) > 2000) {
1798
+ this._ambientTry = Date.now();
1792
1799
  // Turned off only while the site faded or covered its picture (loading,
1793
1800
  // seeking): back on once the picture shows again, while the setting is on.
1794
1801
  const v = this.applied.video, root = this.applied.chain[0].root;
@@ -2304,9 +2311,12 @@ async function handle(m) {
2304
2311
  }
2305
2312
  },
2306
2313
  // What NexusSync is showing right now ('' = nothing).
2307
- feed(text) {
2314
+ feed(text, rich = '') {
2308
2315
  text = String(text || '').trim();
2309
- if (text === this._text && (!this.video || this._shown === text)) return;
2316
+ this._rich = text ? rich : '';
2317
+ const key = text + '\u0001' + this._rich;
2318
+ if (key === this._key && (!this.video || this._shown === text)) return;
2319
+ this._key = key;
2310
2320
  this._text = text;
2311
2321
  if (this.video) this._show(text);
2312
2322
  else if (IS_TOP && SUB_LAYOUT.mirrorFrame?.isConnected) {
@@ -2314,7 +2324,7 @@ async function handle(m) {
2314
2324
  FRAME.postToFrame(SUB_LAYOUT.mirrorFrame, { type: 'NXU_CAPTION', mode: text ? 'sub' : 'clear', text, original: '', color: '', size: Math.round(22 * (typeof SUBS !== 'undefined' ? SUBS.size() : 1)) });
2315
2325
  }
2316
2326
  },
2317
- showOn(v, text) { if (v !== this.video) { if (this.video) this._leave(this.video); this.video = v; } this._text = String(text || '').trim(); this._show(this._text); },
2327
+ showOn(v, text) { if (v !== this.video) { if (this.video) this._leave(this.video); this.video = v; } this._text = String(text || '').trim(); this._rich = ''; this._show(this._text); },
2318
2328
  _track(v) {
2319
2329
  if (v._nxuFsTrack) return v._nxuFsTrack;
2320
2330
  try { v._nxuFsTrack = v.addTextTrack('subtitles', 'NexusSync', (STORE.get('nxu_subtitle_language', '') || navigator.language || 'en').slice(0, 2)); } catch (_) { return null; }
@@ -2332,10 +2342,16 @@ async function handle(m) {
2332
2342
  if (!text) return;
2333
2343
  const Cue = window.VTTCue || window.TextTrackCue;
2334
2344
  if (!Cue) return;
2345
+ if (this._rich && !document.getElementById('nxu-cue-colors')) {
2346
+ const st = document.createElement('style');
2347
+ st.id = 'nxu-cue-colors';
2348
+ st.textContent = SUBS.COLORS.map((c, i) => `video::cue(.nxl${i}) { color: ${c}; }`).join('\n');
2349
+ (document.head || document.documentElement).appendChild(st);
2350
+ }
2335
2351
  try {
2336
2352
  const at = Number.isFinite(v.currentTime) ? v.currentTime : 0;
2337
2353
  // One cue that lasts until the text changes (replaced on every change).
2338
- tr.addCue(new Cue(Math.max(0, at - 0.25), at + 6 * 3600, text));
2354
+ tr.addCue(new Cue(Math.max(0, at - 0.25), at + 6 * 3600, text === this._text && this._rich ? this._rich : text));
2339
2355
  } catch (_) { }
2340
2356
  },
2341
2357
  _leave(v) {
@@ -2451,14 +2467,6 @@ async function handle(m) {
2451
2467
  return code.split(/[-_]/)[0].toLowerCase();
2452
2468
  }
2453
2469
 
2454
- function defaultOutputLanguage() {
2455
- for (const candidate of [...(navigator.languages || []), navigator.language]) {
2456
- const base = baseLang(candidate);
2457
- if (LANG_BY_CODE.has(base)) return base;
2458
- }
2459
- return 'en';
2460
- }
2461
-
2462
2470
  function mediaIsBuffering() {
2463
2471
  const v = STATE.video;
2464
2472
  if (v) return !v.paused && !v.ended && v.readyState < 3;
@@ -3042,6 +3050,44 @@ async function handle(m) {
3042
3050
  }
3043
3051
  } catch (_) { }
3044
3052
  },
3053
+ // iPhone/iPad with Safari's own engine: a card says why the video is not heard and
3054
+ // fixes it in one tap (downloads the offline model, switches to it and restarts).
3055
+ _iosEngineCard() {
3056
+ const container = getContainer();
3057
+ if (!container || this._iosCard?.isConnected) return;
3058
+ const card = createEl('div', 'nx-ai-card');
3059
+ const text = createEl('div', 'nx-ai-card-text', t('subIosEngineCard'));
3060
+ const go = createEl('button', 'nx-ai-card-go', '⬇️ ' + t('subIosGetWhisper'), { type: 'button' });
3061
+ const x = createEl('button', 'nx-ai-card-x', '✕', { type: 'button', 'aria-label': t('talkClose') });
3062
+ const hide = () => { card.classList.remove('in'); setTimeout(() => card.remove(), 260); };
3063
+ ['pointerdown', 'click', 'touchstart'].forEach(n => card.addEventListener(n, (ev) => ev.stopPropagation()));
3064
+ x.onclick = hide;
3065
+ go.onclick = async () => {
3066
+ if (go.disabled) return;
3067
+ go.disabled = true;
3068
+ go.textContent = '⬇️ 0%';
3069
+ try {
3070
+ await LOCAL_WHISPER.load('base', (f) => { go.textContent = '⬇️ ' + Math.round(f * 100) + '%'; });
3071
+ STORE.set('nxu_whisper_model', 'base');
3072
+ STORE.set('nxu_whisper_ready_base', true);
3073
+ STORE.set('nxu_asr_provider', 'local');
3074
+ STORE.set('nxu_audio_mode', 'media');
3075
+ logDebug('Offline Whisper downloaded from the iPhone card; switching to it.', 'success');
3076
+ showToast('✓ ' + t('whisperDone'));
3077
+ hide();
3078
+ this._issue = '';
3079
+ if (this.active) this.restart('whisper ready');
3080
+ } catch (err) {
3081
+ logDebug('Offline Whisper download failed: ' + (err?.message || err), 'error');
3082
+ text.textContent = t('subIosWhisperFailed');
3083
+ go.remove();
3084
+ }
3085
+ };
3086
+ card.append(text, go, x);
3087
+ container.appendChild(card);
3088
+ this._iosCard = card;
3089
+ requestAnimationFrame(() => card.classList.add('in'));
3090
+ },
3045
3091
  _diag: { sound: 0, results: 0, err: '' },
3046
3092
  _createRecognizer() {
3047
3093
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
@@ -3352,7 +3398,7 @@ async function handle(m) {
3352
3398
  chip.classList.toggle('warn', silent);
3353
3399
  chip.classList.toggle('warn', silent || !!this._issue);
3354
3400
  if (this._issue) chip.classList.remove('hide');
3355
- chip.querySelector('.sub-listen-text').textContent = this._issue === 'notrack' ? t('subIssueNoTrack') : this._issue === 'noresult' ? t('subIssueNoResult') : this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
3401
+ chip.querySelector('.sub-listen-text').textContent = this._issue === 'notrack' ? t('subIssueNoTrack') : this._issue === 'noresult' ? t('subIssueNoResult') : this._issue === 'net' ? t('subIssueNet') : this._issue === 'ios-echo' ? t('subIssueIos') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
3356
3402
  const level = Math.max(this._levels.media || 0, this._levels.mic || 0);
3357
3403
  chip.querySelector('.sub-listen-meter i').style.width = Math.min(100, Math.round(level * 400)) + '%';
3358
3404
  chip.querySelector('.sub-listen-btn').style.display = offer ? '' : 'none';
@@ -4212,7 +4258,7 @@ async function handle(m) {
4212
4258
  this._startedAt = Date.now();
4213
4259
  // iPhone/iPad with Safari's own recognizer: it erases the phone's own speaker, so
4214
4260
  // say once how to subtitle the video itself.
4215
- if (this._isAppleMobile() && !this._cloud && !this._toldIosEngine) { this._toldIosEngine = true; showToast(t('subIosEngine')); }
4261
+ if (this._isAppleMobile() && !this._cloud) { this._issue = this._issue || 'ios-echo'; this._iosEngineCard(); }
4216
4262
  try {
4217
4263
  const s = this.mediaStream?.getAudioTracks()[0]?.getSettings?.();
4218
4264
  if (s) logDebug(`AI Sub: microphone echo cancellation ${s.echoCancellation === false ? 'off' : s.echoCancellation ? 'on' : 'unknown'}.`, 'info');
@@ -4249,10 +4295,10 @@ async function handle(m) {
4249
4295
  'microphone blocked by site: ' + (this._micBlockedByPolicy() ? 'YES' : 'no') + ' · permission: ' + (await this._micPermissionState()),
4250
4296
  'recognition: ' + (this._cloud ? 'cloud ' + AI.asrModel() : (this._useWebSpeech ? this._sttProvider || 'web-speech' : '-')) + ' · state: ' + this.state,
4251
4297
  'wanted sound: ' + (this.audioMode || this._audioMode()) + ' · capturing: ' + (this.captureMode || '-') + ' · engine input: ' + (this._recognitionInput || '-') + (this._trackDisabled ? ' (track refused)' : '') + (this._micMixed ? ' · mic mixed in' : '') + (this._useMixTrack ? ' · web-audio track' : '') + ' · rescue step ' + (this._rescueStage || 0),
4252
- '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),
4298
+ 'video: ' + (v ? (v.paused ? 'paused' : 'playing') + (v.muted ? ', muted' : '') + ', volume ' + Math.round((v.volume || 0) * 100) + '%' : (STATE.cinemaIframe ? '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),
4253
4299
  'levels: video ' + Math.round((this._levels?.media || 0) * 400) + ' · mic ' + Math.round((this._levels?.mic || 0) * 400),
4254
4300
  '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),
4255
- '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'
4301
+ 'issue: ' + (this._issue === 'ios-echo' ? 'ios-echo (Safari\'s engine removes the phone\'s own sound: use offline Whisper or Groq as the recognition engine)' : 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'
4256
4302
  ];
4257
4303
  return lines.join('\n');
4258
4304
  },
@@ -8111,7 +8157,8 @@ async function handle(m) {
8111
8157
  // Playback: the same switch for every on/off choice
8112
8158
  const play = section('🎬', t('setPlayback'));
8113
8159
  const autoNext = switchRow(createEl('button', '', '', { type: 'button' }), '⏭ ' + t('setAutoNext'), () => NEXT_EP.enabled(), on => STORE.set('nxu_auto_next', on));
8114
- play.append(parts.autoCinema, parts.adGuard, autoNext);
8160
+ const resumeRow = switchRow(createEl('button', '', '', { type: 'button' }), '⏯ ' + t('setResume'), () => RESUME.enabled(), on => STORE.set('nxu_resume_on', on));
8161
+ play.append(parts.autoCinema, parts.adGuard, autoNext, resumeRow);
8115
8162
  // Tools and this site
8116
8163
  const adv = section('🔧', t('setAdvanced'));
8117
8164
  const tools = createEl('div', 'nx-btn-row nx-tools');
@@ -8682,6 +8729,19 @@ async function handle(m) {
8682
8729
  background:rgba(16,18,24,0.62); -webkit-backdrop-filter:blur(4px); backdrop-filter:blur(4px); box-shadow:0 12px 30px rgba(0,0,0,0.45), 0 0 0 1px rgba(255,255,255,0.14) inset; color:#fff; text-shadow:0 1px 2px rgba(0,0,0,0.8);
8683
8730
  opacity:0; transition:opacity 0.25s ease, transform 0.25s ease; pointer-events:auto; }
8684
8731
  .nx-mode-card.in { opacity:1; transform:translate(-50%, 0); }
8732
+ .nx-resume { position:absolute; left:calc(18px + env(safe-area-inset-left, 0px)); bottom:calc(120px + env(safe-area-inset-bottom, 0px)); z-index:2065; display:flex; align-items:center; gap:6px; padding:6px; border-radius:14px;
8733
+ background:rgba(16,18,24,0.62); -webkit-backdrop-filter:blur(4px); backdrop-filter:blur(4px); box-shadow:0 10px 28px rgba(0,0,0,0.45), 0 0 0 1px rgba(255,255,255,0.14) inset;
8734
+ opacity:0; transform:translateY(12px); transition:opacity 0.25s ease, transform 0.25s ease; pointer-events:auto; }
8735
+ .nx-resume.in { opacity:1; transform:none; }
8736
+ .nx-ai-card { position:absolute; left:50%; top:calc(64px + env(safe-area-inset-top, 0px)); z-index:2066; width:min(92vw, 380px); box-sizing:border-box; display:grid; grid-template-columns:1fr auto; gap:8px 8px; padding:12px; border-radius:14px;
8737
+ background:rgba(16,18,24,0.9); color:#fff; box-shadow:0 10px 28px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.14) inset; opacity:0; transform:translate(-50%, -10px); transition:opacity 0.25s ease, transform 0.25s ease; pointer-events:auto; }
8738
+ .nx-ai-card.in { opacity:1; transform:translate(-50%, 0); }
8739
+ .nx-ai-card-text { font-size:13px; line-height:1.45; grid-column:1; }
8740
+ .nx-ai-card-x { grid-column:2; grid-row:1; align-self:start; width:28px; height:28px; border:none; border-radius:50%; background:rgba(255,255,255,0.12); color:#fff; font-size:11px; cursor:pointer; }
8741
+ .nx-ai-card-go { grid-column:1 / -1; border:none; border-radius:10px; background:#69f0ae; color:#061009; font:800 14px/1 inherit; font-family:inherit; padding:12px 14px; cursor:pointer; }
8742
+ .nx-ai-card-go:disabled { opacity:0.8; }
8743
+ .nx-resume-go { border:none; border-radius:10px; background:#69f0ae; color:#061009; font:800 13px/1 inherit; font-family:inherit; padding:10px 14px; cursor:pointer; }
8744
+ .nx-resume-x { width:28px; height:28px; border:none; border-radius:50%; background:rgba(255,255,255,0.12); color:#fff; font-size:11px; cursor:pointer; }
8685
8745
  .nx-mode-head { display:flex; align-items:center; gap:7px; font-weight:800; font-size:14px; padding-right:26px; }
8686
8746
  .nx-mode-sub { margin-top:4px; font-size:12.5px; line-height:1.4; opacity:0.85; }
8687
8747
  .nx-mode-row { display:flex; gap:7px; margin-top:9px; flex-wrap:wrap; }
@@ -9501,15 +9561,13 @@ async function handle(m) {
9501
9561
  if (!video || video.readyState === 0) {
9502
9562
  video = Array.from(document.querySelectorAll('video')).find(v => v.readyState > 0 && !v.paused) || video;
9503
9563
  }
9564
+ // The video plays inside a frame: asked there (this page cannot reach it).
9565
+ const frame = STATE.cinemaIframe;
9566
+ if ((!video || video.readyState === 0) && frame) { FRAME.postToFrame(frame, { type: 'NXU_MEDIA_CMD', action: 'pip' }); return; }
9504
9567
  if (!video || video.readyState === 0) { showToast(t('noPlayingVideo')); return; }
9505
- try {
9506
- video.removeAttribute('disablepictureinpicture');
9507
- if (document.pictureInPictureElement) await document.exitPictureInPicture();
9508
- else if (video.webkitPresentationMode === 'picture-in-picture') video.webkitSetPresentationMode('inline');
9509
- else if (typeof video.requestPictureInPicture === 'function') await video.requestPictureInPicture();
9510
- else if (typeof video.webkitSetPresentationMode === 'function') video.webkitSetPresentationMode('picture-in-picture');
9511
- else showToast(t('pipUnsupported'));
9512
- } catch (_) { showToast(t('pipBlocked')); }
9568
+ const state = await PIP.toggle(video);
9569
+ if (state === 'unsupported') showToast(t('pipUnsupported'));
9570
+ else if (state === 'blocked') showToast(t('pipBlocked'));
9513
9571
  };
9514
9572
  btnDraw.onclick = () => {
9515
9573
  clearUINotify(btnDraw);
@@ -10486,6 +10544,50 @@ async function handle(m) {
10486
10544
 
10487
10545
  // ───────────────────────── Subtitles in cinema: the video's own tracks, a file, or
10488
10546
  // OpenSubtitles — drawn by NexusSync in one consistent style, with timing and size.
10547
+ // The subtitles you picked from the video's own tracks are remembered per site, by name
10548
+ // ("Korean 2"), and picked again for the next episode or when the site rebuilds its player.
10549
+ // "Off" in the menu forgets them.
10550
+ const SUB_MEMORY = {
10551
+ key() { return 'nxu_sub_pick_' + HOST; },
10552
+ names() { const v = STORE.get(this.key(), null); return Array.isArray(v) ? v.filter(s => typeof s === 'string').slice(0, 3) : []; },
10553
+ save() { STORE.set(this.key(), SUBS.layers.filter(l => l.kind === 'track').map(l => l.label)); },
10554
+ clear() { STORE.set(this.key(), []); },
10555
+ _seen: new WeakSet(),
10556
+ watch(v) {
10557
+ if (!IS_TOP || !v?.textTracks) return;
10558
+ if (!this._seen.has(v)) {
10559
+ this._seen.add(v);
10560
+ const again = () => { if (v === STATE.video) { SUBS.prune(); this.restore(); } };
10561
+ try { v.textTracks.addEventListener('addtrack', again); v.textTracks.addEventListener('removetrack', again); } catch (_) { }
10562
+ v.addEventListener('loadstart', again);
10563
+ }
10564
+ SUBS.prune();
10565
+ this.restore();
10566
+ },
10567
+ restore() {
10568
+ const want = this.names();
10569
+ if (!want.length) return;
10570
+ clearTimeout(this._timer);
10571
+ let tries = 0;
10572
+ const run = () => {
10573
+ this._timer = 0;
10574
+ const v = STATE.video;
10575
+ if (!v) return;
10576
+ const missing = want.filter(n => !SUBS.layers.some(l => l.kind === 'track' && l.label === n));
10577
+ if (!missing.length) return;
10578
+ const picked = [];
10579
+ for (const n of missing) {
10580
+ const tr = SUBS.tracks().find(x => !SUBS.hasTrack(x) && SUBS.trackName(x) === n);
10581
+ if (tr && SUBS.layers.length < SUBS.MAX) { SUBS.useTrack(tr); picked.push(n); }
10582
+ }
10583
+ if (picked.length) { logDebug('Subtitles picked again: ' + picked.join(', '), 'info'); showToast(t('subRestored', { name: picked.join(', ') })); }
10584
+ // Tracks often appear a little after the video: look again for a few seconds.
10585
+ if (picked.length < missing.length && ++tries < 12) this._timer = setTimeout(run, 800);
10586
+ };
10587
+ this._timer = setTimeout(run, 400);
10588
+ }
10589
+ };
10590
+
10489
10591
  const SUBS = {
10490
10592
  // Up to three subtitle layers at once (e.g. Dutch + English + Korean for learning):
10491
10593
  // each is a track of the page's video or a loaded file, drawn in its own colour.
@@ -10509,10 +10611,10 @@ async function handle(m) {
10509
10611
  if (lang === code || lang.startsWith(code + '-') || lang.startsWith(code + '_')) return true;
10510
10612
  const three = { ko: ['kor'], en: ['eng'], ja: ['jpn', 'jap'], zh: ['chi', 'zho'], es: ['spa'], fr: ['fre', 'fra'], de: ['ger', 'deu'], pt: ['por'], ru: ['rus'], it: ['ita'], vi: ['vie'], th: ['tha'], id: ['ind'] }[code] || [];
10511
10613
  if (three.includes(lang)) return true;
10512
- try {
10513
- const names = [new Intl.DisplayNames(['en'], { type: 'language' }).of(code), new Intl.DisplayNames([code], { type: 'language' }).of(code)].map(s => String(s).toLowerCase());
10514
- return names.some(n => n && label.startsWith(n));
10515
- } catch (_) { return false; }
10614
+ const names = (SUBS._langNames ||= {})[code] ||= (() => {
10615
+ try { return [new Intl.DisplayNames(['en'], { type: 'language' }).of(code), new Intl.DisplayNames([code], { type: 'language' }).of(code)].map(s => String(s).toLowerCase()); } catch (_) { return []; }
10616
+ })();
10617
+ return names.some(n => n && label.startsWith(n));
10516
10618
  };
10517
10619
  return is(want) ? 1 : want !== 'en' && is('en') ? 2 : 3;
10518
10620
  },
@@ -10526,6 +10628,18 @@ async function handle(m) {
10526
10628
  _drop(l) {
10527
10629
  if (l.track) { try { l.track.removeEventListener('cuechange', this._onCue); l.track.mode = 'disabled'; } catch (_) { } }
10528
10630
  },
10631
+ // Track layers of a video that is gone (next episode, the site rebuilt its player) show
10632
+ // nothing but still took one of the three places: they are dropped. File/search
10633
+ // subtitles stay.
10634
+ prune() {
10635
+ const live = new Set(this.tracks());
10636
+ const stale = this.layers.filter(l => l.kind === 'track' && !live.has(l.track));
10637
+ if (!stale.length) return false;
10638
+ stale.forEach(l => this._drop(l));
10639
+ this.layers = this.layers.filter(l => !stale.includes(l));
10640
+ if (!this.layers.length) this.off(); else this.tick(true);
10641
+ return true;
10642
+ },
10529
10643
  off() {
10530
10644
  this.layers.forEach(l => this._drop(l));
10531
10645
  this.layers = [];
@@ -10576,7 +10690,8 @@ async function handle(m) {
10576
10690
  _askSite(tr) {
10577
10691
  const v = STATE.video;
10578
10692
  if (!v || tr._nxuAsked) return;
10579
- setTimeout(async () => {
10693
+ // One at a time: two picks at once would open and close the site's menu over each other.
10694
+ const job = async () => {
10580
10695
  if (!this.hasTrack(tr) || tr.cues?.length) return;
10581
10696
  // A <track src> loads its own file: nothing to ask the site for.
10582
10697
  if ([...v.querySelectorAll('track')].some(el => el.track === tr && el.src)) return;
@@ -10605,7 +10720,8 @@ async function handle(m) {
10605
10720
  if (!this.hasTrack(tr)) return;
10606
10721
  if (tr.cues?.length) { this.tick(true); logDebug(`Subtitles: "${label}" loaded through the site's own menu.`, 'info'); }
10607
10722
  else showToast(t('subSiteOnly'));
10608
- }, 1500);
10723
+ };
10724
+ setTimeout(() => { this._askQ = (this._askQ || Promise.resolve()).then(job).catch(() => { }); }, 1500);
10609
10725
  },
10610
10726
  useCues(cues, label) { this._add({ kind: 'cues', cues: cues.sort((a, b) => a.s - b.s), label }); },
10611
10727
  _loop() { clearInterval(this._timer); this._timer = setInterval(() => this.tick(), 150); this.tick(true); },
@@ -10642,7 +10758,10 @@ async function handle(m) {
10642
10758
  if (!force && sig === this._last && this._box?.isConnected) return;
10643
10759
  this._last = sig;
10644
10760
  const any = groups.some(g => g.text);
10645
- FS_SUBS.feed(groups.filter(g => g.text).map(g => g.text.split('\n').filter(Boolean).slice(0, 3).join('\n')).join('\n'));
10761
+ const shown = groups.filter(g => g.text).map(g => ({ c: g.c, lines: g.text.split('\n').filter(Boolean).slice(0, 3) }));
10762
+ // In the video's own fullscreen each subtitle keeps its colour too (WebVTT classes).
10763
+ const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
10764
+ FS_SUBS.feed(shown.map(g => g.lines.join('\n')).join('\n'), this.layers.length > 1 ? shown.map(g => g.lines.map(l => `<c.nxl${g.c}>${esc(l)}</c>`).join('\n')).join('\n') : '');
10646
10765
  const box = any ? this._ensureBox() : this._box;
10647
10766
  if (!box) return;
10648
10767
  const kids = [];
@@ -11193,6 +11312,76 @@ async function handle(m) {
11193
11312
  } catch (_) { }
11194
11313
  }, 1200);
11195
11314
 
11315
+ // ───────────────────────── Continue watching
11316
+ // Where you stopped in a long video (5 min+) is kept per page, and when you open that page
11317
+ // again on your own (not in a room) a small card offers to continue from there — only an
11318
+ // offer, nothing is skipped by itself, and not when the site already continued for you.
11319
+ // Kept for the last 80 videos; finished videos are forgotten.
11320
+ const RESUME = {
11321
+ KEY: 'nxu_resume', MAX: 80,
11322
+ enabled() { return STORE.get('nxu_resume_on', true) !== false; },
11323
+ _key() {
11324
+ const q = location.search.replace(/([?&])(utm_[^&]*|fbclid=[^&]*|gclid=[^&]*|t=\d+[^&]*|start=\d+)(&|$)/g, (m, a, b, c) => (c ? a : '')).replace(/[?&]$/, '');
11325
+ return (location.origin + location.pathname + q).slice(0, 300);
11326
+ },
11327
+ _all() { const m = STORE.get(this.KEY, null); return m && typeof m === 'object' && !Array.isArray(m) ? m : {}; },
11328
+ save(v) {
11329
+ if (!v || !this.enabled()) return;
11330
+ const d = v.duration, tm = v.currentTime;
11331
+ if (!Number.isFinite(d) || d < 300 || !Number.isFinite(tm)) return;
11332
+ const k = this._key(), m = this._all();
11333
+ if (tm < 60) return; // just started (or started over): what was kept stays
11334
+ if (d - tm < Math.max(90, d * 0.04)) { if (!(k in m)) return; delete m[k]; }
11335
+ else {
11336
+ const prev = m[k];
11337
+ if (prev && Math.abs(prev.t - tm) < 5) return;
11338
+ m[k] = { t: Math.floor(tm), d: Math.round(d), at: Date.now() };
11339
+ const keys = Object.keys(m);
11340
+ if (keys.length > this.MAX) keys.sort((a, b) => (m[a].at || 0) - (m[b].at || 0)).slice(0, keys.length - this.MAX).forEach(x => delete m[x]);
11341
+ }
11342
+ STORE.set(this.KEY, m);
11343
+ },
11344
+ _seen: new WeakSet(),
11345
+ watch(v) {
11346
+ if (!IS_TOP || !v || this._seen.has(v)) return;
11347
+ this._seen.add(v);
11348
+ let last = 0;
11349
+ const tick = () => { if (v !== STATE.video || v.paused) return; const now = Date.now(); if (now - last > 15000) { last = now; this.save(v); } };
11350
+ v.addEventListener('timeupdate', tick);
11351
+ v.addEventListener('pause', () => { if (v === STATE.video) this.save(v); });
11352
+ v.addEventListener('ended', () => { if (v === STATE.video) { const m = this._all(); const k = this._key(); if (k in m) { delete m[k]; STORE.set(this.KEY, m); } } });
11353
+ const offer = () => setTimeout(() => this._offer(v), 1200);
11354
+ if (v.readyState >= 1) offer(); else v.addEventListener('loadedmetadata', offer, { once: true });
11355
+ },
11356
+ _offer(v) {
11357
+ if (v !== STATE.video || !this.enabled() || STATE.handshakeVerified || this._offeredFor === this._key()) return;
11358
+ const e = this._all()[this._key()];
11359
+ if (!e || !Number.isFinite(v.duration) || Math.abs(e.d - v.duration) > 5 || e.t < 60 || v.currentTime > 15) return;
11360
+ const container = getContainer();
11361
+ if (!container) { if ((this._wait = (this._wait || 0) + 1) < 8) setTimeout(() => this._offer(v), 1000); return; }
11362
+ this._offeredFor = this._key();
11363
+ logDebug(`Continue watching: offered from ${formatTime(e.t)}.`, 'info');
11364
+ this._card?.remove();
11365
+ const card = createEl('div', 'nx-resume');
11366
+ const go = createEl('button', 'nx-resume-go', '⏯ ' + t('resumeFrom', { time: formatTime(e.t) }), { type: 'button' });
11367
+ const x = createEl('button', 'nx-resume-x', '✕', { type: 'button', 'aria-label': t('talkClose') });
11368
+ const hide = () => { clearTimeout(this._timer); card.classList.remove('in'); setTimeout(() => card.remove(), 260); if (this._card === card) this._card = null; };
11369
+ go.onclick = (ev) => { ev.stopPropagation(); MEDIA_SAFE.seek(v, e.t); if (v.paused) MEDIA_SAFE.play(v); hide(); };
11370
+ x.onclick = (ev) => { ev.stopPropagation(); hide(); };
11371
+ ['pointerdown', 'click', 'touchstart'].forEach(ev => card.addEventListener(ev, (evt) => evt.stopPropagation()));
11372
+ card.append(go, x);
11373
+ container.appendChild(card);
11374
+ this._card = card;
11375
+ requestAnimationFrame(() => card.classList.add('in'));
11376
+ this._timer = setTimeout(hide, 12000);
11377
+ // Playing on past the start (or the site jumping there itself): no longer needed.
11378
+ const watch = () => { if (v.currentTime > 30 || STATE.handshakeVerified) { v.removeEventListener('timeupdate', watch); hide(); } };
11379
+ v.addEventListener('timeupdate', watch);
11380
+ }
11381
+ };
11382
+ window.addEventListener('pagehide', () => { try { if (STATE.video) RESUME.save(STATE.video); } catch (_) { } });
11383
+ document.addEventListener('visibilitychange', () => { try { if (document.hidden && STATE.video) RESUME.save(STATE.video); } catch (_) { } });
11384
+
11196
11385
  // ───────────────────────── Next episode
11197
11386
  // On series pages (drama/anime sites) the page usually has a "next episode" link or
11198
11387
  // button. Near the end of an episode in cinema mode a small card offers it, and when the
@@ -12019,7 +12208,7 @@ async function handle(m) {
12019
12208
  const PRESS_COLORS = { '😂': '#ffd54f', '😭': '#82b1ff', '😡': '#ff5252', '💦': '#4fc3f7', '🍪': '#d7a86e', '☕': '#bcaaa4', '😘': '#ff6fae', '🖕': '#ffb74d' };
12020
12209
  function pressFx(btn, emoji) {
12021
12210
  if (!btn) return;
12022
- btn.style.setProperty('--pop', '#69f0ae');
12211
+ btn.style.setProperty('--pop', PRESS_COLORS[emoji] || '#69f0ae');
12023
12212
  btn.classList.remove('pop');
12024
12213
  void btn.offsetWidth;
12025
12214
  btn.classList.add('pop');
@@ -12472,6 +12661,57 @@ async function handle(m) {
12472
12661
  }
12473
12662
  };
12474
12663
 
12664
+ // Picture-in-picture for the video of this document. Returns 'on' | 'off' | 'blocked' |
12665
+ // 'unsupported'. iPhone/iPad use WebKit's presentation mode first (the long-standing way
12666
+ // there); it never throws, so the result is read back a moment later.
12667
+ const PIP = {
12668
+ supported(v) { return !!v && (typeof v.requestPictureInPicture === 'function' || typeof v.webkitSetPresentationMode === 'function'); },
12669
+ active(v) { return !!v && (document.pictureInPictureElement === v || v.webkitPresentationMode === 'picture-in-picture'); },
12670
+ async toggle(v) {
12671
+ if (!v || v.readyState === 0) return 'unsupported';
12672
+ try { v.removeAttribute('disablepictureinpicture'); v.disablePictureInPicture = false; } catch (_) { }
12673
+ try {
12674
+ if (document.pictureInPictureElement) { await document.exitPictureInPicture(); return 'off'; }
12675
+ if (v.webkitPresentationMode === 'picture-in-picture') { v.webkitSetPresentationMode('inline'); return 'off'; }
12676
+ const webkit = typeof v.webkitSetPresentationMode === 'function' && (typeof v.webkitSupportsPresentationMode !== 'function' || v.webkitSupportsPresentationMode('picture-in-picture'));
12677
+ if (webkit && (IS_IOS || typeof v.requestPictureInPicture !== 'function')) {
12678
+ v.webkitSetPresentationMode('picture-in-picture');
12679
+ await new Promise(r => setTimeout(r, 700));
12680
+ return v.webkitPresentationMode === 'picture-in-picture' ? 'on' : 'blocked';
12681
+ }
12682
+ if (typeof v.requestPictureInPicture === 'function') { await v.requestPictureInPicture(); return 'on'; }
12683
+ return 'unsupported';
12684
+ } catch (err) {
12685
+ return err?.name === 'NotSupportedError' ? 'unsupported' : 'blocked';
12686
+ }
12687
+ },
12688
+ // Inside a frame the request arrives as a message, which browsers may not count as
12689
+ // your tap: then the next tap on the video itself opens the small window.
12690
+ _disarm: null,
12691
+ arm(v) {
12692
+ this._disarm?.();
12693
+ let done = false;
12694
+ const go = () => { if (done) return; off(); this.toggle(v).then(s => FRAME.postToParent({ type: 'NXU_PIP_STATE', state: s })); };
12695
+ const off = () => { done = true; clearTimeout(timer); ['click', 'touchend', 'pointerup'].forEach(n => window.removeEventListener(n, go, true)); this._disarm = null; };
12696
+ ['click', 'touchend', 'pointerup'].forEach(n => window.addEventListener(n, go, true));
12697
+ const timer = setTimeout(off, 10000);
12698
+ this._disarm = off;
12699
+ },
12700
+ // Top page: the result of a request sent into a frame.
12701
+ onFrameState(state) {
12702
+ const g = CINEMA_UI.els?.gesture;
12703
+ clearTimeout(this._passTimer);
12704
+ if (g) g.style.pointerEvents = '';
12705
+ CINEMA_UI.els?.pipBtn?.classList.toggle('on', state === 'on');
12706
+ if (state === 'armed') {
12707
+ // Let the next tap through to the video in the frame (for ten seconds).
12708
+ if (g) { g.style.pointerEvents = 'none'; this._passTimer = setTimeout(() => { g.style.pointerEvents = ''; }, 10000); }
12709
+ showToast(t('pipTapVideo'));
12710
+ } else if (state === 'unsupported') showToast(t('pipUnsupported'));
12711
+ else if (state === 'blocked') showToast(t('pipBlocked'));
12712
+ }
12713
+ };
12714
+
12475
12715
  // Applies a media command inside a frame (or forwards it further down).
12476
12716
  function applyMediaCommand(action, value) {
12477
12717
  STATE._lastUserGestureTs = Date.now();
@@ -12486,6 +12726,12 @@ async function handle(m) {
12486
12726
  case 'seekBy': MEDIA_SAFE.seek(v, Math.max(0, v.currentTime + value)); break;
12487
12727
  case 'volume': v.volume = Math.max(0, Math.min(1, value)); v.muted = value === 0; break;
12488
12728
  case 'mute': v.muted = !v.muted; break;
12729
+ case 'pip':
12730
+ PIP.toggle(v).then(s => {
12731
+ if (s === 'blocked' && !PIP.active(v)) { PIP.arm(v); s = 'armed'; }
12732
+ FRAME.postToParent({ type: 'NXU_PIP_STATE', state: s });
12733
+ });
12734
+ break;
12489
12735
  }
12490
12736
  }
12491
12737
 
@@ -13021,7 +13267,7 @@ async function handle(m) {
13021
13267
  const tracks = SUBS.tracks();
13022
13268
  const nothing = !SUBS.active() && !TRANSLATOR.active && !DOM_SUBS._src;
13023
13269
  const kids = [createEl('div', 'cc-menu-title', t('subMenu')),
13024
- item(t('xsubOff'), nothing, () => { SUBS.off(); if (TRANSLATOR.active) TRANSLATOR.stop(t('subOff')); this.toggleSubMenu(false); })];
13270
+ item(t('xsubOff'), nothing, () => { SUBS.off(); SUB_MEMORY.clear(); if (TRANSLATOR.active) TRANSLATOR.stop(t('subOff')); this.toggleSubMenu(false); })];
13025
13271
  // Several can be on at once (up to three): tap to add, tap again to take away.
13026
13272
  const name = (tr, i) => tr.label || tr.language || t('subTrack') + ' ' + (i + 1);
13027
13273
  const seen = {}, total = {};
@@ -13035,7 +13281,7 @@ async function handle(m) {
13035
13281
  shown.forEach(r => {
13036
13282
  const layer = SUBS.layers.find(l => l.track === r.tr);
13037
13283
  const b = layer ? swatch(layer, r.label, '🎞') : item('🎞 ' + r.label, false, () => { });
13038
- b.onclick = (ev) => { ev.stopPropagation(); SUBS.useTrack(r.tr); this.toggleSubMenu(true); };
13284
+ b.onclick = (ev) => { ev.stopPropagation(); SUBS.useTrack(r.tr); SUB_MEMORY.save(); this.toggleSubMenu(true); };
13039
13285
  kids.push(b);
13040
13286
  });
13041
13287
  if (fold && shown.length < rows.length) kids.push(item(t('subMoreLangs', { n: rows.length - shown.length }), false, () => { this._subAll = true; this.toggleSubMenu(true); }));
@@ -13224,7 +13470,7 @@ async function handle(m) {
13224
13470
  this.els.rotateBtn.classList.toggle('on', !!ROTATE.deg);
13225
13471
  this.els.fsBtn.style.display = fullscreenSupported() ? '' : 'none';
13226
13472
  this.els.volume.style.display = IS_IOS ? 'none' : '';
13227
- this.els.pipBtn.style.display = STATE.video && (document.pictureInPictureEnabled || typeof STATE.video.webkitSetPresentationMode === 'function') ? '' : 'none';
13473
+ this.els.pipBtn.style.display = (STATE.video ? PIP.supported(STATE.video) : !!STATE.cinemaIframe) ? '' : 'none';
13228
13474
  const msTitle = !MEDIA_SESSION._owned && navigator.mediaSession?.metadata?.title;
13229
13475
  this.els.title.textContent = msTitle || document.title || HOST;
13230
13476
  this._barAt = 0;
@@ -13259,7 +13505,7 @@ async function handle(m) {
13259
13505
  e.rateBtn.classList.toggle('on', Math.abs(rate - 1) > 0.01);
13260
13506
  e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle' || SUBS.active());
13261
13507
  e.viewBtn?.classList.toggle('on', Math.abs(BRIGHTNESS.level - 1) > 0.01);
13262
- e.pipBtn.classList.toggle('on', !!document.pictureInPictureElement);
13508
+ if (STATE.video) e.pipBtn.classList.toggle('on', PIP.active(STATE.video));
13263
13509
  e.fsBtn.classList.toggle('on', fullscreenActive());
13264
13510
  [e.rateBtn, e.subBtn, e.viewBtn, e.ambientBtn, e.fitBtn, e.pipBtn, e.fsBtn, this.els.rotateBtn].forEach(b => b && b.setAttribute('aria-pressed', String(b.classList.contains('on'))));
13265
13511
  const canStyle = info.kind === 'video' || !!STATE.cinemaIframe;
@@ -13815,6 +14061,7 @@ async function handle(m) {
13815
14061
  if (!IS_TOP) this._hookBridgeVideo(nextVideo);
13816
14062
  if (STATE.isCinema) keepInline(nextVideo);
13817
14063
  if (STATE.handshakeVerified) attachVideoHooks();
14064
+ if (IS_TOP) { try { SUB_MEMORY.watch(nextVideo); } catch (_) { } try { RESUME.watch(nextVideo); } catch (_) { } }
13818
14065
  } else if (nextFrame) {
13819
14066
  logDebug('Media: player inside embedded frame ' + String(nextFrame.src || '').slice(0, 60), 'success');
13820
14067
  } else {
@@ -14037,6 +14284,10 @@ async function handle(m) {
14037
14284
  if (data.event === 'play' || data.event === 'pause') this.scheduleScan(60);
14038
14285
  break;
14039
14286
  }
14287
+ case 'NXU_PIP_STATE':
14288
+ if (!isTarget) break;
14289
+ if (!IS_TOP) FRAME.postToParent(data); else PIP.onFrameState(data.state);
14290
+ break;
14040
14291
  case 'NXU_FULLSCREEN_STATE':
14041
14292
  case 'NXU_HOTKEY':
14042
14293
  case 'NXU_CINEMA_EXIT_REQ':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangsicj/nexussync",
3
- "version": "1.6.13",
3
+ "version": "1.6.14",
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",