peer.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  1. /*! peerjs.js build:0.1.0, development. Copyright(c) 2013 Michelle Bu <michelle@michellebu.com> */
  2. (function(exports){
  3. var binaryFeatures = {};
  4. binaryFeatures.useBlobBuilder = (function(){
  5. try {
  6. new Blob([]);
  7. return false;
  8. } catch (e) {
  9. return true;
  10. }
  11. })();
  12. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  13. try {
  14. return (new Blob([new Uint8Array([])])).size === 0;
  15. } catch (e) {
  16. return true;
  17. }
  18. })();
  19. exports.binaryFeatures = binaryFeatures;
  20. exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  21. function BufferBuilder(){
  22. this._pieces = [];
  23. this._parts = [];
  24. }
  25. BufferBuilder.prototype.append = function(data) {
  26. if(typeof data === 'number') {
  27. this._pieces.push(data);
  28. } else {
  29. this._flush();
  30. this._parts.push(data);
  31. }
  32. };
  33. BufferBuilder.prototype._flush = function() {
  34. if (this._pieces.length > 0) {
  35. var buf = new Uint8Array(this._pieces);
  36. if(!binaryFeatures.useArrayBufferView) {
  37. buf = buf.buffer;
  38. }
  39. this._parts.push(buf);
  40. this._pieces = [];
  41. }
  42. };
  43. BufferBuilder.prototype.getBuffer = function() {
  44. this._flush();
  45. if(binaryFeatures.useBlobBuilder) {
  46. var builder = new BlobBuilder();
  47. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  48. builder.append(this._parts[i]);
  49. }
  50. return builder.getBlob();
  51. } else {
  52. return new Blob(this._parts);
  53. }
  54. };
  55. exports.BinaryPack = {
  56. unpack: function(data){
  57. var unpacker = new Unpacker(data);
  58. return unpacker.unpack();
  59. },
  60. pack: function(data, utf8){
  61. var packer = new Packer(utf8);
  62. var buffer = packer.pack(data);
  63. return buffer;
  64. }
  65. };
  66. function Unpacker (data){
  67. // Data is ArrayBuffer
  68. this.index = 0;
  69. this.dataBuffer = data;
  70. this.dataView = new Uint8Array(this.dataBuffer);
  71. this.length = this.dataBuffer.byteLength;
  72. }
  73. Unpacker.prototype.unpack = function(){
  74. var type = this.unpack_uint8();
  75. if (type < 0x80){
  76. var positive_fixnum = type;
  77. return positive_fixnum;
  78. } else if ((type ^ 0xe0) < 0x20){
  79. var negative_fixnum = (type ^ 0xe0) - 0x20;
  80. return negative_fixnum;
  81. }
  82. var size;
  83. if ((size = type ^ 0xa0) <= 0x0f){
  84. return this.unpack_raw(size);
  85. } else if ((size = type ^ 0xb0) <= 0x0f){
  86. return this.unpack_string(size);
  87. } else if ((size = type ^ 0x90) <= 0x0f){
  88. return this.unpack_array(size);
  89. } else if ((size = type ^ 0x80) <= 0x0f){
  90. return this.unpack_map(size);
  91. }
  92. switch(type){
  93. case 0xc0:
  94. return null;
  95. case 0xc1:
  96. return undefined;
  97. case 0xc2:
  98. return false;
  99. case 0xc3:
  100. return true;
  101. case 0xca:
  102. return this.unpack_float();
  103. case 0xcb:
  104. return this.unpack_double();
  105. case 0xcc:
  106. return this.unpack_uint8();
  107. case 0xcd:
  108. return this.unpack_uint16();
  109. case 0xce:
  110. return this.unpack_uint32();
  111. case 0xcf:
  112. return this.unpack_uint64();
  113. case 0xd0:
  114. return this.unpack_int8();
  115. case 0xd1:
  116. return this.unpack_int16();
  117. case 0xd2:
  118. return this.unpack_int32();
  119. case 0xd3:
  120. return this.unpack_int64();
  121. case 0xd4:
  122. return undefined;
  123. case 0xd5:
  124. return undefined;
  125. case 0xd6:
  126. return undefined;
  127. case 0xd7:
  128. return undefined;
  129. case 0xd8:
  130. size = this.unpack_uint16();
  131. return this.unpack_string(size);
  132. case 0xd9:
  133. size = this.unpack_uint32();
  134. return this.unpack_string(size);
  135. case 0xda:
  136. size = this.unpack_uint16();
  137. return this.unpack_raw(size);
  138. case 0xdb:
  139. size = this.unpack_uint32();
  140. return this.unpack_raw(size);
  141. case 0xdc:
  142. size = this.unpack_uint16();
  143. return this.unpack_array(size);
  144. case 0xdd:
  145. size = this.unpack_uint32();
  146. return this.unpack_array(size);
  147. case 0xde:
  148. size = this.unpack_uint16();
  149. return this.unpack_map(size);
  150. case 0xdf:
  151. size = this.unpack_uint32();
  152. return this.unpack_map(size);
  153. }
  154. }
  155. Unpacker.prototype.unpack_uint8 = function(){
  156. var byte = this.dataView[this.index] & 0xff;
  157. this.index++;
  158. return byte;
  159. };
  160. Unpacker.prototype.unpack_uint16 = function(){
  161. var bytes = this.read(2);
  162. var uint16 =
  163. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  164. this.index += 2;
  165. return uint16;
  166. }
  167. Unpacker.prototype.unpack_uint32 = function(){
  168. var bytes = this.read(4);
  169. var uint32 =
  170. ((bytes[0] * 256 +
  171. bytes[1]) * 256 +
  172. bytes[2]) * 256 +
  173. bytes[3];
  174. this.index += 4;
  175. return uint32;
  176. }
  177. Unpacker.prototype.unpack_uint64 = function(){
  178. var bytes = this.read(8);
  179. var uint64 =
  180. ((((((bytes[0] * 256 +
  181. bytes[1]) * 256 +
  182. bytes[2]) * 256 +
  183. bytes[3]) * 256 +
  184. bytes[4]) * 256 +
  185. bytes[5]) * 256 +
  186. bytes[6]) * 256 +
  187. bytes[7];
  188. this.index += 8;
  189. return uint64;
  190. }
  191. Unpacker.prototype.unpack_int8 = function(){
  192. var uint8 = this.unpack_uint8();
  193. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  194. };
  195. Unpacker.prototype.unpack_int16 = function(){
  196. var uint16 = this.unpack_uint16();
  197. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  198. }
  199. Unpacker.prototype.unpack_int32 = function(){
  200. var uint32 = this.unpack_uint32();
  201. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  202. uint32 - Math.pow(2, 32);
  203. }
  204. Unpacker.prototype.unpack_int64 = function(){
  205. var uint64 = this.unpack_uint64();
  206. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  207. uint64 - Math.pow(2, 64);
  208. }
  209. Unpacker.prototype.unpack_raw = function(size){
  210. if ( this.length < this.index + size){
  211. throw new Error('BinaryPackFailure: index is out of range'
  212. + ' ' + this.index + ' ' + size + ' ' + this.length);
  213. }
  214. var buf = this.dataBuffer.slice(this.index, this.index + size);
  215. this.index += size;
  216. //buf = util.bufferToString(buf);
  217. return buf;
  218. }
  219. Unpacker.prototype.unpack_string = function(size){
  220. var bytes = this.read(size);
  221. var i = 0, str = '', c, code;
  222. while(i < size){
  223. c = bytes[i];
  224. if ( c < 128){
  225. str += String.fromCharCode(c);
  226. i++;
  227. } else if ((c ^ 0xc0) < 32){
  228. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  229. str += String.fromCharCode(code);
  230. i += 2;
  231. } else {
  232. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  233. (bytes[i+2] & 63);
  234. str += String.fromCharCode(code);
  235. i += 3;
  236. }
  237. }
  238. this.index += size;
  239. return str;
  240. }
  241. Unpacker.prototype.unpack_array = function(size){
  242. var objects = new Array(size);
  243. for(var i = 0; i < size ; i++){
  244. objects[i] = this.unpack();
  245. }
  246. return objects;
  247. }
  248. Unpacker.prototype.unpack_map = function(size){
  249. var map = {};
  250. for(var i = 0; i < size ; i++){
  251. var key = this.unpack();
  252. var value = this.unpack();
  253. map[key] = value;
  254. }
  255. return map;
  256. }
  257. Unpacker.prototype.unpack_float = function(){
  258. var uint32 = this.unpack_uint32();
  259. var sign = uint32 >> 31;
  260. var exp = ((uint32 >> 23) & 0xff) - 127;
  261. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  262. return (sign == 0 ? 1 : -1) *
  263. fraction * Math.pow(2, exp - 23);
  264. }
  265. Unpacker.prototype.unpack_double = function(){
  266. var h32 = this.unpack_uint32();
  267. var l32 = this.unpack_uint32();
  268. var sign = h32 >> 31;
  269. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  270. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  271. var frac = hfrac * Math.pow(2, exp - 20) +
  272. l32 * Math.pow(2, exp - 52);
  273. return (sign == 0 ? 1 : -1) * frac;
  274. }
  275. Unpacker.prototype.read = function(length){
  276. var j = this.index;
  277. if (j + length <= this.length) {
  278. return this.dataView.subarray(j, j + length);
  279. } else {
  280. throw new Error('BinaryPackFailure: read index out of range');
  281. }
  282. }
  283. function Packer(utf8){
  284. this.utf8 = utf8;
  285. this.bufferBuilder = new BufferBuilder();
  286. }
  287. Packer.prototype.pack = function(value){
  288. var type = typeof(value);
  289. if (type == 'string'){
  290. this.pack_string(value);
  291. } else if (type == 'number'){
  292. if (Math.floor(value) === value){
  293. this.pack_integer(value);
  294. } else{
  295. this.pack_double(value);
  296. }
  297. } else if (type == 'boolean'){
  298. if (value === true){
  299. this.bufferBuilder.append(0xc3);
  300. } else if (value === false){
  301. this.bufferBuilder.append(0xc2);
  302. }
  303. } else if (type == 'undefined'){
  304. this.bufferBuilder.append(0xc0);
  305. } else if (type == 'object'){
  306. if (value === null){
  307. this.bufferBuilder.append(0xc0);
  308. } else {
  309. var constructor = value.constructor;
  310. if (constructor == Array){
  311. this.pack_array(value);
  312. } else if (constructor == Blob || constructor == File) {
  313. this.pack_bin(value);
  314. } else if (constructor == ArrayBuffer) {
  315. if(binaryFeatures.useArrayBufferView) {
  316. this.pack_bin(new Uint8Array(value));
  317. } else {
  318. this.pack_bin(value);
  319. }
  320. } else if ('BYTES_PER_ELEMENT' in value){
  321. if(binaryFeatures.useArrayBufferView) {
  322. this.pack_bin(value);
  323. } else {
  324. this.pack_bin(value.buffer);
  325. }
  326. } else if (constructor == Object){
  327. this.pack_object(value);
  328. } else if (constructor == Date){
  329. this.pack_string(value.toString());
  330. } else if (typeof value.toBinaryPack == 'function'){
  331. this.bufferBuilder.append(value.toBinaryPack());
  332. } else {
  333. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  334. }
  335. }
  336. } else {
  337. throw new Error('Type "' + type + '" not yet supported');
  338. }
  339. return this.bufferBuilder.getBuffer();
  340. }
  341. Packer.prototype.pack_bin = function(blob){
  342. var length = blob.length || blob.byteLength || blob.size;
  343. if (length <= 0x0f){
  344. this.pack_uint8(0xa0 + length);
  345. } else if (length <= 0xffff){
  346. this.bufferBuilder.append(0xda) ;
  347. this.pack_uint16(length);
  348. } else if (length <= 0xffffffff){
  349. this.bufferBuilder.append(0xdb);
  350. this.pack_uint32(length);
  351. } else{
  352. throw new Error('Invalid length');
  353. return;
  354. }
  355. this.bufferBuilder.append(blob);
  356. }
  357. Packer.prototype.pack_string = function(str){
  358. var length;
  359. if (this.utf8) {
  360. var blob = new Blob([str]);
  361. length = blob.size;
  362. } else {
  363. length = str.length;
  364. }
  365. if (length <= 0x0f){
  366. this.pack_uint8(0xb0 + length);
  367. } else if (length <= 0xffff){
  368. this.bufferBuilder.append(0xd8) ;
  369. this.pack_uint16(length);
  370. } else if (length <= 0xffffffff){
  371. this.bufferBuilder.append(0xd9);
  372. this.pack_uint32(length);
  373. } else{
  374. throw new Error('Invalid length');
  375. return;
  376. }
  377. this.bufferBuilder.append(str);
  378. }
  379. Packer.prototype.pack_array = function(ary){
  380. var length = ary.length;
  381. if (length <= 0x0f){
  382. this.pack_uint8(0x90 + length);
  383. } else if (length <= 0xffff){
  384. this.bufferBuilder.append(0xdc)
  385. this.pack_uint16(length);
  386. } else if (length <= 0xffffffff){
  387. this.bufferBuilder.append(0xdd);
  388. this.pack_uint32(length);
  389. } else{
  390. throw new Error('Invalid length');
  391. }
  392. for(var i = 0; i < length ; i++){
  393. this.pack(ary[i]);
  394. }
  395. }
  396. Packer.prototype.pack_integer = function(num){
  397. if ( -0x20 <= num && num <= 0x7f){
  398. this.bufferBuilder.append(num & 0xff);
  399. } else if (0x00 <= num && num <= 0xff){
  400. this.bufferBuilder.append(0xcc);
  401. this.pack_uint8(num);
  402. } else if (-0x80 <= num && num <= 0x7f){
  403. this.bufferBuilder.append(0xd0);
  404. this.pack_int8(num);
  405. } else if ( 0x0000 <= num && num <= 0xffff){
  406. this.bufferBuilder.append(0xcd);
  407. this.pack_uint16(num);
  408. } else if (-0x8000 <= num && num <= 0x7fff){
  409. this.bufferBuilder.append(0xd1);
  410. this.pack_int16(num);
  411. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  412. this.bufferBuilder.append(0xce);
  413. this.pack_uint32(num);
  414. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  415. this.bufferBuilder.append(0xd2);
  416. this.pack_int32(num);
  417. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  418. this.bufferBuilder.append(0xd3);
  419. this.pack_int64(num);
  420. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  421. this.bufferBuilder.append(0xcf);
  422. this.pack_uint64(num);
  423. } else{
  424. throw new Error('Invalid integer');
  425. }
  426. }
  427. Packer.prototype.pack_double = function(num){
  428. var sign = 0;
  429. if (num < 0){
  430. sign = 1;
  431. num = -num;
  432. }
  433. var exp = Math.floor(Math.log(num) / Math.LN2);
  434. var frac0 = num / Math.pow(2, exp) - 1;
  435. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  436. var b32 = Math.pow(2, 32);
  437. var h32 = (sign << 31) | ((exp+1023) << 20) |
  438. (frac1 / b32) & 0x0fffff;
  439. var l32 = frac1 % b32;
  440. this.bufferBuilder.append(0xcb);
  441. this.pack_int32(h32);
  442. this.pack_int32(l32);
  443. }
  444. Packer.prototype.pack_object = function(obj){
  445. var keys = Object.keys(obj);
  446. var length = keys.length;
  447. if (length <= 0x0f){
  448. this.pack_uint8(0x80 + length);
  449. } else if (length <= 0xffff){
  450. this.bufferBuilder.append(0xde);
  451. this.pack_uint16(length);
  452. } else if (length <= 0xffffffff){
  453. this.bufferBuilder.append(0xdf);
  454. this.pack_uint32(length);
  455. } else{
  456. throw new Error('Invalid length');
  457. }
  458. for(var prop in obj){
  459. if (obj.hasOwnProperty(prop)){
  460. this.pack(prop);
  461. this.pack(obj[prop]);
  462. }
  463. }
  464. }
  465. Packer.prototype.pack_uint8 = function(num){
  466. this.bufferBuilder.append(num);
  467. }
  468. Packer.prototype.pack_uint16 = function(num){
  469. this.bufferBuilder.append(num >> 8);
  470. this.bufferBuilder.append(num & 0xff);
  471. }
  472. Packer.prototype.pack_uint32 = function(num){
  473. var n = num & 0xffffffff;
  474. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  475. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  476. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  477. this.bufferBuilder.append((n & 0x000000ff));
  478. }
  479. Packer.prototype.pack_uint64 = function(num){
  480. var high = num / Math.pow(2, 32);
  481. var low = num % Math.pow(2, 32);
  482. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  483. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  484. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  485. this.bufferBuilder.append((high & 0x000000ff));
  486. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  487. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  488. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  489. this.bufferBuilder.append((low & 0x000000ff));
  490. }
  491. Packer.prototype.pack_int8 = function(num){
  492. this.bufferBuilder.append(num & 0xff);
  493. }
  494. Packer.prototype.pack_int16 = function(num){
  495. this.bufferBuilder.append((num & 0xff00) >> 8);
  496. this.bufferBuilder.append(num & 0xff);
  497. }
  498. Packer.prototype.pack_int32 = function(num){
  499. this.bufferBuilder.append((num >>> 24) & 0xff);
  500. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  501. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  502. this.bufferBuilder.append((num & 0x000000ff));
  503. }
  504. Packer.prototype.pack_int64 = function(num){
  505. var high = Math.floor(num / Math.pow(2, 32));
  506. var low = num % Math.pow(2, 32);
  507. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  508. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  509. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  510. this.bufferBuilder.append((high & 0x000000ff));
  511. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  512. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  513. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  514. this.bufferBuilder.append((low & 0x000000ff));
  515. }
  516. /**
  517. * Light EventEmitter. Ported from Node.js/events.js
  518. * Eric Zhang
  519. */
  520. /**
  521. * EventEmitter class
  522. * Creates an object with event registering and firing methods
  523. */
  524. function EventEmitter() {
  525. // Initialise required storage variables
  526. this._events = {};
  527. }
  528. var isArray = Array.isArray;
  529. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  530. if ('function' !== typeof listener) {
  531. throw new Error('addListener only takes instances of Function');
  532. }
  533. // To avoid recursion in the case that type == "newListeners"! Before
  534. // adding it to the listeners, first emit "newListeners".
  535. this.emit('newListener', type, typeof listener.listener === 'function' ?
  536. listener.listener : listener);
  537. if (!this._events[type]) {
  538. // Optimize the case of one listener. Don't need the extra array object.
  539. this._events[type] = listener;
  540. } else if (isArray(this._events[type])) {
  541. // If we've already got an array, just append.
  542. this._events[type].push(listener);
  543. } else {
  544. // Adding the second element, need to change to array.
  545. this._events[type] = [this._events[type], listener];
  546. }
  547. return this;
  548. };
  549. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  550. EventEmitter.prototype.once = function(type, listener, scope) {
  551. if ('function' !== typeof listener) {
  552. throw new Error('.once only takes instances of Function');
  553. }
  554. var self = this;
  555. function g() {
  556. self.removeListener(type, g);
  557. listener.apply(this, arguments);
  558. };
  559. g.listener = listener;
  560. self.on(type, g);
  561. return this;
  562. };
  563. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  564. if ('function' !== typeof listener) {
  565. throw new Error('removeListener only takes instances of Function');
  566. }
  567. // does not use listeners(), so no side effect of creating _events[type]
  568. if (!this._events[type]) return this;
  569. var list = this._events[type];
  570. if (isArray(list)) {
  571. var position = -1;
  572. for (var i = 0, length = list.length; i < length; i++) {
  573. if (list[i] === listener ||
  574. (list[i].listener && list[i].listener === listener))
  575. {
  576. position = i;
  577. break;
  578. }
  579. }
  580. if (position < 0) return this;
  581. list.splice(position, 1);
  582. if (list.length == 0)
  583. delete this._events[type];
  584. } else if (list === listener ||
  585. (list.listener && list.listener === listener))
  586. {
  587. delete this._events[type];
  588. }
  589. return this;
  590. };
  591. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  592. EventEmitter.prototype.removeAllListeners = function(type) {
  593. if (arguments.length === 0) {
  594. this._events = {};
  595. return this;
  596. }
  597. // does not use listeners(), so no side effect of creating _events[type]
  598. if (type && this._events && this._events[type]) this._events[type] = null;
  599. return this;
  600. };
  601. EventEmitter.prototype.listeners = function(type) {
  602. if (!this._events[type]) this._events[type] = [];
  603. if (!isArray(this._events[type])) {
  604. this._events[type] = [this._events[type]];
  605. }
  606. return this._events[type];
  607. };
  608. EventEmitter.prototype.emit = function(type) {
  609. var type = arguments[0];
  610. var handler = this._events[type];
  611. if (!handler) return false;
  612. if (typeof handler == 'function') {
  613. switch (arguments.length) {
  614. // fast cases
  615. case 1:
  616. handler.call(this);
  617. break;
  618. case 2:
  619. handler.call(this, arguments[1]);
  620. break;
  621. case 3:
  622. handler.call(this, arguments[1], arguments[2]);
  623. break;
  624. // slower
  625. default:
  626. var l = arguments.length;
  627. var args = new Array(l - 1);
  628. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  629. handler.apply(this, args);
  630. }
  631. return true;
  632. } else if (isArray(handler)) {
  633. var l = arguments.length;
  634. var args = new Array(l - 1);
  635. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  636. var listeners = handler.slice();
  637. for (var i = 0, l = listeners.length; i < l; i++) {
  638. listeners[i].apply(this, args);
  639. }
  640. return true;
  641. } else {
  642. return false;
  643. }
  644. };
  645. var util = {
  646. debug: false,
  647. browserisms: '',
  648. inherits: function(ctor, superCtor) {
  649. ctor.super_ = superCtor;
  650. ctor.prototype = Object.create(superCtor.prototype, {
  651. constructor: {
  652. value: ctor,
  653. enumerable: false,
  654. writable: true,
  655. configurable: true
  656. }
  657. });
  658. },
  659. extend: function(dest, source) {
  660. for(var key in source) {
  661. if(source.hasOwnProperty(key)) {
  662. dest[key] = source[key];
  663. }
  664. }
  665. return dest;
  666. },
  667. pack: BinaryPack.pack,
  668. unpack: BinaryPack.unpack,
  669. randomPort: function() {
  670. return Math.round(Math.random() * 60535) + 5000;
  671. },
  672. log: function () {
  673. if (util.debug) {
  674. var err = false;
  675. var copy = Array.prototype.slice.call(arguments);
  676. copy.unshift('PeerJS: ');
  677. for (var i = 0, l = copy.length; i < l; i++){
  678. if (copy[i] instanceof Error) {
  679. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  680. err = true;
  681. }
  682. }
  683. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  684. }
  685. },
  686. setZeroTimeout: (function(global) {
  687. var timeouts = [];
  688. var messageName = 'zero-timeout-message';
  689. // Like setTimeout, but only takes a function argument. There's
  690. // no time argument (always zero) and no arguments (you have to
  691. // use a closure).
  692. function setZeroTimeoutPostMessage(fn) {
  693. timeouts.push(fn);
  694. global.postMessage(messageName, '*');
  695. }
  696. function handleMessage(event) {
  697. if (event.source == global && event.data == messageName) {
  698. if (event.stopPropagation) {
  699. event.stopPropagation();
  700. }
  701. if (timeouts.length) {
  702. timeouts.shift()();
  703. }
  704. }
  705. }
  706. if (global.addEventListener) {
  707. global.addEventListener('message', handleMessage, true);
  708. } else if (global.attachEvent) {
  709. global.attachEvent('onmessage', handleMessage);
  710. }
  711. return setZeroTimeoutPostMessage;
  712. }(this)),
  713. blobToArrayBuffer: function(blob, cb){
  714. var fr = new FileReader();
  715. fr.onload = function(evt) {
  716. cb(evt.target.result);
  717. };
  718. fr.readAsArrayBuffer(blob);
  719. },
  720. blobToBinaryString: function(blob, cb){
  721. var fr = new FileReader();
  722. fr.onload = function(evt) {
  723. cb(evt.target.result);
  724. };
  725. fr.readAsBinaryString(blob);
  726. },
  727. binaryStringToArrayBuffer: function(binary) {
  728. var byteArray = new Uint8Array(binary.length);
  729. for (var i = 0; i < binary.length; i++) {
  730. byteArray[i] = binary.charCodeAt(i) & 0xff;
  731. }
  732. return byteArray.buffer;
  733. },
  734. randomToken: function () {
  735. return Math.random().toString(36).substr(2);
  736. }
  737. };
  738. /**
  739. * Reliable transfer for Chrome Canary DataChannel impl.
  740. * Author: @michellebu
  741. */
  742. function Reliable(dc, debug) {
  743. if (!(this instanceof Reliable)) return new Reliable(dc);
  744. this._dc = dc;
  745. util.debug = debug;
  746. // Messages sent/received so far.
  747. // id: { ack: n, chunks: [...] }
  748. this._outgoing = {};
  749. // id: { ack: ['ack', id, n], chunks: [...] }
  750. this._incoming = {};
  751. this._received = {};
  752. // Window size.
  753. this._window = 20;
  754. // MTU.
  755. this._mtu = 500;
  756. // Interval for setInterval. In ms.
  757. this._interval = 30;
  758. /**
  759. * TIMES for 5KB:
  760. * Time - wi | mtu | interval
  761. * 4441 - 20 | 500 | 50
  762. * 4317 - 100| 600 | 20
  763. * 4158 - 50 | 600 | 100
  764. * 4151 - 20 | 500 | 30
  765. * 4086 - 20 | 600 | 20
  766. * 4080 - 50 | 600 | 20
  767. * 4049 - 50 | 600 | 10
  768. * 3561 - 50 | 600 | 50
  769. * 2198 - 20 | 800 | 50 - Breaks for bigger files.
  770. * 800 MTU seems to throttle even at 200ms for larger files
  771. *
  772. * TIMES for 23KB:
  773. * 38421 - 20 | 600 | 50
  774. * 29904 - 20 | 500 | 30
  775. * 37906 - 50 | 500 | 30
  776. */
  777. // Messages sent.
  778. this._count = 0;
  779. // Outgoing message queue.
  780. this._queue = [];
  781. this._setupDC();
  782. };
  783. // Send a message reliably.
  784. Reliable.prototype.send = function(msg) {
  785. // Determine if chunking is necessary.
  786. var bl = util.pack(msg);
  787. if (bl.size < this._mtu) {
  788. this._handleSend(['no', bl]);
  789. return;
  790. }
  791. this._outgoing[this._count] = {
  792. ack: 0,
  793. chunks: this._chunk(bl)
  794. };
  795. if (util.debug) {
  796. this._outgoing[this._count].timer = new Date();
  797. }
  798. // Send prelim window.
  799. this._sendWindowedChunks(this._count);
  800. this._count += 1;
  801. };
  802. // Overwritten, typically.
  803. Reliable.prototype.onmessage = function(msg) {};
  804. // Set up interval for processing queue.
  805. Reliable.prototype._setupInterval = function() {
  806. var self = this;
  807. this._timeout = setInterval(function() {
  808. // FIXME: String stuff makes things terribly async.
  809. var msg = self._queue.shift();
  810. util.log('Sending...', msg);
  811. msg = util.pack(msg);
  812. util.blobToBinaryString(msg, function(str) {
  813. self._dc.send(str);
  814. if (self._queue.length === 0) {
  815. clearTimeout(self._timeout);
  816. self._timeout = null;
  817. self._processAcks();
  818. }
  819. });
  820. }, this._interval);
  821. };
  822. // Go through ACKs to send missing pieces.
  823. Reliable.prototype._processAcks = function() {
  824. for (var id in this._outgoing) {
  825. if (this._outgoing.hasOwnProperty(id)) {
  826. this._sendWindowedChunks(id);
  827. }
  828. }
  829. };
  830. // Handle sending a message.
  831. // FIXME: Don't wait for interval time for all messages...
  832. Reliable.prototype._handleSend = function(msg) {
  833. if (this._queue.indexOf(msg) === -1) {
  834. this._queue.push(msg);
  835. if (!this._timeout) {
  836. this._setupInterval();
  837. }
  838. }
  839. };
  840. // Set up DataChannel handlers.
  841. Reliable.prototype._setupDC = function() {
  842. // Handle various message types.
  843. var self = this;
  844. this._dc.onmessage = function(e) {
  845. var msg = e.data;
  846. var datatype = msg.constructor;
  847. // FIXME: msg is String until binary is supported.
  848. // Once that happens, this will have to be smarter.
  849. if (datatype === String) {
  850. var ab = util.binaryStringToArrayBuffer(msg);
  851. msg = util.unpack(ab);
  852. self._handleMessage(msg);
  853. }
  854. };
  855. };
  856. // Handles an incoming message.
  857. Reliable.prototype._handleMessage = function(msg) {
  858. util.log('handleMessage: ', msg);
  859. var id = msg[1];
  860. var idata = this._incoming[id];
  861. var odata = this._outgoing[id];
  862. var data;
  863. switch (msg[0]) {
  864. // No chunking was done.
  865. case 'no':
  866. var message = id;
  867. if (!!message) {
  868. // TODO: What fancy timeout stuff to do with ACK?
  869. this.onmessage(util.unpack(message));
  870. }
  871. break;
  872. // Reached the end of the message.
  873. case 'end':
  874. // What if 'end' is sent out of order? Eventually we will ACK for
  875. // and receive it, so shouldn't be a problem.
  876. data = idata;
  877. if (!!data && data.ack[2] === msg[2]) {
  878. this._complete(id);
  879. this._received[id] = true;
  880. } else if (!!data) {
  881. this._ack(id, data.ack);
  882. }
  883. break;
  884. case 'ack':
  885. data = odata;
  886. if (!!data) {
  887. // TODO: more optimization for window size & data sent.
  888. // TODO: possibly process ACKs only after queue cleared to avoid dups?
  889. var ack = msg[2];
  890. // Take the larger ACK, for out of order messages.
  891. data.ack = Math.max(ack, data.ack);
  892. // Clean up when all chunks are ACKed.
  893. if (data.ack >= data.chunks.length) {
  894. util.log('Time: ', new Date() - data.timer);
  895. delete this._outgoing[id];
  896. }
  897. }
  898. // If !data, just ignore.
  899. break;
  900. // Received a chunk of data.
  901. case 'chunk':
  902. // Create a new entry if none exists.
  903. data = idata;
  904. if (!data) {
  905. if (this._received[id] !== undefined) {
  906. break;
  907. }
  908. data = {
  909. ack: ['ack', id, 0],
  910. chunks: []
  911. };
  912. this._incoming[id] = data;
  913. }
  914. var n = msg[2];
  915. var chunk = msg[3];
  916. data.chunks[n] = chunk;
  917. // If we get the chunk we're looking for, ACK for next missing.
  918. // Otherwise, ACK the same N again.
  919. if (n === data.ack[2]) {
  920. this._calculateNextAck(id);
  921. }
  922. this._ack(id);
  923. break;
  924. default:
  925. // Shouldn't happen, but would make sense for message to just go
  926. // through as is.
  927. this._handleSend(msg);
  928. break;
  929. }
  930. };
  931. // Chunks BL into smaller messages.
  932. Reliable.prototype._chunk = function(bl) {
  933. var chunks = [];
  934. var size = bl.size;
  935. var start = 0;
  936. while (start < size) {
  937. var end = Math.min(size, start + this._mtu);
  938. var b = bl.slice(start, end);
  939. var chunk = {
  940. payload: b
  941. }
  942. chunks.push(chunk);
  943. start = end;
  944. }
  945. return chunks;
  946. };
  947. // Sends ACK N, expecting Nth blob chunk for message ID.
  948. Reliable.prototype._ack = function(id, n) {
  949. var ack = this._incoming[id].ack;
  950. this._handleSend(ack);
  951. };
  952. // Sends END.
  953. Reliable.prototype._end = function(id, n) {
  954. this._handleSend(['end', id, n]);
  955. };
  956. // Calculates the next ACK number, given chunks.
  957. Reliable.prototype._calculateNextAck = function(id) {
  958. var data = this._incoming[id];
  959. var chunks = data.chunks;
  960. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  961. // This chunk is missing!!! Better ACK for it.
  962. if (chunks[i] === undefined) {
  963. data.ack[2] = i;
  964. return;
  965. }
  966. }
  967. data.ack[2] = chunks.length;
  968. };
  969. // Sends the next window of chunks.
  970. Reliable.prototype._sendWindowedChunks = function(id) {
  971. util.log('sendWindowedChunks for: ', id);
  972. var data = this._outgoing[id];
  973. var ch = data.chunks;
  974. var limit = Math.min(data.ack + this._window, ch.length);
  975. var timeout = 0;
  976. for (var i = data.ack; i < limit; i += 1) {
  977. if (!ch[i].sent || i === data.ack) {
  978. ch[i].sent = true;
  979. // TODO: set timer.
  980. this._sendChunk(id, i, ch[i].payload);
  981. }
  982. }
  983. if (data.ack + this._window >= ch.length) {
  984. this._end(id, ch.length);
  985. }
  986. // TODO: set retry timer.
  987. };
  988. // Sends one chunk.
  989. Reliable.prototype._sendChunk = function(id, n, payload) {
  990. util.log('sendChunk', payload);
  991. this._handleSend(['chunk', id, n, payload]);
  992. };
  993. // Puts together a message from chunks.
  994. Reliable.prototype._complete = function(id) {
  995. util.log('complete', id);
  996. // FIXME: handle errors.
  997. var self = this;
  998. var chunks = this._incoming[id].chunks;
  999. var bl = new Blob(chunks);
  1000. util.blobToArrayBuffer(bl, function(ab) {
  1001. self.onmessage(util.unpack(ab));
  1002. });
  1003. delete this._incoming[id];
  1004. };
  1005. exports.Reliable = Reliable;
  1006. var RTCPeerConnection = null;
  1007. var getUserMedia = null;
  1008. var attachMediaStream = null;
  1009. if (navigator.mozGetUserMedia) {
  1010. util.browserisms = 'Firefox';
  1011. RTCSessionDescription = window.mozRTCSessionDescription;
  1012. RTCPeerConnection = window.mozRTCPeerConnection;
  1013. getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1014. } else if (navigator.webkitGetUserMedia) {
  1015. util.browserisms = 'Webkit';
  1016. RTCPeerConnection = window.webkitRTCPeerConnection;
  1017. getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1018. }
  1019. exports.RTCSessionDescription = RTCSessionDescription;
  1020. exports.RTCPeerConnection = RTCPeerConnection;
  1021. exports.getUserMedia = getUserMedia;
  1022. /**
  1023. * A peer who can initiate connections with other peers.
  1024. */
  1025. function Peer(id, options) {
  1026. if (id && id.constructor == Object) {
  1027. options = id;
  1028. id = undefined;
  1029. }
  1030. if (!(this instanceof Peer)) return new Peer(id, options);
  1031. EventEmitter.call(this);
  1032. // Detect relative URL host.
  1033. if (options.host === '/') {
  1034. options.host = window.location.hostname;
  1035. console.log('wat')
  1036. }
  1037. options = util.extend({
  1038. debug: false,
  1039. host: '0.peerjs.com',
  1040. port: 9000,
  1041. key: 'peerjs',
  1042. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  1043. }, options);
  1044. this._options = options;
  1045. util.debug = options.debug;
  1046. // Ensure alphanumeric_-
  1047. var self = this;
  1048. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  1049. util.setZeroTimeout(function() {
  1050. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  1051. });
  1052. return
  1053. }
  1054. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  1055. util.setZeroTimeout(function() {
  1056. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1057. });
  1058. return
  1059. }
  1060. // Connections for this peer.
  1061. this.connections = {};
  1062. // Queued connections to make.
  1063. this._queued = [];
  1064. // Init immediately if ID is given, otherwise ask server for ID
  1065. if (id) {
  1066. this.id = id;
  1067. this._init();
  1068. } else {
  1069. this._getId();
  1070. }
  1071. };
  1072. util.inherits(Peer, EventEmitter);
  1073. Peer.prototype._getId = function(cb) {
  1074. var self = this;
  1075. try {
  1076. var http = new XMLHttpRequest();
  1077. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  1078. // If there's no ID we need to wait for one before trying to init socket.
  1079. http.open('get', url, true);
  1080. http.onreadystatechange = function() {
  1081. if (http.readyState === 4) {
  1082. self.id = http.responseText;
  1083. self._init();
  1084. }
  1085. };
  1086. http.send(null);
  1087. } catch(e) {
  1088. this._abort('server-error', 'Could not get an ID from the server');
  1089. }
  1090. };
  1091. Peer.prototype._init = function() {
  1092. var self = this;
  1093. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  1094. this._socket.on('message', function(data) {
  1095. self._handleServerJSONMessage(data);
  1096. });
  1097. this._socket.on('error', function(error) {
  1098. util.log(error);
  1099. self._abort('socket-error', error);
  1100. });
  1101. this._socket.on('close', function() {
  1102. var msg = 'Underlying socket has closed';
  1103. util.log('error', msg);
  1104. self._abort('socket-closed', msg);
  1105. });
  1106. this._socket.start();
  1107. }
  1108. Peer.prototype._handleServerJSONMessage = function(message) {
  1109. var peer = message.src;
  1110. var connection = this.connections[peer];
  1111. var payload = message.payload;
  1112. switch (message.type) {
  1113. case 'OPEN':
  1114. this._processQueue();
  1115. this.emit('open', this.id);
  1116. break;
  1117. case 'ERROR':
  1118. util.log(payload.msg);
  1119. this._abort('server-error', payload.msg);
  1120. break;
  1121. case 'ID-TAKEN':
  1122. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  1123. break;
  1124. case 'OFFER':
  1125. var options = {
  1126. metadata: payload.metadata,
  1127. serialization: payload.serialization,
  1128. sdp: payload.sdp,
  1129. reliable: payload.reliable,
  1130. config: this._options.config
  1131. };
  1132. var connection = new DataConnection(this.id, peer, this._socket, options);
  1133. this._attachConnectionListeners(connection);
  1134. this.connections[peer] = connection;
  1135. this.emit('connection', connection, payload.metadata);
  1136. break;
  1137. case 'EXPIRE':
  1138. connection = this.connections[peer];
  1139. if (connection) {
  1140. connection.close();
  1141. connection.emit('error', new Error('Could not connect to peer ' + connection.peer));
  1142. }
  1143. break;
  1144. case 'ANSWER':
  1145. if (connection) {
  1146. connection.handleSDP(payload.sdp, message.type);
  1147. }
  1148. break;
  1149. case 'CANDIDATE':
  1150. if (connection) {
  1151. connection.handleCandidate(payload);
  1152. }
  1153. break;
  1154. case 'LEAVE':
  1155. if (connection) {
  1156. connection.handleLeave();
  1157. }
  1158. break;
  1159. case 'INVALID-KEY':
  1160. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1161. break;
  1162. case 'PORT':
  1163. //if (util.browserisms === 'Firefox') {
  1164. // connection.handlePort(payload);
  1165. // break;
  1166. //}
  1167. default:
  1168. util.log('Unrecognized message type:', message.type);
  1169. break;
  1170. }
  1171. };
  1172. /** Process queued calls to connect. */
  1173. Peer.prototype._processQueue = function() {
  1174. while (this._queued.length > 0) {
  1175. var conn = this._queued.pop();
  1176. conn.initialize(this.id, this._socket);
  1177. }
  1178. };
  1179. /** Destroys the Peer and emits an error message. */
  1180. Peer.prototype._abort = function(type, message) {
  1181. var err = new Error(message);
  1182. err.type = type;
  1183. this.destroy();
  1184. this.emit('error', err);
  1185. };
  1186. Peer.prototype._cleanup = function() {
  1187. var self = this;
  1188. if (!!this.connections) {
  1189. var peers = Object.keys(this.connections);
  1190. for (var i = 0, ii = peers.length; i < ii; i++) {
  1191. this.connections[peers[i]].close();
  1192. }
  1193. util.setZeroTimeout(function(){
  1194. self._socket.close();
  1195. });
  1196. }
  1197. this.emit('close');
  1198. };
  1199. /** Listeners for DataConnection events. */
  1200. Peer.prototype._attachConnectionListeners = function(connection) {
  1201. var self = this;
  1202. connection.on('close', function(peer) {
  1203. if (self.connections[peer]) {
  1204. delete self.connections[peer];
  1205. }
  1206. });
  1207. };
  1208. /** Exposed connect function for users. Will try to connect later if user
  1209. * is waiting for an ID. */
  1210. // TODO: pause XHR streaming when not in use and start again when this is
  1211. // called.
  1212. Peer.prototype.connect = function(peer, options) {
  1213. if (this.destroyed) {
  1214. this._abort('peer-destroyed', 'This Peer has been destroyed and is no longer able to make connections.');
  1215. return;
  1216. }
  1217. options = util.extend({
  1218. config: this._options.config
  1219. }, options);
  1220. var connection = new DataConnection(this.id, peer, this._socket, options);
  1221. this._attachConnectionListeners(connection);
  1222. this.connections[peer] = connection;
  1223. if (!this.id) {
  1224. this._queued.push(connection);
  1225. }
  1226. return connection;
  1227. };
  1228. Peer.prototype.destroy = function() {
  1229. if (!this.destroyed) {
  1230. this._cleanup();
  1231. this.destroyed = true;
  1232. }
  1233. };
  1234. exports.Peer = Peer;
  1235. /**
  1236. * A DataChannel|PeerConnection between two Peers.
  1237. */
  1238. function DataConnection(id, peer, socket, options) {
  1239. if (!(this instanceof DataConnection)) return new DataConnection(options);
  1240. EventEmitter.call(this);
  1241. options = util.extend({
  1242. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  1243. reliable: false,
  1244. serialization: 'binary'
  1245. }, options);
  1246. this._options = options;
  1247. // Connection is not open yet.
  1248. this.open = false;
  1249. this.id = id;
  1250. this.peer = peer;
  1251. this.metadata = options.metadata;
  1252. this.serialization = options.serialization;
  1253. this._originator = (options.sdp === undefined);
  1254. this._socket = socket;
  1255. this._sdp = options.sdp;
  1256. if (!!this.id) {
  1257. this.initialize();
  1258. }
  1259. };
  1260. util.inherits(DataConnection, EventEmitter);
  1261. DataConnection.prototype.initialize = function(id, socket) {
  1262. if (!!id) {
  1263. this.id = id;
  1264. }
  1265. if (!!socket) {
  1266. this._socket = socket;
  1267. }
  1268. // Firefoxism: connectDataConnection ports.
  1269. /*if (util.browserisms === 'Firefox') {
  1270. this._firefoxPortSetup();
  1271. }*/
  1272. // Set up PeerConnection.
  1273. this._startPeerConnection();
  1274. // Listen for ICE candidates
  1275. this._setupIce();
  1276. // Listen for negotiation needed
  1277. // ** Chrome only.
  1278. if (util.browserisms !== 'Firefox' && !!this.id) {
  1279. this._setupOffer();
  1280. }
  1281. // Listen for or create a data channel
  1282. this._setupDataChannel();
  1283. var self = this;
  1284. if (!!this._sdp) {
  1285. this.handleSDP(this._sdp, 'OFFER');
  1286. }
  1287. // Makes offer if Firefox
  1288. /*if (util.browserisms === 'Firefox') {
  1289. this._firefoxAdditional();
  1290. }*/
  1291. // No-op this.
  1292. this.initialize = function() {};
  1293. };
  1294. DataConnection.prototype._setupOffer = function() {
  1295. var self = this;
  1296. util.log('Listening for `negotiationneeded`');
  1297. this._pc.onnegotiationneeded = function() {
  1298. util.log('`negotiationneeded` triggered');
  1299. self._makeOffer();
  1300. };
  1301. };
  1302. DataConnection.prototype._setupDataChannel = function() {
  1303. var self = this;
  1304. if (this._originator) {
  1305. util.log('Creating data channel');
  1306. // FOR NOW: reliable DC is not supported.
  1307. this._dc = this._pc.createDataChannel(this.peer, { reliable: false });
  1308. // Experimental reliable wrapper.
  1309. if (this._options.reliable) {
  1310. this._reliable = new Reliable(this._dc, util.debug);
  1311. }
  1312. this._configureDataChannel();
  1313. } else {
  1314. util.log('Listening for data channel');
  1315. this._pc.ondatachannel = function(evt) {
  1316. util.log('Received data channel');
  1317. self._dc = evt.channel;
  1318. // Experimental reliable wrapper.
  1319. if (self._options.reliable) {
  1320. self._reliable = new Reliable(self._dc, util.debug);
  1321. }
  1322. self._configureDataChannel();
  1323. };
  1324. }
  1325. };
  1326. /** Starts a PeerConnection and sets up handlers. */
  1327. DataConnection.prototype._startPeerConnection = function() {
  1328. util.log('Creating RTCPeerConnection');
  1329. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  1330. };
  1331. /** Takes care of ice handlers. */
  1332. DataConnection.prototype._setupIce = function() {
  1333. util.log('Listening for ICE candidates');
  1334. var self = this;
  1335. this._pc.onicecandidate = function(evt) {
  1336. if (evt.candidate) {
  1337. util.log('Received ICE candidates');
  1338. self._socket.send({
  1339. type: 'CANDIDATE',
  1340. payload: {
  1341. candidate: evt.candidate
  1342. },
  1343. dst: self.peer
  1344. });
  1345. }
  1346. };
  1347. };
  1348. /*DataConnection.prototype._firefoxPortSetup = function() {
  1349. if (!DataConnection.usedPorts) {
  1350. DataConnection.usedPorts = [];
  1351. }
  1352. this.localPort = util.randomPort();
  1353. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1354. this.localPort = util.randomPort();
  1355. }
  1356. this.remotePort = util.randomPort();
  1357. while (this.remotePort === this.localPort ||
  1358. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1359. this.remotePort = util.randomPort();
  1360. }
  1361. DataConnection.usedPorts.push(this.remotePort);
  1362. DataConnection.usedPorts.push(this.localPort);
  1363. }*/
  1364. DataConnection.prototype._configureDataChannel = function() {
  1365. var self = this;
  1366. if (util.browserisms !== 'Webkit') {
  1367. this._dc.binaryType = 'arraybuffer';
  1368. }
  1369. this._dc.onopen = function() {
  1370. util.log('Data channel connection success');
  1371. self.open = true;
  1372. self.emit('open');
  1373. };
  1374. if (this._reliable) {
  1375. this._reliable.onmessage = function(msg) {
  1376. self.emit('data', msg);
  1377. };
  1378. } else {
  1379. this._dc.onmessage = function(e) {
  1380. self._handleDataMessage(e);
  1381. };
  1382. }
  1383. this._dc.onclose = function(e) {
  1384. self.emit('close');
  1385. };
  1386. };
  1387. /** Decide whether to handle Firefoxisms. */
  1388. /*DataConnection.prototype._firefoxAdditional = function() {
  1389. var self = this;
  1390. getUserMedia({ audio: true, fake: true }, function(s) {
  1391. self._pc.addStream(s);
  1392. if (self._originator) {
  1393. self._makeOffer();
  1394. }
  1395. }, function(err) { util.log('Could not getUserMedia'); });
  1396. };*/
  1397. DataConnection.prototype._makeOffer = function() {
  1398. var self = this;
  1399. this._pc.createOffer(function(offer) {
  1400. util.log('Created offer');
  1401. self._pc.setLocalDescription(offer, function() {
  1402. util.log('Set localDescription to offer');
  1403. self._socket.send({
  1404. type: 'OFFER',
  1405. payload: {
  1406. sdp: offer,
  1407. serialization: self.serialization,
  1408. metadata: self.metadata,
  1409. reliable: self._options.reliable
  1410. },
  1411. dst: self.peer
  1412. });
  1413. }, function(err) {
  1414. self.emit('error', err);
  1415. util.log('Failed to setLocalDescription, ', err);
  1416. });
  1417. });
  1418. };
  1419. /** Create an answer for PC. */
  1420. DataConnection.prototype._makeAnswer = function() {
  1421. var self = this;
  1422. this._pc.createAnswer(function(answer) {
  1423. util.log('Created answer');
  1424. self._pc.setLocalDescription(answer, function() {
  1425. util.log('Set localDescription to answer');
  1426. self._socket.send({
  1427. type: 'ANSWER',
  1428. payload: {
  1429. sdp: answer
  1430. },
  1431. dst: self.peer
  1432. });
  1433. }, function(err) {
  1434. self.emit('error', err);
  1435. util.log('Failed to setLocalDescription, ', err)
  1436. });
  1437. }, function(err) {
  1438. self.emit('error', err);
  1439. util.log('Failed to create answer, ', err)
  1440. });
  1441. };
  1442. DataConnection.prototype._cleanup = function() {
  1443. if (!!this._dc && this._dc.readyState != 'closed') {
  1444. this._dc.close();
  1445. this._dc = null;
  1446. }
  1447. if (!!this._pc && this._pc.readyState != 'closed') {
  1448. this._pc.close();
  1449. this._pc = null;
  1450. }
  1451. };
  1452. // Handles a DataChannel message.
  1453. DataConnection.prototype._handleDataMessage = function(e) {
  1454. var self = this;
  1455. var data = e.data;
  1456. var datatype = data.constructor;
  1457. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1458. if (datatype === Blob) {
  1459. util.blobToArrayBuffer(data, function(ab) {
  1460. data = util.unpack(ab);
  1461. self.emit('data', data);
  1462. });
  1463. return;
  1464. } else if (datatype === ArrayBuffer) {
  1465. data = util.unpack(data);
  1466. } else if (datatype === String) {
  1467. var ab = util.binaryStringToArrayBuffer(data);
  1468. data = util.unpack(ab);
  1469. }
  1470. } else if (this.serialization === 'json') {
  1471. data = JSON.parse(data);
  1472. }
  1473. this.emit('data', data);
  1474. };
  1475. /**
  1476. * Exposed functionality for users.
  1477. */
  1478. /** Allows user to close connection. */
  1479. DataConnection.prototype.close = function() {
  1480. this._cleanup();
  1481. var self = this;
  1482. if (this.open) {
  1483. this._socket.send({
  1484. type: 'LEAVE',
  1485. dst: self.peer
  1486. });
  1487. }
  1488. this.open = false;
  1489. this.emit('close', this.peer);
  1490. };
  1491. /** Allows user to send data. */
  1492. DataConnection.prototype.send = function(data) {
  1493. if (this._reliable) {
  1494. // Note: reliable sending will make it so that you cannot customize
  1495. // serialization.
  1496. this._reliable.send(data);
  1497. return;
  1498. }
  1499. var self = this;
  1500. if (this.serialization === 'none') {
  1501. this._dc.send(data);
  1502. } else if (this.serialization === 'json') {
  1503. this._dc.send(JSON.stringify(data));
  1504. } else {
  1505. var utf8 = (this.serialization === 'binary-utf8');
  1506. var blob = util.pack(data, utf8);
  1507. // DataChannel currently only supports strings.
  1508. if (util.browserisms === 'Webkit') {
  1509. util.blobToBinaryString(blob, function(str){
  1510. self._dc.send(str);
  1511. });
  1512. } else {
  1513. this._dc.send(blob);
  1514. }
  1515. }
  1516. };
  1517. DataConnection.prototype.handleSDP = function(sdp, type) {
  1518. if (util.browserisms != 'Firefox') {
  1519. sdp = new RTCSessionDescription(sdp);
  1520. }
  1521. var self = this;
  1522. this._pc.setRemoteDescription(sdp, function() {
  1523. util.log('Set remoteDescription: ' + type);
  1524. // Firefoxism
  1525. /**if (type === 'ANSWER' && util.browserisms === 'Firefox') {
  1526. self._pc.connectDataConnection(self.localPort, self.remotePort);
  1527. self._socket.send({
  1528. type: 'PORT',
  1529. dst: self.peer,
  1530. payload: {
  1531. remote: self.localPort,
  1532. local: self.remotePort
  1533. }
  1534. });
  1535. } else*/ if (type === 'OFFER') {
  1536. self._makeAnswer();
  1537. }
  1538. }, function(err) {
  1539. self.emit('error', err);
  1540. util.log('Failed to setRemoteDescription, ', err);
  1541. });
  1542. };
  1543. DataConnection.prototype.handleCandidate = function(message) {
  1544. var candidate = new RTCIceCandidate(message.candidate);
  1545. this._pc.addIceCandidate(candidate);
  1546. util.log('Added ice candidate');
  1547. };
  1548. DataConnection.prototype.handleLeave = function() {
  1549. util.log('Peer ' + this.peer + ' disconnected');
  1550. this.close();
  1551. };
  1552. /*
  1553. DataConnection.prototype.handlePort = function(message) {
  1554. if (!DataConnection.usedPorts) {
  1555. DataConnection.usedPorts = [];
  1556. }
  1557. DataConnection.usedPorts.push(message.local);
  1558. DataConnection.usedPorts.push(message.remote);
  1559. this._pc.connectDataConnection(message.local, message.remote);
  1560. };
  1561. */
  1562. /**
  1563. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1564. * possible connection for peers.
  1565. */
  1566. function Socket(host, port, key, id) {
  1567. if (!(this instanceof Socket)) return new Socket(server, id, key);
  1568. EventEmitter.call(this);
  1569. this._id = id;
  1570. var token = util.randomToken();
  1571. this._httpUrl = 'http://' + host + ':' + port + '/' + key + '/' + id + '/' + token;
  1572. this._wsUrl = 'ws://' + host + ':' + port + '/peerjs?key='+key+'&id='+id+'&token='+token;
  1573. };
  1574. util.inherits(Socket, EventEmitter);
  1575. /** Check in with ID or get one from server. */
  1576. Socket.prototype.start = function() {
  1577. this._startXhrStream();
  1578. this._startWebSocket();
  1579. };
  1580. /** Start up websocket communications. */
  1581. Socket.prototype._startWebSocket = function() {
  1582. var self = this;
  1583. if (!!this._socket) {
  1584. return;
  1585. }
  1586. this._socket = new WebSocket(this._wsUrl);
  1587. this._socket.onmessage = function(event) {
  1588. var data;
  1589. try {
  1590. data = JSON.parse(event.data);
  1591. } catch(e) {
  1592. util.log('Invalid server message', event.data);
  1593. return;
  1594. }
  1595. self.emit('message', data);
  1596. };
  1597. // Take care of the queue of connections if necessary and make sure Peer knows
  1598. // socket is open.
  1599. this._socket.onopen = function() {
  1600. if (!!self._timeout) {
  1601. clearTimeout(self._timeout);
  1602. setTimeout(function(){
  1603. self._http.abort();
  1604. self._http = null;
  1605. }, 5000);
  1606. }
  1607. util.log('Socket open');
  1608. };
  1609. };
  1610. /** Start XHR streaming. */
  1611. Socket.prototype._startXhrStream = function(n) {
  1612. try {
  1613. var self = this;
  1614. this._http = new XMLHttpRequest();
  1615. this._http._index = 1;
  1616. this._http._streamIndex = n || 0;
  1617. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  1618. this._http.onreadystatechange = function() {
  1619. if (this.readyState == 2 && !!this.old) {
  1620. this.old.abort();
  1621. delete this.old;
  1622. }
  1623. if (this.readyState > 2 && this.status == 200 && !!this.responseText) {
  1624. self._handleStream(this);
  1625. }
  1626. };
  1627. this._http.send(null);
  1628. this._setHTTPTimeout();
  1629. } catch(e) {
  1630. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  1631. }
  1632. };
  1633. /** Handles onreadystatechange response as a stream. */
  1634. Socket.prototype._handleStream = function(http) {
  1635. var self = this;
  1636. // 3 and 4 are loading/done state. All others are not relevant.
  1637. var message = http.responseText.split('\n')[http._index];
  1638. if (!!message) {
  1639. http._index += 1;
  1640. try {
  1641. message = JSON.parse(message);
  1642. } catch(e) {
  1643. util.log('Invalid server message', message);
  1644. return;
  1645. }
  1646. self.emit('message', message);
  1647. }
  1648. };
  1649. Socket.prototype._setHTTPTimeout = function() {
  1650. var self = this;
  1651. this._timeout = setTimeout(function() {
  1652. var old = self._http;
  1653. if (!self._wsOpen()) {
  1654. self._startXhrStream(old._streamIndex + 1);
  1655. self._http.old = old;
  1656. } else {
  1657. old.abort();
  1658. }
  1659. }, 25000);
  1660. };
  1661. /** Exposed send for DC & Peer. */
  1662. Socket.prototype.send = function(data) {
  1663. if (!data.type) {
  1664. this.emit('error', 'Invalid message');
  1665. return;
  1666. }
  1667. var message = JSON.stringify(data);
  1668. if (this._wsOpen()) {
  1669. this._socket.send(message);
  1670. } else {
  1671. var http = new XMLHttpRequest();
  1672. var url = this._httpUrl + '/' + data.type.toLowerCase();
  1673. http.open('post', url, true);
  1674. http.setRequestHeader('Content-Type', 'application/json');
  1675. http.send(message);
  1676. }
  1677. };
  1678. Socket.prototype.close = function() {
  1679. if (!!this._wsOpen()) {
  1680. this._socket.close();
  1681. }
  1682. };
  1683. Socket.prototype._wsOpen = function() {
  1684. return !!this._socket && this._socket.readyState == 1;
  1685. };
  1686. })(this);