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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. /* Initial "authentication required" dialog */
  6. var authDialog = null;
  7. /* Loop retry ID that wits for other user to create the room */
  8. var authRetryId = null;
  9. var activecall = null;
  10. var nickname = null;
  11. var focusMucJid = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var bridgeIsDown = false;
  15. //TODO: this array must be removed when firefox implement multistream support
  16. var notReceivedSSRCs = [];
  17. var jid2Ssrc = {};
  18. /**
  19. * Indicates whether ssrc is camera video or desktop stream.
  20. * FIXME: remove those maps
  21. */
  22. var ssrc2videoType = {};
  23. /**
  24. * Currently focused video "src"(displayed in large video).
  25. * @type {String}
  26. */
  27. var focusedVideoInfo = null;
  28. var mutedAudios = {};
  29. /**
  30. * Remembers if we were muted by the focus.
  31. * @type {boolean}
  32. */
  33. var forceMuted = false;
  34. /**
  35. * Indicates if we have muted our audio before the conference has started.
  36. * @type {boolean}
  37. */
  38. var preMuted = false;
  39. var localVideoSrc = null;
  40. var flipXLocalVideo = true;
  41. var isFullScreen = false;
  42. var currentVideoWidth = null;
  43. var currentVideoHeight = null;
  44. var sessionTerminated = false;
  45. function init() {
  46. RTC.addStreamListener(maybeDoJoin, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  47. RTC.start();
  48. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  49. connect(jid);
  50. }
  51. function connect(jid, password) {
  52. var localAudio, localVideo;
  53. if (connection && connection.jingle) {
  54. localAudio = connection.jingle.localAudio;
  55. localVideo = connection.jingle.localVideo;
  56. }
  57. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  58. var settings = UI.getSettings();
  59. var email = settings.email;
  60. var displayName = settings.displayName;
  61. if(email) {
  62. connection.emuc.addEmailToPresence(email);
  63. } else {
  64. connection.emuc.addUserIdToPresence(settings.uid);
  65. }
  66. if(displayName) {
  67. connection.emuc.addDisplayNameToPresence(displayName);
  68. }
  69. if (connection.disco) {
  70. // for chrome, add multistream cap
  71. }
  72. connection.jingle.pc_constraints = RTC.getPCConstraints();
  73. if (config.useIPv6) {
  74. // https://code.google.com/p/webrtc/issues/detail?id=2828
  75. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  76. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  77. }
  78. if (localAudio) connection.jingle.localAudio = localAudio;
  79. if (localVideo) connection.jingle.localVideo = localVideo;
  80. if(!password)
  81. password = document.getElementById('password').value;
  82. var anonymousConnectionFailed = false;
  83. connection.connect(jid, password, function (status, msg) {
  84. console.log('Strophe status changed to', Strophe.getStatusString(status));
  85. if (status === Strophe.Status.CONNECTED) {
  86. if (config.useStunTurn) {
  87. connection.jingle.getStunAndTurnCredentials();
  88. }
  89. document.getElementById('connect').disabled = true;
  90. console.info("My Jabber ID: " + connection.jid);
  91. if(password)
  92. authenticatedUser = true;
  93. maybeDoJoin();
  94. } else if (status === Strophe.Status.CONNFAIL) {
  95. if(msg === 'x-strophe-bad-non-anon-jid') {
  96. anonymousConnectionFailed = true;
  97. }
  98. } else if (status === Strophe.Status.DISCONNECTED) {
  99. if(anonymousConnectionFailed) {
  100. // prompt user for username and password
  101. $(document).trigger('passwordrequired.main');
  102. }
  103. } else if (status === Strophe.Status.AUTHFAIL) {
  104. // wrong password or username, prompt user
  105. $(document).trigger('passwordrequired.main');
  106. }
  107. });
  108. }
  109. function maybeDoJoin() {
  110. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  111. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  112. doJoin();
  113. }
  114. }
  115. function doJoin() {
  116. if (!roomName) {
  117. UI.generateRoomName();
  118. }
  119. Moderator.allocateConferenceFocus(
  120. roomName, doJoinAfterFocus);
  121. }
  122. function doJoinAfterFocus() {
  123. // Close authentication dialog if opened
  124. if (authDialog) {
  125. UI.messageHandler.closeDialog();
  126. authDialog = null;
  127. }
  128. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  129. if (authRetryId) {
  130. window.clearTimeout(authRetryId);
  131. authRetryId = null;
  132. }
  133. var roomjid;
  134. roomjid = roomName;
  135. if (config.useNicks) {
  136. var nick = window.prompt('Your nickname (optional)');
  137. if (nick) {
  138. roomjid += '/' + nick;
  139. } else {
  140. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  141. }
  142. } else {
  143. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  144. if(!authenticatedUser)
  145. tmpJid = tmpJid.substr(0, 8);
  146. roomjid += '/' + tmpJid;
  147. }
  148. connection.emuc.doJoin(roomjid);
  149. }
  150. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  151. // XXX(gp) so, every call to this function is *always* preceded by a call
  152. // to the RTC.attachMediaStream() function but that call is *not* followed
  153. // by an update to the videoSrcToSsrc map!
  154. //
  155. // The above way of doing things results in video SRCs that don't correspond
  156. // to any SSRC for a short period of time (to be more precise, for as long
  157. // the waitForRemoteVideo takes to complete). This causes problems (see
  158. // bellow).
  159. //
  160. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  161. // a second time in here and only then update the videoSrcToSsrc map? Why
  162. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  163. // is called the first time? I actually do that in the lastN changed event
  164. // handler because the "orphan" video SRC is causing troubles there. The
  165. // purpose of this method would then be to fire the "videoactive.jingle".
  166. //
  167. // Food for though I guess :-)
  168. if (selector.removed || !selector.parent().is(":visible")) {
  169. console.warn("Media removed before had started", selector);
  170. return;
  171. }
  172. if (stream.id === 'mixedmslabel') return;
  173. if (selector[0].currentTime > 0) {
  174. var videoStream = simulcast.getReceivingVideoStream(stream);
  175. RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  176. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  177. // in order to get rid of too many maps
  178. if (ssrc && jid) {
  179. jid2Ssrc[Strophe.getResourceFromJid(jid)] = ssrc;
  180. } else {
  181. console.warn("No ssrc given for jid", jid);
  182. }
  183. $(document).trigger('videoactive.jingle', [selector]);
  184. } else {
  185. setTimeout(function () {
  186. waitForRemoteVideo(selector, ssrc, stream, jid);
  187. }, 250);
  188. }
  189. }
  190. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  191. waitForPresence(data, sid);
  192. });
  193. function waitForPresence(data, sid) {
  194. var sess = connection.jingle.sessions[sid];
  195. var thessrc;
  196. // look up an associated JID for a stream id
  197. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  198. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  199. var ssrclines
  200. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  201. ssrclines = ssrclines.filter(function (line) {
  202. // NOTE(gp) previously we filtered on the mslabel, but that property
  203. // is not always present.
  204. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  205. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  206. });
  207. if (ssrclines.length) {
  208. thessrc = ssrclines[0].substring(7).split(' ')[0];
  209. // We signal our streams (through Jingle to the focus) before we set
  210. // our presence (through which peers associate remote streams to
  211. // jids). So, it might arrive that a remote stream is added but
  212. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  213. // successfully set. Here we wait for up to a second for the
  214. // presence to arrive.
  215. if (!ssrc2jid[thessrc]) {
  216. // TODO(gp) limit wait duration to 1 sec.
  217. setTimeout(function(d, s) {
  218. return function() {
  219. waitForPresence(d, s);
  220. }
  221. }(data, sid), 250);
  222. return;
  223. }
  224. // ok to overwrite the one from focus? might save work in colibri.js
  225. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  226. if (ssrc2jid[thessrc]) {
  227. data.peerjid = ssrc2jid[thessrc];
  228. }
  229. }
  230. }
  231. //TODO: this code should be removed when firefox implement multistream support
  232. if(RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  233. {
  234. if((notReceivedSSRCs.length == 0) ||
  235. !ssrc2jid[notReceivedSSRCs[notReceivedSSRCs.length - 1]])
  236. {
  237. // TODO(gp) limit wait duration to 1 sec.
  238. setTimeout(function(d, s) {
  239. return function() {
  240. waitForPresence(d, s);
  241. }
  242. }(data, sid), 250);
  243. return;
  244. }
  245. thessrc = notReceivedSSRCs.pop();
  246. if (ssrc2jid[thessrc]) {
  247. data.peerjid = ssrc2jid[thessrc];
  248. }
  249. }
  250. RTC.createRemoteStream(data, sid, thessrc);
  251. var isVideo = data.stream.getVideoTracks().length > 0;
  252. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  253. if (isVideo &&
  254. data.peerjid && sess.peerjid === data.peerjid &&
  255. data.stream.getVideoTracks().length === 0 &&
  256. connection.jingle.localVideo.getVideoTracks().length > 0) {
  257. //
  258. window.setTimeout(function () {
  259. sendKeyframe(sess.peerconnection);
  260. }, 3000);
  261. }
  262. }
  263. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  264. function sendKeyframe(pc) {
  265. console.log('sendkeyframe', pc.iceConnectionState);
  266. if (pc.iceConnectionState !== 'connected') return; // safe...
  267. pc.setRemoteDescription(
  268. pc.remoteDescription,
  269. function () {
  270. pc.createAnswer(
  271. function (modifiedAnswer) {
  272. pc.setLocalDescription(
  273. modifiedAnswer,
  274. function () {
  275. // noop
  276. },
  277. function (error) {
  278. console.log('triggerKeyframe setLocalDescription failed', error);
  279. UI.messageHandler.showError();
  280. }
  281. );
  282. },
  283. function (error) {
  284. console.log('triggerKeyframe createAnswer failed', error);
  285. UI.messageHandler.showError();
  286. }
  287. );
  288. },
  289. function (error) {
  290. console.log('triggerKeyframe setRemoteDescription failed', error);
  291. UI.messageHandler.showError();
  292. }
  293. );
  294. }
  295. // Really mute video, i.e. dont even send black frames
  296. function muteVideo(pc, unmute) {
  297. // FIXME: this probably needs another of those lovely state safeguards...
  298. // which checks for iceconn == connected and sigstate == stable
  299. pc.setRemoteDescription(pc.remoteDescription,
  300. function () {
  301. pc.createAnswer(
  302. function (answer) {
  303. var sdp = new SDP(answer.sdp);
  304. if (sdp.media.length > 1) {
  305. if (unmute)
  306. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  307. else
  308. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  309. sdp.raw = sdp.session + sdp.media.join('');
  310. answer.sdp = sdp.raw;
  311. }
  312. pc.setLocalDescription(answer,
  313. function () {
  314. console.log('mute SLD ok');
  315. },
  316. function (error) {
  317. console.log('mute SLD error');
  318. UI.messageHandler.showError('Error',
  319. 'Oops! Something went wrong and we failed to ' +
  320. 'mute! (SLD Failure)');
  321. }
  322. );
  323. },
  324. function (error) {
  325. console.log(error);
  326. UI.messageHandler.showError();
  327. }
  328. );
  329. },
  330. function (error) {
  331. console.log('muteVideo SRD error');
  332. UI.messageHandler.showError('Error',
  333. 'Oops! Something went wrong and we failed to stop video!' +
  334. '(SRD Failure)');
  335. }
  336. );
  337. }
  338. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  339. // put our ssrcs into presence so other clients can identify our stream
  340. var sess = connection.jingle.sessions[sid];
  341. var newssrcs = [];
  342. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  343. media.forEach(function (media) {
  344. if(Object.keys(media.sources).length > 0) {
  345. // TODO(gp) maybe exclude FID streams?
  346. Object.keys(media.sources).forEach(function (ssrc) {
  347. newssrcs.push({
  348. 'ssrc': ssrc,
  349. 'type': media.type,
  350. 'direction': media.direction
  351. });
  352. });
  353. }
  354. else if(sess.localStreamsSSRC && sess.localStreamsSSRC[media.type])
  355. {
  356. newssrcs.push({
  357. 'ssrc': sess.localStreamsSSRC[media.type],
  358. 'type': media.type,
  359. 'direction': media.direction
  360. });
  361. }
  362. });
  363. console.log('new ssrcs', newssrcs);
  364. // Have to clear presence map to get rid of removed streams
  365. connection.emuc.clearPresenceMedia();
  366. if (newssrcs.length > 0) {
  367. for (var i = 1; i <= newssrcs.length; i ++) {
  368. // Change video type to screen
  369. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  370. newssrcs[i-1].type = 'screen';
  371. }
  372. connection.emuc.addMediaToPresence(i,
  373. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  374. }
  375. connection.emuc.sendPresence();
  376. }
  377. });
  378. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  379. switch (session.peerconnection.iceConnectionState) {
  380. case 'checking':
  381. session.timeChecking = (new Date()).getTime();
  382. session.firstconnect = true;
  383. break;
  384. case 'completed': // on caller side
  385. case 'connected':
  386. if (session.firstconnect) {
  387. session.firstconnect = false;
  388. var metadata = {};
  389. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  390. session.peerconnection.getStats(function (res) {
  391. if(res && res.result) {
  392. res.result().forEach(function (report) {
  393. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  394. metadata.localCandidateType = report.stat('googLocalCandidateType');
  395. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  396. // log pair as well so we can get nice pie charts
  397. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  398. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  399. metadata.ipv6 = true;
  400. }
  401. }
  402. });
  403. }
  404. });
  405. }
  406. break;
  407. }
  408. });
  409. $(document).bind('presence.muc', function (event, jid, info, pres) {
  410. //check if the video bridge is available
  411. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  412. bridgeIsDown = true;
  413. UI.messageHandler.showError("Error",
  414. "Jitsi Videobridge is currently unavailable. Please try again later!");
  415. }
  416. if (info.isFocus)
  417. {
  418. return;
  419. }
  420. // Remove old ssrcs coming from the jid
  421. Object.keys(ssrc2jid).forEach(function (ssrc) {
  422. if (ssrc2jid[ssrc] == jid) {
  423. delete ssrc2jid[ssrc];
  424. delete ssrc2videoType[ssrc];
  425. }
  426. });
  427. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  428. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  429. var ssrcV = ssrc.getAttribute('ssrc');
  430. ssrc2jid[ssrcV] = jid;
  431. notReceivedSSRCs.push(ssrcV);
  432. var type = ssrc.getAttribute('type');
  433. ssrc2videoType[ssrcV] = type;
  434. // might need to update the direction if participant just went from sendrecv to recvonly
  435. if (type === 'video' || type === 'screen') {
  436. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  437. switch (ssrc.getAttribute('direction')) {
  438. case 'sendrecv':
  439. el.show();
  440. break;
  441. case 'recvonly':
  442. el.hide();
  443. // FIXME: Check if we have to change large video
  444. //VideoLayout.updateLargeVideo(el);
  445. break;
  446. }
  447. }
  448. });
  449. var displayName = !config.displayJids
  450. ? info.displayName : Strophe.getResourceFromJid(jid);
  451. if (displayName && displayName.length > 0)
  452. $(document).trigger('displaynamechanged',
  453. [jid, displayName]);
  454. /*if (focus !== null && info.displayName !== null) {
  455. focus.setEndpointDisplayName(jid, info.displayName);
  456. }*/
  457. //check if the video bridge is available
  458. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  459. bridgeIsDown = true;
  460. UI.messageHandler.showError("Error",
  461. "Jitsi Videobridge is currently unavailable. Please try again later!");
  462. }
  463. var id = $(pres).find('>userID').text();
  464. var email = $(pres).find('>email');
  465. if(email.length > 0) {
  466. id = email.text();
  467. }
  468. UI.setUserAvatar(jid, id);
  469. });
  470. $(document).bind('kicked.muc', function (event, jid) {
  471. console.info(jid + " has been kicked from MUC!");
  472. if (connection.emuc.myroomjid === jid) {
  473. sessionTerminated = true;
  474. disposeConference(false);
  475. connection.emuc.doLeave();
  476. UI.messageHandler.openMessageDialog("Session Terminated",
  477. "Ouch! You have been kicked out of the meet!");
  478. }
  479. });
  480. $(document).bind('passwordrequired.main', function (event) {
  481. console.log('password is required');
  482. UI.messageHandler.openTwoButtonDialog(null,
  483. '<h2>Password required</h2>' +
  484. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  485. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  486. true,
  487. "Ok",
  488. function (e, v, m, f) {
  489. if (v) {
  490. var username = document.getElementById('passwordrequired.username');
  491. var password = document.getElementById('passwordrequired.password');
  492. if (username.value !== null && password.value != null) {
  493. connect(username.value, password.value);
  494. }
  495. }
  496. },
  497. function (event) {
  498. document.getElementById('passwordrequired.username').focus();
  499. }
  500. );
  501. });
  502. /**
  503. * Checks if video identified by given src is desktop stream.
  504. * @param videoSrc eg.
  505. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  506. * @returns {boolean}
  507. */
  508. function isVideoSrcDesktop(jid) {
  509. // FIXME: fix this mapping mess...
  510. // figure out if large video is desktop stream or just a camera
  511. if(!jid)
  512. return false;
  513. var isDesktop = false;
  514. if (connection.emuc.myroomjid &&
  515. Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {
  516. // local video
  517. isDesktop = isUsingScreenStream;
  518. } else {
  519. // Do we have associations...
  520. var videoSsrc = jid2Ssrc[jid];
  521. if (videoSsrc) {
  522. var videoType = ssrc2videoType[videoSsrc];
  523. if (videoType) {
  524. // Finally there...
  525. isDesktop = videoType === 'screen';
  526. } else {
  527. console.error("No video type for ssrc: " + videoSsrc);
  528. }
  529. } else {
  530. console.error("No ssrc for jid: " + jid);
  531. }
  532. }
  533. return isDesktop;
  534. }
  535. /**
  536. * Mutes/unmutes the local video.
  537. *
  538. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  539. * @param options an object which specifies optional arguments such as the
  540. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  541. * specifies whether the method was initiated in response to a user command (in
  542. * contrast to an automatic decision taken by the application logic)
  543. */
  544. function setVideoMute(mute, options) {
  545. if (connection && connection.jingle.localVideo) {
  546. var session = activecall;
  547. if (session) {
  548. session.setVideoMute(
  549. mute,
  550. function (mute) {
  551. var video = $('#video');
  552. var communicativeClass = "icon-camera";
  553. var muteClass = "icon-camera icon-camera-disabled";
  554. if (mute) {
  555. video.removeClass(communicativeClass);
  556. video.addClass(muteClass);
  557. } else {
  558. video.removeClass(muteClass);
  559. video.addClass(communicativeClass);
  560. }
  561. connection.emuc.addVideoInfoToPresence(mute);
  562. connection.emuc.sendPresence();
  563. },
  564. options);
  565. }
  566. }
  567. }
  568. $(document).on('inlastnchanged', function (event, oldValue, newValue) {
  569. if (config.muteLocalVideoIfNotInLastN) {
  570. setVideoMute(!newValue, { 'byUser': false });
  571. }
  572. });
  573. /**
  574. * Mutes/unmutes the local video.
  575. */
  576. function toggleVideo() {
  577. buttonClick("#video", "icon-camera icon-camera-disabled");
  578. if (connection && connection.jingle.localVideo) {
  579. var session = activecall;
  580. if (session) {
  581. setVideoMute(!session.isVideoMute());
  582. }
  583. }
  584. }
  585. /**
  586. * Mutes / unmutes audio for the local participant.
  587. */
  588. function toggleAudio() {
  589. setAudioMuted(!isAudioMuted());
  590. }
  591. /**
  592. * Sets muted audio state for the local participant.
  593. */
  594. function setAudioMuted(mute) {
  595. if (!(connection && connection.jingle.localAudio)) {
  596. preMuted = mute;
  597. // We still click the button.
  598. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  599. return;
  600. }
  601. if (forceMuted && !mute) {
  602. console.info("Asking focus for unmute");
  603. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  604. // FIXME: wait for result before resetting muted status
  605. forceMuted = false;
  606. }
  607. if (mute == isAudioMuted()) {
  608. // Nothing to do
  609. return;
  610. }
  611. // It is not clear what is the right way to handle multiple tracks.
  612. // So at least make sure that they are all muted or all unmuted and
  613. // that we send presence just once.
  614. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  615. if (localAudioTracks.length > 0) {
  616. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  617. localAudioTracks[idx].enabled = !mute;
  618. }
  619. }
  620. // isMuted is the opposite of audioEnabled
  621. connection.emuc.addAudioInfoToPresence(mute);
  622. connection.emuc.sendPresence();
  623. UI.showLocalAudioIndicator(mute);
  624. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  625. }
  626. /**
  627. * Checks whether the audio is muted or not.
  628. * @returns {boolean} true if audio is muted and false if not.
  629. */
  630. function isAudioMuted()
  631. {
  632. var localAudio = connection.jingle.localAudio;
  633. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  634. if(localAudio.getAudioTracks()[idx].enabled === true)
  635. return false;
  636. }
  637. return true;
  638. }
  639. $(document).ready(function () {
  640. if(API.isEnabled())
  641. API.init();
  642. UI.start();
  643. statistics.start();
  644. Moderator.init();
  645. // Set default desktop sharing method
  646. setDesktopSharing(config.desktopSharing);
  647. // Initialize Chrome extension inline installs
  648. if (config.chromeExtensionId) {
  649. initInlineInstalls();
  650. }
  651. });
  652. $(window).bind('beforeunload', function () {
  653. if (connection && connection.connected) {
  654. // ensure signout
  655. $.ajax({
  656. type: 'POST',
  657. url: config.bosh,
  658. async: false,
  659. cache: false,
  660. contentType: 'application/xml',
  661. data: "<body rid='" + (connection.rid || connection._proto.rid)
  662. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  663. + (connection.sid || connection._proto.sid)
  664. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  665. success: function (data) {
  666. console.log('signed out');
  667. console.log(data);
  668. },
  669. error: function (XMLHttpRequest, textStatus, errorThrown) {
  670. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  671. }
  672. });
  673. }
  674. disposeConference(true);
  675. if(API.isEnabled())
  676. API.dispose();
  677. });
  678. function disposeConference(onUnload) {
  679. UI.onDisposeConference(onUnload);
  680. var handler = activecall;
  681. if (handler && handler.peerconnection) {
  682. // FIXME: probably removing streams is not required and close() should
  683. // be enough
  684. if (connection.jingle.localAudio) {
  685. handler.peerconnection.removeStream(connection.jingle.localAudio, onUnload);
  686. }
  687. if (connection.jingle.localVideo) {
  688. handler.peerconnection.removeStream(connection.jingle.localVideo, onUnload);
  689. }
  690. handler.peerconnection.close();
  691. }
  692. statistics.onDisposeConference(onUnload);
  693. activecall = null;
  694. }
  695. /**
  696. * Changes the style class of the element given by id.
  697. */
  698. function buttonClick(id, classname) {
  699. $(id).toggleClass(classname); // add the class to the clicked element
  700. }