All files / src/midi player.ts

32.6% Statements 45/138
1.66% Branches 1/60
30.76% Functions 4/13
33.07% Lines 43/130

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  1x 1x 1x 1x 1x 1x 1x 1x 1x   4x   4x           4x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 832x   52x           52x     4x 4x   1x       1x 1x 1x     1x 1x                     1x                                   1x                               1x   1x 13x     1x                                                                                                                                                                                                                               1x                                                                                      
import { SoundSystem } from "../digital/audio";
import { Format, MIDI } from "./song";
import { GeneralMidiInstruments, GeneralMIDIPercussion, noteByMidi } from "../midi/types";
import { createPlayHeadClock, toSignature, createTempo, PerTickCallback, TickCallbackContainer } from "../metronome";
import { patchPlayer } from "./audio";
import { AndyPatch, AndyPercussionPatch } from './patchBank';
import { SoundOn, SoundOff, NoOp, Tracker, Track } from "../digital/types";
 
const MAX_CHANNELS = 16;
 
type MidiSong = {
  /*I* the "raw" midi song (with events, etc) */
  song: MIDI;
}
 
export type MidiWithTracks = MidiSong & Tracker;
 
export type MidiRun = MidiWithTracks & TickCallbackContainer;
 
export function createRun(system: SoundSystem, song: MIDI): MidiRun {
  if (song.format === Format.MultiAsync)
    throw new Error("Currently only support synchronous tracks");
 
  const run: MidiRun = {
    song: song,
    tracks: [],
    output: system.context().createGain(),
    tickListeners: []
  };
 
  for (let i = 0; i < song.numberOfTracks; i++) {
    const pan = system.context().createPanner();
    pan.orientationX.setValueAtTime(0, 0);
    pan.orientationY.setValueAtTime(0, 0);
    pan.orientationZ.setValueAtTime(-1, 0);
    pan.positionX.setValueAtTime(0, 0);
    pan.positionY.setValueAtTime(1, 0);
    pan.positionZ.setValueAtTime(0, 0);
 
    const vol = system.context().createGain();
    pan.connect(vol);
    vol.connect(run.output);
 
    vol.gain.setValueAtTime(1, 0);
 
    const startFns = new Array<Array<SoundOff>>(MAX_CHANNELS);
    for (let i = 0; i < MAX_CHANNELS; i++) {
      startFns[i] = []; // NoOp;
    }
 
    const t = {
      lastFn: startFns,
      idx: 0,
      vol,
      pan,
    } as Track;
 
    run.tracks.push(t);
  }

  // connect the song output to the speakers
  run.output.connect(system.masterGainNode());
  return run;
}

/** Clean up after the song run has played */
export function destroyRun(system: SoundSystem, run: MidiRun) {
  // TODO: disconnect tracks?
  run.output.disconnect(system.masterGainNode());
  while (run.tickListeners.length) {
    run.tickListeners.pop();
  }
}
 
const useInstrument = (system: SoundSystem, run: MidiRun, patchNum: number): SoundOn => {
  const patch = AndyPatch.get(patchNum);
  if (patch)
    return patchPlayer(system, patch);
  else {
    const p = AndyPatch.get(GeneralMidiInstruments.ChurchOrgan);
    if (p)
      return patchPlayer(system, p);
  }
 
  return (NoOp as any) as SoundOn;
};
 
const usePercussion = (system: SoundSystem, run: MidiRun, patchNum: number): SoundOn => {
  const patch = AndyPercussionPatch.get(patchNum);
  if (patch)
    return patchPlayer(system, patch);
 
  return (NoOp as any) as SoundOn;
};

export function silenceRun(songRun: MidiRun) {
  songRun.tracks.forEach(track => {
    for (let i = 0; i < MAX_CHANNELS; i++) {
      const fns = track.lastFn[i];
      while (fns.length) {
        const soundOff = fns.pop();
        if (soundOff) soundOff();
      }
    }
  });
}
 
export function setRunTimeTo(time: number, songRun: MidiRun) {
  const len = songRun.song.tracks.length;
 
  for (let t = 0; t < len; t++) {
    const elen = songRun.song.tracks[t].events.length;
    // Set the track index to the index closest to the time
    // we are asked to.
    for (let e = 0; e < elen; e++) {
      const abstime = songRun.song.tracks[t].events[e].abstime;
      if (abstime >= time) {
        songRun.tracks[t].idx = e;
        break;
      }
    }
  }
}

export function rewindRun(songRun: MidiRun) {
  songRun.tracks.forEach(track => {
    track.idx = 0;
  });
}

// TODO: this needs, not only a refactor, but for V2 this should go back
// to sending out raw midi events so the whole thing needs
function handleEventCallback(system: SoundSystem, run: MidiRun): PerTickCallback {
  let tempo = createTempo(run.song.ticksPerQuarterNote, 500000);
  let sig = toSignature("4/4");
 
  const tickCallBack: PerTickCallback = (tick, time, bi) => {
    const trackLen = run.song.tracks.length

    const stopAllSounds = (track: Track) => {
      for (let i = 0; i < MAX_CHANNELS; i++) {
        const fns = track.lastFn[i];
        while (fns.length) {
          const soundOff = fns.pop();
          if (soundOff) soundOff();
        }
      }
    }

    // go through all tracks...
    for (let t = 0; t < trackLen; t++) {
      const track = run.tracks[t];
      const events = run.song.tracks[t].events;

      // go through all events in the track, starting from the last
      // index we saw
      for (let e = track.idx; e < events.length; e++) {
        const ce = events[e];
 
        // if the abstime is not this tick, then get out of this
        // loop and set it to check next time
        if (ce.abstime !== tick) {
          track.idx = e;
          break;
        }
 
        if (ce.type === "Meta") {
          if (ce.subtype === "SetTempo") {
            // TODO: immutable?
            tempo = createTempo(tempo.ppq, ce.data[0] as number);
          }

          if (ce.subtype === "TimeSignature") {
            sig.noteBeats = ce.data[0] as number;
            sig.perMeasure = ce.data[1] as number;
            sig.ticksInMetronome = ce.data[2] as number;
            sig.toQuarter32nd = ce.data[3] as number;
          }
        }
 
        if (ce.type === "Channel") {
          if (ce.subtype === "ProgramChange") {
            track.instrument = useInstrument(system, run, ce.data[0] as number);
          }

          if (ce.subtype === "Controller") {
            // Volume
            if (ce.data[0] === 0x7) {
              track.vol.gain.setValueAtTime(
                (ce.data[1] as number / 127),
                time
              );
            }
            //Pan
            if (ce.data[0] === 0xa) {
              const amt = (ce.data[1] as number - 127 + 63.5) / 63.5;
              // Pan is really sensitive so dumb it down a lot.
              const amtScaled = Math.round(amt * 10) / 10;
              track.pan.positionX.setValueAtTime(amtScaled, time);
            }
          }
 
          if (ce.subtype === "NoteOff") {
            const fns = track.lastFn[ce.channel ?? 0];
            while (fns.length) {
              const soundOff = fns.pop();
              if (soundOff) soundOff();
            }
          }
 
          if (ce.subtype === "NoteOn") {
            // @ts-ignore
            const mnote = ce.data[0] ?? 60;
            const note = noteByMidi(mnote as number);
 
            // Drums
            if (ce.channel === 0x9) {
              track.lastFn[ce.channel].push(
                usePercussion(system, run, mnote as number)
                  (note, system.currentTime(), track.pan)
              );
            } else {
              if (track.instrument) {
                // lame version of velocity
                track.vol.gain.setValueAtTime(
                  (ce.data[1] as number / 127), system.currentTime()
                );
                track.lastFn[ce.channel ?? 0].push(
                  track.instrument(note, system.currentTime(), track.pan)
                );
              } else {
                console.warn(`NoteOn event, but no instrument selected. Channel ${ce.channel ?? 0} Track ${t} Event ${e}`);
              }
            }
          }
 
          if (ce.subtype === "EndOfTrack") {
            stopAllSounds(track);
          }
        }
      }
    }
 
    return [tempo, sig]
  }
 
  return tickCallBack;
}
 
/**
 * Sets up the default tempo and signature, and also starts
 * the metronome timer for use in playback and events. Once
 * this is done, you should call `playHeadToggle()` to start
 * the actual song playing.
 */
export function insertRun(system: SoundSystem, run: MidiRun) {
  // default 120bpm
  let tempo = createTempo(run.song.ticksPerQuarterNote, 500000);
  let sig = toSignature("4/4");
 
  run.tickListeners.push(handleEventCallback(system, run));
 
  createPlayHeadClock(system, tempo, sig, run);
}