All files / src/shared/lib/uge ugiHelper.ts

96.13% Statements 149/155
86% Branches 86/100
92.31% Functions 12/13
97.87% Lines 138/141

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                          2x         2x 33x 33x 33x   33x 2277x 2277x   33x 8745x 8745x   33x 33x 33x 33x 33x 33x     33x 33x 33x 2112x 2112x 2112x 2112x 2112x 2112x       33x 18x 18x 18x 18x 18x 18x 18x         18x 18x 18x 18x 18x 18x 18x 18x 15x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   8x 8x 8x 8x 8x 8x 8x         8x 8x 8x 8x 8x 8x 8x 8x     33x               2x 31x 1x         30x       30x   30x   30x 6030x 6030x 6030x   30x 2070x   30x 30x 30x 30x 30x   30x 30x     30x 30x 30x 30x 30x 30x 30x 30x 30x 30x   30x 30x 30x 30x   30x 30x 30x 30x 30x   30x 30x 1920x 1920x 1920x 1920x 1920x   1920x               30x         30x 16x                     16x 14x 6x               6x 8x 7x                 7x   1x           2x 34x   2x 16x   2x 1x         2x              
import {
  DutyInstrument,
  NoiseInstrument,
  SubPatternCell,
  WaveInstrument,
} from "./types";
 
export type UGIInstrument = DutyInstrument | WaveInstrument | NoiseInstrument;
 
// A .ugi file is a raw binary dump of a single TInstrumentV3 struct from
// hUGETracker - identical to one instrument block in a .uge v6 file.
// Total size: 4 + 256 + 4 + 1 + 1 + 4 + 1 + 4 + 4 + 4 + 1 + 4 + 4 + 4 + 1
//             + 64 * (4 + 4 + 4 + 4 + 1) = 1385 bytes
export const UGI_INSTRUMENT_SIZE = 1385;
 
/**
 * Serialize a single instrument to the hUGETracker .ugi binary format.
 */
export const saveUGIInstrument = (instrument: UGIInstrument): Buffer => {
  const buffer = new ArrayBuffer(UGI_INSTRUMENT_SIZE);
  const view = new DataView(buffer);
  let idx = 0;
 
  const addUint8 = (value: number) => {
    view.setUint8(idx, value);
    idx += 1;
  };
  const addUint32 = (value: number) => {
    view.setUint32(idx, value, true);
    idx += 4;
  };
  const addShortString = (s: string) => {
    view.setUint8(idx, s.length);
    idx += 1;
    const te = new TextEncoder();
    te.encodeInto(s, new Uint8Array(buffer, idx, idx + 255));
    idx += 255;
  };
 
  const addSubpattern = (i: UGIInstrument) => {
    addUint8(i.subpatternEnabled ? 1 : 0);
    for (let n = 0; n < 64; n++) {
      const cell = i.subpattern[n];
      addUint32(cell?.note ?? 90);
      addUint32(0); // unused field (Instrument in TCellV2)
      addUint32(cell?.jump ?? 0);
      addUint32(cell?.effectCode ?? 0);
      addUint8(cell?.effectParam ?? 0);
    }
  };
 
  if (isDutyInstrument(instrument)) {
    addUint32(0); // type: duty/square
    addShortString(instrument.name || "");
    addUint32(instrument.length !== null ? 64 - instrument.length : 0);
    addUint8(instrument.length === null ? 0 : 1);
    addUint8(instrument.initialVolume);
    addUint32(instrument.volumeSweepChange < 0 ? 1 : 0);
    addUint8(
      instrument.volumeSweepChange !== 0
        ? 8 - Math.abs(instrument.volumeSweepChange)
        : 0,
    );
    addUint32(instrument.frequencySweepTime);
    addUint32(instrument.frequencySweepShift < 0 ? 1 : 0);
    addUint32(Math.abs(instrument.frequencySweepShift));
    addUint8(instrument.dutyCycle);
    addUint32(0); // waveOutputLevel (unused for duty)
    addUint32(0); // waveWaveformIndex (unused for duty)
    addUint32(0); // counterStep (unused for duty)
    addSubpattern(instrument);
  } else if (isWaveInstrument(instrument)) {
    addUint32(1); // type: wave
    addShortString(instrument.name || "");
    addUint32(instrument.length !== null ? 256 - instrument.length : 0);
    addUint8(instrument.length === null ? 0 : 1);
    addUint8(0); // initialVolume (unused for wave)
    addUint32(0); // volumeDirection (unused for wave)
    addUint8(0); // volumeSweepAmount (unused for wave)
    addUint32(0); // freqSweepTime (unused for wave)
    addUint32(0); // freqSweepDirection (unused for wave)
    addUint32(0); // freqSweepShift (unused for wave)
    addUint8(0); // duty (unused for wave)
    addUint32(instrument.volume);
    addUint32(instrument.waveIndex);
    addUint32(0); // counterStep (unused for wave)
    addSubpattern(instrument);
  } else {
    addUint32(2); // type: noise
    addShortString(instrument.name || "");
    addUint32(instrument.length !== null ? 64 - instrument.length : 0);
    addUint8(instrument.length === null ? 0 : 1);
    addUint8(instrument.initialVolume);
    addUint32(instrument.volumeSweepChange < 0 ? 1 : 0);
    addUint8(
      instrument.volumeSweepChange !== 0
        ? 8 - Math.abs(instrument.volumeSweepChange)
        : 0,
    );
    addUint32(0); // freqSweepTime (unused for noise)
    addUint32(0); // freqSweepDirection (unused for noise)
    addUint32(0); // freqSweepShift (unused for noise)
    addUint8(0); // duty (unused for noise)
    addUint32(0); // waveOutputLevel (unused for noise)
    addUint32(0); // waveWaveformIndex (unused for noise)
    addUint32(instrument.bitCount === 7 ? 1 : 0);
    addSubpattern(instrument);
  }
 
  return Buffer.from(buffer);
};
 
/**
 * Parse a single instrument from a hUGETracker .ugi binary buffer.
 * Returns a typed instrument (DutyInstrument | WaveInstrument | NoiseInstrument).
 * Throws if the buffer is too small or contains an invalid instrument type.
 */
export const loadUGIInstrument = (buffer: Buffer): UGIInstrument => {
  if (buffer.byteLength < UGI_INSTRUMENT_SIZE) {
    throw new Error(
      `UGI buffer too small: expected at least ${UGI_INSTRUMENT_SIZE} bytes, got ${buffer.byteLength}`,
    );
  }
 
  const data = buffer.buffer.slice(
    buffer.byteOffset,
    buffer.byteOffset + buffer.byteLength,
  ) as ArrayBuffer;
  const uint8data = new Uint8Array(data);
 
  let offset = 0;
 
  const readUint32 = (): number => {
    const val = new DataView(data).getUint32(offset, true);
    offset += 4;
    return val;
  };
  const readUint8 = (): number => {
    return uint8data[offset++];
  };
  const readText = (): string => {
    const len = uint8data[offset];
    let text = "";
    if (len > 0) {
      text = new TextDecoder().decode(data.slice(offset + 1, offset + 1 + len));
    }
    offset += 256;
    return text;
  };
 
  const type = readUint32();
  const name = readText();
  const length = readUint32();
  const lengthEnabled = readUint8();
  let initialVolume = readUint8();
  Iif (initialVolume > 15) initialVolume = 15;
  const volumeDirection = readUint32();
  let volumeSweepAmount = readUint8();
  if (volumeSweepAmount !== 0) volumeSweepAmount = 8 - volumeSweepAmount;
  if (volumeDirection) volumeSweepAmount = -volumeSweepAmount;
 
  const freqSweepTime = readUint32();
  const freqSweepDirection = readUint32();
  let freqSweepShift = readUint32();
  if (freqSweepDirection) freqSweepShift = -freqSweepShift;
 
  const duty = readUint8();
  const waveOutputLevel = readUint32();
  const waveWaveformIndex = readUint32();
  const noiseCounterStep = readUint32();
  const subpatternEnabled = readUint8();
 
  const subpattern: SubPatternCell[] = [];
  for (let n = 0; n < 64; n++) {
    const note = readUint32();
    offset += 4; // skip unused Instrument field (TCellV2)
    const jump = readUint32();
    const effectCode = readUint32();
    const effectParam = readUint8();
 
    subpattern.push({
      note: note === 90 ? null : note,
      jump,
      effectCode: effectCode === 0 && effectParam === 0 ? null : effectCode,
      effectParam: effectCode === 0 && effectParam === 0 ? null : effectParam,
    });
  }
 
  const subpatternData = {
    subpatternEnabled: subpatternEnabled !== 0,
    subpattern,
  };
 
  if (type === 0) {
    const instr: DutyInstrument = {
      index: 0,
      name,
      length: lengthEnabled ? 64 - length : null,
      dutyCycle: duty,
      initialVolume,
      volumeSweepChange: volumeSweepAmount,
      frequencySweepTime: freqSweepTime,
      frequencySweepShift: freqSweepShift,
      ...subpatternData,
    };
    return instr;
  } else if (type === 1) {
    const instr: WaveInstrument = {
      index: 0,
      name,
      length: lengthEnabled ? 256 - length : null,
      volume: waveOutputLevel,
      waveIndex: waveWaveformIndex,
      ...subpatternData,
    };
    return instr;
  } else if (type === 2) {
    const instr: NoiseInstrument = {
      index: 0,
      name,
      length: lengthEnabled ? 64 - length : null,
      initialVolume,
      volumeSweepChange: volumeSweepAmount,
      bitCount: noiseCounterStep ? 7 : 15,
      ...subpatternData,
    };
    return instr;
  } else {
    throw new Error(`Invalid UGI instrument type: ${type}`);
  }
};
 
// Type guards
 
export const isDutyInstrument = (i: UGIInstrument): i is DutyInstrument =>
  "dutyCycle" in i;
 
export const isWaveInstrument = (i: UGIInstrument): i is WaveInstrument =>
  "waveIndex" in i;
 
export const isNoiseInstrument = (i: UGIInstrument): i is NoiseInstrument =>
  "bitCount" in i;
 
/**
 * Returns the instrument type string for a given UGIInstrument.
 */
export const ugiInstrumentType = (
  i: UGIInstrument,
): "duty" | "wave" | "noise" => {
  Iif (isDutyInstrument(i)) return "duty";
  Iif (isWaveInstrument(i)) return "wave";
  return "noise";
};