File size: 4,506 Bytes
4cadbaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

const MIDI = require("./MIDI");



const trackDeltaToAbs = events => {
	let tick = 0;

	events.forEach(event => {
		tick += event.deltaTime;
		event.tick = tick;
	});
};


const trackAbsToDelta = events => {
	let lastTick = 0;

	events.sort((e1, e2) => e1.tick - e2.tick).forEach(event => {
		event.deltaTime = event.tick - lastTick;
		lastTick = event.tick;
	});
};


const sliceTrack = (track, startTick, endTick) => {
	trackDeltaToAbs(track);

	const events = [];
	const status = {};

	track.forEach(event => {
		if (event.tick >= startTick && event.tick <= endTick && event.subtype !== "endOfTrack")
			events.push({
				...event,
				tick: event.tick - startTick,
			});
		else if (event.tick < startTick) {
			switch (event.type) {
			case "meta":
				status[event.subtype] = event;

				break;
			}
		}
	});

	Object.values(status).forEach(event => events.push({
		...event,
		tick: 0,
	}));

	events.push({
		tick: endTick - startTick,
		type: "meta",
		subtype: "endOfTrack",
	});

	trackAbsToDelta(events);

	return events;
};


const sliceMidi = (midi, startTick, endTick) => ({
	header: midi.header,
	tracks: midi.tracks.map(track => sliceTrack(track, startTick, endTick)),
});


const TICKS_PER_BEATS = 480;

const EXCLUDE_MIDI_EVENT_SUBTYPES = [
	"endOfTrack", "trackName",
	"noteOn", "noteOff",
];


function encodeToMIDIData(notation, {startTime, unclosedNoteDuration = 30e+3} = {}) {
	notation.microsecondsPerBeat = notation.microsecondsPerBeat || 500000;

	const ticksPerBeat = TICKS_PER_BEATS;
	const msToTicks = ticksPerBeat * 1000 / notation.microsecondsPerBeat;

	const header = { formatType: 0, ticksPerBeat };
	const track = [];

	if (!Number.isFinite(startTime)) {
		if (!notation.notes || !notation.notes[0])
			throw new Error("encodeToMidiData: no start time specificed");

		startTime = notation.notes[0].start;
	}

	track.push({ time: startTime, type: "meta", subtype: "copyrightNotice", text: `Composed by MusicWdigets. BUILT on ${new Date(Number(process.env.VUE_APP_BUILD_TIME)).toDateString()}` });

	const containsTempo = notation.events && notation.events.find(event => event.subtype == "setTempo");
	if (!containsTempo) {
		track.push({ time: startTime, type: "meta", subtype: "timeSignature", numerator: 4, denominator: 4, thirtyseconds: 8 });
		track.push({ time: startTime, type: "meta", subtype: "setTempo", microsecondsPerBeat: notation.microsecondsPerBeat });
	}

	//if (notation.correspondences)
	//	track.push({ time: startTime, type: "meta", subtype: "text", text: "find-corres:" + notation.correspondences.join(",") });

	let endTime = startTime || 0;

	if (notation.notes) {
		for (const note of notation.notes) {
			track.push({
				time: note.start,
				type: "channel",
				subtype: "noteOn",
				channel: note.channel || 0,
				noteNumber: note.pitch,
				velocity: note.velocity,
				finger: note.finger,
			});

			endTime = Math.max(endTime, note.start);

			if (Number.isFinite(unclosedNoteDuration))
				note.duration = note.duration || unclosedNoteDuration;
			if (note.duration) {
				track.push({
					time: note.start + note.duration,
					type: "channel",
					subtype: "noteOff",
					channel: note.channel || 0,
					noteNumber: note.pitch,
					velocity: 0,
				});

				endTime = Math.max(endTime, note.start + note.duration);
			}
		}
	}

	if (notation.events) {
		const events = notation.events.filter(event => !EXCLUDE_MIDI_EVENT_SUBTYPES.includes(event.data.subtype));
		for (const event of events) {
			track.push({
				time: event.time,
				...event.data,
			});

			endTime = Math.max(endTime, event.time);
		}
	}

	track.push({ time: endTime + 100, type: "meta", subtype: "endOfTrack" });

	track.sort(function (e1, e2) { return e1.time - e2.time; });

	// append finger event after every noteOn event
	track.map((event, index) => ({event, index}))
		.filter(({event}) => event.subtype == "noteOn" && event.finger != null)
		.reverse()
		.forEach(({event, index}) => track.splice(index + 1, 0, {
			time: event.time,
			type: "meta",
			subtype: "text",
			text: `fingering(${event.finger})`,
		}));

	track.forEach(event => event.ticks = Math.round((event.time - startTime) * msToTicks));
	track.forEach((event, i) => event.deltaTime = (event.ticks - (i > 0 ? track[i - 1].ticks : 0)));

	return {header, tracks: [track]};
};


function encodeToMIDI(notation, options) {
	const data = encodeToMIDIData(notation, options);
	return MIDI.encodeMidiFile(data);
};



module.exports = {
	sliceMidi,
	encodeToMIDIData,
	encodeToMIDI,
};