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

JingleSessionPC.js 55KB

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