jevstrudel.git / packages / superdough / clockbridge.mjs

clockbridge.mjs Copyright (C) 2022 Strudel contributors - see https://codeberg.org/uzu/strudel/src/branch/main/packages/superdough/index.mjs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/.

thanks freya https://youtu.be/LSNQuFEDOyQ?si=ukZI2IGgWV_NDZzP&t=2979

8export function expDecay(a, b, decay, dt) {
9  return b + (a - b) * Math.exp(-decay * dt);
10}

translates between audio and performance clock

13export class ClockBridge {
14  p; // smoothed clock offset
15  lastTime;
16  audioContext;
17  constructor(audioContext) {
18    this.audioContext = audioContext;
19  }
20  // delta between audio and performance time in ms
21  getOffset() {
22    const { contextTime, performanceTime } = this.audioContext.getOutputTimestamp();
23    if (!contextTime || !performanceTime) {
24      return;
25    }
26    const offset = performanceTime - contextTime * 1000; // clock offset in ms
27    const dt = performanceTime - (this.lastTime ?? performanceTime); // delta time since last hap
28    const decay = 1 / 10000; // how fast offset changes have an effect
29    this.p = expDecay(this.p ?? offset, offset, decay, dt); // smooth clock offset
30    this.lastTime = performanceTime;
31    return this.p;
32  }
33  getPerformanceTime(audioContextTime) {
34    const offset = this.getOffset();
35    return audioContextTime * 1000 + offset; // this is now correct in performance time (ms)
36  }
37  getAudioContextTime(performanceTime) {
38    const offset = this.getOffset();
39    return (performanceTime - offset) / 1000; // this is now correct in audio context time (seconds)
40  }
41}