fixed osc clock

This commit is contained in:
Jade (Rose) Rowland 2024-08-11 12:40:38 -04:00
parent ac0dc7a8de
commit c2be2ed76a
5 changed files with 88 additions and 67 deletions

View file

@ -1,21 +1,10 @@
import { parseNumeral, Pattern, averageArray } from '@strudel/core';
import { parseNumeral, Pattern, ClockCollator } from '@strudel/core';
import { Invoke } from './utils.mjs';
import { getAudioContext } from '../superdough/superdough.mjs';
let offsetTime;
let timeAtPrevOffsetSample;
let prevOffsetTimes = [];
const collator = new ClockCollator({})
export const superdirtOutput = (hap, deadline, hapDuration, cps, targetTime) => {
const ctx = getAudioContext();
const currentTime = ctx.currentTime;
return oscTrigger(null, hap, currentTime, cps, targetTime)
}
async function oscTrigger(t_deprecate, hap, currentTime, cps = 1, targetTime) {
export async function oscTriggerTauri(t_deprecate, hap, currentTime, cps = 1, targetTime) {
hap.ensureObjectValue();
const cycle = hap.wholeOrPart().begin.valueOf();
const delta = hap.duration.valueOf();
@ -26,27 +15,7 @@ async function oscTrigger(t_deprecate, hap, currentTime, cps = 1, targetTime) {
const params = [];
const unixTimeSecs = Date.now() / 1000;
const newOffsetTime = unixTimeSecs - currentTime;
if (offsetTime == null) {
offsetTime = newOffsetTime;
}
prevOffsetTimes.push(newOffsetTime);
if (prevOffsetTimes.length > 8) {
prevOffsetTimes.shift();
}
// every two seconds, the average of the previous 8 offset times is calculated and used as a stable reference
// for calculating the timestamp that will be sent to the backend
if (timeAtPrevOffsetSample == null || unixTimeSecs - timeAtPrevOffsetSample > 2) {
timeAtPrevOffsetSample = unixTimeSecs;
const rollingOffsetTime = averageArray(prevOffsetTimes);
//account for the js clock freezing or resets set the new offset
if (Math.abs(rollingOffsetTime - offsetTime) > 0.01) {
offsetTime = rollingOffsetTime;
}
}
const timestamp = offsetTime + targetTime;
const timestamp = collator.calculateTimestamp(currentTime, targetTime)
Object.keys(controls).forEach((key) => {
const val = controls[key];
@ -71,5 +40,5 @@ async function oscTrigger(t_deprecate, hap, currentTime, cps = 1, targetTime) {
});
}
Pattern.prototype.osc = function () {
return this.onTrigger(oscTrigger);
return this.onTrigger(oscTriggerTauri);
};