osc-chromeapp.js 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462
  1. /*! osc.js 2.0.3, Copyright 2016 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-2015, Colin Clark
  6. * Licensed under the MIT and GPL 3 licenses.
  7. */
  8. /* global require, module, Buffer, dcodeIO */
  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. // A flag to tell us if we're in a Node.js-compatible environment with Buffers,
  19. // which we will assume are faster.
  20. // Unsupported, non-API property.
  21. osc.isBufferEnv = typeof Buffer !== "undefined";
  22. // Unsupported, non-API property.
  23. osc.isCommonJS = typeof module !== "undefined" && module.exports;
  24. // Unsupported, non-API property.
  25. osc.isNode = osc.isCommonJS && typeof window === "undefined";
  26. // Unsupported, non-API function.
  27. osc.isArray = function (obj) {
  28. return obj && Object.prototype.toString.call(obj) === "[object Array]";
  29. };
  30. // Unsupported, non-API function
  31. osc.isTypedArrayView = function (obj) {
  32. return obj.buffer && obj.buffer instanceof ArrayBuffer;
  33. };
  34. // Unsupported, non-API function
  35. osc.isBuffer = function (obj) {
  36. return osc.isBufferEnv && obj instanceof Buffer;
  37. };
  38. // Private instance of the optional Long dependency.
  39. var Long = typeof dcodeIO !== "undefined" ? dcodeIO.Long :
  40. typeof Long !== "undefined" ? Long :
  41. osc.isNode ? require("long") : undefined;
  42. /**
  43. * Wraps the specified object in a DataView.
  44. *
  45. * @param {Array-like} obj the object to wrap in a DataView instance
  46. * @return {DataView} the DataView object
  47. */
  48. // Unsupported, non-API function.
  49. osc.dataView = function (obj, offset, length) {
  50. if (obj.buffer) {
  51. return new DataView(obj.buffer, offset, length);
  52. }
  53. if (obj instanceof ArrayBuffer) {
  54. return new DataView(obj, offset, length);
  55. }
  56. return new DataView(new Uint8Array(obj), offset, length);
  57. };
  58. /**
  59. * Takes an ArrayBuffer, TypedArray, DataView, Buffer, or array-like object
  60. * and returns a Uint8Array view of it.
  61. *
  62. * Throws an error if the object isn't suitably array-like.
  63. *
  64. * @param {Array-like or Array-wrapping} obj an array-like or array-wrapping object
  65. * @returns {Uint8Array} a typed array of octets
  66. */
  67. // Unsupported, non-API function.
  68. osc.byteArray = function (obj) {
  69. if (obj instanceof Uint8Array) {
  70. return obj;
  71. }
  72. var buf = obj.buffer ? obj.buffer : obj;
  73. if (!(buf instanceof ArrayBuffer) && (typeof buf.length === "undefined" || typeof buf === "string")) {
  74. throw new Error("Can't wrap a non-array-like object as Uint8Array. Object was: " +
  75. JSON.stringify(obj, null, 2));
  76. }
  77. // TODO gh-39: This is a potentially unsafe algorithm;
  78. // if we're getting anything other than a TypedArrayView (such as a DataView),
  79. // we really need to determine the range of the view it is viewing.
  80. return new Uint8Array(buf);
  81. };
  82. /**
  83. * Takes an ArrayBuffer, TypedArray, DataView, or array-like object
  84. * and returns a native buffer object
  85. * (i.e. in Node.js, a Buffer object and in the browser, a Uint8Array).
  86. *
  87. * Throws an error if the object isn't suitably array-like.
  88. *
  89. * @param {Array-like or Array-wrapping} obj an array-like or array-wrapping object
  90. * @returns {Buffer|Uint8Array} a buffer object
  91. */
  92. // Unsupported, non-API function.
  93. osc.nativeBuffer = function (obj) {
  94. if (osc.isBufferEnv && osc.isNode) {
  95. return osc.isBuffer(obj) ? obj : new Buffer(obj.buffer ? obj : new Uint8Array(obj));
  96. }
  97. return osc.isTypedArrayView(obj) ? obj : new Uint8Array(obj);
  98. };
  99. // Unsupported, non-API function
  100. osc.copyByteArray = function (source, target, offset) {
  101. if (osc.isTypedArrayView(source) && osc.isTypedArrayView(target)) {
  102. target.set(source, offset);
  103. } else {
  104. var start = offset === undefined ? 0 : offset,
  105. len = Math.min(target.length - offset, source.length);
  106. for (var i = 0, j = start; i < len; i++, j++) {
  107. target[j] = source[i];
  108. }
  109. }
  110. return target;
  111. };
  112. /**
  113. * Reads an OSC-formatted string.
  114. *
  115. * @param {DataView} dv a DataView containing the raw bytes of the OSC string
  116. * @param {Object} offsetState an offsetState object used to store the current offset index
  117. * @return {String} the JavaScript String that was read
  118. */
  119. osc.readString = function (dv, offsetState) {
  120. var charCodes = [],
  121. idx = offsetState.idx;
  122. for (; idx < dv.byteLength; idx++) {
  123. var charCode = dv.getUint8(idx);
  124. if (charCode !== 0) {
  125. charCodes.push(charCode);
  126. } else {
  127. idx++;
  128. break;
  129. }
  130. }
  131. // Round to the nearest 4-byte block.
  132. idx = (idx + 3) & ~0x03;
  133. offsetState.idx = idx;
  134. return String.fromCharCode.apply(null, charCodes);
  135. };
  136. /**
  137. * Writes a JavaScript string as an OSC-formatted string.
  138. *
  139. * @param {String} str the string to write
  140. * @return {Uint8Array} a buffer containing the OSC-formatted string
  141. */
  142. osc.writeString = function (str) {
  143. var terminated = str + "\u0000",
  144. len = terminated.length,
  145. paddedLen = (len + 3) & ~0x03,
  146. arr = new Uint8Array(paddedLen);
  147. for (var i = 0; i < terminated.length; i++) {
  148. var charCode = terminated.charCodeAt(i);
  149. arr[i] = charCode;
  150. }
  151. return arr;
  152. };
  153. // Unsupported, non-API function.
  154. osc.readPrimitive = function (dv, readerName, numBytes, offsetState) {
  155. var val = dv[readerName](offsetState.idx, false);
  156. offsetState.idx += numBytes;
  157. return val;
  158. };
  159. // Unsupported, non-API function.
  160. osc.writePrimitive = function (val, dv, writerName, numBytes, offset) {
  161. offset = offset === undefined ? 0 : offset;
  162. var arr;
  163. if (!dv) {
  164. arr = new Uint8Array(numBytes);
  165. dv = new DataView(arr.buffer);
  166. } else {
  167. arr = new Uint8Array(dv.buffer);
  168. }
  169. dv[writerName](offset, val, false);
  170. return arr;
  171. };
  172. /**
  173. * Reads an OSC int32 ("i") value.
  174. *
  175. * @param {DataView} dv a DataView containing the raw bytes
  176. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  177. * @return {Number} the number that was read
  178. */
  179. osc.readInt32 = function (dv, offsetState) {
  180. return osc.readPrimitive(dv, "getInt32", 4, offsetState);
  181. };
  182. /**
  183. * Writes an OSC int32 ("i") value.
  184. *
  185. * @param {Number} val the number to write
  186. * @param {DataView} [dv] a DataView instance to write the number into
  187. * @param {Number} [offset] an offset into dv
  188. */
  189. osc.writeInt32 = function (val, dv, offset) {
  190. return osc.writePrimitive(val, dv, "setInt32", 4, offset);
  191. };
  192. /**
  193. * Reads an OSC int64 ("h") value.
  194. *
  195. * @param {DataView} dv a DataView containing the raw bytes
  196. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  197. * @return {Number} the number that was read
  198. */
  199. osc.readInt64 = function (dv, offsetState) {
  200. var high = osc.readPrimitive(dv, "getInt32", 4, offsetState),
  201. low = osc.readPrimitive(dv, "getInt32", 4, offsetState);
  202. if (Long) {
  203. return new Long(low, high);
  204. } else {
  205. return {
  206. high: high,
  207. low: low,
  208. unsigned: false
  209. };
  210. }
  211. };
  212. /**
  213. * Writes an OSC int64 ("h") value.
  214. *
  215. * @param {Number} val the number to write
  216. * @param {DataView} [dv] a DataView instance to write the number into
  217. * @param {Number} [offset] an offset into dv
  218. */
  219. osc.writeInt64 = function (val, dv, offset) {
  220. var arr = new Uint8Array(8);
  221. arr.set(osc.writePrimitive(val.high, dv, "setInt32", 4, offset), 0);
  222. arr.set(osc.writePrimitive(val.low, dv, "setInt32", 4, offset + 4), 4);
  223. return arr;
  224. };
  225. /**
  226. * Reads an OSC float32 ("f") value.
  227. *
  228. * @param {DataView} dv a DataView containing the raw bytes
  229. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  230. * @return {Number} the number that was read
  231. */
  232. osc.readFloat32 = function (dv, offsetState) {
  233. return osc.readPrimitive(dv, "getFloat32", 4, offsetState);
  234. };
  235. /**
  236. * Writes an OSC float32 ("f") value.
  237. *
  238. * @param {Number} val the number to write
  239. * @param {DataView} [dv] a DataView instance to write the number into
  240. * @param {Number} [offset] an offset into dv
  241. */
  242. osc.writeFloat32 = function (val, dv, offset) {
  243. return osc.writePrimitive(val, dv, "setFloat32", 4, offset);
  244. };
  245. /**
  246. * Reads an OSC float64 ("d") value.
  247. *
  248. * @param {DataView} dv a DataView containing the raw bytes
  249. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  250. * @return {Number} the number that was read
  251. */
  252. osc.readFloat64 = function (dv, offsetState) {
  253. return osc.readPrimitive(dv, "getFloat64", 8, offsetState);
  254. };
  255. /**
  256. * Writes an OSC float64 ("d") value.
  257. *
  258. * @param {Number} val the number to write
  259. * @param {DataView} [dv] a DataView instance to write the number into
  260. * @param {Number} [offset] an offset into dv
  261. */
  262. osc.writeFloat64 = function (val, dv, offset) {
  263. return osc.writePrimitive(val, dv, "setFloat64", 8, offset);
  264. };
  265. /**
  266. * Reads an OSC 32-bit ASCII character ("c") 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 {String} a string containing the read character
  271. */
  272. osc.readChar32 = function (dv, offsetState) {
  273. var charCode = osc.readPrimitive(dv, "getUint32", 4, offsetState);
  274. return String.fromCharCode(charCode);
  275. };
  276. /**
  277. * Writes an OSC 32-bit ASCII character ("c") value.
  278. *
  279. * @param {String} str the string from which the first character will be written
  280. * @param {DataView} [dv] a DataView instance to write the character into
  281. * @param {Number} [offset] an offset into dv
  282. * @return {String} a string containing the read character
  283. */
  284. osc.writeChar32 = function (str, dv, offset) {
  285. var charCode = str.charCodeAt(0);
  286. if (charCode === undefined || charCode < -1) {
  287. return undefined;
  288. }
  289. return osc.writePrimitive(charCode, dv, "setUint32", 4, offset);
  290. };
  291. /**
  292. * Reads an OSC blob ("b") (i.e. a Uint8Array).
  293. *
  294. * @param {DataView} dv a DataView instance to read from
  295. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  296. * @return {Uint8Array} the data that was read
  297. */
  298. osc.readBlob = function (dv, offsetState) {
  299. var len = osc.readInt32(dv, offsetState),
  300. paddedLen = (len + 3) & ~0x03,
  301. blob = new Uint8Array(dv.buffer, offsetState.idx, len);
  302. offsetState.idx += paddedLen;
  303. return blob;
  304. };
  305. /**
  306. * Writes a raw collection of bytes to a new ArrayBuffer.
  307. *
  308. * @param {Array-like} data a collection of octets
  309. * @return {ArrayBuffer} a buffer containing the OSC-formatted blob
  310. */
  311. osc.writeBlob = function (data) {
  312. data = osc.byteArray(data);
  313. var len = data.byteLength,
  314. paddedLen = (len + 3) & ~0x03,
  315. offset = 4, // Extra 4 bytes is for the size.
  316. blobLen = paddedLen + offset,
  317. arr = new Uint8Array(blobLen),
  318. dv = new DataView(arr.buffer);
  319. // Write the size.
  320. osc.writeInt32(len, dv);
  321. // Since we're writing to a real ArrayBuffer,
  322. // we don't need to pad the remaining bytes.
  323. arr.set(data, offset);
  324. return arr;
  325. };
  326. /**
  327. * Reads an OSC 4-byte MIDI message.
  328. *
  329. * @param {DataView} dv the DataView instance to read from
  330. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  331. * @return {Uint8Array} an array containing (in order) the port ID, status, data1 and data1 bytes
  332. */
  333. osc.readMIDIBytes = function (dv, offsetState) {
  334. var midi = new Uint8Array(dv.buffer, offsetState.idx, 4);
  335. offsetState.idx += 4;
  336. return midi;
  337. };
  338. /**
  339. * Writes an OSC 4-byte MIDI message.
  340. *
  341. * @param {Array-like} bytes a 4-element array consisting of the port ID, status, data1 and data1 bytes
  342. * @return {Uint8Array} the written message
  343. */
  344. osc.writeMIDIBytes = function (bytes) {
  345. bytes = osc.byteArray(bytes);
  346. var arr = new Uint8Array(4);
  347. arr.set(bytes);
  348. return arr;
  349. };
  350. /**
  351. * Reads an OSC RGBA colour value.
  352. *
  353. * @param {DataView} dv the DataView instance to read from
  354. * @param {Object} offsetState an offsetState object used to store the current offset index into dv
  355. * @return {Object} a colour object containing r, g, b, and a properties
  356. */
  357. osc.readColor = function (dv, offsetState) {
  358. var bytes = new Uint8Array(dv.buffer, offsetState.idx, 4),
  359. alpha = bytes[3] / 255;
  360. offsetState.idx += 4;
  361. return {
  362. r: bytes[0],
  363. g: bytes[1],
  364. b: bytes[2],
  365. a: alpha
  366. };
  367. };
  368. /**
  369. * Writes an OSC RGBA colour value.
  370. *
  371. * @param {Object} color a colour object containing r, g, b, and a properties
  372. * @return {Uint8Array} a byte array containing the written color
  373. */
  374. osc.writeColor = function (color) {
  375. var alpha = Math.round(color.a * 255),
  376. arr = new Uint8Array([color.r, color.g, color.b, alpha]);
  377. return arr;
  378. };
  379. /**
  380. * Reads an OSC true ("T") value by directly returning the JavaScript Boolean "true".
  381. */
  382. osc.readTrue = function () {
  383. return true;
  384. };
  385. /**
  386. * Reads an OSC false ("F") value by directly returning the JavaScript Boolean "false".
  387. */
  388. osc.readFalse = function () {
  389. return false;
  390. };
  391. /**
  392. * Reads an OSC nil ("N") value by directly returning the JavaScript "null" value.
  393. */
  394. osc.readNull = function () {
  395. return null;
  396. };
  397. /**
  398. * Reads an OSC impulse/bang/infinitum ("I") value by directly returning 1.0.
  399. */
  400. osc.readImpulse = function () {
  401. return 1.0;
  402. };
  403. /**
  404. * Reads an OSC time tag ("t").
  405. *
  406. * @param {DataView} dv the DataView instance to read from
  407. * @param {Object} offsetState an offset state object containing the current index into dv
  408. * @param {Object} a time tag object containing both the raw NTP as well as the converted native (i.e. JS/UNIX) time
  409. */
  410. osc.readTimeTag = function (dv, offsetState) {
  411. var secs1900 = osc.readPrimitive(dv, "getUint32", 4, offsetState),
  412. frac = osc.readPrimitive(dv, "getUint32", 4, offsetState),
  413. native = (secs1900 === 0 && frac === 1) ? Date.now() : osc.ntpToJSTime(secs1900, frac);
  414. return {
  415. raw: [secs1900, frac],
  416. native: native
  417. };
  418. };
  419. /**
  420. * Writes an OSC time tag ("t").
  421. *
  422. * Takes, as its argument, a time tag object containing either a "raw" or "native property."
  423. * The raw timestamp must conform to the NTP standard representation, consisting of two unsigned int32
  424. * values. The first represents the number of seconds since January 1, 1900; the second, fractions of a second.
  425. * "Native" JavaScript timestamps are specified as a Number representing milliseconds since January 1, 1970.
  426. *
  427. * @param {Object} timeTag time tag object containing either a native JS timestamp (in ms) or a NTP timestamp pair
  428. * @return {Uint8Array} raw bytes for the written time tag
  429. */
  430. osc.writeTimeTag = function (timeTag) {
  431. var raw = timeTag.raw ? timeTag.raw : osc.jsToNTPTime(timeTag.native),
  432. arr = new Uint8Array(8), // Two Unit32s.
  433. dv = new DataView(arr.buffer);
  434. osc.writeInt32(raw[0], dv, 0);
  435. osc.writeInt32(raw[1], dv, 4);
  436. return arr;
  437. };
  438. /**
  439. * Produces a time tag containing a raw NTP timestamp
  440. * relative to now by the specified number of seconds.
  441. *
  442. * @param {Number} secs the number of seconds relative to now (i.e. + for the future, - for the past)
  443. * @param {Number} now the number of milliseconds since epoch to use as the current time. Defaults to Date.now()
  444. * @return {Object} the time tag
  445. */
  446. osc.timeTag = function (secs, now) {
  447. secs = secs || 0;
  448. now = now || Date.now();
  449. var nowSecs = now / 1000,
  450. nowWhole = Math.floor(nowSecs),
  451. nowFracs = nowSecs - nowWhole,
  452. secsWhole = Math.floor(secs),
  453. secsFracs = secs - secsWhole,
  454. fracs = nowFracs + secsFracs;
  455. if (fracs > 1) {
  456. var fracsWhole = Math.floor(fracs),
  457. fracsFracs = fracs - fracsWhole;
  458. secsWhole += fracsWhole;
  459. fracs = fracsFracs;
  460. }
  461. var ntpSecs = nowWhole + secsWhole + osc.SECS_70YRS,
  462. ntpFracs = Math.round(osc.TWO_32 * fracs);
  463. return {
  464. raw: [ntpSecs, ntpFracs]
  465. };
  466. };
  467. /**
  468. * Converts OSC's standard time tag representation (which is the NTP format)
  469. * into the JavaScript/UNIX format in milliseconds.
  470. *
  471. * @param {Number} secs1900 the number of seconds since 1900
  472. * @param {Number} frac the number of fractions of a second (between 0 and 2^32)
  473. * @return {Number} a JavaScript-compatible timestamp in milliseconds
  474. */
  475. osc.ntpToJSTime = function (secs1900, frac) {
  476. var secs1970 = secs1900 - osc.SECS_70YRS,
  477. decimals = frac / osc.TWO_32,
  478. msTime = (secs1970 + decimals) * 1000;
  479. return msTime;
  480. };
  481. osc.jsToNTPTime = function (jsTime) {
  482. var secs = jsTime / 1000,
  483. secsWhole = Math.floor(secs),
  484. secsFrac = secs - secsWhole,
  485. ntpSecs = secsWhole + osc.SECS_70YRS,
  486. ntpFracs = Math.round(osc.TWO_32 * secsFrac);
  487. return [ntpSecs, ntpFracs];
  488. };
  489. /**
  490. * Reads the argument portion of an OSC message.
  491. *
  492. * @param {DataView} dv a DataView instance to read from
  493. * @param {Object} offsetState the offsetState object that stores the current offset into dv
  494. * @param {Oobject} [options] read options
  495. * @return {Array} an array of the OSC arguments that were read
  496. */
  497. osc.readArguments = function (dv, options, offsetState) {
  498. var typeTagString = osc.readString(dv, offsetState);
  499. if (typeTagString.indexOf(",") !== 0) {
  500. // Despite what the OSC 1.0 spec says,
  501. // it just doesn't make sense to handle messages without type tags.
  502. // scsynth appears to read such messages as if they have a single
  503. // Uint8 argument. sclang throws an error if the type tag is omitted.
  504. throw new Error("A malformed type tag string was found while reading " +
  505. "the arguments of an OSC message. String was: " +
  506. typeTagString, " at offset: " + offsetState.idx);
  507. }
  508. var argTypes = typeTagString.substring(1).split(""),
  509. args = [];
  510. osc.readArgumentsIntoArray(args, argTypes, typeTagString, dv, options, offsetState);
  511. return args;
  512. };
  513. // Unsupported, non-API function.
  514. osc.readArgument = function (argType, typeTagString, dv, options, offsetState) {
  515. var typeSpec = osc.argumentTypes[argType];
  516. if (!typeSpec) {
  517. throw new Error("'" + argType + "' is not a valid OSC type tag. Type tag string was: " + typeTagString);
  518. }
  519. var argReader = typeSpec.reader,
  520. arg = osc[argReader](dv, offsetState);
  521. if (options.metadata) {
  522. arg = {
  523. type: argType,
  524. value: arg
  525. };
  526. }
  527. return arg;
  528. };
  529. // Unsupported, non-API function.
  530. osc.readArgumentsIntoArray = function (arr, argTypes, typeTagString, dv, options, offsetState) {
  531. var i = 0;
  532. while (i < argTypes.length) {
  533. var argType = argTypes[i],
  534. arg;
  535. if (argType === "[") {
  536. var fromArrayOpen = argTypes.slice(i + 1),
  537. endArrayIdx = fromArrayOpen.indexOf("]");
  538. if (endArrayIdx < 0) {
  539. throw new Error("Invalid argument type tag: an open array type tag ('[') was found " +
  540. "without a matching close array tag ('[]'). Type tag was: " + typeTagString);
  541. }
  542. var typesInArray = fromArrayOpen.slice(0, endArrayIdx);
  543. arg = osc.readArgumentsIntoArray([], typesInArray, typeTagString, dv, options, offsetState);
  544. i += endArrayIdx + 2;
  545. } else {
  546. arg = osc.readArgument(argType, typeTagString, dv, options, offsetState);
  547. i++;
  548. }
  549. arr.push(arg);
  550. }
  551. return arr;
  552. };
  553. /**
  554. * Writes the specified arguments.
  555. *
  556. * @param {Array} args an array of arguments
  557. * @param {Object} options options for writing
  558. * @return {Uint8Array} a buffer containing the OSC-formatted argument type tag and values
  559. */
  560. osc.writeArguments = function (args, options) {
  561. var argCollection = osc.collectArguments(args, options);
  562. return osc.joinParts(argCollection);
  563. };
  564. // Unsupported, non-API function.
  565. osc.joinParts = function (dataCollection) {
  566. var buf = new Uint8Array(dataCollection.byteLength),
  567. parts = dataCollection.parts,
  568. offset = 0;
  569. for (var i = 0; i < parts.length; i++) {
  570. var part = parts[i];
  571. osc.copyByteArray(part, buf, offset);
  572. offset += part.length;
  573. }
  574. return buf;
  575. };
  576. // Unsupported, non-API function.
  577. osc.addDataPart = function (dataPart, dataCollection) {
  578. dataCollection.parts.push(dataPart);
  579. dataCollection.byteLength += dataPart.length;
  580. };
  581. osc.writeArrayArguments = function (args, dataCollection) {
  582. var typeTag = "[";
  583. for (var i = 0; i < args.length; i++) {
  584. var arg = args[i];
  585. typeTag += osc.writeArgument(arg, dataCollection);
  586. }
  587. typeTag += "]";
  588. return typeTag;
  589. };
  590. osc.writeArgument = function (arg, dataCollection) {
  591. if (osc.isArray(arg)) {
  592. return osc.writeArrayArguments(arg, dataCollection);
  593. }
  594. var type = arg.type,
  595. writer = osc.argumentTypes[type].writer;
  596. if (writer) {
  597. var data = osc[writer](arg.value);
  598. osc.addDataPart(data, dataCollection);
  599. }
  600. return arg.type;
  601. };
  602. // Unsupported, non-API function.
  603. osc.collectArguments = function (args, options, dataCollection) {
  604. if (!osc.isArray(args)) {
  605. args = typeof args === "undefined" ? [] : [args];
  606. }
  607. dataCollection = dataCollection || {
  608. byteLength: 0,
  609. parts: []
  610. };
  611. if (!options.metadata) {
  612. args = osc.annotateArguments(args);
  613. }
  614. var typeTagString = ",",
  615. currPartIdx = dataCollection.parts.length;
  616. for (var i = 0; i < args.length; i++) {
  617. var arg = args[i];
  618. typeTagString += osc.writeArgument(arg, dataCollection);
  619. }
  620. var typeData = osc.writeString(typeTagString);
  621. dataCollection.byteLength += typeData.byteLength;
  622. dataCollection.parts.splice(currPartIdx, 0, typeData);
  623. return dataCollection;
  624. };
  625. /**
  626. * Reads an OSC message.
  627. *
  628. * @param {Array-like} data an array of bytes to read from
  629. * @param {Object} [options] read options
  630. * @param {Object} [offsetState] an offsetState object that stores the current offset into dv
  631. * @return {Object} the OSC message, formatted as a JavaScript object containing "address" and "args" properties
  632. */
  633. osc.readMessage = function (data, options, offsetState) {
  634. options = options || osc.defaults;
  635. var dv = osc.dataView(data, data.byteOffset, data.byteLength);
  636. offsetState = offsetState || {
  637. idx: 0
  638. };
  639. var address = osc.readString(dv, offsetState);
  640. return osc.readMessageContents(address, dv, options, offsetState);
  641. };
  642. // Unsupported, non-API function.
  643. osc.readMessageContents = function (address, dv, options, offsetState) {
  644. if (address.indexOf("/") !== 0) {
  645. throw new Error("A malformed OSC address was found while reading " +
  646. "an OSC message. String was: " + address);
  647. }
  648. var args = osc.readArguments(dv, options, offsetState);
  649. return {
  650. address: address,
  651. args: args.length === 1 && options.unpackSingleArgs ? args[0] : args
  652. };
  653. };
  654. // Unsupported, non-API function.
  655. osc.collectMessageParts = function (msg, options, dataCollection) {
  656. dataCollection = dataCollection || {
  657. byteLength: 0,
  658. parts: []
  659. };
  660. osc.addDataPart(osc.writeString(msg.address), dataCollection);
  661. return osc.collectArguments(msg.args, options, dataCollection);
  662. };
  663. /**
  664. * Writes an OSC message.
  665. *
  666. * @param {Object} msg a message object containing "address" and "args" properties
  667. * @param {Object} [options] write options
  668. * @return {Uint8Array} an array of bytes containing the OSC message
  669. */
  670. osc.writeMessage = function (msg, options) {
  671. options = options || osc.defaults;
  672. if (!osc.isValidMessage(msg)) {
  673. throw new Error("An OSC message must contain a valid address. Message was: " +
  674. JSON.stringify(msg, null, 2));
  675. }
  676. var msgCollection = osc.collectMessageParts(msg, options);
  677. return osc.joinParts(msgCollection);
  678. };
  679. osc.isValidMessage = function (msg) {
  680. return msg.address && msg.address.indexOf("/") === 0;
  681. };
  682. /**
  683. * Reads an OSC bundle.
  684. *
  685. * @param {DataView} dv the DataView instance to read from
  686. * @param {Object} [options] read optoins
  687. * @param {Object} [offsetState] an offsetState object that stores the current offset into dv
  688. * @return {Object} the bundle or message object that was read
  689. */
  690. osc.readBundle = function (dv, options, offsetState) {
  691. return osc.readPacket(dv, options, offsetState);
  692. };
  693. // Unsupported, non-API function.
  694. osc.collectBundlePackets = function (bundle, options, dataCollection) {
  695. dataCollection = dataCollection || {
  696. byteLength: 0,
  697. parts: []
  698. };
  699. osc.addDataPart(osc.writeString("#bundle"), dataCollection);
  700. osc.addDataPart(osc.writeTimeTag(bundle.timeTag), dataCollection);
  701. for (var i = 0; i < bundle.packets.length; i++) {
  702. var packet = bundle.packets[i],
  703. collector = packet.address ? osc.collectMessageParts : osc.collectBundlePackets,
  704. packetCollection = collector(packet, options);
  705. dataCollection.byteLength += packetCollection.byteLength;
  706. osc.addDataPart(osc.writeInt32(packetCollection.byteLength), dataCollection);
  707. dataCollection.parts = dataCollection.parts.concat(packetCollection.parts);
  708. }
  709. return dataCollection;
  710. };
  711. /**
  712. * Writes an OSC bundle.
  713. *
  714. * @param {Object} a bundle object containing "timeTag" and "packets" properties
  715. * @param {object} [options] write options
  716. * @return {Uint8Array} an array of bytes containing the message
  717. */
  718. osc.writeBundle = function (bundle, options) {
  719. if (!osc.isValidBundle(bundle)) {
  720. throw new Error("An OSC bundle must contain 'timeTag' and 'packets' properties. " +
  721. "Bundle was: " + JSON.stringify(bundle, null, 2));
  722. }
  723. options = options || osc.defaults;
  724. var bundleCollection = osc.collectBundlePackets(bundle, options);
  725. return osc.joinParts(bundleCollection);
  726. };
  727. osc.isValidBundle = function (bundle) {
  728. return bundle.timeTag !== undefined && bundle.packets !== undefined;
  729. };
  730. // Unsupported, non-API function.
  731. osc.readBundleContents = function (dv, options, offsetState, len) {
  732. var timeTag = osc.readTimeTag(dv, offsetState),
  733. packets = [];
  734. while (offsetState.idx < len) {
  735. var packetSize = osc.readInt32(dv, offsetState),
  736. packetLen = offsetState.idx + packetSize,
  737. packet = osc.readPacket(dv, options, offsetState, packetLen);
  738. packets.push(packet);
  739. }
  740. return {
  741. timeTag: timeTag,
  742. packets: packets
  743. };
  744. };
  745. /**
  746. * Reads an OSC packet, which may consist of either a bundle or a message.
  747. *
  748. * @param {Array-like} data an array of bytes to read from
  749. * @param {Object} [options] read options
  750. * @return {Object} a bundle or message object
  751. */
  752. osc.readPacket = function (data, options, offsetState, len) {
  753. var dv = osc.dataView(data, data.byteOffset, data.byteLength);
  754. len = len === undefined ? dv.byteLength : len;
  755. offsetState = offsetState || {
  756. idx: 0
  757. };
  758. var header = osc.readString(dv, offsetState),
  759. firstChar = header[0];
  760. if (firstChar === "#") {
  761. return osc.readBundleContents(dv, options, offsetState, len);
  762. } else if (firstChar === "/") {
  763. return osc.readMessageContents(header, dv, options, offsetState);
  764. }
  765. throw new Error("The header of an OSC packet didn't contain an OSC address or a #bundle string." +
  766. " Header was: " + header);
  767. };
  768. /**
  769. * Writes an OSC packet, which may consist of either of a bundle or a message.
  770. *
  771. * @param {Object} a bundle or message object
  772. * @param {Object} [options] write options
  773. * @return {Uint8Array} an array of bytes containing the message
  774. */
  775. osc.writePacket = function (packet, options) {
  776. if (osc.isValidMessage(packet)) {
  777. return osc.writeMessage(packet, options);
  778. } else if (osc.isValidBundle(packet)) {
  779. return osc.writeBundle(packet, options);
  780. } else {
  781. throw new Error("The specified packet was not recognized as a valid OSC message or bundle." +
  782. " Packet was: " + JSON.stringify(packet, null, 2));
  783. }
  784. };
  785. // Unsupported, non-API.
  786. osc.argumentTypes = {
  787. i: {
  788. reader: "readInt32",
  789. writer: "writeInt32"
  790. },
  791. h: {
  792. reader: "readInt64",
  793. writer: "writeInt64"
  794. },
  795. f: {
  796. reader: "readFloat32",
  797. writer: "writeFloat32"
  798. },
  799. s: {
  800. reader: "readString",
  801. writer: "writeString"
  802. },
  803. S: {
  804. reader: "readString",
  805. writer: "writeString"
  806. },
  807. b: {
  808. reader: "readBlob",
  809. writer: "writeBlob"
  810. },
  811. t: {
  812. reader: "readTimeTag",
  813. writer: "writeTimeTag"
  814. },
  815. T: {
  816. reader: "readTrue"
  817. },
  818. F: {
  819. reader: "readFalse"
  820. },
  821. N: {
  822. reader: "readNull"
  823. },
  824. I: {
  825. reader: "readImpulse"
  826. },
  827. d: {
  828. reader: "readFloat64",
  829. writer: "writeFloat64"
  830. },
  831. c: {
  832. reader: "readChar32",
  833. writer: "writeChar32"
  834. },
  835. r: {
  836. reader: "readColor",
  837. writer: "writeColor"
  838. },
  839. m: {
  840. reader: "readMIDIBytes",
  841. writer: "writeMIDIBytes"
  842. },
  843. // [] are special cased within read/writeArguments()
  844. };
  845. // Unsupported, non-API function.
  846. osc.inferTypeForArgument = function (arg) {
  847. var type = typeof arg;
  848. // TODO: This is freaking hideous.
  849. switch (type) {
  850. case "boolean":
  851. return arg ? "T" : "F";
  852. case "string":
  853. return "s";
  854. case "number":
  855. return "f";
  856. case "undefined":
  857. return "N";
  858. case "object":
  859. if (arg === null) {
  860. return "N";
  861. } else if (arg instanceof Uint8Array ||
  862. arg instanceof ArrayBuffer) {
  863. return "b";
  864. } else if (typeof arg.high === "number" && typeof arg.low === "number") {
  865. return "h";
  866. }
  867. break;
  868. }
  869. throw new Error("Can't infer OSC argument type for value: " +
  870. JSON.stringify(arg, null, 2));
  871. };
  872. // Unsupported, non-API function.
  873. osc.annotateArguments = function (args) {
  874. var annotated = [];
  875. for (var i = 0; i < args.length; i++) {
  876. var arg = args[i],
  877. msgArg;
  878. if (typeof (arg) === "object" && arg.type && arg.value !== undefined) {
  879. // We've got an explicitly typed argument.
  880. msgArg = arg;
  881. } else if (osc.isArray(arg)) {
  882. // We've got an array of arguments,
  883. // so they each need to be inferred and expanded.
  884. msgArg = osc.annotateArguments(arg);
  885. } else {
  886. var oscType = osc.inferTypeForArgument(arg);
  887. msgArg = {
  888. type: oscType,
  889. value: arg
  890. };
  891. }
  892. annotated.push(msgArg);
  893. }
  894. return annotated;
  895. };
  896. if (osc.isCommonJS) {
  897. module.exports = osc;
  898. }
  899. }());
  900. ;/*
  901. Copyright 2013 Daniel Wirtz <dcode@dcode.io>
  902. Copyright 2009 The Closure Library Authors. All Rights Reserved.
  903. Licensed under the Apache License, Version 2.0 (the "License");
  904. you may not use this file except in compliance with the License.
  905. You may obtain a copy of the License at
  906. http://www.apache.org/licenses/LICENSE-2.0
  907. Unless required by applicable law or agreed to in writing, software
  908. distributed under the License is distributed on an "AS-IS" BASIS,
  909. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  910. See the License for the specific language governing permissions and
  911. limitations under the License.
  912. */
  913. /**
  914. * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
  915. * Released under the Apache License, Version 2.0
  916. * see: https://github.com/dcodeIO/long.js for details
  917. */
  918. (function(global, factory) {
  919. /* AMD */ if (typeof define === 'function' && define["amd"])
  920. define([], factory);
  921. /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
  922. module["exports"] = factory();
  923. /* Global */ else
  924. (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
  925. })(this, function() {
  926. "use strict";
  927. /**
  928. * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
  929. * See the from* functions below for more convenient ways of constructing Longs.
  930. * @exports Long
  931. * @class A Long class for representing a 64 bit two's-complement integer value.
  932. * @param {number} low The low (signed) 32 bits of the long
  933. * @param {number} high The high (signed) 32 bits of the long
  934. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  935. * @constructor
  936. */
  937. function Long(low, high, unsigned) {
  938. /**
  939. * The low 32 bits as a signed value.
  940. * @type {number}
  941. * @expose
  942. */
  943. this.low = low | 0;
  944. /**
  945. * The high 32 bits as a signed value.
  946. * @type {number}
  947. * @expose
  948. */
  949. this.high = high | 0;
  950. /**
  951. * Whether unsigned or not.
  952. * @type {boolean}
  953. * @expose
  954. */
  955. this.unsigned = !!unsigned;
  956. }
  957. // The internal representation of a long is the two given signed, 32-bit values.
  958. // We use 32-bit pieces because these are the size of integers on which
  959. // Javascript performs bit-operations. For operations like addition and
  960. // multiplication, we split each number into 16 bit pieces, which can easily be
  961. // multiplied within Javascript's floating-point representation without overflow
  962. // or change in sign.
  963. //
  964. // In the algorithms below, we frequently reduce the negative case to the
  965. // positive case by negating the input(s) and then post-processing the result.
  966. // Note that we must ALWAYS check specially whether those values are MIN_VALUE
  967. // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  968. // a positive number, it overflows back into a negative). Not handling this
  969. // case would often result in infinite recursion.
  970. //
  971. // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
  972. // methods on which they depend.
  973. /**
  974. * An indicator used to reliably determine if an object is a Long or not.
  975. * @type {boolean}
  976. * @const
  977. * @expose
  978. * @private
  979. */
  980. Long.__isLong__;
  981. Object.defineProperty(Long.prototype, "__isLong__", {
  982. value: true,
  983. enumerable: false,
  984. configurable: false
  985. });
  986. /**
  987. * @function
  988. * @param {*} obj Object
  989. * @returns {boolean}
  990. * @inner
  991. */
  992. function isLong(obj) {
  993. return (obj && obj["__isLong__"]) === true;
  994. }
  995. /**
  996. * Tests if the specified object is a Long.
  997. * @function
  998. * @param {*} obj Object
  999. * @returns {boolean}
  1000. * @expose
  1001. */
  1002. Long.isLong = isLong;
  1003. /**
  1004. * A cache of the Long representations of small integer values.
  1005. * @type {!Object}
  1006. * @inner
  1007. */
  1008. var INT_CACHE = {};
  1009. /**
  1010. * A cache of the Long representations of small unsigned integer values.
  1011. * @type {!Object}
  1012. * @inner
  1013. */
  1014. var UINT_CACHE = {};
  1015. /**
  1016. * @param {number} value
  1017. * @param {boolean=} unsigned
  1018. * @returns {!Long}
  1019. * @inner
  1020. */
  1021. function fromInt(value, unsigned) {
  1022. var obj, cachedObj, cache;
  1023. if (unsigned) {
  1024. value >>>= 0;
  1025. if (cache = (0 <= value && value < 256)) {
  1026. cachedObj = UINT_CACHE[value];
  1027. if (cachedObj)
  1028. return cachedObj;
  1029. }
  1030. obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  1031. if (cache)
  1032. UINT_CACHE[value] = obj;
  1033. return obj;
  1034. } else {
  1035. value |= 0;
  1036. if (cache = (-128 <= value && value < 128)) {
  1037. cachedObj = INT_CACHE[value];
  1038. if (cachedObj)
  1039. return cachedObj;
  1040. }
  1041. obj = fromBits(value, value < 0 ? -1 : 0, false);
  1042. if (cache)
  1043. INT_CACHE[value] = obj;
  1044. return obj;
  1045. }
  1046. }
  1047. /**
  1048. * Returns a Long representing the given 32 bit integer value.
  1049. * @function
  1050. * @param {number} value The 32 bit integer in question
  1051. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  1052. * @returns {!Long} The corresponding Long value
  1053. * @expose
  1054. */
  1055. Long.fromInt = fromInt;
  1056. /**
  1057. * @param {number} value
  1058. * @param {boolean=} unsigned
  1059. * @returns {!Long}
  1060. * @inner
  1061. */
  1062. function fromNumber(value, unsigned) {
  1063. if (isNaN(value) || !isFinite(value))
  1064. return unsigned ? UZERO : ZERO;
  1065. if (unsigned) {
  1066. if (value < 0)
  1067. return UZERO;
  1068. if (value >= TWO_PWR_64_DBL)
  1069. return MAX_UNSIGNED_VALUE;
  1070. } else {
  1071. if (value <= -TWO_PWR_63_DBL)
  1072. return MIN_VALUE;
  1073. if (value + 1 >= TWO_PWR_63_DBL)
  1074. return MAX_VALUE;
  1075. }
  1076. if (value < 0)
  1077. return fromNumber(-value, unsigned).neg();
  1078. return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  1079. }
  1080. /**
  1081. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  1082. * @function
  1083. * @param {number} value The number in question
  1084. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  1085. * @returns {!Long} The corresponding Long value
  1086. * @expose
  1087. */
  1088. Long.fromNumber = fromNumber;
  1089. /**
  1090. * @param {number} lowBits
  1091. * @param {number} highBits
  1092. * @param {boolean=} unsigned
  1093. * @returns {!Long}
  1094. * @inner
  1095. */
  1096. function fromBits(lowBits, highBits, unsigned) {
  1097. return new Long(lowBits, highBits, unsigned);
  1098. }
  1099. /**
  1100. * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
  1101. * assumed to use 32 bits.
  1102. * @function
  1103. * @param {number} lowBits The low 32 bits
  1104. * @param {number} highBits The high 32 bits
  1105. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  1106. * @returns {!Long} The corresponding Long value
  1107. * @expose
  1108. */
  1109. Long.fromBits = fromBits;
  1110. /**
  1111. * @function
  1112. * @param {number} base
  1113. * @param {number} exponent
  1114. * @returns {number}
  1115. * @inner
  1116. */
  1117. var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
  1118. /**
  1119. * @param {string} str
  1120. * @param {(boolean|number)=} unsigned
  1121. * @param {number=} radix
  1122. * @returns {!Long}
  1123. * @inner
  1124. */
  1125. function fromString(str, unsigned, radix) {
  1126. if (str.length === 0)
  1127. throw Error('empty string');
  1128. if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
  1129. return ZERO;
  1130. if (typeof unsigned === 'number') // For goog.math.long compatibility
  1131. radix = unsigned,
  1132. unsigned = false;
  1133. radix = radix || 10;
  1134. if (radix < 2 || 36 < radix)
  1135. throw RangeError('radix');
  1136. var p;
  1137. if ((p = str.indexOf('-')) > 0)
  1138. throw Error('interior hyphen');
  1139. else if (p === 0) {
  1140. return fromString(str.substring(1), unsigned, radix).neg();
  1141. }
  1142. // Do several (8) digits each time through the loop, so as to
  1143. // minimize the calls to the very expensive emulated div.
  1144. var radixToPower = fromNumber(pow_dbl(radix, 8));
  1145. var result = ZERO;
  1146. for (var i = 0; i < str.length; i += 8) {
  1147. var size = Math.min(8, str.length - i),
  1148. value = parseInt(str.substring(i, i + size), radix);
  1149. if (size < 8) {
  1150. var power = fromNumber(pow_dbl(radix, size));
  1151. result = result.mul(power).add(fromNumber(value));
  1152. } else {
  1153. result = result.mul(radixToPower);
  1154. result = result.add(fromNumber(value));
  1155. }
  1156. }
  1157. result.unsigned = unsigned;
  1158. return result;
  1159. }
  1160. /**
  1161. * Returns a Long representation of the given string, written using the specified radix.
  1162. * @function
  1163. * @param {string} str The textual representation of the Long
  1164. * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
  1165. * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
  1166. * @returns {!Long} The corresponding Long value
  1167. * @expose
  1168. */
  1169. Long.fromString = fromString;
  1170. /**
  1171. * @function
  1172. * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
  1173. * @returns {!Long}
  1174. * @inner
  1175. */
  1176. function fromValue(val) {
  1177. if (val /* is compatible */ instanceof Long)
  1178. return val;
  1179. if (typeof val === 'number')
  1180. return fromNumber(val);
  1181. if (typeof val === 'string')
  1182. return fromString(val);
  1183. // Throws for non-objects, converts non-instanceof Long:
  1184. return fromBits(val.low, val.high, val.unsigned);
  1185. }
  1186. /**
  1187. * Converts the specified value to a Long.
  1188. * @function
  1189. * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
  1190. * @returns {!Long}
  1191. * @expose
  1192. */
  1193. Long.fromValue = fromValue;
  1194. // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
  1195. // no runtime penalty for these.
  1196. /**
  1197. * @type {number}
  1198. * @const
  1199. * @inner
  1200. */
  1201. var TWO_PWR_16_DBL = 1 << 16;
  1202. /**
  1203. * @type {number}
  1204. * @const
  1205. * @inner
  1206. */
  1207. var TWO_PWR_24_DBL = 1 << 24;
  1208. /**
  1209. * @type {number}
  1210. * @const
  1211. * @inner
  1212. */
  1213. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  1214. /**
  1215. * @type {number}
  1216. * @const
  1217. * @inner
  1218. */
  1219. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  1220. /**
  1221. * @type {number}
  1222. * @const
  1223. * @inner
  1224. */
  1225. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  1226. /**
  1227. * @type {!Long}
  1228. * @const
  1229. * @inner
  1230. */
  1231. var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
  1232. /**
  1233. * @type {!Long}
  1234. * @inner
  1235. */
  1236. var ZERO = fromInt(0);
  1237. /**
  1238. * Signed zero.
  1239. * @type {!Long}
  1240. * @expose
  1241. */
  1242. Long.ZERO = ZERO;
  1243. /**
  1244. * @type {!Long}
  1245. * @inner
  1246. */
  1247. var UZERO = fromInt(0, true);
  1248. /**
  1249. * Unsigned zero.
  1250. * @type {!Long}
  1251. * @expose
  1252. */
  1253. Long.UZERO = UZERO;
  1254. /**
  1255. * @type {!Long}
  1256. * @inner
  1257. */
  1258. var ONE = fromInt(1);
  1259. /**
  1260. * Signed one.
  1261. * @type {!Long}
  1262. * @expose
  1263. */
  1264. Long.ONE = ONE;
  1265. /**
  1266. * @type {!Long}
  1267. * @inner
  1268. */
  1269. var UONE = fromInt(1, true);
  1270. /**
  1271. * Unsigned one.
  1272. * @type {!Long}
  1273. * @expose
  1274. */
  1275. Long.UONE = UONE;
  1276. /**
  1277. * @type {!Long}
  1278. * @inner
  1279. */
  1280. var NEG_ONE = fromInt(-1);
  1281. /**
  1282. * Signed negative one.
  1283. * @type {!Long}
  1284. * @expose
  1285. */
  1286. Long.NEG_ONE = NEG_ONE;
  1287. /**
  1288. * @type {!Long}
  1289. * @inner
  1290. */
  1291. var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
  1292. /**
  1293. * Maximum signed value.
  1294. * @type {!Long}
  1295. * @expose
  1296. */
  1297. Long.MAX_VALUE = MAX_VALUE;
  1298. /**
  1299. * @type {!Long}
  1300. * @inner
  1301. */
  1302. var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
  1303. /**
  1304. * Maximum unsigned value.
  1305. * @type {!Long}
  1306. * @expose
  1307. */
  1308. Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
  1309. /**
  1310. * @type {!Long}
  1311. * @inner
  1312. */
  1313. var MIN_VALUE = fromBits(0, 0x80000000|0, false);
  1314. /**
  1315. * Minimum signed value.
  1316. * @type {!Long}
  1317. * @expose
  1318. */
  1319. Long.MIN_VALUE = MIN_VALUE;
  1320. /**
  1321. * @alias Long.prototype
  1322. * @inner
  1323. */
  1324. var LongPrototype = Long.prototype;
  1325. /**
  1326. * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
  1327. * @returns {number}
  1328. * @expose
  1329. */
  1330. LongPrototype.toInt = function toInt() {
  1331. return this.unsigned ? this.low >>> 0 : this.low;
  1332. };
  1333. /**
  1334. * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
  1335. * @returns {number}
  1336. * @expose
  1337. */
  1338. LongPrototype.toNumber = function toNumber() {
  1339. if (this.unsigned)
  1340. return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
  1341. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  1342. };
  1343. /**
  1344. * Converts the Long to a string written in the specified radix.
  1345. * @param {number=} radix Radix (2-36), defaults to 10
  1346. * @returns {string}
  1347. * @override
  1348. * @throws {RangeError} If `radix` is out of range
  1349. * @expose
  1350. */
  1351. LongPrototype.toString = function toString(radix) {
  1352. radix = radix || 10;
  1353. if (radix < 2 || 36 < radix)
  1354. throw RangeError('radix');
  1355. if (this.isZero())
  1356. return '0';
  1357. if (this.isNegative()) { // Unsigned Longs are never negative
  1358. if (this.eq(MIN_VALUE)) {
  1359. // We need to change the Long value before it can be negated, so we remove
  1360. // the bottom-most digit in this base and then recurse to do the rest.
  1361. var radixLong = fromNumber(radix),
  1362. div = this.div(radixLong),
  1363. rem1 = div.mul(radixLong).sub(this);
  1364. return div.toString(radix) + rem1.toInt().toString(radix);
  1365. } else
  1366. return '-' + this.neg().toString(radix);
  1367. }
  1368. // Do several (6) digits each time through the loop, so as to
  1369. // minimize the calls to the very expensive emulated div.
  1370. var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
  1371. rem = this;
  1372. var result = '';
  1373. while (true) {
  1374. var remDiv = rem.div(radixToPower),
  1375. intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
  1376. digits = intval.toString(radix);
  1377. rem = remDiv;
  1378. if (rem.isZero())
  1379. return digits + result;
  1380. else {
  1381. while (digits.length < 6)
  1382. digits = '0' + digits;
  1383. result = '' + digits + result;
  1384. }
  1385. }
  1386. };
  1387. /**
  1388. * Gets the high 32 bits as a signed integer.
  1389. * @returns {number} Signed high bits
  1390. * @expose
  1391. */
  1392. LongPrototype.getHighBits = function getHighBits() {
  1393. return this.high;
  1394. };
  1395. /**
  1396. * Gets the high 32 bits as an unsigned integer.
  1397. * @returns {number} Unsigned high bits
  1398. * @expose
  1399. */
  1400. LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
  1401. return this.high >>> 0;
  1402. };
  1403. /**
  1404. * Gets the low 32 bits as a signed integer.
  1405. * @returns {number} Signed low bits
  1406. * @expose
  1407. */
  1408. LongPrototype.getLowBits = function getLowBits() {
  1409. return this.low;
  1410. };
  1411. /**
  1412. * Gets the low 32 bits as an unsigned integer.
  1413. * @returns {number} Unsigned low bits
  1414. * @expose
  1415. */
  1416. LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
  1417. return this.low >>> 0;
  1418. };
  1419. /**
  1420. * Gets the number of bits needed to represent the absolute value of this Long.
  1421. * @returns {number}
  1422. * @expose
  1423. */
  1424. LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
  1425. if (this.isNegative()) // Unsigned Longs are never negative
  1426. return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  1427. var val = this.high != 0 ? this.high : this.low;
  1428. for (var bit = 31; bit > 0; bit--)
  1429. if ((val & (1 << bit)) != 0)
  1430. break;
  1431. return this.high != 0 ? bit + 33 : bit + 1;
  1432. };
  1433. /**
  1434. * Tests if this Long's value equals zero.
  1435. * @returns {boolean}
  1436. * @expose
  1437. */
  1438. LongPrototype.isZero = function isZero() {
  1439. return this.high === 0 && this.low === 0;
  1440. };
  1441. /**
  1442. * Tests if this Long's value is negative.
  1443. * @returns {boolean}
  1444. * @expose
  1445. */
  1446. LongPrototype.isNegative = function isNegative() {
  1447. return !this.unsigned && this.high < 0;
  1448. };
  1449. /**
  1450. * Tests if this Long's value is positive.
  1451. * @returns {boolean}
  1452. * @expose
  1453. */
  1454. LongPrototype.isPositive = function isPositive() {
  1455. return this.unsigned || this.high >= 0;
  1456. };
  1457. /**
  1458. * Tests if this Long's value is odd.
  1459. * @returns {boolean}
  1460. * @expose
  1461. */
  1462. LongPrototype.isOdd = function isOdd() {
  1463. return (this.low & 1) === 1;
  1464. };
  1465. /**
  1466. * Tests if this Long's value is even.
  1467. * @returns {boolean}
  1468. * @expose
  1469. */
  1470. LongPrototype.isEven = function isEven() {
  1471. return (this.low & 1) === 0;
  1472. };
  1473. /**
  1474. * Tests if this Long's value equals the specified's.
  1475. * @param {!Long|number|string} other Other value
  1476. * @returns {boolean}
  1477. * @expose
  1478. */
  1479. LongPrototype.equals = function equals(other) {
  1480. if (!isLong(other))
  1481. other = fromValue(other);
  1482. if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
  1483. return false;
  1484. return this.high === other.high && this.low === other.low;
  1485. };
  1486. /**
  1487. * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
  1488. * @function
  1489. * @param {!Long|number|string} other Other value
  1490. * @returns {boolean}
  1491. * @expose
  1492. */
  1493. LongPrototype.eq = LongPrototype.equals;
  1494. /**
  1495. * Tests if this Long's value differs from the specified's.
  1496. * @param {!Long|number|string} other Other value
  1497. * @returns {boolean}
  1498. * @expose
  1499. */
  1500. LongPrototype.notEquals = function notEquals(other) {
  1501. return !this.eq(/* validates */ other);
  1502. };
  1503. /**
  1504. * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
  1505. * @function
  1506. * @param {!Long|number|string} other Other value
  1507. * @returns {boolean}
  1508. * @expose
  1509. */
  1510. LongPrototype.neq = LongPrototype.notEquals;
  1511. /**
  1512. * Tests if this Long's value is less than the specified's.
  1513. * @param {!Long|number|string} other Other value
  1514. * @returns {boolean}
  1515. * @expose
  1516. */
  1517. LongPrototype.lessThan = function lessThan(other) {
  1518. return this.comp(/* validates */ other) < 0;
  1519. };
  1520. /**
  1521. * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
  1522. * @function
  1523. * @param {!Long|number|string} other Other value
  1524. * @returns {boolean}
  1525. * @expose
  1526. */
  1527. LongPrototype.lt = LongPrototype.lessThan;
  1528. /**
  1529. * Tests if this Long's value is less than or equal the specified's.
  1530. * @param {!Long|number|string} other Other value
  1531. * @returns {boolean}
  1532. * @expose
  1533. */
  1534. LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
  1535. return this.comp(/* validates */ other) <= 0;
  1536. };
  1537. /**
  1538. * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
  1539. * @function
  1540. * @param {!Long|number|string} other Other value
  1541. * @returns {boolean}
  1542. * @expose
  1543. */
  1544. LongPrototype.lte = LongPrototype.lessThanOrEqual;
  1545. /**
  1546. * Tests if this Long's value is greater than the specified's.
  1547. * @param {!Long|number|string} other Other value
  1548. * @returns {boolean}
  1549. * @expose
  1550. */
  1551. LongPrototype.greaterThan = function greaterThan(other) {
  1552. return this.comp(/* validates */ other) > 0;
  1553. };
  1554. /**
  1555. * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
  1556. * @function
  1557. * @param {!Long|number|string} other Other value
  1558. * @returns {boolean}
  1559. * @expose
  1560. */
  1561. LongPrototype.gt = LongPrototype.greaterThan;
  1562. /**
  1563. * Tests if this Long's value is greater than or equal the specified's.
  1564. * @param {!Long|number|string} other Other value
  1565. * @returns {boolean}
  1566. * @expose
  1567. */
  1568. LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
  1569. return this.comp(/* validates */ other) >= 0;
  1570. };
  1571. /**
  1572. * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
  1573. * @function
  1574. * @param {!Long|number|string} other Other value
  1575. * @returns {boolean}
  1576. * @expose
  1577. */
  1578. LongPrototype.gte = LongPrototype.greaterThanOrEqual;
  1579. /**
  1580. * Compares this Long's value with the specified's.
  1581. * @param {!Long|number|string} other Other value
  1582. * @returns {number} 0 if they are the same, 1 if the this is greater and -1
  1583. * if the given one is greater
  1584. * @expose
  1585. */
  1586. LongPrototype.compare = function compare(other) {
  1587. if (!isLong(other))
  1588. other = fromValue(other);
  1589. if (this.eq(other))
  1590. return 0;
  1591. var thisNeg = this.isNegative(),
  1592. otherNeg = other.isNegative();
  1593. if (thisNeg && !otherNeg)
  1594. return -1;
  1595. if (!thisNeg && otherNeg)
  1596. return 1;
  1597. // At this point the sign bits are the same
  1598. if (!this.unsigned)
  1599. return this.sub(other).isNegative() ? -1 : 1;
  1600. // Both are positive if at least one is unsigned
  1601. return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
  1602. };
  1603. /**
  1604. * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
  1605. * @function
  1606. * @param {!Long|number|string} other Other value
  1607. * @returns {number} 0 if they are the same, 1 if the this is greater and -1
  1608. * if the given one is greater
  1609. * @expose
  1610. */
  1611. LongPrototype.comp = LongPrototype.compare;
  1612. /**
  1613. * Negates this Long's value.
  1614. * @returns {!Long} Negated Long
  1615. * @expose
  1616. */
  1617. LongPrototype.negate = function negate() {
  1618. if (!this.unsigned && this.eq(MIN_VALUE))
  1619. return MIN_VALUE;
  1620. return this.not().add(ONE);
  1621. };
  1622. /**
  1623. * Negates this Long's value. This is an alias of {@link Long#negate}.
  1624. * @function
  1625. * @returns {!Long} Negated Long
  1626. * @expose
  1627. */
  1628. LongPrototype.neg = LongPrototype.negate;
  1629. /**
  1630. * Returns the sum of this and the specified Long.
  1631. * @param {!Long|number|string} addend Addend
  1632. * @returns {!Long} Sum
  1633. * @expose
  1634. */
  1635. LongPrototype.add = function add(addend) {
  1636. if (!isLong(addend))
  1637. addend = fromValue(addend);
  1638. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  1639. var a48 = this.high >>> 16;
  1640. var a32 = this.high & 0xFFFF;
  1641. var a16 = this.low >>> 16;
  1642. var a00 = this.low & 0xFFFF;
  1643. var b48 = addend.high >>> 16;
  1644. var b32 = addend.high & 0xFFFF;
  1645. var b16 = addend.low >>> 16;
  1646. var b00 = addend.low & 0xFFFF;
  1647. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1648. c00 += a00 + b00;
  1649. c16 += c00 >>> 16;
  1650. c00 &= 0xFFFF;
  1651. c16 += a16 + b16;
  1652. c32 += c16 >>> 16;
  1653. c16 &= 0xFFFF;
  1654. c32 += a32 + b32;
  1655. c48 += c32 >>> 16;
  1656. c32 &= 0xFFFF;
  1657. c48 += a48 + b48;
  1658. c48 &= 0xFFFF;
  1659. return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1660. };
  1661. /**
  1662. * Returns the difference of this and the specified Long.
  1663. * @param {!Long|number|string} subtrahend Subtrahend
  1664. * @returns {!Long} Difference
  1665. * @expose
  1666. */
  1667. LongPrototype.subtract = function subtract(subtrahend) {
  1668. if (!isLong(subtrahend))
  1669. subtrahend = fromValue(subtrahend);
  1670. return this.add(subtrahend.neg());
  1671. };
  1672. /**
  1673. * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
  1674. * @function
  1675. * @param {!Long|number|string} subtrahend Subtrahend
  1676. * @returns {!Long} Difference
  1677. * @expose
  1678. */
  1679. LongPrototype.sub = LongPrototype.subtract;
  1680. /**
  1681. * Returns the product of this and the specified Long.
  1682. * @param {!Long|number|string} multiplier Multiplier
  1683. * @returns {!Long} Product
  1684. * @expose
  1685. */
  1686. LongPrototype.multiply = function multiply(multiplier) {
  1687. if (this.isZero())
  1688. return ZERO;
  1689. if (!isLong(multiplier))
  1690. multiplier = fromValue(multiplier);
  1691. if (multiplier.isZero())
  1692. return ZERO;
  1693. if (this.eq(MIN_VALUE))
  1694. return multiplier.isOdd() ? MIN_VALUE : ZERO;
  1695. if (multiplier.eq(MIN_VALUE))
  1696. return this.isOdd() ? MIN_VALUE : ZERO;
  1697. if (this.isNegative()) {
  1698. if (multiplier.isNegative())
  1699. return this.neg().mul(multiplier.neg());
  1700. else
  1701. return this.neg().mul(multiplier).neg();
  1702. } else if (multiplier.isNegative())
  1703. return this.mul(multiplier.neg()).neg();
  1704. // If both longs are small, use float multiplication
  1705. if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
  1706. return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  1707. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  1708. // We can skip products that would overflow.
  1709. var a48 = this.high >>> 16;
  1710. var a32 = this.high & 0xFFFF;
  1711. var a16 = this.low >>> 16;
  1712. var a00 = this.low & 0xFFFF;
  1713. var b48 = multiplier.high >>> 16;
  1714. var b32 = multiplier.high & 0xFFFF;
  1715. var b16 = multiplier.low >>> 16;
  1716. var b00 = multiplier.low & 0xFFFF;
  1717. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1718. c00 += a00 * b00;
  1719. c16 += c00 >>> 16;
  1720. c00 &= 0xFFFF;
  1721. c16 += a16 * b00;
  1722. c32 += c16 >>> 16;
  1723. c16 &= 0xFFFF;
  1724. c16 += a00 * b16;
  1725. c32 += c16 >>> 16;
  1726. c16 &= 0xFFFF;
  1727. c32 += a32 * b00;
  1728. c48 += c32 >>> 16;
  1729. c32 &= 0xFFFF;
  1730. c32 += a16 * b16;
  1731. c48 += c32 >>> 16;
  1732. c32 &= 0xFFFF;
  1733. c32 += a00 * b32;
  1734. c48 += c32 >>> 16;
  1735. c32 &= 0xFFFF;
  1736. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  1737. c48 &= 0xFFFF;
  1738. return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1739. };
  1740. /**
  1741. * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
  1742. * @function
  1743. * @param {!Long|number|string} multiplier Multiplier
  1744. * @returns {!Long} Product
  1745. * @expose
  1746. */
  1747. LongPrototype.mul = LongPrototype.multiply;
  1748. /**
  1749. * Returns this Long divided by the specified.
  1750. * @param {!Long|number|string} divisor Divisor
  1751. * @returns {!Long} Quotient
  1752. * @expose
  1753. */
  1754. LongPrototype.divide = function divide(divisor) {
  1755. if (!isLong(divisor))
  1756. divisor = fromValue(divisor);
  1757. if (divisor.isZero())
  1758. throw Error('division by zero');
  1759. if (this.isZero())
  1760. return this.unsigned ? UZERO : ZERO;
  1761. var approx, rem, res;
  1762. if (this.eq(MIN_VALUE)) {
  1763. if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
  1764. return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
  1765. else if (divisor.eq(MIN_VALUE))
  1766. return ONE;
  1767. else {
  1768. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  1769. var halfThis = this.shr(1);
  1770. approx = halfThis.div(divisor).shl(1);
  1771. if (approx.eq(ZERO)) {
  1772. return divisor.isNegative() ? ONE : NEG_ONE;
  1773. } else {
  1774. rem = this.sub(divisor.mul(approx));
  1775. res = approx.add(rem.div(divisor));
  1776. return res;
  1777. }
  1778. }
  1779. } else if (divisor.eq(MIN_VALUE))
  1780. return this.unsigned ? UZERO : ZERO;
  1781. if (this.isNegative()) {
  1782. if (divisor.isNegative())
  1783. return this.neg().div(divisor.neg());
  1784. return this.neg().div(divisor).neg();
  1785. } else if (divisor.isNegative())
  1786. return this.div(divisor.neg()).neg();
  1787. // Repeat the following until the remainder is less than other: find a
  1788. // floating-point that approximates remainder / other *from below*, add this
  1789. // into the result, and subtract it from the remainder. It is critical that
  1790. // the approximate value is less than or equal to the real value so that the
  1791. // remainder never becomes negative.
  1792. res = ZERO;
  1793. rem = this;
  1794. while (rem.gte(divisor)) {
  1795. // Approximate the result of division. This may be a little greater or
  1796. // smaller than the actual value.
  1797. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  1798. // We will tweak the approximate result by changing it in the 48-th digit or
  1799. // the smallest non-fractional digit, whichever is larger.
  1800. var log2 = Math.ceil(Math.log(approx) / Math.LN2),
  1801. delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
  1802. // Decrease the approximation until it is smaller than the remainder. Note
  1803. // that if it is too large, the product overflows and is negative.
  1804. approxRes = fromNumber(approx),
  1805. approxRem = approxRes.mul(divisor);
  1806. while (approxRem.isNegative() || approxRem.gt(rem)) {
  1807. approx -= delta;
  1808. approxRes = fromNumber(approx, this.unsigned);
  1809. approxRem = approxRes.mul(divisor);
  1810. }
  1811. // We know the answer can't be zero... and actually, zero would cause
  1812. // infinite recursion since we would make no progress.
  1813. if (approxRes.isZero())
  1814. approxRes = ONE;
  1815. res = res.add(approxRes);
  1816. rem = rem.sub(approxRem);
  1817. }
  1818. return res;
  1819. };
  1820. /**
  1821. * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
  1822. * @function
  1823. * @param {!Long|number|string} divisor Divisor
  1824. * @returns {!Long} Quotient
  1825. * @expose
  1826. */
  1827. LongPrototype.div = LongPrototype.divide;
  1828. /**
  1829. * Returns this Long modulo the specified.
  1830. * @param {!Long|number|string} divisor Divisor
  1831. * @returns {!Long} Remainder
  1832. * @expose
  1833. */
  1834. LongPrototype.modulo = function modulo(divisor) {
  1835. if (!isLong(divisor))
  1836. divisor = fromValue(divisor);
  1837. return this.sub(this.div(divisor).mul(divisor));
  1838. };
  1839. /**
  1840. * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
  1841. * @function
  1842. * @param {!Long|number|string} divisor Divisor
  1843. * @returns {!Long} Remainder
  1844. * @expose
  1845. */
  1846. LongPrototype.mod = LongPrototype.modulo;
  1847. /**
  1848. * Returns the bitwise NOT of this Long.
  1849. * @returns {!Long}
  1850. * @expose
  1851. */
  1852. LongPrototype.not = function not() {
  1853. return fromBits(~this.low, ~this.high, this.unsigned);
  1854. };
  1855. /**
  1856. * Returns the bitwise AND of this Long and the specified.
  1857. * @param {!Long|number|string} other Other Long
  1858. * @returns {!Long}
  1859. * @expose
  1860. */
  1861. LongPrototype.and = function and(other) {
  1862. if (!isLong(other))
  1863. other = fromValue(other);
  1864. return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  1865. };
  1866. /**
  1867. * Returns the bitwise OR of this Long and the specified.
  1868. * @param {!Long|number|string} other Other Long
  1869. * @returns {!Long}
  1870. * @expose
  1871. */
  1872. LongPrototype.or = function or(other) {
  1873. if (!isLong(other))
  1874. other = fromValue(other);
  1875. return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  1876. };
  1877. /**
  1878. * Returns the bitwise XOR of this Long and the given one.
  1879. * @param {!Long|number|string} other Other Long
  1880. * @returns {!Long}
  1881. * @expose
  1882. */
  1883. LongPrototype.xor = function xor(other) {
  1884. if (!isLong(other))
  1885. other = fromValue(other);
  1886. return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  1887. };
  1888. /**
  1889. * Returns this Long with bits shifted to the left by the given amount.
  1890. * @param {number|!Long} numBits Number of bits
  1891. * @returns {!Long} Shifted Long
  1892. * @expose
  1893. */
  1894. LongPrototype.shiftLeft = function shiftLeft(numBits) {
  1895. if (isLong(numBits))
  1896. numBits = numBits.toInt();
  1897. if ((numBits &= 63) === 0)
  1898. return this;
  1899. else if (numBits < 32)
  1900. return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  1901. else
  1902. return fromBits(0, this.low << (numBits - 32), this.unsigned);
  1903. };
  1904. /**
  1905. * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
  1906. * @function
  1907. * @param {number|!Long} numBits Number of bits
  1908. * @returns {!Long} Shifted Long
  1909. * @expose
  1910. */
  1911. LongPrototype.shl = LongPrototype.shiftLeft;
  1912. /**
  1913. * Returns this Long with bits arithmetically shifted to the right by the given amount.
  1914. * @param {number|!Long} numBits Number of bits
  1915. * @returns {!Long} Shifted Long
  1916. * @expose
  1917. */
  1918. LongPrototype.shiftRight = function shiftRight(numBits) {
  1919. if (isLong(numBits))
  1920. numBits = numBits.toInt();
  1921. if ((numBits &= 63) === 0)
  1922. return this;
  1923. else if (numBits < 32)
  1924. return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  1925. else
  1926. return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  1927. };
  1928. /**
  1929. * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
  1930. * @function
  1931. * @param {number|!Long} numBits Number of bits
  1932. * @returns {!Long} Shifted Long
  1933. * @expose
  1934. */
  1935. LongPrototype.shr = LongPrototype.shiftRight;
  1936. /**
  1937. * Returns this Long with bits logically shifted to the right by the given amount.
  1938. * @param {number|!Long} numBits Number of bits
  1939. * @returns {!Long} Shifted Long
  1940. * @expose
  1941. */
  1942. LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
  1943. if (isLong(numBits))
  1944. numBits = numBits.toInt();
  1945. numBits &= 63;
  1946. if (numBits === 0)
  1947. return this;
  1948. else {
  1949. var high = this.high;
  1950. if (numBits < 32) {
  1951. var low = this.low;
  1952. return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  1953. } else if (numBits === 32)
  1954. return fromBits(high, 0, this.unsigned);
  1955. else
  1956. return fromBits(high >>> (numBits - 32), 0, this.unsigned);
  1957. }
  1958. };
  1959. /**
  1960. * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
  1961. * @function
  1962. * @param {number|!Long} numBits Number of bits
  1963. * @returns {!Long} Shifted Long
  1964. * @expose
  1965. */
  1966. LongPrototype.shru = LongPrototype.shiftRightUnsigned;
  1967. /**
  1968. * Converts this Long to signed.
  1969. * @returns {!Long} Signed long
  1970. * @expose
  1971. */
  1972. LongPrototype.toSigned = function toSigned() {
  1973. if (!this.unsigned)
  1974. return this;
  1975. return fromBits(this.low, this.high, false);
  1976. };
  1977. /**
  1978. * Converts this Long to unsigned.
  1979. * @returns {!Long} Unsigned long
  1980. * @expose
  1981. */
  1982. LongPrototype.toUnsigned = function toUnsigned() {
  1983. if (this.unsigned)
  1984. return this;
  1985. return fromBits(this.low, this.high, true);
  1986. };
  1987. return Long;
  1988. });
  1989. ;/*
  1990. * slip.js: A plain JavaScript SLIP implementation that works in both the browser and Node.js
  1991. *
  1992. * Copyright 2014, Colin Clark
  1993. * Licensed under the MIT and GPL 3 licenses.
  1994. */
  1995. /*global exports, define*/
  1996. (function (root, factory) {
  1997. "use strict";
  1998. if (typeof exports === "object") {
  1999. // We're in a CommonJS-style loader.
  2000. root.slip = exports;
  2001. factory(exports);
  2002. } else if (typeof define === "function" && define.amd) {
  2003. // We're in an AMD-style loader.
  2004. define(["exports"], function (exports) {
  2005. root.slip = exports;
  2006. return (root.slip, factory(exports));
  2007. });
  2008. } else {
  2009. // Plain old browser.
  2010. root.slip = {};
  2011. factory(root.slip);
  2012. }
  2013. }(this, function (exports) {
  2014. "use strict";
  2015. var slip = exports;
  2016. slip.END = 192;
  2017. slip.ESC = 219;
  2018. slip.ESC_END = 220;
  2019. slip.ESC_ESC = 221;
  2020. slip.byteArray = function (data, offset, length) {
  2021. return data instanceof ArrayBuffer ? new Uint8Array(data, offset, length) : data;
  2022. };
  2023. slip.expandByteArray = function (arr) {
  2024. var expanded = new Uint8Array(arr.length * 2);
  2025. expanded.set(arr);
  2026. return expanded;
  2027. };
  2028. slip.sliceByteArray = function (arr, start, end) {
  2029. var sliced = arr.buffer.slice ? arr.buffer.slice(start, end) : arr.subarray(start, end);
  2030. return new Uint8Array(sliced);
  2031. };
  2032. /**
  2033. * SLIP encodes a byte array.
  2034. *
  2035. * @param {Array-like} data a Uint8Array, Node.js Buffer, ArrayBuffer, or [] containing raw bytes
  2036. * @param {Object} options encoder options
  2037. * @return {Uint8Array} the encoded copy of the data
  2038. */
  2039. slip.encode = function (data, o) {
  2040. o = o || {};
  2041. o.bufferPadding = o.bufferPadding || 4; // Will be rounded to the nearest 4 bytes.
  2042. data = slip.byteArray(data, o.offset, o.byteLength);
  2043. var bufLen = (data.length + o.bufferPadding + 3) & ~0x03,
  2044. encoded = new Uint8Array(bufLen),
  2045. j = 1;
  2046. encoded[0] = slip.END;
  2047. for (var i = 0; i < data.length; i++) {
  2048. // We always need enough space for two value bytes plus a trailing END.
  2049. if (j > encoded.length - 3) {
  2050. encoded = slip.expandByteArray(encoded);
  2051. }
  2052. var val = data[i];
  2053. if (val === slip.END) {
  2054. encoded[j++] = slip.ESC;
  2055. val = slip.ESC_END;
  2056. } else if (val === slip.ESC) {
  2057. encoded[j++] = slip.ESC;
  2058. val = slip.ESC_ESC;
  2059. }
  2060. encoded[j++] = val;
  2061. }
  2062. encoded[j] = slip.END;
  2063. return slip.sliceByteArray(encoded, 0, j + 1);
  2064. };
  2065. /**
  2066. * Creates a new SLIP Decoder.
  2067. * @constructor
  2068. *
  2069. * @param {Function} onMessage a callback function that will be invoked when a message has been fully decoded
  2070. * @param {Number} maxBufferSize the maximum size of a incoming message; larger messages will throw an error
  2071. */
  2072. slip.Decoder = function (o) {
  2073. o = typeof o !== "function" ? o || {} : {
  2074. onMessage: o
  2075. };
  2076. this.maxMessageSize = o.maxMessageSize || 10485760; // Defaults to 10 MB.
  2077. this.bufferSize = o.bufferSize || 1024; // Message buffer defaults to 1 KB.
  2078. this.msgBuffer = new Uint8Array(this.bufferSize);
  2079. this.msgBufferIdx = 0;
  2080. this.onMessage = o.onMessage;
  2081. this.onError = o.onError;
  2082. this.escape = false;
  2083. };
  2084. var p = slip.Decoder.prototype;
  2085. /**
  2086. * Decodes a SLIP data packet.
  2087. * The onMessage callback will be invoked when a complete message has been decoded.
  2088. *
  2089. * @param {Array-like} data an incoming stream of bytes
  2090. */
  2091. p.decode = function (data) {
  2092. data = slip.byteArray(data);
  2093. var msg;
  2094. for (var i = 0; i < data.length; i++) {
  2095. var val = data[i];
  2096. if (this.escape) {
  2097. if (val === slip.ESC_ESC) {
  2098. val = slip.ESC;
  2099. } else if (val === slip.ESC_END) {
  2100. val = slip.END;
  2101. }
  2102. } else {
  2103. if (val === slip.ESC) {
  2104. this.escape = true;
  2105. continue;
  2106. }
  2107. if (val === slip.END) {
  2108. msg = this.handleEnd();
  2109. continue;
  2110. }
  2111. }
  2112. var more = this.addByte(val);
  2113. if (!more) {
  2114. this.handleMessageMaxError();
  2115. }
  2116. }
  2117. return msg;
  2118. };
  2119. p.handleMessageMaxError = function () {
  2120. if (this.onError) {
  2121. this.onError(this.msgBuffer.subarray(0),
  2122. "The message is too large; the maximum message size is " +
  2123. this.maxMessageSize / 1024 + "KB. Use a larger maxMessageSize if necessary.");
  2124. }
  2125. // Reset everything and carry on.
  2126. this.msgBufferIdx = 0;
  2127. this.escape = false;
  2128. };
  2129. // Unsupported, non-API method.
  2130. p.addByte = function (val) {
  2131. if (this.msgBufferIdx > this.msgBuffer.length - 1) {
  2132. this.msgBuffer = slip.expandByteArray(this.msgBuffer);
  2133. }
  2134. this.msgBuffer[this.msgBufferIdx++] = val;
  2135. this.escape = false;
  2136. return this.msgBuffer.length < this.maxMessageSize;
  2137. };
  2138. // Unsupported, non-API method.
  2139. p.handleEnd = function () {
  2140. if (this.msgBufferIdx === 0) {
  2141. return; // Toss opening END byte and carry on.
  2142. }
  2143. var msg = slip.sliceByteArray(this.msgBuffer, 0, this.msgBufferIdx);
  2144. if (this.onMessage) {
  2145. this.onMessage(msg);
  2146. }
  2147. // Clear our pointer into the message buffer.
  2148. this.msgBufferIdx = 0;
  2149. return msg;
  2150. };
  2151. return slip;
  2152. }));
  2153. ;/*!
  2154. * EventEmitter v4.2.11 - git.io/ee
  2155. * Unlicense - http://unlicense.org/
  2156. * Oliver Caldwell - http://oli.me.uk/
  2157. * @preserve
  2158. */
  2159. ;(function () {
  2160. 'use strict';
  2161. /**
  2162. * Class for managing events.
  2163. * Can be extended to provide event functionality in other classes.
  2164. *
  2165. * @class EventEmitter Manages event registering and emitting.
  2166. */
  2167. function EventEmitter() {}
  2168. // Shortcuts to improve speed and size
  2169. var proto = EventEmitter.prototype;
  2170. var exports = this;
  2171. var originalGlobalValue = exports.EventEmitter;
  2172. /**
  2173. * Finds the index of the listener for the event in its storage array.
  2174. *
  2175. * @param {Function[]} listeners Array of listeners to search through.
  2176. * @param {Function} listener Method to look for.
  2177. * @return {Number} Index of the specified listener, -1 if not found
  2178. * @api private
  2179. */
  2180. function indexOfListener(listeners, listener) {
  2181. var i = listeners.length;
  2182. while (i--) {
  2183. if (listeners[i].listener === listener) {
  2184. return i;
  2185. }
  2186. }
  2187. return -1;
  2188. }
  2189. /**
  2190. * Alias a method while keeping the context correct, to allow for overwriting of target method.
  2191. *
  2192. * @param {String} name The name of the target method.
  2193. * @return {Function} The aliased method
  2194. * @api private
  2195. */
  2196. function alias(name) {
  2197. return function aliasClosure() {
  2198. return this[name].apply(this, arguments);
  2199. };
  2200. }
  2201. /**
  2202. * Returns the listener array for the specified event.
  2203. * Will initialise the event object and listener arrays if required.
  2204. * 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.
  2205. * Each property in the object response is an array of listener functions.
  2206. *
  2207. * @param {String|RegExp} evt Name of the event to return the listeners from.
  2208. * @return {Function[]|Object} All listener functions for the event.
  2209. */
  2210. proto.getListeners = function getListeners(evt) {
  2211. var events = this._getEvents();
  2212. var response;
  2213. var key;
  2214. // Return a concatenated array of all matching events if
  2215. // the selector is a regular expression.
  2216. if (evt instanceof RegExp) {
  2217. response = {};
  2218. for (key in events) {
  2219. if (events.hasOwnProperty(key) && evt.test(key)) {
  2220. response[key] = events[key];
  2221. }
  2222. }
  2223. }
  2224. else {
  2225. response = events[evt] || (events[evt] = []);
  2226. }
  2227. return response;
  2228. };
  2229. /**
  2230. * Takes a list of listener objects and flattens it into a list of listener functions.
  2231. *
  2232. * @param {Object[]} listeners Raw listener objects.
  2233. * @return {Function[]} Just the listener functions.
  2234. */
  2235. proto.flattenListeners = function flattenListeners(listeners) {
  2236. var flatListeners = [];
  2237. var i;
  2238. for (i = 0; i < listeners.length; i += 1) {
  2239. flatListeners.push(listeners[i].listener);
  2240. }
  2241. return flatListeners;
  2242. };
  2243. /**
  2244. * 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.
  2245. *
  2246. * @param {String|RegExp} evt Name of the event to return the listeners from.
  2247. * @return {Object} All listener functions for an event in an object.
  2248. */
  2249. proto.getListenersAsObject = function getListenersAsObject(evt) {
  2250. var listeners = this.getListeners(evt);
  2251. var response;
  2252. if (listeners instanceof Array) {
  2253. response = {};
  2254. response[evt] = listeners;
  2255. }
  2256. return response || listeners;
  2257. };
  2258. /**
  2259. * Adds a listener function to the specified event.
  2260. * The listener will not be added if it is a duplicate.
  2261. * If the listener returns true then it will be removed after it is called.
  2262. * If you pass a regular expression as the event name then the listener will be added to all events that match it.
  2263. *
  2264. * @param {String|RegExp} evt Name of the event to attach the listener to.
  2265. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
  2266. * @return {Object} Current instance of EventEmitter for chaining.
  2267. */
  2268. proto.addListener = function addListener(evt, listener) {
  2269. var listeners = this.getListenersAsObject(evt);
  2270. var listenerIsWrapped = typeof listener === 'object';
  2271. var key;
  2272. for (key in listeners) {
  2273. if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
  2274. listeners[key].push(listenerIsWrapped ? listener : {
  2275. listener: listener,
  2276. once: false
  2277. });
  2278. }
  2279. }
  2280. return this;
  2281. };
  2282. /**
  2283. * Alias of addListener
  2284. */
  2285. proto.on = alias('addListener');
  2286. /**
  2287. * Semi-alias of addListener. It will add a listener that will be
  2288. * automatically removed after its first execution.
  2289. *
  2290. * @param {String|RegExp} evt Name of the event to attach the listener to.
  2291. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
  2292. * @return {Object} Current instance of EventEmitter for chaining.
  2293. */
  2294. proto.addOnceListener = function addOnceListener(evt, listener) {
  2295. return this.addListener(evt, {
  2296. listener: listener,
  2297. once: true
  2298. });
  2299. };
  2300. /**
  2301. * Alias of addOnceListener.
  2302. */
  2303. proto.once = alias('addOnceListener');
  2304. /**
  2305. * 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.
  2306. * You need to tell it what event names should be matched by a regex.
  2307. *
  2308. * @param {String} evt Name of the event to create.
  2309. * @return {Object} Current instance of EventEmitter for chaining.
  2310. */
  2311. proto.defineEvent = function defineEvent(evt) {
  2312. this.getListeners(evt);
  2313. return this;
  2314. };
  2315. /**
  2316. * Uses defineEvent to define multiple events.
  2317. *
  2318. * @param {String[]} evts An array of event names to define.
  2319. * @return {Object} Current instance of EventEmitter for chaining.
  2320. */
  2321. proto.defineEvents = function defineEvents(evts) {
  2322. for (var i = 0; i < evts.length; i += 1) {
  2323. this.defineEvent(evts[i]);
  2324. }
  2325. return this;
  2326. };
  2327. /**
  2328. * Removes a listener function from the specified event.
  2329. * When passed a regular expression as the event name, it will remove the listener from all events that match it.
  2330. *
  2331. * @param {String|RegExp} evt Name of the event to remove the listener from.
  2332. * @param {Function} listener Method to remove from the event.
  2333. * @return {Object} Current instance of EventEmitter for chaining.
  2334. */
  2335. proto.removeListener = function removeListener(evt, listener) {
  2336. var listeners = this.getListenersAsObject(evt);
  2337. var index;
  2338. var key;
  2339. for (key in listeners) {
  2340. if (listeners.hasOwnProperty(key)) {
  2341. index = indexOfListener(listeners[key], listener);
  2342. if (index !== -1) {
  2343. listeners[key].splice(index, 1);
  2344. }
  2345. }
  2346. }
  2347. return this;
  2348. };
  2349. /**
  2350. * Alias of removeListener
  2351. */
  2352. proto.off = alias('removeListener');
  2353. /**
  2354. * Adds listeners in bulk using the manipulateListeners method.
  2355. * If you pass an object as the second 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.
  2356. * You can also pass it a regular expression to add the array of listeners to all events that match it.
  2357. * Yeah, this function does quite a bit. That's probably a bad thing.
  2358. *
  2359. * @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.
  2360. * @param {Function[]} [listeners] An optional array of listener functions to add.
  2361. * @return {Object} Current instance of EventEmitter for chaining.
  2362. */
  2363. proto.addListeners = function addListeners(evt, listeners) {
  2364. // Pass through to manipulateListeners
  2365. return this.manipulateListeners(false, evt, listeners);
  2366. };
  2367. /**
  2368. * Removes listeners in bulk using the manipulateListeners method.
  2369. * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
  2370. * You can also pass it an event name and an array of listeners to be removed.
  2371. * You can also pass it a regular expression to remove the listeners from all events that match it.
  2372. *
  2373. * @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.
  2374. * @param {Function[]} [listeners] An optional array of listener functions to remove.
  2375. * @return {Object} Current instance of EventEmitter for chaining.
  2376. */
  2377. proto.removeListeners = function removeListeners(evt, listeners) {
  2378. // Pass through to manipulateListeners
  2379. return this.manipulateListeners(true, evt, listeners);
  2380. };
  2381. /**
  2382. * 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.
  2383. * The first argument will determine if the listeners are removed (true) or added (false).
  2384. * 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.
  2385. * You can also pass it an event name and an array of listeners to be added/removed.
  2386. * You can also pass it a regular expression to manipulate the listeners of all events that match it.
  2387. *
  2388. * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
  2389. * @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.
  2390. * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
  2391. * @return {Object} Current instance of EventEmitter for chaining.
  2392. */
  2393. proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
  2394. var i;
  2395. var value;
  2396. var single = remove ? this.removeListener : this.addListener;
  2397. var multiple = remove ? this.removeListeners : this.addListeners;
  2398. // If evt is an object then pass each of its properties to this method
  2399. if (typeof evt === 'object' && !(evt instanceof RegExp)) {
  2400. for (i in evt) {
  2401. if (evt.hasOwnProperty(i) && (value = evt[i])) {
  2402. // Pass the single listener straight through to the singular method
  2403. if (typeof value === 'function') {
  2404. single.call(this, i, value);
  2405. }
  2406. else {
  2407. // Otherwise pass back to the multiple function
  2408. multiple.call(this, i, value);
  2409. }
  2410. }
  2411. }
  2412. }
  2413. else {
  2414. // So evt must be a string
  2415. // And listeners must be an array of listeners
  2416. // Loop over it and pass each one to the multiple method
  2417. i = listeners.length;
  2418. while (i--) {
  2419. single.call(this, evt, listeners[i]);
  2420. }
  2421. }
  2422. return this;
  2423. };
  2424. /**
  2425. * Removes all listeners from a specified event.
  2426. * If you do not specify an event then all listeners will be removed.
  2427. * That means every event will be emptied.
  2428. * You can also pass a regex to remove all events that match it.
  2429. *
  2430. * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
  2431. * @return {Object} Current instance of EventEmitter for chaining.
  2432. */
  2433. proto.removeEvent = function removeEvent(evt) {
  2434. var type = typeof evt;
  2435. var events = this._getEvents();
  2436. var key;
  2437. // Remove different things depending on the state of evt
  2438. if (type === 'string') {
  2439. // Remove all listeners for the specified event
  2440. delete events[evt];
  2441. }
  2442. else if (evt instanceof RegExp) {
  2443. // Remove all events matching the regex.
  2444. for (key in events) {
  2445. if (events.hasOwnProperty(key) && evt.test(key)) {
  2446. delete events[key];
  2447. }
  2448. }
  2449. }
  2450. else {
  2451. // Remove all listeners in all events
  2452. delete this._events;
  2453. }
  2454. return this;
  2455. };
  2456. /**
  2457. * Alias of removeEvent.
  2458. *
  2459. * Added to mirror the node API.
  2460. */
  2461. proto.removeAllListeners = alias('removeEvent');
  2462. /**
  2463. * Emits an event of your choice.
  2464. * When emitted, every listener attached to that event will be executed.
  2465. * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
  2466. * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
  2467. * So they will not arrive within the array on the other side, they will be separate.
  2468. * You can also pass a regular expression to emit to all events that match it.
  2469. *
  2470. * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
  2471. * @param {Array} [args] Optional array of arguments to be passed to each listener.
  2472. * @return {Object} Current instance of EventEmitter for chaining.
  2473. */
  2474. proto.emitEvent = function emitEvent(evt, args) {
  2475. var listenersMap = this.getListenersAsObject(evt);
  2476. var listeners;
  2477. var listener;
  2478. var i;
  2479. var key;
  2480. var response;
  2481. for (key in listenersMap) {
  2482. if (listenersMap.hasOwnProperty(key)) {
  2483. listeners = listenersMap[key].slice(0);
  2484. i = listeners.length;
  2485. while (i--) {
  2486. // If the listener returns true then it shall be removed from the event
  2487. // The function is executed either with a basic call or an apply if there is an args array
  2488. listener = listeners[i];
  2489. if (listener.once === true) {
  2490. this.removeListener(evt, listener.listener);
  2491. }
  2492. response = listener.listener.apply(this, args || []);
  2493. if (response === this._getOnceReturnValue()) {
  2494. this.removeListener(evt, listener.listener);
  2495. }
  2496. }
  2497. }
  2498. }
  2499. return this;
  2500. };
  2501. /**
  2502. * Alias of emitEvent
  2503. */
  2504. proto.trigger = alias('emitEvent');
  2505. /**
  2506. * 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.
  2507. * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
  2508. *
  2509. * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
  2510. * @param {...*} Optional additional arguments to be passed to each listener.
  2511. * @return {Object} Current instance of EventEmitter for chaining.
  2512. */
  2513. proto.emit = function emit(evt) {
  2514. var args = Array.prototype.slice.call(arguments, 1);
  2515. return this.emitEvent(evt, args);
  2516. };
  2517. /**
  2518. * Sets the current value to check against when executing listeners. If a
  2519. * listeners return value matches the one set here then it will be removed
  2520. * after execution. This value defaults to true.
  2521. *
  2522. * @param {*} value The new value to check for when executing listeners.
  2523. * @return {Object} Current instance of EventEmitter for chaining.
  2524. */
  2525. proto.setOnceReturnValue = function setOnceReturnValue(value) {
  2526. this._onceReturnValue = value;
  2527. return this;
  2528. };
  2529. /**
  2530. * Fetches the current value to check against when executing listeners. If
  2531. * the listeners return value matches this one then it should be removed
  2532. * automatically. It will return true by default.
  2533. *
  2534. * @return {*|Boolean} The current value to check for or the default, true.
  2535. * @api private
  2536. */
  2537. proto._getOnceReturnValue = function _getOnceReturnValue() {
  2538. if (this.hasOwnProperty('_onceReturnValue')) {
  2539. return this._onceReturnValue;
  2540. }
  2541. else {
  2542. return true;
  2543. }
  2544. };
  2545. /**
  2546. * Fetches the events object and creates one if required.
  2547. *
  2548. * @return {Object} The events storage object.
  2549. * @api private
  2550. */
  2551. proto._getEvents = function _getEvents() {
  2552. return this._events || (this._events = {});
  2553. };
  2554. /**
  2555. * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
  2556. *
  2557. * @return {Function} Non conflicting EventEmitter class.
  2558. */
  2559. EventEmitter.noConflict = function noConflict() {
  2560. exports.EventEmitter = originalGlobalValue;
  2561. return EventEmitter;
  2562. };
  2563. // Expose the class either via AMD, CommonJS or the global object
  2564. if (typeof define === 'function' && define.amd) {
  2565. define(function () {
  2566. return EventEmitter;
  2567. });
  2568. }
  2569. else if (typeof module === 'object' && module.exports){
  2570. module.exports = EventEmitter;
  2571. }
  2572. else {
  2573. exports.EventEmitter = EventEmitter;
  2574. }
  2575. }.call(this));
  2576. ;/*
  2577. * osc.js: An Open Sound Control library for JavaScript that works in both the browser and Node.js
  2578. *
  2579. * Cross-platform base transport library for osc.js.
  2580. *
  2581. * Copyright 2014-2015, Colin Clark
  2582. * Licensed under the MIT and GPL 3 licenses.
  2583. */
  2584. /* global require, module */
  2585. var osc = osc || require("./osc.js"),
  2586. slip = slip || require("slip"),
  2587. EventEmitter = EventEmitter || require("events").EventEmitter;
  2588. (function () {
  2589. "use strict";
  2590. // Unsupported, non-API function.
  2591. osc.firePacketEvents = function (port, packet, timeTag, packetInfo) {
  2592. if (packet.address) {
  2593. port.emit("message", packet, timeTag, packetInfo);
  2594. } else {
  2595. osc.fireBundleEvents(port, packet, timeTag, packetInfo);
  2596. }
  2597. };
  2598. // Unsupported, non-API function.
  2599. osc.fireBundleEvents = function (port, bundle, timeTag, packetInfo) {
  2600. port.emit("bundle", bundle, timeTag, packetInfo);
  2601. for (var i = 0; i < bundle.packets.length; i++) {
  2602. var packet = bundle.packets[i];
  2603. osc.firePacketEvents(port, packet, bundle.timeTag, packetInfo);
  2604. }
  2605. };
  2606. osc.Port = function (options) {
  2607. this.options = options || {};
  2608. this.on("data", this.decodeOSC.bind(this));
  2609. };
  2610. var p = osc.Port.prototype = Object.create(EventEmitter.prototype);
  2611. p.constructor = osc.Port;
  2612. p.send = function (oscPacket) {
  2613. var args = Array.prototype.slice.call(arguments),
  2614. encoded = this.encodeOSC(oscPacket),
  2615. buf = osc.nativeBuffer(encoded);
  2616. args[0] = buf;
  2617. this.sendRaw.apply(this, args);
  2618. };
  2619. p.encodeOSC = function (packet) {
  2620. // TODO gh-39: This is unsafe; we should only access the underlying
  2621. // buffer within the range of its view.
  2622. packet = packet.buffer ? packet.buffer : packet;
  2623. var encoded;
  2624. try {
  2625. encoded = osc.writePacket(packet, this.options);
  2626. } catch (err) {
  2627. this.emit("error", err);
  2628. }
  2629. return encoded;
  2630. };
  2631. p.decodeOSC = function (data, packetInfo) {
  2632. data = osc.byteArray(data);
  2633. this.emit("raw", data, packetInfo);
  2634. try {
  2635. var packet = osc.readPacket(data, this.options);
  2636. this.emit("osc", packet, packetInfo);
  2637. osc.firePacketEvents(this, packet, undefined, packetInfo);
  2638. } catch (err) {
  2639. this.emit("error", err);
  2640. }
  2641. };
  2642. osc.SLIPPort = function (options) {
  2643. var that = this;
  2644. var o = this.options = options || {};
  2645. o.useSLIP = o.useSLIP === undefined ? true : o.useSLIP;
  2646. this.decoder = new slip.Decoder({
  2647. onMessage: this.decodeOSC.bind(this),
  2648. onError: function (err) {
  2649. that.emit("error", err);
  2650. }
  2651. });
  2652. var decodeHandler = o.useSLIP ? this.decodeSLIPData : this.decodeOSC;
  2653. this.on("data", decodeHandler.bind(this));
  2654. };
  2655. p = osc.SLIPPort.prototype = Object.create(osc.Port.prototype);
  2656. p.constructor = osc.SLIPPort;
  2657. p.encodeOSC = function (packet) {
  2658. // TODO gh-39: This is unsafe; we should only access the underlying
  2659. // buffer within the range of its view.
  2660. packet = packet.buffer ? packet.buffer : packet;
  2661. var framed;
  2662. try {
  2663. var encoded = osc.writePacket(packet, this.options);
  2664. framed = slip.encode(encoded);
  2665. } catch (err) {
  2666. this.emit("error", err);
  2667. }
  2668. return framed;
  2669. };
  2670. p.decodeSLIPData = function (data, packetInfo) {
  2671. // TODO: Get packetInfo through SLIP decoder.
  2672. this.decoder.decode(data, packetInfo);
  2673. };
  2674. // Unsupported, non-API function.
  2675. osc.relay = function (from, to, eventName, sendFnName, transformFn, sendArgs) {
  2676. eventName = eventName || "message";
  2677. sendFnName = sendFnName || "send";
  2678. transformFn = transformFn || function () {};
  2679. sendArgs = sendArgs ? [null].concat(sendArgs) : [];
  2680. var listener = function (data) {
  2681. sendArgs[0] = data;
  2682. data = transformFn(data);
  2683. to[sendFnName].apply(to, sendArgs);
  2684. };
  2685. from.on(eventName, listener);
  2686. return {
  2687. eventName: eventName,
  2688. listener: listener
  2689. };
  2690. };
  2691. // Unsupported, non-API function.
  2692. osc.relayPorts = function (from, to, o) {
  2693. var eventName = o.raw ? "raw" : "osc",
  2694. sendFnName = o.raw ? "sendRaw" : "send";
  2695. return osc.relay(from, to, eventName, sendFnName, o.transform);
  2696. };
  2697. // Unsupported, non-API function.
  2698. osc.stopRelaying = function (from, relaySpec) {
  2699. from.removeListener(relaySpec.eventName, relaySpec.listener);
  2700. };
  2701. /**
  2702. * A Relay connects two sources of OSC data together,
  2703. * relaying all OSC messages received by each port to the other.
  2704. * @constructor
  2705. *
  2706. * @param {osc.Port} port1 the first port to relay
  2707. * @param {osc.Port} port2 the second port to relay
  2708. * @param {Object} options the configuration options for this relay
  2709. */
  2710. osc.Relay = function (port1, port2, options) {
  2711. var o = this.options = options || {};
  2712. o.raw = false;
  2713. this.port1 = port1;
  2714. this.port2 = port2;
  2715. this.listen();
  2716. };
  2717. p = osc.Relay.prototype = Object.create(EventEmitter.prototype);
  2718. p.constructor = osc.Relay;
  2719. p.open = function () {
  2720. this.port1.open();
  2721. this.port2.open();
  2722. };
  2723. p.listen = function () {
  2724. if (this.port1Spec && this.port2Spec) {
  2725. this.close();
  2726. }
  2727. this.port1Spec = osc.relayPorts(this.port1, this.port2, this.options);
  2728. this.port2Spec = osc.relayPorts(this.port2, this.port1, this.options);
  2729. // Bind port close listeners to ensure that the relay
  2730. // will stop forwarding messages if one of its ports close.
  2731. // Users are still responsible for closing the underlying ports
  2732. // if necessary.
  2733. var closeListener = this.close.bind(this);
  2734. this.port1.on("close", closeListener);
  2735. this.port2.on("close", closeListener);
  2736. };
  2737. p.close = function () {
  2738. osc.stopRelaying(this.port1, this.port1Spec);
  2739. osc.stopRelaying(this.port2, this.port2Spec);
  2740. this.emit("close", this.port1, this.port2);
  2741. };
  2742. // If we're in a require-compatible environment, export ourselves.
  2743. if (typeof module !== "undefined" && module.exports) {
  2744. module.exports = osc;
  2745. }
  2746. }());
  2747. ;/*
  2748. * osc.js: An Open Sound Control library for JavaScript that works in both the browser and Node.js
  2749. *
  2750. * Browser transports for osc.js
  2751. *
  2752. * Copyright 2014-2015, Colin Clark
  2753. * Licensed under the MIT and GPL 3 licenses.
  2754. */
  2755. /*global WebSocket*/
  2756. var osc = osc;
  2757. (function () {
  2758. "use strict";
  2759. osc.WebSocketPort = function (options) {
  2760. osc.Port.call(this, options);
  2761. this.on("open", this.listen.bind(this));
  2762. this.socket = options.socket;
  2763. if (this.socket) {
  2764. if (this.socket.readyState === 1) {
  2765. this.emit("open", this.socket);
  2766. } else {
  2767. this.open();
  2768. }
  2769. }
  2770. };
  2771. var p = osc.WebSocketPort.prototype = Object.create(osc.Port.prototype);
  2772. p.constructor = osc.WebSocketPort;
  2773. p.open = function () {
  2774. if (!this.socket) {
  2775. this.socket = new WebSocket(this.options.url);
  2776. }
  2777. this.socket.binaryType = "arraybuffer";
  2778. var that = this;
  2779. this.socket.onopen = function () {
  2780. that.emit("open", that.socket);
  2781. };
  2782. };
  2783. p.listen = function () {
  2784. var that = this;
  2785. this.socket.onmessage = function (e) {
  2786. that.emit("data", e.data, e);
  2787. };
  2788. this.socket.onerror = function (err) {
  2789. that.emit("error", err);
  2790. };
  2791. this.socket.onclose = function (e) {
  2792. that.emit("close", e);
  2793. };
  2794. that.emit("ready");
  2795. };
  2796. p.sendRaw = function (encoded) {
  2797. if (!this.socket) {
  2798. return;
  2799. }
  2800. this.socket.send(encoded);
  2801. };
  2802. p.close = function (code, reason) {
  2803. this.socket.close(code, reason);
  2804. };
  2805. }());
  2806. ;/*
  2807. * osc.js: An Open Sound Control library for JavaScript that works in both the browser and Node.js
  2808. *
  2809. * Chrome App transports for osc.js
  2810. *
  2811. * Copyright 2014-2015, Colin Clark
  2812. * Licensed under the MIT and GPL 3 licenses.
  2813. */
  2814. /*global chrome*/
  2815. var osc = osc || {};
  2816. (function () {
  2817. "use strict";
  2818. osc.listenToTransport = function (that, transport, idName) {
  2819. transport.onReceive.addListener(function (e) {
  2820. if (e[idName] === that[idName]) {
  2821. that.emit("data", e.data, e);
  2822. }
  2823. });
  2824. transport.onReceiveError.addListener(function (err) {
  2825. that.emit("error", err);
  2826. });
  2827. that.emit("ready");
  2828. };
  2829. osc.emitNetworkError = function (that, resultCode) {
  2830. that.emit("error",
  2831. "There was an error while opening the UDP socket connection. Result code: " +
  2832. resultCode);
  2833. };
  2834. osc.SerialPort = function (options) {
  2835. this.on("open", this.listen.bind(this));
  2836. osc.SLIPPort.call(this, options);
  2837. this.connectionId = this.options.connectionId;
  2838. if (this.connectionId) {
  2839. this.emit("open", this.connectionId);
  2840. }
  2841. };
  2842. var p = osc.SerialPort.prototype = Object.create(osc.SLIPPort.prototype);
  2843. p.constructor = osc.SerialPort;
  2844. p.open = function () {
  2845. var that = this,
  2846. connectionOpts = {
  2847. bitrate: that.options.bitrate
  2848. };
  2849. chrome.serial.connect(this.options.devicePath, connectionOpts, function (info) {
  2850. that.connectionId = info.connectionId;
  2851. that.emit("open", info);
  2852. });
  2853. };
  2854. p.listen = function () {
  2855. osc.listenToTransport(this, chrome.serial, "connectionId");
  2856. };
  2857. p.sendRaw = function (encoded) {
  2858. if (!this.connectionId) {
  2859. return;
  2860. }
  2861. var that = this;
  2862. // TODO gh-39: This is unsafe; we should only access the underlying
  2863. // buffer within the range of its view.
  2864. chrome.serial.send(this.connectionId, encoded.buffer, function (bytesSent, err) {
  2865. if (err) {
  2866. that.emit("error", err + ". Total bytes sent: " + bytesSent);
  2867. }
  2868. });
  2869. };
  2870. p.close = function () {
  2871. if (this.connectionId) {
  2872. var that = this;
  2873. chrome.serial.disconnect(this.connectionId, function (result) {
  2874. if (result) {
  2875. that.emit("close");
  2876. }
  2877. });
  2878. }
  2879. };
  2880. osc.UDPPort = function (options) {
  2881. osc.Port.call(this, options);
  2882. var o = this.options;
  2883. o.localAddress = o.localAddress || "127.0.0.1";
  2884. o.localPort = o.localPort !== undefined ? o.localPort : 57121;
  2885. this.on("open", this.listen.bind(this));
  2886. this.socketId = o.socketId;
  2887. if (this.socketId) {
  2888. this.emit("open", 0);
  2889. }
  2890. };
  2891. p = osc.UDPPort.prototype = Object.create(osc.Port.prototype);
  2892. p.constructor = osc.UDPPort;
  2893. p.open = function () {
  2894. if (this.socketId) {
  2895. return;
  2896. }
  2897. var o = this.options,
  2898. props = {
  2899. persistent: o.persistent,
  2900. name: o.name,
  2901. bufferSize: o.bufferSize
  2902. },
  2903. that = this;
  2904. chrome.sockets.udp.create(props, function (info) {
  2905. that.socketId = info.socketId;
  2906. that.bindSocket();
  2907. });
  2908. };
  2909. p.bindSocket = function () {
  2910. var that = this,
  2911. o = this.options;
  2912. if (o.broadcast !== undefined) {
  2913. chrome.sockets.udp.setBroadcast(this.socketId, o.broadcast, function (resultCode) {
  2914. if (resultCode < 0) {
  2915. that.emit("error",
  2916. new Error("An error occurred while setting the socket's broadcast flag. Result code: " +
  2917. resultCode));
  2918. }
  2919. });
  2920. }
  2921. if (o.multicastTTL !== undefined) {
  2922. chrome.sockets.udp.setMulticastTimeToLive(this.socketId, o.multicastTTL, function (resultCode) {
  2923. if (resultCode < 0) {
  2924. that.emit("error",
  2925. new Error("An error occurred while setting the socket's multicast time to live flag. " +
  2926. "Result code: " + resultCode));
  2927. }
  2928. });
  2929. }
  2930. chrome.sockets.udp.bind(this.socketId, o.localAddress, o.localPort, function (resultCode) {
  2931. if (resultCode > 0) {
  2932. osc.emitNetworkError(that, resultCode);
  2933. return;
  2934. }
  2935. that.emit("open", resultCode);
  2936. });
  2937. };
  2938. p.listen = function () {
  2939. var o = this.options;
  2940. osc.listenToTransport(this, chrome.sockets.udp, "socketId");
  2941. if (o.multicastMembership) {
  2942. if (typeof o.multicastMembership === "string") {
  2943. o.multicastMembership = [o.multicastMembership];
  2944. }
  2945. o.multicastMembership.forEach(function (addr) {
  2946. chrome.sockets.udp.joinGroup(this.socketId, addr, function (resultCode) {
  2947. if (resultCode < 0) {
  2948. this.emit("error", new Error(
  2949. "There was an error while trying to join the multicast group " +
  2950. addr + ". Result code: " + resultCode));
  2951. }
  2952. });
  2953. });
  2954. }
  2955. };
  2956. p.sendRaw = function (encoded, address, port) {
  2957. if (!this.socketId) {
  2958. return;
  2959. }
  2960. var o = this.options,
  2961. that = this;
  2962. address = address || o.remoteAddress;
  2963. port = port !== undefined ? port : o.remotePort;
  2964. // TODO gh-39: This is unsafe; we should only access the underlying
  2965. // buffer within the range of its view.
  2966. chrome.sockets.udp.send(this.socketId, encoded.buffer, address, port, function (info) {
  2967. if (!info) {
  2968. that.emit("error",
  2969. "There was an unknown error while trying to send a UDP message. " +
  2970. "Have you declared the appropriate udp send permissions " +
  2971. "in your application's manifest file?");
  2972. }
  2973. if (info.resultCode > 0) {
  2974. osc.emitNetworkError(that, info.resultCode);
  2975. }
  2976. });
  2977. };
  2978. p.close = function () {
  2979. if (this.socketId) {
  2980. var that = this;
  2981. chrome.sockets.udp.close(this.socketId, function () {
  2982. that.emit("close");
  2983. });
  2984. }
  2985. };
  2986. }());