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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
|
ServerOptions {
// order of variables is important here. Only add new instance variables to the end.
var <numAudioBusChannels=1024;
var <>numControlBusChannels=16384;
var <numInputBusChannels=2;
var <numOutputBusChannels=2;
var <>numBuffers=1026;
var <>maxNodes=1024;
var <>maxSynthDefs=1024;
var <>protocol = \udp;
var <>blockSize = 64;
var <>hardwareBufferSize = nil;
var <>memSize = 8192;
var <>numRGens = 64;
var <>numWireBufs = 64;
var <>sampleRate = nil;
var <>loadDefs = true;
var <>inputStreamsEnabled;
var <>outputStreamsEnabled;
var <>inDevice = nil;
var <>outDevice = nil;
var <>verbosity = 0;
var <>zeroConf = false; // Whether server publishes port to Bonjour, etc.
var <>restrictedPath = nil;
var <>ugenPluginsPath = nil;
var <>initialNodeID = 1000;
var <>remoteControlVolume = false;
var <>memoryLocking = false;
var <>threads = nil; // for supernova
var <>useSystemClock = false; // for supernova
var <numPrivateAudioBusChannels=1020;
var <>reservedNumAudioBusChannels = 0;
var <>reservedNumControlBusChannels = 0;
var <>reservedNumBuffers = 0;
var <>pingsBeforeConsideredDead = 5;
var <>maxLogins = 1;
var <>recHeaderFormat="aiff";
var <>recSampleFormat="float";
var <>recChannels = 2;
var <>recBufSize = nil;
device {
^if(inDevice == outDevice) {
inDevice
} {
[inDevice, outDevice]
}
}
device_ { |dev|
inDevice = outDevice = dev;
}
asOptionsString { | port = 57110 |
var o;
o = if(protocol == \tcp, " -t ", " -u ");
o = o ++ port;
o = o ++ " -a " ++ (numPrivateAudioBusChannels + numInputBusChannels + numOutputBusChannels) ;
if (numControlBusChannels != 16384, {
o = o ++ " -c " ++ numControlBusChannels;
});
if (numInputBusChannels != 8, {
o = o ++ " -i " ++ numInputBusChannels;
});
if (numOutputBusChannels != 8, {
o = o ++ " -o " ++ numOutputBusChannels;
});
if (numBuffers != 1024, {
o = o ++ " -b " ++ numBuffers;
});
if (maxNodes != 1024, {
o = o ++ " -n " ++ maxNodes;
});
if (maxSynthDefs != 1024, {
o = o ++ " -d " ++ maxSynthDefs;
});
if (blockSize != 64, {
o = o ++ " -z " ++ blockSize;
});
if (hardwareBufferSize.notNil, {
o = o ++ " -Z " ++ hardwareBufferSize;
});
if (memSize != 8192, {
o = o ++ " -m " ++ memSize;
});
if (numRGens != 64, {
o = o ++ " -r " ++ numRGens;
});
if (numWireBufs != 64, {
o = o ++ " -w " ++ numWireBufs;
});
if (sampleRate.notNil, {
o = o ++ " -S " ++ sampleRate;
});
if (loadDefs.not, {
o = o ++ " -D 0";
});
if (inputStreamsEnabled.notNil, {
o = o ++ " -I " ++ inputStreamsEnabled ;
});
if (outputStreamsEnabled.notNil, {
o = o ++ " -O " ++ outputStreamsEnabled ;
});
if ((thisProcess.platform.name!=\osx) or: {inDevice == outDevice})
{
if (inDevice.notNil,
{
o = o ++ " -H %".format(inDevice.quote);
});
}
{
o = o ++ " -H % %".format(inDevice.asString.quote, outDevice.asString.quote);
};
if (verbosity != 0, {
o = o ++ " -V " ++ verbosity;
});
if (zeroConf.not, {
o = o ++ " -R 0";
});
if (restrictedPath.notNil, {
o = o ++ " -P " ++ restrictedPath;
});
if (ugenPluginsPath.notNil, {
if(ugenPluginsPath.isString, {
ugenPluginsPath = ugenPluginsPath.bubble;
});
o = o ++ " -U " ++ ugenPluginsPath.collect{|p|
thisProcess.platform.formatPathForCmdLine(p)
}.join(Platform.pathDelimiter);
});
if (memoryLocking, {
o = o ++ " -L";
});
if (threads.notNil, {
if (Server.program.asString.endsWith("supernova")) {
o = o ++ " -T " ++ threads;
}
});
if (useSystemClock.notNil, {
o = o ++ " -C " ++ useSystemClock.asInteger
});
if (maxLogins.notNil, {
o = o ++ " -l " ++ maxLogins;
});
^o
}
firstPrivateBus { // after the outs and ins
^numOutputBusChannels + numInputBusChannels
}
bootInProcess {
_BootInProcessServer
^this.primitiveFailed
}
numPrivateAudioBusChannels_ { |numChannels = 112|
numPrivateAudioBusChannels = numChannels;
this.recalcChannels;
}
numAudioBusChannels_ { |numChannels=1024|
numAudioBusChannels = numChannels;
numPrivateAudioBusChannels = numAudioBusChannels - numInputBusChannels - numOutputBusChannels;
}
numInputBusChannels_ { |numChannels=8|
numInputBusChannels = numChannels;
this.recalcChannels;
}
numOutputBusChannels_ { |numChannels=8|
numOutputBusChannels = numChannels;
this.recalcChannels;
}
recalcChannels {
numAudioBusChannels = numPrivateAudioBusChannels + numInputBusChannels + numOutputBusChannels;
}
*prListDevices {
arg in, out;
_ListAudioDevices
^this.primitiveFailed
}
*devices {
^this.prListDevices(1, 1);
}
*inDevices {
^this.prListDevices(1, 0);
}
*outDevices {
^this.prListDevices(0, 1);
}
}
ServerShmInterface {
// order matters!
var ptr, finalizer;
*new {|port|
^super.new.connect(port)
}
copy {
// never ever copy! will cause duplicate calls to the finalizer!
^this
}
connect {
_ServerShmInterface_connectSharedMem
^this.primitiveFailed
}
disconnect {
_ServerShmInterface_disconnectSharedMem
^this.primitiveFailed
}
getControlBusValue {
_ServerShmInterface_getControlBusValue
^this.primitiveFailed
}
getControlBusValues {
_ServerShmInterface_getControlBusValues
^this.primitiveFailed
}
setControlBusValue {
_ServerShmInterface_setControlBusValue
^this.primitiveFailed
}
setControlBusValues {
_ServerShmInterface_setControlBusValues
^this.primitiveFailed
}
}
Server {
classvar <>local, <>internal, <default;
classvar <>named, <>all, <>program, <>sync_s = true;
classvar <>nodeAllocClass, <>bufferAllocClass, <>busAllocClass;
var <name, <addr, <clientID;
var <isLocal, <inProcess, <>sendQuit, <>remoteControlled;
var maxNumClients; // maxLogins as sent from booted scsynth
var <>options, <>latency = 0.2, <dumpMode = 0;
var <nodeAllocator, <controlBusAllocator, <audioBusAllocator, <bufferAllocator, <scopeBufferAllocator;
var <>tree;
var <defaultGroup, <defaultGroups;
var <syncThread, <syncTasks;
var <window, <>scopeWindow, <emacsbuf;
var <volume, <recorder, <statusWatcher;
var <pid, serverInterface;
var pidReleaseCondition;
*initClass {
Class.initClassTree(ServerOptions);
Class.initClassTree(NotificationCenter);
named = IdentityDictionary.new;
all = Set.new;
nodeAllocClass = NodeIDAllocator;
// nodeAllocClass = ReadableNodeIDAllocator;
bufferAllocClass = ContiguousBlockAllocator;
busAllocClass = ContiguousBlockAllocator;
default = local = Server.new(\localhost, NetAddr("127.0.0.1", 57110));
internal = Server.new(\internal, NetAddr.new);
}
*fromName { |name|
^Server.named[name] ?? {
Server(name, NetAddr.new("127.0.0.1", 57110), ServerOptions.new)
}
}
*default_ { |server|
default = server;
if(sync_s) { thisProcess.interpreter.s = server }; // sync with s?
this.all.do { |each| each.changed(\default, server) };
}
*new { |name, addr, options, clientID|
^super.new.init(name, addr, options, clientID)
}
*remote { |name, addr, options, clientID|
var result;
result = this.new(name, addr, options, clientID);
result.startAliveThread;
^result;
}
init { |argName, argAddr, argOptions, argClientID|
this.addr = argAddr;
options = argOptions ?? { ServerOptions.new };
// set name to get readable posts from clientID set
name = argName.asSymbol;
// make statusWatcher before clientID, so .serverRunning works
statusWatcher = ServerStatusWatcher(server: this);
// go thru setter to test validity
this.clientID = argClientID ? 0;
volume = Volume(server: this, persist: true);
recorder = Recorder(server: this);
recorder.notifyServer = true;
this.name = argName;
all.add(this);
pidReleaseCondition = Condition({ this.pid == nil });
Server.changed(\serverAdded, this);
}
maxNumClients { ^maxNumClients ?? { options.maxLogins } }
remove {
all.remove(this);
named.removeAt(this.name);
}
addr_ { |netAddr|
addr = netAddr ?? { NetAddr("127.0.0.1", 57110) };
inProcess = addr.addr == 0;
isLocal = inProcess || { addr.isLocal };
remoteControlled = isLocal.not;
}
name_ { |argName|
name = argName.asSymbol;
if(named.at(argName).notNil) {
"Server name already exists: '%'. Please use a unique name".format(name, argName).warn;
} {
named.put(name, this);
}
}
initTree {
fork({
this.sendDefaultGroups;
tree.value(this);
this.sync;
ServerTree.run(this);
this.sync;
}, AppClock);
}
/* clientID */
// clientID is settable while server is off, and locked while server is running
// called from prHandleClientLoginInfoFromServer once after booting.
clientID_ { |val|
var failstr = "Server % couldn't set clientID to % - %. clientID is still %.";
if (this.serverRunning) {
failstr.format(name, val.cs, "server is running", clientID).warn;
^this
};
if(val.isInteger.not) {
failstr.format(name, val.cs, "not an Integer", clientID).warn;
^this
};
if (val < 0 or: { val >= this.maxNumClients }) {
failstr.format(name,
val.cs,
"outside of allowed server.maxNumClients range of 0 - %".format(this.maxNumClients - 1),
clientID
).warn;
^this
};
if (clientID != val) {
"% : setting clientID to %.\n".postf(this, val);
};
clientID = val;
this.newAllocators;
}
/* clientID-based id allocators */
newAllocators {
this.newNodeAllocators;
this.newBusAllocators;
this.newBufferAllocators;
this.newScopeBufferAllocators;
NotificationCenter.notify(this, \newAllocators);
}
newNodeAllocators {
nodeAllocator = nodeAllocClass.new(
clientID,
options.initialNodeID,
this.maxNumClients
);
// defaultGroup and defaultGroups depend on allocator,
// so always make them here:
this.makeDefaultGroups;
}
newBusAllocators {
var numControlPerClient, numAudioPerClient;
var controlReservedOffset, controlBusClientOffset;
var audioReservedOffset, audioBusClientOffset;
var audioBusIOOffset = options.firstPrivateBus;
numControlPerClient = options.numControlBusChannels div: this.maxNumClients;
numAudioPerClient = options.numAudioBusChannels - audioBusIOOffset div: this.maxNumClients;
controlReservedOffset = options.reservedNumControlBusChannels;
controlBusClientOffset = numControlPerClient * clientID;
audioReservedOffset = options.reservedNumAudioBusChannels;
audioBusClientOffset = numAudioPerClient * clientID;
controlBusAllocator = busAllocClass.new(
numControlPerClient,
controlReservedOffset,
controlBusClientOffset
);
audioBusAllocator = busAllocClass.new(
numAudioPerClient,
audioReservedOffset,
audioBusClientOffset + audioBusIOOffset
);
}
newBufferAllocators {
var numBuffersPerClient = options.numBuffers div: this.maxNumClients;
var numReservedBuffers = options.reservedNumBuffers;
var bufferClientOffset = numBuffersPerClient * clientID;
bufferAllocator = bufferAllocClass.new(
numBuffersPerClient,
numReservedBuffers,
bufferClientOffset
);
}
newScopeBufferAllocators {
if(isLocal) {
scopeBufferAllocator = StackNumberAllocator.new(0, 127)
}
}
nextBufferNumber { |n|
var bufnum = bufferAllocator.alloc(n);
if(bufnum.isNil) {
if(n > 1) {
Error("No block of % consecutive buffer numbers is available.".format(n)).throw
} {
Error("No more buffer numbers -- free some buffers before allocating more.").throw
}
};
^bufnum
}
freeAllBuffers {
var bundle;
bufferAllocator.blocks.do { arg block;
(block.address .. block.address + block.size - 1).do { |i|
bundle = bundle.add( ["/b_free", i] );
};
bufferAllocator.free(block.address);
};
this.sendBundle(nil, *bundle);
}
nextNodeID {
^nodeAllocator.alloc
}
nextPermNodeID {
^nodeAllocator.allocPerm
}
freePermNodeID { |id|
^nodeAllocator.freePerm(id)
}
prHandleClientLoginInfoFromServer { |newClientID, newMaxLogins|
// only set maxLogins if not internal server
if (inProcess.not) {
if (newMaxLogins.notNil) {
if (newMaxLogins != options.maxLogins) {
"%: server process has maxLogins % - adjusting my options accordingly.\n"
.postf(this, newMaxLogins);
} {
"%: server process's maxLogins (%) matches with my options.\n"
.postf(this, newMaxLogins);
};
options.maxLogins = maxNumClients = newMaxLogins;
} {
"%: no maxLogins info from server process.\n"
.postf(this, newMaxLogins);
};
};
if (newClientID.notNil) {
if (newClientID == clientID) {
"%: keeping clientID (%) as confirmed by server process.\n"
.postf(this, newClientID);
} {
"%: setting clientID to %, as obtained from server process.\n"
.postf(this, newClientID);
};
this.clientID = newClientID;
};
}
prHandleNotifyFailString {|failString, msg|
// post info on some known error cases
case
{ failString.asString.contains("already registered") } {
// when already registered, msg[3] is the clientID by which
// the requesting client was registered previously
"% - already registered with clientID %.\n".postf(this, msg[3]);
statusWatcher.prHandleLoginWhenAlreadyRegistered(msg[3]);
} { failString.asString.contains("not registered") } {
// unregister when already not registered:
"% - not registered.\n".postf(this);
statusWatcher.notified = false;
} { failString.asString.contains("too many users") } {
"% - could not register, too many users.\n".postf(this);
statusWatcher.notified = false;
} {
// throw error if unknown failure
Error(
"Failed to register with server '%' for notifications: %\n"
"To recover, please reboot the server.".format(this, msg)).throw;
};
}
/* network messages */
sendMsg { |... msg|
addr.sendMsg(*msg)
}
sendBundle { |time ... msgs|
addr.sendBundle(time, *msgs)
}
sendRaw { |rawArray|
addr.sendRaw(rawArray)
}
sendMsgSync { |condition ... args|
var cmdName, resp;
if(condition.isNil) { condition = Condition.new };
cmdName = args[0].asString;
if(cmdName[0] != $/) { cmdName = cmdName.insert(0, $/) };
resp = OSCFunc({|msg|
if(msg[1].asString == cmdName) {
resp.free;
condition.test = true;
condition.signal;
};
}, '/done', addr);
condition.test = false;
addr.sendBundle(nil, args);
condition.wait;
}
sync { |condition, bundles, latency| // array of bundles that cause async action
addr.sync(condition, bundles, latency)
}
schedSync { |func|
syncTasks = syncTasks.add(func);
if(syncThread.isNil) {
syncThread = Routine.run {
var c = Condition.new;
while { syncTasks.notEmpty } { syncTasks.removeAt(0).value(c) };
syncThread = nil;
}
}
}
listSendMsg { |msg|
addr.sendMsg(*msg)
}
listSendBundle { |time, msgs|
addr.sendBundle(time, *(msgs.asArray))
}
reorder { |nodeList, target, addAction=\addToHead|
target = target.asTarget;
this.sendMsg(62, Node.actionNumberFor(addAction), target.nodeID, *(nodeList.collect(_.nodeID))) //"/n_order"
}
// load from disk locally, send remote
sendSynthDef { |name, dir|
var file, buffer;
dir = dir ? SynthDef.synthDefDir;
file = File(dir ++ name ++ ".scsyndef","r");
if(file.isOpen.not) { ^nil };
protect {
buffer = Int8Array.newClear(file.length);
file.read(buffer);
} {
file.close;
};
this.sendMsg("/d_recv", buffer);
}
// tell server to load from disk
loadSynthDef { |name, completionMsg, dir|
dir = dir ? SynthDef.synthDefDir;
this.listSendMsg(
["/d_load", dir ++ name ++ ".scsyndef", completionMsg ]
)
}
//loadDir
loadDirectory { |dir, completionMsg|
this.listSendMsg(["/d_loadDir", dir, completionMsg])
}
/* network message bundling */
openBundle { |bundle| // pass in a bundle that you want to
// continue adding to, or nil for a new bundle.
if(addr.hasBundle) {
bundle = addr.bundle.addAll(bundle);
addr.bundle = []; // debatable
};
addr = BundleNetAddr.copyFrom(addr, bundle);
}
closeBundle { |time| // set time to false if you don't want to send.
var bundle;
if(addr.hasBundle) {
bundle = addr.closeBundle(time);
addr = addr.saveAddr;
} {
"there is no open bundle.".warn
};
^bundle;
}
makeBundle { |time, func, bundle|
this.openBundle(bundle);
try {
func.value(this);
bundle = this.closeBundle(time);
} {|error|
addr = addr.saveAddr; // on error restore the normal NetAddr
error.throw
}
^bundle
}
bind { |func|
^this.makeBundle(this.latency, func)
}
/* scheduling */
wait { |responseName|
var routine = thisThread;
OSCFunc({
routine.resume(true)
}, responseName, addr).oneShot;
}
waitForBoot { |onComplete, limit = 100, onFailure|
// onFailure.true: why is this necessary?
// this.boot also calls doWhenBooted.
// doWhenBooted prints the normal boot failure message.
// if the server fails to boot, the failure error gets posted TWICE.
// So, we suppress one of them.
if(this.serverRunning.not) { this.boot(onFailure: true) };
this.doWhenBooted(onComplete, limit, onFailure);
}
doWhenBooted { |onComplete, limit=100, onFailure|
statusWatcher.doWhenBooted(onComplete, limit, onFailure)
}
ifRunning { |func, failFunc|
^if(statusWatcher.unresponsive) {
"server '%' not responsive".format(this.name).postln;
failFunc.value(this)
} {
if(statusWatcher.serverRunning) {
func.value(this)
} {
"server '%' not running".format(this.name).postln;
failFunc.value(this)
}
}
}
ifNotRunning { |func|
^ifRunning(this, nil, func)
}
bootSync { |condition|
condition ?? { condition = Condition.new };
condition.test = false;
this.waitForBoot {
// Setting func to true indicates that our condition has become true and we can go when signaled.
condition.test = true;
condition.signal
};
condition.wait;
}
ping { |n = 1, wait = 0.1, func|
var result = 0, pingFunc;
if(statusWatcher.serverRunning.not) { "server not running".postln; ^this };
pingFunc = {
Routine.run {
var t, dt;
t = Main.elapsedTime;
this.sync;
dt = Main.elapsedTime - t;
("measured latency:" + dt + "s").postln;
result = max(result, dt);
n = n - 1;
if(n > 0) {
SystemClock.sched(wait, { pingFunc.value; nil })
} {
("maximum determined latency of" + name + ":" + result + "s").postln;
func.value(result)
}
};
};
pingFunc.value;
}
cachedBuffersDo { |func|
Buffer.cachedBuffersDo(this, func)
}
cachedBufferAt { |bufnum|
^Buffer.cachedBufferAt(this, bufnum)
}
// keep defaultGroups for all clients on this server:
makeDefaultGroups {
defaultGroups = this.maxNumClients.collect { |clientID|
Group.basicNew(this, nodeAllocator.numIDs * clientID + 1);
};
defaultGroup = defaultGroups[clientID];
}
defaultGroupID { ^defaultGroup.nodeID }
sendDefaultGroups {
defaultGroups.do { |group|
this.sendMsg("/g_new", group.nodeID, 0, 0);
};
}
sendDefaultGroupsForClientIDs { |clientIDs|
defaultGroups[clientIDs].do { |group|
this.sendMsg("/g_new", group.nodeID, 0, 0);
}
}
inputBus {
^Bus(\audio, this.options.numOutputBusChannels, this.options.numInputBusChannels, this)
}
outputBus {
^Bus(\audio, 0, this.options.numOutputBusChannels, this)
}
/* recording formats */
recHeaderFormat { ^options.recHeaderFormat }
recHeaderFormat_ { |string| options.recHeaderFormat_(string) }
recSampleFormat { ^options.recSampleFormat }
recSampleFormat_ { |string| options.recSampleFormat_(string) }
recChannels { ^options.recChannels }
recChannels_ { |n| options.recChannels_(n) }
recBufSize { ^options.recBufSize }
recBufSize_ { |n| options.recBufSize_(n) }
/* server status */
numUGens { ^statusWatcher.numUGens }
numSynths { ^statusWatcher.numSynths }
numGroups { ^statusWatcher.numGroups }
numSynthDefs { ^statusWatcher.numSynthDefs }
avgCPU { ^statusWatcher.avgCPU }
peakCPU { ^statusWatcher.peakCPU }
sampleRate { ^statusWatcher.sampleRate }
actualSampleRate { ^statusWatcher.actualSampleRate }
hasBooted { ^statusWatcher.hasBooted }
serverRunning { ^statusWatcher.serverRunning }
serverBooting { ^statusWatcher.serverBooting }
unresponsive { ^statusWatcher.unresponsive }
startAliveThread { | delay=0.0 | statusWatcher.startAliveThread(delay) }
stopAliveThread { statusWatcher.stopAliveThread }
aliveThreadIsRunning { ^statusWatcher.aliveThread.isPlaying }
aliveThreadPeriod_ { |val| statusWatcher.aliveThreadPeriod_(val) }
aliveThreadPeriod { |val| ^statusWatcher.aliveThreadPeriod }
disconnectSharedMemory {
if(this.hasShmInterface) {
"server '%' disconnected shared memory interface\n".postf(name);
serverInterface.disconnect;
serverInterface = nil;
}
}
connectSharedMemory {
var id;
if(this.isLocal) {
this.disconnectSharedMemory;
id = if(this.inProcess) { thisProcess.pid } { addr.port };
serverInterface = ServerShmInterface(id);
}
}
hasShmInterface { ^serverInterface.notNil }
*resumeThreads {
all.do { |server| server.statusWatcher.resumeThread }
}
boot { | startAliveThread = true, recover = false, onFailure |
if(statusWatcher.unresponsive) {
"server '%' unresponsive, rebooting ...".format(this.name).postln;
this.quit(watchShutDown: false)
};
if(statusWatcher.serverRunning) { "server '%' already running".format(this.name).postln; ^this };
if(statusWatcher.serverBooting) { "server '%' already booting".format(this.name).postln; ^this };
statusWatcher.serverBooting = true;
statusWatcher.doWhenBooted({
statusWatcher.serverBooting = false;
this.bootInit(recover);
}, onFailure: onFailure ? false);
if(remoteControlled) {
"You will have to manually boot remote server.".postln;
} {
this.prPingApp({
this.quit;
this.boot;
}, {
this.prWaitForPidRelease {
this.bootServerApp({
if(startAliveThread) { statusWatcher.startAliveThread }
})
};
}, 0.25);
}
}
prWaitForPidRelease { |onComplete, onFailure, timeout = 1|
var waiting = true;
if (this.inProcess or: { this.isLocal.not or: { this.pid.isNil } }) {
onComplete.value;
^this
};
// FIXME: quick and dirty fix for supernova reboot hang on macOS:
// if we have just quit before running server.boot,
// we wait until server process really ends and sets its pid to nil
SystemClock.sched(timeout, {
if (waiting) {
pidReleaseCondition.unhang
}
});
forkIfNeeded {
pidReleaseCondition.hang;
if (pidReleaseCondition.test.value) {
waiting = false;
onComplete.value;
} {
onFailure.value
}
}
}
// FIXME: recover should happen later, after we have a valid clientID!
// would then need check whether maxLogins and clientID have changed or not,
// and recover would only be possible if no changes.
bootInit { | recover = false |
// if(recover) { this.newNodeAllocators } {
// "% calls newAllocators\n".postf(thisMethod);
// this.newAllocators };
if(dumpMode != 0) { this.sendMsg(\dumpOSC, dumpMode) };
if(sendQuit.isNil) {
sendQuit = this.inProcess or: { this.isLocal };
};
this.connectSharedMemory;
}
prOnServerProcessExit { |exitCode|
pid = nil;
pidReleaseCondition.signal;
"Server '%' exited with exit code %."
.format(this.name, exitCode)
.postln;
statusWatcher.quit(watchShutDown: false);
}
bootServerApp { |onComplete|
if(inProcess) {
"Booting internal server.".postln;
this.bootInProcess;
pid = thisProcess.pid;
onComplete.value;
} {
this.disconnectSharedMemory;
pid = unixCmd(program ++ options.asOptionsString(addr.port), { |exitCode|
this.prOnServerProcessExit(exitCode);
});
("Booting server '%' on address %:%.").format(this.name, addr.hostname, addr.port.asString).postln;
if(options.protocol == \tcp, { addr.tryConnectTCP(onComplete) }, onComplete);
}
}
reboot { |func, onFailure| // func is evaluated when server is off
if(isLocal.not) { "can't reboot a remote server".postln; ^this };
if(statusWatcher.serverRunning and: { this.unresponsive.not }) {
this.quit({
func.value;
defer { this.boot }
}, onFailure);
} {
func.value;
this.boot(onFailure: onFailure);
}
}
applicationRunning {
^pid.tryPerform(\pidRunning) == true
}
status {
addr.sendStatusMsg // backward compatibility
}
sendStatusMsg {
addr.sendStatusMsg
}
notify {
^statusWatcher.notify
}
notify_ { |flag|
statusWatcher.notify_(flag)
}
notified {
^statusWatcher.notified
}
dumpOSC { |code = 1|
/*
0 - turn dumping OFF.
1 - print the parsed contents of the message.
2 - print the contents in hexadecimal.
3 - print both the parsed and hexadecimal representations of the contents.
*/
dumpMode = code;
this.sendMsg(\dumpOSC, code);
this.changed(\dumpOSC, code);
}
quit { |onComplete, onFailure, watchShutDown = true|
var func;
addr.sendMsg("/quit");
if(watchShutDown and: { this.unresponsive }) {
"Server '%' was unresponsive. Quitting anyway.".format(name).postln;
watchShutDown = false;
};
if(options.protocol == \tcp) {
statusWatcher.quit({ addr.tryDisconnectTCP(onComplete, onFailure) }, nil, watchShutDown);
} {
statusWatcher.quit(onComplete, onFailure, watchShutDown);
};
if(inProcess) {
this.quitInProcess;
"Internal server has quit.".postln;
} {
"'/quit' message sent to server '%'.".format(name).postln;
};
// let server process reset pid to nil!
// pid = nil;
sendQuit = nil;
maxNumClients = nil;
if(scopeWindow.notNil) { scopeWindow.quit };
volume.freeSynth;
RootNode(this).freeAll;
this.newAllocators;
}
*quitAll { |watchShutDown = true|
all.do { |server|
if(server.sendQuit === true) {
server.quit(watchShutDown: watchShutDown)
}
}
}
*killAll {
// if you see Exception in World_OpenUDP: unable to bind udp socket
// its because you have multiple servers running, left
// over from crashes, unexpected quits etc.
// you can't cause them to quit via OSC (the boot button)
// this brutally kills them all off
thisProcess.platform.killAll(this.program.basename);
this.quitAll(watchShutDown: false);
}
freeAll {
this.sendMsg("/g_freeAll", 0);
this.sendMsg("/clearSched");
this.initTree;
}
freeMyDefaultGroup {
this.sendMsg("/g_freeAll", defaultGroup.nodeID);
}
freeDefaultGroups {
defaultGroups.do { |group|
this.sendMsg("/g_freeAll", group.nodeID);
};
}
*freeAll { |evenRemote = false|
if(evenRemote) {
all.do { |server|
if( server.serverRunning ) { server.freeAll }
}
} {
all.do { |server|
if(server.isLocal and:{ server.serverRunning }) { server.freeAll }
}
}
}
*hardFreeAll { |evenRemote = false|
if(evenRemote) {
all.do { |server|
server.freeAll
}
} {
all.do { |server|
if(server.isLocal) { server.freeAll }
}
}
}
*allBootedServers {
^this.all.select(_.hasBooted)
}
*allRunningServers {
^this.all.select(_.serverRunning)
}
/* volume control */
volume_ { | newVolume |
volume.volume_(newVolume)
}
mute {
volume.mute
}
unmute {
volume.unmute
}
/* recording output */
record { |path, bus, numChannels, node, duration| recorder.record(path, bus, numChannels, node, duration) }
isRecording { ^recorder.isRecording }
pauseRecording { recorder.pauseRecording }
stopRecording { recorder.stopRecording }
prepareForRecord { |path, numChannels| recorder.prepareForRecord(path, numChannels) }
/* internal server commands */
bootInProcess {
^options.bootInProcess;
}
quitInProcess {
_QuitInProcessServer
^this.primitiveFailed
}
allocSharedControls { |numControls=1024|
_AllocSharedControls
^this.primitiveFailed
}
setSharedControl { |num, value|
_SetSharedControl
^this.primitiveFailed
}
getSharedControl { |num|
_GetSharedControl
^this.primitiveFailed
}
prPingApp { |func, onFailure, timeout = 3|
var id = func.hash;
var resp = OSCFunc({ |msg| if(msg[1] == id, { func.value; task.stop }) }, "/synced", addr);
var task = timeout !? { fork { timeout.wait; resp.free; onFailure.value } };
addr.sendMsg("/sync", id);
}
/* CmdPeriod support for Server-scope and Server-record and Server-volume */
cmdPeriod {
addr = addr.recover;
this.changed(\cmdPeriod)
}
queryAllNodes { | queryControls = false |
var resp, done = false;
if(isLocal) {
this.sendMsg("/g_dumpTree", 0, queryControls.binaryValue)
} {
resp = OSCFunc({ |msg|
var i = 2, tabs = 0, printControls = false, dumpFunc;
if(msg[1] != 0) { printControls = true };
("NODE TREE Group" + msg[2]).postln;
if(msg[3] > 0) {
dumpFunc = {|numChildren|
var j;
tabs = tabs + 1;
numChildren.do {
if(msg[i + 1] >= 0) { i = i + 2 } {
i = i + 3 + if(printControls) { msg[i + 3] * 2 + 1 } { 0 };
};
tabs.do { " ".post };
msg[i].post; // nodeID
if(msg[i + 1] >= 0) {
" group".postln;
if(msg[i + 1] > 0) { dumpFunc.value(msg[i + 1]) };
} {
(" " ++ msg[i + 2]).postln; // defname
if(printControls) {
if(msg[i + 3] > 0) {
" ".post;
tabs.do { " ".post };
};
j = 0;
msg[i + 3].do {
" ".post;
if(msg[i + 4 + j].isMemberOf(Symbol)) {
(msg[i + 4 + j] ++ ": ").post;
};
msg[i + 5 + j].post;
j = j + 2;
};
"\n".post;
}
}
};
tabs = tabs - 1;
};
dumpFunc.value(msg[3]);
};
done = true;
}, '/g_queryTree.reply', addr).oneShot;
this.sendMsg("/g_queryTree", 0, queryControls.binaryValue);
SystemClock.sched(3, {
if(done.not) {
resp.free;
"Remote server failed to respond to queryAllNodes!".warn;
};
})
}
}
printOn { |stream|
stream << name;
}
storeOn { |stream|
var codeStr = switch(this,
Server.default, { if(sync_s) { "s" } { "Server.default" } },
Server.local, { "Server.local" },
Server.internal, { "Server.internal" },
{ "Server.fromName(" + name.asCompileString + ")" }
);
stream << codeStr;
}
archiveAsCompileString { ^true }
archiveAsObject { ^true }
getControlBusValue {|busIndex|
if(serverInterface.isNil) {
Error("Server-getControlBusValue only supports local servers").throw;
} {
^serverInterface.getControlBusValue(busIndex)
}
}
getControlBusValues {|busIndex, busChannels|
if(serverInterface.isNil) {
Error("Server-getControlBusValues only supports local servers").throw;
} {
^serverInterface.getControlBusValues(busIndex, busChannels)
}
}
setControlBusValue {|busIndex, value|
if(serverInterface.isNil) {
Error("Server-getControlBusValue only supports local servers").throw;
} {
^serverInterface.setControlBusValue(busIndex, value)
}
}
setControlBusValues {|busIndex, valueArray|
if(serverInterface.isNil) {
Error("Server-getControlBusValues only supports local servers").throw;
} {
^serverInterface.setControlBusValues(busIndex, valueArray)
}
}
*scsynth {
this.program = this.program.replace("supernova", "scsynth")
}
*supernova {
this.program = this.program.replace("scsynth", "supernova")
}
}
|