diff --git a/_locales/en/messages.json b/_locales/en/messages.json index f3c17c193..3b2c4e691 100644 --- a/_locales/en/messages.json +++ b/_locales/en/messages.json @@ -1835,5 +1835,81 @@ }, "smartSpeedDeleteProfile": { "message": "🗑️ Delete Profile" + }, + "smartSpeedCaptionsEnable": { + "message": "Enable Transcript Analysis" + }, + "smartSpeedCaptionWeight": { + "message": "Caption Weight" + }, + "smartSpeedSpeechLeadSeconds": { + "message": "Speech Lead-in (Seconds)" + }, + "smartSpeedSpeechReleaseSeconds": { + "message": "Speech Release (Seconds)" + }, + "smartSpeedSponsorBlockEnable": { + "message": "SponsorBlock Integration" + }, + "smartSpeedIntroOutroEnable": { + "message": "Intro/Outro Detection" + }, + "smartSpeedIntroOutroMax": { + "message": "Intro/Outro Max Speed" + }, + "smartSpeedSkipIntroButton": { + "message": "Show 'Skip Intro' Button" + }, + "smartSpeedSkipSponsorButton": { + "message": "Show 'Skip Sponsor' Button" + }, + "smartSpeedNoHeatmapFallbackMode": { + "message": "Fallback Mode (No Heatmap)" + }, + "smartSpeedFallbackCaptions": { + "message": "Transcript / Speech Detection" + }, + "smartSpeedFallbackDefaultSpeed": { + "message": "Normal Speed (1.0x)" + }, + "smartSpeedFallbackFixedSpeed": { + "message": "Fixed Speed" + }, + "smartSpeedNoHeatmapFixedSpeed": { + "message": "Fixed Fallback Speed" + }, + "smartSpeedWhitelistShorts": { + "message": "Disable for Shorts" + }, + "smartSpeedShortVideoThreshold": { + "message": "Short Video Threshold (Seconds)" + }, + "smartSpeedWhitelistLive": { + "message": "Disable for Live Streams" + }, + "smartSpeedRulePriority": { + "message": "Rule Evaluation Priority" + }, + "smartSpeedPriorityChannelCategoryLanguage": { + "message": "Channel > Category > Language" + }, + "smartSpeedPriorityChannelLanguageCategory": { + "message": "Channel > Language > Category" + }, + "smartSpeedPriorityLanguageChannelCategory": { + "message": "Language > Channel > Category" + }, + "smartSpeedPriorityCategoryChannelLanguage": { + "message": "Category > Channel > Language" + }, + "smartSpeedSelectLanguage": { + "message": "2. Select Audio Language" + }, + "smartSpeedSelectLanguagePlaceholder": { + "message": "Select Language..." + }, + "smartSpeedAddSelectedLanguage": { + "message": "➕ Add Selected Language" } } + diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index c13213a0c..6b205f6f4 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -560,11 +560,44 @@ document.addEventListener('it-message-from-extension', function () { ImprovedTube.selectDubbedLanguage(); } break - case 'smartSpeed': - if (ImprovedTube.storage.smart_speed === true) { if(ImprovedTube.heatmap) {ImprovedTube.heatmap.init(); }; - } else if (ImprovedTube.storage.smart_speed === false) { if(ImprovedTube.heatmap) { ImprovedTube.heatmap.isEnabled = false; document.querySelector("video").playbackRate = 1.0; } - } + case 'smartSpeed': + case 'smartSpeedIndicator': + case 'smartSpeedMin': + case 'smartSpeedMax': + case 'smartSpeedSensitivity': + case 'smartSpeedCaptionsEnabled': + case 'smartSpeedCaptionWeight': + case 'smartSpeedSpeechLeadSeconds': + case 'smartSpeedSpeechReleaseSeconds': + case 'smartSpeedSponsorblockEnabled': + case 'smartSpeedIntrooutroEnabled': + case 'smartSpeedIntrooutroMax': + case 'smartSpeedSkipIntroButton': + case 'smartSpeedSkipSponsorButton': + case 'smartSpeedNoHeatmapFallbackMode': + case 'smartSpeedNoHeatmapFixedSpeed': + case 'smartSpeedWhitelistShorts': + case 'smartSpeedShortVideoThresholdSeconds': + case 'smartSpeedWhitelistLive': + case 'smartSpeedRulePriority': + case 'smartSpeedProfiles': + if (message.key === 'smart_speed') { + if (ImprovedTube.storage.smart_speed === true) { + if (ImprovedTube.smartSpeed?.init) { ImprovedTube.smartSpeed.init(); } + else if (ImprovedTube.heatmap?.init) { ImprovedTube.heatmap.init(); } + } else if (ImprovedTube.storage.smart_speed === false) { + if (ImprovedTube.smartSpeed?._teardown) { ImprovedTube.smartSpeed._teardown(); } + else if (ImprovedTube.heatmap?.isEnabled !== undefined) { ImprovedTube.heatmap.isEnabled = false; } + const v = document.querySelector("video"); + if (v) v.playbackRate = 1.0; + } + } else { + if (ImprovedTube.smartSpeed?.onStorageChanged) { + ImprovedTube.smartSpeed.onStorageChanged(message.key, message.value); + } + } break + case 'returnYoutubeDislike': if (ImprovedTube.storage.return_youtube_dislike === true) { ImprovedTube.returnYoutubeDislike(); diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index 048d67633..33bf2fd55 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -498,9 +498,14 @@ ImprovedTube.initPlayer = function () { if (ImprovedTube.storage.hide_auto_dubbed_options === true) { ImprovedTube.observeAutoDubbedMenu(); } if (ImprovedTube.storage.preferred_dubbing_language) { ImprovedTube.preferredDubbingLanguage(); } if (ImprovedTube.storage.player_default_dubbed_language && ImprovedTube.storage.player_default_dubbed_language !== 'disabled') { ImprovedTube.selectDubbedLanguage(); } + if (ImprovedTube.storage.smart_speed === true) { + if (ImprovedTube.smartSpeed?.init) { ImprovedTube.smartSpeed.init(); } + else if (ImprovedTube.heatmap?.init) { ImprovedTube.heatmap.init(); } + } } }; + var timeUpdateInterval = null; var noTimeUpdate = null; diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 02ae9a7e5..0aa8db02e 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -3316,519 +3316,1599 @@ ImprovedTube.shortsAutoScroll = function () { } }; -/*------------------------------------------------------------------------------ -SMART SPEED ENGINE (HEATMAP) -------------------------------------------------------------------------------*/ -ImprovedTube.heatmap = { - data: null, - segments: [], - rawMarkersCache: [], - sessionDisabled: false, - targetDurationOverride: null, - indicatorElement: null, - loopInterval: null, - uiInterval: null, - isEnabled: false, - - init: function () { - this.isEnabled = ImprovedTube.storage.smart_speed === true; - console.log('[ImprovedTube] Smart Speed: Init called. Enabled:', this.isEnabled); - if (!this.isEnabled) return; - - this.sessionDisabled = false; - this.targetDurationOverride = null; - this.data = null; - this.segments = []; - this.rawMarkersCache = []; - - this.injectUI(); - this.getData(); - - // Keeps the Whitelist shield accurately updated even if channel changes - if (this.uiInterval) clearInterval(this.uiInterval); - this.uiInterval = setInterval(() => this.updateWhitelistUI(), 1000); - - const video = document.querySelector('video'); - if (video && !video.dataset.itSmartSpeedAttached) { - video.dataset.itSmartSpeedAttached = 'true'; - video.addEventListener('loadeddata', () => { - if (this.isEnabled) { - this.sessionDisabled = false; - this.targetDurationOverride = null; - if (this.indicatorElement) this.indicatorElement.style.opacity = '1'; - this.getData(); - } - }); - } - }, - // SLEEK TOAST NOTIFICATION - showToast: function(message) { - const player = document.querySelector('.html5-video-player'); - if (!player) return; - - let toast = document.getElementById('it-smart-speed-toast'); - if (!toast) { - toast = document.createElement('div'); - toast.id = 'it-smart-speed-toast'; - Object.assign(toast.style, { - position: 'absolute', bottom: '70px', left: '50%', transform: 'translateX(-50%)', - background: 'rgba(0,0,0,0.85)', color: '#fff', padding: '10px 20px', - borderRadius: '4px', zIndex: 9999, fontSize: '14px', fontWeight: 'bold', - pointerEvents: 'none', opacity: '0', transition: 'opacity 0.3s ease-in-out', - border: '1px solid rgba(255,255,255,0.1)' - }); - player.appendChild(toast); - } +/*============================================================================== +SMART SPEED ENGINE +================================================================================ +*/ - toast.innerText = message; - toast.style.opacity = '1'; +(function () { + 'use strict'; + if (typeof ImprovedTube === 'undefined') return; - if (this.toastTimeout) clearTimeout(this.toastTimeout); - this.toastTimeout = setTimeout(() => { - if (toast) toast.style.opacity = '0'; - }, 2500); - }, + /*========================================================================== + 0. UTILITIES + Shared helpers used across the modules below. + ==========================================================================*/ + const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)); - // UI INJECTIONS - injectUI: function () { - const player = document.querySelector('.html5-video-player'); - const controls = document.querySelector('.ytp-right-controls'); - if (!player || !controls) return; + const toNum = (v, fallback, lo = -Infinity, hi = Infinity) => { + if (v === null || v === undefined || v === '') return fallback; + const n = Number(v); + return Number.isFinite(n) ? clamp(n, lo, hi) : fallback; + }; - // 1. Indicator Toggle (Moved to native control bar) - if (!document.getElementById('it-smart-speed-indicator')) { - console.log('[ImprovedTube] Smart Speed: Injecting Speed Indicator into Control Bar'); - this.indicatorElement = document.createElement('button'); - this.indicatorElement.id = 'it-smart-speed-indicator'; - this.indicatorElement.className = 'ytp-button'; + function debugLog(...args) { + if (ImprovedTube.storage && ImprovedTube.storage.smart_speed_debug === true) { + console.debug('[SmartSpeed]', ...args); + } + } - // Styled as a native YouTube text button - this.indicatorElement.style.cssText = 'width: auto; padding: 0 8px; font-weight: bold; font-size: 13px; color: white; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: opacity 0.2s;'; + /** Updates the key in memory and relays the change through the + * content-script bridge so it's persisted and other contexts stay in sync. */ + function setStorage(key, value) { + ImprovedTube.storage[key] = value; + if (ImprovedTube.messages && typeof ImprovedTube.messages.send === 'function') { + ImprovedTube.messages.send({ action: 'storage-set', key, value }); + } + } - if (ImprovedTube.storage.smart_speed_indicator === false) { - this.indicatorElement.style.display = 'none'; - } + /** fetch() with a timeout, plus an optional external AbortSignal + * (e.g. to cancel when the user navigates away from a video). */ + async function fetchWithTimeout(url, { timeoutMs = 5000, signal, ...opts } = {}) { + const ctrl = new AbortController(); + const onExternalAbort = () => ctrl.abort(); + if (signal) { + if (signal.aborted) ctrl.abort(); + else signal.addEventListener('abort', onExternalAbort, { once: true }); + } + const timer = setTimeout(() => ctrl.abort(), timeoutMs); + try { + return await fetch(url, { ...opts, signal: ctrl.signal }); + } finally { + clearTimeout(timer); + if (signal) signal.removeEventListener('abort', onExternalAbort); + } + } - this.indicatorElement.innerText = "⚡ 1.0x"; - this.indicatorElement.title = "Toggle Smart Speed"; + async function sha256Hex(str) { + if (typeof crypto !== 'undefined' && crypto.subtle) { + try { + const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str)); + return Array.from(new Uint8Array(buf), b => b.toString(16).padStart(2, '0')).join(''); + } catch (e) { + debugLog('SHA-256 digest failed', e); + } + } + return null; + } - this.indicatorElement.addEventListener('click', () => { - this.sessionDisabled = !this.sessionDisabled; - console.log('[ImprovedTube] Smart Speed: Toggled session disabled state:', this.sessionDisabled); - let video = document.querySelector('video'); - if (this.sessionDisabled) { - this.indicatorElement.style.opacity = '0.5'; - this.indicatorElement.innerText = "⚡ Off"; - if (video) video.playbackRate = Number(ImprovedTube.storage.player_custom_playback_speed) || 1.0; - this.showToast('⏸️ Smart Speed paused for this session'); - } else { - this.indicatorElement.style.opacity = '1'; - // If no heatmap data, the loop can't apply speed — do it here - if (this.segments.length === 0) { - this.applyNoHeatmapSpeed(); - } else { - this.indicatorElement.innerText = "⚡ On"; - } - this.showToast('▶️ Smart Speed resumed'); - } - }); - controls.prepend(this.indicatorElement); + /** Fixed-capacity cache that evicts the oldest entry once full. */ + class LRUCache { + constructor(max) { this.max = max; this.map = new Map(); } + get(key) { return this.map.get(key); } + has(key) { return this.map.has(key); } + set(key, value) { + this.map.delete(key); + this.map.set(key, value); + if (this.map.size > this.max) this.map.delete(this.map.keys().next().value); } + delete(key) { this.map.delete(key); } + } - // 2. Whitelist Toggle Button (The Shield) - if (!document.getElementById('it-smart-whitelist-btn')) { - console.log('[ImprovedTube] Smart Speed: Injecting Whitelist Toggle'); - let wlBtn = document.createElement('button'); - wlBtn.id = 'it-smart-whitelist-btn'; - wlBtn.className = 'ytp-button'; - wlBtn.style.cssText = 'font-size: 16px; font-weight: bold; color: white; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s;'; - wlBtn.innerText = '🛡️'; - - wlBtn.onclick = () => { - const channelNameElement = document.querySelector('.ytd-channel-name a') || document.querySelector('#upload-info .ytd-channel-name'); - const channelName = channelNameElement ? channelNameElement.textContent.trim() : "Unknown"; - - if (channelName === "Unknown" || !channelName) { - this.showToast("Channel name not loaded yet. Try again."); - return; - } + const _entityTextarea = typeof document !== 'undefined' ? document.createElement('textarea') : null; + const decodeEntities = (s) => { + if (!s || !s.includes('&')) return s || ''; + if (_entityTextarea) { _entityTextarea.innerHTML = s; return _entityTextarea.value; } + return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, "'").replace(/"/g, '"'); + }; + const normalizeText = (s) => decodeEntities(String(s ?? '')).replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); + + // Matches non-speech captions like "[music]" or "(applause)" so they're + // excluded when building speech blocks. + const NON_SPEECH_REGEX = /^[\(\[\{♪\s]*(music|applause|laughter|chuckle|gasp|cough|groan|sigh|cheering|crowd|noise|silence|singing|playing|instrumental|beep|static|screaming|cheers|unintelligible|indistinct)[\)\]\}♪\s]*$/i; + const isNonSpeech = (text) => { + if (!text) return true; + if (NON_SPEECH_REGEX.test(text)) return true; + if (/^[♪\s]+$/.test(text)) return true; + if (/^[\[\(\{\s]*[\]\)\}\s]*$/.test(text)) return true; + return false; + }; - let profiles = ImprovedTube.storage.smart_speed_profiles || {}; - if (!profiles[channelName]) { - profiles[channelName] = { max: 2.0, min: 1.0, sens: 0.5, whitelist: false }; + // Rough syllable-count heuristic for how long a caption cue takes to speak, + // used when a cue has no reliable duration of its own. + function estimateCueSpeechDuration(text) { + const words = normalizeText(text).split(/\s+/).filter(Boolean); + if (words.length === 0) return 1.0; + let totalSyllables = 0, complexBonus = 0; + for (const w of words) { + const clean = w.toLowerCase().replace(/[^\p{L}\p{N}]/gu, ''); + if (!clean) continue; + let syl = 1; + if (/[a-z]/.test(clean)) { + if (clean.length > 3) { + const matches = clean.replace(/(?:ing|ed|es|e)$/, '').match(/[aeiouy]{1,2}/g); + syl = matches ? matches.length : 1; } + } else { + syl = Math.max(1, Math.ceil(clean.length / 3.5)); + } + totalSyllables += syl; + if (syl >= 3) complexBonus += 0.25; + } + return clamp((totalSyllables / 3.8) + complexBonus, 1.0, 12.0); + } - profiles[channelName].whitelist = !profiles[channelName].whitelist; - ImprovedTube.messages.send({ action: 'storage-set', key: 'smart_speed_profiles', value: profiles }); + // Padding added before/after each cue so playback slows down slightly + // ahead of and after the spoken line, not just during it. + const SPEECH_LEAD_IN = 2.0, SPEECH_TAIL = 1.0; + function buildSpeechBlocksFromCues(rawCues) { + const cues = rawCues + .map(c => ({ ...c, text: normalizeText(c.text) })) + .filter(c => c.text && !isNonSpeech(c.text) && Number.isFinite(c.start)) + .sort((a, b) => a.start - b.start); + + const blocks = []; + cues.forEach((c, i) => { + const dur = Math.max(c.dur || 0, estimateCueSpeechDuration(c.text)); + let end = c.start + dur + SPEECH_TAIL; + if (cues[i + 1]) end = Math.min(end, cues[i + 1].start - SPEECH_LEAD_IN + SPEECH_TAIL); + const start = Math.max(0, c.start - SPEECH_LEAD_IN); + if (end > start) blocks.push({ start, end, confidence: 1 }); + }); + return blocks; + } - if (profiles[channelName].whitelist) { - this.showToast(`🛡️ Whitelisted ${channelName} (Speedup Disabled)`); + /*========================================================================== + 1. SPEECH MAP + Sorted timeline of speech blocks with cosine-eased lead-in/release + ramps, used to slow playback around dialogue. + ==========================================================================*/ + const SPEECH_MERGE_MAX_GAP_SEC = 3.0; + const SPEECH_MIN_BLOCK_DURATION_SEC = 0.5; + + class SpeechMap { + constructor() { this.blocks = []; } + reset() { this.blocks = []; } + + addBlocks(list) { + if (!Array.isArray(list) || list.length === 0) return; + const input = list + .map(b => ({ + start: Math.max(0, Number(b.start || 0)), + end: Math.max(0, Number(b.end || 0)), + confidence: typeof b.confidence === 'number' ? clamp(b.confidence, 0, 1) : 1.0 + })) + .filter(b => b.end > b.start) + .sort((a, b) => a.start - b.start); + if (input.length === 0) return; + + const merged = []; + let curr = { ...input[0] }; + for (let i = 1; i < input.length; i++) { + const next = input[i]; + if (next.start <= curr.end || (next.start - curr.end) <= SPEECH_MERGE_MAX_GAP_SEC) { + curr.end = Math.max(curr.end, next.end); + curr.confidence = Math.max(curr.confidence, next.confidence); } else { - this.showToast(`▶️ Removed ${channelName} from Whitelist`); + if ((curr.end - curr.start) >= SPEECH_MIN_BLOCK_DURATION_SEC) merged.push(curr); + curr = { ...next }; } + } + if ((curr.end - curr.start) >= SPEECH_MIN_BLOCK_DURATION_SEC) merged.push(curr); + this.blocks = merged; + } - console.log(`[ImprovedTube] Smart Speed: Toggled whitelist for ${channelName} to ${profiles[channelName].whitelist}`); + // Binary search for the nearest blocks, then apply the cosine ease + // in/out if `t` falls just before or after one. + probabilityAt(t, leadSec = 5.0, releaseSec = 2.0) { + if (this.blocks.length === 0) return 0; + const lead = Math.max(0, leadSec), release = Math.max(0, releaseSec); - this.updateWhitelistUI(); - if (this.rawMarkersCache && this.rawMarkersCache.length > 0) { - this.processSegments(this.rawMarkersCache); + let low = 0, high = this.blocks.length - 1, idx = -1; + while (low <= high) { + const mid = (low + high) >> 1; + if (this.blocks[mid].start <= t) { idx = mid; low = mid + 1; } else { high = mid - 1; } + } + const candidates = new Set([idx, idx + 1, idx - 1].filter(i => i >= 0 && i < this.blocks.length)); + + let maxProb = 0; + for (const i of candidates) { + const b = this.blocks[i]; + let p = 0; + if (t >= b.start && t <= b.end) p = b.confidence; + else if (t < b.start && (b.start - t) <= lead && lead > 0) { + p = b.confidence * (0.5 * (1 + Math.cos(Math.PI * ((b.start - t) / lead)))); + } else if (t > b.end && (t - b.end) <= release && release > 0) { + p = b.confidence * (0.5 * (1 + Math.cos(Math.PI * ((t - b.end) / release)))); } - }; - controls.prepend(wlBtn); + if (p > maxProb) maxProb = p; + } + return maxProb; } + } - // 3. Key Scene (Next Peak) Button - if (!document.getElementById('it-smart-peak-btn')) { - console.log('[ImprovedTube] Smart Speed: Injecting Next Peak Button'); - let peakBtn = document.createElement('button'); - peakBtn.id = 'it-smart-peak-btn'; - peakBtn.className = 'ytp-button'; - peakBtn.style.cssText = 'font-size: 16px; font-weight: bold; color: white; display: inline-flex; align-items: center; justify-content: center;'; - peakBtn.innerText = '⏭️'; - peakBtn.title = "Jump to next high-engagement scene"; - peakBtn.onclick = () => this.jumpToNextPeak(); - controls.prepend(peakBtn); + /*========================================================================== + 2. SPONSORBLOCK CLIENT + Queries the SponsorBlock API using k-anonymity (hash-prefix) lookup, + caching results per video with a result-dependent TTL. + ==========================================================================*/ + const SponsorBlockClient = { + _cache: new LRUCache(20), + _inflight: new Map(), + TTL: { ok: 6 * 36e5, empty: 30 * 6e4, error: 6e4 }, + + isNeeded() { + const s = ImprovedTube.storage || {}; + return s.smart_speed_sponsorblock_enabled !== false + || s.smart_speed_introoutro_enabled !== false + || s.smart_speed_skip_intro_button !== false + || s.smart_speed_skip_sponsor_button !== false; + }, + + + get(videoId, signal) { + if (!videoId) return Promise.resolve([]); + const hit = this._cache.get(videoId); + if (hit && hit.expires > Date.now()) return Promise.resolve(hit.segments); + if (this._inflight.has(videoId)) return this._inflight.get(videoId); + + const p = this._fetch(videoId, signal).finally(() => this._inflight.delete(videoId)); + this._inflight.set(videoId, p); + return p; + }, + + async _fetch(videoId, signal) { + let segments = [], ttl = this.TTL.error; + try { + const hash = await sha256Hex(videoId); + if (!hash) return segments; + const prefix = hash.slice(0, 4); + + const qs = new URLSearchParams({ + categories: JSON.stringify(['sponsor', 'intro', 'outro', 'selfpromo', 'preview']), + service: 'YouTube' + }); + const res = await fetchWithTimeout(`https://sponsor.ajay.app/api/skipSegments/${prefix}?${qs}`, { + credentials: 'omit', referrerPolicy: 'no-referrer', timeoutMs: 5000, signal + }); + + if (res.status === 404) { + ttl = this.TTL.empty; + } else if (res.ok) { + const data = await res.json(); + const entry = Array.isArray(data) ? data.find(e => e.videoID === videoId) : null; + segments = (entry?.segments || []).filter(s => + Array.isArray(s.segment) && s.segment.length === 2 && s.segment.every(Number.isFinite) + ); + ttl = segments.length ? this.TTL.ok : this.TTL.empty; + } + } catch (e) { + debugLog('SponsorBlock fetch error', e); + } + this._cache.set(videoId, { segments, expires: Date.now() + ttl }); + return segments; } + }; - // 4. Target Duration Button & Modal - if (!document.getElementById('it-smart-duration-btn')) { - console.log('[ImprovedTube] Smart Speed: Injecting Target Duration Button'); - let durBtn = document.createElement('button'); - durBtn.id = 'it-smart-duration-btn'; - durBtn.className = 'ytp-button'; - durBtn.style.cssText = 'font-size: 16px; font-weight: bold; color: white; display: inline-flex; align-items: center; justify-content: center;'; - durBtn.innerText = '⏱️'; - durBtn.title = "Set Target Duration for this video"; + /*========================================================================== + 3. HEATMAP SOURCE + Acquires heatmap markers through a tiered fallback: active player, + page globals, local cache, then a network fetch. `acquire()` returns + the first hit and never touches playback state. + ==========================================================================*/ + // Recursively searches a YouTube data object for the heatmap markers node. + function findMarkersDeep(obj, depth = 0) { + if (!obj || typeof obj !== 'object' || depth > 15) return null; + if (obj.markerType === 'MARKER_TYPE_HEATMAP' && Array.isArray(obj.markers)) return obj.markers; + if (obj.key === 'MARKER_TYPE_HEATMAP' && obj.value && Array.isArray(obj.value.markers)) return obj.value.markers; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + const found = findMarkersDeep(obj[key], depth + 1); + if (found) return found; + } + } + return null; + } - let modal = document.createElement('div'); - modal.id = 'it-smart-duration-modal'; - Object.assign(modal.style, { - position: 'absolute', bottom: '50px', right: '10px', background: 'rgba(20,20,20,0.95)', - padding: '10px', borderRadius: '8px', display: 'none', flexDirection: 'column', - gap: '8px', zIndex: 9999, border: '1px solid #444', minWidth: '180px' - }); + // Guards against reusing stale data left over from a previous video. + function belongsToVideo(data, expectedVideoId) { + if (!data || typeof data !== 'object' || !expectedVideoId) return false; + const vidId = data.videoDetails?.videoId + || data.currentVideoEndpoint?.watchEndpoint?.videoId + || data.endpoint?.watchEndpoint?.videoId; + return !vidId || vidId === expectedVideoId; + } - let mTitle = document.createElement('div'); - mTitle.style.cssText = 'color: white; font-size: 12px; font-weight: bold;'; - mTitle.innerText = 'Target Duration'; + const HeatmapSource = { + _cache: new LRUCache(50), + + rememberFor(videoId, markers) { + if (!videoId || !Array.isArray(markers)) return; + this._cache.set(videoId, markers.map(m => ({ + startMillis: Number(m.startMillis || 0), + durationMillis: Number(m.durationMillis || 0), + intensityScoreNormalized: Number(m.intensityScoreNormalized || 0) + }))); + }, + + /** Tier 1: the active YT player object already has it in memory. */ + fromActivePlayer(videoId) { + try { + const resp = document.getElementById('movie_player')?.getPlayerResponse?.(); + if (belongsToVideo(resp, videoId)) { + const markers = findMarkersDeep(resp); + if (markers?.length) return { markers, playerResponse: resp }; + } + } catch (e) { debugLog('heatmap: active player tier failed', e); } + return null; + }, + + /** Tier 2: page-global bootstrap data (present on first paint). */ + fromGlobals(videoId) { + try { + if (belongsToVideo(window.ytInitialData, videoId)) { + const markers = findMarkersDeep(window.ytInitialData); + if (markers?.length) return { markers, playerResponse: null }; + } + if (belongsToVideo(window.ytInitialPlayerResponse, videoId)) { + const markers = findMarkersDeep(window.ytInitialPlayerResponse); + if (markers?.length) return { markers, playerResponse: window.ytInitialPlayerResponse }; + } + } catch (e) { debugLog('heatmap: globals tier failed', e); } + return null; + }, + + /** Tier 3: something we already fetched earlier this session. */ + fromLocalCache(videoId) { + if (this._cache.has(videoId)) return { markers: this._cache.get(videoId), playerResponse: null }; + return null; + }, + + /** Tier 4 (network, last resort): raw watch-page HTML scrape. */ + async fromWatchPageFetch(videoId, signal) { + try { + const res = await fetchWithTimeout(`https://www.youtube.com/watch?v=${videoId}`, { + credentials: 'omit', timeoutMs: 8000, signal + }); + const text = await res.text(); + const matchData = text.match(/var ytInitialData = ({.*?});<\/script>/s) || text.match(/var ytInitialData = ({.*?});/s); + const matchResp = text.match(/var ytInitialPlayerResponse = ({.*?});<\/script>/s) || text.match(/var ytInitialPlayerResponse = ({.*?});/s); + + for (const match of [matchData, matchResp]) { + if (!match) continue; + try { + const parsed = JSON.parse(match[1]); + if (belongsToVideo(parsed, videoId)) { + const markers = findMarkersDeep(parsed); + if (markers?.length) return { markers, playerResponse: match === matchResp ? parsed : null }; + } + } catch (e) { /* try the next candidate */ } + } + } catch (e) { + debugLog('heatmap: watch-page fetch tier failed', e); + } + return null; + }, - let mInput = document.createElement('input'); - mInput.type = 'number'; - mInput.id = 'it-smart-duration-input'; - mInput.placeholder = 'Minutes'; - mInput.style.cssText = 'width: 100%; padding: 4px; background: #333; color: white; border: none; border-radius: 4px;'; + /** Walks all tiers in priority order; caches a hit; returns + * { markers, playerResponse } (markers === [] means "confirmed none"). */ + async acquire(videoId, signal) { + const sync = this.fromActivePlayer(videoId) || this.fromGlobals(videoId) || this.fromLocalCache(videoId); + if (sync) { this.rememberFor(videoId, sync.markers); return sync; } - let mApply = document.createElement('button'); - mApply.style.cssText = 'background: #3ea6ff; color: white; border: none; padding: 5px; border-radius: 4px; cursor: pointer;'; - mApply.innerText = 'Apply Math Algorithm'; + const remote = await this.fromWatchPageFetch(videoId, signal); + if (remote) { this.rememberFor(videoId, remote.markers); return remote; } - let mMsg = document.createElement('div'); - mMsg.id = 'it-smart-duration-msg'; - mMsg.style.cssText = 'color: #ff4e4e; font-size: 11px;'; + return { markers: [], playerResponse: null }; + } + }; - modal.appendChild(mTitle); - modal.appendChild(mInput); - modal.appendChild(mApply); - modal.appendChild(mMsg); - player.appendChild(modal); - controls.prepend(durBtn); + /*========================================================================== + 4. CAPTION SOURCE + Feeds the `transcript` signal. Tries the TimedText API first (fast, + no DOM access), falling back to scraping the transcript panel. + ==========================================================================*/ + const CaptionSource = { + getPlayerResponseHint(session) { return session?.playerResponse || null; }, + + async fromTimedTextApi(videoId, session, signal) { + const playerResponse = this.getPlayerResponseHint(session) || HeatmapSource.fromActivePlayer(videoId)?.playerResponse; + const tracks = playerResponse?.captions?.playerCaptionsTracklistRenderer?.captionTracks; + if (!Array.isArray(tracks) || tracks.length === 0) return null; + + const track = tracks.find(t => t.languageCode === 'en' && t.kind !== 'asr') + || tracks.find(t => t.languageCode === 'en') + || tracks.find(t => t.isTranslatable) + || tracks[0]; + if (!track?.baseUrl) return null; + + try { + const res = await fetchWithTimeout(track.baseUrl + '&fmt=json3', { timeoutMs: 6000, signal }); + if (!res.ok) return null; + const text = await res.text(); + let rawCues = []; + + if (text.trim().startsWith('{') || text.trim().startsWith('[')) { + try { + const data = JSON.parse(text); + for (const ev of data?.events || []) { + if (!ev.segs) continue; + const cueText = ev.segs.map(s => s.utf8 || '').join('').trim(); + const cueStart = (ev.tStartMs || 0) / 1000; + if (cueText && Number.isFinite(cueStart)) { + rawCues.push({ start: cueStart, dur: (ev.dDurationMs || 0) / 1000, text: cueText }); + } + } + } catch (e) { debugLog('timedtext json parse error', e); } + } + if (rawCues.length === 0) { + try { + const nodes = new DOMParser().parseFromString(text, 'text/xml').querySelectorAll('text'); + for (const node of nodes) { + const cueStart = parseFloat(node.getAttribute('start') || '0'); + const cueText = (node.textContent || '').trim(); + if (cueText && Number.isFinite(cueStart)) { + rawCues.push({ start: cueStart, dur: parseFloat(node.getAttribute('dur') || '0'), text: cueText }); + } + } + } catch (e) { debugLog('timedtext xml parse error', e); } + } - durBtn.onclick = () => modal.style.display = modal.style.display === 'none' ? 'flex' : 'none'; + const blocks = buildSpeechBlocksFromCues(rawCues); + return blocks.length ? blocks : null; + } catch (e) { + debugLog('timedtext fetch error', e); + return null; + } + }, + + async fromTranscriptPanel(isStale) { + if (document.fullscreenElement) return { blocks: null, status: 'unavailable:fullscreen' }; + + let button = null; + const searchStart = Date.now(); + while (Date.now() - searchStart < 10000) { + if (isStale()) return { blocks: null, status: null }; + for (const b of document.querySelectorAll('button, [role="button"]')) { + const label = (b.getAttribute('aria-label') || b.textContent || '').trim(); + if (/show transcript|transcript/i.test(label)) { button = b; break; } + } + if (button) break; + await new Promise(r => setTimeout(r, 500)); + } + if (!button) return { blocks: null, status: 'unavailable:no_button' }; + + const panelSelector = 'ytd-engagement-panel-section-list-renderer[target-id*="transcript"]'; + const alreadyExpanded = document.querySelector(panelSelector)?.getAttribute('visibility') === 'ENGAGEMENT_PANEL_VISIBILITY_EXPANDED'; + let openedByUs = false; + if (!alreadyExpanded) { + try { button.click(); openedByUs = true; } + catch (e) { return { blocks: null, status: 'unavailable:click_error' }; } + } - mApply.onclick = () => { - let inputMinutes = Number(mInput.value); - if (!inputMinutes) return; + let rows = []; + const pollStart = Date.now(); + while (Date.now() - pollStart < 5000) { + if (isStale()) return { blocks: null, status: null }; + rows = Array.from(document.querySelectorAll('transcript-segment-view-model, ytd-transcript-segment-renderer')); + if (rows.length) break; + await new Promise(r => setTimeout(r, 200)); + } - let targetSec = inputMinutes * 60; - let baseMax = Number(ImprovedTube.storage.smart_speed_max) || 2.0; - let duration = document.querySelector('video')?.duration || 0; - let absoluteMinSec = duration / baseMax; + // Close the panel again if we're the ones who opened it. + const restore = async () => { + if (!openedByUs) return; + const panel = document.querySelector(panelSelector); + const closeBtn = panel && ( + panel.querySelector('#visibility-button button') + || Array.from(panel.querySelectorAll('button')).find(b => /close/i.test(b.getAttribute('aria-label') || '')) + ); + if (closeBtn) { try { closeBtn.click(); } catch (e) { /* best-effort */ } } + }; - if (targetSec < absoluteMinSec) { - mMsg.style.color = '#ff4e4e'; - mMsg.innerText = `Impossible. Min mathematically possible is: ${Math.ceil(absoluteMinSec/60)}m ${Math.floor(absoluteMinSec%60)}s`; - console.log(`[ImprovedTube] Smart Speed: Target duration rejected. Target: ${targetSec}s, Absolute Min: ${absoluteMinSec}s`); - } else { - mMsg.style.color = '#2ba640'; - mMsg.innerText = "Algorithm Applied!"; - this.targetDurationOverride = targetSec; - this.processSegments(this.rawMarkersCache); - console.log(`[ImprovedTube] Smart Speed: Target duration activated -> ${targetSec}s`); - this.showToast(`⏱️ Video squeezed to ${inputMinutes} minutes!`); - setTimeout(() => { modal.style.display = 'none'; }, 1500); + if (rows.length === 0) { await restore(); return { blocks: null, status: 'unavailable:panel_empty' }; } + + const rawCues = []; + for (const row of rows) { + const rawText = (row.textContent || '').trim().replace(/\s+/g, ' '); + const match = rawText.match(/^(\d{1,2}:\d{2}(?::\d{2})?)\s+(.+)$/); + let timeText = '', cueText = ''; + if (match) { [, timeText, cueText] = match; } + else { + const timeEl = row.querySelector('.segment-timestamp, [class*="timestamp"], div[class*="time"]') || row.children[0]; + const textEl = row.querySelector('.segment-text, [class*="segment-text"], yt-formatted-string, [class*="text"]') || row.children[1]; + timeText = timeEl ? timeEl.textContent.trim() : ''; + cueText = textEl ? textEl.textContent.trim() : rawText.replace(timeText, '').trim(); } - }; - } - }, + if (!timeText || !cueText) continue; + const parts = timeText.split(':').map(p => parseInt(p, 10)); + let totalSec = null; + if (parts.length === 2 && !parts.some(isNaN)) totalSec = parts[0] * 60 + parts[1]; + else if (parts.length === 3 && !parts.some(isNaN)) totalSec = parts[0] * 3600 + parts[1] * 60 + parts[2]; + if (totalSec !== null) rawCues.push({ start: totalSec, text: cueText }); + } - // Updates the visual state of the Whitelist shield - updateWhitelistUI: function() { - const channelNameElement = document.querySelector('.ytd-channel-name a') || document.querySelector('#upload-info .ytd-channel-name'); - const channelName = channelNameElement ? channelNameElement.textContent.trim() : "Unknown"; + await restore(); + const blocks = buildSpeechBlocksFromCues(rawCues); + return { blocks: blocks.length ? blocks : null, status: blocks.length ? null : 'unavailable:parse_error' }; + }, - let profiles = ImprovedTube.storage.smart_speed_profiles || {}; - const genre = document.querySelector('meta[itemprop="genre"]')?.content || "Unknown"; + /** Returns { blocks, status } never throws. `isStale()` lets the + * caller cut a slow DOM scrape short if the user has navigated away. */ + async acquire(videoId, session, signal, isStale) { + if (ImprovedTube.storage.smart_speed_captions_enabled === false) { + return { blocks: null, status: 'unavailable:disabled' }; + } + const apiBlocks = await this.fromTimedTextApi(videoId, session, signal); + if (apiBlocks) return { blocks: apiBlocks, status: `active (${apiBlocks.length} blocks)` }; + if (isStale()) return { blocks: null, status: null }; - let isWhitelisted = (profiles[channelName] && profiles[channelName].whitelist) || (profiles[genre] && profiles[genre].whitelist); + const panelResult = await this.fromTranscriptPanel(isStale); + if (panelResult.blocks) return { blocks: panelResult.blocks, status: `active (${panelResult.blocks.length} blocks)` }; + return { blocks: null, status: panelResult.status || 'unavailable:unknown' }; + } + }; - let btn = document.getElementById('it-smart-whitelist-btn'); - if (btn) { - if (isWhitelisted) { - btn.style.opacity = '1'; - btn.title = `Remove ${channelName} from Whitelist`; - btn.style.textShadow = '0 0 8px #2ba640'; - } else { - btn.style.opacity = '0.5'; - btn.title = `Add ${channelName} to Whitelist`; - btn.style.textShadow = 'none'; - } + /*========================================================================== + 5. PROFILE RESOLVER + Resolves the effective speed settings {min, max, sens, weights, ...} + from the channel/category/language profile hierarchy. Cached until + `Profiles.invalidate()` is called. + ==========================================================================*/ + /** + * @typedef {Object} SpeedContext + * @property {number} currentSec - playback position being evaluated, in seconds + * @property {number} duration - total video duration, in seconds + * @property {Object} profile - resolved speed profile (see Profiles.resolve) + * @property {HTMLVideoElement} video + * @property {string|null} videoId + * @property {Session} session + * @property {Object|null} segment - heatmap segment being evaluated, or null + * @property {number} bias - target-duration speed bias, e.g. -0.5..+0.5 + */ + function makeContext({ currentSec = 0, duration = 0, profile = null, video = null, videoId = null, session = null, segment = null, bias = 0 } = {}) { + return { currentSec, duration, profile, video, videoId, session, segment, bias }; + } + + /** + * Returns the single canonical storage key for a channel identity. + * Prefers `channel:` when channel ID is available, falling back to + * `name:` when only display name is known. + */ + function canonicalChannelKey(ident) { + if (!ident) return null; + if (ident.id) return 'channel:' + ident.id; + if (ident.name) return 'name:' + ident.name; + return null; + } + + /** + * Migrates any existing profile entry saved under the channel's display name + * into the canonical ID-keyed slot once a channel ID becomes available. + */ + function migrateLegacyChannelKey(profiles, ident, cKey) { + if (!ident?.id || !ident?.name || !cKey) return; + const oldNameKey = ident.name; + const oldPrefixedKey = 'name:' + ident.name; + if (profiles[oldNameKey] || profiles[oldPrefixedKey]) { + const legacyData = profiles[oldNameKey] || profiles[oldPrefixedKey]; + profiles[cKey] = { ...legacyData, ...(profiles[cKey] || {}) }; + if (profiles[oldNameKey]) delete profiles[oldNameKey]; + if (profiles[oldPrefixedKey]) delete profiles[oldPrefixedKey]; + setStorage('smart_speed_profiles', profiles); } - }, + } - // DATA HUNTING - getData: function () { - console.log('[ImprovedTube] Smart Speed: Hunting for Heatmap...'); - try { - const playerResponse = document.getElementById('movie_player')?.getPlayerResponse(); - if (this.checkAndProcess(playerResponse, 'Active Player')) return; - } catch (e) {} + const Profiles = { + _cache: null, + _dirty: true, + invalidate() { this._dirty = true; }, + + channelIdentity(playerResponse) { + const details = playerResponse?.videoDetails; + if (details?.channelId) return { id: details.channelId, name: details.author || '' }; + const el = document.querySelector('.ytd-channel-name a') || document.querySelector('#upload-info .ytd-channel-name'); + const name = el ? el.textContent.trim() : null; + return name && name !== 'Unknown' ? { id: null, name } : null; + }, + + audioLanguage(playerResponse) { + const tracks = playerResponse?.captions?.playerCaptionsTracklistRenderer?.captionTracks || []; + const code = (tracks.find(t => t.kind === 'asr') || tracks[0])?.languageCode; + return code ? code.toLowerCase().split('-')[0] : null; + }, + + /** `ctxHint` = { playerResponse } — whatever the current session has + * handy, so we don't need to re-derive it from scratch every call. */ + resolve(ctxHint = {}) { + if (!this._dirty && this._cache) return this._cache; + + const playerResponse = ctxHint.playerResponse || null; + const ident = this.channelIdentity(playerResponse); + const genre = playerResponse?.microformat?.playerMicroformatRenderer?.category + || document.querySelector('meta[itemprop="genre"]')?.content + || 'Unknown'; + const audioLang = this.audioLanguage(playerResponse); + const profiles = ImprovedTube.storage.smart_speed_profiles || {}; + const priorityOrder = (ImprovedTube.storage.smart_speed_rule_priority || 'channel,category,language').split(',').map(s => s.trim()); + + let resolved = null, tier = 'global'; + for (const ruleType of priorityOrder) { + if (ruleType === 'channel' && ident) { + const cKey = canonicalChannelKey(ident); + if (cKey) { + migrateLegacyChannelKey(profiles, ident, cKey); + resolved = profiles[cKey] || (ident.name && profiles['name:' + ident.name]) || (ident.name && profiles[ident.name]); + if (resolved) { tier = 'channel'; break; } + } + } + if (ruleType === 'category') { + resolved = profiles['category:' + genre] || profiles[genre]; + if (resolved) { tier = 'category'; break; } + } + if (ruleType === 'language' && audioLang && profiles['lang:' + audioLang]) { + resolved = profiles['lang:' + audioLang]; + tier = 'language'; + break; + } + } - try { - if (this.checkAndProcess(window.ytInitialData, 'window.ytInitialData')) return; - if (this.checkAndProcess(window.ytInitialPlayerResponse, 'window.ytInitialPlayerResponse')) return; - } catch (e) {} - - const videoId = new URLSearchParams(window.location.search).get('v') || window.location.pathname.split('/').pop(); - if (videoId && videoId.length === 11) { - console.log('[ImprovedTube] Smart Speed: Level 1 and 2 failed. Fetching source...'); - fetch('https://www.youtube.com/watch?v=' + videoId) - .then(res => res.text()) - .then(text => { - const matchData = text.match(/var ytInitialData = ({.*?});/s); - const matchResp = text.match(/var ytInitialPlayerResponse = ({.*?});/s); - - if (matchData && this.checkAndProcess(JSON.parse(matchData[1]), 'Fetched ytInitialData')) return; - if (matchResp && this.checkAndProcess(JSON.parse(matchResp[1]), 'Fetched ytInitialPlayerResponse')) return; - console.log('[ImprovedTube] Smart Speed: Heatmap data not found in source either. Video lacks heatmap — defaulting to minimal speed.'); - this.rawMarkersCache = []; - this.processSegments([]); - }).catch(() => { - // Network error — still default to minimal speed - console.log('[ImprovedTube] Smart Speed: Failed to fetch source. Defaulting to minimal speed.'); - this.rawMarkersCache = []; - this.processSegments([]); - }); + const s = ImprovedTube.storage || {}; + const min = toNum(resolved?.min ?? s.smart_speed_min, 1.0, 0.0625, 16); + let max = toNum(resolved?.max ?? s.smart_speed_max, 2.0, 0.0625, 16); + if (max < min) max = min; + + this._cache = { + min, max, + sens: toNum(resolved?.sens ?? s.smart_speed_sensitivity, 0.5, 0, 1), + speechLead: toNum(s.smart_speed_speech_lead_seconds, 5, 0, 30), + speechRelease: toNum(s.smart_speed_speech_release_seconds, 2, 0, 30), + whitelist: !!resolved?.whitelist, + signalWeights: Object.assign( + { heatmap: 1.0, transcript: toNum(s.smart_speed_caption_weight, 1.0, 0, 10) }, + resolved?.signalWeights || {} + ), + introOutroSpeed: toNum(s.smart_speed_introoutro_max, 2.0, 0.0625, 16), + tier, + channelIdentity: ident + }; + this._dirty = false; + return this._cache; } - }, + }; - findMarkers: function(obj) { - if (!obj || typeof obj !== 'object') return null; - if (obj.markerType === 'MARKER_TYPE_HEATMAP' && Array.isArray(obj.markers)) return obj.markers; - if (obj.key === 'MARKER_TYPE_HEATMAP' && obj.value && Array.isArray(obj.value.markers)) return obj.value.markers; - for (let key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - const found = this.findMarkers(obj[key]); - if (found) return found; + /** Storage keys that invalidate the resolved profile when changed. */ + const PROFILE_AFFECTING_KEYS = new Set([ + 'smart_speed_profiles', 'smart_speed_rule_priority', 'smart_speed_min', + 'smart_speed_max', 'smart_speed_sensitivity', 'smart_speed_speech_lead_seconds', + 'smart_speed_speech_release_seconds', 'smart_speed_caption_weight', 'smart_speed_introoutro_max' + ]); + + /*========================================================================== + 6. SIGNAL REGISTRY + Weighted speed inputs. Each signal is + `{ defaultWeight, enabledKey?, compute(ctx) }`, where compute(ctx) + returns null (not applicable) or {value, confidence}. + computeCompositeSpeed() below blends all active signals — add new + signals here. + ==========================================================================*/ + const Signals = { + heatmap: { + defaultWeight: 1.0, + compute(ctx) { + if (!ctx.segment) return null; + const { sens, min, max } = ctx.profile; + const intensity = clamp(ctx.segment.intensity, 0, 1); + const saturation = Math.max(0.05, 1 - sens); + const t = clamp(intensity / saturation, 0, 1); + return { value: min + (max - min) * (1 - t), confidence: 1.0 }; + } + }, + transcript: { + defaultWeight: 1.0, + enabledKey: 'smart_speed_captions_enabled', + compute(ctx) { + const speechMap = ctx.session?.speechMap; + if (!speechMap || speechMap.blocks.length === 0) return null; + const prob = speechMap.probabilityAt(ctx.currentSec, ctx.profile.speechLead, ctx.profile.speechRelease); + if (prob <= 0) return null; + return { value: ctx.profile.min, confidence: prob }; } } - return null; - }, - - checkAndProcess: function (rootObject, sourceName) { - if (!rootObject) return false; - const markers = this.findMarkers(rootObject); - if (markers && markers.length > 0) { - console.log('[ImprovedTube] Smart Speed: 🎯 Found Heatmap via: ' + sourceName); - this.rawMarkersCache = markers; - this.processSegments(markers); - return true; + }; + + // Blends the active signals into one target speed, weighted by + // (profile weight * signal confidence). + function computeCompositeSpeed(ctx) { + const profile = ctx.profile; + const active = []; + + for (const name in Signals) { + const sig = Signals[name]; + if (sig.enabledKey && ImprovedTube.storage[sig.enabledKey] === false) continue; + const result = sig.compute(ctx); + if (!result) continue; + const baseWeight = profile.signalWeights?.[name] ?? sig.defaultWeight; + const confidence = typeof result.confidence === 'number' ? result.confidence : 1.0; + const effectiveWeight = baseWeight * confidence; + if (effectiveWeight > 0) active.push({ name, value: result.value, weight: effectiveWeight }); } - return false; - }, - - // Applies the minimal speed fallback when no heatmap segments exist - applyNoHeatmapSpeed: function() { - const video = document.querySelector('video'); - let base = Number(ImprovedTube.storage.player_custom_playback_speed) || 1.0; - let baseMin = Number(ImprovedTube.storage.smart_speed_min) || 1.0; - let finalSpeed = base * baseMin; - if (video) video.playbackRate = finalSpeed; - if (this.indicatorElement) { - this.indicatorElement.innerText = `⚡ ${baseMin.toFixed(2)}x`; - this.indicatorElement.style.opacity = '1'; + + if (ctx.session) ctx.session.lastActiveSignals = active; + if (active.length === 0) return profile.max; // no usable signal means default to the ceiling + + const totalWeight = active.reduce((s, a) => s + a.weight, 0); + const weighted = active.reduce((s, a) => s + a.value * (a.weight / totalWeight), 0); + return clamp(weighted + (ctx.bias || 0), profile.min, profile.max); + } + + // Target speed to use when no heatmap data is available for the video. + function noHeatmapTargetSpeed(ctx) { + const mode = ImprovedTube.storage.smart_speed_no_heatmap_fallback_mode || 'captions'; + if (mode === 'default_speed') return { speed: 1.0, source: 'Fallback (1.0x)' }; + if (mode === 'fixed_speed') { + const fixed = toNum(ImprovedTube.storage.smart_speed_no_heatmap_fixed_speed, 1.5, 0.0625, 16); + return { speed: fixed, source: `Fallback (${fixed.toFixed(1)}x)` }; } - }, + const synthCtx = makeContext({ ...ctx, segment: ctx.segment || { intensity: 0.25 } }); + return { speed: computeCompositeSpeed(synthCtx), source: 'Captions Fallback (0.25 Heatmap)' }; + } - // PROCESSING ENGINE - processSegments: function (rawMarkers) { - const video = document.querySelector('video'); - const duration = video ? video.duration : 0; + /*========================================================================== + 7. OVERRIDE REGISTRY + Absolute (non-blended) speeds, checked in order — first match wins. + Each entry is `{ name, enabledKey, resolve(ctx) }`, returning null or + {source, speed}. + ==========================================================================*/ + const Overrides = [ + { + name: 'sponsorBlock', + enabledKey: 'smart_speed_sponsorblock_enabled', + resolve(ctx) { + const segs = ctx.session?.sponsorSegments || []; + const match = segs.find(s => s.category === 'sponsor' && ctx.currentSec >= s.segment[0] && ctx.currentSec <= s.segment[1]); + return match ? { source: 'SponsorBlock (sponsor)', speed: 3.0 } : null; + } + }, + { + name: 'introOutro', + enabledKey: 'smart_speed_introoutro_enabled', + resolve(ctx) { + const speed = ctx.profile.introOutroSpeed; + const segs = ctx.session?.sponsorSegments || []; + + const intro = segs.find(s => s.category === 'intro' && ctx.currentSec >= s.segment[0] && ctx.currentSec <= s.segment[1]); + if (intro) return { source: 'Intro (SponsorBlock)', speed }; + + const outro = segs.find(s => s.category === 'outro' && ctx.currentSec >= s.segment[0] && ctx.currentSec <= s.segment[1]); + if (outro) return { source: 'Outro (SponsorBlock)', speed }; + + // No SponsorBlock outro data for this video — fall back to + // treating the last few percent of the video as the outro. + const hasOutroData = segs.some(s => s.category === 'outro'); + if (!hasOutroData && ctx.duration > 120 && isFinite(ctx.duration)) { + const outroDurationSec = Math.min(15, ctx.duration * 0.03); + if (ctx.currentSec >= ctx.duration - outroDurationSec && ctx.currentSec < ctx.duration) { + return { source: 'Outro (heuristic)', speed }; + } + } + return null; + } + } + ]; - if (!duration || isNaN(duration)) { - setTimeout(() => this.processSegments(rawMarkers), 500); - return; + function resolveOverride(ctx) { + for (const ov of Overrides) { + if (ImprovedTube.storage[ov.enabledKey] === false) continue; + const result = ov.resolve(ctx); + if (result) return result; } + return null; + } - let baseMin = Number(ImprovedTube.storage.smart_speed_min) || 1.0; - let baseMax = Number(ImprovedTube.storage.smart_speed_max) || 2.0; - let sensitivity = Number(ImprovedTube.storage.smart_speed_sensitivity) || 0.5; + /*========================================================================== + 8. TARGET DURATION SOLVER + Binary-searches a global speed bias so the predicted wall-clock watch + time matches a user-requested target duration. + ==========================================================================*/ + const DurationSolver = { + predictWallClock(bias, ctxBase, segments, baseRate) { + let total = 0; + for (const seg of segments) { + const ctx = makeContext({ ...ctxBase, bias, currentSec: (seg.start + seg.end) / 2, segment: seg }); + const override = resolveOverride(ctx); + if (override) total += seg.duration / override.speed; + else total += seg.duration / (baseRate * computeCompositeSpeed(ctx)); + } + return total; + }, - const genre = document.querySelector('meta[itemprop="genre"]')?.content || "Unknown"; - const channelNameElement = document.querySelector('.ytd-channel-name a') || document.querySelector('#upload-info .ytd-channel-name'); - const channelName = channelNameElement ? channelNameElement.textContent.trim() : "Unknown"; - let profiles = ImprovedTube.storage.smart_speed_profiles || {}; + solve(targetSec, ctxBase, segments, baseRate) { + const span = ctxBase.profile.max - ctxBase.profile.min; + const fastest = this.predictWallClock(+span, ctxBase, segments, baseRate); + const slowest = this.predictWallClock(-span, ctxBase, segments, baseRate); - let activeProfile = profiles[channelName] || profiles[genre]; + if (targetSec < fastest) return { ok: false, reason: 'too-short', bestSec: fastest }; + if (targetSec > slowest) return { ok: false, reason: 'too-long', bestSec: slowest }; - if (activeProfile && activeProfile.whitelist) { - console.log(`[ImprovedTube] Smart Speed: WHITELIST ACTIVE for ${channelName || genre}. Engine idled.`); - this.sessionDisabled = true; - if (this.indicatorElement) { - this.indicatorElement.style.opacity = '0.5'; - this.indicatorElement.innerText = "⚡ Whitelisted"; + let lo = -span, hi = span; + for (let i = 0; i < 30; i++) { + const mid = (lo + hi) / 2; + if (this.predictWallClock(mid, ctxBase, segments, baseRate) > targetSec) lo = mid; else hi = mid; } - if (video) video.playbackRate = Number(ImprovedTube.storage.player_custom_playback_speed) || 1.0; - return; - } else if (activeProfile) { - console.log(`[ImprovedTube] Smart Speed: Profile applied -> Min:${activeProfile.min} Max:${activeProfile.max}`); - baseMax = activeProfile.max || baseMax; - baseMin = activeProfile.min || baseMin; - sensitivity = activeProfile.sens || sensitivity; - this.sessionDisabled = false; - if (this.indicatorElement) this.indicatorElement.style.opacity = '1'; + return { ok: true, bias: (lo + hi) / 2 }; } + }; - // No heatmap data — default to minimal speed (whitelist already checked above) - if (rawMarkers.length === 0) { - console.log(`[ImprovedTube] Smart Speed: No heatmap data. Applying minimal speed: ${baseMin}x multiplier.`); - this.applyNoHeatmapSpeed(); + /*========================================================================== + 9. SESSION + State scoped to the video currently being watched. Starting a new + video creates a new Session rather than resetting fields on the old one. + ==========================================================================*/ + class Session { + constructor(videoId) { + this.videoId = videoId; + this.abort = typeof AbortController !== 'undefined' ? new AbortController() : null; + this.playerResponse = null; + this.markers = undefined; // undefined = not fetched yet; [] = confirmed none this.segments = []; - this.startLoop(); - return; + this.sponsorSegments = []; + this.speechMap = new SpeechMap(); + this.processedDuration = null; + this.lastSegIdx = -1; + this.lastActiveSignals = []; + this.captionStatus = 'pending'; + this.paused = false; // user manually paused Smart Speed for this session + this.targetBias = 0; + this.targetDurationOverride = null; } + get isCurrent() { return !Engine.session === false && Engine.session === this; } + dispose() { try { this.abort?.abort(); } catch (e) { /* already aborted */ } } + } - const chunkPct = 100 / rawMarkers.length; - let processed = rawMarkers.map((marker, index) => { - const score = typeof marker.intensityScoreNormalized === 'number' ? marker.intensityScoreNormalized : 0; - const start = ((index * chunkPct) / 100) * duration; - const end = (((index + 1) * chunkPct) / 100) * duration; - return { start, end, duration: end - start, intensity: score }; - }); + /*========================================================================== + 10. ENGINE + State machine driving the Smart Speed lifecycle. + ==========================================================================*/ + const STATE = Object.freeze({ + IDLE: 'idle', // extension/feature off, or no video + LOADING: 'loading', // session created, acquiring data + ACTIVE: 'active', // applying computed/override speed + WHITELISTED: 'whitelisted', // resolved profile says "leave alone" + EXCLUDED: 'excluded', // shorts/live/too-short, base rate only + PAUSED: 'paused', // user manually paused this session + AD: 'ad' // an ad is showing; base rate only + }); - // Target Duration Knapsack - if (this.targetDurationOverride && baseMax > 1.0) { - let reductionNeeded = duration - this.targetDurationOverride; - if (reductionNeeded > 0) { - let sorted = [...processed].sort((a, b) => a.intensity - b.intensity); - for (let seg of sorted) { - if (reductionNeeded <= 0) { - seg.speed = baseMin; - continue; - } - let maxTimeSaved = seg.duration - (seg.duration / baseMax); - if (maxTimeSaved <= reductionNeeded) { - seg.speed = baseMax; - reductionNeeded -= maxTimeSaved; - } else { - let newSegDuration = seg.duration - reductionNeeded; - seg.speed = seg.duration / newSegDuration; - reductionNeeded = 0; + const TICK_MS = 100; + const BOUNDARY_CROSSFADE_WINDOW_SEC = 2.5; + const SEEK_SUPPRESS_MS = 1000; + + const Engine = { + STATE, + session: null, + state: STATE.IDLE, + video: null, + loopTimer: null, + uiTimer: null, + adObserver: null, + adShowing: false, + expectedRate: null, + lastInitializedVideoId: null, + + /*---------------------------- helpers ----------------------------*/ + _getVideo() { + if (this.video?.isConnected) return this.video; + return (this.video = document.querySelector('#movie_player video.html5-main-video') || document.querySelector('video')); + }, + + _getVideoId() { + const loc = window.location; + const path = loc.pathname || ''; + if (!path.startsWith('/watch') && !path.startsWith('/shorts/')) return null; + if (typeof ImprovedTube.videoId === 'function') { + const id = ImprovedTube.videoId(); + if (id) return id; + } + const searchId = new URLSearchParams(loc.search || '').get('v'); + if (searchId) return searchId; + if (path.startsWith('/shorts/')) { + const parts = path.split('/'); + const candidate = parts[parts.indexOf('shorts') + 1]; + if (candidate?.length === 11) return candidate; + } + return null; + }, + + _baseRate() { return toNum(ImprovedTube.storage.player_custom_playback_speed, 1, 0.0625, 16); }, + + _setRate(rate) { + const v = this._getVideo(); + if (!v || Math.abs(v.playbackRate - rate) < 0.01) return; + this.expectedRate = rate; + v.playbackRate = rate; + }, + + _setState(next) { + this.state = next; + UI.onStateChanged(this, next); + }, + + isCurrentlyLive(player) { + player = player || document.querySelector('.html5-video-player'); + const badge = document.querySelector('.ytp-live-badge'); + const visible = badge && badge.offsetParent !== null && !badge.hasAttribute('disabled') && badge.getAttribute('aria-hidden') !== 'true'; + return (player?.getVideoData?.()?.isLive === true || visible === true) && player?.getVideoData?.()?.isEndedLive !== true; + }, + + shouldExcludeVideo(video, player) { + const isShorts = location.pathname.startsWith('/shorts/'); + if (isShorts && ImprovedTube.storage.smart_speed_whitelist_shorts !== false) return true; + + const threshold = toNum(ImprovedTube.storage.smart_speed_short_video_threshold_seconds, 120, 1, 7200); + if (!this.adShowing && ImprovedTube.storage.smart_speed_whitelist_shorts !== false + && video && video.duration > 0 && video.duration < threshold) return true; + + if (ImprovedTube.storage.smart_speed_whitelist_live !== false && this.isCurrentlyLive(player)) return true; + + return false; + }, + + /*---------------------------- lifecycle ----------------------------*/ + init(video) { + const enabled = ImprovedTube.storage.smart_speed === true; + const videoId = this._getVideoId(); + + if (!enabled || !videoId) { + this._teardown(); + return; + } + + const videoEl = video || this._getVideo(); + const player = document.querySelector('.html5-video-player'); + UI.inject(this); + this._watchAds(player); + this._attachVideoListeners(videoEl); + + const sameVideo = videoId === this.lastInitializedVideoId && this.session?.videoId === videoId; + if (sameVideo) return; // already set up for this video; safe to call init() repeatedly + + this.lastInitializedVideoId = videoId; + this._startSession(videoId); + }, + + _teardown() { + this.stopLoop(); + if (this.uiTimer) { clearInterval(this.uiTimer); this.uiTimer = null; } + UI.hide(); + this.lastInitializedVideoId = null; + this.session = null; + this.expectedRate = null; + this._setState(STATE.IDLE); + }, + + _attachVideoListeners(videoEl) { + if (!videoEl || videoEl.dataset.itSmartSpeedAttached) return; + videoEl.dataset.itSmartSpeedAttached = 'true'; + + videoEl.addEventListener('loadstart', () => { + this.expectedRate = null; + }); + videoEl.addEventListener('loadeddata', () => { + if (ImprovedTube.storage.smart_speed !== true) return; + const freshId = this._getVideoId(); + if (!freshId) return; + if (freshId !== this.lastInitializedVideoId) { this.init(videoEl); return; } + if (this.shouldExcludeVideo(videoEl, document.querySelector('.html5-video-player'))) this.stopLoop(); + else if (!this.loopTimer && !this.session?.paused) this.startLoop(); + }); + videoEl.addEventListener('durationchange', () => this._tryProcess()); + videoEl.addEventListener('play', () => { + if (ImprovedTube.storage.smart_speed === true && !this.session?.paused && !this.loopTimer && this._getVideoId()) this.startLoop(); + }); + videoEl.addEventListener('seeked', () => { + this._suppressUntil = Date.now() + SEEK_SUPPRESS_MS; + if (ImprovedTube.storage.smart_speed === true && !this.session?.paused && !this.loopTimer && this._getVideoId()) this.startLoop(); + }); + videoEl.addEventListener('ended', () => { + this.stopLoop(); + UI.setIndicator('⚡ Done', '', 0.5); + }); + }, + + _watchAds(player) { + if (!player || this.adObserver) return; + this.adObserver = new MutationObserver(() => { + const showing = player.classList.contains('ad-showing') || !!player.querySelector('.ad-interrupting, .ytp-ad-player-overlay'); + if (showing === this.adShowing) return; + this.adShowing = showing; + if (showing) { + this._setState(STATE.AD); + this._setRate(this._baseRate()); + } else { + this.expectedRate = null; + if (this.session) this._tryProcess(); + } + }); + this.adObserver.observe(player, { attributes: true, attributeFilter: ['class'] }); + this.adShowing = player.classList.contains('ad-showing') || !!player.querySelector('.ad-interrupting, .ytp-ad-player-overlay'); + }, + + + async _startSession(videoId) { + this.session?.dispose(); + Profiles.invalidate(); + const session = new Session(videoId); + this.session = session; + this._setState(STATE.LOADING); + + const profile = Profiles.resolve(); + if (profile.whitelist) { + this._setState(STATE.WHITELISTED); + this._setRate(this._baseRate()); + } else { + // Heatmap, captions, and SponsorBlock fetch in parallel; a slow + // or failed source just resolves to "nothing found". + const signal = session.abort?.signal; + const heatmapPromise = HeatmapSource.acquire(videoId, signal); + const sponsorPromise = SponsorBlockClient.isNeeded() ? SponsorBlockClient.get(videoId, signal) : Promise.resolve([]); + const captionPromise = CaptionSource.acquire(videoId, session, signal, () => this.session !== session); + + heatmapPromise.then(({ markers, playerResponse }) => { + if (this.session !== session) return; + if (playerResponse) { + session.playerResponse = playerResponse; + Profiles.invalidate(); } + session.markers = markers; + this._tryProcess(); + }); + + sponsorPromise.then(segments => { + if (this.session !== session) return; + session.sponsorSegments = segments || []; + UI.setSkipButtons(this, session); + }); + captionPromise.then(({ blocks, status }) => { + if (this.session !== session) return; + if (blocks) session.speechMap.addBlocks(blocks); + session.captionStatus = status || 'unavailable'; + }); + } + + if (this.uiTimer) clearInterval(this.uiTimer); + this.uiTimer = setInterval(() => UI.refreshContextual(this, this.session), 1000); + this.startLoop(); + }, + + _tryProcess() { + const session = this.session; + if (!session || session.markers === undefined) return; + const v = this._getVideo(); + if (this.adShowing || !v || !Number.isFinite(v.duration) || v.duration <= 0) return; + if (this.shouldExcludeVideo(v, document.querySelector('.html5-video-player'))) { + this._setState(STATE.EXCLUDED); + this.stopLoop(); + return; + } + if (session.processedDuration === v.duration) return; + session.processedDuration = v.duration; + this._processMarkers(session, v.duration); + }, + + _processMarkers(session, duration) { + let rawMarkers = session.markers; + if (!rawMarkers || rawMarkers.length === 0) { + const mode = ImprovedTube.storage.smart_speed_no_heatmap_fallback_mode || 'captions'; + if (mode === 'default_speed' || mode === 'fixed_speed') { + session.segments = []; + this._setState(STATE.ACTIVE); + this.startLoop(); + return; } + // Captions-fallback mode: synthesize flat low-intensity markers + // so the composite signal still has a heatmap value to blend. + rawMarkers = Array.from({ length: 100 }, () => ({ intensityScoreNormalized: 0.25 })); + } + + const chunkPct = 100 / rawMarkers.length; + session.segments = rawMarkers.map((marker, index) => { + const score = typeof marker.intensityScoreNormalized === 'number' ? marker.intensityScoreNormalized : 0; + const start = ((index * chunkPct) / 100) * duration; + const end = (((index + 1) * chunkPct) / 100) * duration; + return { start, end, duration: end - start, intensity: score }; + }); + session.lastSegIdx = -1; + this._setState(STATE.ACTIVE); + this.startLoop(); + }, + + _segmentAt(session, t) { + const segs = session.segments; + if (!segs?.length) return -1; + const last = segs[session.lastSegIdx]; + if (last && t >= last.start && t < last.end) return session.lastSegIdx; + let lo = 0, hi = segs.length - 1, idx = -1; + while (lo <= hi) { + const mid = (lo + hi) >> 1, s = segs[mid]; + if (t < s.start) hi = mid - 1; else if (t >= s.end) lo = mid + 1; else { idx = mid; break; } + } + return (session.lastSegIdx = idx); + }, + + /** Crossfades the speed across a boundary window so + * transitions don't feel like an abrupt jump cut. */ + _blendAcrossBoundary(session, ctx, idx, currentSpeed) { + const seg = session.segments[idx]; + const timeRemaining = seg.end - ctx.currentSec; + if (timeRemaining >= BOUNDARY_CROSSFADE_WINDOW_SEC || idx + 1 >= session.segments.length) return currentSpeed; + const nextSeg = session.segments[idx + 1]; + const nextSpeed = computeCompositeSpeed(makeContext({ ...ctx, segment: nextSeg })); + const progress = 1 - (timeRemaining / BOUNDARY_CROSSFADE_WINDOW_SEC); + return currentSpeed - (currentSpeed - nextSpeed) * progress; + }, + + /*---------------------------- playback loop ----------------------------*/ + startLoop() { + if (this.loopTimer) clearInterval(this.loopTimer); + this.loopTimer = setInterval(() => { + if (!this.session?.paused) this.tick(); + }, TICK_MS); + }, + + stopLoop() { + if (this.loopTimer) { clearInterval(this.loopTimer); this.loopTimer = null; } + this._setRate(this._baseRate()); + UI.setSkipButtons(this, this.session); + }, + + tick() { + if (ImprovedTube.storage.smart_speed !== true) { this._teardown(); return; } + const video = this._getVideo(); + if (!video || video.paused || video.ended || this.adShowing) return; + + // If the actual rate drifted from what we last set, the user (or + // another extension) changed it manually back off instead of + // fighting them. + if (this.expectedRate != null && Math.abs(video.playbackRate - this.expectedRate) > 0.05) { + this.session.paused = true; + this.expectedRate = null; + this._setState(STATE.PAUSED); + UI.toast('⏸️ Smart Speed paused: speed changed manually. Click ⚡ to resume'); + return; + } + if (this._suppressUntil && Date.now() < this._suppressUntil) return; + + const session = this.session; + const duration = video.duration || 0; + const currentSec = video.currentTime; + const profile = Profiles.resolve({ playerResponse: session?.playerResponse }); + + if (profile.whitelist) { + this._setState(STATE.WHITELISTED); + const base = this._baseRate(); + this._setRate(base); + UI.setIndicator(`🛡️ ${base.toFixed(2)}x`, `Whitelisted (${profile.tier})`, 1); + return; + } + + const videoId = this._getVideoId(); + const ctx = makeContext({ currentSec, duration, profile, video, videoId, session, segment: null, bias: session?.targetBias || 0 }); + + const override = resolveOverride(ctx); + let targetSpeed, source, isOverrideSpeed = false; + + if (override) { + targetSpeed = override.speed; source = override.source; isOverrideSpeed = true; + } else if (session?.segments?.length) { + const idx = this._segmentAt(session, currentSec); + if (idx !== -1) { + ctx.segment = session.segments[idx]; + const speed = computeCompositeSpeed(ctx); + targetSpeed = this._blendAcrossBoundary(session, ctx, idx, speed); + source = 'Composite'; + } else { + const res = noHeatmapTargetSpeed(ctx); + targetSpeed = res.speed; source = res.source; + } + } else { + const res = noHeatmapTargetSpeed(ctx); + targetSpeed = res.speed; source = res.source; + } + + const finalSpeed = isOverrideSpeed ? targetSpeed : this._baseRate() * targetSpeed; + this._setRate(finalSpeed); + this._setState(STATE.ACTIVE); + UI.setIndicator(`⚡ ${targetSpeed.toFixed(2)}x`, `Source: ${source} | Tier: ${profile.tier}`, 1); + }, + + /*---------------------------- user actions (called by UI) ----------------------------*/ + toggleSessionPause() { + if (!this.session) return; + this.session.paused = !this.session.paused; + if (this.session.paused) { + this._setState(STATE.PAUSED); + this._setRate(this._baseRate()); + UI.toast('⏸️ Smart Speed paused for this session'); } else { - processed.forEach(seg => seg.speed = baseMin); + this.expectedRate = null; + if (!this.session.segments?.length) this.tick(); + UI.toast('▶️ Smart Speed resumed'); } - } else { - // Standard Mapping - processed.forEach(seg => { - let mappedSpeed = baseMin + (baseMax - baseMin) * (1 - (seg.intensity / sensitivity)); - seg.speed = Math.max(baseMin, Math.min(baseMax, mappedSpeed)); + }, + + toggleLiveWhitelist() { + const updated = !(ImprovedTube.storage.smart_speed_whitelist_live !== false); + setStorage('smart_speed_whitelist_live', updated); + UI.toast(updated ? '📡 Live streams will stay at normal speed' : '📡 Smart Speed will now apply to this live stream'); + this.lastInitializedVideoId = null; + this.init(this._getVideo()); + }, + + toggleShortsWhitelist() { + const updated = !(ImprovedTube.storage.smart_speed_whitelist_shorts !== false); + setStorage('smart_speed_whitelist_shorts', updated); + UI.toast(updated ? '🩳 Shorts will stay at normal speed' : '🩳 Smart Speed will now apply to Shorts'); + this.lastInitializedVideoId = null; + this.init(this._getVideo()); + }, + + toggleChannelWhitelist() { + const ident = Profiles.channelIdentity(this.session?.playerResponse); + if (!ident) { UI.toast('Channel name not loaded yet. Try again.'); return; } + + const cKey = canonicalChannelKey(ident); + if (!cKey) { UI.toast('Channel identity missing. Try again.'); return; } + + const profiles = { ...(ImprovedTube.storage.smart_speed_profiles || {}) }; + const oldNameKey = ident.name; + const oldPrefixedKey = ident.name ? 'name:' + ident.name : null; + const existing = profiles[cKey] || (oldPrefixedKey && profiles[oldPrefixedKey]) || (oldNameKey && profiles[oldNameKey]) || {}; + + const entry = { ...existing, ...(ident.name ? { name: ident.name } : {}) }; + if (entry.whitelist) delete entry.whitelist; else entry.whitelist = true; + + const { name, ...settings } = entry; + if (Object.keys(settings).length > 0) { + profiles[cKey] = entry; + if (oldNameKey && oldNameKey !== cKey) delete profiles[oldNameKey]; + if (oldPrefixedKey && oldPrefixedKey !== cKey) delete profiles[oldPrefixedKey]; + } else { + delete profiles[cKey]; + if (oldNameKey) delete profiles[oldNameKey]; + if (oldPrefixedKey) delete profiles[oldPrefixedKey]; + } + setStorage('smart_speed_profiles', profiles); + Profiles.invalidate(); + + const displayName = ident.name || cKey; + UI.toast(entry.whitelist ? `🛡️ Whitelisted ${displayName} (Speedup Disabled)` : `▶️ Removed ${displayName} from Whitelist`); + this.lastInitializedVideoId = null; + this.init(this._getVideo()); + }, + + + setTargetDuration(minutes) { + const session = this.session; + const video = this._getVideo(); + if (!session || !video?.duration || !isFinite(video.duration)) return { ok: false, reason: 'no-video' }; + + const profile = Profiles.resolve({ playerResponse: session.playerResponse }); + if (profile.max <= profile.min) return { ok: false, reason: 'bad-range' }; + + const targetSec = minutes * 60; + const ctxBase = makeContext({ profile, duration: video.duration, video, videoId: this._getVideoId(), session, bias: session?.targetBias || 0 }); + const result = DurationSolver.solve(targetSec, ctxBase, session.segments, this._baseRate()); + + if (result.ok) { + session.targetBias = result.bias; + session.targetDurationOverride = targetSec; + UI.toast(`⏱️ Target duration bias applied: about ${minutes} minutes`); + } + return result; + }, + + jumpToNextPeak() { + const video = this._getVideo(); + const player = document.querySelector('.html5-video-player'); + const session = this.session; + + if (ImprovedTube.storage.smart_speed !== true || session?.paused || this.shouldExcludeVideo(video, player)) { + UI.toast('Smart Speed is disabled on this video'); + return; + } + const profile = Profiles.resolve({ playerResponse: session?.playerResponse }); + if (profile.whitelist) { UI.toast('Channel is whitelisted'); return; } + if (!video || !session?.segments?.length) { UI.toast('❌ No heatmap peaks available'); return; } + + const duration = video.duration || 0; + const peak = session.segments.find(s => { + const targetTime = Math.max(0, s.start - 2.0); + if (targetTime <= video.currentTime + 1.0) return false; + if (typeof s.intensity === 'number' && s.intensity >= 0.5) return true; + const ctx = makeContext({ currentSec: s.start + s.duration / 2, duration, profile, video, videoId: this._getVideoId(), segment: s, session, bias: session.targetBias || 0 }); + return computeCompositeSpeed(ctx) <= profile.min + 0.1; }); - } - this.segments = processed; - console.log(`[ImprovedTube] Smart Speed: Engine Ready. Computed ${this.segments.length} logical chunks.`); - this.startLoop(); - }, - - // PLAYBACK LOOP - startLoop: function() { - if (this.loopInterval) clearInterval(this.loopInterval); - this.loopInterval = setInterval(() => { - if (!this.sessionDisabled) this.update(); - }, 100); - }, - - update: function () { - const video = document.querySelector('video'); - if (!video || this.segments.length === 0 || video.paused) return; - - let base = Number(ImprovedTube.storage.player_custom_playback_speed) || 1.0; - const currentSec = video.currentTime; - - let currentIndex = this.segments.findIndex(s => currentSec >= s.start && currentSec < s.end); - if (currentIndex === -1) return; - - let activeSegment = this.segments[currentIndex]; - let targetSpeedMultiplier = activeSegment.speed; - - // Smoothing Buffer (LERP) - let timeRemaining = activeSegment.end - currentSec; - if (timeRemaining < 2.5 && currentIndex + 1 < this.segments.length) { - let nextSpeedMultiplier = this.segments[currentIndex + 1].speed; - let progress = 1 - (timeRemaining / 2.5); - targetSpeedMultiplier = activeSegment.speed - ((activeSegment.speed - nextSpeedMultiplier) * progress); + if (peak) { + this._suppressUntil = Date.now() + SEEK_SUPPRESS_MS; + video.currentTime = Math.max(0, peak.start - 2.0); + UI.toast('⏭️ Skipped ahead to next peak'); + } else { + UI.toast('❌ No upcoming peaks detected'); + } + }, + + /*---------------------------- storage integration ----------------------------*/ + /** Routes a storage-changed key to the cheapest correct reaction + * instead of a full reinit. */ + onStorageChanged(key, value) { + if (key === 'smart_speed') { + if (value === true) this.init(this._getVideo()); + else this._teardown(); + return; + } + if (PROFILE_AFFECTING_KEYS.has(key)) Profiles.invalidate(); + if (key === 'smart_speed_indicator' || key === 'smart_speed_skip_intro_button' || key === 'smart_speed_skip_sponsor_button') { + UI.refreshContextual(this, this.session); + } } + }; - let finalSpeed = base * targetSpeedMultiplier; + /*========================================================================== + 11. UI + DOM layer. The engine never touches the DOM directly — it calls + these named methods instead. + ==========================================================================*/ + const UI = { + indicatorEl: null, + toastTimeout: null, - if (Math.abs(video.playbackRate - finalSpeed) > 0.05) { - video.playbackRate = finalSpeed; - } + toast(message) { + const player = document.querySelector('.html5-video-player'); + if (!player) return; + let toastEl = document.getElementById('it-smart-speed-toast'); + if (!toastEl) { + toastEl = document.createElement('div'); + toastEl.id = 'it-smart-speed-toast'; + Object.assign(toastEl.style, { + position: 'absolute', bottom: '70px', left: '50%', transform: 'translateX(-50%)', + background: 'rgba(0,0,0,0.85)', color: '#fff', padding: '10px 20px', borderRadius: '4px', + zIndex: 9999, fontSize: '14px', fontWeight: 'bold', pointerEvents: 'none', + opacity: '0', transition: 'opacity 0.3s ease-in-out', border: '1px solid rgba(255,255,255,0.1)' + }); + player.appendChild(toastEl); + } + toastEl.innerText = message; + toastEl.style.opacity = '1'; + if (this.toastTimeout) clearTimeout(this.toastTimeout); + this.toastTimeout = setTimeout(() => { toastEl.style.opacity = '0'; }, 2500); + }, + + setIndicator(text, title, opacity) { + if (!this.indicatorEl) return; + this.indicatorEl.innerText = text; + if (title !== undefined) this.indicatorEl.title = title; + if (opacity !== undefined) this.indicatorEl.style.opacity = String(opacity); + }, + + onStateChanged(engine, state) { + const labels = { + [STATE.WHITELISTED]: ['🛡️ Whitelisted', 0.5], + [STATE.EXCLUDED]: ['⚡ Excluded', 0.5], + [STATE.PAUSED]: ['⚡ Off', 0.5], + [STATE.AD]: ['⚡ Ad', 0.5], + [STATE.LOADING]: ['⚡ …', 1], + [STATE.ACTIVE]: [null, 1] // left to tick()'s per-frame speed readout + }; + const [text, opacity] = labels[state] || [null, 1]; + if (text) this.setIndicator(text, undefined, opacity); + else if (this.indicatorEl) this.indicatorEl.style.opacity = String(opacity); + }, + + hide() { if (this.indicatorEl) this.indicatorEl.style.display = 'none'; }, + + ensureSkipButtonStyles() { + if (document.getElementById('it-smart-skip-style')) return; + const style = document.createElement('style'); + style.id = 'it-smart-skip-style'; + style.textContent = ` + #it-smart-skip-container { position: absolute; bottom: 72px; right: 24px; z-index: 60; display: flex; flex-direction: column; gap: 8px; pointer-events: none; } + .it-smart-skip-btn { pointer-events: auto; background: #ff0000; color: #0f0f0f; border: none; border-radius: 18px; font-family: "YouTube Sans", "Roboto", sans-serif; font-weight: 700; font-size: 12px; letter-spacing: 0.5px; padding: 8px 18px; cursor: pointer; display: none; align-items: center; justify-content: center; gap: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.5); transition: background 0.15s, transform 0.15s, box-shadow 0.15s; user-select: none; text-transform: uppercase; } + .it-smart-skip-btn:hover { background: #cc0000; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,0.6); } + .it-smart-skip-btn:active { background: #aa0000; transform: translateY(0) scale(0.97); box-shadow: 0 1px 4px rgba(0,0,0,0.5); } + `; + document.head.appendChild(style); + }, + + inject(engine) { + const player = document.querySelector('.html5-video-player'); + const controls = document.querySelector('.ytp-right-controls'); + if (!player || !controls) return; + + if (!document.getElementById('it-smart-speed-indicator')) { + this.indicatorEl = document.createElement('button'); + this.indicatorEl.id = 'it-smart-speed-indicator'; + this.indicatorEl.className = 'ytp-button'; + this.indicatorEl.style.cssText = 'width:auto;padding:0 8px;font-weight:bold;font-size:13px;color:white;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:opacity .2s;'; + this.indicatorEl.innerText = '⚡ 1.0x'; + this.indicatorEl.title = 'Toggle Smart Speed'; + this.indicatorEl.addEventListener('click', () => engine.toggleSessionPause()); + controls.prepend(this.indicatorEl); + } else { + this.indicatorEl = document.getElementById('it-smart-speed-indicator'); + } + this.indicatorEl.style.display = ImprovedTube.storage.smart_speed_indicator !== false ? 'inline-flex' : 'none'; + + this._button(controls, 'it-smart-whitelist-btn', '🛡️', () => engine.toggleChannelWhitelist(), 'inline-flex'); + + this._button(controls, 'it-smart-live-btn', '📡', () => engine.toggleLiveWhitelist(), 'none'); + this._button(controls, 'it-smart-shorts-btn', '🩳', () => engine.toggleShortsWhitelist(), 'none'); + this._button(controls, 'it-smart-peak-btn', '⏭️', () => engine.jumpToNextPeak(), 'inline-flex', 'Jump to next high-engagement scene'); + this._injectDurationModal(engine, player, controls); + this._injectSkipButtons(player); + }, + + _button(controls, id, glyph, onClick, display = 'none', title = '') { + if (document.getElementById(id)) return; + const btn = document.createElement('button'); + btn.id = id; + btn.className = 'ytp-button'; + btn.style.cssText = `font-size:16px;font-weight:bold;color:white;display:${display};align-items:center;justify-content:center;transition:.2s;`; + btn.innerText = glyph; + if (title) btn.title = title; + btn.onclick = onClick; + controls.prepend(btn); + }, + + _injectDurationModal(engine, player, controls) { + if (document.getElementById('it-smart-duration-btn')) return; + const durBtn = document.createElement('button'); + durBtn.id = 'it-smart-duration-btn'; + durBtn.className = 'ytp-button'; + durBtn.style.cssText = 'font-size:16px;font-weight:bold;color:white;display:inline-flex;align-items:center;justify-content:center;'; + durBtn.innerText = '⏱️'; + durBtn.title = 'Set Target Duration for this video'; - if (this.indicatorElement) { - this.indicatorElement.innerText = `⚡ ${targetSpeedMultiplier.toFixed(2)}x`; - } - }, - - jumpToNextPeak: function() { - const video = document.querySelector('video'); - if (!video || this.segments.length === 0) return; - - let minSpeed = Number(ImprovedTube.storage.smart_speed_min) || 1.0; - let peakSegment = this.segments.find(s => s.start > video.currentTime && s.speed <= (minSpeed + 0.1)); - - if (peakSegment) { - console.log(`[ImprovedTube] Smart Speed: Skipping to peak at ${peakSegment.start}s`); - video.currentTime = Math.max(0, peakSegment.start - 2.0); - this.showToast(`⏭️ Skipped ahead to next peak`); - } else { - console.log('[ImprovedTube] Smart Speed: No upcoming peaks detected.'); - this.showToast(`❌ No upcoming peaks detected`); + const modal = document.createElement('div'); + modal.id = 'it-smart-duration-modal'; + Object.assign(modal.style, { + position: 'absolute', bottom: '50px', right: '10px', background: 'rgba(20,20,20,0.95)', + padding: '10px', borderRadius: '8px', display: 'none', flexDirection: 'column', + gap: '8px', zIndex: 9999, border: '1px solid #444', minWidth: '180px' + }); + const title = document.createElement('div'); + title.style.cssText = 'color:white;font-size:12px;font-weight:bold;'; + title.innerText = 'Target Duration'; + const input = document.createElement('input'); + input.type = 'number'; + input.placeholder = 'Minutes'; + input.style.cssText = 'width:100%;padding:4px;background:#333;color:white;border:none;border-radius:4px;'; + input.onkeydown = (e) => e.stopPropagation(); + const apply = document.createElement('button'); + apply.style.cssText = 'background:#3ea6ff;color:white;border:none;padding:5px;border-radius:4px;cursor:pointer;'; + apply.innerText = 'Apply Target Duration'; + const msg = document.createElement('div'); + msg.style.cssText = 'color:#ff4e4e;font-size:11px;'; + + modal.append(title, input, apply, msg); + player.appendChild(modal); + controls.prepend(durBtn); + + durBtn.onclick = () => { modal.style.display = modal.style.display === 'none' ? 'flex' : 'none'; }; + apply.onclick = () => { + const minutes = Number(input.value); + if (!minutes || minutes <= 0) return; + const res = engine.setTargetDuration(minutes); + if (!res.ok) { + const totalSec = Math.ceil(res.bestSec || 0); + const m = Math.floor(totalSec / 60), s = totalSec % 60; + msg.style.color = '#ff4e4e'; + msg.innerText = res.reason === 'too-short' ? `Min possible: ${m}m ${s}s` : res.reason === 'bad-range' ? 'Max speed must be > Min speed' : `Max possible: ${m}m ${s}s`; + } else { + msg.style.color = '#2ba640'; + msg.innerText = 'Algorithm Applied!'; + setTimeout(() => { modal.style.display = 'none'; }, 1500); + } + }; + }, + + _injectSkipButtons(player) { + if (document.getElementById('it-smart-skip-container')) return; + this.ensureSkipButtonStyles(); + const container = document.createElement('div'); + container.id = 'it-smart-skip-container'; + const introBtn = document.createElement('button'); + introBtn.id = 'it-smart-skip-intro-btn'; + introBtn.className = 'it-smart-skip-btn'; + introBtn.innerText = 'Skip Intro'; + const sponsorBtn = document.createElement('button'); + sponsorBtn.id = 'it-smart-skip-sponsor-btn'; + sponsorBtn.className = 'it-smart-skip-btn'; + sponsorBtn.innerText = 'Skip Sponsor'; + container.append(introBtn, sponsorBtn); + player.appendChild(container); + }, + + + setSkipButtons(engine, session) { + const video = engine._getVideo(); + if (!video || !session) return; + const currentTime = video.currentTime; + const segs = session.sponsorSegments || []; + + const introBtn = document.getElementById('it-smart-skip-intro-btn'); + if (introBtn) { + const seg = segs.find(s => ['intro', 'selfpromo', 'preview'].includes(s.category) + && currentTime >= Math.max(0, s.segment[0] - 0.5) && currentTime < s.segment[1] - 0.5); + if (seg && ImprovedTube.storage.smart_speed_skip_intro_button !== false) { + introBtn.style.display = 'inline-flex'; + introBtn.onclick = () => { video.currentTime = seg.segment[1]; this.toast('⏭️ Skipped Intro'); this.setSkipButtons(engine, session); }; + } else introBtn.style.display = 'none'; + } + + const sponsorBtn = document.getElementById('it-smart-skip-sponsor-btn'); + if (sponsorBtn) { + const seg = segs.find(s => s.category === 'sponsor' + && currentTime >= Math.max(0, s.segment[0] - 0.5) && currentTime < s.segment[1] - 0.5); + if (seg && ImprovedTube.storage.smart_speed_skip_sponsor_button !== false) { + sponsorBtn.style.display = 'inline-flex'; + sponsorBtn.onclick = () => { video.currentTime = seg.segment[1]; this.toast('⏩ Skip Sponsor'); this.setSkipButtons(engine, session); }; + } else sponsorBtn.style.display = 'none'; + } + }, + + refreshContextual(engine, session) { + const profile = Profiles.resolve({ playerResponse: session?.playerResponse }); + const ident = Profiles.channelIdentity(session?.playerResponse); + const name = ident ? ident.name : 'Unknown'; + + const wlBtn = document.getElementById('it-smart-whitelist-btn'); + if (wlBtn) { + wlBtn.style.opacity = profile.whitelist ? '1' : '0.5'; + wlBtn.title = profile.whitelist ? `Remove ${name} from Whitelist` : `Add ${name} to Whitelist`; + wlBtn.style.textShadow = profile.whitelist ? '0 0 8px #2ba640' : 'none'; + } + const liveBtn = document.getElementById('it-smart-live-btn'); + if (liveBtn) { + const live = engine.isCurrentlyLive(); + liveBtn.style.display = live ? 'inline-flex' : 'none'; + if (live) { + const on = ImprovedTube.storage.smart_speed_whitelist_live !== false; + liveBtn.style.opacity = on ? '1' : '0.5'; + liveBtn.title = on ? 'Smart Speed disabled for live streams (click to enable)' : 'Smart Speed enabled for live streams (click to disable)'; + } + } + const shortsBtn = document.getElementById('it-smart-shorts-btn'); + if (shortsBtn) { + const isShorts = location.pathname.startsWith('/shorts/'); + shortsBtn.style.display = isShorts ? 'inline-flex' : 'none'; + if (isShorts) { + const on = ImprovedTube.storage.smart_speed_whitelist_shorts !== false; + shortsBtn.style.opacity = on ? '1' : '0.5'; + shortsBtn.title = on ? 'Smart Speed disabled for Shorts (click to enable)' : 'Smart Speed enabled for Shorts (click to disable)'; + } + } + this.setSkipButtons(engine, session); } - } -}; + }; -/*------------------------------------------------------------------------------ -AUTO-START HOOKS -------------------------------------------------------------------------------*/ -setTimeout(function() { - if (ImprovedTube.storage.smart_speed === true) ImprovedTube.heatmap.init(); -}, 2000); + /*========================================================================== + 12. PUBLIC EXPORTS + ==========================================================================*/ + ImprovedTube.sponsorBlock = SponsorBlockClient; + ImprovedTube.heatmap = Engine; // legacy name, kept for the content-script bridge + ImprovedTube.smartSpeed = Engine; // friendlier alias for new integrations -window.addEventListener('yt-navigate-finish', function() { - if (ImprovedTube.storage.smart_speed === true) { - setTimeout(() => ImprovedTube.heatmap.init(), 1000); - } -}); + setTimeout(() => { + if (ImprovedTube.storage && ImprovedTube.storage.smart_speed === true) { + Engine.init(); + } + }, 1000); +})(); -window.addEventListener('keydown', (e) => { - if (e.shiftKey && e.code === 'KeyP' && ImprovedTube.storage.smart_speed) { - ImprovedTube.heatmap.jumpToNextPeak(); - } -}); /*------------------------------------------------------------------------------ AUTO-ACCEPT "CONTINUE WATCHING?" diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index 3ae397897..d10619c12 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -731,8 +731,20 @@ ImprovedTube.shortcutRefreshCategories = function () { 4.7.33 SMART SPEED TOGGLE ------------------------------------------------------------------------------*/ ImprovedTube.shortcutSmartSpeed = function () { - if (ImprovedTube.storage.smart_speed === false) { if(ImprovedTube.heatmap) {ImprovedTube.heatmap.init(); }; - } else if (ImprovedTube.storage.smart_speed === true) { if(ImprovedTube.heatmap) { ImprovedTube.heatmap.isEnabled = false; document.querySelector("video").playbackRate = 1.0; } - } - this.storage.smart_speed = !this.storage.smart_speed; + const newValue = !(ImprovedTube.storage.smart_speed === true); + ImprovedTube.storage.smart_speed = newValue; + if (ImprovedTube.messages && typeof ImprovedTube.messages.send === 'function') { + ImprovedTube.messages.send({ action: 'set', key: 'smart_speed', value: newValue }); + } + + if (newValue) { + if (ImprovedTube.smartSpeed?.init) { ImprovedTube.smartSpeed.init(); } + else if (ImprovedTube.heatmap?.init) { ImprovedTube.heatmap.init(); } + } else { + if (ImprovedTube.smartSpeed?._teardown) { ImprovedTube.smartSpeed._teardown(); } + else if (ImprovedTube.heatmap) { ImprovedTube.heatmap.isEnabled = false; } + const video = document.querySelector('video'); + if (video) video.playbackRate = 1.0; + } }; + diff --git a/menu/skeleton-parts/player.js b/menu/skeleton-parts/player.js index 08725c03a..ce09b790b 100644 --- a/menu/skeleton-parts/player.js +++ b/menu/skeleton-parts/player.js @@ -333,6 +333,97 @@ extension.skeleton.main.layers.section.player.on.click = { value: 0.5, min: 0.01, max: 1.0, step: 0.01 } }, + smart_speed_signals_card: { + component: 'section', + variant: 'card', + smart_speed_captions_enabled: { + component: 'switch', + text: 'smartSpeedCaptionsEnable', + value: true + }, + smart_speed_caption_weight: { + component: 'slider', + text: 'smartSpeedCaptionWeight', + value: 1.0, min: 0.0, max: 3.0, step: 0.1 + }, + smart_speed_speech_lead_seconds: { + component: 'slider', + text: 'smartSpeedSpeechLeadSeconds', + value: 5.0, min: 0.0, max: 10.0, step: 0.5 + }, + smart_speed_speech_release_seconds: { + component: 'slider', + text: 'smartSpeedSpeechReleaseSeconds', + value: 2.0, min: 0.0, max: 5.0, step: 0.5 + } + }, + smart_speed_overrides_card: { + component: 'section', + variant: 'card', + smart_speed_sponsorblock_enabled: { + component: 'switch', + text: 'smartSpeedSponsorBlockEnable', + value: true + }, + smart_speed_introoutro_enabled: { + component: 'switch', + text: 'smartSpeedIntroOutroEnable', + value: true + }, + smart_speed_introoutro_max: { + component: 'slider', + text: 'smartSpeedIntroOutroMax', + value: 2.0, min: 1.0, max: 5.0, step: 0.5 + }, + smart_speed_skip_intro_button: { + component: 'switch', + text: 'smartSpeedSkipIntroButton', + value: true + }, + smart_speed_skip_sponsor_button: { + component: 'switch', + text: 'smartSpeedSkipSponsorButton', + value: true + } + }, + smart_speed_fallback_card: { + component: 'section', + variant: 'card', + smart_speed_no_heatmap_fallback_mode: { + component: 'select', + text: 'smartSpeedNoHeatmapFallbackMode', + options: [ + { text: 'smartSpeedFallbackCaptions', value: 'captions' }, + { text: 'smartSpeedFallbackDefaultSpeed', value: 'default_speed' }, + { text: 'smartSpeedFallbackFixedSpeed', value: 'fixed_speed' } + ], + value: 'captions' + }, + smart_speed_no_heatmap_fixed_speed: { + component: 'slider', + text: 'smartSpeedNoHeatmapFixedSpeed', + value: 1.5, min: 1.0, max: 4.0, step: 0.1 + } + }, + smart_speed_exclusions_card: { + component: 'section', + variant: 'card', + smart_speed_whitelist_shorts: { + component: 'switch', + text: 'smartSpeedWhitelistShorts', + value: true + }, + smart_speed_short_video_threshold_seconds: { + component: 'slider', + text: 'smartSpeedShortVideoThreshold', + value: 120, min: 30, max: 300, step: 10 + }, + smart_speed_whitelist_live: { + component: 'switch', + text: 'smartSpeedWhitelistLive', + value: true + } + }, smart_speed_profiles_card: { component: 'button', text: 'smartSpeedProfiles', @@ -340,6 +431,17 @@ extension.skeleton.main.layers.section.player.on.click = { click: { component: 'section', variant: 'card', + smart_speed_rule_priority: { + component: 'select', + text: 'smartSpeedRulePriority', + options: [ + { text: 'smartSpeedPriorityChannelCategoryLanguage', value: 'channel,category,language' }, + { text: 'smartSpeedPriorityChannelLanguageCategory', value: 'channel,language,category' }, + { text: 'smartSpeedPriorityLanguageChannelCategory', value: 'language,channel,category' }, + { text: 'smartSpeedPriorityCategoryChannelLanguage', value: 'category,channel,language' } + ], + value: 'channel,category,language' + }, smart_speed_profile_list: { component: 'section', on: { @@ -350,26 +452,22 @@ extension.skeleton.main.layers.section.player.on.click = { container.innerHTML = ''; let skeleton = {}; let ts = Date.now(); // Unique ID to prevent caching bugs - - // THE FIX: Check if strictly undefined (first time setup), NOT if it's empty let storedProfiles = satus.storage.get('smart_speed_profiles'); let profiles; if (storedProfiles === undefined) { - // 100% strict defaults as requested profiles = { "Music": { max: 2.0, min: 1.0, sens: 0.5, whitelist: true }, "Education": { max: 2.0, min: 1.0, sens: 0.5, whitelist: false } }; satus.storage.set('smart_speed_profiles', profiles); } else { - // It's not the first run, respect the user's list (even if it's completely empty!) profiles = typeof storedProfiles === 'object' && storedProfiles !== null ? storedProfiles : {}; } let tempCategory = 'none'; + let tempLang = 'none'; - // 1. ADD NEW RULES SECTION skeleton['add_controls_' + ts] = { component: 'section', variant: 'card', @@ -407,7 +505,6 @@ extension.skeleton.main.layers.section.player.on.click = { if (tempCategory !== 'none') { let freshState = Object.assign({}, satus.storage.get('smart_speed_profiles') || {}); let newObj = {}; - // 100% strict defaults as requested newObj[tempCategory] = { max: 2.0, min: 1.0, sens: 0.5, whitelist: false }; satus.storage.set('smart_speed_profiles', Object.assign(newObj, freshState)); @@ -417,6 +514,63 @@ extension.skeleton.main.layers.section.player.on.click = { } }, + add_language_dropdown: { + component: 'select', + text: 'smartSpeedSelectLanguage', + options: [ + {value: 'none', text: 'smartSpeedSelectLanguagePlaceholder'}, + {value: 'en', text: 'English'}, + {value: 'hi', text: 'Hindi'}, + {value: 'es', text: 'Spanish'}, + {value: 'pt', text: 'Portuguese'}, + {value: 'zh', text: 'Chinese'}, + {value: 'ja', text: 'Japanese'}, + {value: 'ko', text: 'Korean'}, + {value: 'de', text: 'German'}, + {value: 'fr', text: 'French'}, + {value: 'ru', text: 'Russian'}, + {value: 'ar', text: 'Arabic'}, + {value: 'it', text: 'Italian'}, + {value: 'id', text: 'Indonesian'}, + {value: 'tr', text: 'Turkish'}, + {value: 'vi', text: 'Vietnamese'}, + {value: 'th', text: 'Thai'}, + {value: 'pl', text: 'Polish'}, + {value: 'nl', text: 'Dutch'}, + {value: 'uk', text: 'Ukrainian'}, + {value: 'sv', text: 'Swedish'}, + {value: 'bn', text: 'Bangla'}, + {value: 'ta', text: 'Tamil'}, + {value: 'te', text: 'Telugu'}, + {value: 'mr', text: 'Marathi'}, + {value: 'ur', text: 'Urdu'}, + {value: 'fa', text: 'Persian'}, + {value: 'cs', text: 'Czech'}, + {value: 'ro', text: 'Romanian'}, + {value: 'hu', text: 'Hungarian'}, + {value: 'el', text: 'Greek'} + ], + on: { + change: function() { tempLang = this.value; } + } + }, + add_language_btn: { + component: 'button', + text: 'smartSpeedAddSelectedLanguage', + on: { + click: function() { + if (tempLang !== 'none') { + let freshState = Object.assign({}, satus.storage.get('smart_speed_profiles') || {}); + let newObj = {}; + newObj['lang:' + tempLang] = { max: 2.0, min: 1.0, sens: 0.5, whitelist: false }; + + satus.storage.set('smart_speed_profiles', Object.assign(newObj, freshState)); + updateView(); + } + } + } + }, + add_channel_btn: { component: 'button', text: 'smartSpeedEnterAddChannelName', @@ -426,7 +580,6 @@ extension.skeleton.main.layers.section.player.on.click = { if (name) { let freshState = Object.assign({}, satus.storage.get('smart_speed_profiles') || {}); let newObj = {}; - // 100% strict defaults as requested newObj[name] = { max: 2.0, min: 1.0, sens: 0.5, whitelist: false }; satus.storage.set('smart_speed_profiles', Object.assign(newObj, freshState)); @@ -437,13 +590,29 @@ extension.skeleton.main.layers.section.player.on.click = { } }; - // 2. ACTIVE RULES LIST + const langNames = { + 'en':'English', 'hi':'Hindi', 'es':'Spanish', 'pt':'Portuguese', 'zh':'Chinese', + 'ja':'Japanese', 'ko':'Korean', 'de':'German', 'fr':'French', 'ru':'Russian', + 'ar':'Arabic', 'it':'Italian', 'id':'Indonesian', 'tr':'Turkish', 'vi':'Vietnamese', + 'th':'Thai', 'pl':'Polish', 'nl':'Dutch', 'uk':'Ukrainian', 'sv':'Swedish', + 'bn':'Bangla', 'ta':'Tamil', 'te':'Telugu', 'mr':'Marathi', 'ur':'Urdu', + 'fa':'Persian', 'cs':'Czech', 'ro':'Romanian', 'hu':'Hungarian', 'el':'Greek' + }; + for (let key in profiles) { let safeKey = key.replace(/[^a-zA-Z0-9]/g, ''); + let ruleTitle; + if (key.startsWith('lang:')) { + let lCode = key.substring(5); + ruleTitle = 'Audio Language: ' + (langNames[lCode] || lCode.toUpperCase()); + } else { + ruleTitle = ({'Entertainment':'categoryEntertainment', 'Music':'categoryMusic', 'Gaming':'categoryGaming', 'People & Blogs':'categoryPeopleBlogs', 'Comedy':'categoryComedy', 'Howto & Style':'categoryHowtoStyle', 'Film & Animation':'categoryFilmAnimation', 'Education':'categoryEducation', 'Science & Technology':'categoryScienceTechnology', 'Sports':'categorySports', 'News & Politics':'categoryNewsPolitics', 'Autos & Vehicles':'categoryAutosVehicles', 'Travel & Events':'categoryTravelEvents', 'Pets & Animals':'categoryPetsAnimals', 'Nonprofits & Activism':'categoryNonprofitsActivism'}[key] || key); + } + skeleton['rule_' + safeKey + '_' + ts] = { component: 'section', variant: 'card', - title: ({'Entertainment':'categoryEntertainment', 'Music':'categoryMusic', 'Gaming':'categoryGaming', 'People & Blogs':'categoryPeopleBlogs', 'Comedy':'categoryComedy', 'Howto & Style':'categoryHowtoStyle', 'Film & Animation':'categoryFilmAnimation', 'Education':'categoryEducation', 'Science & Technology':'categoryScienceTechnology', 'Sports':'categorySports', 'News & Politics':'categoryNewsPolitics', 'Autos & Vehicles':'categoryAutosVehicles', 'Travel & Events':'categoryTravelEvents', 'Pets & Animals':'categoryPetsAnimals', 'Nonprofits & Activism':'categoryNonprofitsActivism'}[key] || key), + title: ruleTitle, whitelist_toggle: { component: 'switch', text: 'smartSpeedWhitelistDisable',