Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

Fixes start muted. Adds the local track before the conference is joined.

hristoterezovf8c12304dc20
diff --git a/conference.js b/conference.js
index 18df3e6fc9..ea59e9e20c 100644
--- a/conference.js
+++ b/conference.js
@@ -225,10 +225,10 @@ export default {
return room.getParticipants().length + 1;
},
get startAudioMuted () {
- return room && room.isStartAudioMuted();
+ return room && room.getStartMutedPolicy().audio;
},
get startVideoMuted () {
- return room && room.isStartVideoMuted();
+ return room && room.getStartMutedPolicy().video;
},
// used by torture currently
isJoined () {
@@ -246,6 +246,16 @@ export default {
_createRoom () {
room = connection.initJitsiConference(APP.conference.roomName,
this._getConferenceOptions());
+ localTracks.forEach((track) => {
+ if(track.isAudioTrack()) {
+ localAudio = track;
+ }
+ else if (track.isVideoTrack()) {
+ localVideo = track;
+ }
+ addTrack(track);
+ APP.UI.addLocalStream(track);
+ });
roomLocker = createRoomLocker(room);
this._room = room; // FIXME do not use this
this.localId = room.myUserId();
@@ -277,17 +287,6 @@ export default {
_setupListeners () {
// add local streams when joined to the conference
room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
- localTracks.forEach((track) => {
- if(track.isAudioTrack()) {
- localAudio = track;
- }
- else if (track.isVideoTrack()) {
- localVideo = track;
- }
- addTrack(track);
- APP.UI.addLocalStream(track);
- });
-
APP.UI.updateAuthInfo(room.isAuthEnabled(), room.getAuthLogin());
APP.UI.mucJoined();
});
@@ -514,18 +513,20 @@ export default {
APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
(startAudioMuted, startVideoMuted) => {
- room.setStartMuted(startAudioMuted, startVideoMuted);
+ room.setStartMutedPolicy({audio: startAudioMuted,
+ video: startVideoMuted});
}
);
room.on(
- ConferenceEvents.START_MUTED,
- function (startAudioMuted, startVideoMuted, initiallyMuted) {
+ ConferenceEvents.START_MUTED_POLICY_CHANGED,
+ (policy) => {
APP.UI.onStartMutedChanged();
- if (initiallyMuted) {
- APP.UI.notifyInitiallyMuted();
- }
}
);
+ room.on(ConferenceEvents.STARTED_MUTED, () => {
+ (room.isStartAudioMuted() || room.isStartVideoMuted())
+ && APP.UI.notifyInitiallyMuted();
+ });
APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
APP.UI.inviteParticipants(
diff --git a/libs/lib-jitsi-meet.js b/libs/lib-jitsi-meet.js
index 85068add18..107381663b 100644
--- a/libs/lib-jitsi-meet.js
+++ b/libs/lib-jitsi-meet.js
@@ -48,7 +48,7 @@ function JitsiConference(options) {
this.authIdentity;
this.startAudioMuted = false;
this.startVideoMuted = false;
- this.tracks = [];
+ this.startMutedPolicy = {audio: false, video: false};
}
/**
@@ -255,16 +255,9 @@ JitsiConference.prototype.setDisplayName = function(name) {
JitsiConference.prototype.addTrack = function (track) {
this.room.addStream(track.getOriginalStream(), function () {
this.rtc.addLocalStream(track);
- if (this.startAudioMuted && track.isAudioTrack()) {
- track.mute();
- }
- if (this.startVideoMuted && track.isVideoTrack()) {
- track.mute();
- }
if (track.startMuted) {
track.mute();
}
- this.tracks.push(track);
var muteHandler = this._fireMuteChangeEvent.bind(this, track);
var stopHandler = this.removeTrack.bind(this, track);
var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
@@ -306,10 +299,6 @@ JitsiConference.prototype._fireMuteChangeEvent = function (track) {
* @param track the JitsiLocalTrack object.
*/
JitsiConference.prototype.removeTrack = function (track) {
- var pos = this.tracks.indexOf(track);
- if (pos > -1) {
- this.tracks.splice(pos, 1);
- }
if(!this.room){
if(this.rtc)
this.rtc.removeLocalStream(track);
@@ -672,25 +661,34 @@ JitsiConference.prototype.getConnectionState = function () {
/**
* Make all new participants mute their audio/video on join.
- * @param {boolean} audioMuted if audio should be muted.
- * @param {boolean} videoMuted if video should be muted.
+ * @param policy {Object} object with 2 boolean properties for video and audio:
+ * @param {boolean} audio if audio should be muted.
+ * @param {boolean} video if video should be muted.
*/
-JitsiConference.prototype.setStartMuted = function (audioMuted, videoMuted) {
+JitsiConference.prototype.setStartMutedPolicy = function (policy) {
if (!this.isModerator()) {
return;
}
-
+ this.startMutedPolicy = policy;
this.room.removeFromPresence("startmuted");
this.room.addToPresence("startmuted", {
attributes: {
- audio: audioMuted,
- video: videoMuted,
+ audio: policy.audio,
+ video: policy.video,
xmlns: 'http://jitsi.org/jitmeet/start-muted'
}
});
this.room.sendPresence();
};
+/**
+ * Returns current start muted policy
+ * @returns {Object} with 2 proprties - audio and video.
+ */
+JitsiConference.prototype.getStartMutedPolicy = function () {
+ return this.startMutedPolicy;
+};
+
/**
* Check if audio is muted on join.
*/
@@ -820,29 +818,24 @@ function setupListeners(conference) {
conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
});
- conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audioMuted, videoMuted) {
- conference.startAudioMuted = audioMuted;
- conference.startVideoMuted = videoMuted;
-
- // mute existing local tracks because this is initial mute from Jicofo
- conference.tracks.forEach(function (track) {
- if (conference.startAudioMuted && track.isAudioTrack()) {
- track.mute();
- }
- if (conference.startVideoMuted && track.isVideoTrack()) {
- track.mute();
- }
- });
+ conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
+ function (audioMuted, videoMuted) {
+ conference.startAudioMuted = audioMuted;
+ conference.startVideoMuted = videoMuted;
- var initiallyMuted = audioMuted || videoMuted;
+ // mute existing local tracks because this is initial mute from
+ // Jicofo
+ conference.getLocalTracks().forEach(function (track) {
+ if (conference.startAudioMuted && track.isAudioTrack()) {
+ track.mute();
+ }
+ if (conference.startVideoMuted && track.isVideoTrack()) {
+ track.mute();
+ }
+ });
- conference.eventEmitter.emit(
- JitsiConferenceEvents.START_MUTED,
- conference.startAudioMuted,
- conference.startVideoMuted,
- initiallyMuted
- );
- });
+ conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
+ });
conference.room.addPresenceListener("startmuted", function (data, from) {
var isModerator = false;
@@ -864,22 +857,20 @@ function setupListeners(conference) {
var updated = false;
- if (startAudioMuted !== conference.startAudioMuted) {
- conference.startAudioMuted = startAudioMuted;
+ if (startAudioMuted !== conference.startMutedPolicy.audio) {
+ conference.startMutedPolicy.audio = startAudioMuted;
updated = true;
}
- if (startVideoMuted !== conference.startVideoMuted) {
- conference.startVideoMuted = startVideoMuted;
+ if (startVideoMuted !== conference.startMutedPolicy.video) {
+ conference.startMutedPolicy.video = startVideoMuted;
updated = true;
}
if (updated) {
conference.eventEmitter.emit(
- JitsiConferenceEvents.START_MUTED,
- conference.startAudioMuted,
- conference.startVideoMuted,
- false
+ JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
+ conference.startMutedPolicy
);
}
});
@@ -1037,7 +1028,11 @@ var JitsiConferenceEvents = {
/**
* Indicates that start muted settings changed.
*/
- START_MUTED: "conference.start_muted",
+ START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
+ /**
+ * Indicates that the local user has started muted.
+ */
+ STARTED_MUTED: "conference.started_muted",
/**
* Indicates that DTMF support changed.
*/
@@ -1589,6 +1584,7 @@ function DataChannels(peerConnection, emitter) {
DataChannels.prototype.onDataChannel = function (event) {
var dataChannel = event.channel;
var self = this;
+ var lastSelectedEndpoint = null;
dataChannel.onopen = function () {
logger.info("Data channel opened by the Videobridge!", dataChannel);
@@ -1600,6 +1596,12 @@ DataChannels.prototype.onDataChannel = function (event) {
//dataChannel.send(new ArrayBuffer(12));
self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
+
+ // when the data channel becomes available, tell the bridge about video
+ // selections so that it can do adaptive simulcast,
+ // we want the notification to trigger even if userJid is undefined,
+ // or null.
+ this.handleSelectedEndpointEvent(this.lastSelectedEndpoint);
};
dataChannel.onerror = function (error) {
@@ -1690,6 +1692,7 @@ DataChannels.prototype.onDataChannel = function (event) {
};
DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
+ this.lastSelectedEndpoint = userResource;
this._onXXXEndpointChanged("selected", userResource);
}
@@ -2392,12 +2395,10 @@ RTC.prototype.setAudioMute = function (value) {
}
}
-RTC.prototype.removeLocalStream = function (stream) {
- for(var i = 0; i < this.localStreams.length; i++) {
- if(this.localStreams[i].getOriginalStream() === stream) {
- delete this.localStreams[i];
- return;
- }
+RTC.prototype.removeLocalStream = function (track) {
+ var pos = this.localStreams.indexOf(track);
+ if (pos > -1) {
+ this.localStreams.splice(pos, 1);
}
};
@@ -10570,7 +10571,8 @@ var getters = {
// if we're running on FF, transform to Plan B first.
if (RTCBrowserType.usesUnifiedPlan()) {
desc = this.interop.toPlanB(desc);
- this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
+ this.trace('getLocalDescription::postTransform (Plan B)',
+ dumpSDP(desc));
}
return desc;
},
@@ -10794,7 +10796,7 @@ TraceablePeerConnection.prototype.getStats = function(callback, errback) {
module.exports = TraceablePeerConnection;
}).call(this,"/modules/xmpp/TraceablePeerConnection.js")
-},{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":69,"sdp-transform":76}],34:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":87,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":48,"sdp-interop":66,"sdp-simulcast":73,"sdp-transform":76}],34:[function(require,module,exports){
(function (__filename){
/* global $, $iq, Promise, Strophe */
@@ -22583,1313 +22585,981 @@ exports.parse = function(sdp) {
};
-},{"sdp-transform":76}],69:[function(require,module,exports){
-/* Copyright @ 2015 Atlassian Pty Ltd
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-var transform = require('sdp-transform');
-var transformUtils = require('./transform-utils');
-var parseSsrcs = transformUtils.parseSsrcs;
-var writeSsrcs = transformUtils.writeSsrcs;
-
-//region Constants
-
-var DEFAULT_NUM_OF_LAYERS = 3;
-
-//endregion
-
-//region Ctor
-
-function Simulcast(options) {
-
- this.options = options ? options : {};
-
- if (!this.options.numOfLayers) {
- this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
- }
-
- this.layers = [];
-}
-
-//endregion
+},{"sdp-transform":70}],69:[function(require,module,exports){
+var grammar = module.exports = {
+ v: [{
+ name: 'version',
+ reg: /^(\d*)$/
+ }],
+ o: [{ //o=- 20518 0 IN IP4 203.0.113.1
+ // NB: sessionId will be a String in most cases because it is huge
+ name: 'origin',
+ reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
+ names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
+ format: "%s %s %d %s IP%d %s"
+ }],
+ // default parsing of these only (though some of these feel outdated)
+ s: [{ name: 'name' }],
+ i: [{ name: 'description' }],
+ u: [{ name: 'uri' }],
+ e: [{ name: 'email' }],
+ p: [{ name: 'phone' }],
+ z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
+ r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
+ //k: [{}], // outdated thing ignored
+ t: [{ //t=0 0
+ name: 'timing',
+ reg: /^(\d*) (\d*)/,
+ names: ['start', 'stop'],
+ format: "%d %d"
+ }],
+ c: [{ //c=IN IP4 10.47.197.26
+ name: 'connection',
+ reg: /^IN IP(\d) (\S*)/,
+ names: ['version', 'ip'],
+ format: "IN IP%d %s"
+ }],
+ b: [{ //b=AS:4000
+ push: 'bandwidth',
+ reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
+ names: ['type', 'limit'],
+ format: "%s:%s"
+ }],
+ m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
+ // NB: special - pushes to session
+ // TODO: rtp/fmtp should be filtered by the payloads found here?
+ reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
+ names: ['type', 'port', 'protocol', 'payloads'],
+ format: "%s %d %s %s"
+ }],
+ a: [
+ { //a=rtpmap:110 opus/48000/2
+ push: 'rtp',
+ reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
+ names: ['payload', 'codec', 'rate', 'encoding'],
+ format: function (o) {
+ return (o.encoding) ?
+ "rtpmap:%d %s/%s/%s":
+ o.rate ?
+ "rtpmap:%d %s/%s":
+ "rtpmap:%d %s";
+ }
+ },
+ {
+ //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
+ //a=fmtp:111 minptime=10; useinbandfec=1
+ push: 'fmtp',
+ reg: /^fmtp:(\d*) ([\S| ]*)/,
+ names: ['payload', 'config'],
+ format: "fmtp:%d %s"
+ },
+ { //a=control:streamid=0
+ name: 'control',
+ reg: /^control:(.*)/,
+ format: "control:%s"
+ },
+ { //a=rtcp:65179 IN IP4 193.84.77.194
+ name: 'rtcp',
+ reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
+ names: ['port', 'netType', 'ipVer', 'address'],
+ format: function (o) {
+ return (o.address != null) ?
+ "rtcp:%d %s IP%d %s":
+ "rtcp:%d";
+ }
+ },
+ { //a=rtcp-fb:98 trr-int 100
+ push: 'rtcpFbTrrInt',
+ reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
+ names: ['payload', 'value'],
+ format: "rtcp-fb:%d trr-int %d"
+ },
+ { //a=rtcp-fb:98 nack rpsi
+ push: 'rtcpFb',
+ reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
+ names: ['payload', 'type', 'subtype'],
+ format: function (o) {
+ return (o.subtype != null) ?
+ "rtcp-fb:%s %s %s":
+ "rtcp-fb:%s %s";
+ }
+ },
+ { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
+ //a=extmap:1/recvonly URI-gps-string
+ push: 'ext',
+ reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
+ names: ['value', 'uri', 'config'], // value may include "/direction" suffix
+ format: function (o) {
+ return (o.config != null) ?
+ "extmap:%s %s %s":
+ "extmap:%s %s";
+ }
+ },
+ {
+ //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
+ push: 'crypto',
+ reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
+ names: ['id', 'suite', 'config', 'sessionConfig'],
+ format: function (o) {
+ return (o.sessionConfig != null) ?
+ "crypto:%d %s %s %s":
+ "crypto:%d %s %s";
+ }
+ },
+ { //a=setup:actpass
+ name: 'setup',
+ reg: /^setup:(\w*)/,
+ format: "setup:%s"
+ },
+ { //a=mid:1
+ name: 'mid',
+ reg: /^mid:([^\s]*)/,
+ format: "mid:%s"
+ },
+ { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
+ name: 'msid',
+ reg: /^msid:(.*)/,
+ format: "msid:%s"
+ },
+ { //a=ptime:20
+ name: 'ptime',
+ reg: /^ptime:(\d*)/,
+ format: "ptime:%d"
+ },
+ { //a=maxptime:60
+ name: 'maxptime',
+ reg: /^maxptime:(\d*)/,
+ format: "maxptime:%d"
+ },
+ { //a=sendrecv
+ name: 'direction',
+ reg: /^(sendrecv|recvonly|sendonly|inactive)/
+ },
+ { //a=ice-lite
+ name: 'icelite',
+ reg: /^(ice-lite)/
+ },
+ { //a=ice-ufrag:F7gI
+ name: 'iceUfrag',
+ reg: /^ice-ufrag:(\S*)/,
+ format: "ice-ufrag:%s"
+ },
+ { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
+ name: 'icePwd',
+ reg: /^ice-pwd:(\S*)/,
+ format: "ice-pwd:%s"
+ },
+ { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
+ name: 'fingerprint',
+ reg: /^fingerprint:(\S*) (\S*)/,
+ names: ['type', 'hash'],
+ format: "fingerprint:%s %s"
+ },
+ {
+ //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
+ //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
+ //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
+ //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
+ //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
+ push:'candidates',
+ reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
+ names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
+ format: function (o) {
+ var str = "candidate:%s %d %s %d %s %d typ %s";
-//region Stateless private utility functions
+ str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
-/**
- * Returns a random integer between min (included) and max (excluded)
- * Using Math.round() gives a non-uniform distribution!
- * @returns {number}
- */
-function generateSSRC() {
- var min = 0, max = 0xffffffff;
- return Math.floor(Math.random() * (max - min)) + min;
-};
+ // NB: candidate has three optional chunks, so %void middles one if it's missing
+ str += (o.tcptype != null) ? " tcptype %s" : "%v";
-function processVideo(session, action) {
- if (session == null || !Array.isArray(session.media)) {
- return;
- }
-
- session.media.forEach(function (mLine) {
- if (mLine.type === 'video') {
- action(mLine);
+ if (o.generation != null) {
+ str += " generation %d";
}
- });
-}
-
-function validateDescription(desc)
-{
- return desc && desc != null
- && desc.type && desc.type != ''
- && desc.sdp && desc.sdp != '';
-}
-
-function explodeRemoteSimulcast(mLine) {
-
- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
- return;
+ return str;
+ }
+ },
+ { //a=end-of-candidates (keep after the candidates line for readability)
+ name: 'endOfCandidates',
+ reg: /^(end-of-candidates)/
+ },
+ { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
+ name: 'remoteCandidates',
+ reg: /^remote-candidates:(.*)/,
+ format: "remote-candidates:%s"
+ },
+ { //a=ice-options:google-ice
+ name: 'iceOptions',
+ reg: /^ice-options:(\S*)/,
+ format: "ice-options:%s"
+ },
+ { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
+ push: "ssrcs",
+ reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
+ names: ['id', 'attribute', 'value'],
+ format: "ssrc:%d %s:%s"
+ },
+ { //a=ssrc-group:FEC 1 2
+ push: "ssrcGroups",
+ reg: /^ssrc-group:(\w*) (.*)/,
+ names: ['semantics', 'ssrcs'],
+ format: "ssrc-group:%s %s"
+ },
+ { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
+ name: "msidSemantic",
+ reg: /^msid-semantic:\s?(\w*) (\S*)/,
+ names: ['semantic', 'token'],
+ format: "msid-semantic: %s %s" // space after ":" is not accidental
+ },
+ { //a=group:BUNDLE audio video
+ push: 'groups',
+ reg: /^group:(\w*) (.*)/,
+ names: ['type', 'mids'],
+ format: "group:%s %s"
+ },
+ { //a=rtcp-mux
+ name: 'rtcpMux',
+ reg: /^(rtcp-mux)/
+ },
+ { //a=rtcp-rsize
+ name: 'rtcpRsize',
+ reg: /^(rtcp-rsize)/
+ },
+ { // any a= that we don't understand is kepts verbatim on media.invalid
+ push: 'invalid',
+ names: ["value"]
}
+ ]
+};
- var sources = parseSsrcs(mLine);
- var order = [];
-
- // Find the SIM group and explode its sources.
- var j = mLine.ssrcGroups.length;
- while (j--) {
-
- if (mLine.ssrcGroups[j].semantics !== 'SIM') {
- continue;
- }
-
- var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
+// set sensible defaults to avoid polluting the grammar with boring details
+Object.keys(grammar).forEach(function (key) {
+ var objs = grammar[key];
+ objs.forEach(function (obj) {
+ if (!obj.reg) {
+ obj.reg = /(.*)/;
+ }
+ if (!obj.format) {
+ obj.format = "%s";
+ }
+ });
+});
- for (var i = 0; i < simulcastSsrcs.length; i++) {
+},{}],70:[function(require,module,exports){
+var parser = require('./parser');
+var writer = require('./writer');
- var ssrc = simulcastSsrcs[i];
- order.push(ssrc);
+exports.write = writer;
+exports.parse = parser.parse;
+exports.parseFmtpConfig = parser.parseFmtpConfig;
+exports.parsePayloads = parser.parsePayloads;
+exports.parseRemoteCandidates = parser.parseRemoteCandidates;
- var parts = sources[ssrc].msid.split(' ');
- sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
- sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
+},{"./parser":71,"./writer":72}],71:[function(require,module,exports){
+var toIntIfInt = function (v) {
+ return String(Number(v)) === v ? Number(v) : v;
+};
- // Remove all the groups that this SSRC participates in.
- mLine.ssrcGroups.forEach(function (relatedGroup) {
- if (relatedGroup.semantics === 'SIM') {
- return;
- }
+var attachProperties = function (match, location, names, rawName) {
+ if (rawName && !names) {
+ location[rawName] = toIntIfInt(match[1]);
+ }
+ else {
+ for (var i = 0; i < names.length; i += 1) {
+ if (match[i+1] != null) {
+ location[names[i]] = toIntIfInt(match[i+1]);
+ }
+ }
+ }
+};
- var relatedSsrcs = relatedGroup.ssrcs.split(' ');
- if (relatedSsrcs.indexOf(ssrc) === -1) {
- return;
- }
+var parseReg = function (obj, location, content) {
+ var needsBlank = obj.name && obj.names;
+ if (obj.push && !location[obj.push]) {
+ location[obj.push] = [];
+ }
+ else if (needsBlank && !location[obj.name]) {
+ location[obj.name] = {};
+ }
+ var keyLocation = obj.push ?
+ {} : // blank object that will be pushed
+ needsBlank ? location[obj.name] : location; // otherwise, named location or root
- // Nuke all the related SSRCs.
- relatedSsrcs.forEach(function (relatedSSRC) {
- sources[relatedSSRC].msid = sources[ssrc].msid;
- sources[relatedSSRC].cname = sources[ssrc].cname;
- if (relatedSSRC !== ssrc) {
- order.push(relatedSSRC);
- }
- });
+ attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
- // Schedule the related group for nuking.
- })
- }
+ if (obj.push) {
+ location[obj.push].push(keyLocation);
+ }
+};
- mLine.ssrcs = writeSsrcs(sources, order);
- mLine.ssrcGroups.splice(j, 1);
- };
-}
+var grammar = require('./grammar');
+var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
-function implodeRemoteSimulcast(mLine) {
+exports.parse = function (sdp) {
+ var session = {}
+ , media = []
+ , location = session; // points at where properties go under (one of the above)
- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
- console.debug('Halt: There are no SSRC groups in the remote ' +
- 'description.');
- return;
+ // parse lines we understand
+ sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
+ var type = l[0];
+ var content = l.slice(2);
+ if (type === 'm') {
+ media.push({rtp: [], fmtp: []});
+ location = media[media.length-1]; // point at latest media line
}
- var sources = parseSsrcs(mLine);
-
- // Find the SIM group and nuke it.
- mLine.ssrcGroups.forEach(function (simulcastGroup) {
- if (simulcastGroup.semantics !== 'SIM') {
- return;
- }
-
- console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
- // Schedule the SIM group for nuking.
- simulcastGroup.nuke = true;
-
- var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
-
- // Nuke all the higher layer SSRCs.
- for (var i = 1; i < simulcastSsrcs.length; i++) {
-
- var ssrc = simulcastSsrcs[i];
- delete sources[ssrc];
+ for (var j = 0; j < (grammar[type] || []).length; j += 1) {
+ var obj = grammar[type][j];
+ if (obj.reg.test(content)) {
+ return parseReg(obj, location, content);
+ }
+ }
+ });
- // Remove all the groups that this SSRC participates in.
- mLine.ssrcGroups.forEach(function (relatedGroup) {
- if (relatedGroup.semantics === 'SIM') {
- return;
- }
+ session.media = media; // link it up
+ return session;
+};
- var relatedSsrcs = relatedGroup.ssrcs.split(' ');
- if (relatedSsrcs.indexOf(ssrc) === -1) {
- return;
- }
+var fmtpReducer = function (acc, expr) {
+ var s = expr.split('=');
+ if (s.length === 2) {
+ acc[s[0]] = toIntIfInt(s[1]);
+ }
+ return acc;
+};
- // Nuke all the related SSRCs.
- relatedSsrcs.forEach(function (relatedSSRC) {
- delete sources[relatedSSRC];
- });
+exports.parseFmtpConfig = function (str) {
+ return str.split(/\;\s?/).reduce(fmtpReducer, {});
+};
- // Schedule the related group for nuking.
- relatedGroup.nuke = true;
- })
- }
+exports.parsePayloads = function (str) {
+ return str.split(' ').map(Number);
+};
- return;
+exports.parseRemoteCandidates = function (str) {
+ var candidates = [];
+ var parts = str.split(' ').map(toIntIfInt);
+ for (var i = 0; i < parts.length; i += 3) {
+ candidates.push({
+ component: parts[i],
+ ip: parts[i + 1],
+ port: parts[i + 2]
});
+ }
+ return candidates;
+};
- mLine.ssrcs = writeSsrcs(sources);
+},{"./grammar":69}],72:[function(require,module,exports){
+var grammar = require('./grammar');
- // Nuke all the scheduled groups.
- var i = mLine.ssrcGroups.length;
- while (i--) {
- if (mLine.ssrcGroups[i].nuke) {
- mLine.ssrcGroups.splice(i, 1);
- }
- }
-}
-
-function removeGoogConference(mLine) {
- if (!mLine || !Array.isArray(mLine.invalid)) {
- return;
- }
-
- var i = mLine.invalid.length;
- while (i--) {
- if (mLine.invalid[i].value == 'x-google-flag:conference') {
- mLine.invalid.splice(i, 1);
- }
- }
-}
-
-function assertGoogConference(mLine) {
- if (!mLine) {
- return;
- }
-
- if (!Array.isArray(mLine.invalid)) {
- mLine.invalid = [];
- }
-
- if (!mLine.invalid.some(
- function (i) { return i.value === 'x-google-flag:conference' })) {
- mLine.invalid.push({'value': 'x-google-flag:conference'});
+// customized util.format - discards excess arguments and can void middle ones
+var formatRegExp = /%[sdv%]/g;
+var format = function (formatStr) {
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ return formatStr.replace(formatRegExp, function (x) {
+ if (i >= len) {
+ return x; // missing argument
}
-}
-
-//endregion
-
-//region "Private" functions
-
-/**
- *
- * @param mLine
- * @private
- */
-Simulcast.prototype._maybeInitializeLayers = function(mLine) {
-
- if (!mLine || mLine.type !== 'video') {
- return;
+ var arg = args[i];
+ i += 1;
+ switch (x) {
+ case '%%':
+ return '%';
+ case '%s':
+ return String(arg);
+ case '%d':
+ return Number(arg);
+ case '%v':
+ return '';
}
+ });
+ // NB: we discard excess arguments - they are typically undefined from makeLine
+};
- var sources = parseSsrcs(mLine);
-
- if (Object.keys(sources).length === 0) {
-
- // no sources, disable simulcast.
- if (this.layers.length !== 0) {
- this.layers = [];
- }
+var makeLine = function (type, obj, location) {
+ var str = obj.format instanceof Function ?
+ (obj.format(obj.push ? location : location[obj.name])) :
+ obj.format;
- return;
+ var args = [type + '=' + str];
+ if (obj.names) {
+ for (var i = 0; i < obj.names.length; i += 1) {
+ var n = obj.names[i];
+ if (obj.name) {
+ args.push(location[obj.name][n]);
+ }
+ else { // for mLine and push attributes
+ args.push(location[obj.names[i]]);
+ }
}
+ }
+ else {
+ args.push(location[obj.name]);
+ }
+ return format.apply(null, args);
+};
- // find the base layer (we'll reuse its msid and cname).
- var baseLayerSSRC = Object.keys(sources)[0];
- var baseLayer = sources[baseLayerSSRC];
+// RFC specified order
+// TODO: extend this with all the rest
+var defaultOuterOrder = [
+ 'v', 'o', 's', 'i',
+ 'u', 'e', 'p', 'c',
+ 'b', 't', 'r', 'z', 'a'
+];
+var defaultInnerOrder = ['i', 'c', 'b', 'a'];
- // todo(gp) handle screen sharing.
- // check if base CNAME has changed and reinitialise layers.
- if (this.layers.length > 0
- && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
- this.layers = [];
+module.exports = function (session, opts) {
+ opts = opts || {};
+ // ensure certain properties exist
+ if (session.version == null) {
+ session.version = 0; // "v=0" must be there (only defined version atm)
+ }
+ if (session.name == null) {
+ session.name = " "; // "s= " must be there if no meaningful name set
+ }
+ session.media.forEach(function (mLine) {
+ if (mLine.payloads == null) {
+ mLine.payloads = "";
}
+ });
- // (re)initialise layers
- if (this.layers.length < 1) {
+ var outerOrder = opts.outerOrder || defaultOuterOrder;
+ var innerOrder = opts.innerOrder || defaultInnerOrder;
+ var sdp = [];
- // first push the base layer.
- this.layers.push({
- ssrc: baseLayerSSRC,
- msid: baseLayer.msid,
- cname: baseLayer.cname
+ // loop through outerOrder for matching properties on session
+ outerOrder.forEach(function (type) {
+ grammar[type].forEach(function (obj) {
+ if (obj.name in session && session[obj.name] != null) {
+ sdp.push(makeLine(type, obj, session));
+ }
+ else if (obj.push in session && session[obj.push] != null) {
+ session[obj.push].forEach(function (el) {
+ sdp.push(makeLine(type, obj, el));
});
+ }
+ });
+ });
- var rtx = false; // RFC 4588
- if (Array.isArray(mLine.rtp)) {
- rtx = mLine.rtp.some(
- function (rtpmap) { return rtpmap.codec === 'rtx'; });
- }
+ // then for each media line, follow the innerOrder
+ session.media.forEach(function (mLine) {
+ sdp.push(makeLine('m', grammar.m[0], mLine));
- if (rtx) {
- this.layers[0].rtx = generateSSRC();
+ innerOrder.forEach(function (type) {
+ grammar[type].forEach(function (obj) {
+ if (obj.name in mLine && mLine[obj.name] != null) {
+ sdp.push(makeLine(type, obj, mLine));
}
-
- // now push additional layers.
- for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
-
- var layer = { ssrc: generateSSRC() };
- if (rtx) {
- layer.rtx = generateSSRC();
- }
-
- this.layers.push(layer);
+ else if (obj.push in mLine && mLine[obj.push] != null) {
+ mLine[obj.push].forEach(function (el) {
+ sdp.push(makeLine(type, obj, el));
+ });
}
- }
+ });
+ });
+ });
+
+ return sdp.join('\r\n') + '\r\n';
};
-/**
+},{"./grammar":69}],73:[function(require,module,exports){
+/* Copyright @ 2015 Atlassian Pty Ltd
*
- * @param mLine
- * @private
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
-Simulcast.prototype._restoreSimulcastView = function(mLine) {
- if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
-
- var sources = {};
- var msid = this.layers[0].msid;
- var cname = this.layers[0].cname;
- var simulcastSsrcs = [];
- var ssrcGroups = [];
+var transform = require('sdp-transform');
+var transformUtils = require('./transform-utils');
+var parseSsrcs = transformUtils.parseSsrcs;
+var writeSsrcs = transformUtils.writeSsrcs;
- for (var i = 0; i < this.layers.length; i++) {
- var layer = this.layers[i];
+//region Constants
- sources[layer.ssrc] = { msid: msid, cname: cname };
- simulcastSsrcs.push(layer.ssrc);
+var DEFAULT_NUM_OF_LAYERS = 3;
- if (layer.rtx) {
+//endregion
- sources[layer.rtx] = {
- msid: msid,
- cname: cname
- }
+//region Ctor
- ssrcGroups.push({
- semantics: 'FID',
- ssrcs: [layer.ssrc, layer.rtx].join(' ')
- });
- }
- }
+function Simulcast(options) {
- ssrcGroups.push({
- semantics: 'SIM',
- ssrcs: simulcastSsrcs.join(' ')
- });
+ this.options = options ? options : {};
- mLine.ssrcGroups = ssrcGroups;
- mLine.ssrcs = writeSsrcs(sources);
+ if (!this.options.numOfLayers) {
+ this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
}
+
+ this.layers = [];
}
//endregion
-//region "Public" functions
-
-Simulcast.prototype.isSupported = function () {
- return window.chrome;
-
- // TODO this needs improvements. For example I doubt that Chrome in Android
- // has simulcast support. Also, only recent versions of Chromium have native
- // simulcast support.
-}
+//region Stateless private utility functions
/**
- *
- * @param desc
- * @returns {RTCSessionDescription}
+ * Returns a random integer between min (included) and max (excluded)
+ * Using Math.round() gives a non-uniform distribution!
+ * @returns {number}
*/
-Simulcast.prototype.mungeRemoteDescription = function (desc) {
+function generateSSRC() {
+ var min = 0, max = 0xffffffff;
+ return Math.floor(Math.random() * (max - min)) + min;
+};
- if (!validateDescription(desc)) {
- return desc;
+function processVideo(session, action) {
+ if (session == null || !Array.isArray(session.media)) {
+ return;
}
- var session = transform.parse(desc.sdp);
+ session.media.forEach(function (mLine) {
+ if (mLine.type === 'video') {
+ action(mLine);
+ }
+ });
+}
- var self = this;
- processVideo(session, function (mLine) {
+function validateDescription(desc)
+{
+ return desc && desc != null
+ && desc.type && desc.type != ''
+ && desc.sdp && desc.sdp != '';
+}
- // Handle simulcast reception.
- if (self.options.explodeRemoteSimulcast) {
- explodeRemoteSimulcast(mLine);
- } else {
- implodeRemoteSimulcast(mLine);
+function explodeRemoteSimulcast(mLine) {
+
+ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
+ return;
+ }
+
+ var sources = parseSsrcs(mLine);
+ var order = [];
+
+ // Find the SIM group and explode its sources.
+ var j = mLine.ssrcGroups.length;
+ while (j--) {
+
+ if (mLine.ssrcGroups[j].semantics !== 'SIM') {
+ continue;
}
- // If native simulcast is enabled, we must append the x-goog-conference
- // attribute to the SDP.
- if (self.layers.length < 1) {
- removeGoogConference(mLine);
- } else {
- assertGoogConference(mLine);
+ var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
+
+ for (var i = 0; i < simulcastSsrcs.length; i++) {
+
+ var ssrc = simulcastSsrcs[i];
+ order.push(ssrc);
+
+ var parts = sources[ssrc].msid.split(' ');
+ sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
+ sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
+
+ // Remove all the groups that this SSRC participates in.
+ mLine.ssrcGroups.forEach(function (relatedGroup) {
+ if (relatedGroup.semantics === 'SIM') {
+ return;
+ }
+
+ var relatedSsrcs = relatedGroup.ssrcs.split(' ');
+ if (relatedSsrcs.indexOf(ssrc) === -1) {
+ return;
+ }
+
+ // Nuke all the related SSRCs.
+ relatedSsrcs.forEach(function (relatedSSRC) {
+ sources[relatedSSRC].msid = sources[ssrc].msid;
+ sources[relatedSSRC].cname = sources[ssrc].cname;
+ if (relatedSSRC !== ssrc) {
+ order.push(relatedSSRC);
+ }
+ });
+
+ // Schedule the related group for nuking.
+ })
}
- });
- return new RTCSessionDescription({
- type: desc.type,
- sdp: transform.write(session)
- });
-};
+ mLine.ssrcs = writeSsrcs(sources, order);
+ mLine.ssrcGroups.splice(j, 1);
+ };
+}
-/**
- *
- * @param desc
- * @returns {RTCSessionDescription}
- */
-Simulcast.prototype.mungeLocalDescription = function (desc) {
+function implodeRemoteSimulcast(mLine) {
- if (!validateDescription(desc) || !this.isSupported()) {
- return desc;
+ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
+ console.info('Halt: There are no SSRC groups in the remote ' +
+ 'description.');
+ return;
}
- var session = transform.parse(desc.sdp);
+ var sources = parseSsrcs(mLine);
- var self = this;
- processVideo(session, function (mLine) {
- // Initialize native simulcast layers, if not already done.
- self._maybeInitializeLayers(mLine);
+ // Find the SIM group and nuke it.
+ mLine.ssrcGroups.forEach(function (simulcastGroup) {
+ if (simulcastGroup.semantics !== 'SIM') {
+ return;
+ }
- // Update the SDP with the simulcast layers.
- self._restoreSimulcastView(mLine);
- });
+ console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
+ // Schedule the SIM group for nuking.
+ simulcastGroup.nuke = true;
- return new RTCSessionDescription({
- type: desc.type,
- sdp: transform.write(session)
+ var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
+
+ // Nuke all the higher layer SSRCs.
+ for (var i = 1; i < simulcastSsrcs.length; i++) {
+
+ var ssrc = simulcastSsrcs[i];
+ delete sources[ssrc];
+
+ // Remove all the groups that this SSRC participates in.
+ mLine.ssrcGroups.forEach(function (relatedGroup) {
+ if (relatedGroup.semantics === 'SIM') {
+ return;
+ }
+
+ var relatedSsrcs = relatedGroup.ssrcs.split(' ');
+ if (relatedSsrcs.indexOf(ssrc) === -1) {
+ return;
+ }
+
+ // Nuke all the related SSRCs.
+ relatedSsrcs.forEach(function (relatedSSRC) {
+ delete sources[relatedSSRC];
+ });
+
+ // Schedule the related group for nuking.
+ relatedGroup.nuke = true;
+ })
+ }
+
+ return;
});
-};
-//endregion
+ mLine.ssrcs = writeSsrcs(sources);
-module.exports = Simulcast;
+ // Nuke all the scheduled groups.
+ var i = mLine.ssrcGroups.length;
+ while (i--) {
+ if (mLine.ssrcGroups[i].nuke) {
+ mLine.ssrcGroups.splice(i, 1);
+ }
+ }
+}
-},{"./transform-utils":70,"sdp-transform":72}],70:[function(require,module,exports){
-/* Copyright @ 2015 Atlassian Pty Ltd
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+function removeGoogConference(mLine) {
+ if (!mLine || !Array.isArray(mLine.invalid)) {
+ return;
+ }
-exports.writeSsrcs = function(sources, order) {
- var ssrcs = [];
+ var i = mLine.invalid.length;
+ while (i--) {
+ if (mLine.invalid[i].value == 'x-google-flag:conference') {
+ mLine.invalid.splice(i, 1);
+ }
+ }
+}
- // expand sources to ssrcs
- if (typeof sources !== 'undefined' &&
- Object.keys(sources).length !== 0) {
+function assertGoogConference(mLine) {
+ if (!mLine) {
+ return;
+ }
- if (Array.isArray(order)) {
- for (var i = 0; i < order.length; i++) {
- var ssrc = order[i];
- var source = sources[ssrc];
- Object.keys(source).forEach(function (attribute) {
- ssrcs.push({
- id: ssrc,
- attribute: attribute,
- value: source[attribute]
- });
- });
- }
- } else {
- Object.keys(sources).forEach(function (ssrc) {
- var source = sources[ssrc];
- Object.keys(source).forEach(function (attribute) {
- ssrcs.push({
- id: ssrc,
- attribute: attribute,
- value: source[attribute]
- });
- });
- });
+ if (!Array.isArray(mLine.invalid)) {
+ mLine.invalid = [];
}
- }
- return ssrcs;
-};
+ if (!mLine.invalid.some(
+ function (i) { return i.value === 'x-google-flag:conference' })) {
+ mLine.invalid.push({'value': 'x-google-flag:conference'});
+ }
+}
-exports.parseSsrcs = function (mLine) {
- var sources = {};
- // group sources attributes by ssrc.
- if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
- mLine.ssrcs.forEach(function (ssrc) {
- if (!sources[ssrc.id])
- sources[ssrc.id] = {};
- sources[ssrc.id][ssrc.attribute] = ssrc.value;
- });
- }
- return sources;
-};
+//endregion
+//region "Private" functions
-},{}],71:[function(require,module,exports){
-var grammar = module.exports = {
- v: [{
- name: 'version',
- reg: /^(\d*)$/
- }],
- o: [{ //o=- 20518 0 IN IP4 203.0.113.1
- // NB: sessionId will be a String in most cases because it is huge
- name: 'origin',
- reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
- names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
- format: "%s %s %d %s IP%d %s"
- }],
- // default parsing of these only (though some of these feel outdated)
- s: [{ name: 'name' }],
- i: [{ name: 'description' }],
- u: [{ name: 'uri' }],
- e: [{ name: 'email' }],
- p: [{ name: 'phone' }],
- z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
- r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
- //k: [{}], // outdated thing ignored
- t: [{ //t=0 0
- name: 'timing',
- reg: /^(\d*) (\d*)/,
- names: ['start', 'stop'],
- format: "%d %d"
- }],
- c: [{ //c=IN IP4 10.47.197.26
- name: 'connection',
- reg: /^IN IP(\d) (\S*)/,
- names: ['version', 'ip'],
- format: "IN IP%d %s"
- }],
- b: [{ //b=AS:4000
- push: 'bandwidth',
- reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
- names: ['type', 'limit'],
- format: "%s:%s"
- }],
- m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
- // NB: special - pushes to session
- // TODO: rtp/fmtp should be filtered by the payloads found here?
- reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
- names: ['type', 'port', 'protocol', 'payloads'],
- format: "%s %d %s %s"
- }],
- a: [
- { //a=rtpmap:110 opus/48000/2
- push: 'rtp',
- reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
- names: ['payload', 'codec', 'rate', 'encoding'],
- format: function (o) {
- return (o.encoding) ?
- "rtpmap:%d %s/%s/%s":
- "rtpmap:%d %s/%s";
- }
- },
- { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
- push: 'fmtp',
- reg: /^fmtp:(\d*) (\S*)/,
- names: ['payload', 'config'],
- format: "fmtp:%d %s"
- },
- { //a=control:streamid=0
- name: 'control',
- reg: /^control:(.*)/,
- format: "control:%s"
- },
- { //a=rtcp:65179 IN IP4 193.84.77.194
- name: 'rtcp',
- reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
- names: ['port', 'netType', 'ipVer', 'address'],
- format: function (o) {
- return (o.address != null) ?
- "rtcp:%d %s IP%d %s":
- "rtcp:%d";
- }
- },
- { //a=rtcp-fb:98 trr-int 100
- push: 'rtcpFbTrrInt',
- reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
- names: ['payload', 'value'],
- format: "rtcp-fb:%d trr-int %d"
- },
- { //a=rtcp-fb:98 nack rpsi
- push: 'rtcpFb',
- reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
- names: ['payload', 'type', 'subtype'],
- format: function (o) {
- return (o.subtype != null) ?
- "rtcp-fb:%s %s %s":
- "rtcp-fb:%s %s";
- }
- },
- { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
- //a=extmap:1/recvonly URI-gps-string
- push: 'ext',
- reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
- names: ['value', 'uri', 'config'], // value may include "/direction" suffix
- format: function (o) {
- return (o.config != null) ?
- "extmap:%s %s %s":
- "extmap:%s %s";
- }
- },
- {
- //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
- push: 'crypto',
- reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
- names: ['id', 'suite', 'config', 'sessionConfig'],
- format: function (o) {
- return (o.sessionConfig != null) ?
- "crypto:%d %s %s %s":
- "crypto:%d %s %s";
- }
- },
- { //a=setup:actpass
- name: 'setup',
- reg: /^setup:(\w*)/,
- format: "setup:%s"
- },
- { //a=mid:1
- name: 'mid',
- reg: /^mid:([^\s]*)/,
- format: "mid:%s"
- },
- { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
- name: 'msid',
- reg: /^msid:(.*)/,
- format: "msid:%s"
- },
- { //a=ptime:20
- name: 'ptime',
- reg: /^ptime:(\d*)/,
- format: "ptime:%d"
- },
- { //a=maxptime:60
- name: 'maxptime',
- reg: /^maxptime:(\d*)/,
- format: "maxptime:%d"
- },
- { //a=sendrecv
- name: 'direction',
- reg: /^(sendrecv|recvonly|sendonly|inactive)/
- },
- { //a=ice-lite
- name: 'icelite',
- reg: /^(ice-lite)/
- },
- { //a=ice-ufrag:F7gI
- name: 'iceUfrag',
- reg: /^ice-ufrag:(\S*)/,
- format: "ice-ufrag:%s"
- },
- { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
- name: 'icePwd',
- reg: /^ice-pwd:(\S*)/,
- format: "ice-pwd:%s"
- },
- { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
- name: 'fingerprint',
- reg: /^fingerprint:(\S*) (\S*)/,
- names: ['type', 'hash'],
- format: "fingerprint:%s %s"
- },
- {
- //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
- //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
- //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
- push:'candidates',
- reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
- names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
- format: function (o) {
- var str = "candidate:%s %d %s %d %s %d typ %s";
- // NB: candidate has two optional chunks, so %void middle one if it's missing
- str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
- if (o.generation != null) {
- str += " generation %d";
- }
- return str;
- }
- },
- { //a=end-of-candidates (keep after the candidates line for readability)
- name: 'endOfCandidates',
- reg: /^(end-of-candidates)/
- },
- { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
- name: 'remoteCandidates',
- reg: /^remote-candidates:(.*)/,
- format: "remote-candidates:%s"
- },
- { //a=ice-options:google-ice
- name: 'iceOptions',
- reg: /^ice-options:(\S*)/,
- format: "ice-options:%s"
- },
- { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
- push: "ssrcs",
- reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
- names: ['id', 'attribute', 'value'],
- format: "ssrc:%d %s:%s"
- },
- { //a=ssrc-group:FEC 1 2
- push: "ssrcGroups",
- reg: /^ssrc-group:(\w*) (.*)/,
- names: ['semantics', 'ssrcs'],
- format: "ssrc-group:%s %s"
- },
- { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
- name: "msidSemantic",
- reg: /^msid-semantic:\s?(\w*) (\S*)/,
- names: ['semantic', 'token'],
- format: "msid-semantic: %s %s" // space after ":" is not accidental
- },
- { //a=group:BUNDLE audio video
- push: 'groups',
- reg: /^group:(\w*) (.*)/,
- names: ['type', 'mids'],
- format: "group:%s %s"
- },
- { //a=rtcp-mux
- name: 'rtcpMux',
- reg: /^(rtcp-mux)/
- },
- { //a=rtcp-rsize
- name: 'rtcpRsize',
- reg: /^(rtcp-rsize)/
- },
- { // any a= that we don't understand is kepts verbatim on media.invalid
- push: 'invalid',
- names: ["value"]
- }
- ]
-};
-
-// set sensible defaults to avoid polluting the grammar with boring details
-Object.keys(grammar).forEach(function (key) {
- var objs = grammar[key];
- objs.forEach(function (obj) {
- if (!obj.reg) {
- obj.reg = /(.*)/;
- }
- if (!obj.format) {
- obj.format = "%s";
- }
- });
-});
-
-},{}],72:[function(require,module,exports){
-var parser = require('./parser');
-var writer = require('./writer');
-
-exports.write = writer;
-exports.parse = parser.parse;
-exports.parseFmtpConfig = parser.parseFmtpConfig;
-exports.parsePayloads = parser.parsePayloads;
-exports.parseRemoteCandidates = parser.parseRemoteCandidates;
-
-},{"./parser":73,"./writer":74}],73:[function(require,module,exports){
-var toIntIfInt = function (v) {
- return String(Number(v)) === v ? Number(v) : v;
-};
-
-var attachProperties = function (match, location, names, rawName) {
- if (rawName && !names) {
- location[rawName] = toIntIfInt(match[1]);
- }
- else {
- for (var i = 0; i < names.length; i += 1) {
- if (match[i+1] != null) {
- location[names[i]] = toIntIfInt(match[i+1]);
- }
- }
- }
-};
-
-var parseReg = function (obj, location, content) {
- var needsBlank = obj.name && obj.names;
- if (obj.push && !location[obj.push]) {
- location[obj.push] = [];
- }
- else if (needsBlank && !location[obj.name]) {
- location[obj.name] = {};
- }
- var keyLocation = obj.push ?
- {} : // blank object that will be pushed
- needsBlank ? location[obj.name] : location; // otherwise, named location or root
-
- attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
-
- if (obj.push) {
- location[obj.push].push(keyLocation);
- }
-};
-
-var grammar = require('./grammar');
-var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
-
-exports.parse = function (sdp) {
- var session = {}
- , media = []
- , location = session; // points at where properties go under (one of the above)
-
- // parse lines we understand
- sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
- var type = l[0];
- var content = l.slice(2);
- if (type === 'm') {
- media.push({rtp: [], fmtp: []});
- location = media[media.length-1]; // point at latest media line
- }
+/**
+ *
+ * @param mLine
+ * @private
+ */
+Simulcast.prototype._maybeInitializeLayers = function(mLine) {
- for (var j = 0; j < (grammar[type] || []).length; j += 1) {
- var obj = grammar[type][j];
- if (obj.reg.test(content)) {
- return parseReg(obj, location, content);
- }
+ if (!mLine || mLine.type !== 'video') {
+ return;
}
- });
-
- session.media = media; // link it up
- return session;
-};
-
-var fmtpReducer = function (acc, expr) {
- var s = expr.split('=');
- if (s.length === 2) {
- acc[s[0]] = toIntIfInt(s[1]);
- }
- return acc;
-};
-
-exports.parseFmtpConfig = function (str) {
- return str.split(';').reduce(fmtpReducer, {});
-};
-
-exports.parsePayloads = function (str) {
- return str.split(' ').map(Number);
-};
-
-exports.parseRemoteCandidates = function (str) {
- var candidates = [];
- var parts = str.split(' ').map(toIntIfInt);
- for (var i = 0; i < parts.length; i += 3) {
- candidates.push({
- component: parts[i],
- ip: parts[i + 1],
- port: parts[i + 2]
- });
- }
- return candidates;
-};
-},{"./grammar":71}],74:[function(require,module,exports){
-var grammar = require('./grammar');
+ var sources = parseSsrcs(mLine);
-// customized util.format - discards excess arguments and can void middle ones
-var formatRegExp = /%[sdv%]/g;
-var format = function (formatStr) {
- var i = 1;
- var args = arguments;
- var len = args.length;
- return formatStr.replace(formatRegExp, function (x) {
- if (i >= len) {
- return x; // missing argument
- }
- var arg = args[i];
- i += 1;
- switch (x) {
- case '%%':
- return '%';
- case '%s':
- return String(arg);
- case '%d':
- return Number(arg);
- case '%v':
- return '';
- }
- });
- // NB: we discard excess arguments - they are typically undefined from makeLine
-};
+ if (Object.keys(sources).length === 0) {
-var makeLine = function (type, obj, location) {
- var str = obj.format instanceof Function ?
- (obj.format(obj.push ? location : location[obj.name])) :
- obj.format;
+ // no sources, disable simulcast.
+ if (this.layers.length !== 0) {
+ this.layers = [];
+ }
- var args = [type + '=' + str];
- if (obj.names) {
- for (var i = 0; i < obj.names.length; i += 1) {
- var n = obj.names[i];
- if (obj.name) {
- args.push(location[obj.name][n]);
- }
- else { // for mLine and push attributes
- args.push(location[obj.names[i]]);
- }
+ return;
}
- }
- else {
- args.push(location[obj.name]);
- }
- return format.apply(null, args);
-};
-// RFC specified order
-// TODO: extend this with all the rest
-var defaultOuterOrder = [
- 'v', 'o', 's', 'i',
- 'u', 'e', 'p', 'c',
- 'b', 't', 'r', 'z', 'a'
-];
-var defaultInnerOrder = ['i', 'c', 'b', 'a'];
+ // find the base layer (we'll reuse its msid and cname).
+ var baseLayerSSRC = Object.keys(sources)[0];
+ var baseLayer = sources[baseLayerSSRC];
+ // todo(gp) handle screen sharing.
-module.exports = function (session, opts) {
- opts = opts || {};
- // ensure certain properties exist
- if (session.version == null) {
- session.version = 0; // "v=0" must be there (only defined version atm)
- }
- if (session.name == null) {
- session.name = " "; // "s= " must be there if no meaningful name set
- }
- session.media.forEach(function (mLine) {
- if (mLine.payloads == null) {
- mLine.payloads = "";
+ // check if base CNAME has changed and reinitialise layers.
+ if (this.layers.length > 0
+ && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
+ this.layers = [];
}
- });
- var outerOrder = opts.outerOrder || defaultOuterOrder;
- var innerOrder = opts.innerOrder || defaultInnerOrder;
- var sdp = [];
-
- // loop through outerOrder for matching properties on session
- outerOrder.forEach(function (type) {
- grammar[type].forEach(function (obj) {
- if (obj.name in session && session[obj.name] != null) {
- sdp.push(makeLine(type, obj, session));
- }
- else if (obj.push in session && session[obj.push] != null) {
- session[obj.push].forEach(function (el) {
- sdp.push(makeLine(type, obj, el));
- });
- }
- });
- });
+ // (re)initialise layers
+ if (this.layers.length < 1) {
- // then for each media line, follow the innerOrder
- session.media.forEach(function (mLine) {
- sdp.push(makeLine('m', grammar.m[0], mLine));
+ // first push the base layer.
+ this.layers.push({
+ ssrc: baseLayerSSRC,
+ msid: baseLayer.msid,
+ cname: baseLayer.cname
+ });
- innerOrder.forEach(function (type) {
- grammar[type].forEach(function (obj) {
- if (obj.name in mLine && mLine[obj.name] != null) {
- sdp.push(makeLine(type, obj, mLine));
+ var rtx = false; // RFC 4588
+ if (Array.isArray(mLine.rtp)) {
+ rtx = mLine.rtp.some(
+ function (rtpmap) { return rtpmap.codec === 'rtx'; });
}
- else if (obj.push in mLine && mLine[obj.push] != null) {
- mLine[obj.push].forEach(function (el) {
- sdp.push(makeLine(type, obj, el));
- });
+
+ if (rtx) {
+ this.layers[0].rtx = generateSSRC();
}
- });
- });
- });
- return sdp.join('\r\n') + '\r\n';
-};
+ // now push additional layers.
+ for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
-},{"./grammar":71}],75:[function(require,module,exports){
-var grammar = module.exports = {
- v: [{
- name: 'version',
- reg: /^(\d*)$/
- }],
- o: [{ //o=- 20518 0 IN IP4 203.0.113.1
- // NB: sessionId will be a String in most cases because it is huge
- name: 'origin',
- reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
- names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
- format: "%s %s %d %s IP%d %s"
- }],
- // default parsing of these only (though some of these feel outdated)
- s: [{ name: 'name' }],
- i: [{ name: 'description' }],
- u: [{ name: 'uri' }],
- e: [{ name: 'email' }],
- p: [{ name: 'phone' }],
- z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
- r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
- //k: [{}], // outdated thing ignored
- t: [{ //t=0 0
- name: 'timing',
- reg: /^(\d*) (\d*)/,
- names: ['start', 'stop'],
- format: "%d %d"
- }],
- c: [{ //c=IN IP4 10.47.197.26
- name: 'connection',
- reg: /^IN IP(\d) (\S*)/,
- names: ['version', 'ip'],
- format: "IN IP%d %s"
- }],
- b: [{ //b=AS:4000
- push: 'bandwidth',
- reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
- names: ['type', 'limit'],
- format: "%s:%s"
- }],
- m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
- // NB: special - pushes to session
- // TODO: rtp/fmtp should be filtered by the payloads found here?
- reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
- names: ['type', 'port', 'protocol', 'payloads'],
- format: "%s %d %s %s"
- }],
- a: [
- { //a=rtpmap:110 opus/48000/2
- push: 'rtp',
- reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
- names: ['payload', 'codec', 'rate', 'encoding'],
- format: function (o) {
- return (o.encoding) ?
- "rtpmap:%d %s/%s/%s":
- "rtpmap:%d %s/%s";
- }
- },
- {
- //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
- //a=fmtp:111 minptime=10; useinbandfec=1
- push: 'fmtp',
- reg: /^fmtp:(\d*) ([\S| ]*)/,
- names: ['payload', 'config'],
- format: "fmtp:%d %s"
- },
- { //a=control:streamid=0
- name: 'control',
- reg: /^control:(.*)/,
- format: "control:%s"
- },
- { //a=rtcp:65179 IN IP4 193.84.77.194
- name: 'rtcp',
- reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
- names: ['port', 'netType', 'ipVer', 'address'],
- format: function (o) {
- return (o.address != null) ?
- "rtcp:%d %s IP%d %s":
- "rtcp:%d";
- }
- },
- { //a=rtcp-fb:98 trr-int 100
- push: 'rtcpFbTrrInt',
- reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
- names: ['payload', 'value'],
- format: "rtcp-fb:%d trr-int %d"
- },
- { //a=rtcp-fb:98 nack rpsi
- push: 'rtcpFb',
- reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
- names: ['payload', 'type', 'subtype'],
- format: function (o) {
- return (o.subtype != null) ?
- "rtcp-fb:%s %s %s":
- "rtcp-fb:%s %s";
- }
- },
- { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
- //a=extmap:1/recvonly URI-gps-string
- push: 'ext',
- reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
- names: ['value', 'uri', 'config'], // value may include "/direction" suffix
- format: function (o) {
- return (o.config != null) ?
- "extmap:%s %s %s":
- "extmap:%s %s";
- }
- },
- {
- //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
- push: 'crypto',
- reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
- names: ['id', 'suite', 'config', 'sessionConfig'],
- format: function (o) {
- return (o.sessionConfig != null) ?
- "crypto:%d %s %s %s":
- "crypto:%d %s %s";
- }
- },
- { //a=setup:actpass
- name: 'setup',
- reg: /^setup:(\w*)/,
- format: "setup:%s"
- },
- { //a=mid:1
- name: 'mid',
- reg: /^mid:([^\s]*)/,
- format: "mid:%s"
- },
- { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
- name: 'msid',
- reg: /^msid:(.*)/,
- format: "msid:%s"
- },
- { //a=ptime:20
- name: 'ptime',
- reg: /^ptime:(\d*)/,
- format: "ptime:%d"
- },
- { //a=maxptime:60
- name: 'maxptime',
- reg: /^maxptime:(\d*)/,
- format: "maxptime:%d"
- },
- { //a=sendrecv
- name: 'direction',
- reg: /^(sendrecv|recvonly|sendonly|inactive)/
- },
- { //a=ice-lite
- name: 'icelite',
- reg: /^(ice-lite)/
- },
- { //a=ice-ufrag:F7gI
- name: 'iceUfrag',
- reg: /^ice-ufrag:(\S*)/,
- format: "ice-ufrag:%s"
- },
- { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
- name: 'icePwd',
- reg: /^ice-pwd:(\S*)/,
- format: "ice-pwd:%s"
- },
- { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
- name: 'fingerprint',
- reg: /^fingerprint:(\S*) (\S*)/,
- names: ['type', 'hash'],
- format: "fingerprint:%s %s"
- },
- {
- //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
- //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
- //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
- push:'candidates',
- reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
- names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
- format: function (o) {
- var str = "candidate:%s %d %s %d %s %d typ %s";
- // NB: candidate has two optional chunks, so %void middle one if it's missing
- str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
- if (o.generation != null) {
- str += " generation %d";
- }
- return str;
- }
- },
- { //a=end-of-candidates (keep after the candidates line for readability)
- name: 'endOfCandidates',
- reg: /^(end-of-candidates)/
- },
- { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
- name: 'remoteCandidates',
- reg: /^remote-candidates:(.*)/,
- format: "remote-candidates:%s"
- },
- { //a=ice-options:google-ice
- name: 'iceOptions',
- reg: /^ice-options:(\S*)/,
- format: "ice-options:%s"
- },
- { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
- push: "ssrcs",
- reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
- names: ['id', 'attribute', 'value'],
- format: "ssrc:%d %s:%s"
- },
- { //a=ssrc-group:FEC 1 2
- push: "ssrcGroups",
- reg: /^ssrc-group:(\w*) (.*)/,
- names: ['semantics', 'ssrcs'],
- format: "ssrc-group:%s %s"
- },
- { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
- name: "msidSemantic",
- reg: /^msid-semantic:\s?(\w*) (\S*)/,
- names: ['semantic', 'token'],
- format: "msid-semantic: %s %s" // space after ":" is not accidental
- },
- { //a=group:BUNDLE audio video
- push: 'groups',
- reg: /^group:(\w*) (.*)/,
- names: ['type', 'mids'],
- format: "group:%s %s"
- },
- { //a=rtcp-mux
- name: 'rtcpMux',
- reg: /^(rtcp-mux)/
- },
- { //a=rtcp-rsize
- name: 'rtcpRsize',
- reg: /^(rtcp-rsize)/
- },
- { // any a= that we don't understand is kepts verbatim on media.invalid
- push: 'invalid',
- names: ["value"]
+ var layer = { ssrc: generateSSRC() };
+ if (rtx) {
+ layer.rtx = generateSSRC();
+ }
+
+ this.layers.push(layer);
+ }
}
- ]
};
-// set sensible defaults to avoid polluting the grammar with boring details
-Object.keys(grammar).forEach(function (key) {
- var objs = grammar[key];
- objs.forEach(function (obj) {
- if (!obj.reg) {
- obj.reg = /(.*)/;
+/**
+ *
+ * @param mLine
+ * @private
+ */
+Simulcast.prototype._restoreSimulcastView = function(mLine) {
+ if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
+
+ var sources = {};
+
+ var msid = this.layers[0].msid;
+ var cname = this.layers[0].cname;
+ var simulcastSsrcs = [];
+ var ssrcGroups = [];
+
+ for (var i = 0; i < this.layers.length; i++) {
+ var layer = this.layers[i];
+
+ sources[layer.ssrc] = { msid: msid, cname: cname };
+ simulcastSsrcs.push(layer.ssrc);
+
+ if (layer.rtx) {
+
+ sources[layer.rtx] = {
+ msid: msid,
+ cname: cname
+ }
+
+ ssrcGroups.push({
+ semantics: 'FID',
+ ssrcs: [layer.ssrc, layer.rtx].join(' ')
+ });
+ }
+ }
+
+ ssrcGroups.push({
+ semantics: 'SIM',
+ ssrcs: simulcastSsrcs.join(' ')
+ });
+
+ mLine.ssrcGroups = ssrcGroups;
+ mLine.ssrcs = writeSsrcs(sources);
}
- if (!obj.format) {
- obj.format = "%s";
+}
+
+//endregion
+
+//region "Public" functions
+
+Simulcast.prototype.isSupported = function () {
+ return window.chrome;
+
+ // TODO this needs improvements. For example I doubt that Chrome in Android
+ // has simulcast support. Also, only recent versions of Chromium have native
+ // simulcast support.
+}
+
+/**
+ *
+ * @param desc
+ * @returns {RTCSessionDescription}
+ */
+Simulcast.prototype.mungeRemoteDescription = function (desc) {
+
+ if (!validateDescription(desc)) {
+ return desc;
}
- });
-});
-},{}],76:[function(require,module,exports){
-arguments[4][72][0].apply(exports,arguments)
-},{"./parser":77,"./writer":78,"dup":72}],77:[function(require,module,exports){
-var toIntIfInt = function (v) {
- return String(Number(v)) === v ? Number(v) : v;
+ var session = transform.parse(desc.sdp);
+
+ var self = this;
+ processVideo(session, function (mLine) {
+
+ // Handle simulcast reception.
+ if (self.options.explodeRemoteSimulcast) {
+ explodeRemoteSimulcast(mLine);
+ } else {
+ implodeRemoteSimulcast(mLine);
+ }
+
+ // If native simulcast is enabled, we must append the x-goog-conference
+ // attribute to the SDP.
+ if (self.layers.length < 1) {
+ removeGoogConference(mLine);
+ } else {
+ assertGoogConference(mLine);
+ }
+ });
+
+ return new RTCSessionDescription({
+ type: desc.type,
+ sdp: transform.write(session)
+ });
};
-var attachProperties = function (match, location, names, rawName) {
- if (rawName && !names) {
- location[rawName] = toIntIfInt(match[1]);
- }
- else {
- for (var i = 0; i < names.length; i += 1) {
- if (match[i+1] != null) {
- location[names[i]] = toIntIfInt(match[i+1]);
- }
+/**
+ *
+ * @param desc
+ * @returns {RTCSessionDescription}
+ */
+Simulcast.prototype.mungeLocalDescription = function (desc) {
+
+ if (!validateDescription(desc) || !this.isSupported()) {
+ return desc;
}
- }
-};
-var parseReg = function (obj, location, content) {
- var needsBlank = obj.name && obj.names;
- if (obj.push && !location[obj.push]) {
- location[obj.push] = [];
- }
- else if (needsBlank && !location[obj.name]) {
- location[obj.name] = {};
- }
- var keyLocation = obj.push ?
- {} : // blank object that will be pushed
- needsBlank ? location[obj.name] : location; // otherwise, named location or root
+ var session = transform.parse(desc.sdp);
- attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
+ var self = this;
+ processVideo(session, function (mLine) {
+ // Initialize native simulcast layers, if not already done.
+ self._maybeInitializeLayers(mLine);
- if (obj.push) {
- location[obj.push].push(keyLocation);
- }
+ // Update the SDP with the simulcast layers.
+ self._restoreSimulcastView(mLine);
+ });
+
+ return new RTCSessionDescription({
+ type: desc.type,
+ sdp: transform.write(session)
+ });
};
-var grammar = require('./grammar');
-var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
+//endregion
-exports.parse = function (sdp) {
- var session = {}
- , media = []
- , location = session; // points at where properties go under (one of the above)
+module.exports = Simulcast;
- // parse lines we understand
- sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
- var type = l[0];
- var content = l.slice(2);
- if (type === 'm') {
- media.push({rtp: [], fmtp: []});
- location = media[media.length-1]; // point at latest media line
- }
+},{"./transform-utils":74,"sdp-transform":76}],74:[function(require,module,exports){
+/* Copyright @ 2015 Atlassian Pty Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
- for (var j = 0; j < (grammar[type] || []).length; j += 1) {
- var obj = grammar[type][j];
- if (obj.reg.test(content)) {
- return parseReg(obj, location, content);
- }
- }
- });
+exports.writeSsrcs = function(sources, order) {
+ var ssrcs = [];
- session.media = media; // link it up
- return session;
-};
+ // expand sources to ssrcs
+ if (typeof sources !== 'undefined' &&
+ Object.keys(sources).length !== 0) {
-var fmtpReducer = function (acc, expr) {
- var s = expr.split('=');
- if (s.length === 2) {
- acc[s[0]] = toIntIfInt(s[1]);
+ if (Array.isArray(order)) {
+ for (var i = 0; i < order.length; i++) {
+ var ssrc = order[i];
+ var source = sources[ssrc];
+ Object.keys(source).forEach(function (attribute) {
+ ssrcs.push({
+ id: ssrc,
+ attribute: attribute,
+ value: source[attribute]
+ });
+ });
+ }
+ } else {
+ Object.keys(sources).forEach(function (ssrc) {
+ var source = sources[ssrc];
+ Object.keys(source).forEach(function (attribute) {
+ ssrcs.push({
+ id: ssrc,
+ attribute: attribute,
+ value: source[attribute]
+ });
+ });
+ });
+ }
}
- return acc;
-};
-
-exports.parseFmtpConfig = function (str) {
- return str.split(/\;\s?/).reduce(fmtpReducer, {});
-};
-exports.parsePayloads = function (str) {
- return str.split(' ').map(Number);
+ return ssrcs;
};
-exports.parseRemoteCandidates = function (str) {
- var candidates = [];
- var parts = str.split(' ').map(toIntIfInt);
- for (var i = 0; i < parts.length; i += 3) {
- candidates.push({
- component: parts[i],
- ip: parts[i + 1],
- port: parts[i + 2]
+exports.parseSsrcs = function (mLine) {
+ var sources = {};
+ // group sources attributes by ssrc.
+ if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
+ mLine.ssrcs.forEach(function (ssrc) {
+ if (!sources[ssrc.id])
+ sources[ssrc.id] = {};
+ sources[ssrc.id][ssrc.attribute] = ssrc.value;
});
}
- return candidates;
+ return sources;
};
-},{"./grammar":75}],78:[function(require,module,exports){
-arguments[4][74][0].apply(exports,arguments)
-},{"./grammar":75,"dup":74}],79:[function(require,module,exports){
+
+},{}],75:[function(require,module,exports){
+arguments[4][69][0].apply(exports,arguments)
+},{"dup":69}],76:[function(require,module,exports){
+arguments[4][70][0].apply(exports,arguments)
+},{"./parser":77,"./writer":78,"dup":70}],77:[function(require,module,exports){
+arguments[4][71][0].apply(exports,arguments)
+},{"./grammar":75,"dup":71}],78:[function(require,module,exports){
+arguments[4][72][0].apply(exports,arguments)
+},{"./grammar":75,"dup":72}],79:[function(require,module,exports){
var MediaStreamType = {
VIDEO_TYPE: "Video",