osc-browser.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  1. /*! osc.js 2.4.1, Copyright 2020 Colin Clark | github.com/colinbdclark/osc.js */
  2. /*
  3. * osc.js: An Open Sound Control library for JavaScript that works in both the browser and Node.js
  4. *
  5. * Copyright 2014-2016, Colin Clark
  6. * Licensed under the MIT and GPL 3 licenses.
  7. */
  8. /* global require, module, process, Buffer, Long, util */
  9. var osc = osc || {};
  10. (function () {
  11. "use strict";
  12. osc.SECS_70YRS = 2208988800;
  13. osc.TWO_32 = 4294967296;
  14. osc.defaults = {
  15. metadata: false,
  16. unpackSingleArgs: true
  17. };
  18. // Unsupported, non-API property.
  19. osc.isCommonJS = typeof module !== "undefined" && module.exports ? true : false;
  20. // Unsupported, non-API property.
  21. osc.isNode = osc.isCommonJS && typeof window === "undefined";
  22. // Unsupported, non-API property.
  23. osc.isElectron = typeof process !== "undefined" &&
  24. process.versions && process.versions.electron ? true : false;
  25. // Unsupported, non-API property.
  26. osc.isBufferEnv = osc.isNode || osc.isElectron;
  27. // Unsupported, non-API function.
  28. osc.isArray = function (obj) {
  29. return obj && Object.prototype.toString.call(obj) === "[object Array]";
  30. };
  31. // Unsupported, non-API function.
  32. osc.isTypedArrayView = function (obj) {
  33. return obj.buffer && obj.buffer instanceof ArrayBuffer;
  34. };
  35. // Unsupported, non-API function.
  36. osc.isBuffer = function (obj) {
  37. return osc.isBufferEnv && obj instanceof Buffer;
  38. };
  39. // Unsupported, non-API member.
  40. osc.Long = typeof Long !== "undefined" ? Long :
  41. osc.isNode ? require("long") : undefined;
  42. // Unsupported, non-API member. Can be removed when supported versions
  43. // of Node.js expose TextDecoder as a global, as in the browser.
  44. osc.TextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8") :
  45. typeof util !== "undefined" && typeof (util.TextDecoder !== "undefined") ? new util.TextDecoder("utf-8") : undefined;
  46. osc.TextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") :
  47. typeof util !== "undefined" && typeof (util.TextEncoder !== "undefined") ? new util.TextEncoder("utf-8") : undefined;
  48. /**
  49. * Wraps the specified object in a DataView.
  50. *
  51. * @param {Array-like} obj the object to wrap in a DataView instance
  52. * @return {DataView} the DataView object
  53. */
  54. // Unsupported, non-API function.
  55. osc.dataView = function (obj, offset, length) {
  56. if (obj.buffer) {
  57. return new DataView(obj.buffer, offset, length);
  58. }
  59. if (obj instanceof ArrayBuffer) {
  60. return new DataView(obj, offset, length);
  61. }
  62. return new DataView(new Uint8Array(obj), offset, length);
  63. };
  64. /**
  65. * Takes an ArrayBuffer, TypedArray, DataView, Buffer, or array-like object
  66. * and returns a Uint8Array view of it.
  67. *
  68. * Throws an error if the object isn't suitably array-like.
  69. *
  70. * @param {Array-like or Array-wrapping} obj an array-like or array-wrapping object
  71. * @returns {Uint8Array} a typed array of octets
  72. */
  73. // Unsupported, non-API function.
  74. osc.byteArray = function (obj) {
  75. if (obj instanceof Uint8Array) {
  76. return obj;
  77. }
  78. var buf = obj.buffer ? obj.buffer : obj;
  79. if (!(buf instanceof ArrayBuffer) && (typeof buf.length === "undefined" || typeof buf === "string")) {
  80. throw new Error("Can't wrap a non-array-like object as Uint8Array. Object was: " +
  81. JSON.stringify(obj, null, 2));
  82. }
  83. // TODO gh-39: This is a potentially unsafe algorithm;
  84. // if we're getting anything other than a TypedArrayView (such as a DataView),
  85. // we really need to determine the range of the view it is viewing.
  86. return new Uint8Array(buf);
  87. };
  88. /**
  89. * Takes an ArrayBuffer, TypedArray, DataView, or array-like object
  90. * and returns a native buffer object
  91. * (i.e. in Node.js, a Buffer object and in the browser, a Uint8Array).
  92. *
  93. * Throws an error if the object isn't suitably array-like.
  94. *
  95. * @param {Array-like or Array-wrapping} obj an array-like or array-wrapping object
  96. * @returns {Buffer|Uint8Array} a buffer object
  97. */
  98. // Unsupported, non-API function.
  99. osc.nativeBuffer = function (obj) {
  100. if (osc.isBufferEnv) {
  101. return osc.isBuffer(obj) ? obj :
  102. Buffer.from(obj.buffer ? obj : new Uint8Array(obj));
  103. }
  104. return osc.isTypedArrayView(obj) ? obj : new Uint8Array(obj);
  105. };
  106. // Unsupported, non-API function
  107. osc.copyByteArray = function (source, target, offset) {
  108. if (osc.isTypedArrayView(source) && osc.isTypedArrayView(target)) {
  109. target.set(source, offset);
  110. } else {
  111. var start = offset === undefined ? 0 : offset,
  112. len = Math.min(target.length - offset, source.length);
  113. for (var i = 0, j = start; i < len; i++, j++) {
  114. target[j] = source[i];
  115. }
  116. }
  117. return target;
  118. };
  119. /**
  120. * Reads an OSC-formatted string.
  121. *
  122. * @param {DataView} dv a DataView containing the raw bytes of the OSC string
  123. * @param {Object} offsetState an offsetState object used to store the current offset index
  124. * @return {String} the JavaScript String that was read
  125. */
  126. osc.readString = function (dv, offsetState) {
  127. var charCodes = [],
  128. idx = offsetState.idx;
  129. for (; idx < dv.byteLength; idx++) {
  130. var charCode = dv.getUint8(idx);
  131. if (charCode !== 0) {
  132. charCodes.push(charCode);
  133. } else {
  134. idx++;
  135. break;
  136. }
  137. }
  138. // Round to the nearest 4-byte block.
  139. idx = (idx + 3) & ~0x03;
  140. offsetState.idx = idx;
  141. var decoder = osc.isBufferEnv ? osc.readString.withBuffer :
  142. osc.TextDecoder ? osc.readString.withTextDecoder : osc.readString.raw;
  143. return decoder(charCodes);
  144. };
  145. osc.readString.raw = function (charCodes) {
  146. // If no Buffer or TextDecoder, resort to fromCharCode
  147. // This does not properly decode multi-byte Unicode characters.
  148. var str = "";
  149. var sliceSize = 10000;
  150. // Processing the array in chunks so as not to exceed argument
  151. // limit, see https://bugs.webkit.org/show_bug.cgi?id=80797
  152. for (var i = 0; i < charCodes.length; i += sliceSize) {
  153. str += String.fromCharCode.apply(null, charCodes.slice(i, i + sliceSize));
  154. }
  155. return str;
  156. };
  157. osc.readString.withTextDecoder = function (charCodes) {
  158. var data = new Int8Array(charCodes);
  159. return osc.TextDecoder.decode(data);
  160. };
  161. osc.readString.withBuffer = function (charCodes) {
  162. return Buffer.from(charCodes).toString("utf-8");
  163. };
  164. /**
  165. * Writes a JavaScript string as an OSC-formatted string.
  166. *
  167. * @param {String} str the string to write
  168. * @return {Uint8Array} a buffer containing the OSC-formatted string
  169. */
  170. osc.writeString = function (str) {
  171. var terminated = str + "\u0000",
  172. len = terminated.length,
  173. paddedLen = (len + 3) & ~0x03,
  174. arr = new Uint8Array(paddedLen);
  175. var encoder = osc.isBufferEnv ? osc.writeString.withBuffer :
  176. osc.TextEncoder ? osc.writeString.withTextEncoder : null,
  177. encodedStr;
  178. if (encoder) {
  179. encodedStr = encoder(terminated);
  180. }
  181. for (var i = 0; i < terminated.length; i++) {
  182. var charCode = encoder ? encodedStr[i] : terminated.charCodeAt(i);
  183. arr[i] = charCode;
  184. }
  185. return arr;
  186. };
  187. osc.writeString.withTextEncoder = function (str) {
  188. return osc.TextEncoder.encode(str);
  189. };
  190. osc.writeString.withBuffer = function (str) {
  191. return Buffer.from(str);
  192. };
  193. // Unsupported, non-API function.
  194. osc.readPrimitive = function (dv, readerName, numBytes, offsetState) {
  195. var val = dv[readerName](offsetState.idx, false);
  196. offsetState.idx += numBytes;
  197. return val;
  198. };
  199. // Unsupported, non-API function.
  200. osc.writePrimitive = function (val, dv, writerName, numBytes, offset) {
  201. offset = offset === undefined ? 0 : offset;
  202. var arr;
  203. if (!dv) {
  204. arr = new Uint8Array(numBytes);
  205. dv = new DataView(arr.buffer);
  206. } else {
  207. arr = new Uint8Array(dv.buffer);
  208. }
  209. dv[writerName](offset, val, false);
  210. return arr;
  211. };
  212. /**
  213. * Reads an OSC int32 ("i") value.
  214. *
  215. * @param {DataView} dv a DataView containing the raw bytes
  216. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  217. * @return {Number} the number that was read
  218. */
  219. osc.readInt32 = function (dv, offsetState) {
  220. return osc.readPrimitive(dv, "getInt32", 4, offsetState);
  221. };
  222. /**
  223. * Writes an OSC int32 ("i") value.
  224. *
  225. * @param {Number} val the number to write
  226. * @param {DataView} [dv] a DataView instance to write the number into
  227. * @param {Number} [offset] an offset into dv
  228. */
  229. osc.writeInt32 = function (val, dv, offset) {
  230. return osc.writePrimitive(val, dv, "setInt32", 4, offset);
  231. };
  232. /**
  233. * Reads an OSC int64 ("h") value.
  234. *
  235. * @param {DataView} dv a DataView containing the raw bytes
  236. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  237. * @return {Number} the number that was read
  238. */
  239. osc.readInt64 = function (dv, offsetState) {
  240. var high = osc.readPrimitive(dv, "getInt32", 4, offsetState),
  241. low = osc.readPrimitive(dv, "getInt32", 4, offsetState);
  242. if (osc.Long) {
  243. return new osc.Long(low, high);
  244. } else {
  245. return {
  246. high: high,
  247. low: low,
  248. unsigned: false
  249. };
  250. }
  251. };
  252. /**
  253. * Writes an OSC int64 ("h") value.
  254. *
  255. * @param {Number} val the number to write
  256. * @param {DataView} [dv] a DataView instance to write the number into
  257. * @param {Number} [offset] an offset into dv
  258. */
  259. osc.writeInt64 = function (val, dv, offset) {
  260. var arr = new Uint8Array(8);
  261. arr.set(osc.writePrimitive(val.high, dv, "setInt32", 4, offset), 0);
  262. arr.set(osc.writePrimitive(val.low, dv, "setInt32", 4, offset + 4), 4);
  263. return arr;
  264. };
  265. /**
  266. * Reads an OSC float32 ("f") value.
  267. *
  268. * @param {DataView} dv a DataView containing the raw bytes
  269. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  270. * @return {Number} the number that was read
  271. */
  272. osc.readFloat32 = function (dv, offsetState) {
  273. return osc.readPrimitive(dv, "getFloat32", 4, offsetState);
  274. };
  275. /**
  276. * Writes an OSC float32 ("f") value.
  277. *
  278. * @param {Number} val the number to write
  279. * @param {DataView} [dv] a DataView instance to write the number into
  280. * @param {Number} [offset] an offset into dv
  281. */
  282. osc.writeFloat32 = function (val, dv, offset) {
  283. return osc.writePrimitive(val, dv, "setFloat32", 4, offset);
  284. };
  285. /**
  286. * Reads an OSC float64 ("d") value.
  287. *
  288. * @param {DataView} dv a DataView containing the raw bytes
  289. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  290. * @return {Number} the number that was read
  291. */
  292. osc.readFloat64 = function (dv, offsetState) {
  293. return osc.readPrimitive(dv, "getFloat64", 8, offsetState);
  294. };
  295. /**
  296. * Writes an OSC float64 ("d") value.
  297. *
  298. * @param {Number} val the number to write
  299. * @param {DataView} [dv] a DataView instance to write the number into
  300. * @param {Number} [offset] an offset into dv
  301. */
  302. osc.writeFloat64 = function (val, dv, offset) {
  303. return osc.writePrimitive(val, dv, "setFloat64", 8, offset);
  304. };
  305. /**
  306. * Reads an OSC 32-bit ASCII character ("c") value.
  307. *
  308. * @param {DataView} dv a DataView containing the raw bytes
  309. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  310. * @return {String} a string containing the read character
  311. */
  312. osc.readChar32 = function (dv, offsetState) {
  313. var charCode = osc.readPrimitive(dv, "getUint32", 4, offsetState);
  314. return String.fromCharCode(charCode);
  315. };
  316. /**
  317. * Writes an OSC 32-bit ASCII character ("c") value.
  318. *
  319. * @param {String} str the string from which the first character will be written
  320. * @param {DataView} [dv] a DataView instance to write the character into
  321. * @param {Number} [offset] an offset into dv
  322. * @return {String} a string containing the read character
  323. */
  324. osc.writeChar32 = function (str, dv, offset) {
  325. var charCode = str.charCodeAt(0);
  326. if (charCode === undefined || charCode < -1) {
  327. return undefined;
  328. }
  329. return osc.writePrimitive(charCode, dv, "setUint32", 4, offset);
  330. };
  331. /**
  332. * Reads an OSC blob ("b") (i.e. a Uint8Array).
  333. *
  334. * @param {DataView} dv a DataView instance to read from
  335. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  336. * @return {Uint8Array} the data that was read
  337. */
  338. osc.readBlob = function (dv, offsetState) {
  339. var len = osc.readInt32(dv, offsetState),
  340. paddedLen = (len + 3) & ~0x03,
  341. blob = new Uint8Array(dv.buffer, offsetState.idx, len);
  342. offsetState.idx += paddedLen;
  343. return blob;
  344. };
  345. /**
  346. * Writes a raw collection of bytes to a new ArrayBuffer.
  347. *
  348. * @param {Array-like} data a collection of octets
  349. * @return {ArrayBuffer} a buffer containing the OSC-formatted blob
  350. */
  351. osc.writeBlob = function (data) {
  352. data = osc.byteArray(data);
  353. var len = data.byteLength,
  354. paddedLen = (len + 3) & ~0x03,
  355. offset = 4, // Extra 4 bytes is for the size.
  356. blobLen = paddedLen + offset,
  357. arr = new Uint8Array(blobLen),
  358. dv = new DataView(arr.buffer);
  359. // Write the size.
  360. osc.writeInt32(len, dv);
  361. // Since we're writing to a real ArrayBuffer,
  362. // we don't need to pad the remaining bytes.
  363. arr.set(data, offset);
  364. return arr;
  365. };
  366. /**
  367. * Reads an OSC 4-byte MIDI message.
  368. *
  369. * @param {DataView} dv the DataView instance to read from
  370. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  371. * @return {Uint8Array} an array containing (in order) the port ID, status, data1 and data1 bytes
  372. */
  373. osc.readMIDIBytes = function (dv, offsetState) {
  374. var midi = new Uint8Array(dv.buffer, offsetState.idx, 4);
  375. offsetState.idx += 4;
  376. return midi;
  377. };
  378. /**
  379. * Writes an OSC 4-byte MIDI message.
  380. *
  381. * @param {Array-like} bytes a 4-element array consisting of the port ID, status, data1 and data1 bytes
  382. * @return {Uint8Array} the written message
  383. */
  384. osc.writeMIDIBytes = function (bytes) {
  385. bytes = osc.byteArray(bytes);
  386. var arr = new Uint8Array(4);
  387. arr.set(bytes);
  388. return arr;
  389. };
  390. /**
  391. * Reads an OSC RGBA colour value.
  392. *
  393. * @param {DataView} dv the DataView instance to read from
  394. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  395. * @return {Object} a colour object containing r, g, b, and a properties
  396. */
  397. osc.readColor = function (dv, offsetState) {
  398. var bytes = new Uint8Array(dv.buffer, offsetState.idx, 4),
  399. alpha = bytes[3] / 255;
  400. offsetState.idx += 4;
  401. return {
  402. r: bytes[0],
  403. g: bytes[1],
  404. b: bytes[2],
  405. a: alpha
  406. };
  407. };
  408. /**
  409. * Writes an OSC RGBA colour value.
  410. *
  411. * @param {Object} color a colour object containing r, g, b, and a properties
  412. * @return {Uint8Array} a byte array containing the written color
  413. */
  414. osc.writeColor = function (color) {
  415. var alpha = Math.round(color.a * 255),
  416. arr = new Uint8Array([color.r, color.g, color.b, alpha]);
  417. return arr;
  418. };
  419. /**
  420. * Reads an OSC true ("T") value by directly returning the JavaScript Boolean "true".
  421. */
  422. osc.readTrue = function () {
  423. return true;
  424. };
  425. /**
  426. * Reads an OSC false ("F") value by directly returning the JavaScript Boolean "false".
  427. */
  428. osc.readFalse = function () {
  429. return false;
  430. };
  431. /**
  432. * Reads an OSC nil ("N") value by directly returning the JavaScript "null" value.
  433. */
  434. osc.readNull = function () {
  435. return null;
  436. };
  437. /**
  438. * Reads an OSC impulse/bang/infinitum ("I") value by directly returning 1.0.
  439. */
  440. osc.readImpulse = function () {
  441. return 1.0;
  442. };
  443. /**
  444. * Reads an OSC time tag ("t").
  445. *
  446. * @param {DataView} dv the DataView instance to read from
  447. * @param {Object} offsetState an offset state object containing the current index into dv
  448. * @param {Object} a time tag object containing both the raw NTP as well as the converted native (i.e. JS/UNIX) time
  449. */
  450. osc.readTimeTag = function (dv, offsetState) {
  451. var secs1900 = osc.readPrimitive(dv, "getUint32", 4, offsetState),
  452. frac = osc.readPrimitive(dv, "getUint32", 4, offsetState),
  453. native = (secs1900 === 0 && frac === 1) ? Date.now() : osc.ntpToJSTime(secs1900, frac);
  454. return {
  455. raw: [secs1900, frac],
  456. native: native
  457. };
  458. };
  459. /**
  460. * Writes an OSC time tag ("t").
  461. *
  462. * Takes, as its argument, a time tag object containing either a "raw" or "native property."
  463. * The raw timestamp must conform to the NTP standard representation, consisting of two unsigned int32
  464. * values. The first represents the number of seconds since January 1, 1900; the second, fractions of a second.
  465. * "Native" JavaScript timestamps are specified as a Number representing milliseconds since January 1, 1970.
  466. *
  467. * @param {Object} timeTag time tag object containing either a native JS timestamp (in ms) or a NTP timestamp pair
  468. * @return {Uint8Array} raw bytes for the written time tag
  469. */
  470. osc.writeTimeTag = function (timeTag) {
  471. var raw = timeTag.raw ? timeTag.raw : osc.jsToNTPTime(timeTag.native),
  472. arr = new Uint8Array(8), // Two Unit32s.
  473. dv = new DataView(arr.buffer);
  474. osc.writeInt32(raw[0], dv, 0);
  475. osc.writeInt32(raw[1], dv, 4);
  476. return arr;
  477. };
  478. /**
  479. * Produces a time tag containing a raw NTP timestamp
  480. * relative to now by the specified number of seconds.
  481. *
  482. * @param {Number} secs the number of seconds relative to now (i.e. + for the future, - for the past)
  483. * @param {Number} now the number of milliseconds since epoch to use as the current time. Defaults to Date.now()
  484. * @return {Object} the time tag
  485. */
  486. osc.timeTag = function (secs, now) {
  487. secs = secs || 0;
  488. now = now || Date.now();
  489. var nowSecs = now / 1000,
  490. nowWhole = Math.floor(nowSecs),
  491. nowFracs = nowSecs - nowWhole,
  492. secsWhole = Math.floor(secs),
  493. secsFracs = secs - secsWhole,
  494. fracs = nowFracs + secsFracs;
  495. if (fracs > 1) {
  496. var fracsWhole = Math.floor(fracs),
  497. fracsFracs = fracs - fracsWhole;
  498. secsWhole += fracsWhole;
  499. fracs = fracsFracs;
  500. }
  501. var ntpSecs = nowWhole + secsWhole + osc.SECS_70YRS,
  502. ntpFracs = Math.round(osc.TWO_32 * fracs);
  503. return {
  504. raw: [ntpSecs, ntpFracs]
  505. };
  506. };
  507. /**
  508. * Converts OSC's standard time tag representation (which is the NTP format)
  509. * into the JavaScript/UNIX format in milliseconds.
  510. *
  511. * @param {Number} secs1900 the number of seconds since 1900
  512. * @param {Number} frac the number of fractions of a second (between 0 and 2^32)
  513. * @return {Number} a JavaScript-compatible timestamp in milliseconds
  514. */
  515. osc.ntpToJSTime = function (secs1900, frac) {
  516. var secs1970 = secs1900 - osc.SECS_70YRS,
  517. decimals = frac / osc.TWO_32,
  518. msTime = (secs1970 + decimals) * 1000;
  519. return msTime;
  520. };
  521. osc.jsToNTPTime = function (jsTime) {
  522. var secs = jsTime / 1000,
  523. secsWhole = Math.floor(secs),
  524. secsFrac = secs - secsWhole,
  525. ntpSecs = secsWhole + osc.SECS_70YRS,
  526. ntpFracs = Math.round(osc.TWO_32 * secsFrac);
  527. return [ntpSecs, ntpFracs];
  528. };
  529. /**
  530. * Reads the argument portion of an OSC message.
  531. *
  532. * @param {DataView} dv a DataView instance to read from
  533. * @param {Object} offsetState the offsetState object that stores the current offset into dv
  534. * @param {Object} [options] read options
  535. * @return {Array} an array of the OSC arguments that were read
  536. */
  537. osc.readArguments = function (dv, options, offsetState) {
  538. var typeTagString = osc.readString(dv, offsetState);
  539. if (typeTagString.indexOf(",") !== 0) {
  540. // Despite what the OSC 1.0 spec says,
  541. // it just doesn't make sense to handle messages without type tags.
  542. // scsynth appears to read such messages as if they have a single
  543. // Uint8 argument. sclang throws an error if the type tag is omitted.
  544. throw new Error("A malformed type tag string was found while reading " +
  545. "the arguments of an OSC message. String was: " +
  546. typeTagString, " at offset: " + offsetState.idx);
  547. }
  548. var argTypes = typeTagString.substring(1).split(""),
  549. args = [];
  550. osc.readArgumentsIntoArray(args, argTypes, typeTagString, dv, options, offsetState);
  551. return args;
  552. };
  553. // Unsupported, non-API function.
  554. osc.readArgument = function (argType, typeTagString, dv, options, offsetState) {
  555. var typeSpec = osc.argumentTypes[argType];
  556. if (!typeSpec) {
  557. throw new Error("'" + argType + "' is not a valid OSC type tag. Type tag string was: " + typeTagString);
  558. }
  559. var argReader = typeSpec.reader,
  560. arg = osc[argReader](dv, offsetState);
  561. if (options.metadata) {
  562. arg = {
  563. type: argType,
  564. value: arg
  565. };
  566. }
  567. return arg;
  568. };
  569. // Unsupported, non-API function.
  570. osc.readArgumentsIntoArray = function (arr, argTypes, typeTagString, dv, options, offsetState) {
  571. var i = 0;
  572. while (i < argTypes.length) {
  573. var argType = argTypes[i],
  574. arg;
  575. if (argType === "[") {
  576. var fromArrayOpen = argTypes.slice(i + 1),
  577. endArrayIdx = fromArrayOpen.indexOf("]");
  578. if (endArrayIdx < 0) {
  579. throw new Error("Invalid argument type tag: an open array type tag ('[') was found " +
  580. "without a matching close array tag ('[]'). Type tag was: " + typeTagString);
  581. }
  582. var typesInArray = fromArrayOpen.slice(0, endArrayIdx);
  583. arg = osc.readArgumentsIntoArray([], typesInArray, typeTagString, dv, options, offsetState);
  584. i += endArrayIdx + 2;
  585. } else {
  586. arg = osc.readArgument(argType, typeTagString, dv, options, offsetState);
  587. i++;
  588. }
  589. arr.push(arg);
  590. }
  591. return arr;
  592. };
  593. /**
  594. * Writes the specified arguments.
  595. *
  596. * @param {Array} args an array of arguments
  597. * @param {Object} options options for writing
  598. * @return {Uint8Array} a buffer containing the OSC-formatted argument type tag and values
  599. */
  600. osc.writeArguments = function (args, options) {
  601. var argCollection = osc.collectArguments(args, options);
  602. return osc.joinParts(argCollection);
  603. };
  604. // Unsupported, non-API function.
  605. osc.joinParts = function (dataCollection) {
  606. var buf = new Uint8Array(dataCollection.byteLength),
  607. parts = dataCollection.parts,
  608. offset = 0;
  609. for (var i = 0; i < parts.length; i++) {
  610. var part = parts[i];
  611. osc.copyByteArray(part, buf, offset);
  612. offset += part.length;
  613. }
  614. return buf;
  615. };
  616. // Unsupported, non-API function.
  617. osc.addDataPart = function (dataPart, dataCollection) {
  618. dataCollection.parts.push(dataPart);
  619. dataCollection.byteLength += dataPart.length;
  620. };
  621. osc.writeArrayArguments = function (args, dataCollection) {
  622. var typeTag = "[";
  623. for (var i = 0; i < args.length; i++) {
  624. var arg = args[i];
  625. typeTag += osc.writeArgument(arg, dataCollection);
  626. }
  627. typeTag += "]";
  628. return typeTag;
  629. };
  630. osc.writeArgument = function (arg, dataCollection) {
  631. if (osc.isArray(arg)) {
  632. return osc.writeArrayArguments(arg, dataCollection);
  633. }
  634. var type = arg.type,
  635. writer = osc.argumentTypes[type].writer;
  636. if (writer) {
  637. var data = osc[writer](arg.value);
  638. osc.addDataPart(data, dataCollection);
  639. }
  640. return arg.type;
  641. };
  642. // Unsupported, non-API function.
  643. osc.collectArguments = function (args, options, dataCollection) {
  644. if (!osc.isArray(args)) {
  645. args = typeof args === "undefined" ? [] : [args];
  646. }
  647. dataCollection = dataCollection || {
  648. byteLength: 0,
  649. parts: []
  650. };
  651. if (!options.metadata) {
  652. args = osc.annotateArguments(args);
  653. }
  654. var typeTagString = ",",
  655. currPartIdx = dataCollection.parts.length;
  656. for (var i = 0; i < args.length; i++) {
  657. var arg = args[i];
  658. typeTagString += osc.writeArgument(arg, dataCollection);
  659. }
  660. var typeData = osc.writeString(typeTagString);
  661. dataCollection.byteLength += typeData.byteLength;
  662. dataCollection.parts.splice(currPartIdx, 0, typeData);
  663. return dataCollection;
  664. };
  665. /**
  666. * Reads an OSC message.
  667. *
  668. * @param {Array-like} data an array of bytes to read from
  669. * @param {Object} [options] read options
  670. * @param {Object} [offsetState] an offsetState object that stores the current offset into dv
  671. * @return {Object} the OSC message, formatted as a JavaScript object containing "address" and "args" properties
  672. */
  673. osc.readMessage = function (data, options, offsetState) {
  674. options = options || osc.defaults;
  675. var dv = osc.dataView(data, data.byteOffset, data.byteLength);
  676. offsetState = offsetState || {
  677. idx: 0
  678. };
  679. var address = osc.readString(dv, offsetState);
  680. return osc.readMessageContents(address, dv, options, offsetState);
  681. };
  682. // Unsupported, non-API function.
  683. osc.readMessageContents = function (address, dv, options, offsetState) {
  684. if (address.indexOf("/") !== 0) {
  685. throw new Error("A malformed OSC address was found while reading " +
  686. "an OSC message. String was: " + address);
  687. }
  688. var args = osc.readArguments(dv, options, offsetState);
  689. return {
  690. address: address,
  691. args: args.length === 1 && options.unpackSingleArgs ? args[0] : args
  692. };
  693. };
  694. // Unsupported, non-API function.
  695. osc.collectMessageParts = function (msg, options, dataCollection) {
  696. dataCollection = dataCollection || {
  697. byteLength: 0,
  698. parts: []
  699. };
  700. osc.addDataPart(osc.writeString(msg.address), dataCollection);
  701. return osc.collectArguments(msg.args, options, dataCollection);
  702. };
  703. /**
  704. * Writes an OSC message.
  705. *
  706. * @param {Object} msg a message object containing "address" and "args" properties
  707. * @param {Object} [options] write options
  708. * @return {Uint8Array} an array of bytes containing the OSC message
  709. */
  710. osc.writeMessage = function (msg, options) {
  711. options = options || osc.defaults;
  712. if (!osc.isValidMessage(msg)) {
  713. throw new Error("An OSC message must contain a valid address. Message was: " +
  714. JSON.stringify(msg, null, 2));
  715. }
  716. var msgCollection = osc.collectMessageParts(msg, options);
  717. return osc.joinParts(msgCollection);
  718. };
  719. osc.isValidMessage = function (msg) {
  720. return msg.address && msg.address.indexOf("/") === 0;
  721. };
  722. /**
  723. * Reads an OSC bundle.
  724. *
  725. * @param {DataView} dv the DataView instance to read from
  726. * @param {Object} [options] read optoins
  727. * @param {Object} [offsetState] an offsetState object that stores the current offset into dv
  728. * @return {Object} the bundle or message object that was read
  729. */
  730. osc.readBundle = function (dv, options, offsetState) {
  731. return osc.readPacket(dv, options, offsetState);
  732. };
  733. // Unsupported, non-API function.
  734. osc.collectBundlePackets = function (bundle, options, dataCollection) {
  735. dataCollection = dataCollection || {
  736. byteLength: 0,
  737. parts: []
  738. };
  739. osc.addDataPart(osc.writeString("#bundle"), dataCollection);
  740. osc.addDataPart(osc.writeTimeTag(bundle.timeTag), dataCollection);
  741. for (var i = 0; i < bundle.packets.length; i++) {
  742. var packet = bundle.packets[i],
  743. collector = packet.address ? osc.collectMessageParts : osc.collectBundlePackets,
  744. packetCollection = collector(packet, options);
  745. dataCollection.byteLength += packetCollection.byteLength;
  746. osc.addDataPart(osc.writeInt32(packetCollection.byteLength), dataCollection);
  747. dataCollection.parts = dataCollection.parts.concat(packetCollection.parts);
  748. }
  749. return dataCollection;
  750. };
  751. /**
  752. * Writes an OSC bundle.
  753. *
  754. * @param {Object} a bundle object containing "timeTag" and "packets" properties
  755. * @param {object} [options] write options
  756. * @return {Uint8Array} an array of bytes containing the message
  757. */
  758. osc.writeBundle = function (bundle, options) {
  759. if (!osc.isValidBundle(bundle)) {
  760. throw new Error("An OSC bundle must contain 'timeTag' and 'packets' properties. " +
  761. "Bundle was: " + JSON.stringify(bundle, null, 2));
  762. }
  763. options = options || osc.defaults;
  764. var bundleCollection = osc.collectBundlePackets(bundle, options);
  765. return osc.joinParts(bundleCollection);
  766. };
  767. osc.isValidBundle = function (bundle) {
  768. return bundle.timeTag !== undefined && bundle.packets !== undefined;
  769. };
  770. // Unsupported, non-API function.
  771. osc.readBundleContents = function (dv, options, offsetState, len) {
  772. var timeTag = osc.readTimeTag(dv, offsetState),
  773. packets = [];
  774. while (offsetState.idx < len) {
  775. var packetSize = osc.readInt32(dv, offsetState),
  776. packetLen = offsetState.idx + packetSize,
  777. packet = osc.readPacket(dv, options, offsetState, packetLen);
  778. packets.push(packet);
  779. }
  780. return {
  781. timeTag: timeTag,
  782. packets: packets
  783. };
  784. };
  785. /**
  786. * Reads an OSC packet, which may consist of either a bundle or a message.
  787. *
  788. * @param {Array-like} data an array of bytes to read from
  789. * @param {Object} [options] read options
  790. * @return {Object} a bundle or message object
  791. */
  792. osc.readPacket = function (data, options, offsetState, len) {
  793. var dv = osc.dataView(data, data.byteOffset, data.byteLength);
  794. len = len === undefined ? dv.byteLength : len;
  795. offsetState = offsetState || {
  796. idx: 0
  797. };
  798. var header = osc.readString(dv, offsetState),
  799. firstChar = header[0];
  800. if (firstChar === "#") {
  801. return osc.readBundleContents(dv, options, offsetState, len);
  802. } else if (firstChar === "/") {
  803. return osc.readMessageContents(header, dv, options, offsetState);
  804. }
  805. throw new Error("The header of an OSC packet didn't contain an OSC address or a #bundle string." +
  806. " Header was: " + header);
  807. };
  808. /**
  809. * Writes an OSC packet, which may consist of either of a bundle or a message.
  810. *
  811. * @param {Object} a bundle or message object
  812. * @param {Object} [options] write options
  813. * @return {Uint8Array} an array of bytes containing the message
  814. */
  815. osc.writePacket = function (packet, options) {
  816. if (osc.isValidMessage(packet)) {
  817. return osc.writeMessage(packet, options);
  818. } else if (osc.isValidBundle(packet)) {
  819. return osc.writeBundle(packet, options);
  820. } else {
  821. throw new Error("The specified packet was not recognized as a valid OSC message or bundle." +
  822. " Packet was: " + JSON.stringify(packet, null, 2));
  823. }
  824. };
  825. // Unsupported, non-API.
  826. osc.argumentTypes = {
  827. i: {
  828. reader: "readInt32",
  829. writer: "writeInt32"
  830. },
  831. h: {
  832. reader: "readInt64",
  833. writer: "writeInt64"
  834. },
  835. f: {
  836. reader: "readFloat32",
  837. writer: "writeFloat32"
  838. },
  839. s: {
  840. reader: "readString",
  841. writer: "writeString"
  842. },
  843. S: {
  844. reader: "readString",
  845. writer: "writeString"
  846. },
  847. b: {
  848. reader: "readBlob",
  849. writer: "writeBlob"
  850. },
  851. t: {
  852. reader: "readTimeTag",
  853. writer: "writeTimeTag"
  854. },
  855. T: {
  856. reader: "readTrue"
  857. },
  858. F: {
  859. reader: "readFalse"
  860. },
  861. N: {
  862. reader: "readNull"
  863. },
  864. I: {
  865. reader: "readImpulse"
  866. },
  867. d: {
  868. reader: "readFloat64",
  869. writer: "writeFloat64"
  870. },
  871. c: {
  872. reader: "readChar32",
  873. writer: "writeChar32"
  874. },
  875. r: {
  876. reader: "readColor",
  877. writer: "writeColor"
  878. },
  879. m: {
  880. reader: "readMIDIBytes",
  881. writer: "writeMIDIBytes"
  882. },
  883. // [] are special cased within read/writeArguments()
  884. };
  885. // Unsupported, non-API function.
  886. osc.inferTypeForArgument = function (arg) {
  887. var type = typeof arg;
  888. // TODO: This is freaking hideous.
  889. switch (type) {
  890. case "boolean":
  891. return arg ? "T" : "F";
  892. case "string":
  893. return "s";
  894. case "number":
  895. return "f";
  896. case "undefined":
  897. return "N";
  898. case "object":
  899. if (arg === null) {
  900. return "N";
  901. } else if (arg instanceof Uint8Array ||
  902. arg instanceof ArrayBuffer) {
  903. return "b";
  904. } else if (typeof arg.high === "number" && typeof arg.low === "number") {
  905. return "h";
  906. }
  907. break;
  908. }
  909. throw new Error("Can't infer OSC argument type for value: " +
  910. JSON.stringify(arg, null, 2));
  911. };
  912. // Unsupported, non-API function.
  913. osc.annotateArguments = function (args) {
  914. var annotated = [];
  915. for (var i = 0; i < args.length; i++) {
  916. var arg = args[i],
  917. msgArg;
  918. if (typeof (arg) === "object" && arg.type && arg.value !== undefined) {
  919. // We've got an explicitly typed argument.
  920. msgArg = arg;
  921. } else if (osc.isArray(arg)) {
  922. // We've got an array of arguments,
  923. // so they each need to be inferred and expanded.
  924. msgArg = osc.annotateArguments(arg);
  925. } else {
  926. var oscType = osc.inferTypeForArgument(arg);
  927. msgArg = {
  928. type: oscType,
  929. value: arg
  930. };
  931. }
  932. annotated.push(msgArg);
  933. }
  934. return annotated;
  935. };
  936. if (osc.isCommonJS) {
  937. module.exports = osc;
  938. }
  939. }());
  940. ;
  941. !function(t,i){"object"==typeof exports&&"object"==typeof module?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.Long=i():t.Long=i()}("undefined"!=typeof self?self:this,function(){return function(t){function i(e){if(n[e])return n[e].exports;var r=n[e]={i:e,l:!1,exports:{}};return t[e].call(r.exports,r,r.exports,i),r.l=!0,r.exports}var n={};return i.m=t,i.c=n,i.d=function(t,n,e){i.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:e})},i.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(n,"a",n),n},i.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},i.p="",i(i.s=0)}([function(t,i){function n(t,i,n){this.low=0|t,this.high=0|i,this.unsigned=!!n}function e(t){return!0===(t&&t.__isLong__)}function r(t,i){var n,e,r;return i?(t>>>=0,(r=0<=t&&t<256)&&(e=l[t])?e:(n=h(t,(0|t)<0?-1:0,!0),r&&(l[t]=n),n)):(t|=0,(r=-128<=t&&t<128)&&(e=f[t])?e:(n=h(t,t<0?-1:0,!1),r&&(f[t]=n),n))}function s(t,i){if(isNaN(t))return i?p:m;if(i){if(t<0)return p;if(t>=c)return q}else{if(t<=-v)return _;if(t+1>=v)return E}return t<0?s(-t,i).neg():h(t%d|0,t/d|0,i)}function h(t,i,e){return new n(t,i,e)}function u(t,i,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof i?(n=i,i=!1):i=!!i,(n=n||10)<2||36<n)throw RangeError("radix");var e;if((e=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===e)return u(t.substring(1),i,n).neg();for(var r=s(a(n,8)),h=m,o=0;o<t.length;o+=8){var g=Math.min(8,t.length-o),f=parseInt(t.substring(o,o+g),n);if(g<8){var l=s(a(n,g));h=h.mul(l).add(s(f))}else h=h.mul(r),h=h.add(s(f))}return h.unsigned=i,h}function o(t,i){return"number"==typeof t?s(t,i):"string"==typeof t?u(t,i):h(t.low,t.high,"boolean"==typeof i?i:t.unsigned)}t.exports=n;var g=null;try{g=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=e;var f={},l={};n.fromInt=r,n.fromNumber=s,n.fromBits=h;var a=Math.pow;n.fromString=u,n.fromValue=o;var d=4294967296,c=d*d,v=c/2,w=r(1<<24),m=r(0);n.ZERO=m;var p=r(0,!0);n.UZERO=p;var y=r(1);n.ONE=y;var b=r(1,!0);n.UONE=b;var N=r(-1);n.NEG_ONE=N;var E=h(-1,2147483647,!1);n.MAX_VALUE=E;var q=h(-1,-1,!0);n.MAX_UNSIGNED_VALUE=q;var _=h(0,-2147483648,!1);n.MIN_VALUE=_;var B=n.prototype;B.toInt=function(){return this.unsigned?this.low>>>0:this.low},B.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},B.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){var i=s(t),n=this.div(i),e=n.mul(i).sub(this);return n.toString(t)+e.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var r=s(a(t,6),this.unsigned),h=this,u="";;){var o=h.div(r),g=h.sub(o.mul(r)).toInt()>>>0,f=g.toString(t);if(h=o,h.isZero())return f+u;for(;f.length<6;)f="0"+f;u=""+f+u}},B.getHighBits=function(){return this.high},B.getHighBitsUnsigned=function(){return this.high>>>0},B.getLowBits=function(){return this.low},B.getLowBitsUnsigned=function(){return this.low>>>0},B.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,i=31;i>0&&0==(t&1<<i);i--);return 0!=this.high?i+33:i+1},B.isZero=function(){return 0===this.high&&0===this.low},B.eqz=B.isZero,B.isNegative=function(){return!this.unsigned&&this.high<0},B.isPositive=function(){return this.unsigned||this.high>=0},B.isOdd=function(){return 1==(1&this.low)},B.isEven=function(){return 0==(1&this.low)},B.equals=function(t){return e(t)||(t=o(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},B.eq=B.equals,B.notEquals=function(t){return!this.eq(t)},B.neq=B.notEquals,B.ne=B.notEquals,B.lessThan=function(t){return this.comp(t)<0},B.lt=B.lessThan,B.lessThanOrEqual=function(t){return this.comp(t)<=0},B.lte=B.lessThanOrEqual,B.le=B.lessThanOrEqual,B.greaterThan=function(t){return this.comp(t)>0},B.gt=B.greaterThan,B.greaterThanOrEqual=function(t){return this.comp(t)>=0},B.gte=B.greaterThanOrEqual,B.ge=B.greaterThanOrEqual,B.compare=function(t){if(e(t)||(t=o(t)),this.eq(t))return 0;var i=this.isNegative(),n=t.isNegative();return i&&!n?-1:!i&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},B.comp=B.compare,B.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(y)},B.neg=B.negate,B.add=function(t){e(t)||(t=o(t));var i=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,u=t.high>>>16,g=65535&t.high,f=t.low>>>16,l=65535&t.low,a=0,d=0,c=0,v=0;return v+=s+l,c+=v>>>16,v&=65535,c+=r+f,d+=c>>>16,c&=65535,d+=n+g,a+=d>>>16,d&=65535,a+=i+u,a&=65535,h(c<<16|v,a<<16|d,this.unsigned)},B.subtract=function(t){return e(t)||(t=o(t)),this.add(t.neg())},B.sub=B.subtract,B.multiply=function(t){if(this.isZero())return m;if(e(t)||(t=o(t)),g){return h(g.mul(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(t.isZero())return m;if(this.eq(_))return t.isOdd()?_:m;if(t.eq(_))return this.isOdd()?_:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(w)&&t.lt(w))return s(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,n=65535&this.high,r=this.low>>>16,u=65535&this.low,f=t.high>>>16,l=65535&t.high,a=t.low>>>16,d=65535&t.low,c=0,v=0,p=0,y=0;return y+=u*d,p+=y>>>16,y&=65535,p+=r*d,v+=p>>>16,p&=65535,p+=u*a,v+=p>>>16,p&=65535,v+=n*d,c+=v>>>16,v&=65535,v+=r*a,c+=v>>>16,v&=65535,v+=u*l,c+=v>>>16,v&=65535,c+=i*d+n*a+r*l+u*f,c&=65535,h(p<<16|y,c<<16|v,this.unsigned)},B.mul=B.multiply,B.divide=function(t){if(e(t)||(t=o(t)),t.isZero())throw Error("division by zero");if(g){if(!this.unsigned&&-2147483648===this.high&&-1===t.low&&-1===t.high)return this;return h((this.unsigned?g.div_u:g.div_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p:m;var i,n,r;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return p;if(t.gt(this.shru(1)))return b;r=p}else{if(this.eq(_)){if(t.eq(y)||t.eq(N))return _;if(t.eq(_))return y;return i=this.shr(1).div(t).shl(1),i.eq(m)?t.isNegative()?y:N:(n=this.sub(t.mul(i)),r=i.add(n.div(t)))}if(t.eq(_))return this.unsigned?p:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();r=m}for(n=this;n.gte(t);){i=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(i)/Math.LN2),f=u<=48?1:a(2,u-48),l=s(i),d=l.mul(t);d.isNegative()||d.gt(n);)i-=f,l=s(i,this.unsigned),d=l.mul(t);l.isZero()&&(l=y),r=r.add(l),n=n.sub(d)}return r},B.div=B.divide,B.modulo=function(t){if(e(t)||(t=o(t)),g){return h((this.unsigned?g.rem_u:g.rem_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},B.mod=B.modulo,B.rem=B.modulo,B.not=function(){return h(~this.low,~this.high,this.unsigned)},B.and=function(t){return e(t)||(t=o(t)),h(this.low&t.low,this.high&t.high,this.unsigned)},B.or=function(t){return e(t)||(t=o(t)),h(this.low|t.low,this.high|t.high,this.unsigned)},B.xor=function(t){return e(t)||(t=o(t)),h(this.low^t.low,this.high^t.high,this.unsigned)},B.shiftLeft=function(t){return e(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?h(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):h(0,this.low<<t-32,this.unsigned)},B.shl=B.shiftLeft,B.shiftRight=function(t){return e(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?h(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):h(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},B.shr=B.shiftRight,B.shiftRightUnsigned=function(t){if(e(t)&&(t=t.toInt()),0===(t&=63))return this;var i=this.high;if(t<32){return h(this.low>>>t|i<<32-t,i>>>t,this.unsigned)}return 32===t?h(i,0,this.unsigned):h(i>>>t-32,0,this.unsigned)},B.shru=B.shiftRightUnsigned,B.shr_u=B.shiftRightUnsigned,B.toSigned=function(){return this.unsigned?h(this.low,this.high,!1):this},B.toUnsigned=function(){return this.unsigned?this:h(this.low,this.high,!0)},B.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},B.toBytesLE=function(){var t=this.high,i=this.low;return[255&i,i>>>8&255,i>>>16&255,i>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},B.toBytesBE=function(){var t=this.high,i=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,i>>>24,i>>>16&255,i>>>8&255,255&i]},n.fromBytes=function(t,i,e){return e?n.fromBytesLE(t,i):n.fromBytesBE(t,i)},n.fromBytesLE=function(t,i){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,i)},n.fromBytesBE=function(t,i){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],i)}}])});
  942. //# sourceMappingURL=long.js.map;
  943. /*
  944. * slip.js: A plain JavaScript SLIP implementation that works in both the browser and Node.js
  945. *
  946. * Copyright 2014, Colin Clark
  947. * Licensed under the MIT and GPL 3 licenses.
  948. */
  949. /*global exports, define*/
  950. (function (root, factory) {
  951. "use strict";
  952. if (typeof exports === "object") {
  953. // We're in a CommonJS-style loader.
  954. root.slip = exports;
  955. factory(exports);
  956. } else if (typeof define === "function" && define.amd) {
  957. // We're in an AMD-style loader.
  958. define(["exports"], function (exports) {
  959. root.slip = exports;
  960. return (root.slip, factory(exports));
  961. });
  962. } else {
  963. // Plain old browser.
  964. root.slip = {};
  965. factory(root.slip);
  966. }
  967. }(this, function (exports) {
  968. "use strict";
  969. var slip = exports;
  970. slip.END = 192;
  971. slip.ESC = 219;
  972. slip.ESC_END = 220;
  973. slip.ESC_ESC = 221;
  974. slip.byteArray = function (data, offset, length) {
  975. return data instanceof ArrayBuffer ? new Uint8Array(data, offset, length) : data;
  976. };
  977. slip.expandByteArray = function (arr) {
  978. var expanded = new Uint8Array(arr.length * 2);
  979. expanded.set(arr);
  980. return expanded;
  981. };
  982. slip.sliceByteArray = function (arr, start, end) {
  983. var sliced = arr.buffer.slice ? arr.buffer.slice(start, end) : arr.subarray(start, end);
  984. return new Uint8Array(sliced);
  985. };
  986. /**
  987. * SLIP encodes a byte array.
  988. *
  989. * @param {Array-like} data a Uint8Array, Node.js Buffer, ArrayBuffer, or [] containing raw bytes
  990. * @param {Object} options encoder options
  991. * @return {Uint8Array} the encoded copy of the data
  992. */
  993. slip.encode = function (data, o) {
  994. o = o || {};
  995. o.bufferPadding = o.bufferPadding || 4; // Will be rounded to the nearest 4 bytes.
  996. data = slip.byteArray(data, o.offset, o.byteLength);
  997. var bufLen = (data.length + o.bufferPadding + 3) & ~0x03,
  998. encoded = new Uint8Array(bufLen),
  999. j = 1;
  1000. encoded[0] = slip.END;
  1001. for (var i = 0; i < data.length; i++) {
  1002. // We always need enough space for two value bytes plus a trailing END.
  1003. if (j > encoded.length - 3) {
  1004. encoded = slip.expandByteArray(encoded);
  1005. }
  1006. var val = data[i];
  1007. if (val === slip.END) {
  1008. encoded[j++] = slip.ESC;
  1009. val = slip.ESC_END;
  1010. } else if (val === slip.ESC) {
  1011. encoded[j++] = slip.ESC;
  1012. val = slip.ESC_ESC;
  1013. }
  1014. encoded[j++] = val;
  1015. }
  1016. encoded[j] = slip.END;
  1017. return slip.sliceByteArray(encoded, 0, j + 1);
  1018. };
  1019. /**
  1020. * Creates a new SLIP Decoder.
  1021. * @constructor
  1022. *
  1023. * @param {Function} onMessage a callback function that will be invoked when a message has been fully decoded
  1024. * @param {Number} maxBufferSize the maximum size of a incoming message; larger messages will throw an error
  1025. */
  1026. slip.Decoder = function (o) {
  1027. o = typeof o !== "function" ? o || {} : {
  1028. onMessage: o
  1029. };
  1030. this.maxMessageSize = o.maxMessageSize || 10485760; // Defaults to 10 MB.
  1031. this.bufferSize = o.bufferSize || 1024; // Message buffer defaults to 1 KB.
  1032. this.msgBuffer = new Uint8Array(this.bufferSize);
  1033. this.msgBufferIdx = 0;
  1034. this.onMessage = o.onMessage;
  1035. this.onError = o.onError;
  1036. this.escape = false;
  1037. };
  1038. var p = slip.Decoder.prototype;
  1039. /**
  1040. * Decodes a SLIP data packet.
  1041. * The onMessage callback will be invoked when a complete message has been decoded.
  1042. *
  1043. * @param {Array-like} data an incoming stream of bytes
  1044. */
  1045. p.decode = function (data) {
  1046. data = slip.byteArray(data);
  1047. var msg;
  1048. for (var i = 0; i < data.length; i++) {
  1049. var val = data[i];
  1050. if (this.escape) {
  1051. if (val === slip.ESC_ESC) {
  1052. val = slip.ESC;
  1053. } else if (val === slip.ESC_END) {
  1054. val = slip.END;
  1055. }
  1056. } else {
  1057. if (val === slip.ESC) {
  1058. this.escape = true;
  1059. continue;
  1060. }
  1061. if (val === slip.END) {
  1062. msg = this.handleEnd();
  1063. continue;
  1064. }
  1065. }
  1066. var more = this.addByte(val);
  1067. if (!more) {
  1068. this.handleMessageMaxError();
  1069. }
  1070. }
  1071. return msg;
  1072. };
  1073. p.handleMessageMaxError = function () {
  1074. if (this.onError) {
  1075. this.onError(this.msgBuffer.subarray(0),
  1076. "The message is too large; the maximum message size is " +
  1077. this.maxMessageSize / 1024 + "KB. Use a larger maxMessageSize if necessary.");
  1078. }
  1079. // Reset everything and carry on.
  1080. this.msgBufferIdx = 0;
  1081. this.escape = false;
  1082. };
  1083. // Unsupported, non-API method.
  1084. p.addByte = function (val) {
  1085. if (this.msgBufferIdx > this.msgBuffer.length - 1) {
  1086. this.msgBuffer = slip.expandByteArray(this.msgBuffer);
  1087. }
  1088. this.msgBuffer[this.msgBufferIdx++] = val;
  1089. this.escape = false;
  1090. return this.msgBuffer.length < this.maxMessageSize;
  1091. };
  1092. // Unsupported, non-API method.
  1093. p.handleEnd = function () {
  1094. if (this.msgBufferIdx === 0) {
  1095. return; // Toss opening END byte and carry on.
  1096. }
  1097. var msg = slip.sliceByteArray(this.msgBuffer, 0, this.msgBufferIdx);
  1098. if (this.onMessage) {
  1099. this.onMessage(msg);
  1100. }
  1101. // Clear our pointer into the message buffer.
  1102. this.msgBufferIdx = 0;
  1103. return msg;
  1104. };
  1105. return slip;
  1106. }));
  1107. ;
  1108. /*!
  1109. * EventEmitter v5.2.9 - git.io/ee
  1110. * Unlicense - http://unlicense.org/
  1111. * Oliver Caldwell - https://oli.me.uk/
  1112. * @preserve
  1113. */
  1114. ;(function (exports) {
  1115. 'use strict';
  1116. /**
  1117. * Class for managing events.
  1118. * Can be extended to provide event functionality in other classes.
  1119. *
  1120. * @class EventEmitter Manages event registering and emitting.
  1121. */
  1122. function EventEmitter() {}
  1123. // Shortcuts to improve speed and size
  1124. var proto = EventEmitter.prototype;
  1125. var originalGlobalValue = exports.EventEmitter;
  1126. /**
  1127. * Finds the index of the listener for the event in its storage array.
  1128. *
  1129. * @param {Function[]} listeners Array of listeners to search through.
  1130. * @param {Function} listener Method to look for.
  1131. * @return {Number} Index of the specified listener, -1 if not found
  1132. * @api private
  1133. */
  1134. function indexOfListener(listeners, listener) {
  1135. var i = listeners.length;
  1136. while (i--) {
  1137. if (listeners[i].listener === listener) {
  1138. return i;
  1139. }
  1140. }
  1141. return -1;
  1142. }
  1143. /**
  1144. * Alias a method while keeping the context correct, to allow for overwriting of target method.
  1145. *
  1146. * @param {String} name The name of the target method.
  1147. * @return {Function} The aliased method
  1148. * @api private
  1149. */
  1150. function alias(name) {
  1151. return function aliasClosure() {
  1152. return this[name].apply(this, arguments);
  1153. };
  1154. }
  1155. /**
  1156. * Returns the listener array for the specified event.
  1157. * Will initialise the event object and listener arrays if required.
  1158. * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
  1159. * Each property in the object response is an array of listener functions.
  1160. *
  1161. * @param {String|RegExp} evt Name of the event to return the listeners from.
  1162. * @return {Function[]|Object} All listener functions for the event.
  1163. */
  1164. proto.getListeners = function getListeners(evt) {
  1165. var events = this._getEvents();
  1166. var response;
  1167. var key;
  1168. // Return a concatenated array of all matching events if
  1169. // the selector is a regular expression.
  1170. if (evt instanceof RegExp) {
  1171. response = {};
  1172. for (key in events) {
  1173. if (events.hasOwnProperty(key) && evt.test(key)) {
  1174. response[key] = events[key];
  1175. }
  1176. }
  1177. }
  1178. else {
  1179. response = events[evt] || (events[evt] = []);
  1180. }
  1181. return response;
  1182. };
  1183. /**
  1184. * Takes a list of listener objects and flattens it into a list of listener functions.
  1185. *
  1186. * @param {Object[]} listeners Raw listener objects.
  1187. * @return {Function[]} Just the listener functions.
  1188. */
  1189. proto.flattenListeners = function flattenListeners(listeners) {
  1190. var flatListeners = [];
  1191. var i;
  1192. for (i = 0; i < listeners.length; i += 1) {
  1193. flatListeners.push(listeners[i].listener);
  1194. }
  1195. return flatListeners;
  1196. };
  1197. /**
  1198. * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
  1199. *
  1200. * @param {String|RegExp} evt Name of the event to return the listeners from.
  1201. * @return {Object} All listener functions for an event in an object.
  1202. */
  1203. proto.getListenersAsObject = function getListenersAsObject(evt) {
  1204. var listeners = this.getListeners(evt);
  1205. var response;
  1206. if (listeners instanceof Array) {
  1207. response = {};
  1208. response[evt] = listeners;
  1209. }
  1210. return response || listeners;
  1211. };
  1212. function isValidListener (listener) {
  1213. if (typeof listener === 'function' || listener instanceof RegExp) {
  1214. return true
  1215. } else if (listener && typeof listener === 'object') {
  1216. return isValidListener(listener.listener)
  1217. } else {
  1218. return false
  1219. }
  1220. }
  1221. /**
  1222. * Adds a listener function to the specified event.
  1223. * The listener will not be added if it is a duplicate.
  1224. * If the listener returns true then it will be removed after it is called.
  1225. * If you pass a regular expression as the event name then the listener will be added to all events that match it.
  1226. *
  1227. * @param {String|RegExp} evt Name of the event to attach the listener to.
  1228. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
  1229. * @return {Object} Current instance of EventEmitter for chaining.
  1230. */
  1231. proto.addListener = function addListener(evt, listener) {
  1232. if (!isValidListener(listener)) {
  1233. throw new TypeError('listener must be a function');
  1234. }
  1235. var listeners = this.getListenersAsObject(evt);
  1236. var listenerIsWrapped = typeof listener === 'object';
  1237. var key;
  1238. for (key in listeners) {
  1239. if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
  1240. listeners[key].push(listenerIsWrapped ? listener : {
  1241. listener: listener,
  1242. once: false
  1243. });
  1244. }
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Alias of addListener
  1250. */
  1251. proto.on = alias('addListener');
  1252. /**
  1253. * Semi-alias of addListener. It will add a listener that will be
  1254. * automatically removed after its first execution.
  1255. *
  1256. * @param {String|RegExp} evt Name of the event to attach the listener to.
  1257. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
  1258. * @return {Object} Current instance of EventEmitter for chaining.
  1259. */
  1260. proto.addOnceListener = function addOnceListener(evt, listener) {
  1261. return this.addListener(evt, {
  1262. listener: listener,
  1263. once: true
  1264. });
  1265. };
  1266. /**
  1267. * Alias of addOnceListener.
  1268. */
  1269. proto.once = alias('addOnceListener');
  1270. /**
  1271. * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
  1272. * You need to tell it what event names should be matched by a regex.
  1273. *
  1274. * @param {String} evt Name of the event to create.
  1275. * @return {Object} Current instance of EventEmitter for chaining.
  1276. */
  1277. proto.defineEvent = function defineEvent(evt) {
  1278. this.getListeners(evt);
  1279. return this;
  1280. };
  1281. /**
  1282. * Uses defineEvent to define multiple events.
  1283. *
  1284. * @param {String[]} evts An array of event names to define.
  1285. * @return {Object} Current instance of EventEmitter for chaining.
  1286. */
  1287. proto.defineEvents = function defineEvents(evts) {
  1288. for (var i = 0; i < evts.length; i += 1) {
  1289. this.defineEvent(evts[i]);
  1290. }
  1291. return this;
  1292. };
  1293. /**
  1294. * Removes a listener function from the specified event.
  1295. * When passed a regular expression as the event name, it will remove the listener from all events that match it.
  1296. *
  1297. * @param {String|RegExp} evt Name of the event to remove the listener from.
  1298. * @param {Function} listener Method to remove from the event.
  1299. * @return {Object} Current instance of EventEmitter for chaining.
  1300. */
  1301. proto.removeListener = function removeListener(evt, listener) {
  1302. var listeners = this.getListenersAsObject(evt);
  1303. var index;
  1304. var key;
  1305. for (key in listeners) {
  1306. if (listeners.hasOwnProperty(key)) {
  1307. index = indexOfListener(listeners[key], listener);
  1308. if (index !== -1) {
  1309. listeners[key].splice(index, 1);
  1310. }
  1311. }
  1312. }
  1313. return this;
  1314. };
  1315. /**
  1316. * Alias of removeListener
  1317. */
  1318. proto.off = alias('removeListener');
  1319. /**
  1320. * Adds listeners in bulk using the manipulateListeners method.
  1321. * If you pass an object as the first argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
  1322. * You can also pass it a regular expression to add the array of listeners to all events that match it.
  1323. * Yeah, this function does quite a bit. That's probably a bad thing.
  1324. *
  1325. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
  1326. * @param {Function[]} [listeners] An optional array of listener functions to add.
  1327. * @return {Object} Current instance of EventEmitter for chaining.
  1328. */
  1329. proto.addListeners = function addListeners(evt, listeners) {
  1330. // Pass through to manipulateListeners
  1331. return this.manipulateListeners(false, evt, listeners);
  1332. };
  1333. /**
  1334. * Removes listeners in bulk using the manipulateListeners method.
  1335. * If you pass an object as the first argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
  1336. * You can also pass it an event name and an array of listeners to be removed.
  1337. * You can also pass it a regular expression to remove the listeners from all events that match it.
  1338. *
  1339. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
  1340. * @param {Function[]} [listeners] An optional array of listener functions to remove.
  1341. * @return {Object} Current instance of EventEmitter for chaining.
  1342. */
  1343. proto.removeListeners = function removeListeners(evt, listeners) {
  1344. // Pass through to manipulateListeners
  1345. return this.manipulateListeners(true, evt, listeners);
  1346. };
  1347. /**
  1348. * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
  1349. * The first argument will determine if the listeners are removed (true) or added (false).
  1350. * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
  1351. * You can also pass it an event name and an array of listeners to be added/removed.
  1352. * You can also pass it a regular expression to manipulate the listeners of all events that match it.
  1353. *
  1354. * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
  1355. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
  1356. * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
  1357. * @return {Object} Current instance of EventEmitter for chaining.
  1358. */
  1359. proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
  1360. var i;
  1361. var value;
  1362. var single = remove ? this.removeListener : this.addListener;
  1363. var multiple = remove ? this.removeListeners : this.addListeners;
  1364. // If evt is an object then pass each of its properties to this method
  1365. if (typeof evt === 'object' && !(evt instanceof RegExp)) {
  1366. for (i in evt) {
  1367. if (evt.hasOwnProperty(i) && (value = evt[i])) {
  1368. // Pass the single listener straight through to the singular method
  1369. if (typeof value === 'function') {
  1370. single.call(this, i, value);
  1371. }
  1372. else {
  1373. // Otherwise pass back to the multiple function
  1374. multiple.call(this, i, value);
  1375. }
  1376. }
  1377. }
  1378. }
  1379. else {
  1380. // So evt must be a string
  1381. // And listeners must be an array of listeners
  1382. // Loop over it and pass each one to the multiple method
  1383. i = listeners.length;
  1384. while (i--) {
  1385. single.call(this, evt, listeners[i]);
  1386. }
  1387. }
  1388. return this;
  1389. };
  1390. /**
  1391. * Removes all listeners from a specified event.
  1392. * If you do not specify an event then all listeners will be removed.
  1393. * That means every event will be emptied.
  1394. * You can also pass a regex to remove all events that match it.
  1395. *
  1396. * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
  1397. * @return {Object} Current instance of EventEmitter for chaining.
  1398. */
  1399. proto.removeEvent = function removeEvent(evt) {
  1400. var type = typeof evt;
  1401. var events = this._getEvents();
  1402. var key;
  1403. // Remove different things depending on the state of evt
  1404. if (type === 'string') {
  1405. // Remove all listeners for the specified event
  1406. delete events[evt];
  1407. }
  1408. else if (evt instanceof RegExp) {
  1409. // Remove all events matching the regex.
  1410. for (key in events) {
  1411. if (events.hasOwnProperty(key) && evt.test(key)) {
  1412. delete events[key];
  1413. }
  1414. }
  1415. }
  1416. else {
  1417. // Remove all listeners in all events
  1418. delete this._events;
  1419. }
  1420. return this;
  1421. };
  1422. /**
  1423. * Alias of removeEvent.
  1424. *
  1425. * Added to mirror the node API.
  1426. */
  1427. proto.removeAllListeners = alias('removeEvent');
  1428. /**
  1429. * Emits an event of your choice.
  1430. * When emitted, every listener attached to that event will be executed.
  1431. * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
  1432. * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
  1433. * So they will not arrive within the array on the other side, they will be separate.
  1434. * You can also pass a regular expression to emit to all events that match it.
  1435. *
  1436. * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
  1437. * @param {Array} [args] Optional array of arguments to be passed to each listener.
  1438. * @return {Object} Current instance of EventEmitter for chaining.
  1439. */
  1440. proto.emitEvent = function emitEvent(evt, args) {
  1441. var listenersMap = this.getListenersAsObject(evt);
  1442. var listeners;
  1443. var listener;
  1444. var i;
  1445. var key;
  1446. var response;
  1447. for (key in listenersMap) {
  1448. if (listenersMap.hasOwnProperty(key)) {
  1449. listeners = listenersMap[key].slice(0);
  1450. for (i = 0; i < listeners.length; i++) {
  1451. // If the listener returns true then it shall be removed from the event
  1452. // The function is executed either with a basic call or an apply if there is an args array
  1453. listener = listeners[i];
  1454. if (listener.once === true) {
  1455. this.removeListener(evt, listener.listener);
  1456. }
  1457. response = listener.listener.apply(this, args || []);
  1458. if (response === this._getOnceReturnValue()) {
  1459. this.removeListener(evt, listener.listener);
  1460. }
  1461. }
  1462. }
  1463. }
  1464. return this;
  1465. };
  1466. /**
  1467. * Alias of emitEvent
  1468. */
  1469. proto.trigger = alias('emitEvent');
  1470. /**
  1471. * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
  1472. * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
  1473. *
  1474. * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
  1475. * @param {...*} Optional additional arguments to be passed to each listener.
  1476. * @return {Object} Current instance of EventEmitter for chaining.
  1477. */
  1478. proto.emit = function emit(evt) {
  1479. var args = Array.prototype.slice.call(arguments, 1);
  1480. return this.emitEvent(evt, args);
  1481. };
  1482. /**
  1483. * Sets the current value to check against when executing listeners. If a
  1484. * listeners return value matches the one set here then it will be removed
  1485. * after execution. This value defaults to true.
  1486. *
  1487. * @param {*} value The new value to check for when executing listeners.
  1488. * @return {Object} Current instance of EventEmitter for chaining.
  1489. */
  1490. proto.setOnceReturnValue = function setOnceReturnValue(value) {
  1491. this._onceReturnValue = value;
  1492. return this;
  1493. };
  1494. /**
  1495. * Fetches the current value to check against when executing listeners. If
  1496. * the listeners return value matches this one then it should be removed
  1497. * automatically. It will return true by default.
  1498. *
  1499. * @return {*|Boolean} The current value to check for or the default, true.
  1500. * @api private
  1501. */
  1502. proto._getOnceReturnValue = function _getOnceReturnValue() {
  1503. if (this.hasOwnProperty('_onceReturnValue')) {
  1504. return this._onceReturnValue;
  1505. }
  1506. else {
  1507. return true;
  1508. }
  1509. };
  1510. /**
  1511. * Fetches the events object and creates one if required.
  1512. *
  1513. * @return {Object} The events storage object.
  1514. * @api private
  1515. */
  1516. proto._getEvents = function _getEvents() {
  1517. return this._events || (this._events = {});
  1518. };
  1519. /**
  1520. * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
  1521. *
  1522. * @return {Function} Non conflicting EventEmitter class.
  1523. */
  1524. EventEmitter.noConflict = function noConflict() {
  1525. exports.EventEmitter = originalGlobalValue;
  1526. return EventEmitter;
  1527. };
  1528. // Expose the class either via AMD, CommonJS or the global object
  1529. if (typeof define === 'function' && define.amd) {
  1530. define(function () {
  1531. return EventEmitter;
  1532. });
  1533. }
  1534. else if (typeof module === 'object' && module.exports){
  1535. module.exports = EventEmitter;
  1536. }
  1537. else {
  1538. exports.EventEmitter = EventEmitter;
  1539. }
  1540. }(typeof window !== 'undefined' ? window : this || {}));
  1541. ;
  1542. /*
  1543. * osc.js: An Open Sound Control library for JavaScript that works in both the browser and Node.js
  1544. *
  1545. * Cross-platform base transport library for osc.js.
  1546. *
  1547. * Copyright 2014-2016, Colin Clark
  1548. * Licensed under the MIT and GPL 3 licenses.
  1549. */
  1550. /* global require, module */
  1551. var osc = osc || require("./osc.js"),
  1552. slip = slip || require("slip"),
  1553. EventEmitter = EventEmitter || require("events").EventEmitter;
  1554. (function () {
  1555. "use strict";
  1556. osc.supportsSerial = false;
  1557. // Unsupported, non-API function.
  1558. osc.firePacketEvents = function (port, packet, timeTag, packetInfo) {
  1559. if (packet.address) {
  1560. port.emit("message", packet, timeTag, packetInfo);
  1561. } else {
  1562. osc.fireBundleEvents(port, packet, timeTag, packetInfo);
  1563. }
  1564. };
  1565. // Unsupported, non-API function.
  1566. osc.fireBundleEvents = function (port, bundle, timeTag, packetInfo) {
  1567. port.emit("bundle", bundle, timeTag, packetInfo);
  1568. for (var i = 0; i < bundle.packets.length; i++) {
  1569. var packet = bundle.packets[i];
  1570. osc.firePacketEvents(port, packet, bundle.timeTag, packetInfo);
  1571. }
  1572. };
  1573. osc.fireClosedPortSendError = function (port, msg) {
  1574. msg = msg || "Can't send packets on a closed osc.Port object. Please open (or reopen) this Port by calling open().";
  1575. port.emit("error", msg);
  1576. };
  1577. osc.Port = function (options) {
  1578. this.options = options || {};
  1579. this.on("data", this.decodeOSC.bind(this));
  1580. };
  1581. var p = osc.Port.prototype = Object.create(EventEmitter.prototype);
  1582. p.constructor = osc.Port;
  1583. p.send = function (oscPacket) {
  1584. var args = Array.prototype.slice.call(arguments),
  1585. encoded = this.encodeOSC(oscPacket),
  1586. buf = osc.nativeBuffer(encoded);
  1587. args[0] = buf;
  1588. this.sendRaw.apply(this, args);
  1589. };
  1590. p.encodeOSC = function (packet) {
  1591. // TODO gh-39: This is unsafe; we should only access the underlying
  1592. // buffer within the range of its view.
  1593. packet = packet.buffer ? packet.buffer : packet;
  1594. var encoded;
  1595. try {
  1596. encoded = osc.writePacket(packet, this.options);
  1597. } catch (err) {
  1598. this.emit("error", err);
  1599. }
  1600. return encoded;
  1601. };
  1602. p.decodeOSC = function (data, packetInfo) {
  1603. data = osc.byteArray(data);
  1604. this.emit("raw", data, packetInfo);
  1605. try {
  1606. var packet = osc.readPacket(data, this.options);
  1607. this.emit("osc", packet, packetInfo);
  1608. osc.firePacketEvents(this, packet, undefined, packetInfo);
  1609. } catch (err) {
  1610. this.emit("error", err);
  1611. }
  1612. };
  1613. osc.SLIPPort = function (options) {
  1614. var that = this;
  1615. var o = this.options = options || {};
  1616. o.useSLIP = o.useSLIP === undefined ? true : o.useSLIP;
  1617. this.decoder = new slip.Decoder({
  1618. onMessage: this.decodeOSC.bind(this),
  1619. onError: function (err) {
  1620. that.emit("error", err);
  1621. }
  1622. });
  1623. var decodeHandler = o.useSLIP ? this.decodeSLIPData : this.decodeOSC;
  1624. this.on("data", decodeHandler.bind(this));
  1625. };
  1626. p = osc.SLIPPort.prototype = Object.create(osc.Port.prototype);
  1627. p.constructor = osc.SLIPPort;
  1628. p.encodeOSC = function (packet) {
  1629. // TODO gh-39: This is unsafe; we should only access the underlying
  1630. // buffer within the range of its view.
  1631. packet = packet.buffer ? packet.buffer : packet;
  1632. var framed;
  1633. try {
  1634. var encoded = osc.writePacket(packet, this.options);
  1635. framed = slip.encode(encoded);
  1636. } catch (err) {
  1637. this.emit("error", err);
  1638. }
  1639. return framed;
  1640. };
  1641. p.decodeSLIPData = function (data, packetInfo) {
  1642. // TODO: Get packetInfo through SLIP decoder.
  1643. this.decoder.decode(data, packetInfo);
  1644. };
  1645. // Unsupported, non-API function.
  1646. osc.relay = function (from, to, eventName, sendFnName, transformFn, sendArgs) {
  1647. eventName = eventName || "message";
  1648. sendFnName = sendFnName || "send";
  1649. transformFn = transformFn || function () {};
  1650. sendArgs = sendArgs ? [null].concat(sendArgs) : [];
  1651. var listener = function (data) {
  1652. sendArgs[0] = data;
  1653. data = transformFn(data);
  1654. to[sendFnName].apply(to, sendArgs);
  1655. };
  1656. from.on(eventName, listener);
  1657. return {
  1658. eventName: eventName,
  1659. listener: listener
  1660. };
  1661. };
  1662. // Unsupported, non-API function.
  1663. osc.relayPorts = function (from, to, o) {
  1664. var eventName = o.raw ? "raw" : "osc",
  1665. sendFnName = o.raw ? "sendRaw" : "send";
  1666. return osc.relay(from, to, eventName, sendFnName, o.transform);
  1667. };
  1668. // Unsupported, non-API function.
  1669. osc.stopRelaying = function (from, relaySpec) {
  1670. from.removeListener(relaySpec.eventName, relaySpec.listener);
  1671. };
  1672. /**
  1673. * A Relay connects two sources of OSC data together,
  1674. * relaying all OSC messages received by each port to the other.
  1675. * @constructor
  1676. *
  1677. * @param {osc.Port} port1 the first port to relay
  1678. * @param {osc.Port} port2 the second port to relay
  1679. * @param {Object} options the configuration options for this relay
  1680. */
  1681. osc.Relay = function (port1, port2, options) {
  1682. var o = this.options = options || {};
  1683. o.raw = false;
  1684. this.port1 = port1;
  1685. this.port2 = port2;
  1686. this.listen();
  1687. };
  1688. p = osc.Relay.prototype = Object.create(EventEmitter.prototype);
  1689. p.constructor = osc.Relay;
  1690. p.open = function () {
  1691. this.port1.open();
  1692. this.port2.open();
  1693. };
  1694. p.listen = function () {
  1695. if (this.port1Spec && this.port2Spec) {
  1696. this.close();
  1697. }
  1698. this.port1Spec = osc.relayPorts(this.port1, this.port2, this.options);
  1699. this.port2Spec = osc.relayPorts(this.port2, this.port1, this.options);
  1700. // Bind port close listeners to ensure that the relay
  1701. // will stop forwarding messages if one of its ports close.
  1702. // Users are still responsible for closing the underlying ports
  1703. // if necessary.
  1704. var closeListener = this.close.bind(this);
  1705. this.port1.on("close", closeListener);
  1706. this.port2.on("close", closeListener);
  1707. };
  1708. p.close = function () {
  1709. osc.stopRelaying(this.port1, this.port1Spec);
  1710. osc.stopRelaying(this.port2, this.port2Spec);
  1711. this.emit("close", this.port1, this.port2);
  1712. };
  1713. // If we're in a require-compatible environment, export ourselves.
  1714. if (typeof module !== "undefined" && module.exports) {
  1715. module.exports = osc;
  1716. }
  1717. }());
  1718. ;
  1719. /*
  1720. * osc.js: An Open Sound Control library for JavaScript that works in both the browser and Node.js
  1721. *
  1722. * Cross-Platform Web Socket client transport for osc.js.
  1723. *
  1724. * Copyright 2014-2016, Colin Clark
  1725. * Licensed under the MIT and GPL 3 licenses.
  1726. */
  1727. /*global WebSocket, require*/
  1728. var osc = osc || require("./osc.js");
  1729. (function () {
  1730. "use strict";
  1731. osc.WebSocket = typeof WebSocket !== "undefined" ? WebSocket : require ("ws");
  1732. osc.WebSocketPort = function (options) {
  1733. osc.Port.call(this, options);
  1734. this.on("open", this.listen.bind(this));
  1735. this.socket = options.socket;
  1736. if (this.socket) {
  1737. if (this.socket.readyState === 1) {
  1738. osc.WebSocketPort.setupSocketForBinary(this.socket);
  1739. this.emit("open", this.socket);
  1740. } else {
  1741. this.open();
  1742. }
  1743. }
  1744. };
  1745. var p = osc.WebSocketPort.prototype = Object.create(osc.Port.prototype);
  1746. p.constructor = osc.WebSocketPort;
  1747. p.open = function () {
  1748. if (!this.socket || this.socket.readyState > 1) {
  1749. this.socket = new osc.WebSocket(this.options.url);
  1750. }
  1751. osc.WebSocketPort.setupSocketForBinary(this.socket);
  1752. var that = this;
  1753. this.socket.onopen = function () {
  1754. that.emit("open", that.socket);
  1755. };
  1756. this.socket.onerror = function (err) {
  1757. that.emit("error", err);
  1758. };
  1759. };
  1760. p.listen = function () {
  1761. var that = this;
  1762. this.socket.onmessage = function (e) {
  1763. that.emit("data", e.data, e);
  1764. };
  1765. this.socket.onclose = function (e) {
  1766. that.emit("close", e);
  1767. };
  1768. that.emit("ready");
  1769. };
  1770. p.sendRaw = function (encoded) {
  1771. if (!this.socket || this.socket.readyState !== 1) {
  1772. osc.fireClosedPortSendError(this);
  1773. return;
  1774. }
  1775. this.socket.send(encoded);
  1776. };
  1777. p.close = function (code, reason) {
  1778. this.socket.close(code, reason);
  1779. };
  1780. osc.WebSocketPort.setupSocketForBinary = function (socket) {
  1781. socket.binaryType = osc.isNode ? "nodebuffer" : "arraybuffer";
  1782. };
  1783. }());