Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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