You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  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. 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. if (APP.RTC.localAudio) {
  154. self.peerconnection.addStream(APP.RTC.localAudio.getOriginalStream());
  155. }
  156. if (APP.RTC.localVideo) {
  157. self.peerconnection.addStream(APP.RTC.localVideo.getOriginalStream());
  158. }
  159. };
  160. function onIceConnectionStateChange(sid, session) {
  161. switch (session.peerconnection.iceConnectionState) {
  162. case 'checking':
  163. session.timeChecking = (new Date()).getTime();
  164. session.firstconnect = true;
  165. break;
  166. case 'completed': // on caller side
  167. case 'connected':
  168. if (session.firstconnect) {
  169. session.firstconnect = false;
  170. var metadata = {};
  171. metadata.setupTime
  172. = (new Date()).getTime() - session.timeChecking;
  173. session.peerconnection.getStats(function (res) {
  174. if(res && res.result) {
  175. res.result().forEach(function (report) {
  176. if (report.type == 'googCandidatePair' &&
  177. report.stat('googActiveConnection') == 'true') {
  178. metadata.localCandidateType
  179. = report.stat('googLocalCandidateType');
  180. metadata.remoteCandidateType
  181. = report.stat('googRemoteCandidateType');
  182. // log pair as well so we can get nice pie
  183. // charts
  184. metadata.candidatePair
  185. = report.stat('googLocalCandidateType') +
  186. ';' +
  187. report.stat('googRemoteCandidateType');
  188. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  189. {
  190. metadata.ipv6 = true;
  191. }
  192. }
  193. });
  194. }
  195. });
  196. }
  197. break;
  198. }
  199. }
  200. JingleSessionPC.prototype.accept = function () {
  201. this.state = 'active';
  202. var pranswer = this.peerconnection.localDescription;
  203. if (!pranswer || pranswer.type != 'pranswer') {
  204. return;
  205. }
  206. console.log('going from pranswer to answer');
  207. if (this.usetrickle) {
  208. // remove candidates already sent from session-accept
  209. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  210. for (var i = 0; i < lines.length; i++) {
  211. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  212. }
  213. }
  214. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  215. // FIXME: change any inactive to sendrecv or whatever they were originally
  216. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  217. }
  218. var prsdp = new SDP(pranswer.sdp);
  219. if (config.webrtcIceTcpDisable) {
  220. prsdp.removeTcpCandidates = true;
  221. }
  222. if (config.webrtcIceUdpDisable) {
  223. prsdp.removeUdpCandidates = true;
  224. }
  225. var accept = $iq({to: this.peerjid,
  226. type: 'set'})
  227. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  228. action: 'session-accept',
  229. initiator: this.initiator,
  230. responder: this.responder,
  231. sid: this.sid });
  232. // FIXME why do we generate session-accept in 3 different places ?
  233. prsdp.toJingle(
  234. accept,
  235. this.initiator == this.me ? 'initiator' : 'responder',
  236. this.localStreamsSSRC);
  237. var sdp = this.peerconnection.localDescription.sdp;
  238. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  239. // FIXME: change any inactive to sendrecv or whatever they were originally
  240. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  241. }
  242. var self = this;
  243. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  244. function () {
  245. //console.log('setLocalDescription success');
  246. self.setLocalDescription();
  247. SSRCReplacement.processSessionInit(accept);
  248. self.connection.sendIQ(accept,
  249. function () {
  250. var ack = {};
  251. ack.source = 'answer';
  252. $(document).trigger('ack.jingle', [self.sid, ack]);
  253. },
  254. function (stanza) {
  255. var error = ($(stanza).find('error').length) ? {
  256. code: $(stanza).find('error').attr('code'),
  257. reason: $(stanza).find('error :first')[0].tagName
  258. }:{};
  259. error.source = 'answer';
  260. JingleSessionPC.onJingleError(self.sid, error);
  261. },
  262. 10000);
  263. },
  264. function (e) {
  265. console.error('setLocalDescription failed', e);
  266. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  267. }
  268. );
  269. };
  270. JingleSessionPC.prototype.terminate = function (reason) {
  271. this.state = 'ended';
  272. this.reason = reason;
  273. this.peerconnection.close();
  274. if (this.statsinterval !== null) {
  275. window.clearInterval(this.statsinterval);
  276. this.statsinterval = null;
  277. }
  278. };
  279. JingleSessionPC.prototype.active = function () {
  280. return this.state == 'active';
  281. };
  282. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  283. var self = this;
  284. if (candidate && !this.lasticecandidate) {
  285. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  286. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  287. if (!(ice && jcand)) {
  288. console.error('failed to get ice && jcand');
  289. return;
  290. }
  291. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  292. if (jcand.type === 'srflx') {
  293. this.hadstuncandidate = true;
  294. } else if (jcand.type === 'relay') {
  295. this.hadturncandidate = true;
  296. }
  297. if (this.usetrickle) {
  298. if (this.usedrip) {
  299. if (this.drip_container.length === 0) {
  300. // start 20ms callout
  301. window.setTimeout(function () {
  302. if (self.drip_container.length === 0) return;
  303. self.sendIceCandidates(self.drip_container);
  304. self.drip_container = [];
  305. }, 20);
  306. }
  307. this.drip_container.push(candidate);
  308. return;
  309. } else {
  310. self.sendIceCandidate([candidate]);
  311. }
  312. }
  313. } else {
  314. //console.log('sendIceCandidate: last candidate.');
  315. if (!this.usetrickle) {
  316. //console.log('should send full offer now...');
  317. //FIXME why do we generate session-accept in 3 different places ?
  318. var init = $iq({to: this.peerjid,
  319. type: 'set'})
  320. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  321. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  322. initiator: this.initiator,
  323. sid: this.sid});
  324. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  325. if (config.webrtcIceTcpDisable) {
  326. this.localSDP.removeTcpCandidates = true;
  327. }
  328. if (config.webrtcIceUdpDisable) {
  329. this.localSDP.removeUdpCandidates = true;
  330. }
  331. var sendJingle = function (ssrc) {
  332. if(!ssrc)
  333. ssrc = {};
  334. self.localSDP.toJingle(
  335. init,
  336. self.initiator == self.me ? 'initiator' : 'responder',
  337. ssrc);
  338. SSRCReplacement.processSessionInit(init);
  339. self.connection.sendIQ(init,
  340. function () {
  341. //console.log('session initiate ack');
  342. var ack = {};
  343. ack.source = 'offer';
  344. $(document).trigger('ack.jingle', [self.sid, ack]);
  345. },
  346. function (stanza) {
  347. self.state = 'error';
  348. self.peerconnection.close();
  349. var error = ($(stanza).find('error').length) ? {
  350. code: $(stanza).find('error').attr('code'),
  351. reason: $(stanza).find('error :first')[0].tagName,
  352. }:{};
  353. error.source = 'offer';
  354. JingleSessionPC.onJingleError(self.sid, error);
  355. },
  356. 10000);
  357. };
  358. sendJingle();
  359. }
  360. this.lasticecandidate = true;
  361. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  362. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  363. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  364. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  365. }
  366. }
  367. };
  368. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  369. console.log('sendIceCandidates', candidates);
  370. var cand = $iq({to: this.peerjid, type: 'set'})
  371. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  372. action: 'transport-info',
  373. initiator: this.initiator,
  374. sid: this.sid});
  375. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  376. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  377. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  378. if (cands.length > 0) {
  379. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  380. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  381. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  382. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  383. }).c('transport', ice);
  384. for (var i = 0; i < cands.length; i++) {
  385. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  386. }
  387. // add fingerprint
  388. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  389. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  390. tmp.required = true;
  391. cand.c(
  392. 'fingerprint',
  393. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  394. .t(tmp.fingerprint);
  395. delete tmp.fingerprint;
  396. cand.attrs(tmp);
  397. cand.up();
  398. }
  399. cand.up(); // transport
  400. cand.up(); // content
  401. }
  402. }
  403. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  404. //console.log('was this the last candidate', this.lasticecandidate);
  405. this.connection.sendIQ(cand,
  406. function () {
  407. var ack = {};
  408. ack.source = 'transportinfo';
  409. $(document).trigger('ack.jingle', [this.sid, ack]);
  410. },
  411. function (stanza) {
  412. var error = ($(stanza).find('error').length) ? {
  413. code: $(stanza).find('error').attr('code'),
  414. reason: $(stanza).find('error :first')[0].tagName,
  415. }:{};
  416. error.source = 'transportinfo';
  417. JingleSessionPC.onJingleError(this.sid, error);
  418. },
  419. 10000);
  420. };
  421. JingleSessionPC.prototype.sendOffer = function () {
  422. //console.log('sendOffer...');
  423. var self = this;
  424. this.peerconnection.createOffer(function (sdp) {
  425. self.createdOffer(sdp);
  426. },
  427. function (e) {
  428. console.error('createOffer failed', e);
  429. },
  430. this.media_constraints
  431. );
  432. };
  433. // FIXME createdOffer is never used in jitsi-meet
  434. JingleSessionPC.prototype.createdOffer = function (sdp) {
  435. //console.log('createdOffer', sdp);
  436. var self = this;
  437. this.localSDP = new SDP(sdp.sdp);
  438. //this.localSDP.mangle();
  439. var sendJingle = function () {
  440. var init = $iq({to: this.peerjid,
  441. type: 'set'})
  442. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  443. action: 'session-initiate',
  444. initiator: this.initiator,
  445. sid: this.sid});
  446. self.localSDP.toJingle(
  447. init,
  448. this.initiator == this.me ? 'initiator' : 'responder',
  449. this.localStreamsSSRC);
  450. SSRCReplacement.processSessionInit(init);
  451. self.connection.sendIQ(init,
  452. function () {
  453. var ack = {};
  454. ack.source = 'offer';
  455. $(document).trigger('ack.jingle', [self.sid, ack]);
  456. },
  457. function (stanza) {
  458. self.state = 'error';
  459. self.peerconnection.close();
  460. var error = ($(stanza).find('error').length) ? {
  461. code: $(stanza).find('error').attr('code'),
  462. reason: $(stanza).find('error :first')[0].tagName,
  463. }:{};
  464. error.source = 'offer';
  465. JingleSessionPC.onJingleError(self.sid, error);
  466. },
  467. 10000);
  468. };
  469. sdp.sdp = this.localSDP.raw;
  470. this.peerconnection.setLocalDescription(sdp,
  471. function () {
  472. if(self.usetrickle)
  473. {
  474. sendJingle();
  475. }
  476. self.setLocalDescription();
  477. //console.log('setLocalDescription success');
  478. },
  479. function (e) {
  480. console.error('setLocalDescription failed', e);
  481. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  482. }
  483. );
  484. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  485. for (var i = 0; i < cands.length; i++) {
  486. var cand = SDPUtil.parse_icecandidate(cands[i]);
  487. if (cand.type == 'srflx') {
  488. this.hadstuncandidate = true;
  489. } else if (cand.type == 'relay') {
  490. this.hadturncandidate = true;
  491. }
  492. }
  493. };
  494. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  495. var self = this;
  496. $(contents).each(function (idx, content) {
  497. var name = $(content).attr('name');
  498. var mediaType = this.getAttribute('name');
  499. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  500. ssrcs.each(function () {
  501. var ssrc = this.getAttribute('ssrc');
  502. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  503. function () {
  504. var owner = this.getAttribute('owner');
  505. self.ssrcOwners[ssrc] = owner;
  506. }
  507. );
  508. });
  509. });
  510. };
  511. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  512. return this.ssrcOwners[ssrc];
  513. };
  514. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  515. this.remoteSDP = new SDP('');
  516. if (config.webrtcIceTcpDisable) {
  517. this.remoteSDP.removeTcpCandidates = true;
  518. }
  519. if (config.webrtcIceUdpDisable) {
  520. this.remoteSDP.removeUdpCandidates = true;
  521. }
  522. this.remoteSDP.fromJingle(elem);
  523. this.readSsrcInfo($(elem).find(">content"));
  524. if (this.peerconnection.remoteDescription !== null) {
  525. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  526. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  527. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  528. for (var i = 0; i < pranswer.media.length; i++) {
  529. // make sure we have ice ufrag and pwd
  530. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  531. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  532. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  533. } else {
  534. console.warn('no ice ufrag?');
  535. }
  536. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  537. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  538. } else {
  539. console.warn('no ice pwd?');
  540. }
  541. }
  542. // copy over candidates
  543. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  544. for (var j = 0; j < lines.length; j++) {
  545. this.remoteSDP.media[i] += lines[j] + '\r\n';
  546. }
  547. }
  548. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  549. }
  550. }
  551. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  552. this.peerconnection.setRemoteDescription(remotedesc,
  553. function () {
  554. //console.log('setRemoteDescription success');
  555. },
  556. function (e) {
  557. console.error('setRemoteDescription error', e);
  558. JingleSessionPC.onJingleFatalError(self, e);
  559. }
  560. );
  561. };
  562. /**
  563. * Adds remote ICE candidates to this Jingle session.
  564. * @param elem An array of Jingle "content" elements?
  565. */
  566. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  567. var self = this;
  568. if (this.peerconnection.signalingState == 'closed') {
  569. return;
  570. }
  571. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  572. console.log('trickle ice candidate arriving before session accept...');
  573. // create a PRANSWER for setRemoteDescription
  574. if (!this.remoteSDP) {
  575. var cobbled = 'v=0\r\n' +
  576. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  577. 's=-\r\n' +
  578. 't=0 0\r\n';
  579. // first, take some things from the local description
  580. for (var i = 0; i < this.localSDP.media.length; i++) {
  581. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  582. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  583. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  584. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  585. }
  586. cobbled += 'a=inactive\r\n';
  587. }
  588. this.remoteSDP = new SDP(cobbled);
  589. }
  590. // then add things like ice and dtls from remote candidate
  591. elem.each(function () {
  592. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  593. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  594. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  595. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  596. var tmp = $(this).find('transport');
  597. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  598. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  599. tmp = $(this).find('transport>fingerprint');
  600. if (tmp.length) {
  601. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  602. } else {
  603. console.log('no dtls fingerprint (webrtc issue #1718?)');
  604. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  605. }
  606. break;
  607. }
  608. }
  609. }
  610. });
  611. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  612. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  613. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  614. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  615. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  616. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  617. }).length == this.remoteSDP.media.length;
  618. if (iscomplete) {
  619. console.log('setting pranswer');
  620. try {
  621. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  622. function() {
  623. },
  624. function(e) {
  625. console.log('setRemoteDescription pranswer failed', e.toString());
  626. });
  627. } catch (e) {
  628. console.error('setting pranswer failed', e);
  629. }
  630. } else {
  631. //console.log('not yet setting pranswer');
  632. }
  633. }
  634. // operate on each content element
  635. elem.each(function () {
  636. // would love to deactivate this, but firefox still requires it
  637. var idx = -1;
  638. var i;
  639. for (i = 0; i < self.remoteSDP.media.length; i++) {
  640. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  641. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  642. idx = i;
  643. break;
  644. }
  645. }
  646. if (idx == -1) { // fall back to localdescription
  647. for (i = 0; i < self.localSDP.media.length; i++) {
  648. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  649. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  650. idx = i;
  651. break;
  652. }
  653. }
  654. }
  655. var name = $(this).attr('name');
  656. // TODO: check ice-pwd and ice-ufrag?
  657. $(this).find('transport>candidate').each(function () {
  658. var line, candidate;
  659. var protocol = this.getAttribute('protocol');
  660. protocol =
  661. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  662. if ((config.webrtcIceTcpDisable && protocol == 'tcp') ||
  663. (config.webrtcIceUdpDisable && protocol == 'udp')) {
  664. return;
  665. }
  666. line = SDPUtil.candidateFromJingle(this);
  667. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  668. sdpMid: name,
  669. candidate: line});
  670. try {
  671. self.peerconnection.addIceCandidate(candidate);
  672. } catch (e) {
  673. console.error('addIceCandidate failed', e.toString(), line);
  674. self.eventEmitter.emit(RTCEvents.ADD_ICE_CANDIDATE_FAILED, err, self.peerconnection);
  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. * @param isAudio whether the streams are audio (if true) or video (if false).
  1039. */
  1040. JingleSessionPC.prototype.switchStreams =
  1041. function (newStream, oldStream, successCallback, isAudio) {
  1042. var self = this;
  1043. var sender, newTrack;
  1044. var senderKind = isAudio ? 'audio' : 'video';
  1045. // Remember SDP to figure out added/removed SSRCs
  1046. var oldSdp = null;
  1047. if (self.peerconnection) {
  1048. if (self.peerconnection.localDescription) {
  1049. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  1050. }
  1051. if (RTCBrowserType.getBrowserType() ===
  1052. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  1053. // On Firefox we don't replace MediaStreams as this messes up the
  1054. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1055. // of complications. Instead, we use the RTPSender and replace just
  1056. // the track.
  1057. // Find the right sender (for audio or video)
  1058. self.peerconnection.peerconnection.getSenders().some(function (s) {
  1059. if (s.track && s.track.kind === senderKind) {
  1060. sender = s;
  1061. return true;
  1062. }
  1063. });
  1064. if (sender) {
  1065. // We assume that our streams have a single track, either audio
  1066. // or video.
  1067. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  1068. newStream.getVideoTracks()[0];
  1069. sender.replaceTrack(newTrack)
  1070. .then(function() {
  1071. console.log("Replaced a track, isAudio=" + isAudio);
  1072. })
  1073. .catch(function(err) {
  1074. console.log("Failed to replace a track: " + err);
  1075. });
  1076. } else {
  1077. console.log("Cannot switch tracks: no RTPSender.");
  1078. }
  1079. } else {
  1080. self.peerconnection.removeStream(oldStream, true);
  1081. if (newStream) {
  1082. self.peerconnection.addStream(newStream);
  1083. }
  1084. }
  1085. }
  1086. // Conference is not active
  1087. if (!oldSdp) {
  1088. successCallback();
  1089. return;
  1090. }
  1091. self.switchstreams = true;
  1092. self.modifySourcesQueue.push(function() {
  1093. console.log('modify sources done');
  1094. successCallback();
  1095. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1096. console.log("SDPs", oldSdp, newSdp);
  1097. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1098. });
  1099. };
  1100. /**
  1101. * Figures out added/removed ssrcs and send update IQs.
  1102. * @param old_sdp SDP object for old description.
  1103. * @param new_sdp SDP object for new description.
  1104. */
  1105. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  1106. if (!(this.peerconnection.signalingState == 'stable' &&
  1107. this.peerconnection.iceConnectionState == 'connected')){
  1108. console.log("Too early to send updates");
  1109. return;
  1110. }
  1111. // send source-remove IQ.
  1112. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1113. var remove = $iq({to: this.peerjid, type: 'set'})
  1114. .c('jingle', {
  1115. xmlns: 'urn:xmpp:jingle:1',
  1116. action: 'source-remove',
  1117. initiator: this.initiator,
  1118. sid: this.sid
  1119. }
  1120. );
  1121. var removed = sdpDiffer.toJingle(remove);
  1122. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  1123. // it in the current form
  1124. if (removed)
  1125. remove = SSRCReplacement.processSourceRemove(remove);
  1126. if (removed && remove) {
  1127. console.info("Sending source-remove", remove);
  1128. this.connection.sendIQ(remove,
  1129. function (res) {
  1130. console.info('got remove result', res);
  1131. },
  1132. function (err) {
  1133. console.error('got remove error', err);
  1134. }
  1135. );
  1136. } else {
  1137. console.log('removal not necessary');
  1138. }
  1139. // send source-add IQ.
  1140. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1141. var add = $iq({to: this.peerjid, type: 'set'})
  1142. .c('jingle', {
  1143. xmlns: 'urn:xmpp:jingle:1',
  1144. action: 'source-add',
  1145. initiator: this.initiator,
  1146. sid: this.sid
  1147. }
  1148. );
  1149. var added = sdpDiffer.toJingle(add);
  1150. // Let 'source-add' IQ through the hack and see if we're allowed to send
  1151. // it in the current form
  1152. if (added)
  1153. add = SSRCReplacement.processSourceAdd(add);
  1154. if (added && add) {
  1155. console.info("Sending source-add", add);
  1156. this.connection.sendIQ(add,
  1157. function (res) {
  1158. console.info('got add result', res);
  1159. },
  1160. function (err) {
  1161. console.error('got add error', err);
  1162. }
  1163. );
  1164. } else {
  1165. console.log('addition not necessary');
  1166. }
  1167. };
  1168. /**
  1169. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  1170. *
  1171. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  1172. * tracks; otherwise, <tt>false</tt>
  1173. * @param callback a function to be invoked with <tt>mute</tt> after all video
  1174. * tracks have been enabled/disabled. The function may, optionally, return
  1175. * another function which is to be invoked after the whole mute/unmute operation
  1176. * has completed successfully.
  1177. * @param options an object which specifies optional arguments such as the
  1178. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1179. * specifies whether the method was initiated in response to a user command (in
  1180. * contrast to an automatic decision made by the application logic)
  1181. */
  1182. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  1183. var byUser;
  1184. if (options) {
  1185. byUser = options.byUser;
  1186. if (typeof byUser === 'undefined') {
  1187. byUser = true;
  1188. }
  1189. } else {
  1190. byUser = true;
  1191. }
  1192. // The user's command to mute the (local) video takes precedence over any
  1193. // automatic decision made by the application logic.
  1194. if (byUser) {
  1195. this.videoMuteByUser = mute;
  1196. } else if (this.videoMuteByUser) {
  1197. return;
  1198. }
  1199. this.hardMuteVideo(mute);
  1200. var self = this;
  1201. var oldSdp = null;
  1202. if(self.peerconnection) {
  1203. if(self.peerconnection.localDescription) {
  1204. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  1205. }
  1206. }
  1207. this.modifySourcesQueue.push(function() {
  1208. console.log('modify sources done');
  1209. callback(mute);
  1210. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1211. console.log("SDPs", oldSdp, newSdp);
  1212. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1213. });
  1214. };
  1215. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  1216. this.pendingop = muted ? 'mute' : 'unmute';
  1217. };
  1218. JingleSessionPC.prototype.sendMute = function (muted, content) {
  1219. var info = $iq({to: this.peerjid,
  1220. type: 'set'})
  1221. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1222. action: 'session-info',
  1223. initiator: this.initiator,
  1224. sid: this.sid });
  1225. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1226. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  1227. if (content) {
  1228. info.attrs({'name': content});
  1229. }
  1230. this.connection.send(info);
  1231. };
  1232. JingleSessionPC.prototype.sendRinging = function () {
  1233. var info = $iq({to: this.peerjid,
  1234. type: 'set'})
  1235. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1236. action: 'session-info',
  1237. initiator: this.initiator,
  1238. sid: this.sid });
  1239. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1240. this.connection.send(info);
  1241. };
  1242. JingleSessionPC.prototype.getStats = function (interval) {
  1243. var self = this;
  1244. var recv = {audio: 0, video: 0};
  1245. var lost = {audio: 0, video: 0};
  1246. var lastrecv = {audio: 0, video: 0};
  1247. var lastlost = {audio: 0, video: 0};
  1248. var loss = {audio: 0, video: 0};
  1249. var delta = {audio: 0, video: 0};
  1250. this.statsinterval = window.setInterval(function () {
  1251. if (self && self.peerconnection && self.peerconnection.getStats) {
  1252. self.peerconnection.getStats(function (stats) {
  1253. var results = stats.result();
  1254. // TODO: there are so much statistics you can get from this..
  1255. for (var i = 0; i < results.length; ++i) {
  1256. if (results[i].type == 'ssrc') {
  1257. var packetsrecv = results[i].stat('packetsReceived');
  1258. var packetslost = results[i].stat('packetsLost');
  1259. if (packetsrecv && packetslost) {
  1260. packetsrecv = parseInt(packetsrecv, 10);
  1261. packetslost = parseInt(packetslost, 10);
  1262. if (results[i].stat('googFrameRateReceived')) {
  1263. lastlost.video = lost.video;
  1264. lastrecv.video = recv.video;
  1265. recv.video = packetsrecv;
  1266. lost.video = packetslost;
  1267. } else {
  1268. lastlost.audio = lost.audio;
  1269. lastrecv.audio = recv.audio;
  1270. recv.audio = packetsrecv;
  1271. lost.audio = packetslost;
  1272. }
  1273. }
  1274. }
  1275. }
  1276. delta.audio = recv.audio - lastrecv.audio;
  1277. delta.video = recv.video - lastrecv.video;
  1278. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  1279. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  1280. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  1281. });
  1282. }
  1283. }, interval || 3000);
  1284. return this.statsinterval;
  1285. };
  1286. JingleSessionPC.onJingleError = function (session, error)
  1287. {
  1288. console.error("Jingle error", error);
  1289. };
  1290. JingleSessionPC.onJingleFatalError = function (session, error)
  1291. {
  1292. this.service.sessionTerminated = true;
  1293. this.connection.emuc.doLeave();
  1294. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  1295. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1296. };
  1297. JingleSessionPC.prototype.setLocalDescription = function () {
  1298. var self = this;
  1299. var newssrcs = [];
  1300. var session = transform.parse(this.peerconnection.localDescription.sdp);
  1301. var i;
  1302. session.media.forEach(function (media) {
  1303. if (media.ssrcs && media.ssrcs.length > 0) {
  1304. // TODO(gp) maybe exclude FID streams?
  1305. media.ssrcs.forEach(function (ssrc) {
  1306. if (ssrc.attribute !== 'cname') {
  1307. return;
  1308. }
  1309. newssrcs.push({
  1310. 'ssrc': ssrc.id,
  1311. 'type': media.type
  1312. });
  1313. });
  1314. }
  1315. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  1316. {
  1317. newssrcs.push({
  1318. 'ssrc': self.localStreamsSSRC[media.type],
  1319. 'type': media.type
  1320. });
  1321. }
  1322. });
  1323. console.log('new ssrcs', newssrcs);
  1324. // Bind us as local SSRCs owner
  1325. if (newssrcs.length > 0) {
  1326. if (config.advertiseSSRCsInPresence) {
  1327. // This is only for backward compatibility with clients which
  1328. // don't support getting sources from Jingle (i.e. jirecon).
  1329. this.connection.emuc.clearPresenceMedia();
  1330. }
  1331. for (i = 0; i < newssrcs.length; i++) {
  1332. var ssrc = newssrcs[i].ssrc;
  1333. var myJid = self.connection.emuc.myroomjid;
  1334. self.ssrcOwners[ssrc] = myJid;
  1335. if (config.advertiseSSRCsInPresence) {
  1336. // This is only for backward compatibility with clients which
  1337. // don't support getting sources from Jingle (i.e. jirecon).
  1338. this.connection.emuc.addMediaToPresence(
  1339. i+1, newssrcs[i].type, ssrc, newssrcs[i].direction);
  1340. }
  1341. }
  1342. if (config.advertiseSSRCsInPresence) {
  1343. this.connection.emuc.sendPresence();
  1344. }
  1345. }
  1346. };
  1347. /**
  1348. * Handles 'onaddstream' events from the RTCPeerConnection.
  1349. * @param event the 'onaddstream' event.
  1350. */
  1351. JingleSessionPC.prototype.remoteStreamAdded = function (event) {
  1352. var self = this;
  1353. var ssrc;
  1354. var ssrclines;
  1355. var streamId = APP.RTC.getStreamID(event.stream);
  1356. // look up an associated JID for a stream id
  1357. if (!streamId) {
  1358. console.error("No stream ID for", event.stream);
  1359. } else if (streamId.indexOf('mixedmslabel') === -1) {
  1360. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  1361. ssrclines = SDPUtil.find_lines(
  1362. this.peerconnection.remoteDescription.sdp,
  1363. 'a=ssrc:');
  1364. ssrclines = ssrclines.filter(function (line) {
  1365. // NOTE(gp) previously we filtered on the mslabel, but that property
  1366. // is not always present.
  1367. // return line.indexOf('mslabel:' + event.stream.label) !== -1;
  1368. if (RTCBrowserType.isTemasysPluginUsed()) {
  1369. return ((line.indexOf('mslabel:' + streamId) !== -1));
  1370. } else {
  1371. return ((line.indexOf('msid:' + streamId) !== -1));
  1372. }
  1373. });
  1374. if (ssrclines.length) {
  1375. ssrc = ssrclines[0].substring(7).split(' ')[0];
  1376. if (!self.ssrcOwners[ssrc]) {
  1377. console.error("No SSRC owner known for: " + ssrc);
  1378. return;
  1379. }
  1380. event.peerjid = self.ssrcOwners[ssrc];
  1381. console.log('Adding remote stream, SSRC ' + ssrc +
  1382. ', associated jid ' + event.peerjid);
  1383. } else {
  1384. console.error("No SSRC lines for ", streamId);
  1385. }
  1386. }
  1387. APP.RTC.createRemoteStream(event, ssrc);
  1388. };
  1389. module.exports = JingleSessionPC;