peer.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448
  1. /*! peerjs.js build:0.3.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. 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. /**
  646. * Reliable transfer for Chrome Canary DataChannel impl.
  647. * Author: @michellebu
  648. */
  649. function Reliable(dc, debug) {
  650. if (!(this instanceof Reliable)) return new Reliable(dc);
  651. this._dc = dc;
  652. util.debug = debug;
  653. // Messages sent/received so far.
  654. // id: { ack: n, chunks: [...] }
  655. this._outgoing = {};
  656. // id: { ack: ['ack', id, n], chunks: [...] }
  657. this._incoming = {};
  658. this._received = {};
  659. // Window size.
  660. this._window = 1000;
  661. // MTU.
  662. this._mtu = 500;
  663. // Interval for setInterval. In ms.
  664. this._interval = 0;
  665. // Messages sent.
  666. this._count = 0;
  667. // Outgoing message queue.
  668. this._queue = [];
  669. this._setupDC();
  670. };
  671. // Send a message reliably.
  672. Reliable.prototype.send = function(msg) {
  673. // Determine if chunking is necessary.
  674. var bl = util.pack(msg);
  675. if (bl.size < this._mtu) {
  676. this._handleSend(['no', bl]);
  677. return;
  678. }
  679. this._outgoing[this._count] = {
  680. ack: 0,
  681. chunks: this._chunk(bl)
  682. };
  683. if (util.debug) {
  684. this._outgoing[this._count].timer = new Date();
  685. }
  686. // Send prelim window.
  687. this._sendWindowedChunks(this._count);
  688. this._count += 1;
  689. };
  690. // Set up interval for processing queue.
  691. Reliable.prototype._setupInterval = function() {
  692. // TODO: fail gracefully.
  693. var self = this;
  694. this._timeout = setInterval(function() {
  695. // FIXME: String stuff makes things terribly async.
  696. var msg = self._queue.shift();
  697. if (msg._multiple) {
  698. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  699. self._intervalSend(msg[i]);
  700. }
  701. } else {
  702. self._intervalSend(msg);
  703. }
  704. }, this._interval);
  705. };
  706. Reliable.prototype._intervalSend = function(msg) {
  707. var self = this;
  708. msg = util.pack(msg);
  709. util.blobToBinaryString(msg, function(str) {
  710. self._dc.send(str);
  711. });
  712. if (self._queue.length === 0) {
  713. clearTimeout(self._timeout);
  714. self._timeout = null;
  715. //self._processAcks();
  716. }
  717. };
  718. // Go through ACKs to send missing pieces.
  719. Reliable.prototype._processAcks = function() {
  720. for (var id in this._outgoing) {
  721. if (this._outgoing.hasOwnProperty(id)) {
  722. this._sendWindowedChunks(id);
  723. }
  724. }
  725. };
  726. // Handle sending a message.
  727. // FIXME: Don't wait for interval time for all messages...
  728. Reliable.prototype._handleSend = function(msg) {
  729. var push = true;
  730. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  731. var item = this._queue[i];
  732. if (item === msg) {
  733. push = false;
  734. } else if (item._multiple && item.indexOf(msg) !== -1) {
  735. push = false;
  736. }
  737. }
  738. if (push) {
  739. this._queue.push(msg);
  740. if (!this._timeout) {
  741. this._setupInterval();
  742. }
  743. }
  744. };
  745. // Set up DataChannel handlers.
  746. Reliable.prototype._setupDC = function() {
  747. // Handle various message types.
  748. var self = this;
  749. this._dc.onmessage = function(e) {
  750. var msg = e.data;
  751. var datatype = msg.constructor;
  752. // FIXME: msg is String until binary is supported.
  753. // Once that happens, this will have to be smarter.
  754. if (datatype === String) {
  755. var ab = util.binaryStringToArrayBuffer(msg);
  756. msg = util.unpack(ab);
  757. self._handleMessage(msg);
  758. }
  759. };
  760. };
  761. // Handles an incoming message.
  762. Reliable.prototype._handleMessage = function(msg) {
  763. var id = msg[1];
  764. var idata = this._incoming[id];
  765. var odata = this._outgoing[id];
  766. var data;
  767. switch (msg[0]) {
  768. // No chunking was done.
  769. case 'no':
  770. var message = id;
  771. if (!!message) {
  772. this.onmessage(util.unpack(message));
  773. }
  774. break;
  775. // Reached the end of the message.
  776. case 'end':
  777. data = idata;
  778. // In case end comes first.
  779. this._received[id] = msg[2];
  780. if (!data) {
  781. break;
  782. }
  783. this._ack(id);
  784. break;
  785. case 'ack':
  786. data = odata;
  787. if (!!data) {
  788. var ack = msg[2];
  789. // Take the larger ACK, for out of order messages.
  790. data.ack = Math.max(ack, data.ack);
  791. // Clean up when all chunks are ACKed.
  792. if (data.ack >= data.chunks.length) {
  793. util.log('Time: ', new Date() - data.timer);
  794. delete this._outgoing[id];
  795. } else {
  796. this._processAcks();
  797. }
  798. }
  799. // If !data, just ignore.
  800. break;
  801. // Received a chunk of data.
  802. case 'chunk':
  803. // Create a new entry if none exists.
  804. data = idata;
  805. if (!data) {
  806. var end = this._received[id];
  807. if (end === true) {
  808. break;
  809. }
  810. data = {
  811. ack: ['ack', id, 0],
  812. chunks: []
  813. };
  814. this._incoming[id] = data;
  815. }
  816. var n = msg[2];
  817. var chunk = msg[3];
  818. data.chunks[n] = new Uint8Array(chunk);
  819. // If we get the chunk we're looking for, ACK for next missing.
  820. // Otherwise, ACK the same N again.
  821. if (n === data.ack[2]) {
  822. this._calculateNextAck(id);
  823. }
  824. this._ack(id);
  825. break;
  826. default:
  827. // Shouldn't happen, but would make sense for message to just go
  828. // through as is.
  829. this._handleSend(msg);
  830. break;
  831. }
  832. };
  833. // Chunks BL into smaller messages.
  834. Reliable.prototype._chunk = function(bl) {
  835. var chunks = [];
  836. var size = bl.size;
  837. var start = 0;
  838. while (start < size) {
  839. var end = Math.min(size, start + this._mtu);
  840. var b = bl.slice(start, end);
  841. var chunk = {
  842. payload: b
  843. }
  844. chunks.push(chunk);
  845. start = end;
  846. }
  847. util.log('Created', chunks.length, 'chunks.');
  848. return chunks;
  849. };
  850. // Sends ACK N, expecting Nth blob chunk for message ID.
  851. Reliable.prototype._ack = function(id) {
  852. var ack = this._incoming[id].ack;
  853. // if ack is the end value, then call _complete.
  854. if (this._received[id] === ack[2]) {
  855. this._complete(id);
  856. this._received[id] = true;
  857. }
  858. this._handleSend(ack);
  859. };
  860. // Calculates the next ACK number, given chunks.
  861. Reliable.prototype._calculateNextAck = function(id) {
  862. var data = this._incoming[id];
  863. var chunks = data.chunks;
  864. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  865. // This chunk is missing!!! Better ACK for it.
  866. if (chunks[i] === undefined) {
  867. data.ack[2] = i;
  868. return;
  869. }
  870. }
  871. data.ack[2] = chunks.length;
  872. };
  873. // Sends the next window of chunks.
  874. Reliable.prototype._sendWindowedChunks = function(id) {
  875. util.log('sendWindowedChunks for: ', id);
  876. var data = this._outgoing[id];
  877. var ch = data.chunks;
  878. var chunks = [];
  879. var limit = Math.min(data.ack + this._window, ch.length);
  880. for (var i = data.ack; i < limit; i += 1) {
  881. if (!ch[i].sent || i === data.ack) {
  882. ch[i].sent = true;
  883. chunks.push(['chunk', id, i, ch[i].payload]);
  884. }
  885. }
  886. if (data.ack + this._window >= ch.length) {
  887. chunks.push(['end', id, ch.length])
  888. }
  889. chunks._multiple = true;
  890. this._handleSend(chunks);
  891. };
  892. // Puts together a message from chunks.
  893. Reliable.prototype._complete = function(id) {
  894. util.log('Completed called for', id);
  895. var self = this;
  896. var chunks = this._incoming[id].chunks;
  897. var bl = new Blob(chunks);
  898. util.blobToArrayBuffer(bl, function(ab) {
  899. self.onmessage(util.unpack(ab));
  900. });
  901. delete this._incoming[id];
  902. };
  903. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  904. Reliable.higherBandwidthSDP = function(sdp) {
  905. // AS stands for Application-Specific Maximum.
  906. // Bandwidth number is in kilobits / sec.
  907. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  908. // Chrome 31+ doesn't want us munging the SDP, so we'll let them have their
  909. // way.
  910. var version = navigator.appVersion.match(/Chrome\/(.*?) /);
  911. if (version) {
  912. version = parseInt(version[1].split('.').shift());
  913. if (version < 31) {
  914. var parts = sdp.split('b=AS:30');
  915. var replace = 'b=AS:102400'; // 100 Mbps
  916. if (parts.length > 1) {
  917. return parts[0] + replace + parts[1];
  918. }
  919. }
  920. }
  921. return sdp;
  922. };
  923. // Overwritten, typically.
  924. Reliable.prototype.onmessage = function(msg) {};
  925. exports.Reliable = Reliable;
  926. exports.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  927. exports.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  928. exports.RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
  929. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  930. var util = {
  931. noop: function() {},
  932. CLOUD_HOST: '0.peerjs.com',
  933. CLOUD_PORT: 9000,
  934. // Logging logic
  935. logLevel: 0,
  936. setLogLevel: function(level) {
  937. var debugLevel = parseInt(level, 10);
  938. if (!isNaN(parseInt(level, 10))) {
  939. util.logLevel = debugLevel;
  940. } else {
  941. // If they are using truthy/falsy values for debug
  942. util.logLevel = level ? 3 : 0;
  943. }
  944. util.log = util.warn = util.error = util.noop;
  945. if (util.logLevel > 0) {
  946. util.error = util._printWith('ERROR');
  947. }
  948. if (util.logLevel > 1) {
  949. util.warn = util._printWith('WARNING');
  950. }
  951. if (util.logLevel > 2) {
  952. util.log = util._print;
  953. }
  954. },
  955. setLogFunction: function(fn) {
  956. if (fn.constructor !== Function) {
  957. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  958. } else {
  959. util._print = fn;
  960. }
  961. },
  962. _printWith: function(prefix) {
  963. return function() {
  964. var copy = Array.prototype.slice.call(arguments);
  965. copy.unshift(prefix);
  966. util._print.apply(util, copy);
  967. };
  968. },
  969. _print: function () {
  970. var err = false;
  971. var copy = Array.prototype.slice.call(arguments);
  972. copy.unshift('PeerJS: ');
  973. for (var i = 0, l = copy.length; i < l; i++){
  974. if (copy[i] instanceof Error) {
  975. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  976. err = true;
  977. }
  978. }
  979. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  980. },
  981. //
  982. // Returns browser-agnostic default config
  983. defaultConfig: defaultConfig,
  984. //
  985. // Returns the current browser.
  986. browser: (function() {
  987. if (window.mozRTCPeerConnection) {
  988. return 'Firefox';
  989. } else if (window.webkitRTCPeerConnection) {
  990. return 'Chrome';
  991. } else if (window.RTCPeerConnection) {
  992. return 'Supported';
  993. } else {
  994. return 'Unsupported';
  995. }
  996. })(),
  997. //
  998. // Lists which features are supported
  999. supports: (function() {
  1000. var data = true;
  1001. var audioVideo = true;
  1002. var pc, dc;
  1003. try {
  1004. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1005. } catch (e) {
  1006. data = false;
  1007. audioVideo = false;
  1008. }
  1009. if (data) {
  1010. try {
  1011. dc = pc.createDataChannel('_PEERJSDATATEST');
  1012. } catch (e) {
  1013. data = false;
  1014. }
  1015. }
  1016. // FIXME: not really the best check...
  1017. if (audioVideo) {
  1018. audioVideo = !!pc.addStream;
  1019. }
  1020. pc.close();
  1021. dc.close();
  1022. return {
  1023. audioVideo: audioVideo,
  1024. data: data,
  1025. binary: data && (function() {
  1026. var pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1027. var dc = pc.createDataChannel('_PEERJSBINARYTEST');
  1028. try {
  1029. dc.binaryType = 'blob';
  1030. } catch (e) {
  1031. pc.close();
  1032. if (e.name === 'NotSupportedError') {
  1033. return false
  1034. }
  1035. }
  1036. pc.close();
  1037. dc.close();
  1038. return true;
  1039. })(),
  1040. reliable: data && (function() {
  1041. // Reliable (not RTP).
  1042. var pc = new RTCPeerConnection(defaultConfig, {});
  1043. var dc;
  1044. try {
  1045. dc = pc.createDataChannel('_PEERJSRELIABLETEST', {maxRetransmits: 0});
  1046. } catch (e) {
  1047. pc.close();
  1048. if (e.name === 'NotSupportedError') {
  1049. return false
  1050. }
  1051. }
  1052. pc.close();
  1053. dc.close();
  1054. return true;
  1055. })(),
  1056. onnegotiationneeded: (data || audioVideo) && (function() {
  1057. var pc = new RTCPeerConnection(defaultConfig, {});
  1058. // sync default check.
  1059. var called = false;
  1060. var pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1061. pc.onnegotiationneeded = function() {
  1062. called = true;
  1063. // async check.
  1064. if (util && util.supports) {
  1065. util.supports.onnegotiationneeded = true;
  1066. }
  1067. };
  1068. // FIXME: this is not great because in theory it doesn't work for
  1069. // av-only browsers (?).
  1070. var dc = pc.createDataChannel('_PEERJSRELIABLETEST');
  1071. pc.close();
  1072. dc.close();
  1073. return called;
  1074. })()
  1075. };
  1076. }()),
  1077. //
  1078. // Ensure alphanumeric ids
  1079. validateId: function(id) {
  1080. // Allow empty ids
  1081. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1082. },
  1083. validateKey: function(key) {
  1084. // Allow empty keys
  1085. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1086. },
  1087. debug: false,
  1088. inherits: function(ctor, superCtor) {
  1089. ctor.super_ = superCtor;
  1090. ctor.prototype = Object.create(superCtor.prototype, {
  1091. constructor: {
  1092. value: ctor,
  1093. enumerable: false,
  1094. writable: true,
  1095. configurable: true
  1096. }
  1097. });
  1098. },
  1099. extend: function(dest, source) {
  1100. for(var key in source) {
  1101. if(source.hasOwnProperty(key)) {
  1102. dest[key] = source[key];
  1103. }
  1104. }
  1105. return dest;
  1106. },
  1107. pack: BinaryPack.pack,
  1108. unpack: BinaryPack.unpack,
  1109. log: function () {
  1110. if (util.debug) {
  1111. var err = false;
  1112. var copy = Array.prototype.slice.call(arguments);
  1113. copy.unshift('PeerJS: ');
  1114. for (var i = 0, l = copy.length; i < l; i++){
  1115. if (copy[i] instanceof Error) {
  1116. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1117. err = true;
  1118. }
  1119. }
  1120. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1121. }
  1122. },
  1123. setZeroTimeout: (function(global) {
  1124. var timeouts = [];
  1125. var messageName = 'zero-timeout-message';
  1126. // Like setTimeout, but only takes a function argument. There's
  1127. // no time argument (always zero) and no arguments (you have to
  1128. // use a closure).
  1129. function setZeroTimeoutPostMessage(fn) {
  1130. timeouts.push(fn);
  1131. global.postMessage(messageName, '*');
  1132. }
  1133. function handleMessage(event) {
  1134. if (event.source == global && event.data == messageName) {
  1135. if (event.stopPropagation) {
  1136. event.stopPropagation();
  1137. }
  1138. if (timeouts.length) {
  1139. timeouts.shift()();
  1140. }
  1141. }
  1142. }
  1143. if (global.addEventListener) {
  1144. global.addEventListener('message', handleMessage, true);
  1145. } else if (global.attachEvent) {
  1146. global.attachEvent('onmessage', handleMessage);
  1147. }
  1148. return setZeroTimeoutPostMessage;
  1149. }(this)),
  1150. // Binary stuff
  1151. blobToArrayBuffer: function(blob, cb){
  1152. var fr = new FileReader();
  1153. fr.onload = function(evt) {
  1154. cb(evt.target.result);
  1155. };
  1156. fr.readAsArrayBuffer(blob);
  1157. },
  1158. blobToBinaryString: function(blob, cb){
  1159. var fr = new FileReader();
  1160. fr.onload = function(evt) {
  1161. cb(evt.target.result);
  1162. };
  1163. fr.readAsBinaryString(blob);
  1164. },
  1165. binaryStringToArrayBuffer: function(binary) {
  1166. var byteArray = new Uint8Array(binary.length);
  1167. for (var i = 0; i < binary.length; i++) {
  1168. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1169. }
  1170. return byteArray.buffer;
  1171. },
  1172. randomToken: function () {
  1173. return Math.random().toString(36).substr(2);
  1174. },
  1175. //
  1176. isSecure: function() {
  1177. return location.protocol === 'https:';
  1178. }
  1179. };
  1180. exports.util = util;
  1181. /**
  1182. * A peer who can initiate connections with other peers.
  1183. */
  1184. function Peer(id, options) {
  1185. if (!(this instanceof Peer)) return new Peer(id, options);
  1186. EventEmitter.call(this);
  1187. // Deal with overloading
  1188. if (id && id.constructor == Object) {
  1189. options = id;
  1190. id = undefined;
  1191. } else if (id) {
  1192. // Ensure id is a string
  1193. id = id.toString();
  1194. }
  1195. //
  1196. // Configurize options
  1197. options = util.extend({
  1198. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1199. host: util.CLOUD_HOST,
  1200. port: util.CLOUD_PORT,
  1201. key: 'peerjs',
  1202. config: util.defaultConfig
  1203. }, options);
  1204. this.options = options;
  1205. // Detect relative URL host.
  1206. if (options.host === '/') {
  1207. options.host = window.location.hostname;
  1208. }
  1209. // Set whether we use SSL to same as current host
  1210. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1211. options.secure = util.isSecure();
  1212. }
  1213. // Set a custom log function if present
  1214. if (options.logFunction) {
  1215. util.setLogFunction(options.logFunction);
  1216. }
  1217. util.setLogLevel(options.debug);
  1218. //
  1219. // Sanity checks
  1220. // Ensure WebRTC supported
  1221. if (!util.supports.audioVideo && !util.supports.data ) {
  1222. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1223. return;
  1224. }
  1225. // Ensure alphanumeric id
  1226. if (!util.validateId(id)) {
  1227. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1228. return;
  1229. }
  1230. // Ensure valid key
  1231. if (!util.validateKey(options.key)) {
  1232. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1233. return;
  1234. }
  1235. // Ensure not using unsecure cloud server on SSL page
  1236. if (options.secure && options.host === '0.peerjs.com') {
  1237. this._delayedAbort('ssl-unavailable',
  1238. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1239. return;
  1240. }
  1241. //
  1242. // States.
  1243. this.destroyed = false; // Connections have been killed
  1244. this.disconnected = false; // Connection to PeerServer killed manually but P2P connections still active
  1245. this.open = false; // Sockets and such are not yet open.
  1246. //
  1247. // References
  1248. this.connections = {}; // DataConnections for this peer.
  1249. this._lostMessages = {}; // src => [list of messages]
  1250. //
  1251. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1252. // websockets.)
  1253. var self = this;
  1254. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.key);
  1255. this.socket.on('message', function(data) {
  1256. self._handleMessage(data);
  1257. });
  1258. this.socket.on('error', function(error) {
  1259. self._abort('socket-error', error);
  1260. });
  1261. this.socket.on('close', function() {
  1262. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  1263. self._abort('socket-closed', 'Underlying socket is already closed.');
  1264. }
  1265. });
  1266. //
  1267. // Start the connections
  1268. if (id) {
  1269. this._initialize(id);
  1270. } else {
  1271. this._retrieveId();
  1272. }
  1273. //
  1274. };
  1275. util.inherits(Peer, EventEmitter);
  1276. /** Get a unique ID from the server via XHR. */
  1277. Peer.prototype._retrieveId = function(cb) {
  1278. var self = this;
  1279. var http = new XMLHttpRequest();
  1280. var protocol = this.options.secure ? 'https://' : 'http://';
  1281. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  1282. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1283. url += queryString;
  1284. // If there's no ID we need to wait for one before trying to init socket.
  1285. http.open('get', url, true);
  1286. http.onerror = function(e) {
  1287. util.error('Error retrieving ID', e);
  1288. self._abort('server-error', 'Could not get an ID from the server');
  1289. }
  1290. http.onreadystatechange = function() {
  1291. if (http.readyState !== 4) {
  1292. return;
  1293. }
  1294. if (http.status !== 200) {
  1295. http.onerror();
  1296. return;
  1297. }
  1298. self._initialize(http.responseText);
  1299. };
  1300. http.send(null);
  1301. };
  1302. /** Initialize a connection with the server. */
  1303. Peer.prototype._initialize = function(id) {
  1304. var self = this;
  1305. this.id = id;
  1306. this.socket.start(this.id);
  1307. }
  1308. /** Handles messages from the server. */
  1309. Peer.prototype._handleMessage = function(message) {
  1310. var type = message.type;
  1311. var payload = message.payload;
  1312. var peer = message.src;
  1313. switch (type) {
  1314. case 'OPEN': // The connection to the server is open.
  1315. this.emit('open', this.id);
  1316. this.open = true;
  1317. break;
  1318. case 'ERROR': // Server error.
  1319. this._abort('server-error', payload.msg);
  1320. break;
  1321. case 'ID-TAKEN': // The selected ID is taken.
  1322. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1323. break;
  1324. case 'INVALID-KEY': // The given API key cannot be found.
  1325. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1326. break;
  1327. //
  1328. case 'LEAVE': // Another peer has closed its connection to this peer.
  1329. util.log('Received leave message from', peer);
  1330. this._cleanupPeer(peer);
  1331. break;
  1332. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1333. this.emit('error', new Error('Could not connect to peer ' + peer));
  1334. break;
  1335. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1336. var connectionId = payload.connectionId;
  1337. var connection = this.getConnection(peer, connectionId);
  1338. if (connection) {
  1339. util.warn('Offer received for existing Connection ID:', connectionId);
  1340. //connection.handleMessage(message);
  1341. } else {
  1342. // Create a new connection.
  1343. if (payload.type === 'media') {
  1344. var connection = new MediaConnection(peer, this, {
  1345. connectionId: connectionId,
  1346. _payload: payload,
  1347. metadata: payload.metadata,
  1348. });
  1349. this._addConnection(peer, connection);
  1350. this.emit('call', connection);
  1351. } else if (payload.type === 'data') {
  1352. connection = new DataConnection(peer, this, {
  1353. connectionId: connectionId,
  1354. _payload: payload,
  1355. metadata: payload.metadata,
  1356. label: payload.label,
  1357. serialization: payload.serialization,
  1358. reliable: payload.reliable
  1359. });
  1360. this._addConnection(peer, connection);
  1361. this.emit('connection', connection);
  1362. } else {
  1363. util.warn('Received malformed connection type:', payload.type);
  1364. return;
  1365. }
  1366. // Find messages.
  1367. var messages = this._getMessages(connectionId);
  1368. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1369. connection.handleMessage(messages[i]);
  1370. }
  1371. }
  1372. break;
  1373. default:
  1374. if (!payload) {
  1375. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1376. return;
  1377. }
  1378. var id = payload.connectionId;
  1379. var connection = this.getConnection(peer, id);
  1380. if (connection && connection.pc) {
  1381. // Pass it on.
  1382. connection.handleMessage(message);
  1383. } else if (id) {
  1384. // Store for possible later use
  1385. this._storeMessage(id, message);
  1386. } else {
  1387. util.warn('You received an unrecognized message:', message);
  1388. }
  1389. break;
  1390. }
  1391. }
  1392. /** Stores messages without a set up connection, to be claimed later. */
  1393. Peer.prototype._storeMessage = function(connectionId, message) {
  1394. if (!this._lostMessages[connectionId]) {
  1395. this._lostMessages[connectionId] = [];
  1396. }
  1397. this._lostMessages[connectionId].push(message);
  1398. }
  1399. /** Retrieve messages from lost message store */
  1400. Peer.prototype._getMessages = function(connectionId) {
  1401. var messages = this._lostMessages[connectionId];
  1402. if (messages) {
  1403. delete this._lostMessages[connectionId];
  1404. return messages;
  1405. } else {
  1406. return [];
  1407. }
  1408. }
  1409. /**
  1410. * Returns a DataConnection to the specified peer. See documentation for a
  1411. * complete list of options.
  1412. */
  1413. Peer.prototype.connect = function(peer, options) {
  1414. if (this.disconnected) {
  1415. util.warn('You cannot connect to a new Peer because you called '
  1416. + '.disconnect() on this Peer and ended your connection with the'
  1417. + ' server. You can create a new Peer to reconnect.');
  1418. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1419. return;
  1420. }
  1421. var connection = new DataConnection(peer, this, options);
  1422. this._addConnection(peer, connection);
  1423. return connection;
  1424. }
  1425. /**
  1426. * Returns a MediaConnection to the specified peer. See documentation for a
  1427. * complete list of options.
  1428. */
  1429. Peer.prototype.call = function(peer, stream, options) {
  1430. if (this.disconnected) {
  1431. util.warn('You cannot connect to a new Peer because you called '
  1432. + '.disconnect() on this Peer and ended your connection with the'
  1433. + ' server. You can create a new Peer to reconnect.');
  1434. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1435. return;
  1436. }
  1437. if (!stream) {
  1438. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1439. return;
  1440. }
  1441. options = options || {};
  1442. options._stream = stream;
  1443. var call = new MediaConnection(peer, this, options);
  1444. this._addConnection(peer, call);
  1445. return call;
  1446. }
  1447. /** Add a data/media connection to this peer. */
  1448. Peer.prototype._addConnection = function(peer, connection) {
  1449. if (!this.connections[peer]) {
  1450. this.connections[peer] = [];
  1451. }
  1452. this.connections[peer].push(connection);
  1453. }
  1454. /** Retrieve a data/media connection for this peer. */
  1455. Peer.prototype.getConnection = function(peer, id) {
  1456. var connections = this.connections[peer];
  1457. if (!connections) {
  1458. return null;
  1459. }
  1460. for (var i = 0, ii = connections.length; i < ii; i++) {
  1461. if (connections[i].id === id) {
  1462. return connections[i];
  1463. }
  1464. }
  1465. return null;
  1466. }
  1467. Peer.prototype._delayedAbort = function(type, message) {
  1468. var self = this;
  1469. util.setZeroTimeout(function(){
  1470. self._abort(type, message);
  1471. });
  1472. }
  1473. /** Destroys the Peer and emits an error message. */
  1474. Peer.prototype._abort = function(type, message) {
  1475. util.error('Aborting. Error:', message);
  1476. var err = new Error(message);
  1477. err.type = type;
  1478. this.destroy();
  1479. this.emit('error', err);
  1480. };
  1481. /**
  1482. * Destroys the Peer: closes all active connections as well as the connection
  1483. * to the server.
  1484. * Warning: The peer can no longer create or accept connections after being
  1485. * destroyed.
  1486. */
  1487. Peer.prototype.destroy = function() {
  1488. if (!this.destroyed) {
  1489. this._cleanup();
  1490. this.disconnect();
  1491. this.destroyed = true;
  1492. }
  1493. }
  1494. /** Disconnects every connection on this peer. */
  1495. Peer.prototype._cleanup = function() {
  1496. var peers = Object.keys(this.connections);
  1497. for (var i = 0, ii = peers.length; i < ii; i++) {
  1498. this._cleanupPeer(peers[i]);
  1499. }
  1500. this.emit('close');
  1501. }
  1502. /** Closes all connections to this peer. */
  1503. Peer.prototype._cleanupPeer = function(peer) {
  1504. var connections = this.connections[peer];
  1505. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1506. connections[j].close();
  1507. }
  1508. }
  1509. /**
  1510. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1511. * active connections.
  1512. * Warning: The peer can no longer create or accept connections after being
  1513. * disconnected. It also cannot reconnect to the server.
  1514. */
  1515. Peer.prototype.disconnect = function() {
  1516. var self = this;
  1517. util.setZeroTimeout(function(){
  1518. if (!self.disconnected) {
  1519. self.disconnected = true;
  1520. self.open = false;
  1521. if (self.socket) {
  1522. self.socket.close();
  1523. }
  1524. self.id = null;
  1525. }
  1526. });
  1527. }
  1528. exports.Peer = Peer;
  1529. /**
  1530. * Wraps a DataChannel between two Peers.
  1531. */
  1532. function DataConnection(peer, provider, options) {
  1533. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1534. EventEmitter.call(this);
  1535. // TODO: perhaps default serialization should be binary-utf8?
  1536. this.options = util.extend({
  1537. serialization: 'binary',
  1538. reliable: false
  1539. }, options);
  1540. // Connection is not open yet.
  1541. this.open = false;
  1542. this.type = 'data';
  1543. this.peer = peer;
  1544. this.provider = provider;
  1545. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1546. this.label = this.options.label || this.id;
  1547. this.metadata = this.options.metadata;
  1548. this.serialization = this.options.serialization;
  1549. this.reliable = this.options.reliable;
  1550. Negotiator.startConnection(
  1551. this,
  1552. this.options._payload || {
  1553. originator: true
  1554. }
  1555. );
  1556. }
  1557. util.inherits(DataConnection, EventEmitter);
  1558. DataConnection._idPrefix = 'dc_';
  1559. /** Called by the Negotiator when the DataChannel is ready. */
  1560. DataConnection.prototype.initialize = function(dc) {
  1561. this._dc = dc;
  1562. this._configureDataChannel();
  1563. }
  1564. DataConnection.prototype._configureDataChannel = function() {
  1565. var self = this;
  1566. if (util.supports.binary) {
  1567. // Webkit doesn't support binary yet
  1568. this._dc.binaryType = 'arraybuffer';
  1569. }
  1570. this._dc.onopen = function() {
  1571. util.log('Data channel connection success');
  1572. self.open = true;
  1573. self.emit('open');
  1574. }
  1575. // Use the Reliable shim for non Firefox browsers
  1576. if (!util.supports.reliable && this.reliable) {
  1577. this._reliable = new Reliable(this._dc, util.debug);
  1578. }
  1579. if (this._reliable) {
  1580. this._reliable.onmessage = function(msg) {
  1581. self.emit('data', msg);
  1582. };
  1583. } else {
  1584. this._dc.onmessage = function(e) {
  1585. self._handleDataMessage(e);
  1586. };
  1587. }
  1588. this._dc.onclose = function(e) {
  1589. util.log('DataChannel closed for:', self.peer);
  1590. self.close();
  1591. };
  1592. }
  1593. // Handles a DataChannel message.
  1594. DataConnection.prototype._handleDataMessage = function(e) {
  1595. var self = this;
  1596. var data = e.data;
  1597. var datatype = data.constructor;
  1598. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1599. if (datatype === Blob) {
  1600. // Datatype should never be blob
  1601. util.blobToArrayBuffer(data, function(ab) {
  1602. data = util.unpack(ab);
  1603. self.emit('data', data);
  1604. });
  1605. return;
  1606. } else if (datatype === ArrayBuffer) {
  1607. data = util.unpack(data);
  1608. } else if (datatype === String) {
  1609. // String fallback for binary data for browsers that don't support binary yet
  1610. var ab = util.binaryStringToArrayBuffer(data);
  1611. data = util.unpack(ab);
  1612. }
  1613. } else if (this.serialization === 'json') {
  1614. data = JSON.parse(data);
  1615. }
  1616. this.emit('data', data);
  1617. }
  1618. /**
  1619. * Exposed functionality for users.
  1620. */
  1621. /** Allows user to close connection. */
  1622. DataConnection.prototype.close = function() {
  1623. if (!this.open) {
  1624. return;
  1625. }
  1626. this.open = false;
  1627. Negotiator.cleanup(this);
  1628. this.emit('close');
  1629. }
  1630. /** Allows user to send data. */
  1631. DataConnection.prototype.send = function(data) {
  1632. if (!this.open) {
  1633. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1634. return;
  1635. }
  1636. if (this._reliable) {
  1637. // Note: reliable shim sending will make it so that you cannot customize
  1638. // serialization.
  1639. this._reliable.send(data);
  1640. return;
  1641. }
  1642. var self = this;
  1643. if (this.serialization === 'json') {
  1644. this._dc.send(JSON.stringify(data));
  1645. } else if ('binary-utf8'.indexOf(this.serialization) !== -1) {
  1646. var utf8 = (this.serialization === 'binary-utf8');
  1647. var blob = util.pack(data, utf8);
  1648. // DataChannel currently only supports strings.
  1649. if (!util.supports.binary) {
  1650. util.blobToBinaryString(blob, function(str){
  1651. self._dc.send(str);
  1652. });
  1653. } else {
  1654. this._dc.send(blob);
  1655. }
  1656. } else {
  1657. this._dc.send(data);
  1658. }
  1659. }
  1660. DataConnection.prototype.handleMessage = function(message) {
  1661. var payload = message.payload;
  1662. switch (message.type) {
  1663. case 'ANSWER':
  1664. // Forward to negotiator
  1665. Negotiator.handleSDP(message.type, this, payload.sdp);
  1666. break;
  1667. case 'CANDIDATE':
  1668. Negotiator.handleCandidate(this, payload.candidate);
  1669. break;
  1670. default:
  1671. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1672. break;
  1673. }
  1674. }
  1675. /**
  1676. * Wraps the streaming interface between two Peers.
  1677. */
  1678. function MediaConnection(peer, provider, options) {
  1679. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1680. EventEmitter.call(this);
  1681. this.options = util.extend({}, options);
  1682. this.open = false;
  1683. this.type = 'media';
  1684. this.peer = peer;
  1685. this.provider = provider;
  1686. this.metadata = this.options.metadata;
  1687. this.localStream = this.options._stream;
  1688. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1689. if (this.localStream) {
  1690. Negotiator.startConnection(
  1691. this,
  1692. {_stream: this.localStream, originator: true}
  1693. );
  1694. }
  1695. };
  1696. util.inherits(MediaConnection, EventEmitter);
  1697. MediaConnection._idPrefix = 'mc_';
  1698. MediaConnection.prototype.addStream = function(remoteStream) {
  1699. util.log('Receiving stream', remoteStream);
  1700. this.remoteStream = remoteStream;
  1701. this.emit('stream', remoteStream); // Should we call this `open`?
  1702. };
  1703. MediaConnection.prototype.handleMessage = function(message) {
  1704. var payload = message.payload;
  1705. switch (message.type) {
  1706. case 'ANSWER':
  1707. // Forward to negotiator
  1708. Negotiator.handleSDP(message.type, this, payload.sdp);
  1709. this.open = true;
  1710. break;
  1711. case 'CANDIDATE':
  1712. Negotiator.handleCandidate(this, payload.candidate);
  1713. break;
  1714. default:
  1715. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1716. break;
  1717. }
  1718. }
  1719. MediaConnection.prototype.answer = function(stream) {
  1720. if (this.localStream) {
  1721. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  1722. return;
  1723. }
  1724. this.options._payload._stream = stream;
  1725. this.localStream = stream;
  1726. Negotiator.startConnection(
  1727. this,
  1728. this.options._payload
  1729. )
  1730. // Retrieve lost messages stored because PeerConnection not set up.
  1731. var messages = this.provider._getMessages(this.id);
  1732. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1733. this.handleMessage(messages[i]);
  1734. }
  1735. this.open = true;
  1736. };
  1737. /**
  1738. * Exposed functionality for users.
  1739. */
  1740. /** Allows user to close connection. */
  1741. MediaConnection.prototype.close = function() {
  1742. if (!this.open) {
  1743. return;
  1744. }
  1745. this.open = false;
  1746. Negotiator.cleanup(this);
  1747. this.emit('close')
  1748. };
  1749. /**
  1750. * Manages all negotiations between Peers.
  1751. */
  1752. var Negotiator = {
  1753. pcs: {
  1754. data: {},
  1755. media: {}
  1756. }, // type => {peerId: {pc_id: pc}}.
  1757. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1758. queue: [] // connections that are delayed due to a PC being in use.
  1759. }
  1760. Negotiator._idPrefix = 'pc_';
  1761. /** Returns a PeerConnection object set up correctly (for data, media). */
  1762. Negotiator.startConnection = function(connection, options) {
  1763. var pc = Negotiator._getPeerConnection(connection, options);
  1764. if (connection.type === 'media' && options._stream) {
  1765. // Add the stream.
  1766. pc.addStream(options._stream);
  1767. }
  1768. // Set the connection's PC.
  1769. connection.pc = pc;
  1770. // What do we need to do now?
  1771. if (options.originator) {
  1772. if (connection.type === 'data') {
  1773. // Create the datachannel.
  1774. var config = {};
  1775. // Dropping reliable:false support, since it seems to be crashing
  1776. // Chrome.
  1777. /*if (util.supports.reliable && !options.reliable) {
  1778. // If we have canonical reliable support...
  1779. config = {maxRetransmits: 0};
  1780. }*/
  1781. // Fallback to ensure older browsers don't crash.
  1782. if (!util.supports.reliable) {
  1783. config = {reliable: options.reliable};
  1784. }
  1785. var dc = pc.createDataChannel(connection.label, config);
  1786. connection.initialize(dc);
  1787. }
  1788. if (!util.supports.onnegotiationneeded) {
  1789. Negotiator._makeOffer(connection);
  1790. }
  1791. } else {
  1792. Negotiator.handleSDP('OFFER', connection, options.sdp);
  1793. }
  1794. }
  1795. Negotiator._getPeerConnection = function(connection, options) {
  1796. if (!Negotiator.pcs[connection.type]) {
  1797. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  1798. }
  1799. if (!Negotiator.pcs[connection.type][connection.peer]) {
  1800. Negotiator.pcs[connection.type][connection.peer] = {};
  1801. }
  1802. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  1803. var pc;
  1804. // Not multiplexing while FF and Chrome have not-great support for it.
  1805. /*if (options.multiplex) {
  1806. ids = Object.keys(peerConnections);
  1807. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  1808. pc = peerConnections[ids[i]];
  1809. if (pc.signalingState === 'stable') {
  1810. break; // We can go ahead and use this PC.
  1811. }
  1812. }
  1813. } else */
  1814. if (options.pc) { // Simplest case: PC id already provided for us.
  1815. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  1816. }
  1817. if (!pc || pc.signalingState !== 'stable') {
  1818. pc = Negotiator._startPeerConnection(connection);
  1819. }
  1820. return pc;
  1821. }
  1822. /*
  1823. Negotiator._addProvider = function(provider) {
  1824. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  1825. // Wait for provider to obtain an ID.
  1826. provider.on('open', function(id) {
  1827. Negotiator._addProvider(provider);
  1828. });
  1829. } else {
  1830. Negotiator.providers[provider.id] = provider;
  1831. }
  1832. }*/
  1833. /** Start a PC. */
  1834. Negotiator._startPeerConnection = function(connection) {
  1835. util.log('Creating RTCPeerConnection.');
  1836. var id = Negotiator._idPrefix + util.randomToken();
  1837. var optional = {};
  1838. if (connection.type === 'data' && !util.supports.reliable) {
  1839. optional = {optional: [{RtpDataChannels: true}]};
  1840. } else if (connection.type === 'media') {
  1841. // Interop req for chrome.
  1842. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  1843. }
  1844. var pc = new RTCPeerConnection(connection.provider.options.config, optional);
  1845. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  1846. Negotiator._setupListeners(connection, pc, id);
  1847. return pc;
  1848. }
  1849. /** Set up various WebRTC listeners. */
  1850. Negotiator._setupListeners = function(connection, pc, pc_id) {
  1851. var peerId = connection.peer;
  1852. var connectionId = connection.id;
  1853. var provider = connection.provider;
  1854. // ICE CANDIDATES.
  1855. util.log('Listening for ICE candidates.');
  1856. pc.onicecandidate = function(evt) {
  1857. if (evt.candidate) {
  1858. util.log('Received ICE candidates for:', connection.peer);
  1859. provider.socket.send({
  1860. type: 'CANDIDATE',
  1861. payload: {
  1862. candidate: evt.candidate,
  1863. type: connection.type,
  1864. connectionId: connection.id
  1865. },
  1866. dst: peerId,
  1867. });
  1868. }
  1869. };
  1870. pc.oniceconnectionstatechange = function() {
  1871. switch (pc.iceConnectionState) {
  1872. case 'disconnected':
  1873. case 'failed':
  1874. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  1875. connection.close();
  1876. break;
  1877. case 'completed':
  1878. pc.onicecandidate = util.noop;
  1879. break;
  1880. }
  1881. };
  1882. // Fallback for older Chrome impls.
  1883. pc.onicechange = pc.oniceconnectionstatechange;
  1884. // ONNEGOTIATIONNEEDED (Chrome)
  1885. util.log('Listening for `negotiationneeded`');
  1886. pc.onnegotiationneeded = function() {
  1887. util.log('`negotiationneeded` triggered');
  1888. if (pc.signalingState == 'stable') {
  1889. Negotiator._makeOffer(connection);
  1890. } else {
  1891. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  1892. }
  1893. };
  1894. // DATACONNECTION.
  1895. util.log('Listening for data channel');
  1896. // Fired between offer and answer, so options should already be saved
  1897. // in the options hash.
  1898. pc.ondatachannel = function(evt) {
  1899. util.log('Received data channel');
  1900. var dc = evt.channel;
  1901. var connection = provider.getConnection(peerId, connectionId);
  1902. connection.initialize(dc);
  1903. };
  1904. // MEDIACONNECTION.
  1905. util.log('Listening for remote stream');
  1906. pc.onaddstream = function(evt) {
  1907. util.log('Received remote stream');
  1908. var stream = evt.stream;
  1909. provider.getConnection(peerId, connectionId).addStream(stream);
  1910. };
  1911. }
  1912. Negotiator.cleanup = function(connection) {
  1913. util.log('Cleaning up PeerConnection to ' + connection.peer);
  1914. var pc = connection.pc;
  1915. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  1916. pc.close();
  1917. connection.pc = null;
  1918. }
  1919. }
  1920. Negotiator._makeOffer = function(connection) {
  1921. var pc = connection.pc;
  1922. pc.createOffer(function(offer) {
  1923. util.log('Created offer.');
  1924. if (!util.supports.reliable && connection.type === 'data' && connection.reliable) {
  1925. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  1926. }
  1927. pc.setLocalDescription(offer, function() {
  1928. util.log('Set localDescription: offer', 'for:', connection.peer);
  1929. connection.provider.socket.send({
  1930. type: 'OFFER',
  1931. payload: {
  1932. sdp: offer,
  1933. type: connection.type,
  1934. label: connection.label,
  1935. reliable: connection.reliable,
  1936. serialization: connection.serialization,
  1937. metadata: connection.metadata,
  1938. connectionId: connection.id,
  1939. sctp: util.supports.reliable
  1940. },
  1941. dst: connection.peer,
  1942. });
  1943. }, function(err) {
  1944. connection.provider.emit('error', err);
  1945. util.log('Failed to setLocalDescription, ', err);
  1946. });
  1947. }, function(err) {
  1948. connection.provider.emit('error', err);
  1949. util.log('Failed to createOffer, ', err);
  1950. }, connection.options.constraints);
  1951. }
  1952. Negotiator._makeAnswer = function(connection) {
  1953. var pc = connection.pc;
  1954. pc.createAnswer(function(answer) {
  1955. util.log('Created answer.');
  1956. if (!util.supports.reliable && connection.type === 'data' && connection.reliable) {
  1957. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  1958. }
  1959. pc.setLocalDescription(answer, function() {
  1960. util.log('Set localDescription: answer', 'for:', connection.peer);
  1961. connection.provider.socket.send({
  1962. type: 'ANSWER',
  1963. payload: {
  1964. sdp: answer,
  1965. type: connection.type,
  1966. connectionId: connection.id
  1967. },
  1968. dst: connection.peer
  1969. });
  1970. }, function(err) {
  1971. connection.provider.emit('error', err);
  1972. util.log('Failed to setLocalDescription, ', err);
  1973. });
  1974. }, function(err) {
  1975. connection.provider.emit('error', err);
  1976. util.log('Failed to create answer, ', err);
  1977. });
  1978. }
  1979. /** Handle an SDP. */
  1980. Negotiator.handleSDP = function(type, connection, sdp) {
  1981. sdp = new RTCSessionDescription(sdp);
  1982. var pc = connection.pc;
  1983. util.log('Setting remote description', sdp);
  1984. pc.setRemoteDescription(sdp, function() {
  1985. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  1986. if (type === 'OFFER') {
  1987. Negotiator._makeAnswer(connection);
  1988. }
  1989. }, function(err) {
  1990. connection.provider.emit('error', err);
  1991. util.log('Failed to setRemoteDescription, ', err);
  1992. });
  1993. }
  1994. /** Handle a candidate. */
  1995. Negotiator.handleCandidate = function(connection, ice) {
  1996. var candidate = ice.candidate;
  1997. var sdpMLineIndex = ice.sdpMLineIndex;
  1998. connection.pc.addIceCandidate(new RTCIceCandidate({
  1999. sdpMLineIndex: sdpMLineIndex,
  2000. candidate: candidate
  2001. }));
  2002. util.log('Added ICE candidate for:', connection.peer);
  2003. }
  2004. /**
  2005. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  2006. * possible connection for peers.
  2007. */
  2008. function Socket(secure, host, port, key) {
  2009. if (!(this instanceof Socket)) return new Socket(secure, host, port, key);
  2010. EventEmitter.call(this);
  2011. // Disconnected manually.
  2012. this.disconnected = false;
  2013. this._queue = [];
  2014. var httpProtocol = secure ? 'https://' : 'http://';
  2015. var wsProtocol = secure ? 'wss://' : 'ws://';
  2016. this._httpUrl = httpProtocol + host + ':' + port + '/' + key;
  2017. this._wsUrl = wsProtocol + host + ':' + port + '/peerjs?key=' + key;
  2018. }
  2019. util.inherits(Socket, EventEmitter);
  2020. /** Check in with ID or get one from server. */
  2021. Socket.prototype.start = function(id) {
  2022. this.id = id;
  2023. var token = util.randomToken();
  2024. this._httpUrl += '/' + id + '/' + token;
  2025. this._wsUrl += '&id='+id+'&token='+token;
  2026. this._startXhrStream();
  2027. this._startWebSocket();
  2028. }
  2029. /** Start up websocket communications. */
  2030. Socket.prototype._startWebSocket = function(id) {
  2031. var self = this;
  2032. if (this._socket) {
  2033. return;
  2034. }
  2035. this._socket = new WebSocket(this._wsUrl);
  2036. this._socket.onmessage = function(event) {
  2037. var data;
  2038. try {
  2039. data = JSON.parse(event.data);
  2040. } catch(e) {
  2041. util.log('Invalid server message', event.data);
  2042. return;
  2043. }
  2044. self.emit('message', data);
  2045. };
  2046. // Take care of the queue of connections if necessary and make sure Peer knows
  2047. // socket is open.
  2048. this._socket.onopen = function() {
  2049. if (self._timeout) {
  2050. clearTimeout(self._timeout);
  2051. setTimeout(function(){
  2052. self._http.abort();
  2053. self._http = null;
  2054. }, 5000);
  2055. }
  2056. self._sendQueuedMessages();
  2057. util.log('Socket open');
  2058. };
  2059. }
  2060. /** Start XHR streaming. */
  2061. Socket.prototype._startXhrStream = function(n) {
  2062. try {
  2063. var self = this;
  2064. this._http = new XMLHttpRequest();
  2065. this._http._index = 1;
  2066. this._http._streamIndex = n || 0;
  2067. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2068. this._http.onreadystatechange = function() {
  2069. if (this.readyState == 2 && this.old) {
  2070. this.old.abort();
  2071. delete this.old;
  2072. }
  2073. if (this.readyState > 2 && this.status == 200 && this.responseText) {
  2074. self._handleStream(this);
  2075. }
  2076. };
  2077. this._http.send(null);
  2078. this._setHTTPTimeout();
  2079. } catch(e) {
  2080. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2081. }
  2082. }
  2083. /** Handles onreadystatechange response as a stream. */
  2084. Socket.prototype._handleStream = function(http) {
  2085. // 3 and 4 are loading/done state. All others are not relevant.
  2086. var messages = http.responseText.split('\n');
  2087. // Check to see if anything needs to be processed on buffer.
  2088. if (http._buffer) {
  2089. while (http._buffer.length > 0) {
  2090. var index = http._buffer.shift();
  2091. var bufferedMessage = messages[index];
  2092. try {
  2093. bufferedMessage = JSON.parse(bufferedMessage);
  2094. } catch(e) {
  2095. http._buffer.shift(index);
  2096. break;
  2097. }
  2098. this.emit('message', bufferedMessage);
  2099. }
  2100. }
  2101. var message = messages[http._index];
  2102. if (message) {
  2103. http._index += 1;
  2104. // Buffering--this message is incomplete and we'll get to it next time.
  2105. // This checks if the httpResponse ended in a `\n`, in which case the last
  2106. // element of messages should be the empty string.
  2107. if (http._index === messages.length) {
  2108. if (!http._buffer) {
  2109. http._buffer = [];
  2110. }
  2111. http._buffer.push(http._index - 1);
  2112. } else {
  2113. try {
  2114. message = JSON.parse(message);
  2115. } catch(e) {
  2116. util.log('Invalid server message', message);
  2117. return;
  2118. }
  2119. this.emit('message', message);
  2120. }
  2121. }
  2122. }
  2123. Socket.prototype._setHTTPTimeout = function() {
  2124. var self = this;
  2125. this._timeout = setTimeout(function() {
  2126. var old = self._http;
  2127. if (!self._wsOpen()) {
  2128. self._startXhrStream(old._streamIndex + 1);
  2129. self._http.old = old;
  2130. } else {
  2131. old.abort();
  2132. }
  2133. }, 25000);
  2134. }
  2135. /** Is the websocket currently open? */
  2136. Socket.prototype._wsOpen = function() {
  2137. return this._socket && this._socket.readyState == 1;
  2138. }
  2139. /** Send queued messages. */
  2140. Socket.prototype._sendQueuedMessages = function() {
  2141. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2142. this.send(this._queue[i]);
  2143. }
  2144. }
  2145. /** Exposed send for DC & Peer. */
  2146. Socket.prototype.send = function(data) {
  2147. if (this.disconnected) {
  2148. return;
  2149. }
  2150. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2151. // up these messages.
  2152. if (!this.id) {
  2153. this._queue.push(data);
  2154. return;
  2155. }
  2156. if (!data.type) {
  2157. this.emit('error', 'Invalid message');
  2158. return;
  2159. }
  2160. var message = JSON.stringify(data);
  2161. if (this._wsOpen()) {
  2162. this._socket.send(message);
  2163. } else {
  2164. var http = new XMLHttpRequest();
  2165. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2166. http.open('post', url, true);
  2167. http.setRequestHeader('Content-Type', 'application/json');
  2168. http.send(message);
  2169. }
  2170. }
  2171. Socket.prototype.close = function() {
  2172. if (!this.disconnected && this._wsOpen()) {
  2173. this._socket.close();
  2174. this.disconnected = true;
  2175. }
  2176. }
  2177. })(this);