peer.js 30 KB

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