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.

colibri.focus.js 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  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. /**
  41. * Local XMPP resource used to join the multi user chat.
  42. * @type {*}
  43. */
  44. this.myMucResource = Strophe.getResourceFromJid(connection.emuc.myroomjid);
  45. /**
  46. * Default channel expire value in seconds.
  47. * @type {number}
  48. */
  49. this.channelExpire
  50. = ('number' === typeof(config.channelExpire))
  51. ? config.channelExpire
  52. : 15;
  53. /**
  54. * Default channel last-n value.
  55. * @type {number}
  56. */
  57. this.channelLastN
  58. = ('number' === typeof(config.channelLastN)) ? config.channelLastN : -1;
  59. // media types of the conference
  60. if (config.openSctp)
  61. this.media = ['audio', 'video', 'data'];
  62. else
  63. this.media = ['audio', 'video'];
  64. this.connection.jingle.sessions[this.sid] = this;
  65. this.mychannel = [];
  66. this.channels = [];
  67. this.remotessrc = {};
  68. // container for candidates from the focus
  69. // gathered before confid is known
  70. this.drip_container = [];
  71. // silly wait flag
  72. this.wait = true;
  73. this.recordingEnabled = false;
  74. // stores information about the endpoints (i.e. display names) to
  75. // be sent to the videobridge.
  76. this.endpointsInfo = null;
  77. }
  78. // creates a conferences with an initial set of peers
  79. ColibriFocus.prototype.makeConference = function (peers) {
  80. var self = this;
  81. if (this.confid !== null) {
  82. console.error('makeConference called twice? Ignoring...');
  83. // FIXME: just invite peers?
  84. return;
  85. }
  86. this.confid = 0; // !null
  87. this.peers = [];
  88. peers.forEach(function (peer) {
  89. self.peers.push(peer);
  90. self.channels.push([]);
  91. });
  92. this.peerconnection
  93. = new TraceablePeerConnection(
  94. this.connection.jingle.ice_config,
  95. this.connection.jingle.pc_constraints );
  96. if(this.connection.jingle.localAudio) {
  97. this.peerconnection.addStream(this.connection.jingle.localAudio);
  98. }
  99. if(this.connection.jingle.localVideo) {
  100. this.peerconnection.addStream(this.connection.jingle.localVideo);
  101. }
  102. this.peerconnection.oniceconnectionstatechange = function (event) {
  103. console.warn('ice connection state changed to', self.peerconnection.iceConnectionState);
  104. /*
  105. if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
  106. console.log('adding new remote SSRCs from iceconnectionstatechange');
  107. window.setTimeout(function() { self.modifySources(); }, 1000);
  108. }
  109. */
  110. };
  111. this.peerconnection.onsignalingstatechange = function (event) {
  112. console.warn(self.peerconnection.signalingState);
  113. /*
  114. if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
  115. console.log('adding new remote SSRCs from signalingstatechange');
  116. window.setTimeout(function() { self.modifySources(); }, 1000);
  117. }
  118. */
  119. };
  120. this.peerconnection.onaddstream = function (event) {
  121. // search the jid associated with this stream
  122. Object.keys(self.remotessrc).forEach(function (jid) {
  123. if (self.remotessrc[jid].join('\r\n').indexOf('mslabel:' + event.stream.id) != -1) {
  124. event.peerjid = jid;
  125. }
  126. });
  127. $(document).trigger('remotestreamadded.jingle', [event, self.sid]);
  128. };
  129. this.peerconnection.onicecandidate = function (event) {
  130. //console.log('focus onicecandidate', self.confid, new Date().getTime(), event.candidate);
  131. if (!event.candidate) {
  132. console.log('end of candidates');
  133. return;
  134. }
  135. self.sendIceCandidate(event.candidate);
  136. };
  137. this._makeConference();
  138. /*
  139. this.peerconnection.createOffer(
  140. function (offer) {
  141. self.peerconnection.setLocalDescription(
  142. offer,
  143. function () {
  144. // success
  145. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  146. // FIXME: could call _makeConference here and trickle candidates later
  147. self._makeConference();
  148. },
  149. function (error) {
  150. console.log('setLocalDescription failed', error);
  151. }
  152. );
  153. },
  154. function (error) {
  155. console.warn(error);
  156. }
  157. );
  158. */
  159. };
  160. // Sends a COLIBRI message which enables or disables (according to 'state') the
  161. // recording on the bridge. Waits for the result IQ and calls 'callback' with
  162. // the new recording state, according to the IQ.
  163. ColibriFocus.prototype.setRecording = function(state, token, callback) {
  164. var self = this;
  165. var elem = $iq({to: this.bridgejid, type: 'set'});
  166. elem.c('conference', {
  167. xmlns: 'http://jitsi.org/protocol/colibri',
  168. id: this.confid
  169. });
  170. elem.c('recording', {state: state, token: token});
  171. elem.up();
  172. this.connection.sendIQ(elem,
  173. function (result) {
  174. console.log('Set recording "', state, '". Result:', result);
  175. var recordingElem = $(result).find('>conference>recording');
  176. var newState = ('true' === recordingElem.attr('state'));
  177. self.recordingEnabled = newState;
  178. callback(newState);
  179. },
  180. function (error) {
  181. console.warn(error);
  182. }
  183. );
  184. };
  185. /*
  186. * Updates the display name for an endpoint with a specific jid.
  187. * jid: the jid associated with the endpoint.
  188. * displayName: the new display name for the endpoint.
  189. */
  190. ColibriFocus.prototype.setEndpointDisplayName = function(jid, displayName) {
  191. var endpointId = jid.substr(1 + jid.lastIndexOf('/'));
  192. var update = false;
  193. if (this.endpointsInfo === null) {
  194. this.endpointsInfo = {};
  195. }
  196. var endpointInfo = this.endpointsInfo[endpointId];
  197. if ('undefined' === typeof endpointInfo) {
  198. endpointInfo = this.endpointsInfo[endpointId] = {};
  199. }
  200. if (endpointInfo['displayname'] !== displayName) {
  201. endpointInfo['displayname'] = displayName;
  202. update = true;
  203. }
  204. if (update) {
  205. this.updateEndpoints();
  206. }
  207. };
  208. /*
  209. * Sends a colibri message to the bridge that contains the
  210. * current endpoints and their display names.
  211. */
  212. ColibriFocus.prototype.updateEndpoints = function() {
  213. if (this.confid === null
  214. || this.endpointsInfo === null) {
  215. return;
  216. }
  217. if (this.confid === 0) {
  218. // the colibri conference is currently initiating
  219. var self = this;
  220. window.setTimeout(function() { self.updateEndpoints()}, 1000);
  221. return;
  222. }
  223. var elem = $iq({to: this.bridgejid, type: 'set'});
  224. elem.c('conference', {
  225. xmlns: 'http://jitsi.org/protocol/colibri',
  226. id: this.confid
  227. });
  228. for (var id in this.endpointsInfo) {
  229. elem.c('endpoint');
  230. elem.attrs({ id: id,
  231. displayname: this.endpointsInfo[id]['displayname']
  232. });
  233. elem.up();
  234. }
  235. //elem.up(); //conference
  236. this.connection.sendIQ(
  237. elem,
  238. function (result) {},
  239. function (error) { console.warn(error); }
  240. );
  241. };
  242. ColibriFocus.prototype._makeConference = function () {
  243. var self = this;
  244. var elem = $iq({ to: this.bridgejid, type: 'get' });
  245. elem.c('conference', { xmlns: 'http://jitsi.org/protocol/colibri' });
  246. this.media.forEach(function (name) {
  247. var elemName;
  248. var elemAttrs = { initiator: 'true', expire: self.channelExpire };
  249. if ('data' === name)
  250. {
  251. elemName = 'sctpconnection';
  252. elemAttrs['port'] = 5000;
  253. }
  254. else
  255. {
  256. elemName = 'channel';
  257. if (('video' === name) && (self.channelLastN >= 0))
  258. elemAttrs['last-n'] = self.channelLastN;
  259. }
  260. elem.c('content', { name: name });
  261. elem.c(elemName, elemAttrs);
  262. elem.attrs({ endpoint: self.myMucResource });
  263. elem.up();// end of channel/sctpconnection
  264. for (var j = 0; j < self.peers.length; j++) {
  265. var peer = self.peers[j];
  266. elem.c(elemName, elemAttrs);
  267. elem.attrs({ endpoint: peer.substr(1 + peer.lastIndexOf('/')) });
  268. if ('channel' === elemName && config.useRtcpMux) {
  269. elem.c('rtcp-mux').up();
  270. }
  271. elem.up(); // end of channel/sctpconnection
  272. }
  273. elem.up(); // end of content
  274. });
  275. if (this.endpointsInfo !== null) {
  276. for (var id in this.endpointsInfo) {
  277. elem.c('endpoint');
  278. elem.attrs({ id: id,
  279. displayname: this.endpointsInfo[id]['displayname']
  280. });
  281. elem.up();
  282. }
  283. }
  284. /*
  285. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  286. localSDP.media.forEach(function (media, channel) {
  287. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  288. elem.c('content', {name: name});
  289. elem.c('channel', {initiator: 'false', expire: self.channelExpire});
  290. // FIXME: should reuse code from .toJingle
  291. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  292. for (var j = 0; j < mline.fmt.length; j++) {
  293. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  294. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  295. elem.up();
  296. }
  297. localSDP.TransportToJingle(channel, elem);
  298. elem.up(); // end of channel
  299. for (j = 0; j < self.peers.length; j++) {
  300. elem.c('channel', {initiator: 'true', expire: self.channelExpire }).up();
  301. }
  302. elem.up(); // end of content
  303. });
  304. */
  305. this.connection.sendIQ(elem,
  306. function (result) {
  307. self.createdConference(result);
  308. },
  309. function (error) {
  310. console.warn(error);
  311. }
  312. );
  313. };
  314. // callback when a conference was created
  315. ColibriFocus.prototype.createdConference = function (result) {
  316. console.log('created a conference on the bridge');
  317. var self = this;
  318. var tmp;
  319. this.confid = $(result).find('>conference').attr('id');
  320. var remotecontents = $(result).find('>conference>content').get();
  321. var numparticipants = 0;
  322. for (var i = 0; i < remotecontents.length; i++)
  323. {
  324. var contentName = $(remotecontents[i]).attr('name');
  325. var channelName
  326. = contentName !== 'data' ? '>channel' : '>sctpconnection';
  327. tmp = $(remotecontents[i]).find(channelName).get();
  328. this.mychannel.push($(tmp.shift()));
  329. numparticipants = tmp.length;
  330. for (j = 0; j < tmp.length; j++) {
  331. if (this.channels[j] === undefined) {
  332. this.channels[j] = [];
  333. }
  334. this.channels[j].push(tmp[j]);
  335. }
  336. }
  337. console.log('remote channels', this.channels);
  338. // Notify that the focus has created the conference on the bridge
  339. $(document).trigger('conferenceCreated.jingle', [self]);
  340. var bridgeSDP = new SDP(
  341. 'v=0\r\n' +
  342. 'o=- 5151055458874951233 2 IN IP4 127.0.0.1\r\n' +
  343. 's=-\r\n' +
  344. 't=0 0\r\n' +
  345. /* Audio */
  346. 'm=audio 1 RTP/SAVPF 111 103 104 0 8 106 105 13 126\r\n' +
  347. 'c=IN IP4 0.0.0.0\r\n' +
  348. 'a=rtcp:1 IN IP4 0.0.0.0\r\n' +
  349. 'a=mid:audio\r\n' +
  350. 'a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\n' +
  351. 'a=sendrecv\r\n' +
  352. 'a=rtpmap:111 opus/48000/2\r\n' +
  353. 'a=fmtp:111 minptime=10\r\n' +
  354. 'a=rtpmap:103 ISAC/16000\r\n' +
  355. 'a=rtpmap:104 ISAC/32000\r\n' +
  356. 'a=rtpmap:0 PCMU/8000\r\n' +
  357. 'a=rtpmap:8 PCMA/8000\r\n' +
  358. 'a=rtpmap:106 CN/32000\r\n' +
  359. 'a=rtpmap:105 CN/16000\r\n' +
  360. 'a=rtpmap:13 CN/8000\r\n' +
  361. 'a=rtpmap:126 telephone-event/8000\r\n' +
  362. 'a=maxptime:60\r\n' +
  363. (config.useRtcpMux ? 'a=rtcp-mux\r\n' : '') +
  364. /* Video */
  365. 'm=video 1 RTP/SAVPF 100 116 117\r\n' +
  366. 'c=IN IP4 0.0.0.0\r\n' +
  367. 'a=rtcp:1 IN IP4 0.0.0.0\r\n' +
  368. 'a=mid:video\r\n' +
  369. 'a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\r\n' +
  370. 'a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n' +
  371. 'a=sendrecv\r\n' +
  372. 'a=rtpmap:100 VP8/90000\r\n' +
  373. 'a=rtcp-fb:100 ccm fir\r\n' +
  374. 'a=rtcp-fb:100 nack\r\n' +
  375. 'a=rtcp-fb:100 goog-remb\r\n' +
  376. 'a=rtpmap:116 red/90000\r\n' +
  377. 'a=rtpmap:117 ulpfec/90000\r\n' +
  378. (config.useRtcpMux ? 'a=rtcp-mux\r\n' : '') +
  379. /* Data SCTP */
  380. (config.openSctp ?
  381. 'm=application 1 DTLS/SCTP 5000\r\n' +
  382. 'c=IN IP4 0.0.0.0\r\n' +
  383. 'a=sctpmap:5000 webrtc-datachannel\r\n' +
  384. 'a=mid:data\r\n'
  385. : '')
  386. );
  387. bridgeSDP.media.length = this.mychannel.length;
  388. var channel;
  389. /*
  390. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  391. bridgeSDP.media[channel] = '';
  392. // unchanged lines
  393. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'm=') + '\r\n';
  394. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'c=') + '\r\n';
  395. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:')) {
  396. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:') + '\r\n';
  397. }
  398. if (SDPUtil.find_line(localSDP.media[channel], 'a=mid:')) {
  399. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=mid:') + '\r\n';
  400. }
  401. if (SDPUtil.find_line(localSDP.media[channel], 'a=sendrecv')) {
  402. bridgeSDP.media[channel] += 'a=sendrecv\r\n';
  403. }
  404. if (SDPUtil.find_line(localSDP.media[channel], 'a=extmap:')) {
  405. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=extmap:').join('\r\n') + '\r\n';
  406. }
  407. // FIXME: should look at m-line and group the ids together
  408. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtpmap:')) {
  409. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtpmap:').join('\r\n') + '\r\n';
  410. }
  411. if (SDPUtil.find_line(localSDP.media[channel], 'a=fmtp:')) {
  412. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=fmtp:').join('\r\n') + '\r\n';
  413. }
  414. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp-fb:')) {
  415. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtcp-fb:').join('\r\n') + '\r\n';
  416. }
  417. // FIXME: changed lines -- a=sendrecv direction, a=setup direction
  418. }
  419. */
  420. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  421. // get the mixed ssrc
  422. tmp = $(this.mychannel[channel]).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  423. // FIXME: check rtp-level-relay-type
  424. var isData = bridgeSDP.media[channel].indexOf('application') !== -1;
  425. if (!isData && tmp.length)
  426. {
  427. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  428. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  429. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
  430. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  431. }
  432. else if (!isData)
  433. {
  434. // make chrome happy... '3735928559' == 0xDEADBEEF
  435. // FIXME: this currently appears as two streams, should be one
  436. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  437. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  438. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
  439. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  440. }
  441. // FIXME: should take code from .fromJingle
  442. tmp = $(this.mychannel[channel]).find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  443. if (tmp.length) {
  444. bridgeSDP.media[channel] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  445. bridgeSDP.media[channel] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  446. tmp.find('>candidate').each(function () {
  447. bridgeSDP.media[channel] += SDPUtil.candidateFromJingle(this);
  448. });
  449. tmp = tmp.find('>fingerprint');
  450. if (tmp.length) {
  451. bridgeSDP.media[channel] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  452. bridgeSDP.media[channel] += 'a=setup:actpass\r\n'; // offer so always actpass
  453. }
  454. }
  455. }
  456. bridgeSDP.raw = bridgeSDP.session + bridgeSDP.media.join('');
  457. this.peerconnection.setRemoteDescription(
  458. new RTCSessionDescription({type: 'offer', sdp: bridgeSDP.raw}),
  459. function () {
  460. console.log('setRemoteDescription success');
  461. self.peerconnection.createAnswer(
  462. function (answer) {
  463. self.peerconnection.setLocalDescription(answer,
  464. function () {
  465. console.log('setLocalDescription succeded.');
  466. // make sure our presence is updated
  467. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  468. var elem = $iq({to: self.bridgejid, type: 'get'});
  469. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: self.confid});
  470. var localSDP = new SDP(self.peerconnection.localDescription.sdp);
  471. localSDP.media.forEach(function (media, channel) {
  472. var name = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  473. elem.c('content', {name: name});
  474. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  475. if (name !== 'data')
  476. {
  477. elem.c('channel', {
  478. initiator: 'true',
  479. expire: self.channelExpire,
  480. id: self.mychannel[channel].attr('id'),
  481. endpoint: self.myMucResource
  482. });
  483. // FIXME: should reuse code from .toJingle
  484. for (var j = 0; j < mline.fmt.length; j++)
  485. {
  486. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  487. if (rtpmap)
  488. {
  489. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  490. elem.up();
  491. }
  492. }
  493. }
  494. else
  495. {
  496. var sctpmap = SDPUtil.find_line(media, 'a=sctpmap:' + mline.fmt[0]);
  497. var sctpPort = SDPUtil.parse_sctpmap(sctpmap)[0];
  498. elem.c("sctpconnection",
  499. {
  500. initiator: 'true',
  501. expire: self.channelExpire,
  502. endpoint: self.myMucResource,
  503. port: sctpPort
  504. }
  505. );
  506. }
  507. localSDP.TransportToJingle(channel, elem);
  508. elem.up(); // end of channel
  509. elem.up(); // end of content
  510. });
  511. self.connection.sendIQ(elem,
  512. function (result) {
  513. // ...
  514. },
  515. function (error) {
  516. console.error(
  517. "ERROR setLocalDescription succeded",
  518. error, elem);
  519. }
  520. );
  521. // now initiate sessions
  522. for (var i = 0; i < numparticipants; i++) {
  523. self.initiate(self.peers[i], true);
  524. }
  525. // Notify we've created the conference
  526. $(document).trigger(
  527. 'conferenceCreated.jingle', self);
  528. },
  529. function (error) {
  530. console.warn('setLocalDescription failed.', error);
  531. }
  532. );
  533. },
  534. function (error) {
  535. console.warn('createAnswer failed.', error);
  536. }
  537. );
  538. /*
  539. for (var i = 0; i < numparticipants; i++) {
  540. self.initiate(self.peers[i], true);
  541. }
  542. */
  543. },
  544. function (error) {
  545. console.log('setRemoteDescription failed.', error);
  546. }
  547. );
  548. };
  549. // send a session-initiate to a new participant
  550. ColibriFocus.prototype.initiate = function (peer, isInitiator) {
  551. var participant = this.peers.indexOf(peer);
  552. console.log('tell', peer, participant);
  553. var sdp;
  554. if (this.peerconnection !== null && this.peerconnection.signalingState == 'stable') {
  555. sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  556. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  557. // throw away stuff we don't want
  558. // not needed with static offer
  559. sdp.removeSessionLines('a=group:');
  560. sdp.removeSessionLines('a=msid-semantic:'); // FIXME: not mapped over jingle anyway...
  561. for (var i = 0; i < sdp.media.length; i++) {
  562. if (!config.useRtcpMux){
  563. sdp.removeMediaLines(i, 'a=rtcp-mux');
  564. }
  565. sdp.removeMediaLines(i, 'a=ssrc:');
  566. sdp.removeMediaLines(i, 'a=crypto:');
  567. sdp.removeMediaLines(i, 'a=candidate:');
  568. sdp.removeMediaLines(i, 'a=ice-options:google-ice');
  569. sdp.removeMediaLines(i, 'a=ice-ufrag:');
  570. sdp.removeMediaLines(i, 'a=ice-pwd:');
  571. sdp.removeMediaLines(i, 'a=fingerprint:');
  572. sdp.removeMediaLines(i, 'a=setup:');
  573. if (1) { //i > 0) { // not for audio FIXME: does not work as intended
  574. // re-add all remote a=ssrcs
  575. for (var jid in this.remotessrc) {
  576. if (jid == peer || !this.remotessrc[jid][i])
  577. continue;
  578. sdp.media[i] += this.remotessrc[jid][i];
  579. }
  580. // and local a=ssrc lines
  581. sdp.media[i] += SDPUtil.find_lines(localSDP.media[i], 'a=ssrc').join('\r\n') + '\r\n';
  582. }
  583. }
  584. sdp.raw = sdp.session + sdp.media.join('');
  585. } else {
  586. console.error('can not initiate a new session without a stable peerconnection');
  587. return;
  588. }
  589. // add stuff we got from the bridge
  590. for (var j = 0; j < sdp.media.length; j++) {
  591. var chan = $(this.channels[participant][j]);
  592. console.log('channel id', chan.attr('id'));
  593. tmp = chan.find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  594. if (tmp.length) {
  595. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  596. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  597. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
  598. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  599. }
  600. // No SSRCs for 'data', comes when j == 2
  601. else if (j < 2)
  602. {
  603. // make chrome happy... '3735928559' == 0xDEADBEEF
  604. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  605. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  606. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
  607. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  608. }
  609. tmp = chan.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  610. if (tmp.length) {
  611. if (tmp.attr('ufrag'))
  612. sdp.media[j] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  613. if (tmp.attr('pwd'))
  614. sdp.media[j] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  615. // and the candidates...
  616. tmp.find('>candidate').each(function () {
  617. sdp.media[j] += SDPUtil.candidateFromJingle(this);
  618. });
  619. tmp = tmp.find('>fingerprint');
  620. if (tmp.length) {
  621. sdp.media[j] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  622. /*
  623. if (tmp.attr('direction')) {
  624. sdp.media[j] += 'a=setup:' + tmp.attr('direction') + '\r\n';
  625. }
  626. */
  627. sdp.media[j] += 'a=setup:actpass\r\n';
  628. }
  629. }
  630. }
  631. // make a new colibri session and configure it
  632. // FIXME: is it correct to use this.connection.jid when used in a MUC?
  633. var sess = new ColibriSession(this.connection.jid,
  634. Math.random().toString(36).substr(2, 12), // random string
  635. this.connection);
  636. sess.initiate(peer);
  637. sess.colibri = this;
  638. // We do not announce our audio per conference peer, so only video is set here
  639. sess.localVideo = this.connection.jingle.localVideo;
  640. sess.media_constraints = this.connection.jingle.media_constraints;
  641. sess.pc_constraints = this.connection.jingle.pc_constraints;
  642. sess.ice_config = this.connection.jingle.ice_config;
  643. this.connection.jingle.sessions[sess.sid] = sess;
  644. this.connection.jingle.jid2session[sess.peerjid] = sess;
  645. // send a session-initiate
  646. var init = $iq({to: peer, type: 'set'})
  647. .c('jingle',
  648. {xmlns: 'urn:xmpp:jingle:1',
  649. action: 'session-initiate',
  650. initiator: sess.me,
  651. sid: sess.sid
  652. }
  653. );
  654. sdp.toJingle(init, 'initiator');
  655. this.connection.sendIQ(init,
  656. function (res) {
  657. console.log('got result');
  658. },
  659. function (err) {
  660. console.log('got error');
  661. }
  662. );
  663. };
  664. // pull in a new participant into the conference
  665. ColibriFocus.prototype.addNewParticipant = function (peer) {
  666. var self = this;
  667. if (this.confid === 0 || !this.peerconnection.localDescription)
  668. {
  669. // bad state
  670. if (this.confid === 0)
  671. {
  672. console.error('confid does not exist yet, postponing', peer);
  673. }
  674. else
  675. {
  676. console.error('local description not ready yet, postponing', peer);
  677. }
  678. window.setTimeout(function () { self.addNewParticipant(peer); }, 250);
  679. return;
  680. }
  681. var index = this.channels.length;
  682. this.channels.push([]);
  683. this.peers.push(peer);
  684. var elem = $iq({to: this.bridgejid, type: 'get'});
  685. elem.c(
  686. 'conference',
  687. { xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid });
  688. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  689. localSDP.media.forEach(function (media, channel) {
  690. var name = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  691. var elemName;
  692. var elemAttrs
  693. = {
  694. initiator: 'true',
  695. expire: self.channelExpire,
  696. endpoint: peer.substr(1 + peer.lastIndexOf('/'))
  697. };
  698. if ('data' == name)
  699. {
  700. elemName = 'sctpconnection';
  701. elemAttrs['port'] = 5000;
  702. }
  703. else
  704. {
  705. elemName = 'channel';
  706. if (('video' === name) && (self.channelLastN >= 0))
  707. elemAttrs['last-n'] = self.channelLastN;
  708. }
  709. elem.c('content', { name: name });
  710. elem.c(elemName, elemAttrs);
  711. if ('channel' === elemName && config.useRtcpMux) {
  712. elem.c('rtcp-mux').up();
  713. }
  714. elem.up(); // end of channel/sctpconnection
  715. elem.up(); // end of content
  716. });
  717. this.connection.sendIQ(elem,
  718. function (result) {
  719. var contents = $(result).find('>conference>content').get();
  720. for (var i = 0; i < contents.length; i++) {
  721. var channelXml = $(contents[i]).find('>channel');
  722. if (channelXml.length)
  723. {
  724. tmp = channelXml.get();
  725. }
  726. else
  727. {
  728. tmp = $(contents[i]).find('>sctpconnection').get();
  729. }
  730. self.channels[index][i] = tmp[0];
  731. }
  732. self.initiate(peer, true);
  733. },
  734. function (error) {
  735. console.warn(error);
  736. }
  737. );
  738. };
  739. // update the channel description (payload-types + dtls fp) for a participant
  740. ColibriFocus.prototype.updateChannel = function (remoteSDP, participant) {
  741. console.log('change allocation for', this.confid);
  742. var self = this;
  743. var change = $iq({to: this.bridgejid, type: 'set'});
  744. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  745. for (channel = 0; channel < this.channels[participant].length; channel++)
  746. {
  747. if (!remoteSDP.media[channel])
  748. continue;
  749. var name = SDPUtil.parse_mid(SDPUtil.find_line(remoteSDP.media[channel], 'a=mid:'));
  750. change.c('content', {name: name});
  751. if (name !== 'data')
  752. {
  753. change.c('channel', {
  754. id: $(this.channels[participant][channel]).attr('id'),
  755. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  756. expire: self.channelExpire
  757. });
  758. if (config.useRtcpMux) {
  759. change.c('rtcp-mux').up();
  760. }
  761. var rtpmap = SDPUtil.find_lines(remoteSDP.media[channel], 'a=rtpmap:');
  762. rtpmap.forEach(function (val) {
  763. // TODO: too much copy-paste
  764. var rtpmap = SDPUtil.parse_rtpmap(val);
  765. change.c('payload-type', rtpmap);
  766. //
  767. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  768. /*
  769. if (SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id)) {
  770. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id));
  771. for (var k = 0; k < tmp.length; k++) {
  772. change.c('parameter', tmp[k]).up();
  773. }
  774. }
  775. */
  776. change.up();
  777. });
  778. }
  779. else
  780. {
  781. var sctpmap = SDPUtil.find_line(remoteSDP.media[channel], 'a=sctpmap:');
  782. change.c('sctpconnection', {
  783. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  784. expire: self.channelExpire,
  785. port: SDPUtil.parse_sctpmap(sctpmap)[0]
  786. });
  787. }
  788. // now add transport
  789. remoteSDP.TransportToJingle(channel, change);
  790. change.up(); // end of channel/sctpconnection
  791. change.up(); // end of content
  792. }
  793. this.connection.sendIQ(change,
  794. function (res) {
  795. console.log('got result');
  796. },
  797. function (err) {
  798. console.log('got error');
  799. }
  800. );
  801. };
  802. // tell everyone about a new participants a=ssrc lines (isadd is true)
  803. // or a leaving participants a=ssrc lines
  804. ColibriFocus.prototype.sendSSRCUpdate = function (sdpMediaSsrcs, fromJid, isadd) {
  805. var self = this;
  806. this.peers.forEach(function (peerjid) {
  807. if (peerjid == fromJid) return;
  808. console.log('tell', peerjid, 'about ' + (isadd ? 'new' : 'removed') + ' ssrcs from', fromJid);
  809. if (!self.remotessrc[peerjid]) {
  810. // FIXME: this should only send to participants that are stable, i.e. who have sent a session-accept
  811. // possibly, this.remoteSSRC[session.peerjid] does not exist yet
  812. console.warn('do we really want to bother', peerjid, 'with updates yet?');
  813. }
  814. var peersess = self.connection.jingle.jid2session[peerjid];
  815. if(!peersess){
  816. console.warn('no session with peer: '+peerjid+' yet...');
  817. return;
  818. }
  819. self.sendSSRCUpdateIq(sdpMediaSsrcs, peersess.sid, peersess.initiator, peerjid, isadd);
  820. });
  821. };
  822. /**
  823. * Overrides SessionBase.addSource.
  824. *
  825. * @param elem proprietary 'add source' Jingle request(XML node).
  826. * @param fromJid JID of the participant to whom new ssrcs belong.
  827. */
  828. ColibriFocus.prototype.addSource = function (elem, fromJid) {
  829. var self = this;
  830. // FIXME: dirty waiting
  831. if (!this.peerconnection.localDescription)
  832. {
  833. console.warn("addSource - localDescription not ready yet")
  834. setTimeout(function() { self.addSource(elem, fromJid); }, 200);
  835. return;
  836. }
  837. this.peerconnection.addSource(elem);
  838. var peerSsrc = this.remotessrc[fromJid];
  839. //console.log("On ADD", self.addssrc, peerSsrc);
  840. this.peerconnection.addssrc.forEach(function(val, idx){
  841. if(!peerSsrc[idx]){
  842. // add ssrc
  843. peerSsrc[idx] = val;
  844. } else {
  845. if(peerSsrc[idx].indexOf(val) == -1){
  846. peerSsrc[idx] = peerSsrc[idx]+val;
  847. }
  848. }
  849. });
  850. var oldRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  851. this.modifySources(function(){
  852. // Notify other participants about added ssrc
  853. var remoteSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  854. var newSSRCs = oldRemoteSdp.getNewMedia(remoteSDP);
  855. self.sendSSRCUpdate(newSSRCs, fromJid, true);
  856. });
  857. };
  858. /**
  859. * Overrides SessionBase.removeSource.
  860. *
  861. * @param elem proprietary 'remove source' Jingle request(XML node).
  862. * @param fromJid JID of the participant to whom removed ssrcs belong.
  863. */
  864. ColibriFocus.prototype.removeSource = function (elem, fromJid) {
  865. var self = this;
  866. // FIXME: dirty waiting
  867. if (!self.peerconnection.localDescription)
  868. {
  869. console.warn("removeSource - localDescription not ready yet");
  870. setTimeout(function() { self.removeSource(elem, fromJid); }, 200);
  871. return;
  872. }
  873. this.peerconnection.removeSource(elem);
  874. var peerSsrc = this.remotessrc[fromJid];
  875. //console.log("On REMOVE", self.removessrc, peerSsrc);
  876. this.peerconnection.removessrc.forEach(function(val, idx){
  877. if(peerSsrc[idx]){
  878. // Remove ssrc
  879. peerSsrc[idx] = peerSsrc[idx].replace(val, '');
  880. }
  881. });
  882. var oldSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  883. this.modifySources(function(){
  884. // Notify other participants about removed ssrc
  885. var remoteSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  886. var removedSSRCs = remoteSDP.getNewMedia(oldSDP);
  887. self.sendSSRCUpdate(removedSSRCs, fromJid, false);
  888. });
  889. };
  890. ColibriFocus.prototype.setRemoteDescription = function (session, elem, desctype) {
  891. var participant = this.peers.indexOf(session.peerjid);
  892. console.log('Colibri.setRemoteDescription from', session.peerjid, participant);
  893. var remoteSDP = new SDP('');
  894. var channel;
  895. remoteSDP.fromJingle(elem);
  896. // ACT 1: change allocation on bridge
  897. this.updateChannel(remoteSDP, participant);
  898. // ACT 2: tell anyone else about the new SSRCs
  899. this.sendSSRCUpdate(remoteSDP.getMediaSsrcMap(), session.peerjid, true);
  900. // ACT 3: note the SSRCs
  901. this.remotessrc[session.peerjid] = [];
  902. for (channel = 0; channel < this.channels[participant].length; channel++) {
  903. //if (channel == 0) continue; FIXME: does not work as intended
  904. if (!remoteSDP.media[channel])
  905. continue;
  906. if (SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').length)
  907. {
  908. this.remotessrc[session.peerjid][channel] =
  909. SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:')
  910. .join('\r\n') + '\r\n';
  911. }
  912. }
  913. // ACT 4: add new a=ssrc lines to local remotedescription
  914. for (channel = 0; channel < this.channels[participant].length; channel++) {
  915. //if (channel == 0) continue; FIXME: does not work as intended
  916. if (!remoteSDP.media[channel])
  917. continue;
  918. if (SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').length) {
  919. this.peerconnection.enqueueAddSsrc(
  920. channel,
  921. SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n'
  922. );
  923. }
  924. }
  925. this.modifySources();
  926. };
  927. // relay ice candidates to bridge using trickle
  928. ColibriFocus.prototype.addIceCandidate = function (session, elem) {
  929. var self = this;
  930. var participant = this.peers.indexOf(session.peerjid);
  931. //console.log('change transport allocation for', this.confid, session.peerjid, participant);
  932. var change = $iq({to: this.bridgejid, type: 'set'});
  933. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  934. $(elem).each(function () {
  935. var name = $(this).attr('name');
  936. var channel = name == 'audio' ? 0 : 1; // FIXME: search mlineindex in localdesc
  937. if (name != 'audio' && name != 'video')
  938. channel = 2; // name == 'data'
  939. change.c('content', {name: name});
  940. if (name !== 'data')
  941. {
  942. change.c('channel', {
  943. id: $(self.channels[participant][channel]).attr('id'),
  944. endpoint: $(self.channels[participant][channel]).attr('endpoint'),
  945. expire: self.channelExpire
  946. });
  947. if (config.useRtcpMux) {
  948. change.c('rtcp-mux').up();
  949. }
  950. }
  951. else
  952. {
  953. change.c('sctpconnection', {
  954. endpoint: $(self.channels[participant][channel]).attr('endpoint'),
  955. expire: self.channelExpire
  956. });
  957. }
  958. $(this).find('>transport').each(function () {
  959. change.c('transport', {
  960. ufrag: $(this).attr('ufrag'),
  961. pwd: $(this).attr('pwd'),
  962. xmlns: $(this).attr('xmlns')
  963. });
  964. $(this).find('>candidate').each(function () {
  965. /* not yet
  966. if (this.getAttribute('protocol') == 'tcp' && this.getAttribute('port') == 0) {
  967. // chrome generates TCP candidates with port 0
  968. return;
  969. }
  970. */
  971. var line = SDPUtil.candidateFromJingle(this);
  972. change.c('candidate', SDPUtil.candidateToJingle(line)).up();
  973. });
  974. change.up(); // end of transport
  975. });
  976. change.up(); // end of channel/sctpconnection
  977. change.up(); // end of content
  978. });
  979. // FIXME: need to check if there is at least one candidate when filtering TCP ones
  980. this.connection.sendIQ(change,
  981. function (res) {
  982. console.log('got result');
  983. },
  984. function (err) {
  985. console.error('got error', err);
  986. }
  987. );
  988. };
  989. // send our own candidate to the bridge
  990. ColibriFocus.prototype.sendIceCandidate = function (candidate) {
  991. var self = this;
  992. //console.log('candidate', candidate);
  993. if (!candidate) {
  994. console.log('end of candidates');
  995. return;
  996. }
  997. if (this.drip_container.length === 0) {
  998. // start 20ms callout
  999. window.setTimeout(
  1000. function () {
  1001. if (self.drip_container.length === 0) return;
  1002. self.sendIceCandidates(self.drip_container);
  1003. self.drip_container = [];
  1004. },
  1005. 20);
  1006. }
  1007. this.drip_container.push(candidate);
  1008. };
  1009. // sort and send multiple candidates
  1010. ColibriFocus.prototype.sendIceCandidates = function (candidates) {
  1011. var self = this;
  1012. var mycands = $iq({to: this.bridgejid, type: 'set'});
  1013. mycands.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  1014. // FIXME: multi-candidate logic is taken from strophe.jingle, should be refactored there
  1015. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1016. for (var mid = 0; mid < localSDP.media.length; mid++)
  1017. {
  1018. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  1019. if (cands.length > 0)
  1020. {
  1021. var name = cands[0].sdpMid;
  1022. mycands.c('content', {name: name });
  1023. if (name !== 'data')
  1024. {
  1025. mycands.c('channel', {
  1026. id: $(this.mychannel[cands[0].sdpMLineIndex]).attr('id'),
  1027. endpoint: $(this.mychannel[cands[0].sdpMLineIndex]).attr('endpoint'),
  1028. expire: self.channelExpire
  1029. });
  1030. if (config.useRtcpMux) {
  1031. mycands.c('rtcp-mux').up();
  1032. }
  1033. }
  1034. else
  1035. {
  1036. mycands.c('sctpconnection', {
  1037. endpoint: $(this.mychannel[cands[0].sdpMLineIndex]).attr('endpoint'),
  1038. port: $(this.mychannel[cands[0].sdpMLineIndex]).attr('port'),
  1039. expire: self.channelExpire
  1040. });
  1041. }
  1042. mycands.c('transport', {xmlns: 'urn:xmpp:jingle:transports:ice-udp:1'});
  1043. for (var i = 0; i < cands.length; i++) {
  1044. mycands.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  1045. }
  1046. mycands.up(); // transport
  1047. mycands.up(); // channel / sctpconnection
  1048. mycands.up(); // content
  1049. }
  1050. }
  1051. console.log('send cands', candidates);
  1052. this.connection.sendIQ(mycands,
  1053. function (res) {
  1054. console.log('got result');
  1055. },
  1056. function (err) {
  1057. console.error('got error', err);
  1058. }
  1059. );
  1060. };
  1061. ColibriFocus.prototype.terminate = function (session, reason) {
  1062. console.log('remote session terminated from', session.peerjid);
  1063. var participant = this.peers.indexOf(session.peerjid);
  1064. if (!this.remotessrc[session.peerjid] || participant == -1) {
  1065. return;
  1066. }
  1067. var ssrcs = this.remotessrc[session.peerjid];
  1068. for (var i = 0; i < ssrcs.length; i++) {
  1069. this.peerconnection.enqueueRemoveSsrc(i, ssrcs[i]);
  1070. }
  1071. // remove from this.peers
  1072. this.peers.splice(participant, 1);
  1073. // expire channel on bridge
  1074. var change = $iq({to: this.bridgejid, type: 'set'});
  1075. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  1076. for (var channel = 0; channel < this.channels[participant].length; channel++) {
  1077. var name = channel === 0 ? 'audio' : 'video';
  1078. if (channel == 2)
  1079. name = 'data';
  1080. change.c('content', {name: name});
  1081. if (name !== 'data')
  1082. {
  1083. change.c('channel', {
  1084. id: $(this.channels[participant][channel]).attr('id'),
  1085. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  1086. expire: '0'
  1087. });
  1088. }
  1089. else
  1090. {
  1091. change.c('sctpconnection', {
  1092. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  1093. expire: '0'
  1094. });
  1095. }
  1096. change.up(); // end of channel/sctpconnection
  1097. change.up(); // end of content
  1098. }
  1099. this.connection.sendIQ(change,
  1100. function (res) {
  1101. console.log('got result');
  1102. },
  1103. function (err) {
  1104. console.error('got error', err);
  1105. }
  1106. );
  1107. // and remove from channels
  1108. this.channels.splice(participant, 1);
  1109. // tell everyone about the ssrcs to be removed
  1110. var sdp = new SDP('');
  1111. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1112. var contents = SDPUtil.find_lines(localSDP.raw, 'a=mid:').map(SDPUtil.parse_mid);
  1113. for (var j = 0; j < ssrcs.length; j++) {
  1114. sdp.media[j] = 'a=mid:' + contents[j] + '\r\n';
  1115. sdp.media[j] += ssrcs[j];
  1116. this.peerconnection.enqueueRemoveSsrc(j, ssrcs[j]);
  1117. }
  1118. this.sendSSRCUpdate(sdp.getMediaSsrcMap(), session.peerjid, false);
  1119. delete this.remotessrc[session.peerjid];
  1120. this.modifySources();
  1121. };
  1122. ColibriFocus.prototype.sendTerminate = function (session, reason, text) {
  1123. var term = $iq({to: session.peerjid, type: 'set'})
  1124. .c('jingle',
  1125. {xmlns: 'urn:xmpp:jingle:1',
  1126. action: 'session-terminate',
  1127. initiator: session.me,
  1128. sid: session.sid})
  1129. .c('reason')
  1130. .c(reason || 'success');
  1131. if (text) {
  1132. term.up().c('text').t(text);
  1133. }
  1134. this.connection.sendIQ(term,
  1135. function () {
  1136. if (!session)
  1137. return;
  1138. if (session.peerconnection) {
  1139. session.peerconnection.close();
  1140. session.peerconnection = null;
  1141. }
  1142. session.terminate();
  1143. var ack = {};
  1144. ack.source = 'terminate';
  1145. $(document).trigger('ack.jingle', [session.sid, ack]);
  1146. },
  1147. function (stanza) {
  1148. var error = ($(stanza).find('error').length) ? {
  1149. code: $(stanza).find('error').attr('code'),
  1150. reason: $(stanza).find('error :first')[0].tagName,
  1151. }:{};
  1152. $(document).trigger('ack.jingle', [self.sid, error]);
  1153. },
  1154. 10000);
  1155. if (this.statsinterval !== null) {
  1156. window.clearInterval(this.statsinterval);
  1157. this.statsinterval = null;
  1158. }
  1159. };
  1160. ColibriFocus.prototype.setRTCPTerminationStrategy = function (strategyFQN) {
  1161. var self = this;
  1162. var strategyIQ = $iq({to: this.bridgejid, type: 'set'});
  1163. strategyIQ.c('conference', {
  1164. xmlns: 'http://jitsi.org/protocol/colibri',
  1165. id: this.confid,
  1166. });
  1167. strategyIQ.c('rtcp-termination-strategy', {name: strategyFQN });
  1168. strategyIQ.c('content', {name: "video"});
  1169. strategyIQ.up(); // end of content
  1170. console.log('setting RTCP termination strategy', strategyFQN);
  1171. this.connection.sendIQ(strategyIQ,
  1172. function (res) {
  1173. console.log('got result');
  1174. },
  1175. function (err) {
  1176. console.error('got error', err);
  1177. }
  1178. );
  1179. };
  1180. /**
  1181. * Sets the default value of the channel last-n attribute in this conference and
  1182. * updates/patches the existing channels.
  1183. */
  1184. ColibriFocus.prototype.setChannelLastN = function (channelLastN) {
  1185. if (('number' === typeof(channelLastN))
  1186. && (this.channelLastN !== channelLastN))
  1187. {
  1188. this.channelLastN = channelLastN;
  1189. // Update/patch the existing channels.
  1190. var patch = $iq({ to: this.bridgejid, type: 'set' });
  1191. patch.c(
  1192. 'conference',
  1193. { xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid });
  1194. patch.c('content', { name: 'video' });
  1195. patch.c(
  1196. 'channel',
  1197. {
  1198. id: $(this.mychannel[1 /* video */]).attr('id'),
  1199. 'last-n': this.channelLastN
  1200. });
  1201. patch.up(); // end of channel
  1202. for (var p = 0; p < this.channels.length; p++)
  1203. {
  1204. patch.c(
  1205. 'channel',
  1206. {
  1207. id: $(this.channels[p][1 /* video */]).attr('id'),
  1208. 'last-n': this.channelLastN
  1209. });
  1210. patch.up(); // end of channel
  1211. }
  1212. this.connection.sendIQ(
  1213. patch,
  1214. function (res) {
  1215. console.info('Set channel last-n succeeded:', res);
  1216. },
  1217. function (err) {
  1218. console.error('Set channel last-n failed:', err);
  1219. });
  1220. }
  1221. };