All files / src/components/music/helpers emulator.ts

0% Statements 0/112
0% Branches 0/28
0% Functions 0/12
0% Lines 0/87

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                                                                                                                                                                                                                                                                                                                                                                                   
import { Binjgb, BinjgbModule } from "./WasmModuleWrapper";
 
type StepType = "single" | "frame" | "run";
 
type Emu = number | undefined;
 
type Emulator = {
  HEAP8: Uint8Array;
  _free: (value: number) => void;
  _malloc: (value: number) => number;
  _emulator_new_simple: (
    romPtr: number,
    romSize: number,
    sampleRate: number,
    audioBufferSize: number
  ) => Emu;
  _emulator_delete: (emu: Emu) => void;
  _emulator_get_ticks_f64: (emu: Emu) => number;
  _emulator_run_until_f64: (emu: Emu, ticks: number) => number;
  _emulator_read_mem: (emu: Emu, addr: number) => number;
  _emulator_write_mem: (emu: Emu, addr: number, value: number) => void;
  _set_audio_channel_mute: (
    emu: Emu,
    channel: number,
    muted: boolean
  ) => boolean;
  _get_audio_buffer_ptr: (emu: Emu) => number;
  _get_audio_buffer_capacity: (emu: Emu) => number;
};
 
let emu: Emu;
let romPtr: number;
let romSize = 0;
let audioCtx: AudioContext;
let audioTime: number;
 
const audioBufferSize = 2048;
 
/* see: 
  https://gist.github.com/surma/b2705b6cca29357ebea1c9e6e15684cc
  https://github.com/webpack/webpack/issues/7352
*/
const locateFile = (module: unknown) => (path: string) => {
  Iif (path.endsWith(".wasm")) {
    return module;
  }
  return path;
};
 
let Module: Emulator;
Binjgb({
  locateFile: locateFile(BinjgbModule),
}).then((module: Emulator) => {
  Module = module;
});
 
const init = (romData: Uint8Array) => {
  console.log("INIT EMULATOR");
  Iif (isAvailable()) destroy();
 
  Iif (typeof audioCtx == "undefined") audioCtx = new AudioContext();
 
  let requiredSize = ((romData.length - 1) | 0x3fff) + 1;
  Iif (requiredSize < 0x8000) requiredSize = 0x8000;
  Iif (romSize < requiredSize) {
    Iif (typeof romPtr != "undefined") Module._free(romPtr);
    romPtr = Module._malloc(requiredSize);
    romSize = requiredSize;
  }
  for (let n = 0; n < romSize; n++) Module.HEAP8[romPtr + n] = 0;
  for (let n = 0; n < romData.length; n++)
    Module.HEAP8[romPtr + n] = romData[n];
 
  emu = Module._emulator_new_simple(
    romPtr,
    romSize,
    audioCtx.sampleRate,
    audioBufferSize
  );
  audioCtx.resume();
  audioTime = audioCtx.currentTime;
};
 
const updateRom = (romData: Uint8Array) => {
  Iif (!isAvailable()) {
    console.log("UPDATE ROM: NOT AVAILABLE");
    return false;
  }
 
  let requiredSize = ((romData.length - 1) | 0x3fff) + 1;
  Iif (requiredSize < 0x8000) requiredSize = 0x8000;
  Iif (romSize < requiredSize) return false;
  for (let n = 0; n < romSize; n++) Module.HEAP8[romPtr + n] = 0;
  for (let n = 0; n < romData.length; n++)
    Module.HEAP8[romPtr + n] = romData[n];
  return true;
};
 
const destroy = () => {
  Iif (!isAvailable()) return;
  Module._emulator_delete(emu);
  emu = undefined;
};
 
const isAvailable = () => typeof emu != "undefined";
 
const step = (stepType: StepType) => {
  Iif (!isAvailable()) return;
  let ticks = Module._emulator_get_ticks_f64(emu);
  if (stepType === "single") ticks += 1;
  else Iif (stepType === "frame") ticks += 70224;
  while (true) {
    const result = Module._emulator_run_until_f64(emu, ticks);
    Iif (result & 2) processAudioBuffer();
    Iif (result & 8)
      // Breakpoint hit
      return true;
    Iif (result & 16)
      // Illegal instruction
      return true;
    Iif (result !== 2 && stepType !== "run") return false;
    Iif (stepType === "run") {
      Iif (result & 4) {
        // Sync to the audio buffer, make sure we have 100ms of audio data buffered.
        if (audioTime < audioCtx.currentTime + 0.1) ticks += 70224;
        else return false;
      }
    }
  }
};
 
const readMem = (addr: number) => {
  Iif (!isAvailable()) return 0xff;
  return Module._emulator_read_mem(emu, addr);
};
 
const writeMem = (addr: number, data: number) => {
  Iif (!isAvailable()) {
    console.log("WRITE MEM NOT AVAILABLE");
    return;
  }
  console.log("WRITE MEM", addr, data);
  return Module._emulator_write_mem(emu, addr, data);
};
 
const setChannel = (channel: number, muted: boolean) => {
  Iif (!isAvailable()) return muted;
  return Module._set_audio_channel_mute(emu, channel, muted);
};
 
function processAudioBuffer() {
  Iif (audioTime < audioCtx.currentTime) audioTime = audioCtx.currentTime;
 
  const inputBuffer = new Uint8Array(
    Module.HEAP8.buffer,
    Module._get_audio_buffer_ptr(emu),
    Module._get_audio_buffer_capacity(emu)
  );
  const volume = 0.5;
  const buffer = audioCtx.createBuffer(2, audioBufferSize, audioCtx.sampleRate);
  const channel0 = buffer.getChannelData(0);
  const channel1 = buffer.getChannelData(1);
 
  for (let i = 0; i < audioBufferSize; i++) {
    channel0[i] = (inputBuffer[2 * i] * volume) / 255;
    channel1[i] = (inputBuffer[2 * i + 1] * volume) / 255;
  }
  const bufferSource = audioCtx.createBufferSource();
  bufferSource.buffer = buffer;
  bufferSource.connect(audioCtx.destination);
  bufferSource.start(audioTime);
  const bufferSec = audioBufferSize / audioCtx.sampleRate;
  audioTime += bufferSec;
}
 
const emulator = {
  init,
  writeMem,
  readMem,
  step,
  updateRom,
  setChannel,
};
 
export default emulator;