Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

colibri.focus.js 56KB

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