Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

colibri.focus.js 51KB

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