-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmidiDudes.ts
501 lines (464 loc) · 15.4 KB
/
midiDudes.ts
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
import _, { get } from 'lodash'
import { terminal } from 'terminal-kit'
import convert from 'color-convert'
import { getLedController } from '@benkrejci/led-dudes/dist/led-controller'
import { ActiveNote, MidiInput } from './MidiInput'
import * as color from './utility/color'
import * as leds from './utility/leds'
import * as curves from './utility/curves'
import * as constants from './constants'
import { EnvelopedNote } from './utility/envelope'
const CURSOR_RGB: color.Rgb = color.to8BitRgb(
convert.hsv.rgb([0, constants.CURSOR_SATURATION, 100])
)
const BACKGROUND_DEFAULT_RGB: color.Rgb = color.to8BitRgb(
convert.hsv.rgb([0, 75, 4])
)
const clampBackground = (value: number): number =>
curves.linear(
value,
0,
255,
constants.BACKGROUND_MIN,
constants.BACKGROUND_MAX
)
const LOWS_RGB: color.Rgb = color
.to8BitRgb(
convert.hsv.rgb([
360 - constants.LOW_HIGH_HUE_OFFSET,
constants.BACKGROUND_SATURATION,
100,
])
)
.map(clampBackground)
const HIGHS_RGB: color.Rgb = color
.to8BitRgb(
convert.hsv.rgb([
constants.LOW_HIGH_HUE_OFFSET,
constants.BACKGROUND_SATURATION,
100,
])
)
.map(clampBackground)
const ledController = getLedController({
ledType: constants.LED_TYPE,
colorOrder: 'grb',
stripLength: constants.LED_STRIP_LENGTH,
})
const midiInput = MidiInput.create()
export interface CurveParams {
scale?: number
sigmoid?: number
power?: number
}
interface MoodListItem {
activeNote: ActiveNote
next?: MoodListItem
}
let moodListFirst: MoodListItem | undefined
let moodListLast: MoodListItem | undefined
const addMoodItem = (activeNote: ActiveNote) => {
if (!moodListFirst || !moodListLast) {
moodListFirst = moodListLast = { activeNote }
} else {
moodListLast.next = { activeNote },
moodListLast = moodListLast.next
}
}
const removeMoodItem = (moodItem: MoodListItem) => {
if (!moodItem || moodItem !== moodListFirst) return
moodListFirst = moodListFirst.next
}
export let activeNotes: Map<number, EnvelopedNote> = new Map()
midiInput.on('add', (activeNote) => {
const existingNote = activeNotes.get(activeNote.note)
if (existingNote) existingNote.setActiveNote(activeNote)
else activeNotes.set(activeNote.note, new EnvelopedNote(activeNote))
// update moving average queues
addMoodItem(activeNote)
})
midiInput.on('remove', (activeNote) => {
const releasableNote = activeNotes.get(activeNote.note)
if (releasableNote)
releasableNote.stopTime = Number(process.hrtime.bigint()) / 1e6
})
type MoodParam =
// | 'force'
| 'forceScale'
| 'forceHue'
// | 'speed'
| 'lows'
| 'highs'
type MoodParams<T = number> = Record<MoodParam, T>
type GetValueWithNoteIndex = (
noteIndex: number,
total: number,
config: MoodConfig,
t: number
) => number
interface MoodConfig {
name: MoodParam
type: 'foreground' | 'background' | 'hue' | 'scale' | 'backgroundScale'
noLimit?: boolean
rgb?: color.Rgb
movingAveragePeriod: number
maxRateOfChangeUp?: number
maxRateOfChangeDown?: number
reduceMoodListItem: (
total: number,
currentItem: MoodListItem,
lastItem: MoodListItem | undefined,
timeLeftInPeriod: number,
config: MoodConfig
) => number
getValue?: (total: number, config: MoodConfig, t: number) => number
getValueWithNoteIndex?: GetValueWithNoteIndex
}
const MOOD_CONFIGS: MoodConfig[] = [
{
name: 'forceScale',
type: 'backgroundScale',
movingAveragePeriod: 2 * 1000,
reduceMoodListItem: (
total,
currentItem,
_lastItem,
timeLeftInPeriod: number,
config: MoodConfig
) =>
Math.max(
total,
((currentItem.activeNote.velocity / constants.VELOCITY_MAX) *
timeLeftInPeriod) /
config.movingAveragePeriod
),
getValue: (total) => curves.parabolic(total, 3, 0.3, 0.9, 0.2, 1),
},
{
name: 'forceHue',
type: 'hue',
movingAveragePeriod: 20 * 1000,
maxRateOfChangeDown: constants.SPEED_MAX_RATE_DOWN,
maxRateOfChangeUp: constants.SPEED_MAX_RATE_UP,
reduceMoodListItem: (
total,
currentItem,
_lastItem,
timeLeftInPeriod: number,
config: MoodConfig
) =>
Math.max(
total,
(currentItem.activeNote.velocity / constants.VELOCITY_MAX) *
(timeLeftInPeriod / config.movingAveragePeriod)
),
getValue: (total) => curves.parabolic(
total,
constants.FORCE_HUE_EXP,
constants.FORCE_HUE_START,
constants.FORCE_HUE_END,
constants.FORCE_HUE_MIN,
constants.FORCE_HUE_MAX
),
},
// {
// name: 'speed',
// type: 'hue',
// noLimit: true,
// movingAveragePeriod: constants.SPEED_MOVING_AVERAGE_PERIOD,
// maxRateOfChangeDown: constants.SPEED_MAX_RATE_DOWN,
// maxRateOfChangeUp: constants.SPEED_MAX_RATE_UP,
// reduceMoodListItem: (total, currentItem, lastItem) =>
// total +
// (currentItem.activeNote.note > constants.SPEED_NOTE_MIN &&
// (!lastItem ||
// currentItem.activeNote.startTime -
// lastItem.activeNote.startTime >
// 30)
// ? 1
// : 0),
// getValue: (total, config, _t) =>
// curves.parabolic(
// total / config.movingAveragePeriod,
// constants.SPEED_HUE_EXP,
// constants.SPEED_HUE_START,
// constants.SPEED_HUE_END,
// constants.SPEED_HUE_MIN,
// constants.SPEED_HUE_MAX
// ),
// },
{
name: 'lows',
type: 'background',
rgb: LOWS_RGB,
movingAveragePeriod: 5e3,
reduceMoodListItem: (
total,
currentItem,
_lastItem,
timeLeftInPeriod,
config
) =>
total +
(curves.parabolic(currentItem.activeNote.note, 2.5, 60, 30) *
timeLeftInPeriod) /
config.movingAveragePeriod,
getValueWithNoteIndex: (noteIndex, total) =>
curves.parabolic(total, 2, 0, 1) *
curves.parabolic(noteIndex, 2, 70, 30),
},
{
name: 'highs',
type: 'background',
rgb: HIGHS_RGB,
movingAveragePeriod: 8 * 1000,
reduceMoodListItem: (
total,
currentItem,
_lastItem,
timeLeftInPeriod,
config
) =>
total +
(curves.parabolic(currentItem.activeNote.note, 2.5, 60, 90) *
timeLeftInPeriod) /
config.movingAveragePeriod,
getValueWithNoteIndex: (noteIndex, total) =>
curves.parabolic(total, 2, 0, 1) *
curves.parabolic(noteIndex, 2, 50, 90),
},
]
const moodConfigWithNoteIndex = MOOD_CONFIGS.filter(
(config) => config.getValueWithNoteIndex
)
let lastMoodParams: MoodParams = {
// force: 0,
forceScale: 0,
forceHue: 0,
// speed: 0,
lows: 0,
highs: 0,
}
interface Mood {
backgroundScale: number
backgroundRgb: color.Rgb
totals: MoodParams
hue: number
scale: number
}
let lastMoodTime = 0
const getMood = (t: number): Mood => {
const dt = t - lastMoodTime
lastMoodTime = t
let currentItem = moodListFirst
const totals: MoodParams = {
// force: 0,
forceScale: 0,
forceHue: 0,
// speed: 0,
lows: 0,
highs: 0,
}
let lastItem: MoodListItem | undefined
while (currentItem) {
const dt = t - currentItem.activeNote.startTime
let numWithinPeriod = 0
for (let config of MOOD_CONFIGS) {
const timeLeftInPeriod = config.movingAveragePeriod - dt
if (timeLeftInPeriod > 0) {
numWithinPeriod++
totals[config.name] = config.reduceMoodListItem(
totals[config.name] || 0,
currentItem,
lastItem,
timeLeftInPeriod,
config
)
}
}
if (!numWithinPeriod) removeMoodItem(currentItem)
lastItem = currentItem
currentItem = currentItem.next
}
let backgroundRgb: color.Rgb = color.to8BitRgb([0, 0, 0])
const hues: number[] = []
const scales: number[] = []
const backgroundScales: number[] = []
for (const config of MOOD_CONFIGS) {
const total = totals[config.name]
if (!config.getValue && !config.getValueWithNoteIndex) {
throw new TypeError(
`Config must provide either getValueWithNoteIndex or getValue function`
)
} else if (config.getValue) {
let amplitude = config.getValue(total, config, t)
amplitude = lastMoodParams[config.name] = curves.approach(
lastMoodParams[config.name],
amplitude,
(config.maxRateOfChangeUp ||
constants.MAX_RATE_OF_CHANGE_UP_DEFAULT) * dt,
(config.maxRateOfChangeDown ||
constants.MAX_RATE_OF_CHANGE_DOWN_DEFAULT) * dt
)
if (config.type === 'background') {
backgroundRgb = <color.Rgb>backgroundRgb.map(
(value, colorIndex) => {
if (!config.rgb || isNaN(config.rgb[colorIndex]))
throw new TypeError(
`Missing required rgb prop on ${config.type} config`
)
return value + config.rgb[colorIndex] * amplitude
}
)
} else if (config.type === 'hue') {
hues.push(amplitude)
} else if (config.type === 'scale') {
scales.push(amplitude)
} else if (config.type === 'backgroundScale') {
backgroundScales.push(amplitude)
}
}
}
let backgroundScale = 1
if (backgroundScales.length) {
backgroundScale =
backgroundScales.reduce((previous, current) => previous + current) /
backgroundScales.length
backgroundRgb = <color.Rgb>(
backgroundRgb.map((value) => value * backgroundScale)
)
}
backgroundRgb = color.defaultBlendRgb(
backgroundRgb,
BACKGROUND_DEFAULT_RGB
)
return {
backgroundScale,
backgroundRgb,
totals,
scale: !scales.length
? 1
: scales.reduce((previous, current) => previous + current) /
scales.length,
hue: !hues.length
? 0
: hues.reduce((previous, current) => previous + current) /
hues.length,
}
}
let frameCount = 0
let lastFpsTime: number = 0
if (constants.DEBUG) terminal.clear()
setInterval(() => {
const t = Number(process.hrtime.bigint()) / 1e6
const { backgroundRgb, backgroundScale, totals, scale, hue } = getMood(t)
const hueMatrix: number[][] = color.getHueMatrix(hue)
// calculate active note colors
let noteColors: leds.NoteColor[] = []
for (const activeNote of activeNotes.values()) {
const center = noteToLedIndex(activeNote.activeNote.note)
const amplitude = activeNote.getAmplitude()
noteColors.push({
rgb: <color.Rgb>CURSOR_RGB.map((value) => amplitude * value),
ledIndex: center,
})
}
// sort in reverse order so we can pop stuff
noteColors = noteColors.sort((a, b) => b.ledIndex - a.ledIndex)
for (let ledIndex = 0; ledIndex < constants.LED_STRIP_LENGTH; ledIndex++) {
let currentColor: color.Rgb = backgroundRgb
const noteIndex = ledToNoteIndex(ledIndex)
for (const config of moodConfigWithNoteIndex) {
const configRgb = config.rgb
if (config.getValueWithNoteIndex && configRgb) {
const total = totals[config.name]
const amplitude = config.getValueWithNoteIndex(
noteIndex,
total,
config,
t
)
currentColor = currentColor.map(
(value, colorIndex) =>
value +
backgroundScale * amplitude * configRgb[colorIndex]
)
}
}
for (
let noteColorIndex = noteColors.length - 1;
noteColorIndex >= 0;
noteColorIndex--
) {
const noteColor = noteColors[noteColorIndex]
const distance = noteColor.ledIndex - ledIndex
if (distance >= constants.LED_NOTE_WIDTH) {
break
} else if (distance < -constants.LED_NOTE_WIDTH) {
noteColors.pop()
} else {
currentColor = <color.Rgb>(
leds
.antialias(ledIndex, noteColor)
.map((value, index) => currentColor[index] + value)
)
}
}
currentColor = color.rotateHue(currentColor, hueMatrix)
ledController.setPixel(
constants.LED_REVERSE
? constants.LED_STRIP_LENGTH - ledIndex
: ledIndex,
...color.toFloatRgb(color.gammaColor(currentColor))
)
}
ledController.update()
if (constants.DEBUG) {
const dt = t - lastFpsTime
frameCount++
if (dt >= constants.DEBUG_INTERVAL) {
const fpsString = `fps: ${debugNum((frameCount / dt) * 1000)}`
if (constants.DEBUG_TERMINAL_KIT) {
terminal
.moveTo(1, 1, fpsString)
.eraseLineAfter()
.moveTo(
1,
2,
`mood: ${JSON.stringify(
Object.fromEntries(
Object.entries(lastMoodParams).map(([k, v]) => [
k,
debugNum(v),
])
)
)}`
)
.eraseLineAfter()
.moveTo(1, 3, `hue: ${debugNum(hue)}`)
.eraseLineAfter()
} else {
console.log(fpsString)
}
frameCount = 0
lastFpsTime = t
}
}
}, 1000 / constants.MAX_FRAME_RATE)
const noteToLedIndex = (note: number): number =>
((note - constants.MIDI_NOTE_MIN) /
(constants.MIDI_NOTE_MAX - constants.MIDI_NOTE_MIN)) *
constants.LED_STRIP_LENGTH
const ledToNoteIndex = (led: number): number =>
(led / constants.LED_STRIP_LENGTH) *
(constants.MIDI_NOTE_MAX - constants.MIDI_NOTE_MIN) +
constants.MIDI_NOTE_MIN
const debugNum = (num: number) => {
const mod = num % 1
const base = num - mod
return (
String(base).padStart(4) +
'.' +
String(Math.abs(Math.round(mod * 100))).padStart(2, '0')
)
}