-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
3495 lines (3400 loc) · 172 KB
/
Copy pathindex.html
File metadata and controls
3495 lines (3400 loc) · 172 KB
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
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AudioWizard -- BPM, MIDI-Clock & Tonart (Webversion)</title>
<!--
AudioWizard Webversion: BPM-Erkennung mit MIDI-Clock, Tonerkennung mit Midi-Ausgabe und Tonart-Anzeige -- eine eigenstaendige HTML-Datei. Laeuft direkt im Browser
(Doppelklick / Strg+O) oder ueber GitHub Pages; kein Server noetig.
Quelle wahlweise Mikrofon/Line-In (getUserMedia) ODER die Wiedergabe
mithoeren (getDisplayMedia: Tab-/System-Audio -- "Loopback").
Umsetzung:
* ScriptProcessorNode statt AudioWorklet. Der Worklet laedt ein Modul,
was der Browser unter file:// (Origin "null") blockiert. Der
ScriptProcessor laedt nichts nach und laeuft daher auch lokal. Er ist
aelter/deprecated, fuer diese leichte Analyse aber voellig ausreichend.
* MIDI-Clock-Timer im Hauptthread (kein Blob-Worker -- der waere unter
file:// ebenfalls gesperrt).
* Tonart-Chroma ueber eine separate groessere FFT (saubere Halbton-
Aufloesung im Bass/Mittenbereich).
Voraussetzungen: Chrome/Edge/Opera (Web MIDI). Beim Start fragt der Browser
nach Mikrofon-Zugriff. Fuer die MIDI-Ausgabe an Software auf demselben
Rechner einen virtuellen MIDI-Port einrichten (Windows: loopMIDI, macOS:
IAC-Treiber).
Autoren: codekoch / claude
-->
<style>
:root {
--bg: #131210; --surface: #1f1d1a; --surface-hi: #2a2723;
--fg: #f2efe9; --muted: #8a857c; --accent: #1d9e75; --warn: #f0a53e;
--bar-bg: #2a2723;
}
* { box-sizing: border-box; }
body {
margin: 0; min-height: 100vh; background: var(--bg); color: var(--fg);
font-family: "Segoe UI", Helvetica, Arial, sans-serif;
display: flex; flex-direction: column;
}
header {
padding: 14px 24px; border-bottom: 1px solid var(--surface);
display: flex; align-items: baseline; gap: 12px;
}
header h1 { font-size: 18px; font-weight: 600; margin: 0; }
header .sub { color: var(--muted); font-size: 13px; }
.controls {
display: flex; flex-wrap: wrap; gap: 16px 20px; align-items: flex-end;
padding: 16px 24px; border-bottom: 1px solid var(--surface);
}
.field { display: flex; flex-direction: column; gap: 4px; }
.field label { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
.field .row { display: flex; align-items: center; gap: 8px; }
button.ghost {
background: var(--surface); color: var(--fg); border: 1px solid var(--surface-hi);
border-radius: 6px; padding: 8px 12px; font-size: 13px; cursor: pointer; white-space: nowrap;
}
button.ghost:hover { background: var(--surface-hi); }
button.ghost:disabled { opacity: .5; cursor: default; }
button.ghost.on { border-color: var(--accent); color: var(--accent); }
button.ghost.rec { border-color: #e0564e; color: #e0564e; } /* Aufnahme laeuft */
select, input[type="number"] {
background: var(--surface); color: var(--fg); border: 1px solid var(--surface-hi);
border-radius: 6px; padding: 8px 10px; font-size: 14px;
}
select { min-width: 200px; }
input[type="number"] { width: 72px; }
.range { display: flex; align-items: center; gap: 6px; }
.filelbl { font-size: 13px; color: var(--muted); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
button#startBtn {
margin-left: auto; background: var(--accent); color: #04342c; border: 0;
border-radius: 8px; padding: 12px 28px; font-size: 16px; font-weight: 700; cursor: pointer;
}
button#startBtn.stop { background: var(--warn); color: #412402; }
button#startBtn:disabled { opacity: .4; cursor: default; }
.chk { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--fg); cursor: pointer; padding: 7px 0; }
.chk input { accent-color: var(--accent); }
main {
flex: 1; display: flex; flex-direction: column; align-items: center;
justify-content: center; gap: 4px; padding: 24px;
}
.bpm {
font-size: clamp(96px, 28vw, 280px); font-weight: 700; line-height: 1;
color: var(--accent); font-variant-numeric: tabular-nums;
}
.bpm.idle { color: var(--muted); opacity: .5; }
.bpm.notes { font-size: clamp(36px, 9vw, 100px); } /* Noten-Modus: mehrere Namen */
/* Akkord-Modus: erkannte Noten klein, grau, in Klammern unter dem Akkord */
.bpm .chordsub { display: block; font-size: .28em; font-weight: 600; color: var(--muted); line-height: 1.2; margin-top: .12em; }
.keyrow { display: flex; gap: 56px; justify-content: center; align-items: flex-start; margin-top: 26px; flex-wrap: wrap; }
.keyblock { text-align: center; }
.key { font-size: clamp(40px, 9vw, 88px); font-weight: 700; line-height: 1; }
#keyName { color: var(--accent); }
#keyName.idle { color: var(--muted); opacity: .6; }
.par { font-size: .42em; font-weight: 600; color: var(--muted); margin-left: .2em; }
.cap { font-size: 14px; color: var(--muted); letter-spacing: .2em; }
.raw { font-size: 15px; color: var(--muted); margin-top: 12px; }
.status { font-size: 15px; color: var(--muted); margin-top: 2px; min-height: 1.2em; }
.level { width: min(680px, 90%); margin: 22px auto 0; display: flex; align-items: center; gap: 12px; }
.level .lbl { font-size: 12px; color: var(--muted); }
.track { flex: 1; height: 12px; background: var(--bar-bg); border-radius: 6px; overflow: hidden; }
.track > div { height: 100%; width: 0; background: var(--accent); transition: width .08s linear; }
.level .db { font-size: 12px; color: var(--muted); width: 56px; text-align: right; }
.hint { padding: 10px 24px; font-size: 13px; color: var(--muted); border-top: 1px solid var(--surface); min-height: 1.2em; }
.hint.error { color: var(--warn); }
.credit { padding: 4px 24px 10px; font-size: 11px; color: #55544e; text-align: right; }
/* Kalibrier-Panel (Tracking-Feinjustage) */
.calib { display: flex; flex-wrap: wrap; gap: 10px 26px; padding: 12px 24px; border-bottom: 1px solid var(--surface); background: #1a1916; }
.calibrow { display: flex; flex-direction: column; gap: 3px; min-width: 210px; }
.calibrow > label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
.calibrow .r { display: flex; align-items: center; gap: 10px; }
.calibrow input[type="range"] { flex: 1; accent-color: var(--accent); min-width: 120px; }
.calibrow .cval { font-size: 12px; color: var(--fg); font-variant-numeric: tabular-nums; min-width: 84px; text-align: right; }
.calib .note { flex-basis: 100%; font-size: 12px; color: var(--muted); margin: 0; }
.calib .actions { display: flex; align-items: flex-end; }
/* Speichern/Prüf-Panel (Aufnahme als Datei[en]) */
.savep { padding: 12px 24px; border-bottom: 1px solid var(--surface); background: #1a1916; display: flex; flex-direction: column; gap: 10px; }
.savep .saverow { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.savep .slbl { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
.savep .seg { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 6px 0; border-top: 1px solid var(--surface); }
.savep .seg.unsure { opacity: .7; }
.savep .seg .ix { font-size: 12px; color: var(--muted); width: 1.6em; text-align: right; }
.savep .seg .meta { font-size: 13px; color: var(--fg); font-variant-numeric: tabular-nums; min-width: 300px; }
.savep .seg .meta .q { color: var(--warn); }
.savep .seg input[type="text"] { flex: 1; min-width: 150px; background: var(--surface); color: var(--fg); border: 1px solid var(--surface-hi); border-radius: 6px; padding: 6px 8px; font-size: 13px; }
.savep .saveactions { display: flex; gap: 10px; flex-wrap: wrap; }
.savep .note { font-size: 12px; color: var(--muted); margin: 0; }
/* DJ-Modus: zwei Decks + Crossfader */
.dj { display: flex; gap: 18px; align-items: stretch; justify-content: center; width: min(1100px, 96%); margin: 8px auto 0; }
.dj .deck { flex: 1; min-width: 0; background: var(--surface); border: 1px solid var(--surface-hi); border-radius: 10px; padding: 14px 16px; text-align: center; cursor: pointer; transition: border-color .15s, background .15s; }
.dj .deck.active { border-color: var(--accent); background: #20302a; }
.dj .decktop { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
.dj .deckno { font-size: 12px; color: var(--muted); letter-spacing: .1em; }
.dj .decktop .filelbl { font-size: 12px; max-width: 60%; }
.dj .djbpm { font-size: clamp(40px, 8vw, 84px); font-weight: 700; color: var(--accent); line-height: 1.05; font-variant-numeric: tabular-nums; }
.dj .djbpm.idle { color: var(--muted); opacity: .5; }
.dj .djkey { font-size: 18px; font-weight: 600; color: var(--fg); min-height: 1.3em; }
.dj .djkey.idle { color: var(--muted); opacity: .6; }
.dj .djpos { font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; }
.dj .deck-lvl { height: 8px; margin: 8px 0; }
.dj .deckbtns { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin-top: 8px; }
.dj .deckeq { display: flex; gap: 22px; justify-content: center; align-items: flex-end; margin-top: 10px; }
.dj .eqband { display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 11px; color: var(--muted); }
.dj .eqband .eqval { font-size: 10px; color: var(--fg); min-width: 2.4em; text-align: center; }
.dj .eqsl { writing-mode: vertical-lr; direction: rtl; width: 8px; height: 96px; accent-color: var(--ok); cursor: pointer; }
.dj .xfade { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; min-width: 120px; }
.dj .xfade input[type="range"] { width: 110px; accent-color: var(--accent); }
.dj .djclock { font-size: 13px; color: var(--accent); font-weight: 700; }
main.djmode .sv { display: none !important; } /* Einzeltrack-Anzeige im DJ-Modus aus */
@media (max-width: 700px) {
.dj { flex-direction: column; gap: 10px; }
.dj .xfade { flex-direction: row; min-width: 0; }
.dj .xfade input[type="range"] { flex: 1; }
}
/* Kompaktere Darstellung auf schmalen Bildschirmen (Handy) */
@media (max-width: 600px) {
header { flex-direction: column; align-items: flex-start; gap: 1px; padding: 8px 14px; }
header h1 { font-size: 16px; }
header .sub { font-size: 11px; line-height: 1.25; }
.controls { padding: 8px 14px; gap: 7px 12px; }
.field { gap: 2px; }
.field label { font-size: 10px; }
select, input[type="number"] { padding: 5px 8px; font-size: 13px; }
select { min-width: 0; }
.field .row { gap: 6px; }
button.ghost { padding: 5px 9px; font-size: 12px; }
button#startBtn { padding: 7px 18px; font-size: 14px; border-radius: 6px; }
main { padding: 10px; }
.bpm { font-size: clamp(56px, 22vw, 150px); }
.bpm.notes { font-size: clamp(30px, 8vw, 72px); }
.key { font-size: clamp(32px, 8vw, 64px); }
.keyblock { margin-top: 14px; }
.raw, .status { font-size: 13px; }
.raw { margin-top: 6px; }
.level { margin-top: 12px; }
.hint { padding: 7px 14px; font-size: 12px; }
.credit { padding: 2px 14px 7px; }
}
</style>
</head>
<body>
<header>
<h1>AudioWizard</h1>
<span class="sub">BPM-Erkennung mit MIDI-Clock, Tonerkennung mit Midi-Ausgabe und Tonarterkennung · Webversion</span>
</header>
<section class="controls">
<div class="field">
<label for="opMode">Modus</label>
<select id="opMode">
<option value="clock">Tempo & MIDI-Clock</option>
<option value="file">Datei/Aufnahme → MIDI-Clock (driftfrei)</option>
<option value="mono">Noten → MIDI (monophon)</option>
<option value="poly">Noten → MIDI (polyphon)</option>
<option value="chord">Noten → MIDI (Akkorde)</option>
<option value="dj">DJ (2 Decks, Clock folgt)</option>
</select>
</div>
<div class="field" id="srcField">
<label for="srcMode">Quelle</label>
<select id="srcMode">
<option value="input">Audio-Eingang (Mikrofon/Line-In)</option>
<option value="display">Wiedergabe mithören (Tab/System)</option>
</select>
</div>
<div class="field" id="inField">
<label for="audioIn">Audio-Eingang</label>
<div class="row">
<select id="audioIn"></select>
<button id="loadInputs" class="ghost"
title="Mikrofon freigeben, damit alle Eingaenge mit Namen erscheinen">
Eingänge laden
</button>
</div>
</div>
<div class="field" id="fileField" style="display:none">
<label for="audioFile">Audio (Datei oder Aufnahme)</label>
<div class="row">
<button id="fileBtn" class="ghost">Datei wählen…</button>
<span id="fileNameLbl" class="filelbl">keine Datei</span>
</div>
<input type="file" id="audioFile" accept="audio/*" style="display:none">
</div>
<div class="field" id="recField" style="display:none">
<label>Aufnahme</label>
<div class="row">
<button id="recArm" class="ghost"
title="Aufnahme-Quelle bereitstellen (Tab/System oder Eingang) – vor der Aufnahme">Quelle bereitstellen</button>
<button id="recToggle" class="ghost" disabled title="Aufnahme manuell starten/stoppen">● Start</button>
<button id="recSave" class="ghost" disabled title="Aufnahme als Datei(en) speichern">Speichern…</button>
</div>
</div>
<div class="field">
<label for="midiOut">MIDI-Ausgang</label>
<select id="midiOut"></select>
</div>
<div class="field">
<label>BPM-Bereich</label>
<div class="range">
<input type="number" id="minBpm" value="70" min="30" max="300" step="1">
<span>–</span>
<input type="number" id="maxBpm" value="140" min="30" max="300" step="1">
</div>
</div>
<div class="field" id="keyField">
<label>Tonart</label>
<button id="keyToggle" class="ghost"
title="Grundtonart (mit Paralleltonart) anzeigen">anzeigen</button>
</div>
<div class="field" id="chordField">
<label>Akkord</label>
<button id="chordToggle" class="ghost"
title="Erkannten Akkord neben der Tonart anzeigen (optional)">anzeigen</button>
</div>
<div class="field" id="holdField">
<label>Hold</label>
<button id="holdBtn" class="ghost"
title="Anzeige einfrieren (für lange Breaks); die MIDI-Clock läuft konstant weiter">anhalten</button>
</div>
<div class="field" id="syncField">
<label for="beatSync">Beat-Sync</label>
<label class="chk" title="Clock regelmäßig auf den erkannten Beat nachführen (gegen Drift). Bei undeutlichem Beat läuft sie frei weiter.">
<input type="checkbox" id="beatSync" checked> auf Beat
</label>
</div>
<div class="field" id="ssField">
<label for="startStop">MIDI Start/Stop</label>
<label class="chk" title="MIDI Start/Stop senden? Aus = nur durchgehende Clock; du startest dein Gerät selbst.">
<input type="checkbox" id="startStop"> senden
</label>
</div>
<div class="field" id="octField">
<label for="octave">Oktave ±</label>
<input type="number" id="octave" value="0" min="-4" max="4" step="1"
title="Erkannte Noten für die MIDI-Ausgabe um N Oktaven verschieben">
</div>
<div class="field" id="calibField" style="display:none">
<label>Kalibrierung</label>
<button id="calibToggle" class="ghost"
title="Tracking feinjustieren (Schwellen, Latenz, Reaktion)">anzeigen</button>
</div>
<button id="startBtn">Start</button>
</section>
<section class="calib" id="calibPanel" style="display:none">
<div class="calibrow" data-modes="mono poly chord">
<label for="cLatency">Latenz (Audioblock)</label>
<div class="r"><input type="range" id="cLatency" min="0" max="3" step="1" value="1"><span class="cval" id="cLatencyV">512</span></div>
</div>
<div class="calibrow" data-modes="mono poly chord">
<label for="cSilence">Anschlag-Schwelle</label>
<div class="r"><input type="range" id="cSilence" min="-66" max="-30" step="1" value="-48"><span class="cval" id="cSilenceV">-48 dB</span></div>
</div>
<div class="calibrow" data-modes="mono chord">
<label for="cSustain">Halte-Schwelle</label>
<div class="r"><input type="range" id="cSustain" min="-78" max="-40" step="1" value="-56"><span class="cval" id="cSustainV">-56 dB</span></div>
</div>
<div class="calibrow" data-modes="mono chord">
<label for="cOff">Note-Aus-Verzögerung</label>
<div class="r"><input type="range" id="cOff" min="1" max="12" step="1" value="3"><span class="cval" id="cOffV">3</span></div>
</div>
<div class="calibrow" data-modes="mono">
<label for="cYin">YIN-Schwelle (Tonhöhe)</label>
<div class="r"><input type="range" id="cYin" min="0.05" max="0.30" step="0.01" value="0.15"><span class="cval" id="cYinV">0.15</span></div>
</div>
<div class="calibrow" data-modes="mono chord">
<label for="cChange">Wechsel-Reaktion</label>
<div class="r"><input type="range" id="cChange" min="1" max="6" step="1" value="2"><span class="cval" id="cChangeV">2</span></div>
</div>
<div class="field actions">
<button id="calibReset" class="ghost">Zurücksetzen</button>
</div>
<p class="note" id="calibNote"></p>
</section>
<section class="savep" id="savePanel" style="display:none">
<div class="saverow">
<span class="slbl">Format</span>
<label class="chk"><input type="radio" name="savefmt" id="fmtWav" value="wav" checked> WAV (unkomprimiert)</label>
<label class="chk"><input type="radio" name="savefmt" id="fmtWebm" value="webm"> WebM-Original (nur ganze Aufnahme)</label>
</div>
<div id="segList"></div>
<div class="saveactions">
<button id="saveAll" class="ghost on">Alle speichern</button>
<button id="mergeAll" class="ghost">Als ein Stück</button>
<button id="splitTime" class="ghost">Nach Zeit trennen…</button>
<button id="saveClose" class="ghost">Schließen</button>
</div>
<p class="note" id="saveNote"></p>
</section>
<main>
<div class="bpm idle sv" id="bpm">—</div>
<div class="cap sv" id="bpmCap">BPM</div>
<div class="raw sv" id="raw">roh: —</div>
<div class="status" id="status">bereit</div>
<div class="keyrow sv" id="keyRow" style="display:none">
<div class="keyblock" id="keyBlock" style="display:none">
<div class="key"><span id="keyName" class="idle">—</span><span class="par" id="keyPar"></span></div>
<div class="cap">TONART</div>
</div>
<div class="keyblock" id="chordBlock" style="display:none">
<div class="key"><span id="chordName" class="idle">—</span></div>
<div class="cap">AKKORD</div>
</div>
</div>
<div class="level sv">
<span class="lbl">PEGEL</span>
<div class="track"><div id="levelBar"></div></div>
<span class="db" id="db">-60 dB</span>
</div>
<!-- DJ-Modus: zwei Decks nebeneinander, Crossfader, Clock folgt -->
<div class="dj" id="djPanel" style="display:none">
<div class="deck" id="djDeckA" data-deck="0">
<div class="decktop"><span class="deckno">DECK A</span><span class="filelbl" id="djNameA">keine Datei</span></div>
<div class="djbpm" id="djBpmA">—</div><div class="cap">BPM</div>
<div class="djkey" id="djKeyA">—</div>
<div class="djpos" id="djPosA">–</div>
<div class="track deck-lvl"><div id="djLvlA"></div></div>
<div class="deckbtns">
<button class="ghost" id="djFileA">Datei A…</button>
<button class="ghost" id="djPlayA" disabled>▶</button>
<button class="ghost" id="djSyncA" disabled title="auf das Tempo des anderen Decks einrasten (tonhöhen-erhaltend)">Sync</button>
<button class="ghost" id="djGlideA" disabled title="Tempo-Übergang: vom Master-Tempo aufs Eigentempo gleiten">Übergang</button>
</div>
<div class="deckeq">
<div class="eqband"><span class="eqval">0</span><input type="range" class="eqsl" data-deck="0" data-band="0" min="-40" max="6" step="1" value="0" title="Doppelklick = 0 dB"><span>Bass</span></div>
<div class="eqband"><span class="eqval">0</span><input type="range" class="eqsl" data-deck="0" data-band="1" min="-40" max="6" step="1" value="0" title="Doppelklick = 0 dB"><span>Mitte</span></div>
<div class="eqband"><span class="eqval">0</span><input type="range" class="eqsl" data-deck="0" data-band="2" min="-40" max="6" step="1" value="0" title="Doppelklick = 0 dB"><span>Höhen</span></div>
</div>
</div>
<div class="xfade">
<button class="ghost" id="djToA" title="zu Deck A überblenden (Clock folgt)">◀ A</button>
<input type="range" id="djCross" min="0" max="100" value="0" title="Crossfader A ↔ B">
<button class="ghost" id="djToB" title="zu Deck B überblenden (Clock folgt)">B ▶</button>
<div class="djclock" id="djClockLbl">Clock: A</div>
</div>
<div class="deck" id="djDeckB" data-deck="1">
<div class="decktop"><span class="deckno">DECK B</span><span class="filelbl" id="djNameB">keine Datei</span></div>
<div class="djbpm" id="djBpmB">—</div><div class="cap">BPM</div>
<div class="djkey" id="djKeyB">—</div>
<div class="djpos" id="djPosB">–</div>
<div class="track deck-lvl"><div id="djLvlB"></div></div>
<div class="deckbtns">
<button class="ghost" id="djFileB">Datei B…</button>
<button class="ghost" id="djPlayB" disabled>▶</button>
<button class="ghost" id="djSyncB" disabled title="auf das Tempo des anderen Decks einrasten (tonhöhen-erhaltend)">Sync</button>
<button class="ghost" id="djGlideB" disabled title="Tempo-Übergang: vom Master-Tempo aufs Eigentempo gleiten">Übergang</button>
</div>
<div class="deckeq">
<div class="eqband"><span class="eqval">0</span><input type="range" class="eqsl" data-deck="1" data-band="0" min="-40" max="6" step="1" value="0" title="Doppelklick = 0 dB"><span>Bass</span></div>
<div class="eqband"><span class="eqval">0</span><input type="range" class="eqsl" data-deck="1" data-band="1" min="-40" max="6" step="1" value="0" title="Doppelklick = 0 dB"><span>Mitte</span></div>
<div class="eqband"><span class="eqval">0</span><input type="range" class="eqsl" data-deck="1" data-band="2" min="-40" max="6" step="1" value="0" title="Doppelklick = 0 dB"><span>Höhen</span></div>
</div>
</div>
<input type="file" id="djFileInA" accept="audio/*" style="display:none">
<input type="file" id="djFileInB" accept="audio/*" style="display:none">
</div>
</main>
<div class="hint" id="hint"></div>
<div class="credit">codekoch / claude</div>
<script>
"use strict";
// ===========================================================================
// Stellschrauben (mirror der Python-Konstanten)
// ===========================================================================
const WINDOW_SECONDS = 8.0;
const FFT_SIZE = 2048;
const HOP_SIZE = 512;
const TEMPO_PRIOR_OCT = 0.9;
const CONF_RATIO = 1.45;
const MIN_ONSET_SUM = 1e-3;
const ANALYSIS_INTERVAL = 0.5; // haeufiger analysieren -> erste BPM frueher + schnellere Stabilisierung
const BPM_MEDIAN_LEN = 16;
const SILENCE_DB = -55.0;
const DEFAULT_MIN_BPM = 70;
const DEFAULT_MAX_BPM = 140;
// Tonart (Sha'ath-Profile, Konstanten wie im Python-Kern)
const NOTE_NAMES = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
const KS_MAJOR = [6.6,2.0,3.5,2.3,4.6,4.0,2.5,5.2,2.4,3.7,2.3,3.4];
const KS_MINOR = [6.5,2.7,3.5,5.4,2.6,3.5,2.5,5.2,4.0,2.7,4.3,3.2];
const BASS_TONIC_WEIGHT = 0.30;
const KEY_BASS_WEIGHT_FILE = 0.60; // staerkere Bass-Evidenz fuer die Einmal-Schaetzung
// (Datei/DJ): entscheidet Dur vs. Mollparallele
// deutlicher; betrifft NICHT die Live-Analyse.
const CHROMA_LOG_COMP = 10.0;
const KEY_EMA_SEC = 15.0;
const KEY_SWITCH_CONFIRM = 2;
const KEY_CONFIDENT_MARGIN = 0.12;
const KEY_CONFIDENT_MIN_N = 16;
const PPQN = 24;
const LOOKAHEAD_MS = 120;
const TICK_MS = 25;
const SLEW_BPM_PER_S = 8.0;
const DEADBAND_BPM = 0.15;
const MSG_CLOCK = 0xF8, MSG_START = 0xFA, MSG_STOP = 0xFC;
// Beat-Phasenkopplung: die Clock laeuft im aus den Beats GEMESSENEN Song-Tempo
// (kein Drift durch Tempo-Schaetzfehler) und zieht die Beat-Phase zusaetzlich
// sanft aufs Song-Raster (Proportional-Nachregelung).
const BEAT_PLL_GAIN = 0.10; // Phasen-Anteil pro Beat
const BEAT_MAX_NUDGE_MS = 6.0; // max. Phasenkorrektur pro Beat (kein hoerbarer Sprung)
const BEAT_VALID_MS = 4000; // so lange gilt ein Beat-Anker als aktuell
const BEAT_MIN_COH = 0.18; // Mindest-Phasenkohaerenz der Onset-Faltung, sonst kein Sync (kein Reissen bei undeutlichem Beat)
// Datei-Modus: Offline-Beat-Map -> driftfreie Clock gegen die Wiedergabe.
const FILE_TIGHTNESS = 100; // DP-Beat-Tracker: Bindung der Beat-Abstaende ans (lokale) Tempo
const FILE_LEAD_S = 0.18; // Vorlauf vor dem Wiedergabestart (Audio + Scheduler einschwingen)
const FILE_SCHED_INTERVAL_MS = 25; // Scheduler-Takt
const FILE_SCHED_LOOKAHEAD_S = 0.12; // so weit im Voraus werden Ticks terminiert
const FILE_CONST_DRIFT = 0.015; // <=1,5% Tempo-Unterschied 1./2. Haelfte -> "konstant" -> perfektes Raster
const FILE_FOLD_REL = 0.006; // Feinsuche der Periode: +-0,6% um den Median-Beat-Abstand
const FILE_FOLD_MIN_R = 0.45; // ab dieser Phasenkohaerenz wird die verfeinerte Periode genutzt
const SONG_GAP_S = 1.2; // Stille-Laenge (s), ab der eine Stueck-Grenze vermutet wird
const SONG_MIN_S = 15; // kuerzere Segmente werden zum Nachbarn gemerged
// Noten-Modus (Pitch -> MIDI)
const NOTE_CH = 0; // MIDI-Kanal 1
const NOTE_MIN_MIDI = 36; // C2
const NOTE_MAX_MIDI = 96; // C7
const NOTE_SILENCE_RMS = 0.004; // ~ -48 dBFS: darunter startet keine neue Note
const NOTE_SUSTAIN_RMS = 0.0015; // gehaltene Note bleibt an, solange Pegel darueber (Ausklingen)
const NOTE_OFF_FRAMES = 3; // so viele wirklich leise Frames vor Note Off (entprellt)
const YIN_THRESHOLD = 0.15; // YIN-Schwelle (kleiner = strenger)
const POLY_HARMONICS = 8; // so viele Obertoene gehen in die Salienz ein
const POLY_REL_THRESH = 0.34; // weitere Note nur, wenn Salienz >= Anteil der staerksten
const POLY_CANCEL_BINS = 3; // +/- Bins, die je Oberton geloescht werden
const NOTE_MAX_POLY = 5; // max. gleichzeitige Noten
// Akkord-Modus (erkannter Akkord -> sauberer MIDI-Akkord, Fehltoene weggefiltert)
const CHORD_MIN_SCORE = 0.74; // Mindest-Aehnlichkeit (Cosinus) Chroma<->Akkord-Template
const CHORD_MIN_MARGIN = 0.02; // Mindestabstand zum besten Akkord mit anderem Grundton (sonst kein klarer Akkord)
const CHORD_ROOT_W = 1.4; // Grundton im Template staerker gewichten (Bass-Evidenz)
const CHORD_CONFIRM = 3; // Frames zur Bestaetigung eines NEUEN Akkords (reitet die Fenster-Mischphase beim Wechsel aus)
const CHORD_OFF_FRAMES = 6; // leise Frames bis Akkord-Off (Akkorde klingen laenger aus)
const CHORD_EMA = 0.5; // Glaettung des Chroma ueber Frames (Stabilitaet bei gehaltenem Akkord)
const CHORD_FMIN = 70; // Chroma nur aus diesem Frequenzbereich -> Grundtoene, weniger Oberton-Mulm
const CHORD_FMAX = 1100;
// Akkordanzeige im Clock-Modus (optional, parallel zur Tonart; gröberer Eindruck
// aus dem Vollmix -> tolerantere Schwellen als der Gitarren-Akkord-Modus).
const CHORD_CLK_MIN_SCORE = 0.60; // ab dieser Cosinus-Aehnlichkeit ueberhaupt anzeigen
const CHORD_CLK_CONF = 0.72; // ab hier "sicher" (nicht gedimmt)
const CHORD_CLK_CONFIRM = 2; // Frames gleicher Akkord vor Anzeigewechsel
// ===========================================================================
// Radix-2-FFT (in-place)
// ===========================================================================
class FFT {
constructor(n) {
this.n = n;
this.cos = new Float32Array(n / 2);
this.sin = new Float32Array(n / 2);
for (let i = 0; i < n / 2; i++) {
this.cos[i] = Math.cos(-2 * Math.PI * i / n);
this.sin[i] = Math.sin(-2 * Math.PI * i / n);
}
const bits = Math.round(Math.log2(n));
this.rev = new Uint32Array(n);
for (let i = 0; i < n; i++) {
let x = i, r = 0;
for (let j = 0; j < bits; j++) { r = (r << 1) | (x & 1); x >>= 1; }
this.rev[i] = r >>> 0;
}
}
transform(re, im) {
const n = this.n, rev = this.rev;
for (let i = 0; i < n; i++) {
const j = rev[i];
if (j > i) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
}
for (let size = 2; size <= n; size <<= 1) {
const half = size >> 1, step = (n / size) | 0;
for (let i = 0; i < n; i += size) {
for (let k = 0; k < half; k++) {
const ci = k * step, c = this.cos[ci], s = this.sin[ci];
const a = i + k, b = a + half;
const tre = re[b] * c - im[b] * s, tim = re[b] * s + im[b] * c;
re[b] = re[a] - tre; im[b] = im[a] - tim;
re[a] += tre; im[a] += tim;
}
}
}
}
}
// ===========================================================================
// TempoAnalyzer: rollende Onset-Huellkurve -> Autokorrelation -> BPM
// ===========================================================================
class TempoAnalyzer {
constructor(sampleRate, minBpm, maxBpm) {
this.sr = sampleRate;
this.minBpm = minBpm;
this.maxBpm = maxBpm;
this.envRate = sampleRate / HOP_SIZE;
this.envLen = Math.round(WINDOW_SECONDS * this.envRate);
this.centerBpm = Math.sqrt(minBpm * maxBpm);
this.fft = new FFT(FFT_SIZE);
this.win = new Float32Array(FFT_SIZE);
for (let i = 0; i < FFT_SIZE; i++) {
this.win[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (FFT_SIZE - 1));
}
this.frame = new Float32Array(FFT_SIZE);
this.re = new Float32Array(FFT_SIZE);
this.im = new Float32Array(FFT_SIZE);
this.prevMag = new Float32Array(FFT_SIZE / 2);
this.onset = [];
this._havePrev = false;
// --- Tonart-Chroma ueber eine SEPARATE, groessere FFT ---
// Bei FFT_SIZE 2048 sind die Bins (~23 Hz) im Bass/Mittenbereich groeber
// als ein Halbton -> einzelne Tonklassen blieben leer ("Loecher"). Eine
// groessere FFT (16384 ~ 0,34 s -> ~3-Hz-Bins) gibt eine saubere Ton-
// klassen-Zuordnung. Wird nur ~1x/s ausgewertet (computeChroma).
this.NC = 16384;
this.fftC = new FFT(this.NC);
this.winC = new Float32Array(this.NC);
for (let i = 0; i < this.NC; i++) {
this.winC[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (this.NC - 1));
}
this.cbuf = new Float32Array(this.NC); // rollender Sample-Puffer
this.cbufFilled = 0;
this.reC = new Float32Array(this.NC);
this.imC = new Float32Array(this.NC);
const halfC = this.NC / 2;
this.binPc = new Int8Array(halfC); // Bin -> Tonklasse (0=C), -1=ignorieren
this.binBass = new Uint8Array(halfC); // Bin im Bassbereich? (Grundton-Evidenz)
for (let k = 1; k < halfC; k++) {
const f = k * sampleRate / this.NC;
if (f < 55 || f > 5000) { this.binPc[k] = -1; continue; }
const midi = Math.round(69 + 12 * Math.log2(f / 440));
this.binPc[k] = ((midi % 12) + 12) % 12;
this.binBass[k] = (f >= 55 && f <= 260) ? 1 : 0; // ~A1..C4
}
this.binPc[0] = -1;
}
pushChunk(chunk) {
// Samples zusaetzlich in den groesseren Chroma-Puffer schieben.
this.cbuf.copyWithin(0, HOP_SIZE);
this.cbuf.set(chunk, this.NC - HOP_SIZE);
if (this.cbufFilled < this.NC) this.cbufFilled += HOP_SIZE;
this.frame.copyWithin(0, HOP_SIZE);
this.frame.set(chunk, FFT_SIZE - HOP_SIZE);
const re = this.re, im = this.im, win = this.win;
for (let i = 0; i < FFT_SIZE; i++) { re[i] = this.frame[i] * win[i]; im[i] = 0; }
this.fft.transform(re, im);
const half = FFT_SIZE / 2;
let flux = 0;
const prev = this.prevMag;
for (let k = 0; k < half; k++) {
const mag = Math.hypot(re[k], im[k]);
const d = mag - prev[k];
if (d > 0) flux += d;
prev[k] = mag;
}
if (this._havePrev) {
this.onset.push(flux);
if (this.onset.length > this.envLen) {
this.onset.splice(0, this.onset.length - this.envLen);
}
}
this._havePrev = true;
}
// Chroma (pcp + bass, je auf Summe 1, log-komprimiert) aus dem aktuellen
// Sample-Puffer ueber die grosse FFT berechnen. null, solange der Puffer
// noch nicht voll ist (~0,34 s nach Start).
computeChroma() {
if (this.cbufFilled < this.NC) return null;
const re = this.reC, im = this.imC, win = this.winC;
for (let i = 0; i < this.NC; i++) { re[i] = this.cbuf[i] * win[i]; im[i] = 0; }
this.fftC.transform(re, im);
const halfC = this.NC / 2;
const c = new Float32Array(12), bas = new Float32Array(12);
const bpc = this.binPc, bbs = this.binBass;
for (let k = 1; k < halfC; k++) {
const pc = bpc[k];
if (pc < 0) continue;
const mag = Math.hypot(re[k], im[k]);
c[pc] += mag;
if (bbs[k]) bas[pc] += mag;
}
const pcp = chromaNorm(c);
const bass = chromaNorm(bas);
return pcp ? { pcp, bass: bass || new Float32Array(12) } : null;
}
estimate() {
const e = this.onset, L = e.length;
if (L < this.envRate * 0.9) return null; // ~0,9 s Mindestfenster -> erste BPM erscheint frueh.
// Unsichere/instabile Schaetzungen filtert ohnehin CONF_RATIO weiter unten,
// d. h. bei undeutlichem Beat wartet die Anzeige automatisch laenger.
let mean = 0;
for (let i = 0; i < L; i++) mean += e[i];
mean /= L;
if (mean < MIN_ONSET_SUM) return null;
const x = new Float32Array(L);
let energy = 0;
for (let i = 0; i < L; i++) { x[i] = e[i] - mean; energy += x[i] * x[i]; }
if (energy <= 0) return null;
const lagMin = Math.max(2, Math.floor(60 * this.envRate / this.maxBpm));
const lagMax = Math.min(L - 2, Math.ceil(60 * this.envRate / this.minBpm));
if (lagMax <= lagMin) return null;
const acfMax = Math.min(L - 2, lagMax * 4);
const acf = new Float32Array(acfMax + 1);
for (let lag = lagMin; lag <= acfMax; lag++) {
let s = 0;
for (let i = 0; i + lag < L; i++) s += x[i] * x[i + lag];
acf[lag] = s / energy;
}
const harmW = [1.0, 0.6, 0.4, 0.25];
let best = -Infinity, bestLag = -1, scoreSum = 0, scoreCnt = 0;
const priorW = TEMPO_PRIOR_OCT;
for (let lag = lagMin; lag <= lagMax; lag++) {
let comb = 0;
for (let h = 1; h <= 4; h++) { const hl = lag * h; if (hl <= acfMax) comb += harmW[h - 1] * acf[hl]; }
const bpm = 60 * this.envRate / lag;
const lo = Math.log2(bpm / this.centerBpm) / priorW;
const prior = Math.exp(-0.5 * lo * lo);
const score = comb * prior;
scoreSum += score; scoreCnt++;
if (score > best) { best = score; bestLag = lag; }
}
if (bestLag < 0) return null;
const meanScore = scoreSum / Math.max(1, scoreCnt);
const ratio = meanScore > 0 ? best / meanScore : 0;
if (best <= 0 || ratio < CONF_RATIO) return null;
let lag = bestLag;
const y0 = acf[bestLag - 1], y1 = acf[bestLag], y2 = acf[bestLag + 1];
const denom = (y0 - 2 * y1 + y2);
if (denom !== 0) { const delta = 0.5 * (y0 - y2) / denom; if (delta > -1 && delta < 1) lag = bestLag + delta; }
return { bpm: 60 * this.envRate / lag, conf: ratio };
}
// Beat-Phase: Abstand (in Sekunden) vom Ende der Huellkurve zum letzten Beat.
// Sucht die Phase, bei der ein Puls-Raster im Beat-Abstand am besten auf die
// Onset-Spitzen faellt. null, wenn zu wenig Daten. Der konstante Mess-Versatz
// (Eingangslatenz) ist egal -- entscheidend ist, dass kein Drift entsteht.
beatPhase(bpm) {
const e = this.onset, L = e.length;
if (L < this.envRate * 2 || bpm <= 0) return null;
const P = 60 * this.envRate / bpm; // Beat-Periode in Frames
if (P < 2) return null;
let mean = 0; for (let i = 0; i < L; i++) mean += e[i]; mean /= L;
const steps = Math.max(12, Math.round(P));
let bestOff = 0, bestScore = -Infinity;
for (let s = 0; s < steps; s++) {
const off = s * P / steps;
let score = 0;
for (let k = 0; ; k++) {
const idx = Math.round(L - 1 - off - k * P);
if (idx < 0) break;
const v = e[idx] - mean;
if (v > 0) score += v; // halbweg-gleichgerichtet
}
if (score > bestScore) { bestScore = score; bestOff = off; }
}
return bestOff / this.envRate; // Sekunden seit letztem Beat
}
// Beat-Raster fuer die Phasenkopplung der Clock: faltet die rollende Onset-
// Huellkurve eng um das Tempo (Phasen-Kohaerenz, wie im Datei-Modus). Liefert
// verfeinerte Periode + Phase (Sekunden seit letztem Beat) + Guete (0..1).
// Robuster als die Einzelfenster-Kammsuche -- nur bei hoher Guete einrasten.
beatGrid(bpm) {
const e = this.onset, L = e.length;
if (!(bpm > 0) || L < this.envRate * 3) return null; // >= ~3 s Historie
let mean = 0; for (let i = 0; i < L; i++) mean += e[i]; mean /= L;
let denom = 0; for (let i = 0; i < L; i++) { const w = e[i] - mean; if (w > 0) denom += w; }
if (denom <= 0) return null;
const P0 = 60 * this.envRate / bpm; // Periode in Frames
const coh = (P) => {
let sc = 0, ss = 0;
for (let i = 0; i < L; i++) { const w = e[i] - mean; if (w <= 0) continue; const a = 2 * Math.PI * i / P; sc += w * Math.cos(a); ss += w * Math.sin(a); }
return [Math.hypot(sc, ss) / denom, Math.atan2(ss, sc)];
};
let lo = P0 * 0.97, hi = P0 * 1.03, bestP = P0, bestR = -1, bestAng = 0;
for (let pass = 0; pass < 2; pass++) { // grob -> fein um das Maximum
const steps = 60;
for (let s = 0; s <= steps; s++) { const P = lo + (hi - lo) * s / steps; const r = coh(P); if (r[0] > bestR) { bestR = r[0]; bestP = P; bestAng = r[1]; } }
const span = (hi - lo) / steps * 3; lo = bestP - span; hi = bestP + span;
}
let phase0 = (bestAng / (2 * Math.PI)) * bestP; phase0 = ((phase0 % bestP) + bestP) % bestP;
const lastIdx = L - 1;
const k = Math.floor((lastIdx - phase0) / bestP);
const offFrames = lastIdx - (phase0 + k * bestP); // Frames seit letztem Beat (0..bestP)
return { offSec: offFrames / this.envRate, periodSec: bestP / this.envRate, coherence: bestR };
}
}
// ===========================================================================
// Tonart-Bestimmung (Sha'ath-Profile, Bass-Evidenz) -- portiert aus
// classify_key() im Python-Kern.
// ===========================================================================
function chromaNorm(v) {
let s = 0; for (let i = 0; i < 12; i++) s += v[i];
if (s <= 0) return null;
const out = new Float32Array(12);
let s2 = 0;
for (let i = 0; i < 12; i++) { out[i] = Math.log1p(CHROMA_LOG_COMP * (v[i] / s)); s2 += out[i]; }
if (s2 > 0) for (let i = 0; i < 12; i++) out[i] /= s2;
return out;
}
// Pearson-Korrelation von pcp mit dem um i rotierten Profil (Grundton -> i):
// rotiertes Profil r[j] = prof[(j - i) mod 12].
function profCorr(pcp, prof, i) {
let ma = 0, mb = 0;
for (let j = 0; j < 12; j++) { ma += pcp[j]; mb += prof[j]; }
ma /= 12; mb /= 12;
let num = 0, da = 0, db = 0;
for (let j = 0; j < 12; j++) {
const pj = prof[((j - i) % 12 + 12) % 12];
const xa = pcp[j] - ma, xb = pj - mb;
num += xa * xb; da += xa * xa; db += xb * xb;
}
const den = Math.sqrt(da * db);
return den > 0 ? num / den : 0;
}
function classifyKey(pcp, bass, bassWeight) {
const useBass = bass && bass.some(v => v > 0);
const w = (bassWeight == null) ? BASS_TONIC_WEIGHT : bassWeight;
const scores = [];
for (let i = 0; i < 12; i++) {
let bonus = 0;
if (useBass) bonus = w * (bass[i] + 0.5 * bass[(i + 7) % 12]);
scores.push([profCorr(pcp, KS_MAJOR, i) + bonus, NOTE_NAMES[i] + ' Dur']);
scores.push([profCorr(pcp, KS_MINOR, i) + bonus, NOTE_NAMES[i] + ' Moll']);
}
scores.sort((a, b) => b[0] - a[0]);
return { name: scores[0][1], margin: scores[0][0] - scores[1][0], second: scores[1][1] };
}
// Paralleltonart (relative Tonart): C-Dur <-> a-Moll usw.
function parallelKey(key) {
const p = key.split(' ');
if (p.length !== 2) return '';
const i = NOTE_NAMES.indexOf(p[0]);
if (i < 0) return '';
if (p[1] === 'Dur') return NOTE_NAMES[(i + 9) % 12] + ' Moll';
if (p[1] === 'Moll') return NOTE_NAMES[(i + 3) % 12] + ' Dur';
return '';
}
// ===========================================================================
// MidiClock -- 24 PPQN, Ticks per send(timestamp) im Voraus geplant.
// Scheduler-Timer hier im Hauptthread (kein Blob-Worker -> file://-tauglich).
// ===========================================================================
class MidiClock {
constructor() {
this.output = null;
this.enabled = false;
this.targetBpm = null;
this.curBpm = 120;
this.running = false;
this.nextTick = 0;
this.tickInBeat = 0; // 0..23; Tick 0 ist ein Beat
this._lastSched = 0;
this.sendStartStop = false; // MIDI Start/Stop senden? (Standard: nein)
// Beat-Phasenkopplung
this.anchor = 0; // geglaettete performance.now-Zeit eines Song-Beats (ms)
this.period = 0; // Beat-Abstand fuers Grid = verfeinerte Periode (ms)
this.anchorTime = 0; // wann der Anker zuletzt aktualisiert wurde
this.anchorValid = false;
this.refPeriod = 0; // aus aufeinanderfolgenden Beats gemessene Periode
this.refAnchor = 0; // letzter gemeldeter echter Beat (fuer die Messung)
this._timer = setInterval(() => this._schedule(), TICK_MS);
}
setOutput(output) {
if (this.output === output) return;
if (this.running && this.sendStartStop) this._send(MSG_STOP);
this.running = false;
this.output = output;
}
enable() {
if (this.enabled) return;
this.enabled = true;
this._lastSched = performance.now();
}
disable() {
this.enabled = false;
if (this.running && this.sendStartStop) this._send(MSG_STOP);
this.running = false;
this.anchorValid = false;
}
setTargetBpm(bpm) { this.targetBpm = bpm; }
// Beat-Kopplung sofort loesen (Beat-Sync aus): Clock laeuft frei im Tempo weiter.
clearBeat() { this.anchorValid = false; this.refPeriod = 0; }
// Song-Beat-Raster melden: anchorMs = Zeit eines Beats, periodMs = Beat-Abstand.
// Der Anker wird leicht geglaettet (auf das vorige Raster projiziert + EMA).
setBeat(anchorMs, periodMs) {
if (!(periodMs > 0)) return;
const now = performance.now();
const fresh = this.anchorValid && (now - this.anchorTime) < BEAT_VALID_MS;
// Echte Beat-Periode aus dem Abstand zweier gemessener Beats verfeinern --
// genauer als die Tempo-Schaetzung, daher laeuft die Clock im Song-Tempo
// und driftet nicht weg.
if (fresh && this.refPeriod > 0) {
const dt = anchorMs - this.refAnchor;
const beats = Math.round(dt / this.refPeriod);
if (beats >= 1 && beats <= 8) {
const measured = dt / beats;
if (measured > periodMs * 0.6 && measured < periodMs * 1.6) {
this.refPeriod += 0.35 * (measured - this.refPeriod);
}
}
} else {
this.refPeriod = periodMs;
}
this.refAnchor = anchorMs;
// Anker fuers Grid auf die verfeinerte Periode projizieren + glaetten.
if (fresh && this.period > 0) {
const m = Math.round((anchorMs - this.anchor) / this.refPeriod);
const proj = this.anchor + m * this.refPeriod;
this.anchor = proj + 0.4 * (anchorMs - proj);
} else {
this.anchor = anchorMs;
}
this.period = this.refPeriod;
this.anchorTime = now;
this.anchorValid = true;
}
_beatActive(now) {
return this.anchorValid && this.period > 0 && (now - this.anchorTime) < BEAT_VALID_MS;
}
_send(status, timestamp) {
if (!this.output) return;
try {
if (timestamp === undefined) this.output.send([status]);
else this.output.send([status], timestamp);
} catch (e) { /* Port verschwunden o.ae. */ }
}
_schedule() {
if (!this.enabled) return;
const now = performance.now();
const dt = Math.max(0, (now - this._lastSched) / 1000);
this._lastSched = now;
const haveTempo = this.targetBpm != null;
if (!this.running) {
if (!haveTempo) return; // auf erste Tempo-Schaetzung warten
this.running = true;
this.curBpm = this.targetBpm;
this.tickInBeat = 0;
// ersten Tick (Beat) auf den naechsten Song-Beat legen, falls bekannt
if (this._beatActive(now)) {
const m = Math.ceil((now + 20 - this.anchor) / this.period);
this.nextTick = this.anchor + m * this.period;
} else {
this.nextTick = now + 20;
}
if (this.sendStartStop) this._send(MSG_START);
} else if (haveTempo) {
const diff = this.targetBpm - this.curBpm;
if (Math.abs(diff) > DEADBAND_BPM) {
const maxStep = SLEW_BPM_PER_S * dt;
this.curBpm += Math.max(-maxStep, Math.min(maxStep, diff));
}
} else if (this.sendStartStop) {
this._send(MSG_STOP); this.running = false; return;
}
// ohne Start/Stop bei Stille: einfach mit letztem Tempo weiterticken.
if (this.nextTick < now - LOOKAHEAD_MS) this.nextTick = now;
const horizon = now + LOOKAHEAD_MS;
while (this.nextTick < horizon) {
// Phase: Beat-Tick (Tick 0) sanft aufs Song-Raster ziehen.
if (this.tickInBeat === 0 && this._beatActive(now)) {
const m = Math.round((this.nextTick - this.anchor) / this.period);
const err = (this.anchor + m * this.period) - this.nextTick; // ms; >0 = Song-Beat spaeter
if (Math.abs(err) < this.period * 0.45) { // Halbbeat-Slips ignorieren
this.nextTick += Math.max(-BEAT_MAX_NUDGE_MS,
Math.min(BEAT_MAX_NUDGE_MS, err * BEAT_PLL_GAIN));
}
}
// Tempo: bei aktivem Beat die GEMESSENE Song-Periode (kein Drift),
// sonst das geschaetzte/geslewte Tempo.
const eff = (this._beatActive(now) && this.refPeriod > 0)
? Math.max(20, 60000 / this.refPeriod)
: Math.max(20, this.curBpm);
this._send(MSG_CLOCK, this.nextTick);
this.nextTick += 60000 / (eff * PPQN);
this.tickInBeat = (this.tickInBeat + 1) % PPQN;
}
}
}
// ===========================================================================
// Noten-Modus: Pitch -> MIDI (monophon: YIN, polyphon: FFT-Peaks)
// ===========================================================================
function midiName(m) {
return NOTE_NAMES[((m % 12) + 12) % 12] + (Math.floor(m / 12) - 1);
}
function velFromLevel(level) {
const db = level > 0 ? 20 * Math.log10(level) : -90;
return Math.max(1, Math.min(127, Math.round((db + 54) / 48 * 127)));
}
// Akkord-Typen: [Suffix, Intervalle, Prior]. Der Prior bevorzugt bei
// Mehrdeutigkeit die haeufigen Dreiklaenge -- Vierklaenge (7/maj7/m7) und
// sus/dim/aug muessen sich gegen einen kleinen Abschlag durchsetzen, damit
// Oberton-Leckstrom (z. B. eine schwache Quinte->maj7) keinen Vierklang
// vortaeuscht.
const CHORD_TYPES = [
['', [0, 4, 7], 1.00], // Dur
['m', [0, 3, 7], 1.00], // Moll
['dim', [0, 3, 6], 0.94],
['aug', [0, 4, 8], 0.92],
['7', [0, 4, 7, 10], 0.98],
['maj7', [0, 4, 7, 11], 0.97],
['m7', [0, 3, 7, 10], 0.97],
['sus4', [0, 5, 7], 0.95],
['sus2', [0, 2, 7], 0.95],
];
// Bester Akkord zu einem 12er-Chroma (Tonklassen-Gewichte) per Cosinus-
// Aehnlichkeit gegen die Akkord-Templates -- die Standardmethode der Akkord-
// erkennung (Template-Matching, Fujishima). Der Grundton ist im Template
// staerker gewichtet (Bass-Evidenz), das stabilisiert Inversion/Mehrdeutigkeit.
// Liefert { root, typeIdx, score, margin } oder null; margin = Abstand zum
// besten Akkord mit ANDEREM Grundton (klein bei Nicht-Akkorden/Rauschen).
function bestChord(pcw) {
let nv = 0; for (let i = 0; i < 12; i++) nv += pcw[i] * pcw[i];
nv = Math.sqrt(nv); if (nv <= 0) return null;
const ranked = [];
for (let root = 0; root < 12; root++) {
for (let ti = 0; ti < CHORD_TYPES.length; ti++) {
const ivs = CHORD_TYPES[ti][1];
const tpl = new Float32Array(12);
for (const iv of ivs) tpl[(root + iv) % 12] = 1;
tpl[root] = CHORD_ROOT_W;
let dot = 0, tn = 0;
for (let i = 0; i < 12; i++) { dot += tpl[i] * pcw[i]; tn += tpl[i] * tpl[i]; }
const score = CHORD_TYPES[ti][2] * dot / (nv * Math.sqrt(tn));
ranked.push({ root, typeIdx: ti, score });
}
}
ranked.sort((a, b) => b.score - a.score);
const best = ranked[0];
const second = ranked.find(r => r.root !== best.root);
best.margin = second ? best.score - second.score : best.score;
return best;
}
// Sauberes Akkord-Voicing (Grundstellung) in dem Register, in dem gespielt
// wurde: der Grundton wird in die Oktave bei/unter der erkannten Bassnote
// gelegt, darueber die uebrigen Akkordtoene. So klingt ein tief gegriffener
// Akkord tief, ein hoher hoch -- unabhaengig von Fehltoenen.
function buildChordVoicing(root, ivs, baseMidi) {
let rootMidi = root + 12 * Math.round((baseMidi - root) / 12);
if (rootMidi > baseMidi) rootMidi -= 12;
while (rootMidi < NOTE_MIN_MIDI) rootMidi += 12;
const v = [];
for (const iv of ivs) { let n = rootMidi + iv; while (n > NOTE_MAX_MIDI) n -= 12; v.push(n); }
return [...new Set(v)].sort((a, b) => a - b);
}
// YIN-Tonhoehe (monophon): kumulative mittlere Differenz + Schwelle +