-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathharmonizer.js
More file actions
368 lines (308 loc) · 10.4 KB
/
harmonizer.js
File metadata and controls
368 lines (308 loc) · 10.4 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
const Max = require("max-api");
const fs = require("fs");
var voices = [];
var currentVoicesIndex = 0;
var currentPitch = undefined;
var currentPreset = { name: "new preset", mapping: [{}, {}] };
const MS = require("musictheoryjs");
let mode = "MIDI";
let currentScale = MS.ScaleTemplates["major"];
let latchMode = false;
let lockMode = false;
let voiceSortMode = "TOP_NOTE"; // DEFAULT, TOP_NOTE
// Store the last output to prevent unnecessary resets
let lastOutput = [0, 0, 0, 0];
// Max.outlet("scales", ...Object.keys(MS.ScaleTemplates));
// Log file path
const LOG_FILE_PATH = "./harmonizer-log.txt";
// Clear the log file at startup
try {
fs.writeFileSync(LOG_FILE_PATH, `Log started: ${new Date().toISOString()}\n`);
Max.post("Log file reset");
} catch (err) {
Max.post("Error resetting log file: " + err.message);
}
// Logging function that writes to a file
const logToFile = (message) => {
const timestamp = new Date().toISOString();
const logMessage = `${timestamp}: ${message}\n`;
try {
fs.appendFileSync(LOG_FILE_PATH, logMessage);
} catch (err) {
Max.post("Error writing to log file: " + err.message);
}
};
const resetNotes = [0, 0, 0, 0];
Max.addHandler("scale", (scale) => {
currentScale = MS.ScaleTemplates[scale];
Max.post("scale", MS.ScaleTemplates[scale]);
});
Max.addHandler("harm-in", (...arr) => {
if (lockMode) return;
logToFile(`Received harm-in: ${JSON.stringify(arr)}`);
assignHarmony(arr);
outputHarmony();
});
Max.addHandler("latchMode", (m) => {
latchMode = m;
});
Max.addHandler("lockMode", (m) => {
lockMode = m;
});
Max.addHandler("voicesPart", (i) => {
logToFile(`Switching voice part index from ${currentVoicesIndex} to ${i}`);
currentVoicesIndex = i;
outputHarmony();
});
Max.addHandler("savePreset", (name) => {
Max.post("saving preset");
currentPreset.name = name;
if (!fs.existsSync("presets")) fs.mkdirSync("presets");
fs.writeFileSync(
`./presets/${currentPreset.name}.json`,
JSON.stringify(currentPreset)
);
});
Max.addHandler("loadPreset", (name) => {
Max.post("loading preset " + name);
currentPreset = JSON.parse(fs.readFileSync(`./presets/${name}`));
Max.post(currentPreset);
outputHarmony();
});
Max.addHandler("mode", (type) => {
mode = type;
});
Max.addHandler("voiceSortMode", (type) => {
logToFile(`Switching voiceSortMode from ${voiceSortMode} to ${type}`);
voiceSortMode = type;
outputHarmony();
});
Max.addHandler("note-in", (pitch) => {
if (pitch < 0) return;
logToFile(
`Received note-in: pitch=${pitch}, mode=${mode}, voiceSortMode=${voiceSortMode}`
);
if (mode === "MIDI") {
midiHarmonize(pitch);
} else {
autoHarmonize(pitch);
}
});
const autoHarmonize = (pitch) => {
currentPitch = pitch;
var chord = new MS.Scale(currentScale).notes.map((n) => n._tone);
// chord.pitch = currentPitch;
Max.post(chord);
var chord2 = new MS.Scale(currentScale).shift(1).notes.map((n) => n._tone);
Max.post(chord2);
// if (chord) {
// var first = chord[0];
// var arr = chord.map(function (v) {
// if (v === null) {
// return 0;
// } else {
// return v - first;
// }
// });
// outputNotes(resetNotes);
// outputNotes(arr);
// } else {
// outputNotes(resetNotes);
// }
};
const midiHarmonize = (pitch) => {
currentPitch = pitch;
var chord = currentPreset.mapping[currentVoicesIndex][pitch];
logToFile(
`midiHarmonize: pitch=${pitch}, voiceIndex=${currentVoicesIndex}, chord=${JSON.stringify(
chord
)}`
);
if (chord) {
const activeNotes = chord.filter((v) => v !== null);
logToFile(`midiHarmonize: activeNotes=${JSON.stringify(activeNotes)}`);
if (activeNotes.length === 0) {
logToFile(`midiHarmonize: No active notes, outputting resetNotes`);
outputNotes(resetNotes);
return;
}
let referenceNote;
if (voiceSortMode === "TOP_NOTE") {
// Use the highest note as reference
referenceNote = Math.max(...activeNotes);
logToFile(`midiHarmonize: TOP_NOTE mode, referenceNote=${referenceNote}`);
} else {
// Use the first note as reference
referenceNote = chord[0];
logToFile(`midiHarmonize: DEFAULT mode, referenceNote=${referenceNote}`);
}
// Calculate intervals from each note to the reference note
let intervals = chord.map(function (v) {
if (v === null) {
return 0;
} else {
return v - referenceNote;
}
});
logToFile(
`midiHarmonize: calculated intervals=${JSON.stringify(intervals)}`
);
outputNotes(intervals);
} else if (latchMode) {
logToFile(
`midiHarmonize: No chord found for pitch ${pitch}, latchMode=${latchMode}, outputting resetNotes`
);
outputNotes(resetNotes);
} else {
logToFile(
`midiHarmonize: No chord found for pitch ${pitch}, no output (latchMode=${latchMode})`
);
}
};
const outputHarmony = () => {
logToFile(
`outputHarmony: Start - voices=${JSON.stringify(
voices
)}, voiceSortMode=${voiceSortMode}`
);
// Filter out null voices and create a copy to work with
const activeVoices = voices.filter((v) => v !== null);
logToFile(`outputHarmony: activeVoices=${JSON.stringify(activeVoices)}`);
if (activeVoices.length === 0) {
logToFile(`outputHarmony: No active voices, outputting resetNotes`);
outputNotes(resetNotes);
return;
}
let arrangedVoices = [];
let referenceNote;
if (voiceSortMode === "TOP_NOTE") {
// Find the highest note (top note)
const topNote = Math.max(...activeVoices);
referenceNote = topNote;
logToFile(`outputHarmony: TOP_NOTE mode, topNote=${topNote}`);
// Sort all voices ascending but put the top note first
arrangedVoices = [
topNote,
...activeVoices.filter((v) => v !== topNote).sort((a, b) => a - b),
];
} else {
// Default mode - first voice as reference, sort other voices
referenceNote = voices[0];
logToFile(`outputHarmony: DEFAULT mode, referenceNote=${referenceNote}`);
arrangedVoices = [
referenceNote,
...voices
.slice(1)
.filter((v) => v !== null)
.sort((a, b) => a - b),
];
}
logToFile(
`outputHarmony: arrangedVoices=${JSON.stringify(
arrangedVoices
)}, referenceNote=${referenceNote}`
);
// Calculate intervals based on reference note
let intervals = voices.map((v) => (v === null ? 0 : v - referenceNote));
logToFile(`outputHarmony: calculated intervals=${JSON.stringify(intervals)}`);
outputNotes(intervals);
};
const outputNotes = (notes) => {
// Ensure we have exactly 4 notes (pad with zeros if needed)
while (notes.length < 4) {
notes.push(0);
}
notes = notes.slice(0, 4); // Ensure no more than 4
// Put the reference note (0) at the beginning and sort other notes
// This improves voice leading while maintaining consistent positioning
// First, we'll place the reference note (0) at position 0
let result = [0, 0, 0, 0]; // Start with all zeros
// Get non-zero notes sorted from highest pitch to lowest
// This means smallest negative values first (-3 before -7 before -12)
const nonZeroNotes = notes.filter(n => n !== 0).sort((a, b) => a - b);
// If this is the first chord we're processing (lastOutput is all zeros)
if (lastOutput.every(n => n === 0) && nonZeroNotes.length > 0) {
// Simple initial assignment - just place in order
for (let i = 0; i < nonZeroNotes.length && i < 3; i++) {
result[i + 1] = nonZeroNotes[i];
}
logToFile(`outputNotes: Initial assignment: ${JSON.stringify(result)}`);
}
// For subsequent chords, try to maintain voice continuity
else if (nonZeroNotes.length > 0) {
// Find the non-zero notes from the previous output
const lastNonZeros = lastOutput.filter(n => n !== 0);
// For each position in the previous output that had a non-zero note,
// find the closest matching note from the new set
const usedIndices = new Set();
// First, go through positions 1-3 and try to assign notes
for (let i = 1; i < 4; i++) {
if (lastOutput[i] !== 0 && nonZeroNotes.length > 0) {
// Find the closest note that hasn't been used yet
let closestIndex = -1;
let minDistance = Infinity;
for (let j = 0; j < nonZeroNotes.length; j++) {
if (!usedIndices.has(j)) {
const distance = Math.abs(nonZeroNotes[j] - lastOutput[i]);
if (distance < minDistance) {
minDistance = distance;
closestIndex = j;
}
}
}
if (closestIndex !== -1) {
result[i] = nonZeroNotes[closestIndex];
usedIndices.add(closestIndex);
}
}
}
// Assign any remaining notes to empty positions
let remainingIndex = 0;
for (let i = 0; i < nonZeroNotes.length; i++) {
if (!usedIndices.has(i)) {
// Find the next empty position
while (remainingIndex < 4 && result[remainingIndex] !== 0) {
remainingIndex++;
}
if (remainingIndex < 4) {
result[remainingIndex] = nonZeroNotes[i];
remainingIndex++;
}
}
}
logToFile(`outputNotes: Voice-led assignment: ${JSON.stringify(result)}`);
}
// Compare with last output - only send if different
const isDifferent =
result[0] !== lastOutput[0] ||
result[1] !== lastOutput[1] ||
result[2] !== lastOutput[2] ||
result[3] !== lastOutput[3];
if (isDifferent) {
logToFile(`outputNotes: Sending to Max (voice-led): ${JSON.stringify(result)}`);
Max.outlet(["notes", ...result]);
lastOutput = [...result]; // Store current output as last output
} else {
logToFile(`outputNotes: Skipping identical output: ${JSON.stringify(result)}`);
}
};
const assignHarmony = (arr) => {
const vel = arr[2];
const pitch = arr[1];
const voice = arr[0];
logToFile(
`assignHarmony: voice=${voice}, pitch=${pitch}, velocity=${vel}, currentPitch=${currentPitch}`
);
if (vel == 0) {
logToFile(`assignHarmony: Setting voice ${voice - 1} to null (note off)`);
voices[voice - 1] = null;
} else {
logToFile(`assignHarmony: Setting voice ${voice - 1} to pitch ${pitch}`);
voices[voice - 1] = pitch;
logToFile(
`assignHarmony: Saving to preset at currentVoicesIndex=${currentVoicesIndex}, currentPitch=${currentPitch}`
);
currentPreset.mapping[currentVoicesIndex][currentPitch] = [...voices];
logToFile(`assignHarmony: Updated voices array: ${JSON.stringify(voices)}`);
}
};