absolution-omega / app /static /studio.js
2Btainment's picture
Remove summed enhance. Keep individual track SFX.
536b543 verified
Raw History Blame Contribute Delete
52 kB
/* Tune-Whisperer (internal: ABSOLUTION Ω) v1.1 — photoreal, unified, local-first studio. No analytics or remote calls. */
"use strict";
(() => {
const $ = (id) => document.getElementById(id);
const ROOT="/api/v1";
const KEY="absolution_omega_studio_active_v1";
const COLORS=["#91ebd3","#f8b974","#be9ef4","#74bfe9","#ef87a1","#d9d079","#74d7f2","#a3ef92","#ff9e7f","#b7bbc9"];
const q=(s)=>encodeURIComponent(s);
const esc=(s)=>String(s??"").replace(/[&<>"']/g,x=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[x]));
const S={id:null,project:null,projects:[],tracks:{},settings:{},peaks:{},plan:[],modelReady:false,rubberband:false,virtualReady:false,busy:false,job:null,mixDirty:true,audioTarget:"original",tab:"workflow",generation:0};
const audio=$("player");
const Live={ctx:null,master:null,nodes:{},buffers:{},pending:{},sources:{},
playing:false,startedAt:0,offset:0,rate:1,duration:0,isolate:null,fileMode:false,raf:0};
const fmt=(n)=>{n=Math.max(0,Math.floor(Number(n)||0));return `${Math.floor(n/3600)?String(Math.floor(n/3600))+":":""}${String(Math.floor(n%3600/60)).padStart(2,"0")}:${String(n%60).padStart(2,"0")}`};
const stemTitle=(id)=>({harmonic:"Harmonik",percussive:"Percussion",residual:"Residual",vocals:"Gesang",drums:"Drums",bass:"Bass",other:"Instrumente",kick_core:"KICK · Bass-Core",bassline_core:"BASSLINE · Bass-Core",noise_difference:"NOISE · Stördifferenz"}[id]||id.replace(/_/g," ").replace(/[-]/g," "));
const role=(id,m)=>id==="noise_difference"?"FREIGEGEBENE DIFFERENZ":id.includes("kick")||id.includes("bassline")?"BASS · DSP-SCHÄTZUNG":m?.role==="base_compensated"?"BASIS · KOMPENSIERT":m?.role==="estimated_percussive"?"DSP-SCHÄTZUNG":m?.role||"AUDIO-STEM";
const json=(obj)=>({headers:{"content-type":"application/json"},body:JSON.stringify(obj)});
const delay=(ms)=>new Promise(resolve=>setTimeout(resolve,ms));
async function req(route,options={}) {
let r;try{r=await fetch(ROOT+route,options)}catch(_){throw Error("Server nicht erreichbar. Bitte Seite neu laden.")}
let data=null;let type=r.headers.get("content-type")||"";
if(type.includes("application/json"))data=await r.json();
if(!r.ok){let e=data?.detail||`HTTP ${r.status}`;if(Array.isArray(e))e=e.map(x=>x.msg).join("; ");throw Error(String(e))}
return data;
}
function note(message,error=false){
const t=$("toast");t.textContent=message;t.className="toast"+(error?" error":"");t.hidden=false;
clearTimeout(note.timer);note.timer=setTimeout(()=>t.hidden=true,6500);
}
const URLFor=(name,preview=true)=>`${ROOT}/projects/${q(S.id)}/audio/${q(name)}${preview?"?preview=true":""}`;
function setLink(id,url){const a=$(id);if(!a)return;if(url){a.href=url;a.removeAttribute("aria-disabled");a.classList.remove("link-disabled");}else{a.removeAttribute("href");a.setAttribute("aria-disabled","true");a.classList.add("link-disabled")}}
function requireSource(){if(!S.project?.asset)throw Error("Bitte zuerst eine Quelle importieren.")}
function markDirty(){
S.mixDirty=true;$("mixStatus").textContent="Live aktiv · Export nicht aktuell";
$("renderMix").disabled=!Object.keys(S.tracks).length||S.busy;
$("previewRender").disabled=true;setLink("downloadRender",null);setLink("exportMix",null);
applyLiveParams();
}
async function loadLibrary(){
const data=await req("/projects");
S.projects=data.projects||[];$("projectCount").textContent=S.projects.length;
renderLibrary();
}
function renderLibrary(){
const text=$("projectSearch").value.toLowerCase().trim();
const list=S.projects.filter(p=>[p.name,p.asset?.filename].some(x=>String(x||"").toLowerCase().includes(text)));
$("projectList").innerHTML=list.length?list.map(p=>`
<button class="project-item ${p.id===S.id?"selected":""}" data-project="${esc(p.id)}" title="${esc(p.asset?.filename||"Projekt ohne Datei")}">
<div class="project-icon">♫</div><span><strong>${esc(p.name)}</strong>
<small>${esc(p.asset?.filename||"Noch keine Quelldatei")}</small>
<small>${p.stem_count||0} Stems · ${p.analysis?.duration_seconds?fmt(p.analysis.duration_seconds):"bereit für Import"}</small></span>
${p.id===S.id?"<i>●</i>":""}
</button>`).join(""):`<p class="quiet">${text?"Keine Treffer.":"Keine Projekte. Importiere deine erste Datei."}</p>`;
}
async function selectProject(id) {
if(S.busy)throw Error("Warte, bis der laufende Auftrag abgeschlossen ist.");
const serial=++S.generation;
const manifest=await req(`/projects/${q(id)}`);
if(serial!==S.generation)return;
const different=S.id!==id;
S.id=id;S.project=manifest;S.plan=(manifest.plan||[]).map(x=>({...x}));
if(different){resetLive();S.peaks={};S.settings={};audio.pause();audio.removeAttribute("src");S.audioTarget="original";}
hideMobile();
const tracks=manifest.unified?.mix_consistent?manifest.unified.stems:(manifest.stems||{});
const names=Object.keys(tracks);
const changed=Object.keys(S.tracks).join("|")!==names.join("|");
S.tracks=tracks;
if(changed){S.settings={};S.peaks={};}
for(const name of names)if(!S.settings[name])S.settings[name]=defaultSettings();
if(different&&manifest.mixer?.settings?.tracks){
for(const [name,s] of Object.entries(manifest.mixer.settings.tracks))if(S.settings[name])S.settings[name]={...S.settings[name],...s};
}
if(different){
$("tempo").value=Math.round((manifest.mixer?.settings?.tempo??1)*100);
$("pitch").value=Number(manifest.mixer?.settings?.pitch_semitones??0);
}
S.mixDirty=!manifest.mixer||changed;
try{localStorage.setItem(KEY,id)}catch(_){}
updateProjectUI();renderFusionSummary();renderLibrary();renderTracks();renderPlan();renderNoise();renderExports();
hideMobile();
const want=["original",...names],pid=id;
await Promise.all(want.map(async name=>{
if(S.peaks[name])return;
try{const res=await req(`/projects/${q(pid)}/wave/${q(name)}?points=480`);
if(S.id===pid){S.peaks[name]=res.samples;redraw()}}
catch(_){/* Some intermediate proxy signals may be temporarily unavailable. */ }
}));
if(S.id===id)redraw();
}
function updateProjectUI(){
const m=S.project,asset=m?.asset,a=m?.analysis||{},names=Object.keys(S.tracks);
$("activeProject").textContent=m?.name||"Kein Projekt ausgewählt";
$("renameProject").disabled=!m;
$("sourceFilename").textContent=asset?.filename||"Noch keine Audiodatei geladen";
$("inspectorSource").textContent=asset?.filename||"der aktiven Datei";
$("workflowSource").textContent=asset?`${asset.filename} · ${fmt(a.duration_seconds)}`:"Noch keine Datei. Der Import erzeugt ein eigenes Projekt.";
$("sourceHash").textContent=asset?.sha256?`SHA256 ${asset.sha256.slice(0,12)}…`:"";
$("sourceMeta").textContent=asset?`${(asset.size_bytes/1024/1024).toFixed(1)} MiB · ${(a.channels||0)} Kanal/Kanäle · Original unverändert`:"Pro Projekt genau eine klar gekennzeichnete Quelldatei.";
$("duration").textContent=asset?fmt(a.duration_seconds):"—";
$("sampleRate").textContent=asset?`${((a.sample_rate||0)/1000).toFixed(1)} kHz`:"—";
$("stemCount").textContent=names.length;$("trackBubble").textContent=names.length;
$("stepSource").textContent=asset?"Geladen":"Offen";
$("stepSeparate").textContent=names.length?`${names.length} Stems`:"Offen";
$("stepMix").textContent=!S.mixDirty&&m?.mixer?"Aktuell":"Offen";
document.querySelectorAll(".journey-step").forEach(step=>{
step.classList.toggle("complete",
(step.dataset.focus==="source"&&!!asset)||
(step.dataset.focus==="separate"&&names.length>0)||
(step.dataset.focus==="export"&&!S.mixDirty&&!!m?.mixer));
});
$("listenOriginal").disabled=!asset;
$("monitorState").textContent=asset?"SOURCE READY":"READY";
$("ruler").innerHTML=`<span>00:00</span><span>${fmt((a.duration_seconds||0)/4)}</span><span>${fmt((a.duration_seconds||0)/2)}</span><span>${fmt((a.duration_seconds||0)*.75)}</span><span>${fmt(a.duration_seconds)}</span>`;
$("consistency").textContent=m?.unified?.mix_consistent?"Mixture Consistency: PASS":names.length?"Basis-Stems vorhanden":"Original bleibt unverändert";
$("consistencyDetail").textContent=m?.unified?.mix_consistent?`Max. Rekonstruktionsfehler ${Number(m.unified.mix_consistency_max_error).toExponential(2)} · Schätzspuren kompensiert`:"Keine automatische Störgeräuschlöschung.";
document.querySelectorAll(".needs-source").forEach(b=>b.disabled=!asset||S.busy);
document.querySelectorAll(".needs-tracks").forEach(b=>b.disabled=!names.length||S.busy);
$("renderMix").disabled=!names.length||S.busy;
$("previewRender").disabled=S.mixDirty||!m?.mixer;
$("mixStatus").textContent=S.mixDirty?"Live aktiv · Export nicht aktuell":"Live aktiv · Export verfügbar";
for(const id of ["tempo","pitch"])$(id).disabled=false;
$("rubberbandInfo").textContent=S.rubberband
?"SFX jeder Spur sind live und im WAV · Pitch-Export über Rubber Band":"SFX jeder Spur sind live hörbar · Export-Pitch braucht Rubber Band";
$("virtualRun").disabled=!asset||!S.virtualReady||a.channels!==2||S.busy;
$("playClean").disabled=!m?.noise?.repair;
$("playDifference").disabled=!m?.noise?.repair;
if(!asset){$("clock").textContent="00:00 / 00:00";}
}
function renderFusionSummary(){
const m=S.project||{},f=m.fusion,node=$("fusionSummary"),lineage=$("fusionLineage");
if(!node||!lineage)return;
if(!f){
node.textContent=m.asset
?"Quelldatei bereit. Ω FUSION analysiert und erzeugt alle lokal verfügbaren Stems."
:"Wähle zunächst eine Audiodatei.";
lineage.innerHTML="";
return;
}
const names=Object.keys(f.stems||{});
const neural=f.method==="demucs";
node.innerHTML=`<b>${esc(f.name)} · ${neural?"KI-Separation":"DSP-Separation"}</b>
<small>${names.length} echte Audio-Tracks · ${Number(f.noise_candidates||0)} Störstellen-Verdachtsfälle ·
${f.mixture_consistent?"Mix-Konsistenz geprüft":"Mix-Konsistenz nicht bestätigt"}</small>
<span class="fusion-status-grid">
<span class="${f.stems?.vocals?"is-ready":"is-pending"}">Gesang: ${f.stems?.vocals?"KI-Spur":"KI benötigt"}</span>
<span class="${f.stems?.kick_core?"is-ready":"is-pending"}">Kick: ${f.stems?.kick_core?"Schätzspur":"Ausstehend"}</span>
<span class="${f.stems?.bassline_core?"is-ready":"is-pending"}">Bassline: ${f.stems?.bassline_core?"Schätzspur":"Ausstehend"}</span>
<span class="${f.stems?.noise_difference?"is-ready":"is-pending"}">Störung: ${f.stems?.noise_difference?"Differenzspur":"Nur Scan"}</span>
</span>`;
const kindText={neural:"KI-QUELLE",dsp_estimate:"DSP-SCHÄTZUNG",approved_repair:"FREIGEGEBENE DIFFERENZ",signal_component:"SIGNALANTEIL"};
const all=Object.entries(f.stems||{});
lineage.innerHTML=`<details><summary>Herkunft aller ${all.length} Spuren anzeigen</summary>
<div class="fusion-origin-list">${all.map(([name,meta])=>`<div class="fusion-origin">
<b>${esc(meta.label||stemTitle(name))}</b><span>${esc(kindText[meta.type]||meta.type||"DSP")}</span>
<small>Entstanden aus: ${esc(meta.derived_from||f.bass_parent?.[name]||f.method)}</small></div>`).join("")}</div></details>
${(f.warnings||[]).length?`<div class="fusion-cautions">${f.warnings.map(x=>`<p>◇ ${esc(x)}</p>`).join("")}</div>`:""}`;
}
function defaultSettings(){return{gain_db:0,pan:0,mute:false,solo:false,highpass_hz:0,lowpass_hz:0,width:1,drive:0,delay_ms:0,delay_mix:0,room:0}}
function renderTracks(){
const entries=Object.entries(S.tracks);
if(!entries.length){$("trackList").innerHTML=`<div class="empty-tracks"><div class="empty-symbol">∿</div><b>${S.project?.asset?"Quelle geladen. Noch keine separierten Spuren.":"Dein Studio wartet auf Audio."}</b>
<p>${S.project?.asset?"Starte Ω FUSION rechts: es erstellt Grundstems, Bass/Kick und scannt Störstellen in einem Durchlauf.":"Importiere eine Datei und bearbeite alle vorhandenen Stems in dieser gemeinsamen Ansicht."}</p><button class="btn btn-primary" data-action="${S.project?.asset?"fusion":"demo"}">${S.project?.asset?"Ω FUSION starten":"Demo laden"}</button></div>`;redraw();return}
$("trackList").innerHTML=entries.map(([name,meta],i)=>{
const s=S.settings[name]||defaultSettings(),col=COLORS[i%COLORS.length];
return `<article class="track ${s.mute?"is-muted":""} ${s.solo?"is-soloed":""}" style="--track-color:${col}" data-stem="${esc(name)}">
<div class="track-head"><div class="track-title"><span class="track-dot"></span><b title="${esc(stemTitle(name))}">${esc(meta?.label||stemTitle(name))}</b><button data-track-action="play" title="Stem einzeln hören">▶</button></div>
<div class="track-type">${esc(role(name,meta))} · STEM ${String(i+1).padStart(2,"0")}</div>
<div class="track-controls"><button class="toggle ${s.mute?"muted":""}" data-track-action="mute" aria-pressed="${!!s.mute}">M</button>
<button class="toggle ${s.solo?"soloed":""}" data-track-action="solo" aria-pressed="${!!s.solo}">S</button>
<input data-param="gain_db" type="range" min="-48" max="12" step=".5" value="${s.gain_db}" aria-label="Lautstärke ${esc(name)}"><output data-out="gain_db">${s.gain_db} dB</output></div>
</div>
<div class="track-middle"><div class="pan-head"><b>L</b><input data-param="pan" type="range" min="-1" max="1" step=".01" value="${s.pan}" aria-label="Stereo-Panorama ${esc(name)}"><b>R</b><output data-out="pan">${s.pan===0?"C":s.pan<0?"L"+Math.round(-s.pan*100):"R"+Math.round(s.pan*100)}</output></div>
<div class="track-wave"><canvas class="track-canvas" data-wave="${esc(name)}" height="80" aria-label="Wellenform ${esc(name)}"></canvas><div class="play-line track-play"></div></div></div>
<div class="sfx-strip" aria-label="SFX ${esc(name)}">
<b>SFX</b>
<label>LOW CUT <output data-out="highpass_hz">${s.highpass_hz?s.highpass_hz+" Hz":"Aus"}</output><input data-param="highpass_hz" type="range" min="0" max="400" step="5" value="${s.highpass_hz||0}" aria-label="Low Cut ${esc(name)}"></label>
<label>HIGH CUT <output data-out="lowpass_hz">${s.lowpass_hz?s.lowpass_hz+" Hz":"Aus"}</output><input data-param="lowpass_hz" type="range" min="0" max="18000" step="100" value="${s.lowpass_hz||0}" aria-label="High Cut ${esc(name)}"></label>
<label>SÄTTIGUNG <output data-out="drive">${Math.round((s.drive||0)*100)} %</output><input data-param="drive" type="range" min="0" max="1" step=".01" value="${s.drive||0}" aria-label="Sättigung ${esc(name)}"></label>
<label>BREITE <output data-out="width">${Math.round((s.width??1)*100)} %</output><input data-param="width" type="range" min="0" max="2" step=".02" value="${s.width??1}" aria-label="Stereo-Breite ${esc(name)}"></label>
<label>ECHO <output data-out="delay_mix">${Math.round((s.delay_mix||0)*100)} %</output><input data-param="delay_mix" type="range" min="0" max="0.55" step=".01" value="${s.delay_mix||0}" aria-label="Echo-Anteil ${esc(name)}"></label>
<label>ZEIT <output data-out="delay_ms">${s.delay_ms?s.delay_ms+" ms":"Aus"}</output><input data-param="delay_ms" type="range" min="0" max="280" step="5" value="${s.delay_ms||0}" aria-label="Echo-Zeit ${esc(name)}"></label>
<label>RAUM <output data-out="room">${Math.round((s.room||0)*100)} %</output><input data-param="room" type="range" min="0" max="0.45" step=".01" value="${s.room||0}" aria-label="Raum ${esc(name)}"></label>
</div></article>`;
}).join("");
redraw();
}
function drawWave(canvas,data,color,opacity=1,baseline=true){
if(!canvas)return;
const width=canvas.clientWidth,height=canvas.clientHeight;
if(!width||!height)return;
const dpr=Math.min(2,window.devicePixelRatio||1);
canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);
const ctx=canvas.getContext("2d");
ctx.setTransform(dpr,0,0,dpr,0,0);
ctx.clearRect(0,0,width,height);
if(baseline){ctx.strokeStyle="#294454";ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(0,height/2);ctx.lineTo(width,height/2);ctx.stroke();
ctx.strokeStyle="#213647";for(let i=1;i<8;i++){const x=width*i/8;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,height);ctx.stroke()}}
if(!data?.length)return;
const n=data.length,bar=width/n;
ctx.globalAlpha=opacity;ctx.fillStyle=color;
for(let i=0;i<n;i++){
const a=Math.max(.01,Math.min(1,Number(data[i])||0)),h=a*height*.46;
ctx.fillRect(Math.floor(i*bar),height/2-h,Math.max(1,Math.ceil(bar*.72)),2*h);
}ctx.globalAlpha=1;
}
function redraw(){
const master=$("masterCanvas"),original=S.peaks.original;
drawWave(master,original,"#5d889c",.45,true);
if(master){
const ctx=master.getContext("2d"),w=master.clientWidth,h=master.clientHeight;
const dpr=Math.min(2,window.devicePixelRatio||1);
ctx.setTransform(dpr,0,0,dpr,0,0);
let index=0;for(const name of Object.keys(S.tracks)){
const samples=S.peaks[name];if(!samples?.length)continue;
const n=samples.length,bar=w/n;
ctx.globalAlpha=.55;ctx.fillStyle=COLORS[index%COLORS.length];
for(let i=0;i<n;i++){
const amplitude=Math.min(1,samples[i])*h*.40;
ctx.fillRect(Math.floor(i*bar),h/2-amplitude,Math.max(1,Math.ceil(bar*.58)),amplitude*2);
}
index++;
}
ctx.globalAlpha=1;
}
document.querySelectorAll("canvas[data-wave]").forEach(canvas=>{
const name=canvas.dataset.wave;const i=Object.keys(S.tracks).indexOf(name);
drawWave(canvas,S.peaks[name],COLORS[(i<0?0:i)%COLORS.length]);
});
paintPlayhead();
}
function liveRate(){
const tempo=Math.max(50,Math.min(200,Number($("tempo")?.value)||100))/100;
const pitch=Math.max(-12,Math.min(12,Number($("pitch")?.value)||0));
return Math.max(0.25,Math.min(4,tempo*Math.pow(2,pitch/12)));
}
function durationSec(){
if(Live.duration>0)return Live.duration;
const a=Number(S.project?.analysis?.duration_seconds);
if(a>0)return a;
if(Number.isFinite(audio.duration)&&audio.duration>0)return audio.duration;
return 1;
}
function nowTime(){
if(Live.playing&&Live.ctx&&!Live.fileMode)
return Math.min(durationSec(),Math.max(0,Live.offset+(Live.ctx.currentTime-Live.startedAt)*Live.rate));
if(Live.fileMode&&audio.src&&Number.isFinite(audio.currentTime))return audio.currentTime;
return Live.offset||0;
}
function paintPlayhead(){
const d=durationSec(),t=nowTime(),fraction=Math.min(1,Math.max(0,t/d));
const pct=(fraction*100).toFixed(4)+"%";
const line=$("overviewPlay");
if(line){line.style.left=pct;line.style.transform="translateX(-50%)"}
const stage=$("waveStage");
if(stage)stage.classList.toggle("is-playing",!!(Live.playing&&!Live.fileMode));
document.querySelectorAll(".track-play").forEach(el=>{el.style.left=pct;el.style.transform="translateX(-50%)"});
const seek=$("seek");if(seek)seek.value=Math.round(fraction*1000);
const clock=$("clock");if(clock)clock.textContent=`${fmt(t)} / ${fmt(d)}`;
if(Live.playing&&!Live.fileMode){
if(t>=d-0.03){stopLive(true);return}
Live.raf=requestAnimationFrame(paintPlayhead);
}
}
function resetLive(){
stopLive(true);
Live.nodes={};Live.buffers={};Live.pending={};Live.sources={};Live.duration=0;Live.isolate=null;
}
function ensureCtx(){
if(!Live.ctx){
const AC=window.AudioContext||window.webkitAudioContext;
if(!AC)throw Error("Web Audio nicht verfügbar");
Live.ctx=new AC();
Live.master=Live.ctx.createGain();
Live.master.connect(Live.ctx.destination);
}
return Live.ctx.resume();
}
function driveCurve(amount){
const n=2048,curve=new Float32Array(n),k=1+Math.max(0,amount)*6;
for(let i=0;i<n;i++){const x=i*2/n-1;curve[i]=Math.tanh(x*k)/Math.tanh(k)}
return curve;
}
function createWidth(ctx){
const input=ctx.createGain();
const splitter=ctx.createChannelSplitter(2);
splitter.channelCount=2;splitter.channelCountMode="explicit";splitter.channelInterpretation="speakers";
const merger=ctx.createChannelMerger(2);
const l2m=ctx.createGain(),r2m=ctx.createGain(),l2s=ctx.createGain(),r2s=ctx.createGain();
l2m.gain.value=0.5;r2m.gain.value=0.5;l2s.gain.value=0.5;r2s.gain.value=-0.5;
const mid=ctx.createGain(),side=ctx.createGain();side.gain.value=1;
const midL=ctx.createGain(),midR=ctx.createGain(),sideL=ctx.createGain(),sideR=ctx.createGain();
midL.gain.value=1;midR.gain.value=1;sideL.gain.value=1;sideR.gain.value=-1;
input.connect(splitter);
splitter.connect(l2m,0);splitter.connect(l2s,0);
splitter.connect(r2m,1);splitter.connect(r2s,1);
l2m.connect(mid);r2m.connect(mid);l2s.connect(side);r2s.connect(side);
mid.connect(midL);mid.connect(midR);side.connect(sideL);side.connect(sideR);
midL.connect(merger,0,0);sideL.connect(merger,0,0);
midR.connect(merger,0,1);sideR.connect(merger,0,1);
return {input,output:merger,side};
}
function chainFor(name){
if(Live.nodes[name])return Live.nodes[name];
const ctx=Live.ctx;
const hp=ctx.createBiquadFilter();hp.type="highpass";hp.frequency.value=20;
const lp=ctx.createBiquadFilter();lp.type="lowpass";lp.frequency.value=Math.max(1000,ctx.sampleRate/2-80);
const shaper=ctx.createWaveShaper();shaper.oversample="2x";
const width=createWidth(ctx);
const pan=ctx.createStereoPanner();
const dry=ctx.createGain();
const echo=ctx.createDelay(0.4);
const echoGain=ctx.createGain();echoGain.gain.value=0;
const roomA=ctx.createDelay(0.2),roomB=ctx.createDelay(0.2),roomC=ctx.createDelay(0.2);
roomA.delayTime.value=0.029;roomB.delayTime.value=0.047;roomC.delayTime.value=0.071;
const ra=ctx.createGain(),rb=ctx.createGain(),rc=ctx.createGain();
ra.gain.value=0.42;rb.gain.value=0.28;rc.gain.value=0.16;
const roomGain=ctx.createGain();roomGain.gain.value=0;
const sum=ctx.createGain();
const gain=ctx.createGain();
hp.connect(lp);lp.connect(shaper);shaper.connect(width.input);width.output.connect(pan);
pan.connect(dry);dry.connect(sum);
pan.connect(echo);echo.connect(echoGain);echoGain.connect(sum);
pan.connect(roomA);roomA.connect(ra);ra.connect(roomGain);
pan.connect(roomB);roomB.connect(rb);rb.connect(roomGain);
pan.connect(roomC);roomC.connect(rc);rc.connect(roomGain);
roomGain.connect(sum);sum.connect(gain);gain.connect(Live.master);
Live.nodes[name]={hp,lp,shaper,width,pan,echo,echoGain,roomGain,gain};
return Live.nodes[name];
}
function audibleGain(name){
const s=S.settings[name]||defaultSettings();
const names=Object.keys(S.tracks);
if(Live.isolate)return name===Live.isolate&&!s.mute?Math.pow(10,Number(s.gain_db||0)/20):0;
const anySolo=names.some(n=>(S.settings[n]||{}).solo);
if(s.mute||(anySolo&&!s.solo))return 0;
return Math.pow(10,Number(s.gain_db||0)/20);
}
function applyLiveParams(){
if(!Live.ctx){
document.querySelectorAll(".track[data-stem]").forEach(row=>{
const name=row.dataset.stem,s=S.settings[name]||defaultSettings();
const names=Object.keys(S.tracks),anySolo=names.some(n=>(S.settings[n]||{}).solo);
row.classList.toggle("is-muted",!!s.mute||(anySolo&&!s.solo));
row.classList.toggle("is-soloed",!!s.solo);
});
const pill=$("livePill");if(pill)pill.classList.toggle("is-playing",false);
return;
}
const nyquist=Math.max(1000,Live.ctx.sampleRate/2-80);
for(const name of Object.keys(S.tracks)){
const s=S.settings[name]||defaultSettings();
const n=Live.nodes[name];if(!n)continue;
const now=Live.ctx.currentTime;
n.gain.gain.setTargetAtTime(audibleGain(name),now,0.02);
n.pan.pan.setTargetAtTime(Math.max(-1,Math.min(1,Number(s.pan)||0)),now,0.02);
n.hp.frequency.value=s.highpass_hz>0?Number(s.highpass_hz):20;
n.lp.frequency.value=s.lowpass_hz>0?Number(s.lowpass_hz):nyquist;
n.shaper.curve=s.drive>0.01?driveCurve(Number(s.drive)):null;
if(n.width)n.width.side.gain.setTargetAtTime(Math.max(0,Math.min(2,Number(s.width??1))),now,0.02);
const echoMix=Math.max(0,Math.min(0.55,Number(s.delay_mix)||0));
const echoMs=Math.max(0,Math.min(280,Number(s.delay_ms)||0));
if(n.echo)n.echo.delayTime.setTargetAtTime(echoMs/1000,now,0.02);
if(n.echoGain)n.echoGain.gain.setTargetAtTime(echoMs>0?echoMix:0,now,0.02);
if(n.roomGain)n.roomGain.gain.setTargetAtTime(Math.max(0,Math.min(0.45,Number(s.room)||0)),now,0.02);
}
if(Live.playing&&!Live.fileMode){
const next=liveRate();
if(Math.abs(next-Live.rate)>1e-4){
Live.offset=nowTime();Live.startedAt=Live.ctx.currentTime;Live.rate=next;
}
Object.values(Live.sources).forEach(src=>{try{src.playbackRate.value=Live.rate}catch(_){}});
}
document.querySelectorAll(".track[data-stem]").forEach(row=>{
const name=row.dataset.stem,s=S.settings[name]||defaultSettings();
const names=Object.keys(S.tracks),anySolo=names.some(n=>(S.settings[n]||{}).solo);
row.classList.toggle("is-muted",!!s.mute||(anySolo&&!s.solo));
row.classList.toggle("is-soloed",!!s.solo);
});
const pill=$("livePill");if(pill)pill.classList.toggle("is-playing",!!Live.playing&&!Live.fileMode);
if($("monitorState")&&S.project?.asset)$("monitorState").textContent=Live.playing?"LIVE PLAY":"SOURCE READY";
}
async function decodeStem(name){
const url=URLFor(name==="__original__"?"original":name,true);
if(Live.buffers[url])return Live.buffers[url];
if(Live.pending[url])return Live.pending[url];
Live.pending[url]=(async()=>{
const r=await fetch(url);if(!r.ok)throw Error("Spur nicht ladbar: "+name);
const raw=await r.arrayBuffer();
const buf=await Live.ctx.decodeAudioData(raw.slice(0));
Live.buffers[url]=buf;return buf;
})();
try{return await Live.pending[url]}finally{delete Live.pending[url]}
}
function stopSources(){
for(const src of Object.values(Live.sources)){try{src.onended=null;src.stop()}catch(_){}}
Live.sources={};
}
function stopLive(reset){
if(Live.raf){cancelAnimationFrame(Live.raf);Live.raf=0}
const t=nowTime();
Live.playing=false;
stopSources();
if(reset)Live.offset=0;else Live.offset=t;
audio.pause();
Live.fileMode=false;
const btn=$("playPause");if(btn)btn.textContent="▶";
applyLiveParams();
paintPlayhead();
}
function startSources(offset){
stopSources();
const names=Live.isolate?[Live.isolate]:(Object.keys(S.tracks).length?Object.keys(S.tracks):["__original__"]);
const ctx=Live.ctx;
Live.rate=liveRate();
Live.startedAt=ctx.currentTime;
Live.offset=Math.max(0,offset||0);
let maxDur=0;
for(const name of names){
const buf=Live.buffers[URLFor(name==="__original__"?"original":name,true)];
if(!buf)continue;
maxDur=Math.max(maxDur,buf.duration);
const src=ctx.createBufferSource();
src.buffer=buf;
src.playbackRate.value=Live.rate;
if(name==="__original__"){
if(!Live.nodes.__original__){
const g=ctx.createGain();g.connect(Live.master);Live.nodes.__original__={gain:g};
}
src.connect(Live.nodes.__original__.gain);
}else{
src.connect(chainFor(name).hp);
}
const off=Math.min(Math.max(0,Live.offset),Math.max(0,buf.duration-0.01));
if(off>=buf.duration)continue;
src.start(ctx.currentTime,off);
Live.sources[name]=src;
}
Live.duration=maxDur||durationSec();
applyLiveParams();
}
async function startTransport(offset){
requireSource();
await ensureCtx();
Live.fileMode=false;
audio.pause();
const want=Live.isolate?[Live.isolate]:(Object.keys(S.tracks).length?Object.keys(S.tracks):["__original__"]);
$("nowPlaying").textContent=Live.isolate?`Live · ${stemTitle(Live.isolate)}`:`Live-Mixer · ${S.project.name}`;
const loaded=await Promise.all(want.map(async n=>{
try{await decodeStem(n==="__original__"?"__original__":n);return n}
catch(_){return null}
}));
if(!loaded.some(Boolean))throw Error("Keine hörbare Spur geladen.");
startSources(offset??Live.offset);
Live.playing=true;
$("playPause").textContent="Ⅱ";
applyLiveParams();
paintPlayhead();
}
function seekTransport(t){
const pos=Math.min(durationSec(),Math.max(0,t));
if(Live.fileMode){if(audio.src)audio.currentTime=pos;paintPlayhead();return}
Live.offset=pos;
if(Live.playing)startSources(pos);
else paintPlayhead();
}
function toggleTransport(){
if(Live.fileMode){
if(!audio.src){startTransport(0).catch(e=>note(e.message,true));return}
if(audio.paused)audio.play().catch(()=>note("Wiedergabe fehlgeschlagen.",true));
else audio.pause();
return;
}
if(Live.playing){stopLive(false);return}
startTransport(Live.offset).catch(e=>note(e.message,true));
}
function player(name="original",kind="stem"){
requireSource();
if(kind==="mix"||kind==="noise"){
stopLive(false);
Live.fileMode=true;Live.playing=false;
let url,label;
if(kind==="mix"){url=`${ROOT}/projects/${q(S.id)}/mixer/audio`;label="Mix-Export";}
else{url=`${ROOT}/projects/${q(S.id)}/noise/audio/${q(name)}?preview=true`;label=`NOISE ${name}`;}
if(S.audioTarget!==url){audio.src=url;S.audioTarget=url;}
$("nowPlaying").textContent=`Player: ${label} · Projekt ${S.project.name}`;
audio.play().catch(()=>note("Audio-Wiedergabe fehlgeschlagen. Bitte Dateien/Backend prüfen.",true));
$("playPause").textContent="Ⅱ";
return;
}
Live.isolate=(name&&name!=="original")?name:null;
startTransport(Live.offset).catch(e=>note(e.message,true));
}
function renderPlan(){
const inv=new Map((S.project?.inventory?.detections||[]).map(x=>[x.id,x]));
$("planItems").innerHTML=S.plan.length?S.plan.map((item,i)=>`<div class="plan-row" data-index="${i}">
<input type="checkbox" class="plan-enabled" ${item.enabled?"checked":""} aria-label="Ziel aktivieren">
<input type="text" class="plan-label" maxlength="100" value="${esc(item.label)}" aria-label="Ziel umbenennen">
${inv.has(item.id)?`<small>${Math.round(inv.get(item.id).score*100)}*</small>`:""}
<button class="plan-remove" title="Entfernen">×</button></div>`).join(""):`<p class="quiet">Noch keine KI-Hypothesen. Starte eine Vorinventur oder ergänze ein eigenes Ziel.</p>`;
$("planReport").textContent=S.project?.omnistem?.compiled?.targets?
`${S.project.omnistem.compiled.ready} verfügbare Ziele · ${S.project.omnistem.compiled.blocked} nicht ausführbar`:
"Die Mini-KI ermittelt Vermutungen. Erst die Plan-Prüfung zeigt, welche Stems möglich sind.";
}
function collectPlan(){
document.querySelectorAll("#planItems .plan-row").forEach(row=>{
const item=S.plan[Number(row.dataset.index)];if(!item)return;
item.enabled=row.querySelector(".plan-enabled").checked;
item.label=row.querySelector(".plan-label").value.trim().slice(0,100)||"Unbenannt";
});
}
async function savePlan(){
collectPlan();requireSource();
return req(`/projects/${q(S.id)}/plan`,{method:"PUT",...json({tracks:S.plan})});
}
function renderNoise(){
const scan=S.project?.noise?.scan,repair=S.project?.noise?.repair;
$("noiseSummary").textContent=scan?`${scan.event_count} unbestätigte Klickkandidaten · Scan verändert keine Audiodaten`:"Noch kein Scan. Nichts wurde entfernt.";
$("noiseEvents").innerHTML=(scan?.events||[]).slice(0,160).map(e=>`<label class="noise-event"><input type="checkbox" value="${Number(e.sample)}"><span>${Number(e.time_seconds).toFixed(3)} s · Sample ${Number(e.sample)} · UNGEWISS</span><button type="button" data-preview-noise="${Number(e.time_seconds)}" title="Original in der Nähe hören">▶</button></label>`).join("");
$("repairSelected").disabled=!scan?.events?.length||S.busy;
}
function renderExports(){
const m=S.project,asset=m?.asset;
setLink("exportOriginal",asset?URLFor("original",false):null);
setLink("exportStems",Object.keys(S.tracks).length?`${ROOT}/projects/${q(S.id)}/export`:null);
setLink("exportBass",m?.bass?`${ROOT}/projects/${q(S.id)}/bass/export`:null);
setLink("exportNoise",m?.noise?.repair?`${ROOT}/projects/${q(S.id)}/noise/export`:null);
setLink("exportMix",(!S.mixDirty&&m?.mixer)?`${ROOT}/projects/${q(S.id)}/mixer/audio`:null);
setLink("downloadRender",(!S.mixDirty&&m?.mixer)?`${ROOT}/projects/${q(S.id)}/mixer/audio`:null);
setLink("virtualDownload",m?.virtualbass?`${ROOT}/projects/${q(S.id)}/virtualbass/audio`:null);
const a=m?.analysis||{},graph=m?.unified,sep=m?.separation,noise=m?.noise;
const values=[["Quelldatei",asset?.filename||"—"],["SHA256",asset?.sha256||"—"],
["Eingangspegel",Number.isFinite(a.peak_dbfs)?a.peak_dbfs+" dBFS":"—"],
["Kanalzahl",a.channels||"—"],["Separation",sep?.method||"nicht durchgeführt"],
["Spuren",Object.keys(S.tracks).length],["Stem-Graph",graph?(graph.mix_consistent?"Rekonstruktion geprüft":"Ungeprüft"):"Noch kein Graph"],
["Klickverdacht",noise?.scan?.event_count??"Nicht gescannt"],["Störspur",noise?.repair?"Bestätigte Reparatur":"Keine"],
["Render",m?.mixer?.result?.peak_dbfs!==undefined?m.mixer.result.peak_dbfs+" dBFS":"Nicht gerendert"]];
$("diagnostics").innerHTML=values.map(([k,v])=>`<div class="diag-row"><span>${esc(k)}</span><b>${esc(v)}</b></div>`).join("");
}
async function jobWait(job,label){
S.busy=true;S.job=job;$("jobLamp").style.background="#ffd88b";lockButtons(true);
const currentId=S.id;
try{
while(true){
await delay(450);
const j=await req(`/jobs/${q(job.id)}`);
$("jobLabel").textContent=j.stage?`${label} · ${j.stage}`:label;$("jobFill").style.width=`${Math.max(0,Math.min(100,j.progress||0))}%`;
$("jobDetails").textContent=`${j.status==="queued"?"Warteschlange":j.status==="running"?"Verarbeitung":"Abschluss"} · ${j.progress||0} %${j.stage?" · "+j.stage:""}`;
if(j.status==="failed")throw Error(j.error||"Auftrag fehlgeschlagen");
if(j.status==="done")break;
}
const fresh=await req(`/projects/${q(currentId)}`);
S.busy=false;S.job=null;await selectProject(currentId);
$("jobLamp").style.background="#77f2c2";$("jobLabel").textContent=label+" · Fertig";$("jobDetails").textContent="Ergebnis im selben Studio verfügbar.";
}finally{S.busy=false;S.job=null;lockButtons(false);updateProjectUI()}
}
function lockButtons(locked){
document.querySelectorAll("[data-action], #virtualRun,#repairSelected,#renderMix,#importTop,#newProject,#importInPanel,#openLibrary,#listenOriginal").forEach(el=>el.disabled=locked);
}
async function action(name){
if(S.busy)return;
try{
if(name==="demo"){await importDemo();return}
if(name==="fusion"){
requireSource();
const mode=$("fusionMode").value;
if(mode==="neural"&&!S.modelReady)throw Error("Für Vocals und echte Demucs-Bassstems zuerst lokale KI-Modellgewichte installieren.");
await jobWait(await req("/jobs/fusion",{method:"POST",...json({
project_id:S.id,mode,include_event_proxies:true,scan_noise:true
})}),"Ω FUSION");
note("Ω FUSION abgeschlossen. Herkunft und Qualität der Spuren sind im Studio dokumentiert.");
}else if(name==="inventory"){
requireSource();setStatus("Mini-KI-Vorinventur");
const data=await req(`/projects/${q(S.id)}/inventory`,{method:"POST"});
S.plan=data.plan||[];S.project.inventory=data.inventory;S.project.plan=S.plan;
renderPlan();showTab("plan");note("Klanghypothesen erstellt. Bitte Vorschläge prüfen.");
}else if(name==="separate"){
requireSource();
const model=$("separationModel").value;
await jobWait(await req("/jobs/separate",{method:"POST",...json({project_id:S.id,model})}),"Quellen trennen");
note("Separation abgeschlossen: echte Signalspuren in der Timeline.");
}else if(name==="bass"){
requireSource();
const params={project_id:S.id,source_mode:$("bassSource").value,crossover_hz:Number($("bassCutoff").value),
kick_gain_db:Number($("kickGain").value),bass_gain_db:Number($("bassGain").value),
sub_gain_db:Number($("subGain").value),harmonics:Number($("harmonics").value)/100,
lowcut_hz:Number($("bassLowcut").value),mono_below_hz:Number($("monoBelow").value),
wet:Number($("bassWet").value)/100};
await jobWait(await req("/jobs/bass",{method:"POST",...json(params)}),"Kick/Bassline erzeugen");
note("Kick und Bassline sind als kompensierte Stems eingebunden.");
}else if(name==="scan"){
requireSource();await jobWait(await req("/jobs/noise/scan",{method:"POST",...json({project_id:S.id})}),"Störverdacht analysieren");
note("Scan abgeschlossen: nur Vermutungen, keine automatische Entfernung.");
}else if(name==="unify"){
requireSource();await jobWait(await req(`/jobs/unify?project_id=${q(S.id)}`,{method:"POST"}),"Spurgraph aktualisieren");
}else if(name==="plan-preview"){
await savePlan();const report=await req(`/projects/${q(S.id)}/omnistem/plan`);
$("planReport").innerHTML=`<b>${report.ready||0}/${report.requested||0} technisch verfügbar · ${report.blocked||0} blockiert</b>`+
(report.targets||[]).map(t=>`<div class="diag-row"><span>${esc(t.label)}</span><b class="${t.status==="blocked"?"plan-blocked":"plan-ready"}">${esc(t.status==="blocked"?"NICHT VERFÜGBAR":t.status==="estimated_dsp"?"DSP-PROXY":"VORHANDEN")}</b></div>`).join("");
}else if(name==="plan-run"){
await savePlan();await jobWait(await req(`/projects/${q(S.id)}/omnistem/run`,{method:"POST"}),"OMNISTEM-Plan ausführen");
note("Plan ausgeführt. Nur wirklich erzeugte Stems wurden ergänzt.");
}
}catch(err){note(err.message,true);$("jobLabel").textContent="Fehler: "+err.message}
}
function setStatus(message){$("jobLabel").textContent=message;$("jobDetails").textContent="Verarbeitung auf dem Server · bitte warten …"}
async function importFile(file){
if(S.busy)return;
if(!file)return;
const name=file.name.slice(0,80).replace(/\.[^.]+$/,"")||"Neuer Track";
try{
S.busy=true;lockButtons(true);setStatus(`Importiere ${file.name}`);
const created=await req("/projects",{method:"POST",...json({name})});
const body=new FormData();body.append("project_id",created.id);body.append("file",file,file.name);
await req("/assets",{method:"POST",body});
S.busy=false;await loadLibrary();await selectProject(created.id);
note(`Datei "${file.name}" geladen — neues, eindeutiges Projekt erstellt.`);
}catch(e){note("Import: "+e.message,true);try{await loadLibrary()}catch(_){}}
finally{S.busy=false;lockButtons(false);updateProjectUI();$("fileInput").value="";}
}
async function importDemo(){
if(S.busy)return;
try{
setStatus("Lade synthetische Demo …");
const response=await fetch(`${ROOT}/demo`);
if(!response.ok)throw Error("Demo nicht verfügbar");
const blob=await response.blob();
await importFile(new File([blob],"TUNE-WHISPERER_DEMO.wav",{type:"audio/wav"}));
}catch(e){note(e.message,true)}
}
async function virtualBass(){
try{
requireSource();
const payload={project_id:S.id,cutoff_hz:Number($("virtualCutoff").value),strength:Number($("virtualStrength").value)};
await jobWait(await req("/jobs/bass/virtual",{method:"POST",...json(payload)}),"Virtual Bass 2.1 exportieren");
note("Virtual Bass 2.1 WAV bereit zum Herunterladen.");
}catch(e){note(e.message,true)}
}
async function repairNoise(){
try{
requireSource();
const samples=[...$("noiseEvents").querySelectorAll("input:checked")].map(x=>Number(x.value));
if(!samples.length)throw Error("Wähle zuerst einzelne Klickkandidaten.");
if(!confirm(`${samples.length} ausgewählte Klickstelle(n) reparieren? Auch musikalische Transienten könnten betroffen sein. Die entnommene Differenz bleibt als hörbare Stem erhalten.`))return;
await jobWait(await req("/jobs/noise/repair",{method:"POST",...json({project_id:S.id,approved_samples:samples,strength:Number($("noiseStrength").value)/100})}),"Gezielte Klick-Reparatur");
note("Reparatur durchgeführt. NOISE-Stem standardmäßig hörbar, erst Mute entfernt sie im Mix.");
}catch(e){note(e.message,true)}
}
async function renderMix(){
try{
if(!Object.keys(S.tracks).length)throw Error("Erst Stems erzeugen.");
S.mixDirty=true;renderExports();
await jobWait(await req("/jobs/mix",{method:"POST",...json({
project_id:S.id,tracks:S.settings,tempo:Number($("tempo").value)/100,
pitch_semitones:Number($("pitch").value)})}),"Mix mit den Spur-SFX berechnen");
S.mixDirty=false;$("mixStatus").textContent="Render aktuell";
$("previewRender").disabled=false;renderExports();updateProjectUI();
note("Mix gerendert. WAV und Hörprobe verfügbar.");
}catch(e){note(e.message,true)}
}
function showTab(id){
S.tab=id;document.querySelectorAll("[data-tab]").forEach(b=>{
b.classList.toggle("chosen",b.dataset.tab===id);b.setAttribute("aria-selected",String(b.dataset.tab===id))});
document.querySelectorAll(".tabcontent").forEach(e=>e.hidden=e.id!==`tab-${id}`);
}
function hideMobile(){$("library").classList.remove("open");$("libraryOverlay").hidden=true;$("library").setAttribute("aria-hidden","true")}
function showMobile(){$("library").classList.add("open");$("libraryOverlay").hidden=false;$("library").setAttribute("aria-hidden","false")}
function bind(){
$("projectSearch").addEventListener("input",renderLibrary);
$("projectList").addEventListener("click",async e=>{
const btn=e.target.closest("[data-project]");if(!btn)return;
try{await selectProject(btn.dataset.project)}catch(err){note(err.message,true)}
});
for(const id of ["newProject","importTop","importInPanel"])$(id).addEventListener("click",()=>$("fileInput").click());
$("fileInput").addEventListener("change",e=>importFile(e.target.files[0]));
const emptyDemo=$("emptyDemo");if(emptyDemo)emptyDemo.addEventListener("click",importDemo);
$("demoInPanel").addEventListener("click",importDemo);
$("renameProject").addEventListener("click",async ()=>{
if(!S.id)return;const name=prompt("Projekt umbenennen:",S.project.name);if(name===null)return;
try{const value=name.trim();if(!value)throw Error("Name darf nicht leer sein.");
await req(`/projects/${q(S.id)}`,{method:"PATCH",...json({name:value})});
S.project.name=value;await loadLibrary();updateProjectUI();note("Projekt umbenannt.");
}catch(e){note(e.message,true)}
});
$("openLibrary").addEventListener("click",showMobile);
$("mobileMenu").addEventListener("click",showMobile);
$("libraryOverlay").addEventListener("click",hideMobile);
$("libraryClose").addEventListener("click",hideMobile);
function focusTool(target){
if(target==="source"){showMobile();return;}
const key=target==="separate"?"separate":target==="repair"?"repair":"export";
const group=$("group-"+key);
group.open=true;
if(key==="repair")$("bassDetails").open=true;
group.scrollIntoView({behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth",block:"nearest"});
document.querySelectorAll("[data-focus]").forEach(el=>el.classList.toggle("active",el.dataset.focus===target));
}
document.querySelectorAll("[data-focus]").forEach(el=>el.addEventListener("click",()=>focusTool(el.dataset.focus)));
document.querySelectorAll("[data-tab]").forEach(b=>b.addEventListener("click",()=>showTab(b.dataset.tab)));
document.body.addEventListener("click",e=>{const btn=e.target.closest("[data-action]");if(btn)action(btn.dataset.action)});
$("listenOriginal").addEventListener("click",()=>{try{Live.isolate=null;player()}catch(e){note(e.message,true)}});
$("playPause").addEventListener("click",()=>{
if(!S.project?.asset){note("Zuerst Audiodatei importieren.",true);return}
toggleTransport();
});
$("stop").addEventListener("click",()=>stopLive(true));
audio.addEventListener("play",()=>{if(Live.fileMode)$("playPause").textContent="Ⅱ"});
audio.addEventListener("pause",()=>{if(Live.fileMode)$("playPause").textContent="▶"});
audio.addEventListener("timeupdate",()=>{if(Live.fileMode)paintPlayhead()});
audio.addEventListener("loadedmetadata",()=>{if(Live.fileMode)paintPlayhead()});
$("seek").addEventListener("input",e=>seekTransport(e.target.value/1000*durationSec()));
$("masterCanvas").addEventListener("click",e=>{const r=e.currentTarget.getBoundingClientRect();seekTransport(Math.min(1,Math.max(0,(e.clientX-r.left)/r.width))*durationSec())});
$("trackList").addEventListener("click",e=>{
const row=e.target.closest("[data-stem]");if(!row)return;
const name=row.dataset.stem,btn=e.target.closest("[data-track-action]");
if(btn){
const action=btn.dataset.trackAction;
if(action==="play"){player(name);return}
if(action==="mute"||action==="solo"){
S.settings[name][action]=!S.settings[name][action];
btn.classList.toggle(action==="mute"?"muted":"soloed",S.settings[name][action]);
btn.setAttribute("aria-pressed",String(S.settings[name][action]));markDirty();return;
}
}
if(e.target.matches("canvas")){const r=e.target.getBoundingClientRect();seekTransport(Math.min(1,Math.max(0,(e.clientX-r.left)/r.width))*durationSec())}
});
$("trackList").addEventListener("input",e=>{
const input=e.target.closest("[data-param]");if(!input)return;
const row=input.closest("[data-stem]"),name=row.dataset.stem,param=input.dataset.param;
S.settings[name][param]=Number(input.value);
const output=row.querySelector(`[data-out="${param}"]`);
if(output){
const v=S.settings[name][param];
output.textContent=param==="pan"?(v===0?"C":v<0?"L"+Math.round(-v*100):"R"+Math.round(v*100)):
param==="gain_db"?`${v} dB`:
param==="drive"||param==="width"||param==="delay_mix"||param==="room"?`${Math.round(v*100)} %`:
param==="delay_ms"?(v?`${v} ms`:"Aus"):
v?`${v} Hz`:"Aus";
}markDirty();
});
for(const id of ["tempo","pitch"])$(id).addEventListener("input",markDirty);
$("renderMix").addEventListener("click",renderMix);
$("previewRender").addEventListener("click",()=>{if(!S.mixDirty)player("","mix")});
$("addPlan").addEventListener("click",()=>{
const input=$("newPlanLabel"),label=input.value.trim().slice(0,100);if(!label)return;
collectPlan();let id="manual_"+Date.now().toString(36);S.plan.push({id,label,enabled:true});input.value="";renderPlan();
});
$("planItems").addEventListener("click",e=>{
if(e.target.closest(".plan-remove")){collectPlan();const i=Number(e.target.closest(".plan-row").dataset.index);S.plan.splice(i,1);renderPlan();}
});
$("virtualRun").addEventListener("click",virtualBass);
$("repairSelected").addEventListener("click",repairNoise);
$("noiseEvents").addEventListener("click",e=>{
const button=e.target.closest("[data-preview-noise]");if(button){e.preventDefault();player();audio.currentTime=Math.max(0,Number(button.dataset.previewNoise)-.25)}
});
$("playClean").addEventListener("click",()=>player("clean","noise"));
$("playDifference").addEventListener("click",()=>player("difference","noise"));
for(const [id,out,formatter] of [["bassCutoff","bassCutoffValue",v=>v+" Hz"],["virtualCutoff","virtualCutoffValue",v=>v+" Hz"],["virtualStrength","virtualStrengthValue",v=>Number(v).toFixed(1)+"×"],["noiseStrength","noiseStrengthValue",v=>v+" %"]]){
$(id).addEventListener("input",()=>$(out).textContent=formatter($(id).value));
}
for(const [id,out,fmtValue] of [
["kickGain","kickGainValue",v=>v+" dB"],["bassGain","bassGainValue",v=>v+" dB"],
["subGain","subGainValue",v=>v+" dB"],["harmonics","harmonicsValue",v=>v+" %"],
["bassLowcut","bassLowcutValue",v=>v+" Hz"],["monoBelow","monoBelowValue",v=>v+" Hz"],
["bassWet","bassWetValue",v=>v+" %"]
])$(id).addEventListener("input",()=>$(out).textContent=fmtValue($(id).value));
window.addEventListener("resize",()=>requestAnimationFrame(redraw));
window.addEventListener("dragenter",e=>{if(e.dataTransfer?.types?.includes("Files")){$("dropOverlay").hidden=false;e.preventDefault()}});
$("dropOverlay").addEventListener("dragover",e=>e.preventDefault());
$("dropOverlay").addEventListener("dragleave",e=>{if(e.target===$("dropOverlay"))$("dropOverlay").hidden=true});
$("dropOverlay").addEventListener("drop",e=>{e.preventDefault();$("dropOverlay").hidden=true;importFile(e.dataTransfer.files[0])});
window.addEventListener("keydown",e=>{
if(e.key==="Escape"){$("dropOverlay").hidden=true;hideMobile()}
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="k"){e.preventDefault();showMobile();$("projectSearch").focus();}
});
// Space = Play/Pause überall, außer beim Tippen in Textfeldern.
const typing=el=>{if(!el)return false;if(el.isContentEditable||el.tagName==="TEXTAREA")return true;
if(el.tagName!=="INPUT")return false;
return !["range","checkbox","radio","button","submit","reset","color","file","image"].includes((el.type||"text").toLowerCase());};
const isSpace=e=>(e.code==="Space"||e.key===" ")&&!e.ctrlKey&&!e.metaKey&&!e.altKey;
const toggleSpace=()=>{
if(!S.project?.asset){note("Zuerst Audiodatei importieren.",true);return}
toggleTransport();
};
window.addEventListener("keydown",e=>{
if(!isSpace(e)||typing(e.target)||typing(document.activeElement))return;
e.preventDefault();e.stopPropagation();
if(!e.repeat)toggleSpace();
},true);
window.addEventListener("keyup",e=>{
if(!isSpace(e)||typing(e.target)||typing(document.activeElement))return;
e.preventDefault();e.stopPropagation();
},true);
}
async function init(){
bind();showTab("workflow");$("group-separate").open=true;$("jobFill").style.width="0%";
try{
const [health,models]=await Promise.all([req("/health"),req("/models")]);
S.rubberband=!!health.rubberband_ready;S.virtualReady=!!health.virtualbass_ready;
S.modelReady=!!models.models?.find(x=>x.id==="demucs")?.ready;
const opt=$("separationModel").querySelector('[value="demucs"]');
opt.disabled=!S.modelReady;opt.textContent=S.modelReady?"Demucs KI · lokale Gewichte erkannt":"Demucs KI · lokale Gewichte fehlen";
const fusionNeural=$("fusionMode").querySelector('option[value="neural"]');
fusionNeural.disabled=!S.modelReady;
fusionNeural.textContent=S.modelReady?"KI-Vorrang · echte Vocal/Drums/Bass/Other Stems":"KI-Vorrang · Demucs-Gewichte fehlen";
await loadLibrary();
let saved=null;try{saved=localStorage.getItem(KEY)}catch(_){}
const id=S.projects.find(x=>x.id===saved)?.id||S.projects[0]?.id;
if(id)await selectProject(id);else {updateProjectUI();redraw();}
$("jobLabel").textContent="System bereit";$("jobDetails").textContent=`Backend v${health.version} · Projekte privat gespeichert`;
}catch(e){note(e.message,true);$("jobLabel").textContent="Verbindungsproblem";}
}
init();
})();