bigbluebutton-Github/bigbluebutton-html5/imports/ui/services/audio-manager/index.js

420 lines
11 KiB
JavaScript
Raw Normal View History

import { Tracker } from 'meteor/tracker';
2017-09-29 21:38:10 +08:00
import { makeCall } from '/imports/ui/services/api';
2017-10-13 03:22:10 +08:00
import VertoBridge from '/imports/api/audio/client/bridge/verto';
import KurentoBridge from '/imports/api/audio/client/bridge/kurento';
2017-11-17 19:52:48 +08:00
import Auth from '/imports/ui/services/auth';
import VoiceUsers from '/imports/api/voice-users';
2017-10-13 03:22:10 +08:00
import SIPBridge from '/imports/api/audio/client/bridge/sip';
import logger from '/imports/startup/client/logger';
import { notify } from '/imports/ui/services/notification';
import browser from 'browser-detect';
import iosWebviewAudioPolyfills from '../../../utils/ios-webview-audio-polyfills';
import { tryGenerateIceCandidates } from '../../../utils/safari-webrtc';
2017-10-18 03:16:42 +08:00
const MEDIA = Meteor.settings.public.media;
const MEDIA_TAG = MEDIA.mediaTag;
2017-10-18 03:16:42 +08:00
const USE_SIP = MEDIA.useSIPAudio;
const ECHO_TEST_NUMBER = MEDIA.echoTestNumber;
const MAX_LISTEN_ONLY_RETRIES = 1;
const CALL_STATES = {
2017-10-05 04:49:11 +08:00
STARTED: 'started',
ENDED: 'ended',
FAILED: 'failed',
};
class AudioManager {
constructor() {
2017-09-30 04:42:34 +08:00
this._inputDevice = {
2018-04-13 20:39:26 +08:00
value: 'default',
tracker: new Tracker.Dependency(),
2017-09-30 04:42:34 +08:00
};
this.defineProperties({
isMuted: false,
isConnected: false,
isConnecting: false,
2017-10-27 01:14:56 +08:00
isHangingUp: false,
2017-09-29 21:38:10 +08:00
isListenOnly: false,
isEchoTest: false,
isTalking: false,
2017-11-09 02:41:15 +08:00
isWaitingPermissions: false,
error: null,
outputDeviceId: null,
2018-01-16 23:56:31 +08:00
muteHandle: null,
});
this.useKurento = Meteor.settings.public.kurento.enableListenOnly;
}
init(userData) {
2017-10-18 03:16:42 +08:00
this.bridge = USE_SIP ? new SIPBridge(userData) : new VertoBridge(userData);
if (this.useKurento) {
this.listenOnlyBridge = new KurentoBridge(userData);
}
2017-10-18 03:16:42 +08:00
this.userData = userData;
this.initialized = true;
2017-10-18 03:16:42 +08:00
}
2018-12-22 01:14:05 +08:00
setAudioMessages(messages) {
this.messages = messages;
}
2017-10-18 03:16:42 +08:00
defineProperties(obj) {
2017-09-29 21:38:10 +08:00
Object.keys(obj).forEach((key) => {
const privateKey = `_${key}`;
this[privateKey] = {
value: obj[key],
tracker: new Tracker.Dependency(),
2017-09-29 21:38:10 +08:00
};
Object.defineProperty(this, key, {
set: (value) => {
2017-09-29 21:38:10 +08:00
this[privateKey].value = value;
this[privateKey].tracker.changed();
},
get: () => {
2017-09-29 21:38:10 +08:00
this[privateKey].tracker.depend();
return this[privateKey].value;
},
});
});
}
askDevicesPermissions() {
// Only change the isWaitingPermissions for the case where the user didnt allowed it yet
const permTimeout = setTimeout(() => {
if (!this.devicesInitialized) { this.isWaitingPermissions = true; }
2017-11-09 02:41:15 +08:00
}, 100);
this.isWaitingPermissions = false;
this.devicesInitialized = false;
2019-01-14 22:41:44 +08:00
return Promise.all([
this.setDefaultInputDevice(),
this.setDefaultOutputDevice(),
]).then(() => {
this.devicesInitialized = true;
this.isWaitingPermissions = false;
}).catch((err) => {
clearTimeout(permTimeout);
this.isConnecting = false;
this.isWaitingPermissions = false;
throw err;
});
}
joinMicrophone() {
this.isListenOnly = false;
this.isEchoTest = false;
const callOptions = {
isListenOnly: false,
extension: null,
inputStream: this.inputStream,
};
return this.askDevicesPermissions()
.then(this.onAudioJoining.bind(this))
.then(() => this.bridge.joinAudio(callOptions, this.callStateCallback.bind(this)));
}
joinEchoTest() {
this.isListenOnly = false;
this.isEchoTest = true;
const callOptions = {
isListenOnly: false,
extension: ECHO_TEST_NUMBER,
inputStream: this.inputStream,
};
return this.askDevicesPermissions()
.then(this.onAudioJoining.bind(this))
.then(() => this.bridge.joinAudio(callOptions, this.callStateCallback.bind(this)));
}
async joinListenOnly(retries = 0) {
this.isListenOnly = true;
this.isEchoTest = false;
const { name } = browser();
// The kurento bridge isn't a full audio bridge yet, so we have to differ it
const bridge = this.useKurento ? this.listenOnlyBridge : this.bridge;
const callOptions = {
isListenOnly: true,
extension: null,
inputStream: this.createListenOnlyStream(),
};
// Webkit ICE restrictions demand a capture device permission to release
// host candidates
if (name === 'safari') {
try {
await tryGenerateIceCandidates();
} catch (e) {
this.notify(this.messages.error.ICE_NEGOTIATION_FAILED);
}
}
2018-12-22 01:14:05 +08:00
// Call polyfills for webrtc client if navigator is "iOS Webview"
const userAgent = window.navigator.userAgent.toLocaleLowerCase();
if ((userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1)
&& userAgent.indexOf('safari') == -1) {
iosWebviewAudioPolyfills();
}
// We need this until we upgrade to SIP 9x. See #4690
const iceGatheringErr = 'ICE_TIMEOUT';
const iceGatheringTimeout = new Promise((resolve, reject) => {
setTimeout(reject, 12000, iceGatheringErr);
});
const handleListenOnlyError = async (err) => {
if (iceGatheringTimeout) {
clearTimeout(iceGatheringTimeout);
}
logger.error('Listen only error:', err, 'on try', retries);
throw {
type: 'MEDIA_ERROR',
message: this.messages.error.MEDIA_ERROR,
};
};
return this.onAudioJoining()
.then(() => Promise.race([
bridge.joinAudio(callOptions, this.callStateCallback.bind(this)),
iceGatheringTimeout,
]))
.catch(async (err) => {
if (retries < MAX_LISTEN_ONLY_RETRIES) {
// Fallback to SIP.js listen only in case of failure
if (this.useKurento) {
// Exit previous SFU session and clean audio tag state
window.kurentoExitAudio();
this.useKurento = false;
const audio = document.querySelector(MEDIA_TAG);
audio.muted = false;
}
try {
await this.joinListenOnly(++retries);
} catch (error) {
return handleListenOnlyError(error);
}
} else {
handleListenOnlyError(err);
}
});
}
onAudioJoining() {
this.isConnecting = true;
this.isMuted = false;
this.error = false;
return Promise.resolve();
}
exitAudio() {
if (!this.isConnected) return Promise.resolve();
const bridge = (this.useKurento && this.isListenOnly) ? this.listenOnlyBridge : this.bridge;
2017-10-27 01:14:56 +08:00
this.isHangingUp = true;
this.isEchoTest = false;
return bridge.exitAudio();
}
transferCall() {
2017-10-18 03:16:42 +08:00
this.onTransferStart();
return this.bridge.transferCall(this.onAudioJoin.bind(this));
}
toggleMuteMicrophone() {
2018-01-16 05:01:57 +08:00
makeCall('toggleSelfVoice');
}
onAudioJoin() {
this.isConnecting = false;
this.isConnected = true;
2017-10-20 18:11:51 +08:00
2018-01-16 05:01:57 +08:00
// listen to the VoiceUsers changes and update the flag
if (!this.muteHandle) {
2018-01-16 05:01:57 +08:00
const query = VoiceUsers.find({ intId: Auth.userID });
2018-01-16 05:13:18 +08:00
this.muteHandle = query.observeChanges({
2018-01-16 05:01:57 +08:00
changed: (id, fields) => {
if (fields.muted !== undefined && fields.muted !== this.isMuted) {
this.isMuted = fields.muted;
const muteState = this.isMuted ? 'selfMuted' : 'selfUnmuted';
window.parent.postMessage({ response: muteState }, '*');
}
if (fields.talking !== undefined && fields.talking !== this.isTalking) {
this.isTalking = fields.talking;
}
if (this.isMuted) {
this.isTalking = false;
}
2018-01-16 05:01:57 +08:00
},
});
}
2017-10-20 18:11:51 +08:00
if (!this.isEchoTest) {
window.parent.postMessage({ response: 'joinedAudio' }, '*');
2017-10-23 20:41:09 +08:00
this.notify(this.messages.info.JOINED_AUDIO);
2017-10-20 18:11:51 +08:00
}
}
onTransferStart() {
this.isEchoTest = false;
this.isConnecting = true;
}
onAudioExit() {
this.isConnected = false;
2017-10-05 04:49:11 +08:00
this.isConnecting = false;
2017-10-27 01:14:56 +08:00
this.isHangingUp = false;
this.isListenOnly = false;
2017-09-29 21:38:10 +08:00
2018-04-18 01:09:05 +08:00
if (this.inputStream) {
window.defaultInputStream.forEach(track => track.stop());
2018-04-18 01:09:05 +08:00
this.inputStream.getTracks().forEach(track => track.stop());
this.inputDevice = { id: 'default' };
}
2018-04-13 20:39:26 +08:00
2017-10-20 18:11:51 +08:00
if (!this.error && !this.isEchoTest) {
2017-10-23 20:41:09 +08:00
this.notify(this.messages.info.LEFT_AUDIO);
2017-09-29 21:38:10 +08:00
}
window.parent.postMessage({ response: 'notInAudio' }, '*');
}
2017-10-05 04:49:11 +08:00
callStateCallback(response) {
2017-09-29 21:38:10 +08:00
return new Promise((resolve) => {
const {
2017-10-05 04:49:11 +08:00
STARTED,
ENDED,
FAILED,
} = CALL_STATES;
2017-09-29 21:38:10 +08:00
2017-10-05 04:49:11 +08:00
const {
status,
error,
2017-10-23 20:41:09 +08:00
bridgeError,
2017-10-05 04:49:11 +08:00
} = response;
if (status === STARTED) {
2017-09-29 21:38:10 +08:00
this.onAudioJoin();
2017-10-05 04:49:11 +08:00
resolve(STARTED);
} else if (status === ENDED) {
2017-09-29 21:38:10 +08:00
this.onAudioExit();
2017-10-05 04:49:11 +08:00
} else if (status === FAILED) {
2017-10-12 05:04:10 +08:00
this.error = error;
2018-06-27 21:56:03 +08:00
this.notify(this.messages.error[error] || this.messages.error.GENERIC_ERROR, true);
logger.error('Audio Error:', error, bridgeError);
this.exitAudio();
2017-09-29 21:38:10 +08:00
this.onAudioExit();
}
});
2017-09-29 21:38:10 +08:00
}
2017-10-05 04:49:11 +08:00
createListenOnlyStream() {
if (this.listenOnlyAudioContext) {
this.listenOnlyAudioContext.close();
}
2018-12-22 01:14:05 +08:00
this.listenOnlyAudioContext = window.AudioContext
? new window.AudioContext()
: new window.webkitAudioContext();
2017-10-10 05:23:05 +08:00
const dest = this.listenOnlyAudioContext.createMediaStreamDestination();
const audio = document.querySelector(MEDIA_TAG);
// Play bogus silent audio to try to circumvent autoplay policy on Safari
audio.src = 'resources/sounds/silence.mp3';
audio.play().catch((e) => {
logger.warn('Error on playing test audio:', e);
});
2018-08-30 03:59:33 +08:00
return dest.stream;
2017-10-05 04:49:11 +08:00
}
isUsingAudio() {
2018-12-22 01:14:05 +08:00
return this.isConnected || this.isConnecting
|| this.isHangingUp || this.isEchoTest;
}
2017-10-27 01:14:56 +08:00
setDefaultInputDevice() {
return this.changeInputDevice();
2017-10-27 01:14:56 +08:00
}
setDefaultOutputDevice() {
return this.changeOutputDevice('default');
}
changeInputDevice(deviceId) {
const handleChangeInputDeviceSuccess = (inputDevice) => {
this.inputDevice = inputDevice;
2017-11-09 02:41:15 +08:00
return Promise.resolve(inputDevice);
};
2018-12-22 01:14:05 +08:00
const handleChangeInputDeviceError = () => Promise.reject({
type: 'MEDIA_ERROR',
message: this.messages.error.MEDIA_ERROR,
});
if (!deviceId) {
return this.bridge.setDefaultInputDevice()
.then(handleChangeInputDeviceSuccess)
.catch(handleChangeInputDeviceError);
2017-10-23 20:41:09 +08:00
}
2018-04-13 20:39:26 +08:00
return this.bridge.changeInputDevice(deviceId)
.then(handleChangeInputDeviceSuccess)
.catch(handleChangeInputDeviceError);
2017-10-18 03:16:42 +08:00
}
2017-09-30 04:42:34 +08:00
2017-10-18 03:16:42 +08:00
async changeOutputDevice(deviceId) {
this.outputDeviceId = await this.bridge.changeOutputDevice(deviceId);
2017-09-30 04:42:34 +08:00
}
2017-10-18 03:16:42 +08:00
set inputDevice(value) {
2018-04-13 20:39:26 +08:00
this._inputDevice.value = value;
2017-10-18 03:16:42 +08:00
this._inputDevice.tracker.changed();
}
get inputStream() {
2018-04-13 20:39:26 +08:00
this._inputDevice.tracker.depend();
return this._inputDevice.value.stream;
2017-09-30 04:42:34 +08:00
}
get inputDeviceId() {
2017-10-04 04:42:10 +08:00
this._inputDevice.tracker.depend();
2018-04-13 20:39:26 +08:00
return this._inputDevice.value.id;
2017-09-30 04:42:34 +08:00
}
2017-10-18 03:16:42 +08:00
set userData(value) {
this._userData = value;
}
get userData() {
return this._userData;
}
2017-10-23 20:41:09 +08:00
notify(message, error = false) {
notify(
message,
error ? 'error' : 'info',
this.isListenOnly ? 'audio_on' : 'unmute',
);
2017-10-23 20:41:09 +08:00
}
}
const audioManager = new AudioManager();
export default audioManager;