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

colibri.js 33KB

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