File size: 7,770 Bytes
6293e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * MIDI Parser - Converts MIDI files to internal Score format
 *
 * This bypasses MusicXML entirely to preserve YourMT3+ transcription accuracy.
 */

import { Midi } from '@tonejs/midi';
import type { Score, Part, Measure, Note } from '../store/notation';

export interface MidiParseOptions {
  tempo?: number;
  timeSignature?: { numerator: number; denominator: number };
  keySignature?: string;
  splitAtMiddleC?: boolean; // For grand staff (treble + bass)
  middleCNote?: number; // MIDI note number for staff split (default: 60)
}

/**
 * Parse MIDI file into Score format
 */
export async function parseMidiFile(
  midiData: ArrayBuffer,
  options: MidiParseOptions = {}
): Promise<Score> {
  const midi = new Midi(midiData);

  // Extract metadata
  const tempo = options.tempo || midi.header.tempos[0]?.bpm || 120;
  const timeSignature = options.timeSignature || {
    numerator: midi.header.timeSignatures[0]?.timeSignature[0] || 4,
    denominator: midi.header.timeSignatures[0]?.timeSignature[1] || 4,
  };
  const keySignature = options.keySignature || 'C';

  // Parse all tracks into single note list
  const allNotes = extractNotesFromMidi(midi);

  // Create measures from notes
  const measureDuration = (timeSignature.numerator / timeSignature.denominator) * 4; // in quarter notes
  const parts = createPartsFromNotes(
    allNotes,
    measureDuration,
    options.splitAtMiddleC ?? true,
    options.middleCNote ?? 60,
    tempo
  );

  return {
    id: 'score-1',
    title: midi.name || 'Transcribed Score',
    composer: 'YourMT3+',
    key: keySignature,
    timeSignature: `${timeSignature.numerator}/${timeSignature.denominator}`,
    tempo,
    parts,
    measures: parts[0]?.measures || [], // Legacy compatibility
  };
}

interface MidiNote {
  midi: number;
  time: number;
  duration: number;
  velocity: number;
}

/**
 * Extract all notes from MIDI tracks
 */
function extractNotesFromMidi(midi: Midi): MidiNote[] {
  const notes: MidiNote[] = [];

  for (const track of midi.tracks) {
    for (const note of track.notes) {
      notes.push({
        midi: note.midi,
        time: note.time,
        duration: note.duration,
        velocity: note.velocity,
      });
    }
  }

  // Sort by time
  notes.sort((a, b) => a.time - b.time);

  return notes;
}

/**
 * Create grand staff parts (treble + bass) or single part
 */
function createPartsFromNotes(
  notes: MidiNote[],
  measureDuration: number,
  splitStaff: boolean,
  middleCNote: number,
  tempo: number
): Part[] {
  if (splitStaff) {
    // Split into treble (>= middle C) and bass (< middle C)
    const trebleNotes = notes.filter((n) => n.midi >= middleCNote);
    const bassNotes = notes.filter((n) => n.midi < middleCNote);

    return [
      {
        id: 'part-treble',
        name: 'Piano Right Hand',
        clef: 'treble',
        measures: createMeasures(trebleNotes, measureDuration, tempo),
      },
      {
        id: 'part-bass',
        name: 'Piano Left Hand',
        clef: 'bass',
        measures: createMeasures(bassNotes, measureDuration, tempo),
      },
    ];
  } else {
    // Single staff
    return [
      {
        id: 'part-1',
        name: 'Piano',
        clef: 'treble',
        measures: createMeasures(notes, measureDuration, tempo),
      },
    ];
  }
}

/**
 * Create measures from notes
 */
function createMeasures(notes: MidiNote[], measureDuration: number, tempo: number = 120): Measure[] {
  if (notes.length === 0) {
    return [
      {
        id: 'measure-1',
        number: 1,
        notes: [],
      },
    ];
  }

  // Calculate total duration and number of measures
  const maxTime = Math.max(...notes.map((n) => n.time + n.duration));
  const numMeasures = Math.ceil(maxTime / measureDuration);

  const measures: Measure[] = [];

  for (let i = 0; i < numMeasures; i++) {
    const measureStart = i * measureDuration;
    const measureEnd = (i + 1) * measureDuration;

    // Find notes that start in this measure
    const measureNotes = notes
      .filter((n) => n.time >= measureStart && n.time < measureEnd)
      .map((midiNote, idx) => convertMidiNoteToNote(midiNote, `m${i + 1}-n${idx}`, measureStart, tempo));

    measures.push({
      id: `measure-${i + 1}`,
      number: i + 1,
      notes: measureNotes,
    });
  }

  return measures;
}

/**
 * Convert MIDI note to internal Note format
 */
function convertMidiNoteToNote(midiNote: MidiNote, id: string, measureStart: number, tempo: number): Note {
  const { pitch, octave, accidental } = midiNumberToPitch(midiNote.midi);
  const { duration, dotted } = durationToNoteName(midiNote.duration, tempo);

  return {
    id,
    pitch: `${pitch}${octave}`,
    duration,
    octave,
    startTime: midiNote.time - measureStart, // Relative to measure start
    dotted,
    accidental,
    isRest: false,
    // chordId will be assigned by grouping simultaneous notes
  };
}

/**
 * Convert MIDI note number to pitch name, octave, and accidental
 */
function midiNumberToPitch(midiNumber: number): {
  pitch: string;
  octave: number;
  accidental?: 'sharp' | 'flat' | 'natural';
} {
  const pitchClasses = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
  const pitchClass = midiNumber % 12;
  const octave = Math.floor(midiNumber / 12) - 1;
  const pitchName = pitchClasses[pitchClass];

  let accidental: 'sharp' | 'flat' | 'natural' | undefined;
  if (pitchName.includes('#')) {
    accidental = 'sharp';
  }

  return {
    pitch: pitchName.replace('#', ''),
    octave,
    accidental,
  };
}

/**
 * Convert duration (in seconds) to note name (whole, half, quarter, etc.)
 */
function durationToNoteName(duration: number, tempo: number): { duration: string; dotted: boolean } {
  // Calculate quarter note duration based on actual tempo
  // At tempo BPM: 1 quarter note = 60/BPM seconds
  const quarterNoteDuration = 60 / tempo;

  const durationInQuarters = duration / quarterNoteDuration;

  // Find closest standard duration (including dotted notes)
  const durations: [number, string, boolean][] = [
    [4, 'whole', false],
    [3, 'half', true],     // dotted half
    [2, 'half', false],
    [1.5, 'quarter', true], // dotted quarter
    [1, 'quarter', false],
    [0.75, 'eighth', true], // dotted eighth
    [0.5, 'eighth', false],
    [0.375, '16th', true],  // dotted 16th
    [0.25, '16th', false],
    [0.125, '32nd', false],
  ];

  let closestDuration = durations[0];
  let minDiff = Math.abs(durationInQuarters - durations[0][0]);

  for (const [value, name, dotted] of durations) {
    const diff = Math.abs(durationInQuarters - value);
    if (diff < minDiff) {
      minDiff = diff;
      closestDuration = [value, name, dotted];
    }
  }

  return {
    duration: closestDuration[1],
    dotted: closestDuration[2],
  };
}

/**
 * Group simultaneous notes into chords
 */
export function assignChordIds(score: Score): Score {
  const CHORD_TOLERANCE = 0.05; // Notes within 50ms are considered simultaneous

  for (const part of score.parts) {
    for (const measure of part.measures) {
      const notes = measure.notes;

      // Group notes by start time
      const groups: Record<string, Note[]> = {};

      for (const note of notes) {
        const timeKey = Math.round(note.startTime / CHORD_TOLERANCE).toString();
        if (!groups[timeKey]) {
          groups[timeKey] = [];
        }
        groups[timeKey].push(note);
      }

      // Assign chordId to groups with multiple notes
      for (const [timeKey, groupNotes] of Object.entries(groups)) {
        if (groupNotes.length > 1) {
          const chordId = `chord-${measure.id}-${timeKey}`;
          groupNotes.forEach((note) => {
            note.chordId = chordId;
          });
        }
      }
    }
  }

  return score;
}