All files / src/packlets/timing-engine index.ts

96.61% Statements 114/118
82% Branches 41/50
100% Functions 21/21
98.11% Lines 104/106

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                                                    2x                                                                                             772x       418x 418x 2x   416x 416x     416x 416x 1x   415x                         103x 103x   103x 77x         103x         103x 103x 103x 118x         118x 15x 15x         103x 103x     266x 266x 266x 18x 18x 14x   4x     266x         772x       4x     772x 772x 772x   772x       6x   766x       806x         92x 88x 88x   4x 4x 4x     92x 506x 506x     92x     103x   385x 385x 385x 385x       389x 389x   389x 389x 389x   386x 962x   962x       962x 962x   962x 6835x 6835x     962x     386x       22x 29x 19x 19x 19x       16x 20x 13x 13x 13x       29x 29x   29x 29x   29x   29x       29x 29x       6x 6x 6x     6x   6x     6x       9x 7x       7x 5x       2x 2x 2x 2x        
/**
 * @packageDocumentation
 *
 * Pure, headless timing engine for computing measure boundaries, snap grid
 * points, and pulse↔seconds conversion from BPM changes and time signature
 * events.
 *
 * All functions operate on plain numeric pulse positions. There is no
 * dependency on React, the DOM, or ECS entities.
 *
 * ## Design principles
 *
 * - **Measure-relative snap grid** — Snap points reset at every measure
 *   boundary, including interrupted measures.
 * - **Time signatures interrupt immediately** — A new time signature at pulse
 *   `P` starts a new measure at `P`, cutting the previous measure short.
 * - **BPM is independent from time signature** — Measure boundaries are
 *   determined solely by time signatures; BPM only affects real-time
 *   conversion.
 * - **Precomputed arrays with binary search** — Measure boundaries and BPM
 *   segments are stored as sorted arrays. Queries use binary search for
 *   O(log n) lookup.
 */
 
import { bisectLeft, bisectRight, bisectRightBy } from "../binary-search";
 
const PPQN = 240;
 
export interface BpmChange {
  pulse: number;
  bpm: number;
}
 
export interface TimeSignature {
  pulse: number;
  numerator: number;
  denominator: number;
}
 
export interface TimingEngine {
  /** Returns measure start pulses in `[start, end)`. */
  getMeasureBoundaries(range: { start: number; end: number }): number[];
 
  /** Returns snap grid points in `[start, end)` for the given snap setting. */
  getSnapPoints(snap: string, range: { start: number; end: number }): number[];
 
  /** Converts a pulse position to seconds using the piecewise BPM curve. */
  pulseToSeconds(pulse: number): number;
 
  /** Converts seconds to the corresponding pulse position. */
  secondsToPulse(seconds: number): number;
 
  /** Snaps a pulse to the nearest grid point for the given snap setting. */
  snapPulse(pulse: number, snap: string): number;
 
  /** Returns the measure index (0-based) and measure start pulse for the given pulse. */
  getMeasureAtPulse(pulse: number): {
    measureIndex: number;
    measureStart: number;
    measureEnd: number;
  };
 
  /** Returns the BPM active at the given pulse. */
  getBpmAtPulse(pulse: number): number;
 
  /** Returns the time signature active at the given pulse. */
  getTimeSignatureAtPulse(pulse: number): TimeSignature;
 
  /** Formats seconds as `MM:SS.mmm`. */
  formatTime(seconds: number): string;
}
 
function getMeasureLength(sig: TimeSignature): number {
  return (sig.numerator * 4 * PPQN) / sig.denominator;
}
 
function parseSnapInterval(snap: string): number {
  const match = snap.match(/^1\/(\d+)$/);
  if (!match) {
    throw new Error(`Invalid snap format: ${snap}`);
  }
  const n = parseInt(match[1], 10);
  Iif (n <= 0) {
    throw new Error(`Invalid snap denominator: ${n}`);
  }
  const interval = (4 * PPQN) / n;
  if (!Number.isInteger(interval)) {
    throw new Error(`Snap ${snap} does not produce an integer pulse interval`);
  }
  return interval;
}
 
interface BpmSegment {
  startPulse: number;
  startSeconds: number;
  bpm: number;
}
 
export function createTimingEngine(
  bpmChanges: BpmChange[],
  timeSignatures: TimeSignature[],
): TimingEngine {
  const sortedBpms = [...bpmChanges].sort((a, b) => a.pulse - b.pulse);
  const sortedSigs = [...timeSignatures].sort((a, b) => a.pulse - b.pulse);
 
  if (sortedBpms.length === 0) {
    sortedBpms.push({ pulse: 0, bpm: 60 });
  }
 
  // Implicit 4/4 at pulse 0 when no explicit signature is present.
  const effectiveSigs: TimeSignature[] =
    sortedSigs.length > 0 && sortedSigs[0].pulse === 0
      ? sortedSigs
      : [{ pulse: 0, numerator: 4, denominator: 4 }, ...sortedSigs];
 
  // Precompute BPM segments.
  const bpmSegments: BpmSegment[] = [];
  let accumulatedSeconds = 0;
  for (let i = 0; i < sortedBpms.length; i++) {
    bpmSegments.push({
      startPulse: sortedBpms[i].pulse,
      startSeconds: accumulatedSeconds,
      bpm: sortedBpms[i].bpm,
    });
    if (i + 1 < sortedBpms.length) {
      const deltaPulse = sortedBpms[i + 1].pulse - sortedBpms[i].pulse;
      accumulatedSeconds += (deltaPulse / PPQN) * (60 / sortedBpms[i].bpm);
    }
  }
 
  // Lazily-computed measure boundaries.
  const boundaries: number[] = [];
  let boundariesComputedUpTo = -Infinity;
 
  function findSigIndex(pulse: number): number {
    let lo = 0;
    let hi = effectiveSigs.length - 1;
    while (lo < hi) {
      const mid = Math.floor((lo + hi + 1) / 2);
      if (effectiveSigs[mid].pulse <= pulse) {
        lo = mid;
      } else {
        hi = mid - 1;
      }
    }
    return lo;
  }
 
  function computeNextBoundary(measureStart: number, sigIndex: number): [number, number] {
    // Advance to the time signature active at this measure start.
    while (
      sigIndex + 1 < effectiveSigs.length &&
      effectiveSigs[sigIndex + 1].pulse <= measureStart
    ) {
      sigIndex++;
    }
 
    const sig = effectiveSigs[sigIndex];
    const length = getMeasureLength(sig);
    const nextMeasureStart = measureStart + length;
 
    if (
      sigIndex + 1 < effectiveSigs.length &&
      effectiveSigs[sigIndex + 1].pulse < nextMeasureStart
    ) {
      return [effectiveSigs[sigIndex + 1].pulse, sigIndex + 1];
    }
    return [nextMeasureStart, sigIndex];
  }
 
  function ensureBoundariesUpTo(targetPulse: number) {
    if (targetPulse < boundariesComputedUpTo) return;
 
    let measureStart: number;
    let sigIndex: number;
 
    if (boundaries.length === 0) {
      measureStart = effectiveSigs[0].pulse;
      sigIndex = 0;
    } else {
      measureStart = boundaries[boundaries.length - 1];
      sigIndex = findSigIndex(measureStart);
      [measureStart, sigIndex] = computeNextBoundary(measureStart, sigIndex);
    }
 
    while (measureStart <= targetPulse) {
      boundaries.push(measureStart);
      [measureStart, sigIndex] = computeNextBoundary(measureStart, sigIndex);
    }
 
    boundariesComputedUpTo = measureStart;
  }
 
  return {
    getMeasureBoundaries({ start, end }) {
      ensureBoundariesUpTo(end);
      const left = bisectLeft(boundaries, start);
      const right = bisectLeft(boundaries, end);
      return boundaries.slice(left, right);
    },
 
    getSnapPoints(snap, { start, end }) {
      const interval = parseSnapInterval(snap);
      ensureBoundariesUpTo(end);
 
      const points: number[] = [];
      let measureIdx = bisectRight(boundaries, start) - 1;
      Iif (measureIdx < 0) measureIdx = 0;
 
      while (measureIdx < boundaries.length && boundaries[measureIdx] < end) {
        const measureStart = boundaries[measureIdx];
        const measureEnd =
          measureIdx + 1 < boundaries.length
            ? boundaries[measureIdx + 1]
            : computeNextBoundary(measureStart, findSigIndex(measureStart))[0];
 
        const rangeStart = Math.max(start, measureStart);
        let point = measureStart + Math.ceil((rangeStart - measureStart) / interval) * interval;
 
        while (point < Math.min(end, measureEnd)) {
          points.push(point);
          point += interval;
        }
 
        measureIdx++;
      }
 
      return points;
    },
 
    pulseToSeconds(pulse) {
      if (pulse <= 0) return 0;
      const idx = Math.max(0, bisectRightBy(bpmSegments, pulse, (s) => s.startPulse) - 1);
      const seg = bpmSegments[idx];
      const deltaPulse = pulse - seg.startPulse;
      return seg.startSeconds + (deltaPulse / PPQN) * (60 / seg.bpm);
    },
 
    secondsToPulse(seconds) {
      if (seconds <= 0) return 0;
      const idx = bisectRightBy(bpmSegments, seconds, (s) => s.startSeconds) - 1;
      const seg = bpmSegments[idx];
      const remaining = seconds - seg.startSeconds;
      return seg.startPulse + (remaining / (60 / seg.bpm)) * PPQN;
    },
 
    snapPulse(pulse, snap) {
      const interval = parseSnapInterval(snap);
      ensureBoundariesUpTo(pulse);
 
      const measureIdx = bisectRight(boundaries, pulse) - 1;
      Iif (measureIdx < 0) return 0;
 
      const measureStart = boundaries[measureIdx];
      const measureEnd =
        measureIdx + 1 < boundaries.length
          ? boundaries[measureIdx + 1]
          : computeNextBoundary(measureStart, findSigIndex(measureStart))[0];
 
      const snapped = measureStart + Math.round((pulse - measureStart) / interval) * interval;
      return Math.max(measureStart, Math.min(snapped, measureEnd - interval));
    },
 
    getMeasureAtPulse(pulse) {
      ensureBoundariesUpTo(pulse);
      const measureIdx = bisectRight(boundaries, pulse) - 1;
      Iif (measureIdx < 0) {
        return { measureIndex: 0, measureStart: 0, measureEnd: boundaries[0] ?? 0 };
      }
      const measureStart = boundaries[measureIdx];
      const measureEnd =
        measureIdx + 1 < boundaries.length
          ? boundaries[measureIdx + 1]
          : computeNextBoundary(measureStart, findSigIndex(measureStart))[0];
      return { measureIndex: measureIdx, measureStart, measureEnd };
    },
 
    getBpmAtPulse(pulse) {
      const idx = Math.max(0, bisectRightBy(bpmSegments, pulse, (s) => s.startPulse) - 1);
      return bpmSegments[idx]?.bpm ?? 60;
    },
 
    getTimeSignatureAtPulse(pulse) {
      const idx = Math.max(0, bisectRightBy(effectiveSigs, pulse, (s) => s.pulse) - 1);
      return effectiveSigs[idx] ?? { pulse: 0, numerator: 4, denominator: 4 };
    },
 
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      const ms = Math.floor((seconds % 1) * 1000);
      return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}.${String(ms).padStart(3, "0")}`;
    },
  };
}