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

JingleSession.js 55KB

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