@r_masseater/song-format 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1128 @@
1
+ #!/usr/bin/env node
2
+ import { t as runMain } from "./app-CdpGdiWq.mjs";
3
+ import { FumxGrammar, FumxTerminals } from "@r_masseater/fumx-parser/language";
4
+ import { AstUtils, GrammarAST } from "langium";
5
+ import { Array, Console, Effect, FileSystem, Match, Option, Order, Path, Predicate, Record, Schema, String as String$1, pipe } from "effect";
6
+ import { Argument, Command, Flag } from "effect/cli";
7
+ import { parseMidi } from "midi-file";
8
+ import { TICKS_PER_WHOLE, fractionOf, readSong } from "@r_masseater/fumx-parser";
9
+ import { Midi } from "tonal";
10
+ // src/app/convert-command.ts
11
+ const INDENT$1 = 2;
12
+ const taggedError$2 = Schema.TaggedError;
13
+ var Mismatch = class extends taggedError$2()("Mismatch", { message: Schema.String }, { identifier: "Mismatch" }) {};
14
+ const encodeSummary = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown, { space: INDENT$1 }));
15
+ const convertMain = (spec) => {
16
+ const convertFile = Effect.fn("convertFile")(function* convertFile(file, out) {
17
+ const fileSystem = yield* FileSystem.FileSystem;
18
+ const path = yield* Path.Path;
19
+ const input = path.resolve(file);
20
+ const parsed = path.parse(input);
21
+ const target = Option.match(out, {
22
+ onNone: () => path.join(parsed.dir, `${parsed.name}.fumx`),
23
+ onSome: (given) => path.resolve(given)
24
+ });
25
+ const bytes = yield* fileSystem.readFile(input);
26
+ const converted = yield* spec.convert({
27
+ bytes,
28
+ title: parsed.name,
29
+ path: target
30
+ });
31
+ yield* fileSystem.writeFileString(target, converted.text);
32
+ return {
33
+ output: target,
34
+ comparison: converted.comparison,
35
+ adjustments: converted.adjustments
36
+ };
37
+ });
38
+ const command = Command.make(spec.name, {
39
+ file: Argument.String("file").pipe(Argument.withDescription(spec.input)),
40
+ out: Flag.String("out").pipe(Flag.withDescription(`Where to write the .fumx file; defaults to the ${spec.source}'s name with .fumx`), Flag.optional)
41
+ }, ({ file, out }) => convertFile(file, out).pipe(Effect.tap((summary) => Effect.flatMap(encodeSummary(summary), Console.log)), Effect.filterOrFail((summary) => summary.comparison.matches, () => Mismatch.make({ message: `The written .fumx does not reproduce every event of the ${spec.source}` })), Effect.asVoid));
42
+ runMain(spec.name)(Command.run(command, { version: "0.0.0" }));
43
+ };
44
+ // src/entities/timeline/model/general-midi.ts
45
+ const PROGRAMS = [
46
+ "acoustic-grand-piano",
47
+ "bright-acoustic-piano",
48
+ "electric-grand-piano",
49
+ "honky-tonk-piano",
50
+ "electric-piano-1",
51
+ "electric-piano-2",
52
+ "harpsichord",
53
+ "clavinet",
54
+ "celesta",
55
+ "glockenspiel",
56
+ "music-box",
57
+ "vibraphone",
58
+ "marimba",
59
+ "xylophone",
60
+ "tubular-bells",
61
+ "dulcimer",
62
+ "drawbar-organ",
63
+ "percussive-organ",
64
+ "rock-organ",
65
+ "church-organ",
66
+ "reed-organ",
67
+ "accordion",
68
+ "harmonica",
69
+ "tango-accordion",
70
+ "acoustic-guitar-nylon",
71
+ "acoustic-guitar-steel",
72
+ "electric-guitar-jazz",
73
+ "electric-guitar-clean",
74
+ "electric-guitar-muted",
75
+ "overdriven-guitar",
76
+ "distortion-guitar",
77
+ "guitar-harmonics",
78
+ "acoustic-bass",
79
+ "electric-bass-finger",
80
+ "electric-bass-pick",
81
+ "fretless-bass",
82
+ "slap-bass-1",
83
+ "slap-bass-2",
84
+ "synth-bass-1",
85
+ "synth-bass-2",
86
+ "violin",
87
+ "viola",
88
+ "cello",
89
+ "contrabass",
90
+ "tremolo-strings",
91
+ "pizzicato-strings",
92
+ "orchestral-harp",
93
+ "timpani",
94
+ "string-ensemble-1",
95
+ "string-ensemble-2",
96
+ "synth-strings-1",
97
+ "synth-strings-2",
98
+ "choir-aahs",
99
+ "voice-oohs",
100
+ "synth-voice",
101
+ "orchestra-hit",
102
+ "trumpet",
103
+ "trombone",
104
+ "tuba",
105
+ "muted-trumpet",
106
+ "french-horn",
107
+ "brass-section",
108
+ "synth-brass-1",
109
+ "synth-brass-2",
110
+ "soprano-sax",
111
+ "alto-sax",
112
+ "tenor-sax",
113
+ "baritone-sax",
114
+ "oboe",
115
+ "english-horn",
116
+ "bassoon",
117
+ "clarinet",
118
+ "piccolo",
119
+ "flute",
120
+ "recorder",
121
+ "pan-flute",
122
+ "blown-bottle",
123
+ "shakuhachi",
124
+ "whistle",
125
+ "ocarina",
126
+ "lead-1-square",
127
+ "lead-2-sawtooth",
128
+ "lead-3-calliope",
129
+ "lead-4-chiff",
130
+ "lead-5-charang",
131
+ "lead-6-voice",
132
+ "lead-7-fifths",
133
+ "lead-8-bass-and-lead",
134
+ "pad-1-new-age",
135
+ "pad-2-warm",
136
+ "pad-3-polysynth",
137
+ "pad-4-choir",
138
+ "pad-5-bowed",
139
+ "pad-6-metallic",
140
+ "pad-7-halo",
141
+ "pad-8-sweep",
142
+ "fx-1-rain",
143
+ "fx-2-soundtrack",
144
+ "fx-3-crystal",
145
+ "fx-4-atmosphere",
146
+ "fx-5-brightness",
147
+ "fx-6-goblins",
148
+ "fx-7-echoes",
149
+ "fx-8-sci-fi",
150
+ "sitar",
151
+ "banjo",
152
+ "shamisen",
153
+ "koto",
154
+ "kalimba",
155
+ "bagpipe",
156
+ "fiddle",
157
+ "shanai",
158
+ "tinkle-bell",
159
+ "agogo",
160
+ "steel-drums",
161
+ "woodblock",
162
+ "taiko-drum",
163
+ "melodic-tom",
164
+ "synth-drum",
165
+ "reverse-cymbal",
166
+ "guitar-fret-noise",
167
+ "breath-noise",
168
+ "seashore",
169
+ "bird-tweet",
170
+ "telephone-ring",
171
+ "helicopter",
172
+ "applause",
173
+ "gunshot"
174
+ ];
175
+ const DRUMS = [
176
+ "acoustic-bass-drum",
177
+ "bass-drum-1",
178
+ "side-stick",
179
+ "acoustic-snare",
180
+ "hand-clap",
181
+ "electric-snare",
182
+ "low-floor-tom",
183
+ "closed-hi-hat",
184
+ "high-floor-tom",
185
+ "pedal-hi-hat",
186
+ "low-tom",
187
+ "open-hi-hat",
188
+ "low-mid-tom",
189
+ "hi-mid-tom",
190
+ "crash-cymbal-1",
191
+ "high-tom",
192
+ "ride-cymbal-1",
193
+ "chinese-cymbal",
194
+ "ride-bell",
195
+ "tambourine",
196
+ "splash-cymbal",
197
+ "cowbell",
198
+ "crash-cymbal-2",
199
+ "vibraslap",
200
+ "ride-cymbal-2",
201
+ "hi-bongo",
202
+ "low-bongo",
203
+ "mute-hi-conga",
204
+ "open-hi-conga",
205
+ "low-conga",
206
+ "high-timbale",
207
+ "low-timbale",
208
+ "high-agogo",
209
+ "low-agogo",
210
+ "cabasa",
211
+ "maracas",
212
+ "short-whistle",
213
+ "long-whistle",
214
+ "short-guiro",
215
+ "long-guiro",
216
+ "claves",
217
+ "hi-wood-block",
218
+ "low-wood-block",
219
+ "mute-cuica",
220
+ "open-cuica",
221
+ "mute-triangle",
222
+ "open-triangle"
223
+ ];
224
+ // src/entities/timeline/model/groups.ts
225
+ const NONE$6 = 0;
226
+ const NEXT$6 = 1;
227
+ const isDrumPart = (part) => part.channel === 9;
228
+ const chordKeyOf = (note) => `${String(note.tick)}:${String(note.end)}:${String(note.velocity)}:${String(note.release)}`;
229
+ const groupOf = (notes) => pipe(Array.head(notes), Option.map((first) => ({
230
+ start: first.tick,
231
+ end: first.end,
232
+ midis: pipe(notes, Array.map((note) => note.midi)),
233
+ velocity: first.velocity,
234
+ release: first.release,
235
+ lyric: Option.none()
236
+ })));
237
+ const stackedOf = (chord) => pipe(chord, Array.map((note, index) => ({
238
+ note,
239
+ layer: pipe(Array.take(chord, index), Array.countBy((earlier) => earlier.midi === note.midi))
240
+ })), Array.groupBy(({ layer }) => String(layer)), Record.values, Array.map((layer) => pipe(layer, Array.map(({ note }) => note))));
241
+ const chordsOf = (part) => {
242
+ if (isDrumPart(part)) return pipe(part.notes, Array.map((note) => [note]));
243
+ return pipe(part.notes, Array.groupBy(chordKeyOf), Record.values, Array.flatMap(stackedOf));
244
+ };
245
+ const byStartThenLonger = Order.combine(Order.mapInput(Order.Number, (group) => group.start), Order.mapInput(Order.flip(Order.Number), (group) => group.end));
246
+ const withLyrics = (part) => (groups) => pipe(groups, Array.map((group, index) => {
247
+ const leads = pipe(Array.get(groups, index - NEXT$6), Option.match({
248
+ onNone: () => true,
249
+ onSome: (previous) => previous.start !== group.start
250
+ }));
251
+ const lyric = pipe(Array.findFirst(part.lyrics, (candidate) => candidate.tick === group.start), Option.filter(() => leads), Option.map((found) => found.text));
252
+ return {
253
+ ...group,
254
+ lyric
255
+ };
256
+ }));
257
+ const groupsOf = (part) => {
258
+ const groups = pipe(chordsOf(part), Array.map(groupOf), Array.getSomes);
259
+ return withLyrics(part)(Array.sort(groups, byStartThenLonger));
260
+ };
261
+ const endOfLine = (line) => Option.match(Array.last(line), {
262
+ onNone: () => NONE$6,
263
+ onSome: (group) => group.end
264
+ });
265
+ const placeGroup = (lines, group) => Option.match(Array.findFirstIndex(lines, (line) => endOfLine(line) <= group.start), {
266
+ onNone: () => [...lines, [group]],
267
+ onSome: (index) => pipe(lines, Array.map((line, position) => {
268
+ if (position === index) return [...line, group];
269
+ return line;
270
+ }))
271
+ });
272
+ const linesOf = (groups) => Array.reduce(groups, [], placeGroup);
273
+ // src/entities/timeline/model/names.ts
274
+ const FIRST_SUFFIX = 2;
275
+ const keywordsIn = (node) => new Set(AstUtils.streamAst(node).filter((child) => GrammarAST.isKeyword(child)).map((keyword) => keyword.value));
276
+ const grammar = FumxGrammar();
277
+ const allowedKeywords = pipe(grammar.rules, Array.findFirst((rule) => rule.name === "Name"), Option.match({
278
+ onNone: () => /* @__PURE__ */ new Set(),
279
+ onSome: keywordsIn
280
+ }));
281
+ const allKeywords = Array.fromIterable(keywordsIn(grammar));
282
+ const reserved = new Set(pipe(allKeywords, Array.filter((keyword) => !allowedKeywords.has(keyword))));
283
+ const otherTerminals = pipe(Record.toEntries(FumxTerminals), Array.filter(([name]) => name !== "ID"), Array.map(([, pattern]) => new RegExp(`^(?:${pattern.source})$`, "u")));
284
+ const identifier = new RegExp(`^(?:${FumxTerminals.ID.source})$`, "u");
285
+ const isUsable = (name) => identifier.test(name) && !reserved.has(name) && !pipe(otherTerminals, Array.some((pattern) => pattern.test(name)));
286
+ const slugOf = (text) => pipe(text, String$1.normalize("NFKD"), String$1.toLowerCase, String$1.replaceAll(/[^a-z0-9]+/gu, "-"), String$1.replaceAll(/^[-0-9]+|-+$/gu, ""));
287
+ const nameFrom = (candidates) => pipe(candidates, Array.map(slugOf), Array.findFirst(isUsable), Option.getOrElse(() => "part"));
288
+ const uniqueAmong = (taken) => (name) => pipe(Array.range(FIRST_SUFFIX, taken.size + FIRST_SUFFIX), Array.map((suffix) => `${name}-${String(suffix)}`), Array.prepend(name), Array.findFirst((candidate) => isUsable(candidate) && !taken.has(candidate)), Option.getOrElse(() => `${name}-${String(taken.size)}`));
289
+ // src/entities/timeline/model/plan.ts
290
+ const NONE$5 = 0;
291
+ const NEXT$5 = 1;
292
+ const SHARED = 1;
293
+ const DEFAULT_PROGRAM = 0;
294
+ const drumNameOf = (midi) => Option.getOrElse(Array.get(DRUMS, midi - 35), () => `note-${String(midi)}`);
295
+ const programNameOf = (program) => Option.getOrElse(Array.get(PROGRAMS, program), () => `program-${String(program)}`);
296
+ const controllerKeyOf = ({ controller }) => {
297
+ if (controller.kind === "cc") return `cc ${String(controller.number)}`;
298
+ if (controller.kind === "pressure") return Option.match(controller.midi, {
299
+ onNone: () => "pressure",
300
+ onSome: (midi) => `pressure ${String(midi)}`
301
+ });
302
+ return controller.kind;
303
+ };
304
+ const isLastAtTick = (controls) => (index) => pipe(Option.all([Array.get(controls, index), Array.get(controls, index + NEXT$5)]), Option.match({
305
+ onNone: () => true,
306
+ onSome: ([control, next]) => next.tick !== control.tick || controllerKeyOf(next) !== controllerKeyOf(control)
307
+ }));
308
+ const byControllerThenTick = Order.combine(Order.mapInput(Order.String, controllerKeyOf), Order.mapInput(Order.Number, (control) => control.tick));
309
+ const controlsOf$1 = (part) => {
310
+ const drumProgram = pipe(part.program, Option.filter(() => isDrumPart(part)), Option.map((value) => ({
311
+ tick: NONE$5,
312
+ controller: { kind: "program" },
313
+ value
314
+ })), Option.toArray);
315
+ const sorted = Array.sort([...drumProgram, ...part.controls], byControllerThenTick);
316
+ return pipe(sorted, Array.filter((_control, index) => isLastAtTick(sorted)(index)));
317
+ };
318
+ const programOf = (part) => Option.getOrElse(part.program, () => DEFAULT_PROGRAM);
319
+ const labelOf = (part) => Option.getOrElse(part.name, () => "");
320
+ const instrumentsOf = (parts) => new Map(pipe(parts, Array.filter((part) => !isDrumPart(part)), Array.map(programOf), Array.dedupe, Array.map((program) => [program, nameFrom([programNameOf(program)])])));
321
+ const drumVoicesOf = (parts) => {
322
+ const midis = pipe(parts, Array.filter(isDrumPart), Array.flatMap((part) => part.notes), Array.map((note) => note.midi), Array.dedupe);
323
+ return new Map(pipe(Array.sort(midis, Order.Number), Array.map((midi) => [midi, drumNameOf(midi)])));
324
+ };
325
+ const channelledOf = (shared) => (part) => {
326
+ const label = labelOf(part);
327
+ if (shared.has(label)) return `${label} ch${String(part.channel + NEXT$5)}`;
328
+ return label;
329
+ };
330
+ const fallbackOf = (part) => {
331
+ if (isDrumPart(part)) return "drums";
332
+ return programNameOf(programOf(part));
333
+ };
334
+ const candidatesOf = (shared) => (part) => [
335
+ channelledOf(shared)(part),
336
+ fallbackOf(part),
337
+ `track ${String(part.track)}`
338
+ ];
339
+ const sharedLabelsOf = (parts) => new Set(pipe(parts, Array.groupBy(labelOf), Record.filter((same) => same.length > SHARED), Record.keys));
340
+ const sourceOf = (instruments) => (part) => {
341
+ if (isDrumPart(part)) return { kind: "kit" };
342
+ const program = programOf(part);
343
+ return {
344
+ kind: "instrument",
345
+ instrument: instruments.get(program) ?? "",
346
+ program
347
+ };
348
+ };
349
+ const namesOf = (planned) => new Set(pipe(planned, Array.map((done) => done.name)));
350
+ const NO_PARTS = [];
351
+ const nextPart = (naming) => (planned, part) => {
352
+ const name = uniqueAmong(namesOf(planned))(nameFrom(naming.candidates(part)));
353
+ return Array.append(planned, {
354
+ part,
355
+ name,
356
+ source: sourceOf(naming.instruments)(part),
357
+ lines: linesOf(groupsOf(part)),
358
+ controls: controlsOf$1(part)
359
+ });
360
+ };
361
+ const planOf = (timeline) => {
362
+ const instruments = instrumentsOf(timeline.parts);
363
+ const candidates = candidatesOf(sharedLabelsOf(timeline.parts));
364
+ return {
365
+ parts: Array.reduce(timeline.parts, NO_PARTS, nextPart({
366
+ instruments,
367
+ candidates
368
+ })),
369
+ instruments,
370
+ drumVoices: drumVoicesOf(timeline.parts)
371
+ };
372
+ };
373
+ // src/entities/timeline/model/tempo-units.ts
374
+ const MICROSECONDS_PER_MINUTE = 6e7;
375
+ const bpmOf = (microseconds) => MICROSECONDS_PER_MINUTE / microseconds;
376
+ const microsecondsOf = (bpm) => Math.round(MICROSECONDS_PER_MINUTE / bpm);
377
+ // src/entities/timeline/model/compare.ts
378
+ const NONE$4 = 0;
379
+ const NEXT$4 = 1;
380
+ const UNKNOWN = -1;
381
+ const FULL$2 = 127;
382
+ const DEFAULT_RELEASE$2 = 64;
383
+ const DECIMALS = 9;
384
+ const SHOWN = 20;
385
+ const countsOf = (keys) => pipe(keys, Array.groupBy((key) => key), Record.map((same) => same.length));
386
+ const surplusOf = (over) => (under) => pipe(Record.toEntries(over), Array.flatMap(([key, count]) => {
387
+ const left = count - Option.getOrElse(Record.get(under, key), () => NONE$4);
388
+ if (left > NONE$4) return Array.makeBy(left, () => key);
389
+ return [];
390
+ }), Array.take(SHOWN));
391
+ const tallyOf = (expected, actual) => {
392
+ const wanted = countsOf(expected);
393
+ const found = countsOf(actual);
394
+ return {
395
+ expected: expected.length,
396
+ actual: actual.length,
397
+ missing: surplusOf(wanted)(found),
398
+ extra: surplusOf(found)(wanted)
399
+ };
400
+ };
401
+ const byteOf = (share) => Math.round(share * FULL$2);
402
+ const releaseOf$1 = (release) => Option.match(release, {
403
+ onNone: () => DEFAULT_RELEASE$2,
404
+ onSome: byteOf
405
+ });
406
+ const keyOf = (parts) => pipe(parts, Array.map(String), Array.join(" "));
407
+ const expectedNotesOf = (plan) => pipe(plan.parts, Array.flatMap((planned) => pipe(planned.part.notes, Array.map((note) => keyOf([
408
+ planned.name,
409
+ note.tick,
410
+ note.end - note.tick,
411
+ note.midi,
412
+ note.velocity,
413
+ note.release
414
+ ])))));
415
+ const actualNotesOf = ({ plan, song }) => {
416
+ const voices = new Map(pipe(Array.fromIterable(plan.drumVoices), Array.map(([midi, name]) => [name, midi])));
417
+ const notes = pipe(song.notes, Array.map((note) => keyOf([
418
+ note.track,
419
+ note.start,
420
+ note.length,
421
+ note.midi,
422
+ byteOf(note.velocity),
423
+ releaseOf$1(note.releaseVelocity)
424
+ ])));
425
+ const hits = pipe(song.hits, Array.map((hit) => keyOf([
426
+ hit.track,
427
+ hit.start,
428
+ hit.length,
429
+ voices.get(hit.voice) ?? UNKNOWN,
430
+ byteOf(hit.velocity),
431
+ releaseOf$1(hit.releaseVelocity)
432
+ ])));
433
+ return [...notes, ...hits];
434
+ };
435
+ const rounded = (value) => String(Number(value.toFixed(DECIMALS)));
436
+ const expectedControlsOf = (plan) => pipe(plan.parts, Array.flatMap((planned) => pipe(planned.controls, Array.map((control) => keyOf([
437
+ planned.name,
438
+ controllerKeyOf(control),
439
+ control.tick,
440
+ rounded(control.value)
441
+ ])))));
442
+ const actualControlsOf = (song) => pipe(song.controls, Array.map((control) => keyOf([
443
+ control.track,
444
+ controllerKeyOf({ controller: control.controller }),
445
+ control.start,
446
+ rounded(control.value)
447
+ ])));
448
+ const FLAT = "-";
449
+ const isFlatRepeat = (point, previous) => Option.isNone(point.target) && Option.isNone(previous.target) && previous.microseconds === point.microseconds;
450
+ const changesOf = (points) => pipe(points, Array.filter((point, index) => pipe(Array.get(points, index - NEXT$4), Option.match({
451
+ onNone: () => true,
452
+ onSome: (previous) => !isFlatRepeat(point, previous)
453
+ }))), Array.map(({ tick, microseconds, target }) => keyOf([
454
+ tick,
455
+ microseconds,
456
+ Option.getOrElse(target, () => FLAT)
457
+ ])));
458
+ const expectedTempoOf = (bars) => changesOf(pipe(bars, Array.flatMap((bar) => pipe(bar.tempo, Array.map((step) => ({
459
+ tick: bar.start + step.offset,
460
+ microseconds: step.microseconds,
461
+ target: step.target
462
+ }))))));
463
+ const barPointsOf = (bar) => {
464
+ if (Array.isReadonlyArrayNonEmpty(bar.tempoSteps)) return pipe(bar.tempoSteps, Array.map((step) => ({
465
+ tick: bar.start + step.offset,
466
+ microseconds: microsecondsOf(step.bpm),
467
+ target: pipe(step.target, Option.map(microsecondsOf))
468
+ })));
469
+ return [{
470
+ tick: bar.start,
471
+ microseconds: microsecondsOf(bar.tempo.bpm),
472
+ target: Option.none()
473
+ }];
474
+ };
475
+ const actualTempoOf = (song) => changesOf(pipe(song.bars, Array.flatMap(barPointsOf)));
476
+ const expectedLyricsOf = (plan) => pipe(plan.parts, Array.flatMap((planned) => pipe(planned.lines, Array.flatten, Array.flatMap((group) => pipe(group.lyric, Option.map((text) => keyOf([
477
+ planned.name,
478
+ group.start,
479
+ text
480
+ ])), Option.toArray)))));
481
+ const syllableKeyOf = (note) => pipe(note.lyric, Option.flatMap((lyric) => {
482
+ if (lyric.kind === "syllable") return Option.some(keyOf([
483
+ note.track,
484
+ note.start,
485
+ lyric.text
486
+ ]));
487
+ return Option.none();
488
+ }));
489
+ const actualLyricsOf = (song) => pipe(song.notes, Array.map(syllableKeyOf), Array.getSomes, Array.dedupe);
490
+ const expectedMarksOf = (bars) => pipe(bars, Array.filter((bar) => Array.isReadonlyArrayNonEmpty(bar.marks)), Array.map((bar) => keyOf([bar.start, Array.join(bar.marks, " / ")])));
491
+ const actualMarksOf = (song) => pipe(song.bars, Array.map((bar) => pipe(bar.mark, Option.map((mark) => keyOf([bar.start, mark])))), Array.getSomes);
492
+ const isClean = (tally) => !Array.isReadonlyArrayNonEmpty(tally.missing) && !Array.isReadonlyArrayNonEmpty(tally.extra);
493
+ const compareWithSong = ({ plan, bars, song }) => {
494
+ const tallies = {
495
+ notes: tallyOf(expectedNotesOf(plan), actualNotesOf({
496
+ plan,
497
+ song
498
+ })),
499
+ controls: tallyOf(expectedControlsOf(plan), actualControlsOf(song)),
500
+ tempo: tallyOf(expectedTempoOf(bars), actualTempoOf(song)),
501
+ lyrics: tallyOf(expectedLyricsOf(plan), actualLyricsOf(song)),
502
+ marks: tallyOf(expectedMarksOf(bars), actualMarksOf(song))
503
+ };
504
+ return {
505
+ ...tallies,
506
+ matches: pipe(Record.values(tallies), Array.every(isClean))
507
+ };
508
+ };
509
+ // src/entities/timeline/model/events.ts
510
+ const byTick = Order.mapInput(Order.Number, (timed) => timed.tick);
511
+ const sortedByTick = (items) => Array.sort(items, byTick);
512
+ const byTickThenPitch = Order.combine(Order.mapInput(Order.Number, (note) => note.tick), Order.mapInput(Order.Number, (note) => note.midi));
513
+ const sortedNotes = (notes) => Array.sort(notes, byTickThenPitch);
514
+ // src/entities/timeline/model/cells.ts
515
+ const NONE$3 = 0;
516
+ const FULL$1 = 127;
517
+ const SHARE_DECIMALS = 3;
518
+ const SEMITONE_DECIMALS = 12;
519
+ const LAST = 1;
520
+ const durationText = (length) => {
521
+ if (length === NONE$3) return "0/1";
522
+ return fractionOf(length);
523
+ };
524
+ const restCell = (length) => ({
525
+ head: "rest",
526
+ attributes: [],
527
+ length
528
+ });
529
+ const restsOf = (length) => {
530
+ if (length > NONE$3) return [restCell(length)];
531
+ return [];
532
+ };
533
+ const isRest = (cell) => cell.head === "rest";
534
+ const mergeRests = (merged, cell) => pipe(Array.last(merged), Option.filter((previous) => isRest(previous) && isRest(cell)), Option.match({
535
+ onNone: () => [...merged, cell],
536
+ onSome: (previous) => [...Array.dropRight(merged, LAST), restCell(previous.length + cell.length)]
537
+ }));
538
+ const NO_CELLS = [];
539
+ const cellText = (cell) => Array.join([
540
+ cell.head,
541
+ durationText(cell.length),
542
+ ...cell.attributes
543
+ ], " ");
544
+ const cellsText = (cells) => pipe(Array.reduce(cells, NO_CELLS, mergeRests), Array.map(cellText), Array.join(", "));
545
+ const quoted = (text) => `"${pipe(text, String$1.replaceAll("\\", String.raw`\\`), String$1.replaceAll("\"", String.raw`\"`), String$1.replaceAll("\n", String.raw`\n`), String$1.replaceAll("\r", String.raw`\r`), String$1.replaceAll(" ", String.raw`\t`))}"`;
546
+ const shareText = (value) => String(Number((value / FULL$1).toFixed(SHARE_DECIMALS)));
547
+ const semitoneText = (value) => {
548
+ const text = String(Number(value.toFixed(SEMITONE_DECIMALS)));
549
+ if (value > NONE$3) return `+${text}st`;
550
+ return `${text}st`;
551
+ };
552
+ const pitchText = (midi) => Midi.midiToNoteName(midi, { sharps: true });
553
+ // src/entities/timeline/model/layout.ts
554
+ const NONE$2 = 0;
555
+ const NEXT$3 = 1;
556
+ const QUARTER = 4;
557
+ const DEFAULT_METER = {
558
+ numerator: QUARTER,
559
+ denominator: QUARTER
560
+ };
561
+ const DEFAULT_MICROSECONDS = 5e5;
562
+ const MAX_DECIMALS = 9;
563
+ const endOfSpan = (span) => span.start + span.length;
564
+ const latestAt = (tick) => (items) => pipe(items, Array.filter((item) => item.tick <= tick), Array.last);
565
+ const lengthOf = (signature) => TICKS_PER_WHOLE * signature.numerator / signature.denominator;
566
+ const meterText = (signature) => (length) => {
567
+ const beats = length * signature.denominator / TICKS_PER_WHOLE;
568
+ if (Number.isInteger(beats)) return `${String(beats)}/${String(signature.denominator)}`;
569
+ return fractionOf(length);
570
+ };
571
+ const rampAt = (tempos) => (tick) => pipe(latestAt(tick)(tempos), Option.flatMap((start) => pipe(start.target, Option.flatMap((target) => pipe(Array.findFirst(tempos, (tempo) => tempo.tick > start.tick), Option.map((next) => ({
572
+ start,
573
+ end: next.tick,
574
+ target
575
+ })))))));
576
+ const interpolated = (ramp) => (tick) => {
577
+ const from = bpmOf(ramp.start.microseconds);
578
+ const to = bpmOf(ramp.target);
579
+ const share = (tick - ramp.start.tick) / (ramp.end - ramp.start.tick);
580
+ return microsecondsOf(from + (to - from) * share);
581
+ };
582
+ const rampedAt = (tempos) => (tick, at) => pipe(rampAt(tempos)(tick), Option.map((ramp) => interpolated(ramp)(at)));
583
+ const steadyAt = (tempos) => (tick) => pipe(latestAt(tick)(tempos), Option.match({
584
+ onNone: () => DEFAULT_MICROSECONDS,
585
+ onSome: (tempo) => tempo.microseconds
586
+ }));
587
+ const tempoAt = (tempos) => (tick) => Option.getOrElse(rampedAt(tempos)(tick, tick), () => steadyAt(tempos)(tick));
588
+ const tempoStepsOf = (tempos) => (bar) => {
589
+ const end = endOfSpan(bar);
590
+ const points = [bar.start, ...pipe(tempos, Array.filter((tempo) => tempo.tick > bar.start && tempo.tick < end), Array.map((tempo) => tempo.tick), Array.dedupe)];
591
+ return pipe(points, Array.map((tick, index) => {
592
+ const stepEnd = Option.getOrElse(Array.get(points, index + NEXT$3), () => end);
593
+ return {
594
+ offset: tick - bar.start,
595
+ length: stepEnd - tick,
596
+ microseconds: tempoAt(tempos)(tick),
597
+ target: rampedAt(tempos)(tick, stepEnd)
598
+ };
599
+ }));
600
+ };
601
+ const marksOf = (markers) => (bar) => pipe(markers, Array.filter((marker) => marker.tick >= bar.start && marker.tick < endOfSpan(bar)), Array.map((marker) => marker.text));
602
+ const spanAt = (meters) => (start) => {
603
+ const signature = Option.getOrElse(latestAt(start)(meters), () => DEFAULT_METER);
604
+ const full = start + lengthOf(signature);
605
+ return {
606
+ start,
607
+ length: pipe(Array.findFirst(meters, (meter) => meter.tick > start), Option.match({
608
+ onNone: () => full,
609
+ onSome: (meter) => Math.min(meter.tick, full)
610
+ })) - start,
611
+ signature
612
+ };
613
+ };
614
+ const barsOf = (timeline) => Array.unfold({
615
+ start: NONE$2,
616
+ first: true
617
+ }, (cursor) => {
618
+ if (!cursor.first && cursor.start >= timeline.end) return Option.none();
619
+ const span = spanAt(timeline.meters)(cursor.start);
620
+ const bar = {
621
+ start: span.start,
622
+ length: span.length,
623
+ meter: meterText(span.signature)(span.length),
624
+ tempo: tempoStepsOf(timeline.tempos)(span),
625
+ marks: marksOf(timeline.markers)(span)
626
+ };
627
+ return Option.some([bar, {
628
+ start: endOfSpan(span),
629
+ first: false
630
+ }]);
631
+ });
632
+ const bpmText = (microseconds) => {
633
+ const exact = bpmOf(microseconds);
634
+ return `${pipe(Array.range(NONE$2, MAX_DECIMALS), Array.map((decimals) => String(Number(exact.toFixed(decimals)))), Array.findFirst((candidate) => microsecondsOf(Number(candidate)) === microseconds), Option.getOrElse(() => String(exact)))}bpm`;
635
+ };
636
+ // src/entities/timeline/model/control-lines.ts
637
+ const NEXT$2 = 1;
638
+ const valueText = (control) => {
639
+ if (control.controller.kind === "bend") return semitoneText(control.value);
640
+ return String(control.value);
641
+ };
642
+ const headOf$1 = (planned) => ({ controller }) => {
643
+ if (controller.kind === "pressure") return Option.match(controller.midi, {
644
+ onNone: () => `${planned.name}.pressure`,
645
+ onSome: (midi) => `${planned.name}.pressure ${pitchText(midi)}`
646
+ });
647
+ return `${planned.name}.${controllerKeyOf({ controller })}`;
648
+ };
649
+ const cellsOf$1 = (bar) => (controls) => {
650
+ const lead = pipe(Array.head(controls), Option.map((first) => first.tick - bar.start), Option.toArray, Array.flatMap(restsOf));
651
+ const steps = pipe(controls, Array.map((control, index) => ({
652
+ head: valueText(control),
653
+ attributes: [],
654
+ length: pipe(Array.get(controls, index + NEXT$2), Option.match({
655
+ onNone: () => endOfSpan(bar),
656
+ onSome: (next) => next.tick
657
+ })) - control.tick
658
+ })));
659
+ return [...lead, ...steps];
660
+ };
661
+ const controlLinesOf = (bar) => (planned) => pipe(planned.controls, Array.filter((control) => control.tick >= bar.start && control.tick < endOfSpan(bar)), Array.groupBy((control) => controllerKeyOf(control)), Record.values, Array.map((controls) => pipe(Array.head(controls), Option.map((first) => `${headOf$1(planned)(first)}: ${cellsText(cellsOf$1(bar)(controls))}`))), Array.getSomes);
662
+ // src/entities/timeline/model/voice-lines.ts
663
+ const FULL = 127;
664
+ const DEFAULT_RELEASE$1 = 64;
665
+ const SINGLE$1 = 1;
666
+ const touches = (bar) => (group) => {
667
+ if (group.end === group.start) return group.start >= bar.start && group.start < endOfSpan(bar);
668
+ return group.start < endOfSpan(bar) && group.end > bar.start;
669
+ };
670
+ const segmentOf = (bar) => (group) => ({
671
+ group,
672
+ start: Math.max(group.start, bar.start),
673
+ end: Math.min(group.end, endOfSpan(bar))
674
+ });
675
+ const pitchesText = (midis) => {
676
+ if (midis.length === SINGLE$1) return Array.join(pipe(midis, Array.map(pitchText)), "");
677
+ return `[${Array.join(pipe(midis, Array.map(pitchText)), " ")}]`;
678
+ };
679
+ const headOf = (voices) => (group) => Option.match(voices, {
680
+ onNone: () => pitchesText(group.midis),
681
+ onSome: (map) => pipe(Array.head(group.midis), Option.flatMap((midi) => Option.fromNullishOr(map.get(midi))), Option.getOrElse(() => ""))
682
+ });
683
+ const when = (condition, text) => {
684
+ if (condition) return [text];
685
+ return [];
686
+ };
687
+ const attributesOf = ({ group, start, end }) => {
688
+ const last = end === group.end;
689
+ return [
690
+ ...when(group.velocity !== FULL, `vel ${shareText(group.velocity)}`),
691
+ ...when(last && group.release !== DEFAULT_RELEASE$1, `off ${shareText(group.release)}`),
692
+ ...when(!last, "tie"),
693
+ ...pipe(group.lyric, Option.filter(() => start === group.start), Option.map((text) => `lyric ${quoted(text)}`), Option.toArray)
694
+ ];
695
+ };
696
+ const cellsOf = (segments, bar, head) => {
697
+ const placed = Array.reduce(segments, {
698
+ cells: [],
699
+ cursor: bar.start
700
+ }, ({ cells, cursor }, segment) => ({
701
+ cells: [
702
+ ...cells,
703
+ ...restsOf(segment.start - cursor),
704
+ {
705
+ head: head(segment.group),
706
+ attributes: attributesOf(segment),
707
+ length: segment.end - segment.start
708
+ }
709
+ ],
710
+ cursor: segment.end
711
+ }));
712
+ return [...placed.cells, ...restsOf(endOfSpan(bar) - placed.cursor)];
713
+ };
714
+ const lineTextOf = (planned, voices, bar) => (line) => {
715
+ const segments = pipe(line, Array.filter(touches(bar)), Array.map(segmentOf(bar)));
716
+ return pipe(Array.head(segments), Option.map((first) => ({
717
+ text: `${planned.name}: ${cellsText(cellsOf(segments, bar, headOf(voices)))}`,
718
+ continues: first.start > first.group.start
719
+ })));
720
+ };
721
+ const continuedFirst = Order.mapInput(Order.Boolean, (voice) => !voice.continues);
722
+ const voiceLinesOf = ({ plan, bar }) => (planned) => {
723
+ const voices = pipe(Option.some(plan.drumVoices), Option.filter(() => planned.source.kind === "kit"));
724
+ const texts = pipe(planned.lines, Array.map(lineTextOf(planned, voices, bar)), Array.getSomes);
725
+ return pipe(Array.sort(texts, continuedFirst), Array.map((voice) => voice.text));
726
+ };
727
+ // src/entities/timeline/model/write.ts
728
+ const SINGLE = 1;
729
+ const INDENT = " ";
730
+ const START = {
731
+ meter: Option.none(),
732
+ microseconds: Option.none()
733
+ };
734
+ const isRamp = (step) => Option.isSome(step.target);
735
+ const stepText = (step) => {
736
+ const ramp = Option.match(step.target, {
737
+ onNone: () => "",
738
+ onSome: (target) => ` -> ${bpmText(target)}`
739
+ });
740
+ return `${bpmText(step.microseconds)}${ramp} ${fractionOf(step.length)}`;
741
+ };
742
+ const tempoLineOf = (bar) => {
743
+ if (bar.tempo.length <= SINGLE && !pipe(bar.tempo, Array.some(isRamp))) return Option.none();
744
+ const steps = pipe(bar.tempo, Array.map(stepText));
745
+ return Option.some(`tempo: ${Array.join(steps, ", ")}`);
746
+ };
747
+ const differs = (previous) => (current) => Option.match(previous, {
748
+ onNone: () => true,
749
+ onSome: (value) => value !== current
750
+ });
751
+ const headerTempoOf = (previous) => (bar) => pipe(Array.head(bar.tempo), Option.filter(() => bar.tempo.length === SINGLE && !pipe(bar.tempo, Array.some(isRamp))), Option.map((step) => step.microseconds), Option.filter(differs(previous.microseconds)), Option.map((microseconds) => `tempo ${bpmText(microseconds)}`), Option.toArray);
752
+ const barHeadOf = (previous) => (bar) => {
753
+ const meter = pipe(Option.some(bar.meter), Option.filter(differs(previous.meter)), Option.map((current) => `meter ${current}`), Option.toArray);
754
+ const mark = pipe(Option.some(bar.marks), Option.filter(Array.isReadonlyArrayNonEmpty), Option.map((marks) => `mark ${quoted(Array.join(marks, " / "))}`), Option.toArray);
755
+ return Array.join([
756
+ "bar",
757
+ ...meter,
758
+ ...headerTempoOf(previous)(bar),
759
+ ...mark,
760
+ "{"
761
+ ], " ");
762
+ };
763
+ const barBodyOf = (plan) => (bar) => [...Option.toArray(tempoLineOf(bar)), ...pipe(plan.parts, Array.flatMap((planned) => [...voiceLinesOf({
764
+ plan,
765
+ bar
766
+ })(planned), ...controlLinesOf(bar)(planned)]))];
767
+ const afterBar = (bar) => ({
768
+ meter: Option.some(bar.meter),
769
+ microseconds: pipe(Array.last(bar.tempo), Option.map((step) => Option.getOrElse(step.target, () => step.microseconds)))
770
+ });
771
+ const walkStep = (plan) => ({ lines, previous }, bar) => ({
772
+ lines: [
773
+ ...lines,
774
+ "",
775
+ barHeadOf(previous)(bar),
776
+ ...pipe(barBodyOf(plan)(bar), Array.map((line) => `${INDENT}${line}`)),
777
+ "}"
778
+ ],
779
+ previous: afterBar(bar)
780
+ });
781
+ const instrumentLinesOf = (plan) => pipe(Array.fromIterable(plan.instruments), Array.map(([program, name]) => `instrument ${name} plugin gm program ${String(program)}`));
782
+ const kitLinesOf = (plan) => {
783
+ if (plan.drumVoices.size < SINGLE) return [];
784
+ return [
785
+ "kit gm-drums {",
786
+ ...pipe(Array.fromIterable(plan.drumVoices.values()), Array.map((name) => `${INDENT}${name} ${quoted(`gm-drums/${name}.flac`)}`)),
787
+ "}"
788
+ ];
789
+ };
790
+ const trackLineOf = (planned) => {
791
+ if (planned.source.kind === "kit") return `track ${planned.name} kit gm-drums role drums`;
792
+ return `track ${planned.name} instrument ${planned.source.instrument}`;
793
+ };
794
+ const headerOf = ({ plan, title }) => [
795
+ `song ${quoted(title)}`,
796
+ "",
797
+ "plugin gm from \"./gm.ts\" { program: number = 0 }",
798
+ "",
799
+ ...instrumentLinesOf(plan),
800
+ ...kitLinesOf(plan),
801
+ "",
802
+ ...pipe(plan.parts, Array.map(trackLineOf))
803
+ ];
804
+ const writeFumx = ({ timeline, title }) => {
805
+ const plan = planOf(timeline);
806
+ const bars = barsOf(timeline);
807
+ const walked = Array.reduce(bars, {
808
+ lines: headerOf({
809
+ plan,
810
+ title
811
+ }),
812
+ previous: START
813
+ }, walkStep(plan));
814
+ return {
815
+ text: `${Array.join(walked.lines, "\n")}\n`,
816
+ plan,
817
+ bars
818
+ };
819
+ };
820
+ // src/features/convert-midi/model/channel.ts
821
+ const NONE$1 = 0;
822
+ const NEXT$1 = 1;
823
+ const DEFAULT_RELEASE = 64;
824
+ const DEFAULT_BEND_RANGE = 2;
825
+ const CENTS_PER_SEMITONE = 100;
826
+ const BEND_HALF = 8192;
827
+ const RPN_MSB = 101;
828
+ const RPN_LSB = 100;
829
+ const DATA_MSB = 6;
830
+ const DATA_LSB = 38;
831
+ const PITCH_BEND_RPN = 0;
832
+ const UNSET = 127;
833
+ const edgeOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "noteOn" }, (on) => Option.some([on.noteNumber, {
834
+ tick,
835
+ on: on.velocity > NONE$1,
836
+ velocity: on.velocity
837
+ }])), Match.when({ type: "noteOff" }, (off) => Option.some([off.noteNumber, {
838
+ tick,
839
+ on: false,
840
+ velocity: off.velocity
841
+ }])), Match.orElse(() => Option.none()));
842
+ const releaseOf = (edge) => {
843
+ if (edge.velocity === NONE$1) return DEFAULT_RELEASE;
844
+ return edge.velocity;
845
+ };
846
+ const START_PAIRING = {
847
+ open: [],
848
+ notes: []
849
+ };
850
+ const pairStep = (midi) => (pairing, edge) => {
851
+ if (edge.on) return {
852
+ ...pairing,
853
+ open: [...pairing.open, edge]
854
+ };
855
+ return Option.match(Array.head(pairing.open), {
856
+ onNone: () => pairing,
857
+ onSome: (started) => ({
858
+ open: Array.drop(pairing.open, NEXT$1),
859
+ notes: [...pairing.notes, {
860
+ tick: started.tick,
861
+ end: edge.tick,
862
+ midi,
863
+ velocity: started.velocity,
864
+ release: releaseOf(edge)
865
+ }]
866
+ })
867
+ });
868
+ };
869
+ const pairedOf = (end) => (edges) => {
870
+ const midi = pipe(Array.head(edges), Option.match({
871
+ onNone: () => NONE$1,
872
+ onSome: ([pitch]) => pitch
873
+ }));
874
+ const steps = pipe(edges, Array.map(([, edge]) => edge));
875
+ const paired = Array.reduce(steps, START_PAIRING, pairStep(midi));
876
+ const unended = pipe(paired.open, Array.map((started) => ({
877
+ tick: started.tick,
878
+ end,
879
+ midi,
880
+ velocity: started.velocity,
881
+ release: DEFAULT_RELEASE
882
+ })));
883
+ return [...paired.notes, ...unended];
884
+ };
885
+ const notesOf = (end) => (events) => {
886
+ const notes = pipe(events, Array.map(edgeOf), Array.getSomes, Array.groupBy(([midi]) => String(midi)), Record.values, Array.flatMap(pairedOf(end)));
887
+ return sortedNotes(notes);
888
+ };
889
+ const START_RPN = {
890
+ msb: UNSET,
891
+ lsb: UNSET,
892
+ semitones: DEFAULT_BEND_RANGE,
893
+ cents: NONE$1
894
+ };
895
+ const isBendRange = (rpn) => rpn.msb === PITCH_BEND_RPN && rpn.lsb === PITCH_BEND_RPN;
896
+ const rpnAfter = (rpn) => ({ controllerType, value }) => {
897
+ if (controllerType === RPN_MSB) return {
898
+ ...rpn,
899
+ msb: value
900
+ };
901
+ if (controllerType === RPN_LSB) return {
902
+ ...rpn,
903
+ lsb: value
904
+ };
905
+ if (isBendRange(rpn) && controllerType === DATA_MSB) return {
906
+ ...rpn,
907
+ semitones: value
908
+ };
909
+ if (isBendRange(rpn) && controllerType === DATA_LSB) return {
910
+ ...rpn,
911
+ cents: value
912
+ };
913
+ return rpn;
914
+ };
915
+ const rpnStep = ([rpn, { event }]) => {
916
+ if (event.type !== "controller") return rpn;
917
+ return rpnAfter(rpn)(event);
918
+ };
919
+ const controlOf = ([{ tick, event }, rpn]) => Match.value(event).pipe(Match.when({ type: "controller" }, (cc) => Option.some({
920
+ tick,
921
+ controller: {
922
+ kind: "cc",
923
+ number: cc.controllerType
924
+ },
925
+ value: cc.value
926
+ })), Match.when({ type: "programChange" }, (change) => Option.some({
927
+ tick,
928
+ controller: { kind: "program" },
929
+ value: change.programNumber
930
+ })), Match.when({ type: "channelAftertouch" }, (pressure) => Option.some({
931
+ tick,
932
+ controller: {
933
+ kind: "pressure",
934
+ midi: Option.none()
935
+ },
936
+ value: pressure.amount
937
+ })), Match.when({ type: "noteAftertouch" }, (pressure) => Option.some({
938
+ tick,
939
+ controller: {
940
+ kind: "pressure",
941
+ midi: Option.some(pressure.noteNumber)
942
+ },
943
+ value: pressure.amount
944
+ })), Match.when({ type: "pitchBend" }, (bend) => Option.some({
945
+ tick,
946
+ controller: { kind: "bend" },
947
+ value: bend.value * (rpn.semitones + rpn.cents / CENTS_PER_SEMITONE) / BEND_HALF
948
+ })), Match.orElse(() => Option.none()));
949
+ const controlsOf = (events) => pipe(Array.zip(events, Array.scan(events, START_RPN, (rpn, placed) => rpnStep([rpn, placed]))), Array.map(controlOf), Array.getSomes);
950
+ const isProgram = (control) => control.controller.kind === "program";
951
+ const initialProgramOf = (read) => pipe(Array.findFirst(read.controls, isProgram), Option.filter((program) => pipe(Array.head(read.notes), Option.match({
952
+ onNone: () => true,
953
+ onSome: (note) => program.tick <= note.tick
954
+ }))));
955
+ const channelReadOf = (end) => ([channel, events]) => {
956
+ const read = {
957
+ channel: Number(channel),
958
+ notes: notesOf(end)(events),
959
+ controls: controlsOf(events)
960
+ };
961
+ const program = initialProgramOf(read);
962
+ return {
963
+ ...read,
964
+ program: pipe(program, Option.map((control) => control.value)),
965
+ controls: Option.match(program, {
966
+ onNone: () => read.controls,
967
+ onSome: (first) => pipe(read.controls, Array.filter((control) => control !== first))
968
+ })
969
+ };
970
+ };
971
+ // src/features/convert-midi/model/timeline.ts
972
+ const QUARTERS_PER_WHOLE = 4;
973
+ const NONE = 0;
974
+ const NEXT = 1;
975
+ const placedOf = (ppq) => (events) => {
976
+ const raw = Array.scan(events, NONE, (tick, event) => tick + event.deltaTime);
977
+ return pipe(events, Array.map((event, index) => {
978
+ const exact = Option.getOrElse(Array.get(raw, index + NEXT), () => NONE) * TICKS_PER_WHOLE / (ppq * QUARTERS_PER_WHOLE);
979
+ return {
980
+ tick: Math.round(exact),
981
+ exact: Number.isInteger(exact),
982
+ event
983
+ };
984
+ }));
985
+ };
986
+ const channelEventOf = ({ tick, event }) => {
987
+ if ("channel" in event) return Option.some({
988
+ tick,
989
+ event
990
+ });
991
+ return Option.none();
992
+ };
993
+ const textOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "trackName" }, (text) => Option.some(["name", {
994
+ tick,
995
+ text: text.text
996
+ }])), Match.when({ type: "lyrics" }, (text) => Option.some(["lyric", {
997
+ tick,
998
+ text: text.text
999
+ }])), Match.when({ type: "marker" }, (text) => Option.some(["marker", {
1000
+ tick,
1001
+ text: text.text
1002
+ }])), Match.orElse(() => Option.none()));
1003
+ const tempoOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "setTempo" }, (tempo) => Option.some({
1004
+ tick,
1005
+ microseconds: tempo.microsecondsPerBeat,
1006
+ target: Option.none()
1007
+ })), Match.orElse(() => Option.none()));
1008
+ const meterOf = ({ tick, event }) => Match.value(event).pipe(Match.when({ type: "timeSignature" }, (meter) => Option.some({
1009
+ tick,
1010
+ numerator: meter.numerator,
1011
+ denominator: meter.denominator
1012
+ })), Match.orElse(() => Option.none()));
1013
+ const textsOf = (placed) => pipe(placed, Array.map(textOf), Array.getSomes, Array.groupBy(([kind]) => kind), Record.map((entries) => pipe(entries, Array.map(([, text]) => text))));
1014
+ const textsIn = (kind) => (read) => Option.getOrElse(Record.get(read.texts, kind), () => []);
1015
+ const byChannel = Order.mapInput(Order.Number, (read) => read.channel);
1016
+ const channelsOf = (end) => (placed) => {
1017
+ const reads = pipe(placed, Array.map(channelEventOf), Array.getSomes, Array.groupBy((item) => String(item.event.channel)), Record.toEntries, Array.map(channelReadOf(end)));
1018
+ return Array.sort(reads, byChannel);
1019
+ };
1020
+ const readTrack = (ppq) => (events) => {
1021
+ const placed = placedOf(ppq)(events);
1022
+ const end = pipe(Array.last(placed), Option.match({
1023
+ onNone: () => NONE,
1024
+ onSome: (last) => last.tick
1025
+ }));
1026
+ const texts = textsOf(placed);
1027
+ return {
1028
+ name: pipe(Array.head(textsIn("name")({ texts })), Option.map((text) => text.text)),
1029
+ end,
1030
+ offGrid: Array.countBy(placed, (item) => !item.exact),
1031
+ channels: channelsOf(end)(placed),
1032
+ texts,
1033
+ tempos: pipe(placed, Array.map(tempoOf), Array.getSomes),
1034
+ meters: pipe(placed, Array.map(meterOf), Array.getSomes)
1035
+ };
1036
+ };
1037
+ const isUsed = (read) => Array.isReadonlyArrayNonEmpty(read.notes) || Array.isReadonlyArrayNonEmpty(read.controls) || Option.isSome(read.program);
1038
+ const partsOf = (read, track) => {
1039
+ const lyrics = textsIn("lyric")(read);
1040
+ return pipe(read.channels, Array.filter(isUsed), Array.map((channel) => ({
1041
+ ...channel,
1042
+ track,
1043
+ name: read.name,
1044
+ lyrics: pipe(lyrics, Array.filter((lyric) => pipe(channel.notes, Array.some((note) => note.tick === lyric.tick))))
1045
+ })));
1046
+ };
1047
+ const titleOf = (reads) => pipe(Array.head(reads), Option.filter((read) => !Array.isReadonlyArrayNonEmpty(read.channels)), Option.flatMap((read) => read.name));
1048
+ const endsOf = (read) => [read.end, ...pipe(read.channels, Array.flatMap((channel) => channel.notes), Array.map((note) => note.end))];
1049
+ const sortedFrom = (pick) => (reads) => sortedByTick(pipe(reads, Array.flatMap(pick)));
1050
+ const timelineOf = (midi) => {
1051
+ const reads = pipe(midi.tracks, Array.map(readTrack(midi.header.ticksPerBeat ?? NONE)));
1052
+ return {
1053
+ title: titleOf(reads),
1054
+ end: Array.reduce(pipe(reads, Array.flatMap(endsOf)), NONE, (latest, tick) => Math.max(latest, tick)),
1055
+ offGrid: Array.reduce(reads, NONE, (total, read) => total + read.offGrid),
1056
+ tempos: sortedFrom((read) => read.tempos)(reads),
1057
+ meters: sortedFrom((read) => read.meters)(reads),
1058
+ markers: sortedFrom(textsIn("marker"))(reads),
1059
+ parts: pipe(reads, Array.flatMap((read, index) => partsOf(read, index)))
1060
+ };
1061
+ };
1062
+ // src/features/convert-midi/model/convert.ts
1063
+ const taggedError$1 = Schema.TaggedError;
1064
+ var UnreadableMidi = class extends taggedError$1()("UnreadableMidi", { message: Schema.String }, { identifier: "UnreadableMidi" }) {};
1065
+ const midiToFumx = Effect.fn("midiToFumx")(function* convert(input) {
1066
+ const midi = yield* Effect.try({
1067
+ try: () => parseMidi(input.bytes),
1068
+ catch: (cause) => UnreadableMidi.make({ message: String(cause) })
1069
+ });
1070
+ if (Predicate.isUndefined(midi.header.ticksPerBeat)) return yield* UnreadableMidi.make({ message: "SMPTE time division is not supported" });
1071
+ const timeline = yield* Effect.sync(() => timelineOf(midi)).pipe(Effect.withSpan("timelineOf"));
1072
+ const written = yield* Effect.sync(() => writeFumx({
1073
+ timeline,
1074
+ title: Option.getOrElse(timeline.title, () => input.title)
1075
+ })).pipe(Effect.withSpan("writeFumx"));
1076
+ yield* Effect.annotateCurrentSpan({
1077
+ parts: written.plan.parts.length,
1078
+ bars: written.bars.length
1079
+ });
1080
+ return {
1081
+ ...written,
1082
+ offGrid: timeline.offGrid
1083
+ };
1084
+ });
1085
+ // src/app/round-trip.ts
1086
+ const taggedError = Schema.TaggedError;
1087
+ var InvalidOutput = class extends taggedError()("InvalidOutput", {
1088
+ message: Schema.String,
1089
+ text: Schema.String
1090
+ }, { identifier: "InvalidOutput" }) {};
1091
+ const issueText = (issue) => `${String(issue.line)}:${String(issue.column)} ${issue.message}`;
1092
+ const roundTrip = Effect.fn("roundTrip")(function* check(path, fumx) {
1093
+ const read = yield* readSong({
1094
+ path,
1095
+ read: () => Effect.succeed(fumx.text)
1096
+ }).pipe(Effect.withSpan("readSong"));
1097
+ if (read.status === "invalid") return yield* InvalidOutput.make({
1098
+ message: pipe(read.issues, Array.map(issueText), Array.join("\n")),
1099
+ text: fumx.text
1100
+ });
1101
+ const comparison = compareWithSong({
1102
+ plan: fumx.plan,
1103
+ bars: fumx.bars,
1104
+ song: read.song
1105
+ });
1106
+ yield* Effect.annotateCurrentSpan({
1107
+ matches: comparison.matches,
1108
+ notes: comparison.notes.expected
1109
+ });
1110
+ return {
1111
+ text: fumx.text,
1112
+ comparison,
1113
+ adjustments: { offGrid: fumx.offGrid }
1114
+ };
1115
+ });
1116
+ // bin/midi-to-fumx.ts
1117
+ convertMain({
1118
+ name: "midi-to-fumx",
1119
+ input: "A Standard MIDI File (.mid)",
1120
+ source: "MIDI file",
1121
+ convert: Effect.fn("convertMidiFile")(function* convert(source) {
1122
+ const fumx = yield* midiToFumx(source);
1123
+ return yield* roundTrip(source.path, fumx);
1124
+ })
1125
+ });
1126
+ export {};
1127
+
1128
+ //# sourceMappingURL=midi-to-fumx.mjs.map