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

JingleSessionPC.js 59KB

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