You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var activecall = null;
  6. var RTC = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var recordingToken ='';
  10. var roomUrl = null;
  11. var roomName = null;
  12. var ssrc2jid = {};
  13. /**
  14. * The stats collector that process stats data and triggers updates to app.js.
  15. * @type {StatsCollector}
  16. */
  17. var statsCollector = null;
  18. /**
  19. * The stats collector for the local stream.
  20. * @type {LocalStatsCollector}
  21. */
  22. var localStatsCollector = null;
  23. /**
  24. * Indicates whether ssrc is camera video or desktop stream.
  25. * FIXME: remove those maps
  26. */
  27. var ssrc2videoType = {};
  28. var videoSrcToSsrc = {};
  29. /**
  30. * Currently focused video "src"(displayed in large video).
  31. * @type {String}
  32. */
  33. var focusedVideoSrc = null;
  34. var mutedAudios = {};
  35. var localVideoSrc = null;
  36. var flipXLocalVideo = true;
  37. var isFullScreen = false;
  38. var toolbarTimeout = null;
  39. var currentVideoWidth = null;
  40. var currentVideoHeight = null;
  41. /**
  42. * Method used to calculate large video size.
  43. * @type {function ()}
  44. */
  45. var getVideoSize;
  46. /**
  47. * Method used to get large video position.
  48. * @type {function ()}
  49. */
  50. var getVideoPosition;
  51. /* window.onbeforeunload = closePageWarning; */
  52. var sessionTerminated = false;
  53. function init() {
  54. RTC = setupRTC();
  55. if (RTC === null) {
  56. window.location.href = 'webrtcrequired.html';
  57. return;
  58. } else if (RTC.browser !== 'chrome') {
  59. window.location.href = 'chromeonly.html';
  60. return;
  61. }
  62. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  63. if (nickname) {
  64. connection.emuc.addDisplayNameToPresence(nickname);
  65. }
  66. if (connection.disco) {
  67. // for chrome, add multistream cap
  68. }
  69. connection.jingle.pc_constraints = RTC.pc_constraints;
  70. if (config.useIPv6) {
  71. // https://code.google.com/p/webrtc/issues/detail?id=2828
  72. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  73. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  74. }
  75. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  76. connection.connect(jid, document.getElementById('password').value, function (status) {
  77. if (status === Strophe.Status.CONNECTED) {
  78. console.log('connected');
  79. if (config.useStunTurn) {
  80. connection.jingle.getStunAndTurnCredentials();
  81. }
  82. obtainAudioAndVideoPermissions(function () {
  83. getUserMediaWithConstraints(['audio'], audioStreamReady,
  84. function (error) {
  85. console.error('failed to obtain audio stream - stop', error);
  86. });
  87. });
  88. document.getElementById('connect').disabled = true;
  89. } else {
  90. console.log('status', status);
  91. }
  92. });
  93. }
  94. /**
  95. * HTTPS only:
  96. * We first ask for audio and video combined stream in order to get permissions and not to ask twice.
  97. * Then we dispose the stream and continue with separate audio, video streams(required for desktop sharing).
  98. */
  99. function obtainAudioAndVideoPermissions(callback) {
  100. // This makes sense only on https sites otherwise we'll be asked for permissions every time
  101. if (location.protocol !== 'https:') {
  102. callback();
  103. return;
  104. }
  105. // Get AV
  106. getUserMediaWithConstraints(
  107. ['audio', 'video'],
  108. function (avStream) {
  109. avStream.stop();
  110. callback();
  111. },
  112. function (error) {
  113. console.error('failed to obtain audio/video stream - stop', error);
  114. });
  115. }
  116. function audioStreamReady(stream) {
  117. VideoLayout.changeLocalAudio(stream);
  118. startLocalRtpStatsCollector(stream);
  119. if (RTC.browser !== 'firefox') {
  120. getUserMediaWithConstraints(['video'],
  121. videoStreamReady,
  122. videoStreamFailed,
  123. config.resolution || '360');
  124. } else {
  125. doJoin();
  126. }
  127. }
  128. function videoStreamReady(stream) {
  129. VideoLayout.changeLocalVideo(stream, true);
  130. doJoin();
  131. }
  132. function videoStreamFailed(error) {
  133. console.warn("Failed to obtain video stream - continue anyway", error);
  134. doJoin();
  135. }
  136. function doJoin() {
  137. var roomnode = null;
  138. var path = window.location.pathname;
  139. var roomjid;
  140. // determinde the room node from the url
  141. // TODO: just the roomnode or the whole bare jid?
  142. if (config.getroomnode && typeof config.getroomnode === 'function') {
  143. // custom function might be responsible for doing the pushstate
  144. roomnode = config.getroomnode(path);
  145. } else {
  146. /* fall back to default strategy
  147. * this is making assumptions about how the URL->room mapping happens.
  148. * It currently assumes deployment at root, with a rewrite like the
  149. * following one (for nginx):
  150. location ~ ^/([a-zA-Z0-9]+)$ {
  151. rewrite ^/(.*)$ / break;
  152. }
  153. */
  154. if (path.length > 1) {
  155. roomnode = path.substr(1).toLowerCase();
  156. } else {
  157. roomnode = Math.random().toString(36).substr(2, 20);
  158. window.history.pushState('VideoChat',
  159. 'Room: ' + roomnode, window.location.pathname + roomnode);
  160. }
  161. }
  162. roomName = roomnode + '@' + config.hosts.muc;
  163. roomjid = roomName;
  164. if (config.useNicks) {
  165. var nick = window.prompt('Your nickname (optional)');
  166. if (nick) {
  167. roomjid += '/' + nick;
  168. } else {
  169. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  170. }
  171. } else {
  172. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0, 8);
  173. }
  174. connection.emuc.doJoin(roomjid);
  175. }
  176. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  177. function waitForRemoteVideo(selector, sid, ssrc) {
  178. if (selector.removed) {
  179. console.warn("media removed before had started", selector);
  180. return;
  181. }
  182. var sess = connection.jingle.sessions[sid];
  183. if (data.stream.id === 'mixedmslabel') return;
  184. var videoTracks = data.stream.getVideoTracks();
  185. // console.log("waiting..", videoTracks, selector[0]);
  186. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  187. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  188. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  189. // in order to get rid of too many maps
  190. if (ssrc) {
  191. videoSrcToSsrc[sel.attr('src')] = ssrc;
  192. } else {
  193. console.warn("No ssrc given for video", sel);
  194. }
  195. $(document).trigger('callactive.jingle', [selector, sid]);
  196. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  197. } else {
  198. setTimeout(function () { waitForRemoteVideo(selector, sid, ssrc); }, 250);
  199. }
  200. }
  201. var sess = connection.jingle.sessions[sid];
  202. var thessrc;
  203. // look up an associated JID for a stream id
  204. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  205. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  206. ssrclines = ssrclines.filter(function (line) {
  207. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  208. });
  209. if (ssrclines.length) {
  210. thessrc = ssrclines[0].substring(7).split(' ')[0];
  211. // ok to overwrite the one from focus? might save work in colibri.js
  212. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  213. if (ssrc2jid[thessrc]) {
  214. data.peerjid = ssrc2jid[thessrc];
  215. }
  216. }
  217. }
  218. var container;
  219. var remotes = document.getElementById('remoteVideos');
  220. if (data.peerjid) {
  221. VideoLayout.ensurePeerContainerExists(data.peerjid);
  222. container = document.getElementById(
  223. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  224. } else {
  225. if (data.stream.id !== 'mixedmslabel') {
  226. console.error( 'can not associate stream',
  227. data.stream.id,
  228. 'with a participant');
  229. // We don't want to add it here since it will cause troubles
  230. return;
  231. }
  232. // FIXME: for the mixed ms we dont need a video -- currently
  233. container = document.createElement('span');
  234. container.className = 'videocontainer';
  235. remotes.appendChild(container);
  236. Util.playSoundNotification('userJoined');
  237. }
  238. var isVideo = data.stream.getVideoTracks().length > 0;
  239. var vid = isVideo ? document.createElement('video') : document.createElement('audio');
  240. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' + data.stream.id;
  241. vid.id = id;
  242. vid.autoplay = true;
  243. vid.oncontextmenu = function () { return false; };
  244. container.appendChild(vid);
  245. // TODO: make mixedstream display:none via css?
  246. if (id.indexOf('mixedmslabel') !== -1) {
  247. container.id = 'mixedstream';
  248. $(container).hide();
  249. }
  250. var sel = $('#' + id);
  251. sel.hide();
  252. RTC.attachMediaStream(sel, data.stream);
  253. if (isVideo) {
  254. waitForRemoteVideo(sel, sid, thessrc);
  255. }
  256. data.stream.onended = function () {
  257. console.log('stream ended', this.id);
  258. // Mark video as removed to cancel waiting loop(if video is removed
  259. // before has started)
  260. sel.removed = true;
  261. sel.remove();
  262. var audioCount = $('#' + container.id + '>audio').length;
  263. var videoCount = $('#' + container.id + '>video').length;
  264. if (!audioCount && !videoCount) {
  265. console.log("Remove whole user", container.id);
  266. // Remove whole container
  267. container.remove();
  268. Util.playSoundNotification('userLeft');
  269. VideoLayout.resizeThumbnails();
  270. }
  271. VideoLayout.checkChangeLargeVideo(vid.src);
  272. };
  273. // Add click handler.
  274. container.onclick = function (event) {
  275. /*
  276. * FIXME It turns out that videoThumb may not exist (if there is no
  277. * actual video).
  278. */
  279. var videoThumb = $('#' + container.id + '>video').get(0);
  280. if (videoThumb)
  281. VideoLayout.handleVideoThumbClicked(videoThumb.src);
  282. event.preventDefault();
  283. return false;
  284. };
  285. // Add hover handler
  286. $(container).hover(
  287. function() {
  288. VideoLayout.showDisplayName(container.id, true);
  289. },
  290. function() {
  291. var videoSrc = null;
  292. if ($('#' + container.id + '>video')
  293. && $('#' + container.id + '>video').length > 0) {
  294. videoSrc = $('#' + container.id + '>video').get(0).src;
  295. }
  296. // If the video has been "pinned" by the user we want to keep the
  297. // display name on place.
  298. if (!VideoLayout.isLargeVideoVisible()
  299. || videoSrc !== $('#largeVideo').attr('src'))
  300. VideoLayout.showDisplayName(container.id, false);
  301. }
  302. );
  303. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  304. if (isVideo &&
  305. data.peerjid && sess.peerjid === data.peerjid &&
  306. data.stream.getVideoTracks().length === 0 &&
  307. connection.jingle.localVideo.getVideoTracks().length > 0) {
  308. //
  309. window.setTimeout(function () {
  310. sendKeyframe(sess.peerconnection);
  311. }, 3000);
  312. }
  313. });
  314. /**
  315. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  316. * @param videoSrc the video "src" identifier.
  317. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  318. * belongs.
  319. */
  320. function getJidFromVideoSrc(videoSrc)
  321. {
  322. if (videoSrc === localVideoSrc)
  323. return connection.emuc.myroomjid;
  324. var ssrc = videoSrcToSsrc[videoSrc];
  325. if (!ssrc)
  326. {
  327. return null;
  328. }
  329. return ssrc2jid[ssrc];
  330. }
  331. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  332. function sendKeyframe(pc) {
  333. console.log('sendkeyframe', pc.iceConnectionState);
  334. if (pc.iceConnectionState !== 'connected') return; // safe...
  335. pc.setRemoteDescription(
  336. pc.remoteDescription,
  337. function () {
  338. pc.createAnswer(
  339. function (modifiedAnswer) {
  340. pc.setLocalDescription(
  341. modifiedAnswer,
  342. function () {
  343. // noop
  344. },
  345. function (error) {
  346. console.log('triggerKeyframe setLocalDescription failed', error);
  347. }
  348. );
  349. },
  350. function (error) {
  351. console.log('triggerKeyframe createAnswer failed', error);
  352. }
  353. );
  354. },
  355. function (error) {
  356. console.log('triggerKeyframe setRemoteDescription failed', error);
  357. }
  358. );
  359. }
  360. // Really mute video, i.e. dont even send black frames
  361. function muteVideo(pc, unmute) {
  362. // FIXME: this probably needs another of those lovely state safeguards...
  363. // which checks for iceconn == connected and sigstate == stable
  364. pc.setRemoteDescription(pc.remoteDescription,
  365. function () {
  366. pc.createAnswer(
  367. function (answer) {
  368. var sdp = new SDP(answer.sdp);
  369. if (sdp.media.length > 1) {
  370. if (unmute)
  371. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  372. else
  373. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  374. sdp.raw = sdp.session + sdp.media.join('');
  375. answer.sdp = sdp.raw;
  376. }
  377. pc.setLocalDescription(answer,
  378. function () {
  379. console.log('mute SLD ok');
  380. },
  381. function (error) {
  382. console.log('mute SLD error');
  383. }
  384. );
  385. },
  386. function (error) {
  387. console.log(error);
  388. }
  389. );
  390. },
  391. function (error) {
  392. console.log('muteVideo SRD error');
  393. }
  394. );
  395. }
  396. /**
  397. * Callback for audio levels changed.
  398. * @param jid JID of the user
  399. * @param audioLevel the audio level value
  400. */
  401. function audioLevelUpdated(jid, audioLevel)
  402. {
  403. var resourceJid;
  404. if(jid === LocalStatsCollector.LOCAL_JID)
  405. {
  406. resourceJid = AudioLevels.LOCAL_LEVEL;
  407. if(isAudioMuted())
  408. return;
  409. }
  410. else
  411. {
  412. resourceJid = Strophe.getResourceFromJid(jid);
  413. }
  414. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  415. }
  416. /**
  417. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  418. */
  419. function startRtpStatsCollector()
  420. {
  421. stopRTPStatsCollector();
  422. if (config.enableRtpStats)
  423. {
  424. statsCollector = new StatsCollector(
  425. getConferenceHandler().peerconnection, 200, audioLevelUpdated);
  426. statsCollector.start();
  427. }
  428. }
  429. /**
  430. * Stops the {@link StatsCollector}.
  431. */
  432. function stopRTPStatsCollector()
  433. {
  434. if (statsCollector)
  435. {
  436. statsCollector.stop();
  437. statsCollector = null;
  438. }
  439. }
  440. /**
  441. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  442. * @param stream the stream that will be used for collecting statistics.
  443. */
  444. function startLocalRtpStatsCollector(stream)
  445. {
  446. if(config.enableRtpStats)
  447. {
  448. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  449. localStatsCollector.start();
  450. }
  451. }
  452. /**
  453. * Stops the {@link LocalStatsCollector}.
  454. */
  455. function stopLocalRtpStatsCollector()
  456. {
  457. if(localStatsCollector)
  458. {
  459. localStatsCollector.stop();
  460. localStatsCollector = null;
  461. }
  462. }
  463. $(document).bind('callincoming.jingle', function (event, sid) {
  464. var sess = connection.jingle.sessions[sid];
  465. // TODO: do we check activecall == null?
  466. activecall = sess;
  467. startRtpStatsCollector();
  468. // Bind data channel listener in case we're a regular participant
  469. if (config.openSctp)
  470. {
  471. bindDataChannelListener(sess.peerconnection);
  472. }
  473. // TODO: check affiliation and/or role
  474. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  475. sess.usedrip = true; // not-so-naive trickle ice
  476. sess.sendAnswer();
  477. sess.accept();
  478. });
  479. $(document).bind('conferenceCreated.jingle', function (event, focus)
  480. {
  481. startRtpStatsCollector();
  482. });
  483. $(document).bind('conferenceCreated.jingle', function (event, focus)
  484. {
  485. // Bind data channel listener in case we're the focus
  486. if (config.openSctp)
  487. {
  488. bindDataChannelListener(focus.peerconnection);
  489. }
  490. });
  491. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  492. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  493. // ignore mixedmslabela0 and v0
  494. videoelem.show();
  495. VideoLayout.resizeThumbnails();
  496. // Update the large video to the last added video only if there's no
  497. // current active or focused speaker.
  498. if (!focusedVideoSrc && !VideoLayout.getDominantSpeakerResourceJid())
  499. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  500. VideoLayout.showFocusIndicator();
  501. }
  502. });
  503. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  504. // Leave the room if my call has been remotely terminated.
  505. if (connection.emuc.joined && focus == null && reason === 'kick') {
  506. sessionTerminated = true;
  507. connection.emuc.doLeave();
  508. openMessageDialog( "Session Terminated",
  509. "Ouch! You have been kicked out of the meet!");
  510. }
  511. });
  512. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  513. // put our ssrcs into presence so other clients can identify our stream
  514. var sess = connection.jingle.sessions[sid];
  515. var newssrcs = {};
  516. var directions = {};
  517. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  518. localSDP.media.forEach(function (media) {
  519. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  520. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  521. // assumes a single local ssrc
  522. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  523. newssrcs[type] = ssrc;
  524. directions[type] = (
  525. SDPUtil.find_line(media, 'a=sendrecv') ||
  526. SDPUtil.find_line(media, 'a=recvonly') ||
  527. SDPUtil.find_line(media, 'a=sendonly') ||
  528. SDPUtil.find_line(media, 'a=inactive') ||
  529. 'a=sendrecv').substr(2);
  530. }
  531. });
  532. console.log('new ssrcs', newssrcs);
  533. // Have to clear presence map to get rid of removed streams
  534. connection.emuc.clearPresenceMedia();
  535. var i = 0;
  536. Object.keys(newssrcs).forEach(function (mtype) {
  537. i++;
  538. var type = mtype;
  539. // Change video type to screen
  540. if (mtype === 'video' && isUsingScreenStream) {
  541. type = 'screen';
  542. }
  543. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  544. });
  545. if (i > 0) {
  546. connection.emuc.sendPresence();
  547. }
  548. });
  549. $(document).bind('joined.muc', function (event, jid, info) {
  550. updateRoomUrl(window.location.href);
  551. document.getElementById('localNick').appendChild(
  552. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  553. );
  554. if (Object.keys(connection.emuc.members).length < 1) {
  555. focus = new ColibriFocus(connection, config.hosts.bridge);
  556. if (nickname !== null) {
  557. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  558. nickname);
  559. }
  560. Toolbar.showSipCallButton(true);
  561. Toolbar.showRecordingButton(false);
  562. }
  563. if (!focus)
  564. {
  565. Toolbar.showSipCallButton(false);
  566. }
  567. if (focus && config.etherpad_base) {
  568. Etherpad.init();
  569. }
  570. VideoLayout.showFocusIndicator();
  571. // Once we've joined the muc show the toolbar
  572. Toolbar.showToolbar();
  573. var displayName = '';
  574. if (info.displayName)
  575. displayName = info.displayName + ' (me)';
  576. VideoLayout.setDisplayName('localVideoContainer', displayName);
  577. });
  578. $(document).bind('entered.muc', function (event, jid, info, pres) {
  579. console.log('entered', jid, info);
  580. console.log('is focus?' + focus ? 'true' : 'false');
  581. // Add Peer's container
  582. VideoLayout.ensurePeerContainerExists(jid);
  583. if (focus !== null) {
  584. // FIXME: this should prepare the video
  585. if (focus.confid === null) {
  586. console.log('make new conference with', jid);
  587. focus.makeConference(Object.keys(connection.emuc.members));
  588. Toolbar.showRecordingButton(true);
  589. } else {
  590. console.log('invite', jid, 'into conference');
  591. focus.addNewParticipant(jid);
  592. }
  593. }
  594. else if (sharedKey) {
  595. Toolbar.updateLockButton();
  596. }
  597. });
  598. $(document).bind('left.muc', function (event, jid) {
  599. console.log('left.muc', jid);
  600. // Need to call this with a slight delay, otherwise the element couldn't be
  601. // found for some reason.
  602. window.setTimeout(function () {
  603. var container = document.getElementById(
  604. 'participant_' + Strophe.getResourceFromJid(jid));
  605. if (container) {
  606. // hide here, wait for video to close before removing
  607. $(container).hide();
  608. VideoLayout.resizeThumbnails();
  609. }
  610. }, 10);
  611. // Unlock large video
  612. if (focusedVideoSrc)
  613. {
  614. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  615. {
  616. console.info("Focused video owner has left the conference");
  617. focusedVideoSrc = null;
  618. }
  619. }
  620. connection.jingle.terminateByJid(jid);
  621. if (focus == null
  622. // I shouldn't be the one that left to enter here.
  623. && jid !== connection.emuc.myroomjid
  624. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  625. // If our session has been terminated for some reason
  626. // (kicked, hangup), don't try to become the focus
  627. && !sessionTerminated) {
  628. console.log('welcome to our new focus... myself');
  629. focus = new ColibriFocus(connection, config.hosts.bridge);
  630. if (nickname !== null) {
  631. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  632. nickname);
  633. }
  634. Toolbar.showSipCallButton(true);
  635. if (Object.keys(connection.emuc.members).length > 0) {
  636. focus.makeConference(Object.keys(connection.emuc.members));
  637. Toolbar.showRecordingButton(true);
  638. }
  639. $(document).trigger('focusechanged.muc', [focus]);
  640. }
  641. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  642. console.log('everyone left');
  643. // FIXME: closing the connection is a hack to avoid some
  644. // problems with reinit
  645. disposeConference();
  646. focus = new ColibriFocus(connection, config.hosts.bridge);
  647. if (nickname !== null) {
  648. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  649. nickname);
  650. }
  651. Toolbar.showSipCallButton(true);
  652. Toolbar.showRecordingButton(false);
  653. }
  654. if (connection.emuc.getPrezi(jid)) {
  655. $(document).trigger('presentationremoved.muc',
  656. [jid, connection.emuc.getPrezi(jid)]);
  657. }
  658. });
  659. $(document).bind('presence.muc', function (event, jid, info, pres) {
  660. // Remove old ssrcs coming from the jid
  661. Object.keys(ssrc2jid).forEach(function (ssrc) {
  662. if (ssrc2jid[ssrc] == jid) {
  663. delete ssrc2jid[ssrc];
  664. }
  665. if (ssrc2videoType[ssrc] == jid) {
  666. delete ssrc2videoType[ssrc];
  667. }
  668. });
  669. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  670. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  671. var ssrcV = ssrc.getAttribute('ssrc');
  672. ssrc2jid[ssrcV] = jid;
  673. var type = ssrc.getAttribute('type');
  674. ssrc2videoType[ssrcV] = type;
  675. // might need to update the direction if participant just went from sendrecv to recvonly
  676. if (type === 'video' || type === 'screen') {
  677. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  678. switch (ssrc.getAttribute('direction')) {
  679. case 'sendrecv':
  680. el.show();
  681. break;
  682. case 'recvonly':
  683. el.hide();
  684. // FIXME: Check if we have to change large video
  685. //VideoLayout.checkChangeLargeVideo(el);
  686. break;
  687. }
  688. }
  689. });
  690. if (jid === connection.emuc.myroomjid) {
  691. VideoLayout.setDisplayName('localVideoContainer',
  692. info.displayName);
  693. } else {
  694. VideoLayout.ensurePeerContainerExists(jid);
  695. VideoLayout.setDisplayName(
  696. 'participant_' + Strophe.getResourceFromJid(jid),
  697. info.displayName, info.status);
  698. }
  699. if (focus !== null && info.displayName !== null) {
  700. focus.setEndpointDisplayName(jid, info.displayName);
  701. }
  702. });
  703. $(document).bind('passwordrequired.muc', function (event, jid) {
  704. console.log('on password required', jid);
  705. $.prompt('<h2>Password required</h2>' +
  706. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  707. persistent: true,
  708. buttons: { "Ok": true, "Cancel": false},
  709. defaultButton: 1,
  710. loaded: function (event) {
  711. document.getElementById('lockKey').focus();
  712. },
  713. submit: function (e, v, m, f) {
  714. if (v) {
  715. var lockKey = document.getElementById('lockKey');
  716. if (lockKey.value !== null) {
  717. setSharedKey(lockKey.value);
  718. connection.emuc.doJoin(jid, lockKey.value);
  719. }
  720. }
  721. }
  722. });
  723. });
  724. /**
  725. * Checks if video identified by given src is desktop stream.
  726. * @param videoSrc eg.
  727. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  728. * @returns {boolean}
  729. */
  730. function isVideoSrcDesktop(videoSrc) {
  731. // FIXME: fix this mapping mess...
  732. // figure out if large video is desktop stream or just a camera
  733. var isDesktop = false;
  734. if (localVideoSrc === videoSrc) {
  735. // local video
  736. isDesktop = isUsingScreenStream;
  737. } else {
  738. // Do we have associations...
  739. var videoSsrc = videoSrcToSsrc[videoSrc];
  740. if (videoSsrc) {
  741. var videoType = ssrc2videoType[videoSsrc];
  742. if (videoType) {
  743. // Finally there...
  744. isDesktop = videoType === 'screen';
  745. } else {
  746. console.error("No video type for ssrc: " + videoSsrc);
  747. }
  748. } else {
  749. console.error("No ssrc for src: " + videoSrc);
  750. }
  751. }
  752. return isDesktop;
  753. }
  754. function getConferenceHandler() {
  755. return focus ? focus : activecall;
  756. }
  757. function toggleVideo() {
  758. if (!(connection && connection.jingle.localVideo))
  759. return;
  760. var sess = getConferenceHandler();
  761. if (sess) {
  762. sess.toggleVideoMute(
  763. function (isMuted) {
  764. if (isMuted) {
  765. $('#video').removeClass("icon-camera");
  766. $('#video').addClass("icon-camera icon-camera-disabled");
  767. } else {
  768. $('#video').removeClass("icon-camera icon-camera-disabled");
  769. $('#video').addClass("icon-camera");
  770. }
  771. }
  772. );
  773. }
  774. sess = focus || activecall;
  775. if (!sess) {
  776. return;
  777. }
  778. sess.pendingop = ismuted ? 'unmute' : 'mute';
  779. // connection.emuc.addVideoInfoToPresence(!ismuted);
  780. // connection.emuc.sendPresence();
  781. sess.modifySources();
  782. }
  783. /**
  784. * Mutes / unmutes audio for the local participant.
  785. */
  786. function toggleAudio() {
  787. if (!(connection && connection.jingle.localAudio)) {
  788. preMuted = true;
  789. // We still click the button.
  790. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  791. return;
  792. }
  793. var localAudio = connection.jingle.localAudio;
  794. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  795. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  796. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  797. // isMuted is the opposite of audioEnabled
  798. connection.emuc.addAudioInfoToPresence(audioEnabled);
  799. connection.emuc.sendPresence();
  800. }
  801. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  802. }
  803. /**
  804. * Checks whether the audio is muted or not.
  805. * @returns {boolean} true if audio is muted and false if not.
  806. */
  807. function isAudioMuted()
  808. {
  809. var localAudio = connection.jingle.localAudio;
  810. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  811. if(localAudio.getAudioTracks()[idx].enabled === true)
  812. return false;
  813. }
  814. return true;
  815. }
  816. // Starts or stops the recording for the conference.
  817. function toggleRecording() {
  818. if (focus === null || focus.confid === null) {
  819. console.log('non-focus, or conference not yet organized: not enabling recording');
  820. return;
  821. }
  822. if (!recordingToken)
  823. {
  824. $.prompt('<h2>Enter recording token</h2>' +
  825. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  826. {
  827. persistent: false,
  828. buttons: { "Save": true, "Cancel": false},
  829. defaultButton: 1,
  830. loaded: function (event) {
  831. document.getElementById('recordingToken').focus();
  832. },
  833. submit: function (e, v, m, f) {
  834. if (v) {
  835. var token = document.getElementById('recordingToken');
  836. if (token.value) {
  837. setRecordingToken(Util.escapeHtml(token.value));
  838. toggleRecording();
  839. }
  840. }
  841. }
  842. }
  843. );
  844. return;
  845. }
  846. var oldState = focus.recordingEnabled;
  847. Toolbar.toggleRecordingButtonState();
  848. focus.setRecording(!oldState,
  849. recordingToken,
  850. function (state) {
  851. console.log("New recording state: ", state);
  852. if (state == oldState) //failed to change, reset the token because it might have been wrong
  853. {
  854. Toolbar.toggleRecordingButtonState();
  855. setRecordingToken(null);
  856. }
  857. }
  858. );
  859. }
  860. /**
  861. * Returns an array of the video horizontal and vertical indents,
  862. * so that if fits its parent.
  863. *
  864. * @return an array with 2 elements, the horizontal indent and the vertical
  865. * indent
  866. */
  867. function getCameraVideoPosition(videoWidth,
  868. videoHeight,
  869. videoSpaceWidth,
  870. videoSpaceHeight) {
  871. // Parent height isn't completely calculated when we position the video in
  872. // full screen mode and this is why we use the screen height in this case.
  873. // Need to think it further at some point and implement it properly.
  874. var isFullScreen = document.fullScreen ||
  875. document.mozFullScreen ||
  876. document.webkitIsFullScreen;
  877. if (isFullScreen)
  878. videoSpaceHeight = window.innerHeight;
  879. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  880. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  881. return [horizontalIndent, verticalIndent];
  882. }
  883. /**
  884. * Returns an array of the video horizontal and vertical indents.
  885. * Centers horizontally and top aligns vertically.
  886. *
  887. * @return an array with 2 elements, the horizontal indent and the vertical
  888. * indent
  889. */
  890. function getDesktopVideoPosition(videoWidth,
  891. videoHeight,
  892. videoSpaceWidth,
  893. videoSpaceHeight) {
  894. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  895. var verticalIndent = 0;// Top aligned
  896. return [horizontalIndent, verticalIndent];
  897. }
  898. /**
  899. * Returns an array of the video dimensions, so that it covers the screen.
  900. * It leaves no empty areas, but some parts of the video might not be visible.
  901. *
  902. * @return an array with 2 elements, the video width and the video height
  903. */
  904. function getCameraVideoSize(videoWidth,
  905. videoHeight,
  906. videoSpaceWidth,
  907. videoSpaceHeight) {
  908. if (!videoWidth)
  909. videoWidth = currentVideoWidth;
  910. if (!videoHeight)
  911. videoHeight = currentVideoHeight;
  912. var aspectRatio = videoWidth / videoHeight;
  913. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  914. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  915. if (availableWidth / aspectRatio < videoSpaceHeight) {
  916. availableHeight = videoSpaceHeight;
  917. availableWidth = availableHeight * aspectRatio;
  918. }
  919. if (availableHeight * aspectRatio < videoSpaceWidth) {
  920. availableWidth = videoSpaceWidth;
  921. availableHeight = availableWidth / aspectRatio;
  922. }
  923. return [availableWidth, availableHeight];
  924. }
  925. $(document).ready(function () {
  926. Chat.init();
  927. $('body').popover({ selector: '[data-toggle=popover]',
  928. trigger: 'click hover'});
  929. // Set the defaults for prompt dialogs.
  930. jQuery.prompt.setDefaults({persistent: false});
  931. // Set default desktop sharing method
  932. setDesktopSharing(config.desktopSharing);
  933. // Initialize Chrome extension inline installs
  934. if (config.chromeExtensionId) {
  935. initInlineInstalls();
  936. }
  937. // By default we use camera
  938. getVideoSize = getCameraVideoSize;
  939. getVideoPosition = getCameraVideoPosition;
  940. VideoLayout.resizeLargeVideoContainer();
  941. $(window).resize(function () {
  942. VideoLayout.resizeLargeVideoContainer();
  943. VideoLayout.positionLarge();
  944. });
  945. // Listen for large video size updates
  946. document.getElementById('largeVideo')
  947. .addEventListener('loadedmetadata', function (e) {
  948. currentVideoWidth = this.videoWidth;
  949. currentVideoHeight = this.videoHeight;
  950. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  951. });
  952. if (!$('#settings').is(':visible')) {
  953. console.log('init');
  954. init();
  955. } else {
  956. loginInfo.onsubmit = function (e) {
  957. if (e.preventDefault) e.preventDefault();
  958. $('#settings').hide();
  959. init();
  960. };
  961. }
  962. });
  963. $(window).bind('beforeunload', function () {
  964. if (connection && connection.connected) {
  965. // ensure signout
  966. $.ajax({
  967. type: 'POST',
  968. url: config.bosh,
  969. async: false,
  970. cache: false,
  971. contentType: 'application/xml',
  972. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  973. success: function (data) {
  974. console.log('signed out');
  975. console.log(data);
  976. },
  977. error: function (XMLHttpRequest, textStatus, errorThrown) {
  978. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  979. }
  980. });
  981. }
  982. disposeConference(true);
  983. });
  984. function disposeConference(onUnload) {
  985. var handler = getConferenceHandler();
  986. if (handler && handler.peerconnection) {
  987. // FIXME: probably removing streams is not required and close() should be enough
  988. if (connection.jingle.localAudio) {
  989. handler.peerconnection.removeStream(connection.jingle.localAudio);
  990. }
  991. if (connection.jingle.localVideo) {
  992. handler.peerconnection.removeStream(connection.jingle.localVideo);
  993. }
  994. handler.peerconnection.close();
  995. }
  996. stopRTPStatsCollector();
  997. if(onUnload) {
  998. stopLocalRtpStatsCollector();
  999. }
  1000. focus = null;
  1001. activecall = null;
  1002. }
  1003. function dump(elem, filename) {
  1004. elem = elem.parentNode;
  1005. elem.download = filename || 'meetlog.json';
  1006. elem.href = 'data:application/json;charset=utf-8,\n';
  1007. var data = {};
  1008. if (connection.jingle) {
  1009. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1010. var session = connection.jingle.sessions[sid];
  1011. if (session.peerconnection && session.peerconnection.updateLog) {
  1012. // FIXME: should probably be a .dump call
  1013. data["jingle_" + session.sid] = {
  1014. updateLog: session.peerconnection.updateLog,
  1015. stats: session.peerconnection.stats,
  1016. url: window.location.href
  1017. };
  1018. }
  1019. });
  1020. }
  1021. metadata = {};
  1022. metadata.time = new Date();
  1023. metadata.url = window.location.href;
  1024. metadata.ua = navigator.userAgent;
  1025. if (connection.logger) {
  1026. metadata.xmpp = connection.logger.log;
  1027. }
  1028. data.metadata = metadata;
  1029. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1030. return false;
  1031. }
  1032. /**
  1033. * Changes the style class of the element given by id.
  1034. */
  1035. function buttonClick(id, classname) {
  1036. $(id).toggleClass(classname); // add the class to the clicked element
  1037. }
  1038. /**
  1039. * Shows a message to the user.
  1040. *
  1041. * @param titleString the title of the message
  1042. * @param messageString the text of the message
  1043. */
  1044. function openMessageDialog(titleString, messageString) {
  1045. $.prompt(messageString,
  1046. {
  1047. title: titleString,
  1048. persistent: false
  1049. }
  1050. );
  1051. }
  1052. /**
  1053. * Locks / unlocks the room.
  1054. */
  1055. function lockRoom(lock) {
  1056. if (lock)
  1057. connection.emuc.lockRoom(sharedKey);
  1058. else
  1059. connection.emuc.lockRoom('');
  1060. Toolbar.updateLockButton();
  1061. }
  1062. /**
  1063. * Sets the shared key.
  1064. */
  1065. function setSharedKey(sKey) {
  1066. sharedKey = sKey;
  1067. }
  1068. function setRecordingToken(token) {
  1069. recordingToken = token;
  1070. }
  1071. /**
  1072. * Updates the room invite url.
  1073. */
  1074. function updateRoomUrl(newRoomUrl) {
  1075. roomUrl = newRoomUrl;
  1076. // If the invite dialog has been already opened we update the information.
  1077. var inviteLink = document.getElementById('inviteLinkRef');
  1078. if (inviteLink) {
  1079. inviteLink.value = roomUrl;
  1080. inviteLink.select();
  1081. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1082. }
  1083. }
  1084. /**
  1085. * Warning to the user that the conference window is about to be closed.
  1086. */
  1087. function closePageWarning() {
  1088. if (focus !== null)
  1089. return "You are the owner of this conference call and"
  1090. + " you are about to end it.";
  1091. else
  1092. return "You are about to leave this conversation.";
  1093. }
  1094. /**
  1095. * Resizes and repositions videos in full screen mode.
  1096. */
  1097. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1098. function () {
  1099. VideoLayout.resizeLargeVideoContainer();
  1100. VideoLayout.positionLarge();
  1101. isFullScreen = document.fullScreen ||
  1102. document.mozFullScreen ||
  1103. document.webkitIsFullScreen;
  1104. if (isFullScreen) {
  1105. setView("fullscreen");
  1106. }
  1107. else {
  1108. setView("default");
  1109. }
  1110. }
  1111. );
  1112. /**
  1113. * Sets the current view.
  1114. */
  1115. function setView(viewName) {
  1116. // if (viewName == "fullscreen") {
  1117. // document.getElementById('videolayout_fullscreen').disabled = false;
  1118. // document.getElementById('videolayout_default').disabled = true;
  1119. // }
  1120. // else {
  1121. // document.getElementById('videolayout_default').disabled = false;
  1122. // document.getElementById('videolayout_fullscreen').disabled = true;
  1123. // }
  1124. }
  1125. $(document).bind('fatalError.jingle',
  1126. function (event, session, error)
  1127. {
  1128. sessionTerminated = true;
  1129. connection.emuc.doLeave();
  1130. openMessageDialog( "Sorry",
  1131. "Your browser version is too old. Please update and try again...");
  1132. }
  1133. );
  1134. function callSipButtonClicked()
  1135. {
  1136. $.prompt('<h2>Enter SIP number</h2>' +
  1137. '<input id="sipNumber" type="text"' +
  1138. ' value="' + config.defaultSipNumber + '" autofocus>',
  1139. {
  1140. persistent: false,
  1141. buttons: { "Dial": true, "Cancel": false},
  1142. defaultButton: 2,
  1143. loaded: function (event)
  1144. {
  1145. document.getElementById('sipNumber').focus();
  1146. },
  1147. submit: function (e, v, m, f)
  1148. {
  1149. if (v)
  1150. {
  1151. var numberInput = document.getElementById('sipNumber');
  1152. if (numberInput.value)
  1153. {
  1154. connection.rayo.dial(
  1155. numberInput.value, 'fromnumber', roomName);
  1156. }
  1157. }
  1158. }
  1159. }
  1160. );
  1161. }