您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 57KB

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