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

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