You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

colibri.focus.js 60KB

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