Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JingleSessionPC.js 55KB

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