peer.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. /*! peerjs.js build:0.0.1, 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. binaryFeatures.supportsBinaryWebsockets = (function(){
  20. try {
  21. var wstest = new WebSocket('ws://null');
  22. wstest.onerror = function(){};
  23. if (typeof(wstest.binaryType) !== "undefined") {
  24. return true;
  25. } else {
  26. return false;
  27. }
  28. wstest.close();
  29. wstest = null;
  30. } catch (e) {
  31. return false;
  32. }
  33. })();
  34. exports.binaryFeatures = binaryFeatures;
  35. exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  36. function BufferBuilder(){
  37. this._pieces = [];
  38. this._parts = [];
  39. }
  40. BufferBuilder.prototype.append = function(data) {
  41. if(typeof data === 'number') {
  42. this._pieces.push(data);
  43. } else {
  44. this._flush();
  45. this._parts.push(data);
  46. }
  47. };
  48. BufferBuilder.prototype._flush = function() {
  49. if (this._pieces.length > 0) {
  50. var buf = new Uint8Array(this._pieces);
  51. if(!binaryFeatures.useArrayBufferView) {
  52. buf = buf.buffer;
  53. }
  54. this._parts.push(buf);
  55. this._pieces = [];
  56. }
  57. };
  58. BufferBuilder.prototype.getBuffer = function() {
  59. this._flush();
  60. if(binaryFeatures.useBlobBuilder) {
  61. var builder = new BlobBuilder();
  62. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  63. builder.append(this._parts[i]);
  64. }
  65. return builder.getBlob();
  66. } else {
  67. return new Blob(this._parts);
  68. }
  69. };
  70. exports.BinaryPack = {
  71. unpack: function(data){
  72. var unpacker = new Unpacker(data);
  73. return unpacker.unpack();
  74. },
  75. pack: function(data){
  76. var packer = new Packer();
  77. var buffer = packer.pack(data);
  78. return buffer;
  79. }
  80. };
  81. function Unpacker (data){
  82. // Data is ArrayBuffer
  83. this.index = 0;
  84. this.dataBuffer = data;
  85. this.dataView = new Uint8Array(this.dataBuffer);
  86. this.length = this.dataBuffer.byteLength;
  87. }
  88. Unpacker.prototype.unpack = function(){
  89. var type = this.unpack_uint8();
  90. if (type < 0x80){
  91. var positive_fixnum = type;
  92. return positive_fixnum;
  93. } else if ((type ^ 0xe0) < 0x20){
  94. var negative_fixnum = (type ^ 0xe0) - 0x20;
  95. return negative_fixnum;
  96. }
  97. var size;
  98. if ((size = type ^ 0xa0) <= 0x0f){
  99. return this.unpack_raw(size);
  100. } else if ((size = type ^ 0xb0) <= 0x0f){
  101. return this.unpack_string(size);
  102. } else if ((size = type ^ 0x90) <= 0x0f){
  103. return this.unpack_array(size);
  104. } else if ((size = type ^ 0x80) <= 0x0f){
  105. return this.unpack_map(size);
  106. }
  107. switch(type){
  108. case 0xc0:
  109. return null;
  110. case 0xc1:
  111. return undefined;
  112. case 0xc2:
  113. return false;
  114. case 0xc3:
  115. return true;
  116. case 0xca:
  117. return this.unpack_float();
  118. case 0xcb:
  119. return this.unpack_double();
  120. case 0xcc:
  121. return this.unpack_uint8();
  122. case 0xcd:
  123. return this.unpack_uint16();
  124. case 0xce:
  125. return this.unpack_uint32();
  126. case 0xcf:
  127. return this.unpack_uint64();
  128. case 0xd0:
  129. return this.unpack_int8();
  130. case 0xd1:
  131. return this.unpack_int16();
  132. case 0xd2:
  133. return this.unpack_int32();
  134. case 0xd3:
  135. return this.unpack_int64();
  136. case 0xd4:
  137. return undefined;
  138. case 0xd5:
  139. return undefined;
  140. case 0xd6:
  141. return undefined;
  142. case 0xd7:
  143. return undefined;
  144. case 0xd8:
  145. size = this.unpack_uint16();
  146. return this.unpack_string(size);
  147. case 0xd9:
  148. size = this.unpack_uint32();
  149. return this.unpack_string(size);
  150. case 0xda:
  151. size = this.unpack_uint16();
  152. return this.unpack_raw(size);
  153. case 0xdb:
  154. size = this.unpack_uint32();
  155. return this.unpack_raw(size);
  156. case 0xdc:
  157. size = this.unpack_uint16();
  158. return this.unpack_array(size);
  159. case 0xdd:
  160. size = this.unpack_uint32();
  161. return this.unpack_array(size);
  162. case 0xde:
  163. size = this.unpack_uint16();
  164. return this.unpack_map(size);
  165. case 0xdf:
  166. size = this.unpack_uint32();
  167. return this.unpack_map(size);
  168. }
  169. }
  170. Unpacker.prototype.unpack_uint8 = function(){
  171. var byte = this.dataView[this.index] & 0xff;
  172. this.index++;
  173. return byte;
  174. };
  175. Unpacker.prototype.unpack_uint16 = function(){
  176. var bytes = this.read(2);
  177. var uint16 =
  178. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  179. this.index += 2;
  180. return uint16;
  181. }
  182. Unpacker.prototype.unpack_uint32 = function(){
  183. var bytes = this.read(4);
  184. var uint32 =
  185. ((bytes[0] * 256 +
  186. bytes[1]) * 256 +
  187. bytes[2]) * 256 +
  188. bytes[3];
  189. this.index += 4;
  190. return uint32;
  191. }
  192. Unpacker.prototype.unpack_uint64 = function(){
  193. var bytes = this.read(8);
  194. var uint64 =
  195. ((((((bytes[0] * 256 +
  196. bytes[1]) * 256 +
  197. bytes[2]) * 256 +
  198. bytes[3]) * 256 +
  199. bytes[4]) * 256 +
  200. bytes[5]) * 256 +
  201. bytes[6]) * 256 +
  202. bytes[7];
  203. this.index += 8;
  204. return uint64;
  205. }
  206. Unpacker.prototype.unpack_int8 = function(){
  207. var uint8 = this.unpack_uint8();
  208. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  209. };
  210. Unpacker.prototype.unpack_int16 = function(){
  211. var uint16 = this.unpack_uint16();
  212. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  213. }
  214. Unpacker.prototype.unpack_int32 = function(){
  215. var uint32 = this.unpack_uint32();
  216. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  217. uint32 - Math.pow(2, 32);
  218. }
  219. Unpacker.prototype.unpack_int64 = function(){
  220. var uint64 = this.unpack_uint64();
  221. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  222. uint64 - Math.pow(2, 64);
  223. }
  224. Unpacker.prototype.unpack_raw = function(size){
  225. if ( this.length < this.index + size){
  226. throw new Error('BinaryPackFailure: index is out of range'
  227. + ' ' + this.index + ' ' + size + ' ' + this.length);
  228. }
  229. var buf = this.dataBuffer.slice(this.index, this.index + size);
  230. this.index += size;
  231. //buf = util.bufferToString(buf);
  232. return buf;
  233. }
  234. Unpacker.prototype.unpack_string = function(size){
  235. var bytes = this.read(size);
  236. var i = 0, str = '', c, code;
  237. while(i < size){
  238. c = bytes[i];
  239. if ( c < 128){
  240. str += String.fromCharCode(c);
  241. i++;
  242. } else if ((c ^ 0xc0) < 32){
  243. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  244. str += String.fromCharCode(code);
  245. i += 2;
  246. } else {
  247. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  248. (bytes[i+2] & 63);
  249. str += String.fromCharCode(code);
  250. i += 3;
  251. }
  252. }
  253. this.index += size;
  254. return str;
  255. }
  256. Unpacker.prototype.unpack_array = function(size){
  257. var objects = new Array(size);
  258. for(var i = 0; i < size ; i++){
  259. objects[i] = this.unpack();
  260. }
  261. return objects;
  262. }
  263. Unpacker.prototype.unpack_map = function(size){
  264. var map = {};
  265. for(var i = 0; i < size ; i++){
  266. var key = this.unpack();
  267. var value = this.unpack();
  268. map[key] = value;
  269. }
  270. return map;
  271. }
  272. Unpacker.prototype.unpack_float = function(){
  273. var uint32 = this.unpack_uint32();
  274. var sign = uint32 >> 31;
  275. var exp = ((uint32 >> 23) & 0xff) - 127;
  276. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  277. return (sign == 0 ? 1 : -1) *
  278. fraction * Math.pow(2, exp - 23);
  279. }
  280. Unpacker.prototype.unpack_double = function(){
  281. var h32 = this.unpack_uint32();
  282. var l32 = this.unpack_uint32();
  283. var sign = h32 >> 31;
  284. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  285. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  286. var frac = hfrac * Math.pow(2, exp - 20) +
  287. l32 * Math.pow(2, exp - 52);
  288. return (sign == 0 ? 1 : -1) * frac;
  289. }
  290. Unpacker.prototype.read = function(length){
  291. var j = this.index;
  292. if (j + length <= this.length) {
  293. return this.dataView.subarray(j, j + length);
  294. } else {
  295. throw new Error('BinaryPackFailure: read index out of range');
  296. }
  297. }
  298. function Packer (){
  299. this.bufferBuilder = new BufferBuilder();
  300. }
  301. Packer.prototype.pack = function(value){
  302. var type = typeof(value);
  303. if (type == 'string'){
  304. this.pack_string(value);
  305. } else if (type == 'number'){
  306. if (Math.floor(value) === value){
  307. this.pack_integer(value);
  308. } else{
  309. this.pack_double(value);
  310. }
  311. } else if (type == 'boolean'){
  312. if (value === true){
  313. this.bufferBuilder.append(0xc3);
  314. } else if (value === false){
  315. this.bufferBuilder.append(0xc2);
  316. }
  317. } else if (type == 'undefined'){
  318. this.bufferBuilder.append(0xc0);
  319. } else if (type == 'object'){
  320. if (value === null){
  321. this.bufferBuilder.append(0xc0);
  322. } else {
  323. var constructor = value.constructor;
  324. if (constructor == Array){
  325. this.pack_array(value);
  326. } else if (constructor == Blob || constructor == File) {
  327. this.pack_bin(value);
  328. } else if (constructor == ArrayBuffer) {
  329. if(binaryFeatures.useArrayBufferView) {
  330. this.pack_bin(new Uint8Array(value));
  331. } else {
  332. this.pack_bin(value);
  333. }
  334. } else if ('BYTES_PER_ELEMENT' in value){
  335. if(binaryFeatures.useArrayBufferView) {
  336. this.pack_bin(value);
  337. } else {
  338. this.pack_bin(value.buffer);
  339. }
  340. } else if (constructor == Object){
  341. this.pack_object(value);
  342. } else if (constructor == Date){
  343. this.pack_string(value.toString());
  344. } else if (typeof value.toBinaryPack == 'function'){
  345. this.bufferBuilder.append(value.toBinaryPack());
  346. } else {
  347. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  348. }
  349. }
  350. } else {
  351. throw new Error('Type "' + type + '" not yet supported');
  352. }
  353. return this.bufferBuilder.getBuffer();
  354. }
  355. Packer.prototype.pack_bin = function(blob){
  356. var length = blob.length || blob.byteLength || blob.size;
  357. if (length <= 0x0f){
  358. this.pack_uint8(0xa0 + length);
  359. } else if (length <= 0xffff){
  360. this.bufferBuilder.append(0xda) ;
  361. this.pack_uint16(length);
  362. } else if (length <= 0xffffffff){
  363. this.bufferBuilder.append(0xdb);
  364. this.pack_uint32(length);
  365. } else{
  366. throw new Error('Invalid length');
  367. return;
  368. }
  369. this.bufferBuilder.append(blob);
  370. }
  371. Packer.prototype.pack_string = function(str){
  372. var length = str.length;
  373. if (length <= 0x0f){
  374. this.pack_uint8(0xb0 + length);
  375. } else if (length <= 0xffff){
  376. this.bufferBuilder.append(0xd8) ;
  377. this.pack_uint16(length);
  378. } else if (length <= 0xffffffff){
  379. this.bufferBuilder.append(0xd9);
  380. this.pack_uint32(length);
  381. } else{
  382. throw new Error('Invalid length');
  383. return;
  384. }
  385. this.bufferBuilder.append(str);
  386. }
  387. Packer.prototype.pack_array = function(ary){
  388. var length = ary.length;
  389. if (length <= 0x0f){
  390. this.pack_uint8(0x90 + length);
  391. } else if (length <= 0xffff){
  392. this.bufferBuilder.append(0xdc)
  393. this.pack_uint16(length);
  394. } else if (length <= 0xffffffff){
  395. this.bufferBuilder.append(0xdd);
  396. this.pack_uint32(length);
  397. } else{
  398. throw new Error('Invalid length');
  399. }
  400. for(var i = 0; i < length ; i++){
  401. this.pack(ary[i]);
  402. }
  403. }
  404. Packer.prototype.pack_integer = function(num){
  405. if ( -0x20 <= num && num <= 0x7f){
  406. this.bufferBuilder.append(num & 0xff);
  407. } else if (0x00 <= num && num <= 0xff){
  408. this.bufferBuilder.append(0xcc);
  409. this.pack_uint8(num);
  410. } else if (-0x80 <= num && num <= 0x7f){
  411. this.bufferBuilder.append(0xd0);
  412. this.pack_int8(num);
  413. } else if ( 0x0000 <= num && num <= 0xffff){
  414. this.bufferBuilder.append(0xcd);
  415. this.pack_uint16(num);
  416. } else if (-0x8000 <= num && num <= 0x7fff){
  417. this.bufferBuilder.append(0xd1);
  418. this.pack_int16(num);
  419. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  420. this.bufferBuilder.append(0xce);
  421. this.pack_uint32(num);
  422. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  423. this.bufferBuilder.append(0xd2);
  424. this.pack_int32(num);
  425. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  426. this.bufferBuilder.append(0xd3);
  427. this.pack_int64(num);
  428. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  429. this.bufferBuilder.append(0xcf);
  430. this.pack_uint64(num);
  431. } else{
  432. throw new Error('Invalid integer');
  433. }
  434. }
  435. Packer.prototype.pack_double = function(num){
  436. var sign = 0;
  437. if (num < 0){
  438. sign = 1;
  439. num = -num;
  440. }
  441. var exp = Math.floor(Math.log(num) / Math.LN2);
  442. var frac0 = num / Math.pow(2, exp) - 1;
  443. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  444. var b32 = Math.pow(2, 32);
  445. var h32 = (sign << 31) | ((exp+1023) << 20) |
  446. (frac1 / b32) & 0x0fffff;
  447. var l32 = frac1 % b32;
  448. this.bufferBuilder.append(0xcb);
  449. this.pack_int32(h32);
  450. this.pack_int32(l32);
  451. }
  452. Packer.prototype.pack_object = function(obj){
  453. var keys = Object.keys(obj);
  454. var length = keys.length;
  455. if (length <= 0x0f){
  456. this.pack_uint8(0x80 + length);
  457. } else if (length <= 0xffff){
  458. this.bufferBuilder.append(0xde);
  459. this.pack_uint16(length);
  460. } else if (length <= 0xffffffff){
  461. this.bufferBuilder.append(0xdf);
  462. this.pack_uint32(length);
  463. } else{
  464. throw new Error('Invalid length');
  465. }
  466. for(var prop in obj){
  467. if (obj.hasOwnProperty(prop)){
  468. this.pack(prop);
  469. this.pack(obj[prop]);
  470. }
  471. }
  472. }
  473. Packer.prototype.pack_uint8 = function(num){
  474. this.bufferBuilder.append(num);
  475. }
  476. Packer.prototype.pack_uint16 = function(num){
  477. this.bufferBuilder.append(num >> 8);
  478. this.bufferBuilder.append(num & 0xff);
  479. }
  480. Packer.prototype.pack_uint32 = function(num){
  481. var n = num & 0xffffffff;
  482. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  483. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  484. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  485. this.bufferBuilder.append((n & 0x000000ff));
  486. }
  487. Packer.prototype.pack_uint64 = function(num){
  488. var high = num / Math.pow(2, 32);
  489. var low = num % Math.pow(2, 32);
  490. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  491. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  492. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  493. this.bufferBuilder.append((high & 0x000000ff));
  494. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  495. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  496. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  497. this.bufferBuilder.append((low & 0x000000ff));
  498. }
  499. Packer.prototype.pack_int8 = function(num){
  500. this.bufferBuilder.append(num & 0xff);
  501. }
  502. Packer.prototype.pack_int16 = function(num){
  503. this.bufferBuilder.append((num & 0xff00) >> 8);
  504. this.bufferBuilder.append(num & 0xff);
  505. }
  506. Packer.prototype.pack_int32 = function(num){
  507. this.bufferBuilder.append((num >>> 24) & 0xff);
  508. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  509. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  510. this.bufferBuilder.append((num & 0x000000ff));
  511. }
  512. Packer.prototype.pack_int64 = function(num){
  513. var high = Math.floor(num / Math.pow(2, 32));
  514. var low = num % Math.pow(2, 32);
  515. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  516. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  517. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  518. this.bufferBuilder.append((high & 0x000000ff));
  519. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  520. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  521. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  522. this.bufferBuilder.append((low & 0x000000ff));
  523. }
  524. /**
  525. * Light EventEmitter. Ported from Node.js/events.js
  526. * Eric Zhang
  527. */
  528. /**
  529. * EventEmitter class
  530. * Creates an object with event registering and firing methods
  531. */
  532. function EventEmitter() {
  533. // Initialise required storage variables
  534. this._events = {};
  535. }
  536. var isArray = Array.isArray;
  537. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  538. if ('function' !== typeof listener) {
  539. throw new Error('addListener only takes instances of Function');
  540. }
  541. // To avoid recursion in the case that type == "newListeners"! Before
  542. // adding it to the listeners, first emit "newListeners".
  543. this.emit('newListener', type, typeof listener.listener === 'function' ?
  544. listener.listener : listener);
  545. if (!this._events[type]) {
  546. // Optimize the case of one listener. Don't need the extra array object.
  547. this._events[type] = listener;
  548. } else if (isArray(this._events[type])) {
  549. // If we've already got an array, just append.
  550. this._events[type].push(listener);
  551. } else {
  552. // Adding the second element, need to change to array.
  553. this._events[type] = [this._events[type], listener];
  554. }
  555. };
  556. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  557. EventEmitter.prototype.once = function(type, listener, scope) {
  558. if ('function' !== typeof listener) {
  559. throw new Error('.once only takes instances of Function');
  560. }
  561. var self = this;
  562. function g() {
  563. self.removeListener(type, g);
  564. listener.apply(this, arguments);
  565. };
  566. g.listener = listener;
  567. self.on(type, g);
  568. return this;
  569. };
  570. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  571. if ('function' !== typeof listener) {
  572. throw new Error('removeListener only takes instances of Function');
  573. }
  574. // does not use listeners(), so no side effect of creating _events[type]
  575. if (!this._events[type]) return this;
  576. var list = this._events[type];
  577. if (isArray(list)) {
  578. var position = -1;
  579. for (var i = 0, length = list.length; i < length; i++) {
  580. if (list[i] === listener ||
  581. (list[i].listener && list[i].listener === listener))
  582. {
  583. position = i;
  584. break;
  585. }
  586. }
  587. if (position < 0) return this;
  588. list.splice(position, 1);
  589. if (list.length == 0)
  590. delete this._events[type];
  591. } else if (list === listener ||
  592. (list.listener && list.listener === listener))
  593. {
  594. delete this._events[type];
  595. }
  596. return this;
  597. };
  598. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  599. EventEmitter.prototype.removeAllListeners = function(type) {
  600. if (arguments.length === 0) {
  601. this._events = {};
  602. return this;
  603. }
  604. // does not use listeners(), so no side effect of creating _events[type]
  605. if (type && this._events && this._events[type]) this._events[type] = null;
  606. return this;
  607. };
  608. EventEmitter.prototype.listeners = function(type) {
  609. if (!this._events[type]) this._events[type] = [];
  610. if (!isArray(this._events[type])) {
  611. this._events[type] = [this._events[type]];
  612. }
  613. return this._events[type];
  614. };
  615. EventEmitter.prototype.emit = function(type) {
  616. var type = arguments[0];
  617. var handler = this._events[type];
  618. if (!handler) return false;
  619. if (typeof handler == 'function') {
  620. switch (arguments.length) {
  621. // fast cases
  622. case 1:
  623. handler.call(this);
  624. break;
  625. case 2:
  626. handler.call(this, arguments[1]);
  627. break;
  628. case 3:
  629. handler.call(this, arguments[1], arguments[2]);
  630. break;
  631. // slower
  632. default:
  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. handler.apply(this, args);
  637. }
  638. return true;
  639. } else if (isArray(handler)) {
  640. var l = arguments.length;
  641. var args = new Array(l - 1);
  642. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  643. var listeners = handler.slice();
  644. for (var i = 0, l = listeners.length; i < l; i++) {
  645. listeners[i].apply(this, args);
  646. }
  647. return true;
  648. } else {
  649. return false;
  650. }
  651. };
  652. var util = {
  653. inherits: function(ctor, superCtor) {
  654. ctor.super_ = superCtor;
  655. ctor.prototype = Object.create(superCtor.prototype, {
  656. constructor: {
  657. value: ctor,
  658. enumerable: false,
  659. writable: true,
  660. configurable: true
  661. }
  662. });
  663. },
  664. extend: function(dest, source) {
  665. for(var key in source) {
  666. if(source.hasOwnProperty(key)) {
  667. dest[key] = source[key];
  668. }
  669. }
  670. return dest;
  671. },
  672. pack: BinaryPack.pack,
  673. unpack: BinaryPack.unpack,
  674. randomPort: function() {
  675. return Math.round(Math.random() * 60535) + 5000;
  676. },
  677. setZeroTimeout: (function(global) {
  678. var timeouts = [];
  679. var messageName = 'zero-timeout-message';
  680. // Like setTimeout, but only takes a function argument. There's
  681. // no time argument (always zero) and no arguments (you have to
  682. // use a closure).
  683. function setZeroTimeoutPostMessage(fn) {
  684. timeouts.push(fn);
  685. global.postMessage(messageName, '*');
  686. }
  687. function handleMessage(event) {
  688. if (event.source == global && event.data == messageName) {
  689. if (event.stopPropagation) {
  690. event.stopPropagation();
  691. }
  692. if (timeouts.length) {
  693. timeouts.shift()();
  694. }
  695. }
  696. }
  697. if (global.addEventListener) {
  698. global.addEventListener('message', handleMessage, true);
  699. } else if (global.attachEvent) {
  700. global.attachEvent('onmessage', handleMessage);
  701. }
  702. return setZeroTimeoutPostMessage;
  703. }(this))
  704. };
  705. var RTCPeerConnection = null;
  706. var getUserMedia = null;
  707. var attachMediaStream = null;
  708. var browserisms = null;
  709. if (navigator.mozGetUserMedia) {
  710. browserisms = 'Firefox'
  711. RTCPeerConnection = mozRTCPeerConnection;
  712. getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  713. attachMediaStream = function(element, stream) {
  714. console.log("Attaching media stream");
  715. element.mozSrcObject = stream;
  716. element.play();
  717. };
  718. } else if (navigator.webkitGetUserMedia) {
  719. browserisms = 'Webkit'
  720. RTCPeerConnection = webkitRTCPeerConnection;
  721. getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  722. attachMediaStream = function(element, stream) {
  723. element.src = webkitURL.createObjectURL(stream);
  724. };
  725. }
  726. exports.RTCPeerConnection = RTCPeerConnection;
  727. exports.getUserMedia = getUserMedia;
  728. exports.attachMediaStream = attachMediaStream;
  729. exports.browserisms = browserisms;
  730. function Peer(options) {
  731. if (!(this instanceof Peer)) return new Peer(options);
  732. EventEmitter.call(this);
  733. this._config = options.config || { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] };
  734. this._peer = options.source || null;
  735. this._video = options.video;
  736. this._data = options.data != undefined ? options.data : true;
  737. this._audio = options.audio;
  738. this._pc = null;
  739. this._id = null;
  740. this._dc = null;
  741. this._socket = new WebSocket(options.ws || 'ws://localhost');
  742. var self = this;
  743. this._socket.onopen = function() {
  744. self.socketInit();
  745. };
  746. // Testing firefox.
  747. // MULTICONNECTION doesn't work still.
  748. if (browserisms == 'Firefox' && !options.source) {
  749. if (!Peer.usedPorts) {
  750. Peer.usedPorts = [];
  751. }
  752. this.localPort = util.randomPort();
  753. while (Peer.usedPorts.indexOf(this.localPort) != -1) {
  754. this.localPort = util.randomPort();
  755. }
  756. this.remotePort = util.randomPort();
  757. while (this.remotePort == this.localPort ||
  758. Peer.usedPorts.indexOf(this.localPort) != -1) {
  759. this.remotePort = util.randomPort();
  760. }
  761. Peer.usedPorts.push(this.remotePort);
  762. Peer.usedPorts.push(this.localPort);
  763. }
  764. };
  765. util.inherits(Peer, EventEmitter);
  766. /** Start up websocket communications. */
  767. Peer.prototype.socketInit = function() {
  768. var self = this;
  769. // Multiple sinks to one source.
  770. if (!!this._peer) {
  771. this._socket.send(JSON.stringify({
  772. type: 'SINK',
  773. source: this._peer,
  774. isms: browserisms
  775. }));
  776. this._socket.onmessage = function(event) {
  777. var message = JSON.parse(event.data);
  778. switch (message.type) {
  779. case 'SINK-ID':
  780. self._id = message.id;
  781. self.emit('ready', self._id);
  782. self.startPeerConnection();
  783. break;
  784. case 'OFFER':
  785. var sdp = message.sdp;
  786. try {
  787. sdp = new RTCSessionDescription(message.sdp);
  788. } catch(e) {
  789. console.log('Firefox');
  790. }
  791. self._pc.setRemoteDescription(sdp, function() {
  792. console.log('setRemoteDescription: offer');
  793. // If we also have to set up a stream on the sink end, do so.
  794. self.handleStream(false, function() {
  795. self.maybeBrowserisms(false);
  796. });
  797. }, function(err) {
  798. console.log('failed to setRemoteDescription with offer, ', err);
  799. });
  800. break;
  801. case 'CANDIDATE':
  802. console.log(message.candidate);
  803. var candidate = new RTCIceCandidate(message.candidate);
  804. self._pc.addIceCandidate(candidate);
  805. break;
  806. case 'PORT':
  807. if (browserisms && browserisms == 'Firefox') {
  808. if (!Peer.usedPorts) {
  809. Peer.usedPorts = [];
  810. }
  811. Peer.usedPorts.push(message.local);
  812. Peer.usedPorts.push(message.remote);
  813. self._pc.connectDataConnection(message.local, message.remote);
  814. break;
  815. }
  816. case 'DEFAULT':
  817. console.log('SINK: unrecognized message ', message.type);
  818. break;
  819. }
  820. };
  821. } else {
  822. // Otherwise, this sink is the originator to another sink and should wait
  823. // for an alert.
  824. this._socket.send(JSON.stringify({
  825. type: 'SOURCE',
  826. isms: browserisms
  827. }));
  828. this._socket.onmessage = function(event) {
  829. var message = JSON.parse(event.data);
  830. switch (message.type) {
  831. case 'SOURCE-ID':
  832. self._id = message.id;
  833. self.emit('ready', self._id);
  834. break;
  835. case 'SINK-CONNECTED':
  836. self._peer = message.sink;
  837. self.startPeerConnection();
  838. self.handleStream(true, function() {
  839. self.maybeBrowserisms(true);
  840. });
  841. break;
  842. case 'ANSWER':
  843. var sdp = message.sdp;
  844. try {
  845. sdp = new RTCSessionDescription(message.sdp);
  846. } catch(e) {
  847. console.log('Firefox');
  848. }
  849. self._pc.setRemoteDescription(sdp, function() {
  850. console.log('setRemoteDescription: answer');
  851. // Firefoxism
  852. if (browserisms == 'Firefox') {
  853. self._pc.connectDataConnection(self.localPort, self.remotePort);
  854. self._socket.send(JSON.stringify({
  855. type: 'PORT',
  856. dst: self._peer,
  857. remote: self.localPort,
  858. local: self.remotePort
  859. }));
  860. }
  861. console.log('ORIGINATOR: PeerConnection success');
  862. }, function(err) {
  863. console.log('failed to setRemoteDescription, ', err);
  864. });
  865. break;
  866. case 'CANDIDATE':
  867. console.log(message.candidate);
  868. var candidate = new RTCIceCandidate(message.candidate);
  869. self._pc.addIceCandidate(candidate);
  870. break;
  871. case 'DEFAULT':
  872. console.log('ORIGINATOR: message not recognized ', message.type);
  873. }
  874. };
  875. }
  876. // Makes sure things clean up neatly.
  877. window.onbeforeunload = function() {
  878. if (!!self._pc) {
  879. self._pc.close();
  880. }
  881. if (!!self._socket && !!self._peer) {
  882. self._socket.send(JSON.stringify({ type: 'LEAVE', dst: self._peer }));
  883. if (!!self._dc) {
  884. self._dc.close();
  885. }
  886. }
  887. }
  888. };
  889. /** Takes care of ice handlers. */
  890. Peer.prototype.setupIce = function() {
  891. var self = this;
  892. this._pc.onicecandidate = function(event) {
  893. console.log('candidates received');
  894. if (event.candidate) {
  895. self._socket.send(JSON.stringify({
  896. type: 'CANDIDATE',
  897. candidate: event.candidate,
  898. dst: self._peer
  899. }));
  900. } else {
  901. console.log("End of candidates.");
  902. }
  903. };
  904. };
  905. /** Starts a PeerConnection and sets up handlers. */
  906. Peer.prototype.startPeerConnection = function() {
  907. this._pc = new RTCPeerConnection(this._config, { optional:[ { RtpDataChannels: true } ]});
  908. this.setupIce();
  909. this.setupAudioVideo();
  910. };
  911. /** Decide whether to handle Firefoxisms. */
  912. Peer.prototype.maybeBrowserisms = function(originator) {
  913. var self = this;
  914. if (browserisms == 'Firefox' && !this._video && !this._audio && !this._stream) {
  915. getUserMedia({ audio: true, fake: true }, function(s) {
  916. self._pc.addStream(s);
  917. if (originator) {
  918. self.makeOffer();
  919. } else {
  920. self.makeAnswer();
  921. }
  922. }, function(err) { console.log('crap'); });
  923. } else {
  924. if (originator) {
  925. this.makeOffer();
  926. } else {
  927. this.makeAnswer();
  928. }
  929. }
  930. }
  931. /** Create an answer for PC. */
  932. Peer.prototype.makeAnswer = function() {
  933. var self = this;
  934. this._pc.createAnswer(function(answer) {
  935. console.log('createAnswer');
  936. self._pc.setLocalDescription(answer, function() {
  937. console.log('setLocalDescription: answer');
  938. self._socket.send(JSON.stringify({
  939. type: 'ANSWER',
  940. src: self._id,
  941. sdp: answer,
  942. dst: self._peer
  943. }));
  944. }, function(err) {
  945. console.log('failed to setLocalDescription, ', err)
  946. });
  947. }, function(err) {
  948. console.log('failed to create answer, ', err)
  949. });
  950. };
  951. /** Create an offer for PC. */
  952. Peer.prototype.makeOffer = function() {
  953. var self = this;
  954. this._pc.createOffer(function(offer) {
  955. console.log('createOffer')
  956. self._pc.setLocalDescription(offer, function() {
  957. console.log('setLocalDescription: offer');
  958. self._socket.send(JSON.stringify({
  959. type: 'OFFER',
  960. sdp: offer,
  961. dst: self._peer,
  962. src: self._id
  963. }));
  964. }, function(err) {
  965. console.log('failed to setLocalDescription, ', err);
  966. });
  967. });
  968. };
  969. /** Sets up A/V stream handler. */
  970. Peer.prototype.setupAudioVideo = function() {
  971. var self = this;
  972. console.log('onaddstream handler added');
  973. this._pc.onaddstream = function(obj) {
  974. console.log('Remote stream added');
  975. this._stream = true;
  976. self.emit('remotestream', obj.type, obj.stream);
  977. };
  978. };
  979. /** Handle the different types of streams requested by user. */
  980. Peer.prototype.handleStream = function(originator, cb) {
  981. if (this._data) {
  982. this.setupDataChannel(originator);
  983. }
  984. this.getAudioVideo(originator, cb);
  985. };
  986. /** Get A/V streams. */
  987. Peer.prototype.getAudioVideo = function(originator, cb) {
  988. var self = this;
  989. if (this._video) {
  990. getUserMedia({ video: true }, function(vstream) {
  991. self._pc.addStream(vstream);
  992. console.log('Local video stream added');
  993. self.emit('localstream', 'video', vstream);
  994. if (self._audio) {
  995. getUserMedia({ audio: true }, function(astream) {
  996. self._pc.addStream(astream);
  997. console.log('Local audio stream added');
  998. self.emit('localstream', 'audio', astream);
  999. cb();
  1000. }, function(err) { console.log('Audio cannot start'); cb(); });
  1001. } else {
  1002. cb();
  1003. }
  1004. }, function(err) { console.log('Video cannot start', err); cb(); });
  1005. } else if (this._audio) {
  1006. getUserMedia({ audio: true }, function(astream) {
  1007. self._pc.addStream(astream);
  1008. self.emit('localstream', 'audio', astream);
  1009. cb();
  1010. }, function(err) { console.log('Audio cannot start'); cb(); });
  1011. } else {
  1012. cb();
  1013. }
  1014. };
  1015. /** Sets up DataChannel handlers. */
  1016. Peer.prototype.setupDataChannel = function(originator, cb) {
  1017. var self = this;
  1018. if (originator) {
  1019. /** ORIGINATOR SETUP */
  1020. if (browserisms == 'Webkit') {
  1021. this._pc.onstatechange = function() {
  1022. console.log('State Change: ', self._pc.readyState);
  1023. /*if (self._pc.readyState == 'active') {
  1024. console.log('ORIGINATOR: active state detected');
  1025. self._dc = self._pc.createDataChannel('StreamAPI', { reliable: false });
  1026. self._dc.binaryType = 'blob';
  1027. if (!!self._handlers['connection']) {
  1028. self._handlers['connection'](self._peer);
  1029. }
  1030. self._dc.onmessage = function(e) {
  1031. self.handleDataMessage(e);
  1032. };
  1033. }*/
  1034. }
  1035. } else {
  1036. this._pc.onconnection = function() {
  1037. console.log('ORIGINATOR: onconnection triggered');
  1038. self.startDataChannel();
  1039. };
  1040. }
  1041. } else {
  1042. /** TARGET SETUP */
  1043. this._pc.ondatachannel = function(dc) {
  1044. console.log('SINK: ondatachannel triggered');
  1045. self._dc = dc;
  1046. self._dc.binaryType = 'blob';
  1047. self.emit('connection', self._peer);
  1048. self._dc.onmessage = function(e) {
  1049. self.handleDataMessage(e);
  1050. };
  1051. };
  1052. this._pc.onconnection = function() {
  1053. console.log('SINK: onconnection triggered');
  1054. };
  1055. }
  1056. this._pc.onclosedconnection = function() {
  1057. // Remove socket handlers perhaps.
  1058. };
  1059. };
  1060. Peer.prototype.startDataChannel = function() {
  1061. var self = this;
  1062. this._dc = this._pc.createDataChannel(this._peer, { reliable: false });
  1063. this._dc.binaryType = 'blob';
  1064. this.emit('connection', this._peer);
  1065. this._dc.onmessage = function(e) {
  1066. self.handleDataMessage(e);
  1067. };
  1068. };
  1069. /** Allows user to send data. */
  1070. Peer.prototype.send = function(data) {
  1071. var ab = BinaryPack.pack(data);
  1072. this._dc.send(ab);
  1073. }
  1074. // Handles a DataChannel message.
  1075. // TODO: have these extend Peer, which will impl these generic handlers.
  1076. Peer.prototype.handleDataMessage = function(e) {
  1077. var self = this;
  1078. var fr = new FileReader();
  1079. fr.onload = function(evt) {
  1080. var ab = evt.target.result;
  1081. var data = BinaryPack.unpack(ab);
  1082. self.emit('data', data);
  1083. };
  1084. fr.readAsArrayBuffer(e.data);
  1085. }
  1086. exports.Peer = Peer;
  1087. })(this);