summaryrefslogtreecommitdiff
path: root/tools/mq_editor/viewer.js
blob: 1ac1afdd41e71ac6b8ef19c59a34ba45418047fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
// Spectrogram Viewer
// Handles all visualization: spectrogram, partials, zoom, mouse interaction

class SpectrogramViewer {
  constructor(canvas, audioBuffer, stftCache) {
    this.canvas = canvas;
    this.ctx = canvas.getContext('2d');
    this.audioBuffer = audioBuffer;
    this.stftCache = stftCache;
    this.partials = [];
    this.frames = [];
    this.showPeaks = false;

    // Fixed time bounds
    this.t_min = 0;
    this.t_max = audioBuffer.duration;

    // View state (zoom and center)
    this.zoom_factor = 1.0; // 1.0 = full view
    this.t_center = audioBuffer.duration / 2;

    // Computed view bounds (updated by updateViewBounds)
    this.t_view_min = 0;
    this.t_view_max = audioBuffer.duration;

    // Fixed frequency bounds (log scale: freqStart must be > 0)
    this.freqStart = 20;
    this.freqEnd = 16000;

    // Tooltip
    this.tooltip = document.getElementById('tooltip');

    // Partial keep count (Infinity = all kept)
    this.keepCount = Infinity;

    // Mouse cursor overlay
    this.cursorCanvas = document.getElementById('cursorCanvas');
    this.cursorCtx = this.cursorCanvas ? this.cursorCanvas.getContext('2d') : null;
    this.mouseX = -1;

    // Playhead overlay
    this.playheadCanvas = document.getElementById('playheadCanvas');
    this.playheadCtx = this.playheadCanvas ? this.playheadCanvas.getContext('2d') : null;
    this.playheadTime = -1; // -1 = not playing

    // Spectrum viewer
    this.spectrumCanvas = document.getElementById('spectrumCanvas');
    this.spectrumCtx = this.spectrumCanvas ? this.spectrumCanvas.getContext('2d') : null;
    this.spectrumTime = 0; // Time to display spectrum for
    this.showSynthFFT = false; // Toggle: false=original, true=synth
    this.synthStftCache = null;

    // Partial spectrum viewer
    this.partialSpectrumCanvas = document.getElementById('partialSpectrumCanvas');
    this.partialSpectrumCtx = this.partialSpectrumCanvas ? this.partialSpectrumCanvas.getContext('2d') : null;
    this._partialSpecCache = null; // {partialIndex, time, specData?} — see renderPartialSpectrum
    this._partialRangeCache = null; // {partialIndex, dbMin, dbMax} — scanned across full partial duration
    this.synthOpts = {}; // synth options forwarded to synthesizeMQ (forceResonator, etc.)
    this.onGetSynthOpts = null; // callback() → opts; called before each spectrum compute

    // Selection and editing
    this.selectedPartial = -1;
    this.dragState = null; // {pointIndex: 0-3}
    this.onPartialSelect = null; // callback(index)
    this.onRender = null; // callback() called after each render (for synced panels)
    this.onBeforeChange = null; // callback() called before any mutation (for undo/redo)

    // Explore mode
    this.exploreMode = false;
    this.previewPartial = null;
    this.onExploreMove = null;   // callback(time, freq)
    this.onExploreCommit = null; // callback(partial)

    // Setup event handlers
    this.setupMouseHandlers();

    // Initial render
    this.updateViewBounds();
    this.render();
  }

  // --- Coordinate API ---

  // time -> canvas X
  timeToX(t) {
    return (t - this.t_view_min) / (this.t_view_max - this.t_view_min) * this.canvas.width;
  }

  // canvas X -> time
  canvasToTime(x) {
    return this.t_view_min + (x / this.canvas.width) * (this.t_view_max - this.t_view_min);
  }

  // freq -> normalized log position [0..1] within [freqStart..freqEnd]
  freqLogNorm(freq) {
    const logMin = Math.log2(this.freqStart);
    const logMax = Math.log2(this.freqEnd);
    return (Math.log2(Math.max(freq, this.freqStart)) - logMin) / (logMax - logMin);
  }

  // normalized log position [0..1] -> freq
  normToFreq(norm) {
    const logMin = Math.log2(this.freqStart);
    const logMax = Math.log2(this.freqEnd);
    return Math.pow(2, logMin + norm * (logMax - logMin));
  }

  // freq -> canvas Y (log scale)
  freqToY(freq) {
    return this.canvas.height * (1 - this.freqLogNorm(freq));
  }

  // canvas Y -> freq (log scale)
  canvasToFreq(y) {
    return this.normToFreq(1 - y / this.canvas.height);
  }

  // DB value -> normalized intensity [0..1], relative to cache maxDB over 80dB range
  normalizeDB(magDB, maxDB) {
    return clamp((magDB - (maxDB - 80)) / 80, 0, 1);
  }

  // Partial index -> display color
  partialColor(p) {
    const colors = [
      '#f44', '#4f4', '#44f', '#ff4', '#f4f', '#4ff',
      '#fa4', '#4fa', '#a4f', '#af4', '#f4a', '#4af'
    ];
    return colors[p % colors.length];
  }

  // --- Public API ---

  setPlayheadTime(time) {
    this.playheadTime = time;
    if (time >= 0) {
      this.spectrumTime = time;
      this.renderSpectrum();
      this.renderPartialSpectrum(time);
    } else if (this.mouseX >= 0) {
      this.spectrumTime = this.canvasToTime(this.mouseX);
    }
    this.drawPlayhead();
  }

  setPartials(partials) {
    this.partials = partials;
    this.render();
  }

  setKeepCount(n) {
    this.keepCount = n;
    this.render();
  }

  setFrames(frames) {
    this.frames = frames;
  }

  setSynthStftCache(cache) {
    this.synthStftCache = cache;
  }

  togglePeaks() {
    this.showPeaks = !this.showPeaks;
    this.render();
  }

  reset() {
    this.zoom_factor = 1.0;
    this.t_center = this.audioBuffer.duration / 2;
    this.updateViewBounds();
    this.render();
  }

  getIntensityAt(time, freq) {
    if (!this.stftCache) return -80;
    return this.stftCache.getMagnitudeDB(time, freq);
  }

  selectPartial(index) {
    this._partialSpecCache = null;
    this._partialRangeCache = null;
    this.selectedPartial = index;
    this.render();
    if (this.onPartialSelect) this.onPartialSelect(index);
  }

  // Hit-test bezier curves: returns index of nearest partial within threshold
  hitTestPartial(x, y) {
    const THRESH = 10;
    let bestIdx = -1, bestDist = THRESH;
    for (let p = 0; p < this.partials.length && p < this.keepCount; ++p) {
      const curve = this.partials[p].freqCurve;
      if (!curve) continue;
      for (let i = 0; i <= 50; ++i) {
        const t = curve.t0 + (curve.t3 - curve.t0) * i / 50;
        if (t < this.t_view_min || t > this.t_view_max) continue;
        const f = evalBezier(curve, t);
        if (f < this.freqStart || f > this.freqEnd) continue;
        const px = this.timeToX(t), py = this.freqToY(f);
        const dist = Math.hypot(px - x, py - y);
        if (dist < bestDist) { bestDist = dist; bestIdx = p; }
      }
    }
    return bestIdx;
  }

  // Hit-test control points of a specific partial's freqCurve
  hitTestControlPoint(x, y, partial) {
    const curve = partial.freqCurve;
    if (!curve) return -1;
    const THRESH = 8;
    for (let i = 0; i < 4; ++i) {
      const t = curve['t' + i], v = curve['v' + i];
      if (t < this.t_view_min || t > this.t_view_max) continue;
      if (v < this.freqStart || v > this.freqEnd) continue;
      const px = this.timeToX(t), py = this.freqToY(v);
      if (Math.hypot(px - x, py - y) <= THRESH) return i;
    }
    return -1;
  }

  // --- Render ---

  render() {
    this.renderSpectrogram();
    if (this.showPeaks) this.renderPeaks();
    this.renderPartials();
    this.drawAxes();
    this.drawPlayhead();
    this.renderSpectrum();
    this.renderPartialSpectrum(this.spectrumTime, true);
    if (this.onRender) this.onRender();
  }

  renderPartials() {
    for (let p = 0; p < this.partials.length; ++p) {
      if (p === this.selectedPartial) continue; // draw selected last (on top)
      this._renderPartial(p, this.partials[p], false);
    }
    if (this.selectedPartial >= 0 && this.selectedPartial < this.partials.length) {
      this._renderPartial(this.selectedPartial, this.partials[this.selectedPartial], true);
    }
    this.ctx.globalAlpha = 1.0;
    this.ctx.shadowBlur = 0;
  }

  _renderPartial(p, partial, isSelected) {
    const {ctx} = this;
    const color = this.partialColor(p);
    let alpha = isSelected ? 1.0 : (p < this.keepCount ? 1.0 : 0.12);
    if (partial.muted && !isSelected) alpha = 0.15;
    ctx.globalAlpha = alpha;

    // Raw trajectory
    ctx.strokeStyle = color + '44';
    ctx.lineWidth = 1;
    ctx.beginPath();
    let started = false;
    for (let i = 0; i < partial.times.length; ++i) {
      const t = partial.times[i];
      const f = partial.freqs[i];
      if (t < this.t_view_min || t > this.t_view_max) continue;
      if (f < this.freqStart || f > this.freqEnd) continue;
      const x = this.timeToX(t);
      const y = this.freqToY(f);
      if (!started) { ctx.moveTo(x, y); started = true; } else ctx.lineTo(x, y);
    }
    if (started) ctx.stroke();

    // Spread band (selected only)
    if (isSelected && partial.freqCurve) {
      this._renderSpreadBand(partial, color);
    }

    // Bezier curve
    if (partial.freqCurve) {
      const curve = partial.freqCurve;
      if (isSelected) { ctx.shadowColor = color; ctx.shadowBlur = 8; }
      ctx.strokeStyle = color;
      ctx.lineWidth = isSelected ? 3 : 2;
      ctx.beginPath();
      started = false;
      for (let i = 0; i <= 50; ++i) {
        const t = curve.t0 + (curve.t3 - curve.t0) * i / 50;
        const freq = evalBezier(curve, t);
        if (t < this.t_view_min || t > this.t_view_max) continue;
        if (freq < this.freqStart || freq > this.freqEnd) continue;
        const x = this.timeToX(t);
        const y = this.freqToY(freq);
        if (!started) { ctx.moveTo(x, y); started = true; } else ctx.lineTo(x, y);
      }
      if (started) ctx.stroke();
      if (isSelected) ctx.shadowBlur = 0;

      ctx.fillStyle = color;
      const cpR = isSelected ? 6 : 4;
      this.drawControlPoint(curve.t0, curve.v0, cpR);
      this.drawControlPoint(curve.t1, curve.v1, cpR);
      this.drawControlPoint(curve.t2, curve.v2, cpR);
      this.drawControlPoint(curve.t3, curve.v3, cpR);
    }
  }

  _renderSpreadBand(partial, color) {
    const {ctx} = this;
    const curve    = partial.freqCurve;
    const harm     = partial.harmonics || {};
    const spread   = harm.spread != null ? harm.spread : 0.02;
    const decay    = harm.decay        != null ? harm.decay        : 0.0;
    const freqMult = harm.freq_mult    != null ? harm.freq_mult    : 2.0;

    const {upper, lower} = buildBandPoints(this, curve, spread, spread);
    if (upper.length < 2) return;

    const savedAlpha = ctx.globalAlpha;

    // Outer soft fill
    ctx.beginPath();
    ctx.moveTo(upper[0][0], upper[0][1]);
    for (let i = 1; i < upper.length; ++i) ctx.lineTo(upper[i][0], upper[i][1]);
    for (let i = lower.length - 1; i >= 0; --i) ctx.lineTo(lower[i][0], lower[i][1]);
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.globalAlpha = 0.13;
    ctx.fill();

    // Dashed boundary lines
    ctx.globalAlpha = 0.75;
    ctx.strokeStyle = color;
    ctx.lineWidth   = 1.5;
    ctx.setLineDash([4, 3]);
    ctx.beginPath();
    ctx.moveTo(upper[0][0], upper[0][1]);
    for (let i = 1; i < upper.length; ++i) ctx.lineTo(upper[i][0], upper[i][1]);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(lower[0][0], lower[0][1]);
    for (let i = 1; i < lower.length; ++i) ctx.lineTo(lower[i][0], lower[i][1]);
    ctx.stroke();
    ctx.setLineDash([]);

    // 50% drop-off reference lines (dotted, dimmer)
    const {upper: p5upper, lower: p5lower} = buildBandPoints(this, curve, 0.50, 0.50);
    if (p5upper.length >= 2) {
      ctx.globalAlpha = 0.55;
      ctx.strokeStyle = color;
      ctx.lineWidth   = 1;
      ctx.setLineDash([1, 5]);
      ctx.beginPath();
      ctx.moveTo(p5upper[0][0], p5upper[0][1]);
      for (let i = 1; i < p5upper.length; ++i) ctx.lineTo(p5upper[i][0], p5upper[i][1]);
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(p5lower[0][0], p5lower[0][1]);
      for (let i = 1; i < p5lower.length; ++i) ctx.lineTo(p5lower[i][0], p5lower[i][1]);
      ctx.stroke();
      ctx.setLineDash([]);
    }

    // Harmonic bands (faint, fading with decay^n)
    if (decay > 0) {
      for (let n = 1; ; ++n) {
        const ampMult = Math.pow(decay, n);
        if (ampMult < 0.001) break;
        const hRatio = n * freqMult;

        // Center line
        const cpts = buildCenterPoints(this, curve, hRatio);
        if (cpts.length >= 2) {
          ctx.globalAlpha = ampMult * 0.85;
          ctx.strokeStyle = color;
          ctx.lineWidth   = 1.5;
          ctx.setLineDash([3, 4]);
          ctx.beginPath();
          ctx.moveTo(cpts[0][0], cpts[0][1]);
          for (let i = 1; i < cpts.length; ++i) ctx.lineTo(cpts[i][0], cpts[i][1]);
          ctx.stroke();
          ctx.setLineDash([]);
        }

        // Spread band fill + boundary dashes
        const {upper: hu, lower: hl} = buildBandPoints(this, curve, spread, spread, hRatio);
        if (hu.length >= 2) {
          ctx.beginPath();
          ctx.moveTo(hu[0][0], hu[0][1]);
          for (let i = 1; i < hu.length; ++i) ctx.lineTo(hu[i][0], hu[i][1]);
          for (let i = hl.length - 1; i >= 0; --i) ctx.lineTo(hl[i][0], hl[i][1]);
          ctx.closePath();
          ctx.fillStyle    = color;
          ctx.globalAlpha  = ampMult * 0.12;
          ctx.fill();

          ctx.globalAlpha  = ampMult * 0.55;
          ctx.strokeStyle  = color;
          ctx.lineWidth    = 1;
          ctx.setLineDash([3, 5]);
          ctx.beginPath();
          ctx.moveTo(hu[0][0], hu[0][1]);
          for (let i = 1; i < hu.length; ++i) ctx.lineTo(hu[i][0], hu[i][1]);
          ctx.stroke();
          ctx.beginPath();
          ctx.moveTo(hl[0][0], hl[0][1]);
          for (let i = 1; i < hl.length; ++i) ctx.lineTo(hl[i][0], hl[i][1]);
          ctx.stroke();
          ctx.setLineDash([]);
        }
      }
    }

    ctx.globalAlpha = savedAlpha;
  }

  renderPeaks() {
    const {ctx, frames} = this;
    if (!frames || frames.length === 0) return;

    ctx.fillStyle = '#fff';
    for (const frame of frames) {
      const t = frame.time;
      if (t < this.t_view_min || t > this.t_view_max) continue;
      const x = this.timeToX(t);
      for (const peak of frame.peaks) {
        if (peak.freq < this.freqStart || peak.freq > this.freqEnd) continue;
        ctx.fillRect(x - 1, this.freqToY(peak.freq) - 1, 3, 3);
      }
    }
  }

  drawControlPoint(t, v, radius = 4) {
    if (t < this.t_view_min || t > this.t_view_max) return;
    if (v < this.freqStart || v > this.freqEnd) return;
    const x = this.timeToX(t);
    const y = this.freqToY(v);
    this.ctx.beginPath();
    this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
    this.ctx.fill();
    this.ctx.strokeStyle = '#fff';
    this.ctx.lineWidth = 1;
    this.ctx.stroke();
  }

  drawMouseCursor(x) {
    if (!this.cursorCtx) return;
    const ctx = this.cursorCtx;
    const h = this.cursorCanvas.height;
    ctx.clearRect(0, 0, this.cursorCanvas.width, h);
    if (x < 0) return;
    ctx.strokeStyle = this.exploreMode === 'contour' ? 'rgba(0,220,220,0.8)'
                    : this.exploreMode             ? 'rgba(255,160,0,0.8)'
                    :                               'rgba(255,60,60,0.7)';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(x, 0);
    ctx.lineTo(x, h);
    ctx.stroke();
    if (this.exploreMode && this.previewPartial) {
      this._drawPreviewPartial(ctx, this.previewPartial);
    }
  }

  setExploreMode(enabled) {
    this.exploreMode = enabled;
    if (!enabled) this.previewPartial = null;
    this.drawMouseCursor(this.mouseX);
    this.canvas.style.cursor = enabled ? 'cell' : 'crosshair';
  }

  setPreviewPartial(partial) {
    this.previewPartial = partial;
    this.drawMouseCursor(this.mouseX);
  }

  _drawPreviewPartial(ctx, partial) {
    const curve = partial.freqCurve;
    if (!curve) return;
    const col = this.exploreMode === 'contour' ? '0,220,220' : '255,160,0';
    ctx.save();
    ctx.strokeStyle = `rgba(${col},0.9)`;
    ctx.lineWidth = 2;
    ctx.setLineDash([6, 3]);
    ctx.shadowColor = `rgba(${col},0.5)`;
    ctx.shadowBlur = 6;
    ctx.beginPath();
    let started = false;
    for (let i = 0; i <= 80; ++i) {
      const t = curve.t0 + (curve.t3 - curve.t0) * i / 80;
      const freq = evalBezier(curve, t);
      if (t < this.t_view_min || t > this.t_view_max) continue;
      if (freq < this.freqStart || freq > this.freqEnd) continue;
      const px = this.timeToX(t);
      const py = this.freqToY(freq);
      if (!started) { ctx.moveTo(px, py); started = true; } else ctx.lineTo(px, py);
    }
    if (started) ctx.stroke();
    ctx.restore();
  }

  drawPlayhead() {
    if (!this.playheadCtx) return;
    const ctx = this.playheadCtx;
    const h = this.playheadCanvas.height;
    ctx.clearRect(0, 0, this.playheadCanvas.width, h);
    if (this.playheadTime < 0) return;
    if (this.playheadTime < this.t_view_min || this.playheadTime > this.t_view_max) return;
    const x = this.timeToX(this.playheadTime);
    ctx.strokeStyle = 'rgba(255, 80, 80, 0.9)';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(x, 0);
    ctx.lineTo(x, h);
    ctx.stroke();
  }

  renderSpectrogram() {
    const {canvas, ctx, stftCache} = this;
    const width = canvas.width;
    const height = canvas.height;

    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, width, height);

    if (!stftCache) return;

    const sampleRate = this.audioBuffer.sampleRate;
    const hopSize = stftCache.hopSize;
    const fftSize = stftCache.fftSize;
    const frameDuration = hopSize / sampleRate;
    const numFrames = stftCache.getNumFrames();

    const startFrameIdx = Math.floor(this.t_view_min * sampleRate / hopSize);
    const endFrameIdx = Math.ceil(this.t_view_max * sampleRate / hopSize);

    for (let frameIdx = startFrameIdx; frameIdx < endFrameIdx; ++frameIdx) {
      if (frameIdx < 0 || frameIdx >= numFrames) continue;

      const frame = stftCache.getFrameAtIndex(frameIdx);
      if (!frame) continue;

      const squaredAmp = frame.squaredAmplitude;
      const xStart = Math.floor(this.timeToX(frame.time));
      const xEnd   = Math.ceil(this.timeToX(frame.time + frameDuration));
      const frameWidth = Math.max(1, xEnd - xStart);

      const numBins = fftSize / 2;
      const binFreqWidth = sampleRate / fftSize;

      for (let bin = 0; bin < numBins; ++bin) {
        const freq     = bin * binFreqWidth;
        const freqNext = (bin + 1) * binFreqWidth;
        if (freqNext < this.freqStart || freq > this.freqEnd) continue;

        const magDB    = 10 * Math.log10(Math.max(squaredAmp[bin], 1e-20));
        const intensity = Math.pow(this.normalizeDB(magDB, stftCache.maxDB), 2.0);

        const y0 = Math.floor(this.freqToY(freqNext));
        const y1 = Math.floor(this.freqToY(Math.max(freq, this.freqStart)));
        const binHeight = Math.max(1, y1 - y0);

        const v = Math.floor(intensity * 255);
        ctx.fillStyle = `rgba(${v},${v},${v}, 0.5)`;
        ctx.fillRect(xStart, y0, frameWidth, binHeight);
      }
    }
  }

  renderSpectrum() {
    if (!this.spectrumCtx || !this.stftCache) return;

    const useSynth = this.showSynthFFT && this.synthStftCache;
    const cache = useSynth ? this.synthStftCache : this.stftCache;

    const canvas = this.spectrumCanvas;
    const ctx = this.spectrumCtx;
    const width = canvas.width;
    const height = canvas.height;

    ctx.fillStyle = '#1e1e1e';
    ctx.fillRect(0, 0, width, height);

    const squaredAmp = cache.getSquaredAmplitude(this.spectrumTime);
    if (!squaredAmp) return;

    const numBins = cache.fftSize / 2;
    const binWidth = cache.sampleRate / cache.fftSize;

    // freq -> mini-spectrum X using same log scale as main view
    const freqToX = (freq) => this.freqLogNorm(freq) * width;

    // Draw histogram bars — one per pixel column
    for (let px = 0; px < width; ++px) {
      const fStart = this.normToFreq(px / width);
      const fEnd   = this.normToFreq((px + 1) / width);

      const bStart = Math.max(0, Math.floor(fStart / binWidth));
      const bEnd   = Math.min(numBins - 1, Math.ceil(fEnd / binWidth));

      let maxSq = 0;
      for (let b = bStart; b <= bEnd; ++b) { if (squaredAmp[b] > maxSq) maxSq = squaredAmp[b]; }
      if (bStart > bEnd) continue;

      const magDB = 10 * Math.log10(Math.max(maxSq, 1e-20));
      const barHeight = Math.round(this.normalizeDB(magDB, cache.maxDB) * height);
      if (barHeight === 0) continue;

      const gradient = ctx.createLinearGradient(0, height - barHeight, 0, height);
      if (useSynth) {
        gradient.addColorStop(0, '#4f8'); gradient.addColorStop(1, '#af4');
      } else {
        gradient.addColorStop(0, '#4af'); gradient.addColorStop(1, '#fa4');
      }
      ctx.fillStyle = gradient;
      ctx.fillRect(px, height - barHeight, 1, barHeight);
    }

    // Overlay extracted peaks (green)
    if (this.frames && this.frames.length > 0) {
      let bestFrame = this.frames[0];
      let bestDt = Math.abs(bestFrame.time - this.spectrumTime);
      for (const f of this.frames) {
        const dt = Math.abs(f.time - this.spectrumTime);
        if (dt < bestDt) { bestDt = dt; bestFrame = f; }
      }
      ctx.fillStyle = '#4f4';
      for (const peak of bestFrame.peaks) {
        if (peak.freq < this.freqStart || peak.freq > this.freqEnd) continue;
        const x0 = Math.floor(freqToX(peak.freq));
        const x1 = Math.max(x0 + 1, Math.floor(freqToX(this.normToFreq(this.freqLogNorm(peak.freq) + 1 / width))));
        ctx.fillRect(x0, 0, x1 - x0, height);
      }
    }

    // Overlay partial f0 markers (red, 2px)
    ctx.strokeStyle = '#f44';
    ctx.lineWidth = 2;
    for (let p = 0; p < this.partials.length && p < this.keepCount; ++p) {
      const curve = this.partials[p].freqCurve;
      if (!curve || this.spectrumTime < curve.t0 || this.spectrumTime > curve.t3) continue;
      const freq = evalBezier(curve, this.spectrumTime);
      if (freq < this.freqStart || freq > this.freqEnd) continue;
      const x = Math.round(freqToX(freq));
      ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke();
    }

    // Label
    ctx.fillStyle = useSynth ? '#4f8' : '#4af';
    ctx.font = '9px monospace';
    ctx.fillText(useSynth ? 'SYNTH [a]' : 'ORIG [a]', 4, 10);
  }

  // Draw synthesized power spectrum of the selected partial into partialSpectrumCanvas.
  // X-axis: log frequency (same scale as main view). Y-axis: dB (normalised to peak).
  // specTime = mouse time if inside partial's [t0,t3], else center of partial's interval.
  // Cached on {partialIndex, specTime}; force=true bypasses cache (param changes, synth toggle).
  renderPartialSpectrum(time, force = false) {
    const ctx = this.partialSpectrumCtx;
    if (!ctx) return;

    const canvas = this.partialSpectrumCanvas;
    const width  = canvas.width;
    const height = canvas.height;
    const p      = this.selectedPartial;

    const showMsg = (msg) => {
      ctx.fillStyle = '#1e1e1e'; ctx.fillRect(0, 0, width, height);
      ctx.font = '9px monospace'; ctx.fillStyle = '#333';
      ctx.fillText(msg, 4, height / 2 + 4);
      this._partialSpecCache = null;
    };

    if (p < 0 || !this.partials || p >= this.partials.length) { showMsg('no partial'); return; }

    const partial = this.partials[p];
    const curve   = partial.freqCurve;
    if (!curve) { showMsg('no curve'); return; }

    // Use mouse time if inside partial's window, else center of partial
    const specTime = (time >= curve.t0 && time <= curve.t3)
      ? time
      : (curve.t0 + curve.t3) / 2;

    // Cache check — must happen before clearing the canvas
    if (!force && this._partialSpecCache &&
        this._partialSpecCache.partialIndex === p &&
        this._partialSpecCache.time === specTime) return;

    ctx.fillStyle = '#1e1e1e';
    ctx.fillRect(0, 0, width, height);
    ctx.font = '9px monospace';

    // Synthesize window → FFT → power spectrum
    const specData = this._computePartialSpectrum(partial, specTime);
    this._partialSpecCache = {partialIndex: p, time: specTime, specData};

    // dB range: scanned across full partial duration, cached per partial
    if (!this._partialRangeCache || this._partialRangeCache.partialIndex !== p) {
      this._partialRangeCache = this._computePartialRange(p, partial);
    }
    const {dbMin: DB_MIN, dbMax: DB_MAX} = this._partialRangeCache;

    const {squaredAmp, sampleRate, fftSize} = specData;
    const numBins  = fftSize / 2;
    const binWidth = sampleRate / fftSize;
    const color    = this.partialColor(p);
    const cr       = parseInt(color[1] + color[1], 16);
    const cg       = parseInt(color[2] + color[2], 16);
    const cb       = parseInt(color[3] + color[3], 16);

    for (let px = 0; px < width; ++px) {
      const fStart = this.normToFreq(px / width);
      const fEnd   = this.normToFreq((px + 1) / width);
      const bStart = Math.max(0, Math.floor(fStart / binWidth));
      const bEnd   = Math.min(numBins - 1, Math.ceil(fEnd / binWidth));
      if (bStart > bEnd) continue;

      let maxSq = 0;
      for (let b = bStart; b <= bEnd; ++b) if (squaredAmp[b] > maxSq) maxSq = squaredAmp[b];

      const magDB = 10 * Math.log10(Math.max(maxSq, 1e-20));
      const barH  = Math.round(Math.max(0, Math.min(1, (magDB - DB_MIN) / (DB_MAX - DB_MIN))) * (height - 12));
      if (barH <= 0) continue;

      const grad = ctx.createLinearGradient(0, height - barH, 0, height);
      grad.addColorStop(0, color);
      grad.addColorStop(1, `rgba(${cr},${cg},${cb},0.53)`);
      ctx.fillStyle = grad;
      ctx.fillRect(px, height - barH, 1, barH);
    }

    ctx.fillStyle = color;
    ctx.fillText('P#' + p + ' @' + specTime.toFixed(3) + 's', 4, 10);

    const amp = evalBezierAmp(curve, specTime);
    ctx.fillStyle = '#f44';
    ctx.textAlign = 'right';
    ctx.fillText('A=' + amp.toFixed(3), width - 3, 10);
    ctx.textAlign = 'left';
  }

  // Synthesise a 2048-sample Hann-windowed frame of `partial` centred on `time`, run FFT,
  // return {squaredAmp, maxDB, sampleRate, fftSize}.  Uses this.synthOpts (forceResonator etc).
  // freqCurve times are shifted so synthesizeMQ's t=0 aligns with tStart = time − window/2.
  _computePartialSpectrum(partial, time) {
    if (this.onGetSynthOpts) this.synthOpts = this.onGetSynthOpts();
    const sampleRate     = this.audioBuffer.sampleRate;
    const FFT_SIZE       = 2048;
    const windowDuration = FFT_SIZE / sampleRate;
    const tStart         = time - windowDuration / 2;

    // Shift curve times so synthesis window [0, windowDuration] maps to [tStart, tStart+windowDuration]
    const fc = partial.freqCurve;
    const shiftedPartial = {
      ...partial,
      freqCurve: {
        t0: fc.t0 - tStart, t1: fc.t1 - tStart,
        t2: fc.t2 - tStart, t3: fc.t3 - tStart,
        v0: fc.v0, v1: fc.v1, v2: fc.v2, v3: fc.v3,
        a0: fc.a0, a1: fc.a1, a2: fc.a2, a3: fc.a3,
      },
    };

    const pcm = synthesizeMQ([shiftedPartial], sampleRate, windowDuration, true, this.synthOpts);

    // Hann window
    for (let i = 0; i < FFT_SIZE; ++i) {
      pcm[i] *= 0.5 * (1 - Math.cos(2 * Math.PI * i / (FFT_SIZE - 1)));
    }

    // FFT
    const real = new Float32Array(FFT_SIZE);
    const imag = new Float32Array(FFT_SIZE);
    for (let i = 0; i < FFT_SIZE; ++i) real[i] = pcm[i];
    fftForward(real, imag, FFT_SIZE);

    // Power spectrum
    const squaredAmp = new Float32Array(FFT_SIZE / 2);
    for (let i = 0; i < FFT_SIZE / 2; ++i) {
      squaredAmp[i] = (real[i] * real[i] + imag[i] * imag[i]) / (FFT_SIZE * FFT_SIZE);
    }

    // maxDB for normalizing the display
    let maxSq = 1e-20;
    for (let i = 0; i < squaredAmp.length; ++i) if (squaredAmp[i] > maxSq) maxSq = squaredAmp[i];
    const maxDB = 10 * Math.log10(maxSq);

    return {squaredAmp, maxDB, sampleRate, fftSize: FFT_SIZE};
  }

  // Scan the partial across its full duration to find the peak dB level, then derive
  // [dbMin, dbMax] as [peak − 60, peak].  Cached per partialIndex; only called once on select.
  _computePartialRange(partialIndex, partial) {
    const fc = partial.freqCurve;
    if (!fc) return {partialIndex, dbMin: -60, dbMax: 0};
    const N = 8;
    let globalMaxSq = 1e-20;
    for (let i = 0; i < N; ++i) {
      const t = fc.t0 + (fc.t3 - fc.t0) * (i + 0.5) / N;
      const {squaredAmp} = this._computePartialSpectrum(partial, t);
      for (let b = 0; b < squaredAmp.length; ++b) {
        if (squaredAmp[b] > globalMaxSq) globalMaxSq = squaredAmp[b];
      }
    }
    const dbMax = 10 * Math.log10(globalMaxSq);
    return {partialIndex, dbMin: dbMax - 60, dbMax};
  }

  // --- View management ---

  updateViewBounds() {
    const full_duration = this.t_max - this.t_min;
    const view_duration = full_duration / this.zoom_factor;

    let t_view_min = this.t_center - view_duration / 2;
    let t_view_max = this.t_center + view_duration / 2;

    if (t_view_min < this.t_min) { t_view_min = this.t_min; t_view_max = this.t_min + view_duration; }
    if (t_view_max > this.t_max) { t_view_max = this.t_max; t_view_min = this.t_max - view_duration; }
    if (t_view_min < this.t_min) t_view_min = this.t_min;
    if (t_view_max > this.t_max) t_view_max = this.t_max;

    this.t_view_min = t_view_min;
    this.t_view_max = t_view_max;

    const actual_duration = this.t_view_max - this.t_view_min;
    this.zoom_factor = full_duration / actual_duration;
    this.t_center = (this.t_view_min + this.t_view_max) / 2;
  }

  destroy() {
    const {canvas} = this;
    canvas.removeEventListener('mousedown',  this._onMousedown);
    canvas.removeEventListener('mousemove',  this._onMousemove);
    canvas.removeEventListener('mouseleave', this._onMouseleave);
    canvas.removeEventListener('mouseup',    this._onMouseup);
    canvas.removeEventListener('wheel',      this._onWheel);
  }

  setupMouseHandlers() {
    const {canvas, tooltip} = this;

    this._onMousedown = (e) => {
      const {x, y} = getCanvasCoords(e, canvas);

      // Explore mode: commit preview on click
      if (this.exploreMode) {
        if (this.previewPartial && this.onExploreCommit) {
          this.onExploreCommit(this.previewPartial);
        }
        return;
      }

      // Check control point drag on selected partial
      if (this.selectedPartial >= 0 && this.selectedPartial < this.partials.length) {
        const ptIdx = this.hitTestControlPoint(x, y, this.partials[this.selectedPartial]);
        if (ptIdx >= 0) {
          if (this.onBeforeChange) this.onBeforeChange();
          this.dragState = { pointIndex: ptIdx };
          canvas.style.cursor = 'grabbing';
          e.preventDefault();
          return;
        }
      }

      // Otherwise: select partial by click
      const idx = this.hitTestPartial(x, y);
      this.selectPartial(idx);
    };
    canvas.addEventListener('mousedown', this._onMousedown);

    this._onMousemove = (e) => {
      const {x, y} = getCanvasCoords(e, canvas);

      if (this.dragState) {
        const t = clamp(this.canvasToTime(x), 0, this.t_max);
        const v = clamp(this.canvasToFreq(y), this.freqStart, this.freqEnd);
        const partial = this.partials[this.selectedPartial];
        const i = this.dragState.pointIndex;
        partial.freqCurve['t' + i] = t;
        partial.freqCurve['v' + i] = v;
        this.render();
        e.preventDefault();
        return;
      }

      this.mouseX = x;
      this.drawMouseCursor(x);

      const time = this.canvasToTime(x);
      const freq = this.canvasToFreq(y);

      if (this.exploreMode && this.onExploreMove) {
        this.onExploreMove(time, freq); // may call setPreviewPartial → redraws cursor canvas
      }

      const intensity = this.getIntensityAt(time, freq);

      if (this.playheadTime < 0) {
        this.spectrumTime = time;
        this.renderSpectrum();
        this.renderPartialSpectrum(time);
      }

      // Cursor hint for control points (skip in explore mode)
      if (!this.exploreMode) {
        if (this.selectedPartial >= 0 && this.selectedPartial < this.partials.length) {
          const ptIdx = this.hitTestControlPoint(x, y, this.partials[this.selectedPartial]);
          canvas.style.cursor = ptIdx >= 0 ? 'grab' : 'crosshair';
        } else {
          canvas.style.cursor = 'crosshair';
        }
      }

      tooltip.style.left = (e.clientX + 10) + 'px';
      tooltip.style.top  = (e.clientY + 10) + 'px';
      tooltip.style.display = 'block';
      tooltip.textContent = `${time.toFixed(3)}s, ${freq.toFixed(1)}Hz, ${intensity.toFixed(1)}dB`;
    };
    canvas.addEventListener('mousemove', this._onMousemove);

    this._onMouseleave = () => {
      this.mouseX = -1;
      this.drawMouseCursor(-1);
      tooltip.style.display = 'none';
    };
    canvas.addEventListener('mouseleave', this._onMouseleave);

    this._onMouseup = () => {
      if (this.dragState) {
        this.dragState = null;
        canvas.style.cursor = 'crosshair';
        if (this.onPartialSelect) this.onPartialSelect(this.selectedPartial);
      }
    };
    canvas.addEventListener('mouseup', this._onMouseup);

    this._onWheel = (e) => {
      e.preventDefault();
      const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX;

      if (e.shiftKey) {
        const rect = canvas.getBoundingClientRect();
        const mouseTime = this.canvasToTime(e.clientX - rect.left);
        const zoomDelta = delta > 0 ? 1.2 : 1 / 1.2;
        const newZoom = this.zoom_factor * zoomDelta;
        if (newZoom < 1.0) {
          this.zoom_factor = 1.0;
          this.t_center = (this.t_max + this.t_min) / 2;
        } else {
          this.zoom_factor = newZoom;
          const newDuration = (this.t_max - this.t_min) / this.zoom_factor;
          const mouseRatio = (mouseTime - this.t_view_min) / (this.t_view_max - this.t_view_min);
          this.t_center = mouseTime - newDuration * (mouseRatio - 0.5);
        }
      } else {
        const timeDuration = this.t_view_max - this.t_view_min;
        this.t_center += (delta / 100) * timeDuration * 0.1;
      }

      this.updateViewBounds();
      this.render();
    };
    canvas.addEventListener('wheel', this._onWheel);
  }

  // --- Utilities ---

  getAxisStep(range) {
    const steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000];
    const targetStep = range / 8;
    for (const step of steps) { if (step >= targetStep) return step; }
    return steps[steps.length - 1];
  }

  drawAxes() {
    const {ctx, canvas} = this;
    const width = canvas.width;
    const height = canvas.height;

    ctx.strokeStyle = '#666';
    ctx.fillStyle = '#aaa';
    ctx.font = '11px monospace';
    ctx.lineWidth = 1;

    // Time axis
    const timeDuration = this.t_view_max - this.t_view_min;
    const timeStep = this.getAxisStep(timeDuration);
    let t = Math.ceil(this.t_view_min / timeStep) * timeStep;
    while (t <= this.t_view_max) {
      const x = this.timeToX(t);
      ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke();
      ctx.fillText(t.toFixed(2) + 's', x + 2, height - 4);
      t += timeStep;
    }

    // Frequency axis (log-spaced ticks)
    for (const f of [20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 16000]) {
      if (f < this.freqStart || f > this.freqEnd) continue;
      const y = this.freqToY(f);
      ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke();
      ctx.fillText((f >= 1000 ? (f/1000).toFixed(0) + 'k' : f.toFixed(0)) + 'Hz', 2, y - 2);
    }
  }
}