123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205 |
- /* global __filename, $ */
-
- import async from 'async';
- import { getLogger } from 'jitsi-meet-logger';
- import { $iq, Strophe } from 'strophe.js';
- import { integerHash } from '../util/StringUtils';
-
- import JingleSession from './JingleSession';
- import * as JingleSessionState from './JingleSessionState';
- import SDP from './SDP';
- import SDPDiffer from './SDPDiffer';
- import SDPUtil from './SDPUtil';
- import SignalingLayerImpl from './SignalingLayerImpl';
-
- import Statistics from '../statistics/statistics';
- import XMPPEvents from '../../service/xmpp/XMPPEvents';
- import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
-
- const logger = getLogger(__filename);
-
- /**
- * Constant tells how long we're going to wait for IQ response, before timeout
- * error is triggered.
- * @type {number}
- */
- const IQ_TIMEOUT = 10000;
-
- /**
- *
- */
- export default class JingleSessionPC extends JingleSession {
- /**
- * Parses 'senders' attribute of the video content.
- * @param {jQuery} jingleContents
- * @return {string|null} one of the values of content "senders" attribute
- * defined by Jingle. If there is no "senders" attribute or if the value is
- * invalid then <tt>null</tt> will be returned.
- * @private
- */
- static parseVideoSenders(jingleContents) {
- const videoContents = jingleContents.find('>content[name="video"]');
-
- if (videoContents.length) {
- const senders = videoContents[0].getAttribute('senders');
-
- if (senders === 'both'
- || senders === 'initiator'
- || senders === 'responder'
- || senders === 'none') {
- return senders;
- }
- }
-
- return null;
- }
-
- /* eslint-disable max-params */
-
- /**
- * Creates new <tt>JingleSessionPC</tt>
- * @param {string} sid the Jingle Session ID - random string which
- * identifies the session
- * @param {string} localJid our JID
- * @param {string} remoteJid remote peer JID
- * @param {Strophe.Connection} connection Strophe XMPP connection instance
- * used to send packets.
- * @param mediaConstraints the media constraints object passed to
- * createOffer/Answer, as defined by the WebRTC standard
- * @param iceConfig the ICE servers config object as defined by the WebRTC
- * standard.
- * @param {boolean} isP2P indicates whether this instance is
- * meant to be used in a direct, peer to peer connection or <tt>false</tt>
- * if it's a JVB connection.
- * @param {boolean} isInitiator indicates whether or not we are the side
- * which sends the 'session-initiate'.
- * @param {object} options a set of config options
- * @param {boolean} options.webrtcIceUdpDisable <tt>true</tt> to block UDP
- * candidates.
- * @param {boolean} options.webrtcIceTcpDisable <tt>true</tt> to block TCP
- * candidates.
- * @param {boolean} options.failICE it's an option used in the tests. Set to
- * <tt>true</tt> to block any real candidates and make the ICE fail.
- *
- * @constructor
- *
- * @implements {SignalingLayer}
- */
- constructor(
- sid,
- localJid,
- remoteJid,
- connection,
- mediaConstraints,
- iceConfig,
- isP2P,
- isInitiator,
- options) {
- super(
- sid, localJid, remoteJid, connection, mediaConstraints, iceConfig);
-
- /**
- * Stores result of {@link window.performance.now()} at the time when
- * ICE enters 'checking' state.
- * @type {number|null} null if no value has been stored yet
- * @private
- */
- this._iceCheckingStartedTimestamp = null;
-
- /**
- * Stores result of {@link window.performance.now()} at the time when
- * first ICE candidate is spawned by the peerconnection to mark when
- * ICE gathering started. That's, because ICE gathering state changed
- * events are not supported by most of the browsers, so we try something
- * that will work everywhere. It may not be as accurate, but given that
- * 'host' candidate usually comes first, the delay should be minimal.
- * @type {number|null} null if no value has been stored yet
- * @private
- */
- this._gatheringStartedTimestamp = null;
-
- /**
- * Indicates whether or not this session is willing to send/receive
- * video media. When set to <tt>false</tt> the underlying peer
- * connection will disable local video transfer and the remote peer will
- * be will be asked to stop sending video via 'content-modify' IQ
- * (the senders attribute of video contents will be adjusted
- * accordingly). Note that this notification is sent only in P2P
- * session, because Jicofo does not support it yet. Obviously when
- * the value is changed from <tt>false</tt> to <tt>true</tt> another
- * notification will be sent to resume video transfer on the remote
- * side.
- * @type {boolean}
- * @private
- */
- this._localVideoActive = true;
-
- /**
- * Indicates whether or not the remote peer has video transfer active.
- * When set to <tt>true</tt> it means that remote peer is neither
- * sending nor willing to receive video. In such case we'll ask
- * our peerconnection to stop sending video by calling
- * {@link TraceablePeerConnection.setVideoTransferActive} with
- * <tt>false</tt>.
- * @type {boolean}
- * @private
- */
- this._remoteVideoActive = true;
-
- /**
- * Marks that ICE gathering duration has been reported already. That
- * prevents reporting it again, after eventual 'transport-replace' (JVB
- * conference migration/ICE restart).
- * @type {boolean}
- * @private
- */
- this._gatheringReported = false;
-
- this.lasticecandidate = false;
- this.closed = false;
-
- /**
- * Indicates whether this instance is an initiator or an answerer of
- * the Jingle session.
- * @type {boolean}
- */
- this.isInitiator = isInitiator;
-
- /**
- * Indicates whether or not this <tt>JingleSessionPC</tt> is used in
- * a peer to peer type of session.
- * @type {boolean} <tt>true</tt> if it's a peer to peer
- * session or <tt>false</tt> if it's a JVB session
- */
- this.isP2P = isP2P;
-
- /**
- * The signaling layer implementation.
- * @type {SignalingLayerImpl}
- */
- this.signalingLayer = new SignalingLayerImpl();
-
- this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
- this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
-
- /**
- * Flag used to enforce ICE failure through the URL parameter for
- * the automatic testing purpose.
- * @type {boolean}
- */
- this.failICE = Boolean(options.failICE);
-
- this.modificationQueue
- = async.queue(this._processQueueTasks.bind(this), 1);
-
- /**
- * Flag used to guarantee that the connection established event is
- * triggered just once.
- * @type {boolean}
- */
- this.wasConnected = false;
-
- /**
- * Keeps track of how long (in ms) it took from ICE start to ICE
- * connect.
- *
- * @type {number}
- */
- this.establishmentDuration = undefined;
- }
-
- /* eslint-enable max-params */
-
- /**
- * Checks whether or not this session instance has been ended and eventually
- * logs a message which mentions that given <tt>actionName</tt> was
- * cancelled.
- * @param {string} actionName
- * @return {boolean} <tt>true</tt> if this {@link JingleSessionPC} has
- * entered {@link JingleSessionState.ENDED} or <tt>false</tt> otherwise.
- * @private
- */
- _assertNotEnded(actionName) {
- if (this.state === JingleSessionState.ENDED) {
- logger.log(
- `The session has ended - cancelling action: ${actionName}`);
-
- return false;
- }
-
- return true;
- }
-
- /**
- *
- */
- doInitialize() {
- this.lasticecandidate = false;
-
- // True if reconnect is in progress
- this.isreconnect = false;
-
- // Set to true if the connection was ever stable
- this.wasstable = false;
-
- const pcOptions = { disableRtx: this.room.options.disableRtx };
-
- if (this.isP2P) {
- // simulcast needs to be disabled for P2P (121) calls
- pcOptions.disableSimulcast = true;
- pcOptions.disableH264
- = this.room.options.p2p && this.room.options.p2p.disableH264;
- pcOptions.preferH264
- = this.room.options.p2p && this.room.options.p2p.preferH264;
-
- const abtestSuspendVideo = this._abtestSuspendVideoEnabled();
-
- if (typeof abtestSuspendVideo !== 'undefined') {
- pcOptions.abtestSuspendVideo = abtestSuspendVideo;
- }
- } else {
- // H264 does not support simulcast, so it needs to be disabled.
- pcOptions.disableSimulcast
- = this.room.options.disableSimulcast
- || (this.room.options.preferH264
- && !this.room.options.disableH264);
- pcOptions.preferH264 = this.room.options.preferH264;
- pcOptions.enableFirefoxSimulcast
- = this.room.options.testing
- && this.room.options.testing.enableFirefoxSimulcast;
- }
-
- this.peerconnection
- = this.rtc.createPeerConnection(
- this.signalingLayer,
- this.iceConfig,
- this.isP2P,
- pcOptions);
-
- this.peerconnection.onicecandidate = ev => {
- if (!ev) {
- // There was an incomplete check for ev before which left
- // the last line of the function unprotected from a potential
- // throw of an exception. Consequently, it may be argued that
- // the check is unnecessary. Anyway, I'm leaving it and making
- // the check complete.
- return;
- }
-
- // XXX this is broken, candidate is not parsed.
- const candidate = ev.candidate;
- const now = window.performance.now();
-
- if (candidate) {
- if (this._gatheringStartedTimestamp === null) {
- this._gatheringStartedTimestamp = now;
- }
-
- // Discard candidates of disabled protocols.
- let protocol = candidate.protocol;
-
- if (typeof protocol === 'string') {
- protocol = protocol.toLowerCase();
- if (protocol === 'tcp' || protocol === 'ssltcp') {
- if (this.webrtcIceTcpDisable) {
- return;
- }
- } else if (protocol === 'udp') {
- if (this.webrtcIceUdpDisable) {
- return;
- }
- }
- }
- } else if (!this._gatheringReported) {
- // End of gathering
- let eventName = this.isP2P ? 'p2p.ice.' : 'ice.';
-
- eventName += this.isInitiator ? 'initiator' : 'responder';
- eventName += '.gatheringDuration';
- Statistics.analytics.sendEvent(
- eventName,
- { value: now - this._gatheringStartedTimestamp });
- this._gatheringReported = true;
- }
- this.sendIceCandidate(candidate);
- };
-
- // Note there is a change in the spec about closed:
- // This value moved into the RTCPeerConnectionState enum in
- // the May 13, 2016 draft of the specification, as it reflects the state
- // of the RTCPeerConnection, not the signaling connection. You now
- // detect a closed connection by checking for connectionState to be
- // "closed" instead.
- // I suppose at some point this will be moved to onconnectionstatechange
- this.peerconnection.onsignalingstatechange = () => {
- if (!this.peerconnection) {
- return;
- }
- if (this.peerconnection.signalingState === 'stable') {
- this.wasstable = true;
- } else if (
- (this.peerconnection.signalingState === 'closed'
- || this.peerconnection.connectionState === 'closed')
- && !this.closed) {
- this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
- }
- };
-
- /**
- * The oniceconnectionstatechange event handler contains the code to
- * execute when the iceconnectionstatechange event, of type Event,
- * is received by this RTCPeerConnection. Such an event is sent when
- * the value of RTCPeerConnection.iceConnectionState changes.
- */
- this.peerconnection.oniceconnectionstatechange = () => {
- if (!this.peerconnection
- || !this._assertNotEnded('oniceconnectionstatechange')) {
- return;
- }
- const now = window.performance.now();
-
- if (!this.isP2P) {
- this.room.connectionTimes[
- `ice.state.${this.peerconnection.iceConnectionState}`]
- = now;
- }
- logger.log(
- `(TIME) ICE ${this.peerconnection.iceConnectionState}`
- + ` P2P? ${this.isP2P}:\t`,
- now);
- Statistics.analytics.sendEvent(
- `${this.isP2P ? 'p2p.ice.' : 'ice.'}`
- + `${this.peerconnection.iceConnectionState}`,
- { value: now });
- this.room.eventEmitter.emit(
- XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
- this,
- this.peerconnection.iceConnectionState);
- switch (this.peerconnection.iceConnectionState) {
- case 'checking':
- this._iceCheckingStartedTimestamp = now;
- break;
- case 'connected':
- // Informs interested parties that the connection has been
- // restored.
- if (this.peerconnection.signalingState === 'stable') {
- if (this.isreconnect) {
- this.room.eventEmitter.emit(
- XMPPEvents.CONNECTION_RESTORED, this);
- }
- }
-
- if (!this.wasConnected && this.wasstable) {
- let eventName = this.isP2P ? 'p2p.ice.' : 'ice.';
-
- eventName += this.isInitiator ? 'initiator.' : 'responder.';
- Statistics.analytics.sendEvent(
- `${eventName}checksDuration`,
- {
- value: now - this._iceCheckingStartedTimestamp
- });
-
- // Switch between ICE gathering and ICE checking whichever
- // started first (scenarios are different for initiator
- // vs responder)
- const iceStarted
- = Math.min(
- this._iceCheckingStartedTimestamp,
- this._gatheringStartedTimestamp);
-
- this.establishmentDuration = now - iceStarted;
-
- Statistics.analytics.sendEvent(
- `${eventName}establishmentDuration`,
- {
- value: this.establishmentDuration
- });
- this.wasConnected = true;
- this.room.eventEmitter.emit(
- XMPPEvents.CONNECTION_ESTABLISHED, this);
- }
- this.isreconnect = false;
- break;
- case 'disconnected':
- if (this.closed) {
- break;
- }
- this.isreconnect = true;
-
- // Informs interested parties that the connection has been
- // interrupted.
- if (this.wasstable) {
- this.room.eventEmitter.emit(
- XMPPEvents.CONNECTION_INTERRUPTED, this);
- }
- break;
- case 'failed':
- this.room.eventEmitter.emit(
- XMPPEvents.CONNECTION_ICE_FAILED, this);
- this.room.eventEmitter.emit(
- XMPPEvents.CONFERENCE_SETUP_FAILED,
- this,
- new Error('ICE fail'));
- break;
- }
- };
- this.peerconnection.onnegotiationneeded = () => {
- this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
- };
-
- // The signaling layer will bind it's listeners at this point
- this.signalingLayer.setChatRoom(this.room);
- }
-
- /**
- * Sends given candidate in Jingle 'transport-info' message.
- * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
- * @private
- */
- sendIceCandidate(candidate) {
- const localSDP = new SDP(this.peerconnection.localDescription.sdp);
-
- if (candidate && !this.lasticecandidate) {
- const ice
- = SDPUtil.iceparams(
- localSDP.media[candidate.sdpMLineIndex], localSDP.session);
- const jcand = SDPUtil.candidateToJingle(candidate.candidate);
-
- if (!(ice && jcand)) {
- const errorMesssage = 'failed to get ice && jcand';
-
- GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
- logger.error(errorMesssage);
-
- return;
- }
- ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
-
- if (this.usedrip) {
- if (this.dripContainer.length === 0) {
- // start 20ms callout
- setTimeout(() => {
- if (this.dripContainer.length === 0) {
- return;
- }
- this.sendIceCandidates(this.dripContainer);
- this.dripContainer = [];
- }, 20);
- }
- this.dripContainer.push(candidate);
- } else {
- this.sendIceCandidates([ candidate ]);
- }
- } else {
- logger.log('sendIceCandidate: last candidate.');
-
- // FIXME: remember to re-think in ICE-restart
- this.lasticecandidate = true;
- }
- }
-
- /**
- * Sends given candidates in Jingle 'transport-info' message.
- * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
- * candidate instances
- * @private
- */
- sendIceCandidates(candidates) {
- if (!this._assertNotEnded('sendIceCandidates')) {
-
- return;
- }
-
- logger.log('sendIceCandidates', candidates);
- const cand = $iq({ to: this.remoteJid,
- type: 'set' })
- .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
- action: 'transport-info',
- initiator: this.initiator,
- sid: this.sid });
-
- const localSDP = new SDP(this.peerconnection.localDescription.sdp);
-
- for (let mid = 0; mid < localSDP.media.length; mid++) {
- const cands = candidates.filter(el => el.sdpMLineIndex === mid);
- const mline
- = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
-
- if (cands.length > 0) {
- const ice
- = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
-
- ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
- cand.c('content', {
- creator: this.initiator === this.localJid
- ? 'initiator' : 'responder',
- name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
- }).c('transport', ice);
- for (let i = 0; i < cands.length; i++) {
- const candidate
- = SDPUtil.candidateToJingle(cands[i].candidate);
-
- // Mangle ICE candidate if 'failICE' test option is enabled
-
- if (this.failICE) {
- candidate.ip = '1.1.1.1';
- }
- cand.c('candidate', candidate).up();
- }
-
- // add fingerprint
- const fingerprintLine
- = SDPUtil.findLine(
- localSDP.media[mid],
- 'a=fingerprint:', localSDP.session);
-
- if (fingerprintLine) {
- const tmp = SDPUtil.parseFingerprint(fingerprintLine);
-
- tmp.required = true;
- cand.c(
- 'fingerprint',
- { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
- .t(tmp.fingerprint);
- delete tmp.fingerprint;
- cand.attrs(tmp);
- cand.up();
- }
- cand.up(); // transport
- cand.up(); // content
- }
- }
-
- // might merge last-candidate notification into this, but it is called
- // a lot later. See webrtc issue #2340
- // logger.log('was this the last candidate', this.lasticecandidate);
- this.connection.sendIQ(
- cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
- }
-
- /**
- * {@inheritDoc}
- */
- addIceCandidates(elem) {
- if (this.peerconnection.signalingState === 'closed') {
- logger.warn('Ignored add ICE candidate when in closed state');
-
- return;
- }
-
- const iceCandidates = [];
-
- elem.find('>content>transport>candidate')
- .each((idx, candidate) => {
- let line = SDPUtil.candidateFromJingle(candidate);
-
- line = line.replace('\r\n', '').replace('a=', '');
-
- // FIXME this code does not care to handle
- // non-bundle transport
- const rtcCandidate = new RTCIceCandidate({
- sdpMLineIndex: 0,
-
- // FF comes up with more complex names like audio-23423,
- // Given that it works on both Chrome and FF without
- // providing it, let's leave it like this for the time
- // being...
- // sdpMid: 'audio',
- sdpMid: '',
- candidate: line
- });
-
- iceCandidates.push(rtcCandidate);
- });
-
- if (!iceCandidates.length) {
- logger.error(
- 'No ICE candidates to add ?', elem[0] && elem[0].outerHTML);
-
- return;
- }
-
- // We want to have this task queued, so that we know it is executed,
- // after the initial sRD/sLD offer/answer cycle was done (based on
- // the assumption that candidates are spawned after the offer/answer
- // and XMPP preserves order).
- const workFunction = finishedCallback => {
- for (const iceCandidate of iceCandidates) {
- this.peerconnection.addIceCandidate(
- iceCandidate,
- () => {
- logger.debug('addIceCandidate ok!');
- },
- error => {
- logger.error('addIceCandidate failed!', error);
- });
- }
-
- finishedCallback();
- };
-
- logger.debug(
- `Queued add (${iceCandidates.length}) ICE candidates task...`);
- this.modificationQueue.push(workFunction);
- }
-
- /**
- *
- * @param contents
- */
- readSsrcInfo(contents) {
- const ssrcs
- = $(contents).find(
- '>description>'
- + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
-
- ssrcs.each((i, ssrcElement) => {
- const ssrc = Number(ssrcElement.getAttribute('ssrc'));
-
- if (this.isP2P) {
- // In P2P all SSRCs are owner by the remote peer
- this.signalingLayer.setSSRCOwner(
- ssrc, Strophe.getResourceFromJid(this.remoteJid));
- } else {
- $(ssrcElement)
- .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
- .each((i3, ssrcInfoElement) => {
- const owner = ssrcInfoElement.getAttribute('owner');
-
- if (owner && owner.length) {
- if (isNaN(ssrc) || ssrc < 0) {
- logger.warn(
- `Invalid SSRC ${ssrc} value received`
- + ` for ${owner}`);
- } else {
- this.signalingLayer.setSSRCOwner(
- ssrc,
- Strophe.getResourceFromJid(owner));
- }
- }
- });
- }
- });
- }
-
- /**
- * Makes the underlying TraceablePeerConnection generate new SSRC for
- * the recvonly video stream.
- * @deprecated
- */
- generateRecvonlySsrc() {
- if (this.peerconnection) {
- this.peerconnection.generateRecvonlySsrc();
- } else {
- logger.error(
- 'Unable to generate recvonly SSRC - no peerconnection');
- }
- }
-
- /* eslint-disable max-params */
- /**
- * Accepts incoming Jingle 'session-initiate' and should send
- * 'session-accept' in result.
- * @param jingleOffer jQuery selector pointing to the jingle element of
- * the offer IQ
- * @param success callback called when we accept incoming session
- * successfully and receive RESULT packet to 'session-accept' sent.
- * @param failure function(error) called if for any reason we fail to accept
- * the incoming offer. 'error' argument can be used to log some details
- * about the error.
- * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
- * the local tracks that will be added, before the offer/answer cycle
- * executes. We allow the localTracks to optionally be passed in so that
- * the addition of the local tracks and the processing of the initial offer
- * can all be done atomically. We want to make sure that any other
- * operations which originate in the XMPP Jingle messages related with
- * this session to be executed with an assumption that the initial
- * offer/answer cycle has been executed already.
- */
- acceptOffer(jingleOffer, success, failure, localTracks) {
- this.setOfferAnswerCycle(
- jingleOffer,
- () => {
- // FIXME we may not care about RESULT packet for session-accept
- // then we should either call 'success' here immediately or
- // modify sendSessionAccept method to do that
- this.sendSessionAccept(success, failure);
- },
- failure,
- localTracks);
- }
-
- /* eslint-enable max-params */
-
- /**
- * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
- * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be
- * added, before the offer/answer cycle executes (for the local track
- * addition to be an atomic operation together with the offer/answer).
- */
- invite(localTracks) {
- if (!this.isInitiator) {
- throw new Error('Trying to invite from the responder session');
- }
- const workFunction = finishedCallback => {
- for (const localTrack of localTracks) {
- this.peerconnection.addTrack(localTrack);
- }
- this.peerconnection.createOffer(
- offerSdp => {
- this.peerconnection.setLocalDescription(
- offerSdp,
- () => {
- // NOTE that the offer is obtained from
- // the localDescription getter as it needs to go
- // though the transformation chain.
- this.sendSessionInitiate(
- this.peerconnection.localDescription.sdp);
- finishedCallback();
- },
- error => {
- logger.error(
- 'Failed to set local SDP', error, offerSdp);
- finishedCallback(error);
- });
- },
- error => {
- logger.error(
- 'Failed to create an offer',
- error,
- this.mediaConstraints);
- finishedCallback(error);
- },
- this.mediaConstraints);
- };
-
- this.modificationQueue.push(
- workFunction,
- error => {
- if (error) {
- logger.error('invite error', error);
- } else {
- logger.debug('invite executed - OK');
- }
- });
- }
-
- /**
- * Sends 'session-initiate' to the remote peer.
- *
- * NOTE this method is synchronous and we're not waiting for the RESULT
- * response which would delay the startup process.
- *
- * @param {string} offerSdp - The local session description which will be
- * used to generate an offer.
- * @private
- */
- sendSessionInitiate(offerSdp) {
- let init = $iq({
- to: this.remoteJid,
- type: 'set'
- }).c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'session-initiate',
- initiator: this.initiator,
- sid: this.sid
- });
-
- new SDP(offerSdp).toJingle(
- init,
- this.initiator === this.me ? 'initiator' : 'responder');
- init = init.tree();
- logger.info('Session-initiate: ', init);
- this.connection.sendIQ(init,
- () => {
- logger.info('Got RESULT for "session-initiate"');
- },
- error => {
- logger.error('"session-initiate" error', error);
- },
- IQ_TIMEOUT);
- }
-
- /**
- * Sets the answer received from the remote peer.
- * @param jingleAnswer
- */
- setAnswer(jingleAnswer) {
- if (!this.isInitiator) {
- throw new Error('Trying to set an answer on the responder session');
- }
- this.setOfferAnswerCycle(
- jingleAnswer,
- () => {
- logger.info('setAnswer - succeeded');
- },
- error => {
- logger.error('setAnswer failed: ', error);
- });
- }
-
- /* eslint-disable max-params */
- /**
- * This is a setRemoteDescription/setLocalDescription cycle which starts at
- * converting Strophe Jingle IQ into remote offer SDP. Once converted
- * setRemoteDescription, createAnswer and setLocalDescription calls follow.
- * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element
- * of the offer (or answer) IQ
- * @param success callback called when sRD/sLD cycle finishes successfully.
- * @param failure callback called with an error object as an argument if we
- * fail at any point during setRD, createAnswer, setLD.
- * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
- * the local tracks that will be added, before the offer/answer cycle
- * executes (for the local track addition to be an atomic operation together
- * with the offer/answer).
- */
- setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks) {
- const workFunction = finishedCallback => {
-
- if (localTracks) {
- for (const track of localTracks) {
- this.peerconnection.addTrack(track);
- }
- }
-
- const newRemoteSdp
- = this._processNewJingleOfferIq(jingleOfferAnswerIq);
- const oldLocalSdp
- = this.peerconnection.localDescription.sdp;
-
- this._renegotiate(newRemoteSdp.raw)
- .then(() => {
- if (this.state === JingleSessionState.PENDING) {
- this.state = JingleSessionState.ACTIVE;
-
- // Sync up video transfer active/inactive only after
- // the initial O/A cycle. We want to adjust the video
- // media direction only in the local SDP and the Jingle
- // contents direction included in the initial
- // offer/answer is mapped to the remote SDP. Jingle
- // 'content-modify' IQ is processed in a way that it
- // will only modify local SDP when remote peer is no
- // longer interested in receiving video content.
- // Changing media direction in the remote SDP will mess
- // up our SDP translation chain (simulcast, video mute,
- // RTX etc.)
- if (this.isP2P && !this._localVideoActive) {
- this.sendContentModify(this._localVideoActive);
- }
- }
-
- // Old local SDP will be available when we're setting answer
- // for the first time, but not when offer and it's fine
- // since we're generating an answer now it will contain all
- // our SSRCs
- if (oldLocalSdp) {
- const newLocalSdp
- = new SDP(this.peerconnection.localDescription.sdp);
-
- this.notifyMySSRCUpdate(
- new SDP(oldLocalSdp), newLocalSdp);
- }
-
- finishedCallback();
- }, error => {
- logger.error(
- `Error renegotiating after setting new remote ${
- this.isInitiator ? 'answer: ' : 'offer: '}${error}`,
- newRemoteSdp);
- JingleSessionPC.onJingleFatalError(this, error);
- finishedCallback(error);
- });
- };
-
- this.modificationQueue.push(
- workFunction,
- error => {
- error ? failure(error) : success();
- });
- }
-
- /* eslint-enable max-params */
-
- /**
- * Although it states "replace transport" it does accept full Jingle offer
- * which should contain new ICE transport details.
- * @param jingleOfferElem an element Jingle IQ that contains new offer and
- * transport info.
- * @param success callback called when we succeed to accept new offer.
- * @param failure function(error) called when we fail to accept new offer.
- */
- replaceTransport(jingleOfferElem, success, failure) {
-
- // We need to first set an offer without the 'data' section to have the
- // SCTP stack cleaned up. After that the original offer is set to have
- // the SCTP connection established with the new bridge.
- this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
- const originalOffer = jingleOfferElem.clone();
-
- jingleOfferElem.find('>content[name=\'data\']').remove();
-
- // First set an offer without the 'data' section
- this.setOfferAnswerCycle(
- jingleOfferElem,
- () => {
- // Now set the original offer(with the 'data' section)
- this.setOfferAnswerCycle(
- originalOffer,
- () => {
- const localSDP
- = new SDP(this.peerconnection.localDescription.sdp);
-
- this.sendTransportAccept(localSDP, success, failure);
- },
- failure);
- },
- failure
- );
- }
-
- /**
- * Sends Jingle 'session-accept' message.
- * @param {function()} success callback called when we receive 'RESULT'
- * packet for the 'session-accept'
- * @param {function(error)} failure called when we receive an error response
- * or when the request has timed out.
- * @private
- */
- sendSessionAccept(success, failure) {
- // NOTE: since we're just reading from it, we don't need to be within
- // the modification queue to access the local description
- const localSDP = new SDP(this.peerconnection.localDescription.sdp);
- let accept = $iq({ to: this.remoteJid,
- type: 'set' })
- .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
- action: 'session-accept',
- initiator: this.initiator,
- responder: this.responder,
- sid: this.sid });
-
- if (this.webrtcIceTcpDisable) {
- localSDP.removeTcpCandidates = true;
- }
- if (this.webrtcIceUdpDisable) {
- localSDP.removeUdpCandidates = true;
- }
- if (this.failICE) {
- localSDP.failICE = true;
- }
- localSDP.toJingle(
- accept,
- this.initiator === this.localJid ? 'initiator' : 'responder',
- null);
-
- // Calling tree() to print something useful
- accept = accept.tree();
- logger.info('Sending session-accept', accept);
- this.connection.sendIQ(accept,
- success,
- this.newJingleErrorHandler(accept, error => {
- failure(error);
-
- // 'session-accept' is a critical timeout and we'll
- // have to restart
- this.room.eventEmitter.emit(
- XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
- }),
- IQ_TIMEOUT);
-
- // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
- // fingerprint and setup) ASAP in order to start the connection
- // establishment.
- //
- // FIXME Flushing the connection at this point triggers an issue with
- // BOSH request handling in Prosody on slow connections.
- //
- // The problem is that this request will be quite large and it may take
- // time before it reaches Prosody. In the meantime Strophe may decide
- // to send the next one. And it was observed that a small request with
- // 'transport-info' usually follows this one. It does reach Prosody
- // before the previous one was completely received. 'rid' on the server
- // is increased and Prosody ignores the request with 'session-accept'.
- // It will never reach Jicofo and everything in the request table is
- // lost. Removing the flush does not guarantee it will never happen, but
- // makes it much less likely('transport-info' is bundled with
- // 'session-accept' and any immediate requests).
- //
- // this.connection.flush();
- }
-
- /**
- * Will send 'content-modify' IQ in order to ask the remote peer to
- * either stop or resume sending video media.
- * @param {boolean} videoTransferActive <tt>false</tt> to let the other peer
- * know that we're not sending nor interested in receiving video contents.
- * When set to <tt>true</tt> remote peer will be asked to resume video
- * transfer.
- * @private
- */
- sendContentModify(videoTransferActive) {
- const newSendersValue = videoTransferActive ? 'both' : 'none';
-
- const sessionModify
- = $iq({
- to: this.remoteJid,
- type: 'set'
- })
- .c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'content-modify',
- initiator: this.initiator,
- sid: this.sid
- })
- .c('content', {
- name: 'video',
- senders: newSendersValue
- });
-
- logger.info(
- `Sending content-modify, video senders: ${newSendersValue}`);
-
- this.connection.sendIQ(
- sessionModify,
- null,
- this.newJingleErrorHandler(sessionModify),
- IQ_TIMEOUT);
- }
-
- /**
- * Sends Jingle 'transport-accept' message which is a response to
- * 'transport-replace'.
- * @param localSDP the 'SDP' object with local session description
- * @param success callback called when we receive 'RESULT' packet for
- * 'transport-replace'
- * @param failure function(error) called when we receive an error response
- * or when the request has timed out.
- * @private
- */
- sendTransportAccept(localSDP, success, failure) {
- let transportAccept = $iq({ to: this.remoteJid,
- type: 'set' })
- .c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'transport-accept',
- initiator: this.initiator,
- sid: this.sid
- });
-
- localSDP.media.forEach((medialines, idx) => {
- const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
-
- transportAccept.c('content',
- {
- creator:
- this.initiator === this.localJid
- ? 'initiator'
- : 'responder',
- name: mline.media
- }
- );
- localSDP.transportToJingle(idx, transportAccept);
- transportAccept.up();
- });
-
- // Calling tree() to print something useful to the logger
- transportAccept = transportAccept.tree();
- logger.info('Sending transport-accept: ', transportAccept);
-
- this.connection.sendIQ(transportAccept,
- success,
- this.newJingleErrorHandler(transportAccept, failure),
- IQ_TIMEOUT);
- }
-
- /**
- * Sends Jingle 'transport-reject' message which is a response to
- * 'transport-replace'.
- * @param success callback called when we receive 'RESULT' packet for
- * 'transport-replace'
- * @param failure function(error) called when we receive an error response
- * or when the request has timed out.
- *
- * FIXME method should be marked as private, but there's some spaghetti that
- * needs to be fixed prior doing that
- */
- sendTransportReject(success, failure) {
- // Send 'transport-reject', so that the focus will
- // know that we've failed
- let transportReject = $iq({ to: this.remoteJid,
- type: 'set' })
- .c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'transport-reject',
- initiator: this.initiator,
- sid: this.sid
- });
-
- transportReject = transportReject.tree();
- logger.info('Sending \'transport-reject', transportReject);
-
- this.connection.sendIQ(transportReject,
- success,
- this.newJingleErrorHandler(transportReject, failure),
- IQ_TIMEOUT);
- }
-
- /**
- * @inheritDoc
- */
- terminate(success, failure, options) {
- if (this.state === JingleSessionState.ENDED) {
- return;
- }
-
- if (!options || Boolean(options.sendSessionTerminate)) {
- let sessionTerminate
- = $iq({
- to: this.remoteJid,
- type: 'set'
- })
- .c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'session-terminate',
- initiator: this.initiator,
- sid: this.sid
- })
- .c('reason')
- .c((options && options.reason) || 'success');
-
- if (options && options.reasonDescription) {
- sessionTerminate.up()
- .c('text')
- .t(options.reasonDescription);
- }
-
- // Calling tree() to print something useful
- sessionTerminate = sessionTerminate.tree();
- logger.info('Sending session-terminate', sessionTerminate);
- this.connection.sendIQ(
- sessionTerminate,
- success,
- this.newJingleErrorHandler(sessionTerminate, failure),
- IQ_TIMEOUT);
- } else {
- logger.info(`Skipped sending session-terminate for ${this}`);
- }
-
- // this should result in 'onTerminated' being called by strope.jingle.js
- this.connection.jingle.terminate(this.sid);
- }
-
- /**
- *
- * @param reasonCondition
- * @param reasonText
- */
- onTerminated(reasonCondition, reasonText) {
- this.state = JingleSessionState.ENDED;
- this.establishmentDuration = undefined;
-
- // Do something with reason and reasonCondition when we start to care
- // this.reasonCondition = reasonCondition;
- // this.reasonText = reasonText;
- logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
-
- this.close();
- }
-
- /**
- * Parse the information from the xml sourceAddElem and translate it
- * into sdp lines
- * @param {jquery xml element} sourceAddElem the source-add
- * element from jingle
- * @param {SDP object} currentRemoteSdp the current remote
- * sdp (as of this new source-add)
- * @returns {list} a list of SDP line strings that should
- * be added to the remote SDP
- */
- _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
- const addSsrcInfo = [];
-
- $(sourceAddElem).each((i1, content) => {
- const name = $(content).attr('name');
- let lines = '';
-
- $(content)
- .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
- .each(function() {
- // eslint-disable-next-line no-invalid-this
- const semantics = this.getAttribute('semantics');
- const ssrcs
- = $(this) // eslint-disable-line no-invalid-this
- .find('>source')
- .map(function() {
- // eslint-disable-next-line no-invalid-this
- return this.getAttribute('ssrc');
- })
- .get();
-
- if (ssrcs.length) {
- lines
- += `a=ssrc-group:${semantics} ${
- ssrcs.join(' ')}\r\n`;
- }
- });
-
- // handles both >source and >description>source
- const tmp
- = $(content).find(
- 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
-
- /* eslint-disable no-invalid-this */
- tmp.each(function() {
- const ssrc = $(this).attr('ssrc');
-
- if (currentRemoteSdp.containsSSRC(ssrc)) {
- logger.warn(
- `Source-add request for existing SSRC: ${ssrc}`);
-
- return;
- }
-
- // eslint-disable-next-line newline-per-chained-call
- $(this).find('>parameter').each(function() {
- lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
- if ($(this).attr('value') && $(this).attr('value').length) {
- lines += `:${$(this).attr('value')}`;
- }
- lines += '\r\n';
- });
- });
-
- /* eslint-enable no-invalid-this */
- currentRemoteSdp.media.forEach((media, i2) => {
- if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
- return;
- }
- if (!addSsrcInfo[i2]) {
- addSsrcInfo[i2] = '';
- }
- addSsrcInfo[i2] += lines;
- });
- });
-
- return addSsrcInfo;
- }
-
- /**
- * Handles a Jingle source-add message for this Jingle session.
- * @param elem An array of Jingle "content" elements.
- */
- addRemoteStream(elem) {
- this._addOrRemoveRemoteStream(true /* add */, elem);
- }
-
- /**
- * Handles a Jingle source-remove message for this Jingle session.
- * @param elem An array of Jingle "content" elements.
- */
- removeRemoteStream(elem) {
- this._addOrRemoveRemoteStream(false /* remove */, elem);
- }
-
- /**
- * Handles either Jingle 'source-add' or 'source-remove' message for this
- * Jingle session.
- * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
- * otherwise.
- * @param {Array<Element>} elem an array of Jingle "content" elements.
- * @private
- */
- _addOrRemoveRemoteStream(isAdd, elem) {
- const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
-
- if (isAdd) {
- this.readSsrcInfo(elem);
- }
-
- const workFunction = finishedCallback => {
- if (!this.peerconnection.localDescription
- || !this.peerconnection.localDescription.sdp) {
- const errMsg = `${logPrefix} - localDescription not ready yet`;
-
- logger.error(errMsg);
- finishedCallback(errMsg);
-
- return;
- }
-
- logger.log(`Processing ${logPrefix}`);
- logger.log(
- 'ICE connection state: ',
- this.peerconnection.iceConnectionState);
-
- const oldLocalSdp
- = new SDP(this.peerconnection.localDescription.sdp);
- const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
- const addOrRemoveSsrcInfo
- = isAdd
- ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
- : this._parseSsrcInfoFromSourceRemove(elem, sdp);
- const newRemoteSdp
- = isAdd
- ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
- : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
-
- this._renegotiate(newRemoteSdp.raw)
- .then(() => {
- const newLocalSdp
- = new SDP(this.peerconnection.localDescription.sdp);
-
- logger.log(
- `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
- this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
- finishedCallback();
- }, error => {
- logger.error(`${logPrefix} failed:`, error);
- finishedCallback(error);
- });
- };
-
- // Queue and execute
- this.modificationQueue.push(workFunction);
- }
-
- /**
- * The 'task' function will be given a callback it MUST call with either:
- * 1) No arguments if it was successful or
- * 2) An error argument if there was an error
- * If the task wants to process the success or failure of the task, it
- * should pass a handler to the .push function, e.g.:
- * queue.push(task, (err) => {
- * if (err) {
- * // error handling
- * } else {
- * // success handling
- * }
- * });
- */
- _processQueueTasks(task, finishedCallback) {
- task(finishedCallback);
- }
-
- /**
- * Takes in a jingle offer iq, returns the new sdp offer
- * @param {jquery xml element} offerIq the incoming offer
- * @returns {SDP object} the jingle offer translated to SDP
- */
- _processNewJingleOfferIq(offerIq) {
- const remoteSdp = new SDP('');
-
- if (this.webrtcIceTcpDisable) {
- remoteSdp.removeTcpCandidates = true;
- }
- if (this.webrtcIceUdpDisable) {
- remoteSdp.removeUdpCandidates = true;
- }
- if (this.failICE) {
- remoteSdp.failICE = true;
- }
-
- remoteSdp.fromJingle(offerIq);
- this.readSsrcInfo($(offerIq).find('>content'));
-
- return remoteSdp;
- }
-
- /**
- * Remove the given ssrc lines from the current remote sdp
- * @param {list} removeSsrcInfo a list of SDP line strings that
- * should be removed from the remote SDP
- * @returns type {SDP Object} the new remote SDP (after removing the lines
- * in removeSsrcInfo
- */
- _processRemoteRemoveSource(removeSsrcInfo) {
- const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
-
- removeSsrcInfo.forEach((lines, idx) => {
- // eslint-disable-next-line no-param-reassign
- lines = lines.split('\r\n');
- lines.pop(); // remove empty last element;
- lines.forEach(line => {
- remoteSdp.media[idx]
- = remoteSdp.media[idx].replace(`${line}\r\n`, '');
- });
- });
- remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
-
- return remoteSdp;
- }
-
- /**
- * Add the given ssrc lines to the current remote sdp
- * @param {list} addSsrcInfo a list of SDP line strings that
- * should be added to the remote SDP
- * @returns type {SDP Object} the new remote SDP (after removing the lines
- * in removeSsrcInfo
- */
- _processRemoteAddSource(addSsrcInfo) {
- const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
-
- addSsrcInfo.forEach((lines, idx) => {
- remoteSdp.media[idx] += lines;
- });
- remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
-
- return remoteSdp;
- }
-
- /**
- * Do a new o/a flow using the existing remote description
- * @param {string} [optionalRemoteSdp] optional, raw remote sdp
- * to use. If not provided, the remote sdp from the
- * peerconnection will be used
- * @returns {Promise} promise which resolves when the
- * o/a flow is complete with no arguments or
- * rejects with an error {string}
- */
- _renegotiate(optionalRemoteSdp) {
- const remoteSdp
- = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
-
- if (!remoteSdp) {
- return Promise.reject(
- 'Can not renegotiate without remote description,'
- + `- current state: ${this.state}`);
- }
-
- const remoteDescription = new RTCSessionDescription({
- type: this.isInitiator ? 'answer' : 'offer',
- sdp: remoteSdp
- });
-
- return new Promise((resolve, reject) => {
- if (this.peerconnection.signalingState === 'closed') {
- reject('Attempted to renegotiate in state closed');
-
- return;
- }
- if (this.isInitiator) {
- this._initiatorRenegotiate(remoteDescription, resolve, reject);
- } else {
- this._responderRenegotiate(remoteDescription, resolve, reject);
- }
- });
- }
-
- /**
- * Renegotiate cycle implementation for the responder case.
- * @param {object} remoteDescription the SDP object as defined by the WebRTC
- * which will be used as remote description in the cycle.
- * @param {function} resolve the success callback
- * @param {function} reject the failure callback
- * @private
- */
- _responderRenegotiate(remoteDescription, resolve, reject) {
- // FIXME use WebRTC promise API to simplify things
- logger.debug('Renegotiate: setting remote description');
- this.peerconnection.setRemoteDescription(
- remoteDescription,
- () => {
- logger.debug('Renegotiate: creating answer');
- this.peerconnection.createAnswer(
- answer => {
- logger.debug('Renegotiate: setting local description');
- this.peerconnection.setLocalDescription(
- answer,
- () => {
- resolve();
- },
- error => {
- reject(
- `setLocalDescription failed: ${error}`);
- }
- );
- },
- error => reject(`createAnswer failed: ${error}`),
- this.mediaConstraints
- );
- },
- error => reject(`setRemoteDescription failed: ${error}`)
- );
- }
-
- /**
- * Renegotiate cycle implementation for the initiator's case.
- * @param {object} remoteDescription the SDP object as defined by the WebRTC
- * which will be used as remote description in the cycle.
- * @param {function} resolve the success callback
- * @param {function} reject the failure callback
- * @private
- */
- _initiatorRenegotiate(remoteDescription, resolve, reject) {
- // FIXME use WebRTC promise API to simplify things
- if (this.peerconnection.signalingState === 'have-local-offer') {
-
- // Skip createOffer and setLocalDescription or FF will fail
- logger.debug(
- 'Renegotiate: setting remote description');
- this.peerconnection.setRemoteDescription(
- remoteDescription,
- () => {
- // In case when the answer is being set for the first time,
- // full sRD/sLD cycle is required to have the local
- // description updated and SSRCs synchronized correctly.
- // Otherwise SSRCs for streams added after invite, but
- // before the answer was accepted will not be detected.
- // The reason for that is that renegotiate can not be called
- // when adding tracks and they will not be reflected in
- // the local SDP.
- this._initiatorRenegotiate(
- remoteDescription, resolve, reject);
- },
- error => reject(`setRemoteDescription failed: ${error}`)
- );
- } else {
- logger.debug('Renegotiate: creating offer');
- this.peerconnection.createOffer(
- offer => {
- logger.debug('Renegotiate: setting local description');
- this.peerconnection.setLocalDescription(offer,
- () => {
- logger.debug(
- 'Renegotiate: setting remote description');
- this.peerconnection.setRemoteDescription(
- remoteDescription,
- () => {
- resolve();
- },
- error => reject(
- `setRemoteDescription failed: ${error}`)
- );
- },
- error => {
- reject('setLocalDescription failed: ', error);
- });
- },
- error => reject(`createOffer failed: ${error}`),
- this.mediaConstraints);
- }
- }
-
- /**
- * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
- * offer/answer cycle after both operations are done. Either
- * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
- * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
- * <tt>oldTrack</tt>
- * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
- * replaced
- * @param {JitsiLocalTrack|null} newTrack the new track to use
- * @returns {Promise} which resolves once the replacement is complete
- * with no arguments or rejects with an error {string}
- */
- replaceTrack(oldTrack, newTrack) {
- const workFunction = finishedCallback => {
- // Check if the connection was closed and pretend everything is OK.
- // This can happen if a track removal is scheduled but takes place
- // after the connection is closed.
- if (this.peerconnection.signalingState === 'closed'
- || this.peerconnection.connectionState === 'closed'
- || this.closed) {
-
- finishedCallback();
-
- return;
- }
-
- const oldLocalSdp = this.peerconnection.localDescription.sdp;
-
- // NOTE the code below assumes that no more than 1 video track
- // can be added to the peer connection.
- // Transition from no video to video (possibly screen sharing)
- if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
- // Clearing current primary SSRC will make
- // the SdpConsistency generate a new one which will result
- // with:
- // 1. source-remove for the recvonly
- // 2. source-add for the new video stream
- this.peerconnection.clearRecvonlySsrc();
-
- // Transition from video to no video
- } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
- // Clearing current primary SSRC and generating the recvonly
- // will result in:
- // 1. source-remove for the old video stream
- // 2. source-add for the recvonly stream
- this.peerconnection.clearRecvonlySsrc();
- this.peerconnection.generateRecvonlySsrc();
- }
- if (oldTrack) {
- this.peerconnection.removeTrack(oldTrack);
- }
- if (newTrack) {
- this.peerconnection.addTrack(newTrack);
- }
-
- if ((oldTrack || newTrack)
- && this.state === JingleSessionState.ACTIVE) {
- this._renegotiate()
- .then(() => {
- const newLocalSDP
- = new SDP(
- this.peerconnection.localDescription.sdp);
-
- this.notifyMySSRCUpdate(
- new SDP(oldLocalSdp), newLocalSDP);
- finishedCallback();
- },
- finishedCallback /* will be called with en error */);
- } else {
- finishedCallback();
- }
- };
-
- this.modificationQueue.push(
- workFunction,
- error => {
- if (error) {
- logger.error('Replace track error:', error);
- } else {
- logger.info('Replace track done!');
- }
- });
- }
-
- /**
- * Parse the information from the xml sourceRemoveElem and translate it
- * into sdp lines
- * @param {jquery xml element} sourceRemoveElem the source-remove
- * element from jingle
- * @param {SDP object} currentRemoteSdp the current remote
- * sdp (as of this new source-remove)
- * @returns {list} a list of SDP line strings that should
- * be removed from the remote SDP
- */
- _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
- const removeSsrcInfo = [];
-
- $(sourceRemoveElem).each((i1, content) => {
- const name = $(content).attr('name');
- let lines = '';
-
- $(content)
- .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
- .each(function() {
- /* eslint-disable no-invalid-this */
- const semantics = this.getAttribute('semantics');
- const ssrcs
- = $(this)
- .find('>source')
- .map(function() {
- return this.getAttribute('ssrc');
- })
- .get();
-
- if (ssrcs.length) {
- lines
- += `a=ssrc-group:${semantics} ${
- ssrcs.join(' ')}\r\n`;
- }
-
- /* eslint-enable no-invalid-this */
- });
- const ssrcs = [];
-
- // handles both >source and >description>source versions
- const tmp
- = $(content).find(
- 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
-
- tmp.each(function() {
- // eslint-disable-next-line no-invalid-this
- const ssrc = $(this).attr('ssrc');
-
- ssrcs.push(ssrc);
- });
- currentRemoteSdp.media.forEach((media, i2) => {
- if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
- return;
- }
- if (!removeSsrcInfo[i2]) {
- removeSsrcInfo[i2] = '';
- }
- ssrcs.forEach(ssrc => {
- const ssrcLines
- = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
-
- if (ssrcLines.length) {
- removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
- }
- });
- removeSsrcInfo[i2] += lines;
- });
- });
-
- return removeSsrcInfo;
- }
-
- /**
- * Will print an error if there is any difference, between the SSRCs given
- * in the <tt>oldSDP</tt> and the ones currently described in
- * the peerconnection's local description.
- * @param {string} operationName the operation's name which will be printed
- * in the error message.
- * @param {SDP} oldSDP the old local SDP which will be compared with
- * the current one.
- * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
- * otherwise.
- * @private
- */
- _verifyNoSSRCChanged(operationName, oldSDP) {
- const currentLocalSDP
- = new SDP(this.peerconnection.localDescription.sdp);
- let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
- const addedMedia = sdpDiff.getNewMedia();
-
- if (Object.keys(addedMedia).length) {
- logger.error(
- `${this} - some SSRC were added on ${operationName}`,
- addedMedia);
-
- return false;
- }
-
- sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
- const removedMedia = sdpDiff.getNewMedia();
-
- if (Object.keys(removedMedia).length) {
- logger.error(
- `${this} - some SSRCs were removed on ${operationName}`,
- removedMedia);
-
- return false;
- }
-
- return true;
- }
-
- /**
- * Adds local track back to this session, as part of the unmute operation.
- * @param {JitsiLocalTrack} track
- * @return {Promise} a promise that will resolve once the local track is
- * added back to this session and renegotiation succeeds. Will be rejected
- * with a <tt>string</tt> that provides some error details in case something
- * goes wrong.
- */
- addTrackAsUnmute(track) {
- return this._addRemoveTrackAsMuteUnmute(
- false /* add as unmute */, track);
- }
-
- /**
- * Remove local track as part of the mute operation.
- * @param {JitsiLocalTrack} track the local track to be removed
- * @return {Promise} a promise which will be resolved once the local track
- * is removed from this session and the renegotiation is performed.
- * The promise will be rejected with a <tt>string</tt> that the describes
- * the error if anything goes wrong.
- */
- removeTrackAsMute(track) {
- return this._addRemoveTrackAsMuteUnmute(
- true /* remove as mute */, track);
- }
-
- /**
- * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
- * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
- * <tt>false</tt> for "add as unmute".
- * @param {JitsiLocalTrack} track the track that will be added/removed
- * @private
- */
- _addRemoveTrackAsMuteUnmute(isMute, track) {
- if (!track) {
- return Promise.reject('invalid "track" argument value');
- }
- const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
- const workFunction = finishedCallback => {
- const tpc = this.peerconnection;
-
- if (!tpc) {
- finishedCallback(
- `Error: tried ${operationName} track with no active peer`
- + 'connection');
-
- return;
- }
- const oldLocalSDP = tpc.localDescription.sdp;
- const tpcOperation
- = isMute
- ? tpc.removeTrackMute.bind(tpc, track)
- : tpc.addTrackUnmute.bind(tpc, track);
-
- if (!tpcOperation()) {
- finishedCallback(`${operationName} failed!`);
- } else if (!oldLocalSDP || !tpc.remoteDescription.sdp) {
- finishedCallback();
- } else {
- this._renegotiate()
- .then(() => {
- // The results are ignored, as this check failure is not
- // enough to fail the whole operation. It will log
- // an error inside.
- this._verifyNoSSRCChanged(
- operationName, new SDP(oldLocalSDP));
- finishedCallback();
- },
- finishedCallback /* will be called with an error */);
- }
- };
-
- return new Promise((resolve, reject) => {
- this.modificationQueue.push(
- workFunction,
- error => {
- if (error) {
- reject(error);
- } else {
- resolve();
- }
- });
- });
- }
-
- /**
- * Resumes or suspends media transfer over the underlying peer connection.
- * @param {boolean} audioActive <tt>true</tt> to enable audio media
- * transfer or <tt>false</tt> to suspend audio media transmission.
- * @param {boolean} videoActive <tt>true</tt> to enable video media
- * transfer or <tt>false</tt> to suspend video media transmission.
- * @return {Promise} a <tt>Promise</tt> which will resolve once
- * the operation is done. It will be rejected with an error description as
- * a string in case anything goes wrong.
- */
- setMediaTransferActive(audioActive, videoActive) {
- if (!this.peerconnection) {
- return Promise.reject(
- 'Can not modify transfer active state,'
- + ' before "initialize" is called');
- }
-
- const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
- const logVideoStr = videoActive ? 'video active' : 'video inactive';
-
- logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
-
- const workFunction = finishedCallback => {
- const isSessionActive = this.state === JingleSessionState.ACTIVE;
-
- // Because the value is modified on the queue it's impossible to
- // check it's final value reliably prior to submitting the task.
- // The rule here is that the last submitted state counts.
- // Check the values here to avoid unnecessary renegotiation cycle.
- const audioActiveChanged
- = this.peerconnection.setAudioTransferActive(audioActive);
-
- if (this._localVideoActive !== videoActive) {
- this._localVideoActive = videoActive;
-
- // Do only for P2P - Jicofo will reply with 'bad-request'
- // We don't want to send 'content-modify', before the initial
- // O/A (state === JingleSessionState.ACTIVE), because that will
- // mess up video media direction in the remote SDP.
- // 'content-modify' when processed only affects the media
- // direction in the local SDP. We're doing that, because setting
- // 'inactive' on video media in remote SDP will mess up our SDP
- // translation chain (simulcast, RTX, video mute etc.).
- if (this.isP2P && isSessionActive) {
- this.sendContentModify(videoActive);
- }
- }
-
- const pcVideoActiveChanged
- = this.peerconnection.setVideoTransferActive(
- this._localVideoActive && this._remoteVideoActive);
-
- // Will do the sRD/sLD cycle to update SDPs and adjust the media
- // direction
- if (isSessionActive
- && (audioActiveChanged || pcVideoActiveChanged)) {
- this._renegotiate()
- .then(
- finishedCallback,
- finishedCallback /* will be called with an error */);
- } else {
- finishedCallback();
- }
- };
-
- return new Promise((resolve, reject) => {
- this.modificationQueue.push(
- workFunction,
- error => {
- if (error) {
- reject(error);
- } else {
- resolve();
- }
- });
- });
- }
-
- /**
- * Will put and execute on the queue a session modify task. Currently it
- * only checks the senders attribute of the video content in order to figure
- * out if the remote peer has video in the inactive state (stored locally
- * in {@link _remoteVideoActive} - see field description for more info).
- * @param {jQuery} jingleContents jQuery selector pointing to the jingle
- * element of the session modify IQ.
- * @see {@link _remoteVideoActive}
- * @see {@link _localVideoActive}
- */
- modifyContents(jingleContents) {
- const newVideoSenders
- = JingleSessionPC.parseVideoSenders(jingleContents);
-
- if (newVideoSenders === null) {
- logger.error(
- `${this} - failed to parse video "senders" attribute in`
- + '"content-modify" action');
-
- return;
- }
-
- const workFunction = finishedCallback => {
- if (this._assertNotEnded('content-modify')
- && this._modifyRemoteVideoActive(newVideoSenders)) {
- // Will do the sRD/sLD cycle to update SDPs and adjust
- // the media direction
- this._renegotiate()
- .then(finishedCallback, finishedCallback /* (error) */);
- } else {
- finishedCallback();
- }
- };
-
- logger.debug(
- `${this} queued "content-modify" task`
- + `(video senders="${newVideoSenders}")`);
-
- this.modificationQueue.push(
- workFunction,
- error => {
- if (error) {
- logger.error('"content-modify" failed', error);
- }
- });
- }
-
- /**
- * Processes new value of remote video "senders" Jingle attribute and tries
- * to apply it for {@link _remoteVideoActive}.
- * @param {string} remoteVideoSenders the value of "senders" attribute of
- * Jingle video content element advertised by remote peer.
- * @return {boolean} <tt>true</tt> if the change affected state of
- * the underlying peerconnection and renegotiation is required for
- * the changes to take effect.
- * @private
- */
- _modifyRemoteVideoActive(remoteVideoSenders) {
- const isRemoteVideoActive
- = remoteVideoSenders === 'both'
- || (remoteVideoSenders === 'initiator' && this.isInitiator)
- || (remoteVideoSenders === 'responder' && !this.isInitiator);
-
- if (isRemoteVideoActive !== this._remoteVideoActive) {
- logger.debug(
- `${this} new remote video active: ${isRemoteVideoActive}`);
- this._remoteVideoActive = isRemoteVideoActive;
- }
-
- return this.peerconnection.setVideoTransferActive(
- this._localVideoActive && this._remoteVideoActive);
- }
-
- /**
- * Figures out added/removed ssrcs and send update IQs.
- * @param oldSDP SDP object for old description.
- * @param newSDP SDP object for new description.
- */
- notifyMySSRCUpdate(oldSDP, newSDP) {
-
- if (this.state !== JingleSessionState.ACTIVE) {
- logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
-
- return;
- }
-
- // send source-remove IQ.
- let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
- const remove = $iq({ to: this.remoteJid,
- type: 'set' })
- .c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'source-remove',
- initiator: this.initiator,
- sid: this.sid
- }
- );
- const removedAnySSRCs = sdpDiffer.toJingle(remove);
-
- if (removedAnySSRCs) {
- logger.info('Sending source-remove', remove.tree());
- this.connection.sendIQ(
- remove, null,
- this.newJingleErrorHandler(remove), IQ_TIMEOUT);
- } else {
- logger.log('removal not necessary');
- }
-
- // send source-add IQ.
- sdpDiffer = new SDPDiffer(oldSDP, newSDP);
- const add = $iq({ to: this.remoteJid,
- type: 'set' })
- .c('jingle', {
- xmlns: 'urn:xmpp:jingle:1',
- action: 'source-add',
- initiator: this.initiator,
- sid: this.sid
- }
- );
-
- const containsNewSSRCs = sdpDiffer.toJingle(add);
-
- if (containsNewSSRCs) {
- logger.info('Sending source-add', add.tree());
- this.connection.sendIQ(
- add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
- } else {
- logger.log('addition not necessary');
- }
- }
-
- /**
- * Method returns function(errorResponse) which is a callback to be passed
- * to Strophe connection.sendIQ method. An 'error' structure is created that
- * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
- * structure is as follows:
- * {
- * code: {XMPP error response code}
- * reason: {the name of XMPP error reason element or 'timeout' if the
- * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
- * source: {request.tree() that provides original request}
- * session: {this JingleSessionPC.toString()}
- * }
- * @param request Strophe IQ instance which is the request to be dumped into
- * the error structure
- * @param failureCb function(error) called when error response was returned
- * or when a timeout has occurred.
- * @returns {function(this:JingleSessionPC)}
- */
- newJingleErrorHandler(request, failureCb) {
- return errResponse => {
-
- const error = {};
-
- // Get XMPP error code and condition(reason)
- const errorElSel = $(errResponse).find('error');
-
- if (errorElSel.length) {
- error.code = errorElSel.attr('code');
- const errorReasonSel = $(errResponse).find('error :first');
-
- if (errorReasonSel.length) {
- error.reason = errorReasonSel[0].tagName;
- }
-
- const errorMsgSel = errorElSel.find('>text');
-
- if (errorMsgSel.length) {
- error.msg = errorMsgSel.text();
- }
- }
-
- if (!errResponse) {
- error.reason = 'timeout';
- }
-
- error.session = this.toString();
-
- if (failureCb) {
- failureCb(error);
- } else if (this.state === JingleSessionState.ENDED
- && error.reason === 'item-not-found') {
- // When remote peer decides to terminate the session, but it
- // still have few messages on the queue for processing,
- // it will first send us 'session-terminate' (we enter ENDED)
- // and then follow with 'item-not-found' for the queued requests
- // We don't want to have that logged on error level.
- logger.debug(`Jingle error: ${JSON.stringify(error)}`);
- } else {
- GlobalOnErrorHandler.callErrorHandler(
- new Error(
- `Jingle error: ${JSON.stringify(error)}`));
- }
- };
- }
-
- /**
- *
- * @param session
- * @param error
- */
- static onJingleFatalError(session, error) {
- if (this.room) {
- this.room.eventEmitter.emit(
- XMPPEvents.CONFERENCE_SETUP_FAILED, session, error);
- this.room.eventEmitter.emit(
- XMPPEvents.JINGLE_FATAL_ERROR, session, error);
- }
- }
-
- /**
- * Returns the ice connection state for the peer connection.
- * @returns the ice connection state for the peer connection.
- */
- getIceConnectionState() {
- return this.peerconnection.iceConnectionState;
- }
-
- /**
- * Closes the peerconnection.
- */
- close() {
- this.closed = true;
-
- // The signaling layer will remove it's listeners
- this.signalingLayer.setChatRoom(null);
-
- // do not try to close if already closed.
- this.peerconnection
- && ((this.peerconnection.signalingState
- && this.peerconnection.signalingState !== 'closed')
- || (this.peerconnection.connectionState
- && this.peerconnection.connectionState !== 'closed'))
- && this.peerconnection.close();
- }
-
- /**
- * Converts to string with minor summary.
- * @return {string}
- */
- toString() {
- return `JingleSessionPC[p2p=${this.isP2P},`
- + `initiator=${this.isInitiator},sid=${this.sid}]`;
- }
-
- /**
- * If the A/B test for suspend video is disabled according to the room's
- * configuration, returns undefined. Otherwise returns a boolean which
- * indicates whether the suspend video option should be enabled or disabled.
- */
- _abtestSuspendVideoEnabled() {
- if (!this.room.options.abTesting
- || !this.room.options.abTesting.enableSuspendVideoTest) {
- return;
- }
-
- // We want the two participants in a P2P call to agree on the value of
- // the "suspend" option. We use the JID of the initiator, because it is
- // both randomly selected and agreed upon by both participants.
- const jid = this._getInitiatorJid();
-
- return integerHash(jid) % 2 === 0;
- }
- }
|