sink.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. function Peer(options) {
  2. if (!(this instanceof Peer)) return new Peer(options);
  3. EventEmitter.call(this);
  4. this._config = options.config || { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] };
  5. this._peer = options.source || null;
  6. this._video = options.video;
  7. this._data = options.data != undefined ? options.data : true;
  8. this._audio = options.audio;
  9. this._pc = null;
  10. this._id = null;
  11. this._dc = null;
  12. this._socket = new WebSocket(options.ws || 'ws://localhost');
  13. var self = this;
  14. this._socket.onopen = function() {
  15. self.socketInit();
  16. };
  17. // Testing firefox.
  18. // MULTICONNECTION doesn't work still.
  19. if (browserisms == 'Firefox' && !options.source) {
  20. if (!Peer.usedPorts) {
  21. Peer.usedPorts = [];
  22. }
  23. this.localPort = util.randomPort();
  24. while (Peer.usedPorts.indexOf(this.localPort) != -1) {
  25. this.localPort = util.randomPort();
  26. }
  27. this.remotePort = util.randomPort();
  28. while (this.remotePort == this.localPort ||
  29. Peer.usedPorts.indexOf(this.localPort) != -1) {
  30. this.remotePort = util.randomPort();
  31. }
  32. Peer.usedPorts.push(this.remotePort);
  33. Peer.usedPorts.push(this.localPort);
  34. }
  35. };
  36. util.inherits(Peer, EventEmitter);
  37. /** Start up websocket communications. */
  38. Peer.prototype.socketInit = function() {
  39. var self = this;
  40. // Multiple sinks to one source.
  41. if (!!this._peer) {
  42. this._socket.send(JSON.stringify({
  43. type: 'SINK',
  44. source: this._peer,
  45. isms: browserisms
  46. }));
  47. this._socket.onmessage = function(event) {
  48. var message = JSON.parse(event.data);
  49. switch (message.type) {
  50. case 'SINK-ID':
  51. self._id = message.id;
  52. self.emit('ready', self._id);
  53. self.startPeerConnection();
  54. break;
  55. case 'OFFER':
  56. var sdp = message.sdp;
  57. try {
  58. sdp = new RTCSessionDescription(message.sdp);
  59. } catch(e) {
  60. console.log('Firefox');
  61. }
  62. self._pc.setRemoteDescription(sdp, function() {
  63. console.log('setRemoteDescription: offer');
  64. // If we also have to set up a stream on the sink end, do so.
  65. self.handleStream(false, function() {
  66. self.maybeBrowserisms(false);
  67. });
  68. }, function(err) {
  69. console.log('failed to setRemoteDescription with offer, ', err);
  70. });
  71. break;
  72. case 'CANDIDATE':
  73. console.log(message.candidate);
  74. var candidate = new RTCIceCandidate(message.candidate);
  75. self._pc.addIceCandidate(candidate);
  76. break;
  77. case 'PORT':
  78. if (browserisms && browserisms == 'Firefox') {
  79. if (!Peer.usedPorts) {
  80. Peer.usedPorts = [];
  81. }
  82. Peer.usedPorts.push(message.local);
  83. Peer.usedPorts.push(message.remote);
  84. self._pc.connectDataConnection(message.local, message.remote);
  85. break;
  86. }
  87. case 'DEFAULT':
  88. console.log('SINK: unrecognized message ', message.type);
  89. break;
  90. }
  91. };
  92. } else {
  93. // Otherwise, this sink is the originator to another sink and should wait
  94. // for an alert.
  95. this._socket.send(JSON.stringify({
  96. type: 'SOURCE',
  97. isms: browserisms
  98. }));
  99. this._socket.onmessage = function(event) {
  100. var message = JSON.parse(event.data);
  101. switch (message.type) {
  102. case 'SOURCE-ID':
  103. self._id = message.id;
  104. self.emit('ready', self._id);
  105. break;
  106. case 'SINK-CONNECTED':
  107. self._peer = message.sink;
  108. self.startPeerConnection();
  109. self.handleStream(true, function() {
  110. self.maybeBrowserisms(true);
  111. });
  112. break;
  113. case 'ANSWER':
  114. var sdp = message.sdp;
  115. try {
  116. sdp = new RTCSessionDescription(message.sdp);
  117. } catch(e) {
  118. console.log('Firefox');
  119. }
  120. self._pc.setRemoteDescription(sdp, function() {
  121. console.log('setRemoteDescription: answer');
  122. // Firefoxism
  123. if (browserisms == 'Firefox') {
  124. self._pc.connectDataConnection(self.localPort, self.remotePort);
  125. self._socket.send(JSON.stringify({
  126. type: 'PORT',
  127. dst: self._peer,
  128. remote: self.localPort,
  129. local: self.remotePort
  130. }));
  131. }
  132. console.log('ORIGINATOR: PeerConnection success');
  133. }, function(err) {
  134. console.log('failed to setRemoteDescription, ', err);
  135. });
  136. break;
  137. case 'CANDIDATE':
  138. console.log(message.candidate);
  139. var candidate = new RTCIceCandidate(message.candidate);
  140. self._pc.addIceCandidate(candidate);
  141. break;
  142. case 'DEFAULT':
  143. console.log('ORIGINATOR: message not recognized ', message.type);
  144. }
  145. };
  146. }
  147. // Makes sure things clean up neatly.
  148. window.onbeforeunload = function() {
  149. if (!!self._pc) {
  150. self._pc.close();
  151. }
  152. if (!!self._socket && !!self._peer) {
  153. self._socket.send(JSON.stringify({ type: 'LEAVE', dst: self._peer }));
  154. if (!!self._dc) {
  155. self._dc.close();
  156. }
  157. }
  158. }
  159. };
  160. /** Takes care of ice handlers. */
  161. Peer.prototype.setupIce = function() {
  162. var self = this;
  163. this._pc.onicecandidate = function(event) {
  164. console.log('candidates received');
  165. if (event.candidate) {
  166. self._socket.send(JSON.stringify({
  167. type: 'CANDIDATE',
  168. candidate: event.candidate,
  169. dst: self._peer
  170. }));
  171. } else {
  172. console.log("End of candidates.");
  173. }
  174. };
  175. };
  176. /** Starts a PeerConnection and sets up handlers. */
  177. Peer.prototype.startPeerConnection = function() {
  178. this._pc = new RTCPeerConnection(this._config, { optional:[ { RtpDataChannels: true } ]});
  179. this.setupIce();
  180. this.setupAudioVideo();
  181. };
  182. /** Decide whether to handle Firefoxisms. */
  183. Peer.prototype.maybeBrowserisms = function(originator) {
  184. var self = this;
  185. if (browserisms == 'Firefox' && !this._video && !this._audio && !this._stream) {
  186. getUserMedia({ audio: true, fake: true }, function(s) {
  187. self._pc.addStream(s);
  188. if (originator) {
  189. self.makeOffer();
  190. } else {
  191. self.makeAnswer();
  192. }
  193. }, function(err) { console.log('crap'); });
  194. } else {
  195. if (originator) {
  196. this.makeOffer();
  197. } else {
  198. this.makeAnswer();
  199. }
  200. }
  201. }
  202. /** Create an answer for PC. */
  203. Peer.prototype.makeAnswer = function() {
  204. var self = this;
  205. this._pc.createAnswer(function(answer) {
  206. console.log('createAnswer');
  207. self._pc.setLocalDescription(answer, function() {
  208. console.log('setLocalDescription: answer');
  209. self._socket.send(JSON.stringify({
  210. type: 'ANSWER',
  211. src: self._id,
  212. sdp: answer,
  213. dst: self._peer
  214. }));
  215. }, function(err) {
  216. console.log('failed to setLocalDescription, ', err)
  217. });
  218. }, function(err) {
  219. console.log('failed to create answer, ', err)
  220. });
  221. };
  222. /** Create an offer for PC. */
  223. Peer.prototype.makeOffer = function() {
  224. var self = this;
  225. this._pc.createOffer(function(offer) {
  226. console.log('createOffer')
  227. self._pc.setLocalDescription(offer, function() {
  228. console.log('setLocalDescription: offer');
  229. self._socket.send(JSON.stringify({
  230. type: 'OFFER',
  231. sdp: offer,
  232. dst: self._peer,
  233. src: self._id
  234. }));
  235. }, function(err) {
  236. console.log('failed to setLocalDescription, ', err);
  237. });
  238. });
  239. };
  240. /** Sets up A/V stream handler. */
  241. Peer.prototype.setupAudioVideo = function() {
  242. var self = this;
  243. console.log('onaddstream handler added');
  244. this._pc.onaddstream = function(obj) {
  245. console.log('Remote stream added');
  246. this._stream = true;
  247. self.emit('remotestream', obj.type, obj.stream);
  248. };
  249. };
  250. /** Handle the different types of streams requested by user. */
  251. Peer.prototype.handleStream = function(originator, cb) {
  252. if (this._data) {
  253. this.setupDataChannel(originator);
  254. }
  255. this.getAudioVideo(originator, cb);
  256. };
  257. /** Get A/V streams. */
  258. Peer.prototype.getAudioVideo = function(originator, cb) {
  259. var self = this;
  260. if (this._video) {
  261. getUserMedia({ video: true }, function(vstream) {
  262. self._pc.addStream(vstream);
  263. console.log('Local video stream added');
  264. self.emit('localstream', 'video', vstream);
  265. if (self._audio) {
  266. getUserMedia({ audio: true }, function(astream) {
  267. self._pc.addStream(astream);
  268. console.log('Local audio stream added');
  269. self.emit('localstream', 'audio', astream);
  270. cb();
  271. }, function(err) { console.log('Audio cannot start'); cb(); });
  272. } else {
  273. cb();
  274. }
  275. }, function(err) { console.log('Video cannot start', err); cb(); });
  276. } else if (this._audio) {
  277. getUserMedia({ audio: true }, function(astream) {
  278. self._pc.addStream(astream);
  279. self.emit('localstream', 'audio', astream);
  280. cb();
  281. }, function(err) { console.log('Audio cannot start'); cb(); });
  282. } else {
  283. cb();
  284. }
  285. };
  286. /** Sets up DataChannel handlers. */
  287. Peer.prototype.setupDataChannel = function(originator, cb) {
  288. var self = this;
  289. if (originator) {
  290. /** ORIGINATOR SETUP */
  291. if (browserisms == 'Webkit') {
  292. this._pc.onstatechange = function() {
  293. console.log('State Change: ', self._pc.readyState);
  294. /*if (self._pc.readyState == 'active') {
  295. console.log('ORIGINATOR: active state detected');
  296. self._dc = self._pc.createDataChannel('StreamAPI', { reliable: false });
  297. self._dc.binaryType = 'blob';
  298. if (!!self._handlers['connection']) {
  299. self._handlers['connection'](self._peer);
  300. }
  301. self._dc.onmessage = function(e) {
  302. self.handleDataMessage(e);
  303. };
  304. }*/
  305. }
  306. } else {
  307. this._pc.onconnection = function() {
  308. console.log('ORIGINATOR: onconnection triggered');
  309. self.startDataChannel();
  310. };
  311. }
  312. } else {
  313. /** TARGET SETUP */
  314. this._pc.ondatachannel = function(dc) {
  315. console.log('SINK: ondatachannel triggered');
  316. self._dc = dc;
  317. self._dc.binaryType = 'blob';
  318. self.emit('connection', self._peer);
  319. self._dc.onmessage = function(e) {
  320. self.handleDataMessage(e);
  321. };
  322. };
  323. this._pc.onconnection = function() {
  324. console.log('SINK: onconnection triggered');
  325. };
  326. }
  327. this._pc.onclosedconnection = function() {
  328. // Remove socket handlers perhaps.
  329. };
  330. };
  331. Peer.prototype.startDataChannel = function() {
  332. var self = this;
  333. this._dc = this._pc.createDataChannel(this._peer, { reliable: false });
  334. this._dc.binaryType = 'blob';
  335. this.emit('connection', this._peer);
  336. this._dc.onmessage = function(e) {
  337. self.handleDataMessage(e);
  338. };
  339. };
  340. /** Allows user to send data. */
  341. Peer.prototype.send = function(data) {
  342. var ab = BinaryPack.pack(data);
  343. this._dc.send(ab);
  344. }
  345. // Handles a DataChannel message.
  346. // TODO: have these extend Peer, which will impl these generic handlers.
  347. Peer.prototype.handleDataMessage = function(e) {
  348. var self = this;
  349. var fr = new FileReader();
  350. fr.onload = function(evt) {
  351. var ab = evt.target.result;
  352. var data = BinaryPack.unpack(ab);
  353. self.emit('data', data);
  354. };
  355. fr.readAsArrayBuffer(e.data);
  356. }
  357. exports.Peer = Peer;