peer.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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. this._config = options.config || { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] };
  536. this._peer = options.source || null;
  537. this._video = options.video;
  538. this._data = options.data != undefined ? options.data : true;
  539. this._audio = options.audio;
  540. this._pc = null;
  541. this._id = null;
  542. this._dc = null;
  543. this._socket = new WebSocket(options.ws || 'ws://localhost');
  544. var self = this;
  545. this._socket.onopen = function() {
  546. self.socketInit();
  547. };
  548. this._handlers = {};
  549. // Testing firefox.
  550. // MULTICONNECTION doesn't work still.
  551. if (browserisms == 'Firefox' && !options.source) {
  552. if (!SinkPeer.usedPorts) {
  553. SinkPeer.usedPorts = [];
  554. }
  555. this.localPort = randomPort();
  556. while (SinkPeer.usedPorts.indexOf(this.localPort) != -1) {
  557. this.localPort = randomPort();
  558. }
  559. this.remotePort = randomPort();
  560. while (this.remotePort == this.localPort ||
  561. SinkPeer.usedPorts.indexOf(this.localPort) != -1) {
  562. this.remotePort = randomPort();
  563. }
  564. SinkPeer.usedPorts.push(this.remotePort);
  565. SinkPeer.usedPorts.push(this.localPort);
  566. }
  567. };
  568. function randomPort() {
  569. return Math.round(Math.random() * 60535) + 5000;
  570. };
  571. /** Start up websocket communications. */
  572. SinkPeer.prototype.socketInit = function() {
  573. var self = this;
  574. // Multiple sinks to one source.
  575. if (!!this._peer) {
  576. this._socket.send(JSON.stringify({
  577. type: 'SINK',
  578. source: this._peer,
  579. isms: browserisms
  580. }));
  581. this._socket.onmessage = function(event) {
  582. var message = JSON.parse(event.data);
  583. switch (message.type) {
  584. case 'SINK-ID':
  585. self._id = message.id;
  586. if (!!self._handlers['ready']) {
  587. self._handlers['ready'](self._id);
  588. }
  589. self.startPeerConnection();
  590. break;
  591. case 'OFFER':
  592. var sdp = message.sdp;
  593. try {
  594. sdp = new RTCSessionDescription(message.sdp);
  595. } catch(e) {
  596. console.log('Firefox');
  597. }
  598. self._pc.setRemoteDescription(sdp, function() {
  599. console.log('setRemoteDescription: offer');
  600. // If we also have to set up a stream on the sink end, do so.
  601. self.handleStream(false, function() {
  602. self.maybeBrowserisms(false);
  603. });
  604. }, function(err) {
  605. console.log('failed to setRemoteDescription with offer, ', err);
  606. });
  607. break;
  608. case 'CANDIDATE':
  609. console.log(message.candidate);
  610. var candidate = new RTCIceCandidate(message.candidate);
  611. self._pc.addIceCandidate(candidate);
  612. break;
  613. case 'PORT':
  614. if (browserisms && browserisms == 'Firefox') {
  615. if (!SinkPeer.usedPorts) {
  616. SinkPeer.usedPorts = [];
  617. }
  618. SinkPeer.usedPorts.push(message.local);
  619. SinkPeer.usedPorts.push(message.remote);
  620. self._pc.connectDataConnection(message.local, message.remote);
  621. break;
  622. }
  623. case 'DEFAULT':
  624. console.log('SINK: unrecognized message ', message.type);
  625. break;
  626. }
  627. };
  628. } else {
  629. // Otherwise, this sink is the originator to another sink and should wait
  630. // for an alert.
  631. this._socket.send(JSON.stringify({
  632. type: 'SOURCE',
  633. isms: browserisms
  634. }));
  635. this._socket.onmessage = function(event) {
  636. var message = JSON.parse(event.data);
  637. switch (message.type) {
  638. case 'SOURCE-ID':
  639. self._id = message.id;
  640. if (!!self._handlers['ready']) {
  641. self._handlers['ready'](self._id);
  642. }
  643. break;
  644. case 'SINK-CONNECTED':
  645. self._peer = message.sink;
  646. self.startPeerConnection();
  647. self.handleStream(true, function() {
  648. self.maybeBrowserisms(true);
  649. });
  650. break;
  651. case 'ANSWER':
  652. var sdp = message.sdp;
  653. try {
  654. sdp = new RTCSessionDescription(message.sdp);
  655. } catch(e) {
  656. console.log('Firefox');
  657. }
  658. self._pc.setRemoteDescription(sdp, function() {
  659. console.log('setRemoteDescription: answer');
  660. // Firefoxism
  661. if (browserisms == 'Firefox') {
  662. self._pc.connectDataConnection(self.localPort, self.remotePort);
  663. self._socket.send(JSON.stringify({
  664. type: 'PORT',
  665. dst: self._peer,
  666. remote: self.localPort,
  667. local: self.remotePort
  668. }));
  669. }
  670. console.log('ORIGINATOR: PeerConnection success');
  671. }, function(err) {
  672. console.log('failed to setRemoteDescription, ', err);
  673. });
  674. break;
  675. case 'CANDIDATE':
  676. console.log(message.candidate);
  677. var candidate = new RTCIceCandidate(message.candidate);
  678. self._pc.addIceCandidate(candidate);
  679. break;
  680. case 'DEFAULT':
  681. console.log('ORIGINATOR: message not recognized ', message.type);
  682. }
  683. };
  684. }
  685. // Makes sure things clean up neatly.
  686. window.onbeforeunload = function() {
  687. if (!!self._pc) {
  688. self._pc.close();
  689. }
  690. if (!!self._socket && !!self._peer) {
  691. self._socket.send(JSON.stringify({ type: 'LEAVE', dst: self._peer }));
  692. if (!!self._dc) {
  693. self._dc.close();
  694. }
  695. }
  696. }
  697. };
  698. /** Takes care of ice handlers. */
  699. SinkPeer.prototype.setupIce = function() {
  700. var self = this;
  701. this._pc.onicecandidate = function(event) {
  702. console.log('candidates received');
  703. if (event.candidate) {
  704. self._socket.send(JSON.stringify({
  705. type: 'CANDIDATE',
  706. candidate: event.candidate,
  707. dst: self._peer
  708. }));
  709. } else {
  710. console.log("End of candidates.");
  711. }
  712. };
  713. };
  714. /** Starts a PeerConnection and sets up handlers. */
  715. SinkPeer.prototype.startPeerConnection = function() {
  716. this._pc = new RTCPeerConnection(this._config, { optional:[ { RtpDataChannels: true } ]});
  717. this.setupIce();
  718. this.setupAudioVideo();
  719. };
  720. /** Decide whether to handle Firefoxisms. */
  721. SinkPeer.prototype.maybeBrowserisms = function(originator) {
  722. var self = this;
  723. if (browserisms == 'Firefox' && !this._video && !this._audio && !this._stream) {
  724. getUserMedia({ audio: true, fake: true }, function(s) {
  725. self._pc.addStream(s);
  726. if (originator) {
  727. self.makeOffer();
  728. } else {
  729. self.makeAnswer();
  730. }
  731. }, function(err) { console.log('crap'); });
  732. } else {
  733. if (originator) {
  734. this.makeOffer();
  735. } else {
  736. this.makeAnswer();
  737. }
  738. }
  739. }
  740. /** Create an answer for PC. */
  741. SinkPeer.prototype.makeAnswer = function() {
  742. var self = this;
  743. this._pc.createAnswer(function(answer) {
  744. console.log('createAnswer');
  745. self._pc.setLocalDescription(answer, function() {
  746. console.log('setLocalDescription: answer');
  747. self._socket.send(JSON.stringify({
  748. type: 'ANSWER',
  749. src: self._id,
  750. sdp: answer,
  751. dst: self._peer
  752. }));
  753. }, function(err) {
  754. console.log('failed to setLocalDescription, ', err)
  755. });
  756. }, function(err) {
  757. console.log('failed to create answer, ', err)
  758. });
  759. };
  760. /** Create an offer for PC. */
  761. SinkPeer.prototype.makeOffer = function() {
  762. var self = this;
  763. this._pc.createOffer(function(offer) {
  764. console.log('createOffer')
  765. self._pc.setLocalDescription(offer, function() {
  766. console.log('setLocalDescription: offer');
  767. self._socket.send(JSON.stringify({
  768. type: 'OFFER',
  769. sdp: offer,
  770. dst: self._peer,
  771. src: self._id
  772. }));
  773. }, function(err) {
  774. console.log('failed to setLocalDescription, ', err);
  775. });
  776. });
  777. };
  778. /** Sets up A/V stream handler. */
  779. SinkPeer.prototype.setupAudioVideo = function() {
  780. var self = this;
  781. console.log('onaddstream handler added');
  782. this._pc.onaddstream = function(obj) {
  783. console.log('Remote stream added');
  784. this._stream = true;
  785. if (!!self._handlers['remotestream']) {
  786. self._handlers['remotestream'](obj.type, obj.stream);
  787. }
  788. };
  789. };
  790. /** Handle the different types of streams requested by user. */
  791. SinkPeer.prototype.handleStream = function(originator, cb) {
  792. if (this._data) {
  793. this.setupDataChannel(originator);
  794. }
  795. this.getAudioVideo(originator, cb);
  796. };
  797. /** Get A/V streams. */
  798. SinkPeer.prototype.getAudioVideo = function(originator, cb) {
  799. var self = this;
  800. if (this._video) {
  801. getUserMedia({ video: true }, function(vstream) {
  802. self._pc.addStream(vstream);
  803. console.log('Local video stream added');
  804. if (!!self._handlers['localstream']) {
  805. self._handlers['localstream']('video', vstream);
  806. }
  807. if (self._audio) {
  808. getUserMedia({ audio: true }, function(astream) {
  809. self._pc.addStream(astream);
  810. console.log('Local audio stream added');
  811. if (!!self._handlers['localstream']) {
  812. self._handlers['localstream']('audio', astream);
  813. }
  814. cb();
  815. }, function(err) { console.log('Audio cannot start'); cb(); });
  816. } else {
  817. cb();
  818. }
  819. }, function(err) { console.log('Video cannot start', err); cb(); });
  820. } else if (this._audio) {
  821. getUserMedia({ audio: true }, function(astream) {
  822. self._pc.addStream(astream);
  823. if (!!self._handlers['localstream']) {
  824. self._handlers['localstream']('audio', astream);
  825. }
  826. cb();
  827. }, function(err) { console.log('Audio cannot start'); cb(); });
  828. } else {
  829. cb();
  830. }
  831. };
  832. /** Sets up DataChannel handlers. */
  833. SinkPeer.prototype.setupDataChannel = function(originator, cb) {
  834. var self = this;
  835. if (originator) {
  836. /** ORIGINATOR SETUP */
  837. if (browserisms == 'Webkit') {
  838. this._pc.onstatechange = function() {
  839. console.log('State Change: ', self._pc.readyState);
  840. /*if (self._pc.readyState == 'active') {
  841. console.log('ORIGINATOR: active state detected');
  842. self._dc = self._pc.createDataChannel('StreamAPI', { reliable: false });
  843. self._dc.binaryType = 'blob';
  844. if (!!self._handlers['connection']) {
  845. self._handlers['connection'](self._peer);
  846. }
  847. self._dc.onmessage = function(e) {
  848. self.handleDataMessage(e);
  849. };
  850. }*/
  851. }
  852. } else {
  853. this._pc.onconnection = function() {
  854. console.log('ORIGINATOR: onconnection triggered');
  855. self.startDataChannel();
  856. };
  857. }
  858. } else {
  859. /** TARGET SETUP */
  860. this._pc.ondatachannel = function(dc) {
  861. console.log('SINK: ondatachannel triggered');
  862. self._dc = dc;
  863. self._dc.binaryType = 'blob';
  864. if (!!self._handlers['connection']) {
  865. self._handlers['connection'](self._peer);
  866. }
  867. self._dc.onmessage = function(e) {
  868. self.handleDataMessage(e);
  869. };
  870. };
  871. this._pc.onconnection = function() {
  872. console.log('SINK: onconnection triggered');
  873. };
  874. }
  875. this._pc.onclosedconnection = function() {
  876. // Remove socket handlers perhaps.
  877. };
  878. };
  879. SinkPeer.prototype.startDataChannel = function() {
  880. var self = this;
  881. this._dc = this._pc.createDataChannel(this._peer, { reliable: false });
  882. this._dc.binaryType = 'blob';
  883. if (!!this._handlers['connection']) {
  884. this._handlers['connection'](this._peer);
  885. }
  886. this._dc.onmessage = function(e) {
  887. self.handleDataMessage(e);
  888. };
  889. };
  890. /** Allows user to send data. */
  891. SinkPeer.prototype.send = function(data) {
  892. var ab = BinaryPack.pack(data);
  893. this._dc.send(ab);
  894. }
  895. // Handles a DataChannel message.
  896. // TODO: have these extend Peer, which will impl these generic handlers.
  897. SinkPeer.prototype.handleDataMessage = function(e) {
  898. var self = this;
  899. var fr = new FileReader();
  900. fr.onload = function(evt) {
  901. var ab = evt.target.result;
  902. var data = BinaryPack.unpack(ab);
  903. if (!!self._handlers['data']) {
  904. self._handlers['data'](data);
  905. }
  906. };
  907. fr.readAsArrayBuffer(e.data);
  908. }
  909. SinkPeer.prototype.on = function(code, cb) {
  910. this._handlers[code] = cb;
  911. }
  912. exports.Peer = SinkPeer;
  913. })(this);