plszz commited on
Commit
bc65b76
·
verified ·
1 Parent(s): 2d0b70d

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +193 -365
app.js CHANGED
@@ -163,7 +163,7 @@ function setPerformanceBpm(newBpm) {
163
  if (bpmInput) bpmInput.value = String(bpmClamped);
164
  if (bpmValueEl) bpmValueEl.textContent = `${bpmClamped} BPM`;
165
  if (tempoEl) tempoEl.textContent = String(bpmClamped);
166
-
167
  if (rushBadgeEl) {
168
  if (bpmClamped >= 240) {
169
  rushBadgeEl.style.display = "inline-block";
@@ -171,7 +171,7 @@ function setPerformanceBpm(newBpm) {
171
  rushBadgeEl.style.display = "none";
172
  }
173
  }
174
-
175
  worker.postMessage({ action: "updateBpm", bpm: bpmClamped });
176
  void pumpTokens();
177
  }
@@ -318,25 +318,11 @@ const midiStartBarTimeEl = document.querySelector("#midiStartBarTime");
318
  const midiBpmModeGroup = document.querySelector("#midiBpmModeGroup");
319
  const midiBpmModeButtons = midiBpmModeGroup ? midiBpmModeGroup.querySelectorAll(".toggle-btn") : [];
320
 
321
- // MIDI sub-mode tabs: "single" (continue one uploaded track) vs "trained" (learn a style from many) vs "remix" (play over or play all)
322
  const midiModeTabGroup = document.querySelector("#midiModeTabGroup");
323
  const midiModeTabButtons = midiModeTabGroup ? midiModeTabGroup.querySelectorAll(".mode-tab-btn") : [];
324
  const singleTrackPanel = document.querySelector("#singleTrackPanel");
325
  const trainedStylePanel = document.querySelector("#trainedStylePanel");
326
- const remixPanel = document.querySelector("#remixPanel");
327
-
328
- const remixFileInput = document.querySelector("#remixFileInput");
329
- const remixFileInfo = document.querySelector("#remixFileInfo");
330
- const remixFileNameEl = document.querySelector("#remixFileName");
331
- const remixFileStatsEl = document.querySelector("#remixFileStats");
332
- const remixSubModeGroup = document.querySelector("#remixSubModeGroup");
333
- const remixSubModeButtons = remixSubModeGroup ? remixSubModeGroup.querySelectorAll(".toggle-btn") : [];
334
- const remixSubModeDesc = document.querySelector("#remixSubModeDesc");
335
- const remixArrangementBadge = document.querySelector("#remixArrangementBadge");
336
- const remixAiLayerBadge = document.querySelector("#remixAiLayerBadge");
337
- const remixCreativityInput = document.querySelector("#remixCreativity");
338
- const remixCreativityVal = document.querySelector("#remixCreativityVal");
339
- const remixCreativityHint = document.querySelector("#remixCreativityHint");
340
 
341
  const trainFilesInput = document.querySelector("#trainFilesInput");
342
  const trainFilesList = document.querySelector("#trainFilesList");
@@ -350,14 +336,7 @@ const activeStyleStatsEl = document.querySelector("#activeStyleStats");
350
  const downloadStyleBtn = document.querySelector("#downloadStyleBtn");
351
  const loadStyleInput = document.querySelector("#loadStyleInput");
352
 
353
- let midiSubMode = "single"; // "single" | "trained" | "remix"
354
- let remixSubMode = "over"; // "over" (original + AI accompaniment) | "all" (AI plays entire piece)
355
- let remixCreativity = 0.85;
356
- let remixTokens = [];
357
- let remixParsedMidi = null;
358
- let remixOriginalSynth = null;
359
- let scheduledOriginalNotes = false;
360
-
361
  let pendingTrainingFiles = []; // { fileName, tokens, noteCount }
362
  let hasActiveStyle = false;
363
  let activeStyleMeta = null;
@@ -379,31 +358,31 @@ class MidiParser {
379
  this.view = new DataView(arrayBuffer);
380
  this.pos = 0;
381
  }
382
-
383
  readUint8() {
384
  const v = this.view.getUint8(this.pos);
385
  this.pos += 1;
386
  return v;
387
  }
388
-
389
  readUint16() {
390
  const v = this.view.getUint16(this.pos);
391
  this.pos += 2;
392
  return v;
393
  }
394
-
395
  readUint32() {
396
  const v = this.view.getUint32(this.pos);
397
  this.pos += 4;
398
  return v;
399
  }
400
-
401
  readBytes(len) {
402
  const buf = new Uint8Array(this.view.buffer, this.pos + this.view.byteOffset, len);
403
  this.pos += len;
404
  return buf;
405
  }
406
-
407
  readVarInt() {
408
  let value = 0;
409
  while (true) {
@@ -413,24 +392,24 @@ class MidiParser {
413
  }
414
  return value;
415
  }
416
-
417
  parse() {
418
  const mthd = String.fromCharCode(...this.readBytes(4));
419
  if (mthd !== "MThd") throw new Error("Not a valid MIDI file (missing MThd)");
420
-
421
  const headerLength = this.readUint32();
422
  const format = this.readUint16();
423
  const numTracks = this.readUint16();
424
  const division = this.readUint16();
425
-
426
  if (headerLength > 6) {
427
  this.readBytes(headerLength - 6);
428
  }
429
-
430
  let bpm = 120;
431
  const notes = [];
432
  const activeNotes = new Map();
433
-
434
  for (let t = 0; t < numTracks; t++) {
435
  const mtrk = String.fromCharCode(...this.readBytes(4));
436
  if (mtrk !== "MTrk") {
@@ -438,17 +417,17 @@ class MidiParser {
438
  this.readBytes(len);
439
  continue;
440
  }
441
-
442
  const trackLength = this.readUint32();
443
  const endPos = this.pos + trackLength;
444
-
445
  let tick = 0;
446
  let runningStatus = 0;
447
-
448
  while (this.pos < endPos) {
449
  const deltaTime = this.readVarInt();
450
  tick += deltaTime;
451
-
452
  let status = this.readUint8();
453
  if (status < 0x80) {
454
  this.pos -= 1;
@@ -456,10 +435,10 @@ class MidiParser {
456
  } else {
457
  runningStatus = status;
458
  }
459
-
460
  const eventType = status & 0xF0;
461
  const channel = status & 0x0F;
462
-
463
  if (eventType === 0x90) {
464
  const pitch = this.readUint8();
465
  const velocity = this.readUint8();
@@ -498,7 +477,7 @@ class MidiParser {
498
  const metaType = this.readUint8();
499
  const len = this.readVarInt();
500
  const data = this.readBytes(len);
501
-
502
  if (metaType === 0x51 && len === 3) {
503
  const tempo = (data[0] << 16) | (data[1] << 8) | data[2];
504
  bpm = Math.round(60000000 / tempo);
@@ -513,7 +492,7 @@ class MidiParser {
513
  }
514
  }
515
  }
516
-
517
  for (const [key, active] of activeNotes.entries()) {
518
  const [pitch, channel] = key.split("_").map(Number);
519
  notes.push({
@@ -523,7 +502,7 @@ class MidiParser {
523
  velocity: active.velocity
524
  });
525
  }
526
-
527
  return { bpm, division, notes };
528
  }
529
  }
@@ -532,13 +511,13 @@ class MidiParser {
532
  function tokenizeMidi(parsedMidi, grid = 64) {
533
  const { bpm, division, notes } = parsedMidi;
534
  const stepsPerQuarter = grid / 4;
535
-
536
  const quantizedNotes = notes.map(note => {
537
  const start_step = Math.round((note.startTick / division) * stepsPerQuarter);
538
  const end_step = Math.round((note.endTick / division) * stepsPerQuarter);
539
  const duration_steps = Math.max(1, end_step - start_step);
540
  const velocity_bucket = Math.max(1, Math.min(8, Math.ceil(note.velocity / 16)));
541
-
542
  return {
543
  pitch: note.pitch,
544
  start_step,
@@ -546,15 +525,15 @@ function tokenizeMidi(parsedMidi, grid = 64) {
546
  velocity_bucket
547
  };
548
  });
549
-
550
  quantizedNotes.sort((a, b) => {
551
  if (a.start_step !== b.start_step) return a.start_step - b.start_step;
552
  return a.pitch - b.pitch;
553
  });
554
-
555
  const tokens = ["BOS", `BPM_${Math.round(bpm)}`, `GRID_${grid}`];
556
  let currentBar = -1;
557
-
558
  const notesByStep = new Map();
559
  for (const note of quantizedNotes) {
560
  if (!notesByStep.has(note.start_step)) {
@@ -562,19 +541,19 @@ function tokenizeMidi(parsedMidi, grid = 64) {
562
  }
563
  notesByStep.get(note.start_step).push(note);
564
  }
565
-
566
  const steps = Array.from(notesByStep.keys()).sort((a, b) => a - b);
567
  for (const step of steps) {
568
  const note_bar = Math.floor(step / grid);
569
  const note_pos = step % grid;
570
-
571
  while (currentBar < note_bar) {
572
  tokens.push("BAR");
573
  currentBar += 1;
574
  }
575
-
576
  tokens.push(`POS_${note_pos}`);
577
-
578
  const stepNotes = notesByStep.get(step);
579
  for (const note of stepNotes) {
580
  tokens.push(`NOTE_${note.pitch}`);
@@ -582,14 +561,14 @@ function tokenizeMidi(parsedMidi, grid = 64) {
582
  tokens.push(`VEL_${note.velocity_bucket}`);
583
  }
584
  }
585
-
586
  return { tokens, maxBar: currentBar };
587
  }
588
 
589
  function findMinStartBar(tokens) {
590
  let barCount = 0;
591
  let tokenCount = 0;
592
-
593
  for (let i = 0; i < tokens.length; i++) {
594
  const t = tokens[i];
595
  if (t === "BAR") {
@@ -643,7 +622,7 @@ function analyzeMidiTokens(tokens) {
643
  function getWarmUpInfo(tokens, targetBar) {
644
  let barCount = 0;
645
  const tokensUpToBar = [];
646
-
647
  for (const t of tokens) {
648
  if (t === "BAR") {
649
  if (barCount === targetBar) {
@@ -653,18 +632,18 @@ function getWarmUpInfo(tokens, targetBar) {
653
  }
654
  tokensUpToBar.push(t);
655
  }
656
-
657
  const totalTokens = tokensUpToBar.length;
658
  const warmUpCount = Math.min(256, totalTokens);
659
  const startIndex = totalTokens - warmUpCount;
660
-
661
  let currentBarOfStart = -1;
662
  for (let i = 0; i < startIndex; i++) {
663
  if (tokens[i] === "BAR") {
664
  currentBarOfStart += 1;
665
  }
666
  }
667
-
668
  return {
669
  startBar: Math.max(0, currentBarOfStart),
670
  endBar: targetBar - 1,
@@ -677,37 +656,37 @@ function renderMidiTimeline(barsData) {
677
  const midiTimeline = document.querySelector("#midiTimeline");
678
  if (!midiTimeline) return;
679
  midiTimeline.innerHTML = "";
680
-
681
  if (!barsData || barsData.length === 0) {
682
  midiTimeline.style.display = "none";
683
  return;
684
  }
685
-
686
  midiTimeline.style.display = "flex";
687
-
688
  const maxNotes = Math.max(...barsData.map(b => b.noteCount), 1);
689
  const minBar = findMinStartBar(midiTokens);
690
-
691
  barsData.forEach((bar, index) => {
692
  const col = document.createElement("div");
693
  col.className = "timeline-bar-col";
694
  col.dataset.barNum = String(index);
695
  col.dataset.barLabel = `${index + 1}`;
696
-
697
  const totalBars = barsData.length;
698
  const labelInterval = totalBars > 64 ? 16 : (totalBars > 32 ? 8 : 4);
699
  if (index % labelInterval === 0) {
700
  col.classList.add("labeled");
701
  }
702
-
703
  const densityVal = (bar.noteCount / maxNotes) * 100;
704
-
705
  const fill = document.createElement("div");
706
  fill.className = "density-fill";
707
  fill.style.height = `${Math.max(10, densityVal)}%`;
708
-
709
  col.appendChild(fill);
710
-
711
  if (index < minBar) {
712
  col.classList.add("disabled");
713
  } else {
@@ -719,23 +698,23 @@ function renderMidiTimeline(barsData) {
719
  updateMidiStartBarText();
720
  });
721
  }
722
-
723
  midiTimeline.appendChild(col);
724
  });
725
-
726
  updateMidiTimelineHighlights();
727
  }
728
 
729
  function updateMidiTimelineHighlights() {
730
  const midiTimeline = document.querySelector("#midiTimeline");
731
  if (!midiTimeline || !midiTokens || midiTokens.length === 0) return;
732
-
733
  const cols = midiTimeline.querySelectorAll(".timeline-bar-col");
734
  const info = getWarmUpInfo(midiTokens, midiStartBar);
735
-
736
  cols.forEach((col, index) => {
737
  col.classList.remove("in-warmup", "is-selected");
738
-
739
  if (index === midiStartBar) {
740
  col.classList.add("is-selected");
741
  if (typeof col.scrollIntoViewIfNeeded === "function") {
@@ -785,15 +764,6 @@ function setMidiSubMode(mode) {
785
  });
786
  if (singleTrackPanel) singleTrackPanel.style.display = mode === "single" ? "block" : "none";
787
  if (trainedStylePanel) trainedStylePanel.style.display = mode === "trained" ? "block" : "none";
788
- if (remixPanel) remixPanel.style.display = mode === "remix" ? "block" : "none";
789
-
790
- if (mode === "remix") {
791
- activePlayingStyle = "remix";
792
- } else if (mode === "trained" && hasActiveStyle) {
793
- activePlayingStyle = "trained";
794
- } else if (mode === "single") {
795
- activePlayingStyle = "midi";
796
- }
797
  refreshMidiSimilarityCopy();
798
  }
799
 
@@ -948,9 +918,7 @@ if (midiModeTabButtons.length) {
948
  btn.addEventListener("click", () => {
949
  if (btn.disabled) return;
950
  setMidiSubMode(btn.dataset.mode);
951
- if (btn.dataset.mode === "remix") {
952
- activePlayingStyle = "remix";
953
- } else if (btn.dataset.mode === "trained" && hasActiveStyle) {
954
  activePlayingStyle = "trained";
955
  } else if (btn.dataset.mode === "single") {
956
  activePlayingStyle = "midi";
@@ -988,7 +956,7 @@ const instrumentSamples = {
988
  function setStatus(message, state = "idle") {
989
  if (appStatusEl) appStatusEl.textContent = message;
990
  if (statusTextEl) statusTextEl.textContent = state.toUpperCase();
991
-
992
  if (statusDotEl) {
993
  statusDotEl.className = "status-dot";
994
  if (state === "playing") {
@@ -1004,7 +972,7 @@ function currentTarget() {
1004
  const currentBpm = Number(tempoEl?.textContent || 120);
1005
  const bpmScale = Math.max(1.0, currentBpm / 110);
1006
  const baseTarget = Math.round(TARGET_QUEUE_EVENTS * bpmScale);
1007
-
1008
  if (avgPumpMs <= 0) return baseTarget;
1009
  const dynamicChunk = Math.min(192, Math.max(64, Math.round(64 * (currentBpm / 120))));
1010
  const cyclesOfSlack = Math.max(3, Math.ceil(avgPumpMs / LOOKAHEAD_MS) + 2);
@@ -1034,21 +1002,20 @@ function midiFromPitchName(note) {
1034
  return (Number(match[3]) + 1) * 12 + semitone + accidental;
1035
  }
1036
 
1037
- function recordVisualEvent(event, startTime, isOriginal = false) {
1038
  if (event.type !== "note") return;
1039
  event.notes.forEach((note, index) => {
1040
  const midi = midiFromPitchName(note);
1041
  if (midi === null) return;
1042
- const duration = event.perNoteDurations
1043
- ? event.perNoteDurations[index]
1044
  : event.duration;
1045
- visualNotes.push({
1046
- midi,
1047
- note,
1048
- start: startTime,
1049
  duration: Math.max(0.08, duration),
1050
- velocity: event.velocities ? event.velocities[index] : 0.72,
1051
- isOriginal: isOriginal
1052
  });
1053
  });
1054
  const now = Tone.now();
@@ -1097,32 +1064,6 @@ function scheduleAudio() {
1097
  if (!running) return;
1098
  const now = Tone.now();
1099
  if (nextNoteTime < now + 0.08) nextNoteTime = now + 0.08;
1100
-
1101
- // 🎸 Play Over Remix Mode: Schedule original MIDI track on piano synth
1102
- if (activePlayingStyle === "remix" && remixSubMode === "over" && !scheduledOriginalNotes && remixParsedMidi) {
1103
- scheduledOriginalNotes = true;
1104
- const { bpm, division, notes } = remixParsedMidi;
1105
- const effectiveBpm = Number(tempoEl?.textContent || bpm || 120);
1106
- const startTimeOffset = nextNoteTime;
1107
-
1108
- notes.forEach((n) => {
1109
- const startSec = (n.startTick / division) * (60 / effectiveBpm);
1110
- const durSec = Math.max(0.08, ((n.endTick - n.startTick) / division) * (60 / effectiveBpm));
1111
- const tonePitch = midiToTonePitch(n.pitch);
1112
- const noteTime = startTimeOffset + startSec;
1113
-
1114
- if (remixOriginalSynth) {
1115
- remixOriginalSynth.triggerAttackRelease(tonePitch, Math.min(3.8, durSec), noteTime, (n.velocity || 110) / 127);
1116
- }
1117
- recordVisualEvent({
1118
- type: "note",
1119
- notes: [tonePitch],
1120
- duration: durSec,
1121
- velocities: [(n.velocity || 110) / 127]
1122
- }, noteTime, true);
1123
- });
1124
- }
1125
-
1126
  while (queue.length && nextNoteTime < now + SCHEDULE_AHEAD_SECONDS) {
1127
  const event = queue.shift();
1128
  if (event.type === "note") {
@@ -1164,7 +1105,7 @@ function scheduleAudio() {
1164
  }
1165
  });
1166
  }
1167
-
1168
  if (isRecording) {
1169
  const eventTime = nextNoteTime;
1170
  if (event.perNoteDurations) {
@@ -1193,17 +1134,17 @@ function scheduleAudio() {
1193
  });
1194
  }
1195
  }
1196
-
1197
  recordVisualEvent({ ...event, duration: event.duration || Math.max(...(event.perNoteDurations ?? [0.2])) }, nextNoteTime);
1198
  }
1199
  nextNoteTime += event.advance ?? event.duration;
1200
  }
1201
-
1202
  // Proactive pumping to ensure queue never starves at high BPMs
1203
  if (!isOfflineRendering && queue.length < currentTarget()) {
1204
  void pumpTokens();
1205
  }
1206
-
1207
  updateReadouts();
1208
  schedulerId = window.setTimeout(scheduleAudio, LOOKAHEAD_MS);
1209
  }
@@ -1224,9 +1165,9 @@ function setRelease(val) {
1224
  }
1225
 
1226
  async function createSampler(instrumentName) {
1227
- if (synth) { try { synth.dispose(); } catch (e) { } synth = null; }
1228
- if (bassSynth) { try { bassSynth.dispose(); } catch (e) { } bassSynth = null; }
1229
- if (chordSynth) { try { chordSynth.dispose(); } catch (e) { } chordSynth = null; }
1230
 
1231
  const initialRel = Number(releaseInput.value);
1232
 
@@ -1287,7 +1228,7 @@ async function createSampler(instrumentName) {
1287
 
1288
  async function ensureInstrument() {
1289
  if (synth) return;
1290
-
1291
  const initialVol = Number(volumeInput.value);
1292
  const initialRev = Number(reverbInput.value);
1293
  const initialDel = Number(delayInput.value);
@@ -1295,23 +1236,10 @@ async function ensureInstrument() {
1295
 
1296
  reverb = new Tone.Reverb({ decay: 2.8, wet: initialRev / 100 }).toDestination();
1297
  delay = new Tone.FeedbackDelay({ delayTime: "8n", feedback: 0.18, wet: initialDel / 100 }).connect(reverb);
1298
-
1299
  await createSampler(currentInstrument);
1300
-
1301
- if (activePlayingStyle === "remix" && remixSubMode === "over") {
1302
- if (!remixOriginalSynth) {
1303
- remixOriginalSynth = new Tone.Sampler({
1304
- urls: pianoSamples,
1305
- baseUrl: "https://tonejs.github.io/audio/salamander/",
1306
- attack: 0,
1307
- release: initialRel,
1308
- curve: "exponential"
1309
- }).connect(delay);
1310
- }
1311
- }
1312
-
1313
  setVolume(initialVol);
1314
-
1315
  if (reverbValue) reverbValue.textContent = `${initialRev}%`;
1316
  if (delayValue) delayValue.textContent = `${initialDel}%`;
1317
  if (releaseValue) releaseValue.textContent = `${initialRel.toFixed(1)}s`;
@@ -1322,21 +1250,20 @@ async function start() {
1322
  startBtn.disabled = true;
1323
  if (renderSongBtn) renderSongBtn.disabled = true;
1324
  setStatus("Starting audio...", "loading");
1325
-
1326
  await Tone.start();
1327
  await ensureInstrument();
1328
-
1329
  queue = [];
1330
  generatedEvents = 0;
1331
  visualNotes = [];
1332
  avgPumpMs = 0;
1333
- scheduledOriginalNotes = false;
1334
-
1335
  const targetBpm = bpmInput ? Number(bpmInput.value) : 120;
1336
  if (tempoEl) tempoEl.textContent = String(targetBpm);
1337
-
1338
  setStatus("Warming AI model prompt...", "buffering");
1339
-
1340
  const warmStart = performance.now();
1341
  try {
1342
  await new Promise((resolve, reject) => {
@@ -1348,9 +1275,7 @@ async function start() {
1348
  topK: Math.max(1, Number(topKInput.value)),
1349
  bpm: targetBpm,
1350
  playingStyle: activePlayingStyle,
1351
- remixMode: remixSubMode,
1352
- remixCreativity: remixCreativity,
1353
- midiTokens: (activePlayingStyle === "remix") ? remixTokens : ((activePlayingStyle === "midi") ? midiTokens : []),
1354
  midiStartBar: midiStartBar,
1355
  midiBpmMode: midiBpmMode,
1356
  heuristicSettings: getHeuristicSettings(),
@@ -1363,7 +1288,7 @@ async function start() {
1363
  return;
1364
  }
1365
  avgPumpMs = performance.now() - warmStart;
1366
-
1367
  running = true;
1368
  stopBtn.disabled = false;
1369
  if (newSongBtn) newSongBtn.disabled = false;
@@ -1374,15 +1299,15 @@ async function start() {
1374
  midiBpmModeButtons.forEach(btn => btn.disabled = true);
1375
  midiFileInput.disabled = true;
1376
  midiStartBarInput.disabled = true;
1377
-
1378
  setStatus("Buffering ahead...", "buffering");
1379
  const primeDeadline = performance.now() + STARTUP_PRIME_BUDGET_MS;
1380
  while (running && queue.length < currentTarget() && performance.now() < primeDeadline) {
1381
  await pumpTokens();
1382
  }
1383
-
1384
  setStatus(`Playing ${activeModelName}`, "playing");
1385
-
1386
  nextNoteTime = Tone.now() + 0.12;
1387
  startVisualizer();
1388
  scheduleAudio();
@@ -1393,16 +1318,15 @@ function stop() {
1393
  stopRecording(true);
1394
  }
1395
  running = false;
1396
- scheduledOriginalNotes = false;
1397
  window.clearTimeout(schedulerId);
1398
  schedulerId = 0;
1399
  window.clearTimeout(pumpWatchdogId);
1400
  pumpWatchdogId = 0;
1401
  pumping = false;
1402
  pumpPromiseResolve = null;
1403
-
1404
  worker.postMessage({ action: "stop" });
1405
-
1406
  startBtn.disabled = !isModelReady;
1407
  if (renderSongBtn) renderSongBtn.disabled = !isModelReady;
1408
  stopBtn.disabled = true;
@@ -1414,14 +1338,13 @@ function stop() {
1414
  midiBpmModeButtons.forEach(btn => btn.disabled = false);
1415
  midiFileInput.disabled = false;
1416
  midiStartBarInput.disabled = false;
 
 
 
 
1417
 
1418
- if (synth) { try { synth.dispose(); } catch (e) { } synth = null; }
1419
- if (bassSynth) { try { bassSynth.dispose(); } catch (e) { } bassSynth = null; }
1420
- if (chordSynth) { try { chordSynth.dispose(); } catch (e) { } chordSynth = null; }
1421
- if (remixOriginalSynth) { try { remixOriginalSynth.dispose(); } catch (e) { } remixOriginalSynth = null; }
1422
-
1423
- if (reverb) { try { reverb.dispose(); } catch (e) { } reverb = null; }
1424
- if (delay) { try { delay.dispose(); } catch (e) { } delay = null; }
1425
 
1426
  if (visualFrame) cancelAnimationFrame(visualFrame);
1427
  visualFrame = 0;
@@ -1432,7 +1355,7 @@ function stop() {
1432
  function startFullSongRender() {
1433
  if (running) stop();
1434
  if (!isModelReady) return;
1435
-
1436
  isOfflineRendering = true;
1437
  if (renderProgressModal) {
1438
  renderProgressModal.style.display = "flex";
@@ -1453,9 +1376,7 @@ function startFullSongRender() {
1453
  topK: Math.max(1, Number(topKInput.value)),
1454
  bpm: targetBpm,
1455
  playingStyle: activePlayingStyle,
1456
- remixMode: remixSubMode,
1457
- remixCreativity: remixCreativity,
1458
- midiTokens: (activePlayingStyle === "remix") ? remixTokens : ((activePlayingStyle === "midi") ? midiTokens : []),
1459
  midiStartBar: midiStartBar,
1460
  midiBpmMode: midiBpmMode,
1461
  heuristicSettings: getHeuristicSettings()
@@ -1466,13 +1387,13 @@ function showRenderDoneModal(data) {
1466
  if (renderDoneModal) {
1467
  renderDoneModal.style.display = "flex";
1468
  }
1469
-
1470
  const events = data.events || [];
1471
  let durationSec = 0;
1472
  events.forEach(e => {
1473
  durationSec += e.advance ?? e.duration ?? 0;
1474
  });
1475
-
1476
  if (doneDurationVal) doneDurationVal.textContent = `${durationSec.toFixed(1)}s`;
1477
  if (doneNoteCountVal) doneNoteCountVal.textContent = `${data.noteCount || 0} Notes`;
1478
  if (doneBpmVal) doneBpmVal.textContent = `${data.bpm || 120} BPM`;
@@ -1480,26 +1401,26 @@ function showRenderDoneModal(data) {
1480
 
1481
  async function previewRenderedSong() {
1482
  if (!lastRenderedResult || !lastRenderedResult.events) return;
1483
-
1484
  if (renderDoneModal) renderDoneModal.style.display = "none";
1485
  if (running) stop();
1486
-
1487
  setStatus("Starting pre-rendered performance...", "loading");
1488
  await Tone.start();
1489
  await ensureInstrument();
1490
-
1491
  queue = [...lastRenderedResult.events];
1492
  generatedEvents = lastRenderedResult.noteCount || queue.filter(e => e.type === "note").length;
1493
  visualNotes = [];
1494
-
1495
  running = true;
1496
  stopBtn.disabled = false;
1497
  if (newSongBtn) newSongBtn.disabled = false;
1498
  if (startBtn) startBtn.disabled = true;
1499
  if (renderSongBtn) renderSongBtn.disabled = true;
1500
-
1501
  setStatus(`Previewing Rendered Song (${dataBpm(lastRenderedResult.bpm)} BPM)`, "playing");
1502
-
1503
  nextNoteTime = Tone.now() + 0.12;
1504
  startVisualizer();
1505
  scheduleAudio();
@@ -1511,13 +1432,13 @@ function dataBpm(bpm) {
1511
 
1512
  function downloadRenderedMidiFile() {
1513
  if (!lastRenderedResult || !lastRenderedResult.events) return;
1514
-
1515
  const events = lastRenderedResult.events;
1516
  const bpm = lastRenderedResult.bpm || 120;
1517
-
1518
  const compiledNotes = [];
1519
  let currentTime = 0;
1520
-
1521
  for (const e of events) {
1522
  if (e.type === "note") {
1523
  if (e.perNoteDurations) {
@@ -1548,7 +1469,7 @@ function downloadRenderedMidiFile() {
1548
  }
1549
  currentTime += e.advance ?? e.duration ?? 0;
1550
  }
1551
-
1552
  if (compiledNotes.length > 0) {
1553
  const fileBytes = compileMidiFile(compiledNotes, bpm);
1554
  downloadMidi(fileBytes, "nanomaestro_ai_1min_song.mid");
@@ -1560,7 +1481,7 @@ function startRecording() {
1560
  isRecording = true;
1561
  recordedNotes = [];
1562
  recordingStartTime = Tone.now();
1563
-
1564
  if (recordBtn) {
1565
  recordBtn.classList.add("btn-recording");
1566
  if (recordIcon) recordIcon.classList.add("pulse-record");
@@ -1574,7 +1495,7 @@ function startRecording() {
1574
  function stopRecording(download = true) {
1575
  if (!isRecording) return;
1576
  isRecording = false;
1577
-
1578
  if (recordBtn) {
1579
  recordBtn.classList.remove("btn-recording");
1580
  if (recordIcon) recordIcon.classList.remove("pulse-record");
@@ -1583,7 +1504,7 @@ function stopRecording(download = true) {
1583
  }
1584
  if (recordBtnText) recordBtnText.textContent = "Record";
1585
  }
1586
-
1587
  if (download && recordedNotes.length > 0) {
1588
  const bpm = Number(tempoEl?.textContent || 120);
1589
  const fileBytes = compileMidiFile(recordedNotes, bpm);
@@ -1608,7 +1529,7 @@ function encodeVLQ(value) {
1608
  function compileMidiFile(recordedNotes, bpm) {
1609
  const division = 480;
1610
  const trackBytes = [];
1611
-
1612
  const tempoMicro = Math.round(60000000 / bpm);
1613
  trackBytes.push(
1614
  0, 0xFF, 0x51, 0x03,
@@ -1616,21 +1537,21 @@ function compileMidiFile(recordedNotes, bpm) {
1616
  (tempoMicro >> 8) & 0xFF,
1617
  tempoMicro & 0xFF
1618
  );
1619
-
1620
  const midiEvents = [];
1621
  for (const note of recordedNotes) {
1622
  const onTicks = Math.round(note.time * (bpm * division / 60));
1623
  const offTicks = Math.round((note.time + note.duration) * (bpm * division / 60));
1624
-
1625
  midiEvents.push({ ticks: onTicks, type: 0x90, note: note.midi, velocity: Math.round(note.velocity * 127) });
1626
  midiEvents.push({ ticks: offTicks, type: 0x80, note: note.midi, velocity: 0 });
1627
  }
1628
-
1629
  midiEvents.sort((a, b) => {
1630
  if (a.ticks !== b.ticks) return a.ticks - b.ticks;
1631
  return a.type - b.type;
1632
  });
1633
-
1634
  let lastTicks = 0;
1635
  for (const event of midiEvents) {
1636
  const delta = event.ticks - lastTicks;
@@ -1638,18 +1559,18 @@ function compileMidiFile(recordedNotes, bpm) {
1638
  trackBytes.push(...encodeVLQ(delta));
1639
  trackBytes.push(event.type, event.note, event.velocity);
1640
  }
1641
-
1642
  trackBytes.push(0, 0xFF, 0x2F, 0x00);
1643
-
1644
  const headerBytes = [0x4d, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, (division >> 8) & 0xFF, division & 0xFF];
1645
  const trackLen = trackBytes.length;
1646
  const trackHeaderBytes = [0x4d, 0x54, 0x72, 0x6b, (trackLen >> 24) & 0xFF, (trackLen >> 16) & 0xFF, (trackLen >> 8) & 0xFF, trackLen & 0xFF];
1647
-
1648
  const fileBytes = new Uint8Array(headerBytes.length + trackHeaderBytes.length + trackBytes.length);
1649
  fileBytes.set(headerBytes, 0);
1650
  fileBytes.set(trackHeaderBytes, headerBytes.length);
1651
  fileBytes.set(trackBytes, headerBytes.length + trackHeaderBytes.length);
1652
-
1653
  return fileBytes;
1654
  }
1655
 
@@ -1686,10 +1607,10 @@ function getKeyPosition(midi, width) {
1686
  const whiteKeyW = width / numWhiteKeys;
1687
  const noteInOctave = (midi - minMidi) % 12;
1688
  const octave = Math.floor((midi - minMidi) / 12);
1689
-
1690
  const whiteKeyOffsets = [0, null, 1, null, 2, 3, null, 4, null, 5, null, 6];
1691
  const isBlack = whiteKeyOffsets[noteInOctave] === null;
1692
-
1693
  if (!isBlack) {
1694
  const whiteIdx = octave * 7 + whiteKeyOffsets[noteInOctave];
1695
  const x = whiteIdx * whiteKeyW;
@@ -1707,7 +1628,7 @@ function getKeyPosition(midi, width) {
1707
  function drawVisualizer() {
1708
  const width = canvasWidth;
1709
  const height = canvasHeight;
1710
-
1711
  const perfNow = performance.now();
1712
  const rawAudioTime = Tone.now();
1713
  if (rawAudioTime !== lastAudioTime) {
@@ -1716,16 +1637,16 @@ function drawVisualizer() {
1716
  }
1717
  const smoothNow = lastAudioTime + (perfNow - lastPerfTime) / 1000;
1718
  const visualNow = smoothNow - VISUAL_DELAY;
1719
-
1720
  const minMidi = 36;
1721
  const maxMidi = 96;
1722
  const secondsVisible = 4.5;
1723
  const keyboardH = width < 640 ? 80 : 120;
1724
  const playLineY = height - keyboardH;
1725
  const speed = playLineY / secondsVisible;
1726
-
1727
  canvasCtx.clearRect(0, 0, width, height);
1728
-
1729
  for (let m = minMidi; m <= maxMidi; m++) {
1730
  const keyInfo = getKeyPosition(m, width);
1731
  if (keyInfo.isBlack) {
@@ -1733,20 +1654,20 @@ function drawVisualizer() {
1733
  canvasCtx.fillRect(keyInfo.x, 0, keyInfo.w, playLineY);
1734
  }
1735
  }
1736
-
1737
  const currentBpm = Number(tempoEl?.textContent || 120);
1738
  const secondsPerBeat = 60 / currentBpm;
1739
-
1740
  const startBeat = Math.floor((visualNow - 1.0) / secondsPerBeat);
1741
  const endBeat = Math.ceil((visualNow + secondsVisible) / secondsPerBeat);
1742
-
1743
  canvasCtx.font = "8px ui-sans-serif, system-ui, sans-serif";
1744
  for (let b = startBeat; b <= endBeat; b++) {
1745
  if (b < 0) continue;
1746
  const beatTime = b * secondsPerBeat;
1747
  const y = playLineY - (beatTime - visualNow) * speed;
1748
  if (y < 0 || y > playLineY) continue;
1749
-
1750
  const isBar = b % 4 === 0;
1751
  if (isBar) {
1752
  canvasCtx.strokeStyle = "rgba(255, 255, 255, 0.06)";
@@ -1757,62 +1678,48 @@ function drawVisualizer() {
1757
  canvasCtx.strokeStyle = "rgba(255, 255, 255, 0.015)";
1758
  canvasCtx.lineWidth = 0.5;
1759
  }
1760
-
1761
  canvasCtx.beginPath();
1762
  canvasCtx.moveTo(0, y);
1763
  canvasCtx.lineTo(width, y);
1764
  canvasCtx.stroke();
1765
  }
1766
-
1767
  const activePitches = new Set();
1768
-
1769
  for (const item of visualNotes) {
1770
  const end = item.start + item.duration;
1771
  if (end < visualNow - 0.5 || item.start > visualNow + secondsVisible) continue;
1772
-
1773
  const active = item.start <= visualNow && end >= visualNow;
1774
  const midiClamped = Math.max(minMidi, Math.min(maxMidi, item.midi));
1775
  if (active) activePitches.add(midiClamped);
1776
-
1777
  const keyInfo = getKeyPosition(midiClamped, width);
1778
  const noteW = keyInfo.isBlack ? keyInfo.w * 0.85 : keyInfo.w * 0.75;
1779
  const noteX = keyInfo.center - noteW / 2;
1780
-
1781
  const bottomY = playLineY - (item.start - visualNow) * speed;
1782
  const topY = playLineY - (end - visualNow) * speed;
1783
-
1784
  const drawTop = Math.max(-100, topY);
1785
  const drawBottom = Math.max(-100, bottomY);
1786
  const noteH = drawBottom - drawTop;
1787
-
1788
  if (noteH > 0) {
1789
- if (item.isOriginal) {
1790
- // Original MIDI Track Notes: Rendered in sleek Silver / White with Ice Glow
1791
- if (active) {
1792
- canvasCtx.fillStyle = "#ffffff";
1793
- canvasCtx.shadowBlur = 14;
1794
- canvasCtx.shadowColor = "rgba(255, 255, 255, 0.95)";
1795
- canvasCtx.globalAlpha = 1.0;
1796
- } else {
1797
- canvasCtx.fillStyle = "#cbd5e1";
1798
- canvasCtx.shadowBlur = 0;
1799
- canvasCtx.globalAlpha = 0.7;
1800
- }
1801
  } else {
1802
- // AI-Generated Accompaniment Notes: Rendered in Vibrant Gold / Emerald / Sky Blue
1803
- if (active) {
1804
- canvasCtx.fillStyle = "#fbbf24";
1805
- canvasCtx.shadowBlur = 12;
1806
- canvasCtx.shadowColor = item.midi < 53 ? "rgba(245, 158, 11, 0.9)" : (item.midi < 72 ? "rgba(52, 211, 153, 0.9)" : "rgba(96, 165, 250, 0.9)");
1807
- canvasCtx.globalAlpha = 0.98;
1808
- } else {
1809
- // Voice layering colors: Bass=Amber, Chords=Emerald, Lead=Sky Blue
1810
- canvasCtx.fillStyle = item.midi < 53 ? "#d97706" : (item.midi < 72 ? "#059669" : "#2563eb");
1811
- canvasCtx.shadowBlur = 0;
1812
- canvasCtx.globalAlpha = 0.65;
1813
- }
1814
  }
1815
-
1816
  canvasCtx.beginPath();
1817
  if (typeof canvasCtx.roundRect === "function") {
1818
  canvasCtx.roundRect(noteX, drawTop, noteW, noteH, Math.min(noteW / 2, 4));
@@ -1822,10 +1729,10 @@ function drawVisualizer() {
1822
  canvasCtx.fill();
1823
  }
1824
  }
1825
-
1826
  canvasCtx.shadowBlur = 0;
1827
  canvasCtx.globalAlpha = 1.0;
1828
-
1829
  const numWhiteKeys = 36;
1830
  const whiteKeyW = width / numWhiteKeys;
1831
  for (let i = 0; i < numWhiteKeys; i++) {
@@ -1833,12 +1740,12 @@ function drawVisualizer() {
1833
  const offsetIdx = i % 7;
1834
  const whiteToNote = [0, 2, 4, 5, 7, 9, 11];
1835
  const midi = 36 + octave * 12 + whiteToNote[offsetIdx];
1836
-
1837
  const active = activePitches.has(midi);
1838
  const x = i * whiteKeyW;
1839
-
1840
  canvasCtx.fillStyle = active ? "#ffffff" : "#1a1f26";
1841
-
1842
  canvasCtx.beginPath();
1843
  if (typeof canvasCtx.roundRect === "function") {
1844
  canvasCtx.roundRect(x + 1, playLineY, whiteKeyW - 2, keyboardH, [0, 0, 3, 3]);
@@ -1846,22 +1753,22 @@ function drawVisualizer() {
1846
  canvasCtx.rect(x + 1, playLineY, whiteKeyW - 2, keyboardH);
1847
  }
1848
  canvasCtx.fill();
1849
-
1850
  canvasCtx.fillStyle = "rgba(0, 0, 0, 0.35)";
1851
  canvasCtx.fillRect(x, playLineY, 1, keyboardH);
1852
  }
1853
-
1854
  const blackKeyHeight = keyboardH * 0.62;
1855
  for (let m = minMidi; m <= maxMidi; m++) {
1856
  const noteInOctave = (m - minMidi) % 12;
1857
  const isBlack = [1, 3, 6, 8, 10].includes(noteInOctave);
1858
  if (!isBlack) continue;
1859
-
1860
  const active = activePitches.has(m);
1861
  const keyInfo = getKeyPosition(m, width);
1862
-
1863
  canvasCtx.fillStyle = active ? "#6f9c78" : "#090a0d";
1864
-
1865
  canvasCtx.beginPath();
1866
  if (typeof canvasCtx.roundRect === "function") {
1867
  canvasCtx.roundRect(keyInfo.x, playLineY, keyInfo.w, blackKeyHeight, [0, 0, 2, 2]);
@@ -1869,25 +1776,25 @@ function drawVisualizer() {
1869
  canvasCtx.rect(keyInfo.x, playLineY, keyInfo.w, blackKeyHeight);
1870
  }
1871
  canvasCtx.fill();
1872
-
1873
  canvasCtx.fillStyle = active ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.05)";
1874
  canvasCtx.fillRect(keyInfo.x, playLineY, keyInfo.w, 2);
1875
  }
1876
-
1877
  canvasCtx.fillStyle = "rgba(255, 255, 255, 0.12)";
1878
  canvasCtx.fillRect(0, playLineY - 1, width, 1);
1879
-
1880
  const playLineShadow = canvasCtx.createLinearGradient(0, playLineY, 0, playLineY + 6);
1881
  playLineShadow.addColorStop(0, "rgba(0, 0, 0, 0.45)");
1882
  playLineShadow.addColorStop(1, "rgba(0, 0, 0, 0)");
1883
  canvasCtx.fillStyle = playLineShadow;
1884
  canvasCtx.fillRect(0, playLineY, width, 6);
1885
-
1886
  canvasCtx.fillStyle = "rgba(255, 255, 255, 0.18)";
1887
  canvasCtx.font = "9px ui-sans-serif, system-ui, sans-serif";
1888
  canvasCtx.fillText("BASS", 12, playLineY - 10);
1889
  canvasCtx.fillText("TREBLE", width - 48, playLineY - 10);
1890
-
1891
  visualNotes = visualNotes.filter((item) => item.start + item.duration > visualNow - 1.5);
1892
  if (running) visualFrame = requestAnimationFrame(drawVisualizer);
1893
  }
@@ -1943,7 +1850,7 @@ async function setCachedData(key, data) {
1943
  const tx = db.transaction("models", "readwrite");
1944
  const store = tx.objectStore("models");
1945
  store.put(data, key);
1946
- } catch (e) { }
1947
  }
1948
 
1949
  async function getFromCacheStorage(cacheKey) {
@@ -1954,7 +1861,7 @@ async function getFromCacheStorage(cacheKey) {
1954
  if (res && res.ok) {
1955
  return res;
1956
  }
1957
- } catch (e) { }
1958
  return null;
1959
  }
1960
 
@@ -1963,13 +1870,13 @@ async function setInCacheStorage(cacheKey, response) {
1963
  if (!("caches" in window)) return;
1964
  const cache = await caches.open("nanomaestro_models_v2");
1965
  await cache.put(cacheKey, response);
1966
- } catch (e) { }
1967
  }
1968
 
1969
  async function fetchStreamWithProgress(response, onProgress) {
1970
  const contentLength = response.headers.get("content-length");
1971
  const total = contentLength ? parseInt(contentLength, 10) : 0;
1972
-
1973
  let loaded = 0;
1974
  if (response.body && typeof response.body.getReader === "function") {
1975
  const reader = response.body.getReader();
@@ -2000,7 +1907,7 @@ async function fetchAssetWithCache(cacheKey, localUrl, remoteUrl, onProgress, is
2000
  }
2001
  return cachedData;
2002
  }
2003
- } catch (e) { }
2004
 
2005
  try {
2006
  const cachedResponse = await getFromCacheStorage(cacheKey);
@@ -2014,7 +1921,7 @@ async function fetchAssetWithCache(cacheKey, localUrl, remoteUrl, onProgress, is
2014
  void setCachedData(cacheKey, data);
2015
  return data;
2016
  }
2017
- } catch (e) { }
2018
 
2019
  console.log(`[Cache MISS] Fetching ${cacheKey} from network...`);
2020
  let data;
@@ -2091,10 +1998,10 @@ async function loadSelectedModel(presetKey, updateProgress) {
2091
 
2092
  const vocabCacheKey = `vocab_${preset.key}_v1`;
2093
  const modelCacheKey = `model_${preset.key}_v1`;
2094
-
2095
  if (updateProgress) updateProgress(5, `Loading ${preset.name} vocabulary...`);
2096
  const vocab = await fetchAssetWithCache(vocabCacheKey, preset.vocabUrl, preset.remoteVocabUrl, null, true);
2097
-
2098
  if (updateProgress) updateProgress(15, `Loading ${preset.name} weights...`);
2099
  const modelBlob = await fetchAssetWithCache(modelCacheKey, preset.modelUrl, preset.remoteModelUrl, (loaded, total) => {
2100
  if (updateProgress) {
@@ -2109,9 +2016,9 @@ async function loadSelectedModel(presetKey, updateProgress) {
2109
  }
2110
  }
2111
  }, false);
2112
-
2113
  if (updateProgress) updateProgress(82, `Initializing ${preset.name} engine (WASM CPU)...`);
2114
-
2115
  const modelBuffer = await modelBlob.arrayBuffer();
2116
  await new Promise((resolve, reject) => {
2117
  let timer = setTimeout(() => {
@@ -2135,10 +2042,10 @@ async function loadSelectedModel(presetKey, updateProgress) {
2135
  modelConfig: preset.config
2136
  }, [modelBuffer]);
2137
  });
2138
-
2139
  activeModelName = preset.name;
2140
  isModelReady = true;
2141
-
2142
  const modelDescEl = document.querySelector("#modelDesc");
2143
  if (modelDescEl) {
2144
  modelDescEl.textContent = preset.desc;
@@ -2151,31 +2058,31 @@ async function init() {
2151
  const loadProgress = document.querySelector("#loadProgress");
2152
  const loadStatus = document.querySelector("#loadStatus");
2153
  const loadPercent = document.querySelector("#loadPercent");
2154
-
2155
  const updateProgress = (pct, text) => {
2156
  if (loadProgress) loadProgress.style.width = `${pct}%`;
2157
  if (loadPercent) loadPercent.textContent = `${Math.round(pct)}%`;
2158
  if (loadStatus) loadStatus.textContent = text;
2159
  };
2160
-
2161
  updateProgress(2, "Initializing NanoMaestro AI engine...");
2162
-
2163
  try {
2164
  updateReadouts();
2165
  startBtn.disabled = true;
2166
  if (renderSongBtn) renderSongBtn.disabled = true;
2167
-
2168
  const topSelect = document.querySelector("#topModelSelect");
2169
  const settingsSelect = document.querySelector("#modelSelect");
2170
  const selectedKey = (topSelect ? topSelect.value : null) || (settingsSelect ? settingsSelect.value : "pro");
2171
-
2172
  await loadSelectedModel(selectedKey, updateProgress);
2173
-
2174
  updateProgress(90, `Loading ${currentInstrument} audio samples...`);
2175
  await ensureInstrument();
2176
-
2177
  updateProgress(100, "Ready!");
2178
-
2179
  setTimeout(() => {
2180
  if (loadingOverlay) {
2181
  loadingOverlay.classList.add("fade-out");
@@ -2183,11 +2090,11 @@ async function init() {
2183
  setStatus(`Ready: ${activeModelName}`, "idle");
2184
  startBtn.disabled = false;
2185
  if (renderSongBtn) renderSongBtn.disabled = false;
2186
-
2187
  resizeCanvas();
2188
  drawVisualizer();
2189
  }, 600);
2190
-
2191
  } catch (error) {
2192
  console.error("Initialization failed:", error);
2193
  if (loadStatus) {
@@ -2310,10 +2217,10 @@ delayInput.addEventListener("input", (e) => {
2310
  toggleButtons.forEach(btn => {
2311
  btn.addEventListener("click", () => {
2312
  if (btn.disabled) return;
2313
-
2314
  toggleButtons.forEach(b => b.classList.remove("active"));
2315
  btn.classList.add("active");
2316
-
2317
  const value = btn.dataset.value;
2318
  if (value === "midi") {
2319
  midiSeedControls.style.display = "block";
@@ -2328,10 +2235,10 @@ toggleButtons.forEach(btn => {
2328
  midiBpmModeButtons.forEach(btn => {
2329
  btn.addEventListener("click", () => {
2330
  if (btn.disabled) return;
2331
-
2332
  midiBpmModeButtons.forEach(b => b.classList.remove("active"));
2333
  btn.classList.add("active");
2334
-
2335
  midiBpmMode = btn.dataset.value;
2336
  });
2337
  });
@@ -2339,31 +2246,31 @@ midiBpmModeButtons.forEach(btn => {
2339
  midiFileInput.addEventListener("change", async (e) => {
2340
  const file = e.target.files?.[0];
2341
  if (!file) return;
2342
-
2343
  midiFileName = file.name;
2344
  midiFileNameEl.textContent = `File: ${file.name}`;
2345
  midiFileInfo.style.display = "block";
2346
  midiFileStatsEl.textContent = "Parsing MIDI file...";
2347
-
2348
  try {
2349
  const buffer = await file.arrayBuffer();
2350
  const parser = new MidiParser(buffer);
2351
  const parsed = parser.parse();
2352
-
2353
  const { tokens, maxBar } = tokenizeMidi(parsed, 64);
2354
  midiTokens = tokens;
2355
  midiBpm = parsed.bpm;
2356
  midiTotalBars = Math.max(1, maxBar + 1);
2357
-
2358
  midiFileStatsEl.textContent = `BPM: ${parsed.bpm} | Total Bars: ${midiTotalBars} | Notes: ${parsed.notes.length}`;
2359
-
2360
  const minBar = findMinStartBar(tokens);
2361
  midiStartBarInput.min = String(minBar);
2362
  midiStartBarInput.max = String(midiTotalBars - 1);
2363
  midiStartBarInput.value = String(minBar);
2364
  midiStartBar = minBar;
2365
  midiStartBarValue.textContent = String(minBar);
2366
-
2367
  const barsData = analyzeMidiTokens(tokens);
2368
  renderMidiTimeline(barsData);
2369
  updateMidiStartBarText();
@@ -2388,88 +2295,10 @@ releaseInput.addEventListener("input", (e) => {
2388
  setRelease(rel);
2389
  });
2390
 
2391
- if (remixFileInput) {
2392
- remixFileInput.addEventListener("change", async (e) => {
2393
- const file = e.target.files?.[0];
2394
- if (!file) return;
2395
-
2396
- remixFileName = file.name;
2397
- if (remixFileNameEl) remixFileNameEl.textContent = `File: ${file.name}`;
2398
- if (remixFileInfo) remixFileInfo.style.display = "block";
2399
- if (remixFileStatsEl) remixFileStatsEl.textContent = "Parsing MIDI file...";
2400
-
2401
- try {
2402
- const buffer = await file.arrayBuffer();
2403
- const parser = new MidiParser(buffer);
2404
- const parsed = parser.parse();
2405
-
2406
- const { tokens, maxBar } = tokenizeMidi(parsed, 64);
2407
- remixTokens = tokens;
2408
- remixParsedMidi = parsed;
2409
- midiTokens = tokens;
2410
-
2411
- if (remixFileStatsEl) {
2412
- remixFileStatsEl.textContent = `BPM: ${parsed.bpm} | Total Bars: ${maxBar + 1} | Notes: ${parsed.notes.length}`;
2413
- }
2414
-
2415
- setPerformanceBpm(parsed.bpm);
2416
- activePlayingStyle = "remix";
2417
- } catch (error) {
2418
- console.error(error);
2419
- if (remixFileStatsEl) remixFileStatsEl.textContent = `Error: ${error.message}`;
2420
- }
2421
- });
2422
- }
2423
-
2424
- if (remixSubModeButtons.length) {
2425
- remixSubModeButtons.forEach(btn => {
2426
- btn.addEventListener("click", () => {
2427
- remixSubModeButtons.forEach(b => b.classList.remove("active"));
2428
- btn.classList.add("active");
2429
- remixSubMode = btn.dataset.value;
2430
-
2431
- if (remixSubModeDesc) {
2432
- if (remixSubMode === "over") {
2433
- remixSubModeDesc.textContent = "Original plays on Piano + AI adds live accompaniment instruments on top.";
2434
- if (remixArrangementBadge) remixArrangementBadge.style.display = "flex";
2435
- } else {
2436
- remixSubModeDesc.textContent = "AI plays the entire piece from your MIDI using neural expression and embellishments.";
2437
- if (remixArrangementBadge) remixArrangementBadge.style.display = "none";
2438
- }
2439
- }
2440
- });
2441
- });
2442
- }
2443
-
2444
- if (remixCreativityInput) {
2445
- remixCreativityInput.addEventListener("input", (e) => {
2446
- remixCreativity = Number(e.target.value) / 100;
2447
- if (remixCreativityVal) remixCreativityVal.textContent = `${e.target.value}%`;
2448
- if (remixCreativityHint) {
2449
- const val = Number(e.target.value);
2450
- if (val >= 80) {
2451
- remixCreativityHint.textContent = `At ${val}%, AI harmonizes closely with your original notes & structure while adding its own natural flair.`;
2452
- } else if (val >= 40) {
2453
- remixCreativityHint.textContent = `At ${val}%, AI balances original motifs with improvisational variations.`;
2454
- } else {
2455
- remixCreativityHint.textContent = `At ${val}%, AI takes loose inspiration from key & rhythm to create a free accompaniment.`;
2456
- }
2457
- }
2458
- });
2459
- }
2460
-
2461
- function updateRemixBadgeText() {
2462
- if (!remixAiLayerBadge) return;
2463
- const selectedOpt = instrumentSelect ? instrumentSelect.options[instrumentSelect.selectedIndex] : null;
2464
- const label = selectedOpt ? selectedOpt.text.replace(/Solo|Multi-Instrument /g, "").trim() : currentInstrument;
2465
- remixAiLayerBadge.textContent = `AI: ${label}`;
2466
- }
2467
-
2468
  const instrumentSelect = document.querySelector("#instrumentSelect");
2469
  if (instrumentSelect) {
2470
  instrumentSelect.addEventListener("change", async (e) => {
2471
  currentInstrument = e.target.value;
2472
- updateRemixBadgeText();
2473
  if (synth || bassSynth || chordSynth) {
2474
  const isAlreadyRunning = running;
2475
  if (isAlreadyRunning) {
@@ -2516,6 +2345,5 @@ window.addEventListener("resize", resizeCanvas);
2516
 
2517
  // Initialize MIDI sub-mode UI copy on load
2518
  setMidiSubMode("single");
2519
- updateRemixBadgeText();
2520
 
2521
  void init();
 
163
  if (bpmInput) bpmInput.value = String(bpmClamped);
164
  if (bpmValueEl) bpmValueEl.textContent = `${bpmClamped} BPM`;
165
  if (tempoEl) tempoEl.textContent = String(bpmClamped);
166
+
167
  if (rushBadgeEl) {
168
  if (bpmClamped >= 240) {
169
  rushBadgeEl.style.display = "inline-block";
 
171
  rushBadgeEl.style.display = "none";
172
  }
173
  }
174
+
175
  worker.postMessage({ action: "updateBpm", bpm: bpmClamped });
176
  void pumpTokens();
177
  }
 
318
  const midiBpmModeGroup = document.querySelector("#midiBpmModeGroup");
319
  const midiBpmModeButtons = midiBpmModeGroup ? midiBpmModeGroup.querySelectorAll(".toggle-btn") : [];
320
 
321
+ // MIDI sub-mode tabs: "single" (continue one uploaded track) vs "trained" (learn a style from many)
322
  const midiModeTabGroup = document.querySelector("#midiModeTabGroup");
323
  const midiModeTabButtons = midiModeTabGroup ? midiModeTabGroup.querySelectorAll(".mode-tab-btn") : [];
324
  const singleTrackPanel = document.querySelector("#singleTrackPanel");
325
  const trainedStylePanel = document.querySelector("#trainedStylePanel");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
  const trainFilesInput = document.querySelector("#trainFilesInput");
328
  const trainFilesList = document.querySelector("#trainFilesList");
 
336
  const downloadStyleBtn = document.querySelector("#downloadStyleBtn");
337
  const loadStyleInput = document.querySelector("#loadStyleInput");
338
 
339
+ let midiSubMode = "single"; // "single" | "trained"
 
 
 
 
 
 
 
340
  let pendingTrainingFiles = []; // { fileName, tokens, noteCount }
341
  let hasActiveStyle = false;
342
  let activeStyleMeta = null;
 
358
  this.view = new DataView(arrayBuffer);
359
  this.pos = 0;
360
  }
361
+
362
  readUint8() {
363
  const v = this.view.getUint8(this.pos);
364
  this.pos += 1;
365
  return v;
366
  }
367
+
368
  readUint16() {
369
  const v = this.view.getUint16(this.pos);
370
  this.pos += 2;
371
  return v;
372
  }
373
+
374
  readUint32() {
375
  const v = this.view.getUint32(this.pos);
376
  this.pos += 4;
377
  return v;
378
  }
379
+
380
  readBytes(len) {
381
  const buf = new Uint8Array(this.view.buffer, this.pos + this.view.byteOffset, len);
382
  this.pos += len;
383
  return buf;
384
  }
385
+
386
  readVarInt() {
387
  let value = 0;
388
  while (true) {
 
392
  }
393
  return value;
394
  }
395
+
396
  parse() {
397
  const mthd = String.fromCharCode(...this.readBytes(4));
398
  if (mthd !== "MThd") throw new Error("Not a valid MIDI file (missing MThd)");
399
+
400
  const headerLength = this.readUint32();
401
  const format = this.readUint16();
402
  const numTracks = this.readUint16();
403
  const division = this.readUint16();
404
+
405
  if (headerLength > 6) {
406
  this.readBytes(headerLength - 6);
407
  }
408
+
409
  let bpm = 120;
410
  const notes = [];
411
  const activeNotes = new Map();
412
+
413
  for (let t = 0; t < numTracks; t++) {
414
  const mtrk = String.fromCharCode(...this.readBytes(4));
415
  if (mtrk !== "MTrk") {
 
417
  this.readBytes(len);
418
  continue;
419
  }
420
+
421
  const trackLength = this.readUint32();
422
  const endPos = this.pos + trackLength;
423
+
424
  let tick = 0;
425
  let runningStatus = 0;
426
+
427
  while (this.pos < endPos) {
428
  const deltaTime = this.readVarInt();
429
  tick += deltaTime;
430
+
431
  let status = this.readUint8();
432
  if (status < 0x80) {
433
  this.pos -= 1;
 
435
  } else {
436
  runningStatus = status;
437
  }
438
+
439
  const eventType = status & 0xF0;
440
  const channel = status & 0x0F;
441
+
442
  if (eventType === 0x90) {
443
  const pitch = this.readUint8();
444
  const velocity = this.readUint8();
 
477
  const metaType = this.readUint8();
478
  const len = this.readVarInt();
479
  const data = this.readBytes(len);
480
+
481
  if (metaType === 0x51 && len === 3) {
482
  const tempo = (data[0] << 16) | (data[1] << 8) | data[2];
483
  bpm = Math.round(60000000 / tempo);
 
492
  }
493
  }
494
  }
495
+
496
  for (const [key, active] of activeNotes.entries()) {
497
  const [pitch, channel] = key.split("_").map(Number);
498
  notes.push({
 
502
  velocity: active.velocity
503
  });
504
  }
505
+
506
  return { bpm, division, notes };
507
  }
508
  }
 
511
  function tokenizeMidi(parsedMidi, grid = 64) {
512
  const { bpm, division, notes } = parsedMidi;
513
  const stepsPerQuarter = grid / 4;
514
+
515
  const quantizedNotes = notes.map(note => {
516
  const start_step = Math.round((note.startTick / division) * stepsPerQuarter);
517
  const end_step = Math.round((note.endTick / division) * stepsPerQuarter);
518
  const duration_steps = Math.max(1, end_step - start_step);
519
  const velocity_bucket = Math.max(1, Math.min(8, Math.ceil(note.velocity / 16)));
520
+
521
  return {
522
  pitch: note.pitch,
523
  start_step,
 
525
  velocity_bucket
526
  };
527
  });
528
+
529
  quantizedNotes.sort((a, b) => {
530
  if (a.start_step !== b.start_step) return a.start_step - b.start_step;
531
  return a.pitch - b.pitch;
532
  });
533
+
534
  const tokens = ["BOS", `BPM_${Math.round(bpm)}`, `GRID_${grid}`];
535
  let currentBar = -1;
536
+
537
  const notesByStep = new Map();
538
  for (const note of quantizedNotes) {
539
  if (!notesByStep.has(note.start_step)) {
 
541
  }
542
  notesByStep.get(note.start_step).push(note);
543
  }
544
+
545
  const steps = Array.from(notesByStep.keys()).sort((a, b) => a - b);
546
  for (const step of steps) {
547
  const note_bar = Math.floor(step / grid);
548
  const note_pos = step % grid;
549
+
550
  while (currentBar < note_bar) {
551
  tokens.push("BAR");
552
  currentBar += 1;
553
  }
554
+
555
  tokens.push(`POS_${note_pos}`);
556
+
557
  const stepNotes = notesByStep.get(step);
558
  for (const note of stepNotes) {
559
  tokens.push(`NOTE_${note.pitch}`);
 
561
  tokens.push(`VEL_${note.velocity_bucket}`);
562
  }
563
  }
564
+
565
  return { tokens, maxBar: currentBar };
566
  }
567
 
568
  function findMinStartBar(tokens) {
569
  let barCount = 0;
570
  let tokenCount = 0;
571
+
572
  for (let i = 0; i < tokens.length; i++) {
573
  const t = tokens[i];
574
  if (t === "BAR") {
 
622
  function getWarmUpInfo(tokens, targetBar) {
623
  let barCount = 0;
624
  const tokensUpToBar = [];
625
+
626
  for (const t of tokens) {
627
  if (t === "BAR") {
628
  if (barCount === targetBar) {
 
632
  }
633
  tokensUpToBar.push(t);
634
  }
635
+
636
  const totalTokens = tokensUpToBar.length;
637
  const warmUpCount = Math.min(256, totalTokens);
638
  const startIndex = totalTokens - warmUpCount;
639
+
640
  let currentBarOfStart = -1;
641
  for (let i = 0; i < startIndex; i++) {
642
  if (tokens[i] === "BAR") {
643
  currentBarOfStart += 1;
644
  }
645
  }
646
+
647
  return {
648
  startBar: Math.max(0, currentBarOfStart),
649
  endBar: targetBar - 1,
 
656
  const midiTimeline = document.querySelector("#midiTimeline");
657
  if (!midiTimeline) return;
658
  midiTimeline.innerHTML = "";
659
+
660
  if (!barsData || barsData.length === 0) {
661
  midiTimeline.style.display = "none";
662
  return;
663
  }
664
+
665
  midiTimeline.style.display = "flex";
666
+
667
  const maxNotes = Math.max(...barsData.map(b => b.noteCount), 1);
668
  const minBar = findMinStartBar(midiTokens);
669
+
670
  barsData.forEach((bar, index) => {
671
  const col = document.createElement("div");
672
  col.className = "timeline-bar-col";
673
  col.dataset.barNum = String(index);
674
  col.dataset.barLabel = `${index + 1}`;
675
+
676
  const totalBars = barsData.length;
677
  const labelInterval = totalBars > 64 ? 16 : (totalBars > 32 ? 8 : 4);
678
  if (index % labelInterval === 0) {
679
  col.classList.add("labeled");
680
  }
681
+
682
  const densityVal = (bar.noteCount / maxNotes) * 100;
683
+
684
  const fill = document.createElement("div");
685
  fill.className = "density-fill";
686
  fill.style.height = `${Math.max(10, densityVal)}%`;
687
+
688
  col.appendChild(fill);
689
+
690
  if (index < minBar) {
691
  col.classList.add("disabled");
692
  } else {
 
698
  updateMidiStartBarText();
699
  });
700
  }
701
+
702
  midiTimeline.appendChild(col);
703
  });
704
+
705
  updateMidiTimelineHighlights();
706
  }
707
 
708
  function updateMidiTimelineHighlights() {
709
  const midiTimeline = document.querySelector("#midiTimeline");
710
  if (!midiTimeline || !midiTokens || midiTokens.length === 0) return;
711
+
712
  const cols = midiTimeline.querySelectorAll(".timeline-bar-col");
713
  const info = getWarmUpInfo(midiTokens, midiStartBar);
714
+
715
  cols.forEach((col, index) => {
716
  col.classList.remove("in-warmup", "is-selected");
717
+
718
  if (index === midiStartBar) {
719
  col.classList.add("is-selected");
720
  if (typeof col.scrollIntoViewIfNeeded === "function") {
 
764
  });
765
  if (singleTrackPanel) singleTrackPanel.style.display = mode === "single" ? "block" : "none";
766
  if (trainedStylePanel) trainedStylePanel.style.display = mode === "trained" ? "block" : "none";
 
 
 
 
 
 
 
 
 
767
  refreshMidiSimilarityCopy();
768
  }
769
 
 
918
  btn.addEventListener("click", () => {
919
  if (btn.disabled) return;
920
  setMidiSubMode(btn.dataset.mode);
921
+ if (btn.dataset.mode === "trained" && hasActiveStyle) {
 
 
922
  activePlayingStyle = "trained";
923
  } else if (btn.dataset.mode === "single") {
924
  activePlayingStyle = "midi";
 
956
  function setStatus(message, state = "idle") {
957
  if (appStatusEl) appStatusEl.textContent = message;
958
  if (statusTextEl) statusTextEl.textContent = state.toUpperCase();
959
+
960
  if (statusDotEl) {
961
  statusDotEl.className = "status-dot";
962
  if (state === "playing") {
 
972
  const currentBpm = Number(tempoEl?.textContent || 120);
973
  const bpmScale = Math.max(1.0, currentBpm / 110);
974
  const baseTarget = Math.round(TARGET_QUEUE_EVENTS * bpmScale);
975
+
976
  if (avgPumpMs <= 0) return baseTarget;
977
  const dynamicChunk = Math.min(192, Math.max(64, Math.round(64 * (currentBpm / 120))));
978
  const cyclesOfSlack = Math.max(3, Math.ceil(avgPumpMs / LOOKAHEAD_MS) + 2);
 
1002
  return (Number(match[3]) + 1) * 12 + semitone + accidental;
1003
  }
1004
 
1005
+ function recordVisualEvent(event, startTime) {
1006
  if (event.type !== "note") return;
1007
  event.notes.forEach((note, index) => {
1008
  const midi = midiFromPitchName(note);
1009
  if (midi === null) return;
1010
+ const duration = event.perNoteDurations
1011
+ ? event.perNoteDurations[index]
1012
  : event.duration;
1013
+ visualNotes.push({
1014
+ midi,
1015
+ note,
1016
+ start: startTime,
1017
  duration: Math.max(0.08, duration),
1018
+ velocity: event.velocities ? event.velocities[index] : 0.72
 
1019
  });
1020
  });
1021
  const now = Tone.now();
 
1064
  if (!running) return;
1065
  const now = Tone.now();
1066
  if (nextNoteTime < now + 0.08) nextNoteTime = now + 0.08;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1067
  while (queue.length && nextNoteTime < now + SCHEDULE_AHEAD_SECONDS) {
1068
  const event = queue.shift();
1069
  if (event.type === "note") {
 
1105
  }
1106
  });
1107
  }
1108
+
1109
  if (isRecording) {
1110
  const eventTime = nextNoteTime;
1111
  if (event.perNoteDurations) {
 
1134
  });
1135
  }
1136
  }
1137
+
1138
  recordVisualEvent({ ...event, duration: event.duration || Math.max(...(event.perNoteDurations ?? [0.2])) }, nextNoteTime);
1139
  }
1140
  nextNoteTime += event.advance ?? event.duration;
1141
  }
1142
+
1143
  // Proactive pumping to ensure queue never starves at high BPMs
1144
  if (!isOfflineRendering && queue.length < currentTarget()) {
1145
  void pumpTokens();
1146
  }
1147
+
1148
  updateReadouts();
1149
  schedulerId = window.setTimeout(scheduleAudio, LOOKAHEAD_MS);
1150
  }
 
1165
  }
1166
 
1167
  async function createSampler(instrumentName) {
1168
+ if (synth) { try { synth.dispose(); } catch (e) {} synth = null; }
1169
+ if (bassSynth) { try { bassSynth.dispose(); } catch (e) {} bassSynth = null; }
1170
+ if (chordSynth) { try { chordSynth.dispose(); } catch (e) {} chordSynth = null; }
1171
 
1172
  const initialRel = Number(releaseInput.value);
1173
 
 
1228
 
1229
  async function ensureInstrument() {
1230
  if (synth) return;
1231
+
1232
  const initialVol = Number(volumeInput.value);
1233
  const initialRev = Number(reverbInput.value);
1234
  const initialDel = Number(delayInput.value);
 
1236
 
1237
  reverb = new Tone.Reverb({ decay: 2.8, wet: initialRev / 100 }).toDestination();
1238
  delay = new Tone.FeedbackDelay({ delayTime: "8n", feedback: 0.18, wet: initialDel / 100 }).connect(reverb);
1239
+
1240
  await createSampler(currentInstrument);
 
 
 
 
 
 
 
 
 
 
 
 
 
1241
  setVolume(initialVol);
1242
+
1243
  if (reverbValue) reverbValue.textContent = `${initialRev}%`;
1244
  if (delayValue) delayValue.textContent = `${initialDel}%`;
1245
  if (releaseValue) releaseValue.textContent = `${initialRel.toFixed(1)}s`;
 
1250
  startBtn.disabled = true;
1251
  if (renderSongBtn) renderSongBtn.disabled = true;
1252
  setStatus("Starting audio...", "loading");
1253
+
1254
  await Tone.start();
1255
  await ensureInstrument();
1256
+
1257
  queue = [];
1258
  generatedEvents = 0;
1259
  visualNotes = [];
1260
  avgPumpMs = 0;
1261
+
 
1262
  const targetBpm = bpmInput ? Number(bpmInput.value) : 120;
1263
  if (tempoEl) tempoEl.textContent = String(targetBpm);
1264
+
1265
  setStatus("Warming AI model prompt...", "buffering");
1266
+
1267
  const warmStart = performance.now();
1268
  try {
1269
  await new Promise((resolve, reject) => {
 
1275
  topK: Math.max(1, Number(topKInput.value)),
1276
  bpm: targetBpm,
1277
  playingStyle: activePlayingStyle,
1278
+ midiTokens: (activePlayingStyle === "midi") ? midiTokens : [],
 
 
1279
  midiStartBar: midiStartBar,
1280
  midiBpmMode: midiBpmMode,
1281
  heuristicSettings: getHeuristicSettings(),
 
1288
  return;
1289
  }
1290
  avgPumpMs = performance.now() - warmStart;
1291
+
1292
  running = true;
1293
  stopBtn.disabled = false;
1294
  if (newSongBtn) newSongBtn.disabled = false;
 
1299
  midiBpmModeButtons.forEach(btn => btn.disabled = true);
1300
  midiFileInput.disabled = true;
1301
  midiStartBarInput.disabled = true;
1302
+
1303
  setStatus("Buffering ahead...", "buffering");
1304
  const primeDeadline = performance.now() + STARTUP_PRIME_BUDGET_MS;
1305
  while (running && queue.length < currentTarget() && performance.now() < primeDeadline) {
1306
  await pumpTokens();
1307
  }
1308
+
1309
  setStatus(`Playing ${activeModelName}`, "playing");
1310
+
1311
  nextNoteTime = Tone.now() + 0.12;
1312
  startVisualizer();
1313
  scheduleAudio();
 
1318
  stopRecording(true);
1319
  }
1320
  running = false;
 
1321
  window.clearTimeout(schedulerId);
1322
  schedulerId = 0;
1323
  window.clearTimeout(pumpWatchdogId);
1324
  pumpWatchdogId = 0;
1325
  pumping = false;
1326
  pumpPromiseResolve = null;
1327
+
1328
  worker.postMessage({ action: "stop" });
1329
+
1330
  startBtn.disabled = !isModelReady;
1331
  if (renderSongBtn) renderSongBtn.disabled = !isModelReady;
1332
  stopBtn.disabled = true;
 
1338
  midiBpmModeButtons.forEach(btn => btn.disabled = false);
1339
  midiFileInput.disabled = false;
1340
  midiStartBarInput.disabled = false;
1341
+
1342
+ if (synth) { try { synth.dispose(); } catch (e) {} synth = null; }
1343
+ if (bassSynth) { try { bassSynth.dispose(); } catch (e) {} bassSynth = null; }
1344
+ if (chordSynth) { try { chordSynth.dispose(); } catch (e) {} chordSynth = null; }
1345
 
1346
+ if (reverb) { try { reverb.dispose(); } catch (e) {} reverb = null; }
1347
+ if (delay) { try { delay.dispose(); } catch (e) {} delay = null; }
 
 
 
 
 
1348
 
1349
  if (visualFrame) cancelAnimationFrame(visualFrame);
1350
  visualFrame = 0;
 
1355
  function startFullSongRender() {
1356
  if (running) stop();
1357
  if (!isModelReady) return;
1358
+
1359
  isOfflineRendering = true;
1360
  if (renderProgressModal) {
1361
  renderProgressModal.style.display = "flex";
 
1376
  topK: Math.max(1, Number(topKInput.value)),
1377
  bpm: targetBpm,
1378
  playingStyle: activePlayingStyle,
1379
+ midiTokens: (activePlayingStyle === "midi") ? midiTokens : [],
 
 
1380
  midiStartBar: midiStartBar,
1381
  midiBpmMode: midiBpmMode,
1382
  heuristicSettings: getHeuristicSettings()
 
1387
  if (renderDoneModal) {
1388
  renderDoneModal.style.display = "flex";
1389
  }
1390
+
1391
  const events = data.events || [];
1392
  let durationSec = 0;
1393
  events.forEach(e => {
1394
  durationSec += e.advance ?? e.duration ?? 0;
1395
  });
1396
+
1397
  if (doneDurationVal) doneDurationVal.textContent = `${durationSec.toFixed(1)}s`;
1398
  if (doneNoteCountVal) doneNoteCountVal.textContent = `${data.noteCount || 0} Notes`;
1399
  if (doneBpmVal) doneBpmVal.textContent = `${data.bpm || 120} BPM`;
 
1401
 
1402
  async function previewRenderedSong() {
1403
  if (!lastRenderedResult || !lastRenderedResult.events) return;
1404
+
1405
  if (renderDoneModal) renderDoneModal.style.display = "none";
1406
  if (running) stop();
1407
+
1408
  setStatus("Starting pre-rendered performance...", "loading");
1409
  await Tone.start();
1410
  await ensureInstrument();
1411
+
1412
  queue = [...lastRenderedResult.events];
1413
  generatedEvents = lastRenderedResult.noteCount || queue.filter(e => e.type === "note").length;
1414
  visualNotes = [];
1415
+
1416
  running = true;
1417
  stopBtn.disabled = false;
1418
  if (newSongBtn) newSongBtn.disabled = false;
1419
  if (startBtn) startBtn.disabled = true;
1420
  if (renderSongBtn) renderSongBtn.disabled = true;
1421
+
1422
  setStatus(`Previewing Rendered Song (${dataBpm(lastRenderedResult.bpm)} BPM)`, "playing");
1423
+
1424
  nextNoteTime = Tone.now() + 0.12;
1425
  startVisualizer();
1426
  scheduleAudio();
 
1432
 
1433
  function downloadRenderedMidiFile() {
1434
  if (!lastRenderedResult || !lastRenderedResult.events) return;
1435
+
1436
  const events = lastRenderedResult.events;
1437
  const bpm = lastRenderedResult.bpm || 120;
1438
+
1439
  const compiledNotes = [];
1440
  let currentTime = 0;
1441
+
1442
  for (const e of events) {
1443
  if (e.type === "note") {
1444
  if (e.perNoteDurations) {
 
1469
  }
1470
  currentTime += e.advance ?? e.duration ?? 0;
1471
  }
1472
+
1473
  if (compiledNotes.length > 0) {
1474
  const fileBytes = compileMidiFile(compiledNotes, bpm);
1475
  downloadMidi(fileBytes, "nanomaestro_ai_1min_song.mid");
 
1481
  isRecording = true;
1482
  recordedNotes = [];
1483
  recordingStartTime = Tone.now();
1484
+
1485
  if (recordBtn) {
1486
  recordBtn.classList.add("btn-recording");
1487
  if (recordIcon) recordIcon.classList.add("pulse-record");
 
1495
  function stopRecording(download = true) {
1496
  if (!isRecording) return;
1497
  isRecording = false;
1498
+
1499
  if (recordBtn) {
1500
  recordBtn.classList.remove("btn-recording");
1501
  if (recordIcon) recordIcon.classList.remove("pulse-record");
 
1504
  }
1505
  if (recordBtnText) recordBtnText.textContent = "Record";
1506
  }
1507
+
1508
  if (download && recordedNotes.length > 0) {
1509
  const bpm = Number(tempoEl?.textContent || 120);
1510
  const fileBytes = compileMidiFile(recordedNotes, bpm);
 
1529
  function compileMidiFile(recordedNotes, bpm) {
1530
  const division = 480;
1531
  const trackBytes = [];
1532
+
1533
  const tempoMicro = Math.round(60000000 / bpm);
1534
  trackBytes.push(
1535
  0, 0xFF, 0x51, 0x03,
 
1537
  (tempoMicro >> 8) & 0xFF,
1538
  tempoMicro & 0xFF
1539
  );
1540
+
1541
  const midiEvents = [];
1542
  for (const note of recordedNotes) {
1543
  const onTicks = Math.round(note.time * (bpm * division / 60));
1544
  const offTicks = Math.round((note.time + note.duration) * (bpm * division / 60));
1545
+
1546
  midiEvents.push({ ticks: onTicks, type: 0x90, note: note.midi, velocity: Math.round(note.velocity * 127) });
1547
  midiEvents.push({ ticks: offTicks, type: 0x80, note: note.midi, velocity: 0 });
1548
  }
1549
+
1550
  midiEvents.sort((a, b) => {
1551
  if (a.ticks !== b.ticks) return a.ticks - b.ticks;
1552
  return a.type - b.type;
1553
  });
1554
+
1555
  let lastTicks = 0;
1556
  for (const event of midiEvents) {
1557
  const delta = event.ticks - lastTicks;
 
1559
  trackBytes.push(...encodeVLQ(delta));
1560
  trackBytes.push(event.type, event.note, event.velocity);
1561
  }
1562
+
1563
  trackBytes.push(0, 0xFF, 0x2F, 0x00);
1564
+
1565
  const headerBytes = [0x4d, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, (division >> 8) & 0xFF, division & 0xFF];
1566
  const trackLen = trackBytes.length;
1567
  const trackHeaderBytes = [0x4d, 0x54, 0x72, 0x6b, (trackLen >> 24) & 0xFF, (trackLen >> 16) & 0xFF, (trackLen >> 8) & 0xFF, trackLen & 0xFF];
1568
+
1569
  const fileBytes = new Uint8Array(headerBytes.length + trackHeaderBytes.length + trackBytes.length);
1570
  fileBytes.set(headerBytes, 0);
1571
  fileBytes.set(trackHeaderBytes, headerBytes.length);
1572
  fileBytes.set(trackBytes, headerBytes.length + trackHeaderBytes.length);
1573
+
1574
  return fileBytes;
1575
  }
1576
 
 
1607
  const whiteKeyW = width / numWhiteKeys;
1608
  const noteInOctave = (midi - minMidi) % 12;
1609
  const octave = Math.floor((midi - minMidi) / 12);
1610
+
1611
  const whiteKeyOffsets = [0, null, 1, null, 2, 3, null, 4, null, 5, null, 6];
1612
  const isBlack = whiteKeyOffsets[noteInOctave] === null;
1613
+
1614
  if (!isBlack) {
1615
  const whiteIdx = octave * 7 + whiteKeyOffsets[noteInOctave];
1616
  const x = whiteIdx * whiteKeyW;
 
1628
  function drawVisualizer() {
1629
  const width = canvasWidth;
1630
  const height = canvasHeight;
1631
+
1632
  const perfNow = performance.now();
1633
  const rawAudioTime = Tone.now();
1634
  if (rawAudioTime !== lastAudioTime) {
 
1637
  }
1638
  const smoothNow = lastAudioTime + (perfNow - lastPerfTime) / 1000;
1639
  const visualNow = smoothNow - VISUAL_DELAY;
1640
+
1641
  const minMidi = 36;
1642
  const maxMidi = 96;
1643
  const secondsVisible = 4.5;
1644
  const keyboardH = width < 640 ? 80 : 120;
1645
  const playLineY = height - keyboardH;
1646
  const speed = playLineY / secondsVisible;
1647
+
1648
  canvasCtx.clearRect(0, 0, width, height);
1649
+
1650
  for (let m = minMidi; m <= maxMidi; m++) {
1651
  const keyInfo = getKeyPosition(m, width);
1652
  if (keyInfo.isBlack) {
 
1654
  canvasCtx.fillRect(keyInfo.x, 0, keyInfo.w, playLineY);
1655
  }
1656
  }
1657
+
1658
  const currentBpm = Number(tempoEl?.textContent || 120);
1659
  const secondsPerBeat = 60 / currentBpm;
1660
+
1661
  const startBeat = Math.floor((visualNow - 1.0) / secondsPerBeat);
1662
  const endBeat = Math.ceil((visualNow + secondsVisible) / secondsPerBeat);
1663
+
1664
  canvasCtx.font = "8px ui-sans-serif, system-ui, sans-serif";
1665
  for (let b = startBeat; b <= endBeat; b++) {
1666
  if (b < 0) continue;
1667
  const beatTime = b * secondsPerBeat;
1668
  const y = playLineY - (beatTime - visualNow) * speed;
1669
  if (y < 0 || y > playLineY) continue;
1670
+
1671
  const isBar = b % 4 === 0;
1672
  if (isBar) {
1673
  canvasCtx.strokeStyle = "rgba(255, 255, 255, 0.06)";
 
1678
  canvasCtx.strokeStyle = "rgba(255, 255, 255, 0.015)";
1679
  canvasCtx.lineWidth = 0.5;
1680
  }
1681
+
1682
  canvasCtx.beginPath();
1683
  canvasCtx.moveTo(0, y);
1684
  canvasCtx.lineTo(width, y);
1685
  canvasCtx.stroke();
1686
  }
1687
+
1688
  const activePitches = new Set();
1689
+
1690
  for (const item of visualNotes) {
1691
  const end = item.start + item.duration;
1692
  if (end < visualNow - 0.5 || item.start > visualNow + secondsVisible) continue;
1693
+
1694
  const active = item.start <= visualNow && end >= visualNow;
1695
  const midiClamped = Math.max(minMidi, Math.min(maxMidi, item.midi));
1696
  if (active) activePitches.add(midiClamped);
1697
+
1698
  const keyInfo = getKeyPosition(midiClamped, width);
1699
  const noteW = keyInfo.isBlack ? keyInfo.w * 0.85 : keyInfo.w * 0.75;
1700
  const noteX = keyInfo.center - noteW / 2;
1701
+
1702
  const bottomY = playLineY - (item.start - visualNow) * speed;
1703
  const topY = playLineY - (end - visualNow) * speed;
1704
+
1705
  const drawTop = Math.max(-100, topY);
1706
  const drawBottom = Math.max(-100, bottomY);
1707
  const noteH = drawBottom - drawTop;
1708
+
1709
  if (noteH > 0) {
1710
+ // Dynamic Multi-Instrument Color Coding in Visualizer
1711
+ if (active) {
1712
+ canvasCtx.fillStyle = "#ffffff";
1713
+ canvasCtx.shadowBlur = 12;
1714
+ canvasCtx.shadowColor = item.midi < 53 ? "rgba(245, 158, 11, 0.9)" : (item.midi < 72 ? "rgba(52, 211, 153, 0.9)" : "rgba(96, 165, 250, 0.9)");
1715
+ canvasCtx.globalAlpha = 0.98;
 
 
 
 
 
 
1716
  } else {
1717
+ // Voice layering colors: Bass=Amber, Chords=Emerald, Lead=Sky Blue
1718
+ canvasCtx.fillStyle = item.midi < 53 ? "#d97706" : (item.midi < 72 ? "#059669" : "#2563eb");
1719
+ canvasCtx.shadowBlur = 0;
1720
+ canvasCtx.globalAlpha = 0.65;
 
 
 
 
 
 
 
 
1721
  }
1722
+
1723
  canvasCtx.beginPath();
1724
  if (typeof canvasCtx.roundRect === "function") {
1725
  canvasCtx.roundRect(noteX, drawTop, noteW, noteH, Math.min(noteW / 2, 4));
 
1729
  canvasCtx.fill();
1730
  }
1731
  }
1732
+
1733
  canvasCtx.shadowBlur = 0;
1734
  canvasCtx.globalAlpha = 1.0;
1735
+
1736
  const numWhiteKeys = 36;
1737
  const whiteKeyW = width / numWhiteKeys;
1738
  for (let i = 0; i < numWhiteKeys; i++) {
 
1740
  const offsetIdx = i % 7;
1741
  const whiteToNote = [0, 2, 4, 5, 7, 9, 11];
1742
  const midi = 36 + octave * 12 + whiteToNote[offsetIdx];
1743
+
1744
  const active = activePitches.has(midi);
1745
  const x = i * whiteKeyW;
1746
+
1747
  canvasCtx.fillStyle = active ? "#ffffff" : "#1a1f26";
1748
+
1749
  canvasCtx.beginPath();
1750
  if (typeof canvasCtx.roundRect === "function") {
1751
  canvasCtx.roundRect(x + 1, playLineY, whiteKeyW - 2, keyboardH, [0, 0, 3, 3]);
 
1753
  canvasCtx.rect(x + 1, playLineY, whiteKeyW - 2, keyboardH);
1754
  }
1755
  canvasCtx.fill();
1756
+
1757
  canvasCtx.fillStyle = "rgba(0, 0, 0, 0.35)";
1758
  canvasCtx.fillRect(x, playLineY, 1, keyboardH);
1759
  }
1760
+
1761
  const blackKeyHeight = keyboardH * 0.62;
1762
  for (let m = minMidi; m <= maxMidi; m++) {
1763
  const noteInOctave = (m - minMidi) % 12;
1764
  const isBlack = [1, 3, 6, 8, 10].includes(noteInOctave);
1765
  if (!isBlack) continue;
1766
+
1767
  const active = activePitches.has(m);
1768
  const keyInfo = getKeyPosition(m, width);
1769
+
1770
  canvasCtx.fillStyle = active ? "#6f9c78" : "#090a0d";
1771
+
1772
  canvasCtx.beginPath();
1773
  if (typeof canvasCtx.roundRect === "function") {
1774
  canvasCtx.roundRect(keyInfo.x, playLineY, keyInfo.w, blackKeyHeight, [0, 0, 2, 2]);
 
1776
  canvasCtx.rect(keyInfo.x, playLineY, keyInfo.w, blackKeyHeight);
1777
  }
1778
  canvasCtx.fill();
1779
+
1780
  canvasCtx.fillStyle = active ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.05)";
1781
  canvasCtx.fillRect(keyInfo.x, playLineY, keyInfo.w, 2);
1782
  }
1783
+
1784
  canvasCtx.fillStyle = "rgba(255, 255, 255, 0.12)";
1785
  canvasCtx.fillRect(0, playLineY - 1, width, 1);
1786
+
1787
  const playLineShadow = canvasCtx.createLinearGradient(0, playLineY, 0, playLineY + 6);
1788
  playLineShadow.addColorStop(0, "rgba(0, 0, 0, 0.45)");
1789
  playLineShadow.addColorStop(1, "rgba(0, 0, 0, 0)");
1790
  canvasCtx.fillStyle = playLineShadow;
1791
  canvasCtx.fillRect(0, playLineY, width, 6);
1792
+
1793
  canvasCtx.fillStyle = "rgba(255, 255, 255, 0.18)";
1794
  canvasCtx.font = "9px ui-sans-serif, system-ui, sans-serif";
1795
  canvasCtx.fillText("BASS", 12, playLineY - 10);
1796
  canvasCtx.fillText("TREBLE", width - 48, playLineY - 10);
1797
+
1798
  visualNotes = visualNotes.filter((item) => item.start + item.duration > visualNow - 1.5);
1799
  if (running) visualFrame = requestAnimationFrame(drawVisualizer);
1800
  }
 
1850
  const tx = db.transaction("models", "readwrite");
1851
  const store = tx.objectStore("models");
1852
  store.put(data, key);
1853
+ } catch (e) {}
1854
  }
1855
 
1856
  async function getFromCacheStorage(cacheKey) {
 
1861
  if (res && res.ok) {
1862
  return res;
1863
  }
1864
+ } catch (e) {}
1865
  return null;
1866
  }
1867
 
 
1870
  if (!("caches" in window)) return;
1871
  const cache = await caches.open("nanomaestro_models_v2");
1872
  await cache.put(cacheKey, response);
1873
+ } catch (e) {}
1874
  }
1875
 
1876
  async function fetchStreamWithProgress(response, onProgress) {
1877
  const contentLength = response.headers.get("content-length");
1878
  const total = contentLength ? parseInt(contentLength, 10) : 0;
1879
+
1880
  let loaded = 0;
1881
  if (response.body && typeof response.body.getReader === "function") {
1882
  const reader = response.body.getReader();
 
1907
  }
1908
  return cachedData;
1909
  }
1910
+ } catch (e) {}
1911
 
1912
  try {
1913
  const cachedResponse = await getFromCacheStorage(cacheKey);
 
1921
  void setCachedData(cacheKey, data);
1922
  return data;
1923
  }
1924
+ } catch (e) {}
1925
 
1926
  console.log(`[Cache MISS] Fetching ${cacheKey} from network...`);
1927
  let data;
 
1998
 
1999
  const vocabCacheKey = `vocab_${preset.key}_v1`;
2000
  const modelCacheKey = `model_${preset.key}_v1`;
2001
+
2002
  if (updateProgress) updateProgress(5, `Loading ${preset.name} vocabulary...`);
2003
  const vocab = await fetchAssetWithCache(vocabCacheKey, preset.vocabUrl, preset.remoteVocabUrl, null, true);
2004
+
2005
  if (updateProgress) updateProgress(15, `Loading ${preset.name} weights...`);
2006
  const modelBlob = await fetchAssetWithCache(modelCacheKey, preset.modelUrl, preset.remoteModelUrl, (loaded, total) => {
2007
  if (updateProgress) {
 
2016
  }
2017
  }
2018
  }, false);
2019
+
2020
  if (updateProgress) updateProgress(82, `Initializing ${preset.name} engine (WASM CPU)...`);
2021
+
2022
  const modelBuffer = await modelBlob.arrayBuffer();
2023
  await new Promise((resolve, reject) => {
2024
  let timer = setTimeout(() => {
 
2042
  modelConfig: preset.config
2043
  }, [modelBuffer]);
2044
  });
2045
+
2046
  activeModelName = preset.name;
2047
  isModelReady = true;
2048
+
2049
  const modelDescEl = document.querySelector("#modelDesc");
2050
  if (modelDescEl) {
2051
  modelDescEl.textContent = preset.desc;
 
2058
  const loadProgress = document.querySelector("#loadProgress");
2059
  const loadStatus = document.querySelector("#loadStatus");
2060
  const loadPercent = document.querySelector("#loadPercent");
2061
+
2062
  const updateProgress = (pct, text) => {
2063
  if (loadProgress) loadProgress.style.width = `${pct}%`;
2064
  if (loadPercent) loadPercent.textContent = `${Math.round(pct)}%`;
2065
  if (loadStatus) loadStatus.textContent = text;
2066
  };
2067
+
2068
  updateProgress(2, "Initializing NanoMaestro AI engine...");
2069
+
2070
  try {
2071
  updateReadouts();
2072
  startBtn.disabled = true;
2073
  if (renderSongBtn) renderSongBtn.disabled = true;
2074
+
2075
  const topSelect = document.querySelector("#topModelSelect");
2076
  const settingsSelect = document.querySelector("#modelSelect");
2077
  const selectedKey = (topSelect ? topSelect.value : null) || (settingsSelect ? settingsSelect.value : "pro");
2078
+
2079
  await loadSelectedModel(selectedKey, updateProgress);
2080
+
2081
  updateProgress(90, `Loading ${currentInstrument} audio samples...`);
2082
  await ensureInstrument();
2083
+
2084
  updateProgress(100, "Ready!");
2085
+
2086
  setTimeout(() => {
2087
  if (loadingOverlay) {
2088
  loadingOverlay.classList.add("fade-out");
 
2090
  setStatus(`Ready: ${activeModelName}`, "idle");
2091
  startBtn.disabled = false;
2092
  if (renderSongBtn) renderSongBtn.disabled = false;
2093
+
2094
  resizeCanvas();
2095
  drawVisualizer();
2096
  }, 600);
2097
+
2098
  } catch (error) {
2099
  console.error("Initialization failed:", error);
2100
  if (loadStatus) {
 
2217
  toggleButtons.forEach(btn => {
2218
  btn.addEventListener("click", () => {
2219
  if (btn.disabled) return;
2220
+
2221
  toggleButtons.forEach(b => b.classList.remove("active"));
2222
  btn.classList.add("active");
2223
+
2224
  const value = btn.dataset.value;
2225
  if (value === "midi") {
2226
  midiSeedControls.style.display = "block";
 
2235
  midiBpmModeButtons.forEach(btn => {
2236
  btn.addEventListener("click", () => {
2237
  if (btn.disabled) return;
2238
+
2239
  midiBpmModeButtons.forEach(b => b.classList.remove("active"));
2240
  btn.classList.add("active");
2241
+
2242
  midiBpmMode = btn.dataset.value;
2243
  });
2244
  });
 
2246
  midiFileInput.addEventListener("change", async (e) => {
2247
  const file = e.target.files?.[0];
2248
  if (!file) return;
2249
+
2250
  midiFileName = file.name;
2251
  midiFileNameEl.textContent = `File: ${file.name}`;
2252
  midiFileInfo.style.display = "block";
2253
  midiFileStatsEl.textContent = "Parsing MIDI file...";
2254
+
2255
  try {
2256
  const buffer = await file.arrayBuffer();
2257
  const parser = new MidiParser(buffer);
2258
  const parsed = parser.parse();
2259
+
2260
  const { tokens, maxBar } = tokenizeMidi(parsed, 64);
2261
  midiTokens = tokens;
2262
  midiBpm = parsed.bpm;
2263
  midiTotalBars = Math.max(1, maxBar + 1);
2264
+
2265
  midiFileStatsEl.textContent = `BPM: ${parsed.bpm} | Total Bars: ${midiTotalBars} | Notes: ${parsed.notes.length}`;
2266
+
2267
  const minBar = findMinStartBar(tokens);
2268
  midiStartBarInput.min = String(minBar);
2269
  midiStartBarInput.max = String(midiTotalBars - 1);
2270
  midiStartBarInput.value = String(minBar);
2271
  midiStartBar = minBar;
2272
  midiStartBarValue.textContent = String(minBar);
2273
+
2274
  const barsData = analyzeMidiTokens(tokens);
2275
  renderMidiTimeline(barsData);
2276
  updateMidiStartBarText();
 
2295
  setRelease(rel);
2296
  });
2297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2298
  const instrumentSelect = document.querySelector("#instrumentSelect");
2299
  if (instrumentSelect) {
2300
  instrumentSelect.addEventListener("change", async (e) => {
2301
  currentInstrument = e.target.value;
 
2302
  if (synth || bassSynth || chordSynth) {
2303
  const isAlreadyRunning = running;
2304
  if (isAlreadyRunning) {
 
2345
 
2346
  // Initialize MIDI sub-mode UI copy on load
2347
  setMidiSubMode("single");
 
2348
 
2349
  void init();