Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 56KB

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