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 56KB

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