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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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
  257. // before has started)
  258. sel.removed = true;
  259. sel.remove();
  260. var audioCount = $('#' + container.id + '>audio').length;
  261. var videoCount = $('#' + container.id + '>video').length;
  262. if (!audioCount && !videoCount) {
  263. console.log("Remove whole user", container.id);
  264. // Remove whole container
  265. container.remove();
  266. Util.playSoundNotification('userLeft');
  267. VideoLayout.resizeThumbnails();
  268. }
  269. VideoLayout.checkChangeLargeVideo(vid.src);
  270. };
  271. // Add click handler.
  272. container.onclick = function (event) {
  273. /*
  274. * FIXME It turns out that videoThumb may not exist (if there is no
  275. * actual video).
  276. */
  277. var videoThumb = $('#' + container.id + '>video').get(0);
  278. if (videoThumb)
  279. VideoLayout.handleVideoThumbClicked(videoThumb.src);
  280. event.preventDefault();
  281. return false;
  282. };
  283. // Add hover handler
  284. $(container).hover(
  285. function() {
  286. VideoLayout.showDisplayName(container.id, true);
  287. },
  288. function() {
  289. var videoSrc = null;
  290. if ($('#' + container.id + '>video')
  291. && $('#' + container.id + '>video').length > 0) {
  292. videoSrc = $('#' + container.id + '>video').get(0).src;
  293. }
  294. // If the video has been "pinned" by the user we want to keep the
  295. // display name on place.
  296. if (!VideoLayout.isLargeVideoVisible()
  297. || videoSrc !== $('#largeVideo').attr('src'))
  298. VideoLayout.showDisplayName(container.id, false);
  299. }
  300. );
  301. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  302. if (isVideo &&
  303. data.peerjid && sess.peerjid === data.peerjid &&
  304. data.stream.getVideoTracks().length === 0 &&
  305. connection.jingle.localVideo.getVideoTracks().length > 0) {
  306. //
  307. window.setTimeout(function () {
  308. sendKeyframe(sess.peerconnection);
  309. }, 3000);
  310. }
  311. });
  312. /**
  313. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  314. * @param videoSrc the video "src" identifier.
  315. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  316. * belongs.
  317. */
  318. function getJidFromVideoSrc(videoSrc)
  319. {
  320. if (videoSrc === localVideoSrc)
  321. return connection.emuc.myroomjid;
  322. var ssrc = videoSrcToSsrc[videoSrc];
  323. if (!ssrc)
  324. {
  325. return null;
  326. }
  327. return ssrc2jid[ssrc];
  328. }
  329. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  330. function sendKeyframe(pc) {
  331. console.log('sendkeyframe', pc.iceConnectionState);
  332. if (pc.iceConnectionState !== 'connected') return; // safe...
  333. pc.setRemoteDescription(
  334. pc.remoteDescription,
  335. function () {
  336. pc.createAnswer(
  337. function (modifiedAnswer) {
  338. pc.setLocalDescription(
  339. modifiedAnswer,
  340. function () {
  341. // noop
  342. },
  343. function (error) {
  344. console.log('triggerKeyframe setLocalDescription failed', error);
  345. }
  346. );
  347. },
  348. function (error) {
  349. console.log('triggerKeyframe createAnswer failed', error);
  350. }
  351. );
  352. },
  353. function (error) {
  354. console.log('triggerKeyframe setRemoteDescription failed', error);
  355. }
  356. );
  357. }
  358. // Really mute video, i.e. dont even send black frames
  359. function muteVideo(pc, unmute) {
  360. // FIXME: this probably needs another of those lovely state safeguards...
  361. // which checks for iceconn == connected and sigstate == stable
  362. pc.setRemoteDescription(pc.remoteDescription,
  363. function () {
  364. pc.createAnswer(
  365. function (answer) {
  366. var sdp = new SDP(answer.sdp);
  367. if (sdp.media.length > 1) {
  368. if (unmute)
  369. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  370. else
  371. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  372. sdp.raw = sdp.session + sdp.media.join('');
  373. answer.sdp = sdp.raw;
  374. }
  375. pc.setLocalDescription(answer,
  376. function () {
  377. console.log('mute SLD ok');
  378. },
  379. function (error) {
  380. console.log('mute SLD error');
  381. }
  382. );
  383. },
  384. function (error) {
  385. console.log(error);
  386. }
  387. );
  388. },
  389. function (error) {
  390. console.log('muteVideo SRD error');
  391. }
  392. );
  393. }
  394. /**
  395. * Callback for audio levels changed.
  396. * @param jid JID of the user
  397. * @param audioLevel the audio level value
  398. */
  399. function audioLevelUpdated(jid, audioLevel)
  400. {
  401. var resourceJid;
  402. if(jid === LocalStatsCollector.LOCAL_JID)
  403. {
  404. resourceJid = AudioLevels.LOCAL_LEVEL;
  405. if(isAudioMuted())
  406. return;
  407. }
  408. else
  409. {
  410. resourceJid = Strophe.getResourceFromJid(jid);
  411. }
  412. AudioLevels.updateAudioLevel(resourceJid, 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, audioLevelUpdated);
  424. statsCollector.start();
  425. }
  426. }
  427. /**
  428. * Stops the {@link StatsCollector}.
  429. */
  430. function stopRTPStatsCollector()
  431. {
  432. if (statsCollector)
  433. {
  434. statsCollector.stop();
  435. statsCollector = null;
  436. }
  437. }
  438. /**
  439. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  440. * @param stream the stream that will be used for collecting statistics.
  441. */
  442. function startLocalRtpStatsCollector(stream)
  443. {
  444. if(config.enableRtpStats)
  445. {
  446. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  447. localStatsCollector.start();
  448. }
  449. }
  450. /**
  451. * Stops the {@link LocalStatsCollector}.
  452. */
  453. function stopLocalRtpStatsCollector()
  454. {
  455. if(localStatsCollector)
  456. {
  457. localStatsCollector.stop();
  458. localStatsCollector = null;
  459. }
  460. }
  461. $(document).bind('callincoming.jingle', function (event, sid) {
  462. var sess = connection.jingle.sessions[sid];
  463. // TODO: do we check activecall == null?
  464. activecall = sess;
  465. startRtpStatsCollector();
  466. // Bind data channel listener in case we're a regular participant
  467. if (config.openSctp)
  468. {
  469. bindDataChannelListener(sess.peerconnection);
  470. }
  471. // TODO: check affiliation and/or role
  472. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  473. sess.usedrip = true; // not-so-naive trickle ice
  474. sess.sendAnswer();
  475. sess.accept();
  476. });
  477. $(document).bind('conferenceCreated.jingle', function (event, focus)
  478. {
  479. startRtpStatsCollector();
  480. });
  481. $(document).bind('conferenceCreated.jingle', function (event, focus)
  482. {
  483. // Bind data channel listener in case we're the focus
  484. if (config.openSctp)
  485. {
  486. bindDataChannelListener(focus.peerconnection);
  487. }
  488. });
  489. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  490. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  491. // ignore mixedmslabela0 and v0
  492. videoelem.show();
  493. VideoLayout.resizeThumbnails();
  494. // Update the large video to the last added video only if there's no
  495. // current active or focused speaker.
  496. if (!focusedVideoSrc && !VideoLayout.getDominantSpeakerResourceJid())
  497. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  498. VideoLayout.showFocusIndicator();
  499. }
  500. });
  501. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  502. // Leave the room if my call has been remotely terminated.
  503. if (connection.emuc.joined && focus == null && reason === 'kick') {
  504. sessionTerminated = true;
  505. connection.emuc.doLeave();
  506. openMessageDialog( "Session Terminated",
  507. "Ouch! You have been kicked out of the meet!");
  508. }
  509. });
  510. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  511. // put our ssrcs into presence so other clients can identify our stream
  512. var sess = connection.jingle.sessions[sid];
  513. var newssrcs = {};
  514. var directions = {};
  515. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  516. localSDP.media.forEach(function (media) {
  517. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  518. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  519. // assumes a single local ssrc
  520. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  521. newssrcs[type] = ssrc;
  522. directions[type] = (
  523. SDPUtil.find_line(media, 'a=sendrecv') ||
  524. SDPUtil.find_line(media, 'a=recvonly') ||
  525. SDPUtil.find_line(media, 'a=sendonly') ||
  526. SDPUtil.find_line(media, 'a=inactive') ||
  527. 'a=sendrecv').substr(2);
  528. }
  529. });
  530. console.log('new ssrcs', newssrcs);
  531. // Have to clear presence map to get rid of removed streams
  532. connection.emuc.clearPresenceMedia();
  533. var i = 0;
  534. Object.keys(newssrcs).forEach(function (mtype) {
  535. i++;
  536. var type = mtype;
  537. // Change video type to screen
  538. if (mtype === 'video' && isUsingScreenStream) {
  539. type = 'screen';
  540. }
  541. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  542. });
  543. if (i > 0) {
  544. connection.emuc.sendPresence();
  545. }
  546. });
  547. $(document).bind('joined.muc', function (event, jid, info) {
  548. updateRoomUrl(window.location.href);
  549. document.getElementById('localNick').appendChild(
  550. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  551. );
  552. if (Object.keys(connection.emuc.members).length < 1) {
  553. focus = new ColibriFocus(connection, config.hosts.bridge);
  554. if (nickname !== null) {
  555. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  556. nickname);
  557. }
  558. Toolbar.showRecordingButton(false);
  559. }
  560. if (focus && config.etherpad_base) {
  561. Etherpad.init();
  562. }
  563. VideoLayout.showFocusIndicator();
  564. // Once we've joined the muc show the toolbar
  565. Toolbar.showToolbar();
  566. var displayName = '';
  567. if (info.displayName)
  568. displayName = info.displayName + ' (me)';
  569. VideoLayout.setDisplayName('localVideoContainer', displayName);
  570. });
  571. $(document).bind('entered.muc', function (event, jid, info, pres) {
  572. console.log('entered', jid, info);
  573. console.log('is focus?' + focus ? 'true' : 'false');
  574. // Add Peer's container
  575. VideoLayout.ensurePeerContainerExists(jid);
  576. if (focus !== null) {
  577. // FIXME: this should prepare the video
  578. if (focus.confid === null) {
  579. console.log('make new conference with', jid);
  580. focus.makeConference(Object.keys(connection.emuc.members));
  581. Toolbar.showRecordingButton(true);
  582. } else {
  583. console.log('invite', jid, 'into conference');
  584. focus.addNewParticipant(jid);
  585. }
  586. }
  587. else if (sharedKey) {
  588. Toolbar.updateLockButton();
  589. }
  590. });
  591. $(document).bind('left.muc', function (event, jid) {
  592. console.log('left.muc', jid);
  593. // Need to call this with a slight delay, otherwise the element couldn't be
  594. // found for some reason.
  595. window.setTimeout(function () {
  596. var container = document.getElementById(
  597. 'participant_' + Strophe.getResourceFromJid(jid));
  598. if (container) {
  599. // hide here, wait for video to close before removing
  600. $(container).hide();
  601. VideoLayout.resizeThumbnails();
  602. }
  603. }, 10);
  604. // Unlock large video
  605. if (focusedVideoSrc)
  606. {
  607. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  608. {
  609. console.info("Focused video owner has left the conference");
  610. focusedVideoSrc = null;
  611. }
  612. }
  613. connection.jingle.terminateByJid(jid);
  614. if (focus == null
  615. // I shouldn't be the one that left to enter here.
  616. && jid !== connection.emuc.myroomjid
  617. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  618. // If our session has been terminated for some reason
  619. // (kicked, hangup), don't try to become the focus
  620. && !sessionTerminated) {
  621. console.log('welcome to our new focus... myself');
  622. focus = new ColibriFocus(connection, config.hosts.bridge);
  623. if (nickname !== null) {
  624. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  625. nickname);
  626. }
  627. if (Object.keys(connection.emuc.members).length > 0) {
  628. focus.makeConference(Object.keys(connection.emuc.members));
  629. Toolbar.showRecordingButton(true);
  630. }
  631. $(document).trigger('focusechanged.muc', [focus]);
  632. }
  633. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  634. console.log('everyone left');
  635. // FIXME: closing the connection is a hack to avoid some
  636. // problems with reinit
  637. disposeConference();
  638. focus = new ColibriFocus(connection, config.hosts.bridge);
  639. if (nickname !== null) {
  640. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  641. nickname);
  642. }
  643. Toolbar.showRecordingButton(false);
  644. }
  645. if (connection.emuc.getPrezi(jid)) {
  646. $(document).trigger('presentationremoved.muc',
  647. [jid, connection.emuc.getPrezi(jid)]);
  648. }
  649. });
  650. $(document).bind('presence.muc', function (event, jid, info, pres) {
  651. // Remove old ssrcs coming from the jid
  652. Object.keys(ssrc2jid).forEach(function (ssrc) {
  653. if (ssrc2jid[ssrc] == jid) {
  654. delete ssrc2jid[ssrc];
  655. }
  656. if (ssrc2videoType[ssrc] == jid) {
  657. delete ssrc2videoType[ssrc];
  658. }
  659. });
  660. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  661. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  662. var ssrcV = ssrc.getAttribute('ssrc');
  663. ssrc2jid[ssrcV] = jid;
  664. var type = ssrc.getAttribute('type');
  665. ssrc2videoType[ssrcV] = type;
  666. // might need to update the direction if participant just went from sendrecv to recvonly
  667. if (type === 'video' || type === 'screen') {
  668. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  669. switch (ssrc.getAttribute('direction')) {
  670. case 'sendrecv':
  671. el.show();
  672. break;
  673. case 'recvonly':
  674. el.hide();
  675. // FIXME: Check if we have to change large video
  676. //VideoLayout.checkChangeLargeVideo(el);
  677. break;
  678. }
  679. }
  680. });
  681. if (jid === connection.emuc.myroomjid) {
  682. VideoLayout.setDisplayName('localVideoContainer',
  683. info.displayName);
  684. } else {
  685. VideoLayout.ensurePeerContainerExists(jid);
  686. VideoLayout.setDisplayName(
  687. 'participant_' + Strophe.getResourceFromJid(jid),
  688. info.displayName);
  689. }
  690. if (focus !== null && info.displayName !== null) {
  691. focus.setEndpointDisplayName(jid, info.displayName);
  692. }
  693. });
  694. $(document).bind('passwordrequired.muc', function (event, jid) {
  695. console.log('on password required', jid);
  696. $.prompt('<h2>Password required</h2>' +
  697. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  698. persistent: true,
  699. buttons: { "Ok": true, "Cancel": false},
  700. defaultButton: 1,
  701. loaded: function (event) {
  702. document.getElementById('lockKey').focus();
  703. },
  704. submit: function (e, v, m, f) {
  705. if (v) {
  706. var lockKey = document.getElementById('lockKey');
  707. if (lockKey.value !== null) {
  708. setSharedKey(lockKey.value);
  709. connection.emuc.doJoin(jid, lockKey.value);
  710. }
  711. }
  712. }
  713. });
  714. });
  715. /**
  716. * Checks if video identified by given src is desktop stream.
  717. * @param videoSrc eg.
  718. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  719. * @returns {boolean}
  720. */
  721. function isVideoSrcDesktop(videoSrc) {
  722. // FIXME: fix this mapping mess...
  723. // figure out if large video is desktop stream or just a camera
  724. var isDesktop = false;
  725. if (localVideoSrc === videoSrc) {
  726. // local video
  727. isDesktop = isUsingScreenStream;
  728. } else {
  729. // Do we have associations...
  730. var videoSsrc = videoSrcToSsrc[videoSrc];
  731. if (videoSsrc) {
  732. var videoType = ssrc2videoType[videoSsrc];
  733. if (videoType) {
  734. // Finally there...
  735. isDesktop = videoType === 'screen';
  736. } else {
  737. console.error("No video type for ssrc: " + videoSsrc);
  738. }
  739. } else {
  740. console.error("No ssrc for src: " + videoSrc);
  741. }
  742. }
  743. return isDesktop;
  744. }
  745. function getConferenceHandler() {
  746. return focus ? focus : activecall;
  747. }
  748. function toggleVideo() {
  749. if (!(connection && connection.jingle.localVideo))
  750. return;
  751. var sess = getConferenceHandler();
  752. if (sess) {
  753. sess.toggleVideoMute(
  754. function (isMuted) {
  755. if (isMuted) {
  756. $('#video').removeClass("icon-camera");
  757. $('#video').addClass("icon-camera icon-camera-disabled");
  758. } else {
  759. $('#video').removeClass("icon-camera icon-camera-disabled");
  760. $('#video').addClass("icon-camera");
  761. }
  762. }
  763. );
  764. }
  765. sess = focus || activecall;
  766. if (!sess) {
  767. return;
  768. }
  769. sess.pendingop = ismuted ? 'unmute' : 'mute';
  770. // connection.emuc.addVideoInfoToPresence(!ismuted);
  771. // connection.emuc.sendPresence();
  772. sess.modifySources();
  773. }
  774. /**
  775. * Mutes / unmutes audio for the local participant.
  776. */
  777. function toggleAudio() {
  778. if (!(connection && connection.jingle.localAudio)) {
  779. preMuted = true;
  780. // We still click the button.
  781. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  782. return;
  783. }
  784. var localAudio = connection.jingle.localAudio;
  785. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  786. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  787. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  788. // isMuted is the opposite of audioEnabled
  789. connection.emuc.addAudioInfoToPresence(audioEnabled);
  790. connection.emuc.sendPresence();
  791. }
  792. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  793. }
  794. /**
  795. * Checks whether the audio is muted or not.
  796. * @returns {boolean} true if audio is muted and false if not.
  797. */
  798. function isAudioMuted()
  799. {
  800. var localAudio = connection.jingle.localAudio;
  801. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  802. if(localAudio.getAudioTracks()[idx].enabled === true)
  803. return false;
  804. }
  805. return true;
  806. }
  807. // Starts or stops the recording for the conference.
  808. function toggleRecording() {
  809. if (focus === null || focus.confid === null) {
  810. console.log('non-focus, or conference not yet organized: not enabling recording');
  811. return;
  812. }
  813. if (!recordingToken)
  814. {
  815. $.prompt('<h2>Enter recording token</h2>' +
  816. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  817. {
  818. persistent: false,
  819. buttons: { "Save": true, "Cancel": false},
  820. defaultButton: 1,
  821. loaded: function (event) {
  822. document.getElementById('recordingToken').focus();
  823. },
  824. submit: function (e, v, m, f) {
  825. if (v) {
  826. var token = document.getElementById('recordingToken');
  827. if (token.value) {
  828. setRecordingToken(Util.escapeHtml(token.value));
  829. toggleRecording();
  830. }
  831. }
  832. }
  833. }
  834. );
  835. return;
  836. }
  837. var oldState = focus.recordingEnabled;
  838. Toolbar.toggleRecordingButtonState();
  839. focus.setRecording(!oldState,
  840. recordingToken,
  841. function (state) {
  842. console.log("New recording state: ", state);
  843. if (state == oldState) //failed to change, reset the token because it might have been wrong
  844. {
  845. Toolbar.toggleRecordingButtonState();
  846. setRecordingToken(null);
  847. }
  848. }
  849. );
  850. }
  851. /**
  852. * Returns an array of the video horizontal and vertical indents,
  853. * so that if fits its parent.
  854. *
  855. * @return an array with 2 elements, the horizontal indent and the vertical
  856. * indent
  857. */
  858. function getCameraVideoPosition(videoWidth,
  859. videoHeight,
  860. videoSpaceWidth,
  861. videoSpaceHeight) {
  862. // Parent height isn't completely calculated when we position the video in
  863. // full screen mode and this is why we use the screen height in this case.
  864. // Need to think it further at some point and implement it properly.
  865. var isFullScreen = document.fullScreen ||
  866. document.mozFullScreen ||
  867. document.webkitIsFullScreen;
  868. if (isFullScreen)
  869. videoSpaceHeight = window.innerHeight;
  870. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  871. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  872. return [horizontalIndent, verticalIndent];
  873. }
  874. /**
  875. * Returns an array of the video horizontal and vertical indents.
  876. * Centers horizontally and top aligns vertically.
  877. *
  878. * @return an array with 2 elements, the horizontal indent and the vertical
  879. * indent
  880. */
  881. function getDesktopVideoPosition(videoWidth,
  882. videoHeight,
  883. videoSpaceWidth,
  884. videoSpaceHeight) {
  885. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  886. var verticalIndent = 0;// Top aligned
  887. return [horizontalIndent, verticalIndent];
  888. }
  889. /**
  890. * Returns an array of the video dimensions, so that it covers the screen.
  891. * It leaves no empty areas, but some parts of the video might not be visible.
  892. *
  893. * @return an array with 2 elements, the video width and the video height
  894. */
  895. function getCameraVideoSize(videoWidth,
  896. videoHeight,
  897. videoSpaceWidth,
  898. videoSpaceHeight) {
  899. if (!videoWidth)
  900. videoWidth = currentVideoWidth;
  901. if (!videoHeight)
  902. videoHeight = currentVideoHeight;
  903. var aspectRatio = videoWidth / videoHeight;
  904. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  905. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  906. if (availableWidth / aspectRatio < videoSpaceHeight) {
  907. availableHeight = videoSpaceHeight;
  908. availableWidth = availableHeight * aspectRatio;
  909. }
  910. if (availableHeight * aspectRatio < videoSpaceWidth) {
  911. availableWidth = videoSpaceWidth;
  912. availableHeight = availableWidth / aspectRatio;
  913. }
  914. return [availableWidth, availableHeight];
  915. }
  916. $(document).ready(function () {
  917. Chat.init();
  918. $('body').popover({ selector: '[data-toggle=popover]',
  919. trigger: 'click hover'});
  920. // Set the defaults for prompt dialogs.
  921. jQuery.prompt.setDefaults({persistent: false});
  922. // Set default desktop sharing method
  923. setDesktopSharing(config.desktopSharing);
  924. // Initialize Chrome extension inline installs
  925. if (config.chromeExtensionId) {
  926. initInlineInstalls();
  927. }
  928. // By default we use camera
  929. getVideoSize = getCameraVideoSize;
  930. getVideoPosition = getCameraVideoPosition;
  931. VideoLayout.resizeLargeVideoContainer();
  932. $(window).resize(function () {
  933. VideoLayout.resizeLargeVideoContainer();
  934. VideoLayout.positionLarge();
  935. });
  936. // Listen for large video size updates
  937. document.getElementById('largeVideo')
  938. .addEventListener('loadedmetadata', function (e) {
  939. currentVideoWidth = this.videoWidth;
  940. currentVideoHeight = this.videoHeight;
  941. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  942. });
  943. if (!$('#settings').is(':visible')) {
  944. console.log('init');
  945. init();
  946. } else {
  947. loginInfo.onsubmit = function (e) {
  948. if (e.preventDefault) e.preventDefault();
  949. $('#settings').hide();
  950. init();
  951. };
  952. }
  953. });
  954. $(window).bind('beforeunload', function () {
  955. if (connection && connection.connected) {
  956. // ensure signout
  957. $.ajax({
  958. type: 'POST',
  959. url: config.bosh,
  960. async: false,
  961. cache: false,
  962. contentType: 'application/xml',
  963. 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>",
  964. success: function (data) {
  965. console.log('signed out');
  966. console.log(data);
  967. },
  968. error: function (XMLHttpRequest, textStatus, errorThrown) {
  969. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  970. }
  971. });
  972. }
  973. disposeConference(true);
  974. });
  975. function disposeConference(onUnload) {
  976. var handler = getConferenceHandler();
  977. if (handler && handler.peerconnection) {
  978. // FIXME: probably removing streams is not required and close() should be enough
  979. if (connection.jingle.localAudio) {
  980. handler.peerconnection.removeStream(connection.jingle.localAudio);
  981. }
  982. if (connection.jingle.localVideo) {
  983. handler.peerconnection.removeStream(connection.jingle.localVideo);
  984. }
  985. handler.peerconnection.close();
  986. }
  987. stopRTPStatsCollector();
  988. if(onUnload) {
  989. stopLocalRtpStatsCollector();
  990. }
  991. focus = null;
  992. activecall = null;
  993. }
  994. function dump(elem, filename) {
  995. elem = elem.parentNode;
  996. elem.download = filename || 'meetlog.json';
  997. elem.href = 'data:application/json;charset=utf-8,\n';
  998. var data = {};
  999. if (connection.jingle) {
  1000. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1001. var session = connection.jingle.sessions[sid];
  1002. if (session.peerconnection && session.peerconnection.updateLog) {
  1003. // FIXME: should probably be a .dump call
  1004. data["jingle_" + session.sid] = {
  1005. updateLog: session.peerconnection.updateLog,
  1006. stats: session.peerconnection.stats,
  1007. url: window.location.href
  1008. };
  1009. }
  1010. });
  1011. }
  1012. metadata = {};
  1013. metadata.time = new Date();
  1014. metadata.url = window.location.href;
  1015. metadata.ua = navigator.userAgent;
  1016. if (connection.logger) {
  1017. metadata.xmpp = connection.logger.log;
  1018. }
  1019. data.metadata = metadata;
  1020. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1021. return false;
  1022. }
  1023. /**
  1024. * Changes the style class of the element given by id.
  1025. */
  1026. function buttonClick(id, classname) {
  1027. $(id).toggleClass(classname); // add the class to the clicked element
  1028. }
  1029. /**
  1030. * Shows a message to the user.
  1031. *
  1032. * @param titleString the title of the message
  1033. * @param messageString the text of the message
  1034. */
  1035. function openMessageDialog(titleString, messageString) {
  1036. $.prompt(messageString,
  1037. {
  1038. title: titleString,
  1039. persistent: false
  1040. }
  1041. );
  1042. }
  1043. /**
  1044. * Locks / unlocks the room.
  1045. */
  1046. function lockRoom(lock) {
  1047. if (lock)
  1048. connection.emuc.lockRoom(sharedKey);
  1049. else
  1050. connection.emuc.lockRoom('');
  1051. Toolbar.updateLockButton();
  1052. }
  1053. /**
  1054. * Sets the shared key.
  1055. */
  1056. function setSharedKey(sKey) {
  1057. sharedKey = sKey;
  1058. }
  1059. function setRecordingToken(token) {
  1060. recordingToken = token;
  1061. }
  1062. /**
  1063. * Updates the room invite url.
  1064. */
  1065. function updateRoomUrl(newRoomUrl) {
  1066. roomUrl = newRoomUrl;
  1067. // If the invite dialog has been already opened we update the information.
  1068. var inviteLink = document.getElementById('inviteLinkRef');
  1069. if (inviteLink) {
  1070. inviteLink.value = roomUrl;
  1071. inviteLink.select();
  1072. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1073. }
  1074. }
  1075. /**
  1076. * Warning to the user that the conference window is about to be closed.
  1077. */
  1078. function closePageWarning() {
  1079. if (focus !== null)
  1080. return "You are the owner of this conference call and"
  1081. + " you are about to end it.";
  1082. else
  1083. return "You are about to leave this conversation.";
  1084. }
  1085. /**
  1086. * Resizes and repositions videos in full screen mode.
  1087. */
  1088. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1089. function () {
  1090. VideoLayout.resizeLargeVideoContainer();
  1091. VideoLayout.positionLarge();
  1092. isFullScreen = document.fullScreen ||
  1093. document.mozFullScreen ||
  1094. document.webkitIsFullScreen;
  1095. if (isFullScreen) {
  1096. setView("fullscreen");
  1097. }
  1098. else {
  1099. setView("default");
  1100. }
  1101. }
  1102. );
  1103. /**
  1104. * Sets the current view.
  1105. */
  1106. function setView(viewName) {
  1107. // if (viewName == "fullscreen") {
  1108. // document.getElementById('videolayout_fullscreen').disabled = false;
  1109. // document.getElementById('videolayout_default').disabled = true;
  1110. // }
  1111. // else {
  1112. // document.getElementById('videolayout_default').disabled = false;
  1113. // document.getElementById('videolayout_fullscreen').disabled = true;
  1114. // }
  1115. }
  1116. $(document).bind('fatalError.jingle',
  1117. function (event, session, error)
  1118. {
  1119. sessionTerminated = true;
  1120. connection.emuc.doLeave();
  1121. openMessageDialog( "Sorry",
  1122. "Your browser version is too old. Please update and try again...");
  1123. }
  1124. );