2 summary:: Object representing an sc-server application
3 categories:: Server>Abstractions
4 related:: Classes/ServerOptions
8 A Server object is the client-side representation of a server app and is used to control the app from the SuperCollider language application. (See link::Guides/ClientVsServer:: for more details on the distinction.)
9 It forwards osc-messages and has a number of allocators that keep track of IDs for nodes, buses and buffers.
11 The server application is a commandline program, so all commands apart from osc-messages are unix commands.
13 The server application represented by a Server object might be running on the same machine as the client (in the same address space as the language application or separately; see below), or it may be running on a remote machine.
15 Most of a Server's options are contolled through its instance of ServerOptions. See the link::Classes/ServerOptions:: helpfile for more detail.
19 Server apps running on the local machine have two unix environment variables: code::SC_SYNTHDEF_PATH:: and code::SC_PLUGIN_PATH::. These indicate directories of synthdefs and ugen plugins that will be loaded at startup. These are in addition to the default synthdef/ and plugin/ directories which are hard-coded.
21 These can be set within SC using the getenv and setenv methods of class link::Classes/String::.
23 // all defs in this directory will be loaded when a local server boots
24 "SC_SYNTHDEF_PATH".setenv("~/scwork/".standardizePath);
25 "echo $SC_SYNTHDEF_PATH".unixCmd;
28 subsection:: The default group
30 When a Server is booted there is a top level group with an ID of 0 that defines the root of the node tree. (This is represented by a subclass of link::Classes/Group:: : link::Classes/RootNode::.)
31 If the server app was booted from within SCLang (as opposed to from the command line) the method code::initTree:: will be called automatically after booting.
32 This will also create a link::Reference/default_group:: with an ID of 1, which is the default group for all link::Classes/Node::s when using object style.
33 This provides a predictable basic node tree so that methods such as Server-scope, Server-record, etc. can function without running into order of execution problems.
35 The default group is persistent, i.e. it is recreated after a reboot, pressing cmd-., etc. See link::Classes/RootNode:: and link::Reference/default_group:: for more information.
37 If a Server has been booted from the command line you must call code::initTree:: manually in order to initialize the default group, if you want it. See code::initTree:: below.
40 subsection:: Local vs. Internal
42 In general, when working with a single machine one will probably be using one of two Server objects which are created at startup and stored in the class variables local and internal. By default two GUI windows are created to control these.
44 The difference between the two is that the local server runs as a separate application with its own address space, and the internal server runs within the same space as the language/client app.
46 The internal server has the advantage of being able to access shared memory, thus allowing for things like scope windows (see below) and link::Classes/SharedIn:: / link::Classes/SharedOut::.
47 It also minimizes messaging latency.
49 The local server, and any other server apps running on your local machine, have the advantage that if the language app crashes, it (and thus possibly your piece) will continue to run. It is thus an inherently more robust arrangement.
51 subsection:: The default Server
53 There is always a default Server, which is stored in the class variable code::default::. Any link::Classes/Synth::s or link::Classes/Group::s created without a target will be created on the default server. At startup this is set to be the local server (see above), but can be set to be any Server.
61 a symbol; each Server object is stored in one global classvariable under its name.
64 an optional instance of link::Classes/NetAddr::, providing host and port.
65 The default is the localhost address using port 57110; the same as the local server.
68 an optional instance of link::Classes/ServerOptions::. If code::nil::, an instance of ServerOptions will be created, using the default values.
71 an integer. In multi client situations, every client can be given a separate nodeID range. The default is 0.
75 get/set the local server, stored in classvar code::local:: (created already on initClass)
78 get/set the internal server, stored in classvar code::internal:: (created already on initClass)
81 Get or set the default server. By default this is the local server (see above).
83 Setting this will also assign it to the link::Classes/Interpreter:: variable 's'.
85 Server.default = Server.internal; // set the internal Server to be the default Server
90 get/set the set of all servers.
92 method:: allRunningServers
93 returns:: the set of all running servers.
96 quit all registered servers
99 query the system for any sc-server apps and hard quit them
102 free all nodes in all registered servers
109 send an osc message to the server.
112 s.sendMsg("/s_new", "default", s.nextNodeID, 0, 1);
116 send an osc bundle to the server.
118 Since the network may have irregular performance, time allows for the bundle to be evaluated at a specified point in the future.
119 Thus all messages are synchronous relative to each other, but delayed by a constant offset.
120 If such a bundle arrives late, the server replies with a late message but still evaluates it.
122 s.sendBundle(0.2, ["/s_new", "default", x = s.nextNodeID, 0, 1], ["/n_set", x, "freq", 500]);
128 as sendMsg, but takes an array as argument.
130 method:: listSendBundle
131 as sendBundle, but takes an array as argument.
133 This allows you to collect messages in an array and then send them.
135 s.listSendBundle(0.2, [["/s_new", "default", x = s.nextNodeID, 0, 1],
136 ["/n_set", x, "freq", 600]]);
139 method:: sendSynthDef
140 send a synthDef to the server that was written in a local directory
142 method:: loadSynthDef
143 load a synthDef that resides in the remote directory
145 method:: loadDirectory
146 load all the SynthDefs in the directory dir.
148 a link::Classes/String:: which is a valid path.
153 method:: nextPermNodeID
154 get a permanent node ID. This node ID is in a reserved range and will be held until you explicitly free it.
156 method:: freePermNodeID
157 free a permanent node ID for later reuse.
160 this can be used within a link::Classes/Routine:: to wait for a server reply
163 evaluate the function code::func:: as soon as the server has booted. If it is running, it is evaluated immediately. If it is not running, boot the server and evaluate the function. code::limit:: indicates the maximum times to try. (5 times/sec)
165 method:: doWhenBooted
166 evaluate the function as soon as the server has booted. If it is running, it is evaluated immediately. code::limit:: is the maximum number of times to try. (5 times/sec)
169 boot the remote server, create new allocators.
170 argument:: startAliveThread
171 if set to false, the server is not queried to give information for the window.
173 N.B. You cannot locally boot a server app on a remote machine.
176 quit the server application
179 quit and restart the server application
182 free all nodes in this server
185 query the server status
188 server sends notifications, for example if a node was created, a 'tr' message from a link::Classes/SendTrig::, or a strong::/done:: action. if code::flag:: is set to false, these messages are not sent. The default is true.
191 measure the time between server and client, which may vary. the code::func:: is
192 evaluated after code::n:: number of times and is passed the resulting maximum.
195 Get or set this Server's link::Classes/ServerOptions:: object. Changes take effect when the server is rebooted.
197 method:: defaultGroup
198 returns:: this Server's default group.
201 Get an instance of Volume that runs after the defualt group, or sets the Volume of the Server's output to level. Level is in db.
204 mute the server's output. This can also be toggled from the Server window with the 'm' key.
207 unmute the server. This can also be toggled from the Server window with the 'm' key.
210 Move the nodes in code::nodeList:: to the location specified by code::target:: and code::addAction::, placing them there in the order indicated by nodeList.
212 Any nodes which have already been freed will be skipped. Passing nil for target and addAction will result in the location being the head of the default group.
215 x = Array.fill(5, {Synth(\default)});
217 s.reorder(x, g, \addToTail);
222 Return a link::Classes/Bus:: object that represents the input audio bus.
225 Return a link::Classes/Bus:: object that represents the output audio bus.
228 subsection:: Information and debugging
233 ## 0 || turn dumping OFF.
234 ## 1 || print the parsed contents of the message.
235 ## 2 || print the contents in hexadecimal.
236 ## 3 || print both the parsed and hexadecimal representations of the contents.
239 method:: queryAllNodes
240 Post a representation of this Server's current node tree to the post window. See link::#-plotTree:: for a graphical variant.
242 Very helpful for debugging. For local servers this uses g_dumpTree and for remote g_queryTree. See link::Classes/Group:: and link::Reference/Server-Command-Reference:: for more info.
245 s.queryAllNodes; // note the root node (ID 0) and the default group (ID 1)
249 method:: peakCPU, avgCPU
250 Get peak and average CPU usage.
253 Get number of running link::Classes/Synth::s.
256 Get number of link::Classes/Group::s.
259 Get number of running link::Classes/UGen::s.
261 method:: numSynthDefs
262 Get number of loaded link::Classes/SynthDef::initions.
265 Get process ID of running server (if not internal).
269 subsection:: Automatic Message Bundling
271 Server provides support for automatically bundling messages. This is quite convenient in object style, and ensures synchronous execution. See also link::Guides/Bundled-Messages::
274 The Function code::func:: is evaluated, and all OSC messages generated by it are deferred and added to a bundle.
275 returns:: The bundle so that it can be further used if needed.
277 If set to nil or a number the bundle will be automatically sent and executed after the corresponding delay in seconds. If code::time:: is set to false the bundle will not be sent.
279 The function to evaluate.
281 allows you to pass in a preexisting bundle and continue adding to it.
283 Calling code::sync:: inside func will split the bundle and wait for asynchronous actions to complete before continuing.
285 If an error is encountered while evaluating code::func:: this method will throw an link::Classes/Error:: and stop message deferral.
289 // send a synth def to server
290 SynthDef("tpulse", { arg out=0,freq=700,sawFreq=440.0;
291 Out.ar(out, SyncSaw.ar(freq, sawFreq,0.1) )
295 // all OSC commands generated in the function contained below will be added to a bundle
296 // and executed simultaneously after 2 seconds.
299 x = Synth.new("tpulse");
300 a = Bus.control.set(440);
308 b = s.makeBundle(false, {
309 x = { PinkNoise.ar(0.1) * In.kr(0, 1); }.play;
312 // now pass b as a pre-existing bundle, and start both synths synchronously
314 s.makeBundle(nil, { // nil executes ASAP
315 y = { SinOsc.kr(0.2).abs }.play(x, 0, 0, \addBefore); // sine envelope
327 ("Look Ma, normal operations resume even though:\n" + error.errorString).postln;
328 x = { FSinOsc.ar(440, 0, 0.2) }.play; // This works fine
336 b = Buffer.read(s, Help.dir +/+ "sounds/a11wlk01.wav");
337 s.sync; // wait until load is done and then send the rest of the bundle
338 x = { PlayBuf.ar(1, b) * 0.5 }.play;
345 Just as in code::makeBundle::, the Function code::func:: is evaluated, and all OSC messages generated by it are deferred and added to a bundle, which is sent to the server, using the server default latency.
350 a = { |freq=100| SinOsc.ar(freq, LFTri.ar(freq)) * 0.2 }.play;
356 subsection:: Shared Controls
358 The internal server has a number of shared control buses. Their values can be set or polled using the methods below.
360 method:: getSharedControl
361 get the current value of a shared control bus. num is the index of the bus to poll. This command is synchronous and only works with the internal server.
363 method:: setSharedControl
364 set the current value of a shared control bus to value. num is the index of the bus to set. This command is synchronous and only works with the internal server.
366 method:: allocSharedControls
367 set the number of shared control buses. Must be done before the internal server is booted. The default is 1024.
369 subsection:: Persistent Node Trees
371 The class link::Classes/ServerTree:: can be used to store functions which will be evaluated after the server is booted, after all nodes are freed, and after cmd-. is pressed.
372 This allows, for example, for one to create a persistent basic node structure. ServerTree is evaluated in the method initTree after the default group is created, so its existence can be relied upon.
375 This method initializes the link::Reference/default_group:: and runs link::Classes/ServerTree::.
377 This method is called automatically when you boot a Server from the language. N.B. If you started a server app from the command line you will have to call initTree manually if you need this functionality.
380 f = {Group.new(s.defaultGroup); "Other code can be evaluated too".postln;};
383 s.queryAllNodes; // note the group within the default group
384 ServerTree.remove(f);
386 link::Classes/ServerBoot:: and link::Classes/ServerQuit:: provide similar functionality at boot and quit times.
388 subsection:: GUI methods
391 Create and show the server window
394 Open a scope window showing the output of the Server.
395 This only works with the internal server.
396 see link::Classes/Stethoscope:: for further details.
398 argument:: numChannels
399 the number of channels to be scoped out. The default is this server's options' numOutputBusChannels.
401 the first channel to be output. The default is 0.
403 the size of the buffer for the ScopeView. The default is 4096.
405 a zoom value for the scope's X axis. Larger values show more. The default is 1.
407 whether to display audio or control rate buses (either \audio or \control)
410 Show frequency analyzer window. This only works with the internal server.
413 Show input/output level meters.
416 Plot the node/group tree. As link::#-queryAllNodes:: but graphical.
418 subsection:: Recording Support
420 The following methods are for convenience use. For recording with sample accurate start and stop times you should make your own nodes. See the link::Classes/DiskOut:: helpfile for more info. For non-realtime recording, see the link::Guides/Non-Realtime-Synthesis:: helpfile.
422 This functionality is also available through the recording button on the server windows.
423 Pressing it once calls record, and pressing it again calls stopRecording (see below). When doing so the file created will be in your recordings folder and be named for the current date and time.
424 The default location of the recordings folder varies from platform to platform but is always stored in code::thisProcess.platform.recordingsDir::. Setting this variable allows you to change the default.
427 record creates the recording synth after the Server's default group and uses In.ar. Thus if you add nodes after the recording synth their output will not be captured.
428 To avoid this, either use Node objects (which use the default node as their target) or (when using messaging style) use a target nodeID of 1.
430 s.sendMsg("/s_new", "default", s.nextNodeID, 1,1);
434 For more detail on this subject see link::Guides/Order-of-execution::, link::Reference/default_group::, and link::Guides/NodeMessaging::.
436 See link::Classes/SoundFile:: for information on the various sample and header formats.
437 Not all sample and header formats are compatible. Note that the sampling rate of the output file will be the same as that of the server app. This can be set using the Server's link::Classes/ServerOptions::.
441 s.boot; // start the server
443 // something to record
445 SynthDef("bubbles", {
447 f = LFSaw.kr(0.4, 0, 24, LFSaw.kr([8,7.23], 0, 3, 80)).midicps; // glissando function
448 zout = CombN.ar(SinOsc.ar(f, 0, 0.04), 0.2, 0.2, 4); // echoing sine wave
451 SynthDef("tpulse", { arg out=0,freq=700,sawFreq=440.0;
452 Out.ar(out, SyncSaw.ar(freq, sawFreq,0.1) )
457 x = Synth.new("bubbles");
459 s.prepareForRecord; // you have to call this first
463 s.pauseRecording; // pausable
465 s.record // start again
467 s.stopRecording; // this closes the file and deallocates the buffer recording node, etc.
469 x.free; // stop the synths
471 // look in your recordings folder and you'll find a file named for this date and time
474 method:: prepareForRecord
475 Allocates the necessary buffer, etc. for recording the server's output. (See code::record:: below.)
477 a link::Classes/String:: representing the path and name of the output file.
479 If you do not specify a path than a file will be created in your recordings folder (see the note above on this) called SC_thisDateAndTime. Changes to the header or sample format, or to the number of channels must be made BEFORE calling this.
482 Starts or resumes recording the output.
484 If you have not called prepareForRecord first (see above) then it will be invoked for you (but that adds a slight delay before recording starts for real).
486 this is optional, and is passed to code::prepareForRecord:: (above).
488 method:: pauseRecording
489 Pauses recording. Can be resumed by executing record again.
491 method:: stopRecording
492 Stops recording, closes the file, and frees the associated resources.
494 You must call this when finished recording or the output file will be unusable. Cmd-. while recording has the same effect.
497 Returns:: the current recording synth so that it can be used as a target. This should only be necessary for nodes which are not created in the default group.
500 Get/set the number of channels (int) to record. The default is two. Must be called BEFORE prepareForRecord.
502 method:: recHeaderFormat
503 Get/set the header format (string) of the output file. The default is "aiff". Must be called BEFORE prepareForRecord.
505 method:: recSampleFormat
506 Get/set the sample format (string) of the output file. The default is "float". Must be called BEFORE prepareForRecord.
508 subsection:: Asynchronous Commands
510 Server provides support for waiting on the completion of asynchronous OSC commands such as reading or writing soundfiles. N.B. The following methods must be called from within a running link::Classes/Routine::. Explicitly passing in a link::Classes/Condition:: allows multiple elements to depend on different conditions. The examples below should make clear how all this works.
513 Boot the Server and wait until it has completed before resuming the thread.
515 an optional instance of link::Classes/Condition:: used for evaluating this.
518 Send the following message to the wait until it has completed before resuming the thread.
520 an optional instance of link::Classes/Condition:: used for evaluating this.
522 one or more valid OSC messages.
525 Send a code::/sync:: message to the server, which will replie with the message code::/synced:: when all pending asynchronous commands have been completed.
527 an optional instance of link::Classes/Condition:: used for evaluating this.
529 one or more OSC messages which will be bundled before the sync message (thus ensuring that they will arrive before the /sync message). argument:: latency
530 allows for the message to be evaluated at a specific point in the future.
533 This may be slightly less safe then sendMsgSync under UDP on a wide area network, as packets may arrive out of order, but on a local network should be okay. Under TCP this should always be safe.
539 // create a condition variable to control execution of the Routine
545 s.sendMsgSync(c, "/b_alloc", 0, 44100, 2);
546 s.sendMsgSync(c, "/b_alloc", 1, 44100, 2);
547 s.sendMsgSync(c, "/b_alloc", 2, 44100, 2);
548 \b_alloc_DONE.postln;
556 // create a condition variable to control execution of the Routine
562 s.sendMsg("/b_alloc", 0, 44100, 2);
563 s.sendMsg("/b_alloc", 1, 44100, 2);
564 s.sendMsg("/b_alloc", 2, 44100, 2);
566 \b_alloc_DONE.postln;
571 section:: Keyboard Shortcuts
573 when a server window is in focus, these shortcuts can be used:
575 ## space || start the server
576 ## d || toggle dumpOSC
577 ## n || post a representation of the node tree
578 ## N || post a representation of the node tree and the current control values of any synths
579 ## s || scope (internal server only)