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

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