選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

colibri.focus.js 56KB

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