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

colibri.js 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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. function ColibriFocus(connection, bridgejid) {
  35. this.connection = connection;
  36. this.bridgejid = bridgejid;
  37. this.peers = [];
  38. this.confid = null;
  39. this.peerconnection = null;
  40. this.sid = Math.random().toString(36).substr(2, 12);
  41. this.connection.jingle.sessions[this.sid] = this;
  42. this.mychannel = [];
  43. this.channels = [];
  44. this.remotessrc = {};
  45. // ssrc lines to be added on next update
  46. this.addssrc = [];
  47. // ssrc lines to be removed on next update
  48. this.removessrc = [];
  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 ob = 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. ob.peers.push(peer);
  64. ob.channels.push([]);
  65. });
  66. this.peerconnection = new TraceablePeerConnection(this.connection.jingle.ice_config, this.connection.jingle.pc_constraints);
  67. this.peerconnection.addStream(this.connection.jingle.localStream);
  68. this.peerconnection.oniceconnectionstatechange = function (event) {
  69. console.warn('ice connection state changed to', ob.peerconnection.iceConnectionState);
  70. /*
  71. if (ob.peerconnection.signalingState == 'stable' && ob.peerconnection.iceConnectionState == 'connected') {
  72. console.log('adding new remote SSRCs from iceconnectionstatechange');
  73. window.setTimeout(function() { ob.modifySources(); }, 1000);
  74. }
  75. */
  76. };
  77. this.peerconnection.onsignalingstatechange = function (event) {
  78. console.warn(ob.peerconnection.signalingState);
  79. /*
  80. if (ob.peerconnection.signalingState == 'stable' && ob.peerconnection.iceConnectionState == 'connected') {
  81. console.log('adding new remote SSRCs from signalingstatechange');
  82. window.setTimeout(function() { ob.modifySources(); }, 1000);
  83. }
  84. */
  85. };
  86. this.peerconnection.onaddstream = function (event) {
  87. ob.remoteStream = event.stream;
  88. $(document).trigger('remotestreamadded.jingle', [event, ob.sid]);
  89. };
  90. this.peerconnection.onicecandidate = function (event) {
  91. ob.sendIceCandidate(event.candidate);
  92. };
  93. this.peerconnection.createOffer(
  94. function (offer) {
  95. ob.peerconnection.setLocalDescription(
  96. offer,
  97. function () {
  98. // success
  99. // FIXME: could call _makeConference here and trickle candidates later
  100. },
  101. function (error) {
  102. console.log('setLocalDescription failed', error);
  103. }
  104. );
  105. },
  106. function (error) {
  107. console.warn(error);
  108. }
  109. );
  110. this.peerconnection.onicecandidate = function (event) {
  111. console.log('candidate', event.candidate);
  112. if (!event.candidate) {
  113. console.log('end of candidates');
  114. ob._makeConference();
  115. return;
  116. }
  117. };
  118. };
  119. ColibriFocus.prototype._makeConference = function () {
  120. var ob = this;
  121. var elem = $iq({to: this.bridgejid, type: 'get'});
  122. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri'});
  123. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  124. localSDP.media.forEach(function (media, channel) {
  125. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  126. elem.c('content', {name: name});
  127. elem.c('channel', {initiator: 'false', expire: '15'});
  128. // FIXME: should reuse code from .toJingle
  129. var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
  130. for (var j = 0; j < mline.fmt.length; j++) {
  131. var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
  132. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  133. elem.up();
  134. }
  135. localSDP.TransportToJingle(channel, elem);
  136. elem.up(); // end of channel
  137. for (j = 0; j < ob.peers.length; j++) {
  138. elem.c('channel', {initiator: 'true', expire:'15' }).up();
  139. }
  140. elem.up(); // end of content
  141. });
  142. this.connection.sendIQ(elem,
  143. function (result) {
  144. ob.createdConference(result);
  145. },
  146. function (error) {
  147. console.warn(error);
  148. }
  149. );
  150. };
  151. // callback when a conference was created
  152. ColibriFocus.prototype.createdConference = function (result) {
  153. console.log('created a conference on the bridge');
  154. var tmp;
  155. this.confid = $(result).find('>conference').attr('id');
  156. var remotecontents = $(result).find('>conference>content').get();
  157. var numparticipants = 0;
  158. for (var i = 0; i < remotecontents.length; i++) {
  159. tmp = $(remotecontents[i]).find('>channel').get();
  160. this.mychannel.push($(tmp.shift()));
  161. numparticipants = tmp.length;
  162. for (j = 0; j < tmp.length; j++) {
  163. if (this.channels[j] === undefined) {
  164. this.channels[j] = [];
  165. }
  166. this.channels[j].push(tmp[j]);
  167. }
  168. }
  169. console.log('remote channels', this.channels);
  170. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  171. localSDP.removeSessionLines('a=group:');
  172. localSDP.removeSessionLines('a=msid-semantic:');
  173. // establish our channel with the bridge
  174. // static answer taken from chrome M31, should be replaced by a
  175. // dynamic one that is based on our offer FIXME
  176. var bridgeSDP = new SDP("");
  177. // 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');
  178. // only do what's in the offer
  179. bridgeSDP.session = localSDP.session;
  180. bridgeSDP.media.length = localSDP.media.length;
  181. var channel;
  182. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  183. bridgeSDP.media[channel] = '';
  184. // unchanged lines
  185. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'm=') + '\r\n';
  186. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'c=') + '\r\n';
  187. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:')) {
  188. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:') + '\r\n';
  189. }
  190. if (SDPUtil.find_line(localSDP.media[channel], 'a=mid:')) {
  191. bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=mid:') + '\r\n';
  192. }
  193. if (SDPUtil.find_line(localSDP.media[channel], 'a=sendrecv')) {
  194. bridgeSDP.media[channel] += 'a=sendrecv\r\n';
  195. }
  196. if (SDPUtil.find_line(localSDP.media[channel], 'a=extmap:')) {
  197. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=extmap:').join('\r\n') + '\r\n';
  198. }
  199. // FIXME: should look at m-line and group the ids together
  200. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtpmap:')) {
  201. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtpmap:').join('\r\n') + '\r\n';
  202. }
  203. if (SDPUtil.find_line(localSDP.media[channel], 'a=fmtp:')) {
  204. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=fmtp:').join('\r\n') + '\r\n';
  205. }
  206. if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp-fb:')) {
  207. bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtcp-fb:').join('\r\n') + '\r\n';
  208. }
  209. // FIXME: changed lines -- a=sendrecv direction, a=setup direction
  210. }
  211. // get the mixed ssrc
  212. for (channel = 0; channel < bridgeSDP.media.length; channel++) {
  213. tmp = $(this.mychannel[channel]).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  214. // FIXME: check rtp-level-relay-type
  215. if (tmp.length) {
  216. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  217. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  218. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabela0 mixedlabela0' + '\r\n';
  219. bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabela0' + '\r\n';
  220. } else {
  221. // make chrome happy... '3735928559' == 0xDEADBEEF
  222. // FIXME: this currently appears as two streams, should be one
  223. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  224. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  225. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabelv0 mixedlabelv0' + '\r\n';
  226. bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabelv0' + '\r\n';
  227. }
  228. // FIXME: should take code from .fromJingle
  229. tmp = $(this.mychannel[channel]).find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  230. if (tmp.length) {
  231. bridgeSDP.media[channel] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  232. bridgeSDP.media[channel] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  233. tmp.find('>candidate').each(function () {
  234. bridgeSDP.media[channel] += SDPUtil.candidateFromJingle(this);
  235. });
  236. tmp = tmp.find('>fingerprint');
  237. if (tmp.length) {
  238. bridgeSDP.media[channel] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  239. if (tmp.attr('setup')) {
  240. bridgeSDP.media[channel] += 'a=setup:' + tmp.attr('setup') + '\r\n';
  241. }
  242. }
  243. }
  244. }
  245. bridgeSDP.raw = bridgeSDP.session + bridgeSDP.media.join('');
  246. var ob = this;
  247. this.peerconnection.setRemoteDescription(
  248. new RTCSessionDescription({type: 'answer', sdp: bridgeSDP.raw}),
  249. function () {
  250. console.log('setRemoteDescription success');
  251. for (var i = 0; i < numparticipants; i++) {
  252. ob.initiate(ob.peers[i], true);
  253. }
  254. },
  255. function (error) {
  256. console.log('setRemoteDescription failed');
  257. }
  258. );
  259. };
  260. // send a session-initiate to a new participant
  261. ColibriFocus.prototype.initiate = function (peer, isInitiator) {
  262. var participant = this.peers.indexOf(peer);
  263. console.log('tell', peer, participant);
  264. var sdp;
  265. if (this.peerconnection !== null && this.peerconnection.signalingState == 'stable') {
  266. sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  267. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  268. // throw away stuff we don't want
  269. // not needed with static offer
  270. sdp.removeSessionLines('a=group:');
  271. sdp.removeSessionLines('a=msid-semantic:'); // FIXME: not mapped over jingle anyway...
  272. for (var i = 0; i < sdp.media.length; i++) {
  273. sdp.removeMediaLines(i, 'a=rtcp-mux');
  274. sdp.removeMediaLines(i, 'a=ssrc:');
  275. sdp.removeMediaLines(i, 'a=crypto:');
  276. sdp.removeMediaLines(i, 'a=candidate:');
  277. sdp.removeMediaLines(i, 'a=ice-options:google-ice');
  278. sdp.removeMediaLines(i, 'a=ice-ufrag:');
  279. sdp.removeMediaLines(i, 'a=ice-pwd:');
  280. sdp.removeMediaLines(i, 'a=fingerprint:');
  281. sdp.removeMediaLines(i, 'a=setup:');
  282. if (i > 0) { // not for audio
  283. // re-add all remote a=ssrcs
  284. for (var jid in this.remotessrc) {
  285. if (jid == peer) continue;
  286. sdp.media[i] += this.remotessrc[jid][i];
  287. }
  288. // and local a=ssrc lines
  289. sdp.media[i] += SDPUtil.find_lines(localSDP.media[i], 'a=ssrc').join('\r\n') + '\r\n';
  290. }
  291. }
  292. sdp.raw = sdp.session + sdp.media.join('');
  293. } else {
  294. console.error('can not initiate a new session without a stable peerconnection');
  295. return;
  296. }
  297. // add stuff we got from the bridge
  298. for (var j = 0; j < sdp.media.length; j++) {
  299. var chan = $(this.channels[participant][j]);
  300. console.log('channel id', chan.attr('id'));
  301. tmp = chan.find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  302. if (tmp.length) {
  303. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
  304. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
  305. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabela0 mixedlabela0' + '\r\n';
  306. sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabela0' + '\r\n';
  307. } else {
  308. // make chrome happy... '3735928559' == 0xDEADBEEF
  309. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
  310. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
  311. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabelv0 mixedlabelv0' + '\r\n';
  312. sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabelv0' + '\r\n';
  313. }
  314. tmp = chan.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  315. if (tmp.length) {
  316. if (tmp.attr('ufrag'))
  317. sdp.media[j] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  318. if (tmp.attr('pwd'))
  319. sdp.media[j] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  320. // and the candidates...
  321. tmp.find('>candidate').each(function () {
  322. sdp.media[j] += SDPUtil.candidateFromJingle(this);
  323. });
  324. tmp = tmp.find('>fingerprint');
  325. if (tmp.length) {
  326. sdp.media[j] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  327. /*
  328. if (tmp.attr('direction')) {
  329. sdp.media[j] += 'a=setup:' + tmp.attr('direction') + '\r\n';
  330. }
  331. */
  332. sdp.media[j] += 'a=setup:actpass\r\n';
  333. }
  334. }
  335. }
  336. // make a new colibri session and configure it
  337. // FIXME: is it correct to use this.connection.jid when used in a MUC?
  338. var sess = new ColibriSession(this.connection.jid,
  339. Math.random().toString(36).substr(2, 12), // random string
  340. this.connection);
  341. sess.initiate(peer);
  342. sess.colibri = this;
  343. sess.localStream = this.connection.jingle.localStream;
  344. sess.media_constraints = this.connection.jingle.media_constraints;
  345. sess.pc_constraints = this.connection.jingle.pc_constraints;
  346. sess.ice_config = this.connection.ice_config;
  347. this.connection.jingle.sessions[sess.sid] = sess;
  348. this.connection.jingle.jid2session[sess.peerjid] = sess;
  349. // send a session-initiate
  350. var init = $iq({to: peer, type: 'set'})
  351. .c('jingle',
  352. {xmlns: 'urn:xmpp:jingle:1',
  353. action: 'session-initiate',
  354. initiator: sess.me,
  355. sid: sess.sid
  356. }
  357. );
  358. sdp.toJingle(init, 'initiator');
  359. this.connection.sendIQ(init,
  360. function (res) {
  361. console.log('got result');
  362. },
  363. function (err) {
  364. console.log('got error');
  365. }
  366. );
  367. };
  368. // pull in a new participant into the conference
  369. ColibriFocus.prototype.addNewParticipant = function (peer) {
  370. var ob = this;
  371. if (this.confid === 0) {
  372. // bad state
  373. console.log('confid does not exist yet, postponing', peer);
  374. window.setTimeout(function () {
  375. ob.addNewParticipant(peer);
  376. }, 250);
  377. return;
  378. }
  379. var index = this.channels.length;
  380. this.channels.push([]);
  381. this.peers.push(peer);
  382. var elem = $iq({to: this.bridgejid, type: 'get'});
  383. elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  384. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  385. localSDP.media.forEach(function (media, channel) {
  386. var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  387. elem.c('content', {name: name});
  388. elem.c('channel', {initiator: 'true', expire:'15'});
  389. elem.up(); // end of channel
  390. elem.up(); // end of content
  391. });
  392. this.connection.sendIQ(elem,
  393. function (result) {
  394. var contents = $(result).find('>conference>content').get();
  395. for (var i = 0; i < contents.length; i++) {
  396. tmp = $(contents[i]).find('>channel').get();
  397. ob.channels[index][i] = tmp[0];
  398. }
  399. ob.initiate(peer, true);
  400. },
  401. function (error) {
  402. console.warn(error);
  403. }
  404. );
  405. };
  406. // update the channel description (payload-types + dtls fp) for a participant
  407. ColibriFocus.prototype.updateChannel = function (remoteSDP, participant) {
  408. console.log('change allocation for', this.confid);
  409. var change = $iq({to: this.bridgejid, type: 'set'});
  410. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  411. for (channel = 0; channel < this.channels[participant].length; channel++) {
  412. change.c('content', {name: channel === 0 ? 'audio' : 'video'});
  413. change.c('channel', {id: $(this.channels[participant][channel]).attr('id')});
  414. var rtpmap = SDPUtil.find_lines(remoteSDP.media[channel], 'a=rtpmap:');
  415. rtpmap.forEach(function (val) {
  416. // TODO: too much copy-paste
  417. var rtpmap = SDPUtil.parse_rtpmap(val);
  418. change.c('payload-type', rtpmap);
  419. //
  420. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  421. /*
  422. if (SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id)) {
  423. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id));
  424. for (var k = 0; k < tmp.length; k++) {
  425. change.c('parameter', tmp[k]).up();
  426. }
  427. }
  428. */
  429. change.up();
  430. });
  431. // now add transport
  432. remoteSDP.TransportToJingle(channel, change);
  433. change.up(); // end of channel
  434. change.up(); // end of content
  435. }
  436. this.connection.sendIQ(change,
  437. function (res) {
  438. console.log('got result');
  439. },
  440. function (err) {
  441. console.log('got error');
  442. }
  443. );
  444. };
  445. // tell everyone about a new participants a=ssrc lines (isadd is true)
  446. // or a leaving participants a=ssrc lines
  447. // FIXME: should not take an SDP, but rather the a=ssrc lines and probably a=mid
  448. ColibriFocus.prototype.sendSSRCUpdate = function (sdp, exclude, isadd) {
  449. var ob = this;
  450. this.peers.forEach(function (peerjid) {
  451. if (peerjid == exclude) return;
  452. console.log('tell', peerjid, 'about ' + (isadd ? 'new' : 'removed') + ' ssrcs from', exclude);
  453. if (!ob.remotessrc[peerjid]) {
  454. // FIXME: this should only send to participants that are stable, i.e. who have sent a session-accept
  455. // possibly, this.remoteSSRC[session.peerjid] does not exist yet
  456. console.warn('do we really want to bother', peerjid, 'with updates yet?');
  457. }
  458. var channel;
  459. var peersess = ob.connection.jingle.jid2session[peerjid];
  460. var modify = $iq({to: peerjid, type: 'set'})
  461. .c('jingle', {
  462. xmlns: 'urn:xmpp:jingle:1',
  463. action: isadd ? 'addsource' : 'removesource',
  464. initiator: peersess.initiator,
  465. sid: peersess.sid
  466. }
  467. );
  468. // FIXME: only announce video ssrcs since we mix audio and dont need
  469. // the audio ssrcs therefore
  470. var modified = false;
  471. for (channel = 0; channel < sdp.media.length; channel++) {
  472. modified = true;
  473. tmp = SDPUtil.find_lines(sdp.media[channel], 'a=ssrc:');
  474. modify.c('content', {name: SDPUtil.parse_mid(SDPUtil.find_line(sdp.media[channel], 'a=mid:'))});
  475. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  476. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  477. tmp.forEach(function (line) {
  478. var idx = line.indexOf(' ');
  479. var linessrc = line.substr(0, idx).substr(7);
  480. modify.attrs({ssrc: linessrc});
  481. var kv = line.substr(idx + 1);
  482. modify.c('parameter');
  483. if (kv.indexOf(':') == -1) {
  484. modify.attrs({ name: kv });
  485. } else {
  486. modify.attrs({ name: kv.split(':', 2)[0] });
  487. modify.attrs({ value: kv.split(':', 2)[1] });
  488. }
  489. modify.up();
  490. });
  491. modify.up(); // end of source
  492. modify.up(); // end of content
  493. }
  494. if (modified) {
  495. ob.connection.sendIQ(modify,
  496. function (res) {
  497. console.warn('got modify result');
  498. },
  499. function (err) {
  500. console.warn('got modify error');
  501. }
  502. );
  503. } else {
  504. console.log('modification not necessary');
  505. }
  506. });
  507. };
  508. ColibriFocus.prototype.setRemoteDescription = function (session, elem, desctype) {
  509. var participant = this.peers.indexOf(session.peerjid);
  510. console.log('Colibri.setRemoteDescription from', session.peerjid, participant);
  511. var ob = this;
  512. var remoteSDP = new SDP('');
  513. var tmp;
  514. var channel;
  515. remoteSDP.fromJingle(elem);
  516. // ACT 1: change allocation on bridge
  517. this.updateChannel(remoteSDP, participant);
  518. // ACT 2: tell anyone else about the new SSRCs
  519. this.sendSSRCUpdate(remoteSDP, session.peerjid, true);
  520. // ACT 3: note the SSRCs
  521. this.remotessrc[session.peerjid] = [];
  522. for (channel = 0; channel < this.channels[participant].length; channel++) {
  523. if (channel == 0) continue;
  524. this.remotessrc[session.peerjid][channel] = SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n';
  525. }
  526. // ACT 4: add new a=ssrc lines to local remotedescription
  527. for (channel = 0; channel < this.channels[participant].length; channel++) {
  528. if (channel == 0) continue;
  529. if (!this.addssrc[channel]) this.addssrc[channel] = '';
  530. this.addssrc[channel] += SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n';
  531. }
  532. this.modifySources();
  533. };
  534. // relay ice candidates to bridge using trickle
  535. ColibriFocus.prototype.addIceCandidate = function (session, elem) {
  536. var ob = this;
  537. var participant = this.peers.indexOf(session.peerjid);
  538. console.log('change transport allocation for', this.confid, session.peerjid, participant);
  539. var change = $iq({to: this.bridgejid, type: 'set'});
  540. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  541. $(elem).each(function () {
  542. var name = $(this).attr('name');
  543. var channel = name == 'audio' ? 0 : 1; // FIXME: search mlineindex in localdesc
  544. change.c('content', {name: name});
  545. change.c('channel', {id: $(ob.channels[participant][channel]).attr('id')});
  546. $(this).find('>transport').each(function () {
  547. change.c('transport', {
  548. ufrag: $(this).attr('ufrag'),
  549. pwd: $(this).attr('pwd'),
  550. xmlns: $(this).attr('xmlns')
  551. });
  552. $(this).find('>candidate').each(function () {
  553. /* not yet
  554. if (this.getAttribute('protocol') == 'tcp' && this.getAttribute('port') == 0) {
  555. // chrome generates TCP candidates with port 0
  556. return;
  557. }
  558. */
  559. var line = SDPUtil.candidateFromJingle(this);
  560. change.c('candidate', SDPUtil.candidateToJingle(line)).up();
  561. });
  562. change.up(); // end of transport
  563. });
  564. change.up(); // end of channel
  565. change.up(); // end of content
  566. });
  567. // FIXME: need to check if there is at least one candidate when filtering TCP ones
  568. this.connection.sendIQ(change,
  569. function (res) {
  570. console.log('got result');
  571. },
  572. function (err) {
  573. console.warn('got error');
  574. }
  575. );
  576. };
  577. // send our own candidate to the bridge
  578. ColibriFocus.prototype.sendIceCandidate = function (candidate) {
  579. //console.log('candidate', candidate);
  580. if (!candidate) {
  581. console.log('end of candidates');
  582. return;
  583. }
  584. var mycands = $iq({to: this.bridgejid, type: 'set'});
  585. mycands.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  586. mycands.c('content', {name: candidate.sdpMid });
  587. mycands.c('channel', {id: $(this.mychannel[candidate.sdpMLineIndex]).attr('id')});
  588. mycands.c('transport', {xmlns: 'urn:xmpp:jingle:transports:ice-udp:1'});
  589. tmp = SDPUtil.candidateToJingle(candidate.candidate);
  590. mycands.c('candidate', tmp).up();
  591. this.connection.sendIQ(mycands,
  592. function (res) {
  593. console.log('got result');
  594. },
  595. function (err) {
  596. console.warn('got error');
  597. }
  598. );
  599. };
  600. ColibriFocus.prototype.terminate = function (session, reason) {
  601. console.log('remote session terminated from', session.peerjid);
  602. var participant = this.peers.indexOf(session.peerjid);
  603. if (!this.remotessrc[session.peerjid] || participant == -1) {
  604. return;
  605. }
  606. console.log('remote ssrcs:', this.remotessrc[session.peerjid]);
  607. var ssrcs = this.remotessrc[session.peerjid];
  608. for (var i = 0; i < ssrcs.length; i++) {
  609. if (!this.removessrc[i]) this.removessrc[i] = '';
  610. this.removessrc[i] += ssrcs[i];
  611. }
  612. // remove from this.peers
  613. this.peers.splice(participant, 1);
  614. // expire channel on bridge
  615. var change = $iq({to: this.bridgejid, type: 'set'});
  616. change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
  617. for (var channel = 0; channel < this.channels[participant].length; channel++) {
  618. change.c('content', {name: channel === 0 ? 'audio' : 'video'});
  619. change.c('channel', {id: $(this.channels[participant][channel]).attr('id'), expire: '0'});
  620. change.up(); // end of channel
  621. change.up(); // end of content
  622. }
  623. this.connection.sendIQ(change,
  624. function (res) {
  625. console.log('got result');
  626. },
  627. function (err) {
  628. console.log('got error');
  629. }
  630. );
  631. // and remove from channels
  632. this.channels.splice(participant, 1);
  633. // tell everyone about the ssrcs to be removed
  634. var sdp = new SDP('');
  635. var localSDP = new SDP(this.peerconnection.localDescription.sdp);
  636. var contents = SDPUtil.find_lines(localSDP.raw, 'a=mid:').map(SDPUtil.parse_mid);
  637. for (var j = 0; j < ssrcs.length; j++) {
  638. sdp.media[j] = 'a=mid:' + contents[j] + '\r\n';
  639. sdp.media[j] += ssrcs[j];
  640. this.removessrc[j] += ssrcs[j];
  641. }
  642. this.sendSSRCUpdate(sdp, session.peerjid, false);
  643. delete this.remotessrc[session.peerjid];
  644. this.modifySources();
  645. };
  646. ColibriFocus.prototype.modifySources = function () {
  647. var ob = this;
  648. if (!(this.addssrc.length || this.removessrc.length)) return;
  649. if (this.peerconnection.signalingState == 'closed') return;
  650. // FIXME: this is a big hack
  651. // https://code.google.com/p/webrtc/issues/detail?id=2688
  652. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  653. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  654. window.setTimeout(function () { ob.modifySources(); }, 250);
  655. this.wait = true;
  656. return;
  657. }
  658. if (this.wait) {
  659. window.setTimeout(function () { ob.modifySources(); }, 2500);
  660. this.wait = false;
  661. return;
  662. }
  663. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  664. // add sources
  665. this.addssrc.forEach(function (lines, idx) {
  666. sdp.media[idx] += lines;
  667. });
  668. this.addssrc = [];
  669. // remove sources
  670. this.removessrc.forEach(function (lines, idx) {
  671. lines = lines.split('\r\n');
  672. lines.pop(); // remove empty last element;
  673. lines.forEach(function (line) {
  674. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  675. });
  676. });
  677. this.removessrc = [];
  678. sdp.raw = sdp.session + sdp.media.join('');
  679. this.peerconnection.setRemoteDescription(
  680. new RTCSessionDescription({type: 'offer', sdp: sdp.raw }),
  681. function () {
  682. console.log('setModifiedRemoteDescription ok');
  683. ob.peerconnection.createAnswer(
  684. function (modifiedAnswer) {
  685. console.log('modifiedAnswer created');
  686. // FIXME: pushing down an answer while ice connection state
  687. // is still checking is bad...
  688. console.log(ob.peerconnection.iceConnectionState);
  689. ob.peerconnection.setLocalDescription(modifiedAnswer,
  690. function () {
  691. console.log('setModifiedLocalDescription ok');
  692. },
  693. function (error) {
  694. console.log('setModifiedLocalDescription failed');
  695. }
  696. );
  697. },
  698. function (error) {
  699. console.log('createModifiedAnswer failed');
  700. }
  701. );
  702. },
  703. function (error) {
  704. console.log('setModifiedRemoteDescription failed');
  705. }
  706. );
  707. };
  708. // A colibri session is similar to a jingle session, it just implements some things differently
  709. // FIXME: inherit jinglesession, see https://github.com/legastero/Jingle-RTCPeerConnection/blob/master/index.js
  710. function ColibriSession(me, sid, connection) {
  711. this.me = me;
  712. this.sid = sid;
  713. this.connection = connection;
  714. //this.peerconnection = null;
  715. //this.mychannel = null;
  716. //this.channels = null;
  717. this.peerjid = null;
  718. this.colibri = null;
  719. }
  720. // implementation of JingleSession interface
  721. ColibriSession.prototype.initiate = function (peerjid, isInitiator) {
  722. this.peerjid = peerjid;
  723. };
  724. ColibriSession.prototype.sendOffer = function (offer) {
  725. console.log('ColibriSession.sendOffer');
  726. };
  727. ColibriSession.prototype.accept = function () {
  728. console.log('ColibriSession.accept');
  729. };
  730. ColibriSession.prototype.terminate = function (reason) {
  731. this.colibri.terminate(this, reason);
  732. };
  733. ColibriSession.prototype.active = function () {
  734. console.log('ColibriSession.active');
  735. };
  736. ColibriSession.prototype.setRemoteDescription = function (elem, desctype) {
  737. this.colibri.setRemoteDescription(this, elem, desctype);
  738. };
  739. ColibriSession.prototype.addIceCandidate = function (elem) {
  740. this.colibri.addIceCandidate(this, elem);
  741. };
  742. ColibriSession.prototype.sendAnswer = function (sdp, provisional) {
  743. console.log('ColibriSession.sendAnswer');
  744. };
  745. ColibriSession.prototype.sendTerminate = function (reason, text) {
  746. console.log('ColibriSession.sendTerminate');
  747. };