peer.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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. debug: false,
  654. inherits: function(ctor, superCtor) {
  655. ctor.super_ = superCtor;
  656. ctor.prototype = Object.create(superCtor.prototype, {
  657. constructor: {
  658. value: ctor,
  659. enumerable: false,
  660. writable: true,
  661. configurable: true
  662. }
  663. });
  664. },
  665. extend: function(dest, source) {
  666. for(var key in source) {
  667. if(source.hasOwnProperty(key)) {
  668. dest[key] = source[key];
  669. }
  670. }
  671. return dest;
  672. },
  673. pack: BinaryPack.pack,
  674. unpack: BinaryPack.unpack,
  675. randomPort: function() {
  676. return Math.round(Math.random() * 60535) + 5000;
  677. },
  678. log: function () {
  679. if (util.debug) {
  680. for (var i = 0; i < arguments.length; i++) {
  681. console.log('*', i, '-- ', arguments[i]);
  682. }
  683. }
  684. },
  685. setZeroTimeout: (function(global) {
  686. var timeouts = [];
  687. var messageName = 'zero-timeout-message';
  688. // Like setTimeout, but only takes a function argument. There's
  689. // no time argument (always zero) and no arguments (you have to
  690. // use a closure).
  691. function setZeroTimeoutPostMessage(fn) {
  692. timeouts.push(fn);
  693. global.postMessage(messageName, '*');
  694. }
  695. function handleMessage(event) {
  696. if (event.source == global && event.data == messageName) {
  697. if (event.stopPropagation) {
  698. event.stopPropagation();
  699. }
  700. if (timeouts.length) {
  701. timeouts.shift()();
  702. }
  703. }
  704. }
  705. if (global.addEventListener) {
  706. global.addEventListener('message', handleMessage, true);
  707. } else if (global.attachEvent) {
  708. global.attachEvent('onmessage', handleMessage);
  709. }
  710. return setZeroTimeoutPostMessage;
  711. }(this)),
  712. blobToArrayBuffer: function(blob, cb){
  713. var fr = new FileReader();
  714. fr.onload = function(evt) {
  715. cb(evt.target.result);
  716. };
  717. fr.readAsArrayBuffer(blob);
  718. },
  719. blobToBinaryString: function(blob, cb){
  720. var fr = new FileReader();
  721. fr.onload = function(evt) {
  722. cb(evt.target.result);
  723. };
  724. fr.readAsBinaryString(blob);
  725. },
  726. binaryStringToArrayBuffer: function(binary) {
  727. var byteArray = new Uint8Array(binary.length);
  728. for (var i = 0; i < binary.length; i++) {
  729. byteArray[i] = binary.charCodeAt(i) & 0xff;
  730. }
  731. return byteArray.buffer;
  732. }
  733. };
  734. var RTCPeerConnection = null;
  735. var getUserMedia = null;
  736. var attachMediaStream = null;
  737. var browserisms = null;
  738. if (navigator.mozGetUserMedia) {
  739. browserisms = 'Firefox'
  740. RTCPeerConnection = mozRTCPeerConnection;
  741. getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  742. attachMediaStream = function(element, stream) {
  743. console.log("Attaching media stream");
  744. element.mozSrcObject = stream;
  745. element.play();
  746. };
  747. } else if (navigator.webkitGetUserMedia) {
  748. browserisms = 'Webkit'
  749. RTCPeerConnection = webkitRTCPeerConnection;
  750. getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  751. attachMediaStream = function(element, stream) {
  752. element.src = webkitURL.createObjectURL(stream);
  753. };
  754. }
  755. exports.RTCPeerConnection = RTCPeerConnection;
  756. exports.getUserMedia = getUserMedia;
  757. exports.attachMediaStream = attachMediaStream;
  758. exports.browserisms = browserisms;
  759. function Peer(options) {
  760. if (!(this instanceof Peer)) return new Peer(options);
  761. EventEmitter.call(this);
  762. options = util.extend({
  763. debug: false,
  764. peer: 'ws://localhost'
  765. }, options);
  766. this.options = options;
  767. util.debug = options.debug;
  768. this._id = null;
  769. this._socket = new WebSocket(options.ws);
  770. this._socketInit();
  771. // Connections
  772. this.connections = {};
  773. };
  774. util.inherits(Peer, EventEmitter);
  775. /** Start up websocket communications. */
  776. Peer.prototype._socketInit = function() {
  777. var self = this;
  778. this._socket.onmessage = function(event) {
  779. var message = JSON.parse(event.data);
  780. var peer = message.src;
  781. var connection = self.connections[peer];
  782. switch (message.type) {
  783. case 'ID':
  784. self._id = message.id;
  785. self.emit('ready', self._id);
  786. break;
  787. case 'OFFER':
  788. var options = {
  789. metadata: message.metadata,
  790. sdp: message.sdp
  791. };
  792. var connection = new DataConnection(self._id, peer, self._socket, function(err, connection) {
  793. if (!err) {
  794. self.emit('connection', connection);
  795. }
  796. }, options);
  797. self.connections[peer] = connection;
  798. break;
  799. case 'ANSWER':
  800. if (connection) connection.handleSDP(message);
  801. break;
  802. case 'CANDIDATE':
  803. if (connection) connection.handleCandidate(message);
  804. break;
  805. case 'LEAVE':
  806. if (connection) connection.handleLeave(message);
  807. break;
  808. case 'PORT':
  809. if (browserisms == 'Firefox') {
  810. connection.handlePort(message);
  811. break;
  812. }
  813. case 'DEFAULT':
  814. util.log('PEER: unrecognized message ', message.type);
  815. break;
  816. }
  817. };
  818. this._socket.onopen = function() {
  819. // Announce as a PEER to receive an ID.
  820. self._socket.send(JSON.stringify({
  821. type: 'PEER'
  822. }));
  823. };
  824. };
  825. Peer.prototype.connect = function(peer, metadata, cb) {
  826. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  827. var options = {
  828. metadata: metadata
  829. };
  830. var connection = new DataConnection(this._id, peer, this._socket, cb, options);
  831. this.connections[peer] = connection;
  832. };
  833. exports.Peer = Peer;
  834. function DataConnection(id, peer, socket, cb, options) {
  835. if (!(this instanceof DataConnection)) return new DataConnection(options);
  836. EventEmitter.call(this);
  837. options = util.extend({
  838. debug: false,
  839. ice: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  840. }, options);
  841. this.options = options;
  842. // Is this the originator?
  843. this._id = id;
  844. this._peer = peer;
  845. this._originator = (options.sdp == undefined);
  846. this._cb = cb;
  847. this.metadata = options.metadata;
  848. // Set up socket handlers.
  849. this._socket = socket;
  850. // Firefoxism: connectDataConnection ports.
  851. if (browserisms == 'Firefox') {
  852. this._firefoxPortSetup();
  853. }
  854. //
  855. // Set up PeerConnection.
  856. this._startPeerConnection();
  857. // Listen for ICE candidates
  858. this._setupIce();
  859. // Listen for negotiation needed
  860. this._setupOffer();
  861. // Listen or create a data channel
  862. this._setupDataChannel();
  863. var self = this;
  864. if (options.sdp) {
  865. this.handleSDP({type: 'OFFER', sdp: options.sdp});
  866. if (browserisms !== 'Firefox') {
  867. this._makeAnswer();
  868. }
  869. }
  870. if (browserisms == 'Firefox') {
  871. this._firefoxAdditional();
  872. }
  873. };
  874. util.inherits(DataConnection, EventEmitter);
  875. DataConnection.prototype._setupOffer = function() {
  876. var self = this;
  877. util.log('Listening for `negotiationneeded`');
  878. this._pc.onnegotiationneeded = function() {
  879. util.log('`negotiationneeded` triggered');
  880. self._makeOffer();
  881. };
  882. }
  883. DataConnection.prototype._setupDataChannel = function() {
  884. var self = this;
  885. if (this._originator) {
  886. util.log('Creating data channel');
  887. this._dc = this._pc.createDataChannel(this._peer, { reliable: false });
  888. this._configureDataChannel();
  889. } else {
  890. util.log('Listening for data channel');
  891. this._pc.ondatachannel = function(evt) {
  892. util.log('Received data channel');
  893. self._dc = evt.channel;
  894. self._configureDataChannel();
  895. };
  896. }
  897. };
  898. DataConnection.prototype.handleSDP = function(message) {
  899. var sdp = message.sdp;
  900. if (browserisms != 'Firefox') {
  901. sdp = new RTCSessionDescription(sdp);
  902. }
  903. var self = this;
  904. this._pc.setRemoteDescription(sdp, function() {
  905. util.log('Set remoteDescription: ' + message.type);
  906. // Firefoxism
  907. if (message.type == 'ANSWER' && browserisms == 'Firefox') {
  908. self._pc.connectDataConnection(self.localPort, self.remotePort);
  909. self._socket.send(JSON.stringify({
  910. type: 'PORT',
  911. dst: self._peer,
  912. src: self._id,
  913. remote: self.localPort,
  914. local: self.remotePort
  915. }));
  916. }
  917. }, function(err) {
  918. this._cb('Failed to setRemoteDescription');
  919. util.log('Failed to setRemoteDescription, ', err);
  920. });
  921. };
  922. DataConnection.prototype.handleCandidate = function(message) {
  923. var candidate = new RTCIceCandidate(message.candidate);
  924. this._pc.addIceCandidate(candidate);
  925. };
  926. DataConnection.prototype.handleLeave = function(message) {
  927. util.log('Peer ' + this._peer + ' disconnected');
  928. if (!!this._pc && this._pc.readyState != 'closed') {
  929. this._pc.close();
  930. this._pc = null;
  931. }
  932. if (!!this._dc && this._dc.readyState != 'closed') {
  933. this._dc.close();
  934. this._dc = null;
  935. }
  936. this.emit('close', this._peer);
  937. };
  938. DataConnection.prototype.handlePort = function(message) {
  939. if (!DataConnection.usedPorts) {
  940. DataConnection.usedPorts = [];
  941. }
  942. DataConnection.usedPorts.push(message.local);
  943. DataConnection.usedPorts.push(message.remote);
  944. this._pc.connectDataConnection(message.local, message.remote);
  945. };
  946. /** Starts a PeerConnection and sets up handlers. */
  947. DataConnection.prototype._startPeerConnection = function() {
  948. util.log('Creating RTCPeerConnection: ', this.options.ice);
  949. this._pc = new RTCPeerConnection(this.options.ice, { optional:[ { RtpDataChannels: true } ]});
  950. };
  951. /** Takes care of ice handlers. */
  952. DataConnection.prototype._setupIce = function() {
  953. util.log('Listening for ICE candidates');
  954. var self = this;
  955. this._pc.onicecandidate = function(evt) {
  956. if (evt.candidate) {
  957. util.log('Received ICE candidates');
  958. self._socket.send(JSON.stringify({
  959. type: 'CANDIDATE',
  960. candidate: evt.candidate,
  961. dst: self._peer,
  962. src: self._id
  963. }));
  964. }
  965. };
  966. };
  967. /** Sets up DataChannel handlers.
  968. DataConnection.prototype._setupDataChannel = function() {
  969. var self = this;
  970. if (this._originator) {
  971. if (browserisms == 'Webkit') {
  972. // TODO: figure out the right thing to do with this.
  973. this._pc.onstatechange = function() {
  974. util.log('State Change: ', self._pc.readyState);
  975. }
  976. } else {
  977. this._pc.onconnection = function() {
  978. util.log('ORIGINATOR: onconnection triggered');
  979. self._startDataChannel();
  980. };
  981. }
  982. } else {
  983. this._pc.onconnection = function() {
  984. util.log('SINK: onconnection triggered');
  985. };
  986. }
  987. this._pc.onclosedconnection = function() {
  988. // Remove socket handlers perhaps.
  989. self.emit('close', self._peer);
  990. };
  991. };
  992. */
  993. DataConnection.prototype._firefoxPortSetup = function() {
  994. if (!DataConnection.usedPorts) {
  995. DataConnection.usedPorts = [];
  996. }
  997. this.localPort = util.randomPort();
  998. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  999. this.localPort = util.randomPort();
  1000. }
  1001. this.remotePort = util.randomPort();
  1002. while (this.remotePort == this.localPort ||
  1003. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1004. this.remotePort = util.randomPort();
  1005. }
  1006. DataConnection.usedPorts.push(this.remotePort);
  1007. DataConnection.usedPorts.push(this.localPort);
  1008. }
  1009. DataConnection.prototype._configureDataChannel = function() {
  1010. var self = this;
  1011. if (browserisms == 'Firefox') {
  1012. this._dc.binaryType = 'blob';
  1013. }
  1014. this._dc.onopen = function() {
  1015. util.log('Data channel connection success');
  1016. self._cb(null, self);
  1017. };
  1018. this._dc.onmessage = function(e) {
  1019. self._handleDataMessage(e);
  1020. };
  1021. };
  1022. /** Decide whether to handle Firefoxisms. */
  1023. DataConnection.prototype._firefoxAdditional = function() {
  1024. var self = this;
  1025. getUserMedia({ audio: true, fake: true }, function(s) {
  1026. self._pc.addStream(s);
  1027. if (self._originator) {
  1028. self._makeOffer();
  1029. } else {
  1030. self._makeAnswer();
  1031. }
  1032. }, function(err) { util.log('Could not getUserMedia'); });
  1033. }
  1034. DataConnection.prototype._makeOffer = function() {
  1035. var self = this;
  1036. this._pc.createOffer(function(offer) {
  1037. util.log('Created offer');
  1038. self._pc.setLocalDescription(offer, function() {
  1039. util.log('Set localDescription to offer');
  1040. self._socket.send(JSON.stringify({
  1041. type: 'OFFER',
  1042. sdp: offer,
  1043. dst: self._peer,
  1044. src: self._id,
  1045. metadata: self._metadata
  1046. }));
  1047. }, function(err) {
  1048. self._cb('Failed to setLocalDescription');
  1049. util.log('Failed to setLocalDescription, ', err);
  1050. });
  1051. });
  1052. };
  1053. /** Create an answer for PC. */
  1054. DataConnection.prototype._makeAnswer = function() {
  1055. var self = this;
  1056. this._pc.createAnswer(function(answer) {
  1057. util.log('Created answer');
  1058. self._pc.setLocalDescription(answer, function() {
  1059. util.log('Set localDescription to answer');
  1060. self._socket.send(JSON.stringify({
  1061. type: 'ANSWER',
  1062. src: self._id,
  1063. sdp: answer,
  1064. dst: self._peer
  1065. }));
  1066. }, function(err) {
  1067. self._cb('Failed to setLocalDescription');
  1068. util.log('Failed to setLocalDescription, ', err)
  1069. });
  1070. }, function(err) {
  1071. self._cb('Failed to create answer');
  1072. util.log('Failed to create answer, ', err)
  1073. });
  1074. };
  1075. /** Allows user to send data. */
  1076. DataConnection.prototype.send = function(data) {
  1077. var self = this;
  1078. var blob = BinaryPack.pack(data);
  1079. if (browserisms == 'Webkit') {
  1080. util.blobToBinaryString(blob, function(str){
  1081. self._dc.send(str);
  1082. });
  1083. } else {
  1084. this._dc.send(blob);
  1085. }
  1086. };
  1087. // Handles a DataChannel message.
  1088. DataConnection.prototype._handleDataMessage = function(e) {
  1089. var self = this;
  1090. if (e.data.constructor == Blob) {
  1091. util.blobToArrayBuffer(e.data, function(ab) {
  1092. var data = BinaryPack.unpack(ab);
  1093. self.emit('data', data);
  1094. });
  1095. } else if (e.data.constructor == ArrayBuffer) {
  1096. var data = BinaryPack.unpack(e.data);
  1097. self.emit('data', data);
  1098. } else if (e.data.constructor == String) {
  1099. var ab = util.binaryStringToArrayBuffer(e.data);
  1100. var data = BinaryPack.unpack(ab);
  1101. self.emit('data', data);
  1102. }
  1103. };
  1104. })(this);