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

JingleSessionPC.js 55KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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 SSRCReplacement = require("./LocalSSRCReplacement");
  11. // Jingle stuff
  12. function JingleSessionPC(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. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  61. var signalingState = this.peerconnection.signalingState;
  62. var iceConnectionState = this.peerconnection.iceConnectionState;
  63. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  64. this.modifySourcesQueue.resume();
  65. } else {
  66. this.modifySourcesQueue.pause();
  67. }
  68. };
  69. JingleSessionPC.prototype.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. JingleSessionPC.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. SSRCReplacement.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.prototype.active = function () {
  270. return this.state == 'active';
  271. };
  272. JingleSessionPC.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. SSRCReplacement.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.onJingleError(this.sid, error);
  403. },
  404. 10000);
  405. };
  406. JingleSessionPC.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. JingleSessionPC.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. SSRCReplacement.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  497. return this.ssrcOwners[ssrc];
  498. };
  499. JingleSessionPC.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. JingleSessionPC.onJingleFatalError(self, e);
  539. }
  540. );
  541. };
  542. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.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. SSRCReplacement.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.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. JingleSessionPC.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 = SSRCReplacement.processSourceRemove(remove);
  1049. if (removed && remove) {
  1050. console.info("Sending source-remove", remove);
  1051. this.connection.sendIQ(remove,
  1052. function (res) {
  1053. console.info('got remove result', res);
  1054. },
  1055. function (err) {
  1056. console.error('got remove error', err);
  1057. }
  1058. );
  1059. } else {
  1060. console.log('removal not necessary');
  1061. }
  1062. // send source-add IQ.
  1063. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1064. var add = $iq({to: this.peerjid, type: 'set'})
  1065. .c('jingle', {
  1066. xmlns: 'urn:xmpp:jingle:1',
  1067. action: 'source-add',
  1068. initiator: this.initiator,
  1069. sid: this.sid
  1070. }
  1071. );
  1072. var added = sdpDiffer.toJingle(add);
  1073. // Let 'source-add' IQ through the hack and see if we're allowed to send
  1074. // it in the current form
  1075. if (added)
  1076. add = SSRCReplacement.processSourceAdd(add);
  1077. if (added && add) {
  1078. console.info("Sending source-add", add);
  1079. this.connection.sendIQ(add,
  1080. function (res) {
  1081. console.info('got add result', res);
  1082. },
  1083. function (err) {
  1084. console.error('got add error', err);
  1085. }
  1086. );
  1087. } else {
  1088. console.log('addition not necessary');
  1089. }
  1090. };
  1091. /**
  1092. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  1093. *
  1094. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  1095. * tracks; otherwise, <tt>false</tt>
  1096. * @param callback a function to be invoked with <tt>mute</tt> after all video
  1097. * tracks have been enabled/disabled. The function may, optionally, return
  1098. * another function which is to be invoked after the whole mute/unmute operation
  1099. * has completed successfully.
  1100. * @param options an object which specifies optional arguments such as the
  1101. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1102. * specifies whether the method was initiated in response to a user command (in
  1103. * contrast to an automatic decision made by the application logic)
  1104. */
  1105. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  1106. var byUser;
  1107. if (options) {
  1108. byUser = options.byUser;
  1109. if (typeof byUser === 'undefined') {
  1110. byUser = true;
  1111. }
  1112. } else {
  1113. byUser = true;
  1114. }
  1115. // The user's command to mute the (local) video takes precedence over any
  1116. // automatic decision made by the application logic.
  1117. if (byUser) {
  1118. this.videoMuteByUser = mute;
  1119. } else if (this.videoMuteByUser) {
  1120. return;
  1121. }
  1122. this.hardMuteVideo(mute);
  1123. var self = this;
  1124. var oldSdp = null;
  1125. if(self.peerconnection) {
  1126. if(self.peerconnection.localDescription) {
  1127. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  1128. }
  1129. }
  1130. this.modifySourcesQueue.push(function() {
  1131. console.log('modify sources done');
  1132. callback(mute);
  1133. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  1134. console.log("SDPs", oldSdp, newSdp);
  1135. self.notifyMySSRCUpdate(oldSdp, newSdp);
  1136. });
  1137. };
  1138. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  1139. this.pendingop = muted ? 'mute' : 'unmute';
  1140. };
  1141. JingleSessionPC.prototype.sendMute = function (muted, content) {
  1142. var info = $iq({to: this.peerjid,
  1143. type: 'set'})
  1144. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1145. action: 'session-info',
  1146. initiator: this.initiator,
  1147. sid: this.sid });
  1148. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1149. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  1150. if (content) {
  1151. info.attrs({'name': content});
  1152. }
  1153. this.connection.send(info);
  1154. };
  1155. JingleSessionPC.prototype.sendRinging = function () {
  1156. var info = $iq({to: this.peerjid,
  1157. type: 'set'})
  1158. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1159. action: 'session-info',
  1160. initiator: this.initiator,
  1161. sid: this.sid });
  1162. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1163. this.connection.send(info);
  1164. };
  1165. JingleSessionPC.prototype.getStats = function (interval) {
  1166. var self = this;
  1167. var recv = {audio: 0, video: 0};
  1168. var lost = {audio: 0, video: 0};
  1169. var lastrecv = {audio: 0, video: 0};
  1170. var lastlost = {audio: 0, video: 0};
  1171. var loss = {audio: 0, video: 0};
  1172. var delta = {audio: 0, video: 0};
  1173. this.statsinterval = window.setInterval(function () {
  1174. if (self && self.peerconnection && self.peerconnection.getStats) {
  1175. self.peerconnection.getStats(function (stats) {
  1176. var results = stats.result();
  1177. // TODO: there are so much statistics you can get from this..
  1178. for (var i = 0; i < results.length; ++i) {
  1179. if (results[i].type == 'ssrc') {
  1180. var packetsrecv = results[i].stat('packetsReceived');
  1181. var packetslost = results[i].stat('packetsLost');
  1182. if (packetsrecv && packetslost) {
  1183. packetsrecv = parseInt(packetsrecv, 10);
  1184. packetslost = parseInt(packetslost, 10);
  1185. if (results[i].stat('googFrameRateReceived')) {
  1186. lastlost.video = lost.video;
  1187. lastrecv.video = recv.video;
  1188. recv.video = packetsrecv;
  1189. lost.video = packetslost;
  1190. } else {
  1191. lastlost.audio = lost.audio;
  1192. lastrecv.audio = recv.audio;
  1193. recv.audio = packetsrecv;
  1194. lost.audio = packetslost;
  1195. }
  1196. }
  1197. }
  1198. }
  1199. delta.audio = recv.audio - lastrecv.audio;
  1200. delta.video = recv.video - lastrecv.video;
  1201. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  1202. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  1203. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  1204. });
  1205. }
  1206. }, interval || 3000);
  1207. return this.statsinterval;
  1208. };
  1209. JingleSessionPC.onJingleError = function (session, error)
  1210. {
  1211. console.error("Jingle error", error);
  1212. }
  1213. JingleSessionPC.onJingleFatalError = function (session, error)
  1214. {
  1215. this.service.sessionTerminated = true;
  1216. this.connection.emuc.doLeave();
  1217. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  1218. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1219. }
  1220. JingleSessionPC.prototype.setLocalDescription = function () {
  1221. var self = this;
  1222. var newssrcs = [];
  1223. var session = transform.parse(this.peerconnection.localDescription.sdp);
  1224. session.media.forEach(function (media) {
  1225. if (media.ssrcs != null && media.ssrcs.length > 0) {
  1226. // TODO(gp) maybe exclude FID streams?
  1227. media.ssrcs.forEach(function (ssrc) {
  1228. if (ssrc.attribute !== 'cname') {
  1229. return;
  1230. }
  1231. newssrcs.push({
  1232. 'ssrc': ssrc.id,
  1233. 'type': media.type
  1234. });
  1235. });
  1236. }
  1237. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  1238. {
  1239. newssrcs.push({
  1240. 'ssrc': self.localStreamsSSRC[media.type],
  1241. 'type': media.type
  1242. });
  1243. }
  1244. });
  1245. console.log('new ssrcs', newssrcs);
  1246. // Bind us as local SSRCs owner
  1247. if (newssrcs.length > 0) {
  1248. for (var i = 1; i <= newssrcs.length; i ++) {
  1249. var ssrc = newssrcs[i-1].ssrc;
  1250. var myJid = self.connection.emuc.myroomjid;
  1251. self.ssrcOwners[ssrc] = myJid;
  1252. }
  1253. }
  1254. }
  1255. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1256. function sendKeyframe(pc) {
  1257. console.log('sendkeyframe', pc.iceConnectionState);
  1258. if (pc.iceConnectionState !== 'connected') return; // safe...
  1259. var self = this;
  1260. pc.setRemoteDescription(
  1261. pc.remoteDescription,
  1262. function () {
  1263. pc.createAnswer(
  1264. function (modifiedAnswer) {
  1265. pc.setLocalDescription(
  1266. modifiedAnswer,
  1267. function () {
  1268. // noop
  1269. },
  1270. function (error) {
  1271. console.log('triggerKeyframe setLocalDescription failed', error);
  1272. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  1273. }
  1274. );
  1275. },
  1276. function (error) {
  1277. console.log('triggerKeyframe createAnswer failed', error);
  1278. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  1279. }
  1280. );
  1281. },
  1282. function (error) {
  1283. console.log('triggerKeyframe setRemoteDescription failed', error);
  1284. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  1285. }
  1286. );
  1287. }
  1288. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  1289. var self = this;
  1290. var thessrc;
  1291. var streamId = APP.RTC.getStreamID(data.stream);
  1292. // look up an associated JID for a stream id
  1293. if (!streamId) {
  1294. console.error("No stream ID for", data.stream);
  1295. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  1296. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  1297. var ssrclines
  1298. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  1299. ssrclines = ssrclines.filter(function (line) {
  1300. // NOTE(gp) previously we filtered on the mslabel, but that property
  1301. // is not always present.
  1302. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  1303. if (RTCBrowserType.isTemasysPluginUsed()) {
  1304. return ((line.indexOf('mslabel:' + streamId) !== -1));
  1305. } else {
  1306. return ((line.indexOf('msid:' + streamId) !== -1));
  1307. }
  1308. });
  1309. if (ssrclines.length) {
  1310. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1311. if (!self.ssrcOwners[thessrc]) {
  1312. console.error("No SSRC owner known for: " + thessrc);
  1313. return;
  1314. }
  1315. data.peerjid = self.ssrcOwners[thessrc];
  1316. console.log('associated jid', self.ssrcOwners[thessrc]);
  1317. } else {
  1318. console.error("No SSRC lines for ", streamId);
  1319. }
  1320. }
  1321. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  1322. var isVideo = data.stream.getVideoTracks().length > 0;
  1323. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1324. if (isVideo &&
  1325. data.peerjid && this.peerjid === data.peerjid &&
  1326. data.stream.getVideoTracks().length === 0 &&
  1327. APP.RTC.localVideo.getTracks().length > 0) {
  1328. window.setTimeout(function () {
  1329. sendKeyframe(self.peerconnection);
  1330. }, 3000);
  1331. }
  1332. }
  1333. module.exports = JingleSessionPC;