@kangsicj/nexussync 1.3.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@
8
8
  // @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
9
9
  // @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
10
10
  // @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
11
- // @version 1.3.1
11
+ // @version 1.4.0
12
12
  // @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
13
13
  // @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
14
14
  // @match *://*/*
@@ -32,6 +32,8 @@
32
32
  // @connect api.anthropic.com
33
33
  // @connect api-free.deepl.com
34
34
  // @connect api.deepl.com
35
+ // @connect rest.opensubtitles.org
36
+ // @connect dl.opensubtitles.org
35
37
  // ==/UserScript==
36
38
 
37
39
  (async function () {
@@ -43,12 +45,12 @@
43
45
 
44
46
  // The version of the code that is actually running (the manager's metadata can lag
45
47
  // behind when an old copy is still installed).
46
- const NXU_VERSION = '1.3.1';
48
+ const NXU_VERSION = '1.4.0';
47
49
  // Rank used by the one-instance guard below and to tell newer builds apart in a room.
48
50
  // It is independent of the public version (1.0.0 is the first public release, after
49
51
  // private builds that reached ranks up to 10.2.0), so every older copy still installed
50
52
  // steps aside instead of this release.
51
- const NXU_RANK = '11.3.1';
53
+ const NXU_RANK = '11.4.0';
52
54
  const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
53
55
  // App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
54
56
  const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
@@ -171,6 +173,8 @@
171
173
  const HOST = location.hostname || 'local';
172
174
  await STORE.init([
173
175
  'nxu_hide_fab_' + HOST,
176
+ 'nxu_avatar', 'nxu_status', 'nxu_reactions', 'nxu_recv_react', 'nxu_recv_nudge', 'nxu_recv_ink', 'nxu_recv_chat', 'nxu_recv_ping', 'nxu_bm_lib', 'nxu_pending_jump', 'nxu_moff',
177
+ 'nxu_bright', 'nxu_boost', 'nxu_xsub_size', 'nxu_os_lang', 'nxu_panel_size_settings-modal', 'nxu_panel_size_bm-panel', 'nxu_panel_size_tune-panel', 'nxu_panel_size_os-panel',
174
178
  'nxu_idle_timeout', 'nxu_sub_size', 'nxu_sub_opacity', 'nxu_sub_position', 'nxu_speaker_language',
175
179
  'nxu_subtitle_language', 'nxu_audio_mode', 'nxu_translation_provider', 'nxu_stt_local_first',
176
180
  'nxu_smart_speech_locale', 'nxu_fab_pos', 'nxu_asr_provider', 'nxu_key_openai', 'nxu_key_anthropic', 'nxu_key_groq', 'nxu_key_deepl',
@@ -338,9 +342,15 @@
338
342
  case 'NXU_CINEMA':
339
343
  return typeof data.on === 'boolean' && bool(data.ambient) && (data.fit === undefined || ['contain', 'cover', 'fill'].includes(data.fit)) && bool(data.nexus);
340
344
  case 'NXU_MEDIA_CMD':
341
- return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute'].includes(data.action) && num(data.value);
345
+ return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute', 'boost'].includes(data.action) && num(data.value);
342
346
  case 'NXU_SYNC_CMD':
343
347
  return ['play', 'pause', 'rate'].includes(data.cmd) && num(data.time) && num(data.rate) && str(data.eventId) && str(data.action) && num(data.startIn);
348
+ case 'NXU_TUNE':
349
+ return ['snap', 'env', 'arm'].includes(data.op) && str(data.rid) && bool(data.on);
350
+ case 'NXU_TUNE_DATA': {
351
+ const arr = a => a === undefined || (Array.isArray(a) && a.length <= 4000 && a.every(x => Number.isFinite(x)));
352
+ return ['snap', 'env'].includes(data.op) && str(data.rid) && (data.img === undefined || data.img === null || (typeof data.img === 'string' && data.img.length < 90000 && data.img.startsWith('data:image/'))) && num(data.t) && arr(data.a) && arr(data.l) && arr(data.ts);
353
+ }
344
354
  case 'NXU_CAPTION':
345
355
  return ['final', 'interim', 'clear'].includes(data.mode) && str(data.text) && str(data.original) && str(data.color) && num(data.size);
346
356
  default:
@@ -667,6 +677,23 @@
667
677
  subHistory: 'Subtitle History', export: 'Export', clear: 'Clear', logCleared: '🧹 Subtitle history cleared', logExported: '💾 Subtitle history exported',
668
678
  createRoom: 'Create a room', copyPin: 'Copy PIN', enterPin: 'Enter PIN', joinRoom: 'Join Room', viewerMode: 'Viewer mode (follow without controlling)',
669
679
  aiSubSettings: 'AI Subtitles', debugConsole: 'Debug Console', uiHide: 'Auto-hide', keepOpen: 'Keep open',
680
+ 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',
681
+ tuneTitle: 'Sync timing', tuneMenu: 'Sync timing', tuneOffset: 'My offset', tuneOffsetZero: 'Same timing as the room', tuneAhead: 'My video runs {s} ahead of the room', tuneBehind: 'My video runs {s} behind the room',
682
+ tuneResync: 'Re-sync now', tuneReset: 'Reset', tuneHelp: 'Different site, different version (an extra studio logo, a shorter intro)? Move your own timing until the pictures match. Only your device changes.',
683
+ tuneCompare: 'Compare pictures', tuneMine: 'Me', tuneTheirs: '{name}', tuneNoPicture: 'No picture (protected video)', tuneWaiting: 'Waiting for the picture…',
684
+ tuneMark: 'Same scene', tuneMarkHint: 'Each of you pauses on the same moment (e.g. the first shot after the logos) and taps “This scene”.', tuneMarkBtn: '📍 This scene', tuneMarkMine: 'Mine: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: 'Apply',
685
+ tuneAuto: 'Automatic', tuneAutoBtn: '🤖 Find the timing automatically', tuneAutoHint: 'Uses the sound (or the picture) of what both of you have played over the last minutes. Play together for a little while first.',
686
+ tuneAutoNeed: 'Not enough to compare yet — play together for a little longer and try again.', tuneAutoFound: 'Found: {s} ({c}% sure)', tuneAutoNone: 'No clear match. Try “Same scene” instead.', tuneAsking: 'Asking the others…', tuneApplied: '⏱ Timing set: {s}',
687
+ tuneMarkReceived: '📍 {name} marked a scene', tuneNoPeer: 'Nobody else is in the room yet.',
688
+ 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',
689
+ subLoaded: '💬 Subtitles: {name}', subNone: 'No subtitles found in this video.', subSuggest: '💬 No subtitles? Find them', subLoadFail: 'Could not load these subtitles.',
690
+ osTitle: 'Find subtitles', 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.',
691
+ viewMenu: 'Picture & sound', viewBright: 'Brightness', viewBoost: 'Volume boost', viewReset: 'Reset', boostBlocked: 'This video’s sound cannot be boosted here (it comes from another site).',
692
+ settings: 'Settings', setProfile: 'Profile', setAvatar: 'Avatar', setStatus: 'Status message', setStatusPh: 'e.g. Popcorn ready 🍿', setReactions: 'My reactions',
693
+ setReactionsHint: 'Tap a slot, then pick an emoji (or type any emoji).', setReactionsReset: 'Back to the default reactions', setPlayback: 'Playback', setAutoNext: 'Next episode automatically',
694
+ setTogether: 'Watching together', setRecvReact: 'Show others’ reactions', setRecvNudge: 'Receive nudges (shake)', setRecvInk: 'Show others’ sketches', setRecvChat: 'Show chat bubbles', setRecvPing: 'Show pointers',
695
+ setPeople: 'People in this room', setMute: 'Hide', setUnmute: 'Show', setMutedHint: 'Hidden people’s messages, reactions and sketches are not shown on this device (only for this room).',
696
+ setAdvanced: 'Advanced', setEmojiPh: 'Any emoji', setNobody: 'Nobody else is here yet.',
670
697
  speakerLanguage: 'Spoken language', speakerHelp: 'The language spoken in the video or by you. Recognition only understands this language.',
671
698
  subtitleLanguage: 'Translate subtitles to', audioSource: 'Audio source', audioAuto: 'Auto (video audio when possible + mic)', audioMic: 'Microphone only',
672
699
  audioMedia: 'Video / tab audio only', audioDual: 'Microphone + video audio',
@@ -683,7 +710,7 @@
683
710
  subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
684
711
  subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
685
712
  subHearVideo: '🎧 Listening to the video', subHearMic: '🎧 Listening through the microphone', subVideoSilent: '🔇 No sound reaches the subtitles from this video',
686
- subIssueNet: '⚠️ Speech service connection is unstable — retrying', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
713
+ subIssueNet: '⚠️ Speech service connection is unstable — retrying', subIssueNoResult: '⚠️ Sound arrives but no words are recognised', 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”.',
687
714
  subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
688
715
  advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
689
716
  providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
@@ -763,6 +790,23 @@
763
790
  subHistory: '자막 기록', export: '내보내기', clear: '지우기', logCleared: '🧹 자막 기록을 지웠습니다', logExported: '💾 자막 기록을 저장했습니다',
764
791
  createRoom: '방 만들기', copyPin: 'PIN 복사', enterPin: 'PIN 입력', joinRoom: '방 참여', viewerMode: '시청자 모드 (조작 없이 따라보기)',
765
792
  aiSubSettings: 'AI 자막', debugConsole: '디버그 콘솔', uiHide: '자동 숨김', keepOpen: '고정',
793
+ bmLibrary: '북마크', bmAddHere: '지금 장면 북마크', bmSearch: '북마크 검색', bmEmpty: '아직 북마크가 없어요. 보는 중에 “지금 장면 북마크”를 눌러 보세요.', bmLive: '라이브', bmOpening: '📌 북마크를 여는 중…', bmJumped: '📌 {time}(으)로 돌아왔어요', bmLiveOpened: '🔴 라이브 방송을 바로 재생해요', bmDelete: '삭제', bmThisPage: '이 페이지', bmCopy: '링크 복사', bmCopied: '📋 링크를 복사했어요',
794
+ tuneTitle: '싱크 맞추기', tuneMenu: '싱크 맞추기', tuneOffset: '내 시간 보정', tuneOffsetZero: '방과 같은 타이밍', tuneAhead: '내 영상이 방보다 {s} 앞서 재생돼요', tuneBehind: '내 영상이 방보다 {s} 늦게 재생돼요',
795
+ tuneResync: '지금 다시 맞추기', tuneReset: '초기화', tuneHelp: '사이트가 달라 영상 길이가 다른가요? (배급사 로고·인트로 차이) 화면이 같아질 때까지 내 타이밍만 옮기면 돼요. 다른 사람에겐 영향이 없어요.',
796
+ tuneCompare: '화면 비교', tuneMine: '나', tuneTheirs: '{name}', tuneNoPicture: '화면을 가져올 수 없어요 (보호된 영상)', tuneWaiting: '화면을 받는 중…',
797
+ tuneMark: '같은 장면', tuneMarkHint: '각자 같은 장면(예: 로고가 끝난 첫 장면)에서 멈춘 뒤 “이 장면”을 누르세요.', tuneMarkBtn: '📍 이 장면', tuneMarkMine: '나: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: '적용',
798
+ tuneAuto: '자동', tuneAutoBtn: '🤖 자동으로 맞추기', tuneAutoHint: '최근 몇 분 동안 서로 재생한 소리(또는 화면)를 비교해요. 먼저 잠시 함께 재생해 주세요.',
799
+ tuneAutoNeed: '아직 비교할 내용이 부족해요 — 조금 더 함께 재생한 뒤 다시 시도하세요.', tuneAutoFound: '찾았어요: {s} (확신 {c}%)', tuneAutoNone: '뚜렷한 일치를 못 찾았어요. “같은 장면”으로 맞춰 보세요.', tuneAsking: '다른 사람에게 요청하는 중…', tuneApplied: '⏱ 타이밍 보정: {s}',
800
+ tuneMarkReceived: '📍 {name}님이 장면을 표시했어요', tuneNoPeer: '아직 방에 다른 사람이 없어요.',
801
+ subMenu: '자막', xsubOff: '끄기', subTrack: '영상에 포함된 자막', subSearch: '🔎 자막 찾기 (OpenSubtitles)', subFile: '📂 자막 파일 열기…', subAi: '🧠 AI 실시간 자막', subDelay: '싱크', subLater: '늦게', subEarlier: '빠르게', xsubSize: '크기',
802
+ subLoaded: '💬 자막: {name}', subNone: '이 영상에는 포함된 자막이 없어요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
803
+ osTitle: '자막 찾기', osQuery: '제목 (영어 제목이 가장 잘 찾아져요)', osSeason: '시즌', osEpisode: '회차', osLang: '언어', osSearch: '검색', osSearching: '찾는 중…', osNone: '찾지 못했어요. 영어 제목으로 바꾸거나 연도를 빼 보세요.', osError: 'OpenSubtitles가 응답하지 않아요. 잠시 후 다시 시도하세요.', osDownloads: '다운로드 {n}회', osLoading: '불러오는 중…', osHint: '자막은 OpenSubtitles.org에서 가져와 NexusSync 스타일로 보여 줘요. 빠르거나 늦으면 자막 메뉴의 “싱크”로 맞추세요.',
804
+ viewMenu: '화면 · 소리', viewBright: '밝기', viewBoost: '볼륨 부스트', viewReset: '초기화', boostBlocked: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
805
+ settings: '설정', setProfile: '프로필', setAvatar: '아바타', setStatus: '상태 메시지', setStatusPh: '예: 팝콘 준비 완료 🍿', setReactions: '내 리액션',
806
+ setReactionsHint: '칸을 누른 뒤 이모지를 고르세요 (아무 이모지나 입력해도 돼요).', setReactionsReset: '기본 리액션으로', setPlayback: '재생', setAutoNext: '다음 화 자동으로 넘기기',
807
+ setTogether: '함께 보기', setRecvReact: '다른 사람 리액션 보기', setRecvNudge: '찌르기 받기 (흔들림)', setRecvInk: '다른 사람 그림 보기', setRecvChat: '말풍선 보기', setRecvPing: '포인터 보기',
808
+ setPeople: '이 방의 사람들', setMute: '숨기기', setUnmute: '보이기', setMutedHint: '숨긴 사람의 메시지·리액션·그림은 이 기기에서 보이지 않아요 (이 방에서만).',
809
+ setAdvanced: '고급', setEmojiPh: '이모지 입력', setNobody: '아직 다른 사람이 없어요.',
766
810
  speakerLanguage: '말하는 언어', speakerHelp: '영상(또는 말하는 사람)의 언어를 선택하세요. 음성 인식은 이 언어만 알아듣습니다.',
767
811
  subtitleLanguage: '자막 번역 언어', audioSource: '오디오 입력', audioAuto: '자동 (가능하면 영상 소리 + 마이크)', audioMic: '마이크만',
768
812
  audioMedia: '영상/탭 소리만', audioDual: '마이크 + 영상 소리',
@@ -779,7 +823,7 @@
779
823
  subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
780
824
  subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
781
825
  subHearVideo: '🎧 영상 소리 듣는 중', subHearMic: '🎧 마이크로 듣는 중', subVideoSilent: '🔇 이 영상의 소리가 자막에 전달되지 않아요',
782
- subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
826
+ subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
783
827
  subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
784
828
  advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
785
829
  providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
@@ -1715,7 +1759,8 @@
1715
1759
  render() {
1716
1760
  const v = this.video, root = this._root();
1717
1761
  if (!v || !root) { this.box?.remove(); this.box = null; return; }
1718
- const cues = this._cues();
1762
+ // NexusSync's own subtitle layer has taken over: no second copy.
1763
+ const cues = typeof SUBS !== 'undefined' && SUBS.active() ? [] : this._cues();
1719
1764
  const doc = v.ownerDocument;
1720
1765
  if (!this.box || !this.box.isConnected || this.box.parentNode !== root) {
1721
1766
  this.box?.remove();
@@ -2640,6 +2685,7 @@
2640
2685
  const media = this._readLevel(a.media);
2641
2686
  this._levels = { mic, media };
2642
2687
  this._mediaPeak = Math.max(this._mediaPeak, media);
2688
+ if (Math.max(mic, media) > SPEECH_LEVEL) this._soundMs = (this._soundMs || 0) + 400;
2643
2689
  const keys = [];
2644
2690
  if (mic > SPEECH_LEVEL) keys.push('mic');
2645
2691
  if (media > SPEECH_LEVEL) keys.push('media');
@@ -2834,6 +2880,8 @@
2834
2880
  this._createRecognizer();
2835
2881
  this._scheduleRestart('track-fallback', 150, true);
2836
2882
  }
2883
+ // Plenty of sound but not a single word back: say so, with a one-tap way out.
2884
+ if (this._useWebSpeech && !this._issue && this._soundMs > 25000 && (this._lastResultAt || 0) < (this._startedAt || 0)) this._issue = 'noresult';
2837
2885
  this._updateListenChip();
2838
2886
  updateAIBtnUX();
2839
2887
  },
@@ -2918,10 +2966,22 @@
2918
2966
  chip.classList.toggle('warn', silent);
2919
2967
  chip.classList.toggle('warn', silent || !!this._issue);
2920
2968
  if (this._issue) chip.classList.remove('hide');
2921
- chip.querySelector('.sub-listen-text').textContent = this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
2969
+ chip.querySelector('.sub-listen-text').textContent = this._issue === 'noresult' ? t('subIssueNoResult') : this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
2922
2970
  const level = Math.max(this._levels.media || 0, this._levels.mic || 0);
2923
2971
  chip.querySelector('.sub-listen-meter i').style.width = Math.min(100, Math.round(level * 400)) + '%';
2924
2972
  chip.querySelector('.sub-listen-btn').style.display = offer ? '' : 'none';
2973
+ let alt = chip.querySelector('.sub-listen-alt');
2974
+ const wantAlt = this._issue === 'noresult';
2975
+ if (wantAlt && !alt) {
2976
+ alt = createEl('button', 'sub-listen-btn sub-listen-alt', '', { type: 'button' });
2977
+ alt.addEventListener('click', (e) => {
2978
+ e.stopPropagation();
2979
+ if (this.audioMode === 'media') { STORE.set('nxu_audio_mode', 'mic'); this.restart('no words from the video sound'); }
2980
+ else { const m = shadow?.getElementById('trans-modal'); if (m) { openPanel(m); const d = m.querySelector('.ai-advanced'); if (d) d.open = true; } }
2981
+ });
2982
+ chip.appendChild(alt);
2983
+ }
2984
+ if (alt) { alt.style.display = wantAlt ? '' : 'none'; alt.textContent = this.audioMode === 'media' ? t('subTryMic') : t('subTryKey'); }
2925
2985
  },
2926
2986
  _preparePlaybackMic() {
2927
2987
  const track = this.mediaStream?.getAudioTracks?.()[0];
@@ -3711,6 +3771,8 @@
3711
3771
  if (this._useWebSpeech) await this._prepareLocalSpeech(SR).catch(() => { });
3712
3772
  if (token !== this._startToken) return;
3713
3773
  this.state = 'running';
3774
+ this._startedAt = Date.now();
3775
+ this._soundMs = 0;
3714
3776
  this.active = true;
3715
3777
  if (this._useWebSpeech) {
3716
3778
  this._createRecognizer();
@@ -4167,6 +4229,8 @@
4167
4229
 
4168
4230
  function _commitVideoState({ play, time, action = 'user', rate = 1.0, videoId = '', timestamp: at = null }) {
4169
4231
  if (!ydoc || !yVideo) return null;
4232
+ // The room speaks in room time; this device's own timing correction is taken off.
4233
+ if (Number.isFinite(time)) time = Math.max(0, time - TUNE.offset());
4170
4234
  const sequenceNumber = ++STATE._videoSequence;
4171
4235
  const timestamp = Number.isFinite(at) ? at : getSyncedTime();
4172
4236
  const intent = STATE._acceptedIntent;
@@ -5181,7 +5245,7 @@
5181
5245
  case 'reaction':
5182
5246
  onRemoteReaction(d);
5183
5247
  break;
5184
- case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto':
5248
+ case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto': case 'tune':
5185
5249
  SOCIAL.receive(p.t, d);
5186
5250
  break;
5187
5251
  }
@@ -5195,6 +5259,7 @@
5195
5259
  // Sends room authority to the player inside a cross-origin frame.
5196
5260
  function sendStateToFrame(state, frame = STATE.cinemaIframe) {
5197
5261
  if (!frame || !state) return;
5262
+ state = TUNE.local(state);
5198
5263
  const rate = clampRate(state.rate);
5199
5264
  const wait = state.timestamp - getSyncedTime();
5200
5265
  const elapsed = state.play && wait < 0 ? (-wait / 1000) * rate : 0;
@@ -5279,8 +5344,9 @@
5279
5344
  yChat.observe(event => {
5280
5345
  event.changes.added.forEach(item => {
5281
5346
  item.content.getContent().forEach(content => {
5347
+ if (content && content.sender !== STATE.userId && !SAFETY.allows(content.sender)) return;
5282
5348
  appendChatMessage(content);
5283
- if (content.sender !== STATE.userId) { triggerUINotify('chat'); SOCIAL.onChat(content); }
5349
+ if (content.sender !== STATE.userId && SAFETY.receive('chat')) { triggerUINotify('chat'); SOCIAL.onChat(content); }
5284
5350
  });
5285
5351
  });
5286
5352
  });
@@ -5362,6 +5428,7 @@
5362
5428
  function applyRemoteStateToVideo(remoteState) {
5363
5429
  const video = STATE.video;
5364
5430
  if (!video) return;
5431
+ remoteState = TUNE.local(remoteState);
5365
5432
  const { play, time, timestamp: ts, action, rate } = remoteState;
5366
5433
  const base = clampRate(rate);
5367
5434
  STATE._lastRemoteApplyAt = Date.now();
@@ -5429,6 +5496,403 @@
5429
5496
  }
5430
5497
  }
5431
5498
 
5499
+ // ───────────────────────── Sync timing between different versions of a movie
5500
+ // Watching the same film on two different sites often means two different cuts: one
5501
+ // starts with a studio logo or a longer intro. Each device can shift its own timing
5502
+ // ("offset", seconds: my picture = room time + offset). Three ways to find it:
5503
+ // • Compare pictures: both screens side by side (small snapshots, about once a second).
5504
+ // • Same scene: each pauses on the same moment and marks it; the difference is the offset.
5505
+ // • Automatic: the sound (or, without sound access, the picture's brightness) of what
5506
+ // each device played over the last minutes is compared; the best match is the offset.
5507
+ const TUNE = {
5508
+ LIMIT: 900,
5509
+ _off: null,
5510
+ _key() { return location.href.split('#')[0].slice(0, 300); },
5511
+ offset() {
5512
+ if (!STATE.handshakeVerified && IS_TOP) return 0;
5513
+ if (this._off === null) {
5514
+ const all = STORE.get('nxu_moff', {});
5515
+ const v = all && typeof all === 'object' ? Number(all[this._key()]) : 0;
5516
+ this._off = Number.isFinite(v) ? Math.max(-this.LIMIT, Math.min(this.LIMIT, v)) : 0;
5517
+ }
5518
+ return this._off;
5519
+ },
5520
+ local(state) {
5521
+ const off = this.offset();
5522
+ if (!off || !state || !Number.isFinite(state.time)) return state;
5523
+ return { ...state, time: Math.max(0, state.time + off) };
5524
+ },
5525
+ set(seconds, { quiet = false } = {}) {
5526
+ const v = Math.round(Math.max(-this.LIMIT, Math.min(this.LIMIT, Number(seconds) || 0)) * 10) / 10;
5527
+ this._off = v;
5528
+ const all = { ...(STORE.get('nxu_moff', {}) || {}) };
5529
+ if (v) all[this._key()] = v; else delete all[this._key()];
5530
+ const keys = Object.keys(all);
5531
+ if (keys.length > 120) delete all[keys[0]];
5532
+ STORE.set('nxu_moff', all);
5533
+ // Move to the new timing right away.
5534
+ const room = _getVideoState();
5535
+ if (room && STATE.video) applyRemoteStateToVideo({ ...room, action: 'user' });
5536
+ else if (room && STATE.cinemaIframe) sendStateToFrame({ ...room, action: 'user' });
5537
+ this.paint();
5538
+ if (!quiet) showToast(t('tuneApplied', { s: this.fmt(v) }));
5539
+ },
5540
+ fmt(v) { return (v > 0 ? '+' : v < 0 ? '−' : '') + Math.abs(v).toFixed(Math.abs(v) < 100 ? 1 : 0) + 's'; },
5541
+
5542
+ // ── what this device played: sound energy and picture brightness by media time
5543
+ REC: { hz: 10, keep: 2400 },
5544
+ _rec: null,
5545
+ arm(on) {
5546
+ if (!on) { this._stopRec(); return; }
5547
+ const v = STATE.video;
5548
+ if (!v) { if (STATE.cinemaIframe) FRAME.postToFrame(STATE.cinemaIframe, { type: 'NXU_TUNE', op: 'arm', rid: '', on: true }); return; }
5549
+ if (this._rec && this._rec.v === v) return;
5550
+ this._stopRec();
5551
+ const rec = { v, ts: [], a: [], l: [], an: null, ctx: null, cvs: null, cx: null, tainted: false, timer: 0 };
5552
+ try {
5553
+ // The video's own audio (no change to what is heard). Not on Firefox's
5554
+ // mozCaptureStream, which silences the element.
5555
+ if (typeof v.captureStream === 'function') {
5556
+ const tracks = v.captureStream().getAudioTracks();
5557
+ const Ctx = window.AudioContext || window.webkitAudioContext;
5558
+ if (tracks.length && Ctx) {
5559
+ rec.ctx = new Ctx();
5560
+ const src = rec.ctx.createMediaStreamSource(new MediaStream(tracks));
5561
+ rec.an = rec.ctx.createAnalyser();
5562
+ rec.an.fftSize = 1024;
5563
+ src.connect(rec.an);
5564
+ rec.buf = new Float32Array(rec.an.fftSize);
5565
+ }
5566
+ }
5567
+ } catch (_) { rec.an = null; }
5568
+ rec.cvs = document.createElement('canvas');
5569
+ rec.cvs.width = 16; rec.cvs.height = 9;
5570
+ rec.cx = rec.cvs.getContext('2d', { willReadFrequently: true });
5571
+ let n = 0;
5572
+ rec.timer = setInterval(() => {
5573
+ if (v.paused || v.seeking || v.readyState < 2 || document.hidden) return;
5574
+ if (rec.ctx && rec.ctx.state === 'suspended') { try { rec.ctx.resume(); } catch (_) { } }
5575
+ let a = 0, l = -1;
5576
+ if (rec.an) {
5577
+ rec.an.getFloatTimeDomainData(rec.buf);
5578
+ let s = 0; for (let i = 0; i < rec.buf.length; i++) s += rec.buf[i] * rec.buf[i];
5579
+ a = Math.sqrt(s / rec.buf.length);
5580
+ }
5581
+ // Brightness: 10 per second on computers, 5 on phones (reading pixels back costs).
5582
+ if (!rec.tainted && (n++ % (IS_TOUCH ? 2 : 1)) === 0) {
5583
+ try {
5584
+ rec.cx.drawImage(v, 0, 0, 16, 9);
5585
+ const d = rec.cx.getImageData(0, 0, 16, 9).data;
5586
+ let s = 0; for (let i = 0; i < d.length; i += 4) s += d[i] * 0.3 + d[i + 1] * 0.59 + d[i + 2] * 0.11;
5587
+ l = s / (d.length / 4);
5588
+ } catch (_) { rec.tainted = true; }
5589
+ }
5590
+ rec.ts.push(Math.round(v.currentTime * 100) / 100); rec.a.push(Math.round(a * 1e5) / 1e5); rec.l.push(Math.round(l * 10) / 10);
5591
+ if (rec.ts.length > this.REC.keep) { rec.ts.shift(); rec.a.shift(); rec.l.shift(); }
5592
+ }, 1000 / this.REC.hz);
5593
+ this._rec = rec;
5594
+ },
5595
+ _stopRec() {
5596
+ const r = this._rec;
5597
+ this._rec = null;
5598
+ if (!r) return;
5599
+ clearInterval(r.timer);
5600
+ try { r.ctx?.close(); } catch (_) { }
5601
+ },
5602
+ _envelope() {
5603
+ const r = this._rec;
5604
+ if (!r || r.ts.length < 100) return null;
5605
+ return { ts: r.ts.slice(), a: r.a.slice(), l: r.l.slice() };
5606
+ },
5607
+ snapshot() {
5608
+ const v = STATE.video;
5609
+ if (!v || v.readyState < 2) return null;
5610
+ try {
5611
+ const c = document.createElement('canvas');
5612
+ const w = 240, h = Math.round(240 * ((v.videoHeight || 9) / (v.videoWidth || 16)));
5613
+ c.width = w; c.height = Math.max(60, Math.min(180, h));
5614
+ c.getContext('2d').drawImage(v, 0, 0, c.width, c.height);
5615
+ return c.toDataURL('image/jpeg', 0.55);
5616
+ } catch (_) { return null; } // protected / cross-origin picture
5617
+ },
5618
+ mediaTime() {
5619
+ const info = currentMediaInfo();
5620
+ return info && Number.isFinite(info.time) ? info.time : 0;
5621
+ },
5622
+
5623
+ // ── frames: the player may sit in another site's frame
5624
+ _frameWait: new Map(),
5625
+ _askFrame(op) {
5626
+ return new Promise((resolve) => {
5627
+ if (!STATE.cinemaIframe) { resolve(null); return; }
5628
+ const rid = Math.random().toString(36).slice(2, 10);
5629
+ this._frameWait.set(rid, resolve);
5630
+ FRAME.postToFrame(STATE.cinemaIframe, { type: 'NXU_TUNE', op, rid, on: true });
5631
+ setTimeout(() => { if (this._frameWait.has(rid)) { this._frameWait.delete(rid); resolve(null); } }, 2500);
5632
+ });
5633
+ },
5634
+ onFrameRequest(data) {
5635
+ if (data.op === 'arm') { this.arm(!!data.on); return; }
5636
+ const reply = { type: 'NXU_TUNE_DATA', op: data.op, rid: data.rid, t: STATE.video ? STATE.video.currentTime : 0 };
5637
+ if (data.op === 'snap') reply.img = this.snapshot();
5638
+ else { this.arm(true); const env = this._envelope(); if (env) Object.assign(reply, env); }
5639
+ FRAME.postToParent(reply);
5640
+ },
5641
+ onFrameData(data) {
5642
+ const res = this._frameWait.get(data.rid);
5643
+ if (res) { this._frameWait.delete(data.rid); res(data); }
5644
+ },
5645
+ async _mySnap() {
5646
+ if (STATE.video) return { img: this.snapshot(), t: STATE.video.currentTime };
5647
+ const d = await this._askFrame('snap');
5648
+ return d ? { img: d.img || null, t: d.t } : null;
5649
+ },
5650
+ async _myEnv() {
5651
+ if (STATE.video) { this.arm(true); return this._envelope(); }
5652
+ const d = await this._askFrame('env');
5653
+ return d && Array.isArray(d.ts) ? { ts: d.ts, a: d.a || [], l: d.l || [] } : null;
5654
+ },
5655
+
5656
+ // ── room messages
5657
+ _peer: null, // last picture from someone else
5658
+ _marks: new Map(), // uid → { t, off, name }
5659
+ _peekUntil: 0,
5660
+ onRemote(who, d) {
5661
+ const op = d.op;
5662
+ if (op === 'peek') {
5663
+ // Someone opened "Compare pictures": send ours about once a second for a while.
5664
+ this._peekUntil = Date.now() + 45000;
5665
+ this._startPeek();
5666
+ } else if (op === 'snap' && (d.img === null || (typeof d.img === 'string' && d.img.startsWith('data:image/jpeg') && d.img.length < 90000))) {
5667
+ this._peer = { uid: d.uid, name: who.name, color: who.color, img: d.img, t: Number(d.t) || 0, off: Number(d.off) || 0, at: Date.now() };
5668
+ this.paint();
5669
+ } else if (op === 'mark' && Number.isFinite(d.t)) {
5670
+ this._marks.set(d.uid, { t: d.t, off: Number(d.off) || 0, name: who.name, color: who.color });
5671
+ showToast(t('tuneMarkReceived', { name: who.name }));
5672
+ this.paint();
5673
+ } else if (op === 'envreq') {
5674
+ this._myEnv().then(env => { if (env) SOCIAL.send('tune', { op: 'env', ...this._pack(env), off: this.offset(), to: d.uid }); });
5675
+ } else if (op === 'env' && d.to === STATE.userId && this._autoWait) {
5676
+ const env = this._unpack(d);
5677
+ const done = this._autoWait;
5678
+ this._autoWait = null;
5679
+ done(env ? { env, off: Number(d.off) || 0, name: who.name } : null);
5680
+ }
5681
+ },
5682
+ // Envelopes go over the room channel as compact integer lists.
5683
+ _pack(env) {
5684
+ return { ts0: env.ts[0], ts: env.ts.map(x => Math.round((x - env.ts[0]) * 10)), a: env.a.map(x => Math.round(x * 1e4)), l: env.l.map(x => Math.round(x)) };
5685
+ },
5686
+ _unpack(d) {
5687
+ const ok = arr => Array.isArray(arr) && arr.length <= 4000 && arr.every(Number.isFinite);
5688
+ if (!Number.isFinite(d.ts0) || !ok(d.ts) || !ok(d.a) || !ok(d.l) || d.ts.length !== d.a.length) return null;
5689
+ return { ts: d.ts.map(x => d.ts0 + x / 10), a: d.a.map(x => x / 1e4), l: d.l };
5690
+ },
5691
+ _startPeek() {
5692
+ if (this._peekTimer) return;
5693
+ const loop = async () => {
5694
+ if (Date.now() > this._peekUntil || !SOCIAL.live()) { this._peekTimer = null; return; }
5695
+ const s = await this._mySnap();
5696
+ SOCIAL.send('tune', { op: 'snap', img: s ? s.img : null, t: s ? s.t : 0, off: this.offset() });
5697
+ this._peekTimer = setTimeout(loop, 1200);
5698
+ };
5699
+ this._peekTimer = setTimeout(loop, 50);
5700
+ },
5701
+ async mark() {
5702
+ const t0 = this.mediaTime();
5703
+ this._myMark = { t: t0, off: this.offset() };
5704
+ SOCIAL.send('tune', { op: 'mark', t: t0, off: this.offset() });
5705
+ this.paint();
5706
+ },
5707
+ // My offset so that my marked scene and theirs line up: off_me = off_them + (mine − theirs).
5708
+ markOffset() {
5709
+ const mine = this._myMark;
5710
+ const theirs = [...this._marks.values()].pop();
5711
+ if (!mine || !theirs) return null;
5712
+ return theirs.off + (mine.t - theirs.t);
5713
+ },
5714
+
5715
+ // ── automatic: cross-correlation of what both played (onsets of sound / brightness)
5716
+ _series(env, useLuma) {
5717
+ // Uniform 0.1 s grid by media time; onset strength = rise of log energy (or change of brightness).
5718
+ const step = 0.1;
5719
+ const pts = [];
5720
+ for (let i = 0; i < env.ts.length; i++) {
5721
+ const val = useLuma ? env.l[i] : env.a[i];
5722
+ if (useLuma && val < 0) continue;
5723
+ pts.push([env.ts[i], val]);
5724
+ }
5725
+ if (pts.length < 80) return null;
5726
+ pts.sort((x, y) => x[0] - y[0]);
5727
+ const t0 = pts[0][0], t1 = pts[pts.length - 1][0];
5728
+ const n = Math.min(6000, Math.floor((t1 - t0) / step) + 1);
5729
+ const raw = new Float64Array(n).fill(NaN);
5730
+ for (const [ts, val] of pts) { const k = Math.round((ts - t0) / step); if (k >= 0 && k < n) raw[k] = useLuma ? val : Math.log(1e-4 + val); }
5731
+ // fill small gaps
5732
+ for (let i = 1; i < n; i++) if (Number.isNaN(raw[i])) raw[i] = raw[i - 1];
5733
+ const out = new Float64Array(n);
5734
+ // Sound: rises of loudness (onsets). Picture: the brightness curve itself plus its
5735
+ // jumps (scene cuts), so slow fades and hard cuts both count.
5736
+ // High-pass (minus the 2 s running mean) keeps the changes, not the slow level.
5737
+ const W = 20;
5738
+ let acc = 0;
5739
+ for (let i = 0; i < n; i++) {
5740
+ acc += raw[i]; if (i >= W) acc -= raw[i - W];
5741
+ const mean = acc / Math.min(i + 1, W);
5742
+ const d = i ? raw[i] - raw[i - 1] : 0;
5743
+ out[i] = useLuma ? (raw[i] - mean) / 32 + Math.abs(d) / 8 : Math.max(0, d);
5744
+ }
5745
+ return { t0, step, v: out };
5746
+ },
5747
+ _correlate(me, them, maxLag) {
5748
+ // lag d (seconds): my content at time x equals theirs at time x − d.
5749
+ const step = me.step;
5750
+ let best = { score: -Infinity, d: 0 }, second = -Infinity;
5751
+ const norm = (arr, a, b) => { let m = 0, c = 0; for (let i = a; i < b; i++) { m += arr[i]; c++; } m /= Math.max(1, c); let s = 0; for (let i = a; i < b; i++) s += (arr[i] - m) ** 2; return { m, s: Math.sqrt(s) || 1 }; };
5752
+ const scores = [];
5753
+ for (let k = -Math.round(maxLag / step); k <= Math.round(maxLag / step); k++) {
5754
+ const d = k * step;
5755
+ // my index i ↔ their time (me.t0 + i*step − d)
5756
+ const shift = (me.t0 - d - them.t0) / step;
5757
+ const j0 = Math.round(shift);
5758
+ const a = Math.max(0, -j0), b = Math.min(me.v.length, them.v.length - j0);
5759
+ if (b - a < 150) { scores.push(-Infinity); continue; } // at least 15 s together
5760
+ const nm = norm(me.v, a, b), nt = norm(them.v, a + j0, b + j0);
5761
+ let s = 0;
5762
+ for (let i = a; i < b; i++) s += (me.v[i] - nm.m) * (them.v[i + j0] - nt.m);
5763
+ const r = s / (nm.s * nt.s);
5764
+ scores.push(r);
5765
+ if (r > best.score) best = { score: r, d };
5766
+ }
5767
+ // second best away from the peak (±1.5 s), and how far the peak stands out
5768
+ const bk = Math.round(best.d / step) + Math.round(maxLag / step);
5769
+ scores.forEach((r, idx) => { if (Math.abs(idx - bk) > 15 && r > second) second = r; });
5770
+ // Sub-step peak (parabola through the best score and its neighbours).
5771
+ const s0 = scores[bk - 1], s2 = scores[bk + 1];
5772
+ if (Number.isFinite(s0) && Number.isFinite(s2)) {
5773
+ const den = s0 - 2 * best.score + s2;
5774
+ if (den < 0) best.d += step * Math.max(-0.5, Math.min(0.5, (s0 - s2) / (2 * den)));
5775
+ }
5776
+ const fin = scores.filter(Number.isFinite);
5777
+ const mean = fin.reduce((s, x) => s + x, 0) / Math.max(1, fin.length);
5778
+ const sd = Math.sqrt(fin.reduce((s, x) => s + (x - mean) ** 2, 0) / Math.max(1, fin.length)) || 1;
5779
+ return { d: best.d, score: best.score, second, z: (best.score - mean) / sd };
5780
+ },
5781
+ async auto() {
5782
+ if (!PRESENCE.others().length) { this._autoMsg = t('tuneNoPeer'); this.paint(); return; }
5783
+ this._autoMsg = t('tuneAsking'); this.paint();
5784
+ const mine = await this._myEnv();
5785
+ const theirs = await new Promise((resolve) => {
5786
+ this._autoWait = resolve;
5787
+ SOCIAL.send('tune', { op: 'envreq' });
5788
+ setTimeout(() => { if (this._autoWait === resolve) { this._autoWait = null; resolve(null); } }, 9000);
5789
+ });
5790
+ if (!mine || !theirs) { this._autoMsg = t('tuneAutoNeed'); this.paint(); return; }
5791
+ let res = null;
5792
+ for (const luma of [false, true]) {
5793
+ const a = this._series(mine, luma), b = this._series(theirs.env, luma);
5794
+ if (!a || !b) continue;
5795
+ const r = this._correlate(a, b, 240);
5796
+ if (Number.isFinite(r.score) && (!res || r.z > res.z)) res = r;
5797
+ }
5798
+ logDebug(`Sync timing: compared ${mine.ts.length} / ${theirs.env.ts.length} samples → ${res ? `lag ${res.d.toFixed(1)}s, r=${res.score.toFixed(2)}, next ${res.second.toFixed(2)}, z=${res.z.toFixed(1)}` : 'nothing comparable'}`, 'info');
5799
+ if (!res || !(res.score > 0.3) || !(res.z >= 4)) { this._autoMsg = t('tuneAutoNone'); this._autoFound = null; this.paint(); return; }
5800
+ // d: my content at time x = theirs at x − d. With both following the room, my
5801
+ // offset must be theirs + d.
5802
+ const want = Math.round((theirs.off + res.d) * 10) / 10;
5803
+ const sure = Math.round(Math.min(0.99, Math.max(0.5, 0.5 + (res.z - 4) * 0.06 + (res.score - 0.3) * 0.4)) * 100);
5804
+ this._autoFound = want;
5805
+ this._autoMsg = t('tuneAutoFound', { s: this.fmt(want), c: sure });
5806
+ this.paint();
5807
+ },
5808
+
5809
+ // ── panel
5810
+ open() {
5811
+ const panel = shadow?.getElementById('tune-panel');
5812
+ if (!panel) return;
5813
+ this._armedByUser = true;
5814
+ this.arm(true);
5815
+ openPanel(panel);
5816
+ this.paint();
5817
+ // Ask the others for their picture while the panel is open.
5818
+ if (SOCIAL.live()) SOCIAL.send('tune', { op: 'peek' });
5819
+ clearInterval(this._paintTimer);
5820
+ this._paintTimer = setInterval(async () => {
5821
+ if (panel.style.display !== 'flex') { clearInterval(this._paintTimer); return; }
5822
+ const s = await this._mySnap();
5823
+ this._mine = s;
5824
+ if (Date.now() - (this._lastPeekReq || 0) > 30000 && SOCIAL.live()) { this._lastPeekReq = Date.now(); SOCIAL.send('tune', { op: 'peek' }); }
5825
+ this.paint();
5826
+ }, 1000);
5827
+ },
5828
+ paint() {
5829
+ const panel = shadow?.getElementById('tune-panel');
5830
+ if (!panel || panel.style.display !== 'flex') return;
5831
+ const off = this.offset();
5832
+ const q = s => panel.querySelector(s);
5833
+ q('.tune-off-val').textContent = this.fmt(off);
5834
+ q('.tune-off-desc').textContent = !off ? t('tuneOffsetZero') : t(off > 0 ? 'tuneAhead' : 'tuneBehind', { s: Math.abs(off).toFixed(1) + 's' });
5835
+ const pic = (box, data, label, waiting) => {
5836
+ const img = box.querySelector('img'), cap = box.querySelector('.tune-cap');
5837
+ if (data && data.img) { img.src = data.img; img.style.visibility = 'visible'; }
5838
+ else img.style.visibility = 'hidden';
5839
+ cap.textContent = label + (data ? ' · ' + formatTime(data.t || 0) : '') + (data && !data.img ? ' · ' + t('tuneNoPicture') : !data && waiting ? ' · ' + t('tuneWaiting') : '');
5840
+ };
5841
+ pic(q('.tune-pic.mine'), this._mine, t('tuneMine'), false);
5842
+ const p = this._peer && Date.now() - this._peer.at < 8000 ? this._peer : null;
5843
+ pic(q('.tune-pic.theirs'), p, p ? p.name : (PRESENCE.others().length ? participantName(PRESENCE.others()[0]) : '—'), !!PRESENCE.others().length);
5844
+ const theirs = [...this._marks.values()].pop();
5845
+ q('.tune-marks').textContent = [this._myMark ? t('tuneMarkMine', { t: formatTime(this._myMark.t) }) : '', theirs ? t('tuneMarkTheirs', { name: theirs.name, t: formatTime(theirs.t) }) : ''].filter(Boolean).join(' · ');
5846
+ const mo = this.markOffset();
5847
+ const ma = q('.tune-mark-apply');
5848
+ ma.style.display = mo === null ? 'none' : '';
5849
+ if (mo !== null) ma.textContent = t('tuneApply') + ' ' + this.fmt(Math.round(mo * 10) / 10);
5850
+ q('.tune-auto-msg').textContent = this._autoMsg || '';
5851
+ const aa = q('.tune-auto-apply');
5852
+ aa.style.display = this._autoFound == null ? 'none' : '';
5853
+ if (this._autoFound != null) aa.textContent = t('tuneApply') + ' ' + this.fmt(this._autoFound);
5854
+ },
5855
+ build() {
5856
+ const body = createEl('div', 'manual-body tune-body');
5857
+ const offRow = createEl('div', 'tune-off');
5858
+ offRow.append(createEl('span', 'tune-off-val', '0.0s'), createEl('span', 'tune-off-desc', ''));
5859
+ const nudges = createEl('div', 'tune-nudges');
5860
+ [-10, -1, -0.1, 0.1, 1, 10].forEach(dv => {
5861
+ const b = createEl('button', 'btn subtle', (dv > 0 ? '+' : '−') + Math.abs(dv) + 's', { type: 'button' });
5862
+ b.onclick = (ev) => { ev.stopPropagation(); this.set(this.offset() + dv, { quiet: true }); };
5863
+ nudges.appendChild(b);
5864
+ });
5865
+ const tools = createEl('div', 'tune-tools');
5866
+ const resync = createEl('button', 'btn', '🔄 ' + t('tuneResync'), { type: 'button' });
5867
+ resync.onclick = () => uiElements.btnSyncStatus?.click();
5868
+ const reset = createEl('button', 'btn subtle', '↺ ' + t('tuneReset'), { type: 'button' });
5869
+ reset.onclick = () => this.set(0);
5870
+ tools.append(resync, reset);
5871
+ const pics = createEl('div', 'tune-pics');
5872
+ ['mine', 'theirs'].forEach(k => {
5873
+ const box = createEl('div', 'tune-pic ' + k);
5874
+ box.append(createEl('img', '', '', { alt: '' }), createEl('div', 'tune-cap'));
5875
+ pics.appendChild(box);
5876
+ });
5877
+ const markBtn = createEl('button', 'btn', t('tuneMarkBtn'), { type: 'button' });
5878
+ markBtn.onclick = () => this.mark();
5879
+ const markApply = createEl('button', 'btn primary tune-mark-apply', t('tuneApply'), { type: 'button' });
5880
+ markApply.onclick = () => { const mo = this.markOffset(); if (mo !== null) this.set(mo); };
5881
+ const autoBtn = createEl('button', 'btn', t('tuneAutoBtn'), { type: 'button' });
5882
+ autoBtn.onclick = () => this.auto();
5883
+ const autoApply = createEl('button', 'btn primary tune-auto-apply', t('tuneApply'), { type: 'button' });
5884
+ autoApply.onclick = () => { if (this._autoFound != null) this.set(this._autoFound); };
5885
+ const h = text => createEl('div', 'field-label', text);
5886
+ body.append(
5887
+ h(t('tuneOffset')), offRow, nudges, tools, createEl('div', 'trans-help', t('tuneHelp')),
5888
+ h(t('tuneCompare')), pics,
5889
+ h(t('tuneMark')), createEl('div', 'trans-help', t('tuneMarkHint')), markBtn, createEl('div', 'tune-marks trans-help'), markApply,
5890
+ h(t('tuneAuto')), createEl('div', 'trans-help', t('tuneAutoHint')), autoBtn, createEl('div', 'tune-auto-msg trans-help'), autoApply
5891
+ );
5892
+ return body;
5893
+ }
5894
+ };
5895
+
5432
5896
  // ───────────────────────── Fine sync
5433
5897
  // Heartbeats alone left devices up to a quarter of a second apart (corrections only
5434
5898
  // started beyond 0.25 s and only when a heartbeat arrived). Now every follower compares
@@ -5477,7 +5941,7 @@
5477
5941
  if (this._steps) { this._steps = 0; if (!idle) RATE.apply(v, room ? room.rate : RATE.base(v)); }
5478
5942
  return;
5479
5943
  }
5480
- const expected = Math.min(room.time + (getSyncedTime() - room.timestamp) / 1000 * room.rate + this.offset(), (v.duration || Infinity) - 0.1);
5944
+ const expected = Math.min(room.time + TUNE.offset() + (getSyncedTime() - room.timestamp) / 1000 * room.rate + this.offset(), (v.duration || Infinity) - 0.1);
5481
5945
  const drift = expected - this.mediaTime(v);
5482
5946
  this.drift = drift;
5483
5947
  this._ema = Math.abs(drift - this._ema) > 0.5 ? drift : this._ema * 0.6 + drift * 0.4;
@@ -5514,6 +5978,17 @@
5514
5978
  }
5515
5979
  };
5516
5980
 
5981
+ // Sync timing keeps a short history of what was played while in a room (on a computer
5982
+ // all the time; on phones only once the timing panel was opened, to save battery).
5983
+ if (IS_TOP) setInterval(() => {
5984
+ try {
5985
+ const want = STATE.handshakeVerified && (!IS_TOUCH || TUNE._armedByUser) && !!(STATE.video || STATE.cinemaIframe);
5986
+ if (want && !TUNE._armed) { TUNE._armed = true; TUNE.arm(true); }
5987
+ else if (!want && TUNE._armed) { TUNE._armed = false; TUNE.arm(false); }
5988
+ else if (want && STATE.video && TUNE._rec && TUNE._rec.v !== STATE.video) TUNE.arm(true);
5989
+ } catch (_) { }
5990
+ }, 3000);
5991
+
5517
5992
  // The shared clock drifts a little over a long movie: measure it again every 10 minutes.
5518
5993
  if (IS_TOP) setInterval(() => { if (STATE.handshakeVerified && !document.hidden) syncServerClock(); }, 600000);
5519
5994
 
@@ -5821,7 +6296,7 @@
5821
6296
  if (STATE._presenceTimer) return;
5822
6297
  const beat = () => {
5823
6298
  if (ydoc && yPresence && STATE.role !== 'IDLE' && !STATE.isReadOnly) {
5824
- ydoc.transact(() => yPresence.set(STATE.userId, { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden }), 'local');
6299
+ ydoc.transact(() => yPresence.set(STATE.userId, PROFILE.value()), 'local');
5825
6300
  }
5826
6301
  PRESENCE.refresh();
5827
6302
  };
@@ -5978,6 +6453,9 @@
5978
6453
  name: self ? (STATE.nickname || t('you')) : (p?.nick || 'ID:' + String(uid).slice(0, 3)),
5979
6454
  color: safeColor(self ? STATE.color : p?.color),
5980
6455
  viewer: self ? !!STATE.isViewer : !!p?.viewer,
6456
+ av: safeEmoji(self ? PROFILE.avatar() : p?.av),
6457
+ st: String((self ? PROFILE.status() : p?.st) || '').slice(0, 40),
6458
+ muted: !self && SAFETY.muted.has(uid),
5981
6459
  away: !self && !!p?.hid,
5982
6460
  oldVer: !self && !!(p?.v && p.v !== NXU_VERSION)
5983
6461
  };
@@ -5987,7 +6465,7 @@
5987
6465
  }
5988
6466
  function renderRoster(box, max = 4) {
5989
6467
  const list = roomRoster();
5990
- const sig = max + '|' + list.map(m => [m.uid, m.name, m.color, m.viewer, m.away, m.oldVer].join(',')).join(';');
6468
+ const sig = max + '|' + list.map(m => [m.uid, m.name, m.color, m.viewer, m.away, m.oldVer, m.av, m.st, m.muted].join(',')).join(';');
5991
6469
  if (box._rosterSig === sig) return list;
5992
6470
  box._rosterSig = sig;
5993
6471
  box.replaceChildren();
@@ -5995,11 +6473,15 @@
5995
6473
  const chip = createEl('span', 'nx-who' + (m.away ? ' away' : '') + (m.self ? ' me' : ''));
5996
6474
  const dot = createEl('i', 'nx-who-dot');
5997
6475
  dot.style.background = m.color;
5998
- chip.append(dot, createEl('span', 'nx-who-name', m.name + (m.self && STATE.nickname ? ' ' + t('meTag') : '')));
6476
+ chip.append(dot);
6477
+ if (m.av) chip.append(createEl('span', 'nx-who-av', m.av));
6478
+ chip.append(createEl('span', 'nx-who-name', m.name + (m.self && STATE.nickname ? ' ' + t('meTag') : '')));
6479
+ if (m.muted) chip.append(createEl('span', 'nx-who-tag', '🔇'));
6480
+ if (m.st && max > 4) chip.append(createEl('span', 'nx-who-st', m.st));
5999
6481
  if (m.viewer) chip.append(createEl('span', 'nx-who-tag', '👀'));
6000
6482
  if (m.away) chip.append(createEl('span', 'nx-who-tag', '💤'));
6001
6483
  if (m.oldVer) chip.append(createEl('span', 'nx-who-tag', '⚠️'));
6002
- chip.title = [m.name, m.viewer && t('whoViewer'), m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
6484
+ chip.title = [m.name, m.st, m.viewer && t('whoViewer'), m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
6003
6485
  box.appendChild(chip);
6004
6486
  });
6005
6487
  if (list.length > max) box.appendChild(createEl('span', 'nx-who more', '+' + (list.length - max)));
@@ -6130,9 +6612,130 @@
6130
6612
  }
6131
6613
  }
6132
6614
 
6615
+ // ───────────────────────── Bookmark library (every site, kept in the userscript manager)
6616
+ // Each bookmark remembers the page, the moment and the title; opening one goes back to
6617
+ // that page and that moment. A live stream has no moment to return to: its bookmark
6618
+ // plays the stream right away (the stream's own address when the page exposed one).
6619
+ const LIBRARY = {
6620
+ KEY: 'nxu_bm_lib',
6621
+ MAX: 400,
6622
+ pageUrl() { return location.href.split('#')[0]; },
6623
+ all() { const v = STORE.get(this.KEY, []); return Array.isArray(v) ? v.filter(b => b && typeof b.url === 'string' && /^https?:/i.test(b.url)) : []; },
6624
+ save(list) { STORE.set(this.KEY, list.slice(0, this.MAX)); },
6625
+ // The stream address of a live channel, when the page loaded one directly (HLS / DASH).
6626
+ streamUrl(info) {
6627
+ try {
6628
+ const v = info?.kind === 'video' ? info.el : null;
6629
+ const src = v?.currentSrc || '';
6630
+ if (/^https?:/i.test(src)) return src;
6631
+ const hits = performance.getEntriesByType('resource').map(r => r.name).filter(n => /\.(m3u8|mpd)(\?|$)/i.test(n));
6632
+ return hits.length ? hits[hits.length - 1] : '';
6633
+ } catch (_) { return ''; }
6634
+ },
6635
+ add(info) {
6636
+ const live = !!info.live;
6637
+ const title = String(document.title || HOST).replace(/\s+/g, ' ').trim().slice(0, 120);
6638
+ const entry = {
6639
+ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
6640
+ url: this.pageUrl(), host: HOST, title, live,
6641
+ time: live ? 0 : Math.max(0, Math.round((info.time || 0) * 10) / 10),
6642
+ dur: Number.isFinite(info.duration) ? Math.round(info.duration) : 0,
6643
+ stream: live ? this.streamUrl(info).slice(0, 600) : '',
6644
+ ts: Date.now()
6645
+ };
6646
+ const list = this.all().filter(b => !(b.url === entry.url && Math.abs((b.time || 0) - entry.time) < 2 && !!b.live === live));
6647
+ list.unshift(entry);
6648
+ this.save(list);
6649
+ return entry;
6650
+ },
6651
+ remove(id) { this.save(this.all().filter(b => b.id !== id)); },
6652
+ // Opening: on this page it simply jumps; elsewhere the moment is handed to the page
6653
+ // that opens (through the manager's storage, so no address is changed).
6654
+ open(b, newTab = false) {
6655
+ if (b.url === this.pageUrl() && !newTab) {
6656
+ if (b.live) { JUMP.playLive(); return; }
6657
+ seekMedia(b.time); showToast(t('bmJumped', { time: formatTime(b.time) }));
6658
+ return;
6659
+ }
6660
+ STORE.set('nxu_pending_jump', { url: b.url, time: b.time, live: !!b.live, at: Date.now() });
6661
+ showToast(t('bmOpening'));
6662
+ const target = b.live && b.stream && /\.(mp4|webm|m3u8)(\?|$)/i.test(b.stream) && /iP(hone|ad|od)|Macintosh.*Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) ? b.stream : b.url;
6663
+ if (newTab) window.open(target, '_blank', 'noopener');
6664
+ else location.href = target;
6665
+ }
6666
+ };
6667
+ // Applies a bookmark opened from the library once this page's media is ready.
6668
+ const JUMP = {
6669
+ _pending: null,
6670
+ init() {
6671
+ if (!IS_TOP) return;
6672
+ const p = STORE.get('nxu_pending_jump', null);
6673
+ if (!p || typeof p.url !== 'string' || Date.now() - (p.at || 0) > 120000) return;
6674
+ if (p.url !== LIBRARY.pageUrl()) return;
6675
+ STORE.set('nxu_pending_jump', null);
6676
+ this._pending = { ...p, until: Date.now() + 60000 };
6677
+ },
6678
+ playLive() {
6679
+ const v = STATE.video;
6680
+ try { if (v) { v.muted = false; MEDIA_SAFE.play(v); } else applyMediaCommand('play'); } catch (_) { }
6681
+ if (!STATE.isCinema) try { CINEMA.set(true, { silent: true }); } catch (_) { }
6682
+ showToast(t('bmLiveOpened'));
6683
+ },
6684
+ tick() {
6685
+ const p = this._pending;
6686
+ if (!p) return;
6687
+ if (Date.now() > p.until) { this._pending = null; return; }
6688
+ const info = currentMediaInfo();
6689
+ if (!info) return;
6690
+ if (info.kind === 'video' && info.el.readyState < 1) return;
6691
+ this._pending = null;
6692
+ if (p.live) { this.playLive(); return; }
6693
+ seekMedia(p.time);
6694
+ try { if (info.kind === 'video' && info.paused) MEDIA_SAFE.play(info.el); } catch (_) { }
6695
+ showToast(t('bmJumped', { time: formatTime(p.time) }));
6696
+ }
6697
+ };
6698
+ function buildBookmarkPanel() {
6699
+ const body = createEl('div', 'manual-body nx-bm');
6700
+ const addBtn = createEl('button', 'btn primary', '📌 ' + t('bmAddHere'), { type: 'button', id: 'nxu-bm-add' });
6701
+ const search = createEl('input', 'nx-compose-input nx-bm-search', '', { type: 'search', placeholder: t('bmSearch'), autocomplete: 'off' });
6702
+ const list = createEl('div', 'nx-bm-list');
6703
+ const render = () => {
6704
+ const q = search.value.trim().toLowerCase();
6705
+ const here = LIBRARY.pageUrl();
6706
+ addBtn.style.display = currentMediaInfo() ? '' : 'none';
6707
+ const items = LIBRARY.all().filter(b => !q || (b.title + ' ' + b.host).toLowerCase().includes(q));
6708
+ if (!items.length) { list.replaceChildren(createEl('div', 'trans-help', t('bmEmpty'))); return; }
6709
+ list.replaceChildren(...items.map(b => {
6710
+ const row = createEl('div', 'nx-bm-item');
6711
+ const link = createEl('a', 'nx-bm-link', '', { href: b.url, rel: 'noopener', title: b.url });
6712
+ const when = b.live ? createEl('span', 'nx-bm-live', '● ' + t('bmLive')) : createEl('span', 'nx-bm-time', formatTime(b.time) + (b.dur ? ' / ' + formatTime(b.dur) : ''));
6713
+ const meta = createEl('span', 'nx-bm-meta', (b.url === here ? t('bmThisPage') : b.host) + ' · ' + new Date(b.ts).toLocaleDateString());
6714
+ link.append(when, createEl('span', 'nx-bm-title', b.title || b.host), meta);
6715
+ link.addEventListener('click', (ev) => {
6716
+ ev.preventDefault(); ev.stopPropagation();
6717
+ LIBRARY.open(b, ev.ctrlKey || ev.metaKey || ev.button === 1);
6718
+ });
6719
+ const copy = createEl('button', 'nx-bm-act', '🔗', { type: 'button', title: t('bmCopy') });
6720
+ copy.onclick = (ev) => { ev.stopPropagation(); try { navigator.clipboard.writeText(b.live && b.stream ? b.stream : b.url); showToast(t('bmCopied')); } catch (_) { } };
6721
+ const del = createEl('button', 'nx-bm-act', '✕', { type: 'button', title: t('bmDelete') });
6722
+ del.onclick = (ev) => { ev.stopPropagation(); LIBRARY.remove(b.id); render(); };
6723
+ row.append(link, copy, del);
6724
+ return row;
6725
+ }));
6726
+ };
6727
+ addBtn.onclick = () => { addBookmark(); render(); };
6728
+ search.addEventListener('input', render);
6729
+ search.addEventListener('keydown', (e) => e.stopPropagation());
6730
+ body.append(addBtn, search, list);
6731
+ body.render = render;
6732
+ return body;
6733
+ }
6734
+
6133
6735
  function addBookmark(label = '') {
6134
6736
  const info = currentMediaInfo();
6135
6737
  if (!info) { showToast(t('noVideo')); return; }
6738
+ try { LIBRARY.add(info); } catch (_) { }
6136
6739
  const bm = { time: info.time || 0, label, color: STATE.color, userId: STATE.userId, ts: Date.now() };
6137
6740
  if (ydoc && yBookmarks && STATE.handshakeVerified) yBookmarks.push([bm]);
6138
6741
  else { STATE.bookmarks.push(bm); renderBookmarkPins(); }
@@ -6682,6 +7285,92 @@
6682
7285
  return select;
6683
7286
  }
6684
7287
 
7288
+ // ⚙️ Settings: profile, my reactions, playback, what reaches me from others, advanced.
7289
+ function buildSettingsPanel(parts) {
7290
+ const body = createEl('div', 'manual-body settings-body nx-settings');
7291
+ const section = (icon, title) => {
7292
+ const sec = createEl('details', 'nx-set-sec');
7293
+ sec.append(createEl('summary', 'nx-set-head', icon + ' ' + title));
7294
+ body.appendChild(sec);
7295
+ return sec;
7296
+ };
7297
+ const toggle = (label, get, set) => {
7298
+ const row = createEl('label', 'trans-row nx-set-row');
7299
+ const box = createEl('input', 'trans-check', '', { type: 'checkbox' });
7300
+ box.checked = !!get();
7301
+ box.addEventListener('change', () => set(!!box.checked));
7302
+ row.append(createEl('span', '', label), box);
7303
+ return row;
7304
+ };
7305
+ // Profile
7306
+ const prof = section('👤', t('setProfile'));
7307
+ prof.open = true;
7308
+ prof.appendChild(PROFILE.editor());
7309
+ const avRow = createEl('div', 'nx-av-row');
7310
+ const paintAv = () => avRow.querySelectorAll('.nx-av').forEach(b => b.classList.toggle('on', b.dataset.av === PROFILE.avatar()));
7311
+ ['', ...PROFILE.AVATARS].forEach(a => {
7312
+ const b = createEl('button', 'nx-av', a || '∅', { type: 'button', 'aria-label': a || 'none' });
7313
+ b.dataset.av = a;
7314
+ b.onclick = (ev) => { ev.stopPropagation(); PROFILE.setAvatar(a); paintAv(); };
7315
+ avRow.appendChild(b);
7316
+ });
7317
+ paintAv();
7318
+ const status = createEl('input', 'nx-compose-input nx-status-input', '', { type: 'text', maxlength: '40', placeholder: t('setStatusPh'), autocomplete: 'off' });
7319
+ status.value = PROFILE.status();
7320
+ status.addEventListener('input', () => PROFILE.setStatus(status.value));
7321
+ prof.append(createEl('div', 'field-label', t('setAvatar')), avRow, createEl('div', 'field-label', t('setStatus')), status);
7322
+ // My reactions
7323
+ const reac = section('😀', t('setReactions'));
7324
+ const slots = createEl('div', 'nx-react-slots');
7325
+ let pick = 0;
7326
+ const PALETTE = ['❤️', '🔥', '👏', '🤣', '😱', '😍', '🥺', '🤯', '👀', '💀', '🙏', '👍', '🎉', '💯', '😴', '🤔', '🍿', '😂', '😭', '😡', '💦', '🍪', '☕', '😘'];
7327
+ const paintSlots = () => {
7328
+ slots.replaceChildren(...REACTIONS.list().map((em, i) => {
7329
+ const b = createEl('button', 'nx-react-slot' + (i === pick ? ' on' : ''), em, { type: 'button' });
7330
+ b.onclick = (ev) => { ev.stopPropagation(); pick = i; paintSlots(); };
7331
+ return b;
7332
+ }));
7333
+ };
7334
+ const pal = createEl('div', 'nx-react-pal');
7335
+ PALETTE.forEach(em => {
7336
+ const b = createEl('button', 'nx-react-pick', em, { type: 'button' });
7337
+ b.onclick = (ev) => { ev.stopPropagation(); if (REACTIONS.set(pick, em)) { pick = (pick + 1) % 8; paintSlots(); } };
7338
+ pal.appendChild(b);
7339
+ });
7340
+ const custom = createEl('input', 'nx-compose-input nx-react-custom', '', { type: 'text', maxlength: '16', placeholder: t('setEmojiPh'), autocomplete: 'off' });
7341
+ custom.addEventListener('input', () => { if (REACTIONS.set(pick, custom.value)) { custom.value = ''; pick = (pick + 1) % 8; paintSlots(); } });
7342
+ const resetBtn = createEl('button', 'btn subtle', '↺ ' + t('setReactionsReset'), { type: 'button' });
7343
+ resetBtn.onclick = () => { REACTIONS.reset(); pick = 0; paintSlots(); };
7344
+ paintSlots();
7345
+ reac.append(slots, createEl('div', 'trans-help', t('setReactionsHint')), pal, custom, resetBtn);
7346
+ // Playback
7347
+ const play = section('🎬', t('setPlayback'));
7348
+ play.append(parts.autoCinema, parts.adGuard, toggle(t('setAutoNext'), () => NEXT_EP.enabled(), on => STORE.set('nxu_auto_next', on)));
7349
+ // Watching together: what reaches me, and from whom
7350
+ const tog = section('🛡️', t('setTogether'));
7351
+ [['react', 'setRecvReact'], ['nudge', 'setRecvNudge'], ['ink', 'setRecvInk'], ['chat', 'setRecvChat'], ['ping', 'setRecvPing']].forEach(([k, label]) => tog.appendChild(toggle(t(label), () => SAFETY.receive(k), on => SAFETY.set(k, on))));
7352
+ const people = createEl('div', 'nx-people');
7353
+ const paintPeople = () => {
7354
+ const others = roomRoster().filter(m => !m.self);
7355
+ if (!others.length) { people.replaceChildren(createEl('div', 'trans-help', t('setNobody'))); return; }
7356
+ people.replaceChildren(...others.map(m => {
7357
+ const row = createEl('div', 'nx-person');
7358
+ const dot = createEl('i', 'nx-who-dot'); dot.style.background = m.color;
7359
+ const b = createEl('button', 'btn subtle', SAFETY.muted.has(m.uid) ? '👁 ' + t('setUnmute') : '🔇 ' + t('setMute'), { type: 'button' });
7360
+ b.onclick = (ev) => { ev.stopPropagation(); SAFETY.toggleMute(m.uid); paintPeople(); updatePresenceUI(); };
7361
+ row.append(dot, createEl('span', 'nx-person-name', (m.av ? m.av + ' ' : '') + m.name), b);
7362
+ return row;
7363
+ }));
7364
+ };
7365
+ tog.addEventListener('toggle', () => { if (tog.open) paintPeople(); });
7366
+ tog.append(createEl('div', 'field-label', t('setPeople')), people, createEl('div', 'trans-help', t('setMutedHint')));
7367
+ // Advanced
7368
+ const adv = section('🔧', t('setAdvanced'));
7369
+ adv.append(parts.subLog, parts.debug, parts.idleRow, parts.hideSite);
7370
+ body.refreshPeople = paintPeople;
7371
+ return body;
7372
+ }
7373
+
6685
7374
  function buildTranslationSettings() {
6686
7375
  const body = createEl('div', 'manual-body settings-body');
6687
7376
  const label = text => createEl('div', 'field-label', text);
@@ -6922,6 +7611,9 @@
6922
7611
  .nx-who-dot { flex:none; width:8px; height:8px; border-radius:50%; box-shadow:0 0 5px currentColor; }
6923
7612
  .nx-who-name { overflow:hidden; text-overflow:ellipsis; }
6924
7613
  .nx-who-tag { font-size:10px; }
7614
+ .nx-who-av { font-size:12px; line-height:1; }
7615
+ .nx-who-st { font-weight:500; opacity:0.7; margin-left:4px; overflow:hidden; text-overflow:ellipsis; }
7616
+ .nx-talk-avatar.emoji { background:rgba(255,255,255,0.12) !important; font-size:16px; }
6925
7617
  .dock { position:absolute; background:var(--glass-strong); border-radius:16px; padding:10px; display:flex; flex-direction:column; gap:6px; pointer-events:none; opacity:0; border:1px solid rgba(255,255,255,0.1);
6926
7618
  transition:opacity 0.25s ease, transform 0.25s ease; box-shadow:0 10px 30px rgba(0,0,0,0.35); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); z-index:90; overflow-y:auto; text-shadow:0 1px 2px rgba(0,0,0,0.8); overflow-x:hidden; width:clamp(150px, 40vw, 190px); width:clamp(150px, 40cqw, 190px); }
6927
7619
  .dock.open { opacity:1; pointer-events:auto; border-color:rgba(0,230,118,0.3); }
@@ -6938,7 +7630,9 @@
6938
7630
  border:1px solid rgba(255,255,255,0.18); overflow:hidden; box-shadow:0 15px 40px rgba(0,0,0,0.6); z-index:105; transition:opacity 0.4s ease;
6939
7631
  width:min(420px, calc(100vw - 24px)); width:min(420px, calc(100cqw - 24px)); max-height:calc(100vh - 24px); max-height:calc(100cqh - 24px); }
6940
7632
  #chat-panel, #sub-log-panel, #debug-panel { height:min(520px, calc(100vh - 24px)); height:min(520px, calc(100cqh - 24px)); }
6941
- #manual-modal, #trans-modal { overflow-y:auto; }
7633
+ #manual-modal, #trans-modal, #settings-modal, #bm-panel, #tune-panel, #os-panel { overflow-y:auto; }
7634
+ /* Windows you read and fill in stay legible over a busy picture. */
7635
+ #manual-modal, #trans-modal, #settings-modal, #bm-panel, #tune-panel, #os-panel, #debug-panel { background:rgba(16,20,26,0.9); }
6942
7636
  .drag-header { background:rgba(0,0,0,0.3); padding:10px 14px; font-size:13px; color:#eee; font-weight:700; cursor:grab; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid rgba(255,255,255,0.06); user-select:none; touch-action:none; flex:0 0 auto; }
6943
7637
  .header-controls { display:flex; gap:10px; align-items:center; }
6944
7638
  .pin-btn, .close-btn { background:transparent; border:none; cursor:pointer; color:#fff; font-size:15px; line-height:1; padding:0; opacity:0.6; }
@@ -6989,6 +7683,68 @@
6989
7683
  .trans-check { width:18px; height:18px; accent-color:var(--accent); }
6990
7684
  .trans-help { font-size:11px; line-height:1.45; color:rgba(255,255,255,0.55); }
6991
7685
  .trans-help.center { text-align:center; margin-top:4px; }
7686
+ /* NexusSync subtitles: soft plate, generous line height, clear of the controls. */
7687
+ .nx-xsub { position:absolute; left:50%; bottom:9%; transform:translateX(-50%); width:min(92%, 1100px); display:flex; flex-direction:column; align-items:center; gap:4px; z-index:66; pointer-events:none; opacity:0; transition:opacity 0.18s ease, bottom 0.3s ease; --xs:1; }
7688
+ .nx-xsub.on { opacity:1; }
7689
+ .nexus-container.cinema-nexus:not(.chrome-idle) .nx-xsub { bottom:calc(104px + env(safe-area-inset-bottom, 0px)); }
7690
+ .nx-xsub-line { display:inline-block; max-width:100%; padding:0.12em 0.55em; border-radius:0.35em; background:rgba(8,10,14,0.62); color:#fff; text-align:center; white-space:pre-line; overflow-wrap:anywhere;
7691
+ font:600 calc(clamp(15px, 2.6cqw, 34px) * var(--xs)) / 1.32 system-ui, -apple-system, "Apple SD Gothic Neo", "Pretendard", "Segoe UI", sans-serif; letter-spacing:0.01em; text-shadow:0 1px 2px rgba(0,0,0,0.85), 0 0 8px rgba(0,0,0,0.35); }
7692
+ .nx-sub-suggest { position:absolute; right:calc(16px + env(safe-area-inset-right, 0px)); bottom:calc(112px + env(safe-area-inset-bottom, 0px)); z-index:75; border:1px solid rgba(255,255,255,0.18); border-radius:99px; padding:8px 14px; background:rgba(16,20,26,0.82); color:#fff; font:inherit; font-size:13px; font-weight:700; cursor:pointer; opacity:0; transform:translateY(8px); transition:opacity 0.3s ease, transform 0.3s ease; pointer-events:auto; }
7693
+ .nx-sub-suggest.in { opacity:1; transform:none; }
7694
+ .cc-menu-adjust, .cc-slider { display:flex; align-items:center; gap:8px; padding:6px 10px; font-size:12.5px; }
7695
+ .cc-adj-label { flex:1; opacity:0.8; white-space:nowrap; }
7696
+ .cc-adj { width:auto !important; padding:4px 9px !important; background:rgba(255,255,255,0.1) !important; border-radius:7px !important; font-variant-numeric:tabular-nums; }
7697
+ .cc-adj-val { min-width:46px; text-align:center; font-variant-numeric:tabular-nums; font-weight:700; }
7698
+ .cc-slider input { width:110px; accent-color:var(--cc-accent); }
7699
+ .cc-menu-note { font-size:11.5px; opacity:0.6; padding:4px 10px 6px; max-width:240px; }
7700
+ .os-body { gap:8px; }
7701
+ .os-row { display:grid; grid-template-columns:1fr 1fr 1.4fr; gap:6px; }
7702
+ .os-results { display:flex; flex-direction:column; gap:4px; max-height:min(46vh, 380px); overflow-y:auto; }
7703
+ .os-item { display:flex; flex-direction:column; align-items:flex-start; gap:2px; text-align:left; padding:8px 10px; border-radius:10px; border:0; background:rgba(255,255,255,0.06); color:inherit; font:inherit; cursor:pointer; }
7704
+ .os-item:hover { background:rgba(255,255,255,0.12); }
7705
+ .os-item.busy { opacity:0.6; }
7706
+ .os-name { font-size:12.5px; font-weight:700; word-break:break-all; }
7707
+ .os-meta { font-size:11px; opacity:0.65; }
7708
+ .tune-body { gap:7px; }
7709
+ .tune-off { display:flex; align-items:baseline; gap:10px; }
7710
+ .tune-off-val { font-size:24px; font-weight:800; font-variant-numeric:tabular-nums; color:var(--accent); }
7711
+ .tune-off-desc { font-size:12px; opacity:0.75; }
7712
+ .tune-nudges { display:grid; grid-template-columns:repeat(6, 1fr); gap:4px; }
7713
+ .tune-nudges .btn { padding:8px 0; font-variant-numeric:tabular-nums; }
7714
+ .tune-tools { display:grid; grid-template-columns:2fr 1fr; gap:6px; }
7715
+ .tune-pics { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
7716
+ .tune-pic { position:relative; aspect-ratio:16/9; border-radius:10px; overflow:hidden; background:#000; border:1px solid rgba(255,255,255,0.12); }
7717
+ .tune-pic img { width:100%; height:100%; object-fit:cover; display:block; }
7718
+ .tune-cap { position:absolute; left:0; right:0; bottom:0; padding:3px 6px; font-size:11px; font-weight:700; background:linear-gradient(transparent, rgba(0,0,0,0.75)); }
7719
+ .nx-bm { gap:8px; }
7720
+ .nx-bm-list { display:flex; flex-direction:column; gap:5px; max-height:min(52vh, 420px); overflow-y:auto; }
7721
+ .nx-bm-item { display:flex; align-items:stretch; gap:4px; }
7722
+ .nx-bm-link { flex:1; min-width:0; display:grid; grid-template-columns:auto 1fr; column-gap:8px; row-gap:1px; padding:7px 9px; border-radius:10px; background:rgba(255,255,255,0.06); color:inherit; text-decoration:none; }
7723
+ .nx-bm-link:hover { background:rgba(255,255,255,0.12); }
7724
+ .nx-bm-time, .nx-bm-live { grid-row:span 2; align-self:center; font-variant-numeric:tabular-nums; font-weight:800; font-size:12px; color:var(--accent); }
7725
+ .nx-bm-live { color:#ff5252; }
7726
+ .nx-bm-title { font-size:12.5px; font-weight:700; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
7727
+ .nx-bm-meta { font-size:11px; opacity:0.6; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
7728
+ .nx-bm-act { width:34px; border:0; border-radius:9px; background:rgba(255,255,255,0.06); color:inherit; cursor:pointer; font-size:13px; padding:0; }
7729
+ .nx-settings { gap:8px; }
7730
+ .nx-set-sec { border:1px solid rgba(255,255,255,0.1); border-radius:12px; background:rgba(0,0,0,0.16); padding:2px 10px; }
7731
+ .nx-set-sec[open] { padding-bottom:10px; }
7732
+ .nx-set-head { cursor:pointer; font-weight:800; font-size:13px; padding:9px 0; list-style:none; }
7733
+ .nx-set-head::-webkit-details-marker { display:none; }
7734
+ .nx-set-head::after { content:'▾'; float:right; opacity:0.6; }
7735
+ .nx-set-sec[open] > .nx-set-head::after { content:'▴'; }
7736
+ .nx-set-sec > :not(summary) { margin-top:6px; }
7737
+ .nx-set-row { display:flex; align-items:center; justify-content:space-between; gap:10px; font-size:12.5px; padding:4px 0; }
7738
+ .nx-av-row, .nx-react-pal { display:flex; flex-wrap:wrap; gap:4px; }
7739
+ .nx-av, .nx-react-pick { width:34px; height:34px; border-radius:9px; border:1px solid rgba(255,255,255,0.12); background:rgba(255,255,255,0.06); font-size:18px; cursor:pointer; padding:0; color:inherit; }
7740
+ .nx-av.on { border-color:var(--accent); background:var(--glass-active); }
7741
+ .nx-react-slots { display:grid; grid-template-columns:repeat(8, 1fr); gap:4px; }
7742
+ .nx-react-slot { height:40px; border-radius:10px; border:1px solid rgba(255,255,255,0.14); background:rgba(255,255,255,0.08); font-size:20px; cursor:pointer; padding:0; }
7743
+ .nx-react-slot.on { border-color:var(--accent); box-shadow:0 0 0 2px rgba(0,230,118,0.35); }
7744
+ .nx-people { display:flex; flex-direction:column; gap:4px; }
7745
+ .nx-person { display:flex; align-items:center; gap:8px; font-size:12.5px; }
7746
+ .nx-person .btn { width:auto; margin-left:auto; }
7747
+ .nx-person-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
6992
7748
  .seg { display:flex; gap:6px; }
6993
7749
  .seg-btn { flex:1; min-height:38px; padding:8px 6px; border-radius:10px; border:1px solid rgba(255,255,255,0.16); background:rgba(255,255,255,0.06); color:inherit; font:inherit; font-size:13px; font-weight:700; cursor:pointer; }
6994
7750
  .seg-btn.on { background:rgba(124,77,255,0.38); border-color:rgba(160,130,255,0.95); }
@@ -7409,6 +8165,7 @@
7409
8165
  const fab = createEl('button', 'fab', '⚙️', { title: 'NexusSync' });
7410
8166
  const reactPill = createEl('div');
7411
8167
  reactPill.id = 'reaction-pill';
8168
+ CONFIG.emojis = REACTIONS.list();
7412
8169
  CONFIG.emojis.forEach(emoji => {
7413
8170
  const btn = createEl('button', 'react-btn', emoji);
7414
8171
  btn.onclick = () => { pressFx(btn, emoji); handleLocalReactionClick(emoji); };
@@ -7453,6 +8210,7 @@
7453
8210
  const btnSubLog = mk('', '📝 ' + t('subLog'));
7454
8211
  const btnDebug = mk('', '🐛 ' + t('debug'));
7455
8212
  const btnHideSite = createEl('button', 'btn subtle', '🙈 ' + t('hideOnSite'), { title: t('hideOnSiteTitle') });
8213
+ const btnSettings = mk('nxu-settings', '⚙️ ' + t('settings'));
7456
8214
  [btnLink, btnSyncStatus, btnInvite, btnCinema, btnPiP, btnRate, btnDraw, btnBookmark, btnChat].forEach(b => { b.style.display = 'none'; });
7457
8215
  btnSubLog.style.display = 'none';
7458
8216
 
@@ -7546,7 +8304,35 @@
7546
8304
  idleVal.textContent = idleSlider.value + 's';
7547
8305
  idleSlider.addEventListener('input', () => { idleVal.textContent = idleSlider.value + 's'; STORE.set('nxu_idle_timeout', +idleSlider.value); });
7548
8306
  idleRow.append(createEl('span', '', '⏱️ ' + t('uiHide')), idleSlider, idleVal, createEl('span', '', 'v' + NXU_VERSION, { style: 'margin-left:6px;opacity:0.6;' }));
7549
- debugPanel.append(debugHeader, idleRow, debugContent, debugJumpBtn);
8307
+ debugPanel.append(debugHeader, debugContent, debugJumpBtn);
8308
+
8309
+ // Sync timing (offset between different versions of a movie)
8310
+ const tunePanel = createEl('div', 'window-frame');
8311
+ tunePanel.id = 'tune-panel';
8312
+ const tuneHeader = createWindowHeader('🎯 ' + t('tuneTitle'), [{ className: 'close-btn', text: '✖' }]);
8313
+ tunePanel.append(tuneHeader, TUNE.build());
8314
+ const btnTune = mk('nxu-tune', '🎯 ' + t('tuneMenu'));
8315
+ btnTune.style.display = 'none';
8316
+
8317
+ // Find subtitles (OpenSubtitles)
8318
+ const osPanel = createEl('div', 'window-frame');
8319
+ osPanel.id = 'os-panel';
8320
+ const osHeader = createWindowHeader('💬 ' + t('osTitle'), [{ className: 'close-btn', text: '✖' }]);
8321
+ osPanel.append(osHeader, OPENSUBS.build());
8322
+
8323
+ // Bookmarks (every site)
8324
+ const bmPanel = createEl('div', 'window-frame');
8325
+ bmPanel.id = 'bm-panel';
8326
+ const bmHeader = createWindowHeader('📌 ' + t('bmLibrary'), [{ className: 'close-btn', text: '✖' }]);
8327
+ const bmBody = buildBookmarkPanel();
8328
+ bmPanel.append(bmHeader, bmBody);
8329
+
8330
+ // Settings (things that are set once live here, not in the menu)
8331
+ const settingsModal = createEl('div', 'window-frame');
8332
+ settingsModal.id = 'settings-modal';
8333
+ const settingsHeader = createWindowHeader('⚙️ ' + t('settings'), [{ className: 'close-btn', text: '✖' }]);
8334
+ const settingsBody = buildSettingsPanel({ autoCinema: btnAutoCinema, adGuard: btnAdGuard, subLog: btnSubLog, debug: btnDebug, idleRow, hideSite: btnHideSite });
8335
+ settingsModal.append(settingsHeader, settingsBody);
7550
8336
 
7551
8337
  const drawCanvas = createEl('canvas');
7552
8338
  drawCanvas.id = 'draw-canvas';
@@ -7555,9 +8341,11 @@
7555
8341
  toast.setAttribute('role', 'status');
7556
8342
 
7557
8343
  // Sketching and chat live in the reaction bar (🖍️ 💬); the menu does not repeat them.
7558
- dock.append(btnFindMedia, btnLink, btnInvite, btnSyncStatus, btnCinema, btnAutoCinema, btnAdGuard, btnPiP, btnRate, btnBookmark, btnTranslate, btnSubLog, btnDebug, btnHideSite);
8344
+ // The menu keeps only what is used while watching; speed and PiP live in the cinema
8345
+ // controls, and everything that is set once lives in ⚙️ Settings.
8346
+ dock.append(btnFindMedia, btnLink, btnInvite, btnTune, btnCinema, btnBookmark, btnTranslate, btnSettings);
7559
8347
  uiWrapper.append(dock, reactPill, fab);
7560
- nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, toast, debugPanel);
8348
+ nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, settingsModal, bmPanel, tunePanel, osPanel, toast, debugPanel);
7561
8349
  shadow.appendChild(nexusContainer);
7562
8350
  promoteHost();
7563
8351
 
@@ -7567,7 +8355,7 @@
7567
8355
 
7568
8356
  uiElements = {
7569
8357
  uiWrapper, fab, reactPill, dock, btnFindMedia, btnLink, btnSyncStatus, btnTranslate, btnCinema, btnAutoCinema, btnPiP, btnRate, btnDraw, btnBookmark, btnChat, btnSubLog,
7570
- btnDebug, btnHideSite, chatPanel, chatMessages, chatInput, chatJumpBtn, subLogPanel, subLogMessages,
8358
+ btnDebug, btnHideSite, btnSettings, settingsModal, btnTune, tunePanel, chatPanel, chatMessages, chatInput, chatJumpBtn, subLogPanel, subLogMessages,
7571
8359
  subLogJumpBtn, drawCanvas, manualModal, transModal, toast, debugJumpBtn, syncBubble: null,
7572
8360
  pinError, guestInput, pinHint, pinDisplay, pinCopyBtn, hostBtn, connectBtn, btnInvite, typingRow, nickInput
7573
8361
  };
@@ -7577,9 +8365,9 @@
7577
8365
  attachJumpLogic(subLogMessages, subLogJumpBtn);
7578
8366
  attachJumpLogic(debugContent, debugJumpBtn);
7579
8367
  makeDraggable(uiWrapper, fab);
7580
- [[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [debugPanel, debugHeader]]
8368
+ [[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [settingsModal, settingsHeader], [bmPanel, bmHeader], [tunePanel, tuneHeader], [osPanel, osHeader], [debugPanel, debugHeader]]
7581
8369
  .forEach(([panel, header]) => makePanelDraggable(panel, header));
7582
- [chatPanel, subLogPanel, debugPanel, transModal].forEach(panel => PANEL_SIZE.attach(panel));
8370
+ [chatPanel, subLogPanel, debugPanel, transModal, settingsModal, bmPanel, tunePanel, osPanel].forEach(panel => PANEL_SIZE.attach(panel));
7583
8371
 
7584
8372
  shadow.querySelectorAll('.window-frame').forEach(panel => {
7585
8373
  const pinBtn = panel.querySelector('.pin-btn');
@@ -7625,6 +8413,11 @@
7625
8413
  };
7626
8414
 
7627
8415
  btnTranslate.onclick = () => { updateAIBtnUX(); openPanel(transModal); };
8416
+ btnSettings.onclick = () => { settingsBody.refreshPeople?.(); openPanel(settingsModal); };
8417
+ btnTune.onclick = () => TUNE.open();
8418
+ tuneHeader.querySelector('.close-btn').onclick = () => closePanel(tunePanel);
8419
+ osHeader.querySelector('.close-btn').onclick = () => closePanel(osPanel);
8420
+ settingsHeader.querySelector('.close-btn').onclick = () => closePanel(settingsModal);
7628
8421
  shadow.getElementById('stt-toggle').onclick = () => { TRANSLATOR.toggle(); if (TRANSLATOR.state !== 'idle') closePanel(transModal); };
7629
8422
 
7630
8423
  btnChat.onclick = () => {
@@ -7823,7 +8616,9 @@
7823
8616
  if (uiElements.dock?.classList.contains('open')) toggleDock(false);
7824
8617
  INK.start();
7825
8618
  };
7826
- btnBookmark.onclick = () => addBookmark();
8619
+ // 📌 opens the library (every site); "Bookmark this moment" is its first button.
8620
+ btnBookmark.onclick = () => { bmBody.render(); openPanel(bmPanel); };
8621
+ bmHeader.querySelector('.close-btn').onclick = () => closePanel(bmPanel);
7827
8622
  btnHideSite.onclick = () => setFabHiddenOnSite(true);
7828
8623
 
7829
8624
  setupCanvasLogic();
@@ -7930,7 +8725,7 @@
7930
8725
  function sendChatMessage(text) {
7931
8726
  if (!yChat) return;
7932
8727
  const info = currentMediaInfo();
7933
- yChat.push([{ sender: STATE.userId, color: STATE.color, text: text.slice(0, 500), videoTime: info && Number.isFinite(info.time) ? info.time : null, nick: STATE.nickname || null, ts: Date.now() }]);
8728
+ yChat.push([{ sender: STATE.userId, color: STATE.color, text: text.slice(0, 500), videoTime: info && Number.isFinite(info.time) ? info.time : null, nick: STATE.nickname || null, av: PROFILE.avatar() || null, ts: Date.now() }]);
7934
8729
  }
7935
8730
 
7936
8731
  function appendChatMessage(msg) {
@@ -7938,7 +8733,8 @@
7938
8733
  const color = /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(msg.color || '') ? msg.color : '#69f0ae';
7939
8734
  const row = createEl('div', 'chat-msg' + (msg.sender === STATE.userId ? ' mine' : ''));
7940
8735
  row.style.borderLeft = `4px solid ${color}`;
7941
- const name = createEl('span', 'chat-name', (msg.nick && String(msg.nick).trim().slice(0, 16)) || ('ID:' + String(msg.sender || '').substring(0, 3)));
8736
+ const av = safeEmoji(msg.av);
8737
+ const name = createEl('span', 'chat-name', (av ? av + ' ' : '') + ((msg.nick && String(msg.nick).trim().slice(0, 16)) || ('ID:' + String(msg.sender || '').substring(0, 3))));
7942
8738
  name.style.color = color;
7943
8739
  row.appendChild(name);
7944
8740
  if (msg.ts) {
@@ -8007,6 +8803,71 @@
8007
8803
  }
8008
8804
 
8009
8805
  // ───────────────────────── My profile (name + colour shown to others)
8806
+ // One emoji (a single grapheme that is a pictograph), or ''.
8807
+ function safeEmoji(s) {
8808
+ const str = String(s || '').trim();
8809
+ if (!str) return '';
8810
+ let first = str;
8811
+ try { if (typeof Intl !== 'undefined' && Intl.Segmenter) first = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(str)][0]?.segment || ''; else first = Array.from(str).slice(0, 2).join(''); } catch (_) { first = Array.from(str)[0] || ''; }
8812
+ return first.length <= 16 && /\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(first) ? first : '';
8813
+ }
8814
+
8815
+ // What reaches this device from the others, and from whom: kinds of events can be turned
8816
+ // off, a person can be muted for this room, and floods of reactions are thinned out.
8817
+ const SAFETY = {
8818
+ KINDS: ['react', 'nudge', 'ink', 'chat', 'ping'],
8819
+ muted: new Set(),
8820
+ receive(kind) { return STORE.get('nxu_recv_' + kind, true) !== false; },
8821
+ set(kind, on) { STORE.set('nxu_recv_' + kind, !!on); },
8822
+ allows(uid, kind) {
8823
+ if (uid && this.muted.has(uid)) return false;
8824
+ return !kind || this.receive(kind);
8825
+ },
8826
+ toggleMute(uid) { if (this.muted.has(uid)) this.muted.delete(uid); else this.muted.add(uid); },
8827
+ _rate: new Map(),
8828
+ // More than 6 reactions a second from one person: the rest are not shown.
8829
+ flood(uid, max = 6) {
8830
+ const now = Date.now();
8831
+ const list = (this._rate.get(uid) || []).filter(ts => now - ts < 1000);
8832
+ list.push(now);
8833
+ this._rate.set(uid, list);
8834
+ if (this._rate.size > 50) this._rate.delete(this._rate.keys().next().value);
8835
+ return list.length > max;
8836
+ }
8837
+ };
8838
+
8839
+ // The eight reaction buttons: the user's own choice (any emoji), or the defaults.
8840
+ const REACTIONS = {
8841
+ DEFAULT: ['😂', '😭', '😡', '💦', '🍪', '☕', '😘', '🖕'],
8842
+ list() {
8843
+ const saved = STORE.get('nxu_reactions', null);
8844
+ const arr = Array.isArray(saved) ? saved.map(safeEmoji) : [];
8845
+ return this.DEFAULT.map((d, i) => arr[i] || d);
8846
+ },
8847
+ set(i, emoji) {
8848
+ const list = this.list();
8849
+ const e = safeEmoji(emoji);
8850
+ if (!e || i < 0 || i >= list.length) return false;
8851
+ list[i] = e;
8852
+ STORE.set('nxu_reactions', list);
8853
+ this.apply();
8854
+ return true;
8855
+ },
8856
+ reset() { STORE.set('nxu_reactions', null); this.apply(); },
8857
+ apply() {
8858
+ CONFIG.emojis = this.list();
8859
+ const pill = uiElements.reactPill;
8860
+ if (!pill) return;
8861
+ pill.querySelectorAll('.react-btn:not(.together-btn)').forEach(b => b.remove());
8862
+ const first = pill.firstChild;
8863
+ CONFIG.emojis.forEach(emoji => {
8864
+ const btn = createEl('button', 'react-btn', emoji);
8865
+ btn.onclick = () => { pressFx(btn, emoji); handleLocalReactionClick(emoji); };
8866
+ pill.insertBefore(btn, first);
8867
+ });
8868
+ }
8869
+ };
8870
+
8010
8871
  const PROFILE = {
8011
8872
  SWATCHES: ['#69f0ae', '#40c4ff', '#7c4dff', '#ff4fa3', '#ff6e40', '#ffd740', '#b2ff59', '#18ffff', '#ea80fc', '#ff8a80'],
8012
8873
  color() {
@@ -8020,6 +8881,18 @@
8020
8881
  this.publish();
8021
8882
  shadow?.querySelectorAll('.nx-me-dot').forEach(el => el.style.setProperty('--c', c));
8022
8883
  },
8884
+ // What this device announces in the room (presence): name, colour, avatar, status.
8885
+ value() {
8886
+ return { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', av: this.avatar(), st: this.status(), v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden };
8887
+ },
8888
+ AVATARS: ['🙂', '😎', '🦊', '🐱', '🐶', '🐼', '🐸', '🦄', '🐧', '🍿', '🎧', '🌙', '🔥', '🌸', '👾', '🤖'],
8889
+ avatar() { return safeEmoji(STORE.get('nxu_avatar', '')); },
8890
+ status() { return String(STORE.get('nxu_status', '') || '').replace(/\s+/g, ' ').trim().slice(0, 40); },
8891
+ setAvatar(a) { STORE.set('nxu_avatar', safeEmoji(a)); this.publish(); updatePresenceUI(); },
8892
+ setStatus(s) {
8893
+ STORE.set('nxu_status', String(s || '').replace(/\s+/g, ' ').slice(0, 40));
8894
+ clearTimeout(this._st); this._st = setTimeout(() => { this.publish(); updatePresenceUI(); }, 600);
8895
+ },
8023
8896
  setName(name) {
8024
8897
  STATE.nickname = String(name || '').trim().slice(0, 16);
8025
8898
  STORE.set('nxu_nickname', STATE.nickname);
@@ -8029,7 +8902,7 @@
8029
8902
  },
8030
8903
  publish() {
8031
8904
  try {
8032
- if (ydoc && yPresence && STATE.handshakeVerified) ydoc.transact(() => yPresence.set(STATE.userId, { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden }), 'local');
8905
+ if (ydoc && yPresence && STATE.handshakeVerified) ydoc.transact(() => yPresence.set(STATE.userId, this.value()), 'local');
8033
8906
  } catch (_) { }
8034
8907
  },
8035
8908
  // Small editor: name + colour swatches + any colour.
@@ -8203,7 +9076,8 @@
8203
9076
  const text = String(msg.text).slice(0, 200);
8204
9077
  const card = createEl('button', 'nx-bubble nx-talk' + (mine ? ' mine' : ''), '', { type: 'button' });
8205
9078
  card.style.setProperty('--c', color);
8206
- const avatar = createEl('span', 'nx-talk-avatar', (Array.from(name.replace(/^ID:/, ''))[0] || '?').toUpperCase());
9079
+ const av = safeEmoji(mine ? PROFILE.avatar() : (msg.av || STATE.presenceMap?.[msg.sender]?.av));
9080
+ const avatar = createEl('span', 'nx-talk-avatar' + (av ? ' emoji' : ''), av || (Array.from(name.replace(/^ID:/, ''))[0] || '?').toUpperCase());
8207
9081
  const body = createEl('span', 'nx-talk-body');
8208
9082
  body.append(createEl('span', 'nx-bubble-name', name), createEl('span', 'nx-bubble-text', text));
8209
9083
  card.append(avatar, body);
@@ -8654,12 +9528,324 @@
8654
9528
  // darker or brighter (CSS filter on the player only — subtitles and controls unchanged).
8655
9529
  const BRIGHTNESS = {
8656
9530
  MIN: 0.3,
8657
- MAX: 1.5,
9531
+ MAX: 2,
8658
9532
  level: 1,
8659
- set(x) {
9533
+ // A filter on the picture only while it is not at 100 % (a filtered video cannot use
9534
+ // the device's direct video path, which costs battery), remembered per site.
9535
+ set(x, { save = true } = {}) {
8660
9536
  this.level = Math.round(Math.max(this.MIN, Math.min(this.MAX, x)) * 100) / 100;
8661
- ensurePageStyle(document, 'nxu-bright-style', `.nxu-cinema-root video, video.nxu-cinema-root, iframe.nxu-cinema-root, .nxu-cinema-root iframe { filter: brightness(var(--nxu-bright, 1)) !important; }`);
9537
+ ensurePageStyle(document, 'nxu-bright-style', `html.nxu-bright-on .nxu-cinema-root video, html.nxu-bright-on video.nxu-cinema-root, html.nxu-bright-on iframe.nxu-cinema-root, html.nxu-bright-on .nxu-cinema-root iframe { filter: brightness(var(--nxu-bright, 1)) !important; }`);
8662
9538
  document.documentElement.style.setProperty('--nxu-bright', String(this.level));
9539
+ document.documentElement.classList.toggle('nxu-bright-on', Math.abs(this.level - 1) > 0.01);
9540
+ if (save) { const all = { ...(STORE.get('nxu_bright', {}) || {}) }; if (Math.abs(this.level - 1) > 0.01) all[HOST] = this.level; else delete all[HOST]; STORE.set('nxu_bright', all); }
9541
+ },
9542
+ restore() { const v = Number((STORE.get('nxu_bright', {}) || {})[HOST]); if (Number.isFinite(v) && v !== 1) this.set(v, { save: false }); }
9543
+ };
9544
+
9545
+ // Volume above 100 % (quiet films): the page's audio goes through a gain with a gentle
9546
+ // limiter. Only possible when the sound may be read by the page (same site or a stream
9547
+ // the page loaded itself); otherwise the browser would silence it, so it is refused.
9548
+ const BOOST = {
9549
+ level: 1,
9550
+ _ctx: null, _gain: null, _el: null,
9551
+ can(v) {
9552
+ if (!v) return false;
9553
+ const src = v.currentSrc || v.src || '';
9554
+ if (/^(blob|data):/i.test(src) || v.srcObject) return true;
9555
+ try { if (new URL(src, location.href).origin === location.origin) return true; } catch (_) { }
9556
+ return !!v.crossOrigin;
9557
+ },
9558
+ set(x) {
9559
+ const level = Math.round(Math.max(1, Math.min(3, Number(x) || 1)) * 100) / 100;
9560
+ const v = STATE.video;
9561
+ if (!v) {
9562
+ if (STATE.cinemaIframe) FRAME.postToFrame(STATE.cinemaIframe, { type: 'NXU_MEDIA_CMD', action: 'boost', value: level });
9563
+ this.level = level;
9564
+ return true;
9565
+ }
9566
+ if (this._el && this._el !== v) { try { this._ctx?.close(); } catch (_) { } this._ctx = this._gain = this._el = null; }
9567
+ if (level > 1 && !this._gain) {
9568
+ if (!this.can(v)) { showToast(t('boostBlocked')); return false; }
9569
+ try {
9570
+ const Ctx = window.AudioContext || window.webkitAudioContext;
9571
+ const ctx = new Ctx();
9572
+ const src = ctx.createMediaElementSource(v);
9573
+ const gain = ctx.createGain();
9574
+ const lim = ctx.createDynamicsCompressor();
9575
+ lim.threshold.value = -6; lim.knee.value = 6; lim.ratio.value = 12; lim.attack.value = 0.003; lim.release.value = 0.2;
9576
+ src.connect(gain); gain.connect(lim); lim.connect(ctx.destination);
9577
+ this._ctx = ctx; this._gain = gain; this._el = v;
9578
+ } catch (_) { showToast(t('boostBlocked')); return false; }
9579
+ }
9580
+ if (this._ctx?.state === 'suspended') { try { this._ctx.resume(); } catch (_) { } }
9581
+ if (this._gain) this._gain.gain.value = level;
9582
+ this.level = level;
9583
+ return true;
9584
+ }
9585
+ };
9586
+
9587
+ // ───────────────────────── Subtitles in cinema: the video's own tracks, a file, or
9588
+ // OpenSubtitles — drawn by NexusSync in one consistent style, with timing and size.
9589
+ const SUBS = {
9590
+ cues: null, // [{ s, e, text }] for an external file
9591
+ label: '',
9592
+ track: null, // a TextTrack of the page's video
9593
+ delay: 0,
9594
+ _box: null, _timer: 0, _last: '',
9595
+ size() { const v = Number(STORE.get('nxu_xsub_size', 1)); return Number.isFinite(v) ? Math.max(0.7, Math.min(1.8, v)) : 1; },
9596
+ tracks() {
9597
+ const v = STATE.video;
9598
+ if (!v || !v.textTracks) return [];
9599
+ return [...v.textTracks].filter(tr => tr.kind === 'subtitles' || tr.kind === 'captions');
9600
+ },
9601
+ active() { return !!(this.cues || this.track); },
9602
+ _ensureBox() {
9603
+ const c = getContainer();
9604
+ if (!c) return null;
9605
+ if (!this._box || !this._box.isConnected) { this._box = createEl('div', 'nx-xsub'); c.appendChild(this._box); }
9606
+ this._box.style.setProperty('--xs', String(this.size()));
9607
+ return this._box;
9608
+ },
9609
+ off() {
9610
+ if (this.track) { try { this.track.mode = 'disabled'; this.track.removeEventListener('cuechange', this._onCue); } catch (_) { } }
9611
+ this.track = null; this.cues = null; this.label = '';
9612
+ clearInterval(this._timer); this._timer = 0;
9613
+ this._render('');
9614
+ try { CUE_MIRROR.render(); } catch (_) { }
9615
+ },
9616
+ useTrack(tr) {
9617
+ this.off();
9618
+ this.tracks().forEach(x => { if (x !== tr && x.mode === 'showing') x.mode = 'disabled'; });
9619
+ this.track = tr;
9620
+ this.label = tr.label || tr.language || t('subTrack');
9621
+ tr.mode = 'hidden'; // cues still arrive, the browser does not draw them itself
9622
+ try { CUE_MIRROR.render(); } catch (_) { }
9623
+ this._onCue = () => this.tick();
9624
+ tr.addEventListener('cuechange', this._onCue);
9625
+ this._loop();
9626
+ showToast(t('subLoaded', { name: this.label }));
9627
+ },
9628
+ useCues(cues, label) {
9629
+ this.off();
9630
+ this.cues = cues.sort((a, b) => a.s - b.s);
9631
+ this.label = label;
9632
+ try { CUE_MIRROR.render(); } catch (_) { }
9633
+ this._loop();
9634
+ showToast(t('subLoaded', { name: label }));
9635
+ },
9636
+ _loop() { clearInterval(this._timer); this._timer = setInterval(() => this.tick(), 150); this.tick(); },
9637
+ setDelay(d) { this.delay = Math.round(Math.max(-120, Math.min(120, d)) * 10) / 10; this.tick(); },
9638
+ _now() {
9639
+ const info = currentMediaInfo();
9640
+ if (!info) return null;
9641
+ let tm = info.time || 0;
9642
+ if (info.kind === 'iframe' && !info.paused) {
9643
+ const rep = VIDEO_DETECTOR.frameReports.get(info.el);
9644
+ if (rep?.ts) tm = (rep.currentTime || 0) + Math.min(1, (Date.now() - rep.ts) / 1000) * (rep.rate || 1);
9645
+ }
9646
+ return tm;
9647
+ },
9648
+ tick() {
9649
+ if (!this.active()) return;
9650
+ const tm = this._now();
9651
+ if (tm == null) return;
9652
+ const at = tm - this.delay;
9653
+ let text = '';
9654
+ if (this.cues) {
9655
+ // binary search for the last cue starting before `at`
9656
+ let lo = 0, hi = this.cues.length - 1, idx = -1;
9657
+ while (lo <= hi) { const mid = (lo + hi) >> 1; if (this.cues[mid].s <= at) { idx = mid; lo = mid + 1; } else hi = mid - 1; }
9658
+ const parts = [];
9659
+ for (let i = idx; i >= 0 && i > idx - 4; i--) { const c = this.cues[i]; if (c.s <= at && at < c.e) parts.unshift(c.text); }
9660
+ text = parts.join('\n');
9661
+ } else if (this.track) {
9662
+ const list = this.track.cues ? [...this.track.cues] : [];
9663
+ // With a delay the active cues are looked up by time instead of cuechange.
9664
+ const act = this.delay ? list.filter(c => c.startTime <= at && at < c.endTime) : [...(this.track.activeCues || [])];
9665
+ text = act.map(c => (c.text || '')).join('\n');
9666
+ }
9667
+ this._render(this._clean(text));
9668
+ },
9669
+ _clean(s) { return String(s || '').replace(/<[^>]+>/g, '').replace(/\{\\[^}]*\}/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').trim(); },
9670
+ _render(text) {
9671
+ if (text === this._last && this._box?.isConnected) return;
9672
+ this._last = text;
9673
+ const box = text ? this._ensureBox() : this._box;
9674
+ if (!box) return;
9675
+ box.replaceChildren(...(text ? text.split('\n').filter(Boolean).slice(0, 4).map(line => createEl('span', 'nx-xsub-line', line)) : []));
9676
+ box.classList.toggle('on', !!text);
9677
+ },
9678
+ // ── parsing: SRT, WebVTT and (basic) ASS/SSA
9679
+ parse(text) {
9680
+ const src = String(text || '').replace(/^\uFEFF/, '').replace(/\r/g, '');
9681
+ const ts = s => { const m = s.trim().match(/(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})/); return m ? (+(m[1] || 0)) * 3600 + (+m[2]) * 60 + (+m[3]) + (+m[4].padEnd(3, '0')) / 1000 : NaN; };
9682
+ const out = [];
9683
+ if (/^\[Script Info\]/m.test(src) || /^Dialogue:/m.test(src)) {
9684
+ const fmt = (src.match(/^Format:\s*(.+)$/m)?.[1] || 'Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text').split(',').map(x => x.trim().toLowerCase());
9685
+ const iS = fmt.indexOf('start'), iE = fmt.indexOf('end'), iT = fmt.indexOf('text');
9686
+ const assTs = s => { const m = s.trim().match(/(\d+):(\d{2}):(\d{2})[.](\d{1,2})/); return m ? +m[1] * 3600 + +m[2] * 60 + +m[3] + +m[4] / 100 : NaN; };
9687
+ src.split('\n').forEach(line => {
9688
+ if (!line.startsWith('Dialogue:')) return;
9689
+ const parts = line.slice(9).split(',');
9690
+ const textPart = parts.slice(iT).join(',').replace(/\\N/gi, '\n');
9691
+ const s = assTs(parts[iS] || ''), e = assTs(parts[iE] || '');
9692
+ if (Number.isFinite(s) && Number.isFinite(e)) out.push({ s, e, text: this._clean(textPart) });
9693
+ });
9694
+ return out;
9695
+ }
9696
+ src.split(/\n{2,}/).forEach(block => {
9697
+ const lines = block.split('\n').filter(l => l.trim() !== '');
9698
+ const k = lines.findIndex(l => l.includes('-->'));
9699
+ if (k < 0) return;
9700
+ const [a, b] = lines[k].split('-->');
9701
+ const s = ts(a), e = ts(b);
9702
+ const body = this._clean(lines.slice(k + 1).join('\n'));
9703
+ if (Number.isFinite(s) && Number.isFinite(e) && body) out.push({ s, e, text: body });
9704
+ });
9705
+ return out;
9706
+ },
9707
+ async openFile() {
9708
+ const input = document.createElement('input');
9709
+ input.type = 'file'; input.accept = '.srt,.vtt,.ass,.ssa,.sub,text/plain';
9710
+ input.onchange = async () => {
9711
+ const f = input.files?.[0];
9712
+ if (!f) return;
9713
+ const cues = this.parse(await f.text());
9714
+ if (cues.length) this.useCues(cues, f.name.replace(/\.[^.]+$/, '')); else showToast(t('subLoadFail'));
9715
+ };
9716
+ input.click();
9717
+ },
9718
+ // A gentle offer when cinema has nothing to read: once per page.
9719
+ maybeSuggest() {
9720
+ if (!IS_TOP || !STATE.isCinema || this.active() || this._suggested === location.href) return;
9721
+ if (this.tracks().length || (CUE_MIRROR.box?.textContent || '').trim() || TRANSLATOR.active) return;
9722
+ const info = currentMediaInfo();
9723
+ if (!info || info.live || info.paused) return;
9724
+ this._suggested = location.href;
9725
+ const c = getContainer();
9726
+ if (!c) return;
9727
+ const chip = createEl('button', 'nx-sub-suggest', t('subSuggest'), { type: 'button' });
9728
+ chip.onclick = (e) => { e.stopPropagation(); chip.remove(); OPENSUBS.open(); };
9729
+ c.appendChild(chip);
9730
+ setTimeout(() => chip.classList.add('in'), 30);
9731
+ setTimeout(() => { chip.classList.remove('in'); setTimeout(() => chip.remove(), 400); }, 12000);
9732
+ }
9733
+ };
9734
+
9735
+ // OpenSubtitles.org search (its public REST interface: no account needed).
9736
+ const OPENSUBS = {
9737
+ LANG3: { ko: 'kor', en: 'eng', ja: 'jpn', zh: 'chi', es: 'spa', fr: 'fre', de: 'ger', it: 'ita', pt: 'por', ru: 'rus', vi: 'vie', th: 'tha', id: 'ind', tr: 'tur', ar: 'ara', hi: 'hin', nl: 'dut', pl: 'pol', sv: 'swe', uk: 'ukr', ms: 'may', tl: 'tgl' },
9738
+ lang() { return STORE.get('nxu_os_lang', '') || baseLang(STORE.get('nxu_subtitle_language', '') || navigator.language || 'en'); },
9739
+ // Title, year and episode from the page (site names and "watch online" words removed).
9740
+ guess() {
9741
+ const og = document.querySelector('meta[property="og:title"]')?.content || '';
9742
+ let s = (og || document.title || '').replace(/\s+/g, ' ');
9743
+ let season = 0, episode = 0;
9744
+ let m = s.match(/S(\d{1,2})\s*E(\d{1,3})/i) || s.match(/시즌\s*(\d{1,2})\D{0,4}(\d{1,3})\s*화/);
9745
+ if (m) { season = +m[1]; episode = +m[2]; }
9746
+ else if ((m = s.match(/(\d{1,3})\s*(화|회|episode|ep\.?)/i))) { episode = +m[1]; season = 1; }
9747
+ const year = (s.match(/\b(19[3-9]\d|20[0-4]\d)\b/) || [])[1] || '';
9748
+ s = s.split(/\s[|\-–—:]\s|\s?\|\s?/)[0];
9749
+ s = s.replace(/S\d{1,2}\s*E\d{1,3}/ig, '').replace(/시즌\s*\d+|\d+\s*(화|회)|다시보기|무료|보기|스트리밍|영화|드라마|watch|online|free|full\s*movie|hd|1080p|720p|streaming/ig, ' ')
9750
+ .replace(/[\[\](){}]/g, ' ').replace(/\b(19|20)\d{2}\b/g, ' ').replace(/\s+/g, ' ').trim();
9751
+ return { query: s, year, season, episode };
9752
+ },
9753
+ async search({ query, season, episode, lang }) {
9754
+ const l3 = this.LANG3[lang] || 'eng';
9755
+ const parts = [];
9756
+ if (episode) parts.push('episode-' + episode);
9757
+ parts.push('query-' + encodeURIComponent(query.toLowerCase()));
9758
+ if (season && episode) parts.push('season-' + season);
9759
+ parts.push('sublanguageid-' + l3);
9760
+ const res = await httpRequest({ url: 'https://rest.opensubtitles.org/search/' + parts.join('/'), headers: { 'X-User-Agent': 'TemporaryUserAgent' }, timeout: 15000 });
9761
+ if (res.status !== 200) throw new Error('HTTP ' + res.status);
9762
+ const list = JSON.parse(res.text || '[]');
9763
+ return (Array.isArray(list) ? list : []).filter(x => x && /^https:\/\/dl\.opensubtitles\.org\//.test(String(x.SubDownloadLink || '')))
9764
+ .sort((a, b) => (+b.SubDownloadsCnt || 0) - (+a.SubDownloadsCnt || 0)).slice(0, 40);
9765
+ },
9766
+ _binary(url) {
9767
+ return new Promise((resolve, reject) => {
9768
+ const gm = typeof GM_xmlhttpRequest === 'function' ? GM_xmlhttpRequest : (typeof GM !== 'undefined' && GM?.xmlHttpRequest ? GM.xmlHttpRequest.bind(GM) : null);
9769
+ if (gm) {
9770
+ const viaFetch = () => fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error('HTTP ' + r.status)))).then(resolve, reject);
9771
+ try {
9772
+ gm({ method: 'GET', url, responseType: 'arraybuffer', timeout: 20000,
9773
+ // Some managers return no binary body: fall back to a plain request.
9774
+ onload: r => (r.status === 200 && r.response instanceof ArrayBuffer ? resolve(r.response) : r.status === 200 ? viaFetch() : reject(new Error('HTTP ' + r.status))),
9775
+ onerror: () => viaFetch(), ontimeout: () => reject(new Error('timeout')) });
9776
+ return;
9777
+ } catch (_) { }
9778
+ }
9779
+ fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error('HTTP ' + r.status)))).then(resolve, reject);
9780
+ });
9781
+ },
9782
+ async download(item) {
9783
+ let buf = await this._binary(item.SubDownloadLink);
9784
+ const head = new Uint8Array(buf.slice(0, 2));
9785
+ if (head[0] === 0x1f && head[1] === 0x8b) {
9786
+ if (typeof DecompressionStream === 'undefined') throw new Error('gzip unsupported');
9787
+ buf = await new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer();
9788
+ }
9789
+ const enc = String(item.SubEncoding || 'UTF-8').toLowerCase().replace(/^cp(949|936|950)$/, (m, n) => ({ 949: 'euc-kr', 936: 'gbk', 950: 'big5' })[n]).replace(/^cp(\d+)$/, 'windows-$1');
9790
+ let text;
9791
+ try { text = new TextDecoder(enc).decode(buf); } catch (_) { text = new TextDecoder('utf-8').decode(buf); }
9792
+ return SUBS.parse(text);
9793
+ },
9794
+ open() {
9795
+ const panel = shadow?.getElementById('os-panel');
9796
+ if (!panel) return;
9797
+ const g = this.guess();
9798
+ const q = panel.querySelector('.os-q'), se = panel.querySelector('.os-season'), ep = panel.querySelector('.os-episode'), lg = panel.querySelector('.os-lang');
9799
+ if (!q.value || q.dataset.page !== location.href) { q.value = g.query; se.value = g.season || ''; ep.value = g.episode || ''; q.dataset.page = location.href; }
9800
+ lg.value = this.LANG3[this.lang()] ? this.lang() : 'en';
9801
+ openPanel(panel);
9802
+ if (q.value && !panel.querySelector('.os-item')) this.run(panel);
9803
+ },
9804
+ async run(panel) {
9805
+ const q = panel.querySelector('.os-q').value.trim();
9806
+ const out = panel.querySelector('.os-results');
9807
+ if (!q) return;
9808
+ const lang = panel.querySelector('.os-lang').value;
9809
+ STORE.set('nxu_os_lang', lang);
9810
+ out.replaceChildren(createEl('div', 'trans-help', t('osSearching')));
9811
+ try {
9812
+ const list = await this.search({ query: q, season: +panel.querySelector('.os-season').value || 0, episode: +panel.querySelector('.os-episode').value || 0, lang });
9813
+ if (!list.length) { out.replaceChildren(createEl('div', 'trans-help', t('osNone'))); return; }
9814
+ out.replaceChildren(...list.map(item => {
9815
+ const b = createEl('button', 'os-item', '', { type: 'button' });
9816
+ b.append(createEl('span', 'os-name', String(item.MovieReleaseName || item.SubFileName || item.MovieName || '').slice(0, 140)),
9817
+ createEl('span', 'os-meta', [item.MovieName, item.MovieYear, item.LanguageName, String(item.SubFormat || '').toUpperCase(), t('osDownloads', { n: item.SubDownloadsCnt || 0 })].filter(Boolean).join(' · ')));
9818
+ b.onclick = async () => {
9819
+ b.classList.add('busy'); b.querySelector('.os-meta').textContent = t('osLoading');
9820
+ try {
9821
+ const cues = await this.download(item);
9822
+ if (!cues.length) throw new Error('empty');
9823
+ SUBS.useCues(cues, String(item.MovieName || q).slice(0, 60) + ' · ' + (item.LanguageName || lang));
9824
+ closePanel(panel);
9825
+ } catch (err) { logDebug('Subtitles download failed: ' + (err.message || err), 'warn'); showToast(t('subLoadFail')); b.classList.remove('busy'); }
9826
+ };
9827
+ return b;
9828
+ }));
9829
+ } catch (err) {
9830
+ logDebug('OpenSubtitles search failed: ' + (err.message || err), 'warn');
9831
+ out.replaceChildren(createEl('div', 'trans-help', t('osError')));
9832
+ }
9833
+ },
9834
+ build() {
9835
+ const body = createEl('div', 'manual-body os-body');
9836
+ const q = createEl('input', 'nx-compose-input os-q', '', { type: 'search', placeholder: t('osQuery'), autocomplete: 'off' });
9837
+ const row = createEl('div', 'os-row');
9838
+ const se = createEl('input', 'nx-compose-input os-season', '', { type: 'number', min: '0', max: '99', placeholder: t('osSeason') });
9839
+ const ep = createEl('input', 'nx-compose-input os-episode', '', { type: 'number', min: '0', max: '999', placeholder: t('osEpisode') });
9840
+ const lg = createSelect('', Object.keys(this.LANG3).map(c => ({ value: c, label: LANG_BY_CODE.get(c)?.label || c })));
9841
+ lg.classList.add('os-lang');
9842
+ row.append(se, ep, lg);
9843
+ const go = createEl('button', 'btn primary', '🔎 ' + t('osSearch'), { type: 'button' });
9844
+ const out = createEl('div', 'os-results');
9845
+ go.onclick = () => this.run(body);
9846
+ [q, se, ep].forEach(i => i.addEventListener('keydown', (ev) => { ev.stopPropagation(); if (ev.key === 'Enter') this.run(body); }));
9847
+ body.append(q, row, go, out, createEl('div', 'trans-help', t('osHint')));
9848
+ return body;
8663
9849
  }
8664
9850
  };
8665
9851
 
@@ -8822,6 +10008,7 @@
8822
10008
  if (!STATE.isCinema) { this._auto = false; STATE.controlsOverride = null; }
8823
10009
  },
8824
10010
  onEnter() {
10011
+ try { BRIGHTNESS.restore(); } catch (_) { }
8825
10012
  const auto = this._auto;
8826
10013
  this._auto = false;
8827
10014
  setTimeout(() => this._showCard(auto), 400);
@@ -8875,7 +10062,15 @@
8875
10062
  resetIdleTimer(true);
8876
10063
  }
8877
10064
  };
8878
- setInterval(() => { try { AUTO_CINEMA.tick(); } catch (_) { } }, 1200);
10065
+ setInterval(() => {
10066
+ try { AUTO_CINEMA.tick(); } catch (_) { }
10067
+ try { JUMP.tick(); } catch (_) { }
10068
+ try {
10069
+ if (STATE.isCinema) { SUBS._cinemaSince = SUBS._cinemaSince || Date.now(); if (Date.now() - SUBS._cinemaSince > 6000) SUBS.maybeSuggest(); }
10070
+ else SUBS._cinemaSince = 0;
10071
+ } catch (_) { }
10072
+ }, 1200);
10073
+ try { JUMP.init(); } catch (_) { }
8879
10074
 
8880
10075
  // ───────────────────────── Next episode
8881
10076
  // On series pages (drama/anime sites) the page usually has a "next episode" link or
@@ -9186,7 +10381,7 @@
9186
10381
  _typing: new Map(),
9187
10382
  _connectedAt: 0,
9188
10383
  _lastCanvasBubble: 0,
9189
- TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto'],
10384
+ TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto', 'tune'],
9190
10385
  live() { return STATE.handshakeVerified && !STATE.isReadOnly && STATE.role !== 'IDLE'; },
9191
10386
  send(type, data = {}) {
9192
10387
  if (!this.live()) return false;
@@ -9197,6 +10392,10 @@
9197
10392
  },
9198
10393
  receive(type, d) {
9199
10394
  if (!d || typeof d !== 'object' || d.uid === STATE.userId || !this.live()) return;
10395
+ // Muted people and switched-off kinds (the cover, countdowns and "go together"
10396
+ // always come through: they keep everyone watching the same thing).
10397
+ const kind = { nudge: 'nudge', ink: 'ink', pointer: 'ping', typing: 'chat' }[type];
10398
+ if (!SAFETY.allows(typeof d.uid === 'string' ? d.uid : '', kind)) return;
9200
10399
  if (typeof d.id === 'string') {
9201
10400
  if (this._seen.has(d.id)) return;
9202
10401
  this._seen.add(d.id);
@@ -9211,6 +10410,7 @@
9211
10410
  else if (type === 'ink') INK.onRemote(who, d);
9212
10411
  else if (type === 'cover') COVER.onRemote(who, d);
9213
10412
  else if (type === 'goto') TRAVEL.onRemote(who, d);
10413
+ else if (type === 'tune') TUNE.onRemote(who, d);
9214
10414
  },
9215
10415
  // Fresh events only: the history a newcomer downloads must not pop up as notifications.
9216
10416
  isFresh(ts) {
@@ -10008,6 +11208,7 @@
10008
11208
  function onRemoteReaction(d) {
10009
11209
  if (!d || typeof d.emoji !== 'string' || d.emoji.length > 8) return;
10010
11210
  const uid = typeof d.uid === 'string' ? d.uid.slice(0, 40) : 'peer';
11211
+ if (!SAFETY.allows(uid, 'react') || SAFETY.flood(uid)) return;
10011
11212
  const color = typeof d.color === 'string' && /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(d.color) ? d.color : '#82b1ff';
10012
11213
  const name = (typeof d.nick === 'string' && d.nick.trim().slice(0, 16)) || participantName(uid);
10013
11214
  const now = Date.now();
@@ -10118,6 +11319,7 @@
10118
11319
  case 'seekBy': MEDIA_SAFE.seek(v, Math.max(0, v.currentTime + value)); break;
10119
11320
  case 'volume': v.volume = Math.max(0, Math.min(1, value)); v.muted = value === 0; break;
10120
11321
  case 'mute': v.muted = !v.muted; break;
11322
+ case 'boost': BOOST.set(value); break;
10121
11323
  }
10122
11324
  }
10123
11325
 
@@ -10175,6 +11377,7 @@
10175
11377
  fitCover: 'M3 5v4h2V5h4V3H5a2 2 0 0 0-2 2zm2 10H3v4a2 2 0 0 0 2 2h4v-2H5v-4zm14 4h-4v2h4a2 2 0 0 0 2-2v-4h-2v4zm0-16h-4v2h4v4h2V5a2 2 0 0 0-2-2zM7 7h10v10H7z',
10176
11378
  close: 'M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z',
10177
11379
  rotate: 'M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77a1.49 1.49 0 0 0-2.12 0L1.75 8.11a1.49 1.49 0 0 0 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29A10.49 10.49 0 0 1 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z',
11380
+ view: 'M20 15.31 23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18V6c3.31 0 6 2.69 6 6s-2.69 6-6 6z',
10178
11381
  tune: 'M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z',
10179
11382
  film: 'M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z',
10180
11383
  keyboard: 'M20 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z'
@@ -10294,9 +11497,10 @@
10294
11497
  const subBtn = btn('cc-sub', 'cc', t('aiSubTitle'));
10295
11498
  const fitBtn = btn('cc-fit', 'fit', t('ccFit'));
10296
11499
  const ambientBtn = btn('cc-ambient', 'ambient', t('ccAmbient'));
11500
+ const viewBtn = btn('cc-view', 'view', t('viewMenu'));
10297
11501
  const pipBtn = btn('cc-pip', 'pip', t('ccPip'));
10298
11502
  const fsBtn = btn('cc-fs', 'fullscreen', t('ccFullscreen'));
10299
- row.append(playBtn, backBtn, fwdBtn, vol, time, live, spacer, rateBtn, subBtn, fitBtn, ambientBtn, pipBtn, fsBtn);
11503
+ row.append(playBtn, backBtn, fwdBtn, vol, time, live, spacer, rateBtn, subBtn, viewBtn, fitBtn, ambientBtn, pipBtn, fsBtn);
10300
11504
  bottom.append(seek, row);
10301
11505
 
10302
11506
  const menu = createEl('div', 'cc-menu', '', { role: 'menu' });
@@ -10305,7 +11509,7 @@
10305
11509
  root.append(gesture, scrim, rippleL, rippleR, spinner, center, flash, scrub, top, bottom, menu, help);
10306
11510
  container.appendChild(root);
10307
11511
  this.root = root;
10308
- this.els = { gesture, scrim, rippleL, rippleR, flash, spinner, spinnerLabel, scrub, title, room, helpBtn, rotateBtn, modeBtn, exitBtn, center, cBack, cPlay, cFwd, bottom, seek, track, bufferBar, progress, pins, thumb, range, hover, playBtn, backBtn, fwdBtn, vol, muteBtn, volume, time, live, rateBtn, subBtn, fitBtn, ambientBtn, pipBtn, fsBtn, menu, help };
11512
+ this.els = { gesture, scrim, rippleL, rippleR, flash, spinner, spinnerLabel, scrub, title, room, helpBtn, rotateBtn, modeBtn, exitBtn, center, cBack, cPlay, cFwd, bottom, seek, track, bufferBar, progress, pins, thumb, range, hover, playBtn, backBtn, fwdBtn, vol, muteBtn, volume, time, live, rateBtn, subBtn, viewBtn, fitBtn, ambientBtn, pipBtn, fsBtn, menu, help };
10309
11513
 
10310
11514
  const stop = (e) => e.stopPropagation();
10311
11515
  [top, bottom, menu, help, center].forEach(el => el.addEventListener('pointerdown', stop));
@@ -10344,7 +11548,8 @@
10344
11548
  volume.addEventListener('input', () => PLAYER.setVolume(volume.value / 100));
10345
11549
  time.onclick = () => { STORE.set('nxu_cc_remaining', !STORE.get('nxu_cc_remaining', false)); this.update(); };
10346
11550
  rateBtn.onclick = () => this.toggleRateMenu();
10347
- subBtn.onclick = () => TRANSLATOR.toggle();
11551
+ subBtn.onclick = () => this.toggleSubMenu();
11552
+ viewBtn.onclick = () => this.toggleViewMenu();
10348
11553
  fitBtn.onclick = () => this.cycleFit();
10349
11554
  ambientBtn.onclick = () => {
10350
11555
  const on = !CINEMA.ambientEnabled();
@@ -10619,6 +11824,7 @@
10619
11824
  this.els.help.classList.remove('open');
10620
11825
  menu.classList.toggle('open', open);
10621
11826
  this.els.rateBtn.setAttribute('aria-expanded', String(open));
11827
+ menu.dataset.kind = 'rate';
10622
11828
  if (!open) return;
10623
11829
  const current = currentPlaybackRate();
10624
11830
  menu.replaceChildren(createEl('div', 'cc-menu-title', t('ccSpeed')), ...[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map(r => {
@@ -10629,6 +11835,67 @@
10629
11835
  resetIdleTimer(true);
10630
11836
  },
10631
11837
 
11838
+ // Subtitles: the video's own tracks, a file, OpenSubtitles, AI live subtitles; timing and size.
11839
+ toggleSubMenu(force) {
11840
+ const menu = this.els.menu;
11841
+ if (!menu) return;
11842
+ const open = force ?? !(menu.classList.contains('open') && menu.dataset.kind === 'sub');
11843
+ this.els.help.classList.remove('open');
11844
+ menu.classList.toggle('open', open);
11845
+ menu.dataset.kind = 'sub';
11846
+ if (!open) return;
11847
+ const item = (label, sel, fn) => { const b = createEl('button', sel ? 'sel' : '', label, { type: 'button', role: 'menuitemradio' }); b.onclick = (ev) => { ev.stopPropagation(); fn(); }; return b; };
11848
+ const tracks = SUBS.tracks();
11849
+ const kids = [createEl('div', 'cc-menu-title', t('subMenu')),
11850
+ item(t('xsubOff'), !SUBS.active(), () => { SUBS.off(); this.toggleSubMenu(false); })];
11851
+ tracks.forEach((tr, i) => kids.push(item('🎞 ' + (tr.label || tr.language || t('subTrack') + ' ' + (i + 1)), SUBS.track === tr, () => { SUBS.useTrack(tr); this.toggleSubMenu(false); })));
11852
+ if (SUBS.cues) kids.push(item('💬 ' + SUBS.label, true, () => this.toggleSubMenu(false)));
11853
+ kids.push(item(t('subSearch'), false, () => { this.toggleSubMenu(false); OPENSUBS.open(); }));
11854
+ kids.push(item(t('subFile'), false, () => { this.toggleSubMenu(false); SUBS.openFile(); }));
11855
+ kids.push(item(t('subAi') + (TRANSLATOR.active ? ' ✓' : ''), false, () => { this.toggleSubMenu(false); TRANSLATOR.toggle(); }));
11856
+ if (SUBS.active()) {
11857
+ const d = createEl('div', 'cc-menu-adjust');
11858
+ const val = createEl('span', 'cc-adj-val', (SUBS.delay > 0 ? '+' : '') + SUBS.delay.toFixed(1) + 's');
11859
+ const step = (x) => { SUBS.setDelay(SUBS.delay + x); val.textContent = (SUBS.delay > 0 ? '+' : '') + SUBS.delay.toFixed(1) + 's'; };
11860
+ const mkb = (txt, x) => { const b = createEl('button', 'cc-adj', txt, { type: 'button' }); b.onclick = (ev) => { ev.stopPropagation(); step(x); }; return b; };
11861
+ d.append(createEl('span', 'cc-adj-label', t('subDelay')), mkb('−0.5', -0.5), val, mkb('+0.5', 0.5));
11862
+ const z = createEl('div', 'cc-menu-adjust');
11863
+ const sz = (x) => { STORE.set('nxu_xsub_size', Math.round(Math.max(0.7, Math.min(1.8, SUBS.size() + x)) * 10) / 10); SUBS._box?.style.setProperty('--xs', String(SUBS.size())); szv.textContent = Math.round(SUBS.size() * 100) + '%'; };
11864
+ const szv = createEl('span', 'cc-adj-val', Math.round(SUBS.size() * 100) + '%');
11865
+ const mz = (txt, x) => { const b = createEl('button', 'cc-adj', txt, { type: 'button' }); b.onclick = (ev) => { ev.stopPropagation(); sz(x); }; return b; };
11866
+ z.append(createEl('span', 'cc-adj-label', t('xsubSize')), mz('A−', -0.1), szv, mz('A+', 0.1));
11867
+ kids.push(d, z);
11868
+ } else if (!tracks.length) kids.push(createEl('div', 'cc-menu-note', t('subNone')));
11869
+ menu.replaceChildren(...kids);
11870
+ resetIdleTimer(true);
11871
+ },
11872
+ // Picture & sound: brightness for dark films, volume above 100 %.
11873
+ toggleViewMenu(force) {
11874
+ const menu = this.els.menu;
11875
+ if (!menu) return;
11876
+ const open = force ?? !(menu.classList.contains('open') && menu.dataset.kind === 'view');
11877
+ this.els.help.classList.remove('open');
11878
+ menu.classList.toggle('open', open);
11879
+ menu.dataset.kind = 'view';
11880
+ if (!open) return;
11881
+ const slider = (label, min, max, value, fmt, on) => {
11882
+ const row = createEl('label', 'cc-slider');
11883
+ const out = createEl('span', 'cc-adj-val', fmt(value));
11884
+ const r = createEl('input', '', '', { type: 'range', min: String(min), max: String(max), step: '5', value: String(Math.round(value * 100)) });
11885
+ r.addEventListener('input', () => { const v = +r.value / 100; if (on(v) === false) { r.value = '100'; out.textContent = fmt(1); return; } out.textContent = fmt(v); });
11886
+ r.addEventListener('pointerdown', (ev) => ev.stopPropagation());
11887
+ row.append(createEl('span', 'cc-adj-label', label), r, out);
11888
+ return { row, r, out };
11889
+ };
11890
+ const pct = v => Math.round(v * 100) + '%';
11891
+ const b = slider('☀️ ' + t('viewBright'), 30, 200, BRIGHTNESS.level, pct, v => BRIGHTNESS.set(v));
11892
+ const s = slider('🔊 ' + t('viewBoost'), 100, 300, BOOST.level, pct, v => BOOST.set(v));
11893
+ const reset = createEl('button', '', '↺ ' + t('viewReset'), { type: 'button' });
11894
+ reset.onclick = (ev) => { ev.stopPropagation(); BRIGHTNESS.set(1); BOOST.set(1); b.r.value = '100'; s.r.value = '100'; b.out.textContent = s.out.textContent = '100%'; };
11895
+ menu.replaceChildren(createEl('div', 'cc-menu-title', t('viewMenu')), b.row, s.row, reset);
11896
+ resetIdleTimer(true);
11897
+ },
11898
+
10632
11899
  stepRate(dir) {
10633
11900
  const current = currentPlaybackRate();
10634
11901
  let i = RATE_STEPS.findIndex(r => r >= current - 0.01);
@@ -11462,6 +12729,10 @@
11462
12729
  _onChildMessage(ifr, data) {
11463
12730
  const isTarget = STATE.cinemaIframe === ifr;
11464
12731
  switch (data.type) {
12732
+ case 'NXU_TUNE_DATA':
12733
+ if (!isTarget) break;
12734
+ if (IS_TOP) TUNE.onFrameData(data); else FRAME.postToParent(data);
12735
+ break;
11465
12736
  case 'NXU_VIDEO_FOUND':
11466
12737
  this._watchFrameBox(ifr);
11467
12738
  this.frameReports.set(ifr, {
@@ -11544,6 +12815,10 @@
11544
12815
  this._reportUp(true);
11545
12816
  this.probeFrames();
11546
12817
  break;
12818
+ case 'NXU_TUNE':
12819
+ if (STATE.video) TUNE.onFrameRequest(data);
12820
+ else if (STATE.cinemaIframe) FRAME.postToFrame(STATE.cinemaIframe, data);
12821
+ break;
11547
12822
  }
11548
12823
  },
11549
12824
 
@@ -11551,7 +12826,7 @@
11551
12826
  window.addEventListener('message', (e) => {
11552
12827
  const data = e.data;
11553
12828
  if (!FRAME.isValid(data)) return;
11554
- if (['NXU_CINEMA', 'NXU_SYNC_CMD', 'NXU_CAPTION', 'NXU_PROBE', 'NXU_MEDIA_CMD'].includes(data.type)) {
12829
+ if (['NXU_CINEMA', 'NXU_SYNC_CMD', 'NXU_CAPTION', 'NXU_PROBE', 'NXU_MEDIA_CMD', 'NXU_TUNE'].includes(data.type)) {
11555
12830
  if (FRAME.isFromParent(e)) this._onParentMessage(data);
11556
12831
  return;
11557
12832
  }
@@ -11634,7 +12909,7 @@
11634
12909
  updateRateButton();
11635
12910
  if (uiElements.btnCinema) uiElements.btnCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none';
11636
12911
  if (uiElements.btnAutoCinema) { uiElements.btnAutoCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none'; AUTO_CINEMA.paintButton(); }
11637
- if (uiElements.btnBookmark) uiElements.btnBookmark.style.display = hasMedia ? '' : 'none';
12912
+ if (uiElements.btnBookmark) uiElements.btnBookmark.style.display = ''; // the library is useful anywhere
11638
12913
  if (uiElements.btnFindMedia) uiElements.btnFindMedia.style.display = hasMedia ? 'none' : '';
11639
12914
  if (uiElements.btnLink) uiElements.btnLink.style.display = hasMedia || connected ? '' : 'none';
11640
12915
  updateDockMenuState();
@@ -11645,7 +12920,7 @@
11645
12920
  const show = connected ? '' : 'none';
11646
12921
  const hasHistory = !!uiElements.subLogMessages?.childElementCount;
11647
12922
  const showSubLog = connected || TRANSLATOR.active || hasHistory;
11648
- ['btnSyncStatus', 'btnDraw', 'btnChat', 'btnInvite'].forEach(key => { if (uiElements[key]) uiElements[key].style.display = show; });
12923
+ ['btnSyncStatus', 'btnDraw', 'btnChat', 'btnInvite', 'btnTune'].forEach(key => { if (uiElements[key]) uiElements[key].style.display = show; });
11649
12924
  if (uiElements.btnSubLog) uiElements.btnSubLog.style.display = showSubLog ? '' : 'none';
11650
12925
  if (!connected) {
11651
12926
  if (STATE.chatActive) {