File: MeterSync.sc

package info (click to toggle)
supercollider 1%3A3.13.0%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 80,292 kB
  • sloc: cpp: 476,363; lisp: 84,680; ansic: 77,685; sh: 25,509; python: 7,909; makefile: 3,440; perl: 1,964; javascript: 974; xml: 826; java: 677; yacc: 314; lex: 175; objc: 152; ruby: 136
file content (252 lines) | stat: -rw-r--r-- 7,674 bytes parent folder | download | duplicates (4)
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
// originally conceived for LinkClock (Ableton Link support)
// but this may in theory apply to any clock that answers to
// baseBarBeat_ (e.g. MIDISyncClocks, or BeaconClock)

MeterSync {
	var <clock, <id, <ports;
	var <repeats = 4, <delta = 0.01, lastReceived;
	var addrs, meterChangeResp, meterQueryResp;

	// normally clock.setMeterAtBeat notifies \meter
	// and this watcher should broadcast the change.
	// but the watcher may need to change baseBarBeat internally.
	// this should not broadcast. flag is off in that case
	var broadcastMeter = true;

	*new { |clock, id, ports|
		^super.new.init(clock, id, ports)
	}

	init { |argClock, argId, argPorts|
		// these should not be changed after the fact
		// create a new object instead
		clock = argClock;
		id = argId ?? { 0x7FFFFFFF.rand };
		ports = (argPorts ?? { (57120 .. 57127) }).asArray;
		addrs = ports.collect { |port| NetAddr("255.255.255.255", port) };
		meterQueryResp = OSCFunc({ |msg|
			// because of redundancy ('repeats'), we may receive this message
			// multiple times. Respond only once.
			if(msg != lastReceived) {
				lastReceived = msg;
				this.prBroadcast(
					'/SC_LinkClock/meterReply', id, msg[1], this.enabled.asInteger,
					clock.beats, clock.beatsPerBar, clock.baseBarBeat, clock.beatInBar
				);
			};
		}, '/SC_LinkClock/queryMeter');
		clock.addDependant(this);
		this.enabled = true;  // assume enabled when creating
	}

	free {
		clock.removeDependant(this);
		meterQueryResp.free;
		meterChangeResp.free;
	}

	enabled { ^meterChangeResp.notNil }

	enabled_ { |bool|
		var watcher, foundPeers = false;
		if(bool) {
			if(clock.numPeers == 0) {
				// if there are peers, then we get a \numPeers notification
				watcher = SimpleController(clock)
				.put(\numPeers, { |... args|
					watcher.remove;
					foundPeers = true;
					this.resyncMeter(verbose: clock.numPeers > 0)
				})
				.put(\stop, { watcher.remove });
				SystemClock.sched(0.25, {
					if(foundPeers.not) {
						watcher.remove;
						// some clocks other than Link might not broadcast numPeers
						// but they might have peers anyway. If not, this is a no-op
						this.resyncMeter(verbose: clock.numPeers > 0);
					};
				});
			} {
				this.resyncMeter;
			};
			meterChangeResp = OSCFunc({ |msg|
				if(msg[1] != id and: { msg != lastReceived }) {  // ignore message that I sent
					lastReceived = msg;
					// [2] = beatsPerBar, [3] = remote clock's real time, [4] = remote clock's barline
					// also, 5/8 means maybe setting the barline to a half-beat
					// but we have to round the barline because OSC receipt time is inexact
					// -- get the rounding factor from baseBarBeat.asFraction
					// *and* use my utility method because we do not want to broadcast here
					this.prSetMeterAtBeat(msg[2],
						(clock.beats + msg[4] - msg[3]).round(msg[4].asFraction[1].reciprocal)
					);
				};
			}, '/SC_LinkClock/changeMeter');
		} {
			meterChangeResp.free;
			meterChangeResp = nil;
		};
	}

	repeats_ { |value|
		if(value < 1) {
			Error("Invalid number of repeats '%'".format(value)).throw;
		};
		repeats = value
	}

	delta_ { |value|
		if(value <= 0) {
			Error("Invalid messaging delta '%'".format(value)).throw;
		};
		delta = value
	}

	prSetMeterAtBeat { |newBeatsPerBar, beats|
		var saveFlag = broadcastMeter;
		protect {
			broadcastMeter = false;
			clock.setMeterAtBeat(newBeatsPerBar, beats);
		} { broadcastMeter = saveFlag };
	}

	// must always call action after timeout!
	// resyncMeter depends on this
	queryMeter { |action, timeout = 0.2|
		var replies, resp;
		if(timeout.isKindOf(SimpleNumber).not or: { timeout <= 0 }) {
			Error("Invalid timeout '%' provided".format(timeout)).throw;
		};
		if(clock.numPeers > 0) {
			replies = Dictionary.new;
			// no need to check lastReceived here;
			// Dictionary already collapses replies per id
			resp = OSCFunc({ |msg, time, addr|
				if(msg[1] != id) {
					replies.put(msg[1], (
						id: msg[1],
						queriedAtBeat: msg[2],
						syncMeter: msg[3].asBoolean,
						beats: msg[4],
						beatsPerBar: msg[5],
						baseBarBeat: msg[6],
						beatInBar: msg[7]
					));
				};
			}, '/SC_LinkClock/meterReply');
			{
				protect {
					this.prBroadcast('/SC_LinkClock/queryMeter', clock.beats);
					(timeout + (repeats * delta)).wait;
				} { resp.free };
				action.value(replies.values);
			}.fork(SystemClock);
		} {
			// no peers, don't bother asking
			// sched is needed to make sure Conditions waiting for this method still work
			SystemClock.sched(0, { action.value(List.new) });
		};
	}

	resyncMeter { |round, verbose = true|
		var replies, cond = Condition.new, newBeatsPerBar, newBase;
		fork {
			// queryMeter should never hang (based on default timeout)
			this.queryMeter { |val|
				replies = val;
				cond.unhang;
			};
			cond.hang;
			replies = replies.select { |reply| reply[\syncMeter] };
			if(replies.size > 0) {
				#newBeatsPerBar, newBase = this.prGetMeter(replies, round);
				if(verbose and: { newBeatsPerBar != clock.beatsPerBar }) {
					"syncing meter to %, base = %\n".postf(newBeatsPerBar, newBase)
				};
				this.prSetMeterAtBeat(newBeatsPerBar, newBase);  // local only
				clock.changed(\resynced, true);
			} {
				if(verbose) {
					"(%) Found no SC Link peers synchronizing meter; cannot resync".format(id).warn;
				};
				clock.changed(\resynced, false);  // esp. for unit test
			}
		}
	}

	adjustMeterBase { |localBeats, remoteBeats, round = 1|
		// 'this.prSetMeterAtBeat' to avoid \meter notification
		this.prSetMeterAtBeat(clock.beatsPerBar,
			clock.baseBarBeat + ((localBeats - remoteBeats) % clock.beatsPerBar).round(round)
		);
	}

	update { |obj, what|
		switch(what)
		{ \meter } {
			if(broadcastMeter) {
				this.prBroadcast(
					'/SC_LinkClock/changeMeter',
					id, clock.beatsPerBar, clock.beats, clock.baseBarBeat
				);
			};
		}
		// if the 'model' clock is stopped, no need to keep monitoring
		{ \stop } { this.free }
		{ \disableMeterSync } { this.free };
	}

	prBroadcast { |... msg|
		var saveFlag;
		{
			repeats.do {
				// it is not safe to modify NetAddr.broadcastFlag
				// for this entire loop because we can't block other threads
				// from using it. So, do it atomically for each repeat.
				saveFlag = NetAddr.broadcastFlag;
				protect {
					NetAddr.broadcastFlag = true;
					addrs.do { |addr|
						addr.sendMsg(*msg);
					};
				} { NetAddr.broadcastFlag = saveFlag };
				delta.wait;
			};
		}.fork(SystemClock);
	}

	prGetMeter { |replies, round|
		var bpbs, baseBeats, denom, newBeatsPerBar, newBase;
		bpbs = Set.new;
		baseBeats = Set.new;
		denom = 1;
		replies.do { |reply|
			denom = lcm(denom, reply[\baseBarBeat].asFraction[1]);
			bpbs.add(reply[\beatsPerBar]);
			baseBeats.add(reply[\queriedAtBeat] - reply[\beatInBar]);
		};
		if(round.isNil) { round = denom.reciprocal };
		// All 'syncMeter' peers should have the same beatsPerBar (size == 1).
		// But, if something failed, maybe there are more.
		if(bpbs.size == 1) {
			// 'pop' = easy way to get one item from an unordered collection
			newBeatsPerBar = bpbs.pop;
			// Collapse remote baseBeats to minimum size
			baseBeats = baseBeats.collect { |x| x.round(round) % newBeatsPerBar };
			if(baseBeats.size == 1) {
				// 'baseBeats.add()' above has calculated baseBarBeat
				// such that my local beatInBar will match theirs
				newBase = baseBeats.pop;
			} {
				// this should not happen
				Error("LinkClock peers disagree on barline positions; cannot sync barlines").throw;
			};
		} {
			Error("LinkClock peers disagree on beatsPerBar; cannot sync barlines").throw;
		};
		^[newBeatsPerBar, newBase]
	}

	clock_ { ^this.shouldNotImplement(thisMethod) }
}