v4.3.18: web-ui 폴더 정리 - html/js/css 분리, server.ts 레거시 리다이렉트 추가
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
d1032019de
commit
52b373f2d4
34 files changed
+317
-107
No files matched your search
+17
-4
@@ -2590,7 +2590,7 @@ app.use((req, _res, next) => {
|
||||
if (!auth.enabled) return next();
|
||||
|
||||
// Allow auth endpoints, login page, and static assets without authentication
|
||||
if (req.path.startsWith('/api/auth/') || req.path === '/login.html') return next();
|
||||
if (req.path.startsWith('/api/auth/') || req.path === '/login.html' || req.path === '/html/login.html') return next();
|
||||
// companion.py / install_autostart.py must be fetchable by a standalone script running
|
||||
// on the user's machine (no session cookie available there), so they're public downloads.
|
||||
if (req.path === '/companion.py' || req.path === '/install_autostart.py') return next();
|
||||
@@ -2630,7 +2630,7 @@ app.use((req, _res, next) => {
|
||||
if (req.path.startsWith('/api/')) {
|
||||
_res.status(401).json({ error: 'Authentication required' });
|
||||
} else {
|
||||
_res.redirect('/login.html');
|
||||
_res.redirect('/html/login.html');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2664,7 +2664,7 @@ app.use('/wavacity', express.static(path.join(webUiPath, 'wavacity'), {
|
||||
// see /pdf-editor below — so the case id is never sent in that request.)
|
||||
app.get('/pdf-editor-open', (req: express.Request, res: express.Response) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) { res.redirect('/login.html'); return; }
|
||||
if (!session) { res.redirect('/html/login.html'); return; }
|
||||
const caseId = String(req.query.caseId || '');
|
||||
if (/^[a-zA-Z0-9_-]+$/.test(caseId)) {
|
||||
res.setHeader('Set-Cookie', `dt_pdf_case=${caseId}; Path=/pdf-editor; HttpOnly; SameSite=Lax; Max-Age=3600`);
|
||||
@@ -4335,7 +4335,20 @@ registerUserRoutes(app, {
|
||||
registerDetectiveRoutes(app, getSessionUser, isPathInsideDir, CONFIG_DIR_PATH);
|
||||
|
||||
|
||||
app.get('/{*path}', (_req, res) => { res.sendFile(path.join(webUiPath, 'index.html')); });
|
||||
// Redirect legacy top-level HTML routes into /html/ after web-ui reorganization.
|
||||
const LEGACY_HTML_REDIRECTS = [
|
||||
'/login.html','/index.html','/claude-app.html','/code.html','/writer-app.html',
|
||||
'/language-app.html','/nvr-app.html','/weather-app.html','/music-app.html',
|
||||
'/mind-app.html','/lawyer-app.html','/investor-app.html','/accountant-app.html',
|
||||
'/detective-app.html','/studio-app.html','/pptx-wizard.html','/traffic-app.html',
|
||||
'/android-emulator.html','/arduino-emulator.html','/esp32-flasher.html',
|
||||
'/python-runner.html','/xlsx-viewer.html','/dental-agent.html'
|
||||
];
|
||||
for (const p of LEGACY_HTML_REDIRECTS) {
|
||||
app.get(p, (_req, res) => { res.redirect(`/html${p}`); });
|
||||
}
|
||||
|
||||
app.get('/{*path}', (_req, res) => { res.sendFile(path.join(webUiPath, 'html', 'index.html')); });
|
||||
|
||||
|
||||
const server = http.createServer(app);
|
||||
|
||||
@@ -1982,6 +1982,11 @@
|
||||
align-items: stretch;
|
||||
background: var(--panel);
|
||||
border-top: 1px solid var(--line);
|
||||
/* 메뉴(aside)가 열리면 position:fixed;inset:0;z-index:600 풀스크린 오버레이가 되는데,
|
||||
이 바는 z-index가 없어서 그 밑에 깔려 탭이 안 눌림(2026-07-21, "메뉴 누르면 못 빠져나옴"
|
||||
리포트) — 항상 그 위에 떠 있도록 고정. */
|
||||
position: relative;
|
||||
z-index: 601;
|
||||
}
|
||||
.mob-tab {
|
||||
flex: 1;
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>📊 회계 어시스턴트</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>
|
||||
try { var _t=localStorage.getItem('homeclaw_theme')||'dark'; document.documentElement.setAttribute('data-theme',_t); } catch(e){}
|
||||
</script>
|
||||
@@ -136,7 +136,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
#mob-backdrop{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="voice-utils.js"></script>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ac-drop" id="drop-overlay">📊 Excel 파일을 드롭하세요</div>
|
||||
File renamed without changes.
File renamed without changes.
@@ -212,6 +212,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="claude-app.js"></script>
|
||||
<script src="../js/claude-app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -20,7 +20,7 @@
|
||||
<script src="/vendor/xterm.js"></script>
|
||||
<script src="/vendor/addon-fit.js"></script>
|
||||
<script src="/vendor/addon-web-links.js"></script>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<!-- Monaco loader (AMD). Hide define.amd first so any stray UMD lib does not call Monaco's anonymous define(). -->
|
||||
<script src="/vendor/vs/loader.js"></script>
|
||||
<script>
|
||||
@@ -294,12 +294,14 @@
|
||||
<span id="csb-board-qemu-badge" style="display:none;font-size:9px;padding:1px 5px;border-radius:3px;flex-shrink:0;background:#1a3a1a;color:#22c55e;border:1px solid #2a5a2a">🖥 QEMU</span>
|
||||
<span style="color:var(--muted);flex-shrink:0;font-size:10px">▾</span>
|
||||
</div>
|
||||
<div id="csb-board-sel-dropdown" style="display:none;position:absolute;top:100%;left:0;right:0;z-index:200;background:var(--panel);border:1px solid var(--line);border-radius:6px;box-shadow:0 4px 16px rgba(0,0,0,.15);margin-top:2px;max-height:280px;overflow:hidden;flex-direction:column">
|
||||
<!-- position:fixed + JS로 좌표 계산(csbBoardSelOpen) — 부모 패널이 overflow:hidden/auto라
|
||||
position:absolute로는 그 경계 밖으로 못 나가고 잘림("2칸만 보임" 리포트, 2026-07-21) -->
|
||||
<div id="csb-board-sel-dropdown" style="display:none;position:fixed;z-index:200;background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--brand);border-radius:6px;box-shadow:0 -8px 28px rgba(0,0,0,.22);overflow:hidden;flex-direction:column">
|
||||
<div style="padding:6px 8px;border-bottom:1px solid var(--line);flex-shrink:0">
|
||||
<input id="csb-board-sel-q" placeholder="보드 검색..." oninput="csbBoardSelSearch()" onkeydown="csbBoardSelKey(event)"
|
||||
style="width:100%;font-size:11px;padding:5px 8px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:4px;font-family:inherit;box-sizing:border-box;outline:none">
|
||||
</div>
|
||||
<div id="csb-board-sel-list" style="overflow-y:auto;flex:1;max-height:220px"></div>
|
||||
<div id="csb-board-sel-list" style="overflow-y:auto;flex:1;max-height:min(60vh,560px);display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));align-content:start"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -584,7 +586,7 @@
|
||||
<div style="display:flex;align-items:center;height:30px;background:#1c1424;border-bottom:1px solid #4a2d6b;flex-shrink:0;padding:0 8px;gap:6px">
|
||||
<span style="font-size:13px;flex-shrink:0">🤖</span>
|
||||
<span style="font-size:12px;font-weight:700;color:#c9a9e8;font-family:'IBM Plex Mono',monospace;flex:1">Claude App</span>
|
||||
<button onclick="window.open('/claude-app.html','_blank')" title="새 탭에서 열기" style="background:none;border:none;color:#8a6c9e;cursor:pointer;font-size:13px;padding:0 5px;flex-shrink:0">⧉</button>
|
||||
<button onclick="window.open('/html/claude-app.html','_blank')" title="새 탭에서 열기" style="background:none;border:none;color:#8a6c9e;cursor:pointer;font-size:13px;padding:0 5px;flex-shrink:0">⧉</button>
|
||||
<button onclick="toggleClaudeAppPanel()" title="닫기" style="background:none;border:none;color:#6b4d7e;cursor:pointer;font-size:16px;padding:0 6px;line-height:1;flex-shrink:0">×</button>
|
||||
</div>
|
||||
<iframe id="code-claude-iframe" src="" style="flex:1;border:none;min-height:0" allow="local-network-access"></iframe>
|
||||
@@ -675,7 +677,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="code.js?v=20260604s"></script>
|
||||
<script src="../js/code.js?v=20260721b"></script>
|
||||
<script>
|
||||
function mobCloseAll(){
|
||||
document.querySelector('.code-sidebar-wrap').classList.remove('mob-open');
|
||||
File renamed without changes.
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🔍 탐정 어시스턴트</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
html,body{height:100%;margin:0;padding:0;}
|
||||
@@ -232,7 +232,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.hash-btn{background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:4px 10px;font-size:11px;color:var(--fg);cursor:pointer;transition:.15s;}
|
||||
.hash-btn:hover{background:var(--panel-3,#2a2a3a);border-color:#93c5fd;}
|
||||
</style>
|
||||
<script src="voice-utils.js"></script>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
File renamed without changes.
@@ -26,7 +26,7 @@
|
||||
<script src="/vendor/katex/auto-render.min.js"></script>
|
||||
<script src="/vendor/katex/mhchem.min.js"></script>
|
||||
<script src="/vendor/smiles-drawer/smiles-drawer.min.js"></script>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
|
||||
<script src="/vendor/tone-midi.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/combine/npm/tone@14,npm/@magenta/music@1.23.1/es6/core.js,npm/html-midi-player@1.6.0" defer></script>
|
||||
@@ -59,21 +59,21 @@
|
||||
</div>
|
||||
|
||||
<div class="mode-toggle" style="margin-left:8px">
|
||||
<button class="mode-btn" onclick="window.open('/investor-app.html','_blank')" title="투자 어시스턴트">📈 투자</button>
|
||||
<button class="mode-btn" onclick="window.open('/weather-app.html','_blank')" title="날씨 어시스턴트">🌤️ 날씨</button>
|
||||
<button class="mode-btn" onclick="window.open('/code.html','_blank')" title="코드 에디터">💻 코드</button>
|
||||
<button class="mode-btn" onclick="window.open('/pptx-wizard.html','_blank')" title="슬라이드 제작">📊 슬라이드</button>
|
||||
<button class="mode-btn" onclick="window.open('/language-app.html','_blank')" title="우즈베크어 학습">🇺🇿 언어</button>
|
||||
<button class="mode-btn" onclick="window.open('/music-app.html','_blank')" title="음악 스튜디오">🎵 음악</button>
|
||||
<button class="mode-btn" onclick="window.open('/studio-app.html','_blank')" title="이미지·동영상 생성">🎨 스튜디오</button>
|
||||
<button class="mode-btn" onclick="window.open('/accountant-app.html','_blank')" title="회계 어시스턴트">📊 회계</button>
|
||||
<button class="mode-btn" onclick="window.open('/mind-app.html','_blank')" title="마음 상담실">🧠 상담</button>
|
||||
<button class="mode-btn" onclick="window.open('/lawyer-app.html','_blank')" title="법률 어시스턴트">⚖️ 법률</button>
|
||||
<button class="mode-btn" onclick="window.open('/detective-app.html','_blank')" title="탐정 어시스턴트">🔍 탐정</button>
|
||||
<button class="mode-btn" onclick="window.open('/traffic-app.html','_blank')" title="교통 CCTV">🚦 교통</button>
|
||||
<button class="mode-btn" onclick="window.open('/nvr-app.html','_blank')" title="홈 CCTV">📹 홈CCTV</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/investor-app.html','_blank')" title="투자 어시스턴트">📈 투자</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/weather-app.html','_blank')" title="날씨 어시스턴트">🌤️ 날씨</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/code.html','_blank')" title="코드 에디터">💻 코드</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/pptx-wizard.html','_blank')" title="슬라이드 제작">📊 슬라이드</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/language-app.html','_blank')" title="우즈베크어 학습">🇺🇿 언어</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/music-app.html','_blank')" title="음악 스튜디오">🎵 음악</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/studio-app.html','_blank')" title="이미지·동영상 생성">🎨 스튜디오</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/accountant-app.html','_blank')" title="회계 어시스턴트">📊 회계</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/mind-app.html','_blank')" title="마음 상담실">🧠 상담</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/lawyer-app.html','_blank')" title="법률 어시스턴트">⚖️ 법률</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/detective-app.html','_blank')" title="탐정 어시스턴트">🔍 탐정</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/traffic-app.html','_blank')" title="교통 CCTV">🚦 교통</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/nvr-app.html','_blank')" title="홈 CCTV">📹 홈CCTV</button>
|
||||
<button class="mode-btn" onclick="window.open('/dental-agent.html?t='+Date.now(),'_blank')" title="치과 사전 이미지 에이전트">🦷 치과</button>
|
||||
<button class="mode-btn" onclick="window.open('/writer-app.html','_blank')" title="작가 어시스턴트">✍️ 작가</button>
|
||||
<button class="mode-btn" onclick="window.open('/html/writer-app.html','_blank')" title="작가 어시스턴트">✍️ 작가</button>
|
||||
</div>
|
||||
|
||||
<div class="status-bar">
|
||||
@@ -93,23 +93,17 @@
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3c-.04.25-.06.5-.06.76a8 8 0 0 0 9.85 7.84z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button onclick="openSettings()" title="Settings" style="display:flex;align-items:center;gap:6px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius-sm);padding:6px 12px;font-size:13px;font-weight:600;color:var(--muted);cursor:pointer;white-space:nowrap" onmouseover="this.style.color='var(--text)';this.style.borderColor='var(--line-strong)'" onmouseout="this.style.color='var(--muted)';this.style.borderColor='var(--line)'">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
|
||||
설정
|
||||
</button>
|
||||
<!-- User info + logout (hidden until auth check confirms logged-in user) -->
|
||||
<div id="user-info-pill" style="display:none;align-items:center;gap:6px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius-sm);padding:4px 10px 4px 8px;font-size:12px;color:var(--muted)">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
|
||||
<span id="user-info-name" style="font-weight:600;color:var(--text);max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"></span>
|
||||
<button onclick="logout()" title="로그아웃" style="display:flex;align-items:center;gap:4px;background:none;border:none;cursor:pointer;padding:2px 4px;border-radius:5px;font-size:11px;color:var(--muted)" onmouseover="this.style.background='var(--line)';this.style.color='var(--text)'" onmouseout="this.style.background='none';this.style.color='var(--muted)'">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
|
||||
로그아웃
|
||||
<button onclick="logout()" title="로그아웃" style="display:flex;align-items:center;gap:2px;background:none;border:none;cursor:pointer;padding:1px 2px;border-radius:4px;font-size:9px;color:var(--muted)" onmouseover="this.style.background='var(--line)';this.style.color='var(--text)'" onmouseout="this.style.background='none';this.style.color='var(--muted)'">
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="status-pill">
|
||||
<div class="dot" id="ollama-dot"></div>
|
||||
<span id="ollama-status">확인 중...</span>
|
||||
</div>
|
||||
<button onclick="openSettings()" title="설정" class="icon-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -142,6 +136,10 @@
|
||||
<span style="font-size:11px;color:var(--muted);font-weight:700">모델</span>
|
||||
<span id="current-provider-badge" style="font-size:11px;font-weight:800;color:var(--muted)"></span>
|
||||
<span id="current-model" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">-</span>
|
||||
<span class="status-pill" style="margin-left:auto;flex-shrink:0;padding:4px 9px;font-size:11px">
|
||||
<span class="dot" id="ollama-dot"></span>
|
||||
<span id="ollama-status" style="font-weight:700">확인 중...</span>
|
||||
</span>
|
||||
</div>
|
||||
<!-- 리소스 바 -->
|
||||
<div id="system-pill" style="flex-shrink:0;display:flex;flex-direction:column;gap:5px;padding:9px 14px;border-top:1px solid var(--line);background:var(--panel-2)">
|
||||
@@ -1944,8 +1942,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="voice-call.js"></script>
|
||||
<script src="app.js"></script>
|
||||
<script src="../js/voice-call.js"></script>
|
||||
<script src="../js/app.js"></script>
|
||||
|
||||
<!-- Code folder browser dropdown (fixed, rendered outside any overflow:hidden container) -->
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>📈 투자 어시스턴트</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
html,body{height:100%;margin:0;padding:0;}
|
||||
@@ -160,7 +160,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
#mob-backdrop{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="voice-utils.js"></script>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Nanum+Gothic:wght@400;700;800&display=swap" rel="stylesheet">
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>
|
||||
try {
|
||||
var _t = localStorage.getItem('homeclaw_theme') || 'dark';
|
||||
@@ -1058,6 +1058,29 @@ function loadProgress() {
|
||||
STATE.lessonsDone = p.lessonsDone || {};
|
||||
} catch { STATE.known = new Set(); STATE.lessonsDone = {}; }
|
||||
}
|
||||
// AI로 생성한 카드는 VOCAB_DATA(하드코딩 기본 단어장)에 없으므로 서버에 별도 저장/로드한다
|
||||
// (2026-07-21) — 안 그러면 새로고침·언어전환마다 사라짐. progress와 동일하게 URL의
|
||||
// :userId는 서버가 무시하고 세션으로 유저를 판별(레거시 route param).
|
||||
async function loadCustomCards() {
|
||||
try {
|
||||
const res = await fetch('/api/language/custom-cards/session?lang=' + STATE.lang);
|
||||
const data = await res.json();
|
||||
if (data.success && Array.isArray(data.cards) && data.cards.length) {
|
||||
const existing = new Set(VOCAB.map(v => v.word));
|
||||
const fresh = data.cards.filter(c => !existing.has(c.word));
|
||||
VOCAB = [...VOCAB, ...fresh];
|
||||
buildDeck(STATE.category);
|
||||
if (STATE.nav === 'vocab') renderVocabTable();
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
function saveCustomCards(cards) {
|
||||
if (!cards.length) return;
|
||||
fetch('/api/language/custom-cards/session', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ lang: STATE.lang, cards }),
|
||||
}).catch(() => {});
|
||||
}
|
||||
function saveProgress() {
|
||||
try {
|
||||
localStorage.setItem('lg_progress_' + STATE.lang, JSON.stringify({
|
||||
@@ -1238,6 +1261,7 @@ async function generateMoreCards() {
|
||||
const newCards = data.cards.filter(c=>!existing.has(c.word));
|
||||
VOCAB = [...VOCAB, ...newCards];
|
||||
buildDeck(STATE.category);
|
||||
saveCustomCards(newCards);
|
||||
alert(`✅ ${newCards.length}개 새 단어가 추가되었습니다!`);
|
||||
}
|
||||
} catch(e) { alert('카드 생성 실패: '+e.message); }
|
||||
@@ -1937,6 +1961,7 @@ function setLanguage(lang) {
|
||||
localStorage.setItem('lg_selected_lang', lang);
|
||||
LESSONS_DATA = LESSONS_DATA_BY_LANG[lang];
|
||||
VOCAB = [...VOCAB_DATA[lang]];
|
||||
loadCustomCards();
|
||||
applyCustomCategories(lang);
|
||||
STATE.category = 'all'; STATE.vocabCat = 'all'; STATE.quizCat = 'all';
|
||||
STATE.currentLesson = null;
|
||||
@@ -1960,6 +1985,7 @@ function setLanguage(lang) {
|
||||
// INIT
|
||||
// ═══════════════════════════════════════════════════════
|
||||
loadProgress();
|
||||
loadCustomCards();
|
||||
applyCustomCategories(STATE.lang);
|
||||
renderCategoryButtons();
|
||||
buildDeck('all');
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>⚖️ 법률 어시스턴트</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
html,body{height:100%;margin:0;padding:0;}
|
||||
@@ -161,7 +161,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
#mob-backdrop{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="voice-utils.js"></script>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
File renamed without changes.
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🧠 마음 상담실</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
html,body{height:100%;margin:0;padding:0;}
|
||||
@@ -247,7 +247,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.mn-send:hover:not(:disabled){background:#6d28d9;}
|
||||
.mn-send:disabled{opacity:.5;cursor:not-allowed;}
|
||||
</style>
|
||||
<script src="voice-utils.js"></script>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🎵 음악 스튜디오</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/@coderline/alphatab@latest/dist/alphaTab.min.js"></script>
|
||||
<script>
|
||||
try { var _t=localStorage.getItem('homeclaw_music_theme')||'dark'; document.documentElement.setAttribute('data-theme',_t); } catch(e){}
|
||||
@@ -1351,7 +1351,7 @@ async function _ensureSpessa() {
|
||||
if (!window.SpessaSynth) {
|
||||
await new Promise((res, rej) => {
|
||||
const s = document.createElement('script');
|
||||
s.src = '/spessasynth.js';
|
||||
s.src = '/js/spessasynth.js';
|
||||
s.onload = res; s.onerror = () => rej(new Error('SpessaSynth 로드 실패'));
|
||||
document.head.appendChild(s);
|
||||
});
|
||||
@@ -1367,7 +1367,7 @@ async function _ensureSpessa() {
|
||||
_spessaSfBuf = await r.arrayBuffer();
|
||||
}
|
||||
|
||||
await _spessaCtx.audioWorklet.addModule('/spessasynth_processor.min.js');
|
||||
await _spessaCtx.audioWorklet.addModule('/js/spessasynth_processor.min.js');
|
||||
const { WorkletSynthesizer, Sequencer } = window.SpessaSynth;
|
||||
_spessaSynth = new WorkletSynthesizer(_spessaCtx);
|
||||
_spessaSynth.connect(_spessaCtx.destination); // AudioWorkletNode → output (the global connect-patch redirects this through the master FX chain)
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>📹 홈 CCTV</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
:root{--brand:#22c55e;}
|
||||
@@ -73,7 +73,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.quad-hint{font-size:10px;color:var(--muted);}
|
||||
.quad-sp{flex:1;}
|
||||
.quad-quality{font-size:11px;color:var(--muted);display:flex;align-items:center;gap:4px;cursor:pointer;}
|
||||
.quad-grid{display:grid;grid-template-columns:repeat(3,1fr);grid-template-rows:1fr 1fr;gap:6px;background:#000;border:1px solid var(--line);border-radius:10px;padding:6px;aspect-ratio:16/9;}
|
||||
.quad-grid{display:grid;grid-template-columns:repeat(2,1fr);grid-template-rows:repeat(3,1fr);gap:6px;background:#000;border:1px solid var(--line);border-radius:10px;padding:6px;aspect-ratio:32/27;}
|
||||
.quad-cell{position:relative;background:#000;border-radius:6px;overflow:hidden;cursor:pointer;min-height:0;display:flex;align-items:center;justify-content:center;}
|
||||
.quad-cell.empty-slot{background:var(--panel-2);cursor:default;}
|
||||
.quad-cell img{width:100%;height:100%;object-fit:contain;display:block;}
|
||||
File renamed without changes.
File renamed without changes.
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🎨 이미지·동영상 스튜디오</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
:root{--brand:#a78bfa;}
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🚦 교통 CCTV</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
:root{--brand:#f59e0b;}
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>🌤️ 날씨 어시스턴트</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
:root{--brand:#38bdf8;}
|
||||
@@ -176,7 +176,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;fon
|
||||
#mob-tabbar{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="voice-utils.js"></script>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title id="doc-title">✍️ 작가</title>
|
||||
<link rel="icon" type="image/png" sizes="64x64" href="homeclaw_logo.png">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="stylesheet" href="../css/styles.css">
|
||||
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
|
||||
<style>
|
||||
:root{--brand:#8b5cf6;}
|
||||
@@ -108,7 +108,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.ebook-page-viewport.spread .ebook-page-spread{gap:56px}
|
||||
.ebook-page-viewport.spread .ebook-page-spread::after{content:'';position:absolute;top:0;bottom:0;left:50%;width:1px;background:rgba(0,0,0,.08);z-index:2;pointer-events:none}
|
||||
:root[data-theme="dark"] .ebook-page-viewport.spread .ebook-page-spread::after{background:rgba(0,0,0,.35)}
|
||||
.ebook-page-slot{box-sizing:border-box;padding:30px 40px;color:#2b2417;font-size:14.5px;line-height:1.85;white-space:pre-wrap;overflow:hidden;flex:1 1 0;min-width:0;opacity:1;transition:opacity .2s}
|
||||
.ebook-page-slot{box-sizing:border-box;padding:60px 40px 30px;color:#2b2417;font-size:14.5px;line-height:1.85;white-space:pre-wrap;overflow:hidden;flex:1 1 0;min-width:0;opacity:1;transition:opacity .2s}
|
||||
:root[data-theme="dark"] .ebook-page-slot{color:#dcd2b8}
|
||||
.ebook-page-slot.hidden{display:none}
|
||||
.ebook-page-slot.fading{opacity:0}
|
||||
@@ -218,6 +218,10 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
<button class="hdr-btn" onclick="closeEbookReader()">← 목록으로</button>
|
||||
<b id="ebook-reader-title" style="font-size:13px"></b>
|
||||
<button class="hdr-btn" onclick="readEbookAloud()" id="ebook-tts-btn">🔊 낭독</button>
|
||||
<label class="work-meta" style="display:flex;align-items:center;gap:4px">속도
|
||||
<input type="range" id="ebook-tts-speed" min="0.7" max="1.5" step="0.05" value="0.9" style="width:90px" oninput="document.getElementById('ebook-tts-speed-label').textContent=Number(this.value).toFixed(2)+'x'">
|
||||
<span id="ebook-tts-speed-label">0.90x</span>
|
||||
</label>
|
||||
<span class="work-meta" id="ebook-tts-status"></span>
|
||||
<div class="hdr-sp"></div>
|
||||
<span class="work-meta" id="ebook-page-label" style="font-weight:700"></span>
|
||||
@@ -699,9 +703,9 @@ async function loadEbookLibrary(){
|
||||
<div class="ebook-card">
|
||||
<div class="et">${escHtml(b.title)}</div>
|
||||
<div class="ea">${escHtml(b.authors||'저자 미상')}</div>
|
||||
<div class="ea">${(b.sizeBytes/1024).toFixed(0)}KB · ${new Date(b.downloadedAt).toLocaleDateString('ko-KR')}</div>
|
||||
<div class="ea">${(b.sizeBytes/1024).toFixed(0)}KB · ${new Date(b.downloadedAt).toLocaleDateString('ko-KR')}${b.bookmarkOffset?' · 책갈피 있음':''}</div>
|
||||
<div class="eb-actions">
|
||||
${b.readUrl?`<button onclick='openEbookReader(${JSON.stringify(b.readUrl)},${JSON.stringify(b.title)})'>읽기</button>`:''}
|
||||
${b.readUrl?`<button onclick='openEbookReader(${JSON.stringify(b.readUrl)},${JSON.stringify(b.title)},${JSON.stringify(b.id)},${b.bookmarkOffset||0})'>${b.bookmarkOffset?'이어읽기':'읽기'}</button>`:''}
|
||||
<a href="/api/writer/ebooks/library/${b.id}/file">받기</a>
|
||||
<button onclick="deleteEbookFromLibrary('${b.id}')">삭제</button>
|
||||
</div>
|
||||
@@ -723,9 +727,9 @@ async function deleteEbookFromLibrary(id){
|
||||
// 책마다, 페이지마다 하단 여백이 균일하지 않을 수 있지만(글자수 기준일 뿐 실제 줄바꿈은
|
||||
// 안 재보므로) 버그 표면적이 훨씬 작다 — 사용자 요청으로 단순한 방식을 택함(2026-07-22).
|
||||
let ebookPager={pageW:0,spread:1,charsPerPage:1500,pageOffsets:[0],pageIdx:0,fetching:false};
|
||||
async function openEbookReader(url,title){
|
||||
async function openEbookReader(url,title,libraryId,bookmarkOffset){
|
||||
const returnView=document.getElementById('ebook-view-library').classList.contains('active')?'library':'search';
|
||||
ebookReaderState={url,title,fullText:'',totalLength:0,nextOffset:null,returnView};
|
||||
ebookReaderState={url,title,fullText:'',totalLength:0,nextOffset:null,returnView,libraryId:libraryId||null,baseOffset:0};
|
||||
ebookPager={pageW:0,spread:1,charsPerPage:1500,pageOffsets:[0],pageIdx:0,fetching:false};
|
||||
document.getElementById('ebook-search-view').style.display='none';
|
||||
document.getElementById('ebook-library-view').style.display='none';
|
||||
@@ -733,9 +737,28 @@ async function openEbookReader(url,title){
|
||||
document.getElementById('ebook-reader-title').textContent=title;
|
||||
document.getElementById('ebook-page-left').textContent='불러오는 중...';
|
||||
document.getElementById('ebook-page-right').textContent='';
|
||||
await loadMoreEbookText(true);
|
||||
await loadMoreEbookText(true,bookmarkOffset>0?`offset=${bookmarkOffset}`:undefined);
|
||||
}
|
||||
// 책갈피: 서재에서 연 책이면(libraryId 있음) 페이지가 바뀔 때마다 절대 오프셋(baseOffset+
|
||||
// 현재 페이지의 청크 내 오프셋)을 저장해뒀다가, 다음에 "이어읽기"로 그 자리부터 바로 연다.
|
||||
let ebookBookmarkTimer=null;
|
||||
function currentAbsoluteEbookOffset(){
|
||||
if(!ebookReaderState) return 0;
|
||||
return (ebookReaderState.baseOffset||0)+(ebookPager.pageOffsets[ebookPager.pageIdx]||0);
|
||||
}
|
||||
function saveEbookBookmarkNow(){
|
||||
if(!ebookReaderState||!ebookReaderState.libraryId) return;
|
||||
const offset=currentAbsoluteEbookOffset();
|
||||
fetch(`/api/writer/ebooks/library/${ebookReaderState.libraryId}/bookmark`,{method:'PUT',headers:authH({'Content-Type':'application/json'}),body:JSON.stringify({offset})}).catch(()=>{});
|
||||
}
|
||||
function scheduleEbookBookmarkSave(){
|
||||
if(!ebookReaderState||!ebookReaderState.libraryId) return;
|
||||
clearTimeout(ebookBookmarkTimer);
|
||||
ebookBookmarkTimer=setTimeout(saveEbookBookmarkNow,1200);
|
||||
}
|
||||
function closeEbookReader(){
|
||||
if(ebookAutoReading) stopEbookAloud();
|
||||
if(ebookBookmarkTimer){ clearTimeout(ebookBookmarkTimer); saveEbookBookmarkNow(); }
|
||||
const returnView=ebookReaderState?.returnView||'search';
|
||||
ebookReaderState=null;
|
||||
document.getElementById('ebook-reader').style.display='none';
|
||||
@@ -748,7 +771,7 @@ async function loadMoreEbookText(replace,extraParams){
|
||||
const r=await fetch(`/api/writer/ebooks/read?url=${encodeURIComponent(ebookReaderState.url)}&${params}`,{headers:authH()});
|
||||
const d=await r.json();
|
||||
if(!d.success) throw new Error(d.error||'읽기 실패');
|
||||
if(replace){ ebookReaderState.fullText=d.text; ebookPager.pageIdx=0; }
|
||||
if(replace){ ebookReaderState.fullText=d.text; ebookPager.pageIdx=0; ebookReaderState.baseOffset=d.offset||0; }
|
||||
else{ ebookReaderState.fullText+=d.text; }
|
||||
if(d.totalLength){
|
||||
ebookReaderState.totalLength=d.totalLength;
|
||||
@@ -771,7 +794,7 @@ function jumpEbookTo(percent){
|
||||
// 표기가 달라 완벽할 수 없는 휴리스틱이지만, 영어 Gutenberg 텍스트에서 가장 흔한 패턴이다.
|
||||
function findChapterOffsets(text){
|
||||
const offsets=[];
|
||||
const re=/^[ \t]*(?:CHAPTER|PART|BOOK|VOLUME)\s+[IVXLCDM0-9]+\.?[ \t]*$/gim;
|
||||
const re=/^[ \t]*(?:CHAPTER|LETTER|PART|BOOK|VOLUME)\s+[IVXLCDM0-9]+\.?[ \t]*$/gim;
|
||||
let m;
|
||||
while((m=re.exec(text))) offsets.push(m.index);
|
||||
return offsets;
|
||||
@@ -781,30 +804,77 @@ function findChapterOffsets(text){
|
||||
// 안 끊기도록) ③ 그것도 없으면 가장 가까운 공백에서(최소한 단어는 안 끊기도록 — 그냥 글자수
|
||||
// 로 딱 자르면 "furlough"가 "furlo"/"ugh"로 잘려나가 보기 흉했다). DOM 측정 없는 순수
|
||||
// 문자열 검색이라 가볍고, 크로미움 렌더링 버그와도 무관하다.
|
||||
function computePageOffsets(text,charsPerPage,chapterOffsets){
|
||||
// hasMore(서버에 이어지는 텍스트가 더 있음)일 때는 "지금 로드된 텍스트의 끝"이 "책의 끝"이
|
||||
// 아니므로, 그 경계에서도 문단/단어 스냅을 그대로 적용한다 — 안 그러면 서버 청크(2만자)
|
||||
// 경계가 하필 단어 중간이면("forcin|g") 스냅 없이 그대로 반토막 난 채 페이지가 끝나버린다
|
||||
// (2026-07-23, 프랑켄슈타인 실독 중 발견). 스냅 지점을 못 찾으면(로드된 부분에 공백이 없을
|
||||
// 만큼 촉박한 경우) 아예 이 페이지를 만들지 않고 루프를 멈춘다 — 다음 청크가 로드되면
|
||||
// 이 함수가 더 큰 버퍼로 다시 호출되어 정상적으로 계산된다.
|
||||
// charsPerPage는 "한 줄을 cols자만큼 채운 프로즈"를 가정해 어림한 예산이라, 책 제목면/
|
||||
// 편지 인사말처럼 짧은 줄+빈 줄이 잔뜩인 구간에서는 실제 시각적 줄 수가 예산보다 훨씬
|
||||
// 커져(짧은 줄도 세로 공간은 한 줄 그대로 차지) 페이지 하단이 넘쳐 잘린다(2026-07-23,
|
||||
// 프랑켄슈타인 1페이지 실측: 글자수 예산상 19줄 자리인데 실제로는 34줄 필요했음).
|
||||
// 그래서 글자수 예산과는 별도로 "실제 줄 수" 상한도 계산해서 더 짧은 쪽을 쓴다.
|
||||
// 문장 끝(.!? + 선택적 닫는 인용부호/괄호) 바로 뒤 공백인지 판정 — 문단 경계가 없을 때
|
||||
// 아무 단어 사이에서나 끊지 않고 문장 단위로 끊기게 하기 위함(2026-07-23 사용자 요청).
|
||||
function isSentenceBoundary(text,i){
|
||||
if(!/\s/.test(text[i-1])) return false;
|
||||
let j=i-2;
|
||||
while(j>=0 && /["'\)\]]/.test(text[j])) j--;
|
||||
return j>=0 && /[.!?]/.test(text[j]);
|
||||
}
|
||||
function visualLineCutoff(text,pos,limit,cols){
|
||||
let i=pos, used=0;
|
||||
while(i<text.length && used<limit){
|
||||
let nl=text.indexOf('\n',i);
|
||||
if(nl===-1) nl=text.length;
|
||||
const len=nl-i;
|
||||
const vis=Math.max(1,Math.ceil((len||1)/cols));
|
||||
if(used+vis>limit){
|
||||
const remain=limit-used;
|
||||
return Math.min(text.length,i+remain*cols);
|
||||
}
|
||||
used+=vis;
|
||||
i=nl+1;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
function computePageOffsets(text,charsPerPage,chapterOffsets,hasMore,linesPerPage,cols){
|
||||
const offsets=[0];
|
||||
let pos=0;
|
||||
while(pos<text.length){
|
||||
let next=Math.min(text.length,pos+charsPerPage);
|
||||
if(linesPerPage&&cols){
|
||||
const lineCap=visualLineCutoff(text,pos,linesPerPage,cols);
|
||||
if(lineCap<next) next=lineCap;
|
||||
}
|
||||
const forced=chapterOffsets.find(c=>c>pos+20 && c<next);
|
||||
if(forced!=null){
|
||||
next=forced;
|
||||
}else if(next<text.length){
|
||||
}else if(next<text.length || hasMore){
|
||||
const paraBack=Math.max(pos+Math.floor(charsPerPage*0.5),next-200);
|
||||
const paraIdx=text.lastIndexOf('\n\n',next-1);
|
||||
if(paraIdx>=paraBack && paraIdx>pos){
|
||||
next=paraIdx+2;
|
||||
}else if(!/\s/.test(text[next-1]) && !/\s/.test(text[next])){
|
||||
let snap=-1;
|
||||
const back=Math.max(pos+1,next-40);
|
||||
for(let i=next;i>back;i--){ if(/\s/.test(text[i-1])){ snap=i; break; } }
|
||||
if(snap===-1){
|
||||
const fwd=Math.min(text.length,next+40);
|
||||
for(let i=next;i<fwd;i++){ if(/\s/.test(text[i])){ snap=i+1; break; } }
|
||||
}else{
|
||||
let sentSnap=-1;
|
||||
for(let i=next;i>paraBack;i--){ if(isSentenceBoundary(text,i)){ sentSnap=i; break; } }
|
||||
if(sentSnap>pos){
|
||||
next=sentSnap;
|
||||
}else if(next>=text.length || (!/\s/.test(text[next-1]) && !/\s/.test(text[next]))){
|
||||
let snap=-1;
|
||||
const back=Math.max(pos+1,next-40);
|
||||
for(let i=next;i>back;i--){ if(/\s/.test(text[i-1])){ snap=i; break; } }
|
||||
if(snap===-1 && next<text.length){
|
||||
const fwd=Math.min(text.length,next+40);
|
||||
for(let i=next;i<fwd;i++){ if(/\s/.test(text[i])){ snap=i+1; break; } }
|
||||
}
|
||||
if(snap>pos){ next=snap; }
|
||||
else if(next>=text.length && hasMore){ break; }
|
||||
}
|
||||
if(snap>pos) next=snap;
|
||||
}
|
||||
}
|
||||
if(next<=pos) break;
|
||||
offsets.push(next);
|
||||
pos=next;
|
||||
}
|
||||
@@ -814,14 +884,18 @@ function computePageOffsets(text,charsPerPage,chapterOffsets){
|
||||
// 그래야 브라우저 창 크기를 바꿔도 페이지 구분이 흔들리지 않는다(2026-07-22 사용자 요청).
|
||||
// 화면에는 이 고정 크기 그대로 그린 뒤 CSS transform:scale로 뷰포트에 맞춰 확대/축소만
|
||||
// 한다 — 고정 레이아웃 PDF/이북처럼 내용은 안 변하고 화면에 맞춰 배율만 바뀌는 방식.
|
||||
const REF_ASPECT=0.66, REF_SPREAD_PAGE_W=420, REF_SPREAD_GAP=56, REF_NARROW_PAGE_W=380;
|
||||
// 페이지 크기(가로폭)는 페이지당 글자수를 좌우한다 — 원래 값(380/420)은 페이지당 630~
|
||||
// 785자(약 100~130단어)로, 일반 페이퍼백 소설(페이지당 약 250~300단어, 1500~1800자)보다
|
||||
// 훨씬 적었다. 폰트/줄간격은 그대로 두고 페이지 자체를 키워 페이지당 약 1650~1800자가
|
||||
// 되도록 조정(2026-07-23, 사용자 요청).
|
||||
const REF_ASPECT=0.66, REF_SPREAD_PAGE_W=600, REF_SPREAD_GAP=56, REF_NARROW_PAGE_W=580;
|
||||
function computeEbookLayout(){
|
||||
const viewport=document.getElementById('ebook-page-viewport');
|
||||
const spreadEl=document.getElementById('ebook-page-spread');
|
||||
if(!viewport||!spreadEl||!ebookReaderState) return;
|
||||
const vw=viewport.clientWidth, vh=viewport.clientHeight;
|
||||
if(vw<10||vh<10) return;
|
||||
const padX=40, padY=30;
|
||||
const padX=40, padTop=60, padBottom=30;
|
||||
const narrow=vw<760;
|
||||
const spread=narrow?1:2;
|
||||
const gap=narrow?0:REF_SPREAD_GAP;
|
||||
@@ -835,7 +909,7 @@ function computeEbookLayout(){
|
||||
spreadEl.style.top='0';
|
||||
spreadEl.style.transformOrigin='top left';
|
||||
spreadEl.style.transform=`translate(${Math.round((vw-bookW*scale)/2)}px, ${Math.round((vh-bookH*scale)/2)}px) scale(${scale})`;
|
||||
const pageInnerH=bookH-padY*2, pageInnerW=pageW-padX*2;
|
||||
const pageInnerH=bookH-padTop-padBottom, pageInnerW=pageW-padX*2;
|
||||
const LINE_H=26.8, AVG_CHAR_W=7.6, FILL=0.85; // 넘치지 않게 여유를 두고 어림(overflow:hidden이 안전망)
|
||||
const lines=Math.max(1,Math.floor(pageInnerH/LINE_H));
|
||||
const cols=Math.max(1,Math.floor(pageInnerW/AVG_CHAR_W));
|
||||
@@ -844,7 +918,8 @@ function computeEbookLayout(){
|
||||
// 화면 전환(spread 모드 변경) 시에는 바뀔 수 있어 읽던 위치(글자 오프셋)는 유지한다.
|
||||
const charOffset=(ebookPager.pageOffsets&&ebookPager.pageOffsets[ebookPager.pageIdx])||0;
|
||||
const chapterOffsets=findChapterOffsets(ebookReaderState.fullText);
|
||||
const pageOffsets=computePageOffsets(ebookReaderState.fullText,charsPerPage,chapterOffsets);
|
||||
const hasMore=ebookReaderState.nextOffset!=null;
|
||||
const pageOffsets=computePageOffsets(ebookReaderState.fullText,charsPerPage,chapterOffsets,hasMore,lines,cols);
|
||||
let pageIdx=0;
|
||||
while(pageIdx<pageOffsets.length-1 && pageOffsets[pageIdx+1]<=charOffset) pageIdx++;
|
||||
ebookPager={...ebookPager,pageW,spread,charsPerPage,pageOffsets,pageIdx};
|
||||
@@ -889,6 +964,7 @@ function renderLeaves(){
|
||||
p.fetching=true;
|
||||
loadMoreEbookText(false).finally(()=>{ ebookPager.fetching=false; });
|
||||
}
|
||||
scheduleEbookBookmarkSave();
|
||||
}
|
||||
async function ebookNextPage(){
|
||||
const p=ebookPager;
|
||||
@@ -917,28 +993,71 @@ document.addEventListener('keydown',(e)=>{
|
||||
if(e.key==='ArrowRight'){ ebookNextPage(); }
|
||||
else if(e.key==='ArrowLeft'){ ebookPrevPage(); }
|
||||
});
|
||||
async function readEbookAloud(){
|
||||
const left=document.getElementById('ebook-page-left').textContent||'';
|
||||
const right=ebookPager.spread===2?(document.getElementById('ebook-page-right').textContent||''):'';
|
||||
const text=(left+' '+right).trim();
|
||||
if(!text){ showToast('읽을 내용이 없습니다',true); return; }
|
||||
// DOM textContent는 renderLeaves()의 requestAnimationFrame 안에서 갱신돼 페이지를 막
|
||||
// 넘긴 직후엔 아직 이전 페이지 텍스트가 남아있을 수 있다 — 연속 낭독 중 다음 페이지로
|
||||
// 넘어가자마자 바로 읽으면 헌 페이지를 읽어버리는 걸 피하려고, DOM이 아니라
|
||||
// ebookPager 상태(pageOffsets/fullText)에서 직접 현재 페이지 텍스트를 계산한다.
|
||||
function getCurrentEbookPageText(){
|
||||
const p=ebookPager, fullText=ebookReaderState.fullText;
|
||||
const totalPages=p.pageOffsets.length-1;
|
||||
const left=p.pageIdx<totalPages?fullText.slice(p.pageOffsets[p.pageIdx],p.pageOffsets[p.pageIdx+1]):'';
|
||||
const right=(p.spread===2&&p.pageIdx+1<totalPages)?fullText.slice(p.pageOffsets[p.pageIdx+1],p.pageOffsets[p.pageIdx+2]):'';
|
||||
return (left+' '+right).trim();
|
||||
}
|
||||
let ebookAutoReading=false;
|
||||
function stopEbookAloud(){
|
||||
ebookAutoReading=false;
|
||||
const audio=document.getElementById('ebook-tts-audio');
|
||||
audio.onended=null;
|
||||
audio.pause();
|
||||
const btn=document.getElementById('ebook-tts-btn');
|
||||
btn.disabled=true;
|
||||
btn.textContent='🔊 낭독';
|
||||
btn.disabled=false;
|
||||
document.getElementById('ebook-tts-status').textContent='';
|
||||
}
|
||||
async function readEbookAloud(){
|
||||
if(ebookAutoReading){ stopEbookAloud(); return; }
|
||||
ebookAutoReading=true;
|
||||
document.getElementById('ebook-tts-btn').textContent='⏸ 정지';
|
||||
await readCurrentEbookPageAloud();
|
||||
}
|
||||
async function readCurrentEbookPageAloud(){
|
||||
const text=getCurrentEbookPageText();
|
||||
if(!text){ if(ebookAutoReading) stopEbookAloud(); else showToast('읽을 내용이 없습니다',true); return; }
|
||||
document.getElementById('ebook-tts-status').textContent='음성 합성 중...';
|
||||
try{
|
||||
const r=await fetch('/api/writer/ebooks/tts',{method:'POST',headers:authH({'Content-Type':'application/json'}),body:JSON.stringify({text:text.slice(0,3000)})});
|
||||
const speed=Number(document.getElementById('ebook-tts-speed').value)||1;
|
||||
const r=await fetch('/api/writer/ebooks/tts',{method:'POST',headers:authH({'Content-Type':'application/json'}),body:JSON.stringify({text:text.slice(0,3000),speed})});
|
||||
if(!r.ok){ const d=await r.json().catch(()=>({})); throw new Error(d.error||'낭독 실패'); }
|
||||
const blob=await r.blob();
|
||||
const url=URL.createObjectURL(blob);
|
||||
const audio=document.getElementById('ebook-tts-audio');
|
||||
audio.src=url;
|
||||
audio.style.display='block';
|
||||
// 연속 낭독 모드면 오디오가 끝났을 때 자동으로 다음 페이지로 넘기고 이어서 읽는다.
|
||||
audio.onended=()=>{ if(ebookAutoReading) ebookAdvanceAndContinueReading(); };
|
||||
audio.play().catch(()=>{});
|
||||
document.getElementById('ebook-tts-status').textContent=text.length>3000?'현재 화면의 앞 3000자만 재생됩니다':'';
|
||||
}catch(e){
|
||||
document.getElementById('ebook-tts-status').textContent='';
|
||||
showToast('오류: '+e.message,true);
|
||||
}finally{ btn.disabled=false; }
|
||||
stopEbookAloud();
|
||||
}
|
||||
}
|
||||
async function ebookAdvanceAndContinueReading(){
|
||||
const p=ebookPager;
|
||||
const totalPages=p.pageOffsets.length-1;
|
||||
const maxPageIdx=Math.max(0,p.spread===2?Math.floor((totalPages-1)/2)*2:totalPages-1);
|
||||
if(p.pageIdx<maxPageIdx){
|
||||
p.pageIdx+=p.spread;
|
||||
renderLeaves();
|
||||
}else if(ebookReaderState&&ebookReaderState.nextOffset!=null){
|
||||
await loadMoreEbookText(false);
|
||||
}else{
|
||||
stopEbookAloud();
|
||||
return;
|
||||
}
|
||||
if(ebookAutoReading) await readCurrentEbookPageAloud();
|
||||
}
|
||||
|
||||
// ── INIT ──
|
||||
File renamed without changes.
@@ -2458,7 +2458,7 @@ async function api(path, opts = {}) {
|
||||
const { headers: optsHeaders, credentials: _discard, ...restOpts } = opts;
|
||||
const headers = authHeaders({ 'Content-Type': 'application/json', ...optsHeaders });
|
||||
const r = await fetch(API + path, { headers, ...restOpts });
|
||||
if (r.status === 401) { setAuthToken(''); window.location.href = '/login.html'; throw new Error('Authentication required'); }
|
||||
if (r.status === 401) { setAuthToken(''); window.location.href='/html/login.html'; throw new Error('Authentication required'); }
|
||||
const ct = String(r.headers.get('content-type') || '').toLowerCase();
|
||||
const bodyText = await r.text();
|
||||
|
||||
@@ -2508,11 +2508,11 @@ async function checkAuth() {
|
||||
const res = await fetch('/api/auth/status', { headers: authHeaders() });
|
||||
const data = await res.json();
|
||||
if (data.enabled && !data.authenticated && !data.hasPassword) {
|
||||
window.location.href = '/login.html';
|
||||
window.location.href='/html/login.html';
|
||||
return;
|
||||
}
|
||||
if (data.enabled && !data.authenticated) {
|
||||
window.location.href = '/login.html';
|
||||
window.location.href='/html/login.html';
|
||||
return;
|
||||
}
|
||||
if (data.authenticated && data.username) {
|
||||
@@ -2554,7 +2554,7 @@ async function logout() {
|
||||
clearLocalUserState('logout');
|
||||
try { localStorage.removeItem(LAST_USER_KEY); } catch {}
|
||||
setAuthToken('');
|
||||
window.location.href = '/login.html';
|
||||
window.location.href='/html/login.html';
|
||||
}
|
||||
|
||||
async function loadSearchSettingsSummary() {
|
||||
File renamed without changes.
@@ -31,7 +31,7 @@ async function api(path, opts = {}) {
|
||||
const { headers: optsHeaders, credentials: _discard, ...restOpts } = opts;
|
||||
const headers = authHeaders({ 'Content-Type': 'application/json', ...optsHeaders });
|
||||
const r = await fetch(API + path, { headers, ...restOpts });
|
||||
if (r.status === 401) { setAuthToken(''); window.location.href = '/login.html'; throw new Error('Authentication required'); }
|
||||
if (r.status === 401) { setAuthToken(''); window.location.href='/html/login.html'; throw new Error('Authentication required'); }
|
||||
const ct = String(r.headers.get('content-type') || '').toLowerCase();
|
||||
const bodyText = await r.text();
|
||||
if (!ct.includes('application/json')) {
|
||||
@@ -1763,7 +1763,7 @@ function codeRunWith(mode) {
|
||||
if (mode === 'pyodide') {
|
||||
sessionStorage.setItem('py_run_code', file.content);
|
||||
sessionStorage.setItem('py_run_name', file.name);
|
||||
const w = window.open('/python-runner.html', '_blank');
|
||||
const w = window.open('/html/python-runner.html', '_blank');
|
||||
if (!w) codeAiAppend('system', '⚠️ 팝업 차단됨 — 브라우저에서 팝업을 허용해주세요');
|
||||
return;
|
||||
}
|
||||
@@ -5141,12 +5141,23 @@ function csbBoardSelOpen() {
|
||||
const dd = document.getElementById('csb-board-sel-dropdown');
|
||||
if (!dd) return;
|
||||
const open = dd.style.display !== 'none';
|
||||
dd.style.display = open ? 'none' : 'flex';
|
||||
if (!open) {
|
||||
const q = document.getElementById('csb-board-sel-q');
|
||||
if (q) { q.value = ''; q.focus(); }
|
||||
csbBoardSelSearch();
|
||||
}
|
||||
if (open) { dd.style.display = 'none'; return; }
|
||||
// position:fixed + 여기서 좌표 계산 — 부모 패널이 overflow:hidden/overflow-y:auto라
|
||||
// position:absolute로는 그 경계 밖으로 못 나가고 잘림(2026-07-21, "2칸만 보임" 리포트).
|
||||
// 버튼 기준 뷰포트 좌표로 직접 배치해 어떤 조상의 overflow에도 안 걸리게 한다.
|
||||
const btn = document.getElementById('csb-board-sel-display');
|
||||
const rect = btn ? btn.getBoundingClientRect() : { left: 20, top: window.innerHeight - 40 };
|
||||
const margin = 20;
|
||||
dd.style.left = margin + 'px';
|
||||
dd.style.width = `calc(100vw - ${margin * 2}px)`;
|
||||
dd.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
|
||||
dd.style.maxHeight = 'min(70vh, 620px)';
|
||||
dd.style.display = 'flex';
|
||||
const list = document.getElementById('csb-board-sel-list');
|
||||
if (list) list.style.maxHeight = 'min(60vh, 560px)';
|
||||
const q = document.getElementById('csb-board-sel-q');
|
||||
if (q) { q.value = ''; q.focus(); }
|
||||
csbBoardSelSearch();
|
||||
}
|
||||
|
||||
function csbBoardSelClose() {
|
||||
@@ -5164,12 +5175,12 @@ async function csbBoardSelSearch() {
|
||||
const q = (document.getElementById('csb-board-sel-q')?.value || '').trim();
|
||||
const list = document.getElementById('csb-board-sel-list');
|
||||
if (!list) return;
|
||||
list.innerHTML = '<div style="padding:10px;color:var(--muted);font-size:11px;text-align:center">불러오는 중...</div>';
|
||||
list.innerHTML = '<div style="grid-column:1/-1;padding:10px;color:var(--muted);font-size:11px;text-align:center">불러오는 중...</div>';
|
||||
try {
|
||||
// 언어 옵션 고정 섹션
|
||||
// 언어 옵션 고정 섹션 — 그리드 레이아웃에서도 헤더/구분선은 전체 폭을 차지해야 하므로 grid-column:1/-1
|
||||
const langFiltered = q ? _LANG_BOARDS.filter(b => b.name.includes(q) || b.desc.includes(q)) : _LANG_BOARDS;
|
||||
const langHtml = langFiltered.length ? [
|
||||
`<div style="padding:4px 10px 2px;font-size:9px;color:var(--muted);font-weight:600;letter-spacing:.05em;text-transform:uppercase">언어</div>`,
|
||||
`<div style="grid-column:1/-1;padding:4px 10px 2px;font-size:9px;color:var(--muted);font-weight:600;letter-spacing:.05em;text-transform:uppercase">언어</div>`,
|
||||
...langFiltered.map(b => {
|
||||
const sel = b.fqbn === _csbSelBoard.fqbn;
|
||||
return `<div data-fqbn="${_csbEsc(b.fqbn)}" data-name="${_csbEsc(b.name)}" data-qemu="" data-chip=""
|
||||
@@ -5178,12 +5189,12 @@ async function csbBoardSelSearch() {
|
||||
<span style="font-size:10px;${sel?'color:rgba(255,255,255,.7)':'color:var(--muted)'}">${b.desc}</span>
|
||||
</div>`;
|
||||
}),
|
||||
`<div style="padding:4px 10px 2px;font-size:9px;color:var(--muted);font-weight:600;letter-spacing:.05em;text-transform:uppercase;border-top:1px solid var(--line)">보드</div>`,
|
||||
`<div style="grid-column:1/-1;padding:4px 10px 2px;font-size:9px;color:var(--muted);font-weight:600;letter-spacing:.05em;text-transform:uppercase;border-top:1px solid var(--line)">보드</div>`,
|
||||
].join('') : '';
|
||||
|
||||
const data = await api('/api/arduino/boards/listall?q=' + encodeURIComponent(q));
|
||||
const boards = data.boards || [];
|
||||
if (!boards.length && !langFiltered.length) { list.innerHTML = '<div style="padding:10px;color:var(--muted);font-size:11px;text-align:center">검색 결과 없음</div>'; return; }
|
||||
if (!boards.length && !langFiltered.length) { list.innerHTML = '<div style="grid-column:1/-1;padding:10px;color:var(--muted);font-size:11px;text-align:center">검색 결과 없음</div>'; return; }
|
||||
list.innerHTML = langHtml + boards.map(b => {
|
||||
const sel = b.fqbn === _csbSelBoard.fqbn;
|
||||
const qemuBadge = b.qemu === 'esp8266-native'
|
||||
@@ -5218,7 +5229,7 @@ async function csbBoardSelSearch() {
|
||||
el.addEventListener('mouseenter', () => { if (el.dataset.fqbn !== _csbSelBoard.fqbn) el.style.background = 'var(--bg)'; });
|
||||
el.addEventListener('mouseleave', () => { if (el.dataset.fqbn !== _csbSelBoard.fqbn) el.style.background = ''; });
|
||||
});
|
||||
} catch(e) { list.innerHTML = `<div style="padding:10px;color:var(--muted);font-size:11px;text-align:center">오류: ${e.message}</div>`; }
|
||||
} catch(e) { list.innerHTML = `<div style="grid-column:1/-1;padding:10px;color:var(--muted);font-size:11px;text-align:center">오류: ${e.message}</div>`; }
|
||||
}
|
||||
|
||||
function csbBoardSelKey(e) {
|
||||
File renamed without changes.
@@ -0,0 +1,18 @@
|
||||
var SpessaSynth=(()=>{var eA=Object.defineProperty;var Ls=Object.getOwnPropertyDescriptor;var Ps=Object.getOwnPropertyNames;var Ts=Object.prototype.hasOwnProperty;var Ns=(A,e)=>{for(var t in e)eA(A,t,{get:e[t],enumerable:!0})},xs=(A,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ps(e))!Ts.call(A,n)&&n!==t&&eA(A,n,{get:()=>e[n],enumerable:!(s=Ls(e,n))||s.enumerable});return A};var Us=A=>xs(eA({},"__esModule",{value:!0}),A);var jn={};Ns(jn,{BasicMIDI:()=>kt,MIDIBuilder:()=>ss,Sequencer:()=>Fs,WorkletSynthesizer:()=>vs});function $t(A,e,t=0){let s=0;for(let n=0;n<e;n++)s=s<<8|A[t+n];return s>>>0}function yt(A,e){let t=$t(A,e,A.currentIndex);return A.currentIndex+=e,t}function Ot(A,e){let t=new Array(e).fill(0);for(let s=e-1;s>=0;s--)t[s]=A&255,A>>=8;return t}function Os(A,e){let t=Hs(A,e,A.currentIndex);return A.currentIndex+=e,t}function Hs(A,e,t=0){let s=0n;for(let n=0;n<e;n++)s|=BigInt(A[t+n])<<BigInt(n*8);return Number(s)}function J(A,e){let t=QA(A,e,A.currentIndex);return A.currentIndex+=e,t}function QA(A,e,t=0){let s=0;for(let n=0;n<e;n++)s|=A[t+n]<<n*8;return s>>>0}function mA(A,e,t){for(let s=0;s<t;s++)A[A.currentIndex++]=e>>s*8&255}function Y(A,e){A[A.currentIndex++]=e&255,A[A.currentIndex++]=e>>8}function ie(A,e){mA(A,e,4)}function tA(A,e){let t=BigInt(e);for(let s=0n;s<8n;s++)A[A.currentIndex++]=Number(t>>s*8n&255n)}function qs(A,e){let t=e<<8|A;return t>32767?t-65536:t}var K=class extends Uint8Array{currentIndex=0;slice(A,e){let t=super.slice(A,e);return t.currentIndex=0,t}};function at(A,e=A.length,t=0){let s="";for(let n=0;n<e;n++){let a=A[t+n];if(a===0)return s;s+=String.fromCharCode(a)}return s}function ve(A,e){let t=A.currentIndex;return A.currentIndex+=e,at(A,e,t)}function Oe(A,e=!1,t=!1){let s=A.length;e&&s++,t&&s%2!==0&&s++;let n=new K(s);return De(n,A),n}function De(A,e,t=0){t>0&&e.length>t&&(e=e.slice(0,t));for(let s=0;s<e.length;s++)A[A.currentIndex++]=e.charCodeAt(s);if(t>e.length)for(let s=0;s<t-e.length;s++)A[A.currentIndex++]=0;return A}function fe(A){let e=0;for(;A;){let t=A[A.currentIndex++];if(e=e<<7|t&127,t>>7!==1)break}return e}function AA(A){let e=[A&127];for(A>>=7;A>0;)e.unshift(A&127|128),A>>=7;return e}function Ys(A){A=Math.floor(A);let e=Math.floor(A/60),t=Math.round(A-e*60);return{minutes:e,seconds:t,time:`${e.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}}function Js(A){let e="";for(let t=0;t<A.length;t++){let s=A[t].toString(16).padStart(2,"0").toUpperCase();e+=s,t<A.length-1&&(e+=" ")}return e}var l={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"},ZA;(()=>{var A=Uint8Array,e=Uint16Array,t=Int32Array,s=new A([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),n=new A([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new A([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=function(L,T){for(var q=new e(31),Z=0;Z<31;++Z)q[Z]=T+=1<<L[Z-1];for(var _=new t(q[30]),Z=1;Z<30;++Z)for(var te=q[Z];te<q[Z+1];++te)_[te]=te-q[Z]<<5|Z;return{b:q,r:_}},h=o(s,2),c=h.b,g=h.r;c[28]=258,g[258]=28;var I=o(n,0),E=I.b;I.r;var f=new e(32768);for(S=0;S<32768;++S)r=(S&43690)>>1|(S&21845)<<1,r=(r&52428)>>2|(r&13107)<<2,r=(r&61680)>>4|(r&3855)<<4,f[S]=((r&65280)>>8|(r&255)<<8)>>1;var r,S,C=function(L,T,q){for(var Z=L.length,_=0,te=new e(T);_<Z;++_)L[_]&&++te[L[_]-1];var se=new e(T);for(_=1;_<T;++_)se[_]=se[_-1]+te[_-1]<<1;var O;if(q){O=new e(1<<T);var U=15-T;for(_=0;_<Z;++_)if(L[_])for(var $=_<<4|L[_],Ae=T-L[_],R=se[L[_]-1]++<<Ae,oe=R|(1<<Ae)-1;R<=oe;++R)O[f[R]>>U]=$}else for(O=new e(Z),_=0;_<Z;++_)L[_]&&(O[_]=f[se[L[_]-1]++]>>15-L[_]);return O},w=new A(288);for(S=0;S<144;++S)w[S]=8;var S;for(S=144;S<256;++S)w[S]=9;var S;for(S=256;S<280;++S)w[S]=7;var S;for(S=280;S<288;++S)w[S]=8;var S,b=new A(32);for(S=0;S<32;++S)b[S]=5;var S,v=C(w,9,1),y=C(b,5,1),G=function(L){for(var T=L[0],q=1;q<L.length;++q)L[q]>T&&(T=L[q]);return T},N=function(L,T,q){var Z=T/8|0;return(L[Z]|L[Z+1]<<8)>>(T&7)&q},W=function(L,T){var q=T/8|0;return(L[q]|L[q+1]<<8|L[q+2]<<16)>>(T&7)},k=function(L){return(L+7)/8|0},D=function(L,T,q){return(T==null||T<0)&&(T=0),(q==null||q>L.length)&&(q=L.length),new A(L.subarray(T,q))},ee=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ne=function(L,T,q){var Z=new Error(T||ee[L]);if(Z.code=L,Error.captureStackTrace&&Error.captureStackTrace(Z,ne),!q)throw Z;return Z},ae=function(L,T,q,Z){var _=L.length,te=Z?Z.length:0;if(!_||T.f&&!T.l)return q||new A(0);var se=!q,O=se||T.i!=2,U=T.i;se&&(q=new A(_*3));var $=function(Ie){var ce=q.length;if(Ie>ce){var Re=new A(Math.max(ce*2,Ie));Re.set(q),q=Re}},Ae=T.f||0,R=T.p||0,oe=T.b||0,Ge=T.l,it=T.d,et=T.m,ot=T.n,dt=_*8;do{if(!Ge){Ae=N(L,R,1);var Bt=N(L,R+1,3);if(R+=3,Bt)ifLine truncated
|
||||
Secondary source: ${this.secondarySource.toString()}
|
||||
to: ${this.destinationName}
|
||||
amount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(e,t){Y(e,this.primarySource.toSourceEnum()),Y(e,this.destination),Y(e,this.transformAmount),Y(e,this.secondarySource.toSourceEnum()),Y(e,this.transformType),t&&t.mod++}sumTransform(e){let t=lA.copyFrom(this);return t.transformAmount+=e.transformAmount,t}},ue=class extends me{constructor(A,e,t,s,n){super($e.fromSourceEnum(A),$e.fromSourceEnum(e),t,s,n),this.destination>Is&&(this.destination=i.invalid)}},fn=[new ue(Ue(le.concave,!1,!0,!1,Be.noteOnVelocity),0,i.initialAttenuation,960,0),new ue(129,0,i.vibLfoToPitch,50,0),new ue(Ue(le.concave,!1,!0,!0,B.mainVolume),0,i.initialAttenuation,960,0),new ue(13,0,i.vibLfoToPitch,50,0),new ue(526,16,i.fineTune,12700,0),new ue(650,0,i.pan,500,0),new ue(Ue(le.concave,!1,!0,!0,B.expression),0,i.initialAttenuation,960,0),new ue(219,0,i.reverbEffectsSend,200,0),new ue(221,0,i.chorusEffectsSend,200,0)],un=[new ue(Ue(le.convex,!0,!1,!0,B.attackTime),0,i.attackVolEnv,6e3,0),new ue(Ue(le.linear,!0,!1,!0,B.releaseTime),0,i.releaseVolEnv,3600,0),new ue(Ue(le.linear,!0,!1,!0,B.decayTime),0,i.decayVolEnv,3600,0),new ue(Ue(le.linear,!0,!1,!0,B.brightness),0,i.initialFilterFc,9600,0),new ue(Bs,0,i.initialFilterQ,250,0),new ue(Ue(le.switch,!1,!1,!0,B.softPedal),0,i.initialAttenuation,50,0),new ue(Ue(le.switch,!1,!1,!0,B.softPedal),0,i.initialFilterFc,-2400,0),new ue(Ue(le.linear,!0,!1,!0,B.balance),0,i.pan,500,0)],Es=[...fn,...un],be=class{type;value=0;constructor(A,e,t=!0){if(this.type=A,e===void 0)throw new Error("No value provided.");if(this.value=Math.round(e),t){let s=Xe[A];s!==void 0&&(this.value=Math.max(s.min,Math.min(s.max,this.value)))}}write(A){Y(A,this.type),Y(A,this.value)}toString(){return`${Object.keys(i).find(A=>i[A]===this.type)}: ${this.value}`}},Pt=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}get fineTuning(){let A=this.getGenerator(i.coarseTune,0),e=this.getGenerator(i.fineTune,0);return A*100+e}set fineTuning(A){let e=Math.trunc(A/100),t=A%100;this.setGenerator(i.coarseTune,e),this.setGenerator(i.fineTune,t)}addToGenerator(A,e,t=!0){let s=this.getGenerator(A,Xe[A].def);this.setGenerator(A,e+s,t)}setGenerator(A,e,t=!0){switch(A){case i.sampleID:throw new Error("Use setSample()");case i.instrument:throw new Error("Use setInstrument()");case i.velRange:case i.keyRange:throw new Error("Set the range manually")}if(e===null){this.generators=this.generators.filter(n=>n.type!==A);return}let s=this.generators.findIndex(n=>n.type===A);s===-1?this.addGenerators(new be(A,e,t)):this.generators[s]=new be(A,e,t)}addGenerators(...A){for(let e of A)switch(e.type){default:this.generators.push(e);break;case i.sampleID:case i.instrument:break;case i.velRange:this.velRange.min=e.value&127,this.velRange.max=e.value>>8&127;break;case i.keyRange:this.keyRange.min=e.value&127,this.keyRange.max=e.value>>8&127}}addModulators(...A){this.modulators.push(...A)}getGenerator(A,e){return this.generators.find(t=>t.type===A)?.value??e}copyFrom(A){this.generators=A.generators.map(e=>new be(e.type,e.value,!1)),this.modulators=A.modulators.map(me.copyFrom.bind(me)),this.velRange={...A.velRange},this.keyRange={...A.keyRange}}getWriteGenerators(A){let e=this.generators.filter(t=>t.type!==i.sampleID&&t.type!==i.instrument&&t.type!==i.keyRange&&t.type!==i.velRange);if(!A)throw new Error("No bank provided! ");return this.hasVelRange&&e.unshift(new be(i.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&e.unshift(new be(i.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),e}},Qn=48e3,kA=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(A,e,t,s,n,a,o){this.name=A,this.sampleRate=e,this.originalKey=t,this.pitchCorrection=s,this.loopStart=a,this.loopEnd=o,this.sampleType=n}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===Se.rightSample||this.sampleType===Se.leftSample||this.sampleType===Se.linkedSample}get useCount(){return this.linkedTo.length}getRawData(A){return this.compressedData&&A&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(A){let e=this.getAudioData(),t=A/this.sampleRate,s=new Float32Array(Math.floor(e.length*t));for(let n=0;n<s.length;n++)s[n]=e[Math.floor(n*(1/t))];e=s,this.sampleRate=A,this.loopStart=Math.floor(this.loopStart*t),this.loopEnd=Math.floor(this.loopEnd*t),this.audioData=e}async compressSample(A){if(!this.isCompressed)try{let e=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(Qn),e=this.getAudioData());let t=await A(e,this.sampleRate);this.setCompressedData(t)}catch(e){d.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`,e),this.compressedData=void 0}}setSampleType(A){if(this.sampleType=A,this.i
Line truncated
|
||||
`:"")+c.subject:c?.comment),h("ISFT",e),A.defaultModulators.some(y=>!Es.some(G=>me.isIdentical(G,y,!0)))&&t){let y=A.defaultModulators;d.info(`%cWriting %c${y.length}%c default modulators...`,l.info,l.recognized,l.info);let G=new K(10+y.length*10);for(let N of y)N.write(G);mA(G,0,10),o.push(...F.getParts("DMOD",[G],a))}d.groupEnd(),d.info("%cWriting SDTA...",l.info);let g=[],I=[],E=kn(A,g,I,a);d.info("%cWriting PDTA...",l.info),d.info("%cWriting SHDR...",l.info);let f=Dn(A,g,I,a);d.group("%cWriting instruments...",l.info);let r=KA(A,a,!1);d.groupEnd(),d.group("%cWriting presets...",l.info);let C=KA(A,a,!0,n);d.groupEnd();let w=[C.hdr,C.bag,C.mod,C.gen,r.hdr,r.bag,r.mod,r.gen,f],b=F.getParts("pdta",w.map(y=>y.pdta),a,!0);s&&(r.writeXdta||C.writeXdta||A.presets.some(y=>y.name.length>20)||A.instruments.some(y=>y.name.length>20)||A.samples.some(y=>y.name.length>20))&&(d.info("%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.",l.info,l.value),o.push(...F.getParts("xdta",w.map(y=>y.xdta),a,!0)));let S=F.getParts("INFO",o,a,!0);d.info("%cWriting the output file...",l.info);let v=F.writeParts(a?"RIFS":"RIFF",[Oe(n?"sfen":"sfbk"),...S,...E,...b],a);return d.info(`%cSaved successfully! Final file size: %c${v.length}`,l.info,l.recognized),d.groupEnd(),v.buffer}var Dt=class{static verifyHeader(A,...e){for(let t of e)if(A.header.toLowerCase()===t.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${e.join(", or ")}" got "${A.header.toLowerCase()}"`)}static verifyText(A,...e){for(let t of e)if(A.toLowerCase()===t.toLowerCase())return;this.parsingError(`FourCC error: Expected "${e.join(", or ")}" got "${A.toLowerCase()}"`)}static parsingError(A){throw d.groupEnd(),new Error(`DLS parse error: ${A} The file may be corrupted.`)}static verifyAndReadList(A,...e){this.verifyHeader(A,"LIST"),A.data.currentIndex=0,this.verifyText(ve(A.data,4),...e);let t=[];for(;A.data.length>A.data.currentIndex;)t.push(F.read(A.data));return t}},P={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},p={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,reservedEG1:520,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,reservedEG2:780,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281},VA={forward:0,loopAndRelease:1},qt=20,Yt=16,St=class Rt extends Dt{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(e){let t=new Rt;return t.unityNote=e.unityNote,t.gain=e.gain,t.fineTune=e.fineTune,t.loops=e.loops.map(s=>({...s})),t.fulOptions=e.fulOptions,t}static read(e){this.verifyHeader(e,"wsmp");let t=new Rt,s=J(e.data,4);if(s!==qt&&d.warn(`Wsmp cbSize mismatch: got ${s}, expected ${qt}.`),t.unityNote=J(e.data,2),t.fineTune=qs(e.data[e.data.currentIndex++],e.data[e.data.currentIndex++]),t.gain=J(e.data,4)|0,t.fulOptions=J(e.data,4),J(e.data,4)!==0){let n=J(e.data,4);n!==Yt&&d.warn(`CbSize for loop in wsmp mismatch. Expected ${Yt}, got ${n}.`);let a=J(e.data,4),o=J(e.data,4),h=J(e.data,4);t.loops.push({loopStart:o,loopLength:h,loopType:a})}return t}static fromSFSample(e){let t=new Rt;return t.unityNote=e.originalKey,t.fineTune=e.pitchCorrection,(e.loopEnd!==0||e.loopStart!==0)&&t.loops.push({loopStart:e.loopStart,loopLength:e.loopEnd-e.loopStart,loopType:VA.forward}),t}static fromSFZone(e){let t=new Rt;t.unityNote=e.getGenerator(i.overridingRootKey,e.sample.originalKey),e.getGenerator(i.scaleTuning,100)===0&&e.keyRange.max-e.keyRange.min===0&&(t.unityNote=e.keyRange.min),t.fineTune=e.fineTuning+e.sample.pitchCorrection,t.gain=-(e.getGenerator(i.initialAttenuation,0)*.4)<<16;let s=e.getGenerator(i.sampleModes,0);if(s!==0){let n=e.sample.loopStart+e.getGenerator(i.startloopAddrsOffset,0)+e.getGenerator(i.startloopAddrsCoarseOffset,0)*32768,a=e.sample.loopEnd+e.getGenerator(i.endloopAddrsOffset,0)+e.getGenerator(i.endloopAddrsCoarseOffset,0)*32768,o;switch(s){case 1:default:o=0;break;case 3:o=1}t.loops.push({loopType:o,loopStart:n,loopLength:a-n})}return t}toSFZone(e,t){let s=0,n=this.loops[0];n&&(s=n.loopType===VA.loopAndRelease?3:1),s!==0&&e.setGenerator(i.sampleModes,s);let a=-(this.gain>>16)/.4;if(a!==0&&e.setGenerator(i.initialAttenuation,a),e.fineTuning=this.fineTune-t.pitchCorrection,this.unityNote!==t.originalKey&&e.setGenerator(i.overridingRootKey,this.unityNote),n){let o=n.loopStart-t.loopStart,h=n.loopStart+n.loopLength-t.loopEnd;if(o!==0){let c=o%32768;e.setGenerator(i.startloopAddrsOffset,c);let g=Math.trunc(o/32768);g!==0&&e.setGenerator(i.startloopAddrsCoarseOffset,g)}if(h!==0){let c=h%32768;e.setGenerator(i.endloopAddrsOffset,c);let g=Math.trunc(h/32768);
Line truncated
|
||||
${e.toString()}
|
||||
(${I})`)};if(e.transformType!==0){s("Absolute transform type is not supported");return}if(me.isIdentical(e,ps,!0)||me.isIdentical(e,ms,!0))return;let n=Je.fromSFSource(e.primarySource);if(!n){s("Invalid primary source");return}let a=Je.fromSFSource(e.secondarySource);if(!a){s("Invalid secondary source");return}let o=It.fromSFDestination(e.destination,e.transformAmount);if(o===void 0){s("Invalid destination");return}let h=e.transformAmount,c;if(typeof o=="number")c=o;else if(c=o.destination,h=o.amount,o.source!==P.none){if(a.source!==P.none&&n.source!==P.none){s("Articulation generators with secondary source are not supported");return}n.source!==P.none&&(a=n),n=new Je(o.source,le.linear,o.isBipolar)}let g=new It(n,a,c,0,h<<16);t.connectionBlocks.push(g)}static copyFrom(e){return new It(Je.copyFrom(e.source),Je.copyFrom(e.control),e.destination,e.transform,e.scale)}static fromSFGenerator(e,t){if(Fn.has(e.type))return;let s=c=>{d.warn(`Failed converting SF2 generator into DLS:
|
||||
${e.toString()}
|
||||
(${c})`)},n=It.fromSFDestination(e.type,e.value);if(n===void 0){s("Invalid type");return}let a=new Je,o,h=e.value;typeof n=="number"?o=n:(o=n.destination,h=n.amount,a.source=n.source,a.bipolar=n.isBipolar),t.connectionBlocks.push(new It(a,new Je,o,0,h<<16))}static fromSFDestination(e,t){switch(e){default:return;case i.initialAttenuation:return{destination:p.gain,amount:-t,isBipolar:!1,source:P.none};case i.fineTune:return p.pitch;case i.pan:return p.pan;case i.keyNum:return p.keyNum;case i.reverbEffectsSend:return p.reverbSend;case i.chorusEffectsSend:return p.chorusSend;case i.freqModLFO:return p.modLfoFreq;case i.delayModLFO:return p.modLfoDelay;case i.delayVibLFO:return p.vibLfoDelay;case i.freqVibLFO:return p.vibLfoFreq;case i.delayVolEnv:return p.volEnvDelay;case i.attackVolEnv:return p.volEnvAttack;case i.holdVolEnv:return p.volEnvHold;case i.decayVolEnv:return p.volEnvDecay;case i.sustainVolEnv:return{destination:p.volEnvSustain,amount:1e3-t,isBipolar:!1,source:P.none};case i.releaseVolEnv:return p.volEnvRelease;case i.delayModEnv:return p.modEnvDelay;case i.attackModEnv:return p.modEnvAttack;case i.holdModEnv:return p.modEnvHold;case i.decayModEnv:return p.modEnvDecay;case i.sustainModEnv:return{destination:p.modEnvSustain,amount:1e3-t,isBipolar:!1,source:P.none};case i.releaseModEnv:return p.modEnvRelease;case i.initialFilterFc:return p.filterCutoff;case i.initialFilterQ:return p.filterQ;case i.modEnvToFilterFc:return{source:P.modEnv,destination:p.filterCutoff,amount:t,isBipolar:!1};case i.modEnvToPitch:return{source:P.modEnv,destination:p.pitch,amount:t,isBipolar:!1};case i.modLfoToFilterFc:return{source:P.modLfo,destination:p.filterCutoff,amount:t,isBipolar:!0};case i.modLfoToVolume:return{source:P.modLfo,destination:p.gain,amount:t,isBipolar:!0};case i.modLfoToPitch:return{source:P.modLfo,destination:p.pitch,amount:t,isBipolar:!0};case i.vibLfoToPitch:return{source:P.vibratoLfo,destination:p.pitch,amount:t,isBipolar:!0};case i.keyNumToVolEnvHold:return{source:P.keyNum,destination:p.volEnvHold,amount:t,isBipolar:!0};case i.keyNumToVolEnvDecay:return{source:P.keyNum,destination:p.volEnvDecay,amount:t,isBipolar:!0};case i.keyNumToModEnvHold:return{source:P.keyNum,destination:p.modEnvHold,amount:t,isBipolar:!0};case i.keyNumToModEnvDecay:return{source:P.keyNum,destination:p.modEnvDecay,amount:t,isBipolar:!0};case i.scaleTuning:return{source:P.keyNum,destination:p.pitch,amount:t*128,isBipolar:!1}}}toString(){return`Source: ${this.source.toString()},
|
||||
Control: ${this.control.toString()},
|
||||
Scale: ${this.scale} >> 16 = ${this.shortScale},
|
||||
Output transform: ${this.transformName}
|
||||
Destination: ${this.destinationName}`}write(){let e=new K(12);return Y(e,this.source.source),Y(e,this.control.source),Y(e,this.destination),Y(e,this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10),ie(e,this.scale),e}toSFGenerator(e){let t=this.destination,s=this.shortScale;switch(t){default:d.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c
|
||||
(invalid destination)`,l.warn,l.value,l.unrecognized);return;case p.pan:e.setGenerator(i.pan,s);break;case p.gain:e.addToGenerator(i.initialAttenuation,-s/.4);break;case p.filterCutoff:e.setGenerator(i.initialFilterFc,s);break;case p.filterQ:e.setGenerator(i.initialFilterQ,s);break;case p.modLfoFreq:e.setGenerator(i.freqModLFO,s);break;case p.modLfoDelay:e.setGenerator(i.delayModLFO,s);break;case p.vibLfoFreq:e.setGenerator(i.freqVibLFO,s);break;case p.vibLfoDelay:e.setGenerator(i.delayVibLFO,s);break;case p.volEnvDelay:e.setGenerator(i.delayVolEnv,s);break;case p.volEnvAttack:e.setGenerator(i.attackVolEnv,s);break;case p.volEnvHold:e.setGenerator(i.holdVolEnv,s);break;case p.volEnvDecay:e.setGenerator(i.decayVolEnv,s);break;case p.volEnvRelease:e.setGenerator(i.releaseVolEnv,s);break;case p.volEnvSustain:e.setGenerator(i.sustainVolEnv,1e3-s);break;case p.modEnvDelay:e.setGenerator(i.delayModEnv,s);break;case p.modEnvAttack:e.setGenerator(i.attackModEnv,s);break;case p.modEnvHold:e.setGenerator(i.holdModEnv,s);break;case p.modEnvDecay:e.setGenerator(i.decayModEnv,s);break;case p.modEnvRelease:e.setGenerator(i.releaseModEnv,s);break;case p.modEnvSustain:e.setGenerator(i.sustainModEnv,1e3-s);break;case p.reverbSend:e.setGenerator(i.reverbEffectsSend,s);break;case p.chorusSend:e.setGenerator(i.chorusEffectsSend,s);break;case p.pitch:e.fineTuning+=s;break}}toSFModulator(e){let t=this.shortScale,s,n,a=new $e,o=this.toCombinedSFDestination();if(o){s=o;let c=this.control.toSFSource();if(!c){this.failedConversion("Invalid control");return}n=c}else{let c=this.toSFDestination();if(!c){this.failedConversion("Invalid destination");return}typeof c=="object"?(t=c.newAmount,s=c.gen):s=c;let g=this.source.toSFSource();if(!g){this.failedConversion("Invalid source");return}n=g;let I=this.control.toSFSource();if(!I){this.failedConversion("Invalid control");return}a=I}this.transform!==le.linear&&n.curveType===le.linear&&(n.curveType=this.transform),s===i.initialAttenuation&&((this.source.source===P.velocity||this.source.source===P.volume||this.source.source===P.expression)&&(n.isNegative=!0),t=Math.min(960,Math.max(0,t)));let h=new me(n,a,s,t,0);e.addModulators(h)}toCombinedSFDestination(){let e=this.source.source,t=this.destination;return e===P.vibratoLfo&&t===p.pitch?i.vibLfoToPitch:e===P.modLfo&&t===p.pitch?i.modLfoToPitch:e===P.modLfo&&t===p.filterCutoff?i.modLfoToFilterFc:e===P.modLfo&&t===p.gain?i.modLfoToVolume:e===P.modEnv&&t===p.filterCutoff?i.modEnvToFilterFc:e===P.modEnv&&t===p.pitch?i.modEnvToPitch:void 0}failedConversion(e){d.info(`%cFailed converting DLS articulator into SF2:
|
||||
%c${this.toString()}%c
|
||||
(${e})`,l.warn,l.value,l.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case p.none:return;case p.pan:return i.pan;case p.gain:return{gen:i.initialAttenuation,newAmount:-e};case p.pitch:return i.fineTune;case p.keyNum:return i.overridingRootKey;case p.volEnvDelay:return i.delayVolEnv;case p.volEnvAttack:return i.attackVolEnv;case p.volEnvHold:return i.holdVolEnv;case p.volEnvDecay:return i.decayVolEnv;case p.volEnvSustain:return{gen:i.sustainVolEnv,newAmount:1e3-e};case p.volEnvRelease:return i.releaseVolEnv;case p.modEnvDelay:return i.delayModEnv;case p.modEnvAttack:return i.attackModEnv;case p.modEnvHold:return i.holdModEnv;case p.modEnvDecay:return i.decayModEnv;case p.modEnvSustain:return{gen:i.sustainModEnv,newAmount:1e3-e};case p.modEnvRelease:return i.releaseModEnv;case p.filterCutoff:return i.initialFilterFc;case p.filterQ:return i.initialFilterQ;case p.chorusSend:return i.chorusEffectsSend;case p.reverbSend:return i.reverbEffectsSend;case p.modLfoFreq:return i.freqModLFO;case p.modLfoDelay:return i.delayModLFO;case p.vibLfoFreq:return i.freqVibLFO;case p.vibLfoDelay:return i.delayVibLFO}}},ys=class extends Dt{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(A){this.mode=A.mode;for(let e of A.connectionBlocks)this.connectionBlocks.push(vt.copyFrom(e))}fromSFZone(A){this.mode="dls2";let e=new Pt;e.copyFrom(A);for(let t of e.generators){let s;switch(t.type){default:continue;case i.keyNumToVolEnvDecay:s=i.decayVolEnv;break;case i.keyNumToVolEnvHold:s=i.holdVolEnv;break;case i.keyNumToModEnvDecay:s=i.decayModEnv;break;case i.keyNumToModEnvHold:s=i.holdModEnv}let n=e.getGenerator(s,void 0),a=t.value*-128;if(n===void 0)continue;let o=n-60/128*a;e.setGenerator(t.type,a,!1),e.setGenerator(s,o,!1)}for(let t of e.generators)vt.fromSFGenerator(t,this);for(let t of e.modulators)vt.fromSFModulator(t,this)}read(A){let e=F.findListType(A,"lart"),t=F.findListType(A,"lar2");if(e)for(this.mode="dls1";e.data.currentIndex<e.data.length;){let s=F.read(e.data);if(s.header!=="art1"&&s.header!=="art2")continue;let n=s.data,a=J(n,4);a!==8&&d.warn(`CbSize in articulation mismatch. Expected 8, got ${a}`);let o=J(n,4);for(let h=0;h<o;h++)this.connectionBlocks.push(vt.read(n))}else if(t)for(this.mode="dls2";t.data.currentIndex<t.data.length;){let s=F.read(t.data);if(s.header!=="art1"&&s.header!=="art2")continue;let n=s.data,a=J(n,4);a!==8&&d.warn(`CbSize in articulation mismatch. Expected 8, got ${a}`);let o=J(n,4);for(let h=0;h<o;h++)this.connectionBlocks.push(vt.read(n))}}write(){let A=new K(8);ie(A,8),ie(A,this.connectionBlocks.length);let e=this.connectionBlocks.map(s=>s.write()),t=F.getParts(this.mode==="dls2"?"art2":"art1",[A,...e]);return F.getParts(this.mode==="dls2"?"lar2":"lart",t,!0)}toSFZone(A){let e=(t,s,n,a)=>{let o=t/-128;if(A.setGenerator(s,o),o<=120){let h=Math.round(.46875*t),c=this.connectionBlocks.find(g=>g.isStaticParameter&&g.destination===a);c&&A.setGenerator(n,h+c.shortScale)}};for(let t of this.connectionBlocks){let s=t.shortScale,n=t.source.source,a=t.control.source,o=t.destination;if(t.isStaticParameter){t.toSFGenerator(A);continue}if(a===P.none)if(n===P.keyNum){if(o===p.pitch){A.setGenerator(i.scaleTuning,s/128);continue}if(o===p.modEnvHold||o===p.modEnvDecay||o===p.volEnvHold||o===p.volEnvDecay)continue}else{let h=t.toCombinedSFDestination();if(h){A.setGenerator(h,s);continue}}t.toSFModulator(A)}for(let t of this.connectionBlocks){if(t.source.source!==P.keyNum)continue;let s=t.shortScale;switch(t.destination){default:case p.volEnvHold:e(s,i.keyNumToVolEnvHold,i.holdVolEnv,p.volEnvHold);break;case p.volEnvDecay:e(s,i.keyNumToVolEnvDecay,i.decayVolEnv,p.volEnvDecay);break;case p.modEnvHold:e(s,i.keyNumToModEnvHold,i.holdModEnv,p.modEnvHold);break;case p.modEnvDecay:e(s,i.keyNumToModEnvDecay,i.decayModEnv,p.modEnvDecay);break}}if(this.mode==="dls1"){A.setGenerator(i.delayVibLFO,A.getGenerator(i.delayModLFO,null)),A.setGenerator(i.freqVibLFO,A.getGenerator(i.freqModLFO,null)),A.setGenerator(i.vibLfoToPitch,A.getGenerator(i.modLfoToPitch,null)),A.setGenerator(i.modLfoToPitch,null);for(let t of A.modulators)t.destination===i.modLfoToPitch&&(t.destination=i.vibLfoToPitch)}}},iA=class Jt{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let t=new Jt(e.tableIndex);return t.channel=e.channel,t.phaseGroup=e.phaseGroup,t.fusOptions=e.fusOptions,t}static read(e){let t=J(e.data,2),s=J(e.data,2),n=J(e.data,4),a=new Jt(J(e.data,4));return a.channel=n,a.fusOptions=t,a.phaseGroup=s,a}static fromSFZone(e,t){let s=e.indexOf(t.sample);if(s===-1)throw new Error(`Wave link error: Sample ${t.sample.name} does not exist in the sample list.`);let n=new Jt(s);switch(t.sample.sampleType){default:case Se.leftSample:case Se.monoSample:n.channel=Math.trunc(1);break;case Se.rightSample:n.channel=2}return n}write(){let e=new K(12);return Y(e,this.fusOptions),Y(e,this.phaseGroup),ie(e,this.channel
Line truncated
|
||||
Expected ${this._outputCount} got ${A.length}`);for(let e=0;e<this._outputCount;e++)this.connectChannel(A[e],e)}disconnectIndividualOutputs(A){if(A.length!==this._outputCount)throw new Error(`input nodes amount differs from the system's outputs amount!
|
||||
Expected ${this._outputCount} got ${A.length}`);for(let e=0;e<this._outputCount;e++)this.disconnectChannel(A[e],e)}sendMessage(A,e=0,t=Ke){this._sendInternal(A,e,t)}noteOn(A,e,t,s=Ke){let n=A%16,a=A-n;e%=128,t%=128,this.sendMessage([M.noteOn|n,e,t],a,s)}noteOff(A,e,t=Ke){e%=128;let s=A%16,n=A-s;this._sendInternal([M.noteOff|s,e],n,t)}stopAll(A=!1){this.post({channelNumber:-1,type:"stopAll",data:A?1:0})}controllerChange(A,e,t,s=Ke){if(e>127||e<0)throw new Error(`Invalid controller number: ${e}`);t=Math.floor(t)%128,e=Math.floor(e)%128;let n=A%16,a=A-n;this._sendInternal([M.controllerChange|n,e,t],a,s)}reset(){this.post({channelNumber:-1,type:"ccReset",data:null})}channelPressure(A,e,t=Ke){let s=A%16,n=A-s;e%=128,this.sendMessage([M.channelPressure|s,e],n,t)}polyPressure(A,e,t,s=Ke){let n=A%16,a=A-n;e%=128,t%=128,this.sendMessage([M.polyPressure|n,e,t],a,s)}pitchWheel(A,e,t=Ke){let s=A%16,n=A-s;this.sendMessage([M.pitchWheel|s,e&127,e>>7],n,t)}pitchWheelRange(A,e,t=Ke){this.controllerChange(A,B.registeredParameterMSB,0,t),this.controllerChange(A,B.registeredParameterLSB,0,t),this.controllerChange(A,B.dataEntryMSB,e),this.controllerChange(A,B.registeredParameterMSB,127,t),this.controllerChange(A,B.registeredParameterLSB,127,t),this.controllerChange(A,B.dataEntryMSB,0,t)}programChange(A,e,t=Ke){let s=A%16,n=A-s;e%=128,this.sendMessage([M.programChange|s,e],n,t)}systemExclusive(A,e=0,t=Ke){this._sendInternal([M.systemExclusive,...Array.from(A)],e,t)}tuneKeys(A,e){if(e.length>127)throw new Error("Too many tunings. Maximum allowed is 127.");let t=[127,16,8,2,A,e.length];for(let s of e)if(t.push(s.sourceKey),s.targetPitch===-1)t.push(127,127,127);else{let n=Math.floor(s.targetPitch),a=Math.floor((s.targetPitch-n)/61e-6);t.push(n,a>>7&127,a&127)}t.push(247),this.systemExclusive(t)}reverbateEverythingBecauseWhyNot(){for(let A=0;A<this.midiChannels.length;A++)this.controllerChange(A,B.reverbDepth,127),this.midiChannels[A].lockController(B.reverbDepth,!0);return"That's the spirit!"}awaitWorkerResponse(A,e){this.resolveMap.set(A,e)}assignNewSequencer(A){return this.post({channelNumber:-1,type:"requestNewSequencer",data:null}),this.sequencers.push(A),this.sequencers.length-1}assignProgressTracker(A,e){if(this.renderingProgressTracker.get(A))throw new Error("Something is already being rendered!");this.renderingProgressTracker.set(A,e)}revokeProgressTracker(A){this.renderingProgressTracker.delete(A)}_sendInternal(A,e,t){let s=RA(t,Ke);this.post({type:"midiMessage",channelNumber:-1,data:{messageData:new Uint8Array(A),channelOffset:e,options:s}})}handleMessage(A){switch(A.type){case"eventCall":this.eventHandler.callEventInternal(A.data.type,A.data.data);break;case"sequencerReturn":this.sequencers[A.data.id]?.(A.data);break;case"voiceCountChange":for(let e=0;e<A.data.length;e++)this.midiChannels[e].voiceCount=A.data[e],this._voiceCount=A.data.reduce((t,s)=>t+s,0);break;case"isFullyInitialized":this.workletResponds(A.data.type,A.data.data);break;case"soundBankError":d.warn(A.data),this.eventHandler.callEventInternal("soundBankError",A.data);break;case"renderingProgress":this.renderingProgressTracker.get(A.data.type)?.(A.data.data)}}addNewChannelInternal(A){this.midiChannels.push(new Kn(this.midiChannels.length,this)),A&&this.post({channelNumber:0,type:"addNewChannel",data:null})}workletResponds(A,e){this.resolveMap.get(A)?.(e),this.resolveMap.delete(A)}registerInternalEvent(A,e){this.eventHandler.addEvent(A,Vn(A),e)}},vs=class extends _n{constructor(A,e=bs){let t=RA(e,bs),s=new Array(17).fill(2),n=17;t.oneOutput&&(s=[34],n=1);let a;try{a=(t?.audioNodeCreators?.worklet??((o,h,c)=>new AudioWorkletNode(o,h,c)))(A,On,{outputChannelCount:s,numberOfOutputs:n,processorOptions:{oneOutput:t.oneOutput,eventsEnabled:t.eventsEnabled}})}catch(o){throw console.error(o),new Error("Could not create the AudioWorkletNode. Did you forget to addModule()?",{cause:o})}super(a,(o,h=[])=>{a.port.postMessage(o,h)},t)}async startOfflineRender(A){this.post({type:"startOfflineRender",data:A,channelNumber:-1},A.soundBankList.map(e=>e.soundBankBuffer)),await new Promise(e=>this.awaitWorkerResponse("startOfflineRender",e))}destroy(){this.post({channelNumber:0,type:"destroyWorklet",data:null}),this.worklet.disconnect(),delete this.worklet}};var FA={trim:!0,bankID:"",writeEmbeddedSoundBank:!0,sequencerID:0},Wn={...FA,writeDefaultModulators:!0,writeExtendedLimits:!0,compressionAction:"keep",compressionQuality:1,software:"SpessaSynth"},Pa={...FA,applySnapshot:!1,bankOffset:0,correctBankOffset:!0,metadata:{},format:"sf2",...Wn},Ta={...FA,software:"SpessaSynth"};var Xn=class extends Lt{events=[];constructor(A){super(),super.copyFrom(A),this.events=[]}},Zn=class Rs extends kt{tracks;timeline=[];embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(e){super(),super.copyMetadataFrom(e),this.tracks=e.tracks.map(t=>new Xn(t)),this.embeddedSoundBankSize=e instanceof Rs?e.embeddedSoundBankSize:e?.embeddedSoundBank?.byteLength}},vA={shuffleOn:1,shuffleO
Line truncated
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
function Ht(t,e,A=0){let s=0;for(let a=0;a<e;a++)s=s<<8|t[A+a];return s>>>0}function Nt(t,e){let A=Ht(t,e,t.currentIndex);return t.currentIndex+=e,A}function nA(t,e){let A=new Array(e).fill(0);for(let s=e-1;s>=0;s--)A[s]=t&255,t>>=8;return A}function X(t,e){let A=cs(t,e,t.currentIndex);return t.currentIndex+=e,A}function cs(t,e,A=0){let s=0;for(let a=0;a<e;a++)s|=t[A+a]<<a*8;return s>>>0}function hs(t,e,A){for(let s=0;s<A;s++)t[t.currentIndex++]=e>>s*8&255}function se(t,e){t[t.currentIndex++]=e&255,t[t.currentIndex++]=e>>8}function ge(t,e){hs(t,e,4)}function ls(t,e){let A=e<<8|t;return A>32767?A-65536:A}function Jn(t){return t>127?t-256:t}var ne=class extends Uint8Array{currentIndex=0;slice(t,e){let A=super.slice(t,e);return A.currentIndex=0,A}};function $e(t,e=t.length,A=0){let s="";for(let a=0;a<e;a++){let n=t[A+a];if(n===0)return s;s+=String.fromCharCode(n)}return s}function de(t,e){let A=t.currentIndex;return t.currentIndex+=e,$e(t,e,A)}function et(t,e=!1,A=!1){let s=t.length;e&&s++,A&&s%2!==0&&s++;let a=new ne(s);return Ne(a,t),a}function Ne(t,e,A=0){A>0&&e.length>A&&(e=e.slice(0,A));for(let s=0;s<e.length;s++)t[t.currentIndex++]=e.charCodeAt(s);if(A>e.length)for(let s=0;s<A-e.length;s++)t[t.currentIndex++]=0;return t}function pe(t){let e=0;for(;t;){let A=t[t.currentIndex++];if(e=e<<7|A&127,A>>7!==1)break}return e}function xA(t){let e=[t&127];for(t>>=7;t>0;)e.unshift(t&127|128),t>>=7;return e}function zA(t){t=Math.floor(t);let e=Math.floor(t/60),A=Math.round(t-e*60);return{minutes:e,seconds:A,time:`${e.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`}}function js(t){let e="";for(let A=0;A<t.length;A++){let s=t[A].toString(16).padStart(2,"0").toUpperCase();e+=s,A<t.length-1&&(e+=" ")}return e}var d={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"},en;(()=>{var t=Uint8Array,e=Uint16Array,A=Int32Array,s=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),a=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),n=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(x,D){for(var Q=new e(31),T=0;T<31;++T)Q[T]=D+=1<<x[T-1];for(var H=new A(Q[30]),T=1;T<30;++T)for(var z=Q[T];z<Q[T+1];++z)H[z]=z-Q[T]<<5|T;return{b:Q,r:H}},i=r(s,2),o=i.b,I=i.r;o[28]=258,I[258]=28;var l=r(a,0),B=l.b;l.r;var C=new e(32768);for(u=0;u<32768;++u)g=(u&43690)>>1|(u&21845)<<1,g=(g&52428)>>2|(g&13107)<<2,g=(g&61680)>>4|(g&3855)<<4,C[u]=((g&65280)>>8|(g&255)<<8)>>1;var g,u,E=function(x,D,Q){for(var T=x.length,H=0,z=new e(D);H<T;++H)x[H]&&++z[x[H]-1];var j=new e(D);for(H=1;H<D;++H)j[H]=j[H-1]+z[H-1]<<1;var W;if(Q){W=new e(1<<D);var K=15-D;for(H=0;H<T;++H)if(x[H])for(var ee=H<<4|x[H],Ae=D-x[H],O=j[x[H]-1]++<<Ae,re=O|(1<<Ae)-1;O<=re;++O)W[C[O]>>K]=ee}else for(W=new e(T),H=0;H<T;++H)x[H]&&(W[H]=C[j[x[H]-1]++]>>15-x[H]);return W},S=new t(288);for(u=0;u<144;++u)S[u]=8;var u;for(u=144;u<256;++u)S[u]=9;var u;for(u=256;u<280;++u)S[u]=7;var u;for(u=280;u<288;++u)S[u]=8;var u,k=new t(32);for(u=0;u<32;++u)k[u]=5;var u,M=E(S,9,1),w=E(k,5,1),R=function(x){for(var D=x[0],Q=1;Q<x.length;++Q)x[Q]>D&&(D=x[Q]);return D},F=function(x,D,Q){var T=D/8|0;return(x[T]|x[T+1]<<8)>>(D&7)&Q},N=function(x,D){var Q=D/8|0;return(x[Q]|x[Q+1]<<8|x[Q+2]<<16)>>(D&7)},m=function(x){return(x+7)/8|0},p=function(x,D,Q){return(D==null||D<0)&&(D=0),(Q==null||Q>x.length)&&(Q=x.length),new t(x.subarray(D,Q))},y=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],V=function(x,D,Q){var T=new Error(D||y[x]);if(T.code=x,Error.captureStackTrace&&Error.captureStackTrace(T,V),!Q)throw T;return T},Y=function(x,D,Q,T){var H=x.length,z=T?T.length:0;if(!H||D.f&&!D.l)return Q||new t(0);var j=!Q,W=j||D.i!=2,K=D.i;j&&(Q=new t(H*3));var ee=function(Be){var he=Q.length;if(Be>he){var xe=new t(Math.max(he*2,Be));xe.set(Q),Q=xe}},Ae=D.f||0,O=D.p||0,re=D.b||0,ue=D.l,Le=D.d,Ee=D.m,Re=D.n,Oe=H*8;do{if(!ue){Ae=F(x,O,1);var Bt=F(x,O+1,3);if(O+=3,Bt)if(Bt==1)ue=M,Le=w,Ee=9,Re=5;else if(Bt==2){var Et=F(x,O,31)+257,eA=F(x,O+10,15)+4,tA=Et+F(x,O+5,31)+1;O+=14;for(var Je=new t(tA),Qt=new t(19),ve=0;ve<eA;++ve)Qt[n[ve]]=F(x,O+ve*3,7);O+=eA*3;for(var Yt=R(Qt),bt=(1<<Yt)-1,UA=E(Qt,Yt,1),ve=0;ve<tA;){var qt=UA[F(x,O,bt)];O+=qt&15;var ze=qt>>4;if(ze<16)Je[ve++]=ze;else{var It=0,dt=0;for(ze==16?(dt=3+F(x,O,3),O+=2,It=Je[ve-1]):ze==17?(dt=3+F(x,O,7),O+=3):ze==18&&(dt=11+F(x,O,127),O+=7);dt--;)Je[ve++]=It}}var Rt=Je.subarray(0,Et),Ke=Je.subarray(Et);Ee=R(Rt),Re=R(Ke),ue=E(Rt,Ee,1),Le=E(Ke,Re,1)}else V(1);else{var ze=m(O)+4,ut=x[ze-4]|x[ze-3]<<8,tt=ze+ut;if(tt>H){K&&V(0);break}W&&ee(re+ut),Q.set(x.subarray(ze,tt),re),D.b=re+=ut,D.p=O=tt*8,D.f=Ae;continue}if(O>Oe){K&&V(0);break}}W&&ee(re+131072);for(var v=(1<<Ee)-1,b=(1<<Re)-1,L=O;;L=O){var ItLine truncated
|
||||
Secondary source: ${this.secondarySource.toString()}
|
||||
to: ${this.destinationName}
|
||||
amount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(e,A){se(e,this.primarySource.toSourceEnum()),se(e,this.destination),se(e,this.transformAmount),se(e,this.secondarySource.toSourceEnum()),se(e,this.transformType),A&&A.mod++}sumTransform(e){let A=as.copyFrom(this);return A.transformAmount+=e.transformAmount,A}},ye=class extends we{constructor(t,e,A,s,a){super(at.fromSourceEnum(t),at.fromSourceEnum(e),A,s,a),this.destination>hn&&(this.destination=c.invalid)}},Ha=[new ye(_e(Ce.concave,!1,!0,!1,Ie.noteOnVelocity),0,c.initialAttenuation,960,0),new ye(129,0,c.vibLfoToPitch,50,0),new ye(_e(Ce.concave,!1,!0,!0,f.mainVolume),0,c.initialAttenuation,960,0),new ye(13,0,c.vibLfoToPitch,50,0),new ye(526,16,c.fineTune,12700,0),new ye(650,0,c.pan,500,0),new ye(_e(Ce.concave,!1,!0,!0,f.expression),0,c.initialAttenuation,960,0),new ye(219,0,c.reverbEffectsSend,200,0),new ye(221,0,c.chorusEffectsSend,200,0)],Oa=[new ye(_e(Ce.convex,!0,!1,!0,f.attackTime),0,c.attackVolEnv,6e3,0),new ye(_e(Ce.linear,!0,!1,!0,f.releaseTime),0,c.releaseVolEnv,3600,0),new ye(_e(Ce.linear,!0,!1,!0,f.decayTime),0,c.decayVolEnv,3600,0),new ye(_e(Ce.linear,!0,!1,!0,f.brightness),0,c.initialFilterFc,9600,0),new ye(Bn,0,c.initialFilterQ,250,0),new ye(_e(Ce.switch,!1,!1,!0,f.softPedal),0,c.initialAttenuation,50,0),new ye(_e(Ce.switch,!1,!1,!0,f.softPedal),0,c.initialFilterFc,-2400,0),new ye(_e(Ce.linear,!0,!1,!0,f.balance),0,c.pan,500,0)],En=[...Ha,...Oa],Pe=class{type;value=0;constructor(t,e,A=!0){if(this.type=t,e===void 0)throw new Error("No value provided.");if(this.value=Math.round(e),A){let s=We[t];s!==void 0&&(this.value=Math.max(s.min,Math.min(s.max,this.value)))}}write(t){se(t,this.type),se(t,this.value)}toString(){return`${Object.keys(c).find(t=>c[t]===this.type)}: ${this.value}`}},$t=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}get fineTuning(){let t=this.getGenerator(c.coarseTune,0),e=this.getGenerator(c.fineTune,0);return t*100+e}set fineTuning(t){let e=Math.trunc(t/100),A=t%100;this.setGenerator(c.coarseTune,e),this.setGenerator(c.fineTune,A)}addToGenerator(t,e,A=!0){let s=this.getGenerator(t,We[t].def);this.setGenerator(t,e+s,A)}setGenerator(t,e,A=!0){switch(t){case c.sampleID:throw new Error("Use setSample()");case c.instrument:throw new Error("Use setInstrument()");case c.velRange:case c.keyRange:throw new Error("Set the range manually")}if(e===null){this.generators=this.generators.filter(a=>a.type!==t);return}let s=this.generators.findIndex(a=>a.type===t);s===-1?this.addGenerators(new Pe(t,e,A)):this.generators[s]=new Pe(t,e,A)}addGenerators(...t){for(let e of t)switch(e.type){default:this.generators.push(e);break;case c.sampleID:case c.instrument:break;case c.velRange:this.velRange.min=e.value&127,this.velRange.max=e.value>>8&127;break;case c.keyRange:this.keyRange.min=e.value&127,this.keyRange.max=e.value>>8&127}}addModulators(...t){this.modulators.push(...t)}getGenerator(t,e){return this.generators.find(A=>A.type===t)?.value??e}copyFrom(t){this.generators=t.generators.map(e=>new Pe(e.type,e.value,!1)),this.modulators=t.modulators.map(we.copyFrom.bind(we)),this.velRange={...t.velRange},this.keyRange={...t.keyRange}}getWriteGenerators(t){let e=this.generators.filter(A=>A.type!==c.sampleID&&A.type!==c.instrument&&A.type!==c.keyRange&&A.type!==c.velRange);if(!t)throw new Error("No bank provided! ");return this.hasVelRange&&e.unshift(new Pe(c.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&e.unshift(new Pe(c.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),e}},Ya=48e3,FA=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(t,e,A,s,a,n,r){this.name=t,this.sampleRate=e,this.originalKey=A,this.pitchCorrection=s,this.loopStart=n,this.loopEnd=r,this.sampleType=a}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===Fe.rightSample||this.sampleType===Fe.leftSample||this.sampleType===Fe.linkedSample}get useCount(){return this.linkedTo.length}getRawData(t){return this.compressedData&&t&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(t){let e=this.getAudioData(),A=t/this.sampleRate,s=new Float32Array(Math.floor(e.length*A));for(let a=0;a<s.length;a++)s[a]=e[Math.floor(a*(1/A))];e=s,this.sampleRate=t,this.loopStart=Math.floor(this.loopStart*A),this.loopEnd=Math.floor(this.loopEnd*A),this.audioData=e}async compressSample(t){if(!this.isCompressed)try{let e=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(Ya),e=this.getAudioData());let A=await t(e,this.sampleRate);this.setCompressedData(A)}catch(e){h.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`,e),this.compressedData=void 0}}setSampleType(t){if(this.sampleType=t
Line truncated
|
||||
`:"")+n.subject:n?.comment);let r=A.software;if(a("ISFT",r),t.defaultModulators.some(u=>!En.some(M=>we.isIdentical(M,u,!0)))&&A?.writeDefaultModulators){let u=t.defaultModulators;h.info(`%cWriting %c${u.length}%c default modulators...`,d.info,d.recognized,d.info);let M=new ne(10+u.length*10);for(let w of u)w.write(M);hs(M,0,10),s.push(...U.getParts("DMOD",[M]))}h.groupEnd(),h.info("%cWriting SDTA...",d.info);let i=[],o=[],I=Ka(t,i,o);h.info("%cWriting PDTA...",d.info),h.info("%cWriting SHDR...",d.info);let l=Za(t,i,o);h.group("%cWriting instruments...",d.info);let B=Fs(t,!1);h.groupEnd(),h.group("%cWriting presets...",d.info);let C=Fs(t,!0);h.groupEnd();let g=[C.hdr,C.bag,C.mod,C.gen,B.hdr,B.bag,B.mod,B.gen,l],E=U.getParts("pdta",g.map(u=>u.pdta),!0);A.writeExtendedLimits&&(B.writeXdta||C.writeXdta||t.presets.some(u=>u.name.length>20)||t.instruments.some(u=>u.name.length>20)||t.samples.some(u=>u.name.length>20))&&(h.info("%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.",d.info,d.value),s.push(...U.getParts("xdta",g.map(u=>u.xdta),!0)));let S=U.getParts("INFO",s,!0);h.info("%cWriting the output file...",d.info);let k=U.writeParts("RIFF",[et("sfbk"),...S,...I,...E]);return h.info(`%cSaved successfully! Final file size: %c${k.length}`,d.info,d.recognized),h.groupEnd(),k.buffer}var Ot=class{static verifyHeader(t,...e){for(let A of e)if(t.header.toLowerCase()===A.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${e.join(", or ")}" got "${t.header.toLowerCase()}"`)}static verifyText(t,...e){for(let A of e)if(t.toLowerCase()===A.toLowerCase())return;this.parsingError(`FourCC error: Expected "${e.join(", or ")}" got "${t.toLowerCase()}"`)}static parsingError(t){throw h.groupEnd(),new Error(`DLS parse error: ${t} The file may be corrupted.`)}static verifyAndReadList(t,...e){this.verifyHeader(t,"LIST"),t.data.currentIndex=0,this.verifyText(de(t.data,4),...e);let A=[];for(;t.data.length>t.data.currentIndex;)A.push(U.read(t.data));return A}},Z={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},P={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,reservedEG1:520,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,reservedEG2:780,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281},Gs={forward:0,loopAndRelease:1},gA=20,IA=16,xt=class Xt extends Ot{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(e){let A=new Xt;return A.unityNote=e.unityNote,A.gain=e.gain,A.fineTune=e.fineTune,A.loops=e.loops.map(s=>({...s})),A.fulOptions=e.fulOptions,A}static read(e){this.verifyHeader(e,"wsmp");let A=new Xt,s=X(e.data,4);if(s!==gA&&h.warn(`Wsmp cbSize mismatch: got ${s}, expected ${gA}.`),A.unityNote=X(e.data,2),A.fineTune=ls(e.data[e.data.currentIndex++],e.data[e.data.currentIndex++]),A.gain=X(e.data,4)|0,A.fulOptions=X(e.data,4),X(e.data,4)!==0){let a=X(e.data,4);a!==IA&&h.warn(`CbSize for loop in wsmp mismatch. Expected ${IA}, got ${a}.`);let n=X(e.data,4),r=X(e.data,4),i=X(e.data,4);A.loops.push({loopStart:r,loopLength:i,loopType:n})}return A}static fromSFSample(e){let A=new Xt;return A.unityNote=e.originalKey,A.fineTune=e.pitchCorrection,(e.loopEnd!==0||e.loopStart!==0)&&A.loops.push({loopStart:e.loopStart,loopLength:e.loopEnd-e.loopStart,loopType:Gs.forward}),A}static fromSFZone(e){let A=new Xt;A.unityNote=e.getGenerator(c.overridingRootKey,e.sample.originalKey),e.getGenerator(c.scaleTuning,100)===0&&e.keyRange.max-e.keyRange.min===0&&(A.unityNote=e.keyRange.min),A.fineTune=e.fineTuning+e.sample.pitchCorrection,A.gain=-(e.getGenerator(c.initialAttenuation,0)*.4)<<16;let s=e.getGenerator(c.sampleModes,0);if(s!==0){let a=e.sample.loopStart+e.getGenerator(c.startloopAddrsOffset,0)+e.getGenerator(c.startloopAddrsCoarseOffset,0)*32768,n=e.sample.loopEnd+e.getGenerator(c.endloopAddrsOffset,0)+e.getGenerator(c.endloopAddrsCoarseOffset,0)*32768,r;switch(s){case 1:default:r=0;break;case 3:r=1}A.loops.push({loopType:r,loopStart:a,loopLength:n-a})}return A}toSFZone(e,A){let s=0,a=this.loops[0];a&&(s=a.loopType===Gs.loopAndRelease?3:1),s!==0&&e.setGenerator(c.sampleModes,s);let n=-(this.gain>>16)/.4;if(n!==0&&e.setGenerator(c.initialAttenuation,n),e.fineTuning=this.fineTune-A.pitchCorrection,this.unityNote!==A.originalKey&&e.setGenerator(c.overridingRootKey,this.unityNote),a){let r=a.loopStart-A.loopStart,i=a.loopStart+a.loopLength-A.loopEnd;if(r!==0){let o=r%32768;e.setGenerator(c.startloopAddrsOffset,o);let I=Math.trunc(r/32768);I!==0&&e.setGenerator(c.startloopAddrsCoarseOffset,I)}if(i!==0){let o=i%32768;e.setGenerator(c.endloopAddrsOffset,o)
Line truncated
|
||||
${e.toString()}
|
||||
(${l})`)};if(e.transformType!==0){s("Absolute transform type is not supported");return}if(we.isIdentical(e,mn,!0)||we.isIdentical(e,un,!0))return;let a=nt.fromSFSource(e.primarySource);if(!a){s("Invalid primary source");return}let n=nt.fromSFSource(e.secondarySource);if(!n){s("Invalid secondary source");return}let r=pt.fromSFDestination(e.destination,e.transformAmount);if(r===void 0){s("Invalid destination");return}let i=e.transformAmount,o;if(typeof r=="number")o=r;else if(o=r.destination,i=r.amount,r.source!==Z.none){if(n.source!==Z.none&&a.source!==Z.none){s("Articulation generators with secondary source are not supported");return}a.source!==Z.none&&(n=a),a=new nt(r.source,Ce.linear,r.isBipolar)}let I=new pt(a,n,o,0,i<<16);A.connectionBlocks.push(I)}static copyFrom(e){return new pt(nt.copyFrom(e.source),nt.copyFrom(e.control),e.destination,e.transform,e.scale)}static fromSFGenerator(e,A){if(ja.has(e.type))return;let s=o=>{h.warn(`Failed converting SF2 generator into DLS:
|
||||
${e.toString()}
|
||||
(${o})`)},a=pt.fromSFDestination(e.type,e.value);if(a===void 0){s("Invalid type");return}let n=new nt,r,i=e.value;typeof a=="number"?r=a:(r=a.destination,i=a.amount,n.source=a.source,n.bipolar=a.isBipolar),A.connectionBlocks.push(new pt(n,new nt,r,0,i<<16))}static fromSFDestination(e,A){switch(e){default:return;case c.initialAttenuation:return{destination:P.gain,amount:-A,isBipolar:!1,source:Z.none};case c.fineTune:return P.pitch;case c.pan:return P.pan;case c.keyNum:return P.keyNum;case c.reverbEffectsSend:return P.reverbSend;case c.chorusEffectsSend:return P.chorusSend;case c.freqModLFO:return P.modLfoFreq;case c.delayModLFO:return P.modLfoDelay;case c.delayVibLFO:return P.vibLfoDelay;case c.freqVibLFO:return P.vibLfoFreq;case c.delayVolEnv:return P.volEnvDelay;case c.attackVolEnv:return P.volEnvAttack;case c.holdVolEnv:return P.volEnvHold;case c.decayVolEnv:return P.volEnvDecay;case c.sustainVolEnv:return{destination:P.volEnvSustain,amount:1e3-A,isBipolar:!1,source:Z.none};case c.releaseVolEnv:return P.volEnvRelease;case c.delayModEnv:return P.modEnvDelay;case c.attackModEnv:return P.modEnvAttack;case c.holdModEnv:return P.modEnvHold;case c.decayModEnv:return P.modEnvDecay;case c.sustainModEnv:return{destination:P.modEnvSustain,amount:1e3-A,isBipolar:!1,source:Z.none};case c.releaseModEnv:return P.modEnvRelease;case c.initialFilterFc:return P.filterCutoff;case c.initialFilterQ:return P.filterQ;case c.modEnvToFilterFc:return{source:Z.modEnv,destination:P.filterCutoff,amount:A,isBipolar:!1};case c.modEnvToPitch:return{source:Z.modEnv,destination:P.pitch,amount:A,isBipolar:!1};case c.modLfoToFilterFc:return{source:Z.modLfo,destination:P.filterCutoff,amount:A,isBipolar:!0};case c.modLfoToVolume:return{source:Z.modLfo,destination:P.gain,amount:A,isBipolar:!0};case c.modLfoToPitch:return{source:Z.modLfo,destination:P.pitch,amount:A,isBipolar:!0};case c.vibLfoToPitch:return{source:Z.vibratoLfo,destination:P.pitch,amount:A,isBipolar:!0};case c.keyNumToVolEnvHold:return{source:Z.keyNum,destination:P.volEnvHold,amount:A,isBipolar:!0};case c.keyNumToVolEnvDecay:return{source:Z.keyNum,destination:P.volEnvDecay,amount:A,isBipolar:!0};case c.keyNumToModEnvHold:return{source:Z.keyNum,destination:P.modEnvHold,amount:A,isBipolar:!0};case c.keyNumToModEnvDecay:return{source:Z.keyNum,destination:P.modEnvDecay,amount:A,isBipolar:!0};case c.scaleTuning:return{source:Z.keyNum,destination:P.pitch,amount:A*128,isBipolar:!1}}}toString(){return`Source: ${this.source.toString()},
|
||||
Control: ${this.control.toString()},
|
||||
Scale: ${this.scale} >> 16 = ${this.shortScale},
|
||||
Output transform: ${this.transformName}
|
||||
Destination: ${this.destinationName}`}write(){let e=new ne(12);return se(e,this.source.source),se(e,this.control.source),se(e,this.destination),se(e,this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10),ge(e,this.scale),e}toSFGenerator(e){let A=this.destination,s=this.shortScale;switch(A){default:h.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c
|
||||
(invalid destination)`,d.warn,d.value,d.unrecognized);return;case P.pan:e.setGenerator(c.pan,s);break;case P.gain:e.addToGenerator(c.initialAttenuation,-s/.4);break;case P.filterCutoff:e.setGenerator(c.initialFilterFc,s);break;case P.filterQ:e.setGenerator(c.initialFilterQ,s);break;case P.modLfoFreq:e.setGenerator(c.freqModLFO,s);break;case P.modLfoDelay:e.setGenerator(c.delayModLFO,s);break;case P.vibLfoFreq:e.setGenerator(c.freqVibLFO,s);break;case P.vibLfoDelay:e.setGenerator(c.delayVibLFO,s);break;case P.volEnvDelay:e.setGenerator(c.delayVolEnv,s);break;case P.volEnvAttack:e.setGenerator(c.attackVolEnv,s);break;case P.volEnvHold:e.setGenerator(c.holdVolEnv,s);break;case P.volEnvDecay:e.setGenerator(c.decayVolEnv,s);break;case P.volEnvRelease:e.setGenerator(c.releaseVolEnv,s);break;case P.volEnvSustain:e.setGenerator(c.sustainVolEnv,1e3-s);break;case P.modEnvDelay:e.setGenerator(c.delayModEnv,s);break;case P.modEnvAttack:e.setGenerator(c.attackModEnv,s);break;case P.modEnvHold:e.setGenerator(c.holdModEnv,s);break;case P.modEnvDecay:e.setGenerator(c.decayModEnv,s);break;case P.modEnvRelease:e.setGenerator(c.releaseModEnv,s);break;case P.modEnvSustain:e.setGenerator(c.sustainModEnv,1e3-s);break;case P.reverbSend:e.setGenerator(c.reverbEffectsSend,s);break;case P.chorusSend:e.setGenerator(c.chorusEffectsSend,s);break;case P.pitch:e.fineTuning+=s;break}}toSFModulator(e){let A=this.shortScale,s,a,n=new at,r=this.toCombinedSFDestination();if(r){s=r;let o=this.control.toSFSource();if(!o){this.failedConversion("Invalid control");return}a=o}else{let o=this.toSFDestination();if(!o){this.failedConversion("Invalid destination");return}typeof o=="object"?(A=o.newAmount,s=o.gen):s=o;let I=this.source.toSFSource();if(!I){this.failedConversion("Invalid source");return}a=I;let l=this.control.toSFSource();if(!l){this.failedConversion("Invalid control");return}n=l}this.transform!==Ce.linear&&a.curveType===Ce.linear&&(a.curveType=this.transform),s===c.initialAttenuation&&((this.source.source===Z.velocity||this.source.source===Z.volume||this.source.source===Z.expression)&&(a.isNegative=!0),A=Math.min(960,Math.max(0,A)));let i=new we(a,n,s,A,0);e.addModulators(i)}toCombinedSFDestination(){let e=this.source.source,A=this.destination;return e===Z.vibratoLfo&&A===P.pitch?c.vibLfoToPitch:e===Z.modLfo&&A===P.pitch?c.modLfoToPitch:e===Z.modLfo&&A===P.filterCutoff?c.modLfoToFilterFc:e===Z.modLfo&&A===P.gain?c.modLfoToVolume:e===Z.modEnv&&A===P.filterCutoff?c.modEnvToFilterFc:e===Z.modEnv&&A===P.pitch?c.modEnvToPitch:void 0}failedConversion(e){h.info(`%cFailed converting DLS articulator into SF2:
|
||||
%c${this.toString()}%c
|
||||
(${e})`,d.warn,d.value,d.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case P.none:return;case P.pan:return c.pan;case P.gain:return{gen:c.initialAttenuation,newAmount:-e};case P.pitch:return c.fineTune;case P.keyNum:return c.overridingRootKey;case P.volEnvDelay:return c.delayVolEnv;case P.volEnvAttack:return c.attackVolEnv;case P.volEnvHold:return c.holdVolEnv;case P.volEnvDecay:return c.decayVolEnv;case P.volEnvSustain:return{gen:c.sustainVolEnv,newAmount:1e3-e};case P.volEnvRelease:return c.releaseVolEnv;case P.modEnvDelay:return c.delayModEnv;case P.modEnvAttack:return c.attackModEnv;case P.modEnvHold:return c.holdModEnv;case P.modEnvDecay:return c.decayModEnv;case P.modEnvSustain:return{gen:c.sustainModEnv,newAmount:1e3-e};case P.modEnvRelease:return c.releaseModEnv;case P.filterCutoff:return c.initialFilterFc;case P.filterQ:return c.initialFilterQ;case P.chorusSend:return c.chorusEffectsSend;case P.reverbSend:return c.reverbEffectsSend;case P.modLfoFreq:return c.freqModLFO;case P.modLfoDelay:return c.delayModLFO;case P.vibLfoFreq:return c.freqVibLFO;case P.vibLfoDelay:return c.delayVibLFO}}},pn=class extends Ot{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(t){this.mode=t.mode;for(let e of t.connectionBlocks)this.connectionBlocks.push(Jt.copyFrom(e))}fromSFZone(t){this.mode="dls2";let e=new $t;e.copyFrom(t);for(let A of e.generators){let s;switch(A.type){default:continue;case c.keyNumToVolEnvDecay:s=c.decayVolEnv;break;case c.keyNumToVolEnvHold:s=c.holdVolEnv;break;case c.keyNumToModEnvDecay:s=c.decayModEnv;break;case c.keyNumToModEnvHold:s=c.holdModEnv}let a=e.getGenerator(s,void 0),n=A.value*-128;if(a===void 0)continue;let r=a-60/128*n;e.setGenerator(A.type,n,!1),e.setGenerator(s,r,!1)}for(let A of e.generators)Jt.fromSFGenerator(A,this);for(let A of e.modulators)Jt.fromSFModulator(A,this)}read(t){let e=U.findListType(t,"lart"),A=U.findListType(t,"lar2");if(e)for(this.mode="dls1";e.data.currentIndex<e.data.length;){let s=U.read(e.data);if(s.header!=="art1"&&s.header!=="art2")continue;let a=s.data,n=X(a,4);n!==8&&h.warn(`CbSize in articulation mismatch. Expected 8, got ${n}`);let r=X(a,4);for(let i=0;i<r;i++)this.connectionBlocks.push(Jt.read(a))}else if(A)for(this.mode="dls2";A.data.currentIndex<A.data.length;){let s=U.read(A.data);if(s.header!=="art1"&&s.header!=="art2")continue;let a=s.data,n=X(a,4);n!==8&&h.warn(`CbSize in articulation mismatch. Expected 8, got ${n}`);let r=X(a,4);for(let i=0;i<r;i++)this.connectionBlocks.push(Jt.read(a))}}write(){let t=new ne(8);ge(t,8),ge(t,this.connectionBlocks.length);let e=this.connectionBlocks.map(s=>s.write()),A=U.getParts(this.mode==="dls2"?"art2":"art1",[t,...e]);return U.getParts(this.mode==="dls2"?"lar2":"lart",A,!0)}toSFZone(t){let e=(A,s,a,n)=>{let r=A/-128;if(t.setGenerator(s,r),r<=120){let i=Math.round(.46875*A),o=this.connectionBlocks.find(I=>I.isStaticParameter&&I.destination===n);o&&t.setGenerator(a,i+o.shortScale)}};for(let A of this.connectionBlocks){let s=A.shortScale,a=A.source.source,n=A.control.source,r=A.destination;if(A.isStaticParameter){A.toSFGenerator(t);continue}if(n===Z.none)if(a===Z.keyNum){if(r===P.pitch){t.setGenerator(c.scaleTuning,s/128);continue}if(r===P.modEnvHold||r===P.modEnvDecay||r===P.volEnvHold||r===P.volEnvDecay)continue}else{let i=A.toCombinedSFDestination();if(i){t.setGenerator(i,s);continue}}A.toSFModulator(t)}for(let A of this.connectionBlocks){if(A.source.source!==Z.keyNum)continue;let s=A.shortScale;switch(A.destination){default:case P.volEnvHold:e(s,c.keyNumToVolEnvHold,c.holdVolEnv,P.volEnvHold);break;case P.volEnvDecay:e(s,c.keyNumToVolEnvDecay,c.decayVolEnv,P.volEnvDecay);break;case P.modEnvHold:e(s,c.keyNumToModEnvHold,c.holdModEnv,P.modEnvHold);break;case P.modEnvDecay:e(s,c.keyNumToModEnvDecay,c.decayModEnv,P.modEnvDecay);break}}if(this.mode==="dls1"){t.setGenerator(c.delayVibLFO,t.getGenerator(c.delayModLFO,null)),t.setGenerator(c.freqVibLFO,t.getGenerator(c.freqModLFO,null)),t.setGenerator(c.vibLfoToPitch,t.getGenerator(c.modLfoToPitch,null)),t.setGenerator(c.modLfoToPitch,null);for(let A of t.modulators)A.destination===c.modLfoToPitch&&(A.destination=c.vibLfoToPitch)}}},KA=class CA{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let A=new CA(e.tableIndex);return A.channel=e.channel,A.phaseGroup=e.phaseGroup,A.fusOptions=e.fusOptions,A}static read(e){let A=X(e.data,2),s=X(e.data,2),a=X(e.data,4),n=new CA(X(e.data,4));return n.channel=a,n.fusOptions=A,n.phaseGroup=s,n}static fromSFZone(e,A){let s=e.indexOf(A.sample);if(s===-1)throw new Error(`Wave link error: Sample ${A.sample.name} does not exist in the sample list.`);let a=new CA(s);switch(A.sample.sampleType){default:case Fe.leftSample:case Fe.monoSample:a.channel=Math.trunc(1);break;case Fe.rightSample:a.channel=2}return a}write(){let e=new ne(12);return se(e,this.fusOptions),se(e,this.phaseGroup),ge(e,this.cha
Line truncated
|
||||
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized,d.info),h.groupEnd()}verifyHeader(t,e){t.header.toLowerCase()!==e.toLowerCase()&&(h.groupEnd(),this.parsingError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${t.header.toLowerCase()}"`))}verifyText(t,e){t.toLowerCase()!==e.toLowerCase()&&(h.groupEnd(),this.parsingError(`Invalid FourCC: Expected "${e.toLowerCase()}" got "${t.toLowerCase()}"\``))}},jt=class{static fromArrayBuffer(t){return de(new ne(t.slice(8,12)),4).toLowerCase()==="dls "?this.loadDLS(t):new ar(t,!1)}static loadDLS(t){return yn.read(t).toSF()}},DA=class kn extends we{isEffectModulator;isDefaultResonantModulator;isModWheelModulator;constructor(e,A,s,a,n,r,i,o){super(e,A,s,a,n),this.isEffectModulator=r,this.isDefaultResonantModulator=i,this.isModWheelModulator=o}static fromData(e,A,s,a,n){let r=e.toSourceEnum(),i=A.toSourceEnum();return new kn(e,A,s,a,n,(r===219||r===221)&&i===0&&(s===c.reverbEffectsSend||s===c.chorusEffectsSend),r===Bn&&i===0&&s===c.initialFilterQ,(e.isCC&&e.index===f.modulationWheel||A.isCC&&A.index===f.modulationWheel)&&(s===c.modLfoToPitch||s===c.vibLfoToPitch))}static fromModulator(e){return this.fromData(e.primarySource,e.secondarySource,e.destination,e.transformAmount,e.transformType)}},rr=class{sampleData;generators;modulators;exclusiveClass;targetKey;velocity;rootKey;loopStart;loopEnd;playbackStep;loopingMode;constructor(t,e,A,s){let a=t.sample,n=t.generators;this.modulators=t.modulators.map(DA.fromModulator.bind(DA)),this.generators=n,this.rootKey=a.originalKey,n[c.overridingRootKey]>-1&&(this.rootKey=n[c.overridingRootKey]),this.targetKey=e,n[c.keyNum]>-1&&(this.targetKey=n[c.keyNum]),this.velocity=A,n[c.velocity]>-1&&(this.velocity=n[c.velocity]),this.exclusiveClass=n[c.exclusiveClass],this.loopStart=a.loopStart,this.loopEnd=a.loopEnd,this.sampleData=a.getAudioData(),this.playbackStep=a.sampleRate/s*Math.pow(2,a.pitchCorrection/1200),this.loopingMode=n[c.sampleModes]}},Us=Math.PI/2,fA=-500,Dn=500,us=Dn-fA,wn=new Float32Array(us+1),Mn=new Float32Array(us+1);for(let t=fA;t<=Dn;t++){let e=(t-fA)/us,A=t-fA;wn[A]=Math.cos(Us*e),Mn[A]=Math.sin(Us*e)}function ir(t,e,A,s,a,n){if(!t.isInRelease&&e>=t.releaseStartTime&&(t.isInRelease=!0,t.volEnv.startRelease(t),t.modEnv.startRelease(t),t.loopingMode===3&&(t.wavetable.isLooping=!1)),t.hasRendered=!0,!t.isActive)return;let r=this.synthCore,i=r.sampleRate,o=t.modulatedGenerators,I=t.targetKey,l=t.pitchOffset+o[c.fineTune]+this.octaveTuning[I]+this.currentTuning,B=o[c.coarseTune],C=r.tunings[this.preset.program*128+t.midiNote];if(C!==-1&&(I=Math.trunc(C),B+=C-I),t.portamentoFromKey>-1){let Q=Math.min((e-t.startTime)/t.portamentoDuration,1),T=I-t.portamentoFromKey;B-=T*(1-Q)}l+=(I-t.rootKey)*o[c.scaleTuning];let g=0,E=0,S=t.gainModifier*(1+o[c.amplitude]/1e3);if(e>=t.vibLfoStartTime){let Q=o[c.vibLfoToPitch],T=o[c.vibLfoToFilterFc],H=o[c.vibLfoAmplitudeDepth];if(Q!==0||T!==0||H!==0){let z=Math.max(0,As(o[c.freqVibLFO])+o[c.vibLfoRate]/100)*n/i,j=1-4*Math.abs(t.vibLfoPhase-.5);(t.vibLfoPhase+=z)>=1&&(t.vibLfoPhase-=1),l+=j*Q,g+=j*T,S*=1-(j+1)/2*(H/1e3)}}if(e>=t.modLfoStartTime){let Q=o[c.modLfoToPitch],T=o[c.modLfoToVolume],H=o[c.modLfoToFilterFc],z=o[c.modLfoAmplitudeDepth];if(Q!==0||H!==0||T!==0||z!==0){let j=Math.max(0,As(o[c.freqModLFO])+o[c.modLfoRate]/100)*n/i,W=1-4*Math.abs(t.modLfoPhase-.5);(t.modLfoPhase+=j)>=1&&(t.modLfoPhase-=1),l+=W*Q,E+=-W*T,g+=W*H,S*=1-(W+1)/2*(z/1e3)}}let k=o[c.modEnvToPitch],u=o[c.modEnvToFilterFc];if(u!==0||k!==0){let Q=t.modEnv.process(t,e);g+=Q*u,l+=Q*k}E-=t.resonanceOffset;let M=l+B*100,w=M|0;w!==t.tuningCents&&(t.tuningCents=w,t.tuningRatio=Math.pow(2,M/1200));let R=SA(o[c.initialAttenuation])*SA(E);if(t.loopingMode===2&&!t.isInRelease){t.isActive=t.volEnv.process(n,R);return}let F=r.voiceBuffer;t.isActive=t.wavetable.process(n,t.tuningRatio,F);let N=t.volEnv.outputGain,m=t.volEnv.process(n,R),p=(t.volEnv.outputGain-N)/n;{let Q=t.filter,T=o[c.initialFilterFc];Q.initialized?Q.currentInitialFc+=(T-Q.currentInitialFc)*fs.smoothingConstant:(Q.initialized=!0,Q.currentInitialFc=T);let H=Q.currentInitialFc+g,z=o[c.initialFilterQ];if(Q.currentInitialFc>13499&&H>13499&&z===0){Q.currentInitialFc=13500;for(let j=0;j<n;j++)F[j]*=N,N+=p}else{(Math.abs(Q.lastTargetCutoff-H)>1||Q.resonanceCb!==z)&&(Q.lastTargetCutoff=H,Q.resonanceCb=z,Q.calculateCoefficients(H));let{a0:j,a1:W,a2:K,a3:ee,a4:Ae}=Q,{x1:O,x2:re,y1:ue,y2:Le}=Q;for(let Ee=0;Ee<n;Ee++){let Re=F[Ee],Oe=j*Re+W*O+K*re-ee*ue-Le*Ae;re=O,O=Re,Le=ue,ue=Oe,F[Ee]=Oe*N,N+=p}Q.x1=O,Q.x2=re,Q.y1=ue,Q.y2=Le}}t.isActive=t.isActive&&m;let y;t.overridePan?y=t.overridePan:(t.currentPan+=(o[c.pan]-t.currentPan)*r.panSmoothingFactor,y=t.currentPan);let{systemParameters:V}=r,Y=this.currentGain*S,q=Math.min(Math.max(-500,y+this.currentPan),500)+500|0,J=wn[q]*Y,te=Mn[q]*Y;if(this._midiParameters.efxAssign){let Q=r.insertionInputL,T=r.inLine truncated
|
||||
//# sourceMappingURL=spessasynth_processor.min.js.map
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
Reference in new issue
Block a user