Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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