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 56KB

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