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

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