jam-cloud/web/app/assets/javascripts/session.js

1706 lines
74 KiB
JavaScript
Raw Normal View History

(function(context,$) {
"use strict";
context.JK = context.JK || {};
context.JK.SessionScreen = function(app) {
var EVENTS = context.JK.EVENTS;
2014-11-11 22:21:29 +00:00
var MIX_MODES = context.JK.MIX_MODES;
var NAMED_MESSAGES = context.JK.NAMED_MESSAGES;
var gearUtils = context.JK.GearUtils;
var sessionUtils = context.JK.SessionUtils;
2014-11-11 22:21:29 +00:00
var modUtils = context.JK.ModUtils;
var logger = context.JK.logger;
var self = this;
var sessionModel = null;
var sessionId;
var tracks = {};
2013-05-15 05:59:09 +00:00
var myTracks = [];
2014-11-17 23:16:30 +00:00
var masterMixers = [];
var personalMixers = [];
var configureTrackDialog;
var addNewGearDialog;
2014-01-05 03:47:23 +00:00
var localRecordingsDialog = null;
var recordingFinishedDialog = null;
2014-01-13 16:11:26 +00:00
var friendSelectorDialog = null;
2014-01-14 06:12:00 +00:00
var inviteMusiciansUtil = null;
2013-05-31 02:07:33 +00:00
var screenActive = false;
var currentMixerRangeMin = null;
var currentMixerRangeMax = null;
var lookingForMixersCount = 0;
var lookingForMixersTimer = null;
var lookingForMixers = {};
var $recordingTimer = null;
var recordingTimerInterval = null;
var startTimeDate = null;
var startingRecording = false; // double-click guard
2014-01-05 03:47:23 +00:00
var claimedRecording = null;
var playbackControls = null;
var promptLeave = false;
2014-05-01 01:48:57 +00:00
var rateSessionDialog = null;
var friendInput = null;
var sessionPageDone = null;
var $recordingManagerViewer = null;
var $screen = null;
2014-11-09 15:13:22 +00:00
var $mixModeDropdown = null;
2014-11-11 22:21:29 +00:00
var $templateMixerModeChange = null;
2014-11-11 22:21:29 +00:00
var rest = context.JK.Rest();
var RENDER_SESSION_DELAY = 750; // When I need to render a session, I have to wait a bit for the mixers to be there.
var defaultParticipant = {
tracks: [{
instrument_id: "unknown"
}],
user: {
first_name: 'Unknown',
last_name: 'User',
photo_url: null
}
};
// Be sure to copy/extend these instead of modifying in place
var trackVuOpts = {
vuType: "vertical",
lightCount: 13,
lightWidth: 3,
lightHeight: 17
};
// Must add faderId key to this
var trackFaderOpts = {
faderType: "vertical",
height: 83
};
2013-02-26 03:54:09 +00:00
// Recreate ChannelGroupIDs ENUM from C++
var ChannelGroupIds = {
"MasterGroup": 0,
"MonitorGroup": 1,
"AudioInputMusicGroup": 2,
"AudioInputChatGroup": 3,
"MediaTrackGroup": 4,
"StreamOutMusicGroup": 5,
"StreamOutChatGroup": 6,
"UserMusicInputGroup": 7,
"UserChatInputGroup": 8,
2013-09-11 22:29:32 +00:00
"PeerAudioInputMusicGroup": 9,
"PeerMediaTrackGroup": 10
2013-02-26 03:54:09 +00:00
};
function beforeShow(data) {
sessionId = data.id;
if(!sessionId) {
window.location = '/client#/home';
}
promptLeave = true;
$('#session-mytracks-container').empty();
displayDoneRecording(); // assumption is that you can't join a recording session, so this should be safe
2014-02-07 05:57:31 +00:00
var shareDialog = new JK.ShareDialog(context.JK.app, sessionId, "session");
shareDialog.initialize(context.JK.FacebookHelperInstance);
}
2014-04-09 17:25:52 +00:00
function beforeDisconnect() {
return { freezeInteraction: true };
}
function initializeSession() {
// Subscribe for callbacks on audio events
context.jamClient.SessionRegisterCallback("JK.HandleBridgeCallback");
context.jamClient.RegisterRecordingCallbacks("JK.HandleRecordingStartResult", "JK.HandleRecordingStopResult", "JK.HandleRecordingStarted", "JK.HandleRecordingStopped", "JK.HandleRecordingAborted");
context.jamClient.SessionSetConnectionStatusRefreshRate(1000);
// If you load this page directly, the loading of the current user
// is happening in parallel. We can't join the session until the
// current user has been completely loaded. Poll for the current user
// before proceeding with session joining.
function checkForCurrentUser() {
if (context.JK.userMe) {
afterCurrentUserLoaded();
} else {
context.setTimeout(checkForCurrentUser, 100);
}
}
checkForCurrentUser();
}
function afterShow(data) {
2013-05-31 02:07:33 +00:00
2014-06-26 02:50:20 +00:00
if(!context.JK.JamServer.connected) {
promptLeave = false;
app.notifyAlert("Not Connected", 'To create or join a session, you must be connected to the server.');
window.location = '/client#/home'
return;
}
2014-04-09 17:25:52 +00:00
// The SessionModel is a singleton.
// a client can only be in one session at a time,
// and other parts of the code want to know at any certain times
// about the current session, if any (for example, reconnect logic)
if(context.JK.CurrentSessionModel) {
context.JK.CurrentSessionModel.ensureEnded();
}
context.JK.CurrentSessionModel = sessionModel = new context.JK.SessionModel(
context.JK.app,
context.JK.JamServer,
context.jamClient,
self
);
sessionModel.start(sessionId);
// indicate that the screen is active, so that
// body-scoped drag handlers can go active
screenActive = true;
gearUtils.guardAgainstInvalidConfiguration(app)
.fail(function() {
promptLeave = false;
window.location = '/client#/home'
})
.done(function(){
var result = sessionUtils.SessionPageEnter();
gearUtils.guardAgainstActiveProfileMissing(app, result)
.fail(function(data) {
promptLeave = false;
if(data && data.reason == 'handled') {
if(data.nav == 'BACK') {
window.history.go(-1);
}
else {
window.location = data.nav;
}
}
else {
window.location = '/client#/home';
}
})
.done(function(){
sessionModel.waitForSessionPageEnterDone()
.done(function(userTracks) {
context.JK.CurrentSessionModel.setUserTracks(userTracks);
initializeSession();
})
.fail(function(data) {
if(data == "timeout") {
context.JK.alertSupportedNeeded('The audio system has not reported your configured tracks in a timely fashion.')
}
else if(data == 'session_over') {
// do nothing; session ended before we got the user track info. just bail
}
else {
contetx.JK.alertSupportedNeeded('Unable to determine configured tracks due to reason: ' + data)
}
promptLeave = false;
window.location = '/client#/home'
});
})
})
2013-02-26 03:54:09 +00:00
}
2013-11-16 04:35:40 +00:00
function notifyWithUserInfo(title , text, clientId) {
sessionModel.findUserBy({clientId: clientId})
.done(function(user) {
app.notify({
"title": title,
"text": user.name + " " + text,
"icon_url": context.JK.resolveAvatarUrl(user.photo_url)
});
})
.fail(function() {
app.notify({
"title": title,
"text": 'Someone ' + text,
"icon_url": "/assets/content/icon_alert_big.png"
});
});
}
2013-02-26 03:54:09 +00:00
function afterCurrentUserLoaded() {
var sessionModel = context.JK.CurrentSessionModel;
$(sessionModel.recordingModel)
.on('startingRecording', function(e, data) {
2013-11-16 04:35:40 +00:00
displayStartingRecording();
})
.on('startedRecording', function(e, data) {
if(data.reason) {
2013-11-16 04:35:40 +00:00
var reason = data.reason;
var detail = data.detail;
var title = "Could Not Start Recording";
if(data.reason == 'client-no-response') {
notifyWithUserInfo(title, 'did not respond to the start signal.', detail);
}
else if(data.reason == 'empty-recording-id') {
app.notifyAlert(title, "No recording ID specified.");
}
else if(data.reason == 'missing-client') {
notifyWithUserInfo(title, 'could not be signalled to start recording.', detail);
}
else if(data.reason == 'already-recording') {
app.notifyAlert(title, 'Already recording. If this appears incorrect, try restarting JamKazam.');
2013-11-16 04:35:40 +00:00
}
else if(data.reason == 'recording-engine-unspecified') {
notifyWithUserInfo(title, 'had a problem writing recording data to disk.', detail);
}
else if(data.reason == 'recording-engine-create-directory') {
notifyWithUserInfo(title, 'had a problem creating a recording folder.', detail);
}
else if(data.reason == 'recording-engine-create-file') {
notifyWithUserInfo(title, 'had a problem creating a recording file.', detail);
}
else if(data.reason == 'recording-engine-sample-rate') {
notifyWithUserInfo(title, 'had a problem recording at the specified sample rate.', detail);
}
2014-01-05 03:47:23 +00:00
else if(data.reason == 'rest') {
var jqXHR = detail[0];
app.notifyServerError(jqXHR);
}
2013-11-16 04:35:40 +00:00
else {
notifyWithUserInfo(title, 'Error Reason: ' + reason);
}
displayDoneRecording();
}
2013-11-16 04:35:40 +00:00
else
{
displayStartedRecording();
displayWhoCreated(data.clientId);
}
})
.on('stoppingRecording', function(e, data) {
displayStoppingRecording(data);
})
.on('stoppedRecording', function(e, data) {
if(data.reason) {
2014-05-19 23:49:02 +00:00
logger.warn("Recording Discarded: ", data);
var reason = data.reason;
2013-11-16 04:35:40 +00:00
var detail = data.detail;
var title = "Recording Discarded";
if(data.reason == 'client-no-response') {
2013-11-16 04:35:40 +00:00
notifyWithUserInfo(title, 'did not respond to the stop signal.', detail);
}
2013-11-16 04:35:40 +00:00
else if(data.reason == 'missing-client') {
notifyWithUserInfo(title, 'could not be signalled to stop recording.', detail);
}
else if(data.reason == 'empty-recording-id') {
app.notifyAlert(title, "No recording ID specified.");
}
else if(data.reason == 'wrong-recording-id') {
app.notifyAlert(title, "Wrong recording ID specified.");
}
else if(data.reason == 'not-recording') {
app.notifyAlert(title, "Not currently recording.");
}
else if(data.reason == 'already-stopping') {
app.notifyAlert(title, "Already stopping the current recording.");
}
else if(data.reason == 'start-before-stop') {
notifyWithUserInfo(title, 'asked that we start a new recording; cancelling the current one.', detail);
}
else {
app.notifyAlert(title, "Error reason: " + reason);
}
displayDoneRecording();
}
else {
displayDoneRecording();
promptUserToSave(data.recordingId);
}
})
2013-11-16 04:35:40 +00:00
.on('abortedRecording', function(e, data) {
var reason = data.reason;
var detail = data.detail;
2013-11-16 04:35:40 +00:00
var title = "Recording Cancelled";
2013-11-16 04:35:40 +00:00
if(data.reason == 'client-no-response') {
notifyWithUserInfo(title, 'did not respond to the start signal.', detail);
}
else if(data.reason == 'missing-client') {
notifyWithUserInfo(title, 'could not be signalled to start recording.', detail);
}
else if(data.reason == 'populate-recording-info') {
notifyWithUserInfo(title, 'could not synchronize with the server.', detail);
}
else if(data.reason == 'recording-engine-unspecified') {
notifyWithUserInfo(title, 'had a problem writing recording data to disk.', detail);
}
else if(data.reason == 'recording-engine-create-directory') {
notifyWithUserInfo(title, 'had a problem creating a recording folder.', detail);
}
else if(data.reason == 'recording-engine-create-file') {
notifyWithUserInfo(title, 'had a problem creating a recording file.', detail);
}
else if(data.reason == 'recording-engine-sample-rate') {
notifyWithUserInfo(title, 'had a problem recording at the specified sample rate.', detail);
}
else {
app.notifyAlert(title, "Error reason: " + reason);
}
displayDoneRecording();
})
sessionModel.subscribe('sessionScreen', sessionChanged);
sessionModel.joinSession(sessionId)
.fail(function(xhr, textStatus, errorMessage) {
if(xhr.status == 404) {
// we tried to join the session, but it's already gone. kick user back to join session screen
promptLeave = false;
2014-02-06 13:03:44 +00:00
context.window.location = "/client#/findSession";
app.notify(
{ title: "Unable to Join Session",
text: "The session you attempted to join is over."
},
null,
true);
}
else if(xhr.status == 422) {
var response = JSON.parse(xhr.responseText);
if(response["errors"] && response["errors"]["tracks"] && response["errors"]["tracks"][0] == "Please select at least one track") {
app.notifyAlert("No Inputs Configured", $('<span>You will need to reconfigure your audio device.</span>'));
}
else if(response["errors"] && response["errors"]["music_session"] && response["errors"]["music_session"][0] == ["is currently recording"]) {
promptLeave = false;
context.window.location = "/client#/findSession";
app.notify( { title: "Unable to Join Session", text: "The session is currently recording." }, null, true);
}
else {
app.notifyServerError(xhr, 'Unable to Join Session');
}
}
else {
app.notifyServerError(xhr, 'Unable to Join Session');
}
});
}
2014-02-25 02:20:17 +00:00
// not leave session but leave screen
function beforeLeave(data) {
if(promptLeave) {
var leaveSessionWarningDialog = new context.JK.LeaveSessionWarningDialog(context.JK.app,
function() { promptLeave = false; context.location.hash = data.hash });
leaveSessionWarningDialog.initialize();
app.layout.showDialog('leave-session-warning');
return false;
}
2014-02-25 19:22:32 +00:00
return true;
}
function beforeHide(data) {
if(screenActive) {
// this path is possible if FTUE is invoked on session page, and they cancel
sessionModel.leaveCurrentSession()
.fail(function(jqXHR) {
if(jqXHR.status != 404) {
logger.debug("leave session failed");
app.ajaxError(arguments)
}
});
}
screenActive = false;
sessionUtils.SessionPageLeave();
}
2014-01-05 03:47:23 +00:00
function handleTransitionsInRecordingPlayback() {
// let's see if we detect a transition to start playback or stop playback
var currentSession = sessionModel.getCurrentSession();
if(claimedRecording == null && (currentSession && currentSession.claimed_recording != null)) {
// this is a 'started with a claimed_recording' transition.
// we need to start a timer to watch for the state of the play session
playbackControls.startMonitor();
2014-01-05 03:47:23 +00:00
}
else if(claimedRecording && (currentSession == null || currentSession.claimed_recording == null)) {
playbackControls.stopMonitor();
2014-01-05 03:47:23 +00:00
}
claimedRecording = currentSession == null ? null : currentSession.claimed_recording;
}
function sessionChanged() {
2014-01-05 03:47:23 +00:00
handleTransitionsInRecordingPlayback();
// TODO - in the specific case of a user changing their tracks using the configureTrack dialog,
// this event appears to fire before the underlying mixers have updated. I have no event to
// know definitively when the underlying mixers are up to date, so for now, we just delay slightly.
// This obviously has the possibility of introducing time-based bugs.
context.setTimeout(renderSession, RENDER_SESSION_DELAY);
}
/**
* the mixers object is a list. In order to find one by key,
* you must iterate. Convenience method to locate a particular
* mixer by id.
*/
2014-11-17 23:16:30 +00:00
function getMixer(mixerId, mixMode) {
var foundMixer = null;
2014-11-17 23:16:30 +00:00
var mixers = mixMode == MIX_MODES.MASTER ? masterMixers : personalMixers;
$.each(mixers, function(index, mixer) {
if (mixer.id === mixerId) {
foundMixer = mixer;
}
});
return foundMixer;
}
function renderSession() {
$('#session-mytracks-container').empty();
$('.session-track').remove(); // Remove previous tracks
var $voiceChat = $('#voice-chat');
$voiceChat.hide();
2013-01-30 16:50:43 +00:00
_updateMixers();
_renderTracks();
2014-01-05 03:47:23 +00:00
_renderLocalMediaTracks();
2013-02-07 04:58:41 +00:00
_wireTopVolume();
2013-04-10 15:01:29 +00:00
_wireTopMix();
2013-02-07 04:58:41 +00:00
_addVoiceChat();
_initDialogs();
if ($('.session-livetracks .track').length === 0) {
$('.session-livetracks .when-empty').show();
}
2014-01-05 03:47:23 +00:00
if ($('.session-recordings .track').length === 0) {
$('.session-recordings .when-empty').show();
$('.session-recording-name-wrapper').hide();
$('.session-recordings .recording-controls').hide();
2014-01-05 03:47:23 +00:00
}
}
2013-05-12 05:43:36 +00:00
function _initDialogs() {
configureTrackDialog.initialize();
addNewGearDialog.initialize();
2013-01-30 16:50:43 +00:00
}
// Get the latest list of underlying audio mixer channels
function _updateMixers() {
2014-11-11 22:21:29 +00:00
2014-11-17 23:16:30 +00:00
masterMixers = context.jamClient.SessionGetAllControlState(true);
//var holder = $.extend(true, {}, {mixers: context.jamClient.SessionGetControlState(masterMixerIds, true)});
//masterMixers = masterMixerIds.mixers;
personalMixers = context.jamClient.SessionGetAllControlState(false);
//holder = $.extend(true, {}, {mixers: context.jamClient.SessionGetControlState(personalMixerIds, false)});
//personalMixers = personalMixerIds.mixers;
2014-11-11 22:21:29 +00:00
2014-11-17 23:16:30 +00:00
console.log("masterMixers", masterMixers)
console.log("personalMixers", personalMixers)
2013-04-10 15:01:29 +00:00
// Always add a hard-coded simplified 'mixer' for the L2M mix
2014-11-09 15:13:22 +00:00
2014-11-11 22:21:29 +00:00
/**
var l2m_mixer = {
id: '__L2M__',
range_low: -80,
range_high: 20,
volume_left: context.jamClient.SessionGetMasterLocalMix()
};
mixers.push(l2m_mixer);*/
}
2014-11-17 23:16:30 +00:00
function _mixersForGroupId(groupId, mixMode) {
2014-01-05 03:47:23 +00:00
var foundMixers = [];
2014-11-17 23:16:30 +00:00
var mixers = mixMode == MIX_MODES.MASTER ? masterMixers : personalMixers;
2014-01-05 03:47:23 +00:00
$.each(mixers, function(index, mixer) {
2014-11-17 23:16:30 +00:00
if ( mixer.group_id === groupId) {
2014-01-05 03:47:23 +00:00
foundMixers.push(mixer);
}
});
return foundMixers;
}
2014-11-17 23:16:30 +00:00
function _clientIdForUserInputMixer(mixerId, mixMode) {
var found = null;
2014-11-17 23:16:30 +00:00
var mixers = mixMode == MIX_MODES.MASTER ? masterMixers : personalMixers;
$.each(mixers, function(index, mixer) {
if (mixer.group_id === ChannelGroupIds.UserMusicInputGroup && mixer.id == mixerId) {
found = mixer.client_id;
return false;
}
});
return found;
}
// TODO FIXME - This needs to support multiple tracks for an individual
// client id and group.
function _mixerForClientId(clientId, groupIds, usedMixers) {
2014-06-20 17:50:31 +00:00
//logger.debug("clientId", clientId, "groupIds", groupIds, "mixers", mixers)
var foundMixer = null;
$.each(mixers, function(index, mixer) {
if (mixer.client_id === clientId) {
for (var i=0; i<groupIds.length; i++) {
if (mixer.group_id === groupIds[i]) {
if (!(mixer.id in usedMixers)) {
foundMixer = mixer;
return false;
}
}
}
}
});
return foundMixer;
2013-01-30 16:50:43 +00:00
}
2014-11-17 23:16:30 +00:00
function _groupedMixersForClientId(clientId, groupIds, usedMixers, mixMode) {
2014-11-12 02:39:46 +00:00
//logger.debug("clientId", clientId, "groupIds", groupIds, "mixers", mixers)
var foundMixers = {};
2014-11-17 23:16:30 +00:00
var mixers = mixMode == MIX_MODES.MASTER ? masterMixers : personalMixers;
console.log("_groupedMixersForClientId", mixers)
2014-11-12 02:39:46 +00:00
$.each(mixers, function(index, mixer) {
if (mixer.client_id === clientId) {
for (var i=0; i<groupIds.length; i++) {
if (mixer.group_id === groupIds[i]) {
if ((mixer.groupId != ChannelGroupIds.UserMusicInputGroup) && !(mixer.id in usedMixers)) {
var mixers = foundMixers[mixer.group_id]
if(!mixers) {
mixers = []
foundMixers[mixer.group_id] = mixers;
}
mixers.push(mixer)
}
}
}
}
});
return foundMixers;
}
2013-02-07 04:58:41 +00:00
function _wireTopVolume() {
var gainPercent = 0;
2013-03-14 03:29:57 +00:00
var mixerIds = [];
2014-11-17 23:16:30 +00:00
var mixers = sessionModel.isMasterMixMode() ? masterMixers : personalMixers;
2013-02-07 04:58:41 +00:00
$.each(mixers, function(index, mixer) {
2014-11-11 22:21:29 +00:00
if (sessionModel.isMasterMixMode() && mixer.group_id === ChannelGroupIds.MasterGroup) {
2013-03-14 03:29:57 +00:00
mixerIds.push(mixer.id);
gainPercent = percentFromMixerValue(
mixer.range_low, mixer.range_high, mixer.volume_left);
2013-02-07 04:58:41 +00:00
}
2014-11-11 22:21:29 +00:00
else if (!sessionModel.isMasterMixMode() && mixer.group_id === ChannelGroupIds.MonitorGroup) {
2013-03-14 03:29:57 +00:00
mixerIds.push(mixer.id);
2014-11-11 22:21:29 +00:00
gainPercent = percentFromMixerValue(
mixer.range_low, mixer.range_high, mixer.volume_left);
2013-02-07 04:58:41 +00:00
}
});
2014-11-17 23:16:30 +00:00
if(mixerIds.length == 0) {
logger.debug("did not find master/monitor volume", mixers)
}
var faderId = mixerIds.join(',');
2014-06-13 17:51:03 +00:00
var $volume = $('#volume');
$volume.attr('mixer-id', faderId);
var faderOpts = {
faderId: faderId,
faderType: "horizontal",
width: 50,
style: {
"background-image": "none",
"background-repeat":"no-repeat",
"height": "24px"
}
};
2014-06-13 17:51:03 +00:00
context.JK.FaderHelpers.renderFader($volume, faderOpts);
$volume.on('fader_change', faderChanged);
// Visually update fader to underlying mixer start value.
// Always do this, even if gainPercent is zero.
context.JK.FaderHelpers.setFaderValue(faderId, gainPercent);
2013-02-07 04:58:41 +00:00
}
2013-04-10 15:01:29 +00:00
/**
* This control has it's own Set/Get methods, so we don't need to
* line it up with some mixer later. We'll use a special mixer-id value
* to let us know we're dealing with the mix control.
*/
function _wireTopMix() {
var $mixSlider = $('#l2m');
var l2m_mixer = {
range_low: -80,
range_high: 20,
volume_left: context.jamClient.SessionGetMasterLocalMix()
};
2013-09-05 21:51:29 +00:00
// var gainPercent = percentFromMixerValue(
// l2m_mixer.range_low, l2m_mixer.range_high, l2m_mixer.volume_left);
var faderId = '#l2m'; // also the selector for renderFader
var faderOpts = {
faderId: faderId,
faderType: "horizontal",
width: 70,
style: {
"background-image": "none",
"background-repeat":"no-repeat",
"height": "24px"
}
};
2014-06-13 17:51:03 +00:00
context.JK.FaderHelpers.renderFader($mixSlider, faderOpts);
$mixSlider.on('fader_change', l2mChanged);
2013-09-05 21:51:29 +00:00
var value = context.jamClient.SessionGetMasterLocalMix();
context.JK.FaderHelpers.setFaderValue(faderId, percentFromMixerValue(-80, 20, value));
}
/**
* This has a specialized jamClient call, so custom handler.
*/
2014-06-13 17:51:03 +00:00
function l2mChanged(e, data) {
//var dbValue = context.JK.FaderHelpers.convertLinearToDb(newValue);
2014-06-13 17:51:03 +00:00
context.jamClient.SessionSetMasterLocalMix(data.percentage - 80);
2013-04-10 15:01:29 +00:00
}
2013-02-07 04:58:41 +00:00
function _addVoiceChat() {
// If, and only if, there is a mixer in group 3 (voice chat)
// Add the voice chat controls below my tracks, and hook up the mixer.
// Assumption is that there is only ever one, so we just take the first one.
2014-11-17 23:16:30 +00:00
var mixers = sessionModel.isMasterMixMode() ? masterMixers : personalMixers;
$.each(mixers, function(index, mixer) {
2013-02-26 03:54:09 +00:00
if (mixer.group_id === ChannelGroupIds.AudioInputChatGroup) {
var $voiceChat = $('#voice-chat');
$voiceChat.show();
$voiceChat.attr('mixer-id', mixer.id);
2014-06-13 17:51:03 +00:00
var $voiceChatGain = $voiceChat.find('.voicechat-gain');
$voiceChatGain.attr('mixer-id', mixer.id);
2014-06-13 17:51:03 +00:00
var $voiceChatMute = $voiceChat.find('.voicechat-mute').attr('mixer-id', mixer.id);
var gainPercent = percentFromMixerValue(
mixer.range_low, mixer.range_high, mixer.volume_left);
var faderOpts = {
faderId: mixer.id,
faderType: "horizontal",
width: 50
};
2014-06-13 17:51:03 +00:00
context.JK.FaderHelpers.renderFader($voiceChatGain, faderOpts);
$voiceChatGain.on('fader_change', faderChanged);
context.JK.FaderHelpers.setFaderValue(mixer.id, gainPercent);
2014-11-12 14:46:21 +00:00
//if (mixer.mute) {
_toggleVisualMuteControl($voiceChatMute, mixer, null);
//}
}
});
2013-02-07 04:58:41 +00:00
}
2014-01-05 03:47:23 +00:00
function _renderLocalMediaTracks() {
2014-11-17 23:16:30 +00:00
var localMediaMixers = _mixersForGroupId(ChannelGroupIds.MediaTrackGroup, sessionModel.getMixMode());
2014-01-05 03:47:23 +00:00
if(localMediaMixers.length == 0) {
2014-11-17 23:16:30 +00:00
localMediaMixers = _mixersForGroupId(ChannelGroupIds.PeerMediaTrackGroup, sessionModel.getMixMode());
2014-01-05 03:47:23 +00:00
}
var recordedTracks = sessionModel.recordedTracks();
if(recordedTracks && localMediaMixers.length == 0) {
// if we are the creator, then rather than raise an error, tell the server the recording is over.
// this shoudl only happen if we get temporarily disconnected by forced reload, which isn't a very normal scenario
if(sessionModel.getCurrentSession().claimed_recording_initiator_id == context.JK.userMe.id) {
closeRecording();
return;
}
}
if(recordedTracks) {
$('.session-recording-name').text(sessionModel.getCurrentSession().claimed_recording.name);
var noCorrespondingTracks = false;
$.each(localMediaMixers, function(index, mixer) {
var preMasteredClass = "";
// find the track or tracks that correspond to the mixer
var correspondingTracks = []
$.each(recordedTracks, function(i, recordedTrack) {
if(mixer.id.indexOf("L") == 0) {
if(mixer.id.substring(1) == recordedTrack.client_track_id) {
correspondingTracks.push(recordedTrack);
}
}
else if(mixer.id.indexOf("C") == 0) {
if(mixer.id.substring(1) == recordedTrack.client_id) {
correspondingTracks.push(recordedTrack);
preMasteredClass = "pre-mastered-track";
}
}
else {
// this should not be possible
alert("Invalid state: the recorded track had neither persisted_track_id or persisted_client_id");
}
});
if(correspondingTracks.length == 0) {
noCorrespondingTracks = true;
app.notify({
title: "Unable to Open Recording",
text: "Could not correlate server and client tracks",
icon_url: "/assets/content/icon_alert_big.png"});
return false;
}
// prune found recorded tracks
recordedTracks = $.grep(recordedTracks, function(value) {
return $.inArray(value, correspondingTracks) < 0;
});
var oneOfTheTracks = correspondingTracks[0];
var instrumentIcon = context.JK.getInstrumentIcon45(oneOfTheTracks.instrument_id);
var photoUrl = "/assets/content/icon_recording.png";
var name = oneOfTheTracks.user.name;
if (!(name)) {
name = oneOfTheTracks.user.first_name + ' ' + oneOfTheTracks.user.last_name;
}
// Default trackData to participant + no Mixer state.
var trackData = {
trackId: oneOfTheTracks.id,
clientId: oneOfTheTracks.client_id,
name: name,
instrumentIcon: instrumentIcon,
avatar: photoUrl,
latency: "good",
gainPercent: 0,
muteClass: 'muted',
mixerId: "",
avatarClass : 'avatar-recording',
preMasteredClass: preMasteredClass
};
var gainPercent = percentFromMixerValue(
mixer.range_low, mixer.range_high, mixer.volume_left);
var muteClass = "enabled";
if (mixer.mute) {
muteClass = "muted";
}
trackData.gainPercent = gainPercent;
trackData.muteClass = muteClass;
trackData.mixerId = mixer.id;
_addMediaTrack(trackData);
2014-01-05 03:47:23 +00:00
});
if(!noCorrespondingTracks && recordedTracks.length > 0) {
logger.error("unable to find all recorded tracks against client tracks");
app.notify({title:"All tracks not found",
text: "Some tracks in the recording are not present in the playback",
icon_url: "/assets/content/icon_alert_big.png"})
}
}
}
2014-11-13 15:20:08 +00:00
function trackMuteSelected(e, data) {
var muteOption = data.muteOption; // muteOption is going to be either 'master' or 'personal'. We mute the correct one, based on track info
var $muteControl = $(this);
// mixer is the mixer object returned from the backend corresponding to the mixer in this particular mode
// oppositeMixer is the mixer correspond to the opposite mode.
// Note that oppositeMixer is not ever set for ChannelGroupIds.AudioInputMusicGroup or ChannelGroupIds.MediaTrackGroup
var mixer = $muteControl.data('mixer')
var oppositeMixer = $muteControl.data('opposite-mixer')
if(mixer.group_id == ChannelGroupIds.AudioInputMusicGroup || mixer.group_id == ChannelGroupIds.MediaTrackGroup) {
context.jamClient.SessionSetControlState(mixer.id, sessionModel.isMasterMixMode());
context.jamClient.SessionSetControlState(mixer.id, !sessionModel.isMasterMixMode());
}
else if(mixer.group_id == ChannelGroupIds.UserMusicInputGroup || mixer.group_id == ChannelGroupIds.PeerAudioInputMusicGroup) {
context.jamClient.SessionSetControlState(mixer.id, sessionModel.isMasterMixMode());
context.jamClient.SessionSetControlState(oppositeMixer.id, !sessionModel.isMasterMixMode());
}
_toggleVisualMuteControl($control, true);
}
function _renderTracks() {
2013-05-15 05:59:09 +00:00
myTracks = [];
// Participants are here now, but the mixers don't update right away.
// Draw tracks from participants, then setup timers to look for the
// mixers that go with those participants, if they're missing.
lookingForMixersCount = 0;
$.each(sessionModel.participants(), function(index, participant) {
var name = participant.user.name;
if (!(name)) {
name = participant.user.first_name + ' ' + participant.user.last_name;
}
var usedMixers = {}; // Once we use a mixer, we add it here to allow us to find 'second' tracks
2013-05-15 05:59:09 +00:00
// loop through all tracks for each participant
$.each(participant.tracks, function(index, track) {
var instrumentIcon = context.JK.getInstrumentIcon45(track.instrument_id);
var photoUrl = context.JK.resolveAvatarUrl(participant.user.photo_url);
var myTrack = false;
// Default trackData to participant + no Mixer state.
var trackData = {
trackId: track.id,
2013-05-22 11:48:37 +00:00
connection_id: track.connection_id,
2013-05-15 05:59:09 +00:00
clientId: participant.client_id,
name: name,
instrumentIcon: instrumentIcon,
avatar: photoUrl,
latency: "good",
gainPercent: 0,
muteClass: 'muted',
2014-01-05 03:47:23 +00:00
mixerId: "",
avatarClass: 'avatar-med',
preMasteredClass: ""
2013-05-15 05:59:09 +00:00
};
// This is the likely cause of multi-track problems.
// This should really become _mixersForClientId and return a list.
// With multiple tracks, there will be more than one mixer for a
// particular client, in a particular group, and I'll need to further
// identify by track id or something similar.
2014-11-11 22:21:29 +00:00
2014-11-17 19:32:13 +00:00
2014-11-17 23:16:30 +00:00
var currentMixers = _groupedMixersForClientId(
participant.client_id,
[
ChannelGroupIds.AudioInputMusicGroup,
ChannelGroupIds.PeerAudioInputMusicGroup,
ChannelGroupIds.UserMusicInputGroup
],
usedMixers, sessionModel.getMixMode());
var oppositeMixers = _groupedMixersForClientId(
participant.client_id,
[
ChannelGroupIds.AudioInputMusicGroup,
ChannelGroupIds.PeerAudioInputMusicGroup,
ChannelGroupIds.UserMusicInputGroup
],
usedMixers, !sessionModel.getMixMode());
console.log("currentMixers", currentMixers)
console.log("oppositeMixers", oppositeMixers)
2014-11-11 22:21:29 +00:00
2014-11-12 02:39:46 +00:00
var mixer = null;
var oppositeMixer = null;
2014-11-17 23:16:30 +00:00
if(currentMixers) {
if(currentMixers[ChannelGroupIds.AudioInputMusicGroup]) {
mixer = currentMixers[ChannelGroupIds.AudioInputMusicGroup][0]
oppositeMixer = oppositeMixers[ChannelGroupIds.AudioInputMusicGroup][0]
2014-11-12 02:39:46 +00:00
}
2014-11-17 23:16:30 +00:00
else if(sessionModel.isMasterMixMode() && currentMixers[ChannelGroupIds.PeerAudioInputMusicGroup]) {
mixer = currentMixers[ChannelGroupIds.PeerAudioInputMusicGroup][0]
oppositeMixer = oppositeMixers[ChannelGroupIds.UserMusicInputGroup][0]
2014-11-12 02:39:46 +00:00
}
2014-11-17 23:16:30 +00:00
else if(!sessionModel.isMasterMixMode() && currentMixers[ChannelGroupIds.UserMusicInputGroup]) {
mixer = currentMixers[ChannelGroupIds.UserMusicInputGroup][0]
oppositeMixer = oppositeMixers[ChannelGroupIds.PeerAudioInputMusicGroup][0]
2014-11-12 02:39:46 +00:00
}
}
2013-05-15 05:59:09 +00:00
if (mixer) {
usedMixers[mixer.id] = true;
2013-05-15 05:59:09 +00:00
myTrack = (mixer.group_id === ChannelGroupIds.AudioInputMusicGroup);
var gainPercent = percentFromMixerValue(
mixer.range_low, mixer.range_high, mixer.volume_left);
var muteClass = "enabled";
if (mixer.mute) {
muteClass = "muted";
}
2013-05-15 05:59:09 +00:00
trackData.gainPercent = gainPercent;
trackData.muteClass = muteClass;
trackData.mixerId = mixer.id;
trackData.noaudio = false;
2014-11-11 22:21:29 +00:00
trackData.group_id = mixer.group_id;
2014-11-12 02:39:46 +00:00
trackData.oppositeMixer = oppositeMixer;
2013-09-24 07:22:41 +00:00
context.jamClient.SessionSetUserName(participant.client_id,name);
2013-05-15 05:59:09 +00:00
} else { // No mixer to match, yet
lookingForMixers[track.id] = participant.client_id;
trackData.noaudio = true;
2013-05-15 05:59:09 +00:00
if (!(lookingForMixersTimer)) {
logger.debug("waiting for mixer to show up for track: " + track.id)
lookingForMixersTimer = context.setInterval(lookForMixers, 500);
2013-05-15 05:59:09 +00:00
}
}
var allowDelete = myTrack && index > 0;
2014-11-13 15:20:08 +00:00
_addTrack(allowDelete, trackData, mixer);
2013-05-15 05:59:09 +00:00
// Show settings icons only for my tracks
if (myTrack) {
2013-05-24 01:16:00 +00:00
myTracks.push(trackData);
}
2013-05-24 01:16:00 +00:00
// TODO: UNCOMMENT THIS WHEN TESTING LOCALLY IN BROWSER
//myTracks.push(trackData);
2013-05-15 05:59:09 +00:00
});
});
configureTrackDialog = new context.JK.ConfigureTrackDialog(app, myTracks, sessionId, sessionModel);
addNewGearDialog = new context.JK.AddNewGearDialog(app, self);
}
2014-11-11 22:21:29 +00:00
function connectTrackToMixer(trackSelector, clientId, mixerId, gainPercent, groupId) {
var vuOpts = $.extend({}, trackVuOpts);
var faderOpts = $.extend({}, trackFaderOpts);
faderOpts.faderId = mixerId;
var vuLeftSelector = trackSelector + " .track-vu-left";
var vuRightSelector = trackSelector + " .track-vu-right";
var faderSelector = trackSelector + " .track-gain";
2014-11-11 22:21:29 +00:00
var $fader = $(faderSelector).attr('mixer-id', mixerId).data('groupId', groupId)
var $track = $(trackSelector);
// Set mixer-id attributes and render VU/Fader
context.JK.VuHelpers.renderVU(vuLeftSelector, vuOpts);
2014-11-11 22:21:29 +00:00
$track.find('.track-vu-left').attr('mixer-id', mixerId + '_vul').data('groupId', groupId)
context.JK.VuHelpers.renderVU(vuRightSelector, vuOpts);
2014-11-11 22:21:29 +00:00
$track.find('.track-vu-right').attr('mixer-id', mixerId + '_vur').data('groupId', groupId)
2014-06-13 17:51:03 +00:00
context.JK.FaderHelpers.renderFader($fader, faderOpts);
// Set gain position
context.JK.FaderHelpers.setFaderValue(mixerId, gainPercent);
2014-06-13 17:51:03 +00:00
$fader.on('fader_change', faderChanged);
}
// Function called on an interval when participants change. Mixers seem to
// show up later, so we render the tracks from participants, but keep track
// of the ones there weren't any mixers for, and continually try to find them
// and get them connected to the mixers underneath.
function lookForMixers() {
lookingForMixersCount++;
_updateMixers();
var usedMixers = {};
var keysToDelete = [];
for (var key in lookingForMixers) {
var clientId = lookingForMixers[key];
2014-11-17 23:16:30 +00:00
var currentMixers = _groupedMixersForClientId(
clientId,
[
ChannelGroupIds.AudioInputMusicGroup,
ChannelGroupIds.PeerAudioInputMusicGroup,
ChannelGroupIds.UserMusicInputGroup
],
usedMixers, sessionModel.getMixMode());
var oppositeMixers = _groupedMixersForClientId(
2014-11-12 14:46:21 +00:00
clientId,
[
ChannelGroupIds.AudioInputMusicGroup,
ChannelGroupIds.PeerAudioInputMusicGroup,
ChannelGroupIds.UserMusicInputGroup
],
2014-11-17 23:16:30 +00:00
usedMixers, !sessionModel.getMixMode());
2014-11-12 02:39:46 +00:00
var mixer = null;
var oppositeMixer = null;
2014-11-17 23:16:30 +00:00
if(currentMixers) {
if(currentMixers[ChannelGroupIds.AudioInputMusicGroup]) {
mixer = currentMixers[ChannelGroupIds.AudioInputMusicGroup][0]
oppositeMixer = oppositeMixers[ChannelGroupIds.AudioInputMusicGroup][0]
2014-11-12 02:39:46 +00:00
}
2014-11-17 23:16:30 +00:00
else if(sessionModel.isMasterMixMode() && currentMixers[ChannelGroupIds.PeerAudioInputMusicGroup]) {
mixer = currentMixers[ChannelGroupIds.PeerAudioInputMusicGroup][0]
oppositeMixer = oppositeMixers[ChannelGroupIds.UserMusicInputGroup][0]
2014-11-12 02:39:46 +00:00
}
2014-11-17 23:16:30 +00:00
else if(!sessionModel.isMasterMixMode() && currentMixers[ChannelGroupIds.UserMusicInputGroup]) {
mixer = currentMixers[ChannelGroupIds.UserMusicInputGroup][0]
oppositeMixer = oppositeMixers[ChannelGroupIds.PeerAudioInputMusicGroup][0]
2014-11-12 02:39:46 +00:00
}
2014-11-11 22:21:29 +00:00
}
if (mixer) {
var participant = (sessionModel.getParticipant(clientId) || {name:'unknown'}).name;
logger.debug("found mixer=" + mixer.id + ", participant=" + participant)
usedMixers[mixer.id] = true;
keysToDelete.push(key);
var gainPercent = percentFromMixerValue(
mixer.range_low, mixer.range_high, mixer.volume_left);
var trackSelector = 'div.track[track-id="' + key + '"]';
2014-11-11 22:21:29 +00:00
connectTrackToMixer(trackSelector, key, mixer.id, gainPercent, mixer.group_id);
var $track = $('div.track[client-id="' + clientId + '"]');
2014-11-13 15:20:08 +00:00
var $trackIconMute = $track.find('.track-icon-mute')
$trackIconMute.attr('mixer-id', mixer.id).attr('opposite-mixer-id', oppositeMixer.id).data('mixer', mixer).data('opposite-mixer', oppositeMixer)
$trackIconMute.muteSelector().on(EVENTS.MUTE_SELECTED, trackMuteSelected)
// hide overlay for all tracks associated with this client id (if one mixer is present, then all tracks are valid)
$('.disabled-track-overlay', $track).hide();
$('.track-connection', $track).removeClass('red yellow green').addClass('grey');
// Set mute state
2014-11-13 15:20:08 +00:00
_toggleVisualMuteControl($trackIconMute, mixer, oppositeMixer);
}
else {
// if 1 second has gone by and still no mixer, then we gray the participant's tracks
if(lookingForMixersCount == 2) {
var $track = $('div.track[client-id="' + clientId + '"]');
$('.disabled-track-overlay', $track).show();
$('.track-connection', $track).removeClass('red yellow green').addClass('red');
}
var participant = (sessionModel.getParticipant(clientId) || { user: {name: 'unknown'}}).user.name;
2014-06-13 20:07:17 +00:00
logger.debug("still looking for mixer for participant=" + participant + ", clientId=" + clientId)
}
}
for (var i=0; i<keysToDelete.length; i++) {
delete lookingForMixers[keysToDelete[i]];
}
if (context.JK.dlen(lookingForMixers) === 0 ||
lookingForMixersCount > 20) {
lookingForMixersCount = 0;
lookingForMixers = {};
context.clearTimeout(lookingForMixersTimer);
lookingForMixersTimer = null;
}
}
2013-01-30 16:50:43 +00:00
// Given a mixerID and a value between 0.0-1.0,
// light up the proper VU lights.
function _updateVU(mixerId, value) {
// Special-case for mono tracks. If mono, and it's a _vul id,
// update both sides, otherwise do nothing.
// If it's a stereo track, just do the normal thing.
var selector;
var pureMixerId = mixerId.replace("_vul", "");
pureMixerId = pureMixerId.replace("_vur", "");
2014-11-17 23:16:30 +00:00
var mixer = getMixer(pureMixerId, sessionModel.getMixMode());
if (mixer) {
if (!(mixer.stereo)) { // mono track
if (mixerId.substr(-4) === "_vul") {
// Do the left
2014-06-13 17:51:03 +00:00
selector = $('#tracks [mixer-id="' + pureMixerId + '_vul"]');
context.JK.VuHelpers.updateVU(selector, value);
// Do the right
2014-06-13 17:51:03 +00:00
selector = $('#tracks [mixer-id="' + pureMixerId + '_vur"]');
context.JK.VuHelpers.updateVU(selector, value);
} // otherwise, it's a mono track, _vur event - ignore.
} else { // stereo track
2014-06-13 17:51:03 +00:00
selector = $('#tracks [mixer-id="' + mixerId + '"]');
context.JK.VuHelpers.updateVU(selector, value);
}
}
2013-01-30 16:50:43 +00:00
}
2014-11-13 15:20:08 +00:00
function _addTrack(allowDelete, trackData, mixer) {
var parentSelector = '#session-mytracks-container';
var $destination = $(parentSelector);
if (trackData.clientId !== app.clientId) {
parentSelector = '#session-livetracks-container';
$destination = $(parentSelector);
$('.session-livetracks .when-empty').hide();
}
var template = $('#template-session-track').html();
2014-01-05 03:47:23 +00:00
var newTrack = $(context.JK.fillTemplate(template, trackData));
var audioOverlay = $('.disabled-track-overlay', newTrack);
2014-11-13 15:20:08 +00:00
var $trackIconMute = newTrack.find('.track-icon-mute')
$trackIconMute.muteSelector().on(EVENTS.MUTE_SELECTED, trackMuteSelected)
$trackIconMute.data('mixer', mixer)
audioOverlay.hide(); // always start with overlay hidden, and only show if no audio persists
$destination.append(newTrack);
// Render VU meters and gain fader
var trackSelector = parentSelector + ' .session-track[track-id="' + trackData.trackId + '"]';
var gainPercent = trackData.gainPercent || 0;
2014-11-11 22:21:29 +00:00
connectTrackToMixer(trackSelector, trackData.clientId, trackData.mixerId, gainPercent, trackData.group_id);
var $closeButton = $('#div-track-close', 'div[track-id="' + trackData.trackId + '"]');
if (!allowDelete) {
$closeButton.hide();
}
else {
$closeButton.click(deleteTrack);
}
2013-05-15 05:59:09 +00:00
tracks[trackData.trackId] = new context.JK.SessionTrack(trackData.clientId);
}
2014-01-05 03:47:23 +00:00
function _addMediaTrack(trackData) {
2014-01-05 03:47:23 +00:00
var parentSelector = '#session-recordedtracks-container';
var $destination = $(parentSelector);
$('.session-recordings .when-empty').hide();
$('.session-recording-name-wrapper').show();
$('.session-recordings .recording-controls').show();
2014-01-05 03:47:23 +00:00
var template = $('#template-session-track').html();
var newTrack = $(context.JK.fillTemplate(template, trackData));
$destination.append(newTrack);
if(trackData.preMasteredClass) {
context.JK.helpBubble($('.track-instrument', newTrack), 'pre-processed-track', {}, {offsetParent: newTrack.closest('.content-body')});
}
// Render VU meters and gain fader
var trackSelector = parentSelector + ' .session-track[track-id="' + trackData.trackId + '"]';
var gainPercent = trackData.gainPercent || 0;
2014-11-11 22:21:29 +00:00
connectTrackToMixer(trackSelector, trackData.clientId, trackData.mixerId, gainPercent, null);
2014-01-05 03:47:23 +00:00
tracks[trackData.trackId] = new context.JK.SessionTrack(trackData.clientId);
}
/**
* Will be called when fader changes. The fader id (provided at subscribe time),
* the new value (0-100) and whether the fader is still being dragged are passed.
*/
2014-06-13 17:51:03 +00:00
function faderChanged(e, data) {
var $target = $(this);
var faderId = $target.attr('mixer-id');
2014-11-11 22:21:29 +00:00
var groupId = $target.data('groupId');
var mixerIds = faderId.split(',');
$.each(mixerIds, function(i,v) {
2014-06-13 17:51:03 +00:00
var broadcast = !(data.dragging); // If fader is still dragging, don't broadcast
fillTrackVolumeObject(v, broadcast);
2014-06-13 17:51:03 +00:00
setMixerVolume(v, data.percentage);
2014-11-11 22:21:29 +00:00
if(groupId == ChannelGroupIds.UserMusicInputGroup) {
// there may be other mixers with this same ID in the case of a Peer Music Stream, so update them as well
context.JK.FaderHelpers.setFaderValue(v, data.percentage);
}
});
}
function handleVolumeChangeCallback(mixerId, isLeft, value, isMuted) {
// Visually update mixer
// There is no need to actually set the back-end mixer value as the
// back-end will already have updated the audio mixer directly prior to sending
// me this event. I simply need to visually show the new fader position.
// TODO: Use mixer's range
var faderValue = percentFromMixerValue(-80, 20, value);
context.JK.FaderHelpers.setFaderValue(mixerId, faderValue);
2014-11-12 14:46:21 +00:00
//var $muteControl = $('[control="mute"][mixer-id="' + mixerId + '"]');
//_toggleVisualMuteControl($muteControl, isMuted);
}
function handleBridgeCallback() {
var eventName = null;
var mixerId = null;
var value = null;
var tuples = arguments.length / 3;
for (var i=0; i<tuples; i++) {
eventName = arguments[3*i];
mixerId = arguments[(3*i)+1];
value = arguments[(3*i)+2];
var vuVal = 0.0;
if (eventName === 'left_vu' || eventName === 'right_vu') {
// TODO - no guarantee range will be -80 to 20. Get from the
// GetControlState for this mixer which returns min/max
// value is a DB value from -80 to 20. Convert to float from 0.0-1.0
vuVal = (value + 80) / 100;
if (eventName === 'left_vu') {
mixerId = mixerId + "_vul";
} else {
mixerId = mixerId + "_vur";
}
_updateVU(mixerId, vuVal);
} else if (eventName === 'connection_status') {
// Connection Quality Change
var connectionClass = 'green';
if (value < 7) {
connectionClass = 'yellow';
}
if (value < 4) {
connectionClass = 'red';
}
2014-11-17 23:16:30 +00:00
var clientId = _clientIdForUserInputMixer(mixerId, sessionModel.getMixMode());
if(clientId) {
var $connection = $('.session-track[client-id="' + clientId + '"] .track-connection');
if($connection.length == 0) {
logger.debug("connection status: looking for clientId: " + clientId + ", mixer: " + mixerId)
}
else {
$connection.removeClass('red yellow green grey');
$connection.addClass(connectionClass);
}
}
} else if (eventName === 'add' || eventName === 'remove') {
// TODO - _renderSession. Note I get streams of these in
// sequence, so have Nat fix, or buffer/spam protect
// Note - this is already handled from websocket events.
// However, there may be use of these two events to avoid
// the polling-style check for when a mixer has been added
// to match a participant track.
} else {
// Examples of other events
// Add media file track: "add", "The_Abyss_4T", 0
logger.debug('non-vu event: ' + eventName + ',' + mixerId + ',' + value);
}
2013-01-30 16:50:43 +00:00
}
}
function deleteSession(evt) {
var sessionId = $(evt.currentTarget).attr("action-id");
if (sessionId) {
$.ajax({
type: "DELETE",
2013-02-26 03:54:09 +00:00
url: "/api/sessions/" + sessionId,
success: function(response) {
2014-02-06 13:03:44 +00:00
context.location="/client#/home";
2013-02-26 03:54:09 +00:00
},
error: function(jqXHR, textStatus, errorThrown) {
logger.error("Error deleting session " + sessionId);
}
});
}
}
function deleteTrack(evt) {
var trackId = $(evt.currentTarget).attr("track-id");
sessionModel.deleteTrack(sessionId, trackId);
}
2014-11-12 14:46:21 +00:00
function _toggleVisualMuteControl($control, currentMixer, oppositeMixer) {
if (currentMixer.mute) {
$control.removeClass('enabled');
$control.addClass('muted');
} else {
$control.removeClass('muted');
$control.addClass('enabled');
}
}
function _toggleAudioMute(mixerId, muting) {
fillTrackVolumeObject(mixerId);
context.trackVolumeObject.mute = muting;
2014-11-17 23:16:30 +00:00
context.jamClient.SessionSetControlState(mixerId, sessionModel.getMixerMode());
}
2014-11-13 15:20:08 +00:00
function showMuteDropdowns($control) {
$control.btOn();
}
function toggleMute(evt) {
var $control = $(evt.currentTarget);
var muting = ($control.hasClass('enabled'));
var mixerIds = $control.attr('mixer-id').split(',');
2014-11-13 15:20:08 +00:00
// track icons have a special mute behavior
if($control.is('.track-icon-mute')) {
$.each(mixerIds, function(i,v) {
if(muting) {
// show insta-dropdown providing two options for mute
showMuteDropdowns($control);
}
else {
_toggleAudioMute(v, muting);
}
});
if(!muting) {
_toggleVisualMuteControl($control, muting);
}
}
else {
$.each(mixerIds, function(i,v) {
_toggleAudioMute(v, muting);
2014-11-13 15:20:08 +00:00
});
_toggleVisualMuteControl($control, muting);
}
}
function fillTrackVolumeObject(mixerId, broadcast) {
_updateMixers();
var mixer = null;
var _broadcast = true;
if (broadcast !== undefined) {
_broadcast = broadcast;
}
for (var i=0; i<mixers.length; i++) {
mixer = mixers[i];
if (mixer.id === mixerId) {
context.trackVolumeObject.clientID = mixer.client_id;
context.trackVolumeObject.broadcast = _broadcast;
context.trackVolumeObject.master = mixer.master;
context.trackVolumeObject.monitor = mixer.monitor;
context.trackVolumeObject.mute = mixer.mute;
context.trackVolumeObject.name = mixer.name;
context.trackVolumeObject.record = mixer.record;
context.trackVolumeObject.volL = mixer.volume_left;
context.trackVolumeObject.volR = mixer.volume_right;
// trackVolumeObject doesn't have a place for range min/max
currentMixerRangeMin = mixer.range_low;
currentMixerRangeMax = mixer.range_high;
break;
}
}
}
// Given a mixer's min/max and current value, return it as
// a percent from 0-100. Return an integer.
function percentFromMixerValue(min, max, value) {
try {
var range = Math.abs(max - min);
var magnitude = value - min;
var percent = Math.round(100*(magnitude/range));
return percent;
} catch(err) {
return 0;
}
}
// Given a mixer's min/max and a percent value, return it as
// the mixer's value. Returns an integer.
function percentToMixerValue(min, max, percent) {
var range = Math.abs(max - min);
var multiplier = percent/100; // Change 85 into 0.85
var value = min + (multiplier * range);
// Protect against percents < 0 and > 100
if (value < min) {
value = min;
}
if (value > max) {
value = max;
}
return value;
}
// Given a volume percent (0-100), set the underlying
// audio volume level of the passed mixerId to the correct
// value.
function setMixerVolume(mixerId, volumePercent) {
// The context.trackVolumeObject has been filled with the mixer values
// that go with mixerId, and the range of that mixer
// has been set in currentMixerRangeMin-Max.
// All that needs doing is to translate the incoming percent
// into the real value ont the sliders range. Set Left/Right
// volumes on trackVolumeObject, and call SetControlState to stick.
var sliderValue = percentToMixerValue(
currentMixerRangeMin, currentMixerRangeMax, volumePercent);
context.trackVolumeObject.volL = context.JK.FaderHelpers.convertPercentToAudioTaper(volumePercent);
context.trackVolumeObject.volR = context.JK.FaderHelpers.convertPercentToAudioTaper(volumePercent);
2013-04-10 15:01:29 +00:00
// Special case for L2M mix:
if (mixerId === '__L2M__') {
2013-09-05 21:51:29 +00:00
logger.debug("L2M volumePercent=" + volumePercent);
var dbValue = context.JK.FaderHelpers.convertLinearToDb(volumePercent);
context.jamClient.SessionSetMasterLocalMix(dbValue);
// context.jamClient.SessionSetMasterLocalMix(sliderValue);
2013-04-10 15:01:29 +00:00
} else {
2014-11-17 23:16:30 +00:00
context.jamClient.SessionSetControlState(mixerId, sessionModel.getMixerMode());
2013-04-10 15:01:29 +00:00
}
}
2014-05-01 06:35:16 +00:00
function bailOut() {
promptLeave = false;
context.window.location = '/client#/home';
}
2014-02-25 02:20:17 +00:00
function sessionLeave(evt) {
evt.preventDefault();
2014-04-30 16:44:37 +00:00
rateSession();
2014-05-01 06:35:16 +00:00
bailOut();
2014-04-30 16:44:37 +00:00
return false;
}
2014-02-25 02:20:17 +00:00
2014-04-30 16:44:37 +00:00
function rateSession() {
2014-05-01 01:48:57 +00:00
if (rateSessionDialog === null) {
2014-05-01 06:35:16 +00:00
rateSessionDialog = new context.JK.RateSessionDialog(context.JK.app);
2014-05-01 01:48:57 +00:00
rateSessionDialog.initialize();
}
2014-05-01 06:35:16 +00:00
rateSessionDialog.showDialog();
2014-04-30 16:44:37 +00:00
return true;
2014-02-25 02:20:17 +00:00
}
function sessionResync(evt) {
evt.preventDefault();
var response = context.jamClient.SessionAudioResync();
if (response) {
app.notify({
"title": "Error",
"text": response,
"icon_url": "/assets/content/icon_alert_big.png"});
}
return false;
}
// http://stackoverflow.com/questions/2604450/how-to-create-a-jquery-clock-timer
function updateRecordingTimer() {
function pretty_time_string(num) {
return ( num < 10 ? "0" : "" ) + num;
}
var total_seconds = (new Date - startTimeDate) / 1000;
var hours = Math.floor(total_seconds / 3600);
total_seconds = total_seconds % 3600;
var minutes = Math.floor(total_seconds / 60);
total_seconds = total_seconds % 60;
var seconds = Math.floor(total_seconds);
hours = pretty_time_string(hours);
minutes = pretty_time_string(minutes);
seconds = pretty_time_string(seconds);
if(hours > 0) {
var currentTimeString = hours + ":" + minutes + ":" + seconds;
}
else {
var currentTimeString = minutes + ":" + seconds;
}
$recordingTimer.text('(' + currentTimeString + ')');
}
function displayStartingRecording() {
$('#recording-start-stop').addClass('currently-recording');
$('#recording-status').text("Starting...")
}
function displayStartedRecording() {
startTimeDate = new Date;
$recordingTimer = $("<span id='recording-timer'>(0:00)</span>");
var $recordingStatus = $('<span></span>').append("<span>Stop Recording</span>").append($recordingTimer);
$('#recording-status').html( $recordingStatus );
recordingTimerInterval = setInterval(updateRecordingTimer, 1000);
}
function displayStoppingRecording(data) {
if(data) {
if(data.reason) {
app.notify({
"title": "Recording Aborted",
"text": "The recording was aborted due to '" + data.reason + '"',
"icon_url": "/assets/content/icon_alert_big.png"
});
}
}
$('#recording-status').text("Stopping...");
}
function displayDoneRecording() {
if(recordingTimerInterval) {
clearInterval(recordingTimerInterval);
recordingTimerInterval = null;
startTimeDate = null;
}
$recordingTimer = null;
$('#recording-start-stop').removeClass('currently-recording');
$('#recording-status').text("Make a Recording");
}
function displayWhoCreated(clientId) {
if(app.clientId != clientId) { // don't show to creator
sessionModel.findUserBy({clientId: clientId})
.done(function(user) {
app.notify({
"title": "Recording Started",
"text": user.name + " started a recording",
"icon_url": context.JK.resolveAvatarUrl(user.photo_url)
});
})
.fail(function() {
app.notify({
"title": "Recording Started",
"text": "Oops! Can't determine who started this recording",
"icon_url": "/assets/content/icon_alert_big.png"
});
})
}
}
function promptUserToSave(recordingId) {
rest.getRecording( {id: recordingId} )
.done(function(recording) {
recordingFinishedDialog.setRecording(recording);
app.layout.showDialog('recordingFinished').one(EVENTS.DIALOG_CLOSED, function(e, data) {
if(data.result && data.result.keep){
context.JK.prodBubble($recordingManagerViewer, 'file-manager-poke', {}, {positions:['top', 'left', 'right', 'bottom'], offsetParent: $screen.parent()})
}
})
})
.fail(app.ajaxError);
}
2014-01-05 03:47:23 +00:00
function openRecording(e) {
// just ignore the click if they are currently recording for now
if(sessionModel.recordingModel.isRecording()) {
app.notify({
"title": "Currently Recording",
"text": "You can't open a recording while creating a recording.",
"icon_url": "/assets/content/icon_alert_big.png"
});
return false;
}
if(!localRecordingsDialog.isShowing()) {
app.layout.showDialog('localRecordings');
}
return false;
}
function closeRecording() {
rest.stopPlayClaimedRecording({id: sessionModel.id(), claimed_recording_id: sessionModel.getCurrentSession().claimed_recording.id})
.done(function() {
sessionModel.refreshCurrentSession();
})
.fail(function(jqXHR) {
app.notify({
"title": "Couldn't Stop Recording Playback",
"text": "Couldn't inform the server to stop playback. msg=" + jqXHR.responseText,
"icon_url": "/assets/content/icon_alert_big.png"
});
});
context.jamClient.CloseRecording();
return false;
}
function onPause() {
logger.debug("calling jamClient.SessionStopPlay");
context.jamClient.SessionStopPlay();
}
function onPlay(e, data) {
2014-01-05 03:47:23 +00:00
logger.debug("calling jamClient.SessionStartPlay");
context.jamClient.SessionStartPlay(data.playbackMode);
2014-01-05 03:47:23 +00:00
}
function onChangePlayPosition(e, data){
logger.debug("calling jamClient.SessionTrackSeekMs(" + data.positionMs + ")");
context.jamClient.SessionTrackSeekMs(data.positionMs);
}
function startStopRecording() {
if(sessionModel.recordingModel.isRecording()) {
sessionModel.recordingModel.stopRecording();
}
else {
sessionModel.recordingModel.startRecording();
}
}
function inviteMusicians() {
friendInput = inviteMusiciansUtil.inviteSessionUpdate('#update-session-invite-musicians',
sessionId);
inviteMusiciansUtil.loadFriends();
$(friendInput).show();
2014-11-11 22:21:29 +00:00
}
function onMixerModeChanged(e, data)
{
$mixModeDropdown.easyDropDown('select', data.mode, true);
setTimeout(renderSession, 1);
}
function onUserChangeMixMode(e) {
var mode = $mixModeDropdown.val() == "master" ? MIX_MODES.MASTER : MIX_MODES.PERSONAL;
context.jamClient.SetMixerMode(mode)
modUtils.shouldShow(NAMED_MESSAGES.MASTER_VS_PERSONAL_MIX).done(function(shouldShow) {
if(shouldShow) {
var modeChangeHtml = $($templateMixerModeChange.html());
context.JK.Banner.show({title: 'Master vs. Personal Mix', text: modeChangeHtml, no_show: NAMED_MESSAGES.MASTER_VS_PERSONAL_MIX});
}
})
return true;
}
function events() {
2014-02-25 02:20:17 +00:00
$('#session-leave').on('click', sessionLeave);
$('#session-resync').on('click', sessionResync);
$('#session-contents').on("click", '[action="delete"]', deleteSession);
$('#tracks').on('click', 'div[control="mute"]', toggleMute);
2014-01-05 03:47:23 +00:00
$('#recording-start-stop').on('click', startStopRecording);
$('#open-a-recording').on('click', openRecording);
$('#session-invite-musicians').on('click', inviteMusicians);
$('#session-invite-musicians2').on('click', inviteMusicians);
$('#track-settings').click(function() {
configureTrackDialog.refresh();
configureTrackDialog.showVoiceChatPanel(true);
configureTrackDialog.showMusicAudioPanel(true);
2013-05-18 05:59:25 +00:00
});
2014-01-25 15:37:15 +00:00
2014-01-05 03:47:23 +00:00
$('#close-playback-recording').on('click', closeRecording);
$(playbackControls)
.on('pause', onPause)
.on('play', onPlay)
.on('change-position', onChangePlayPosition);
$(friendInput).focus(function() { $(this).val(''); })
2014-11-11 22:21:29 +00:00
$(document).on(EVENTS.MIXER_MODE_CHANGED, onMixerModeChanged)
$mixModeDropdown.change(onUserChangeMixMode)
}
this.initialize = function(localRecordingsDialogInstance, recordingFinishedDialogInstance, friendSelectorDialog) {
inviteMusiciansUtil = new JK.InviteMusiciansUtil(JK.app);
inviteMusiciansUtil.initialize(friendSelectorDialog);
2014-01-05 03:47:23 +00:00
localRecordingsDialog = localRecordingsDialogInstance;
recordingFinishedDialog = recordingFinishedDialogInstance;
context.jamClient.SetVURefreshRate(150);
context.jamClient.RegisterVolChangeCallBack("JK.HandleVolumeChangeCallback");
2014-01-05 03:47:23 +00:00
playbackControls = new context.JK.PlaybackControls($('.session-recordings .recording-controls'));
var screenBindings = {
'beforeShow': beforeShow,
'afterShow': afterShow,
'beforeHide': beforeHide,
2014-04-09 17:25:52 +00:00
'beforeLeave' : beforeLeave,
'beforeDisconnect' : beforeDisconnect,
};
app.bindScreen('session', screenBindings);
2014-05-22 16:26:56 +00:00
$recordingManagerViewer = $('#recording-manager-viewer');
$screen = $('#session-screen');
2014-11-09 15:13:22 +00:00
$mixModeDropdown = $screen.find('select.monitor-mode')
2014-11-11 22:21:29 +00:00
$templateMixerModeChange = $('#template-mixer-mode-change');
events();
2014-11-09 15:13:22 +00:00
// make sure no previous plays are still going on by accident
2014-05-22 16:26:56 +00:00
context.jamClient.SessionStopPlay();
if(context.jamClient.SessionRemoveAllPlayTracks) {
// upgrade guard
context.jamClient.SessionRemoveAllPlayTracks();
}
};
this.tracks = tracks;
this.getCurrentSession = function() {
return sessionModel.getCurrentSession();
};
this.refreshCurrentSession = function(force) {
sessionModel.refreshCurrentSession(force);
};
this.setPromptLeave = function(_promptLeave) {
promptLeave = _promptLeave;
}
context.JK.HandleVolumeChangeCallback = handleVolumeChangeCallback;
2013-01-30 16:50:43 +00:00
context.JK.HandleBridgeCallback = handleBridgeCallback;
};
})(window,jQuery);