Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

colibri.focus.js 56KB

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