@r_masseater/song-format 0.1.0 → 0.2.1

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.
Files changed (57) hide show
  1. package/README.md +33 -1
  2. package/dist/als-to-fumx.mjs +525 -0
  3. package/dist/als-to-fumx.mjs.map +1 -0
  4. package/dist/analysis.d.mts +95 -0
  5. package/dist/analysis.mjs +328 -0
  6. package/dist/analysis.mjs.map +1 -0
  7. package/dist/convert-als.d.mts +18 -0
  8. package/dist/convert-als.mjs +512 -0
  9. package/dist/convert-als.mjs.map +1 -0
  10. package/dist/convert-midi.d.mts +2 -75
  11. package/dist/convert-midi.mjs +5 -650
  12. package/dist/convert-midi.mjs.map +1 -1
  13. package/dist/fumx-language-server.mjs +1 -1
  14. package/dist/fumx-language-server.mjs.map +1 -1
  15. package/dist/fumx-module-CqxUe07y.mjs +12485 -0
  16. package/dist/fumx-module-CqxUe07y.mjs.map +1 -0
  17. package/dist/fumx-module-CtXvLKU1.mjs +2632 -0
  18. package/dist/fumx-module-CtXvLKU1.mjs.map +1 -0
  19. package/dist/grammar-86_uhiTo.mjs +9836 -0
  20. package/dist/grammar-86_uhiTo.mjs.map +1 -0
  21. package/dist/index-Cup9xTad.d.mts +105 -0
  22. package/dist/index-DPt8MZ6e.d.mts +796 -0
  23. package/dist/index-JXjnMHXw.d.mts +1350 -0
  24. package/dist/index.d.mts +9 -0
  25. package/dist/index.mjs +4 -0
  26. package/dist/language.d.mts +13 -0
  27. package/dist/language.mjs +3 -0
  28. package/dist/mapper.mjs +1 -1
  29. package/dist/midi-to-fumx.mjs +12 -854
  30. package/dist/midi-to-fumx.mjs.map +1 -1
  31. package/dist/read-song-BzqX5MuZ.mjs +122 -0
  32. package/dist/read-song-BzqX5MuZ.mjs.map +1 -0
  33. package/dist/read-song-CzMPm8u8.mjs +123 -0
  34. package/dist/read-song-CzMPm8u8.mjs.map +1 -0
  35. package/dist/round-trip-Cz8iQlpW.mjs +946 -0
  36. package/dist/round-trip-Cz8iQlpW.mjs.map +1 -0
  37. package/dist/run-main-Bf32CgzU.mjs +26 -0
  38. package/dist/run-main-Bf32CgzU.mjs.map +1 -0
  39. package/dist/song-3Zm9g84K.d.mts +1478 -0
  40. package/dist/song-CYFBSTbH.mjs +387 -0
  41. package/dist/song-CYFBSTbH.mjs.map +1 -0
  42. package/dist/song-report.mjs +327 -4
  43. package/dist/song-report.mjs.map +1 -1
  44. package/dist/ticks-CXehHP2w.mjs +27 -0
  45. package/dist/ticks-CXehHP2w.mjs.map +1 -0
  46. package/dist/{transform-C24h3upp.mjs → transform-BoSDqqPW.mjs} +4 -3
  47. package/dist/transform-BoSDqqPW.mjs.map +1 -0
  48. package/dist/vite.mjs +4 -3
  49. package/dist/vite.mjs.map +1 -1
  50. package/dist/write-CuDbIkpM.mjs +747 -0
  51. package/dist/write-CuDbIkpM.mjs.map +1 -0
  52. package/package.json +49 -12
  53. package/skills/read-fumx/SKILL.md +85 -0
  54. package/skills/use-fumx-tools/SKILL.md +1 -2
  55. package/dist/app-CdpGdiWq.mjs +0 -190
  56. package/dist/app-CdpGdiWq.mjs.map +0 -1
  57. package/dist/transform-C24h3upp.mjs.map +0 -1
package/README.md CHANGED
@@ -2,12 +2,44 @@
2
2
 
3
3
  Tooling for `.fumx` songs: import a song from TypeScript with Vite, edit it with a language server, convert a MIDI file to `.fumx` with a check against the original, and print a report of its keys, chords and repeated bars.
4
4
 
5
- It requires [Vite+](https://viteplus.dev/) and Node.js 26 or later. `effect` and `vite-plus` are peer dependencies. The grammar and the reader live in [`@r_masseater/fumx-parser`](https://www.npmjs.com/package/@r_masseater/fumx-parser).
5
+ It requires [Vite+](https://viteplus.dev/) and Node.js 26 or later. `effect` and `vite-plus` are peer dependencies. It also holds the grammar and the reader of `.fumx`.
6
6
 
7
7
  ```sh
8
8
  vp add @r_masseater/song-format effect vite-plus
9
9
  ```
10
10
 
11
+ ## Read a song
12
+
13
+ ```ts
14
+ import { readSong } from "@r_masseater/song-format";
15
+ import { Effect } from "effect";
16
+
17
+ const text = `song "lint me"
18
+
19
+ instrument lead sample "lead.flac" root C4
20
+
21
+ track lead instrument lead
22
+
23
+ bar meter 4/4 tempo 120bpm {
24
+ lead: C4 1/4, E4 1/4, B5 1/2 vel 0.9
25
+ lead.cc 64: 127 1/2, 0 1/2
26
+ }
27
+ `;
28
+
29
+ const source = await Effect.runPromise(
30
+ readSong({ path: "/song.fumx", read: () => Effect.succeed(text) }),
31
+ );
32
+ if (source.status === "valid") {
33
+ const tooHigh = source.song.notes.filter((note) => note.midi > 79);
34
+ }
35
+ ```
36
+
37
+ `readSong` follows `import` statements through `read`, so the files can come from disk, memory or a network. An invalid file gives `issues` with a path, line and column. The messages are in Japanese. `outline.comments` lists the `//` and `/* */` comments of the entry file with their line and column, so tools such as linters can read directives from them.
38
+
39
+ Times are integer ticks, `TICKS_PER_WHOLE` to a whole note; `fractionOf` prints them as `1/4`. `@r_masseater/song-format/analysis` estimates what the notes imply but the file does not write: the key of a range of bars (`keyIn`), the chord on each beat (`chordsOf`) and bars that repeat. `analyze` returns all of them for a song, and `soundingsOf` lists the notes of unmuted tracks with their track role, source line and column, and the spelling and pitch class as written. Chord names follow that spelling, so `E G C` is `CM/E`, not `Em#5`.
40
+
41
+ `@r_masseater/song-format/language` exports the Langium grammar and modules for editors and language servers.
42
+
11
43
  ## Import a song
12
44
 
13
45
  Add the Vite plugin. TypeScript then reads a compiled song as a value.
@@ -0,0 +1,525 @@
1
+ #!/usr/bin/env node
2
+ import { a as sortedNotes, i as sortedByTick, n as writeFumx, o as microsecondsOf, s as convertMain, t as roundTrip } from "./round-trip-Cz8iQlpW.mjs";
3
+ import { t as MIXER_PARAMETERS } from "./song-CYFBSTbH.mjs";
4
+ import { s as TICKS_PER_WHOLE } from "./fumx-module-CqxUe07y.mjs";
5
+ import { Array, Boolean, Effect, Option, Order, Record, Schema, pipe } from "effect";
6
+ import { XMLParser } from "fast-xml-parser";
7
+ import { decodeTimeSignatureId } from "ableton-als";
8
+ // src/features/convert-als/model/live-set.ts
9
+ const taggedError = Schema.TaggedError;
10
+ var UnreadableAls = class extends taggedError()("UnreadableAls", { message: Schema.String }, { identifier: "UnreadableAls" }) {};
11
+ const REPEATED = /* @__PURE__ */ new Set([
12
+ "MidiTrack",
13
+ "AudioTrack",
14
+ "GroupTrack",
15
+ "ReturnTrack",
16
+ "MidiClip",
17
+ "AudioClip",
18
+ "KeyTrack",
19
+ "MidiNoteEvent",
20
+ "Locator",
21
+ "AutomationEnvelope",
22
+ "FloatEvent",
23
+ "EnumEvent",
24
+ "BoolEvent",
25
+ "TrackSendHolder"
26
+ ]);
27
+ const ATTRIBUTES = "@";
28
+ const parser = new XMLParser({
29
+ ignoreAttributes: false,
30
+ attributeNamePrefix: "",
31
+ attributesGroupName: ATTRIBUTES,
32
+ parseTagValue: false,
33
+ parseAttributeValue: false,
34
+ jPath: false,
35
+ isArray: (name) => REPEATED.has(name)
36
+ });
37
+ const Num = Schema.Struct({ Value: Schema.FiniteFromString });
38
+ const Text = Schema.Struct({ Value: Schema.String });
39
+ const Flag = Schema.Struct({ Value: Schema.Literals(["true", "false"]) });
40
+ const EventSchema = Schema.Struct({
41
+ Time: Schema.FiniteFromString,
42
+ Value: Schema.String
43
+ });
44
+ const EventsSchema = Schema.Struct({
45
+ FloatEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),
46
+ EnumEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey),
47
+ BoolEvent: EventSchema.pipe(Schema.Array, Schema.optionalKey)
48
+ });
49
+ const EnvelopeSchema = Schema.Struct({
50
+ EnvelopeTarget: Schema.Struct({ PointeeId: Num }),
51
+ Automation: Schema.Struct({ Events: EventsSchema })
52
+ });
53
+ const EnvelopeListSchema = Schema.Struct({ AutomationEnvelope: EnvelopeSchema.pipe(Schema.Array, Schema.optionalKey) });
54
+ const EnvelopesSchema = Schema.Struct({ Envelopes: EnvelopeListSchema });
55
+ const TargetSchema = Schema.Struct({ Id: Schema.FiniteFromString });
56
+ const ParameterSchema = Schema.Struct({
57
+ Manual: Schema.optionalKey(Num),
58
+ AutomationTarget: Schema.optionalKey(TargetSchema),
59
+ ArrangerAutomation: Schema.optionalKey(Schema.Struct({ Events: EventsSchema }))
60
+ });
61
+ const NoteSchema = Schema.Struct({
62
+ Time: Schema.FiniteFromString,
63
+ Duration: Schema.FiniteFromString,
64
+ Velocity: Schema.FiniteFromString,
65
+ OffVelocity: Schema.optionalKey(Schema.FiniteFromString),
66
+ IsEnabled: Schema.optionalKey(Schema.Literals(["true", "false"])),
67
+ Probability: Schema.optionalKey(Schema.FiniteFromString),
68
+ VelocityDeviation: Schema.optionalKey(Schema.FiniteFromString)
69
+ });
70
+ const NoteListSchema = Schema.Struct({ MidiNoteEvent: NoteSchema.pipe(Schema.Array, Schema.optionalKey) });
71
+ const KeyTrackSchema = Schema.Struct({
72
+ Notes: NoteListSchema,
73
+ MidiKey: Num
74
+ });
75
+ const LoopSchema = Schema.Struct({
76
+ LoopStart: Num,
77
+ LoopEnd: Num,
78
+ StartRelative: Num,
79
+ LoopOn: Flag
80
+ });
81
+ const KeyTracksSchema = Schema.Struct({ KeyTrack: KeyTrackSchema.pipe(Schema.Array, Schema.optionalKey) });
82
+ const ClipSchema = Schema.Struct({
83
+ CurrentStart: Num,
84
+ CurrentEnd: Num,
85
+ Loop: LoopSchema,
86
+ Disabled: Schema.optionalKey(Flag),
87
+ Notes: Schema.Struct({ KeyTracks: KeyTracksSchema })
88
+ });
89
+ const NameSchema = Schema.Struct({
90
+ EffectiveName: Schema.optionalKey(Text),
91
+ UserName: Schema.optionalKey(Text)
92
+ });
93
+ const DrumsSchema = Schema.Struct({ DrumGroupDevice: Schema.optionalKey(Schema.Unknown) });
94
+ const DevicesSchema = Schema.Struct({ Devices: Schema.optionalKey(DrumsSchema) });
95
+ const ClipEventsSchema = Schema.Struct({ MidiClip: ClipSchema.pipe(Schema.Array, Schema.optionalKey) });
96
+ const ArrangementSchema = Schema.Struct({ ArrangerAutomation: Schema.Struct({ Events: ClipEventsSchema }) });
97
+ const SendHolderSchema = Schema.Struct({ Send: ParameterSchema });
98
+ const SendsSchema = Schema.Struct({ TrackSendHolder: SendHolderSchema.pipe(Schema.Array, Schema.optionalKey) });
99
+ const SpeakerSchema = Schema.Struct({ Manual: Schema.optionalKey(Flag) });
100
+ const TrackMixerSchema = Schema.Struct({
101
+ Volume: ParameterSchema,
102
+ Pan: ParameterSchema,
103
+ Speaker: Schema.optionalKey(SpeakerSchema),
104
+ Sends: Schema.optionalKey(SendsSchema)
105
+ });
106
+ const TrackChainSchema = Schema.Struct({
107
+ DeviceChain: Schema.optionalKey(DevicesSchema),
108
+ Mixer: Schema.optionalKey(TrackMixerSchema),
109
+ MainSequencer: Schema.Struct({ ClipTimeable: ArrangementSchema })
110
+ });
111
+ const MidiTrackSchema = Schema.Struct({
112
+ Id: Schema.String,
113
+ Name: NameSchema,
114
+ AutomationEnvelopes: Schema.optionalKey(EnvelopesSchema),
115
+ DeviceChain: TrackChainSchema
116
+ });
117
+ const ReturnTrackSchema = Schema.Struct({
118
+ Name: NameSchema,
119
+ DeviceChain: Schema.Struct({ Mixer: Schema.optionalKey(TrackMixerSchema) })
120
+ });
121
+ const MixerSchema = Schema.Struct({
122
+ Tempo: ParameterSchema,
123
+ TimeSignature: ParameterSchema
124
+ });
125
+ const MasterSchema = Schema.Struct({
126
+ AutomationEnvelopes: Schema.optionalKey(EnvelopesSchema),
127
+ DeviceChain: Schema.optionalKey(Schema.Struct({ Mixer: MixerSchema })),
128
+ MasterChain: Schema.optionalKey(Schema.Struct({ Mixer: MixerSchema }))
129
+ });
130
+ const LocatorSchema = Schema.Struct({
131
+ Time: Num,
132
+ Name: Text
133
+ });
134
+ const TracksSchema = Schema.Struct({
135
+ MidiTrack: MidiTrackSchema.pipe(Schema.Array, Schema.optionalKey),
136
+ ReturnTrack: ReturnTrackSchema.pipe(Schema.Array, Schema.optionalKey)
137
+ });
138
+ const LocatorListSchema = Schema.Struct({ Locator: LocatorSchema.pipe(Schema.Array, Schema.optionalKey) });
139
+ const LiveSetSchema = Schema.Struct({
140
+ Tracks: TracksSchema,
141
+ MasterTrack: Schema.optionalKey(MasterSchema),
142
+ MainTrack: Schema.optionalKey(MasterSchema),
143
+ Locators: Schema.optionalKey(Schema.Struct({ Locators: LocatorListSchema }))
144
+ });
145
+ const DocumentSchema = Schema.Struct({ Ableton: Schema.Struct({
146
+ MajorVersion: Schema.String,
147
+ MinorVersion: Schema.String,
148
+ Creator: Schema.optionalKey(Schema.String),
149
+ LiveSet: LiveSetSchema
150
+ }) });
151
+ const decodeDocument = Schema.decodeUnknownEffect(DocumentSchema);
152
+ const isElement = Schema.is(Schema.Record(Schema.String, Schema.Unknown));
153
+ const isAttributes = Schema.is(Schema.Record(Schema.String, Schema.String));
154
+ const flattened = (node) => {
155
+ if (node === "") return {};
156
+ if (Array.isArray(node)) return pipe(node, Array.map((child) => flattened(child)));
157
+ if (isElement(node)) {
158
+ const { [ATTRIBUTES]: attributes, ...children } = node;
159
+ const own = pipe(Option.liftPredicate(attributes, isAttributes), Option.getOrElse(() => ({})));
160
+ return {
161
+ ...pipe(children, Record.map((child) => flattened(child))),
162
+ ...own
163
+ };
164
+ }
165
+ return node;
166
+ };
167
+ const gunzip = (bytes) => Effect.tryPromise({
168
+ try: () => new Response(new Blob([Uint8Array.from(bytes)]).stream().pipeThrough(new DecompressionStream("gzip"))).text(),
169
+ catch: (cause) => UnreadableAls.make({ message: `Not a gzipped Live Set: ${String(cause)}` })
170
+ });
171
+ const readAlsDocument = Effect.fn("readAlsDocument")(function* read(bytes) {
172
+ const xml = yield* gunzip(bytes);
173
+ const parsed = yield* Effect.try({
174
+ try: () => flattened(parser.parse(xml)),
175
+ catch: (cause) => UnreadableAls.make({ message: `Not XML: ${String(cause)}` })
176
+ });
177
+ return yield* decodeDocument(parsed).pipe(Effect.mapError((issue) => UnreadableAls.make({ message: `Not a Live Set this converter reads: ${String(issue)}` })));
178
+ });
179
+ // src/features/convert-als/model/clips.ts
180
+ const NONE$2 = 0;
181
+ const DEFAULT_RELEASE = 64;
182
+ const modulo = (value, size) => (value % size + size) % size;
183
+ const passesOf = (clip) => {
184
+ const start = clip.CurrentStart.Value;
185
+ const length = clip.CurrentEnd.Value - start;
186
+ const loopStart = clip.Loop.LoopStart.Value;
187
+ const loopLength = clip.Loop.LoopEnd.Value - loopStart;
188
+ if (clip.Loop.LoopOn.Value === "false" || loopLength <= NONE$2) return [{
189
+ at: start,
190
+ from: loopStart,
191
+ to: loopStart + length
192
+ }];
193
+ const first = loopStart + modulo(clip.Loop.StartRelative.Value, loopLength);
194
+ const walk = (elapsed, from, passes) => {
195
+ if (elapsed >= length) return passes;
196
+ const span = Math.min(clip.Loop.LoopEnd.Value - from, length - elapsed);
197
+ return walk(elapsed + span, loopStart, [...passes, {
198
+ at: start + elapsed,
199
+ from,
200
+ to: from + span
201
+ }]);
202
+ };
203
+ return walk(NONE$2, first, []);
204
+ };
205
+ const releaseOf = (offVelocity) => pipe(Option.fromUndefinedOr(offVelocity), Option.filter((off) => off !== NONE$2), Option.match({
206
+ onNone: () => DEFAULT_RELEASE,
207
+ onSome: Math.round
208
+ }));
209
+ const sourceNotesOf = (clip) => pipe(clip.Notes.KeyTracks.KeyTrack ?? [], Array.flatMap((keyTrack) => pipe(keyTrack.Notes.MidiNoteEvent ?? [], Array.filter((note) => note.IsEnabled !== "false"), Array.map((note) => ({
210
+ time: note.Time,
211
+ end: note.Time + note.Duration,
212
+ midi: keyTrack.MidiKey.Value,
213
+ velocity: Math.round(note.Velocity),
214
+ release: releaseOf(note.OffVelocity)
215
+ })))));
216
+ const inPass = (notes) => (pass) => pipe(notes, Array.filter((note) => note.time >= pass.from && note.time < pass.to), Array.map((note) => ({
217
+ beat: pass.at + note.time - pass.from,
218
+ length: Math.min(note.end, pass.to) - note.time,
219
+ midi: note.midi,
220
+ velocity: note.velocity,
221
+ release: note.release
222
+ })));
223
+ const byStartThenPitch = Order.combine(Order.mapInput(Order.Number, (note) => note.beat), Order.mapInput(Order.Number, (note) => note.midi));
224
+ const isDisabled = (clip) => Option.exists(Option.fromUndefinedOr(clip.Disabled), (flag) => flag.Value === "true");
225
+ const notesOfClip = (clip) => {
226
+ if (isDisabled(clip)) return [];
227
+ const notes = sourceNotesOf(clip);
228
+ return pipe(passesOf(clip), Array.flatMap(inPass(notes)), Array.sortBy(byStartThenPitch));
229
+ };
230
+ const masterOf = (liveSet) => Option.orElse(Option.fromUndefinedOr(liveSet.MasterTrack), () => Option.fromUndefinedOr(liveSet.MainTrack));
231
+ const mixerOf = (master) => pipe(Option.fromUndefinedOr(master.DeviceChain), Option.orElse(() => Option.fromUndefinedOr(master.MasterChain)), Option.map((chain) => chain.Mixer));
232
+ const eventsOf = (events) => [
233
+ ...events.FloatEvent ?? [],
234
+ ...events.EnumEvent ?? [],
235
+ ...events.BoolEvent ?? []
236
+ ];
237
+ const automationEnvelopesOf = (owner) => pipe(Option.fromUndefinedOr(owner.AutomationEnvelopes), Option.flatMap((envelopes) => Option.fromUndefinedOr(envelopes.Envelopes.AutomationEnvelope)), Option.getOrElse(() => []));
238
+ const byTime = Order.mapInput(Order.Number, (event) => event.Time);
239
+ const envelopeOf = (owner) => (parameter) => {
240
+ const inline = pipe(Option.fromUndefinedOr(parameter.ArrangerAutomation), Option.map((automation) => automation.Events));
241
+ const pointed = pipe(Option.fromUndefinedOr(parameter.AutomationTarget), Option.flatMap((target) => pipe(automationEnvelopesOf(owner), Array.findFirst((envelope) => envelope.EnvelopeTarget.PointeeId.Value === target.Id))), Option.map((envelope) => envelope.Automation.Events));
242
+ return pipe(Option.orElse(pointed, () => inline), Option.map(eventsOf), Option.getOrElse(() => []), Array.sortBy(byTime));
243
+ };
244
+ const SINGLE = 1;
245
+ const NEXT$2 = 1;
246
+ const automationOf = (select) => (liveSet) => pipe(masterOf(liveSet), Option.flatMap((master) => pipe(mixerOf(master), Option.map((mixer) => {
247
+ const parameter = select(mixer);
248
+ return {
249
+ events: envelopeOf(master)(parameter),
250
+ manual: pipe(Option.fromUndefinedOr(parameter.Manual), Option.map((manual) => manual.Value))
251
+ };
252
+ }))));
253
+ const tempoAutomationOf = automationOf((mixer) => mixer.Tempo);
254
+ const pointsOf$1 = (events) => pipe(events, Array.map((event) => ({
255
+ beat: event.Time,
256
+ value: Number(event.Value)
257
+ })));
258
+ const tempoFrom = (resolve) => (liveSet) => pipe(tempoAutomationOf(liveSet), Option.map(resolve), Option.getOrElse(() => []));
259
+ const tempoEnvelopeOf = tempoFrom(({ events }) => pointsOf$1(events));
260
+ const manualPointsOf = tempoFrom(({ manual }) => pipe(manual, Option.map((value) => [{
261
+ beat: 0,
262
+ value
263
+ }]), Option.getOrElse(() => [])));
264
+ const tempoPointsOf = (liveSet) => {
265
+ const envelope = tempoEnvelopeOf(liveSet);
266
+ const manual = manualPointsOf(liveSet);
267
+ if (envelope.length > SINGLE || !Array.isReadonlyArrayNonEmpty(manual)) return envelope;
268
+ return manual;
269
+ };
270
+ const valueAt = (from, to) => (beat) => {
271
+ if (to.beat === from.beat) return to.value;
272
+ return from.value + (to.value - from.value) * (beat - from.beat) / (to.beat - from.beat);
273
+ };
274
+ const segmentOf = (from, next) => {
275
+ const start = Math.max(from.beat, 0);
276
+ return Option.match(next, {
277
+ onNone: () => ({
278
+ beat: start,
279
+ bpm: from.value,
280
+ target: Option.none()
281
+ }),
282
+ onSome: (to) => {
283
+ const bpm = valueAt(from, to)(start);
284
+ if (to.beat <= start || to.value === bpm) return {
285
+ beat: start,
286
+ bpm,
287
+ target: Option.none()
288
+ };
289
+ return {
290
+ beat: start,
291
+ bpm,
292
+ target: Option.some(to.value)
293
+ };
294
+ }
295
+ });
296
+ };
297
+ const keptWith = (kept, segment) => {
298
+ const earlier = pipe(Array.last(kept), Option.filter((last) => last.beat === segment.beat), Option.match({
299
+ onNone: () => kept,
300
+ onSome: () => Array.dropRight(kept, SINGLE)
301
+ }));
302
+ if (pipe(Array.last(earlier), Option.exists((last) => Option.isNone(last.target) && Option.isNone(segment.target) && last.bpm === segment.bpm))) return earlier;
303
+ return [...earlier, segment];
304
+ };
305
+ const withoutRepeats = (segments) => {
306
+ let kept = [];
307
+ for (const segment of segments) kept = keptWith(kept, segment);
308
+ return kept;
309
+ };
310
+ const tempoSegmentsOf = (points) => pipe(points, Array.map((point, index) => ({
311
+ point,
312
+ next: Array.get(points, index + NEXT$2)
313
+ })), Array.filter(({ next }) => Option.match(next, {
314
+ onNone: () => true,
315
+ onSome: (to) => to.beat > 0
316
+ })), Array.map(({ point, next }) => segmentOf(point, next)), withoutRepeats);
317
+ const meterOfId = (beat, id) => pipe(Option.fromNullishOr(decodeTimeSignatureId(id)), Option.map((signature) => ({
318
+ beat: Math.max(beat, 0),
319
+ numerator: signature.num,
320
+ denominator: signature.den
321
+ })));
322
+ const metersOf = (liveSet) => pipe(automationOf((mixer) => mixer.TimeSignature)(liveSet), Option.map(({ events, manual }) => {
323
+ if (events.length > SINGLE || Option.isNone(manual)) return pipe(events, Array.map((event) => meterOfId(event.Time, Number(event.Value))), Array.getSomes, Array.reverse, Array.dedupeAdjacentWith((later, earlier) => later.beat === earlier.beat), Array.reverse);
324
+ return Option.toArray(meterOfId(0, manual.value));
325
+ }), Option.getOrElse(() => []));
326
+ const byBeat = Order.mapInput(Order.Number, (locator) => locator.beat);
327
+ const locatorsOf = (liveSet) => pipe(Option.fromUndefinedOr(liveSet.Locators), Option.flatMap((locators) => Option.fromUndefinedOr(locators.Locators.Locator)), Option.getOrElse(() => []), Array.map((locator) => ({
328
+ beat: locator.Time.Value,
329
+ name: locator.Name.Value
330
+ })), Array.sortBy(byBeat));
331
+ // src/features/convert-als/model/ticks.ts
332
+ const TICKS_PER_BEAT = TICKS_PER_WHOLE / 4;
333
+ const tickOf = (beat) => {
334
+ const exact = beat * TICKS_PER_BEAT;
335
+ return {
336
+ tick: Math.round(exact),
337
+ exact: Number.isInteger(exact)
338
+ };
339
+ };
340
+ // src/features/convert-als/model/mix.ts
341
+ const DECIBELS_PER_DECADE = 20;
342
+ const SILENT_DECIBELS = -70;
343
+ const AUDIBLE_SEND = .001;
344
+ const NONE$1 = 0;
345
+ const NEXT$1 = 1;
346
+ const SILENT = 10 ** (SILENT_DECIBELS / DECIBELS_PER_DECADE);
347
+ const decibelsOf = (gain) => DECIBELS_PER_DECADE * Math.log10(Math.max(gain, SILENT));
348
+ const [VOLUME, PAN] = MIXER_PARAMETERS;
349
+ const VALUES = {
350
+ volume: decibelsOf,
351
+ pan: (pan) => pan
352
+ };
353
+ const RESTING = {
354
+ volume: NONE$1,
355
+ pan: NONE$1
356
+ };
357
+ const pointsOf = ({ owner, parameter }) => (control) => pipe(envelopeOf(owner)(control), Array.map((event) => ({
358
+ tick: tickOf(Math.max(event.Time, 0)).tick,
359
+ value: VALUES[parameter](Number(event.Value))
360
+ })), Array.filter((point) => Number.isFinite(point.value)));
361
+ const startOf = (owned) => (control) => pipe(pointsOf(owned)(control), Array.head, Option.map((point) => point.value), Option.orElse(() => pipe(Option.fromUndefinedOr(control.Manual), Option.map((manual) => VALUES[owned.parameter](manual.Value)))), Option.getOrElse(() => RESTING[owned.parameter]));
362
+ const levelOf = (owner) => (mixer) => ({
363
+ decibels: startOf({
364
+ owner,
365
+ parameter: VOLUME
366
+ })(mixer.Volume),
367
+ pan: startOf({
368
+ owner,
369
+ parameter: PAN
370
+ })(mixer.Pan),
371
+ muted: pipe(Option.fromUndefinedOr(mixer.Speaker), Option.flatMap((speaker) => Option.fromUndefinedOr(speaker.Manual)), Option.exists((manual) => manual.Value === "false"))
372
+ });
373
+ const sendsOf = (mixer) => pipe(Option.fromUndefinedOr(mixer.Sends), Option.flatMap((sends) => Option.fromUndefinedOr(sends.TrackSendHolder)), Option.getOrElse(() => []), Array.map((holder, bus) => ({
374
+ bus,
375
+ amount: pipe(Option.fromUndefinedOr(holder.Send.Manual), Option.match({
376
+ onNone: () => NONE$1,
377
+ onSome: (manual) => manual.Value
378
+ }))
379
+ })), Array.filter((send) => send.amount > AUDIBLE_SEND));
380
+ const envelopesOf = (owner) => (mixer) => pipe([{
381
+ parameter: "volume",
382
+ control: mixer.Volume
383
+ }, {
384
+ parameter: "pan",
385
+ control: mixer.Pan
386
+ }], Array.map(({ parameter, control }) => ({
387
+ parameter,
388
+ points: pointsOf({
389
+ owner,
390
+ parameter
391
+ })(control)
392
+ })), Array.filter((envelope) => envelope.points.length > NEXT$1));
393
+ const trackMixOf = (track) => pipe(Option.fromUndefinedOr(track.DeviceChain.Mixer), Option.map((mixer) => ({
394
+ level: levelOf(track)(mixer),
395
+ sends: sendsOf(mixer),
396
+ envelopes: envelopesOf(track)(mixer)
397
+ })));
398
+ const NO_ENVELOPES = {};
399
+ const busOf = (nameOf) => (track) => ({
400
+ name: nameOf(track.Name),
401
+ level: pipe(Option.fromUndefinedOr(track.DeviceChain.Mixer), Option.match({
402
+ onNone: () => ({
403
+ decibels: NONE$1,
404
+ pan: NONE$1,
405
+ muted: false
406
+ }),
407
+ onSome: levelOf(NO_ENVELOPES)
408
+ }))
409
+ });
410
+ const mixOf = (nameOf) => (liveSet) => ({
411
+ tracks: new Map(pipe(liveSet.Tracks.MidiTrack ?? [], Array.flatMap((track, index) => pipe(trackMixOf(track), Option.map((mix) => [index, mix]), Option.toArray)))),
412
+ buses: pipe(liveSet.Tracks.ReturnTrack ?? [], Array.map(busOf(nameOf)))
413
+ });
414
+ // src/features/convert-als/model/timeline.ts
415
+ const MELODIC_CHANNEL = 0;
416
+ const DRUM_CHANNEL = 9;
417
+ const NONE = 0;
418
+ const NEXT = 1;
419
+ const nameOf = (label) => pipe([label.EffectiveName, label.UserName], Array.map(Option.fromUndefinedOr), Array.getSomes, Array.map((name) => name.Value), Array.findFirst((name) => name !== ""));
420
+ const isDrumRack = (track) => pipe(Option.fromUndefinedOr(track.DeviceChain.DeviceChain), Option.flatMap((chain) => Option.fromUndefinedOr(chain.Devices)), Option.flatMap((devices) => Option.fromUndefinedOr(devices.DrumGroupDevice)), Option.isSome);
421
+ const trackNotesOf = (track) => {
422
+ const played = pipe(track.DeviceChain.MainSequencer.ClipTimeable.ArrangerAutomation.Events.MidiClip ?? [], Array.flatMap(notesOfClip));
423
+ const placed = pipe(played, Array.map((note) => ({
424
+ note,
425
+ start: tickOf(note.beat),
426
+ end: tickOf(note.beat + note.length)
427
+ })));
428
+ return {
429
+ notes: sortedNotes(pipe(placed, Array.map(({ note, start, end }) => ({
430
+ tick: start.tick,
431
+ end: end.tick,
432
+ midi: note.midi,
433
+ velocity: note.velocity,
434
+ release: note.release
435
+ })))),
436
+ offGrid: Array.countBy(placed, ({ start, end }) => !start.exact || !end.exact)
437
+ };
438
+ };
439
+ const partOf = (track, index) => {
440
+ const read = trackNotesOf(track);
441
+ return {
442
+ part: {
443
+ track: index,
444
+ channel: Boolean.match(isDrumRack(track), {
445
+ onFalse: () => MELODIC_CHANNEL,
446
+ onTrue: () => DRUM_CHANNEL
447
+ }),
448
+ name: nameOf(track.Name),
449
+ program: Option.none(),
450
+ notes: read.notes,
451
+ controls: [],
452
+ lyrics: []
453
+ },
454
+ offGrid: read.offGrid
455
+ };
456
+ };
457
+ const temposOf = (liveSet) => pipe(tempoSegmentsOf(tempoPointsOf(liveSet)), Array.map((segment) => ({
458
+ tick: tickOf(segment.beat).tick,
459
+ microseconds: microsecondsOf(segment.bpm),
460
+ target: pipe(segment.target, Option.map(microsecondsOf))
461
+ })));
462
+ const lastOf = (ticks) => Array.reduce(ticks, NONE, (latest, tick) => Math.max(latest, tick));
463
+ const timelineOf = (liveSet) => {
464
+ const reads = pipe(liveSet.Tracks.MidiTrack ?? [], Array.map(partOf), Array.filter((read) => Array.isReadonlyArrayNonEmpty(read.part.notes)));
465
+ const parts = pipe(reads, Array.map((read) => read.part));
466
+ const markers = sortedByTick(pipe(locatorsOf(liveSet), Array.map((locator) => ({
467
+ tick: tickOf(locator.beat).tick,
468
+ text: locator.name
469
+ }))));
470
+ const tempos = temposOf(liveSet);
471
+ const meters = pipe(metersOf(liveSet), Array.map((meter) => ({
472
+ tick: tickOf(meter.beat).tick,
473
+ numerator: meter.numerator,
474
+ denominator: meter.denominator
475
+ })));
476
+ const noteEnds = pipe(parts, Array.flatMap((part) => part.notes), Array.map((note) => note.end));
477
+ const pointEnds = pipe([
478
+ ...markers,
479
+ ...tempos,
480
+ ...meters
481
+ ], Array.map((point) => point.tick + NEXT));
482
+ return {
483
+ title: Option.none(),
484
+ end: lastOf([...noteEnds, ...pointEnds]),
485
+ offGrid: Array.reduce(reads, NONE, (sum, read) => sum + read.offGrid),
486
+ tempos,
487
+ meters,
488
+ markers,
489
+ parts,
490
+ mix: mixOf(nameOf)(liveSet)
491
+ };
492
+ };
493
+ // src/features/convert-als/model/convert.ts
494
+ const alsToFumx = Effect.fn("alsToFumx")(function* convert(input) {
495
+ const document = yield* readAlsDocument(input.bytes);
496
+ const timeline = yield* Effect.sync(() => timelineOf(document.Ableton.LiveSet)).pipe(Effect.withSpan("timelineOf"));
497
+ const written = yield* Effect.sync(() => writeFumx({
498
+ timeline,
499
+ title: input.title
500
+ })).pipe(Effect.withSpan("writeFumx"));
501
+ yield* Effect.annotateCurrentSpan({
502
+ creator: document.Ableton.Creator ?? "",
503
+ parts: written.plan.parts.length,
504
+ bars: written.bars.length
505
+ });
506
+ return {
507
+ ...written,
508
+ offGrid: timeline.offGrid
509
+ };
510
+ });
511
+ // src/app/als-to-fumx.ts
512
+ const convertLiveSetFile = Effect.fn("convertLiveSetFile")(function* convert(source) {
513
+ const fumx = yield* alsToFumx(source);
514
+ return yield* roundTrip(source.path, fumx);
515
+ });
516
+ // bin/als-to-fumx.ts
517
+ convertMain({
518
+ name: "als-to-fumx",
519
+ input: "An Ableton Live Set (.als)",
520
+ source: "Live Set",
521
+ convert: convertLiveSetFile
522
+ });
523
+ export {};
524
+
525
+ //# sourceMappingURL=als-to-fumx.mjs.map