選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

colibri.js 40KB

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