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

JingleSessionPC.js 55KB

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