You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 62KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. /* jshint -W117 */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var JingleSession = require("./JingleSession");
  4. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5. var SDPDiffer = require("./SDPDiffer");
  6. var SDPUtil = require("./SDPUtil");
  7. var SDP = require("./SDP");
  8. var async = require("async");
  9. var transform = require("sdp-transform");
  10. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11. var RTCBrowserType = require("../RTC/RTCBrowserType");
  12. var RTC = require("../RTC/RTC");
  13. // Jingle stuff
  14. function JingleSessionPC(me, sid, connection, service) {
  15. JingleSession.call(this, me, sid, connection, service);
  16. this.initiator = null;
  17. this.responder = null;
  18. this.peerjid = null;
  19. this.state = null;
  20. this.localSDP = null;
  21. this.remoteSDP = null;
  22. this.relayedStreams = [];
  23. this.usetrickle = true;
  24. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  25. this.hadstuncandidate = false;
  26. this.hadturncandidate = false;
  27. this.lasticecandidate = false;
  28. this.statsinterval = null;
  29. this.reason = null;
  30. this.addssrc = [];
  31. this.removessrc = [];
  32. this.pendingop = null;
  33. this.switchstreams = false;
  34. this.addingStreams = false;
  35. this.wait = true;
  36. /**
  37. * A map that stores SSRCs of local streams
  38. * @type {{}} maps media type('audio' or 'video') to SSRC number
  39. */
  40. this.localStreamsSSRC = {};
  41. this.ssrcOwners = {};
  42. this.ssrcVideoTypes = {};
  43. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  44. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  45. /**
  46. * The indicator which determines whether the (local) video has been muted
  47. * in response to a user command in contrast to an automatic decision made
  48. * by the application logic.
  49. */
  50. this.videoMuteByUser = false;
  51. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  52. // We start with the queue paused. We resume it when the signaling state is
  53. // stable and the ice connection state is connected.
  54. this.modifySourcesQueue.pause();
  55. }
  56. //XXX this is badly broken...
  57. JingleSessionPC.prototype = JingleSession.prototype;
  58. JingleSessionPC.prototype.constructor = JingleSessionPC;
  59. JingleSessionPC.prototype.setOffer = function(offer) {
  60. this.setRemoteDescription(offer, 'offer');
  61. };
  62. JingleSessionPC.prototype.setAnswer = function(answer) {
  63. this.setRemoteDescription(answer, 'answer');
  64. };
  65. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  66. var signalingState = this.peerconnection.signalingState;
  67. var iceConnectionState = this.peerconnection.iceConnectionState;
  68. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  69. this.modifySourcesQueue.resume();
  70. } else {
  71. this.modifySourcesQueue.pause();
  72. }
  73. };
  74. JingleSessionPC.prototype.doInitialize = function () {
  75. var self = this;
  76. this.hadstuncandidate = false;
  77. this.hadturncandidate = false;
  78. this.lasticecandidate = false;
  79. // True if reconnect is in progress
  80. this.isreconnect = false;
  81. // Set to true if the connection was ever stable
  82. this.wasstable = false;
  83. this.peerconnection = new TraceablePeerConnection(
  84. this.connection.jingle.ice_config,
  85. RTC.getPCConstraints(),
  86. this);
  87. this.peerconnection.onicecandidate = function (event) {
  88. var protocol;
  89. if (event && event.candidate) {
  90. protocol = (typeof event.candidate.protocol === 'string')
  91. ? event.candidate.protocol.toLowerCase() : '';
  92. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  93. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  94. return;
  95. }
  96. }
  97. self.sendIceCandidate(event.candidate);
  98. };
  99. this.peerconnection.onaddstream = function (event) {
  100. if (event.stream.id !== 'default') {
  101. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  102. self.remoteStreamAdded(event);
  103. } else {
  104. // This is a recvonly stream. Clients that implement Unified Plan,
  105. // such as Firefox use recvonly "streams/channels/tracks" for
  106. // receiving remote stream/tracks, as opposed to Plan B where there
  107. // are only 3 channels: audio, video and data.
  108. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  109. }
  110. };
  111. this.peerconnection.onremovestream = function (event) {
  112. // Remove the stream from remoteStreams
  113. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  114. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  115. };
  116. this.peerconnection.onsignalingstatechange = function (event) {
  117. if (!(self && self.peerconnection)) return;
  118. if (self.peerconnection.signalingState === 'stable') {
  119. self.wasstable = true;
  120. }
  121. self.updateModifySourcesQueue();
  122. };
  123. /**
  124. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  125. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  126. * RTCPeerConnection.iceConnectionState changes.
  127. *
  128. * @param event the event containing information about the change
  129. */
  130. this.peerconnection.oniceconnectionstatechange = function (event) {
  131. if (!(self && self.peerconnection)) return;
  132. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  133. ":\t", window.performance.now());
  134. self.updateModifySourcesQueue();
  135. switch (self.peerconnection.iceConnectionState) {
  136. case 'connected':
  137. // Informs interested parties that the connection has been restored.
  138. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  139. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  140. self.isreconnect = false;
  141. break;
  142. case 'disconnected':
  143. self.isreconnect = true;
  144. // Informs interested parties that the connection has been interrupted.
  145. if (self.wasstable)
  146. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  147. break;
  148. case 'failed':
  149. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  150. break;
  151. }
  152. onIceConnectionStateChange(self.sid, self);
  153. };
  154. this.peerconnection.onnegotiationneeded = function (event) {
  155. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  156. };
  157. this.relayedStreams.forEach(function(stream) {
  158. self.peerconnection.addStream(stream);
  159. });
  160. };
  161. function onIceConnectionStateChange(sid, session) {
  162. switch (session.peerconnection.iceConnectionState) {
  163. case 'checking':
  164. session.timeChecking = (new Date()).getTime();
  165. session.firstconnect = true;
  166. break;
  167. case 'completed': // on caller side
  168. case 'connected':
  169. if (session.firstconnect) {
  170. session.firstconnect = false;
  171. var metadata = {};
  172. metadata.setupTime
  173. = (new Date()).getTime() - session.timeChecking;
  174. session.peerconnection.getStats(function (res) {
  175. if(res && res.result) {
  176. res.result().forEach(function (report) {
  177. if (report.type == 'googCandidatePair' &&
  178. report.stat('googActiveConnection') == 'true') {
  179. metadata.localCandidateType
  180. = report.stat('googLocalCandidateType');
  181. metadata.remoteCandidateType
  182. = report.stat('googRemoteCandidateType');
  183. // log pair as well so we can get nice pie
  184. // charts
  185. metadata.candidatePair
  186. = report.stat('googLocalCandidateType') +
  187. ';' +
  188. report.stat('googRemoteCandidateType');
  189. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  190. {
  191. metadata.ipv6 = true;
  192. }
  193. }
  194. });
  195. }
  196. });
  197. }
  198. break;
  199. }
  200. }
  201. JingleSessionPC.prototype.accept = function () {
  202. this.state = 'active';
  203. var pranswer = this.peerconnection.localDescription;
  204. if (!pranswer || pranswer.type != 'pranswer') {
  205. return;
  206. }
  207. logger.log('going from pranswer to answer');
  208. if (this.usetrickle) {
  209. // remove candidates already sent from session-accept
  210. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  211. for (var i = 0; i < lines.length; i++) {
  212. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  213. }
  214. }
  215. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  216. // FIXME: change any inactive to sendrecv or whatever they were originally
  217. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  218. }
  219. var prsdp = new SDP(pranswer.sdp);
  220. if (this.webrtcIceTcpDisable) {
  221. prsdp.removeTcpCandidates = true;
  222. }
  223. if (this.webrtcIceUdpDisable) {
  224. prsdp.removeUdpCandidates = true;
  225. }
  226. var accept = $iq({to: this.peerjid,
  227. type: 'set'})
  228. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  229. action: 'session-accept',
  230. initiator: this.initiator,
  231. responder: this.responder,
  232. sid: this.sid });
  233. // FIXME why do we generate session-accept in 3 different places ?
  234. prsdp.toJingle(
  235. accept,
  236. this.initiator == this.me ? 'initiator' : 'responder');
  237. var sdp = this.peerconnection.localDescription.sdp;
  238. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  239. // FIXME: change any inactive to sendrecv or whatever they were originally
  240. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  241. }
  242. var self = this;
  243. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  244. function () {
  245. //logger.log('setLocalDescription success');
  246. self.setLocalDescription();
  247. self.connection.sendIQ(accept,
  248. function () {
  249. var ack = {};
  250. ack.source = 'answer';
  251. $(document).trigger('ack.jingle', [self.sid, ack]);
  252. },
  253. function (stanza) {
  254. var error = ($(stanza).find('error').length) ? {
  255. code: $(stanza).find('error').attr('code'),
  256. reason: $(stanza).find('error :first')[0].tagName
  257. }:{};
  258. error.source = 'answer';
  259. JingleSessionPC.onJingleError(self.sid, error);
  260. },
  261. 10000);
  262. },
  263. function (e) {
  264. logger.error('setLocalDescription failed', e);
  265. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  266. }
  267. );
  268. };
  269. JingleSessionPC.prototype.terminate = function (reason) {
  270. this.state = 'ended';
  271. this.reason = reason;
  272. this.peerconnection.close();
  273. if (this.statsinterval !== null) {
  274. window.clearInterval(this.statsinterval);
  275. this.statsinterval = null;
  276. }
  277. };
  278. JingleSessionPC.prototype.active = function () {
  279. return this.state == 'active';
  280. };
  281. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  282. var self = this;
  283. if (candidate && !this.lasticecandidate) {
  284. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  285. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  286. if (!(ice && jcand)) {
  287. logger.error('failed to get ice && jcand');
  288. return;
  289. }
  290. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  291. if (jcand.type === 'srflx') {
  292. this.hadstuncandidate = true;
  293. } else if (jcand.type === 'relay') {
  294. this.hadturncandidate = true;
  295. }
  296. if (this.usetrickle) {
  297. if (this.usedrip) {
  298. if (this.drip_container.length === 0) {
  299. // start 20ms callout
  300. window.setTimeout(function () {
  301. if (self.drip_container.length === 0) return;
  302. self.sendIceCandidates(self.drip_container);
  303. self.drip_container = [];
  304. }, 20);
  305. }
  306. this.drip_container.push(candidate);
  307. return;
  308. } else {
  309. self.sendIceCandidate([candidate]);
  310. }
  311. }
  312. } else {
  313. //logger.log('sendIceCandidate: last candidate.');
  314. if (!this.usetrickle) {
  315. //logger.log('should send full offer now...');
  316. //FIXME why do we generate session-accept in 3 different places ?
  317. var init = $iq({to: this.peerjid,
  318. type: 'set'})
  319. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  320. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  321. initiator: this.initiator,
  322. sid: this.sid});
  323. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  324. if (self.webrtcIceTcpDisable) {
  325. this.localSDP.removeTcpCandidates = true;
  326. }
  327. if (self.webrtcIceUdpDisable) {
  328. this.localSDP.removeUdpCandidates = true;
  329. }
  330. var sendJingle = function (ssrc) {
  331. if(!ssrc)
  332. ssrc = {};
  333. self.localSDP.toJingle(
  334. init,
  335. self.initiator == self.me ? 'initiator' : 'responder',
  336. ssrc);
  337. self.connection.sendIQ(init,
  338. function () {
  339. //logger.log('session initiate ack');
  340. var ack = {};
  341. ack.source = 'offer';
  342. $(document).trigger('ack.jingle', [self.sid, ack]);
  343. },
  344. function (stanza) {
  345. self.state = 'error';
  346. self.peerconnection.close();
  347. var error = ($(stanza).find('error').length) ? {
  348. code: $(stanza).find('error').attr('code'),
  349. reason: $(stanza).find('error :first')[0].tagName,
  350. }:{};
  351. error.source = 'offer';
  352. JingleSessionPC.onJingleError(self.sid, error);
  353. },
  354. 10000);
  355. };
  356. sendJingle();
  357. }
  358. this.lasticecandidate = true;
  359. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  360. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  361. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  362. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  363. }
  364. }
  365. };
  366. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  367. logger.log('sendIceCandidates', candidates);
  368. var cand = $iq({to: this.peerjid, type: 'set'})
  369. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  370. action: 'transport-info',
  371. initiator: this.initiator,
  372. sid: this.sid});
  373. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  374. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  375. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  376. if (cands.length > 0) {
  377. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  378. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  379. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  380. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  381. }).c('transport', ice);
  382. for (var i = 0; i < cands.length; i++) {
  383. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  384. }
  385. // add fingerprint
  386. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  387. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  388. tmp.required = true;
  389. cand.c(
  390. 'fingerprint',
  391. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  392. .t(tmp.fingerprint);
  393. delete tmp.fingerprint;
  394. cand.attrs(tmp);
  395. cand.up();
  396. }
  397. cand.up(); // transport
  398. cand.up(); // content
  399. }
  400. }
  401. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  402. //logger.log('was this the last candidate', this.lasticecandidate);
  403. this.connection.sendIQ(cand,
  404. function () {
  405. var ack = {};
  406. ack.source = 'transportinfo';
  407. $(document).trigger('ack.jingle', [this.sid, ack]);
  408. },
  409. function (stanza) {
  410. var error = ($(stanza).find('error').length) ? {
  411. code: $(stanza).find('error').attr('code'),
  412. reason: $(stanza).find('error :first')[0].tagName,
  413. }:{};
  414. error.source = 'transportinfo';
  415. JingleSessionPC.onJingleError(this.sid, error);
  416. },
  417. 10000);
  418. };
  419. JingleSessionPC.prototype.sendOffer = function () {
  420. //logger.log('sendOffer...');
  421. var self = this;
  422. this.peerconnection.createOffer(function (sdp) {
  423. self.createdOffer(sdp);
  424. },
  425. function (e) {
  426. logger.error('createOffer failed', e);
  427. },
  428. this.media_constraints
  429. );
  430. };
  431. // FIXME createdOffer is never used in jitsi-meet
  432. JingleSessionPC.prototype.createdOffer = function (sdp) {
  433. //logger.log('createdOffer', sdp);
  434. var self = this;
  435. this.localSDP = new SDP(sdp.sdp);
  436. //this.localSDP.mangle();
  437. var sendJingle = function () {
  438. var init = $iq({to: this.peerjid,
  439. type: 'set'})
  440. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  441. action: 'session-initiate',
  442. initiator: this.initiator,
  443. sid: this.sid});
  444. self.localSDP.toJingle(
  445. init,
  446. this.initiator == this.me ? 'initiator' : 'responder');
  447. self.connection.sendIQ(init,
  448. function () {
  449. var ack = {};
  450. ack.source = 'offer';
  451. $(document).trigger('ack.jingle', [self.sid, ack]);
  452. },
  453. function (stanza) {
  454. self.state = 'error';
  455. self.peerconnection.close();
  456. var error = ($(stanza).find('error').length) ? {
  457. code: $(stanza).find('error').attr('code'),
  458. reason: $(stanza).find('error :first')[0].tagName,
  459. }:{};
  460. error.source = 'offer';
  461. JingleSessionPC.onJingleError(self.sid, error);
  462. },
  463. 10000);
  464. }
  465. sdp.sdp = this.localSDP.raw;
  466. this.peerconnection.setLocalDescription(sdp,
  467. function () {
  468. if(self.usetrickle)
  469. {
  470. sendJingle();
  471. }
  472. self.setLocalDescription();
  473. //logger.log('setLocalDescription success');
  474. },
  475. function (e) {
  476. logger.error('setLocalDescription failed', e);
  477. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  478. }
  479. );
  480. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  481. for (var i = 0; i < cands.length; i++) {
  482. var cand = SDPUtil.parse_icecandidate(cands[i]);
  483. if (cand.type == 'srflx') {
  484. this.hadstuncandidate = true;
  485. } else if (cand.type == 'relay') {
  486. this.hadturncandidate = true;
  487. }
  488. }
  489. };
  490. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  491. var self = this;
  492. $(contents).each(function (idx, content) {
  493. var name = $(content).attr('name');
  494. var mediaType = this.getAttribute('name');
  495. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  496. ssrcs.each(function () {
  497. var ssrc = this.getAttribute('ssrc');
  498. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  499. function () {
  500. var owner = this.getAttribute('owner');
  501. self.ssrcOwners[ssrc] = owner;
  502. }
  503. );
  504. });
  505. });
  506. };
  507. /**
  508. * Returns the SSRC of local audio stream.
  509. * @param mediaType 'audio' or 'video' media type
  510. * @returns {*} the SSRC number of local audio or video stream.
  511. */
  512. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  513. return this.localStreamsSSRC[mediaType];
  514. };
  515. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  516. return this.ssrcOwners[ssrc];
  517. };
  518. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  519. //logger.log('setting remote description... ', desctype);
  520. this.remoteSDP = new SDP('');
  521. if (this.webrtcIceTcpDisable) {
  522. this.remoteSDP.removeTcpCandidates = true;
  523. }
  524. if (this.webrtcIceUdpDisable) {
  525. this.remoteSDP.removeUdpCandidates = true;
  526. }
  527. this.remoteSDP.fromJingle(elem);
  528. this.readSsrcInfo($(elem).find(">content"));
  529. if (this.peerconnection.remoteDescription) {
  530. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  531. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  532. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  533. for (var i = 0; i < pranswer.media.length; i++) {
  534. // make sure we have ice ufrag and pwd
  535. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  536. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  537. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  538. } else {
  539. logger.warn('no ice ufrag?');
  540. }
  541. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  542. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  543. } else {
  544. logger.warn('no ice pwd?');
  545. }
  546. }
  547. // copy over candidates
  548. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  549. for (var j = 0; j < lines.length; j++) {
  550. this.remoteSDP.media[i] += lines[j] + '\r\n';
  551. }
  552. }
  553. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  554. }
  555. }
  556. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  557. this.peerconnection.setRemoteDescription(remotedesc,
  558. function () {
  559. //logger.log('setRemoteDescription success');
  560. },
  561. function (e) {
  562. logger.error('setRemoteDescription error', e);
  563. JingleSessionPC.onJingleFatalError(self, e);
  564. }
  565. );
  566. };
  567. /**
  568. * Adds remote ICE candidates to this Jingle session.
  569. * @param elem An array of Jingle "content" elements?
  570. */
  571. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  572. var self = this;
  573. if (this.peerconnection.signalingState == 'closed') {
  574. return;
  575. }
  576. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  577. logger.log('trickle ice candidate arriving before session accept...');
  578. // create a PRANSWER for setRemoteDescription
  579. if (!this.remoteSDP) {
  580. var cobbled = 'v=0\r\n' +
  581. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  582. 's=-\r\n' +
  583. 't=0 0\r\n';
  584. // first, take some things from the local description
  585. for (var i = 0; i < this.localSDP.media.length; i++) {
  586. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  587. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  588. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  589. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  590. }
  591. cobbled += 'a=inactive\r\n';
  592. }
  593. this.remoteSDP = new SDP(cobbled);
  594. }
  595. // then add things like ice and dtls from remote candidate
  596. elem.each(function () {
  597. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  598. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  599. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  600. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  601. var tmp = $(this).find('transport');
  602. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  603. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  604. tmp = $(this).find('transport>fingerprint');
  605. if (tmp.length) {
  606. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  607. } else {
  608. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  609. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  610. }
  611. break;
  612. }
  613. }
  614. }
  615. });
  616. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  617. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  618. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  619. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  620. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  621. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  622. }).length == this.remoteSDP.media.length;
  623. if (iscomplete) {
  624. logger.log('setting pranswer');
  625. try {
  626. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  627. function() {
  628. },
  629. function(e) {
  630. logger.log('setRemoteDescription pranswer failed', e.toString());
  631. });
  632. } catch (e) {
  633. logger.error('setting pranswer failed', e);
  634. }
  635. } else {
  636. //logger.log('not yet setting pranswer');
  637. }
  638. }
  639. // operate on each content element
  640. elem.each(function () {
  641. // would love to deactivate this, but firefox still requires it
  642. var idx = -1;
  643. var i;
  644. for (i = 0; i < self.remoteSDP.media.length; i++) {
  645. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  646. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  647. idx = i;
  648. break;
  649. }
  650. }
  651. if (idx == -1) { // fall back to localdescription
  652. for (i = 0; i < self.localSDP.media.length; i++) {
  653. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  654. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  655. idx = i;
  656. break;
  657. }
  658. }
  659. }
  660. var name = $(this).attr('name');
  661. // TODO: check ice-pwd and ice-ufrag?
  662. $(this).find('transport>candidate').each(function () {
  663. var line, candidate;
  664. var protocol = this.getAttribute('protocol');
  665. protocol =
  666. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  667. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  668. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  669. return;
  670. }
  671. line = SDPUtil.candidateFromJingle(this);
  672. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  673. sdpMid: name,
  674. candidate: line});
  675. try {
  676. self.peerconnection.addIceCandidate(candidate);
  677. } catch (e) {
  678. logger.error('addIceCandidate failed', e.toString(), line);
  679. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  680. err, self.peerconnection);
  681. }
  682. });
  683. });
  684. };
  685. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  686. //logger.log('createAnswer', provisional);
  687. var self = this;
  688. this.peerconnection.createAnswer(
  689. function (sdp) {
  690. self.createdAnswer(sdp, provisional);
  691. },
  692. function (e) {
  693. logger.error('createAnswer failed', e);
  694. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  695. },
  696. this.media_constraints
  697. );
  698. };
  699. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  700. //logger.log('createAnswer callback');
  701. var self = this;
  702. this.localSDP = new SDP(sdp.sdp);
  703. //this.localSDP.mangle();
  704. this.usepranswer = provisional === true;
  705. if (this.usetrickle) {
  706. if (this.usepranswer) {
  707. sdp.type = 'pranswer';
  708. for (var i = 0; i < this.localSDP.media.length; i++) {
  709. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  710. }
  711. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  712. }
  713. }
  714. var self = this;
  715. var sendJingle = function (ssrcs) {
  716. // FIXME why do we generate session-accept in 3 different places ?
  717. var accept = $iq({to: self.peerjid,
  718. type: 'set'})
  719. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  720. action: 'session-accept',
  721. initiator: self.initiator,
  722. responder: self.responder,
  723. sid: self.sid });
  724. if (self.webrtcIceTcpDisable) {
  725. self.localSDP.removeTcpCandidates = true;
  726. }
  727. if (self.webrtcIceUdpDisable) {
  728. self.localSDP.removeUdpCandidates = true;
  729. }
  730. self.localSDP.toJingle(
  731. accept,
  732. self.initiator == self.me ? 'initiator' : 'responder',
  733. ssrcs);
  734. self.connection.sendIQ(accept,
  735. function () {
  736. var ack = {};
  737. ack.source = 'answer';
  738. $(document).trigger('ack.jingle', [self.sid, ack]);
  739. },
  740. function (stanza) {
  741. var error = ($(stanza).find('error').length) ? {
  742. code: $(stanza).find('error').attr('code'),
  743. reason: $(stanza).find('error :first')[0].tagName,
  744. }:{};
  745. error.source = 'answer';
  746. JingleSessionPC.onJingleError(self.sid, error);
  747. },
  748. 10000);
  749. }
  750. sdp.sdp = this.localSDP.raw;
  751. this.peerconnection.setLocalDescription(sdp,
  752. function () {
  753. //logger.log('setLocalDescription success');
  754. if (self.usetrickle && !self.usepranswer) {
  755. sendJingle();
  756. }
  757. self.setLocalDescription();
  758. },
  759. function (e) {
  760. logger.error('setLocalDescription failed', e);
  761. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  762. }
  763. );
  764. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  765. for (var j = 0; j < cands.length; j++) {
  766. var cand = SDPUtil.parse_icecandidate(cands[j]);
  767. if (cand.type == 'srflx') {
  768. this.hadstuncandidate = true;
  769. } else if (cand.type == 'relay') {
  770. this.hadturncandidate = true;
  771. }
  772. }
  773. };
  774. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  775. var self = this,
  776. term = $iq({to: this.peerjid,
  777. type: 'set'})
  778. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  779. action: 'session-terminate',
  780. initiator: this.initiator,
  781. sid: this.sid})
  782. .c('reason')
  783. .c(reason || 'success');
  784. if (text) {
  785. term.up().c('text').t(text);
  786. }
  787. this.connection.sendIQ(term,
  788. function () {
  789. self.peerconnection.close();
  790. self.peerconnection = null;
  791. self.terminate();
  792. var ack = {};
  793. ack.source = 'terminate';
  794. $(document).trigger('ack.jingle', [self.sid, ack]);
  795. },
  796. function (stanza) {
  797. var error = ($(stanza).find('error').length) ? {
  798. code: $(stanza).find('error').attr('code'),
  799. reason: $(stanza).find('error :first')[0].tagName,
  800. }:{};
  801. $(document).trigger('ack.jingle', [self.sid, error]);
  802. },
  803. 10000);
  804. if (this.statsinterval !== null) {
  805. window.clearInterval(this.statsinterval);
  806. this.statsinterval = null;
  807. }
  808. };
  809. /**
  810. * Handles a Jingle source-add message for this Jingle session.
  811. * @param elem An array of Jingle "content" elements.
  812. */
  813. JingleSessionPC.prototype.addSource = function (elem) {
  814. var self = this;
  815. // FIXME: dirty waiting
  816. if (!this.peerconnection.localDescription)
  817. {
  818. logger.warn("addSource - localDescription not ready yet")
  819. setTimeout(function()
  820. {
  821. self.addSource(elem);
  822. },
  823. 200
  824. );
  825. return;
  826. }
  827. logger.log('addssrc', new Date().getTime());
  828. logger.log('ice', this.peerconnection.iceConnectionState);
  829. this.readSsrcInfo(elem);
  830. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  831. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  832. $(elem).each(function (idx, content) {
  833. var name = $(content).attr('name');
  834. var lines = '';
  835. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  836. var semantics = this.getAttribute('semantics');
  837. var ssrcs = $(this).find('>source').map(function () {
  838. return this.getAttribute('ssrc');
  839. }).get();
  840. if (ssrcs.length) {
  841. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  842. }
  843. });
  844. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  845. tmp.each(function () {
  846. var ssrc = $(this).attr('ssrc');
  847. if(mySdp.containsSSRC(ssrc)){
  848. /**
  849. * This happens when multiple participants change their streams at the same time and
  850. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  851. * addssrc are scheduled for update IQ. See
  852. */
  853. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  854. return;
  855. }
  856. if (sdp.containsSSRC(ssrc)) {
  857. logger.warn("Source-add request for existing SSRC: " + ssrc);
  858. return;
  859. }
  860. $(this).find('>parameter').each(function () {
  861. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  862. if ($(this).attr('value') && $(this).attr('value').length)
  863. lines += ':' + $(this).attr('value');
  864. lines += '\r\n';
  865. });
  866. });
  867. sdp.media.forEach(function(media, idx) {
  868. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  869. return;
  870. sdp.media[idx] += lines;
  871. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  872. self.addssrc[idx] += lines;
  873. });
  874. sdp.raw = sdp.session + sdp.media.join('');
  875. });
  876. this.modifySourcesQueue.push(function() {
  877. // When a source is added and if this is FF, a new channel is allocated
  878. // for receiving the added source. We need to diffuse the SSRC of this
  879. // new recvonly channel to the rest of the peers.
  880. logger.log('modify sources done');
  881. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  882. logger.log("SDPs", mySdp, newSdp);
  883. self.notifyMySSRCUpdate(mySdp, newSdp);
  884. });
  885. };
  886. /**
  887. * Handles a Jingle source-remove message for this Jingle session.
  888. * @param elem An array of Jingle "content" elements.
  889. */
  890. JingleSessionPC.prototype.removeSource = function (elem) {
  891. var self = this;
  892. // FIXME: dirty waiting
  893. if (!this.peerconnection.localDescription) {
  894. logger.warn("removeSource - localDescription not ready yet");
  895. setTimeout(function() {
  896. self.removeSource(elem);
  897. },
  898. 200
  899. );
  900. return;
  901. }
  902. logger.log('removessrc', new Date().getTime());
  903. logger.log('ice', this.peerconnection.iceConnectionState);
  904. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  905. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  906. $(elem).each(function (idx, content) {
  907. var name = $(content).attr('name');
  908. var lines = '';
  909. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  910. var semantics = this.getAttribute('semantics');
  911. var ssrcs = $(this).find('>source').map(function () {
  912. return this.getAttribute('ssrc');
  913. }).get();
  914. if (ssrcs.length) {
  915. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  916. }
  917. });
  918. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  919. tmp.each(function () {
  920. var ssrc = $(this).attr('ssrc');
  921. // This should never happen, but can be useful for bug detection
  922. if(mySdp.containsSSRC(ssrc)){
  923. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  924. return;
  925. }
  926. $(this).find('>parameter').each(function () {
  927. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  928. if ($(this).attr('value') && $(this).attr('value').length)
  929. lines += ':' + $(this).attr('value');
  930. lines += '\r\n';
  931. });
  932. });
  933. sdp.media.forEach(function(media, idx) {
  934. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  935. return;
  936. sdp.media[idx] += lines;
  937. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  938. self.removessrc[idx] += lines;
  939. });
  940. sdp.raw = sdp.session + sdp.media.join('');
  941. });
  942. this.modifySourcesQueue.push(function() {
  943. // When a source is removed and if this is FF, the recvonly channel that
  944. // receives the remote stream is deactivated . We need to diffuse the
  945. // recvonly SSRC removal to the rest of the peers.
  946. logger.log('modify sources done');
  947. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  948. logger.log("SDPs", mySdp, newSdp);
  949. self.notifyMySSRCUpdate(mySdp, newSdp);
  950. });
  951. };
  952. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  953. var self = this;
  954. if (this.peerconnection.signalingState == 'closed') return;
  955. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  956. || this.switchstreams || this.addingStreams)){
  957. // There is nothing to do since scheduled job might have been executed by another succeeding call
  958. this.setLocalDescription();
  959. if(successCallback){
  960. successCallback();
  961. }
  962. queueCallback();
  963. return;
  964. }
  965. // Reset switch streams flags
  966. this.switchstreams = false;
  967. this.addingStreams = false;
  968. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  969. // add sources
  970. this.addssrc.forEach(function(lines, idx) {
  971. sdp.media[idx] += lines;
  972. });
  973. this.addssrc = [];
  974. // remove sources
  975. this.removessrc.forEach(function(lines, idx) {
  976. lines = lines.split('\r\n');
  977. lines.pop(); // remove empty last element;
  978. lines.forEach(function(line) {
  979. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  980. });
  981. });
  982. this.removessrc = [];
  983. sdp.raw = sdp.session + sdp.media.join('');
  984. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  985. function() {
  986. if(self.signalingState == 'closed') {
  987. logger.error("createAnswer attempt on closed state");
  988. queueCallback("createAnswer attempt on closed state");
  989. return;
  990. }
  991. self.peerconnection.createAnswer(
  992. function(modifiedAnswer) {
  993. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  994. if (self.pendingop !== null) {
  995. var sdp = new SDP(modifiedAnswer.sdp);
  996. if (sdp.media.length > 1) {
  997. switch(self.pendingop) {
  998. case 'mute':
  999. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  1000. break;
  1001. case 'unmute':
  1002. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  1003. break;
  1004. }
  1005. sdp.raw = sdp.session + sdp.media.join('');
  1006. modifiedAnswer.sdp = sdp.raw;
  1007. }
  1008. self.pendingop = null;
  1009. }
  1010. // FIXME: pushing down an answer while ice connection state
  1011. // is still checking is bad...
  1012. //logger.log(self.peerconnection.iceConnectionState);
  1013. // trying to work around another chrome bug
  1014. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  1015. self.peerconnection.setLocalDescription(modifiedAnswer,
  1016. function() {
  1017. //logger.log('modified setLocalDescription ok');
  1018. self.setLocalDescription();
  1019. if(successCallback){
  1020. successCallback();
  1021. }
  1022. queueCallback();
  1023. },
  1024. function(error) {
  1025. logger.error('modified setLocalDescription failed', error);
  1026. queueCallback(error);
  1027. }
  1028. );
  1029. },
  1030. function(error) {
  1031. logger.error('modified answer failed', error);
  1032. queueCallback(error);
  1033. }
  1034. );
  1035. },
  1036. function(error) {
  1037. logger.error('modify failed', error);
  1038. queueCallback(error);
  1039. }
  1040. );
  1041. };
  1042. /**
  1043. * Switches video streams.
  1044. * @param newStream new stream that will be used as video of this session.
  1045. * @param oldStream old video stream of this session.
  1046. * @param successCallback callback executed after successful stream switch.
  1047. * @param isAudio whether the streams are audio (if true) or video (if false).
  1048. */
  1049. JingleSessionPC.prototype.switchStreams =
  1050. function (newStream, oldStream, successCallback, isAudio) {
  1051. var self = this;
  1052. var sender, newTrack;
  1053. var senderKind = isAudio ? 'audio' : 'video';
  1054. // Remember SDP to figure out added/removed SSRCs
  1055. var oldSdp = null;
  1056. if (self.peerconnection) {
  1057. if (self.peerconnection.localDescription) {
  1058. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  1059. }
  1060. if (RTCBrowserType.getBrowserType() ===
  1061. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1062. // On Firefox we don't replace MediaStreams as this messes up the
  1063. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1064. // of complications. Instead, we use the RTPSender and replace just
  1065. // the track.
  1066. // Find the right sender (for audio or video)
  1067. self.peerconnection.peerconnection.getSenders().some(function (s) {
  1068. if (s.track && s.track.kind === senderKind) {
  1069. sender = s;
  1070. return true;
  1071. }
  1072. });
  1073. if (sender) {
  1074. // We assume that our streams have a single track, either audio
  1075. // or video.
  1076. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  1077. newStream.getVideoTracks()[0];
  1078. sender.replaceTrack(newTrack)
  1079. .then(function() {
  1080. console.log("Replaced a track, isAudio=" + isAudio);
  1081. })
  1082. .catch(function(err) {
  1083. console.log("Failed to replace a track: " + err);
  1084. });
  1085. } else {
  1086. console.log("Cannot switch tracks: no RTPSender.");
  1087. }
  1088. } else {
  1089. self.peerconnection.removeStream(oldStream, true);
  1090. if (newStream) {
  1091. self.peerconnection.addStream(newStream);
  1092. }
  1093. }
  1094. }
  1095. // Conference is not active
  1096. if (!oldSdp) {
  1097. successCallback();
  1098. return;
  1099. }
  1100. self.switchstreams = true;
  1101. self.modifySourcesQueue.push(function() {
  1102. logger.log('modify sources done');
  1103. successCallback();
  1104. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1105. logger.log("SDPs", oldSdp, newSdp);
  1106. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1107. });
  1108. };
  1109. /**
  1110. * Adds streams.
  1111. * @param stream new stream that will be added.
  1112. * @param success_callback callback executed after successful stream addition.
  1113. */
  1114. JingleSessionPC.prototype.addStream = function (stream, callback) {
  1115. var self = this;
  1116. // Remember SDP to figure out added/removed SSRCs
  1117. var oldSdp = null;
  1118. if(this.peerconnection) {
  1119. if(this.peerconnection.localDescription) {
  1120. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1121. }
  1122. if(stream)
  1123. this.peerconnection.addStream(stream);
  1124. }
  1125. // Conference is not active
  1126. if(!oldSdp || !this.peerconnection) {
  1127. callback();
  1128. return;
  1129. }
  1130. this.addingStreams = true;
  1131. this.modifySourcesQueue.push(function() {
  1132. logger.log('modify sources done');
  1133. callback();
  1134. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1135. logger.log("SDPs", oldSdp, newSdp);
  1136. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1137. });
  1138. }
  1139. /**
  1140. * Remove streams.
  1141. * @param stream stream that will be removed.
  1142. * @param success_callback callback executed after successful stream addition.
  1143. */
  1144. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  1145. var self = this;
  1146. // Remember SDP to figure out added/removed SSRCs
  1147. var oldSdp = null;
  1148. if(this.peerconnection) {
  1149. if(this.peerconnection.localDescription) {
  1150. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1151. }
  1152. if (RTCBrowserType.getBrowserType() ===
  1153. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1154. var sender = null;
  1155. // On Firefox we don't replace MediaStreams as this messes up the
  1156. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1157. // of complications. Instead, we use the RTPSender and replace just
  1158. // the track.
  1159. var track = null;
  1160. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  1161. track = stream.getAudioTracks()[0];
  1162. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  1163. {
  1164. track = stream.getVideoTracks()[0];
  1165. }
  1166. if(!track) {
  1167. console.log("Cannot switch tracks: no tracks.");
  1168. return;
  1169. }
  1170. // Find the right sender (for audio or video)
  1171. self.peerconnection.peerconnection.getSenders().some(function (s) {
  1172. if (s.track === track) {
  1173. sender = s;
  1174. return true;
  1175. }
  1176. });
  1177. if (sender) {
  1178. self.peerconnection.peerconnection.removeTrack(sender);
  1179. // .then(function() {
  1180. // console.log("Replaced a track, isAudio=" + isAudio);
  1181. // })
  1182. // .catch(function(err) {
  1183. // console.log("Failed to replace a track: " + err);
  1184. // });
  1185. } else {
  1186. console.log("Cannot switch tracks: no RTPSender.");
  1187. }
  1188. } else if(stream)
  1189. this.peerconnection.removeStream(stream);
  1190. }
  1191. // Conference is not active
  1192. if(!oldSdp || !this.peerconnection) {
  1193. callback();
  1194. return;
  1195. }
  1196. this.addingStreams = true;
  1197. this.modifySourcesQueue.push(function() {
  1198. logger.log('modify sources done');
  1199. callback();
  1200. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1201. logger.log("SDPs", oldSdp, newSdp);
  1202. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1203. });
  1204. }
  1205. /**
  1206. * Figures out added/removed ssrcs and send update IQs.
  1207. * @param old_sdp SDP object for old description.
  1208. * @param new_sdp SDP object for new description.
  1209. */
  1210. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  1211. if (!(this.peerconnection.signalingState == 'stable' &&
  1212. this.peerconnection.iceConnectionState == 'connected')){
  1213. logger.log("Too early to send updates");
  1214. return;
  1215. }
  1216. // send source-remove IQ.
  1217. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1218. var remove = $iq({to: this.peerjid, type: 'set'})
  1219. .c('jingle', {
  1220. xmlns: 'urn:xmpp:jingle:1',
  1221. action: 'source-remove',
  1222. initiator: this.initiator,
  1223. sid: this.sid
  1224. }
  1225. );
  1226. var removed = sdpDiffer.toJingle(remove);
  1227. if (removed && remove) {
  1228. logger.info("Sending source-remove", remove);
  1229. this.connection.sendIQ(remove,
  1230. function (res) {
  1231. logger.info('got remove result', res);
  1232. },
  1233. function (err) {
  1234. logger.error('got remove error', err);
  1235. }
  1236. );
  1237. } else {
  1238. logger.log('removal not necessary');
  1239. }
  1240. // send source-add IQ.
  1241. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1242. var add = $iq({to: this.peerjid, type: 'set'})
  1243. .c('jingle', {
  1244. xmlns: 'urn:xmpp:jingle:1',
  1245. action: 'source-add',
  1246. initiator: this.initiator,
  1247. sid: this.sid
  1248. }
  1249. );
  1250. var added = sdpDiffer.toJingle(add);
  1251. if (added && add) {
  1252. logger.info("Sending source-add", add);
  1253. this.connection.sendIQ(add,
  1254. function (res) {
  1255. logger.info('got add result', res);
  1256. },
  1257. function (err) {
  1258. logger.error('got add error', err);
  1259. }
  1260. );
  1261. } else {
  1262. logger.log('addition not necessary');
  1263. }
  1264. };
  1265. /**
  1266. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  1267. *
  1268. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  1269. * tracks; otherwise, <tt>false</tt>
  1270. * @param callback a function to be invoked with <tt>mute</tt> after all video
  1271. * tracks have been enabled/disabled. The function may, optionally, return
  1272. * another function which is to be invoked after the whole mute/unmute operation
  1273. * has completed successfully.
  1274. * @param options an object which specifies optional arguments such as the
  1275. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1276. * specifies whether the method was initiated in response to a user command (in
  1277. * contrast to an automatic decision made by the application logic)
  1278. */
  1279. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  1280. var byUser;
  1281. if (options) {
  1282. byUser = options.byUser;
  1283. if (typeof byUser === 'undefined') {
  1284. byUser = true;
  1285. }
  1286. } else {
  1287. byUser = true;
  1288. }
  1289. // The user's command to mute the (local) video takes precedence over any
  1290. // automatic decision made by the application logic.
  1291. if (byUser) {
  1292. this.videoMuteByUser = mute;
  1293. } else if (this.videoMuteByUser) {
  1294. return;
  1295. }
  1296. this.hardMuteVideo(mute);
  1297. var self = this;
  1298. var oldSdp = null;
  1299. if(self.peerconnection) {
  1300. if(self.peerconnection.localDescription) {
  1301. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  1302. }
  1303. }
  1304. this.modifySourcesQueue.push(function() {
  1305. logger.log('modify sources done');
  1306. callback(mute);
  1307. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1308. logger.log("SDPs", oldSdp, newSdp);
  1309. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1310. });
  1311. };
  1312. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  1313. this.pendingop = muted ? 'mute' : 'unmute';
  1314. };
  1315. JingleSessionPC.prototype.sendMute = function (muted, content) {
  1316. var info = $iq({to: this.peerjid,
  1317. type: 'set'})
  1318. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1319. action: 'session-info',
  1320. initiator: this.initiator,
  1321. sid: this.sid });
  1322. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1323. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  1324. if (content) {
  1325. info.attrs({'name': content});
  1326. }
  1327. this.connection.send(info);
  1328. };
  1329. JingleSessionPC.prototype.sendRinging = function () {
  1330. var info = $iq({to: this.peerjid,
  1331. type: 'set'})
  1332. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1333. action: 'session-info',
  1334. initiator: this.initiator,
  1335. sid: this.sid });
  1336. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1337. this.connection.send(info);
  1338. };
  1339. JingleSessionPC.prototype.getStats = function (interval) {
  1340. var self = this;
  1341. var recv = {audio: 0, video: 0};
  1342. var lost = {audio: 0, video: 0};
  1343. var lastrecv = {audio: 0, video: 0};
  1344. var lastlost = {audio: 0, video: 0};
  1345. var loss = {audio: 0, video: 0};
  1346. var delta = {audio: 0, video: 0};
  1347. this.statsinterval = window.setInterval(function () {
  1348. if (self && self.peerconnection && self.peerconnection.getStats) {
  1349. self.peerconnection.getStats(function (stats) {
  1350. var results = stats.result();
  1351. // TODO: there are so much statistics you can get from this..
  1352. for (var i = 0; i < results.length; ++i) {
  1353. if (results[i].type == 'ssrc') {
  1354. var packetsrecv = results[i].stat('packetsReceived');
  1355. var packetslost = results[i].stat('packetsLost');
  1356. if (packetsrecv && packetslost) {
  1357. packetsrecv = parseInt(packetsrecv, 10);
  1358. packetslost = parseInt(packetslost, 10);
  1359. if (results[i].stat('googFrameRateReceived')) {
  1360. lastlost.video = lost.video;
  1361. lastrecv.video = recv.video;
  1362. recv.video = packetsrecv;
  1363. lost.video = packetslost;
  1364. } else {
  1365. lastlost.audio = lost.audio;
  1366. lastrecv.audio = recv.audio;
  1367. recv.audio = packetsrecv;
  1368. lost.audio = packetslost;
  1369. }
  1370. }
  1371. }
  1372. }
  1373. delta.audio = recv.audio - lastrecv.audio;
  1374. delta.video = recv.video - lastrecv.video;
  1375. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  1376. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  1377. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  1378. });
  1379. }
  1380. }, interval || 3000);
  1381. return this.statsinterval;
  1382. };
  1383. JingleSessionPC.onJingleError = function (session, error)
  1384. {
  1385. logger.error("Jingle error", error);
  1386. }
  1387. JingleSessionPC.onJingleFatalError = function (session, error)
  1388. {
  1389. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  1390. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1391. }
  1392. JingleSessionPC.prototype.setLocalDescription = function () {
  1393. var self = this;
  1394. var newssrcs = [];
  1395. if(!this.peerconnection.localDescription)
  1396. return;
  1397. var session = transform.parse(this.peerconnection.localDescription.sdp);
  1398. var i;
  1399. session.media.forEach(function (media) {
  1400. if (media.ssrcs && media.ssrcs.length > 0) {
  1401. // TODO(gp) maybe exclude FID streams?
  1402. media.ssrcs.forEach(function (ssrc) {
  1403. if (ssrc.attribute !== 'cname') {
  1404. return;
  1405. }
  1406. newssrcs.push({
  1407. 'ssrc': ssrc.id,
  1408. 'type': media.type
  1409. });
  1410. // FIXME allows for only one SSRC per media type
  1411. self.localStreamsSSRC[media.type] = ssrc.id;
  1412. });
  1413. }
  1414. });
  1415. logger.log('new ssrcs', newssrcs);
  1416. // Bind us as local SSRCs owner
  1417. if (newssrcs.length > 0) {
  1418. for (i = 0; i < newssrcs.length; i++) {
  1419. var ssrc = newssrcs[i].ssrc;
  1420. var myJid = self.me;
  1421. self.ssrcOwners[ssrc] = myJid;
  1422. }
  1423. }
  1424. }
  1425. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1426. JingleSessionPC.prototype.sendKeyframe = function () {
  1427. var pc = this.peerconnection;
  1428. logger.log('sendkeyframe', pc.iceConnectionState);
  1429. if (pc.iceConnectionState !== 'connected') return; // safe...
  1430. var self = this;
  1431. pc.setRemoteDescription(
  1432. pc.remoteDescription,
  1433. function () {
  1434. pc.createAnswer(
  1435. function (modifiedAnswer) {
  1436. pc.setLocalDescription(
  1437. modifiedAnswer,
  1438. function () {
  1439. // noop
  1440. },
  1441. function (error) {
  1442. logger.log('triggerKeyframe setLocalDescription failed', error);
  1443. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  1444. }
  1445. );
  1446. },
  1447. function (error) {
  1448. logger.log('triggerKeyframe createAnswer failed', error);
  1449. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  1450. }
  1451. );
  1452. },
  1453. function (error) {
  1454. logger.log('triggerKeyframe setRemoteDescription failed', error);
  1455. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  1456. }
  1457. );
  1458. }
  1459. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  1460. var self = this;
  1461. var thessrc;
  1462. var streamId = RTC.getStreamID(data.stream);
  1463. // look up an associated JID for a stream id
  1464. if (!streamId) {
  1465. logger.error("No stream ID for", data.stream);
  1466. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  1467. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  1468. var ssrclines = this.peerconnection.remoteDescription?
  1469. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  1470. ssrclines = ssrclines.filter(function (line) {
  1471. // NOTE(gp) previously we filtered on the mslabel, but that property
  1472. // is not always present.
  1473. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  1474. if (RTCBrowserType.isTemasysPluginUsed()) {
  1475. return ((line.indexOf('mslabel:' + streamId) !== -1));
  1476. } else {
  1477. return ((line.indexOf('msid:' + streamId) !== -1));
  1478. }
  1479. });
  1480. if (ssrclines.length) {
  1481. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1482. if (!self.ssrcOwners[thessrc]) {
  1483. logger.error("No SSRC owner known for: " + thessrc);
  1484. return;
  1485. }
  1486. data.peerjid = self.ssrcOwners[thessrc];
  1487. logger.log('associated jid', self.ssrcOwners[thessrc]);
  1488. } else {
  1489. logger.error("No SSRC lines for ", streamId);
  1490. }
  1491. }
  1492. this.room.remoteStreamAdded(data, this.sid, thessrc);
  1493. var isVideo = data.stream.getVideoTracks().length > 0;
  1494. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1495. if (isVideo &&
  1496. data.peerjid && this.peerjid === data.peerjid &&
  1497. data.stream.getVideoTracks().length === 0 &&
  1498. RTC.localVideo.getTracks().length > 0) {
  1499. window.setTimeout(function () {
  1500. self.sendKeyframe();
  1501. }, 3000);
  1502. }
  1503. }
  1504. /**
  1505. * Returns the ice connection state for the peer connection.
  1506. * @returns the ice connection state for the peer connection.
  1507. */
  1508. JingleSessionPC.prototype.getIceConnectionState = function () {
  1509. return this.peerconnection.iceConnectionState;
  1510. }
  1511. module.exports = JingleSessionPC;