您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

colibri.js 34KB

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