/
TickSource.ts
338 lines (301 loc) · 10.2 KB
/
TickSource.ts
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { ToneWithContext, ToneWithContextOptions } from "../context/ToneWithContext";
import { Seconds, Ticks, Time } from "../type/Units";
import { optionsFromArguments } from "../util/Defaults";
import { readOnly } from "../util/Interface";
import { PlaybackState, StateTimeline, StateTimelineEvent } from "../util/StateTimeline";
import { Timeline } from "../util/Timeline";
import { isDefined } from "../util/TypeCheck";
import { TickSignal } from "./TickSignal";
import { EQ } from "../util/Math";
interface TickSourceOptions extends ToneWithContextOptions {
frequency: number;
units: "bpm" | "hertz";
}
interface TickSourceOffsetEvent {
ticks: number;
time: number;
seconds: number;
}
/**
* Uses [TickSignal](TickSignal) to track elapsed ticks with complex automation curves.
*/
export class TickSource<TypeName extends "bpm" | "hertz"> extends ToneWithContext<TickSourceOptions> {
readonly name: string = "TickSource";
/**
* The frequency the callback function should be invoked.
*/
readonly frequency: TickSignal<TypeName>;
/**
* The state timeline
*/
private _state: StateTimeline = new StateTimeline();
/**
* The offset values of the ticks
*/
private _tickOffset: Timeline<TickSourceOffsetEvent> = new Timeline();
/**
* @param frequency The initial frequency that the signal ticks at
*/
constructor(frequency?: number);
constructor(options?: Partial<TickSourceOptions>);
constructor() {
super(optionsFromArguments(TickSource.getDefaults(), arguments, ["frequency"]));
const options = optionsFromArguments(TickSource.getDefaults(), arguments, ["frequency"]);
this.frequency = new TickSignal({
context: this.context,
units: options.units as TypeName,
value: options.frequency,
});
readOnly(this, "frequency");
// set the initial state
this._state.setStateAtTime("stopped", 0);
// add the first event
this.setTicksAtTime(0, 0);
}
static getDefaults(): TickSourceOptions {
return Object.assign({
frequency: 1,
units: "hertz" as "hertz",
}, ToneWithContext.getDefaults());
}
/**
* Returns the playback state of the source, either "started", "stopped" or "paused".
*/
get state(): PlaybackState {
return this.getStateAtTime(this.now());
}
/**
* Start the clock at the given time. Optionally pass in an offset
* of where to start the tick counter from.
* @param time The time the clock should start
* @param offset The number of ticks to start the source at
*/
start(time: Time, offset?: Ticks): this {
const computedTime = this.toSeconds(time);
if (this._state.getValueAtTime(computedTime) !== "started") {
this._state.setStateAtTime("started", computedTime);
if (isDefined(offset)) {
this.setTicksAtTime(offset, computedTime);
}
}
return this;
}
/**
* Stop the clock. Stopping the clock resets the tick counter to 0.
* @param time The time when the clock should stop.
*/
stop(time: Time): this {
const computedTime = this.toSeconds(time);
// cancel the previous stop
if (this._state.getValueAtTime(computedTime) === "stopped") {
const event = this._state.get(computedTime);
if (event && event.time > 0) {
this._tickOffset.cancel(event.time);
this._state.cancel(event.time);
}
}
this._state.cancel(computedTime);
this._state.setStateAtTime("stopped", computedTime);
this.setTicksAtTime(0, computedTime);
return this;
}
/**
* Pause the clock. Pausing does not reset the tick counter.
* @param time The time when the clock should stop.
*/
pause(time: Time): this {
const computedTime = this.toSeconds(time);
if (this._state.getValueAtTime(computedTime) === "started") {
this._state.setStateAtTime("paused", computedTime);
}
return this;
}
/**
* Cancel start/stop/pause and setTickAtTime events scheduled after the given time.
* @param time When to clear the events after
*/
cancel(time: Time): this {
time = this.toSeconds(time);
this._state.cancel(time);
this._tickOffset.cancel(time);
return this;
}
/**
* Get the elapsed ticks at the given time
* @param time When to get the tick value
* @return The number of ticks
*/
getTicksAtTime(time?: Time): Ticks {
const computedTime = this.toSeconds(time);
const stopEvent = this._state.getLastState("stopped", computedTime) as StateTimelineEvent;
// this event allows forEachBetween to iterate until the current time
const tmpEvent: StateTimelineEvent = { state: "paused", time: computedTime };
this._state.add(tmpEvent);
// keep track of the previous offset event
let lastState = stopEvent;
let elapsedTicks = 0;
// iterate through all the events since the last stop
this._state.forEachBetween(stopEvent.time, computedTime + this.sampleTime, e => {
let periodStartTime = lastState.time;
// if there is an offset event in this period use that
const offsetEvent = this._tickOffset.get(e.time);
if (offsetEvent && offsetEvent.time >= lastState.time) {
elapsedTicks = offsetEvent.ticks;
periodStartTime = offsetEvent.time;
}
if (lastState.state === "started" && e.state !== "started") {
elapsedTicks += this.frequency.getTicksAtTime(e.time) - this.frequency.getTicksAtTime(periodStartTime);
}
lastState = e;
});
// remove the temporary event
this._state.remove(tmpEvent);
// return the ticks
return elapsedTicks;
}
/**
* The number of times the callback was invoked. Starts counting at 0
* and increments after the callback was invoked. Returns -1 when stopped.
*/
get ticks(): Ticks {
return this.getTicksAtTime(this.now());
}
set ticks(t: Ticks) {
this.setTicksAtTime(t, this.now());
}
/**
* The time since ticks=0 that the TickSource has been running. Accounts
* for tempo curves
*/
get seconds(): Seconds {
return this.getSecondsAtTime(this.now());
}
set seconds(s: Seconds) {
const now = this.now();
const ticks = this.frequency.timeToTicks(s, now);
this.setTicksAtTime(ticks, now);
}
/**
* Return the elapsed seconds at the given time.
* @param time When to get the elapsed seconds
* @return The number of elapsed seconds
*/
getSecondsAtTime(time: Time): Seconds {
time = this.toSeconds(time);
const stopEvent = this._state.getLastState("stopped", time) as StateTimelineEvent;
// this event allows forEachBetween to iterate until the current time
const tmpEvent: StateTimelineEvent = { state: "paused", time };
this._state.add(tmpEvent);
// keep track of the previous offset event
let lastState = stopEvent;
let elapsedSeconds = 0;
// iterate through all the events since the last stop
this._state.forEachBetween(stopEvent.time, time + this.sampleTime, e => {
let periodStartTime = lastState.time;
// if there is an offset event in this period use that
const offsetEvent = this._tickOffset.get(e.time);
if (offsetEvent && offsetEvent.time >= lastState.time) {
elapsedSeconds = offsetEvent.seconds;
periodStartTime = offsetEvent.time;
}
if (lastState.state === "started" && e.state !== "started") {
elapsedSeconds += e.time - periodStartTime;
}
lastState = e;
});
// remove the temporary event
this._state.remove(tmpEvent);
// return the ticks
return elapsedSeconds;
}
/**
* Set the clock's ticks at the given time.
* @param ticks The tick value to set
* @param time When to set the tick value
*/
setTicksAtTime(ticks: Ticks, time: Time): this {
time = this.toSeconds(time);
this._tickOffset.cancel(time);
this._tickOffset.add({
seconds: this.frequency.getDurationOfTicks(ticks, time),
ticks,
time,
});
return this;
}
/**
* Returns the scheduled state at the given time.
* @param time The time to query.
*/
getStateAtTime(time: Time): PlaybackState {
time = this.toSeconds(time);
return this._state.getValueAtTime(time);
}
/**
* Get the time of the given tick. The second argument
* is when to test before. Since ticks can be set (with setTicksAtTime)
* there may be multiple times for a given tick value.
* @param tick The tick number.
* @param before When to measure the tick value from.
* @return The time of the tick
*/
getTimeOfTick(tick: Ticks, before = this.now()): Seconds {
const offset = this._tickOffset.get(before) as TickSourceOffsetEvent;
const event = this._state.get(before) as StateTimelineEvent;
const startTime = Math.max(offset.time, event.time);
const absoluteTicks = this.frequency.getTicksAtTime(startTime) + tick - offset.ticks;
return this.frequency.getTimeOfTick(absoluteTicks);
}
/**
* Invoke the callback event at all scheduled ticks between the
* start time and the end time
* @param startTime The beginning of the search range
* @param endTime The end of the search range
* @param callback The callback to invoke with each tick
*/
forEachTickBetween(startTime: number, endTime: number, callback: (when: Seconds, ticks: Ticks) => void): this {
// only iterate through the sections where it is "started"
let lastStateEvent = this._state.get(startTime);
this._state.forEachBetween(startTime, endTime, event => {
if (lastStateEvent && lastStateEvent.state === "started" && event.state !== "started") {
this.forEachTickBetween(Math.max(lastStateEvent.time, startTime), event.time - this.sampleTime, callback);
}
lastStateEvent = event;
});
let error: Error | null = null;
if (lastStateEvent && lastStateEvent.state === "started") {
const maxStartTime = Math.max(lastStateEvent.time, startTime);
// figure out the difference between the frequency ticks and the
const startTicks = this.frequency.getTicksAtTime(maxStartTime);
const ticksAtStart = this.frequency.getTicksAtTime(lastStateEvent.time);
const diff = startTicks - ticksAtStart;
let offset = Math.ceil(diff) - diff;
// guard against floating point issues
offset = EQ(offset, 1) ? 0 : offset;
let nextTickTime = this.frequency.getTimeOfTick(startTicks + offset);
while (nextTickTime < endTime) {
try {
callback(nextTickTime, Math.round(this.getTicksAtTime(nextTickTime)));
} catch (e) {
error = e;
break;
}
nextTickTime += this.frequency.getDurationOfTicks(1, nextTickTime);
}
}
if (error) {
throw error;
}
return this;
}
/**
* Clean up
*/
dispose(): this {
super.dispose();
this._state.dispose();
this._tickOffset.dispose();
this.frequency.dispose();
return this;
}
}