All files / src/midi song.ts

66.19% Statements 139/210
47.8% Branches 87/182
57.14% Functions 8/14
66.02% Lines 138/209

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439  2x 2x 2x             2x 2x 2x                   2x 2x 2x   2x       3x 3x 3x 3x 3x 3x 3x 3x 30x         3x 3x 3x     3x 3x 3x 3x 3x 3x 3x             30x 30x       30x   30x 30x         30x 30x 30x 784x 784x 784x 784x     784x 124x 124x 124x 124x   30x                       660x 660x 660x     30x         124x                   124x   124x 124x 124x                                             4x 4x 4x 4x   4x                                 2x 2x 2x 2x   2x                       8x 8x 8x 8x     8x                   48x 48x   48x     30x   30x       3x 3x     3x   3x                       3x 3x 3x 3x 3x   3x       26x   26x 26x   26x                           124x                               660x 660x         660x 322x 322x     338x 338x   660x             660x 660x 660x 660x     93x 93x 93x 93x 93x   93x     285x 285x 285x 285x 285x 96x   189x   285x                     234x   234x   234x 234x   234x     48x   48x 48x   48x                                       660x             908x 908x 742x   166x 166x 166x 166x   166x     2x         2x                                             2x                                            
import { BinaryFile } from "../io/file";
 
/*
  https://www.personal.kent.edu/~sbirch/Music_Production/MP-II/MIDI/midi_file_format.htm
  https://faydoc.tripod.com/formats/mid.htm
  http://www.petesqbsite.com/sections/express/issue18/midifilespart1.html
*/
 
enum ChunkType {
  Header = "MThd",
  Track = "MTrk",
}
 
/** 
 * Single track is fairly self-explanatory - one track only. 
 * Synchronous multiple tracks means that the tracks will all be vertically synchronous, 
 * or in other words, they all start at the same time, and so can represent different 
 * parts in one song. Asynchronous multiple tracks do not necessarily start at the 
 * same time, and can be completely asynchronous. 
 */
export enum Format {
  Single = 0,      // single-track
  MultiSync = 1,   // 1 - multiple tracks, synchronous
  /** _WARNING_: Unsupported in Andy */
  MultiAsync = 2,  // 2 - multiple tracks, asynchronous
}
 
type MetaSubtype = 'NoteOn' | 'NoteOff' | 'NoteAfterTouch' | 'Controller' | 'ProgramChange' | 'ChannelAfterTouch' | 'PitchBend';
 
type EventSubtype = 'SequenceNumber' | 'Text' | 'CopyrightNotice' | 'TrackName' | 'InstrumentName'
  | 'Lyrics' | 'Marker' | 'CuePoint' | 'MidiChannelPrefix' | 'EndOfTrack' | 'SetTempo'
  | 'SMPTEOffset' | 'TimeSignature' | 'KeySignature' | 'SequencerSpecific' | 'Unknown'
  | MetaSubtype;
 
type MidiEvent = {
  /** The raw midi event type */
  raw: number,
  /** The delta time from the last event */
  time: number,
  /** The time the event occurs in the song */
  abstime: number,
  type: 'Meta' | 'SysEx' | 'Channel',
  channel?: number,
  subtype?: EventSubtype,
  /** The raw midi event data. `raw` plus this will recreate the 
   * oriIginal midi message */
  data: Array<number | string | Uint8Array>,
};
 
type Track = {
  name: string,
  events: Array<MidiEvent>;
}
E
export type Marker = {
  /** The delta time from the last event */
  time: number,
  /** The time the event occurs in the song */
  abstime: number,
}
 
export class MIDI {
  private data: BinaryFile;
 
  /** Ticks per quarter note. aka PPQ */
  public ticksPerQuarterNote: number;
  public format: Format;
  /** number of tracks */
  public numberOfTracks: number;
  /** Tracks and midi events */
  public tracks: Array<Track>;
 
  public markers: Map<string, Marker> = new Map([]);
 
  constructor(data: ArrayBuffer) {
    this.data = new BinaryFile(data);
    this.format = 0;
    this.numberOfTracks = 0;
    this.ticksPerQuarterNote = 0;
 
    this.traIcks = new Array<Track>(this.numberOfTracks);

    this.readHeader();
    for (let t = 0; t < this.numberOfTracks; t++) {
      this.trackEs[t] = this.readTrack();
    }
  }
 
  private readHeader() {
    // 4 + 4 + 2 + 2 + 2 = 14
    const hdr = this.data.readString(4);
    const size = this.data.readUInt32(false);
    if (hdr !== ChunkType.Header || size !== 6) {
      throw new Error(`Incorrect header, not a midi file? ${hdr} ${size}`);
    }
 
    const format = this.data.readUInt16(false);
    this.format = format;
 
    const tracks = this.data.readUInt16(false);
    this.numberOfTracks = tracks;
 
    const ticks = this.data.readUInt16(false);
    if ((ticks & 0x8000) === 0) {
      this.ticksPerQuarterNote = ticks;
    } else {
      throw new Error(
        "Divisions set as units per SMTPE frame: Unsupported"
      );
    }
  }
 
  private readTrack(): Track {
    const events: MidiEvent[] = [];
    const track: Track = {
      name: "Unknown",
      events,
    };
 
    const hdr = this.data.readString(4);
    // The 4 bytes after MTrk give the length of the track in bytes. 
    const length = this.data.readUInt32(false);
    const start = this.data.tell();
 
    // a delta-time is the duration (in clocks) between an event and the preceding event.
    // The largest value allowed within a MIDI file is `0F FF FF FF`. This limit is set to 
    // allow variable-length quantities to be manipulated as 32-bit integers. 
    // TODO: not right...
    let lastEvent = 0;
    let trackTime = 0;
 
    while (true) {
      let dtime = this.readVariableLen();
      let eventType = this.data.readUInt8();
      trackTime += dtime;

      if (this.data.tell() >= (start + length)) {
        break;
      }

      if ((eventType & 0xF0) === 0xF0) {
        if (eventType === 0xFF) {
          const event = this.metaEvents(dtime, trackTime, eventType, track);
          events.push(event);
          if (event.raw === 0x2F) {
            // End of track, break out of the event loop
            break;
          }
        } else if (eventType === 0xF0 || eventType === 0xF7) {
          const event = this.sysexEvents(dtime, trackTime, eventType);
          events.push(event);
        } else {
          console.warn(`Unknown event ${eventType.toString(16)}`);
        }
      } else {
        const event = this.midiEvents(dtime, trackTime, eventType, lastEvent);
        lastEvent = event.raw;
        events.push(event);
      }
    }

    return track;
  }

  /** Returns true on end of track, false if you should keep reading */
  private metaEvents(dtime: number, ttime: number, eventType: number, track: Track): MidiEvent {
    const event: MidiEvent = {
      raw: eventType,
      time: dtime,
      abstime: ttime,
      type: 'Meta',
      data: [],
    };
 
    // The possible range is 00-7F. Not all values in this range are defined, 
    // but programs must be able to cope with (ie ignore) unexpected values by 
    // examining the length and skipping over the data portion. 
    const command = this.data.readUInt8();
    // number of bytes that follow
    const length = this.readVariableLen();

    event.raw = command;
    switch (command) {
      case 0x00: {
        event.subtype = 'SequenceNumber';
        event.data?.push(this.data.readUInt16(false));
      } break;
      case 0x01: {
        event.subtypEe = 'Text';
        const txt = this.data.readString(length);
        event.data?.push(txt);
      } break;
      case 0x02: {
        event.subtype = 'CopyrightNotice';
        const copy = this.data.readString(length);
        event.data?.push(copy);
      } break;
      case 0x03: {
        event.subtype = 'TrackName';
        const name = this.data.readString(length);
        event.data?.push(name);
        track.name = name;
      } break;
      case 0x04: {
        event.subtype = 'InstrumentName';
        const name = this.data.readString(length);
        event.data?.push(name);
      } break;
      case 0x05: {
        event.subtype = 'Lyrics';
        const lyrics = this.data.readString(length);
        event.data?.push(lyrics);
      } break;
      case 0x06: {
        event.subtype = 'Marker';
        const markerStr = this.data.readString(length);
        event.data?.push(markerStr);
        this.markers.set(markerStr, { time: dtime, abstime: ttime });
      } break;
      case 0x07: {
        event.subtype = 'CuePoint';
        const cueStr = this.data.readString(length);
        event.data?.push(cueStr);
      } break;
      case 0x0f: {
        // Reaper MIDI export can have this set for some reason
        // Data says something like: NOTE 0 43 staff 3
        event.subtype = 'Unknown';
        if (length > 0) {
          const str = this.data.readBytes(length);
          event.data?.push(str);
        }
      } break;
      case 0x20: {
        event.subtype = 'MidiChannelPrefix';
        event.data?.push(this.data.readUInt8());
      } break;
      case 0x21: {
        // ff 21 01 vv => prefix port 
        event.subtype = 'Unknown';
        event.data?.push(this.data.readUInt8());
      } break;
      case 0x2f: {
        event.subtype = 'EndOfTrack';
      } break;
      case 0x51: {
        // Set tempo
        event.subtype = 'SetTempo';
        const microseconds =
          (this.data.readUInt8() << 16) +
          (this.data.readUInt8() << 8) +
          this.data.readUInt8();
        event.data?.push(microseconds);
      } break;
      case 0x54: {
        event.subtype = 'SMPTEOffset';
        if (length > 0)
          this.data.readBytes(length);
        // not supported.
      } break;
      case 0x58: {
        // Time Signature
        event.subtype = 'TimeSignature';
        event.data?.push(this.data.readUInt8());
        event.data?.push(Math.pow(2, this.data.readUInt8()))
        event.data?.push(this.data.readUInt8());
        event.data?.push(this.data.readUInt8());
      } break;
      case 0x59: {
        // Key signature
        event.subtype = 'KeySignature';
        // key / scale
        event.data?.push(this.data.readInt8());
        event.data?.push(this.data.readUInt8());
      } break;
      case 0x7F: {
        event.subtype = "SequencerSpecific";
        const _data = this.data.readBytes(length);
      } break;
      default: {
        console.warn(`Unknown meta event ${eventType.toString(16)} ${command.toString(16)} ${length}`);
        event.subtype = 'Unknown';
        if (length > 0)
          event.data?.push(this.data.readBytes(length));
      }
    }
 
    return event;
  }
 
  private sysexEvents(dtime: number, ttime: number, eventType: number): MidiEvent {
    const event: MidiEvent = {
      raw: eventType,
      abstime: ttime,
      time: dtime,
      type: 'SysEx',
      data: [],
    };
 
    const length = this.readVariableLen();
    const _data = this.data.readBytes(length);
    return event;
  }
 
  private midiEvents(dtime: number, ttime: number, command: number, lastEvent: number): MidiEvent {
    let useEvent = 0;
    let param = 0;

    // This is confusing... we need to keep track
    // of the last command, and if the current command &0x80 is not
    // set, then we need to use the last command. This is used to
    // save space in the midi file :-/
    if ((command & 0x80) === 0) {
      param = command;
      useEvent = lastEvent;
    } else {
      param = this.data.readUInt8();
      useEvent = command;
    }
 
    const event: MidiEvent = {
      raw: useEvent,
      time: dtime,
      abstime: ttime,
      type: 'Channel',
      data: [],
    };

    const cmd = ((useEvent & 0xF0) >> 4);
    const channel = ((useEvent & 0x0F));
    event.channel = channel;

    switch (cmd) {
      case 0x8: {
        event.subtype = 'NoteOff';
        const note = param;
        event.data?.push(note);
        const velocity = this.data.readUInt8();
        event.data?.push(velocity);
      } break;
      case 0x9: {
        const note = param;
        event.data?.push(note);
        const velocity = this.data.readUInt8();
        event.data?.push(velocity);
        if (velocity == 0)
          event.subtype = 'NoteOff';
        else
          event.subtype = 'NoteOn';
      } break;
      case 0xa: {
        event.subtype = 'NoteAfterTouch';
        event.data?.push(param);
        const amount = this.data.readUInt8();
        event.data?.push(amount);
      } break;
      case 0xb: {
        event.subtype = 'Controller';
        // controller number
        event.data?.push(param);
        // new value
        const value = this.data.readUInt8();
        event.data?.push(value);
      } break;
      case 0xc: {
        event.subtype = 'ProgramChange';
        // new program (patch) number
        const type = param;
        event.data?.push(type);
      } break;
      case 0xd: {
        event.subtype = 'ChannelAfterTouch';
        event.data?.push(param);
      } break;
      case 0xe: {
        event.subtype = 'PitchBend';
        // Pitch wheel change (2000H is normal or no change)
        // bb - bottom (least sig) 7 bits of value
        // tt - top (most sig) 7 bits of value
        const amount = param + (this.data.readUInt8() << 7);
        event.data?.push(amount);
      } break;
      default:
        console.warn(`[[UNKNOWN ${command.toString(16)}]]`);
    }
 
    return event;
  }
 
  /**
   * Reads a variable length variable assumes the data read
   * head is all set.
   */
  private readVariableLen(): number {
    const start = this.data.readUInt8();
    if ((start & 0x80) === 0) {
      return start;
    }

    let c = 0;
    let value = start & 0x7F;
    do {
      value = (value << 7) + ((c = this.data.readUInt8() & 0x7F));
    } while (c & 0);
 
    return value;
  }
}
 

/**
 * Load a midi from the server, and pass it through the 
 * sound system to try to setup the file for play
 */
export const loadMidi = (url: string): Promise<MIDI> => {
  return new Promise((resolve, reject) => {
    const headers = new Headers();
    headers.append('User-Agent', 'Andy/1.0');
    headers.append('Accept', 'audio/midi');
    const body = undefined;
    fetch(url, {
      method: 'GET',
      mode: 'cors',
      cache: 'reload',
      headers: headers,
      credentials: 'same-origin',
      redirect: 'follow',
      referrerPolicy: 'no-referrer',
      body: (body) ? JSON.stringify(body) : body,
    })
      .then(response => response.arrayBuffer())
      .then(response => {
        const mid = new MIDI(response);
        resolve(mid);
      }).catch(e => console.error(e));
  });
};