You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. /* colibri.js -- a COLIBRI focus
  2. * The colibri spec has been submitted to the XMPP Standards Foundation
  3. * for publications as a XMPP extensions:
  4. * http://xmpp.org/extensions/inbox/colibri.html
  5. *
  6. * colibri.js is a participating focus, i.e. the focus participates
  7. * in the conference. The conference itself can be ad-hoc, through a
  8. * MUC, through PubSub, etc.
  9. *
  10. * colibri.js relies heavily on the strophe.jingle library available
  11. * from https://github.com/ESTOS/strophe.jingle
  12. * and interoperates with the Jitsi videobridge available from
  13. * https://jitsi.org/Projects/JitsiVideobridge
  14. */
  15. /*
  16. Copyright (c) 2013 ESTOS GmbH
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23. The above copyright notice and this permission notice shall be included in
  24. all copies or substantial portions of the Software.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31. THE SOFTWARE.
  32. */
  33. /* jshint -W117 */
  34. ColibriFocus.prototype = Object.create(SessionBase.prototype);
  35. function ColibriFocus(connection, bridgejid) {
  36. SessionBase.call(this, connection, Math.random().toString(36).substr(2, 12));
  37. this.bridgejid = bridgejid;
  38. this.peers = [];
  39. this.confid = null;
  40. // media types of the conference
  41. this.media = ['audio', 'video'];
  42. this.connection.jingle.sessions[this.sid] = this;
  43. this.mychannel = [];
  44. this.channels = [];
  45. this.remotessrc = {};
  46. // container for candidates from the focus
  47. // gathered before confid is known
  48. this.drip_container = [];
  49. // silly wait flag
  50. this.wait = true;
  51. }
  52. // creates a conferences with an initial set of peers
  53. ColibriFocus.prototype.makeConference = function (peers) {
  54. var self = this;
  55. if (this.confid !== null) {
  56. console.error('makeConference called twice? Ignoring...');
  57. // FIXME: just invite peers?
  58. return;
  59. }
  60. this.confid = 0; // !null
  61. this.peers = [];
  62. peers.forEach(function (peer) {
  63. self.peers.push(peer);
  64. self.channels.push([]);
  65. });
  66. if(connection.jingle.localAudio) {
  67. this.peerconnection.addStream(connection.jingle.localAudio);
  68. }
  69. if(connection.jingle.localVideo) {
  70. this.peerconnection.addStream(connection.jingle.localVideo);
  71. }
  72. this.peerconnection.oniceconnectionstatechange = function (event) {
  73. console.warn('ice connection state changed to', self.peerconnection.iceConnectionState);
  74. /*
  75. if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
  76. console.log('adding new remote SSRCs from iceconnectionstatechange');
  77. window.setTimeout(function() { self.modifySources(); }, 1000);
  78. }
  79. */
  80. };
  81. this.peerconnection.onsignalingstatechange = function (event) {
  82. console.warn(self.peerconnection.signalingState);
  83. /*
  84. if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
  85. console.log('adding new remote SSRCs from signalingstatechange');
  86. window.setTimeout(function() { self.modifySources(); }, 1000);
  87. }
  88. */
  89. };
  90. this.peerconnection.onaddstream = function (event) {
  91. // search the jid associated with this stream
  92. Object.keys(self.remotessrc).forEach(function (jid) {
  93. if (self.remotessrc[jid].join('\r\n').indexOf('mslabel:' + event.stream.id) != -1) {
  94. event.peerjid = jid;
  95. }
  96. });
  97. $(document).trigger('remotestreamadded.jingle', [event, self.sid]);
  98. };
  99. this.peerconnection.onicecandidate = function (event) {
  100. //console.log('focus onicecandidate', self.confid, new Date().getTime(), event.candidate);
  101. if (!event.candidate) {
  102. console.log('end of candidates');
  103. return;
  104. }
  105. self.sendIceCandidate(event.candidate);
  106. };
  107. this._makeConference();
  108. /*
  109. this.peerconnection.createOffer(
  110. function (offer) {
  111. self.peerconnection.setLocalDescription(
  112. offer,
  113. function () {
  114. // success
  115. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  116. // FIXME: could call _makeConference here and trickle candidates later
  117. self._makeConference();
  118. },
  119. function (error) {
  120. console.log('setLocalDescription failed', error);
  121. }
  122. );
  123. },
  124. function (error) {
  125. console.warn(error);
  126. }
  127. );
  128. */
  129. };
  130. ColibriFocus.prototype._makeConference = function () {
  131. var self = this;
  132. var elem = $iq({to: this.bridgejid, type: 'get'});
  133. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri'});
  134. this.media.forEach(function (name) {
  135. elem.c('content', {name: name});
  136. elem.c('channel', {
  137. initiator: 'true',
  138. expire: '15',
  139. endpoint: 'fix_me_focus_endpoint'}).up();
  140. for (var j = 0; j < self.peers.length; j++) {
  141. elem.c('channel', {
  142. initiator: 'true',
  143. expire: '15',
  144. endpoint: self.peers[j].substr(1 + self.peers[j].lastIndexOf('/'));
  145. }).up();
  146. }
  147. elem.up(); // end of content
  148. });
  149. /*
  150. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  151. localSDP.media.forEach(function (media, channel) {
  152. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  153. elem.c('content', {name: name});
  154. elem.c('channel', {initiator: 'false', expire: '15'});
  155. // FIXME: should reuse code from .toJingle
  156. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  157. for (var j = 0; j < mline.fmt.length; j++) {
  158. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  159. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  160. elem.up();
  161. }
  162. localSDP.TransportToJingle(channel, elem);
  163. elem.up(); // end of channel
  164. for (j = 0; j < self.peers.length; j++) {
  165. elem.c('channel', {initiator: 'true', expire:'15' }).up();
  166. }
  167. elem.up(); // end of content
  168. });
  169. */
  170. this.connection.sendIQ(elem,
  171. function (result) {
  172. self.createdConference(result);
  173. },
  174. function (error) {
  175. console.warn(error);
  176. }
  177. );
  178. };
  179. // callback when a conference was created
  180. ColibriFocus.prototype.createdConference = function (result) {
  181. console.log('created a conference on the bridge');
  182. var self = this;
  183. var tmp;
  184. this.confid = $(result).find('>conference').attr('id');
  185. var remotecontents = $(result).find('>conference>content').get();
  186. var numparticipants = 0;
  187. for (var i = 0; i < remotecontents.length; i++) {
  188. tmp = $(remotecontents[i]).find('>channel').get();
  189. this.mychannel.push($(tmp.shift()));
  190. numparticipants = tmp.length;
  191. for (j = 0; j < tmp.length; j++) {
  192. if (this.channels[j] === undefined) {
  193. this.channels[j] = [];
  194. }
  195. this.channels[j].push(tmp[j]);
  196. }
  197. }
  198. console.log('remote channels', this.channels);
  199. var bridgeSDP = new SDP('v=0\r\no=- 5151055458874951233 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1 RTP/SAVPF 111 103 104 0 8 106 105 13 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=mid:audio\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\na=fmtp:111 minptime=10\r\na=rtpmap:103 ISAC/16000\r\na=rtpmap:104 ISAC/32000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:106 CN/32000\r\na=rtpmap:105 CN/16000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:126 telephone-event/8000\r\na=maxptime:60\r\nm=video 1 RTP/SAVPF 100 116 117\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=mid:video\r\na=extmap:2 urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=rtpmap:100 VP8/90000\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 goog-remb\r\na=rtpmap:116 red/90000\r\na=rtpmap:117 ulpfec/90000\r\n');
  200. bridgeSDP.media.length = this.mychannel.length;
  201. var channel;
  202. /*
  203. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  204. bridgeSDP.media[channel] = '';
  205. // unchanged lines
  206. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'm=') + '\r\n';
  207. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'c=') + '\r\n';
  208. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:')) {
  209. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:') + '\r\n';
  210. }
  211. if (SDPUtil.find_line(localSDP.media[channel], 'a=mid:')) {
  212. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=mid:') + '\r\n';
  213. }
  214. if (SDPUtil.find_line(localSDP.media[channel], 'a=sendrecv')) {
  215. bridgeSDP.media[channel] += 'a=sendrecv\r\n';
  216. }
  217. if (SDPUtil.find_line(localSDP.media[channel], 'a=extmap:')) {
  218. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=extmap:').join('\r\n') + '\r\n';
  219. }
  220. // FIXME: should look at m-line and group the ids together
  221. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtpmap:')) {
  222. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtpmap:').join('\r\n') + '\r\n';
  223. }
  224. if (SDPUtil.find_line(localSDP.media[channel], 'a=fmtp:')) {
  225. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=fmtp:').join('\r\n') + '\r\n';
  226. }
  227. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp-fb:')) {
  228. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtcp-fb:').join('\r\n') + '\r\n';
  229. }
  230. // FIXME: changed lines -- a=sendrecv direction, a=setup direction
  231. }
  232. */
  233. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  234. // get the mixed ssrc
  235. tmp = $(this.mychannel[channel]).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  236. // FIXME: check rtp-level-relay-type
  237. if (tmp.length) {
  238. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  239. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  240. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
  241. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  242. } else {
  243. // make chrome happy... '3735928559' == 0xDEADBEEF
  244. // FIXME: this currently appears as two streams, should be one
  245. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  246. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  247. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
  248. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  249. }
  250. // FIXME: should take code from .fromJingle
  251. tmp = $(this.mychannel[channel]).find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  252. if (tmp.length) {
  253. bridgeSDP.media[channel] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  254. bridgeSDP.media[channel] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  255. tmp.find('>candidate').each(function () {
  256. bridgeSDP.media[channel] += SDPUtil.candidateFromJingle(this);
  257. });
  258. tmp = tmp.find('>fingerprint');
  259. if (tmp.length) {
  260. bridgeSDP.media[channel] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  261. bridgeSDP.media[channel] += 'a=setup:actpass\r\n'; // offer so always actpass
  262. }
  263. }
  264. }
  265. bridgeSDP.raw = bridgeSDP.session + bridgeSDP.media.join('');
  266. this.peerconnection.setRemoteDescription(
  267. new RTCSessionDescription({type: 'offer', sdp: bridgeSDP.raw}),
  268. function () {
  269. console.log('setRemoteDescription success');
  270. self.peerconnection.createAnswer(
  271. function (answer) {
  272. self.peerconnection.setLocalDescription(answer,
  273. function () {
  274. console.log('setLocalDescription succeded.');
  275. // make sure our presence is updated
  276. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  277. var elem = $iq({to: self.bridgejid, type: 'get'});
  278. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: self.confid});
  279. var localSDP = new SDP(self.peerconnection.localDescription.sdp);
  280. localSDP.media.forEach(function (media, channel) {
  281. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  282. elem.c('content', {name: name});
  283. elem.c('channel', {
  284. initiator: 'true',
  285. expire: '15',
  286. id: self.mychannel[channel].attr('id'),
  287. endpoint: 'fix_me_focus_endpoint'
  288. });
  289. // FIXME: should reuse code from .toJingle
  290. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  291. for (var j = 0; j < mline.fmt.length; j++) {
  292. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  293. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  294. elem.up();
  295. }
  296. localSDP.TransportToJingle(channel, elem);
  297. elem.up(); // end of channel
  298. elem.up(); // end of content
  299. });
  300. self.connection.sendIQ(elem,
  301. function (result) {
  302. // ...
  303. },
  304. function (error) {
  305. console.warn(error);
  306. }
  307. );
  308. // now initiate sessions
  309. for (var i = 0; i < numparticipants; i++) {
  310. self.initiate(self.peers[i], true);
  311. }
  312. },
  313. function (error) {
  314. console.warn('setLocalDescription failed.', error);
  315. }
  316. );
  317. },
  318. function (error) {
  319. console.warn('createAnswer failed.', error);
  320. }
  321. );
  322. /*
  323. for (var i = 0; i < numparticipants; i++) {
  324. self.initiate(self.peers[i], true);
  325. }
  326. */
  327. },
  328. function (error) {
  329. console.log('setRemoteDescription failed.', error);
  330. }
  331. );
  332. };
  333. // send a session-initiate to a new participant
  334. ColibriFocus.prototype.initiate = function (peer, isInitiator) {
  335. var participant = this.peers.indexOf(peer);
  336. console.log('tell', peer, participant);
  337. var sdp;
  338. if (this.peerconnection !== null && this.peerconnection.signalingState == 'stable') {
  339. sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  340. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  341. // throw away stuff we don't want
  342. // not needed with static offer
  343. sdp.removeSessionLines('a=group:');
  344. sdp.removeSessionLines('a=msid-semantic:'); // FIXME: not mapped over jingle anyway...
  345. for (var i = 0; i < sdp.media.length; i++) {
  346. sdp.removeMediaLines(i, 'a=rtcp-mux');
  347. sdp.removeMediaLines(i, 'a=ssrc:');
  348. sdp.removeMediaLines(i, 'a=crypto:');
  349. sdp.removeMediaLines(i, 'a=candidate:');
  350. sdp.removeMediaLines(i, 'a=ice-options:google-ice');
  351. sdp.removeMediaLines(i, 'a=ice-ufrag:');
  352. sdp.removeMediaLines(i, 'a=ice-pwd:');
  353. sdp.removeMediaLines(i, 'a=fingerprint:');
  354. sdp.removeMediaLines(i, 'a=setup:');
  355. if (1) { //i > 0) { // not for audio FIXME: does not work as intended
  356. // re-add all remote a=ssrcs
  357. for (var jid in this.remotessrc) {
  358. if (jid == peer) continue;
  359. sdp.media[i] += this.remotessrc[jid][i];
  360. }
  361. // and local a=ssrc lines
  362. sdp.media[i] += SDPUtil.find_lines(localSDP.media[i], 'a=ssrc').join('\r\n') + '\r\n';
  363. }
  364. }
  365. sdp.raw = sdp.session + sdp.media.join('');
  366. } else {
  367. console.error('can not initiate a new session without a stable peerconnection');
  368. return;
  369. }
  370. // add stuff we got from the bridge
  371. for (var j = 0; j < sdp.media.length; j++) {
  372. var chan = $(this.channels[participant][j]);
  373. console.log('channel id', chan.attr('id'));
  374. tmp = chan.find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  375. if (tmp.length) {
  376. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  377. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  378. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
  379. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  380. } else {
  381. // make chrome happy... '3735928559' == 0xDEADBEEF
  382. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  383. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  384. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
  385. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  386. }
  387. tmp = chan.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  388. if (tmp.length) {
  389. if (tmp.attr('ufrag'))
  390. sdp.media[j] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  391. if (tmp.attr('pwd'))
  392. sdp.media[j] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  393. // and the candidates...
  394. tmp.find('>candidate').each(function () {
  395. sdp.media[j] += SDPUtil.candidateFromJingle(this);
  396. });
  397. tmp = tmp.find('>fingerprint');
  398. if (tmp.length) {
  399. sdp.media[j] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  400. /*
  401. if (tmp.attr('direction')) {
  402. sdp.media[j] += 'a=setup:' + tmp.attr('direction') + '\r\n';
  403. }
  404. */
  405. sdp.media[j] += 'a=setup:actpass\r\n';
  406. }
  407. }
  408. }
  409. // make a new colibri session and configure it
  410. // FIXME: is it correct to use this.connection.jid when used in a MUC?
  411. var sess = new ColibriSession(this.connection.jid,
  412. Math.random().toString(36).substr(2, 12), // random string
  413. this.connection);
  414. sess.initiate(peer);
  415. sess.colibri = this;
  416. // We do not announce our audio per conference peer, so only video is set here
  417. sess.localVideo = this.connection.jingle.localVideo;
  418. sess.media_constraints = this.connection.jingle.media_constraints;
  419. sess.pc_constraints = this.connection.jingle.pc_constraints;
  420. sess.ice_config = this.connection.jingle.ice_config;
  421. this.connection.jingle.sessions[sess.sid] = sess;
  422. this.connection.jingle.jid2session[sess.peerjid] = sess;
  423. // send a session-initiate
  424. var init = $iq({to: peer, type: 'set'})
  425. .c('jingle',
  426. {xmlns: 'urn:xmpp:jingle:1',
  427. action: 'session-initiate',
  428. initiator: sess.me,
  429. sid: sess.sid
  430. }
  431. );
  432. sdp.toJingle(init, 'initiator');
  433. this.connection.sendIQ(init,
  434. function (res) {
  435. console.log('got result');
  436. },
  437. function (err) {
  438. console.log('got error');
  439. }
  440. );
  441. };
  442. // pull in a new participant into the conference
  443. ColibriFocus.prototype.addNewParticipant = function (peer) {
  444. var self = this;
  445. if (this.confid === 0) {
  446. // bad state
  447. console.log('confid does not exist yet, postponing', peer);
  448. window.setTimeout(function () {
  449. self.addNewParticipant(peer);
  450. }, 250);
  451. return;
  452. }
  453. var index = this.channels.length;
  454. this.channels.push([]);
  455. this.peers.push(peer);
  456. var elem = $iq({to: this.bridgejid, type: 'get'});
  457. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  458. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  459. localSDP.media.forEach(function (media, channel) {
  460. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  461. elem.c('content', {name: name});
  462. elem.c('channel', {
  463. initiator: 'true',
  464. expire:'15',
  465. endpoint: peer.substr(1 + peer.lastIndexOf('/'))
  466. });
  467. elem.up(); // end of channel
  468. elem.up(); // end of content
  469. });
  470. this.connection.sendIQ(elem,
  471. function (result) {
  472. var contents = $(result).find('>conference>content').get();
  473. for (var i = 0; i < contents.length; i++) {
  474. tmp = $(contents[i]).find('>channel').get();
  475. self.channels[index][i] = tmp[0];
  476. }
  477. self.initiate(peer, true);
  478. },
  479. function (error) {
  480. console.warn(error);
  481. }
  482. );
  483. };
  484. // update the channel description (payload-types + dtls fp) for a participant
  485. ColibriFocus.prototype.updateChannel = function (remoteSDP, participant) {
  486. console.log('change allocation for', this.confid);
  487. var change = $iq({to: this.bridgejid, type: 'set'});
  488. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  489. for (channel = 0; channel < this.channels[participant].length; channel++) {
  490. change.c('content', {name: channel === 0 ? 'audio' : 'video'});
  491. change.c('channel', {
  492. id: $(this.channels[participant][channel]).attr('id'),
  493. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  494. expire: '15'
  495. });
  496. var rtpmap = SDPUtil.find_lines(remoteSDP.media[channel], 'a=rtpmap:');
  497. rtpmap.forEach(function (val) {
  498. // TODO: too much copy-paste
  499. var rtpmap = SDPUtil.parse_rtpmap(val);
  500. change.c('payload-type', rtpmap);
  501. //
  502. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  503. /*
  504. if (SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id)) {
  505. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id));
  506. for (var k = 0; k < tmp.length; k++) {
  507. change.c('parameter', tmp[k]).up();
  508. }
  509. }
  510. */
  511. change.up();
  512. });
  513. // now add transport
  514. remoteSDP.TransportToJingle(channel, change);
  515. change.up(); // end of channel
  516. change.up(); // end of content
  517. }
  518. this.connection.sendIQ(change,
  519. function (res) {
  520. console.log('got result');
  521. },
  522. function (err) {
  523. console.log('got error');
  524. }
  525. );
  526. };
  527. // tell everyone about a new participants a=ssrc lines (isadd is true)
  528. // or a leaving participants a=ssrc lines
  529. ColibriFocus.prototype.sendSSRCUpdate = function (sdpMediaSsrcs, fromJid, isadd) {
  530. var self = this;
  531. this.peers.forEach(function (peerjid) {
  532. if (peerjid == fromJid) return;
  533. console.log('tell', peerjid, 'about ' + (isadd ? 'new' : 'removed') + ' ssrcs from', fromJid);
  534. if (!self.remotessrc[peerjid]) {
  535. // FIXME: this should only send to participants that are stable, i.e. who have sent a session-accept
  536. // possibly, this.remoteSSRC[session.peerjid] does not exist yet
  537. console.warn('do we really want to bother', peerjid, 'with updates yet?');
  538. }
  539. var peersess = self.connection.jingle.jid2session[peerjid];
  540. if(!peersess){
  541. console.warn('no session with peer: '+peerjid+' yet...');
  542. return;
  543. }
  544. self.sendSSRCUpdateIq(sdpMediaSsrcs, peersess.sid, peersess.initiator, peerjid, isadd);
  545. });
  546. };
  547. /**
  548. * Overrides SessionBase.addSource.
  549. *
  550. * @param elem proprietary 'add source' Jingle request(XML node).
  551. * @param fromJid JID of the participant to whom new ssrcs belong.
  552. */
  553. ColibriFocus.prototype.addSource = function (elem, fromJid) {
  554. var self = this;
  555. this.peerconnection.addSource(elem);
  556. var peerSsrc = this.remotessrc[fromJid];
  557. //console.log("On ADD", self.addssrc, peerSsrc);
  558. this.peerconnection.addssrc.forEach(function(val, idx){
  559. if(!peerSsrc[idx]){
  560. // add ssrc
  561. peerSsrc[idx] = val;
  562. } else {
  563. if(peerSsrc[idx].indexOf(val) == -1){
  564. peerSsrc[idx] = peerSsrc[idx]+val;
  565. }
  566. }
  567. });
  568. var oldRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  569. this.modifySources(function(){
  570. // Notify other participants about added ssrc
  571. var remoteSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  572. var newSSRCs = oldRemoteSdp.getNewMedia(remoteSDP);
  573. self.sendSSRCUpdate(newSSRCs, fromJid, true);
  574. });
  575. };
  576. /**
  577. * Overrides SessionBase.removeSource.
  578. *
  579. * @param elem proprietary 'remove source' Jingle request(XML node).
  580. * @param fromJid JID of the participant to whom removed ssrcs belong.
  581. */
  582. ColibriFocus.prototype.removeSource = function (elem, fromJid) {
  583. var self = this;
  584. this.peerconnection.removeSource(elem);
  585. var peerSsrc = this.remotessrc[fromJid];
  586. //console.log("On REMOVE", self.removessrc, peerSsrc);
  587. this.peerconnection.removessrc.forEach(function(val, idx){
  588. if(peerSsrc[idx]){
  589. // Remove ssrc
  590. peerSsrc[idx] = peerSsrc[idx].replace(val, '');
  591. }
  592. });
  593. var oldSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  594. this.modifySources(function(){
  595. // Notify other participants about removed ssrc
  596. var remoteSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  597. var removedSSRCs = remoteSDP.getNewMedia(oldSDP);
  598. self.sendSSRCUpdate(removedSSRCs, fromJid, false);
  599. });
  600. };
  601. ColibriFocus.prototype.setRemoteDescription = function (session, elem, desctype) {
  602. var participant = this.peers.indexOf(session.peerjid);
  603. console.log('Colibri.setRemoteDescription from', session.peerjid, participant);
  604. var remoteSDP = new SDP('');
  605. var channel;
  606. remoteSDP.fromJingle(elem);
  607. // ACT 1: change allocation on bridge
  608. this.updateChannel(remoteSDP, participant);
  609. // ACT 2: tell anyone else about the new SSRCs
  610. this.sendSSRCUpdate(remoteSDP.getMediaSsrcMap(), session.peerjid, true);
  611. // ACT 3: note the SSRCs
  612. this.remotessrc[session.peerjid] = [];
  613. for (channel = 0; channel < this.channels[participant].length; channel++) {
  614. //if (channel == 0) continue; FIXME: does not work as intended
  615. if (SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').length) {
  616. this.remotessrc[session.peerjid][channel] = SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n';
  617. }
  618. }
  619. // ACT 4: add new a=ssrc lines to local remotedescription
  620. for (channel = 0; channel < this.channels[participant].length; channel++) {
  621. //if (channel == 0) continue; FIXME: does not work as intended
  622. if (SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').length) {
  623. this.peerconnection.enqueueAddSsrc(
  624. channel,
  625. SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n'
  626. );
  627. }
  628. }
  629. this.modifySources();
  630. };
  631. // relay ice candidates to bridge using trickle
  632. ColibriFocus.prototype.addIceCandidate = function (session, elem) {
  633. var self = this;
  634. var participant = this.peers.indexOf(session.peerjid);
  635. //console.log('change transport allocation for', this.confid, session.peerjid, participant);
  636. var change = $iq({to: this.bridgejid, type: 'set'});
  637. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  638. $(elem).each(function () {
  639. var name = $(this).attr('name');
  640. var channel = name == 'audio' ? 0 : 1; // FIXME: search mlineindex in localdesc
  641. change.c('content', {name: name});
  642. change.c('channel', {
  643. id: $(self.channels[participant][channel]).attr('id'),
  644. endpoint: $(self.channels[participant][channel]).attr('endpoint'),
  645. expire: '15'
  646. });
  647. $(this).find('>transport').each(function () {
  648. change.c('transport', {
  649. ufrag: $(this).attr('ufrag'),
  650. pwd: $(this).attr('pwd'),
  651. xmlns: $(this).attr('xmlns')
  652. });
  653. $(this).find('>candidate').each(function () {
  654. /* not yet
  655. if (this.getAttribute('protocol') == 'tcp' && this.getAttribute('port') == 0) {
  656. // chrome generates TCP candidates with port 0
  657. return;
  658. }
  659. */
  660. var line = SDPUtil.candidateFromJingle(this);
  661. change.c('candidate', SDPUtil.candidateToJingle(line)).up();
  662. });
  663. change.up(); // end of transport
  664. });
  665. change.up(); // end of channel
  666. change.up(); // end of content
  667. });
  668. // FIXME: need to check if there is at least one candidate when filtering TCP ones
  669. this.connection.sendIQ(change,
  670. function (res) {
  671. console.log('got result');
  672. },
  673. function (err) {
  674. console.error('got error', err);
  675. }
  676. );
  677. };
  678. // send our own candidate to the bridge
  679. ColibriFocus.prototype.sendIceCandidate = function (candidate) {
  680. var self = this;
  681. //console.log('candidate', candidate);
  682. if (!candidate) {
  683. console.log('end of candidates');
  684. return;
  685. }
  686. if (this.drip_container.length === 0) {
  687. // start 20ms callout
  688. window.setTimeout(function () {
  689. if (self.drip_container.length === 0) return;
  690. self.sendIceCandidates(self.drip_container);
  691. self.drip_container = [];
  692. }, 20);
  693. }
  694. this.drip_container.push(candidate);
  695. };
  696. // sort and send multiple candidates
  697. ColibriFocus.prototype.sendIceCandidates = function (candidates) {
  698. var self = this;
  699. var mycands = $iq({to: this.bridgejid, type: 'set'});
  700. mycands.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  701. // FIXME: multi-candidate logic is taken from strophe.jingle, should be refactored there
  702. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  703. for (var mid = 0; mid < localSDP.media.length; mid++) {
  704. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  705. if (cands.length > 0) {
  706. mycands.c('content', {name: cands[0].sdpMid });
  707. mycands.c('channel', {
  708. id: $(this.mychannel[cands[0].sdpMLineIndex]).attr('id'),
  709. endpoint: $(this.mychannel[cands[0].sdpMLineIndex]).attr('endpoint'),
  710. expire: '15'
  711. });
  712. mycands.c('transport', {xmlns: 'urn:xmpp:jingle:transports:ice-udp:1'});
  713. for (var i = 0; i < cands.length; i++) {
  714. mycands.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  715. }
  716. mycands.up(); // transport
  717. mycands.up(); // channel
  718. mycands.up(); // content
  719. }
  720. }
  721. console.log('send cands', candidates);
  722. this.connection.sendIQ(mycands,
  723. function (res) {
  724. console.log('got result');
  725. },
  726. function (err) {
  727. console.error('got error', err);
  728. }
  729. );
  730. };
  731. ColibriFocus.prototype.terminate = function (session, reason) {
  732. console.log('remote session terminated from', session.peerjid);
  733. var participant = this.peers.indexOf(session.peerjid);
  734. if (!this.remotessrc[session.peerjid] || participant == -1) {
  735. return;
  736. }
  737. var ssrcs = this.remotessrc[session.peerjid];
  738. for (var i = 0; i < ssrcs.length; i++) {
  739. this.peerconnection.enqueueRemoveSsrc(i, ssrcs[i]);
  740. }
  741. // remove from this.peers
  742. this.peers.splice(participant, 1);
  743. // expire channel on bridge
  744. var change = $iq({to: this.bridgejid, type: 'set'});
  745. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  746. for (var channel = 0; channel < this.channels[participant].length; channel++) {
  747. change.c('content', {name: channel === 0 ? 'audio' : 'video'});
  748. change.c('channel', {
  749. id: $(this.channels[participant][channel]).attr('id'),
  750. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  751. expire: '0'
  752. });
  753. change.up(); // end of channel
  754. change.up(); // end of content
  755. }
  756. this.connection.sendIQ(change,
  757. function (res) {
  758. console.log('got result');
  759. },
  760. function (err) {
  761. console.error('got error', err);
  762. }
  763. );
  764. // and remove from channels
  765. this.channels.splice(participant, 1);
  766. // tell everyone about the ssrcs to be removed
  767. var sdp = new SDP('');
  768. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  769. var contents = SDPUtil.find_lines(localSDP.raw, 'a=mid:').map(SDPUtil.parse_mid);
  770. for (var j = 0; j < ssrcs.length; j++) {
  771. sdp.media[j] = 'a=mid:' + contents[j] + '\r\n';
  772. sdp.media[j] += ssrcs[j];
  773. this.peerconnection.enqueueRemoveSsrc(j, ssrcs[j]);
  774. }
  775. this.sendSSRCUpdate(sdp.getMediaSsrcMap(), session.peerjid, false);
  776. delete this.remotessrc[session.peerjid];
  777. this.modifySources();
  778. };