您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

colibri.focus.js 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. /* colibri.js -- a COLIBRI focus
  2. * The colibri spec has been submitted to the XMPP Standards Foundation
  3. * for publications as a XMPP extensions:
  4. * http://xmpp.org/extensions/inbox/colibri.html
  5. *
  6. * colibri.js is a participating focus, i.e. the focus participates
  7. * in the conference. The conference itself can be ad-hoc, through a
  8. * MUC, through PubSub, etc.
  9. *
  10. * colibri.js relies heavily on the strophe.jingle library available
  11. * from https://github.com/ESTOS/strophe.jingle
  12. * and interoperates with the Jitsi videobridge available from
  13. * https://jitsi.org/Projects/JitsiVideobridge
  14. */
  15. /*
  16. Copyright (c) 2013 ESTOS GmbH
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23. The above copyright notice and this permission notice shall be included in
  24. all copies or substantial portions of the Software.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31. THE SOFTWARE.
  32. */
  33. /* jshint -W117 */
  34. ColibriFocus.prototype = Object.create(SessionBase.prototype);
  35. function ColibriFocus(connection, bridgejid) {
  36. SessionBase.call(this, connection, Math.random().toString(36).substr(2, 12));
  37. this.bridgejid = bridgejid;
  38. this.peers = [];
  39. this.confid = null;
  40. // media types of the conference
  41. this.media = ['audio', 'video'];
  42. this.connection.jingle.sessions[this.sid] = this;
  43. this.mychannel = [];
  44. this.channels = [];
  45. this.remotessrc = {};
  46. // container for candidates from the focus
  47. // gathered before confid is known
  48. this.drip_container = [];
  49. // silly wait flag
  50. this.wait = true;
  51. }
  52. // creates a conferences with an initial set of peers
  53. ColibriFocus.prototype.makeConference = function (peers) {
  54. var self = this;
  55. if (this.confid !== null) {
  56. console.error('makeConference called twice? Ignoring...');
  57. // FIXME: just invite peers?
  58. return;
  59. }
  60. this.confid = 0; // !null
  61. this.peers = [];
  62. peers.forEach(function (peer) {
  63. self.peers.push(peer);
  64. self.channels.push([]);
  65. });
  66. this.peerconnection
  67. = new TraceablePeerConnection(
  68. this.connection.jingle.ice_config,
  69. this.connection.jingle.pc_constraints );
  70. if(this.connection.jingle.localAudio) {
  71. this.peerconnection.addStream(this.connection.jingle.localAudio);
  72. }
  73. if(this.connection.jingle.localVideo) {
  74. this.peerconnection.addStream(this.connection.jingle.localVideo);
  75. }
  76. this.peerconnection.oniceconnectionstatechange = function (event) {
  77. console.warn('ice connection state changed to', self.peerconnection.iceConnectionState);
  78. /*
  79. if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
  80. console.log('adding new remote SSRCs from iceconnectionstatechange');
  81. window.setTimeout(function() { self.modifySources(); }, 1000);
  82. }
  83. */
  84. };
  85. this.peerconnection.onsignalingstatechange = function (event) {
  86. console.warn(self.peerconnection.signalingState);
  87. /*
  88. if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
  89. console.log('adding new remote SSRCs from signalingstatechange');
  90. window.setTimeout(function() { self.modifySources(); }, 1000);
  91. }
  92. */
  93. };
  94. this.peerconnection.onaddstream = function (event) {
  95. // search the jid associated with this stream
  96. Object.keys(self.remotessrc).forEach(function (jid) {
  97. if (self.remotessrc[jid].join('\r\n').indexOf('mslabel:' + event.stream.id) != -1) {
  98. event.peerjid = jid;
  99. }
  100. });
  101. $(document).trigger('remotestreamadded.jingle', [event, self.sid]);
  102. };
  103. this.peerconnection.onicecandidate = function (event) {
  104. //console.log('focus onicecandidate', self.confid, new Date().getTime(), event.candidate);
  105. if (!event.candidate) {
  106. console.log('end of candidates');
  107. return;
  108. }
  109. self.sendIceCandidate(event.candidate);
  110. };
  111. this._makeConference();
  112. /*
  113. this.peerconnection.createOffer(
  114. function (offer) {
  115. self.peerconnection.setLocalDescription(
  116. offer,
  117. function () {
  118. // success
  119. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  120. // FIXME: could call _makeConference here and trickle candidates later
  121. self._makeConference();
  122. },
  123. function (error) {
  124. console.log('setLocalDescription failed', error);
  125. }
  126. );
  127. },
  128. function (error) {
  129. console.warn(error);
  130. }
  131. );
  132. */
  133. };
  134. ColibriFocus.prototype._makeConference = function () {
  135. var self = this;
  136. var elem = $iq({to: this.bridgejid, type: 'get'});
  137. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri'});
  138. this.media.forEach(function (name) {
  139. elem.c('content', {name: name});
  140. elem.c('channel', {
  141. initiator: 'true',
  142. expire: '15',
  143. endpoint: 'fix_me_focus_endpoint'}).up();
  144. for (var j = 0; j < self.peers.length; j++) {
  145. elem.c('channel', {
  146. initiator: 'true',
  147. expire: '15',
  148. endpoint: self.peers[j].substr(1 + self.peers[j].lastIndexOf('/'))
  149. }).up();
  150. }
  151. elem.up(); // end of content
  152. });
  153. /*
  154. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  155. localSDP.media.forEach(function (media, channel) {
  156. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  157. elem.c('content', {name: name});
  158. elem.c('channel', {initiator: 'false', expire: '15'});
  159. // FIXME: should reuse code from .toJingle
  160. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  161. for (var j = 0; j < mline.fmt.length; j++) {
  162. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  163. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  164. elem.up();
  165. }
  166. localSDP.TransportToJingle(channel, elem);
  167. elem.up(); // end of channel
  168. for (j = 0; j < self.peers.length; j++) {
  169. elem.c('channel', {initiator: 'true', expire:'15' }).up();
  170. }
  171. elem.up(); // end of content
  172. });
  173. */
  174. this.connection.sendIQ(elem,
  175. function (result) {
  176. self.createdConference(result);
  177. },
  178. function (error) {
  179. console.warn(error);
  180. }
  181. );
  182. };
  183. // callback when a conference was created
  184. ColibriFocus.prototype.createdConference = function (result) {
  185. console.log('created a conference on the bridge');
  186. var self = this;
  187. var tmp;
  188. this.confid = $(result).find('>conference').attr('id');
  189. var remotecontents = $(result).find('>conference>content').get();
  190. var numparticipants = 0;
  191. for (var i = 0; i < remotecontents.length; i++) {
  192. tmp = $(remotecontents[i]).find('>channel').get();
  193. this.mychannel.push($(tmp.shift()));
  194. numparticipants = tmp.length;
  195. for (j = 0; j < tmp.length; j++) {
  196. if (this.channels[j] === undefined) {
  197. this.channels[j] = [];
  198. }
  199. this.channels[j].push(tmp[j]);
  200. }
  201. }
  202. console.log('remote channels', this.channels);
  203. var bridgeSDP = new SDP('v=0\r\no=- 5151055458874951233 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1 RTP/SAVPF 111 103 104 0 8 106 105 13 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=mid:audio\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\na=fmtp:111 minptime=10\r\na=rtpmap:103 ISAC/16000\r\na=rtpmap:104 ISAC/32000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:106 CN/32000\r\na=rtpmap:105 CN/16000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:126 telephone-event/8000\r\na=maxptime:60\r\nm=video 1 RTP/SAVPF 100 116 117\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=mid:video\r\na=extmap:2 urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=rtpmap:100 VP8/90000\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 goog-remb\r\na=rtpmap:116 red/90000\r\na=rtpmap:117 ulpfec/90000\r\n');
  204. bridgeSDP.media.length = this.mychannel.length;
  205. var channel;
  206. /*
  207. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  208. bridgeSDP.media[channel] = '';
  209. // unchanged lines
  210. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'm=') + '\r\n';
  211. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'c=') + '\r\n';
  212. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:')) {
  213. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:') + '\r\n';
  214. }
  215. if (SDPUtil.find_line(localSDP.media[channel], 'a=mid:')) {
  216. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=mid:') + '\r\n';
  217. }
  218. if (SDPUtil.find_line(localSDP.media[channel], 'a=sendrecv')) {
  219. bridgeSDP.media[channel] += 'a=sendrecv\r\n';
  220. }
  221. if (SDPUtil.find_line(localSDP.media[channel], 'a=extmap:')) {
  222. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=extmap:').join('\r\n') + '\r\n';
  223. }
  224. // FIXME: should look at m-line and group the ids together
  225. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtpmap:')) {
  226. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtpmap:').join('\r\n') + '\r\n';
  227. }
  228. if (SDPUtil.find_line(localSDP.media[channel], 'a=fmtp:')) {
  229. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=fmtp:').join('\r\n') + '\r\n';
  230. }
  231. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp-fb:')) {
  232. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtcp-fb:').join('\r\n') + '\r\n';
  233. }
  234. // FIXME: changed lines -- a=sendrecv direction, a=setup direction
  235. }
  236. */
  237. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  238. // get the mixed ssrc
  239. tmp = $(this.mychannel[channel]).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  240. // FIXME: check rtp-level-relay-type
  241. if (tmp.length) {
  242. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  243. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  244. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
  245. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  246. } else {
  247. // make chrome happy... '3735928559' == 0xDEADBEEF
  248. // FIXME: this currently appears as two streams, should be one
  249. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  250. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  251. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
  252. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  253. }
  254. // FIXME: should take code from .fromJingle
  255. tmp = $(this.mychannel[channel]).find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  256. if (tmp.length) {
  257. bridgeSDP.media[channel] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  258. bridgeSDP.media[channel] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  259. tmp.find('>candidate').each(function () {
  260. bridgeSDP.media[channel] += SDPUtil.candidateFromJingle(this);
  261. });
  262. tmp = tmp.find('>fingerprint');
  263. if (tmp.length) {
  264. bridgeSDP.media[channel] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  265. bridgeSDP.media[channel] += 'a=setup:actpass\r\n'; // offer so always actpass
  266. }
  267. }
  268. }
  269. bridgeSDP.raw = bridgeSDP.session + bridgeSDP.media.join('');
  270. this.peerconnection.setRemoteDescription(
  271. new RTCSessionDescription({type: 'offer', sdp: bridgeSDP.raw}),
  272. function () {
  273. console.log('setRemoteDescription success');
  274. self.peerconnection.createAnswer(
  275. function (answer) {
  276. self.peerconnection.setLocalDescription(answer,
  277. function () {
  278. console.log('setLocalDescription succeded.');
  279. // make sure our presence is updated
  280. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  281. var elem = $iq({to: self.bridgejid, type: 'get'});
  282. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: self.confid});
  283. var localSDP = new SDP(self.peerconnection.localDescription.sdp);
  284. localSDP.media.forEach(function (media, channel) {
  285. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  286. elem.c('content', {name: name});
  287. elem.c('channel', {
  288. initiator: 'true',
  289. expire: '15',
  290. id: self.mychannel[channel].attr('id'),
  291. endpoint: 'fix_me_focus_endpoint'
  292. });
  293. // FIXME: should reuse code from .toJingle
  294. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  295. for (var j = 0; j < mline.fmt.length; j++) {
  296. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  297. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  298. elem.up();
  299. }
  300. localSDP.TransportToJingle(channel, elem);
  301. elem.up(); // end of channel
  302. elem.up(); // end of content
  303. });
  304. self.connection.sendIQ(elem,
  305. function (result) {
  306. // ...
  307. },
  308. function (error) {
  309. console.warn(error);
  310. }
  311. );
  312. // now initiate sessions
  313. for (var i = 0; i < numparticipants; i++) {
  314. self.initiate(self.peers[i], true);
  315. }
  316. },
  317. function (error) {
  318. console.warn('setLocalDescription failed.', error);
  319. }
  320. );
  321. },
  322. function (error) {
  323. console.warn('createAnswer failed.', error);
  324. }
  325. );
  326. /*
  327. for (var i = 0; i < numparticipants; i++) {
  328. self.initiate(self.peers[i], true);
  329. }
  330. */
  331. },
  332. function (error) {
  333. console.log('setRemoteDescription failed.', error);
  334. }
  335. );
  336. };
  337. // send a session-initiate to a new participant
  338. ColibriFocus.prototype.initiate = function (peer, isInitiator) {
  339. var participant = this.peers.indexOf(peer);
  340. console.log('tell', peer, participant);
  341. var sdp;
  342. if (this.peerconnection !== null && this.peerconnection.signalingState == 'stable') {
  343. sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  344. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  345. // throw away stuff we don't want
  346. // not needed with static offer
  347. sdp.removeSessionLines('a=group:');
  348. sdp.removeSessionLines('a=msid-semantic:'); // FIXME: not mapped over jingle anyway...
  349. for (var i = 0; i < sdp.media.length; i++) {
  350. sdp.removeMediaLines(i, 'a=rtcp-mux');
  351. sdp.removeMediaLines(i, 'a=ssrc:');
  352. sdp.removeMediaLines(i, 'a=crypto:');
  353. sdp.removeMediaLines(i, 'a=candidate:');
  354. sdp.removeMediaLines(i, 'a=ice-options:google-ice');
  355. sdp.removeMediaLines(i, 'a=ice-ufrag:');
  356. sdp.removeMediaLines(i, 'a=ice-pwd:');
  357. sdp.removeMediaLines(i, 'a=fingerprint:');
  358. sdp.removeMediaLines(i, 'a=setup:');
  359. if (1) { //i > 0) { // not for audio FIXME: does not work as intended
  360. // re-add all remote a=ssrcs
  361. for (var jid in this.remotessrc) {
  362. if (jid == peer) continue;
  363. sdp.media[i] += this.remotessrc[jid][i];
  364. }
  365. // and local a=ssrc lines
  366. sdp.media[i] += SDPUtil.find_lines(localSDP.media[i], 'a=ssrc').join('\r\n') + '\r\n';
  367. }
  368. }
  369. sdp.raw = sdp.session + sdp.media.join('');
  370. } else {
  371. console.error('can not initiate a new session without a stable peerconnection');
  372. return;
  373. }
  374. // add stuff we got from the bridge
  375. for (var j = 0; j < sdp.media.length; j++) {
  376. var chan = $(this.channels[participant][j]);
  377. console.log('channel id', chan.attr('id'));
  378. tmp = chan.find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  379. if (tmp.length) {
  380. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  381. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  382. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
  383. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  384. } else {
  385. // make chrome happy... '3735928559' == 0xDEADBEEF
  386. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  387. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  388. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
  389. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
  390. }
  391. tmp = chan.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  392. if (tmp.length) {
  393. if (tmp.attr('ufrag'))
  394. sdp.media[j] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  395. if (tmp.attr('pwd'))
  396. sdp.media[j] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  397. // and the candidates...
  398. tmp.find('>candidate').each(function () {
  399. sdp.media[j] += SDPUtil.candidateFromJingle(this);
  400. });
  401. tmp = tmp.find('>fingerprint');
  402. if (tmp.length) {
  403. sdp.media[j] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  404. /*
  405. if (tmp.attr('direction')) {
  406. sdp.media[j] += 'a=setup:' + tmp.attr('direction') + '\r\n';
  407. }
  408. */
  409. sdp.media[j] += 'a=setup:actpass\r\n';
  410. }
  411. }
  412. }
  413. // make a new colibri session and configure it
  414. // FIXME: is it correct to use this.connection.jid when used in a MUC?
  415. var sess = new ColibriSession(this.connection.jid,
  416. Math.random().toString(36).substr(2, 12), // random string
  417. this.connection);
  418. sess.initiate(peer);
  419. sess.colibri = this;
  420. // We do not announce our audio per conference peer, so only video is set here
  421. sess.localVideo = this.connection.jingle.localVideo;
  422. sess.media_constraints = this.connection.jingle.media_constraints;
  423. sess.pc_constraints = this.connection.jingle.pc_constraints;
  424. sess.ice_config = this.connection.jingle.ice_config;
  425. this.connection.jingle.sessions[sess.sid] = sess;
  426. this.connection.jingle.jid2session[sess.peerjid] = sess;
  427. // send a session-initiate
  428. var init = $iq({to: peer, type: 'set'})
  429. .c('jingle',
  430. {xmlns: 'urn:xmpp:jingle:1',
  431. action: 'session-initiate',
  432. initiator: sess.me,
  433. sid: sess.sid
  434. }
  435. );
  436. sdp.toJingle(init, 'initiator');
  437. this.connection.sendIQ(init,
  438. function (res) {
  439. console.log('got result');
  440. },
  441. function (err) {
  442. console.log('got error');
  443. }
  444. );
  445. };
  446. // pull in a new participant into the conference
  447. ColibriFocus.prototype.addNewParticipant = function (peer) {
  448. var self = this;
  449. if (this.confid === 0) {
  450. // bad state
  451. console.log('confid does not exist yet, postponing', peer);
  452. window.setTimeout(function () {
  453. self.addNewParticipant(peer);
  454. }, 250);
  455. return;
  456. }
  457. var index = this.channels.length;
  458. this.channels.push([]);
  459. this.peers.push(peer);
  460. var elem = $iq({to: this.bridgejid, type: 'get'});
  461. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  462. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  463. localSDP.media.forEach(function (media, channel) {
  464. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  465. elem.c('content', {name: name});
  466. elem.c('channel', {
  467. initiator: 'true',
  468. expire:'15',
  469. endpoint: peer.substr(1 + peer.lastIndexOf('/'))
  470. });
  471. elem.up(); // end of channel
  472. elem.up(); // end of content
  473. });
  474. this.connection.sendIQ(elem,
  475. function (result) {
  476. var contents = $(result).find('>conference>content').get();
  477. for (var i = 0; i < contents.length; i++) {
  478. tmp = $(contents[i]).find('>channel').get();
  479. self.channels[index][i] = tmp[0];
  480. }
  481. self.initiate(peer, true);
  482. },
  483. function (error) {
  484. console.warn(error);
  485. }
  486. );
  487. };
  488. // update the channel description (payload-types + dtls fp) for a participant
  489. ColibriFocus.prototype.updateChannel = function (remoteSDP, participant) {
  490. console.log('change allocation for', this.confid);
  491. var change = $iq({to: this.bridgejid, type: 'set'});
  492. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  493. for (channel = 0; channel < this.channels[participant].length; channel++) {
  494. change.c('content', {name: channel === 0 ? 'audio' : 'video'});
  495. change.c('channel', {
  496. id: $(this.channels[participant][channel]).attr('id'),
  497. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  498. expire: '15'
  499. });
  500. var rtpmap = SDPUtil.find_lines(remoteSDP.media[channel], 'a=rtpmap:');
  501. rtpmap.forEach(function (val) {
  502. // TODO: too much copy-paste
  503. var rtpmap = SDPUtil.parse_rtpmap(val);
  504. change.c('payload-type', rtpmap);
  505. //
  506. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  507. /*
  508. if (SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id)) {
  509. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id));
  510. for (var k = 0; k < tmp.length; k++) {
  511. change.c('parameter', tmp[k]).up();
  512. }
  513. }
  514. */
  515. change.up();
  516. });
  517. // now add transport
  518. remoteSDP.TransportToJingle(channel, change);
  519. change.up(); // end of channel
  520. change.up(); // end of content
  521. }
  522. this.connection.sendIQ(change,
  523. function (res) {
  524. console.log('got result');
  525. },
  526. function (err) {
  527. console.log('got error');
  528. }
  529. );
  530. };
  531. // tell everyone about a new participants a=ssrc lines (isadd is true)
  532. // or a leaving participants a=ssrc lines
  533. ColibriFocus.prototype.sendSSRCUpdate = function (sdpMediaSsrcs, fromJid, isadd) {
  534. var self = this;
  535. this.peers.forEach(function (peerjid) {
  536. if (peerjid == fromJid) return;
  537. console.log('tell', peerjid, 'about ' + (isadd ? 'new' : 'removed') + ' ssrcs from', fromJid);
  538. if (!self.remotessrc[peerjid]) {
  539. // FIXME: this should only send to participants that are stable, i.e. who have sent a session-accept
  540. // possibly, this.remoteSSRC[session.peerjid] does not exist yet
  541. console.warn('do we really want to bother', peerjid, 'with updates yet?');
  542. }
  543. var peersess = self.connection.jingle.jid2session[peerjid];
  544. if(!peersess){
  545. console.warn('no session with peer: '+peerjid+' yet...');
  546. return;
  547. }
  548. self.sendSSRCUpdateIq(sdpMediaSsrcs, peersess.sid, peersess.initiator, peerjid, isadd);
  549. });
  550. };
  551. /**
  552. * Overrides SessionBase.addSource.
  553. *
  554. * @param elem proprietary 'add source' Jingle request(XML node).
  555. * @param fromJid JID of the participant to whom new ssrcs belong.
  556. */
  557. ColibriFocus.prototype.addSource = function (elem, fromJid) {
  558. var self = this;
  559. this.peerconnection.addSource(elem);
  560. var peerSsrc = this.remotessrc[fromJid];
  561. //console.log("On ADD", self.addssrc, peerSsrc);
  562. this.peerconnection.addssrc.forEach(function(val, idx){
  563. if(!peerSsrc[idx]){
  564. // add ssrc
  565. peerSsrc[idx] = val;
  566. } else {
  567. if(peerSsrc[idx].indexOf(val) == -1){
  568. peerSsrc[idx] = peerSsrc[idx]+val;
  569. }
  570. }
  571. });
  572. var oldRemoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  573. this.modifySources(function(){
  574. // Notify other participants about added ssrc
  575. var remoteSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  576. var newSSRCs = oldRemoteSdp.getNewMedia(remoteSDP);
  577. self.sendSSRCUpdate(newSSRCs, fromJid, true);
  578. });
  579. };
  580. /**
  581. * Overrides SessionBase.removeSource.
  582. *
  583. * @param elem proprietary 'remove source' Jingle request(XML node).
  584. * @param fromJid JID of the participant to whom removed ssrcs belong.
  585. */
  586. ColibriFocus.prototype.removeSource = function (elem, fromJid) {
  587. var self = this;
  588. this.peerconnection.removeSource(elem);
  589. var peerSsrc = this.remotessrc[fromJid];
  590. //console.log("On REMOVE", self.removessrc, peerSsrc);
  591. this.peerconnection.removessrc.forEach(function(val, idx){
  592. if(peerSsrc[idx]){
  593. // Remove ssrc
  594. peerSsrc[idx] = peerSsrc[idx].replace(val, '');
  595. }
  596. });
  597. var oldSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  598. this.modifySources(function(){
  599. // Notify other participants about removed ssrc
  600. var remoteSDP = new SDP(self.peerconnection.remoteDescription.sdp);
  601. var removedSSRCs = remoteSDP.getNewMedia(oldSDP);
  602. self.sendSSRCUpdate(removedSSRCs, fromJid, false);
  603. });
  604. };
  605. ColibriFocus.prototype.setRemoteDescription = function (session, elem, desctype) {
  606. var participant = this.peers.indexOf(session.peerjid);
  607. console.log('Colibri.setRemoteDescription from', session.peerjid, participant);
  608. var remoteSDP = new SDP('');
  609. var channel;
  610. remoteSDP.fromJingle(elem);
  611. // ACT 1: change allocation on bridge
  612. this.updateChannel(remoteSDP, participant);
  613. // ACT 2: tell anyone else about the new SSRCs
  614. this.sendSSRCUpdate(remoteSDP.getMediaSsrcMap(), session.peerjid, true);
  615. // ACT 3: note the SSRCs
  616. this.remotessrc[session.peerjid] = [];
  617. for (channel = 0; channel < this.channels[participant].length; channel++) {
  618. //if (channel == 0) continue; FIXME: does not work as intended
  619. if (SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').length) {
  620. this.remotessrc[session.peerjid][channel] = SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n';
  621. }
  622. }
  623. // ACT 4: add new a=ssrc lines to local remotedescription
  624. for (channel = 0; channel < this.channels[participant].length; channel++) {
  625. //if (channel == 0) continue; FIXME: does not work as intended
  626. if (SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').length) {
  627. this.peerconnection.enqueueAddSsrc(
  628. channel,
  629. SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n'
  630. );
  631. }
  632. }
  633. this.modifySources();
  634. };
  635. // relay ice candidates to bridge using trickle
  636. ColibriFocus.prototype.addIceCandidate = function (session, elem) {
  637. var self = this;
  638. var participant = this.peers.indexOf(session.peerjid);
  639. //console.log('change transport allocation for', this.confid, session.peerjid, participant);
  640. var change = $iq({to: this.bridgejid, type: 'set'});
  641. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  642. $(elem).each(function () {
  643. var name = $(this).attr('name');
  644. var channel = name == 'audio' ? 0 : 1; // FIXME: search mlineindex in localdesc
  645. change.c('content', {name: name});
  646. change.c('channel', {
  647. id: $(self.channels[participant][channel]).attr('id'),
  648. endpoint: $(self.channels[participant][channel]).attr('endpoint'),
  649. expire: '15'
  650. });
  651. $(this).find('>transport').each(function () {
  652. change.c('transport', {
  653. ufrag: $(this).attr('ufrag'),
  654. pwd: $(this).attr('pwd'),
  655. xmlns: $(this).attr('xmlns')
  656. });
  657. $(this).find('>candidate').each(function () {
  658. /* not yet
  659. if (this.getAttribute('protocol') == 'tcp' && this.getAttribute('port') == 0) {
  660. // chrome generates TCP candidates with port 0
  661. return;
  662. }
  663. */
  664. var line = SDPUtil.candidateFromJingle(this);
  665. change.c('candidate', SDPUtil.candidateToJingle(line)).up();
  666. });
  667. change.up(); // end of transport
  668. });
  669. change.up(); // end of channel
  670. change.up(); // end of content
  671. });
  672. // FIXME: need to check if there is at least one candidate when filtering TCP ones
  673. this.connection.sendIQ(change,
  674. function (res) {
  675. console.log('got result');
  676. },
  677. function (err) {
  678. console.error('got error', err);
  679. }
  680. );
  681. };
  682. // send our own candidate to the bridge
  683. ColibriFocus.prototype.sendIceCandidate = function (candidate) {
  684. var self = this;
  685. //console.log('candidate', candidate);
  686. if (!candidate) {
  687. console.log('end of candidates');
  688. return;
  689. }
  690. if (this.drip_container.length === 0) {
  691. // start 20ms callout
  692. window.setTimeout(function () {
  693. if (self.drip_container.length === 0) return;
  694. self.sendIceCandidates(self.drip_container);
  695. self.drip_container = [];
  696. }, 20);
  697. }
  698. this.drip_container.push(candidate);
  699. };
  700. // sort and send multiple candidates
  701. ColibriFocus.prototype.sendIceCandidates = function (candidates) {
  702. var self = this;
  703. var mycands = $iq({to: this.bridgejid, type: 'set'});
  704. mycands.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  705. // FIXME: multi-candidate logic is taken from strophe.jingle, should be refactored there
  706. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  707. for (var mid = 0; mid < localSDP.media.length; mid++) {
  708. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  709. if (cands.length > 0) {
  710. mycands.c('content', {name: cands[0].sdpMid });
  711. mycands.c('channel', {
  712. id: $(this.mychannel[cands[0].sdpMLineIndex]).attr('id'),
  713. endpoint: $(this.mychannel[cands[0].sdpMLineIndex]).attr('endpoint'),
  714. expire: '15'
  715. });
  716. mycands.c('transport', {xmlns: 'urn:xmpp:jingle:transports:ice-udp:1'});
  717. for (var i = 0; i < cands.length; i++) {
  718. mycands.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  719. }
  720. mycands.up(); // transport
  721. mycands.up(); // channel
  722. mycands.up(); // content
  723. }
  724. }
  725. console.log('send cands', candidates);
  726. this.connection.sendIQ(mycands,
  727. function (res) {
  728. console.log('got result');
  729. },
  730. function (err) {
  731. console.error('got error', err);
  732. }
  733. );
  734. };
  735. ColibriFocus.prototype.terminate = function (session, reason) {
  736. console.log('remote session terminated from', session.peerjid);
  737. var participant = this.peers.indexOf(session.peerjid);
  738. if (!this.remotessrc[session.peerjid] || participant == -1) {
  739. return;
  740. }
  741. var ssrcs = this.remotessrc[session.peerjid];
  742. for (var i = 0; i < ssrcs.length; i++) {
  743. this.peerconnection.enqueueRemoveSsrc(i, ssrcs[i]);
  744. }
  745. // remove from this.peers
  746. this.peers.splice(participant, 1);
  747. // expire channel on bridge
  748. var change = $iq({to: this.bridgejid, type: 'set'});
  749. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  750. for (var channel = 0; channel < this.channels[participant].length; channel++) {
  751. change.c('content', {name: channel === 0 ? 'audio' : 'video'});
  752. change.c('channel', {
  753. id: $(this.channels[participant][channel]).attr('id'),
  754. endpoint: $(this.channels[participant][channel]).attr('endpoint'),
  755. expire: '0'
  756. });
  757. change.up(); // end of channel
  758. change.up(); // end of content
  759. }
  760. this.connection.sendIQ(change,
  761. function (res) {
  762. console.log('got result');
  763. },
  764. function (err) {
  765. console.error('got error', err);
  766. }
  767. );
  768. // and remove from channels
  769. this.channels.splice(participant, 1);
  770. // tell everyone about the ssrcs to be removed
  771. var sdp = new SDP('');
  772. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  773. var contents = SDPUtil.find_lines(localSDP.raw, 'a=mid:').map(SDPUtil.parse_mid);
  774. for (var j = 0; j < ssrcs.length; j++) {
  775. sdp.media[j] = 'a=mid:' + contents[j] + '\r\n';
  776. sdp.media[j] += ssrcs[j];
  777. this.peerconnection.enqueueRemoveSsrc(j, ssrcs[j]);
  778. }
  779. this.sendSSRCUpdate(sdp.getMediaSsrcMap(), session.peerjid, false);
  780. delete this.remotessrc[session.peerjid];
  781. this.modifySources();
  782. };
  783. ColibriFocus.prototype.sendTerminate = function (session, reason, text) {
  784. var term = $iq({to: session.peerjid, type: 'set'})
  785. .c('jingle',
  786. {xmlns: 'urn:xmpp:jingle:1',
  787. action: 'session-terminate',
  788. initiator: session.me,
  789. sid: session.sid})
  790. .c('reason')
  791. .c(reason || 'success');
  792. if (text) {
  793. term.up().c('text').t(text);
  794. }
  795. this.connection.sendIQ(term,
  796. function () {
  797. if (!session)
  798. return;
  799. if (session.peerconnection) {
  800. session.peerconnection.close();
  801. session.peerconnection = null;
  802. }
  803. session.terminate();
  804. var ack = {};
  805. ack.source = 'terminate';
  806. $(document).trigger('ack.jingle', [session.sid, ack]);
  807. },
  808. function (stanza) {
  809. var error = ($(stanza).find('error').length) ? {
  810. code: $(stanza).find('error').attr('code'),
  811. reason: $(stanza).find('error :first')[0].tagName,
  812. }:{};
  813. $(document).trigger('ack.jingle', [self.sid, error]);
  814. },
  815. 10000);
  816. if (this.statsinterval !== null) {
  817. window.clearInterval(this.statsinterval);
  818. this.statsinterval = null;
  819. }
  820. };