Spaces:
Running
Running
Round 3: True-Peak, Stems-Jobs (Queue/ETA/Abbruch), Cloud-Autosave privat, Smart-Prompt mit Takes, Mixer + FX-Presets, Undo komplett
Browse files- requirements.txt +1 -0
- static/daw/daw.css +69 -0
- static/daw/daw.js +287 -57
- studio/daw/analyze.py +85 -0
- studio/daw/api.py +109 -9
- studio/daw/engine.py +19 -1
- studio/daw/jobs.py +56 -10
- studio/daw/stems.py +22 -2
- tests/__init__.py +0 -0
- tests/test_daw_round2.py +14 -0
- tests/test_daw_round3.py +117 -0
requirements.txt
CHANGED
|
@@ -6,6 +6,7 @@ huggingface_hub>=0.24,<2.0
|
|
| 6 |
numpy>=1.26,<3.0
|
| 7 |
pedalboard>=0.9.16,<1.0
|
| 8 |
pyloudnorm>=0.1.1
|
|
|
|
| 9 |
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 10 |
torch>=2.4,<2.9
|
| 11 |
torchaudio>=2.4,<2.9
|
|
|
|
| 6 |
numpy>=1.26,<3.0
|
| 7 |
pedalboard>=0.9.16,<1.0
|
| 8 |
pyloudnorm>=0.1.1
|
| 9 |
+
scipy>=1.10
|
| 10 |
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 11 |
torch>=2.4,<2.9
|
| 12 |
torchaudio>=2.4,<2.9
|
static/daw/daw.css
CHANGED
|
@@ -194,3 +194,72 @@
|
|
| 194 |
.daw-lufs span { display: inline-flex; gap: 4px; align-items: baseline; white-space: nowrap; }
|
| 195 |
@media (max-width: 1100px) { .daw-main { grid-template-columns: 200px minmax(0, 1fr); } }
|
| 196 |
@media (max-width: 640px) { .daw-main { grid-template-columns: 132px minmax(0, 1fr); } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
.daw-lufs span { display: inline-flex; gap: 4px; align-items: baseline; white-space: nowrap; }
|
| 195 |
@media (max-width: 1100px) { .daw-main { grid-template-columns: 200px minmax(0, 1fr); } }
|
| 196 |
@media (max-width: 640px) { .daw-main { grid-template-columns: 132px minmax(0, 1fr); } }
|
| 197 |
+
|
| 198 |
+
/* ---------- v3 · Mixer, Smart-Prompt, Cloud ---------- */
|
| 199 |
+
.daw-lufs small { font-size: 8.5px; color: var(--mut); margin-left: 1px; }
|
| 200 |
+
.daw-lufs .is-hot b { color: #ff6b8a; }
|
| 201 |
+
.daw-progress { display: flex; align-items: center; }
|
| 202 |
+
.daw-progress span { flex: 1; }
|
| 203 |
+
.daw-progress__x { position: relative; flex: 0 0 auto; width: 20px; height: 20px; border: 0; border-left: 1px solid rgba(57,255,136,.25); background: transparent; color: var(--txt); cursor: pointer; font-size: 14px; line-height: 1; }
|
| 204 |
+
.daw-progress__x:hover { color: #ff8fa5; }
|
| 205 |
+
.daw-cloud { font: 600 10.5px var(--tb-mono, monospace); color: var(--mut); white-space: nowrap; padding: 3px 7px; border-radius: 999px; border: 1px solid rgba(255,255,255,.08); }
|
| 206 |
+
.daw-cloud[data-state=ok] { color: var(--rad); border-color: rgba(57,255,136,.3); }
|
| 207 |
+
.daw-cloud[data-state=saving], .daw-cloud[data-state=pending] { color: var(--g2); border-color: rgba(212,175,55,.35); }
|
| 208 |
+
.daw-cloud[data-state=err] { color: #ff8fa5; border-color: rgba(255,107,138,.35); }
|
| 209 |
+
.daw-mixer { display: flex; gap: 8px; overflow-x: auto; padding: 12px; grid-column: 1 / 3; min-height: 420px; align-items: stretch;
|
| 210 |
+
background: radial-gradient(120% 80% at 50% 0%, rgba(212,175,55,.06), transparent 60%), rgba(6,5,4,.55); scrollbar-color: rgba(212,175,55,.35) transparent; }
|
| 211 |
+
.daw.is-mixer .daw-heads, .daw.is-mixer .daw-scroll { display: none; }
|
| 212 |
+
.daw-strip { flex: 0 0 104px; display: flex; flex-direction: column; align-items: stretch; gap: 6px; padding: 8px 7px 9px; border-radius: 10px; cursor: pointer;
|
| 213 |
+
background: linear-gradient(180deg, rgba(28,24,17,.95), rgba(12,11,8,.95)); border: 1px solid rgba(212,175,55,.16); border-top: 3px solid var(--c, var(--g)); box-shadow: inset 0 1px 0 rgba(240,214,138,.06); }
|
| 214 |
+
.daw-strip.is-sel { border-color: rgba(212,175,55,.55); box-shadow: 0 0 0 1px rgba(212,175,55,.25), 0 10px 30px -18px rgba(212,175,55,.6); }
|
| 215 |
+
.daw-strip--master { flex-basis: 120px; border-top-color: var(--rad); background: linear-gradient(180deg, rgba(20,28,20,.95), rgba(10,12,9,.95)); margin-left: auto; position: sticky; right: 0; }
|
| 216 |
+
.daw-strip__name { font: 800 11px var(--tb-ui, sans-serif); letter-spacing: .06em; text-transform: uppercase; color: var(--txt); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: center; }
|
| 217 |
+
.daw-ins { display: grid; gap: 3px; }
|
| 218 |
+
.daw-in { height: 19px; border-radius: 4px; border: 1px solid rgba(255,255,255,.07); background: rgba(0,0,0,.4); color: var(--mut); font: 700 9.5px var(--tb-ui, sans-serif); letter-spacing: .08em; text-transform: uppercase; cursor: pointer; display: grid; place-items: center; }
|
| 219 |
+
.daw-in.is-on { color: #071a0e; background: linear-gradient(90deg, #39ff88, #8dffc0); border-color: transparent; }
|
| 220 |
+
.daw-in:hover { border-color: var(--g); }
|
| 221 |
+
.daw-preset { width: 100%; height: 24px; background: rgba(0,0,0,.5); border: 1px solid rgba(212,175,55,.22); border-radius: 5px; color: var(--txt); font: 600 10.5px var(--tb-font, sans-serif); }
|
| 222 |
+
.daw-knob { display: grid; gap: 1px; font: 700 9px var(--tb-ui, sans-serif); letter-spacing: .1em; text-transform: uppercase; color: var(--mut); }
|
| 223 |
+
.daw-knob input, .daw-strip input[type=range] { accent-color: var(--g); width: 100%; }
|
| 224 |
+
.daw-strip__ms { display: flex; justify-content: center; gap: 4px; }
|
| 225 |
+
.daw-fader { flex: 1; display: flex; justify-content: center; align-items: stretch; gap: 6px; min-height: 150px; }
|
| 226 |
+
.daw-fader input[type=range] { writing-mode: vertical-lr; direction: rtl; width: 22px; height: auto; min-height: 150px; margin: 0; }
|
| 227 |
+
.daw-smeter { display: inline-flex; gap: 2px; width: 7px; background: rgba(255,255,255,.04); border-radius: 3px; overflow: hidden; }
|
| 228 |
+
.daw-smeter--m { width: 14px; }
|
| 229 |
+
.daw-smeter i { flex: 1; display: block; height: 100%; background: linear-gradient(0deg, #1f9e57, var(--rad) 70%, #d4af37 90%, #ff6b8a); transform: scaleY(0); transform-origin: bottom; will-change: transform; }
|
| 230 |
+
.daw-db { text-align: center; font: 600 10.5px var(--tb-mono, monospace); color: var(--g2); font-variant-numeric: tabular-nums; }
|
| 231 |
+
.daw-mlufs { display: grid; gap: 1px; font: 600 10px var(--tb-mono, monospace); color: var(--mut); text-align: center; min-height: 42px; }
|
| 232 |
+
.daw-mlufs b { color: var(--rad); }
|
| 233 |
+
.daw-presetrow { display: flex; gap: 6px; margin-top: 10px; }
|
| 234 |
+
.daw-presetrow .daw-preset { flex: 1; height: 26px; }
|
| 235 |
+
.daw-ctx { margin: 8px 0 4px; padding: 7px 10px; border-radius: 8px; font-size: 12px; color: var(--txt); background: rgba(57,255,136,.06); border: 1px solid rgba(57,255,136,.18); display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
| 236 |
+
.daw-ctx:empty { display: none; }
|
| 237 |
+
.daw-ctx__l { font: 800 9.5px var(--tb-ui, sans-serif); letter-spacing: .14em; text-transform: uppercase; color: var(--rad); }
|
| 238 |
+
.daw-ctx b { color: var(--g2); }
|
| 239 |
+
.daw-ctx small { color: var(--mut); }
|
| 240 |
+
.daw-ctx .daw-b { margin-left: auto; }
|
| 241 |
+
.daw-sugg { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 8px; }
|
| 242 |
+
.daw-chip { max-width: 100%; padding: 5px 10px; border-radius: 999px; border: 1px solid rgba(212,175,55,.3); background: rgba(212,175,55,.06); color: var(--txt); font: 500 11.5px var(--tb-font, sans-serif); cursor: pointer; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: background-color .15s, border-color .15s; }
|
| 243 |
+
.daw-chip:hover { background: rgba(212,175,55,.16); border-color: var(--g); }
|
| 244 |
+
.daw-takes { margin-top: 8px; padding: 8px; border-radius: 10px; border: 1px solid rgba(212,175,55,.25); background: rgba(0,0,0,.35); display: grid; gap: 6px; }
|
| 245 |
+
.daw-takes__h { margin: 0 0 2px; font: 800 10px var(--tb-ui, sans-serif); letter-spacing: .14em; text-transform: uppercase; color: var(--g); }
|
| 246 |
+
.daw-take { display: flex; align-items: center; gap: 8px; font-size: 12px; }
|
| 247 |
+
.daw-take span { flex: 1; color: var(--mut); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
| 248 |
+
.daw-take.is-err span { color: #ff8fa5; }
|
| 249 |
+
.daw-take.is-wait span { color: var(--g2); animation: daw-pulse2 1.2s ease-in-out infinite; }
|
| 250 |
+
@keyframes daw-pulse2 { 50% { opacity: .45; } }
|
| 251 |
+
@media (max-width: 1100px) { .daw-mixer { grid-column: 1 / -1; } }
|
| 252 |
+
@media (max-width: 640px) { .daw-strip { flex-basis: 92px; } .daw-mixer { min-height: 360px; padding: 8px; } .daw-cloud { order: 5; } }
|
| 253 |
+
/* v3 · Spezifität gegen Gradio-Basisstile */
|
| 254 |
+
#daw-root .daw-strip--master { position: static; margin-left: 0; }
|
| 255 |
+
#daw-root .daw-in { height: 19px; padding: 0; border-radius: 4px; border: 1px solid rgba(255,255,255,.08); background: rgba(0,0,0,.45); color: var(--mut); font: 700 9.5px/1 var(--tb-ui, sans-serif); letter-spacing: .08em; text-transform: uppercase; box-shadow: none; min-width: 0; }
|
| 256 |
+
#daw-root .daw-in.is-on { color: #071a0e; background: linear-gradient(90deg, #39ff88, #8dffc0); border-color: transparent; }
|
| 257 |
+
#daw-root select, #daw-root .daw-preset { background: rgba(0,0,0,.5) !important; color: var(--txt) !important; border: 1px solid rgba(212,175,55,.25) !important; border-radius: 6px; color-scheme: dark; }
|
| 258 |
+
#daw-root .daw-preset { height: 24px; font: 600 10.5px var(--tb-font, sans-serif); padding: 0 4px; }
|
| 259 |
+
#daw-root .daw-chip { padding: 5px 11px; font: 500 11.5px/1.3 var(--tb-font, sans-serif); border-radius: 999px; border: 1px solid rgba(212,175,55,.3); background: rgba(212,175,55,.06); color: var(--txt); min-width: 0; height: auto; box-shadow: none; }
|
| 260 |
+
#daw-root .daw-chip:hover { background: rgba(212,175,55,.16); border-color: var(--g); }
|
| 261 |
+
#daw-root .daw-b--sm { height: 26px; min-width: 0; padding: 0 9px; font: 700 10px/1 var(--tb-ui, sans-serif); letter-spacing: .06em; }
|
| 262 |
+
#daw-root .daw-progress__x { width: 20px; height: 20px; padding: 0; min-width: 0; border-radius: 0; background: transparent; }
|
| 263 |
+
#daw-root .daw-take .daw-b--sm { flex: 0 0 auto; }
|
| 264 |
+
#daw-root .daw-strip--master { position: sticky; right: -12px; z-index: 2; margin-left: auto; background: linear-gradient(180deg, #142016, #0a0c09); box-shadow: -14px 0 22px -10px #000; }
|
| 265 |
+
#daw-root .daw-strip { flex-basis: 96px; }
|
static/daw/daw.js
CHANGED
|
@@ -64,9 +64,18 @@
|
|
| 64 |
S.tracks.push(t); return t;
|
| 65 |
}
|
| 66 |
function trackDefaults(t) { t.arm = !!t.arm; t.auto = { vol: [], pan: [], ...(t.auto || {}) }; t.autoView = t.autoView || null; t.live = { ...LIVE_DEFAULT, ...(t.live || {}) }; return t; }
|
| 67 |
-
const snapshot = () => JSON.stringify({ tracks: S.tracks, clips: S.clips, markers: S.markers, loopR: S.loopR });
|
| 68 |
-
|
| 69 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
function undo() { if (!S.undo.length) return note("Nichts rückgängig zu machen"); S.redo.push(snapshot()); restore(S.undo.pop()); note("Rückgängig"); }
|
| 71 |
function redoFn() { if (!S.redo.length) return note("Nichts wiederherzustellen"); S.undo.push(snapshot()); restore(S.redo.pop()); note("Wiederhergestellt"); }
|
| 72 |
const clipEnd = c => c.start + c.dur;
|
|
@@ -91,17 +100,22 @@
|
|
| 91 |
class L extends AudioWorkletProcessor{constructor(){super();const fs=sampleRate;let f0=1681.974450955533,Q=0.7071752369554196,K=Math.tan(Math.PI*f0/fs);const Vh=Math.pow(10,3.999843853973347/20),Vb=Math.pow(Vh,0.4996667741545416),a0=1+K/Q+K*K;
|
| 92 |
this.b1=[(Vh+Vb*K/Q+K*K)/a0,2*(K*K-Vh)/a0,(Vh-Vb*K/Q+K*K)/a0];this.a1=[2*(K*K-1)/a0,(1-K/Q+K*K)/a0];
|
| 93 |
f0=38.13547087602444;Q=0.5003270373238773;K=Math.tan(Math.PI*f0/fs);const d=1+K/Q+K*K;this.a2=[2*(K*K-1)/d,(1-K/Q+K*K)/d];
|
| 94 |
-
this.z=[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]];this.blk=Math.round(fs/10);this.n=0;this.acc=0;this.e=[];this.
|
| 95 |
-
this.
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
| 98 |
const y1=b1[0]*v+b1[1]*z[0]+b1[2]*z[1]-a1[0]*z[2]-a1[1]*z[3];z[1]=z[0];z[0]=v;z[3]=z[2];z[2]=y1;
|
| 99 |
-
const y2=y1-2*z[4]+z[5]-a2[0]*z[6]-a2[1]*z[7];z[5]=z[4];z[4]=y1;z[7]=z[6];z[6]=y2;s+=y2*y2}this.acc+=s;this.pk[c]=pk}
|
| 100 |
this.n+=N;if(this.n>=this.blk){this.e.push(this.acc/this.n);if(this.e.length>30)this.e.shift();this.acc=0;this.n=0;
|
| 101 |
-
const Lu=e=>-0.691+10*Math.log10(e+1e-12),m=a=>a.reduce((p,q)=>p+q,0)/a.length,M=m(this.e.slice(-4));
|
| 102 |
-
if(this.e.length>=4){
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
registerProcessor("daw-loud",L);
|
| 106 |
class R extends AudioWorkletProcessor{constructor(){super();this.on=false;this.at=0;this.buf=[];this.len=0;
|
| 107 |
this.port.onmessage=e=>{const d=e.data;if(d.cmd==="start"){this.on=true;this.at=d.at}else if(d.cmd==="stop"){this.on=false;this.flush();this.port.postMessage({done:true})}}}
|
|
@@ -198,8 +212,13 @@
|
|
| 198 |
for (let i = 0; i < n; i++) { let mn = 1, mx = -1; const s = i * per, e = Math.min(buffer.length, s + per);
|
| 199 |
for (const d of chs) for (let j = s; j < e; j += 4) { const v = d[j]; if (v < mn) mn = v; if (v > mx) mx = v; }
|
| 200 |
out[i * 2] = mn; out[i * 2 + 1] = mx; }
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
}
|
|
|
|
| 203 |
async function addAsset({ buffer, name, path = null, url: u = null, blob = null, meta = {} }) {
|
| 204 |
const id = uid();
|
| 205 |
S.assets[id] = { id, name, buffer, peaks: peaks(buffer), path, url: u, blob, meta };
|
|
@@ -281,7 +300,7 @@
|
|
| 281 |
cancelAnimationFrame(raf); tick();
|
| 282 |
}
|
| 283 |
function stopSources() { for (const s of sources) { try { s.stop(); } catch { } } sources = []; }
|
| 284 |
-
function pause() { if (S.rec) { stopRecord(); return; } if (!S.playing) return; S.cursor = playPos(); stopSources(); metroStop(); S.playing = false; rebuildGraphImmediate(); ui.play.classList.remove("is-on"); ui.play.textContent = "▶"; ui.play.setAttribute("aria-label", "Abspielen"); draw(); }
|
| 285 |
function stop() { const was = S.playing; pause(); if (!was) S.cursor = 0; else S.cursor = playStartPos; draw(); }
|
| 286 |
const playPos = () => playStartPos + Math.max(0, ctx.currentTime - playStartCtx);
|
| 287 |
function tick() {
|
|
@@ -293,24 +312,28 @@
|
|
| 293 |
S.cursor = pos;
|
| 294 |
const vw = ui.scroll.clientWidth; const x = pos * S.pps;
|
| 295 |
if (x > S.scroll + vw - 40) ui.scroll.scrollLeft = x - 80;
|
| 296 |
-
|
| 297 |
raf = requestAnimationFrame(tick);
|
| 298 |
}
|
| 299 |
function rebuildGraphImmediate() { if (!ctx) return; for (const t of S.tracks) if (nodes[t.id]) applyTrack(ctx, t, nodes[t.id], true); }
|
| 300 |
const mbuf = new Float32Array(1024), tbuf = new Float32Array(256);
|
| 301 |
const db = v => 20 * Math.log10(v + 1e-9), mScale = d => clamp((d + 60) / 60, 0, 1);
|
| 302 |
-
let lastLoud = 0;
|
| 303 |
function meter() {
|
| 304 |
if (!analyser) return; analyser.getFloatTimeDomainData(mbuf); let pk = 0; for (const v of mbuf) pk = Math.max(pk, Math.abs(v));
|
| 305 |
const dbv = db(pk); ui.meter.style.transform = `scaleX(${mScale(dbv)})`; ui.meter.classList.toggle("is-hot", dbv > -1.5);
|
| 306 |
ui.time.textContent = fmt(S.cursor); ui.bb.textContent = bbt(S.cursor);
|
| 307 |
-
|
|
|
|
|
|
|
| 308 |
const L = S.loudness; if (!L) return;
|
| 309 |
ui.mL.style.transform = `scaleY(${mScale(db(L.pl))})`; ui.mR.style.transform = `scaleY(${mScale(db(L.pr))})`;
|
|
|
|
| 310 |
ui.mL.classList.toggle("is-hot", L.pl > 0.89); ui.mR.classList.toggle("is-hot", L.pr > 0.89);
|
| 311 |
const now = performance.now(); if (now - lastLoud < 120) return; lastLoud = now;
|
| 312 |
const f = v => (v == null || !isFinite(v) || v < -69) ? "–∞" : v.toFixed(1);
|
| 313 |
-
|
|
|
|
| 314 |
}
|
| 315 |
|
| 316 |
/* ------------------------------------------------------------ UI */
|
|
@@ -351,7 +374,8 @@
|
|
| 351 |
</div>
|
| 352 |
<div class="daw-grp daw-grp--main">
|
| 353 |
<button class="daw-b daw-craft" data-a="craft" title="Smart-Prompt: Element in Spur/Bereich craften (Doppelklick)">✦ Craft</button>
|
| 354 |
-
<button class="daw-b" data-a="transition" title="Übergang zwischen zwei anliegenden Clips">⤳ Übergang</button>
|
|
|
|
| 355 |
</div>
|
| 356 |
<div class="daw-grp daw-grp--io">
|
| 357 |
<button class="daw-b" data-a="import" title="Audio importieren (WAV/MP3/FLAC/OGG)">⇪ Import</button>
|
|
@@ -370,6 +394,7 @@
|
|
| 370 |
<div class="daw-heads" role="list" aria-label="Spuren"></div>
|
| 371 |
<div class="daw-scroll" aria-label="Timeline"><div class="daw-spacer"><canvas class="daw-cv"></canvas></div>
|
| 372 |
<div class="daw-drop">Audio hier ablegen</div></div>
|
|
|
|
| 373 |
<aside class="daw-insp" aria-label="Inspector">
|
| 374 |
<div class="daw-tabs" role="tablist">
|
| 375 |
<button role="tab" class="is-on" data-tab="live" aria-selected="true">Live-FX</button>
|
|
@@ -383,12 +408,13 @@
|
|
| 383 |
</div>
|
| 384 |
<div class="daw-foot"><button class="daw-b daw-add" data-a="addtrack" title="Neue Spur">+ Spur</button>
|
| 385 |
<span class="daw-status" role="status" aria-live="polite">Bereit · Doppelklick in eine Spur öffnet Smart-Prompt · Rechtsklick für Kontextmenü</span>
|
| 386 |
-
<div class="daw-progress" hidden><i></i><span></span></div>
|
|
|
|
| 387 |
<span class="daw-save" title="Lokales Autosave (IndexedDB, nur in diesem Browser)">Autosave bereit</span>
|
| 388 |
<div class="daw-master" title="Master: Lautstärke, Pegel L/R, LUFS">
|
| 389 |
<span class="daw-master__l">Master</span><input type="range" min="0" max="1.5" step="0.01" value="1" data-k="mvol" aria-label="Master-Lautstärke">
|
| 390 |
<span class="daw-mmeter" aria-hidden="true"><i class="mL"></i><i class="mR"></i></span>
|
| 391 |
-
<output class="daw-lufs"><span>
|
| 392 |
</div></div>
|
| 393 |
<div class="daw-menu" hidden role="menu"></div>
|
| 394 |
<div class="daw-tip" hidden role="tooltip"></div>
|
|
@@ -397,24 +423,32 @@
|
|
| 397 |
<dt><kbd>R</kbd></dt><dd>Aufnahme starten / stoppen</dd><dt><kbd>L</kbd></dt><dd>Loop an/aus</dd><dt><kbd>C</kbd></dt><dd>Metronom</dd><dt><kbd>K</kbd></dt><dd>Marker setzen</dd>
|
| 398 |
<dt><kbd>Strg Z</kbd> / <kbd>Strg Y</kbd></dt><dd>Rückgängig / Wiederholen</dd><dt><kbd>Strg C</kbd> <kbd>Strg V</kbd> <kbd>Strg D</kbd></dt><dd>Kopieren · Einfügen · Duplizieren</dd>
|
| 399 |
<dt><kbd>Entf</kbd></dt><dd>Löschen (Clip oder Bereich)</dd><dt><kbd>+</kbd> <kbd>−</kbd> <kbd>F</kbd></dt><dd>Zoom · Alles zeigen</dd><dt><kbd>P</kbd> <kbd>T</kbd></dt><dd>Smart-Prompt · Übergang</dd>
|
| 400 |
-
<dt><kbd>Strg S</kbd></dt><dd>Projekt speichern</dd><dt><kbd>Home</kbd></dt><dd>Zum Anfang</dd><dt><kbd>?</kbd></dt><dd>Diese Übersicht</dd>
|
| 401 |
<dt>Maus</dt><dd>Lineal ziehen = Loop · Doppelklick Lineal = Marker · Shift+Ziehen = Bereich · Alt+Ziehen = Kopie · Clip-Ecken oben = Fades · Strg+Rad = Zoom</dd></dl></div></div>
|
| 402 |
<div class="daw-pop" hidden role="dialog" aria-modal="true" aria-labelledby="daw-pop-h">
|
| 403 |
<form class="daw-pop__card" novalidate>
|
| 404 |
<header><h3 id="daw-pop-h">✦ Smart-Prompt</h3><span class="daw-pop__where"></span><button type="button" class="daw-x" data-a="popclose" aria-label="Schließen">×</button></header>
|
| 405 |
<div class="daw-els" role="radiogroup" aria-label="Element"></div>
|
|
|
|
|
|
|
| 406 |
<label class="daw-l">Prompt<textarea name="prompt" rows="2" placeholder="z. B. dark trap, 808, rolling hi-hats"></textarea></label>
|
| 407 |
<div class="daw-row2">
|
| 408 |
<label class="daw-l">Negativ-Prompt<input name="negative" placeholder="was vermieden werden soll"></label>
|
| 409 |
<label class="daw-l">Modell<select name="model"></select></label>
|
| 410 |
</div>
|
| 411 |
<label class="daw-l daw-lyr">Lyrics<textarea name="lyrics" rows="3" placeholder="[Verse]\n…"></textarea></label>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
<div class="daw-row3">
|
| 413 |
<label class="daw-l">Länge s<input name="seconds" type="number" min="1" max="285" step="0.5"></label>
|
| 414 |
<label class="daw-l">BPM<input name="bpm" type="number" min="40" max="240"></label>
|
| 415 |
<label class="daw-l">Key<input name="key"></label>
|
| 416 |
</div>
|
| 417 |
<p class="daw-lic"></p>
|
|
|
|
| 418 |
<footer><span class="daw-pop__st" role="status"></span><button type="submit" class="daw-b daw-craft">✦ In Spur craften</button></footer>
|
| 419 |
</form>
|
| 420 |
</div>
|
|
@@ -427,12 +461,12 @@
|
|
| 427 |
Object.assign(ui, {
|
| 428 |
root: r, heads: $(".daw-heads", r), scroll: $(".daw-scroll", r), spacer: $(".daw-spacer", r), cv: $(".daw-cv", r),
|
| 429 |
time: $(".daw-time", r), bb: $(".daw-bb", r), meter: $(".daw-meter i", r), mL: $(".mL", r), mR: $(".mR", r), lufs: $(".daw-lufs", r),
|
| 430 |
-
banner: $(".daw-banner", r), prog: $(".daw-progress", r), save: $(".daw-save", r), menu: $(".daw-menu", r), tip: $(".daw-tip", r), help: $(".daw-help", r), play: $('[data-a="play"]', r), status: $(".daw-status", r),
|
| 431 |
file: $(".daw-file", r), proj: $(".daw-proj", r), pop: $(".daw-pop", r), form: $(".daw-pop form", r), live: $('[data-pane="live"]', r),
|
| 432 |
fx: $('[data-pane="fx"]', r), info: $('[data-pane="info"]', r),
|
| 433 |
});
|
| 434 |
if (!S.tracks.length) { for (const n of ["Beat", "Bass", "Melodie", "Vocals", "FX"]) newTrack(n); S.selTrack = S.tracks[0].id; }
|
| 435 |
-
bind(); renderAll(); loadCatalog(); checkRestore();
|
| 436 |
try { ensureCtx(false); } catch { }
|
| 437 |
}
|
| 438 |
function note(msg, kind = "") { if (!ui.status) return; ui.status.textContent = msg; ui.status.dataset.kind = kind; }
|
|
@@ -453,6 +487,7 @@
|
|
| 453 |
<label title="Panorama L–R">L·R<input type="range" min="-1" max="1" step="0.01" value="${t.pan}" data-p="pan"></label>
|
| 454 |
<label title="Stereo-Breite">Width<input type="range" min="0" max="2" step="0.01" value="${t.width}" data-p="width"></label>
|
| 455 |
</div></div>`).join("");
|
|
|
|
| 456 |
}
|
| 457 |
/* Inspector */
|
| 458 |
const LIVE_UI = [["denoise", "Rauschminderung", 0, 100, 1, "%"], ["low", "EQ Bass", -12, 12, 0.5, "dB"], ["mid", "EQ Mitten", -12, 12, 0.5, "dB"], ["high", "EQ Höhen", -12, 12, 0.5, "dB"],
|
|
@@ -462,6 +497,7 @@
|
|
| 462 |
if (!t) { ui.live.innerHTML = `<p class="daw-hint">Spur wählen.</p>`; return; }
|
| 463 |
ui.live.innerHTML = `<p class="daw-insp__t" style="--c:${t.color}">${esc(t.name)} · Echtzeit</p>` + LIVE_UI.map(([k, l, mn, mx, st, u]) =>
|
| 464 |
`<label class="daw-sl"><span>${l}</span><input type="range" min="${mn}" max="${mx}" step="${st}" value="${t.live[k]}" data-live="${k}"><output>${(+t.live[k]).toFixed(st < 1 ? 2 : 0)}${u}</output></label>`).join("")
|
|
|
|
| 465 |
+ `<button class="daw-b daw-b--ghost" data-a="livereset">Zurücksetzen</button>`;
|
| 466 |
}
|
| 467 |
const FX = [
|
|
@@ -516,7 +552,9 @@
|
|
| 516 |
ui.cv.getContext("2d").setTransform(dpr, 0, 0, dpr, 0, 0);
|
| 517 |
ui.heads.style.paddingTop = `${RULER}px`;
|
| 518 |
}
|
| 519 |
-
|
|
|
|
|
|
|
| 520 |
if (!ui.cv) return;
|
| 521 |
const g = ui.cv.getContext("2d"), sx = S.scroll, pps = S.pps;
|
| 522 |
g.clearRect(0, 0, cw, ch);
|
|
@@ -554,7 +592,7 @@
|
|
| 554 |
g.fillStyle = t.color + (sel ? "" : "cc"); g.fillRect(x, y, w, 15);
|
| 555 |
g.fillStyle = "#0b0a08"; g.font = "700 10px 'Chakra Petch', sans-serif"; g.fillText((a?.name || "Clip").slice(0, Math.max(3, Math.floor(w / 6))), x + 6, y + 8);
|
| 556 |
if (a) {
|
| 557 |
-
const p = a.peaks, mid = y + 15 + (h - 15) / 2, amp = (h - 19) / 2 * (c.gain ?? 1);
|
| 558 |
g.fillStyle = sel ? "#f0d68a" : t.color; const fx0 = Math.max(0, -x), fx1 = Math.min(w, cw - x);
|
| 559 |
for (let px = fx0; px < fx1; px += 1) {
|
| 560 |
const tt = (c.offset || 0) + px / pps, j = Math.floor(tt * p.rate) * 2; if (j >= p.data.length) break;
|
|
@@ -643,7 +681,7 @@
|
|
| 643 |
function onMove(ev) {
|
| 644 |
if (!drag) { const h = hit(ev); ui.cv.style.cursor = h.clip ? (h.edge ? "ew-resize" : "grab") : h.ruler ? "pointer" : "crosshair"; return; }
|
| 645 |
const h = hit(ev);
|
| 646 |
-
if (drag.mode === "seek") { if (Math.abs(h.x - drag.x0) > 4) { const a = drag.t0, b = Math.max(0, snapT(h.t)); S.loopR = { t0: Math.min(a, b), t1: Math.max(a, b) }; drag.loop = true; } else S.cursor = Math.max(0, snapT(h.t)); }
|
| 647 |
else if (drag.mode === "marker") { drag.m.t = Math.max(0, snapT(h.t)); drag.changed = true; }
|
| 648 |
else if (drag.mode === "auto") { const a = autoHit({ ...h, track: drag.track, ti: trackIdx(drag.track.id) }); drag.p.t = Math.max(0, snapT(h.t)); drag.p.v = a.v; drag.pts.sort((x, y) => x.t - y.t); }
|
| 649 |
else if (drag.mode === "auto-noop") { }
|
|
@@ -749,14 +787,15 @@
|
|
| 749 |
$("#daw-pop-h", ui.pop).textContent = mode === "transition" ? "⤳ Übergang craften" : "✦ Smart-Prompt";
|
| 750 |
$(".daw-pop__where", ui.pop).textContent = mode === "transition" ? `an ${fmt(popCtx.at)}` : `${S.tracks[trackIdx(popCtx.track)]?.name} · ab ${fmt(popCtx.start)}${popCtx.len ? ` · ${popCtx.len.toFixed(1)} s` : ""}`;
|
| 751 |
f.bpm.value = S.bpm; f.key.value = S.key; f.prompt.value = mode === "transition" ? "rising riser into drop, whoosh" : f.prompt.value;
|
| 752 |
-
|
|
|
|
| 753 |
}
|
| 754 |
function syncElement() {
|
| 755 |
const f = ui.form, id = (f.querySelector('input[name="element"]:checked') || {}).value, el = S.catalog.elements.find(e => e.id === id); if (!el) return;
|
| 756 |
f.model.innerHTML = `<option value="auto">Auto (bestes verfügbares)</option>` + el.models.map(m => `<option value="${m.id}" ${/paused|broken|unauth|unreach/.test(m.state) ? "disabled" : ""}>${esc(m.label)} · ${esc(m.badge_label)}${/paused/.test(m.state) ? " · pausiert" : ""}</option>`).join("");
|
| 757 |
$(".daw-lyr", ui.pop).hidden = !el.lyrics;
|
| 758 |
f.seconds.value = popCtx.mode === "transition" ? 4 : (popCtx.len ? popCtx.len.toFixed(1) : el.dur);
|
| 759 |
-
renderLic(el);
|
| 760 |
}
|
| 761 |
function renderLic(el) {
|
| 762 |
const f = ui.form, m = el.models.find(x => x.id === f.model.value);
|
|
@@ -766,7 +805,7 @@
|
|
| 766 |
async function submitCraft(ev) {
|
| 767 |
ev.preventDefault();
|
| 768 |
const f = ui.form, el = (f.querySelector('input[name="element"]:checked') || {}).value, ctxp = popCtx, btn = f.querySelector('button[type="submit"]');
|
| 769 |
-
const st = $(".daw-pop__st", ui.pop); btn.disabled = true; let secs = 0; const timer = setInterval(() => { secs++; st.textContent = `Crafting … ${secs}s · GPU-Warteschlange kann 30–120 s dauern`; }, 1000);
|
| 770 |
S.bpm = +f.bpm.value || S.bpm; S.key = f.key.value || S.key;
|
| 771 |
try {
|
| 772 |
let res, a;
|
|
@@ -781,17 +820,139 @@
|
|
| 781 |
ctxp.a.fadeOut = xf; ctxp.b.fadeIn = xf;
|
| 782 |
note(`Übergang gesetzt · ${res.model_label} · Crossfade ${xf.toFixed(1)} s`);
|
| 783 |
} else {
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 789 |
}
|
| 790 |
ui.pop.hidden = true; renderAll();
|
| 791 |
} catch (e) { st.textContent = "Fehler: " + e.message; note("Craft fehlgeschlagen: " + e.message, "err"); }
|
| 792 |
finally { clearInterval(timer); btn.disabled = false; if (ui.pop.hidden) st.textContent = ""; }
|
| 793 |
}
|
| 794 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 795 |
/* Destruktive FX */
|
| 796 |
async function applyFx() {
|
| 797 |
const c = selectedClips()[0]; if (!c) return;
|
|
@@ -820,12 +981,27 @@
|
|
| 820 |
return await oc.startRendering();
|
| 821 |
}
|
| 822 |
function download(href, name) { const a = document.createElement("a"); a.href = href; a.download = name; document.body.appendChild(a); a.click(); a.remove(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
async function exportMix(kind) {
|
| 824 |
try {
|
| 825 |
-
note(`Rendere Mixdown (${kind.toUpperCase()}) …`); const buf = await renderMix();
|
| 826 |
-
if (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
const p = await upload(wav, "mix.wav"); const r = await api("daw_encode", [p, "mp3"]);
|
| 828 |
-
|
|
|
|
| 829 |
} catch (e) { note("Export fehlgeschlagen: " + e.message, "err"); }
|
| 830 |
}
|
| 831 |
async function saveProject() {
|
|
@@ -858,27 +1034,69 @@
|
|
| 858 |
function syncLoopBtn() { const b = $('[data-a="loop"]', ui.root); if (b) { b.classList.toggle("is-on", S.loop); b.setAttribute("aria-pressed", S.loop); } draw(); }
|
| 859 |
function addMarker(t = S.cursor) { commit(); const m = { id: uid(), t: Math.max(0, snapT(t)), name: `M${S.markers.length + 1}` }; S.markers.push(m); S.markers.sort((a, b) => a.t - b.t); note(`Marker ${m.name} bei ${bbt(m.t)}`); draw(); return m; }
|
| 860 |
function fit() { const len = Math.max(8, ...S.clips.map(clipEnd)); S.pps = clamp((ui.scroll.clientWidth - 30) / len, 4, 600); layout(); ui.scroll.scrollLeft = 0; S.scroll = 0; draw(); }
|
| 861 |
-
function progress(p, msg) { if (p == null) { ui.prog.hidden = true; return; } ui.prog.hidden = false; ui.prog.
|
| 862 |
-
function toggleTrack(t, k) { if (!t) return; t[k] = !t[k]; ensureCtx(); rebuildGraph(); renderHeads(); scheduleAutosave(); note(`${t.name}: ${{ mute: "Stumm", solo: "Solo", arm: "Aufnahme scharf" }[k]} ${t[k] ? "an" : "aus"}`); }
|
| 863 |
function cycleAuto(t, v) { t.autoView = v !== undefined ? v : ({ null: "vol", vol: "pan", pan: null })[t.autoView]; renderHeads(); draw(); note(t.autoView ? `${t.name}: Automation ${AUTO[t.autoView].label} – Klick in die Spur setzt Punkte` : `${t.name}: Automation ausgeblendet`); }
|
| 864 |
|
| 865 |
-
/* Stems (Demucs) */
|
|
|
|
|
|
|
|
|
|
| 866 |
async function stemsFor(c) {
|
|
|
|
| 867 |
c = c || selectedClips()[0]; if (!c) return note("Für Stems zuerst einen Clip wählen", "err");
|
| 868 |
const st = S.catalog?.stems; if (st && !st.available) return note("Stem-Trennung ist auf diesem Server nicht verfügbar", "err");
|
| 869 |
if (st && c.dur > st.max_s + 0.5) return note(`Clip ist ${c.dur.toFixed(0)} s – auf CPU max. ${st.max_s} s. Bitte vorher schneiden (S).`, "err");
|
| 870 |
-
const a = S.assets[c.asset]; progress(0.02, "Stems: lade Audio hoch …");
|
| 871 |
try {
|
| 872 |
-
const p = await ensureServer(a); const j = await api("daw_stems", [p, c.offset || 0, (c.offset || 0) + c.dur]);
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
if (r.state === "error") throw new Error(r.error || "Job fehlgeschlagen");
|
|
|
|
| 877 |
const loaded = []; for (const s of r.result) loaded.push([s, await assetFromUrl(s.url, `${s.label} · ${a.name}`.slice(0, 48), s.path, s)]);
|
| 878 |
commit(); let at = trackIdx(c.track) + 1;
|
| 879 |
for (const [s, na] of loaded) { const t = newTrack(s.label); S.tracks.pop(); S.tracks.splice(at++, 0, t); addClip(na, t.id, c.start, Math.min(c.dur, na.buffer.duration)); }
|
| 880 |
c.muted = true; progress(null); rebuildGraph(); renderAll(); note(`${loaded.length} Stems erzeugt · Original-Clip stumm (Rechtsklick → aktivieren)`);
|
| 881 |
-
} catch (e) { progress(null); note("Stems fehlgeschlagen: " + e.message, "err"); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 882 |
}
|
| 883 |
|
| 884 |
/* Aufnahme */
|
|
@@ -918,7 +1136,7 @@
|
|
| 918 |
let idbP = null, asTimer = 0; const asSaved = new Set();
|
| 919 |
function idb() { return idbP || (idbP = new Promise((res, rej) => { const r = indexedDB.open("2b-studio-daw", 1); r.onupgradeneeded = () => { r.result.createObjectStore("kv"); r.result.createObjectStore("audio"); }; r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); })); }
|
| 920 |
async function idbOp(store, mode, fn) { const d = await idb(); return new Promise((res, rej) => { const tx = d.transaction(store, mode), rq = fn(tx.objectStore(store)); tx.oncomplete = () => res(rq?.result); tx.onerror = () => rej(tx.error); }); }
|
| 921 |
-
function scheduleAutosave() { clearTimeout(asTimer); asTimer = setTimeout(autosave, 1200); }
|
| 922 |
async function autosave() {
|
| 923 |
if (!window.indexedDB || !ui.save || (ui.banner && !ui.banner.hidden)) return;
|
| 924 |
try {
|
|
@@ -927,6 +1145,8 @@
|
|
| 927 |
await idbOp("audio", "readwrite", st => st.put({ sr: b.sampleRate, chs, name: a.name, meta: a.meta }, id)); asSaved.add(id); }
|
| 928 |
await idbOp("kv", "readwrite", st => st.put({ at: Date.now(), title: S.title, bpm: S.bpm, key: S.key, sig: S.sig, grid: S.grid, tracks: S.tracks, clips: S.clips, markers: S.markers, loopR: S.loopR, master: S.master, assets: used }, "auto"));
|
| 929 |
ui.save.textContent = "✓ gesichert " + new Date().toLocaleTimeString("de-DE").slice(0, 5); ui.save.dataset.state = "ok";
|
|
|
|
|
|
|
| 930 |
} catch { ui.save.textContent = "Autosave nicht möglich"; ui.save.dataset.state = "err"; }
|
| 931 |
}
|
| 932 |
async function checkRestore() {
|
|
@@ -960,7 +1180,7 @@
|
|
| 960 |
function canvasMenu(ev) {
|
| 961 |
const h = hit(ev); ensureCtx(false);
|
| 962 |
if (h.ruler) return menu(ev, [{ l: "Marker hier setzen", k: "K", f: () => addMarker(h.t) }, ...(h.marker ? [{ l: `Marker ${h.marker.name} löschen`, f: () => { commit(); S.markers = S.markers.filter(m => m !== h.marker); draw(); } }] : []),
|
| 963 |
-
{ l: "Loop-Bereich entfernen", dis: !S.loopR, f: () => { S.loopR = null; S.loop = false; syncLoopBtn(); } }, { l: "Loop an/aus", k: "L", f: () => ACTIONS.loop() }]);
|
| 964 |
if (h.track) { S.selTrack = h.track.id; renderHeadsSel(); }
|
| 965 |
if (h.track?.autoView) { const a = autoHit(h); return menu(ev, [{ l: "Punkt löschen", dis: !a.p, f: () => { commit(); a.pts.splice(a.pts.indexOf(a.p), 1); rebuildGraph(); draw(); } },
|
| 966 |
{ l: "Automation leeren", f: () => { commit(); a.pts.length = 0; rebuildGraph(); draw(); } }, { l: "Automation ausblenden", f: () => cycleAuto(h.track, null) }]); }
|
|
@@ -998,17 +1218,21 @@
|
|
| 998 |
loop: () => { S.loop = !S.loop; syncLoopBtn(); note(S.loop ? (loopRegion() ? `Loop ${fmt(loopRegion().t0)} – ${fmt(loopRegion().t1)}` : "Loop an – Bereich im Lineal ziehen") : "Loop aus"); },
|
| 999 |
rec: toggleRecord, metro: b => { S.metro = !S.metro; b = b || $('[data-a="metro"]', ui.root); b.classList.toggle("is-on", S.metro); b.setAttribute("aria-pressed", S.metro); if (S.playing) S.metro ? metroStart() : metroStop(); note(`Metronom ${S.metro ? "an" : "aus"}`); },
|
| 1000 |
countin: b => { S.countIn = !S.countIn; b.classList.toggle("is-on", S.countIn); b.setAttribute("aria-pressed", S.countIn); note(`Einzähler ${S.countIn ? "an" : "aus"}`); },
|
| 1001 |
-
marker: () => addMarker(), stems: () => stemsFor(), fit, help: () => { ui.help.hidden = !ui.help.hidden; }, helpclose: () => { ui.help.hidden = true; },
|
| 1002 |
restore: restoreAuto, discard: () => { ui.banner.hidden = true; S.pending = null; idbOp("kv", "readwrite", st => st.delete("auto")).catch(() => { }); note("Alte Sitzung verworfen"); },
|
| 1003 |
snap: b => { S.snap = !S.snap; b.classList.toggle("is-on", S.snap); b.setAttribute("aria-pressed", S.snap); },
|
| 1004 |
zoomin: () => zoom(1.4), zoomout: () => zoom(1 / 1.4),
|
| 1005 |
split, copy, paste, dup: duplicate, del, undo, redo: redoFn,
|
| 1006 |
craft: () => openCraft("craft"), transition: () => openCraft("transition"),
|
| 1007 |
import: () => ui.file.click(), take: takeFromGenerate, wav: () => exportMix("wav"), mp3: () => exportMix("mp3"),
|
| 1008 |
-
save: saveProject, open: () => ui.proj.click(), popclose: () => (ui.pop.hidden = true
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1009 |
addtrack: () => { commit(); const t = newTrack(); S.selTrack = t.id; rebuildGraph(); renderAll(); },
|
| 1010 |
applyfx: applyFx,
|
| 1011 |
-
livereset: () => { const t = S.tracks.find(x => x.id === S.selTrack); if (t) { t.live = { ...LIVE_DEFAULT }; rebuildGraph(); renderLive(); } },
|
| 1012 |
};
|
| 1013 |
function bind() {
|
| 1014 |
const r = ui.root;
|
|
@@ -1024,20 +1248,26 @@
|
|
| 1024 |
else if (m.dataset.m === "craft") { S.selTrack = id; S.range = null; openCraft("craft"); }
|
| 1025 |
else if (m.dataset.m === "rm") { if (S.tracks.length < 2) return; commit(); S.clips = S.clips.filter(c => c.track !== id); S.tracks = S.tracks.filter(x => x.id !== id); S.selTrack = S.tracks[0].id; rebuildGraph(); renderAll(); }
|
| 1026 |
return; }
|
|
|
|
|
|
|
| 1027 |
const head = e.target.closest(".daw-head"); if (head) { S.selTrack = head.dataset.t; renderHeadsSel(); draw(); }
|
| 1028 |
});
|
| 1029 |
r.addEventListener("input", e => {
|
| 1030 |
const el = e.target;
|
| 1031 |
-
if (el.dataset.
|
|
|
|
| 1032 |
else if (el.dataset.live) { const t = S.tracks.find(x => x.id === S.selTrack); t.live[el.dataset.live] = +el.value; el.nextElementSibling.textContent = (+el.value).toFixed(+el.step < 1 ? 2 : 0) + (LIVE_UI.find(x => x[0] === el.dataset.live)[5]); ensureCtx(); rebuildGraph(); }
|
| 1033 |
else if (el.dataset.fxp) el.nextElementSibling.textContent = el.value;
|
| 1034 |
else if (el.dataset.clip) { const c = selectedClips()[0]; if (c) { c[el.dataset.clip] = +el.value; el.nextElementSibling.textContent = (+el.value).toFixed(2); draw(); } }
|
| 1035 |
else if (el.classList.contains("daw-name")) { const t = S.tracks.find(x => x.id === el.closest("[data-t]").dataset.t); t.name = el.value; }
|
| 1036 |
else if (el.dataset.k === "bpm") { S.bpm = clamp(+el.value || 120, 40, 240); draw(); scheduleAutosave(); }
|
| 1037 |
-
else if (el.dataset.k === "mvol") { S.master.vol = +el.value; if (master) master.vol.gain.setTargetAtTime(S.master.vol, ctx.currentTime, 0.02); }
|
| 1038 |
else if (el.dataset.k === "key") S.key = el.value;
|
| 1039 |
});
|
| 1040 |
-
r.addEventListener("change", e => {
|
|
|
|
|
|
|
|
|
|
| 1041 |
if (e.target.classList.contains("daw-fxsel")) renderFxParams(); if (e.target.name === "element") syncElement(); if (e.target.name === "model") renderLic(S.catalog.elements.find(x => x.id === ui.form.querySelector('input[name="element"]:checked').value)); });
|
| 1042 |
ui.form.addEventListener("submit", submitCraft);
|
| 1043 |
ui.pop.addEventListener("click", e => { if (e.target === ui.pop) ui.pop.hidden = true; });
|
|
@@ -1067,7 +1297,7 @@
|
|
| 1067 |
if (e.key === "?") { e.preventDefault(); ACTIONS.help(); return; }
|
| 1068 |
const map = { " ": () => (S.rec ? stopRecord() : S.playing ? pause() : play()), s: () => (e.shiftKey ? toggleTrack(selT, "solo") : split()), l: () => ACTIONS.loop(), delete: del, backspace: del,
|
| 1069 |
escape: () => { ui.pop.hidden = true; ui.help.hidden = true; closeMenu(); S.sel.clear(); S.range = null; draw(); }, home: ACTIONS.home, m: () => toggleTrack(selT, "mute"), r: toggleRecord, c: () => ACTIONS.metro(),
|
| 1070 |
-
k: () => addMarker(), "+": () => zoom(1.4), "=": () => zoom(1.4), "-": () => zoom(1 / 1.4), f: fit, p: () => openCraft("craft"), t: () => openCraft("transition") };
|
| 1071 |
if (mod && k === "z") { e.preventDefault(); e.shiftKey ? redoFn() : undo(); return; }
|
| 1072 |
if (mod && k === "y") { e.preventDefault(); redoFn(); return; }
|
| 1073 |
if (mod && k === "c") { e.preventDefault(); copy(); return; }
|
|
@@ -1085,5 +1315,5 @@
|
|
| 1085 |
const wake = () => { if (ctx && ctx.state === "suspended") ctx.resume().catch(() => { }); };
|
| 1086 |
document.addEventListener("pointerdown", wake, true); document.addEventListener("keydown", wake, true);
|
| 1087 |
window.__daw = { S, api, play, pause, stop, split, undo, redo: redoFn, copy, paste, renderMix, autosave, addMarker, toggleRecord, stopRecord, stemsFor, fit,
|
| 1088 |
-
get ctx() { return ctx; }, get loudness() { return S.loudness; } };
|
| 1089 |
})();
|
|
|
|
| 64 |
S.tracks.push(t); return t;
|
| 65 |
}
|
| 66 |
function trackDefaults(t) { t.arm = !!t.arm; t.auto = { vol: [], pan: [], ...(t.auto || {}) }; t.autoView = t.autoView || null; t.live = { ...LIVE_DEFAULT, ...(t.live || {}) }; return t; }
|
| 67 |
+
const snapshot = () => JSON.stringify({ tracks: S.tracks, clips: S.clips, markers: S.markers, loopR: S.loopR, master: S.master, bpm: S.bpm, key: S.key, sig: S.sig, grid: S.grid, title: S.title });
|
| 68 |
+
let gest = null, commits = 0;
|
| 69 |
+
function commit() { S.undo.push(snapshot()); if (S.undo.length > 120) S.undo.shift(); S.redo = []; scheduleAutosave(); if (++commits % 25 === 0) setTimeout(pruneAssets, 500); }
|
| 70 |
+
function commitOnce(tag) { if (gest !== tag) { commit(); gest = tag; } }
|
| 71 |
+
// Speicher: Audio-Assets freigeben, die weder in Clips noch in Undo/Redo vorkommen
|
| 72 |
+
function pruneAssets() {
|
| 73 |
+
const keep = new Set(S.clips.map(c => c.asset)); for (const js of [...S.undo, ...S.redo]) for (const m of js.matchAll(/"asset":"([a-z0-9]+)"/g)) keep.add(m[1]);
|
| 74 |
+
let n = 0; for (const id of Object.keys(S.assets)) if (!keep.has(id)) { delete S.assets[id]; asSaved.delete(id); n++; } return n;
|
| 75 |
+
}
|
| 76 |
+
function restore(js) { const o = JSON.parse(js); S.tracks = o.tracks.map(trackDefaults); S.clips = o.clips; S.markers = o.markers || []; S.loopR = o.loopR || null; gest = null;
|
| 77 |
+
for (const k of ["master", "bpm", "key", "sig", "grid", "title"]) if (o[k] !== undefined) S[k] = o[k];
|
| 78 |
+
if (ui.root) syncInputs(); if (master) master.vol.gain.value = S.master.vol; if (!S.tracks.some(t => t.id === S.selTrack)) S.selTrack = S.tracks[0]?.id; scheduleAutosave(); S.sel = new Set([...S.sel].filter(id => S.clips.some(c => c.id === id))); rebuildGraph(); renderAll(); }
|
| 79 |
function undo() { if (!S.undo.length) return note("Nichts rückgängig zu machen"); S.redo.push(snapshot()); restore(S.undo.pop()); note("Rückgängig"); }
|
| 80 |
function redoFn() { if (!S.redo.length) return note("Nichts wiederherzustellen"); S.undo.push(snapshot()); restore(S.redo.pop()); note("Wiederhergestellt"); }
|
| 81 |
const clipEnd = c => c.start + c.dur;
|
|
|
|
| 100 |
class L extends AudioWorkletProcessor{constructor(){super();const fs=sampleRate;let f0=1681.974450955533,Q=0.7071752369554196,K=Math.tan(Math.PI*f0/fs);const Vh=Math.pow(10,3.999843853973347/20),Vb=Math.pow(Vh,0.4996667741545416),a0=1+K/Q+K*K;
|
| 101 |
this.b1=[(Vh+Vb*K/Q+K*K)/a0,2*(K*K-Vh)/a0,(Vh-Vb*K/Q+K*K)/a0];this.a1=[2*(K*K-1)/a0,(1-K/Q+K*K)/a0];
|
| 102 |
f0=38.13547087602444;Q=0.5003270373238773;K=Math.tan(Math.PI*f0/fs);const d=1+K/Q+K*K;this.a2=[2*(K*K-1)/d,(1-K/Q+K*K)/d];
|
| 103 |
+
this.z=[[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]];this.blk=Math.round(fs/10);this.n=0;this.acc=0;this.e=[];this.pk=[0,0];this.tp=0;
|
| 104 |
+
this.hc=new Uint32Array(1001);this.hs=new Float64Array(1001);this.hb=[new Float32Array(24),new Float32Array(24)];this.hi=[0,0];
|
| 105 |
+
this.h=[1,2,3].map(p=>{const c=[];let sm=0;for(let j=0;j<12;j++){const x=6-j-p/4,s=Math.abs(x)<1e-9?1:Math.sin(Math.PI*x)/(Math.PI*x),w=Math.abs(x)<6.5?0.5+0.5*Math.cos(Math.PI*x/6.5):0;c.push(s*w);sm+=s*w}return c.map(v=>v/sm)});
|
| 106 |
+
this.port.onmessage=e=>{if(e.data==="reset"){this.e=[];this.hc.fill(0);this.hs.fill(0);this.tp=0}}}
|
| 107 |
+
process(i){const inp=i[0];if(!inp||!inp.length)return true;const N=inp[0].length,b1=this.b1,a1=this.a1,a2=this.a2,H=this.h;
|
| 108 |
+
for(let c=0;c<2;c++){const x=inp[c]||inp[0],z=this.z[c],hb=this.hb[c];let s=0,pk=this.pk[c],hi=this.hi[c];for(let k=0;k<N;k++){const v=x[k];let av=v<0?-v:v;
|
| 109 |
+
hi=hi===11?0:hi+1;hb[hi]=v;hb[hi+12]=v;for(let p=0;p<3;p++){const cp=H[p];let y=0;for(let j=0;j<12;j++)y+=cp[j]*hb[hi+12-j];if(y<0)y=-y;if(y>av)av=y}if(av>pk)pk=av;
|
| 110 |
const y1=b1[0]*v+b1[1]*z[0]+b1[2]*z[1]-a1[0]*z[2]-a1[1]*z[3];z[1]=z[0];z[0]=v;z[3]=z[2];z[2]=y1;
|
| 111 |
+
const y2=y1-2*z[4]+z[5]-a2[0]*z[6]-a2[1]*z[7];z[5]=z[4];z[4]=y1;z[7]=z[6];z[6]=y2;s+=y2*y2}this.acc+=s;this.pk[c]=pk;this.hi[c]=hi}
|
| 112 |
this.n+=N;if(this.n>=this.blk){this.e.push(this.acc/this.n);if(this.e.length>30)this.e.shift();this.acc=0;this.n=0;
|
| 113 |
+
const Lu=e=>-0.691+10*Math.log10(e+1e-12),m=a=>a.reduce((p,q)=>p+q,0)/a.length,M=m(this.e.slice(-4)),LM=Lu(M);
|
| 114 |
+
if(this.e.length>=4&&LM>-70){const ix=Math.min(1000,Math.floor((LM+70)*10));this.hc[ix]++;this.hs[ix]+=M}
|
| 115 |
+
let I=null,C=0,E=0;for(let b=0;b<1001;b++){C+=this.hc[b];E+=this.hs[b]}
|
| 116 |
+
if(C){const i0=Math.max(0,Math.ceil((Lu(E/C)-10+70)*10));let c2=0,e2=0;for(let b=i0;b<1001;b++){c2+=this.hc[b];e2+=this.hs[b]}if(c2)I=Lu(e2/c2)}
|
| 117 |
+
this.tp=Math.max(this.tp,this.pk[0],this.pk[1]);
|
| 118 |
+
this.port.postMessage({m:LM,s:Lu(m(this.e)),i:I,pl:this.pk[0],pr:this.pk[1],tp:this.tp});this.pk=[0,0]}return true}}
|
| 119 |
registerProcessor("daw-loud",L);
|
| 120 |
class R extends AudioWorkletProcessor{constructor(){super();this.on=false;this.at=0;this.buf=[];this.len=0;
|
| 121 |
this.port.onmessage=e=>{const d=e.data;if(d.cmd==="start"){this.on=true;this.at=d.at}else if(d.cmd==="stop"){this.on=false;this.flush();this.port.postMessage({done:true})}}}
|
|
|
|
| 212 |
for (let i = 0; i < n; i++) { let mn = 1, mx = -1; const s = i * per, e = Math.min(buffer.length, s + per);
|
| 213 |
for (const d of chs) for (let j = s; j < e; j += 4) { const v = d[j]; if (v < mn) mn = v; if (v > mx) mx = v; }
|
| 214 |
out[i * 2] = mn; out[i * 2 + 1] = mx; }
|
| 215 |
+
const levels = [{ data: out, rate: 200 }];
|
| 216 |
+
while (levels[levels.length - 1].data.length > 64) { const L = levels[levels.length - 1], m = L.data.length / 2, n2 = Math.ceil(m / 4), d = new Float32Array(n2 * 2);
|
| 217 |
+
for (let i = 0; i < n2; i++) { let mn = 1, mx = -1; for (let k = i * 4; k < Math.min(m, i * 4 + 4); k++) { if (L.data[k * 2] < mn) mn = L.data[k * 2]; if (L.data[k * 2 + 1] > mx) mx = L.data[k * 2 + 1]; } d[i * 2] = mn; d[i * 2 + 1] = mx; }
|
| 218 |
+
levels.push({ data: d, rate: L.rate / 4 }); }
|
| 219 |
+
return { data: out, rate: 200, levels };
|
| 220 |
}
|
| 221 |
+
function pickPeaks(p, pps) { if (!p.levels) return p; let best = p.levels[0]; for (const L of p.levels) if (L.rate >= pps) best = L; return best; }
|
| 222 |
async function addAsset({ buffer, name, path = null, url: u = null, blob = null, meta = {} }) {
|
| 223 |
const id = uid();
|
| 224 |
S.assets[id] = { id, name, buffer, peaks: peaks(buffer), path, url: u, blob, meta };
|
|
|
|
| 300 |
cancelAnimationFrame(raf); tick();
|
| 301 |
}
|
| 302 |
function stopSources() { for (const s of sources) { try { s.stop(); } catch { } } sources = []; }
|
| 303 |
+
function pause() { if (S.rec) { stopRecord(); return; } if (!S.playing) return; S.cursor = playPos(); stopSources(); metroStop(); S.playing = false; rebuildGraphImmediate(); $$(".daw-tmeter2 i, .daw-smeter i", ui.root).forEach(i => { i.style.transform = ""; i._v = undefined; }); ui.play.classList.remove("is-on"); ui.play.textContent = "▶"; ui.play.setAttribute("aria-label", "Abspielen"); draw(); }
|
| 304 |
function stop() { const was = S.playing; pause(); if (!was) S.cursor = 0; else S.cursor = playStartPos; draw(); }
|
| 305 |
const playPos = () => playStartPos + Math.max(0, ctx.currentTime - playStartCtx);
|
| 306 |
function tick() {
|
|
|
|
| 312 |
S.cursor = pos;
|
| 313 |
const vw = ui.scroll.clientWidth; const x = pos * S.pps;
|
| 314 |
if (x > S.scroll + vw - 40) ui.scroll.scrollLeft = x - 80;
|
| 315 |
+
drawNow(); meter();
|
| 316 |
raf = requestAnimationFrame(tick);
|
| 317 |
}
|
| 318 |
function rebuildGraphImmediate() { if (!ctx) return; for (const t of S.tracks) if (nodes[t.id]) applyTrack(ctx, t, nodes[t.id], true); }
|
| 319 |
const mbuf = new Float32Array(1024), tbuf = new Float32Array(256);
|
| 320 |
const db = v => 20 * Math.log10(v + 1e-9), mScale = d => clamp((d + 60) / 60, 0, 1);
|
| 321 |
+
let lastLoud = 0, frame = 0;
|
| 322 |
function meter() {
|
| 323 |
if (!analyser) return; analyser.getFloatTimeDomainData(mbuf); let pk = 0; for (const v of mbuf) pk = Math.max(pk, Math.abs(v));
|
| 324 |
const dbv = db(pk); ui.meter.style.transform = `scaleX(${mScale(dbv)})`; ui.meter.classList.toggle("is-hot", dbv > -1.5);
|
| 325 |
ui.time.textContent = fmt(S.cursor); ui.bb.textContent = bbt(S.cursor);
|
| 326 |
+
const mix = S.view === "mixer"; frame++;
|
| 327 |
+
if (frame % 2 === 0) for (const h of (mix ? ui.mixer : ui.heads).children) { const n = nodes[h.dataset.t], i = h.querySelector(mix ? ".daw-smeter i" : ".daw-tmeter2 i"); if (!n || !i) continue;
|
| 328 |
+
n.meter.getFloatTimeDomainData(tbuf); let p = 0; for (const v of tbuf) { const a = v < 0 ? -v : v; if (a > p) p = a; } const sc = mScale(db(p)); if (Math.abs((i._v ?? -1) - sc) < 0.01) continue; i._v = sc; i.style.transform = mix ? `scaleY(${sc})` : `scaleX(${sc})`; }
|
| 329 |
const L = S.loudness; if (!L) return;
|
| 330 |
ui.mL.style.transform = `scaleY(${mScale(db(L.pl))})`; ui.mR.style.transform = `scaleY(${mScale(db(L.pr))})`;
|
| 331 |
+
if (mix) { const a = ui.mixer.querySelector(".m2L"), b = ui.mixer.querySelector(".m2R"); if (a) { a.style.transform = `scaleY(${mScale(db(L.pl))})`; b.style.transform = `scaleY(${mScale(db(L.pr))})`; } }
|
| 332 |
ui.mL.classList.toggle("is-hot", L.pl > 0.89); ui.mR.classList.toggle("is-hot", L.pr > 0.89);
|
| 333 |
const now = performance.now(); if (now - lastLoud < 120) return; lastLoud = now;
|
| 334 |
const f = v => (v == null || !isFinite(v) || v < -69) ? "–∞" : v.toFixed(1);
|
| 335 |
+
if (mix) { const o = ui.mixer.querySelector(".daw-mlufs"); if (o) o.innerHTML = `<span>TP <b>${f(db(L.tp))}</b></span><span>S <b>${f(L.s)}</b></span><span>I <b>${f(L.i)}</b></span>`; }
|
| 336 |
+
ui.lufs.innerHTML = `<span title="True-Peak (4× Oversampling, BS.1770) seit Start" class="${L.tp > 0.891 ? "is-hot" : ""}">TP <b>${f(db(L.tp))}</b><small>dBTP</small></span><span title="Short-term LUFS (3 s)">S <b>${f(L.s)}</b></span><span title="Integrated LUFS (gated, BS.1770)">I <b>${f(L.i)}</b></span>`;
|
| 337 |
}
|
| 338 |
|
| 339 |
/* ------------------------------------------------------------ UI */
|
|
|
|
| 374 |
</div>
|
| 375 |
<div class="daw-grp daw-grp--main">
|
| 376 |
<button class="daw-b daw-craft" data-a="craft" title="Smart-Prompt: Element in Spur/Bereich craften (Doppelklick)">✦ Craft</button>
|
| 377 |
+
<button class="daw-b" data-a="transition" title="Übergang zwischen zwei anliegenden Clips (T)">⤳ Übergang</button>
|
| 378 |
+
<button class="daw-b" data-a="mixer" title="Mixer-Ansicht (X)" aria-pressed="false">Mixer</button>
|
| 379 |
</div>
|
| 380 |
<div class="daw-grp daw-grp--io">
|
| 381 |
<button class="daw-b" data-a="import" title="Audio importieren (WAV/MP3/FLAC/OGG)">⇪ Import</button>
|
|
|
|
| 394 |
<div class="daw-heads" role="list" aria-label="Spuren"></div>
|
| 395 |
<div class="daw-scroll" aria-label="Timeline"><div class="daw-spacer"><canvas class="daw-cv"></canvas></div>
|
| 396 |
<div class="daw-drop">Audio hier ablegen</div></div>
|
| 397 |
+
<div class="daw-mixer" hidden role="region" aria-label="Mixer"></div>
|
| 398 |
<aside class="daw-insp" aria-label="Inspector">
|
| 399 |
<div class="daw-tabs" role="tablist">
|
| 400 |
<button role="tab" class="is-on" data-tab="live" aria-selected="true">Live-FX</button>
|
|
|
|
| 408 |
</div>
|
| 409 |
<div class="daw-foot"><button class="daw-b daw-add" data-a="addtrack" title="Neue Spur">+ Spur</button>
|
| 410 |
<span class="daw-status" role="status" aria-live="polite">Bereit · Doppelklick in eine Spur öffnet Smart-Prompt · Rechtsklick für Kontextmenü</span>
|
| 411 |
+
<div class="daw-progress" hidden><i></i><span></span><button class="daw-progress__x" data-a="stemcancel" title="Stem-Trennung abbrechen" aria-label="Abbrechen">×</button></div>
|
| 412 |
+
<span class="daw-cloud" data-state="off" role="status">☁ Cloud: mit HF-Login</span>
|
| 413 |
<span class="daw-save" title="Lokales Autosave (IndexedDB, nur in diesem Browser)">Autosave bereit</span>
|
| 414 |
<div class="daw-master" title="Master: Lautstärke, Pegel L/R, LUFS">
|
| 415 |
<span class="daw-master__l">Master</span><input type="range" min="0" max="1.5" step="0.01" value="1" data-k="mvol" aria-label="Master-Lautstärke">
|
| 416 |
<span class="daw-mmeter" aria-hidden="true"><i class="mL"></i><i class="mR"></i></span>
|
| 417 |
+
<output class="daw-lufs"><span>TP <b>–∞</b><small>dBTP</small></span><span>S <b>–∞</b></span><span>I <b>–∞</b></span></output>
|
| 418 |
</div></div>
|
| 419 |
<div class="daw-menu" hidden role="menu"></div>
|
| 420 |
<div class="daw-tip" hidden role="tooltip"></div>
|
|
|
|
| 423 |
<dt><kbd>R</kbd></dt><dd>Aufnahme starten / stoppen</dd><dt><kbd>L</kbd></dt><dd>Loop an/aus</dd><dt><kbd>C</kbd></dt><dd>Metronom</dd><dt><kbd>K</kbd></dt><dd>Marker setzen</dd>
|
| 424 |
<dt><kbd>Strg Z</kbd> / <kbd>Strg Y</kbd></dt><dd>Rückgängig / Wiederholen</dd><dt><kbd>Strg C</kbd> <kbd>Strg V</kbd> <kbd>Strg D</kbd></dt><dd>Kopieren · Einfügen · Duplizieren</dd>
|
| 425 |
<dt><kbd>Entf</kbd></dt><dd>Löschen (Clip oder Bereich)</dd><dt><kbd>+</kbd> <kbd>−</kbd> <kbd>F</kbd></dt><dd>Zoom · Alles zeigen</dd><dt><kbd>P</kbd> <kbd>T</kbd></dt><dd>Smart-Prompt · Übergang</dd>
|
| 426 |
+
<dt><kbd>Strg S</kbd></dt><dd>Projekt speichern</dd><dt><kbd>Home</kbd></dt><dd>Zum Anfang</dd><dt><kbd>X</kbd></dt><dd>Mixer / Timeline</dd><dt><kbd>?</kbd></dt><dd>Diese Übersicht</dd>
|
| 427 |
<dt>Maus</dt><dd>Lineal ziehen = Loop · Doppelklick Lineal = Marker · Shift+Ziehen = Bereich · Alt+Ziehen = Kopie · Clip-Ecken oben = Fades · Strg+Rad = Zoom</dd></dl></div></div>
|
| 428 |
<div class="daw-pop" hidden role="dialog" aria-modal="true" aria-labelledby="daw-pop-h">
|
| 429 |
<form class="daw-pop__card" novalidate>
|
| 430 |
<header><h3 id="daw-pop-h">✦ Smart-Prompt</h3><span class="daw-pop__where"></span><button type="button" class="daw-x" data-a="popclose" aria-label="Schließen">×</button></header>
|
| 431 |
<div class="daw-els" role="radiogroup" aria-label="Element"></div>
|
| 432 |
+
<div class="daw-ctx" aria-live="polite"></div>
|
| 433 |
+
<div class="daw-sugg" aria-label="Vorschläge"></div>
|
| 434 |
<label class="daw-l">Prompt<textarea name="prompt" rows="2" placeholder="z. B. dark trap, 808, rolling hi-hats"></textarea></label>
|
| 435 |
<div class="daw-row2">
|
| 436 |
<label class="daw-l">Negativ-Prompt<input name="negative" placeholder="was vermieden werden soll"></label>
|
| 437 |
<label class="daw-l">Modell<select name="model"></select></label>
|
| 438 |
</div>
|
| 439 |
<label class="daw-l daw-lyr">Lyrics<textarea name="lyrics" rows="3" placeholder="[Verse]\n…"></textarea></label>
|
| 440 |
+
<div class="daw-row3">
|
| 441 |
+
<label class="daw-l">Preset<select name="preset"><option value="">– passend zum Projekt –</option>${Object.entries(GENRE_PRESETS).map(([k, p]) => `<option value="${k}">${p.label} · ${p.bpm}</option>`).join("")}</select></label>
|
| 442 |
+
<label class="daw-l">Varianten<select name="variants"><option value="1">1 Take</option><option value="2">2 Takes</option><option value="3">3 Takes</option></select></label>
|
| 443 |
+
<span></span>
|
| 444 |
+
</div>
|
| 445 |
<div class="daw-row3">
|
| 446 |
<label class="daw-l">Länge s<input name="seconds" type="number" min="1" max="285" step="0.5"></label>
|
| 447 |
<label class="daw-l">BPM<input name="bpm" type="number" min="40" max="240"></label>
|
| 448 |
<label class="daw-l">Key<input name="key"></label>
|
| 449 |
</div>
|
| 450 |
<p class="daw-lic"></p>
|
| 451 |
+
<div class="daw-takes" hidden></div>
|
| 452 |
<footer><span class="daw-pop__st" role="status"></span><button type="submit" class="daw-b daw-craft">✦ In Spur craften</button></footer>
|
| 453 |
</form>
|
| 454 |
</div>
|
|
|
|
| 461 |
Object.assign(ui, {
|
| 462 |
root: r, heads: $(".daw-heads", r), scroll: $(".daw-scroll", r), spacer: $(".daw-spacer", r), cv: $(".daw-cv", r),
|
| 463 |
time: $(".daw-time", r), bb: $(".daw-bb", r), meter: $(".daw-meter i", r), mL: $(".mL", r), mR: $(".mR", r), lufs: $(".daw-lufs", r),
|
| 464 |
+
banner: $(".daw-banner", r), cloud: $(".daw-cloud", r), mixer: $(".daw-mixer", r), prog: $(".daw-progress", r), save: $(".daw-save", r), menu: $(".daw-menu", r), tip: $(".daw-tip", r), help: $(".daw-help", r), play: $('[data-a="play"]', r), status: $(".daw-status", r),
|
| 465 |
file: $(".daw-file", r), proj: $(".daw-proj", r), pop: $(".daw-pop", r), form: $(".daw-pop form", r), live: $('[data-pane="live"]', r),
|
| 466 |
fx: $('[data-pane="fx"]', r), info: $('[data-pane="info"]', r),
|
| 467 |
});
|
| 468 |
if (!S.tracks.length) { for (const n of ["Beat", "Bass", "Melodie", "Vocals", "FX"]) newTrack(n); S.selTrack = S.tracks[0].id; }
|
| 469 |
+
bind(); renderAll(); loadCatalog(); checkRestore(); cloudInit();
|
| 470 |
try { ensureCtx(false); } catch { }
|
| 471 |
}
|
| 472 |
function note(msg, kind = "") { if (!ui.status) return; ui.status.textContent = msg; ui.status.dataset.kind = kind; }
|
|
|
|
| 487 |
<label title="Panorama L–R">L·R<input type="range" min="-1" max="1" step="0.01" value="${t.pan}" data-p="pan"></label>
|
| 488 |
<label title="Stereo-Breite">Width<input type="range" min="0" max="2" step="0.01" value="${t.width}" data-p="width"></label>
|
| 489 |
</div></div>`).join("");
|
| 490 |
+
renderMixer();
|
| 491 |
}
|
| 492 |
/* Inspector */
|
| 493 |
const LIVE_UI = [["denoise", "Rauschminderung", 0, 100, 1, "%"], ["low", "EQ Bass", -12, 12, 0.5, "dB"], ["mid", "EQ Mitten", -12, 12, 0.5, "dB"], ["high", "EQ Höhen", -12, 12, 0.5, "dB"],
|
|
|
|
| 497 |
if (!t) { ui.live.innerHTML = `<p class="daw-hint">Spur wählen.</p>`; return; }
|
| 498 |
ui.live.innerHTML = `<p class="daw-insp__t" style="--c:${t.color}">${esc(t.name)} · Echtzeit</p>` + LIVE_UI.map(([k, l, mn, mx, st, u]) =>
|
| 499 |
`<label class="daw-sl"><span>${l}</span><input type="range" min="${mn}" max="${mx}" step="${st}" value="${t.live[k]}" data-live="${k}"><output>${(+t.live[k]).toFixed(st < 1 ? 2 : 0)}${u}</output></label>`).join("")
|
| 500 |
+
+ `<div class="daw-presetrow"><select class="daw-preset" data-preset aria-label="Effekt-Preset">${presetOptions().replace(`value="${esc(t.preset || "")}"`, `value="${esc(t.preset || "")}" selected`)}</select><button class="daw-b daw-b--sm" data-a="presetsave" title="Aktuelle Live-FX als eigenes Preset speichern">Speichern</button></div>`
|
| 501 |
+ `<button class="daw-b daw-b--ghost" data-a="livereset">Zurücksetzen</button>`;
|
| 502 |
}
|
| 503 |
const FX = [
|
|
|
|
| 552 |
ui.cv.getContext("2d").setTransform(dpr, 0, 0, dpr, 0, 0);
|
| 553 |
ui.heads.style.paddingTop = `${RULER}px`;
|
| 554 |
}
|
| 555 |
+
let drawQ = false;
|
| 556 |
+
function draw() { if (drawQ) return; drawQ = true; requestAnimationFrame(() => { drawQ = false; drawNow(); }); }
|
| 557 |
+
function drawNow() {
|
| 558 |
if (!ui.cv) return;
|
| 559 |
const g = ui.cv.getContext("2d"), sx = S.scroll, pps = S.pps;
|
| 560 |
g.clearRect(0, 0, cw, ch);
|
|
|
|
| 592 |
g.fillStyle = t.color + (sel ? "" : "cc"); g.fillRect(x, y, w, 15);
|
| 593 |
g.fillStyle = "#0b0a08"; g.font = "700 10px 'Chakra Petch', sans-serif"; g.fillText((a?.name || "Clip").slice(0, Math.max(3, Math.floor(w / 6))), x + 6, y + 8);
|
| 594 |
if (a) {
|
| 595 |
+
const p = pickPeaks(a.peaks, pps), mid = y + 15 + (h - 15) / 2, amp = (h - 19) / 2 * (c.gain ?? 1);
|
| 596 |
g.fillStyle = sel ? "#f0d68a" : t.color; const fx0 = Math.max(0, -x), fx1 = Math.min(w, cw - x);
|
| 597 |
for (let px = fx0; px < fx1; px += 1) {
|
| 598 |
const tt = (c.offset || 0) + px / pps, j = Math.floor(tt * p.rate) * 2; if (j >= p.data.length) break;
|
|
|
|
| 681 |
function onMove(ev) {
|
| 682 |
if (!drag) { const h = hit(ev); ui.cv.style.cursor = h.clip ? (h.edge ? "ew-resize" : "grab") : h.ruler ? "pointer" : "crosshair"; return; }
|
| 683 |
const h = hit(ev);
|
| 684 |
+
if (drag.mode === "seek") { if (Math.abs(h.x - drag.x0) > 4) { if (!drag.loop) commit(); const a = drag.t0, b = Math.max(0, snapT(h.t)); S.loopR = { t0: Math.min(a, b), t1: Math.max(a, b) }; drag.loop = true; } else S.cursor = Math.max(0, snapT(h.t)); }
|
| 685 |
else if (drag.mode === "marker") { drag.m.t = Math.max(0, snapT(h.t)); drag.changed = true; }
|
| 686 |
else if (drag.mode === "auto") { const a = autoHit({ ...h, track: drag.track, ti: trackIdx(drag.track.id) }); drag.p.t = Math.max(0, snapT(h.t)); drag.p.v = a.v; drag.pts.sort((x, y) => x.t - y.t); }
|
| 687 |
else if (drag.mode === "auto-noop") { }
|
|
|
|
| 787 |
$("#daw-pop-h", ui.pop).textContent = mode === "transition" ? "⤳ Übergang craften" : "✦ Smart-Prompt";
|
| 788 |
$(".daw-pop__where", ui.pop).textContent = mode === "transition" ? `an ${fmt(popCtx.at)}` : `${S.tracks[trackIdx(popCtx.track)]?.name} · ab ${fmt(popCtx.start)}${popCtx.len ? ` · ${popCtx.len.toFixed(1)} s` : ""}`;
|
| 789 |
f.bpm.value = S.bpm; f.key.value = S.key; f.prompt.value = mode === "transition" ? "rising riser into drop, whoosh" : f.prompt.value;
|
| 790 |
+
stopPreview(); S.takes = null; renderTakes(); $(".daw-pop__st", ui.pop).textContent = "";
|
| 791 |
+
syncElement(); ui.pop.hidden = false; setTimeout(() => f.prompt.focus(), 30); smartContext(popCtx);
|
| 792 |
}
|
| 793 |
function syncElement() {
|
| 794 |
const f = ui.form, id = (f.querySelector('input[name="element"]:checked') || {}).value, el = S.catalog.elements.find(e => e.id === id); if (!el) return;
|
| 795 |
f.model.innerHTML = `<option value="auto">Auto (bestes verfügbares)</option>` + el.models.map(m => `<option value="${m.id}" ${/paused|broken|unauth|unreach/.test(m.state) ? "disabled" : ""}>${esc(m.label)} · ${esc(m.badge_label)}${/paused/.test(m.state) ? " · pausiert" : ""}</option>`).join("");
|
| 796 |
$(".daw-lyr", ui.pop).hidden = !el.lyrics;
|
| 797 |
f.seconds.value = popCtx.mode === "transition" ? 4 : (popCtx.len ? popCtx.len.toFixed(1) : el.dur);
|
| 798 |
+
renderLic(el); renderSugg();
|
| 799 |
}
|
| 800 |
function renderLic(el) {
|
| 801 |
const f = ui.form, m = el.models.find(x => x.id === f.model.value);
|
|
|
|
| 805 |
async function submitCraft(ev) {
|
| 806 |
ev.preventDefault();
|
| 807 |
const f = ui.form, el = (f.querySelector('input[name="element"]:checked') || {}).value, ctxp = popCtx, btn = f.querySelector('button[type="submit"]');
|
| 808 |
+
const st = $(".daw-pop__st", ui.pop); btn.disabled = true; let secs = 0; st.dataset.take = ""; stopPreview(); const timer = setInterval(() => { secs++; st.textContent = `${st.dataset.take ? st.dataset.take + " · " : ""}Crafting … ${secs}s · GPU-Warteschlange kann 30–120 s dauern`; }, 1000);
|
| 809 |
S.bpm = +f.bpm.value || S.bpm; S.key = f.key.value || S.key;
|
| 810 |
try {
|
| 811 |
let res, a;
|
|
|
|
| 820 |
ctxp.a.fadeOut = xf; ctxp.b.fadeIn = xf;
|
| 821 |
note(`Übergang gesetzt · ${res.model_label} · Crossfade ${xf.toFixed(1)} s`);
|
| 822 |
} else {
|
| 823 |
+
const elLabel = S.catalog.elements.find(e => e.id === el)?.label || el, nV = clamp(+(f.variants?.value || 1), 1, 3), takes = [];
|
| 824 |
+
if (nV > 1) { S.takes = { list: takes, n: nV, ctxp, elLabel }; renderTakes(); }
|
| 825 |
+
for (let i = 0; i < nV; i++) {
|
| 826 |
+
if (nV > 1) { st.dataset.take = `Take ${i + 1}/${nV}`; secs = 0; }
|
| 827 |
+
const seed = nV > 1 ? Math.floor(Math.random() * 2147483646) + 1 : 0;
|
| 828 |
+
try { res = await api("daw_generate", [el, f.model.value, f.prompt.value, f.negative.value, f.lyrics.value, +f.seconds.value, S.bpm, S.key, seed]); }
|
| 829 |
+
catch (e) { if (nV === 1) throw e; takes.push({ err: e.message }); renderTakes(); continue; }
|
| 830 |
+
a = await assetFromUrl(res.url, `${elLabel}${nV > 1 ? ` · Take ${i + 1}` : ""} · ${(f.prompt.value || "").slice(0, 20)}`, res.path, res);
|
| 831 |
+
takes.push({ a, res, seed }); if (nV > 1) renderTakes();
|
| 832 |
+
}
|
| 833 |
+
if (!takes.some(t => t.a)) throw new Error(takes[0]?.err || "keine Takes erzeugt");
|
| 834 |
+
if (nV > 1) { st.dataset.take = ""; clearInterval(timer); st.textContent = `${takes.filter(t => t.a).length} Takes bereit`; note(`${takes.filter(t => t.a).length} Takes bereit – anhören (▶) und einen übernehmen`); return; }
|
| 835 |
+
useTake(takes[0], ctxp, elLabel);
|
| 836 |
}
|
| 837 |
ui.pop.hidden = true; renderAll();
|
| 838 |
} catch (e) { st.textContent = "Fehler: " + e.message; note("Craft fehlgeschlagen: " + e.message, "err"); }
|
| 839 |
finally { clearInterval(timer); btn.disabled = false; if (ui.pop.hidden) st.textContent = ""; }
|
| 840 |
}
|
| 841 |
|
| 842 |
+
|
| 843 |
+
/* Smart-Prompt: Kontext (BPM/Key/Genre der Nachbarspuren), Vorschläge, Presets, Takes */
|
| 844 |
+
const GENRES = ["deep house", "drum and bass", "hip hop", "boom bap", "lo-fi", "lofi", "trap", "drill", "house", "techno", "pop", "rock", "ambient", "cinematic", "dnb", "edm", "dubstep", "reggaeton", "afrobeats", "jazz", "soul", "r&b", "rnb", "metal", "synthwave", "phonk", "garage", "trance", "funk", "disco", "orchestral"];
|
| 845 |
+
const GENRE_PRESETS = {
|
| 846 |
+
trap: { label: "Trap", bpm: 140, key: "F minor", tags: "dark trap, 808 bass, rolling hi-hats" }, house: { label: "House", bpm: 124, key: "A minor", tags: "deep house, warm chords, four-on-the-floor" },
|
| 847 |
+
lofi: { label: "Lo-Fi", bpm: 82, key: "D minor", tags: "lo-fi hip hop, dusty vinyl, mellow" }, techno: { label: "Techno", bpm: 130, key: "A minor", tags: "driving techno, hypnotic, industrial" },
|
| 848 |
+
cinematic: { label: "Cinematic", bpm: 90, key: "C minor", tags: "cinematic, epic, orchestral" }, pop: { label: "Pop", bpm: 116, key: "C major", tags: "modern pop, bright, catchy" },
|
| 849 |
+
dnb: { label: "Drum & Bass", bpm: 174, key: "E minor", tags: "drum and bass, rolling breaks, sub bass" }, afro: { label: "Afrobeats", bpm: 108, key: "G minor", tags: "afrobeats, syncopated percussion, warm" },
|
| 850 |
+
synthwave: { label: "Synthwave", bpm: 100, key: "A minor", tags: "synthwave, retro 80s, analog synths" },
|
| 851 |
+
};
|
| 852 |
+
const EL_TPL = { full_song: ["full song with vocals, verse and hook", "anthemic chorus, big hook", "intimate verse, sparse"], voice: ["lead vocal, a cappella, clean, dry", "airy female vocal hook", "deep male vocal, spoken"],
|
| 853 |
+
drums: ["drums, punchy kick, crisp snare, tight hats", "minimal percussion, shakers, rim", "heavy drums, big room, energetic"], bass: ["bassline, tight low end, groovy", "sub bass, long notes, clean", "plucked bass, syncopated"],
|
| 854 |
+
instrument: ["chords, warm keys", "guitar riff, clean tone", "pad layer, evolving texture"], instrumental_song: ["instrumental, full arrangement", "instrumental, stripped back", "instrumental, high energy drop"],
|
| 855 |
+
melody_solo: ["lead melody, solo synth, catchy", "solo piano melody, emotional", "flute lead, airy"], melody_ensemble: ["melody ensemble, layered strings", "brass section melody, bold", "choir and strings, cinematic"],
|
| 856 |
+
sfx: ["riser into drop, whoosh", "impact hit, deep boom", "ambient texture, room tone"], transition: ["rising riser into drop, whoosh", "reverse cymbal swell", "downlifter, filter sweep"] };
|
| 857 |
+
let smartTok = 0;
|
| 858 |
+
const elNow = () => (ui.form.querySelector('input[name="element"]:checked') || {}).value;
|
| 859 |
+
async function analyzeClip(c) {
|
| 860 |
+
const a = S.assets[c.asset]; if (!a) return null; const key = `${c.offset || 0}|${c.dur.toFixed(2)}`;
|
| 861 |
+
a.meta.analysis = a.meta.analysis || {}; if (a.meta.analysis[key]) return a.meta.analysis[key];
|
| 862 |
+
const p = await ensureServer(a); const r = await api("daw_analyze", [p, c.offset || 0, (c.offset || 0) + Math.min(c.dur, 60)]); a.meta.analysis[key] = r; return r;
|
| 863 |
+
}
|
| 864 |
+
async function smartContext(ctxp) {
|
| 865 |
+
const tok = ++smartTok, box = $(".daw-ctx", ui.pop); S.smart = { genre: null, bpm: null, key: null, n: 0 };
|
| 866 |
+
const t0 = ctxp.mode === "transition" ? ctxp.at - 10 : ctxp.start - 8, t1 = ctxp.mode === "transition" ? ctxp.at + 10 : ctxp.start + (ctxp.len || 30) + 8;
|
| 867 |
+
let nb = S.clips.filter(c => !c.muted && c.track !== ctxp.track && clipEnd(c) > t0 && c.start < t1); if (!nb.length) nb = S.clips.filter(c => !c.muted && c.track !== ctxp.track);
|
| 868 |
+
nb = nb.sort((a, b) => b.dur - a.dur).slice(0, 3);
|
| 869 |
+
const words = [S.title, ...nb.map(c => S.assets[c.asset]?.meta?.prompt || S.assets[c.asset]?.name || "")].join(" ").toLowerCase();
|
| 870 |
+
S.smart.genre = GENRES.find(g => words.includes(g)) || null;
|
| 871 |
+
renderSugg();
|
| 872 |
+
if (!nb.length) { box.innerHTML = `<span class="daw-ctx__l">Kontext</span> leeres Projekt · Preset wählen oder frei prompten`; return; }
|
| 873 |
+
box.innerHTML = `<span class="daw-ctx__l">Kontext</span> analysiere ${nb.length} Nachbar-Clip${nb.length > 1 ? "s" : ""} (BPM/Tonart, CPU) …`;
|
| 874 |
+
const res = []; for (const c of nb) { try { const r = await analyzeClip(c); if (r) res.push(r); } catch { } if (tok !== smartTok) return; }
|
| 875 |
+
if (tok !== smartTok) return;
|
| 876 |
+
const bb = res.filter(r => r.bpm).sort((a, b) => b.bpm_conf - a.bpm_conf)[0], votes = {};
|
| 877 |
+
for (const r of res) if (r.key) votes[r.key] = (votes[r.key] || 0) + 0.2 + r.key_conf;
|
| 878 |
+
const key = Object.entries(votes).sort((a, b) => b[1] - a[1])[0]?.[0] || null;
|
| 879 |
+
Object.assign(S.smart, { bpm: bb && bb.bpm_conf >= 0.25 ? bb.bpm : null, key, n: res.length });
|
| 880 |
+
const f = ui.form;
|
| 881 |
+
if (S.smart.bpm && +f.bpm.value === S.bpm && S.bpm === 120) f.bpm.value = S.smart.bpm;
|
| 882 |
+
if (S.smart.key && f.key.value === S.key && S.key === "C minor") f.key.value = S.smart.key;
|
| 883 |
+
box.innerHTML = `<span class="daw-ctx__l">Kontext</span> <b>${S.smart.bpm ?? "?"} BPM</b> · <b>${esc(S.smart.key || "?")}</b>${S.smart.genre ? ` · ${esc(S.smart.genre)}` : ""} <small>aus ${res.length} Nachbar-Clip${res.length > 1 ? "s" : ""}</small>
|
| 884 |
+
<button type="button" class="daw-b daw-b--sm" data-a="ctxapply" title="BPM und Tonart ins Formular und ins Projekt übernehmen">Übernehmen</button>`;
|
| 885 |
+
renderSugg();
|
| 886 |
+
}
|
| 887 |
+
function renderSugg() {
|
| 888 |
+
const el = popCtx?.mode === "transition" ? "transition" : elNow(), box = $(".daw-sugg", ui.pop); if (!box || !el) return;
|
| 889 |
+
const f = ui.form, preset = GENRE_PRESETS[f.preset?.value], g = preset ? preset.tags : (S.smart?.genre || "");
|
| 890 |
+
const bpm = f.bpm.value || S.bpm, key = f.key.value || S.key, tpl = EL_TPL[el] || EL_TPL.instrument;
|
| 891 |
+
S.sugg = tpl.map(t => [g, t, `${bpm} BPM`, el === "sfx" || el === "transition" || el === "drums" ? "" : key].filter(Boolean).join(", "));
|
| 892 |
+
box.innerHTML = S.sugg.map((s, i) => `<button type="button" class="daw-chip" data-a="sugg" data-i="${i}" title="Vorschlag übernehmen">${esc(s)}</button>`).join("");
|
| 893 |
+
}
|
| 894 |
+
function applyPreset() { const f = ui.form, p = GENRE_PRESETS[f.preset.value]; if (!p) return renderSugg(); f.bpm.value = p.bpm; f.key.value = p.key; renderSugg(); f.prompt.value = S.sugg[0]; }
|
| 895 |
+
let prev = null;
|
| 896 |
+
function stopPreview() { if (!prev) return; try { prev.src.stop(); } catch { } prev.b.textContent = "▶"; prev.b.classList.remove("is-on"); prev = null; }
|
| 897 |
+
function togglePreview(i, b) {
|
| 898 |
+
const was = prev?.i === i; stopPreview(); if (was) return; const t = S.takes?.list[i]; if (!t?.a) return;
|
| 899 |
+
ensureCtx(); const src = ctx.createBufferSource(), g = ctx.createGain(); src.buffer = t.a.buffer; g.gain.value = 0.9; src.connect(g); g.connect(ctx.destination); src.start();
|
| 900 |
+
src.onended = () => { if (prev?.src === src) stopPreview(); }; prev = { i, src, b }; b.textContent = "■"; b.classList.add("is-on");
|
| 901 |
+
}
|
| 902 |
+
function renderTakes() {
|
| 903 |
+
const T = S.takes, box = $(".daw-takes", ui.pop); if (!T) { box.hidden = true; box.innerHTML = ""; return; } box.hidden = false;
|
| 904 |
+
box.innerHTML = `<p class="daw-takes__h">Takes · anhören und einen übernehmen</p>` + T.list.map((t, i) => t.a
|
| 905 |
+
? `<div class="daw-take"><b>Take ${i + 1}</b><span>${esc(t.res.model_label)} · ${t.a.buffer.duration.toFixed(1)} s${t.res.lufs != null ? ` · ${t.res.lufs} LUFS` : ""}</span><button type="button" class="daw-b daw-b--sm" data-a="takeplay" data-i="${i}" aria-label="Take ${i + 1} anhören">▶</button><button type="button" class="daw-b daw-b--sm daw-craft" data-a="takeuse" data-i="${i}">Übernehmen</button></div>`
|
| 906 |
+
: `<div class="daw-take is-err"><b>Take ${i + 1}</b><span>Fehler: ${esc(t.err || "")}</span></div>`).join("")
|
| 907 |
+
+ (T.list.length < T.n ? `<div class="daw-take is-wait"><b>Take ${T.list.length + 1}</b><span>wird gecraftet …</span></div>` : "");
|
| 908 |
+
}
|
| 909 |
+
function useTake(t, ctxp, elLabel) {
|
| 910 |
+
commit(); const c = addClip(t.a, ctxp.track, ctxp.start, ctxp.len ? Math.min(ctxp.len, t.a.buffer.duration) : t.a.buffer.duration);
|
| 911 |
+
S.sel = new Set([c.id]); note(`${elLabel} gecraftet · ${t.res.model_label} · ${t.res.elapsed_s}s${t.res.fallback_errors?.length ? " (Fallback genutzt)" : ""}`);
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
/* Mixer-Ansicht: Channel-Strips + Effekt-Presets je Spur */
|
| 916 |
+
const TRACK_PRESETS = {
|
| 917 |
+
"Neutral": {}, "Vocal Clean": { denoise: 25, low: -3, mid: 1, high: 3, comp: 45, hall: 18, hallSize: 0.35 }, "Vocal Radio": { denoise: 30, low: -8, mid: 5, high: -2, comp: 70, echo: 10, echoTime: 0.18, hall: 8, hallSize: 0.3 },
|
| 918 |
+
"Vocal Space": { denoise: 20, low: -2, high: 4, comp: 40, echo: 28, echoTime: 0.375, hall: 45, hallSize: 0.75 }, "Drum Punch": { low: 4, mid: -2, high: 3, comp: 65, hall: 6, hallSize: 0.25 },
|
| 919 |
+
"Bass Tight": { low: 3, mid: -3, high: -4, comp: 60 }, "Wide Pad": { low: -4, high: 2, comp: 20, hall: 40, hallSize: 0.8, width: 1.6 }, "Lo-Fi Tape": { low: 2, mid: -1, high: -9, comp: 50, echo: 15, echoTime: 0.25, hall: 20, hallSize: 0.4 },
|
| 920 |
+
};
|
| 921 |
+
const userPresets = () => { try { return JSON.parse(localStorage.getItem("2b-daw-fx-presets") || "{}"); } catch { return {}; } };
|
| 922 |
+
const allPresets = () => ({ ...TRACK_PRESETS, ...userPresets() });
|
| 923 |
+
const presetOptions = () => `<option value="">Preset …</option>` + Object.keys(allPresets()).map(n => `<option value="${esc(n)}">${esc(n)}</option>`).join("");
|
| 924 |
+
function applyTrackPreset(t, name) {
|
| 925 |
+
const p = allPresets()[name]; if (!t || !p) return; commit(); const { width, ...live } = p; t.live = { ...LIVE_DEFAULT, ...live }; if (width != null) t.width = width; t.preset = name;
|
| 926 |
+
ensureCtx(); rebuildGraph(); renderHeads(); renderLive(); note(`${t.name}: Preset „${name}“`);
|
| 927 |
+
}
|
| 928 |
+
function savePreset() {
|
| 929 |
+
const t = S.tracks.find(x => x.id === S.selTrack); if (!t) return; const u = userPresets(); const name = `Eigenes ${Object.keys(u).length + 1} (${t.name})`.slice(0, 40);
|
| 930 |
+
u[name] = { ...t.live, width: t.width }; try { localStorage.setItem("2b-daw-fx-presets", JSON.stringify(u)); } catch { } t.preset = name; renderLive(); renderMixer(); note(`Preset „${name}“ gespeichert (dieser Browser)`);
|
| 931 |
+
}
|
| 932 |
+
const INSERTS = [["denoise", "Gate", L => L.denoise > 0], ["eq", "EQ", L => L.low || L.mid || L.high], ["comp", "Comp", L => L.comp > 0], ["echo", "Echo", L => L.echo > 0], ["hall", "Hall", L => L.hall > 0]];
|
| 933 |
+
const fdb = v => v <= 0.0001 ? "−∞" : `${(20 * Math.log10(v)).toFixed(1)} dB`;
|
| 934 |
+
function renderMixer() {
|
| 935 |
+
if (!ui.mixer || ui.mixer.hidden) return;
|
| 936 |
+
ui.mixer.innerHTML = S.tracks.map(t => `<div class="daw-strip${t.id === S.selTrack ? " is-sel" : ""}" data-t="${t.id}" style="--c:${t.color}">
|
| 937 |
+
<div class="daw-strip__name" title="${esc(t.name)}">${esc(t.name)}</div>
|
| 938 |
+
<div class="daw-ins" aria-label="Inserts">${INSERTS.map(([k, l, on]) => `<button class="daw-in${on(t.live) ? " is-on" : ""}" data-ins="${k}" title="Insert ${l} – im Live-FX-Tab einstellen">${l}</button>`).join("")}</div>
|
| 939 |
+
<select class="daw-preset" data-preset aria-label="Effekt-Preset ${esc(t.name)}">${presetOptions().replace(`value="${esc(t.preset || "")}"`, `value="${esc(t.preset || "")}" selected`)}</select>
|
| 940 |
+
<label class="daw-knob" title="Panorama L–R">Pan<input type="range" min="-1" max="1" step="0.01" value="${t.pan}" data-p="pan"></label>
|
| 941 |
+
<label class="daw-knob" title="Stereo-Breite">Width<input type="range" min="0" max="2" step="0.01" value="${t.width}" data-p="width"></label>
|
| 942 |
+
<div class="daw-strip__ms"><button class="daw-ms${t.mute ? " is-on" : ""}" data-m="mute" title="Stumm (M)">M</button><button class="daw-ms daw-ms--s${t.solo ? " is-on" : ""}" data-m="solo" title="Solo">S</button><button class="daw-ms daw-ms--r${t.arm ? " is-on" : ""}" data-m="arm" title="Aufnahme scharf">●</button></div>
|
| 943 |
+
<div class="daw-fader"><input type="range" min="0" max="1.5" step="0.01" value="${t.vol}" data-p="vol" aria-label="Fader ${esc(t.name)}"><span class="daw-smeter" aria-hidden="true"><i></i></span></div>
|
| 944 |
+
<output class="daw-db">${fdb(t.vol)}</output></div>`).join("")
|
| 945 |
+
+ `<div class="daw-strip daw-strip--master"><div class="daw-strip__name">Master</div><div class="daw-ins"><span class="daw-in is-on" title="Brickwall-Limiter −1,5 dBFS">Limit</span></div>
|
| 946 |
+
<output class="daw-mlufs"></output>
|
| 947 |
+
<div class="daw-fader"><input type="range" min="0" max="1.5" step="0.01" value="${S.master.vol}" data-k="mvol" aria-label="Master-Fader"><span class="daw-smeter daw-smeter--m" aria-hidden="true"><i class="m2L"></i><i class="m2R"></i></span></div>
|
| 948 |
+
<output class="daw-db">${fdb(S.master.vol)}</output></div>`;
|
| 949 |
+
}
|
| 950 |
+
function toggleMixer(force) {
|
| 951 |
+
const on = force ?? S.view !== "mixer"; S.view = on ? "mixer" : "arrange"; ui.mixer.hidden = !on; ui.root.classList.toggle("is-mixer", on);
|
| 952 |
+
const b = $('[data-a="mixer"]', ui.root); b.classList.toggle("is-on", on); b.setAttribute("aria-pressed", on);
|
| 953 |
+
if (on) renderMixer(); else { syncInputs(); renderHeads(); layout(); draw(); } note(on ? "Mixer · X schaltet zurück zur Timeline" : "Timeline");
|
| 954 |
+
}
|
| 955 |
+
|
| 956 |
/* Destruktive FX */
|
| 957 |
async function applyFx() {
|
| 958 |
const c = selectedClips()[0]; if (!c) return;
|
|
|
|
| 981 |
return await oc.startRendering();
|
| 982 |
}
|
| 983 |
function download(href, name) { const a = document.createElement("a"); a.href = href; a.download = name; document.body.appendChild(a); a.click(); a.remove(); }
|
| 984 |
+
// True-Peak (4× Oversampling, 12-Tap-Polyphasen-FIR wie im Master-Meter) eines AudioBuffers
|
| 985 |
+
const TPH = [1, 2, 3].map(p => { const c = []; let sm = 0; for (let j = 0; j < 12; j++) { const x = 6 - j - p / 4, s = Math.sin(Math.PI * x) / (Math.PI * x), w = 0.5 + 0.5 * Math.cos(Math.PI * x / 6.5); c.push(s * w); sm += s * w; } return c.map(v => v / sm); });
|
| 986 |
+
function truePeak(buf) {
|
| 987 |
+
let pk = 0;
|
| 988 |
+
for (let ch = 0; ch < buf.numberOfChannels; ch++) { const d = buf.getChannelData(ch);
|
| 989 |
+
for (let k = 0; k < d.length; k++) { const v = d[k] < 0 ? -d[k] : d[k]; if (v > pk) pk = v;
|
| 990 |
+
if (k >= 11 && (d[k] > 0.25 || d[k] < -0.25 || d[k - 6] > 0.25 || d[k - 6] < -0.25)) for (let p = 0; p < 3; p++) { const cp = TPH[p]; let y = 0; for (let j = 0; j < 12; j++) y += cp[j] * d[k - j]; if (y < 0) y = -y; if (y > pk) pk = y; } } }
|
| 991 |
+
return pk;
|
| 992 |
+
}
|
| 993 |
+
S.tpCeil = -1;
|
| 994 |
async function exportMix(kind) {
|
| 995 |
try {
|
| 996 |
+
note(`Rendere Mixdown (${kind.toUpperCase()}) …`); const buf = await renderMix(); let tp = db(truePeak(buf)), adj = 0;
|
| 997 |
+
if (S.tpCeil != null && tp > S.tpCeil) { adj = S.tpCeil - tp; const g = Math.pow(10, adj / 20); for (let ch = 0; ch < buf.numberOfChannels; ch++) { const d = buf.getChannelData(ch); for (let i = 0; i < d.length; i++) d[i] *= g; } tp = db(truePeak(buf)); }
|
| 998 |
+
S.lastExport = { kind, tp: +tp.toFixed(2), adj: +adj.toFixed(2), dur: buf.duration };
|
| 999 |
+
const tpTxt = `True-Peak ${tp.toFixed(1)} dBTP${adj ? ` (Sicherheits-Gain ${adj.toFixed(1)} dB → Ceiling ${S.tpCeil} dBTP)` : ""}`;
|
| 1000 |
+
const wav = encodeWav(buf, kind === "wav" ? 24 : 16);
|
| 1001 |
+
if (kind === "wav") { const u = URL.createObjectURL(wav); download(u, `${S.title.replace(/\W+/g, "-")}.wav`); setTimeout(() => URL.revokeObjectURL(u), 4000); note(`WAV exportiert · ${buf.duration.toFixed(1)} s · 24-bit · ${tpTxt}`); return; }
|
| 1002 |
const p = await upload(wav, "mix.wav"); const r = await api("daw_encode", [p, "mp3"]);
|
| 1003 |
+
S.lastExport.server_tp = r.true_peak_db;
|
| 1004 |
+
download(url(r.url), `${S.title.replace(/\W+/g, "-")}.mp3`); note(`MP3 320 exportiert · ${r.duration_s} s · ${r.lufs} LUFS · ${tpTxt}`);
|
| 1005 |
} catch (e) { note("Export fehlgeschlagen: " + e.message, "err"); }
|
| 1006 |
}
|
| 1007 |
async function saveProject() {
|
|
|
|
| 1034 |
function syncLoopBtn() { const b = $('[data-a="loop"]', ui.root); if (b) { b.classList.toggle("is-on", S.loop); b.setAttribute("aria-pressed", S.loop); } draw(); }
|
| 1035 |
function addMarker(t = S.cursor) { commit(); const m = { id: uid(), t: Math.max(0, snapT(t)), name: `M${S.markers.length + 1}` }; S.markers.push(m); S.markers.sort((a, b) => a.t - b.t); note(`Marker ${m.name} bei ${bbt(m.t)}`); draw(); return m; }
|
| 1036 |
function fit() { const len = Math.max(8, ...S.clips.map(clipEnd)); S.pps = clamp((ui.scroll.clientWidth - 30) / len, 4, 600); layout(); ui.scroll.scrollLeft = 0; S.scroll = 0; draw(); }
|
| 1037 |
+
function progress(p, msg, cancellable = false) { if (p == null) { ui.prog.hidden = true; return; } ui.prog.hidden = false; ui.prog.querySelector("i").style.width = `${Math.round(clamp(p, 0.02, 1) * 100)}%`; ui.prog.querySelector("span").textContent = msg; ui.prog.querySelector("button").hidden = !cancellable; }
|
| 1038 |
+
function toggleTrack(t, k) { if (!t) return; commit(); t[k] = !t[k]; ensureCtx(); rebuildGraph(); renderHeads(); scheduleAutosave(); note(`${t.name}: ${{ mute: "Stumm", solo: "Solo", arm: "Aufnahme scharf" }[k]} ${t[k] ? "an" : "aus"}`); }
|
| 1039 |
function cycleAuto(t, v) { t.autoView = v !== undefined ? v : ({ null: "vol", vol: "pan", pan: null })[t.autoView]; renderHeads(); draw(); note(t.autoView ? `${t.name}: Automation ${AUTO[t.autoView].label} – Klick in die Spur setzt Punkte` : `${t.name}: Automation ausgeblendet`); }
|
| 1040 |
|
| 1041 |
+
/* Stems (Demucs) – Job mit Segment-Fortschritt, Warteschlange, ETA, Timeout, Abbruch */
|
| 1042 |
+
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
| 1043 |
+
const fmtS = s => { s = Math.max(0, Math.round(s || 0)); return s < 60 ? `${s} s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")} min`; };
|
| 1044 |
+
let stemJob = null;
|
| 1045 |
async function stemsFor(c) {
|
| 1046 |
+
if (stemJob) return note("Es läuft bereits eine Stem-Trennung – abwarten oder abbrechen (×)", "err");
|
| 1047 |
c = c || selectedClips()[0]; if (!c) return note("Für Stems zuerst einen Clip wählen", "err");
|
| 1048 |
const st = S.catalog?.stems; if (st && !st.available) return note("Stem-Trennung ist auf diesem Server nicht verfügbar", "err");
|
| 1049 |
if (st && c.dur > st.max_s + 0.5) return note(`Clip ist ${c.dur.toFixed(0)} s – auf CPU max. ${st.max_s} s. Bitte vorher schneiden (S).`, "err");
|
| 1050 |
+
const a = S.assets[c.asset], job = stemJob = { id: null, cancelled: false }; progress(0.02, "Stems: lade Audio hoch …", true);
|
| 1051 |
try {
|
| 1052 |
+
const p = await ensureServer(a); const j = await api("daw_stems", [p, c.offset || 0, (c.offset || 0) + c.dur]); job.id = j.job;
|
| 1053 |
+
if (job.cancelled) api("daw_job_cancel", [j.job]).catch(() => { });
|
| 1054 |
+
let r, lastP = -1, lastChange = Date.now(), fails = 0; const t0 = Date.now();
|
| 1055 |
+
for (; ;) {
|
| 1056 |
+
await sleep(1000);
|
| 1057 |
+
try { r = await api("daw_job", [j.job]); fails = 0; } catch (e) { if (++fails >= 5) throw new Error("Server antwortet nicht (evtl. neu gestartet) – bitte erneut versuchen"); continue; }
|
| 1058 |
+
if (["done", "error", "cancelled"].includes(r.state)) break;
|
| 1059 |
+
if (job.cancelled) { if (Date.now() - t0 > 600000) throw new Error("abgebrochen"); continue; }
|
| 1060 |
+
if (r.progress !== lastP) { lastP = r.progress; lastChange = Date.now(); }
|
| 1061 |
+
else if (r.state === "running" && Date.now() - lastChange > 180000) { api("daw_job_cancel", [j.job]).catch(() => { }); throw new Error("keine Rückmeldung seit 3 min – Job abgebrochen. Clip kürzen oder später erneut versuchen"); }
|
| 1062 |
+
progress(r.progress, r.state === "queued" ? `Stems: Warteschlange · Platz ${r.queue + 1} · Start in ~${fmtS(r.wait_s)} · Dauer ~${fmtS(r.eta_s)}`
|
| 1063 |
+
: `Stems (htdemucs, CPU) · ${r.msg} · ${Math.round(r.progress * 100)}% · noch ~${fmtS(r.eta_s)}`, true);
|
| 1064 |
+
}
|
| 1065 |
+
if (r.state === "cancelled" || job.cancelled) throw new Error("abgebrochen");
|
| 1066 |
if (r.state === "error") throw new Error(r.error || "Job fehlgeschlagen");
|
| 1067 |
+
progress(0.99, "Stems: lade Spuren …", false);
|
| 1068 |
const loaded = []; for (const s of r.result) loaded.push([s, await assetFromUrl(s.url, `${s.label} · ${a.name}`.slice(0, 48), s.path, s)]);
|
| 1069 |
commit(); let at = trackIdx(c.track) + 1;
|
| 1070 |
for (const [s, na] of loaded) { const t = newTrack(s.label); S.tracks.pop(); S.tracks.splice(at++, 0, t); addClip(na, t.id, c.start, Math.min(c.dur, na.buffer.duration)); }
|
| 1071 |
c.muted = true; progress(null); rebuildGraph(); renderAll(); note(`${loaded.length} Stems erzeugt · Original-Clip stumm (Rechtsklick → aktivieren)`);
|
| 1072 |
+
} catch (e) { progress(null); const ab = e.message === "abgebrochen"; note(ab ? "Stem-Trennung abgebrochen" : "Stems fehlgeschlagen: " + e.message, ab ? "" : "err"); }
|
| 1073 |
+
finally { if (stemJob === job) stemJob = null; }
|
| 1074 |
+
}
|
| 1075 |
+
function cancelStems() { if (!stemJob) return; stemJob.cancelled = true; if (stemJob.id) api("daw_job_cancel", [stemJob.id]).catch(() => { }); progress(null); note("Stem-Trennung wird abgebrochen …"); }
|
| 1076 |
+
|
| 1077 |
+
/* Cloud-Autosave ins private HF-Dataset (nur mit Login; lokal bleibt IndexedDB) */
|
| 1078 |
+
const SESSION = (() => { try { let v = sessionStorage.getItem("2b-daw-session"); if (!v) { v = (uid() + uid()).slice(0, 16); sessionStorage.setItem("2b-daw-session", v); } return v; } catch { return (uid() + uid()).slice(0, 16); } })();
|
| 1079 |
+
const cloud = { user: null, on: false, dirty: false, busy: false, last: 0, every: 60000, timer: 0, state: "off", msg: "" };
|
| 1080 |
+
async function cloudInit() {
|
| 1081 |
+
try { const r = await api("daw_whoami", []); cloud.user = r.user; cloud.on = !!r.cloud; } catch { cloud.on = false; }
|
| 1082 |
+
renderCloud(cloud.on ? (S.clips.length ? "pending" : "ok") : "off"); if (cloud.on && !cloud.timer) cloud.timer = setInterval(cloudTick, 2000);
|
| 1083 |
+
}
|
| 1084 |
+
function renderCloud(state, msg = "") {
|
| 1085 |
+
cloud.state = state; cloud.msg = msg; const el = ui.cloud; if (!el) return; el.dataset.state = state;
|
| 1086 |
+
el.textContent = { off: "☁ Cloud: mit HF-Login", pending: "☁ Änderungen …", saving: "☁ speichert …", ok: cloud.last ? `☁ privat · ${new Date(cloud.last).toLocaleTimeString("de-DE").slice(0, 5)}` : "☁ privat · aktiv", err: "☁ Fehler · lokal gesichert" }[state];
|
| 1087 |
+
el.dataset.tip = state === "off" ? "Mit HF-Login wird das Projekt alle 60 s bei Änderungen in dein PRIVATES Dataset <user>/2b-studio-projects gesichert" : state === "err" ? `Cloud-Autosave fehlgeschlagen: ${msg} – nächster Versuch automatisch` : `Privates Dataset ${cloud.user}/2b-studio-projects · Ordner autosave/${SESSION}`;
|
| 1088 |
+
}
|
| 1089 |
+
function cloudTick() { if (!cloud.on || cloud.busy || !cloud.dirty || !S.clips.length) return; if (Date.now() - cloud.last < cloud.every) return; cloudSave(); }
|
| 1090 |
+
async function cloudSave() {
|
| 1091 |
+
cloud.busy = true; cloud.dirty = false; renderCloud("saving");
|
| 1092 |
+
try {
|
| 1093 |
+
const used = [...new Set(S.clips.map(c => c.asset))].map(id => S.assets[id]).filter(Boolean); for (const a of used) await ensureServer(a);
|
| 1094 |
+
const proj = { app: "2b-studio-daw", v: 3, title: S.title, bpm: S.bpm, key: S.key, sig: S.sig, grid: S.grid, markers: S.markers, loopR: S.loopR, master: S.master, tracks: S.tracks, clips: S.clips,
|
| 1095 |
+
assets: used.map(a => ({ id: a.id, name: a.name, path: a.path, meta: a.meta })) };
|
| 1096 |
+
const r = await api("daw_autosave", [JSON.stringify(proj), S.title, SESSION]); cloud.last = Date.now();
|
| 1097 |
+
if (r.ok) renderCloud("ok"); else if (r.reason === "login") { cloud.on = false; renderCloud("off"); } else { cloud.dirty = true; renderCloud("err", r.error || r.reason); }
|
| 1098 |
+
} catch (e) { cloud.dirty = true; cloud.last = Date.now(); renderCloud("err", e.message); }
|
| 1099 |
+
finally { cloud.busy = false; }
|
| 1100 |
}
|
| 1101 |
|
| 1102 |
/* Aufnahme */
|
|
|
|
| 1136 |
let idbP = null, asTimer = 0; const asSaved = new Set();
|
| 1137 |
function idb() { return idbP || (idbP = new Promise((res, rej) => { const r = indexedDB.open("2b-studio-daw", 1); r.onupgradeneeded = () => { r.result.createObjectStore("kv"); r.result.createObjectStore("audio"); }; r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); })); }
|
| 1138 |
async function idbOp(store, mode, fn) { const d = await idb(); return new Promise((res, rej) => { const tx = d.transaction(store, mode), rq = fn(tx.objectStore(store)); tx.oncomplete = () => res(rq?.result); tx.onerror = () => rej(tx.error); }); }
|
| 1139 |
+
function scheduleAutosave() { clearTimeout(asTimer); asTimer = setTimeout(autosave, 1200); if (cloud.on) { cloud.dirty = true; if (cloud.state !== "saving") renderCloud("pending"); } }
|
| 1140 |
async function autosave() {
|
| 1141 |
if (!window.indexedDB || !ui.save || (ui.banner && !ui.banner.hidden)) return;
|
| 1142 |
try {
|
|
|
|
| 1145 |
await idbOp("audio", "readwrite", st => st.put({ sr: b.sampleRate, chs, name: a.name, meta: a.meta }, id)); asSaved.add(id); }
|
| 1146 |
await idbOp("kv", "readwrite", st => st.put({ at: Date.now(), title: S.title, bpm: S.bpm, key: S.key, sig: S.sig, grid: S.grid, tracks: S.tracks, clips: S.clips, markers: S.markers, loopR: S.loopR, master: S.master, assets: used }, "auto"));
|
| 1147 |
ui.save.textContent = "✓ gesichert " + new Date().toLocaleTimeString("de-DE").slice(0, 5); ui.save.dataset.state = "ok";
|
| 1148 |
+
const keys = await idbOp("audio", "readonly", st => st.getAllKeys()); const stale = keys.filter(k => !used.includes(k));
|
| 1149 |
+
if (stale.length) { await idbOp("audio", "readwrite", st => { for (const k of stale) st.delete(k); return null; }); stale.forEach(k => asSaved.delete(k)); }
|
| 1150 |
} catch { ui.save.textContent = "Autosave nicht möglich"; ui.save.dataset.state = "err"; }
|
| 1151 |
}
|
| 1152 |
async function checkRestore() {
|
|
|
|
| 1180 |
function canvasMenu(ev) {
|
| 1181 |
const h = hit(ev); ensureCtx(false);
|
| 1182 |
if (h.ruler) return menu(ev, [{ l: "Marker hier setzen", k: "K", f: () => addMarker(h.t) }, ...(h.marker ? [{ l: `Marker ${h.marker.name} löschen`, f: () => { commit(); S.markers = S.markers.filter(m => m !== h.marker); draw(); } }] : []),
|
| 1183 |
+
{ l: "Loop-Bereich entfernen", dis: !S.loopR, f: () => { commit(); S.loopR = null; S.loop = false; syncLoopBtn(); } }, { l: "Loop an/aus", k: "L", f: () => ACTIONS.loop() }]);
|
| 1184 |
if (h.track) { S.selTrack = h.track.id; renderHeadsSel(); }
|
| 1185 |
if (h.track?.autoView) { const a = autoHit(h); return menu(ev, [{ l: "Punkt löschen", dis: !a.p, f: () => { commit(); a.pts.splice(a.pts.indexOf(a.p), 1); rebuildGraph(); draw(); } },
|
| 1186 |
{ l: "Automation leeren", f: () => { commit(); a.pts.length = 0; rebuildGraph(); draw(); } }, { l: "Automation ausblenden", f: () => cycleAuto(h.track, null) }]); }
|
|
|
|
| 1218 |
loop: () => { S.loop = !S.loop; syncLoopBtn(); note(S.loop ? (loopRegion() ? `Loop ${fmt(loopRegion().t0)} – ${fmt(loopRegion().t1)}` : "Loop an – Bereich im Lineal ziehen") : "Loop aus"); },
|
| 1219 |
rec: toggleRecord, metro: b => { S.metro = !S.metro; b = b || $('[data-a="metro"]', ui.root); b.classList.toggle("is-on", S.metro); b.setAttribute("aria-pressed", S.metro); if (S.playing) S.metro ? metroStart() : metroStop(); note(`Metronom ${S.metro ? "an" : "aus"}`); },
|
| 1220 |
countin: b => { S.countIn = !S.countIn; b.classList.toggle("is-on", S.countIn); b.setAttribute("aria-pressed", S.countIn); note(`Einzähler ${S.countIn ? "an" : "aus"}`); },
|
| 1221 |
+
marker: () => addMarker(), stems: () => stemsFor(), stemcancel: cancelStems, mixer: () => toggleMixer(), presetsave: savePreset, fit, help: () => { ui.help.hidden = !ui.help.hidden; }, helpclose: () => { ui.help.hidden = true; },
|
| 1222 |
restore: restoreAuto, discard: () => { ui.banner.hidden = true; S.pending = null; idbOp("kv", "readwrite", st => st.delete("auto")).catch(() => { }); note("Alte Sitzung verworfen"); },
|
| 1223 |
snap: b => { S.snap = !S.snap; b.classList.toggle("is-on", S.snap); b.setAttribute("aria-pressed", S.snap); },
|
| 1224 |
zoomin: () => zoom(1.4), zoomout: () => zoom(1 / 1.4),
|
| 1225 |
split, copy, paste, dup: duplicate, del, undo, redo: redoFn,
|
| 1226 |
craft: () => openCraft("craft"), transition: () => openCraft("transition"),
|
| 1227 |
import: () => ui.file.click(), take: takeFromGenerate, wav: () => exportMix("wav"), mp3: () => exportMix("mp3"),
|
| 1228 |
+
save: saveProject, open: () => ui.proj.click(), popclose: () => { stopPreview(); ui.pop.hidden = true; },
|
| 1229 |
+
sugg: b => { ui.form.prompt.value = S.sugg[+b.dataset.i]; ui.form.prompt.focus(); },
|
| 1230 |
+
ctxapply: () => { const f = ui.form; if (S.smart?.bpm) f.bpm.value = S.smart.bpm; if (S.smart?.key) f.key.value = S.smart.key; commit(); S.bpm = +f.bpm.value || S.bpm; S.key = f.key.value || S.key; syncInputs(); renderSugg(); draw(); note(`Projekt auf ${S.bpm} BPM · ${S.key} gesetzt`); },
|
| 1231 |
+
takeplay: b => togglePreview(+b.dataset.i, b),
|
| 1232 |
+
takeuse: b => { const T = S.takes, t = T?.list[+b.dataset.i]; if (!t?.a) return; stopPreview(); useTake(t, T.ctxp, T.elLabel); S.takes = null; renderTakes(); ui.pop.hidden = true; renderAll(); },
|
| 1233 |
addtrack: () => { commit(); const t = newTrack(); S.selTrack = t.id; rebuildGraph(); renderAll(); },
|
| 1234 |
applyfx: applyFx,
|
| 1235 |
+
livereset: () => { const t = S.tracks.find(x => x.id === S.selTrack); if (t) { commit(); t.live = { ...LIVE_DEFAULT }; rebuildGraph(); renderLive(); } },
|
| 1236 |
};
|
| 1237 |
function bind() {
|
| 1238 |
const r = ui.root;
|
|
|
|
| 1248 |
else if (m.dataset.m === "craft") { S.selTrack = id; S.range = null; openCraft("craft"); }
|
| 1249 |
else if (m.dataset.m === "rm") { if (S.tracks.length < 2) return; commit(); S.clips = S.clips.filter(c => c.track !== id); S.tracks = S.tracks.filter(x => x.id !== id); S.selTrack = S.tracks[0].id; rebuildGraph(); renderAll(); }
|
| 1250 |
return; }
|
| 1251 |
+
const ins = e.target.closest("[data-ins]"); if (ins) { S.selTrack = ins.closest("[data-t]").dataset.t; $('[data-tab="live"]', r).click(); renderMixer(); note(`Insert ${ins.textContent} · ${S.tracks.find(x => x.id === S.selTrack)?.name} – rechts im Live-FX-Tab`); return; }
|
| 1252 |
+
const strip = e.target.closest(".daw-strip[data-t]"); if (strip && !e.target.closest("input, select, button")) { S.selTrack = strip.dataset.t; renderMixer(); renderLive(); return; }
|
| 1253 |
const head = e.target.closest(".daw-head"); if (head) { S.selTrack = head.dataset.t; renderHeadsSel(); draw(); }
|
| 1254 |
});
|
| 1255 |
r.addEventListener("input", e => {
|
| 1256 |
const el = e.target;
|
| 1257 |
+
if (!el.closest(".daw-pop") && !el.dataset.fxp) { const tag = el.dataset.p || el.dataset.live || el.dataset.clip || el.dataset.k || (el.classList.contains("daw-name") ? "name" : ""); if (tag) commitOnce(`${tag}:${el.closest("[data-t]")?.dataset.t || S.selTrack}:${selectedClips()[0]?.id || ""}`); }
|
| 1258 |
+
if (el.dataset.p) { const t = S.tracks.find(x => x.id === el.closest("[data-t]").dataset.t); t[el.dataset.p] = +el.value; ensureCtx(); rebuildGraph(); if (el.dataset.p === "vol") { const o = el.closest(".daw-strip")?.querySelector(".daw-db"); if (o) o.textContent = fdb(+el.value); } }
|
| 1259 |
else if (el.dataset.live) { const t = S.tracks.find(x => x.id === S.selTrack); t.live[el.dataset.live] = +el.value; el.nextElementSibling.textContent = (+el.value).toFixed(+el.step < 1 ? 2 : 0) + (LIVE_UI.find(x => x[0] === el.dataset.live)[5]); ensureCtx(); rebuildGraph(); }
|
| 1260 |
else if (el.dataset.fxp) el.nextElementSibling.textContent = el.value;
|
| 1261 |
else if (el.dataset.clip) { const c = selectedClips()[0]; if (c) { c[el.dataset.clip] = +el.value; el.nextElementSibling.textContent = (+el.value).toFixed(2); draw(); } }
|
| 1262 |
else if (el.classList.contains("daw-name")) { const t = S.tracks.find(x => x.id === el.closest("[data-t]").dataset.t); t.name = el.value; }
|
| 1263 |
else if (el.dataset.k === "bpm") { S.bpm = clamp(+el.value || 120, 40, 240); draw(); scheduleAutosave(); }
|
| 1264 |
+
else if (el.dataset.k === "mvol") { const o = el.closest(".daw-strip")?.querySelector(".daw-db"); if (o) o.textContent = fdb(+el.value); S.master.vol = +el.value; if (master) master.vol.gain.setTargetAtTime(S.master.vol, ctx.currentTime, 0.02); }
|
| 1265 |
else if (el.dataset.k === "key") S.key = el.value;
|
| 1266 |
});
|
| 1267 |
+
r.addEventListener("change", e => { gest = null; const k = e.target.dataset.k;
|
| 1268 |
+
if (e.target.hasAttribute("data-preset")) { applyTrackPreset(S.tracks.find(x => x.id === (e.target.closest("[data-t]")?.dataset.t || S.selTrack)), e.target.value); return; }
|
| 1269 |
+
if (e.target.name === "preset") applyPreset(); if (e.target.name === "bpm" || e.target.name === "key") renderSugg();
|
| 1270 |
+
if (k === "mvol") $$('[data-k="mvol"]', ui.root).forEach(x => { x.value = S.master.vol; }); if (k === "sig") { S.sig = +e.target.value; draw(); scheduleAutosave(); } else if (k === "grid") { S.grid = e.target.value; S.snap = S.grid !== "off"; note(`Raster: ${e.target.selectedOptions[0].text}`); scheduleAutosave(); } else if (e.target.dataset.p || e.target.dataset.live || e.target.dataset.clip || k === "mvol") scheduleAutosave();
|
| 1271 |
if (e.target.classList.contains("daw-fxsel")) renderFxParams(); if (e.target.name === "element") syncElement(); if (e.target.name === "model") renderLic(S.catalog.elements.find(x => x.id === ui.form.querySelector('input[name="element"]:checked').value)); });
|
| 1272 |
ui.form.addEventListener("submit", submitCraft);
|
| 1273 |
ui.pop.addEventListener("click", e => { if (e.target === ui.pop) ui.pop.hidden = true; });
|
|
|
|
| 1297 |
if (e.key === "?") { e.preventDefault(); ACTIONS.help(); return; }
|
| 1298 |
const map = { " ": () => (S.rec ? stopRecord() : S.playing ? pause() : play()), s: () => (e.shiftKey ? toggleTrack(selT, "solo") : split()), l: () => ACTIONS.loop(), delete: del, backspace: del,
|
| 1299 |
escape: () => { ui.pop.hidden = true; ui.help.hidden = true; closeMenu(); S.sel.clear(); S.range = null; draw(); }, home: ACTIONS.home, m: () => toggleTrack(selT, "mute"), r: toggleRecord, c: () => ACTIONS.metro(),
|
| 1300 |
+
k: () => addMarker(), x: () => toggleMixer(), "+": () => zoom(1.4), "=": () => zoom(1.4), "-": () => zoom(1 / 1.4), f: fit, p: () => openCraft("craft"), t: () => openCraft("transition") };
|
| 1301 |
if (mod && k === "z") { e.preventDefault(); e.shiftKey ? redoFn() : undo(); return; }
|
| 1302 |
if (mod && k === "y") { e.preventDefault(); redoFn(); return; }
|
| 1303 |
if (mod && k === "c") { e.preventDefault(); copy(); return; }
|
|
|
|
| 1315 |
const wake = () => { if (ctx && ctx.state === "suspended") ctx.resume().catch(() => { }); };
|
| 1316 |
document.addEventListener("pointerdown", wake, true); document.addEventListener("keydown", wake, true);
|
| 1317 |
window.__daw = { S, api, play, pause, stop, split, undo, redo: redoFn, copy, paste, renderMix, autosave, addMarker, toggleRecord, stopRecord, stemsFor, fit,
|
| 1318 |
+
get ctx() { return ctx; }, get loudness() { return S.loudness; }, cloud, cloudSave, toggleMixer, truePeak, pruneAssets, exportMix, session: SESSION };
|
| 1319 |
})();
|
studio/daw/analyze.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tempo- und Tonart-Erkennung auf CPU (numpy): Spektralfluss-Autokorrelation + Krumhansl-Profile."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
NOTES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
|
| 8 |
+
_MAJ = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
|
| 9 |
+
_MIN = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _stft_mag(x: np.ndarray, n_fft: int, hop: int) -> np.ndarray:
|
| 13 |
+
if x.size < n_fft:
|
| 14 |
+
x = np.pad(x, (0, n_fft - x.size))
|
| 15 |
+
frames = 1 + (x.size - n_fft) // hop
|
| 16 |
+
idx = np.arange(n_fft)[None, :] + hop * np.arange(frames)[:, None]
|
| 17 |
+
return np.abs(np.fft.rfft(x[idx] * np.hanning(n_fft), axis=1)).astype(np.float32)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def bpm(mono: np.ndarray, sr: int) -> tuple[float | None, float]:
|
| 21 |
+
hop = 512
|
| 22 |
+
mag = _stft_mag(mono, 2048, hop)
|
| 23 |
+
if mag.shape[0] < 16:
|
| 24 |
+
return None, 0.0
|
| 25 |
+
lg = np.log1p(100 * mag)
|
| 26 |
+
flux = np.maximum(0, np.diff(lg, axis=0)).sum(axis=1)
|
| 27 |
+
flux = flux - np.convolve(flux, np.ones(16) / 16, mode="same")
|
| 28 |
+
flux = np.maximum(flux, 0)
|
| 29 |
+
if not flux.any():
|
| 30 |
+
return None, 0.0
|
| 31 |
+
fr = sr / hop
|
| 32 |
+
ac = np.correlate(flux, flux, mode="full")[flux.size - 1:]
|
| 33 |
+
ac = ac / (ac[0] + 1e-9)
|
| 34 |
+
lags = np.arange(len(ac))
|
| 35 |
+
lo, hi = int(fr * 60 / 200), min(len(ac) - 1, int(fr * 60 / 55))
|
| 36 |
+
if hi <= lo + 2:
|
| 37 |
+
return None, 0.0
|
| 38 |
+
cand = lags[lo:hi]
|
| 39 |
+
tempo = 60 * fr / cand
|
| 40 |
+
weight = np.exp(-0.5 * (np.log2(tempo / 120) / 0.9) ** 2)
|
| 41 |
+
score = ac[lo:hi] * weight
|
| 42 |
+
k = int(np.argmax(score))
|
| 43 |
+
lag = cand[k]
|
| 44 |
+
if 0 < k < len(score) - 1: # parabolische Verfeinerung
|
| 45 |
+
a, b, c = score[k - 1], score[k], score[k + 1]
|
| 46 |
+
den = a - 2 * b + c
|
| 47 |
+
lag = lag + (0.5 * (a - c) / den if den else 0)
|
| 48 |
+
t = 60 * fr / lag
|
| 49 |
+
while t < 70:
|
| 50 |
+
t *= 2
|
| 51 |
+
while t > 180:
|
| 52 |
+
t /= 2
|
| 53 |
+
conf = float(np.clip((score[k] - np.median(score)) / (np.max(ac[1:]) + 1e-9), 0, 1))
|
| 54 |
+
return float(round(t)), round(conf, 2)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def key(mono: np.ndarray, sr: int) -> tuple[str | None, float]:
|
| 58 |
+
mag = _stft_mag(mono, 8192, 4096)
|
| 59 |
+
freqs = np.fft.rfftfreq(8192, 1 / sr)
|
| 60 |
+
band = (freqs > 55) & (freqs < 4200)
|
| 61 |
+
pcs = (np.round(12 * np.log2(freqs[band] / 440.0)) + 9) % 12
|
| 62 |
+
energy = (mag[:, band] ** 2).sum(axis=0)
|
| 63 |
+
chroma = np.bincount(pcs.astype(int), weights=energy, minlength=12)
|
| 64 |
+
if chroma.sum() <= 0:
|
| 65 |
+
return None, 0.0
|
| 66 |
+
chroma = chroma / chroma.max()
|
| 67 |
+
scores = []
|
| 68 |
+
for i in range(12):
|
| 69 |
+
scores.append((float(np.corrcoef(chroma, np.roll(_MAJ, i))[0, 1]), f"{NOTES[i]} major"))
|
| 70 |
+
scores.append((float(np.corrcoef(chroma, np.roll(_MIN, i))[0, 1]), f"{NOTES[i]} minor"))
|
| 71 |
+
scores.sort(reverse=True)
|
| 72 |
+
return scores[0][1], round(min(1.0, max(0.0, scores[0][0] - scores[1][0]) * 4), 2)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def analyze(data: np.ndarray, sr: int, max_s: float = 60.0) -> dict:
|
| 76 |
+
mono = np.asarray(data, dtype=np.float32)
|
| 77 |
+
mono = mono.mean(axis=0) if mono.ndim == 2 else mono
|
| 78 |
+
mono = mono[: int(max_s * sr)]
|
| 79 |
+
if mono.size < sr:
|
| 80 |
+
return {"bpm": None, "bpm_conf": 0.0, "key": None, "key_conf": 0.0}
|
| 81 |
+
if sr > 24000: # halbieren reicht für beides und spart CPU
|
| 82 |
+
mono, sr = mono[: mono.size // 2 * 2].reshape(-1, 2).mean(axis=1), sr // 2
|
| 83 |
+
b, bc = bpm(mono, sr)
|
| 84 |
+
k, kc = key(mono, sr)
|
| 85 |
+
return {"bpm": b, "bpm_conf": bc, "key": k, "key_conf": kc}
|
studio/daw/api.py
CHANGED
|
@@ -23,7 +23,7 @@ import numpy as np
|
|
| 23 |
from studio.adapters.base import GenerateRequest
|
| 24 |
from studio.adapters.health import set_visitor_ip_token
|
| 25 |
from studio.adapters.router import AdapterRouter
|
| 26 |
-
from studio.daw import engine, jobs, stems
|
| 27 |
from studio.model_status import is_unusable, model_state
|
| 28 |
from studio.registry import load_registry
|
| 29 |
|
|
@@ -81,7 +81,7 @@ def _model_info(mid: str) -> dict[str, Any]:
|
|
| 81 |
def daw_catalog() -> str:
|
| 82 |
"""Elemente, passende Modelle (mit Lizenz-Badge/Status) und Plugin-Status."""
|
| 83 |
out = {"elements": [], "plugins": engine.plugin_status(), "mock": MOCK,
|
| 84 |
-
"stems": {"available": stems.available(), "max_s": stems.MAX_SECONDS}}
|
| 85 |
for key, el in ELEMENTS.items():
|
| 86 |
out["elements"].append({"id": key, "label": el["label"], "lyrics": bool(el.get("lyrics")),
|
| 87 |
"dur": el["dur"], "loop": el["loop"], "models": [_model_info(m) for m in el["models"]]})
|
|
@@ -230,11 +230,10 @@ def daw_save(project: str, title: str, oauth_token: gr.OAuthToken | None = None,
|
|
| 230 |
from huggingface_hub import HfApi
|
| 231 |
|
| 232 |
user = str(profile.username or "")
|
| 233 |
-
if not
|
| 234 |
raise ValueError("Ungültiger HF-Benutzername.")
|
| 235 |
api = HfApi(token=oauth_token.token)
|
| 236 |
-
repo =
|
| 237 |
-
api.create_repo(repo, repo_type="dataset", private=True, exist_ok=True)
|
| 238 |
api.upload_file(path_or_fileobj=str(dest), path_in_repo=f"projects/{dest.name}", repo_id=repo,
|
| 239 |
repo_type="dataset", commit_message=f"2B-Studio: {name}")
|
| 240 |
result["hf"] = f"https://huggingface.co/datasets/{repo}"
|
|
@@ -283,22 +282,119 @@ def daw_stems(path: str, start: float, end: float) -> str:
|
|
| 283 |
out.append({"stem": name, "label": STEM_LABELS.get(name, name), **info})
|
| 284 |
return out
|
| 285 |
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
|
| 289 |
def daw_job(job_id: str) -> str:
|
| 290 |
job = jobs.get(job_id)
|
| 291 |
if job is None:
|
| 292 |
raise gr.Error("Job unbekannt oder abgelaufen.")
|
| 293 |
-
return json.dumps({k: job[k] for k in ("id", "state", "progress", "msg", "result", "error", "queue")})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
def _prewarm_stems() -> None:
|
| 297 |
if stems.available() and os.environ.get("DAW_STEMS_PREWARM", "1") == "1":
|
| 298 |
def warm():
|
| 299 |
-
time.sleep(
|
| 300 |
try:
|
| 301 |
-
stems.
|
| 302 |
except Exception: # noqa: BLE001
|
| 303 |
pass
|
| 304 |
threading.Thread(target=warm, daemon=True, name="stems-prewarm").start()
|
|
@@ -315,4 +411,8 @@ def register(app: gr.Blocks) -> None:
|
|
| 315 |
gr.api(daw_load, api_name="daw_load", concurrency_limit=2)
|
| 316 |
gr.api(daw_stems, api_name="daw_stems", concurrency_limit=2)
|
| 317 |
gr.api(daw_job, api_name="daw_job", concurrency_limit=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
_prewarm_stems()
|
|
|
|
| 23 |
from studio.adapters.base import GenerateRequest
|
| 24 |
from studio.adapters.health import set_visitor_ip_token
|
| 25 |
from studio.adapters.router import AdapterRouter
|
| 26 |
+
from studio.daw import analyze, engine, jobs, stems
|
| 27 |
from studio.model_status import is_unusable, model_state
|
| 28 |
from studio.registry import load_registry
|
| 29 |
|
|
|
|
| 81 |
def daw_catalog() -> str:
|
| 82 |
"""Elemente, passende Modelle (mit Lizenz-Badge/Status) und Plugin-Status."""
|
| 83 |
out = {"elements": [], "plugins": engine.plugin_status(), "mock": MOCK,
|
| 84 |
+
"stems": {"available": stems.available(), "max_s": stems.MAX_SECONDS, "warm": stems._MODEL is not None}}
|
| 85 |
for key, el in ELEMENTS.items():
|
| 86 |
out["elements"].append({"id": key, "label": el["label"], "lyrics": bool(el.get("lyrics")),
|
| 87 |
"dur": el["dur"], "loop": el["loop"], "models": [_model_info(m) for m in el["models"]]})
|
|
|
|
| 230 |
from huggingface_hub import HfApi
|
| 231 |
|
| 232 |
user = str(profile.username or "")
|
| 233 |
+
if not USER_RX.fullmatch(user):
|
| 234 |
raise ValueError("Ungültiger HF-Benutzername.")
|
| 235 |
api = HfApi(token=oauth_token.token)
|
| 236 |
+
repo = _private_repo(api, user)
|
|
|
|
| 237 |
api.upload_file(path_or_fileobj=str(dest), path_in_repo=f"projects/{dest.name}", repo_id=repo,
|
| 238 |
repo_type="dataset", commit_message=f"2B-Studio: {name}")
|
| 239 |
result["hf"] = f"https://huggingface.co/datasets/{repo}"
|
|
|
|
| 282 |
out.append({"stem": name, "label": STEM_LABELS.get(name, name), **info})
|
| 283 |
return out
|
| 284 |
|
| 285 |
+
secs = seg.shape[1] / sr
|
| 286 |
+
try:
|
| 287 |
+
job = jobs.start("stems", work, est_s=stems.estimate_s(secs), timeout_s=max(240.0, secs * 6 + 120))
|
| 288 |
+
except RuntimeError as error:
|
| 289 |
+
raise gr.Error(str(error)) from None
|
| 290 |
+
return json.dumps({"job": job, "seconds": round(secs, 1), "est_s": round(stems.estimate_s(secs))})
|
| 291 |
|
| 292 |
|
| 293 |
def daw_job(job_id: str) -> str:
|
| 294 |
job = jobs.get(job_id)
|
| 295 |
if job is None:
|
| 296 |
raise gr.Error("Job unbekannt oder abgelaufen.")
|
| 297 |
+
return json.dumps({k: job[k] for k in ("id", "state", "progress", "msg", "result", "error", "queue", "wait_s", "eta_s")})
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def daw_job_cancel(job_id: str) -> str:
|
| 301 |
+
return json.dumps({"cancelled": jobs.cancel(job_id)})
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
_ANALYSIS: dict[str, dict] = {}
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def daw_analyze(path: str, start: float, end: float) -> str:
|
| 308 |
+
"""Tempo und Tonart eines Clip-Bereichs (CPU, max. 60 s)."""
|
| 309 |
+
src = _allowed(path)
|
| 310 |
+
key = f"{src}|{float(start or 0):.2f}|{float(end or 0):.2f}"
|
| 311 |
+
if key not in _ANALYSIS:
|
| 312 |
+
data, sr = engine.load(src)
|
| 313 |
+
s = max(0, int(float(start or 0) * sr))
|
| 314 |
+
e = int(float(end) * sr) if end and float(end) > 0 else data.shape[1]
|
| 315 |
+
_ANALYSIS[key] = analyze.analyze(data[:, s:e], sr)
|
| 316 |
+
if len(_ANALYSIS) > 512:
|
| 317 |
+
_ANALYSIS.pop(next(iter(_ANALYSIS)))
|
| 318 |
+
return json.dumps(_ANALYSIS[key])
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def daw_whoami(profile: gr.OAuthProfile | None = None) -> str:
|
| 322 |
+
user = str(getattr(profile, "username", "") or "") if profile is not None else ""
|
| 323 |
+
ok = bool(user) and os.environ.get("DAW_HF_SAVE", "1") == "1"
|
| 324 |
+
return json.dumps({"user": user or None, "cloud": ok})
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
USER_RX = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}")
|
| 328 |
+
SESSION_RX = re.compile(r"[a-z0-9]{6,32}")
|
| 329 |
+
_UPLOADED: dict[str, set[str]] = {}
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _private_repo(api: Any, user: str) -> str:
|
| 333 |
+
"""Privates Dataset <user>/2b-studio-projects anlegen/prüfen – niemals öffentlich schreiben."""
|
| 334 |
+
if not USER_RX.fullmatch(user):
|
| 335 |
+
raise ValueError("Ungültiger HF-Benutzername.")
|
| 336 |
+
repo = f"{user}/2b-studio-projects"
|
| 337 |
+
api.create_repo(repo, repo_type="dataset", private=True, exist_ok=True)
|
| 338 |
+
info = api.repo_info(repo, repo_type="dataset")
|
| 339 |
+
if not getattr(info, "private", False):
|
| 340 |
+
raise PermissionError(f"{repo} ist öffentlich – aus Sicherheitsgründen wird dort nichts gespeichert.")
|
| 341 |
+
return repo
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def daw_autosave(project: str, title: str, session: str, oauth_token: gr.OAuthToken | None = None,
|
| 345 |
+
profile: gr.OAuthProfile | None = None) -> str:
|
| 346 |
+
"""Cloud-Autosave: Projekt-JSON + noch nicht hochgeladene Audios (inhaltsadressiert) in EINEM Commit
|
| 347 |
+
nach autosave/<session>/ im privaten Dataset. Jede Browser-Sitzung schreibt nur ihren eigenen Ordner."""
|
| 348 |
+
if oauth_token is None or profile is None or os.environ.get("DAW_HF_SAVE", "1") != "1":
|
| 349 |
+
return json.dumps({"ok": False, "reason": "login"})
|
| 350 |
+
if not SESSION_RX.fullmatch(session or ""):
|
| 351 |
+
raise gr.Error("Ungültige Sitzungs-ID.")
|
| 352 |
+
import hashlib
|
| 353 |
+
|
| 354 |
+
from huggingface_hub import CommitOperationAdd, HfApi
|
| 355 |
+
|
| 356 |
+
user = str(profile.username or "")
|
| 357 |
+
api = HfApi(token=oauth_token.token)
|
| 358 |
+
try:
|
| 359 |
+
repo = _private_repo(api, user)
|
| 360 |
+
except Exception as error: # noqa: BLE001
|
| 361 |
+
return json.dumps({"ok": False, "reason": "repo", "error": str(error)[:200]})
|
| 362 |
+
proj = json.loads(project)
|
| 363 |
+
base = f"autosave/{session}"
|
| 364 |
+
known = _UPLOADED.setdefault(repo, set())
|
| 365 |
+
if not known:
|
| 366 |
+
try:
|
| 367 |
+
known.update(f for f in api.list_repo_files(repo, repo_type="dataset") if f.startswith("autosave/"))
|
| 368 |
+
except Exception: # noqa: BLE001
|
| 369 |
+
pass
|
| 370 |
+
ops = []
|
| 371 |
+
for asset in proj.get("assets", []):
|
| 372 |
+
src = _allowed(asset["path"])
|
| 373 |
+
digest = hashlib.sha1(src.read_bytes()).hexdigest()[:20]
|
| 374 |
+
arc = f"{base}/audio/{digest}{src.suffix}"
|
| 375 |
+
asset["path"], asset["sha1"] = arc, digest
|
| 376 |
+
asset.pop("url", None)
|
| 377 |
+
if arc not in known:
|
| 378 |
+
ops.append(CommitOperationAdd(path_in_repo=arc, path_or_fileobj=str(src)))
|
| 379 |
+
proj["saved_at"] = time.time()
|
| 380 |
+
ops.append(CommitOperationAdd(path_in_repo=f"{base}/project.json",
|
| 381 |
+
path_or_fileobj=json.dumps(proj, ensure_ascii=False).encode("utf-8")))
|
| 382 |
+
try:
|
| 383 |
+
info = api.create_commit(repo, operations=ops, repo_type="dataset",
|
| 384 |
+
commit_message=f"2B-Studio Autosave: {_safe_name(title)} ({session})")
|
| 385 |
+
except Exception as error: # noqa: BLE001
|
| 386 |
+
return json.dumps({"ok": False, "reason": "commit", "error": str(error)[:200]})
|
| 387 |
+
known.update(op.path_in_repo for op in ops)
|
| 388 |
+
return json.dumps({"ok": True, "repo": f"https://huggingface.co/datasets/{repo}", "path": base,
|
| 389 |
+
"files": len(ops), "commit": getattr(info, "oid", None), "at": proj["saved_at"]})
|
| 390 |
|
| 391 |
|
| 392 |
def _prewarm_stems() -> None:
|
| 393 |
if stems.available() and os.environ.get("DAW_STEMS_PREWARM", "1") == "1":
|
| 394 |
def warm():
|
| 395 |
+
time.sleep(3)
|
| 396 |
try:
|
| 397 |
+
stems.warm()
|
| 398 |
except Exception: # noqa: BLE001
|
| 399 |
pass
|
| 400 |
threading.Thread(target=warm, daemon=True, name="stems-prewarm").start()
|
|
|
|
| 411 |
gr.api(daw_load, api_name="daw_load", concurrency_limit=2)
|
| 412 |
gr.api(daw_stems, api_name="daw_stems", concurrency_limit=2)
|
| 413 |
gr.api(daw_job, api_name="daw_job", concurrency_limit=None)
|
| 414 |
+
gr.api(daw_job_cancel, api_name="daw_job_cancel", concurrency_limit=None)
|
| 415 |
+
gr.api(daw_analyze, api_name="daw_analyze", concurrency_limit=2)
|
| 416 |
+
gr.api(daw_whoami, api_name="daw_whoami", concurrency_limit=None)
|
| 417 |
+
gr.api(daw_autosave, api_name="daw_autosave", concurrency_limit=2)
|
| 418 |
_prewarm_stems()
|
studio/daw/engine.py
CHANGED
|
@@ -54,9 +54,27 @@ def lufs(data: np.ndarray, sr: int) -> float:
|
|
| 54 |
return float(pyln.Meter(sr).integrated_loudness(data.T.astype(np.float64)))
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def stats(data: np.ndarray, sr: int) -> dict[str, Any]:
|
| 58 |
lv = lufs(data, sr)
|
| 59 |
-
return {"peak_db": round(peak_db(data), 2), "
|
|
|
|
| 60 |
"duration_s": round(data.shape[1] / sr, 3), "sample_rate": sr}
|
| 61 |
|
| 62 |
|
|
|
|
| 54 |
return float(pyln.Meter(sr).integrated_loudness(data.T.astype(np.float64)))
|
| 55 |
|
| 56 |
|
| 57 |
+
def true_peak_db(data: np.ndarray) -> float:
|
| 58 |
+
"""True-Peak nach ITU-R BS.1770-4 (4× Oversampling, polyphaser FIR) in dBTP."""
|
| 59 |
+
if not data.size:
|
| 60 |
+
return -120.0
|
| 61 |
+
from scipy.signal import resample_poly
|
| 62 |
+
|
| 63 |
+
x = np.asarray(data, dtype=np.float64)
|
| 64 |
+
if x.ndim == 1:
|
| 65 |
+
x = x[None, :]
|
| 66 |
+
peak = 0.0
|
| 67 |
+
step = 1 << 20 # blockweise → konstanter Speicher
|
| 68 |
+
for s in range(0, x.shape[1], step):
|
| 69 |
+
blk = x[:, max(0, s - 64):s + step + 64]
|
| 70 |
+
peak = max(peak, float(np.max(np.abs(resample_poly(blk, 4, 1, axis=1, window=("kaiser", 8.0))))))
|
| 71 |
+
return db(max(peak, float(np.max(np.abs(x)))))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
def stats(data: np.ndarray, sr: int) -> dict[str, Any]:
|
| 75 |
lv = lufs(data, sr)
|
| 76 |
+
return {"peak_db": round(peak_db(data), 2), "true_peak_db": round(true_peak_db(data), 2),
|
| 77 |
+
"lufs": None if not math.isfinite(lv) else round(lv, 2),
|
| 78 |
"duration_s": round(data.shape[1] / sr, 3), "sample_rate": sr}
|
| 79 |
|
| 80 |
|
studio/daw/jobs.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
"""Hintergrund-Jobs mit Fortschritt (z. B. Demucs-Stems auf CPU)."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 5 |
import threading
|
| 6 |
import time
|
| 7 |
import traceback
|
|
@@ -12,37 +13,82 @@ from uuid import uuid4
|
|
| 12 |
_JOBS: dict[str, dict[str, Any]] = {}
|
| 13 |
_LOCK = threading.Lock()
|
| 14 |
_CPU = threading.Semaphore(1) # cpu-basic: immer nur ein schwerer Job gleichzeitig
|
|
|
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
with _LOCK:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
_JOBS[job_id] = job
|
| 23 |
-
for k in [k for k, j in _JOBS.items() if time.time() - j["created"] > 3600]:
|
| 24 |
_JOBS.pop(k, None)
|
| 25 |
|
| 26 |
def report(p: float, msg: str) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
job["progress"], job["msg"] = max(0.0, min(1.0, float(p))), msg
|
| 28 |
|
| 29 |
def run() -> None:
|
| 30 |
with _CPU:
|
| 31 |
-
job["
|
|
|
|
|
|
|
|
|
|
| 32 |
try:
|
| 33 |
job["result"] = fn(report)
|
| 34 |
job["state"], job["progress"], job["msg"] = "done", 1.0, "Fertig"
|
|
|
|
|
|
|
| 35 |
except Exception as error: # noqa: BLE001
|
| 36 |
traceback.print_exc()
|
| 37 |
-
job["state"], job["error"] = "error", str(error)[:300]
|
| 38 |
|
| 39 |
threading.Thread(target=run, daemon=True, name=f"job-{kind}-{job_id}").start()
|
| 40 |
return job_id
|
| 41 |
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def get(job_id: str) -> dict[str, Any] | None:
|
| 44 |
job = _JOBS.get(job_id)
|
| 45 |
if job is None:
|
| 46 |
return None
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hintergrund-Jobs mit Fortschritt, Warteschlange, ETA, Timeout und Abbruch (z. B. Demucs-Stems auf CPU)."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
+
import os
|
| 6 |
import threading
|
| 7 |
import time
|
| 8 |
import traceback
|
|
|
|
| 13 |
_JOBS: dict[str, dict[str, Any]] = {}
|
| 14 |
_LOCK = threading.Lock()
|
| 15 |
_CPU = threading.Semaphore(1) # cpu-basic: immer nur ein schwerer Job gleichzeitig
|
| 16 |
+
MAX_QUEUE = int(os.environ.get("DAW_JOBS_MAX_QUEUE", "4"))
|
| 17 |
+
TIMEOUT_S = float(os.environ.get("DAW_JOBS_TIMEOUT_S", "900"))
|
| 18 |
|
| 19 |
|
| 20 |
+
class Cancelled(Exception):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _active() -> list[dict[str, Any]]:
|
| 25 |
+
return sorted((j for j in _JOBS.values() if j["state"] in ("queued", "running")), key=lambda j: j["created"])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def start(kind: str, fn: Callable[[Callable[[float, str], None]], Any], *, est_s: float = 30.0,
|
| 29 |
+
timeout_s: float | None = None) -> str:
|
| 30 |
with _LOCK:
|
| 31 |
+
if len(_active()) >= MAX_QUEUE:
|
| 32 |
+
raise RuntimeError(f"Warteschlange voll ({MAX_QUEUE} Jobs). Bitte in einer Minute erneut versuchen.")
|
| 33 |
+
job_id = uuid4().hex[:12]
|
| 34 |
+
job = {"id": job_id, "kind": kind, "state": "queued", "progress": 0.0, "msg": "In Warteschlange …",
|
| 35 |
+
"result": None, "error": None, "created": time.time(), "started": None, "est_s": float(est_s),
|
| 36 |
+
"timeout_s": float(timeout_s or TIMEOUT_S), "cancel": False}
|
| 37 |
_JOBS[job_id] = job
|
| 38 |
+
for k in [k for k, j in _JOBS.items() if time.time() - j["created"] > 3600 and j["state"] not in ("queued", "running")]:
|
| 39 |
_JOBS.pop(k, None)
|
| 40 |
|
| 41 |
def report(p: float, msg: str) -> None:
|
| 42 |
+
if job["cancel"]:
|
| 43 |
+
raise Cancelled()
|
| 44 |
+
if job["started"] and time.time() - job["started"] > job["timeout_s"]:
|
| 45 |
+
raise TimeoutError(f"Zeitlimit {int(job['timeout_s'])} s überschritten – Clip kürzen oder später erneut versuchen.")
|
| 46 |
job["progress"], job["msg"] = max(0.0, min(1.0, float(p))), msg
|
| 47 |
|
| 48 |
def run() -> None:
|
| 49 |
with _CPU:
|
| 50 |
+
if job["cancel"]:
|
| 51 |
+
job["state"], job["msg"] = "cancelled", "Abgebrochen"
|
| 52 |
+
return
|
| 53 |
+
job["state"], job["started"] = "running", time.time()
|
| 54 |
try:
|
| 55 |
job["result"] = fn(report)
|
| 56 |
job["state"], job["progress"], job["msg"] = "done", 1.0, "Fertig"
|
| 57 |
+
except Cancelled:
|
| 58 |
+
job["state"], job["msg"] = "cancelled", "Abgebrochen"
|
| 59 |
except Exception as error: # noqa: BLE001
|
| 60 |
traceback.print_exc()
|
| 61 |
+
job["state"], job["error"] = "error", (str(error) or type(error).__name__)[:300]
|
| 62 |
|
| 63 |
threading.Thread(target=run, daemon=True, name=f"job-{kind}-{job_id}").start()
|
| 64 |
return job_id
|
| 65 |
|
| 66 |
|
| 67 |
+
def _remaining(j: dict[str, Any]) -> float:
|
| 68 |
+
if j["state"] == "running" and j["started"]:
|
| 69 |
+
el = time.time() - j["started"]
|
| 70 |
+
p = j["progress"]
|
| 71 |
+
return max(1.0, el / p - el) if p > 0.08 else max(1.0, j["est_s"] - el)
|
| 72 |
+
return j["est_s"]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
def get(job_id: str) -> dict[str, Any] | None:
|
| 76 |
job = _JOBS.get(job_id)
|
| 77 |
if job is None:
|
| 78 |
return None
|
| 79 |
+
ahead = [j for j in _active() if j["created"] < job["created"]] if job["state"] == "queued" else []
|
| 80 |
+
out = {k: v for k, v in job.items() if k != "cancel"}
|
| 81 |
+
out["queue"] = len(ahead)
|
| 82 |
+
out["wait_s"] = round(sum(_remaining(j) for j in ahead))
|
| 83 |
+
out["eta_s"] = round(_remaining(job)) if job["state"] in ("queued", "running") else 0
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def cancel(job_id: str) -> bool:
|
| 88 |
+
job = _JOBS.get(job_id)
|
| 89 |
+
if job is None or job["state"] not in ("queued", "running"):
|
| 90 |
+
return False
|
| 91 |
+
job["cancel"] = True
|
| 92 |
+
if job["state"] == "queued":
|
| 93 |
+
job["msg"] = "Wird abgebrochen …"
|
| 94 |
+
return True
|
studio/daw/stems.py
CHANGED
|
@@ -4,11 +4,14 @@ from __future__ import annotations
|
|
| 4 |
|
| 5 |
import os
|
| 6 |
import threading
|
|
|
|
| 7 |
from collections.abc import Callable
|
| 8 |
|
| 9 |
import numpy as np
|
| 10 |
|
| 11 |
MAX_SECONDS = float(os.environ.get("DAW_STEMS_MAX_S", "240"))
|
|
|
|
|
|
|
| 12 |
_MODEL = None
|
| 13 |
_MLOCK = threading.Lock()
|
| 14 |
|
|
@@ -51,13 +54,14 @@ def separate(data: np.ndarray, sr: int, report: Callable[[float, str], None]) ->
|
|
| 51 |
mean, std = float(ref.mean()), float(ref.std()) or 1.0
|
| 52 |
wav = torch.from_numpy(((x - mean) / std).astype(np.float32))
|
| 53 |
n = wav.shape[1]
|
| 54 |
-
block, overlap = int(
|
| 55 |
out = np.zeros((len(model.sources), 2, n), dtype=np.float32)
|
| 56 |
weight = np.zeros(n, dtype=np.float32)
|
| 57 |
starts = list(range(0, max(1, n - overlap), block - overlap)) or [0]
|
| 58 |
for i, s in enumerate(starts):
|
| 59 |
e = min(n, s + block)
|
| 60 |
-
report(0.05 + 0.9 * i / len(starts), f"
|
|
|
|
| 61 |
with torch.no_grad():
|
| 62 |
seg = apply_model(model, wav[None, :, s:e], device="cpu", split=True, overlap=0.1, progress=False)[0]
|
| 63 |
w = np.ones(e - s, dtype=np.float32)
|
|
@@ -66,6 +70,7 @@ def separate(data: np.ndarray, sr: int, report: Callable[[float, str], None]) ->
|
|
| 66 |
w[:f] = np.linspace(0, 1, f)
|
| 67 |
if e < n and f:
|
| 68 |
w[-f:] = np.linspace(1, 0, f)
|
|
|
|
| 69 |
out[:, :, s:e] += seg.numpy() * w
|
| 70 |
weight[s:e] += w
|
| 71 |
if e >= n:
|
|
@@ -80,3 +85,18 @@ def _resample(data: np.ndarray, sr: int, target: int) -> np.ndarray:
|
|
| 80 |
import torch
|
| 81 |
|
| 82 |
return julius.resample_frac(torch.from_numpy(data.astype(np.float32)), sr, target).numpy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
import os
|
| 6 |
import threading
|
| 7 |
+
import time
|
| 8 |
from collections.abc import Callable
|
| 9 |
|
| 10 |
import numpy as np
|
| 11 |
|
| 12 |
MAX_SECONDS = float(os.environ.get("DAW_STEMS_MAX_S", "240"))
|
| 13 |
+
BLOCK_S = float(os.environ.get("DAW_STEMS_BLOCK_S", "12"))
|
| 14 |
+
RATE = {"x": 0.45} # gemessene Sekunden Rechenzeit pro Sekunde Audio (für ETA), wird live nachgeführt
|
| 15 |
_MODEL = None
|
| 16 |
_MLOCK = threading.Lock()
|
| 17 |
|
|
|
|
| 54 |
mean, std = float(ref.mean()), float(ref.std()) or 1.0
|
| 55 |
wav = torch.from_numpy(((x - mean) / std).astype(np.float32))
|
| 56 |
n = wav.shape[1]
|
| 57 |
+
block, overlap = int(BLOCK_S * msr), int(1 * msr)
|
| 58 |
out = np.zeros((len(model.sources), 2, n), dtype=np.float32)
|
| 59 |
weight = np.zeros(n, dtype=np.float32)
|
| 60 |
starts = list(range(0, max(1, n - overlap), block - overlap)) or [0]
|
| 61 |
for i, s in enumerate(starts):
|
| 62 |
e = min(n, s + block)
|
| 63 |
+
report(0.05 + 0.9 * i / len(starts), f"Segment {i + 1}/{len(starts)}")
|
| 64 |
+
t0 = time.time()
|
| 65 |
with torch.no_grad():
|
| 66 |
seg = apply_model(model, wav[None, :, s:e], device="cpu", split=True, overlap=0.1, progress=False)[0]
|
| 67 |
w = np.ones(e - s, dtype=np.float32)
|
|
|
|
| 70 |
w[:f] = np.linspace(0, 1, f)
|
| 71 |
if e < n and f:
|
| 72 |
w[-f:] = np.linspace(1, 0, f)
|
| 73 |
+
RATE["x"] = 0.7 * RATE["x"] + 0.3 * (time.time() - t0) / max(0.5, (e - s) / msr)
|
| 74 |
out[:, :, s:e] += seg.numpy() * w
|
| 75 |
weight[s:e] += w
|
| 76 |
if e >= n:
|
|
|
|
| 85 |
import torch
|
| 86 |
|
| 87 |
return julius.resample_frac(torch.from_numpy(data.astype(np.float32)), sr, target).numpy()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def estimate_s(seconds: float) -> float:
|
| 91 |
+
"""Grobe Laufzeit-Schätzung (inkl. Modell-Laden, falls noch kalt)."""
|
| 92 |
+
return seconds * RATE["x"] + (0 if _MODEL is not None else 12) + 3
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def warm() -> None:
|
| 96 |
+
"""Modell laden und einmal kurz durchrechnen (JIT/Allocator warm)."""
|
| 97 |
+
import torch
|
| 98 |
+
from demucs.apply import apply_model
|
| 99 |
+
|
| 100 |
+
model = _model()
|
| 101 |
+
with torch.no_grad():
|
| 102 |
+
apply_model(model, torch.zeros(1, 2, int(model.samplerate)), device="cpu", split=True, progress=False)
|
tests/__init__.py
ADDED
|
File without changes
|
tests/test_daw_round2.py
CHANGED
|
@@ -17,6 +17,7 @@ def _proj_with_asset():
|
|
| 17 |
|
| 18 |
class _FakeApi:
|
| 19 |
calls: list = []
|
|
|
|
| 20 |
|
| 21 |
def __init__(self, token=None):
|
| 22 |
_FakeApi.calls.append(("init", token))
|
|
@@ -27,11 +28,24 @@ class _FakeApi:
|
|
| 27 |
def upload_file(self, **kw):
|
| 28 |
_FakeApi.calls.append(("upload_file", kw))
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
@pytest.fixture
|
| 32 |
def fake_hf(monkeypatch):
|
| 33 |
import huggingface_hub
|
| 34 |
_FakeApi.calls = []
|
|
|
|
|
|
|
| 35 |
monkeypatch.setattr(huggingface_hub, "HfApi", _FakeApi)
|
| 36 |
monkeypatch.setenv("DAW_HF_SAVE", "1")
|
| 37 |
return _FakeApi.calls
|
|
|
|
| 17 |
|
| 18 |
class _FakeApi:
|
| 19 |
calls: list = []
|
| 20 |
+
private = True
|
| 21 |
|
| 22 |
def __init__(self, token=None):
|
| 23 |
_FakeApi.calls.append(("init", token))
|
|
|
|
| 28 |
def upload_file(self, **kw):
|
| 29 |
_FakeApi.calls.append(("upload_file", kw))
|
| 30 |
|
| 31 |
+
def repo_info(self, repo, **kw):
|
| 32 |
+
_FakeApi.calls.append(("repo_info", repo))
|
| 33 |
+
return types.SimpleNamespace(private=_FakeApi.private)
|
| 34 |
+
|
| 35 |
+
def list_repo_files(self, repo, **kw):
|
| 36 |
+
return []
|
| 37 |
+
|
| 38 |
+
def create_commit(self, repo, operations, **kw):
|
| 39 |
+
_FakeApi.calls.append(("create_commit", repo, [o.path_in_repo for o in operations], kw))
|
| 40 |
+
return types.SimpleNamespace(oid="abc123")
|
| 41 |
+
|
| 42 |
|
| 43 |
@pytest.fixture
|
| 44 |
def fake_hf(monkeypatch):
|
| 45 |
import huggingface_hub
|
| 46 |
_FakeApi.calls = []
|
| 47 |
+
_FakeApi.private = True
|
| 48 |
+
api._UPLOADED.clear()
|
| 49 |
monkeypatch.setattr(huggingface_hub, "HfApi", _FakeApi)
|
| 50 |
monkeypatch.setenv("DAW_HF_SAVE", "1")
|
| 51 |
return _FakeApi.calls
|
tests/test_daw_round3.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
import types
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from studio.daw import analyze, api, engine, jobs
|
| 9 |
+
from tests.test_daw_round2 import _FakeApi, _proj_with_asset, fake_hf # noqa: F401
|
| 10 |
+
|
| 11 |
+
SR = 44100
|
| 12 |
+
TOK = types.SimpleNamespace(token="hf_mocked")
|
| 13 |
+
ROB = types.SimpleNamespace(username="rob-boss")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _wait(jid, states=("done", "error", "cancelled"), n=300):
|
| 17 |
+
for _ in range(n):
|
| 18 |
+
j = jobs.get(jid)
|
| 19 |
+
if j["state"] in states:
|
| 20 |
+
return j
|
| 21 |
+
time.sleep(0.02)
|
| 22 |
+
return jobs.get(jid)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_true_peak_catches_intersample_overs():
|
| 26 |
+
x = (0.99 * np.sin(2 * np.pi * (SR / 4) * np.arange(SR) / SR + 0.7)).astype(np.float32)[None]
|
| 27 |
+
assert engine.peak_db(x) < -2.0 and engine.true_peak_db(x) > -0.3
|
| 28 |
+
assert "true_peak_db" in engine.stats(np.vstack([x[0], x[0]]), SR)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_analyze_bpm_and_key():
|
| 32 |
+
t = np.arange(SR * 12) / SR
|
| 33 |
+
x = np.zeros_like(t)
|
| 34 |
+
for b in np.arange(0, 12, 60 / 128):
|
| 35 |
+
i = int(b * SR)
|
| 36 |
+
n = min(4000, len(x) - i)
|
| 37 |
+
x[i:i + n] += np.sin(2 * np.pi * 60 * np.arange(n) / SR) * np.exp(-np.arange(n) / 800)
|
| 38 |
+
for f in (220, 261.63, 329.63, 110):
|
| 39 |
+
x += 0.15 * np.sin(2 * np.pi * f * t)
|
| 40 |
+
r = analyze.analyze(np.vstack([x, x]), SR)
|
| 41 |
+
assert abs(r["bpm"] - 128) <= 1 and r["key"] == "A minor"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_daw_analyze_endpoint_cached():
|
| 45 |
+
res = json.loads(api.daw_generate("drums", "procedural", "impact", "", "", 4, 120, "", 0, None))
|
| 46 |
+
a = json.loads(api.daw_analyze(res["path"], 0, 0))
|
| 47 |
+
assert set(a) == {"bpm", "bpm_conf", "key", "key_conf"}
|
| 48 |
+
assert json.loads(api.daw_analyze(res["path"], 0, 0)) == a
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_job_cancel_running_and_queued():
|
| 52 |
+
import threading
|
| 53 |
+
gate = threading.Event()
|
| 54 |
+
|
| 55 |
+
def slow(report):
|
| 56 |
+
for i in range(200):
|
| 57 |
+
report(i / 200, f"Segment {i + 1}/200")
|
| 58 |
+
gate.wait(0.01)
|
| 59 |
+
return 1
|
| 60 |
+
j1 = jobs.start("t", slow, est_s=5)
|
| 61 |
+
j2 = jobs.start("t", slow, est_s=5)
|
| 62 |
+
time.sleep(0.1)
|
| 63 |
+
q = jobs.get(j2)
|
| 64 |
+
assert q["state"] == "queued" and q["queue"] == 1 and q["wait_s"] >= 1
|
| 65 |
+
assert jobs.cancel(j2) and jobs.cancel(j1)
|
| 66 |
+
assert _wait(j1)["state"] == "cancelled" and _wait(j2)["state"] == "cancelled"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_job_timeout_message():
|
| 70 |
+
def slow(report):
|
| 71 |
+
for _ in range(100):
|
| 72 |
+
report(0.1, "x")
|
| 73 |
+
time.sleep(0.02)
|
| 74 |
+
j = _wait(jobs.start("t", slow, timeout_s=0.1))
|
| 75 |
+
assert j["state"] == "error" and "Zeitlimit" in j["error"]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_queue_full(monkeypatch):
|
| 79 |
+
monkeypatch.setattr(jobs, "MAX_QUEUE", 0)
|
| 80 |
+
with pytest.raises(RuntimeError, match="Warteschlange voll"):
|
| 81 |
+
jobs.start("t", lambda r: 1)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_cloud_autosave_private_single_commit_and_dedup(fake_hf):
|
| 85 |
+
proj = _proj_with_asset()
|
| 86 |
+
r = json.loads(api.daw_autosave(json.dumps(proj), "Song", "sess01abcd", TOK, ROB))
|
| 87 |
+
assert r["ok"] and r["path"] == "autosave/sess01abcd"
|
| 88 |
+
commit = [c for c in fake_hf if c[0] == "create_commit"][0]
|
| 89 |
+
assert commit[1] == "rob-boss/2b-studio-projects"
|
| 90 |
+
assert "autosave/sess01abcd/project.json" in commit[2] and any(p.startswith("autosave/sess01abcd/audio/") for p in commit[2])
|
| 91 |
+
create = [c for c in fake_hf if c[0] == "create_repo"][0]
|
| 92 |
+
assert create[2]["private"] is True
|
| 93 |
+
r2 = json.loads(api.daw_autosave(json.dumps(proj), "Song", "sess01abcd", TOK, ROB))
|
| 94 |
+
commits = [c for c in fake_hf if c[0] == "create_commit"]
|
| 95 |
+
assert r2["ok"] and commits[1][2] == ["autosave/sess01abcd/project.json"] # Audio nicht erneut hochgeladen
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_cloud_autosave_refuses_public_repo(fake_hf):
|
| 99 |
+
_FakeApi.private = False
|
| 100 |
+
r = json.loads(api.daw_autosave(json.dumps(_proj_with_asset()), "Song", "sess01abcd", TOK, ROB))
|
| 101 |
+
assert not r["ok"] and r["reason"] == "repo" and "öffentlich" in r["error"]
|
| 102 |
+
assert not [c for c in fake_hf if c[0] == "create_commit"]
|
| 103 |
+
s = json.loads(api.daw_save(json.dumps(_proj_with_asset()), "T", TOK, ROB))
|
| 104 |
+
assert s["hf"] is None and "öffentlich" in s["hf_error"]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_cloud_autosave_guards(fake_hf):
|
| 108 |
+
assert json.loads(api.daw_autosave("{}", "x", "sess01abcd", None, None))["reason"] == "login"
|
| 109 |
+
with pytest.raises(Exception):
|
| 110 |
+
api.daw_autosave("{}", "x", "../../etc", TOK, ROB)
|
| 111 |
+
bad = json.loads(api.daw_autosave(json.dumps(_proj_with_asset()), "x", "sess01abcd", TOK, types.SimpleNamespace(username="../x")))
|
| 112 |
+
assert not bad["ok"] and not [c for c in fake_hf if c[0] == "create_commit"]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_whoami():
|
| 116 |
+
assert json.loads(api.daw_whoami(None)) == {"user": None, "cloud": False}
|
| 117 |
+
assert json.loads(api.daw_whoami(ROB))["user"] == "rob-boss"
|