What's in YOUR startup file(s)? Let's see 'em!

Motivation: updating the doc for the Sclang StartupFile, i.e. StartupFile.schelp. See this PR of mine, Docs: Sclang Startup File by HotwheelsSisyphus · Pull Request #7333 · supercollider/supercollider · GitHub, where it probably wasn’t obvious that I was asking for input. Just hoping to put togegether a decent example startup file on the basis of actual usage. The example included in the PR is still a bit of a placeholder; here’s a pdf preview of the updated schelp, I apologize for the attempts at humor.

Title is self explanatory. Obviously don’t include personal info or your deepest sound design secrets here. Of particular interest: What are settings/options that should be recommended to new users? Any OS-specific peculiarities? (the old schelp, for instance, suggested setting JACK env vars for Linux, I’ve been getting away without that here using pipewire)?

note to self re blockSize/linux

Note to self: Setting block size on linux/pipewire (or jack?) from within sclang doesn’t work as it does in MacOS, forgot the details. Consider that if blockSize is included in startupfile.

For starters, here’s mine:

var sdo = Server.default.options;
var home = (
    numWireBufs: 8192, //lol
    useSystemClock: false,
    sampleRate: 48000,
    memSize: 2**20, // 1 GB
    maxNodes: 2048, //hell yeah gimme grains yo
);
var elsewhere = ();

home.keysValuesDo { |k,v| sdo.perform((k ++ \_).asSymbol, v)};

// the above only sets ServerOptions. Still need to set Server attributes:
Server.default.latency = 0.5; // not very live. 0.2 best for most people?

// only for scnvim users
if (\SCNvim.asClass.notNil) {
    Server.default.doWhenBooted {
        \SCNvim.asClass.updateStatusLine(1, \SCNvim.asClass.port);
    }
};

CmdPeriod.add {
    "________________HARD_STOP_______________".postln;
};

topEnvironment.know = true

haven’t looked at this in a while. The idea seems to have been that it lets me define different settings for different locations (here, only home is defined), if I’m elsewhere, I just paste that in the keysValuesDo loop.

the bit about topEnvironment.know is probably unnecessary, just a convenience when ~ is ambiguous (e.g. inside Pbinds).

Hi,

and thanks for this initiative!

On Linuxes the user home is almost always in
/home/userName
rather than
/Users/userName.

I could be good to clarify if loading other documents willl just open
them in the IDE or also execute its contens and give examples for both,
at which point the well-known synchronicity problem (waiting for server
boot, then load file, execute contents such as compiling synthdefs)
comes in and should me mentioned.

cheersz,
Peter

1 Like

I was actually thinking of posting this.

  • Ctrl-Esc a – open a VST frequency analyzer
  • Ctrl-Esc b – open the class browser
  • Ctrl-Esc g – attach gdb to sclang
  • Ctrl-Esc k – scd file bookmarks
  • Ctrl-Esc p – emergency release port 57120
  • Ctrl-Esc q – query all nodes
  • Ctrl-Esc s – open SynthDescLib browser
// do not init GUI when launching from command line
if(Platform.ideName != "none") {
	if(GUI.get(\qt).notNil) {
		fork({
			var w, title;
			var ntpStatus = false, cond = CondVar.new;
			'QtGUI'.asClass.palette = 'QPalette'.asClass.dark;
		}, AppClock);
	};
	
	
	// ctrl-esc hotkey commands
	
	StartUp.add({
		var e = Environment.make {
			~cmds = (
				$q: "Query all nodes" -> { Server.default.queryAllNodes },
				$s: "Browse SynthDescLib" -> { SynthDescLib.global.browse },
				$b: "Class browser" -> { Object.browse },
				$d: "Dismiss" -> { ~win.visible = false },
				$k: "Bookmarks" -> { ~openBookmark.() },
				$p: "Free 57120" -> { "fuser -k 57120/udp".unixCmd; "Please reboot interpreter".postln },
				$g: "Attach gdb" -> {
					"sudo gdb -p %"
					.format(
						thisProcess.pid
					)
					.debug("running")
					.runInTerminal
				},
				$a: "Analyzer" -> {
					if(Library.at(\freqSynth).notNil) {
						Library.at(\freqSynth).free;
						Library.put(\freqSynth, nil);
					} {
						if(s.serverRunning) {
							fork {
								var synth, ctl;
								var cond = CondVar.new;
								var chan = s.options.numOutputBusChannels;
								var name = ("vstAna" ++ chan).asSymbol;
								SynthDef(name, { |out = 0|
									VSTPlugin.ar(In.ar(out, chan), chan);
								}).add;
								s.sync;
								synth = Synth(name, target: s.defaultGroup, addAction: \addAfter);
								ctl = VSTPluginController(synth);
								// Linux native but not really freq analyzer:
								// TB_Spectrogram_v1.vst3
								ctl.open("Spectrum Analyzer.vst3", action: { |c, ok|
									if(ok) {
										c.editor;
										Library.put(\freqSynth, synth);
									} {
										"Could not open plugin".warn;
									};
								});
							};
						} {
							"Default server isn't running, can't open analyzer".warn;
						};
					};
				};
			);

			~makeWin = {
				~win = Window("util", Rect(800, 679, ~cmds.size * 30 + 10, 70));
				~win.layout = HLayout(*
					~cmds.keys.asArray.sort.collect { |key|
						Button().fixedWidth_(20)
						.states_([[key]])
						.action_(inEnvir { ~win.close; ~cmds[key].value.value; })
						.toolTip_(~cmds[key].key)
						.keyDownAction_(false);
					}
				);
				~win.view.keyDownAction = inEnvir { |view, char|
					if(~cmds[char].notNil) {
						~win.close; //.visible = false;
						~cmds[char].value.value;
					};
				};

				~win.front;

				~bkShutdownFunc = nil;
				Library.put(\ddwBookmarksDirty, false);
				~openBookmark = {
					var file, line, book = Library.at(\ddwBookmarks),
					win, list, openBtn, addBtn, removeBtn, cancelBtn, lastClick = 0;
					if(book.isNil) {
						file = File(Platform.userConfigDir +/+ "ddwBookmarks.txt", "r");
						if(file.isOpen) {
							while {
								line = file.getLine;
								line.notNil
							} {
								book = book.add(line);
							};
						} {
							"Could not read bookmarks file".warn;
							book = Array.new;
						};
					};

					if(~bkShutdownFunc.isNil) {
						~bkShutdownFunc = {
							var file;
							if(Library.at(\ddwBookmarksDirty) ?? { false }) {
								file = File(Platform.userConfigDir +/+ "ddwBookmarks.txt", "w");
								if(file.isOpen) {
									protect {
										Library.at(\ddwBookmarks).do { |path|
											file << path << "\n";
										};
									} { file.close };
								} {
									"Could not write bookmarks file".warn;
								};
							};
						};
						ShutDown.add(~bkShutdownFunc);
					};

					win = Window("Bookmarks",
						Rect.aboutPoint(Window.screenBounds.center, 200, 150));
					win.layout = HLayout(
						list = ListView(),
						VLayout(
							nil,
							openBtn = Button().fixedWidth_(80),
							addBtn = Button().fixedWidth_(80),
							removeBtn = Button().fixedWidth_(80),
							cancelBtn = Button().fixedWidth_(80),
							nil
						)
					);
					list.items_(book.collect(_.basename)).value_(0)
					.enterKeyAction_({ |view|
						openBtn.doAction
					})
					.mouseDownAction_({ |view|
						if(AppClock.seconds - lastClick < 0.3) {
							openBtn.doAction
						} {
							lastClick = AppClock.seconds;
						};
					});
					openBtn.states_([["Open"]])
					.action_({
						book[list.value].openDocument;
						win.close;
					});
					addBtn.states_([["Add"]])
					.action_({
						var new = 'Document'.asClass.current.path, base, i;
						if(new.isNil) {
							"Document is unsaved; can't bookmark".warn;
						} {
							if(book.size == 0) {
								book = [new];
								i = 0;
							} {
								base = new.basename;
								i = book.detectIndex { |path| base < path.basename };
								if(i.notNil) {
									book = book.insert(i, new);
								} {
									book = book.add(new);
									i = book.size - 1;
								};
							};
						};
						Library.put(\ddwBookmarks, book);
						Library.put(\ddwBookmarksDirty, true);
						list.items_(book.collect(_.basename)).value_(i);
					});
					removeBtn.states_([["Remove"]])
					.action_({
						var saveItem;
						book.removeAt(list.value);
						saveItem = book[list.value];
						Library.put(\ddwBookmarks, book);
						Library.put(\ddwBookmarksDirty, true);
						list.items_(book.collect(_.basename))
						.value_(book.indexOfEqual(saveItem) ?? { book.size - 1 })
					});
					cancelBtn.states_([["Exit"]])
					.action_({ win.close });
					win.front;
				};
			};
		};
		{
			if('Document'.asClass.respondsTo(\globalKeyDownAction_)) {
				'Document'.asClass.globalKeyDownAction = 'Document'.asClass.globalKeyDownAction.addFunc({ |doc, char, modifiers, ascii|
					
					// on my linux machine, this is ctrl-esc
					// change as you see fit
					if(ascii == 27 and: { modifiers.bitAnd(262144) != 0 }) {
						~makeWin.value; // ~win.front;
					};
				}.inEnvir(e));
			};
		}.defer(3.0);

		Library.put(\utilityEnvir, e);
	});
};

Class browser, SynthDescLib browser, and bookmarks, I use a lot.

Some bits assume Linux.

hjh

2 Likes

On Linuxes the user home is almost always in
/home/userName

Thanks, you are right, in fact it’s like that on my own machine. No idea where the Users came from, probably MacOs, and/or the old version of the helpfile.

give examples for both

also good point. path.load executes and Document.open opens.

synchronicity problem

yes, that should be done via SystemActions

That’s a cool example!
For the PR, I was actually hoping for more barebones stuff, basically sane defaults rather than fancy scripts. In that respect, my own example (though far from fancy) was probably misleading. For example, I’m less interested in what method folks might be using to load different settings but rather what settings (mostly ServerOptions) to recommend to begin with. I don’t want the StartupFile.schelp to become huge, I don’t want to have to explain a lot, but I do want an overview of basic things people might want to put in there.

1 Like

Absolutely nothing.

I always forget it exists and can never find it.

4 Likes

I have never used the startup file, dont even know where that lives. Every project of mine has the same folder structure and in the root of that folder is a main.scd file which boots the server and loads all the resources.

For what it’s worth, the IDE tries to make the startup file easy to find by providing a “File → Open startup file” command.

That’s not to say that use of the startup file is mandatory – just pointing out that it isn’t meant to be obscure.

I actually agree with the last two posters that I don’t use the startup file for server settings. If I need to change them, I’ll do that in project init scripts generally. I do have some other bits for QtGUI palette setting, and the hotkeys as above.

The other thing I do in startup is to check the language port, and if it isn’t the default 57120, kill all processes that are using 57120, and exit sclang. That’s because OSC interfaces don’t automatically adapt when sclang wakes up on a different port from the default. I found that it’s easier to halt the startup sequence than to load my environment and only then encounter a non-responsive interface.

StartUp.add {
	{
		var pipe = Pipe("fuser 57120/udp", "r");
		var line;
		var pids = List.new;
		var cond = CondVar.new;
		var ok, allOK = true;
		protect {
			while {
				line = pipe.getLine.postln;
				line.notNil
			} {
				line.split($ ).do { |id|
					if(id.asInteger != 0) {
						pids.add(id)
					};
				};
			};
		} { pipe.close };
		fork {
			pids.do { |id|
				ok = false;
				"kill -9 %".format(id).unixCmd { |exit|
					if(exit == 0) {
						ok = true
					};
					cond.signalOne;
				};
				cond.waitFor(1);
				if(ok.not) {
					"Failed to stop pid %".format(id).warn;
				};
				allOK = allOK and: ok;
			};
			if(allOK) { 0.exit } { "Some processes didn't die".warn };
		};
	} => Func(\fixPorts);
};

// ... and...

{
	if(Platform.ideName == "scqt" and: { NetAddr.langPort != 57120 }) {
		"Language port is %, networking may fail".format(NetAddr.langPort).warn;
		"Attempting to force-quit leftover processes\nIf successful, reboot the interpreter".postln;
		\fixPorts.eval;
	};
}.defer(1.0);

(Func is global storage for functions, in the ddwChucklib quark. The function itself is fine without using Func to store it, of course.)

hjh

Interesting. I wonder: Those who don’t use the startup file or don’t use it for server settings, how would you phrase the reasoning behind that? Not because it needs justification, but maybe so we can formulate some recommendations as to what (not) to use the startup file for.

On the basis of replies so far, I can imagine that a project-based server setup generally makes more sense because e.g. one project may be non-interactive so latency can be higher, another project may use a specific sample rate because it wants to (not) provoke FM aliasing artifacts, etc. That leaves the things mentioned by James, i.e. gui customization, hotkeys and the language port check (or more generally, anything that adds a StartUp action); as well as extension-specific things like the scnvim bit in mine.


There is also the linux-specific bit in the old StartupFile.schelp:

"SC_JACK_DEFAULT_INPUTS".setenv("system");
"SC_JACK_DEFAULT_OUTPUTS".setenv("system");

I’m not sure how up-to-date this still is. I’ve been using pipewire and inputs/outputs have been working out of the box, or otherwise I set them for a specific project.

You can do all of these things automatically in a class’s *initClass method.

I have one langconfig file next to my project pointing at the global class library, and a local directory called classes.

it’s really fun reading your posts in the different accents i randomly imagine for you

This is what mine looks like at a high-level:

s.boot;

(
// Symlinked to /Users/Library/Application Support/SuperCollider
"/home/pakled/Startup/serverOptions.scd".load; // serverOptions live in their own file

~federation = Federation(s); // Instantiate a custom class of helper functions
~globalContext = ~federation.getSuperGlobalContext;
~globalContext.defaultOut = 0;

// From PanAz Help
// 0 for stereo; 4.5 for octo
// Should be 0 if the front is a vertex of the spanning polygon. The first speaker
// will be directly in front. Should be 0.5 if the front bisects a side of the
// spanning polygon. Then the first speaker will be the one left of center.
~globalContext.numChans = 2;
~globalContext.orientation = 0;

~synths = Dictionary.new;
~sounds = Dictionary.new;
~loadSounds = [
  "/home/Local/Sources/Audio/corpus/soundfiles.WAV",
  ...
];

s.waitForBoot {
  "--> Server booted".postln;
  thisProcess.platform.recordingsDir = "/home/Local/Saved Output/";
  MIDIClient.init;
  MIDIIn.connectAll;
  ~loadSounds.do {|n,i|
    var filename = PathName(n).fileNameWithoutExtension;
    ~sounds[filename.asSymbol] = Buffer.read(s, n);
  };
  ~looper = ();
  ~looper.recordbuf = Buffer.alloc(s, s.sampleRate * 12.0);
}

); // end

~pakled = Pakled( // my main performance instrument
  s: Server.default,
  loadGUI: true,
  debug: false,
  loadScripts: [
    // load scripts and random bits of code here
  ];
);

~federation.loadSynthDefDir("/MetaHodos/SynthFunctions/*","MetaHodos");
// lazy compile sketches as SynthDefs and add a per project naming prefix to
// disambiguate them from other things