peer.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571
  1. /*! peerjs.js build:0.3.5, 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. packer.pack(data);
  63. var buffer = packer.getBuffer();
  64. return buffer;
  65. }
  66. };
  67. function Unpacker (data){
  68. // Data is ArrayBuffer
  69. this.index = 0;
  70. this.dataBuffer = data;
  71. this.dataView = new Uint8Array(this.dataBuffer);
  72. this.length = this.dataBuffer.byteLength;
  73. }
  74. Unpacker.prototype.unpack = function(){
  75. var type = this.unpack_uint8();
  76. if (type < 0x80){
  77. var positive_fixnum = type;
  78. return positive_fixnum;
  79. } else if ((type ^ 0xe0) < 0x20){
  80. var negative_fixnum = (type ^ 0xe0) - 0x20;
  81. return negative_fixnum;
  82. }
  83. var size;
  84. if ((size = type ^ 0xa0) <= 0x0f){
  85. return this.unpack_raw(size);
  86. } else if ((size = type ^ 0xb0) <= 0x0f){
  87. return this.unpack_string(size);
  88. } else if ((size = type ^ 0x90) <= 0x0f){
  89. return this.unpack_array(size);
  90. } else if ((size = type ^ 0x80) <= 0x0f){
  91. return this.unpack_map(size);
  92. }
  93. switch(type){
  94. case 0xc0:
  95. return null;
  96. case 0xc1:
  97. return undefined;
  98. case 0xc2:
  99. return false;
  100. case 0xc3:
  101. return true;
  102. case 0xca:
  103. return this.unpack_float();
  104. case 0xcb:
  105. return this.unpack_double();
  106. case 0xcc:
  107. return this.unpack_uint8();
  108. case 0xcd:
  109. return this.unpack_uint16();
  110. case 0xce:
  111. return this.unpack_uint32();
  112. case 0xcf:
  113. return this.unpack_uint64();
  114. case 0xd0:
  115. return this.unpack_int8();
  116. case 0xd1:
  117. return this.unpack_int16();
  118. case 0xd2:
  119. return this.unpack_int32();
  120. case 0xd3:
  121. return this.unpack_int64();
  122. case 0xd4:
  123. return undefined;
  124. case 0xd5:
  125. return undefined;
  126. case 0xd6:
  127. return undefined;
  128. case 0xd7:
  129. return undefined;
  130. case 0xd8:
  131. size = this.unpack_uint16();
  132. return this.unpack_string(size);
  133. case 0xd9:
  134. size = this.unpack_uint32();
  135. return this.unpack_string(size);
  136. case 0xda:
  137. size = this.unpack_uint16();
  138. return this.unpack_raw(size);
  139. case 0xdb:
  140. size = this.unpack_uint32();
  141. return this.unpack_raw(size);
  142. case 0xdc:
  143. size = this.unpack_uint16();
  144. return this.unpack_array(size);
  145. case 0xdd:
  146. size = this.unpack_uint32();
  147. return this.unpack_array(size);
  148. case 0xde:
  149. size = this.unpack_uint16();
  150. return this.unpack_map(size);
  151. case 0xdf:
  152. size = this.unpack_uint32();
  153. return this.unpack_map(size);
  154. }
  155. }
  156. Unpacker.prototype.unpack_uint8 = function(){
  157. var byte = this.dataView[this.index] & 0xff;
  158. this.index++;
  159. return byte;
  160. };
  161. Unpacker.prototype.unpack_uint16 = function(){
  162. var bytes = this.read(2);
  163. var uint16 =
  164. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  165. this.index += 2;
  166. return uint16;
  167. }
  168. Unpacker.prototype.unpack_uint32 = function(){
  169. var bytes = this.read(4);
  170. var uint32 =
  171. ((bytes[0] * 256 +
  172. bytes[1]) * 256 +
  173. bytes[2]) * 256 +
  174. bytes[3];
  175. this.index += 4;
  176. return uint32;
  177. }
  178. Unpacker.prototype.unpack_uint64 = function(){
  179. var bytes = this.read(8);
  180. var uint64 =
  181. ((((((bytes[0] * 256 +
  182. bytes[1]) * 256 +
  183. bytes[2]) * 256 +
  184. bytes[3]) * 256 +
  185. bytes[4]) * 256 +
  186. bytes[5]) * 256 +
  187. bytes[6]) * 256 +
  188. bytes[7];
  189. this.index += 8;
  190. return uint64;
  191. }
  192. Unpacker.prototype.unpack_int8 = function(){
  193. var uint8 = this.unpack_uint8();
  194. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  195. };
  196. Unpacker.prototype.unpack_int16 = function(){
  197. var uint16 = this.unpack_uint16();
  198. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  199. }
  200. Unpacker.prototype.unpack_int32 = function(){
  201. var uint32 = this.unpack_uint32();
  202. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  203. uint32 - Math.pow(2, 32);
  204. }
  205. Unpacker.prototype.unpack_int64 = function(){
  206. var uint64 = this.unpack_uint64();
  207. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  208. uint64 - Math.pow(2, 64);
  209. }
  210. Unpacker.prototype.unpack_raw = function(size){
  211. if ( this.length < this.index + size){
  212. throw new Error('BinaryPackFailure: index is out of range'
  213. + ' ' + this.index + ' ' + size + ' ' + this.length);
  214. }
  215. var buf = this.dataBuffer.slice(this.index, this.index + size);
  216. this.index += size;
  217. //buf = util.bufferToString(buf);
  218. return buf;
  219. }
  220. Unpacker.prototype.unpack_string = function(size){
  221. var bytes = this.read(size);
  222. var i = 0, str = '', c, code;
  223. while(i < size){
  224. c = bytes[i];
  225. if ( c < 128){
  226. str += String.fromCharCode(c);
  227. i++;
  228. } else if ((c ^ 0xc0) < 32){
  229. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  230. str += String.fromCharCode(code);
  231. i += 2;
  232. } else {
  233. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  234. (bytes[i+2] & 63);
  235. str += String.fromCharCode(code);
  236. i += 3;
  237. }
  238. }
  239. this.index += size;
  240. return str;
  241. }
  242. Unpacker.prototype.unpack_array = function(size){
  243. var objects = new Array(size);
  244. for(var i = 0; i < size ; i++){
  245. objects[i] = this.unpack();
  246. }
  247. return objects;
  248. }
  249. Unpacker.prototype.unpack_map = function(size){
  250. var map = {};
  251. for(var i = 0; i < size ; i++){
  252. var key = this.unpack();
  253. var value = this.unpack();
  254. map[key] = value;
  255. }
  256. return map;
  257. }
  258. Unpacker.prototype.unpack_float = function(){
  259. var uint32 = this.unpack_uint32();
  260. var sign = uint32 >> 31;
  261. var exp = ((uint32 >> 23) & 0xff) - 127;
  262. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  263. return (sign == 0 ? 1 : -1) *
  264. fraction * Math.pow(2, exp - 23);
  265. }
  266. Unpacker.prototype.unpack_double = function(){
  267. var h32 = this.unpack_uint32();
  268. var l32 = this.unpack_uint32();
  269. var sign = h32 >> 31;
  270. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  271. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  272. var frac = hfrac * Math.pow(2, exp - 20) +
  273. l32 * Math.pow(2, exp - 52);
  274. return (sign == 0 ? 1 : -1) * frac;
  275. }
  276. Unpacker.prototype.read = function(length){
  277. var j = this.index;
  278. if (j + length <= this.length) {
  279. return this.dataView.subarray(j, j + length);
  280. } else {
  281. throw new Error('BinaryPackFailure: read index out of range');
  282. }
  283. }
  284. function Packer(utf8){
  285. this.utf8 = utf8;
  286. this.bufferBuilder = new BufferBuilder();
  287. }
  288. Packer.prototype.getBuffer = function(){
  289. return this.bufferBuilder.getBuffer();
  290. }
  291. Packer.prototype.pack = function(value){
  292. var type = typeof(value);
  293. if (type == 'string'){
  294. this.pack_string(value);
  295. } else if (type == 'number'){
  296. if (Math.floor(value) === value){
  297. this.pack_integer(value);
  298. } else{
  299. this.pack_double(value);
  300. }
  301. } else if (type == 'boolean'){
  302. if (value === true){
  303. this.bufferBuilder.append(0xc3);
  304. } else if (value === false){
  305. this.bufferBuilder.append(0xc2);
  306. }
  307. } else if (type == 'undefined'){
  308. this.bufferBuilder.append(0xc0);
  309. } else if (type == 'object'){
  310. if (value === null){
  311. this.bufferBuilder.append(0xc0);
  312. } else {
  313. var constructor = value.constructor;
  314. if (constructor == Array){
  315. this.pack_array(value);
  316. } else if (constructor == Blob || constructor == File) {
  317. this.pack_bin(value);
  318. } else if (constructor == ArrayBuffer) {
  319. if(binaryFeatures.useArrayBufferView) {
  320. this.pack_bin(new Uint8Array(value));
  321. } else {
  322. this.pack_bin(value);
  323. }
  324. } else if ('BYTES_PER_ELEMENT' in value){
  325. if(binaryFeatures.useArrayBufferView) {
  326. this.pack_bin(value);
  327. } else {
  328. this.pack_bin(value.buffer);
  329. }
  330. } else if (constructor == Object){
  331. this.pack_object(value);
  332. } else if (constructor == Date){
  333. this.pack_string(value.toString());
  334. } else if (typeof value.toBinaryPack == 'function'){
  335. this.bufferBuilder.append(value.toBinaryPack());
  336. } else {
  337. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  338. }
  339. }
  340. } else {
  341. throw new Error('Type "' + type + '" not yet supported');
  342. }
  343. this.bufferBuilder.flush();
  344. }
  345. Packer.prototype.pack_bin = function(blob){
  346. var length = blob.length || blob.byteLength || blob.size;
  347. if (length <= 0x0f){
  348. this.pack_uint8(0xa0 + length);
  349. } else if (length <= 0xffff){
  350. this.bufferBuilder.append(0xda) ;
  351. this.pack_uint16(length);
  352. } else if (length <= 0xffffffff){
  353. this.bufferBuilder.append(0xdb);
  354. this.pack_uint32(length);
  355. } else{
  356. throw new Error('Invalid length');
  357. return;
  358. }
  359. this.bufferBuilder.append(blob);
  360. }
  361. Packer.prototype.pack_string = function(str){
  362. var length;
  363. if (this.utf8) {
  364. var blob = new Blob([str]);
  365. length = blob.size;
  366. } else {
  367. length = str.length;
  368. }
  369. if (length <= 0x0f){
  370. this.pack_uint8(0xb0 + length);
  371. } else if (length <= 0xffff){
  372. this.bufferBuilder.append(0xd8) ;
  373. this.pack_uint16(length);
  374. } else if (length <= 0xffffffff){
  375. this.bufferBuilder.append(0xd9);
  376. this.pack_uint32(length);
  377. } else{
  378. throw new Error('Invalid length');
  379. return;
  380. }
  381. this.bufferBuilder.append(str);
  382. }
  383. Packer.prototype.pack_array = function(ary){
  384. var length = ary.length;
  385. if (length <= 0x0f){
  386. this.pack_uint8(0x90 + length);
  387. } else if (length <= 0xffff){
  388. this.bufferBuilder.append(0xdc)
  389. this.pack_uint16(length);
  390. } else if (length <= 0xffffffff){
  391. this.bufferBuilder.append(0xdd);
  392. this.pack_uint32(length);
  393. } else{
  394. throw new Error('Invalid length');
  395. }
  396. for(var i = 0; i < length ; i++){
  397. this.pack(ary[i]);
  398. }
  399. }
  400. Packer.prototype.pack_integer = function(num){
  401. if ( -0x20 <= num && num <= 0x7f){
  402. this.bufferBuilder.append(num & 0xff);
  403. } else if (0x00 <= num && num <= 0xff){
  404. this.bufferBuilder.append(0xcc);
  405. this.pack_uint8(num);
  406. } else if (-0x80 <= num && num <= 0x7f){
  407. this.bufferBuilder.append(0xd0);
  408. this.pack_int8(num);
  409. } else if ( 0x0000 <= num && num <= 0xffff){
  410. this.bufferBuilder.append(0xcd);
  411. this.pack_uint16(num);
  412. } else if (-0x8000 <= num && num <= 0x7fff){
  413. this.bufferBuilder.append(0xd1);
  414. this.pack_int16(num);
  415. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  416. this.bufferBuilder.append(0xce);
  417. this.pack_uint32(num);
  418. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  419. this.bufferBuilder.append(0xd2);
  420. this.pack_int32(num);
  421. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  422. this.bufferBuilder.append(0xd3);
  423. this.pack_int64(num);
  424. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  425. this.bufferBuilder.append(0xcf);
  426. this.pack_uint64(num);
  427. } else{
  428. throw new Error('Invalid integer');
  429. }
  430. }
  431. Packer.prototype.pack_double = function(num){
  432. var sign = 0;
  433. if (num < 0){
  434. sign = 1;
  435. num = -num;
  436. }
  437. var exp = Math.floor(Math.log(num) / Math.LN2);
  438. var frac0 = num / Math.pow(2, exp) - 1;
  439. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  440. var b32 = Math.pow(2, 32);
  441. var h32 = (sign << 31) | ((exp+1023) << 20) |
  442. (frac1 / b32) & 0x0fffff;
  443. var l32 = frac1 % b32;
  444. this.bufferBuilder.append(0xcb);
  445. this.pack_int32(h32);
  446. this.pack_int32(l32);
  447. }
  448. Packer.prototype.pack_object = function(obj){
  449. var keys = Object.keys(obj);
  450. var length = keys.length;
  451. if (length <= 0x0f){
  452. this.pack_uint8(0x80 + length);
  453. } else if (length <= 0xffff){
  454. this.bufferBuilder.append(0xde);
  455. this.pack_uint16(length);
  456. } else if (length <= 0xffffffff){
  457. this.bufferBuilder.append(0xdf);
  458. this.pack_uint32(length);
  459. } else{
  460. throw new Error('Invalid length');
  461. }
  462. for(var prop in obj){
  463. if (obj.hasOwnProperty(prop)){
  464. this.pack(prop);
  465. this.pack(obj[prop]);
  466. }
  467. }
  468. }
  469. Packer.prototype.pack_uint8 = function(num){
  470. this.bufferBuilder.append(num);
  471. }
  472. Packer.prototype.pack_uint16 = function(num){
  473. this.bufferBuilder.append(num >> 8);
  474. this.bufferBuilder.append(num & 0xff);
  475. }
  476. Packer.prototype.pack_uint32 = function(num){
  477. var n = num & 0xffffffff;
  478. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  479. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  480. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  481. this.bufferBuilder.append((n & 0x000000ff));
  482. }
  483. Packer.prototype.pack_uint64 = function(num){
  484. var high = num / Math.pow(2, 32);
  485. var low = num % Math.pow(2, 32);
  486. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  487. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  488. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  489. this.bufferBuilder.append((high & 0x000000ff));
  490. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  491. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  492. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  493. this.bufferBuilder.append((low & 0x000000ff));
  494. }
  495. Packer.prototype.pack_int8 = function(num){
  496. this.bufferBuilder.append(num & 0xff);
  497. }
  498. Packer.prototype.pack_int16 = function(num){
  499. this.bufferBuilder.append((num & 0xff00) >> 8);
  500. this.bufferBuilder.append(num & 0xff);
  501. }
  502. Packer.prototype.pack_int32 = function(num){
  503. this.bufferBuilder.append((num >>> 24) & 0xff);
  504. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  505. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  506. this.bufferBuilder.append((num & 0x000000ff));
  507. }
  508. Packer.prototype.pack_int64 = function(num){
  509. var high = Math.floor(num / Math.pow(2, 32));
  510. var low = num % Math.pow(2, 32);
  511. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  512. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  513. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  514. this.bufferBuilder.append((high & 0x000000ff));
  515. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  516. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  517. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  518. this.bufferBuilder.append((low & 0x000000ff));
  519. }
  520. /**
  521. * Light EventEmitter. Ported from Node.js/events.js
  522. * Eric Zhang
  523. */
  524. /**
  525. * EventEmitter class
  526. * Creates an object with event registering and firing methods
  527. */
  528. function EventEmitter() {
  529. // Initialise required storage variables
  530. this._events = {};
  531. }
  532. var isArray = Array.isArray;
  533. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  534. if ('function' !== typeof listener) {
  535. throw new Error('addListener only takes instances of Function');
  536. }
  537. // To avoid recursion in the case that type == "newListeners"! Before
  538. // adding it to the listeners, first emit "newListeners".
  539. this.emit('newListener', type, typeof listener.listener === 'function' ?
  540. listener.listener : listener);
  541. if (!this._events[type]) {
  542. // Optimize the case of one listener. Don't need the extra array object.
  543. this._events[type] = listener;
  544. } else if (isArray(this._events[type])) {
  545. // If we've already got an array, just append.
  546. this._events[type].push(listener);
  547. } else {
  548. // Adding the second element, need to change to array.
  549. this._events[type] = [this._events[type], listener];
  550. }
  551. return this;
  552. };
  553. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  554. EventEmitter.prototype.once = function(type, listener, scope) {
  555. if ('function' !== typeof listener) {
  556. throw new Error('.once only takes instances of Function');
  557. }
  558. var self = this;
  559. function g() {
  560. self.removeListener(type, g);
  561. listener.apply(this, arguments);
  562. };
  563. g.listener = listener;
  564. self.on(type, g);
  565. return this;
  566. };
  567. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  568. if ('function' !== typeof listener) {
  569. throw new Error('removeListener only takes instances of Function');
  570. }
  571. // does not use listeners(), so no side effect of creating _events[type]
  572. if (!this._events[type]) return this;
  573. var list = this._events[type];
  574. if (isArray(list)) {
  575. var position = -1;
  576. for (var i = 0, length = list.length; i < length; i++) {
  577. if (list[i] === listener ||
  578. (list[i].listener && list[i].listener === listener))
  579. {
  580. position = i;
  581. break;
  582. }
  583. }
  584. if (position < 0) return this;
  585. list.splice(position, 1);
  586. if (list.length == 0)
  587. delete this._events[type];
  588. } else if (list === listener ||
  589. (list.listener && list.listener === listener))
  590. {
  591. delete this._events[type];
  592. }
  593. return this;
  594. };
  595. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  596. EventEmitter.prototype.removeAllListeners = function(type) {
  597. if (arguments.length === 0) {
  598. this._events = {};
  599. return this;
  600. }
  601. // does not use listeners(), so no side effect of creating _events[type]
  602. if (type && this._events && this._events[type]) this._events[type] = null;
  603. return this;
  604. };
  605. EventEmitter.prototype.listeners = function(type) {
  606. if (!this._events[type]) this._events[type] = [];
  607. if (!isArray(this._events[type])) {
  608. this._events[type] = [this._events[type]];
  609. }
  610. return this._events[type];
  611. };
  612. EventEmitter.prototype.emit = function(type) {
  613. var type = arguments[0];
  614. var handler = this._events[type];
  615. if (!handler) return false;
  616. if (typeof handler == 'function') {
  617. switch (arguments.length) {
  618. // fast cases
  619. case 1:
  620. handler.call(this);
  621. break;
  622. case 2:
  623. handler.call(this, arguments[1]);
  624. break;
  625. case 3:
  626. handler.call(this, arguments[1], arguments[2]);
  627. break;
  628. // slower
  629. default:
  630. var l = arguments.length;
  631. var args = new Array(l - 1);
  632. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  633. handler.apply(this, args);
  634. }
  635. return true;
  636. } else if (isArray(handler)) {
  637. var l = arguments.length;
  638. var args = new Array(l - 1);
  639. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  640. var listeners = handler.slice();
  641. for (var i = 0, l = listeners.length; i < l; i++) {
  642. listeners[i].apply(this, args);
  643. }
  644. return true;
  645. } else {
  646. return false;
  647. }
  648. };
  649. /**
  650. * Reliable transfer for Chrome Canary DataChannel impl.
  651. * Author: @michellebu
  652. */
  653. function Reliable(dc, debug) {
  654. if (!(this instanceof Reliable)) return new Reliable(dc);
  655. this._dc = dc;
  656. util.debug = debug;
  657. // Messages sent/received so far.
  658. // id: { ack: n, chunks: [...] }
  659. this._outgoing = {};
  660. // id: { ack: ['ack', id, n], chunks: [...] }
  661. this._incoming = {};
  662. this._received = {};
  663. // Window size.
  664. this._window = 1000;
  665. // MTU.
  666. this._mtu = 500;
  667. // Interval for setInterval. In ms.
  668. this._interval = 0;
  669. // Messages sent.
  670. this._count = 0;
  671. // Outgoing message queue.
  672. this._queue = [];
  673. this._setupDC();
  674. };
  675. // Send a message reliably.
  676. Reliable.prototype.send = function(msg) {
  677. // Determine if chunking is necessary.
  678. var bl = util.pack(msg);
  679. if (bl.size < this._mtu) {
  680. this._handleSend(['no', bl]);
  681. return;
  682. }
  683. this._outgoing[this._count] = {
  684. ack: 0,
  685. chunks: this._chunk(bl)
  686. };
  687. if (util.debug) {
  688. this._outgoing[this._count].timer = new Date();
  689. }
  690. // Send prelim window.
  691. this._sendWindowedChunks(this._count);
  692. this._count += 1;
  693. };
  694. // Set up interval for processing queue.
  695. Reliable.prototype._setupInterval = function() {
  696. // TODO: fail gracefully.
  697. var self = this;
  698. this._timeout = setInterval(function() {
  699. // FIXME: String stuff makes things terribly async.
  700. var msg = self._queue.shift();
  701. if (msg._multiple) {
  702. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  703. self._intervalSend(msg[i]);
  704. }
  705. } else {
  706. self._intervalSend(msg);
  707. }
  708. }, this._interval);
  709. };
  710. Reliable.prototype._intervalSend = function(msg) {
  711. var self = this;
  712. msg = util.pack(msg);
  713. util.blobToBinaryString(msg, function(str) {
  714. self._dc.send(str);
  715. });
  716. if (self._queue.length === 0) {
  717. clearTimeout(self._timeout);
  718. self._timeout = null;
  719. //self._processAcks();
  720. }
  721. };
  722. // Go through ACKs to send missing pieces.
  723. Reliable.prototype._processAcks = function() {
  724. for (var id in this._outgoing) {
  725. if (this._outgoing.hasOwnProperty(id)) {
  726. this._sendWindowedChunks(id);
  727. }
  728. }
  729. };
  730. // Handle sending a message.
  731. // FIXME: Don't wait for interval time for all messages...
  732. Reliable.prototype._handleSend = function(msg) {
  733. var push = true;
  734. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  735. var item = this._queue[i];
  736. if (item === msg) {
  737. push = false;
  738. } else if (item._multiple && item.indexOf(msg) !== -1) {
  739. push = false;
  740. }
  741. }
  742. if (push) {
  743. this._queue.push(msg);
  744. if (!this._timeout) {
  745. this._setupInterval();
  746. }
  747. }
  748. };
  749. // Set up DataChannel handlers.
  750. Reliable.prototype._setupDC = function() {
  751. // Handle various message types.
  752. var self = this;
  753. this._dc.onmessage = function(e) {
  754. var msg = e.data;
  755. var datatype = msg.constructor;
  756. // FIXME: msg is String until binary is supported.
  757. // Once that happens, this will have to be smarter.
  758. if (datatype === String) {
  759. var ab = util.binaryStringToArrayBuffer(msg);
  760. msg = util.unpack(ab);
  761. self._handleMessage(msg);
  762. }
  763. };
  764. };
  765. // Handles an incoming message.
  766. Reliable.prototype._handleMessage = function(msg) {
  767. var id = msg[1];
  768. var idata = this._incoming[id];
  769. var odata = this._outgoing[id];
  770. var data;
  771. switch (msg[0]) {
  772. // No chunking was done.
  773. case 'no':
  774. var message = id;
  775. if (!!message) {
  776. this.onmessage(util.unpack(message));
  777. }
  778. break;
  779. // Reached the end of the message.
  780. case 'end':
  781. data = idata;
  782. // In case end comes first.
  783. this._received[id] = msg[2];
  784. if (!data) {
  785. break;
  786. }
  787. this._ack(id);
  788. break;
  789. case 'ack':
  790. data = odata;
  791. if (!!data) {
  792. var ack = msg[2];
  793. // Take the larger ACK, for out of order messages.
  794. data.ack = Math.max(ack, data.ack);
  795. // Clean up when all chunks are ACKed.
  796. if (data.ack >= data.chunks.length) {
  797. util.log('Time: ', new Date() - data.timer);
  798. delete this._outgoing[id];
  799. } else {
  800. this._processAcks();
  801. }
  802. }
  803. // If !data, just ignore.
  804. break;
  805. // Received a chunk of data.
  806. case 'chunk':
  807. // Create a new entry if none exists.
  808. data = idata;
  809. if (!data) {
  810. var end = this._received[id];
  811. if (end === true) {
  812. break;
  813. }
  814. data = {
  815. ack: ['ack', id, 0],
  816. chunks: []
  817. };
  818. this._incoming[id] = data;
  819. }
  820. var n = msg[2];
  821. var chunk = msg[3];
  822. data.chunks[n] = new Uint8Array(chunk);
  823. // If we get the chunk we're looking for, ACK for next missing.
  824. // Otherwise, ACK the same N again.
  825. if (n === data.ack[2]) {
  826. this._calculateNextAck(id);
  827. }
  828. this._ack(id);
  829. break;
  830. default:
  831. // Shouldn't happen, but would make sense for message to just go
  832. // through as is.
  833. this._handleSend(msg);
  834. break;
  835. }
  836. };
  837. // Chunks BL into smaller messages.
  838. Reliable.prototype._chunk = function(bl) {
  839. var chunks = [];
  840. var size = bl.size;
  841. var start = 0;
  842. while (start < size) {
  843. var end = Math.min(size, start + this._mtu);
  844. var b = bl.slice(start, end);
  845. var chunk = {
  846. payload: b
  847. }
  848. chunks.push(chunk);
  849. start = end;
  850. }
  851. util.log('Created', chunks.length, 'chunks.');
  852. return chunks;
  853. };
  854. // Sends ACK N, expecting Nth blob chunk for message ID.
  855. Reliable.prototype._ack = function(id) {
  856. var ack = this._incoming[id].ack;
  857. // if ack is the end value, then call _complete.
  858. if (this._received[id] === ack[2]) {
  859. this._complete(id);
  860. this._received[id] = true;
  861. }
  862. this._handleSend(ack);
  863. };
  864. // Calculates the next ACK number, given chunks.
  865. Reliable.prototype._calculateNextAck = function(id) {
  866. var data = this._incoming[id];
  867. var chunks = data.chunks;
  868. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  869. // This chunk is missing!!! Better ACK for it.
  870. if (chunks[i] === undefined) {
  871. data.ack[2] = i;
  872. return;
  873. }
  874. }
  875. data.ack[2] = chunks.length;
  876. };
  877. // Sends the next window of chunks.
  878. Reliable.prototype._sendWindowedChunks = function(id) {
  879. util.log('sendWindowedChunks for: ', id);
  880. var data = this._outgoing[id];
  881. var ch = data.chunks;
  882. var chunks = [];
  883. var limit = Math.min(data.ack + this._window, ch.length);
  884. for (var i = data.ack; i < limit; i += 1) {
  885. if (!ch[i].sent || i === data.ack) {
  886. ch[i].sent = true;
  887. chunks.push(['chunk', id, i, ch[i].payload]);
  888. }
  889. }
  890. if (data.ack + this._window >= ch.length) {
  891. chunks.push(['end', id, ch.length])
  892. }
  893. chunks._multiple = true;
  894. this._handleSend(chunks);
  895. };
  896. // Puts together a message from chunks.
  897. Reliable.prototype._complete = function(id) {
  898. util.log('Completed called for', id);
  899. var self = this;
  900. var chunks = this._incoming[id].chunks;
  901. var bl = new Blob(chunks);
  902. util.blobToArrayBuffer(bl, function(ab) {
  903. self.onmessage(util.unpack(ab));
  904. });
  905. delete this._incoming[id];
  906. };
  907. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  908. Reliable.higherBandwidthSDP = function(sdp) {
  909. // AS stands for Application-Specific Maximum.
  910. // Bandwidth number is in kilobits / sec.
  911. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  912. // Chrome 31+ doesn't want us munging the SDP, so we'll let them have their
  913. // way.
  914. var version = navigator.appVersion.match(/Chrome\/(.*?) /);
  915. if (version) {
  916. version = parseInt(version[1].split('.').shift());
  917. if (version < 31) {
  918. var parts = sdp.split('b=AS:30');
  919. var replace = 'b=AS:102400'; // 100 Mbps
  920. if (parts.length > 1) {
  921. return parts[0] + replace + parts[1];
  922. }
  923. }
  924. }
  925. return sdp;
  926. };
  927. // Overwritten, typically.
  928. Reliable.prototype.onmessage = function(msg) {};
  929. exports.Reliable = Reliable;
  930. exports.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  931. exports.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  932. exports.RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
  933. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  934. var dataCount = 1;
  935. var util = {
  936. noop: function() {},
  937. CLOUD_HOST: '0.peerjs.com',
  938. CLOUD_PORT: 9000,
  939. chunkedMTU: 60000, // 60KB
  940. // Logging logic
  941. logLevel: 0,
  942. setLogLevel: function(level) {
  943. var debugLevel = parseInt(level, 10);
  944. if (!isNaN(parseInt(level, 10))) {
  945. util.logLevel = debugLevel;
  946. } else {
  947. // If they are using truthy/falsy values for debug
  948. util.logLevel = level ? 3 : 0;
  949. }
  950. util.log = util.warn = util.error = util.noop;
  951. if (util.logLevel > 0) {
  952. util.error = util._printWith('ERROR');
  953. }
  954. if (util.logLevel > 1) {
  955. util.warn = util._printWith('WARNING');
  956. }
  957. if (util.logLevel > 2) {
  958. util.log = util._print;
  959. }
  960. },
  961. setLogFunction: function(fn) {
  962. if (fn.constructor !== Function) {
  963. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  964. } else {
  965. util._print = fn;
  966. }
  967. },
  968. _printWith: function(prefix) {
  969. return function() {
  970. var copy = Array.prototype.slice.call(arguments);
  971. copy.unshift(prefix);
  972. util._print.apply(util, copy);
  973. };
  974. },
  975. _print: function () {
  976. var err = false;
  977. var copy = Array.prototype.slice.call(arguments);
  978. copy.unshift('PeerJS: ');
  979. for (var i = 0, l = copy.length; i < l; i++){
  980. if (copy[i] instanceof Error) {
  981. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  982. err = true;
  983. }
  984. }
  985. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  986. },
  987. //
  988. // Returns browser-agnostic default config
  989. defaultConfig: defaultConfig,
  990. //
  991. // Returns the current browser.
  992. browser: (function() {
  993. if (window.mozRTCPeerConnection) {
  994. return 'Firefox';
  995. } else if (window.webkitRTCPeerConnection) {
  996. return 'Chrome';
  997. } else if (window.RTCPeerConnection) {
  998. return 'Supported';
  999. } else {
  1000. return 'Unsupported';
  1001. }
  1002. })(),
  1003. //
  1004. // Lists which features are supported
  1005. supports: (function() {
  1006. if (typeof RTCPeerConnection === 'undefined') {
  1007. return {};
  1008. }
  1009. var data = true;
  1010. var audioVideo = true;
  1011. var binaryBlob = false;
  1012. var sctp = false;
  1013. var onnegotiationneeded = !!window.webkitRTCPeerConnection;
  1014. var pc, dc;
  1015. try {
  1016. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1017. } catch (e) {
  1018. data = false;
  1019. audioVideo = false;
  1020. }
  1021. if (data) {
  1022. try {
  1023. dc = pc.createDataChannel('_PEERJSTEST');
  1024. } catch (e) {
  1025. data = false;
  1026. }
  1027. }
  1028. if (data) {
  1029. // Binary test
  1030. try {
  1031. dc.binaryType = 'blob';
  1032. binaryBlob = true;
  1033. } catch (e) {
  1034. }
  1035. // Reliable test.
  1036. // Unfortunately Chrome is a bit unreliable about whether or not they
  1037. // support reliable.
  1038. var reliablePC = new RTCPeerConnection(defaultConfig, {});
  1039. try {
  1040. var reliableDC = reliablePC.createDataChannel('_PEERJSRELIABLETEST', {});
  1041. sctp = reliableDC.reliable;
  1042. } catch (e) {
  1043. }
  1044. reliablePC.close();
  1045. }
  1046. // FIXME: not really the best check...
  1047. if (audioVideo) {
  1048. audioVideo = !!pc.addStream;
  1049. }
  1050. // FIXME: this is not great because in theory it doesn't work for
  1051. // av-only browsers (?).
  1052. if (!onnegotiationneeded && data) {
  1053. // sync default check.
  1054. var negotiationPC = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1055. negotiationPC.onnegotiationneeded = function() {
  1056. onnegotiationneeded = true;
  1057. // async check.
  1058. if (util && util.supports) {
  1059. util.supports.onnegotiationneeded = true;
  1060. }
  1061. };
  1062. var negotiationDC = negotiationPC.createDataChannel('_PEERJSNEGOTIATIONTEST');
  1063. setTimeout(function() {
  1064. negotiationPC.close();
  1065. }, 1000);
  1066. }
  1067. if (pc) {
  1068. pc.close();
  1069. }
  1070. return {
  1071. audioVideo: audioVideo,
  1072. data: data,
  1073. binaryBlob: binaryBlob,
  1074. binary: sctp, // deprecated; sctp implies binary support.
  1075. reliable: sctp, // deprecated; sctp implies reliable data.
  1076. sctp: sctp,
  1077. onnegotiationneeded: onnegotiationneeded
  1078. };
  1079. }()),
  1080. //
  1081. // Ensure alphanumeric ids
  1082. validateId: function(id) {
  1083. // Allow empty ids
  1084. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1085. },
  1086. validateKey: function(key) {
  1087. // Allow empty keys
  1088. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1089. },
  1090. debug: false,
  1091. inherits: function(ctor, superCtor) {
  1092. ctor.super_ = superCtor;
  1093. ctor.prototype = Object.create(superCtor.prototype, {
  1094. constructor: {
  1095. value: ctor,
  1096. enumerable: false,
  1097. writable: true,
  1098. configurable: true
  1099. }
  1100. });
  1101. },
  1102. extend: function(dest, source) {
  1103. for(var key in source) {
  1104. if(source.hasOwnProperty(key)) {
  1105. dest[key] = source[key];
  1106. }
  1107. }
  1108. return dest;
  1109. },
  1110. pack: BinaryPack.pack,
  1111. unpack: BinaryPack.unpack,
  1112. log: function () {
  1113. if (util.debug) {
  1114. var err = false;
  1115. var copy = Array.prototype.slice.call(arguments);
  1116. copy.unshift('PeerJS: ');
  1117. for (var i = 0, l = copy.length; i < l; i++){
  1118. if (copy[i] instanceof Error) {
  1119. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1120. err = true;
  1121. }
  1122. }
  1123. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1124. }
  1125. },
  1126. setZeroTimeout: (function(global) {
  1127. var timeouts = [];
  1128. var messageName = 'zero-timeout-message';
  1129. // Like setTimeout, but only takes a function argument. There's
  1130. // no time argument (always zero) and no arguments (you have to
  1131. // use a closure).
  1132. function setZeroTimeoutPostMessage(fn) {
  1133. timeouts.push(fn);
  1134. global.postMessage(messageName, '*');
  1135. }
  1136. function handleMessage(event) {
  1137. if (event.source == global && event.data == messageName) {
  1138. if (event.stopPropagation) {
  1139. event.stopPropagation();
  1140. }
  1141. if (timeouts.length) {
  1142. timeouts.shift()();
  1143. }
  1144. }
  1145. }
  1146. if (global.addEventListener) {
  1147. global.addEventListener('message', handleMessage, true);
  1148. } else if (global.attachEvent) {
  1149. global.attachEvent('onmessage', handleMessage);
  1150. }
  1151. return setZeroTimeoutPostMessage;
  1152. }(this)),
  1153. // Binary stuff
  1154. // chunks a blob.
  1155. chunk: function(bl) {
  1156. var chunks = [];
  1157. var size = bl.size;
  1158. var start = index = 0;
  1159. var total = Math.ceil(size / util.chunkedMTU);
  1160. while (start < size) {
  1161. var end = Math.min(size, start + util.chunkedMTU);
  1162. var b = bl.slice(start, end);
  1163. var chunk = {
  1164. __peerData: dataCount,
  1165. n: index,
  1166. data: b,
  1167. total: total
  1168. };
  1169. chunks.push(chunk);
  1170. start = end;
  1171. index += 1;
  1172. }
  1173. dataCount += 1;
  1174. return chunks;
  1175. },
  1176. blobToArrayBuffer: function(blob, cb){
  1177. var fr = new FileReader();
  1178. fr.onload = function(evt) {
  1179. cb(evt.target.result);
  1180. };
  1181. fr.readAsArrayBuffer(blob);
  1182. },
  1183. blobToBinaryString: function(blob, cb){
  1184. var fr = new FileReader();
  1185. fr.onload = function(evt) {
  1186. cb(evt.target.result);
  1187. };
  1188. fr.readAsBinaryString(blob);
  1189. },
  1190. binaryStringToArrayBuffer: function(binary) {
  1191. var byteArray = new Uint8Array(binary.length);
  1192. for (var i = 0; i < binary.length; i++) {
  1193. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1194. }
  1195. return byteArray.buffer;
  1196. },
  1197. randomToken: function () {
  1198. return Math.random().toString(36).substr(2);
  1199. },
  1200. //
  1201. isSecure: function() {
  1202. return location.protocol === 'https:';
  1203. }
  1204. };
  1205. exports.util = util;
  1206. /**
  1207. * A peer who can initiate connections with other peers.
  1208. */
  1209. function Peer(id, options) {
  1210. if (!(this instanceof Peer)) return new Peer(id, options);
  1211. EventEmitter.call(this);
  1212. // Deal with overloading
  1213. if (id && id.constructor == Object) {
  1214. options = id;
  1215. id = undefined;
  1216. } else if (id) {
  1217. // Ensure id is a string
  1218. id = id.toString();
  1219. }
  1220. //
  1221. // Configurize options
  1222. options = util.extend({
  1223. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1224. host: util.CLOUD_HOST,
  1225. port: util.CLOUD_PORT,
  1226. key: 'peerjs',
  1227. config: util.defaultConfig
  1228. }, options);
  1229. this.options = options;
  1230. // Detect relative URL host.
  1231. if (options.host === '/') {
  1232. options.host = window.location.hostname;
  1233. }
  1234. // Set whether we use SSL to same as current host
  1235. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1236. options.secure = util.isSecure();
  1237. }
  1238. // Set a custom log function if present
  1239. if (options.logFunction) {
  1240. util.setLogFunction(options.logFunction);
  1241. }
  1242. util.setLogLevel(options.debug);
  1243. //
  1244. // Sanity checks
  1245. // Ensure WebRTC supported
  1246. if (!util.supports.audioVideo && !util.supports.data ) {
  1247. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1248. return;
  1249. }
  1250. // Ensure alphanumeric id
  1251. if (!util.validateId(id)) {
  1252. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1253. return;
  1254. }
  1255. // Ensure valid key
  1256. if (!util.validateKey(options.key)) {
  1257. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1258. return;
  1259. }
  1260. // Ensure not using unsecure cloud server on SSL page
  1261. if (options.secure && options.host === '0.peerjs.com') {
  1262. this._delayedAbort('ssl-unavailable',
  1263. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1264. return;
  1265. }
  1266. //
  1267. // States.
  1268. this.destroyed = false; // Connections have been killed
  1269. this.disconnected = false; // Connection to PeerServer killed manually but P2P connections still active
  1270. this.open = false; // Sockets and such are not yet open.
  1271. //
  1272. // References
  1273. this.connections = {}; // DataConnections for this peer.
  1274. this._lostMessages = {}; // src => [list of messages]
  1275. //
  1276. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1277. // websockets.)
  1278. var self = this;
  1279. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.key);
  1280. this.socket.on('message', function(data) {
  1281. self._handleMessage(data);
  1282. });
  1283. this.socket.on('error', function(error) {
  1284. self._abort('socket-error', error);
  1285. });
  1286. this.socket.on('close', function() {
  1287. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  1288. self._abort('socket-closed', 'Underlying socket is already closed.');
  1289. }
  1290. });
  1291. //
  1292. // Start the connections
  1293. if (id) {
  1294. this._initialize(id);
  1295. } else {
  1296. this._retrieveId();
  1297. }
  1298. //
  1299. };
  1300. util.inherits(Peer, EventEmitter);
  1301. /** Get a unique ID from the server via XHR. */
  1302. Peer.prototype._retrieveId = function(cb) {
  1303. var self = this;
  1304. var http = new XMLHttpRequest();
  1305. var protocol = this.options.secure ? 'https://' : 'http://';
  1306. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  1307. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1308. url += queryString;
  1309. // If there's no ID we need to wait for one before trying to init socket.
  1310. http.open('get', url, true);
  1311. http.onerror = function(e) {
  1312. util.error('Error retrieving ID', e);
  1313. self._abort('server-error', 'Could not get an ID from the server');
  1314. }
  1315. http.onreadystatechange = function() {
  1316. if (http.readyState !== 4) {
  1317. return;
  1318. }
  1319. if (http.status !== 200) {
  1320. http.onerror();
  1321. return;
  1322. }
  1323. self._initialize(http.responseText);
  1324. };
  1325. http.send(null);
  1326. };
  1327. /** Initialize a connection with the server. */
  1328. Peer.prototype._initialize = function(id) {
  1329. var self = this;
  1330. this.id = id;
  1331. this.socket.start(this.id);
  1332. }
  1333. /** Handles messages from the server. */
  1334. Peer.prototype._handleMessage = function(message) {
  1335. var type = message.type;
  1336. var payload = message.payload;
  1337. var peer = message.src;
  1338. switch (type) {
  1339. case 'OPEN': // The connection to the server is open.
  1340. this.emit('open', this.id);
  1341. this.open = true;
  1342. break;
  1343. case 'ERROR': // Server error.
  1344. this._abort('server-error', payload.msg);
  1345. break;
  1346. case 'ID-TAKEN': // The selected ID is taken.
  1347. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1348. break;
  1349. case 'INVALID-KEY': // The given API key cannot be found.
  1350. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1351. break;
  1352. //
  1353. case 'LEAVE': // Another peer has closed its connection to this peer.
  1354. util.log('Received leave message from', peer);
  1355. this._cleanupPeer(peer);
  1356. break;
  1357. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1358. this.emit('error', new Error('Could not connect to peer ' + peer));
  1359. break;
  1360. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1361. var connectionId = payload.connectionId;
  1362. var connection = this.getConnection(peer, connectionId);
  1363. if (connection) {
  1364. util.warn('Offer received for existing Connection ID:', connectionId);
  1365. //connection.handleMessage(message);
  1366. } else {
  1367. // Create a new connection.
  1368. if (payload.type === 'media') {
  1369. var connection = new MediaConnection(peer, this, {
  1370. connectionId: connectionId,
  1371. _payload: payload,
  1372. metadata: payload.metadata
  1373. });
  1374. this._addConnection(peer, connection);
  1375. this.emit('call', connection);
  1376. } else if (payload.type === 'data') {
  1377. connection = new DataConnection(peer, this, {
  1378. connectionId: connectionId,
  1379. _payload: payload,
  1380. metadata: payload.metadata,
  1381. label: payload.label,
  1382. serialization: payload.serialization,
  1383. reliable: payload.reliable
  1384. });
  1385. this._addConnection(peer, connection);
  1386. this.emit('connection', connection);
  1387. } else {
  1388. util.warn('Received malformed connection type:', payload.type);
  1389. return;
  1390. }
  1391. // Find messages.
  1392. var messages = this._getMessages(connectionId);
  1393. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1394. connection.handleMessage(messages[i]);
  1395. }
  1396. }
  1397. break;
  1398. default:
  1399. if (!payload) {
  1400. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1401. return;
  1402. }
  1403. var id = payload.connectionId;
  1404. var connection = this.getConnection(peer, id);
  1405. if (connection && connection.pc) {
  1406. // Pass it on.
  1407. connection.handleMessage(message);
  1408. } else if (id) {
  1409. // Store for possible later use
  1410. this._storeMessage(id, message);
  1411. } else {
  1412. util.warn('You received an unrecognized message:', message);
  1413. }
  1414. break;
  1415. }
  1416. }
  1417. /** Stores messages without a set up connection, to be claimed later. */
  1418. Peer.prototype._storeMessage = function(connectionId, message) {
  1419. if (!this._lostMessages[connectionId]) {
  1420. this._lostMessages[connectionId] = [];
  1421. }
  1422. this._lostMessages[connectionId].push(message);
  1423. }
  1424. /** Retrieve messages from lost message store */
  1425. Peer.prototype._getMessages = function(connectionId) {
  1426. var messages = this._lostMessages[connectionId];
  1427. if (messages) {
  1428. delete this._lostMessages[connectionId];
  1429. return messages;
  1430. } else {
  1431. return [];
  1432. }
  1433. }
  1434. /**
  1435. * Returns a DataConnection to the specified peer. See documentation for a
  1436. * complete list of options.
  1437. */
  1438. Peer.prototype.connect = function(peer, options) {
  1439. if (this.disconnected) {
  1440. util.warn('You cannot connect to a new Peer because you called '
  1441. + '.disconnect() on this Peer and ended your connection with the'
  1442. + ' server. You can create a new Peer to reconnect.');
  1443. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1444. return;
  1445. }
  1446. var connection = new DataConnection(peer, this, options);
  1447. this._addConnection(peer, connection);
  1448. return connection;
  1449. }
  1450. /**
  1451. * Returns a MediaConnection to the specified peer. See documentation for a
  1452. * complete list of options.
  1453. */
  1454. Peer.prototype.call = function(peer, stream, options) {
  1455. if (this.disconnected) {
  1456. util.warn('You cannot connect to a new Peer because you called '
  1457. + '.disconnect() on this Peer and ended your connection with the'
  1458. + ' server. You can create a new Peer to reconnect.');
  1459. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1460. return;
  1461. }
  1462. if (!stream) {
  1463. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1464. return;
  1465. }
  1466. options = options || {};
  1467. options._stream = stream;
  1468. var call = new MediaConnection(peer, this, options);
  1469. this._addConnection(peer, call);
  1470. return call;
  1471. }
  1472. /** Add a data/media connection to this peer. */
  1473. Peer.prototype._addConnection = function(peer, connection) {
  1474. if (!this.connections[peer]) {
  1475. this.connections[peer] = [];
  1476. }
  1477. this.connections[peer].push(connection);
  1478. }
  1479. /** Retrieve a data/media connection for this peer. */
  1480. Peer.prototype.getConnection = function(peer, id) {
  1481. var connections = this.connections[peer];
  1482. if (!connections) {
  1483. return null;
  1484. }
  1485. for (var i = 0, ii = connections.length; i < ii; i++) {
  1486. if (connections[i].id === id) {
  1487. return connections[i];
  1488. }
  1489. }
  1490. return null;
  1491. }
  1492. Peer.prototype._delayedAbort = function(type, message) {
  1493. var self = this;
  1494. util.setZeroTimeout(function(){
  1495. self._abort(type, message);
  1496. });
  1497. }
  1498. /** Destroys the Peer and emits an error message. */
  1499. Peer.prototype._abort = function(type, message) {
  1500. util.error('Aborting. Error:', message);
  1501. var err = new Error(message);
  1502. err.type = type;
  1503. this.destroy();
  1504. this.emit('error', err);
  1505. };
  1506. /**
  1507. * Destroys the Peer: closes all active connections as well as the connection
  1508. * to the server.
  1509. * Warning: The peer can no longer create or accept connections after being
  1510. * destroyed.
  1511. */
  1512. Peer.prototype.destroy = function() {
  1513. if (!this.destroyed) {
  1514. this._cleanup();
  1515. this.disconnect();
  1516. this.destroyed = true;
  1517. }
  1518. }
  1519. /** Disconnects every connection on this peer. */
  1520. Peer.prototype._cleanup = function() {
  1521. if (this.connections) {
  1522. var peers = Object.keys(this.connections);
  1523. for (var i = 0, ii = peers.length; i < ii; i++) {
  1524. this._cleanupPeer(peers[i]);
  1525. }
  1526. }
  1527. this.emit('close');
  1528. }
  1529. /** Closes all connections to this peer. */
  1530. Peer.prototype._cleanupPeer = function(peer) {
  1531. var connections = this.connections[peer];
  1532. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1533. connections[j].close();
  1534. }
  1535. }
  1536. /**
  1537. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1538. * active connections.
  1539. * Warning: The peer can no longer create or accept connections after being
  1540. * disconnected. It also cannot reconnect to the server.
  1541. */
  1542. Peer.prototype.disconnect = function() {
  1543. var self = this;
  1544. util.setZeroTimeout(function(){
  1545. if (!self.disconnected) {
  1546. self.disconnected = true;
  1547. self.open = false;
  1548. if (self.socket) {
  1549. self.socket.close();
  1550. }
  1551. self.id = null;
  1552. }
  1553. });
  1554. }
  1555. exports.Peer = Peer;
  1556. /**
  1557. * Wraps a DataChannel between two Peers.
  1558. */
  1559. function DataConnection(peer, provider, options) {
  1560. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1561. EventEmitter.call(this);
  1562. // TODO: perhaps default serialization should be binary-utf8?
  1563. this.options = util.extend({
  1564. serialization: 'binary',
  1565. reliable: false
  1566. }, options);
  1567. // Connection is not open yet.
  1568. this.open = false;
  1569. this.type = 'data';
  1570. this.peer = peer;
  1571. this.provider = provider;
  1572. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1573. this.label = this.options.label || this.id;
  1574. this.metadata = this.options.metadata;
  1575. this.serialization = this.options.serialization;
  1576. this.reliable = this.options.reliable;
  1577. // Data channel buffering.
  1578. this._buffer = [];
  1579. this._buffering = false;
  1580. this.bufferSize = 0;
  1581. // For storing large data.
  1582. this._chunkedData = {};
  1583. Negotiator.startConnection(
  1584. this,
  1585. this.options._payload || {
  1586. originator: true
  1587. }
  1588. );
  1589. }
  1590. util.inherits(DataConnection, EventEmitter);
  1591. DataConnection._idPrefix = 'dc_';
  1592. /** Called by the Negotiator when the DataChannel is ready. */
  1593. DataConnection.prototype.initialize = function(dc) {
  1594. this._dc = this.dataChannel = dc;
  1595. this._configureDataChannel();
  1596. }
  1597. DataConnection.prototype._configureDataChannel = function() {
  1598. var self = this;
  1599. if (util.supports.sctp) {
  1600. this._dc.binaryType = 'arraybuffer';
  1601. }
  1602. this._dc.onopen = function() {
  1603. util.log('Data channel connection success');
  1604. self.open = true;
  1605. self.emit('open');
  1606. }
  1607. // Use the Reliable shim for non Firefox browsers
  1608. if (!util.supports.sctp && this.reliable) {
  1609. this._reliable = new Reliable(this._dc, util.debug);
  1610. }
  1611. if (this._reliable) {
  1612. this._reliable.onmessage = function(msg) {
  1613. self.emit('data', msg);
  1614. };
  1615. } else {
  1616. this._dc.onmessage = function(e) {
  1617. self._handleDataMessage(e);
  1618. };
  1619. }
  1620. this._dc.onclose = function(e) {
  1621. util.log('DataChannel closed for:', self.peer);
  1622. self.close();
  1623. };
  1624. }
  1625. // Handles a DataChannel message.
  1626. DataConnection.prototype._handleDataMessage = function(e) {
  1627. var self = this;
  1628. var data = e.data;
  1629. var datatype = data.constructor;
  1630. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1631. if (datatype === Blob) {
  1632. // Datatype should never be blob
  1633. util.blobToArrayBuffer(data, function(ab) {
  1634. data = util.unpack(ab);
  1635. self.emit('data', data);
  1636. });
  1637. return;
  1638. } else if (datatype === ArrayBuffer) {
  1639. data = util.unpack(data);
  1640. } else if (datatype === String) {
  1641. // String fallback for binary data for browsers that don't support binary yet
  1642. var ab = util.binaryStringToArrayBuffer(data);
  1643. data = util.unpack(ab);
  1644. }
  1645. } else if (this.serialization === 'json') {
  1646. data = JSON.parse(data);
  1647. }
  1648. // Check if we've chunked--if so, piece things back together.
  1649. // We're guaranteed that this isn't 0.
  1650. if (data.__peerData) {
  1651. var id = data.__peerData;
  1652. var chunkInfo = this._chunkedData[id] || {data: [], count: 0, total: data.total};
  1653. chunkInfo.data[data.n] = data.data;
  1654. chunkInfo.count += 1;
  1655. if (chunkInfo.total === chunkInfo.count) {
  1656. // We've received all the chunks--time to construct the complete data.
  1657. data = new Blob(chunkInfo.data);
  1658. this._handleDataMessage({data: data});
  1659. // We can also just delete the chunks now.
  1660. delete this._chunkedData[id];
  1661. }
  1662. this._chunkedData[id] = chunkInfo;
  1663. return;
  1664. }
  1665. this.emit('data', data);
  1666. }
  1667. /**
  1668. * Exposed functionality for users.
  1669. */
  1670. /** Allows user to close connection. */
  1671. DataConnection.prototype.close = function() {
  1672. if (!this.open) {
  1673. return;
  1674. }
  1675. this.open = false;
  1676. Negotiator.cleanup(this);
  1677. this.emit('close');
  1678. }
  1679. /** Allows user to send data. */
  1680. DataConnection.prototype.send = function(data, chunked) {
  1681. if (!this.open) {
  1682. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1683. return;
  1684. }
  1685. if (this._reliable) {
  1686. // Note: reliable shim sending will make it so that you cannot customize
  1687. // serialization.
  1688. this._reliable.send(data);
  1689. return;
  1690. }
  1691. var self = this;
  1692. if (this.serialization === 'json') {
  1693. this._bufferedSend(JSON.stringify(data));
  1694. } else if ('binary-utf8'.indexOf(this.serialization) !== -1) {
  1695. var utf8 = (this.serialization === 'binary-utf8');
  1696. var blob = util.pack(data, utf8);
  1697. if (util.browser !== 'Firefox' && !chunked && blob.size > util.chunkedMTU) {
  1698. this._sendChunks(blob);
  1699. return;
  1700. }
  1701. // DataChannel currently only supports strings.
  1702. if (!util.supports.sctp) {
  1703. util.blobToBinaryString(blob, function(str) {
  1704. self._bufferedSend(str);
  1705. });
  1706. } else if (!util.supports.binaryBlob) {
  1707. // We only do this if we really need to (e.g. blobs are not supported),
  1708. // because this conversion is costly.
  1709. util.blobToArrayBuffer(blob, function(ab) {
  1710. self._bufferedSend(ab);
  1711. });
  1712. } else {
  1713. this._bufferedSend(blob);
  1714. }
  1715. } else {
  1716. this._bufferedSend(data);
  1717. }
  1718. }
  1719. DataConnection.prototype._bufferedSend = function(msg) {
  1720. if (this._buffering || !this._trySend(msg)) {
  1721. this._buffer.push(msg);
  1722. this.bufferSize = this._buffer.length;
  1723. }
  1724. }
  1725. // Returns true if the send succeeds.
  1726. DataConnection.prototype._trySend = function(msg) {
  1727. try {
  1728. this._dc.send(msg);
  1729. } catch (e) {
  1730. this._buffering = true;
  1731. var self = this;
  1732. setTimeout(function() {
  1733. // Try again.
  1734. self._buffering = false;
  1735. self._tryBuffer();
  1736. }, 100);
  1737. return false;
  1738. }
  1739. return true;
  1740. }
  1741. // Try to send the first message in the buffer.
  1742. DataConnection.prototype._tryBuffer = function() {
  1743. if (this._buffer.length === 0) {
  1744. return;
  1745. }
  1746. var msg = this._buffer[0];
  1747. if (this._trySend(msg)) {
  1748. this._buffer.shift();
  1749. this.bufferSize = this._buffer.length;
  1750. this._tryBuffer();
  1751. }
  1752. }
  1753. DataConnection.prototype._sendChunks = function(blob) {
  1754. var blobs = util.chunk(blob);
  1755. for (var i = 0, ii = blobs.length; i < ii; i += 1) {
  1756. var blob = blobs[i];
  1757. this.send(blob, true);
  1758. }
  1759. }
  1760. DataConnection.prototype.handleMessage = function(message) {
  1761. var payload = message.payload;
  1762. switch (message.type) {
  1763. case 'ANSWER':
  1764. // Forward to negotiator
  1765. Negotiator.handleSDP(message.type, this, payload.sdp);
  1766. break;
  1767. case 'CANDIDATE':
  1768. Negotiator.handleCandidate(this, payload.candidate);
  1769. break;
  1770. default:
  1771. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1772. break;
  1773. }
  1774. }
  1775. /**
  1776. * Wraps the streaming interface between two Peers.
  1777. */
  1778. function MediaConnection(peer, provider, options) {
  1779. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1780. EventEmitter.call(this);
  1781. this.options = util.extend({}, options);
  1782. this.open = false;
  1783. this.type = 'media';
  1784. this.peer = peer;
  1785. this.provider = provider;
  1786. this.metadata = this.options.metadata;
  1787. this.localStream = this.options._stream;
  1788. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1789. if (this.localStream) {
  1790. Negotiator.startConnection(
  1791. this,
  1792. {_stream: this.localStream, originator: true}
  1793. );
  1794. }
  1795. };
  1796. util.inherits(MediaConnection, EventEmitter);
  1797. MediaConnection._idPrefix = 'mc_';
  1798. MediaConnection.prototype.addStream = function(remoteStream) {
  1799. util.log('Receiving stream', remoteStream);
  1800. this.remoteStream = remoteStream;
  1801. this.emit('stream', remoteStream); // Should we call this `open`?
  1802. };
  1803. MediaConnection.prototype.handleMessage = function(message) {
  1804. var payload = message.payload;
  1805. switch (message.type) {
  1806. case 'ANSWER':
  1807. // Forward to negotiator
  1808. Negotiator.handleSDP(message.type, this, payload.sdp);
  1809. this.open = true;
  1810. break;
  1811. case 'CANDIDATE':
  1812. Negotiator.handleCandidate(this, payload.candidate);
  1813. break;
  1814. default:
  1815. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1816. break;
  1817. }
  1818. }
  1819. MediaConnection.prototype.answer = function(stream) {
  1820. if (this.localStream) {
  1821. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  1822. return;
  1823. }
  1824. this.options._payload._stream = stream;
  1825. this.localStream = stream;
  1826. Negotiator.startConnection(
  1827. this,
  1828. this.options._payload
  1829. )
  1830. // Retrieve lost messages stored because PeerConnection not set up.
  1831. var messages = this.provider._getMessages(this.id);
  1832. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1833. this.handleMessage(messages[i]);
  1834. }
  1835. this.open = true;
  1836. };
  1837. /**
  1838. * Exposed functionality for users.
  1839. */
  1840. /** Allows user to close connection. */
  1841. MediaConnection.prototype.close = function() {
  1842. if (!this.open) {
  1843. return;
  1844. }
  1845. this.open = false;
  1846. Negotiator.cleanup(this);
  1847. this.emit('close')
  1848. };
  1849. /**
  1850. * Manages all negotiations between Peers.
  1851. */
  1852. var Negotiator = {
  1853. pcs: {
  1854. data: {},
  1855. media: {}
  1856. }, // type => {peerId: {pc_id: pc}}.
  1857. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1858. queue: [] // connections that are delayed due to a PC being in use.
  1859. }
  1860. Negotiator._idPrefix = 'pc_';
  1861. /** Returns a PeerConnection object set up correctly (for data, media). */
  1862. Negotiator.startConnection = function(connection, options) {
  1863. var pc = Negotiator._getPeerConnection(connection, options);
  1864. if (connection.type === 'media' && options._stream) {
  1865. // Add the stream.
  1866. pc.addStream(options._stream);
  1867. }
  1868. // Set the connection's PC.
  1869. connection.pc = pc;
  1870. // What do we need to do now?
  1871. if (options.originator) {
  1872. if (connection.type === 'data') {
  1873. // Create the datachannel.
  1874. var config = {};
  1875. // Dropping reliable:false support, since it seems to be crashing
  1876. // Chrome.
  1877. /*if (util.supports.sctp && !options.reliable) {
  1878. // If we have canonical reliable support...
  1879. config = {maxRetransmits: 0};
  1880. }*/
  1881. // Fallback to ensure older browsers don't crash.
  1882. if (!util.supports.sctp) {
  1883. config = {reliable: options.reliable};
  1884. }
  1885. var dc = pc.createDataChannel(connection.label, config);
  1886. connection.initialize(dc);
  1887. }
  1888. if (!util.supports.onnegotiationneeded) {
  1889. Negotiator._makeOffer(connection);
  1890. }
  1891. } else {
  1892. Negotiator.handleSDP('OFFER', connection, options.sdp);
  1893. }
  1894. }
  1895. Negotiator._getPeerConnection = function(connection, options) {
  1896. if (!Negotiator.pcs[connection.type]) {
  1897. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  1898. }
  1899. if (!Negotiator.pcs[connection.type][connection.peer]) {
  1900. Negotiator.pcs[connection.type][connection.peer] = {};
  1901. }
  1902. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  1903. var pc;
  1904. // Not multiplexing while FF and Chrome have not-great support for it.
  1905. /*if (options.multiplex) {
  1906. ids = Object.keys(peerConnections);
  1907. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  1908. pc = peerConnections[ids[i]];
  1909. if (pc.signalingState === 'stable') {
  1910. break; // We can go ahead and use this PC.
  1911. }
  1912. }
  1913. } else */
  1914. if (options.pc) { // Simplest case: PC id already provided for us.
  1915. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  1916. }
  1917. if (!pc || pc.signalingState !== 'stable') {
  1918. pc = Negotiator._startPeerConnection(connection);
  1919. }
  1920. return pc;
  1921. }
  1922. /*
  1923. Negotiator._addProvider = function(provider) {
  1924. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  1925. // Wait for provider to obtain an ID.
  1926. provider.on('open', function(id) {
  1927. Negotiator._addProvider(provider);
  1928. });
  1929. } else {
  1930. Negotiator.providers[provider.id] = provider;
  1931. }
  1932. }*/
  1933. /** Start a PC. */
  1934. Negotiator._startPeerConnection = function(connection) {
  1935. util.log('Creating RTCPeerConnection.');
  1936. var id = Negotiator._idPrefix + util.randomToken();
  1937. var optional = {};
  1938. if (connection.type === 'data' && !util.supports.sctp) {
  1939. optional = {optional: [{RtpDataChannels: true}]};
  1940. } else if (connection.type === 'media') {
  1941. // Interop req for chrome.
  1942. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  1943. }
  1944. var pc = new RTCPeerConnection(connection.provider.options.config, optional);
  1945. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  1946. Negotiator._setupListeners(connection, pc, id);
  1947. return pc;
  1948. }
  1949. /** Set up various WebRTC listeners. */
  1950. Negotiator._setupListeners = function(connection, pc, pc_id) {
  1951. var peerId = connection.peer;
  1952. var connectionId = connection.id;
  1953. var provider = connection.provider;
  1954. // ICE CANDIDATES.
  1955. util.log('Listening for ICE candidates.');
  1956. pc.onicecandidate = function(evt) {
  1957. if (evt.candidate) {
  1958. util.log('Received ICE candidates for:', connection.peer);
  1959. provider.socket.send({
  1960. type: 'CANDIDATE',
  1961. payload: {
  1962. candidate: evt.candidate,
  1963. type: connection.type,
  1964. connectionId: connection.id
  1965. },
  1966. dst: peerId
  1967. });
  1968. }
  1969. };
  1970. pc.oniceconnectionstatechange = function() {
  1971. switch (pc.iceConnectionState) {
  1972. case 'disconnected':
  1973. case 'failed':
  1974. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  1975. connection.close();
  1976. break;
  1977. case 'completed':
  1978. pc.onicecandidate = util.noop;
  1979. break;
  1980. }
  1981. };
  1982. // Fallback for older Chrome impls.
  1983. pc.onicechange = pc.oniceconnectionstatechange;
  1984. // ONNEGOTIATIONNEEDED (Chrome)
  1985. util.log('Listening for `negotiationneeded`');
  1986. pc.onnegotiationneeded = function() {
  1987. util.log('`negotiationneeded` triggered');
  1988. if (pc.signalingState == 'stable') {
  1989. Negotiator._makeOffer(connection);
  1990. } else {
  1991. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  1992. }
  1993. };
  1994. // DATACONNECTION.
  1995. util.log('Listening for data channel');
  1996. // Fired between offer and answer, so options should already be saved
  1997. // in the options hash.
  1998. pc.ondatachannel = function(evt) {
  1999. util.log('Received data channel');
  2000. var dc = evt.channel;
  2001. var connection = provider.getConnection(peerId, connectionId);
  2002. connection.initialize(dc);
  2003. };
  2004. // MEDIACONNECTION.
  2005. util.log('Listening for remote stream');
  2006. pc.onaddstream = function(evt) {
  2007. util.log('Received remote stream');
  2008. var stream = evt.stream;
  2009. provider.getConnection(peerId, connectionId).addStream(stream);
  2010. };
  2011. }
  2012. Negotiator.cleanup = function(connection) {
  2013. util.log('Cleaning up PeerConnection to ' + connection.peer);
  2014. var pc = connection.pc;
  2015. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  2016. pc.close();
  2017. connection.pc = null;
  2018. }
  2019. }
  2020. Negotiator._makeOffer = function(connection) {
  2021. var pc = connection.pc;
  2022. pc.createOffer(function(offer) {
  2023. util.log('Created offer.');
  2024. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  2025. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  2026. }
  2027. pc.setLocalDescription(offer, function() {
  2028. util.log('Set localDescription: offer', 'for:', connection.peer);
  2029. connection.provider.socket.send({
  2030. type: 'OFFER',
  2031. payload: {
  2032. sdp: offer,
  2033. type: connection.type,
  2034. label: connection.label,
  2035. reliable: connection.reliable,
  2036. serialization: connection.serialization,
  2037. metadata: connection.metadata,
  2038. connectionId: connection.id,
  2039. sctp: util.supports.sctp
  2040. },
  2041. dst: connection.peer
  2042. });
  2043. }, function(err) {
  2044. connection.provider.emit('error', err);
  2045. util.log('Failed to setLocalDescription, ', err);
  2046. });
  2047. }, function(err) {
  2048. connection.provider.emit('error', err);
  2049. util.log('Failed to createOffer, ', err);
  2050. }, connection.options.constraints);
  2051. }
  2052. Negotiator._makeAnswer = function(connection) {
  2053. var pc = connection.pc;
  2054. pc.createAnswer(function(answer) {
  2055. util.log('Created answer.');
  2056. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  2057. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  2058. }
  2059. pc.setLocalDescription(answer, function() {
  2060. util.log('Set localDescription: answer', 'for:', connection.peer);
  2061. connection.provider.socket.send({
  2062. type: 'ANSWER',
  2063. payload: {
  2064. sdp: answer,
  2065. type: connection.type,
  2066. connectionId: connection.id
  2067. },
  2068. dst: connection.peer
  2069. });
  2070. }, function(err) {
  2071. connection.provider.emit('error', err);
  2072. util.log('Failed to setLocalDescription, ', err);
  2073. });
  2074. }, function(err) {
  2075. connection.provider.emit('error', err);
  2076. util.log('Failed to create answer, ', err);
  2077. });
  2078. }
  2079. /** Handle an SDP. */
  2080. Negotiator.handleSDP = function(type, connection, sdp) {
  2081. sdp = new RTCSessionDescription(sdp);
  2082. var pc = connection.pc;
  2083. util.log('Setting remote description', sdp);
  2084. pc.setRemoteDescription(sdp, function() {
  2085. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  2086. if (type === 'OFFER') {
  2087. Negotiator._makeAnswer(connection);
  2088. }
  2089. }, function(err) {
  2090. connection.provider.emit('error', err);
  2091. util.log('Failed to setRemoteDescription, ', err);
  2092. });
  2093. }
  2094. /** Handle a candidate. */
  2095. Negotiator.handleCandidate = function(connection, ice) {
  2096. var candidate = ice.candidate;
  2097. var sdpMLineIndex = ice.sdpMLineIndex;
  2098. connection.pc.addIceCandidate(new RTCIceCandidate({
  2099. sdpMLineIndex: sdpMLineIndex,
  2100. candidate: candidate
  2101. }));
  2102. util.log('Added ICE candidate for:', connection.peer);
  2103. }
  2104. /**
  2105. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  2106. * possible connection for peers.
  2107. */
  2108. function Socket(secure, host, port, key) {
  2109. if (!(this instanceof Socket)) return new Socket(secure, host, port, key);
  2110. EventEmitter.call(this);
  2111. // Disconnected manually.
  2112. this.disconnected = false;
  2113. this._queue = [];
  2114. var httpProtocol = secure ? 'https://' : 'http://';
  2115. var wsProtocol = secure ? 'wss://' : 'ws://';
  2116. this._httpUrl = httpProtocol + host + ':' + port + '/' + key;
  2117. this._wsUrl = wsProtocol + host + ':' + port + '/peerjs?key=' + key;
  2118. }
  2119. util.inherits(Socket, EventEmitter);
  2120. /** Check in with ID or get one from server. */
  2121. Socket.prototype.start = function(id) {
  2122. this.id = id;
  2123. var token = util.randomToken();
  2124. this._httpUrl += '/' + id + '/' + token;
  2125. this._wsUrl += '&id='+id+'&token='+token;
  2126. this._startXhrStream();
  2127. this._startWebSocket();
  2128. }
  2129. /** Start up websocket communications. */
  2130. Socket.prototype._startWebSocket = function(id) {
  2131. var self = this;
  2132. if (this._socket) {
  2133. return;
  2134. }
  2135. this._socket = new WebSocket(this._wsUrl);
  2136. this._socket.onmessage = function(event) {
  2137. var data;
  2138. try {
  2139. data = JSON.parse(event.data);
  2140. } catch(e) {
  2141. util.log('Invalid server message', event.data);
  2142. return;
  2143. }
  2144. self.emit('message', data);
  2145. };
  2146. // Take care of the queue of connections if necessary and make sure Peer knows
  2147. // socket is open.
  2148. this._socket.onopen = function() {
  2149. if (self._timeout) {
  2150. clearTimeout(self._timeout);
  2151. setTimeout(function(){
  2152. self._http.abort();
  2153. self._http = null;
  2154. }, 5000);
  2155. }
  2156. self._sendQueuedMessages();
  2157. util.log('Socket open');
  2158. };
  2159. }
  2160. /** Start XHR streaming. */
  2161. Socket.prototype._startXhrStream = function(n) {
  2162. try {
  2163. var self = this;
  2164. this._http = new XMLHttpRequest();
  2165. this._http._index = 1;
  2166. this._http._streamIndex = n || 0;
  2167. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2168. this._http.onreadystatechange = function() {
  2169. if (this.readyState == 2 && this.old) {
  2170. this.old.abort();
  2171. delete this.old;
  2172. }
  2173. if (this.readyState > 2 && this.status == 200 && this.responseText) {
  2174. self._handleStream(this);
  2175. }
  2176. };
  2177. this._http.send(null);
  2178. this._setHTTPTimeout();
  2179. } catch(e) {
  2180. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2181. }
  2182. }
  2183. /** Handles onreadystatechange response as a stream. */
  2184. Socket.prototype._handleStream = function(http) {
  2185. // 3 and 4 are loading/done state. All others are not relevant.
  2186. var messages = http.responseText.split('\n');
  2187. // Check to see if anything needs to be processed on buffer.
  2188. if (http._buffer) {
  2189. while (http._buffer.length > 0) {
  2190. var index = http._buffer.shift();
  2191. var bufferedMessage = messages[index];
  2192. try {
  2193. bufferedMessage = JSON.parse(bufferedMessage);
  2194. } catch(e) {
  2195. http._buffer.shift(index);
  2196. break;
  2197. }
  2198. this.emit('message', bufferedMessage);
  2199. }
  2200. }
  2201. var message = messages[http._index];
  2202. if (message) {
  2203. http._index += 1;
  2204. // Buffering--this message is incomplete and we'll get to it next time.
  2205. // This checks if the httpResponse ended in a `\n`, in which case the last
  2206. // element of messages should be the empty string.
  2207. if (http._index === messages.length) {
  2208. if (!http._buffer) {
  2209. http._buffer = [];
  2210. }
  2211. http._buffer.push(http._index - 1);
  2212. } else {
  2213. try {
  2214. message = JSON.parse(message);
  2215. } catch(e) {
  2216. util.log('Invalid server message', message);
  2217. return;
  2218. }
  2219. this.emit('message', message);
  2220. }
  2221. }
  2222. }
  2223. Socket.prototype._setHTTPTimeout = function() {
  2224. var self = this;
  2225. this._timeout = setTimeout(function() {
  2226. var old = self._http;
  2227. if (!self._wsOpen()) {
  2228. self._startXhrStream(old._streamIndex + 1);
  2229. self._http.old = old;
  2230. } else {
  2231. old.abort();
  2232. }
  2233. }, 25000);
  2234. }
  2235. /** Is the websocket currently open? */
  2236. Socket.prototype._wsOpen = function() {
  2237. return this._socket && this._socket.readyState == 1;
  2238. }
  2239. /** Send queued messages. */
  2240. Socket.prototype._sendQueuedMessages = function() {
  2241. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2242. this.send(this._queue[i]);
  2243. }
  2244. }
  2245. /** Exposed send for DC & Peer. */
  2246. Socket.prototype.send = function(data) {
  2247. if (this.disconnected) {
  2248. return;
  2249. }
  2250. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2251. // up these messages.
  2252. if (!this.id) {
  2253. this._queue.push(data);
  2254. return;
  2255. }
  2256. if (!data.type) {
  2257. this.emit('error', 'Invalid message');
  2258. return;
  2259. }
  2260. var message = JSON.stringify(data);
  2261. if (this._wsOpen()) {
  2262. this._socket.send(message);
  2263. } else {
  2264. var http = new XMLHttpRequest();
  2265. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2266. http.open('post', url, true);
  2267. http.setRequestHeader('Content-Type', 'application/json');
  2268. http.send(message);
  2269. }
  2270. }
  2271. Socket.prototype.close = function() {
  2272. if (!this.disconnected && this._wsOpen()) {
  2273. this._socket.close();
  2274. this.disconnected = true;
  2275. }
  2276. }
  2277. })(this);