Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 59KB

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