sink.js 12 KB

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