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 36KB

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