Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 63KB

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