File: NetAddr.sc

package info (click to toggle)
supercollider 1%3A3.10.0%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 45,496 kB
  • sloc: cpp: 283,513; lisp: 74,040; ansic: 72,252; sh: 23,016; python: 7,175; makefile: 1,087; perl: 766; java: 677; yacc: 314; lex: 175; ruby: 136; objc: 65; xml: 15
file content (321 lines) | stat: -rw-r--r-- 6,688 bytes parent folder | download
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
NetAddr {
	var <addr=0, <>port, <hostname, <socket;
	classvar connections;

	*initClass {
		connections = IdentityDictionary.new;
	}

	*new { arg hostname, port;
		var addr;
		addr = if (hostname.notNil,{ hostname.gethostbyname },{ 0 });
		^super.newCopyArgs(addr, port, hostname);
	}

	*fromIP { arg addr, port;
		^super.newCopyArgs(addr, port, addr.asIPString)
	}

	*langPort {
		_GetLangPort
		^this.primitiveFailed;
	}

	*matchLangIP {|ipstring|
		_MatchLangIP
		^this.primitiveFailed;
	}

	*localEndPoint {
		^this.new(this.langIP, this.langPort)
	}

	*localAddr {
		^this.new("127.0.0.1", this.langPort)
	}

	*useDoubles_ { arg flag = false;
		_NetAddr_UseDoubles
		^this.primitiveFailed;
	}

	*broadcastFlag {
		_NetAddr_GetBroadcastFlag
		^this.primitiveFailed
	}

	*broadcastFlag_ { arg flag = true;
		_NetAddr_SetBroadcastFlag
		^this.primitiveFailed
	}

	*disconnectAll {
		if(connections.notNil) {
			connections.keys.do { |netAddr|
				netAddr.disconnect;
			}
		}
	}

	hostname_ { arg inHostname;
		hostname = inHostname;
		addr = inHostname.gethostbyname;
	}

	sendRaw { arg rawArray;
		_NetAddr_SendRaw
		^this.primitiveFailed;
	}

	sendMsg { arg ... args;
		_NetAddr_SendMsg
		^this.primitiveFailed;
	}

	// warning: this primitive will fail to send if the bundle size is too large
	// but it will not throw an error.  this needs to be fixed
	sendBundle { arg time ... args;
		_NetAddr_SendBundle
		^this.primitiveFailed;
	}

	sendStatusMsg {
		this.sendMsg("/status");
	}

	sendClumpedBundles { arg time ... args;
		if(args.bundleSize > 65535) {// udp max size.
			args.clumpBundles.do { |item|
				if(time.notNil) { time = time + 1e-9 }; // make it a nanosecond later
				this.sendBundle(time, *item)
			};
		} {
			this.sendBundle(time, *args)
		}
	}

	sync { arg condition, bundles, latency; // array of bundles that cause async action
		var resp, id;
		if (condition.isNil) { condition = Condition.new };
		if(bundles.isNil) {
			id = this.makeSyncResponder(condition);
			this.sendBundle(latency, ["/sync", id]);
			condition.wait;
		} {
			// not sure what the exact size is, but its about 20000
			// this relates to what _NetAddr_SendBundle can send
			if(bundles.bundleSize > 20000/*65515*/) { // 65515 = 65535 - 16 - 4 (sync msg size)
				bundles.clumpBundles.do { |item|
					id = this.makeSyncResponder(condition);
					this.sendBundle(latency, *(item ++ [["/sync", id]]));
					if(latency.notNil) { latency = latency + 1e-9 };
					condition.wait;
				}
			} {
				id = this.makeSyncResponder(condition);
				this.sendBundle(latency, *(bundles ++ [["/sync", id]]));
				condition.wait;
			}
		};
		// maybe needed: a timeout
	}

	makeSyncResponder { arg condition;
		var id = UniqueID.next;
		var resp = OSCFunc({|msg|
			if (msg[1] == id) {
				resp.free;
				condition.test = true;
				condition.signal;
			};
		}, '/synced', this);
		condition.test = false;
		^id
	}

	isConnected {
		^socket.notNil
	}

	connect { | disconnectHandler |
		if (this.isConnected.not) {
			this.prConnect;
			connections.put(this, disconnectHandler);
		}
	}

	disconnect {
		if (this.isConnected) {
			this.prDisconnect;
			this.prConnectionClosed;
		};
	}

	tryConnectTCP { |onComplete, onFailure, maxAttempts = 10|
		var func = { |attempts|
			attempts = attempts - 1;
			try {
				this.connect
			} { |err|
				if(err.isKindOf(PrimitiveFailedError) and: { err.failedPrimitiveName == '_NetAddr_Connect'}) {
					if(attempts > 0) {
						0.2.wait;
						func.value(attempts)
					} {
						"Couldn't connect to TCP address %:%\n".format(hostname, port).warn;
						onFailure.value(this)
					}
				} {
					err.throw;
				}
			}
		};
		fork {
			func.value(maxAttempts);
			onComplete.value(this);
		}
	}

	tryDisconnectTCP { |onComplete, onFailure|
		try {
			this.disconnect
		} { |err|
			if(err.isKindOf(PrimitiveFailedError) and: { err.failedPrimitiveName == '_NetAddr_SendMsg'}) {
				"Couldn't disconnect from TCP address %:%\n".format(hostname, port).warn;
				onFailure.value(this)
			} {
				err.throw;
			}
		};
		this.disconnect;
		onComplete.value(this);
	}

	== { arg that;
		^this.compareObject(that, #[\port, \addr])
	}

	hash {
		^this.instVarHash(#[\port, \addr])
	}

	// Asymmetric: "that" may be nil or have nil port (wildcards)
	matches { arg that;
		^that.isNil
		or: { this.isLocal and: { that.isLocal } and: { that.port.isNil or: { this.port == that.port } } }
		or: { this == that }
		or: { that.port.isNil and: { this.addr == that.addr } }
	}

	isLocal { ^this.class.matchLangIP(this.ip) }

	ip {
		^addr.asIPString
	}

	hasBundle { ^false }

	printOn { | stream |
		super.printOn(stream);
		stream << $( << this.ip << ", " << port << $)
	}
	storeOn { | stream |
		super.storeOn(stream);
		stream << $( << "\"" << this.ip << "\", " << port << $)
	}

	// PRIVATE
	prConnect {
		_NetAddr_Connect
		^this.primitiveFailed;
	}

	prDisconnect {
		_NetAddr_Disconnect
		^this.primitiveFailed;
	}

	prConnectionClosed {
		// called when connection is closed either by sclang or by peer
		socket = nil;
		connections.removeAt(this).value(this);
	}

	recover { ^this }
}

BundleNetAddr : NetAddr {
	var <saveAddr, <>bundle;
	var <async = false;

	*copyFrom { arg addr, bundle;
		^super.newCopyArgs(addr.addr, addr.port, addr.hostname, addr.socket, addr, bundle ? []);
	}

	sendRaw { arg rawArray;
		bundle = bundle.add( rawArray );
	}

	sendMsg { arg ... args;
		bundle = bundle.add( args );
	}

	sendBundle { arg time ... args;
		bundle = bundle.addAll( args );
	}

	sendClumpedBundles { arg time ... args;
		bundle = bundle.addAll( args );
	}

	sendStatusMsg {} // ignore status messages

	recover {
		^saveAddr.recover
	}

	hasBundle { ^true }

	sync { arg condition, bundles, latency;
		bundle = bundle.add([\syncFlag, bundles, latency]);
		// not sure about condition. here we ignore it.
		async = true;
	}

	closeBundle { arg time;
		var bundleList, lastBundles;
		if(time != false) {
			if(async.not) {
				saveAddr.sendClumpedBundles(time, *bundle);
				^bundle;
			};

			forkIfNeeded {
				bundleList = this.splitBundles(time);
				lastBundles = bundleList.pop;
				bundleList.do { |bundles|
					var t = bundles.removeAt(0);
					saveAddr.sync(nil, bundles, t); // make an independent condition.
				};
				saveAddr.sendClumpedBundles(*lastBundles);  // time ... args
			}
		};
		^bundle
	}

	splitBundles { arg time;
		var res, curr;
		curr = [time]; // first element in the array is always the time
		bundle.do { |item|
			if(item[0] === \syncFlag) {
				curr = curr.addAll(item[1]); // then comes the messages
				res = res.add(curr);
				curr = [item[2]]; // time
			} {
				curr = curr.add(item)
			}
		};
		res = res.add(curr);
		^res
	}
}