sip-connector 5.1.4 → 5.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/__mocks__/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,2DAAuD;AAE1C,QAAA,IAAI,GAAG,MAAM,CAAC;AACd,QAAA,WAAW,GAAG,aAAa,CAAC;AAC5B,QAAA,cAAc,GAAG,gBAAgB,CAAC;AAClC,QAAA,yBAAyB,GAAG,2BAA2B,CAAC;AAErE,MAAM,MAAM,GAAG,IAAI,oBAAK,CAAC,kBAAkB,CAAC,iCAAyB,CAAC,CAAC;AAEvE,MAAM,qBAAqB,GAAG;IAC5B,YAAY,EAAE,sBAAc;IAC5B,qBAAqB,EAAE,iCAAyB;CACjD,CAAC;AAEW,QAAA,uDAAuD,qBAC/D,qBAAqB,EACxB;AACW,QAAA,kCAAkC,mCAC1C,qBAAqB,KACxB,IAAI,EAAJ,YAAI,EACJ,QAAQ,EAAE,6BAAgB,EAC1B,QAAQ,EAAE,IAAI,IACd;AACW,QAAA,iDAAiD,mCACzD,0CAAkC,KACrC,WAAW,EAAX,mBAAW,IACX;AACW,QAAA,qCAAqC,mCAC7C,qBAAqB,KACxB,WAAW,EAAX,mBA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BAAoB,qBAAa,EAAE,CAAC,CAAC"}
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -1 +1 @@
1
- {"version":3,"file":"jssip.mock.js","sourceRoot":"","sources":["../../src/__mocks__/jssip.mock.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,wFAA2D;AAC3D,qDAAqF;AAyC5E,iGAzCI,0BAAgB,OAyCJ;AAAE,mGAzCI,4BAAkB,OAyCJ;AAAE,+FAzCI,wBAAc,OAyCJ;AAxC7D,+DAAmE;AAwCJ,yGAxC7C,uCAAwB,OAwC6C;AAvCvF,kEAAqC;AAErC,MAAM,cAAc,GAAG,CAAC,OAAmB,EAAE,YAAwB,EAAE,EAAE;IACvE,MAAM,UAAU,GAAG,QAAQ,CAAC;IAC5B,MAAM,OAAO,GAAG,IAAI,sBAAO,CAAC,YAAY,CAAC,CAAC;IAC1C,MAAM,iBAAiB,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC;IAElD,aAAa;IACb,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;AACrC,CAAC,CAAC;AAEF,MAAM,kBAAkB,GAAG,CAAC,EAAM,EAAE,YAAwB,EAAE,EAAE;IAC9D,MAAM,OAAO,GAAG,IAAI,sBAAO,CAAC,YAAY,CAAC,CAAC;IAC1C,MAAM,gBAAgB,GAAG,EAAE,OAAO,EAAE,CAAC;IAErC,EA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IAC1B,CAAC,EAAE;QACD,MAAM,EAAE,QAAQ;KACjB;CACF,CAAC;AAEF,kBAAe,KAAK,CAAC"}
package/dist/index.es5.js CHANGED
@@ -13,5 +13,5 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
15
  ***************************************************************************** */
16
- function o(e,t,s,i){return new(s||(s=Promise))((function(n,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}const r=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,a=r(1),c=r(void 0),h=(e,t,s)=>{const i=e.getParameters();i.encodings&&0!==i.encodings.length||(i.encodings=[{}]);const[n]=i.encodings,o=n.scaleResolutionDownBy,r=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&a(s,t))return s})(t.scaleResolutionDownBy,o);let h=!1;void 0!==r&&(i.encodings[0].scaleResolutionDownBy=r,h=!0);const d=n.maxBitrate,l=((e,t)=>{if(c(e,t))return e})(t.maxBitrate,d);return void 0!==l&&(i.encodings[0].maxBitrate=l,h=!0),h?(s&&s(i),e.setParameters(i)):Promise.resolve()},d=["incomingCall","declinedIncomingCall","failedIncomingCall"],l=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],g=["availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","shareState","enterRoom","peerconnection:confirmed","peerconnection:ontrack","channels","channels:notify","ended:fromserver","main-cam-control","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-conference","participant:move-request-to-stream","participant:canceling-word-request","webcast:started","webcast:stopped","account:changed","account:deleted","conference:participant-token-issued"],u=["ended","connecting","sending","reinvite","replaces","refer","progress","accepted","confirmed","peerconnection","failed","muted","unmuted","newDTMF","newInfo","hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],m=[...l,...d],_=[...u,...g];var S=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:d,UA_JSSIP_EVENT_NAMES:l,SESSION_SYNTHETICS_EVENT_NAMES:g,SESSION_JSSIP_EVENT_NAMES:u,UA_EVENT_NAMES:m,SESSION_EVENT_NAMES:_});const f="Terminated";var v=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:f,WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"});const p=e=>e.trim().replace(/ /g,"_"),E=(C=1e5,T=99999999,()=>Math.floor(Math.random()*(T-C))+C);var C,T;const b=e=>{const t=[...e.getAudioTracks(),...e.getVideoTracks()],s=new MediaStream(t);return s.getTracks=()=>[...s.getAudioTracks(),...s.getVideoTracks()],s};var R;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION"}(R||(R={}));const N=(e=new Error)=>{const{originator:s,cause:i}=e;return!!t(e)||"string"==typeof i&&("Request Timeout"===i||"Rejected"===i||"local"===s&&("Canceled"===i||i===f))},w="SipConnector";class y{constructor({JsSIP:t}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.isPendingPresentation=!1,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger("connecting",void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const i=this.incomingSession,n=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger("declinedIncomingCall",n),t(i.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if("remote"===e){this.incomingSession=t;const e=this.remoteCallerData;this.incomingSession.on("failed",(()=>{this.removeIncomingSession(),this._uaEvents.trigger("failedIncomingCall",e)})),this._uaEvents.trigger("incomingCall",e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:i=!1,sipServerUrl:n,sipWebSocketServerURL:r,remoteAddress:a,extraHeaders:c=[],sdpSemantics:h="plan-b",sessionTimers:d=!1,registerExpires:g=300,connectionRecoveryMinInterval:u=2,connectionRecoveryMaxInterval:m=6})=>o(this,void 0,void 0,(function*(){if(!n)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(i&&!t)throw new Error("user is required for authorized connection");if(i&&!s)throw new Error("password is required for authorized connection");let o;this._connectionConfiguration={sipServerUrl:n,displayName:e,register:i,user:t,password:s},this._init({sipServerUrl:n,sipWebSocketServerURL:r}),o=i&&t?t.trim():E();let _="Chrome";"unified-plan"===h&&(_="ChromeNew");const S={password:s,register:i,display_name:p(e),user_agent:_,sdp_semantics:h,sockets:[this.socket],uri:this.getSipServerUrl(o),session_timers:d,register_expires:g,connection_recovery_min_interval:u,connection_recovery_max_interval:m};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!S.register,this.ua=new this.JsSIP.UA(S),this._uaEvents.eachTriggers(((e,t)=>{const s=l.find((e=>e===t));s&&this.ua.on(s,e)}));const f=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(a),v=[...f,...c];return this.ua.registrator().setExtraHeaders(v),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{n(),e(this.ua)},i=e=>{n(),t(e)},n=()=>{this.off("registered",s),this.off("registrationFailed",i),this.off("connected",s),this.off("disconnected",i)};(()=>{this.isRegisterConfig?(this.on("registered",s),this.on("registrationFailed",i)):this.on("connected",s),this.on("disconnected",i)})(),this.on("newRTCSession",this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,i)=>{let n=!1,o=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(n=this.ua.set("display_name",p(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(o=this.ua.set("password",t),this._connectionConfiguration.password=t);const r=n||o;o&&this.isRegisterConfig?this.register().then((()=>s(r))).catch(i):r?s(r):i(r)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>o(this,void 0,void 0,(function*(){this.off("newRTCSession",this.handleNewRTCSession);const e=new Promise((e=>{this.once("disconnected",(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger("disconnected",void 0)):this._uaEvents.trigger("disconnected",void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:i,iceServers:n})=>new Promise(((o,r)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(o).catch(r),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:b(t),eventHandlers:this._sessionEvents.triggers,pcConfig:{iceServers:n}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:i})=>new Promise(((n,o)=>{if(!this.isAvailableIncomingCall)return void o(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession(),this._sessionEvents.eachTriggers(((e,t)=>{const s=u.find((e=>e===t));s&&this.session.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=this.session.remote_identity.uri.user,this._handleCall({ontrack:t}).then(n).catch(o);const r=e?b(e):void 0;this.session.answer({extraHeaders:s,mediaStream:r,pcConfig:{iceServers:i}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const i=()=>{this.offSession("peerconnection",a),this.offSession("confirmed",c)},n=()=>{this.offSession("failed",o),this.offSession("ended",o)},o=e=>{i(),n(),s(e)};let r;const a=({peerconnection:t})=>{r=t,r.ontrack=t=>{this._sessionEvents.trigger("peerconnection:ontrack",r),e&&e(t)}},c=()=>{r&&this._sessionEvents.trigger("peerconnection:confirmed",r),i(),n(),t(r)};(()=>{this.onSession("peerconnection",a),this.onSession("confirmed",c)})(),(()=>{this.onSession("failed",o),this.onSession("ended",o)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{this.session?(this.onceSession("newDTMF",(({originator:e})=>{"local"===e&&t()})),this.session.sendDTMF(e,{duration:120,interToneGap:600})):s()})),this._hangUpWithoutCancelRequests=()=>o(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case"YOUCANRECEIVECONTENT":this._sessionEvents.trigger("availableSecondRemoteStream",void 0);break;case"CONTENTEND":this._sessionEvents.trigger("notAvailableSecondRemoteStream",void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger("mustStopPresentation",void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader("X-WEBRTC-INPUT-CHANNELS"),s=e.getHeader("X-WEBRTC-OUTPUT-CHANNELS");if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger("channels",e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._maybeTriggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._maybeTriggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._maybeTriggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._maybeTriggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._maybeTriggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._maybeTriggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._maybeTriggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._maybeTriggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._maybeTriggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._maybeTriggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._maybeTriggerConferenceParticipantTokenIssued(t)}},this._maybeTriggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._sessionEvents.trigger("participant:removed-from-list-moderators",t)},this._maybeTriggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._sessionEvents.trigger("participant:added-to-list-moderators",t)},this._maybeTriggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._sessionEvents.trigger("webcast:started",s)},this._maybeTriggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._sessionEvents.trigger("webcast:stopped",s)},this._maybeTriggerAccountChangedNotify=()=>{this._sessionEvents.trigger("account:changed",void 0)},this._maybeTriggerAccountDeletedNotify=()=>{this._sessionEvents.trigger("account:deleted",void 0)},this._maybeTriggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this._sessionEvents.trigger("conference:participant-token-issued",i)},this._maybeTriggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this.session&&this._sessionEvents.trigger("channels:notify",t)},this._maybeTriggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._sessionEvents.trigger("participant:move-request-to-conference",t)},this._maybeTriggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._sessionEvents.trigger("participant:canceling-word-request",t)},this._maybeTriggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._sessionEvents.trigger("participant:move-request-to-stream",t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger("enterRoom",t)},this._triggerShareState=e=>{const t=e.getHeader("x-webrtc-share-state");this._sessionEvents.trigger("shareState",t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger("main-cam-control",{mainCam:t,resolutionMainCam:s})},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,i=s.getHeader("content-type");if(i)switch(i){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case"application/vinteo.webrtc.sharedesktop":this._triggerShareState(s);break;case"application/vinteo.webrtc.maincam":this._triggerMainCamControl(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;"remote"===t&&this._sessionEvents.trigger("ended:fromserver",e),this._restoreSession()},this.JsSIP=t,this._sessionEvents=new s(_),this._uaEvents=new s(m),this._cancelableConnect=new e(this._connect,w,(()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()})),this._cancelableCreateUa=new e(this._createUa,w),this._cancelableDisconnect=new e(this._disconnect,w),this._cancelableSet=new e(this._set,w),this._cancelableCall=new e(this._call,w),this._cancelableAnswer=new e(this._answer,w),this._cancelableSendDTMF=new e(this._sendDTMF,w),this.onSession("shareState",this._handleShareState),this.onSession("newInfo",this._handleNewInfo),this.on("sipEvent",this._handleSipEvent),this.onSession("failed",this._handleEnded),this.onSession("ended",this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on("registered",e),this.ua.on("registrationFailed",t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on("unregistered",e),this.ua.unregister()):t(new Error("ua is not registered"))}))}replaceMediaStream(e,t){return this.session.replaceMediaStream(e,t)}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:i}={}){this.isPendingPresentation=!0;const n=b(e);this._streamPresentationCurrent=n;let o=Promise.resolve();const r=s?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"];return this.isEstablishedSession&&(o=this.session.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:r}).then((()=>this.session.startPresentation(n,t))).then((()=>{const{connection:t}=this;if(!t||void 0===i)return;return((e,t,s)=>{const i=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return i?h(i,{maxBitrate:s}):Promise.resolve()})(t.getSenders(),e,i)})).then((()=>e)).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e}))),o.finally((()=>{this.isPendingPresentation=!1}))}stopPresentation({isP2P:e=!1}={}){this.isPendingPresentation=!0;const t=this._streamPresentationCurrent;let s=Promise.resolve();const i=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"];return this.isEstablishedSession&&t&&(s=this.session.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:i}).then((()=>this.session.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e}))),!this.isEstablishedSession&&t&&this._sessionEvents.trigger("presentation:ended",t),s.finally((()=>{this._resetPresentation()}))}_resetPresentation(){delete this._streamPresentationCurrent,this.isPendingPresentation=!1}on(e,t){this._uaEvents.on(e,t)}once(e,t){this._uaEvents.once(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){this._sessionEvents.on(e,t)}onceSession(e,t){this._sessionEvents.once(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isMutedVideo(){if(this.session)return this.session.isMuted().video}isMutedAudio(){if(this.session)return this.session.isMuted().audio}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,i,n,o;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(i=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===i?void 0:i.uri.host,incomingNumber:null===(o=null===(n=null==this?void 0:this.incomingSession)||void 0===n?void 0:n.remote_identity)||void 0===o?void 0:o.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get isEstablishedSession(){return this.session&&this.session.isEstablished()}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!(!this.ua||!this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,i=this._remoteStreams[s]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[s]=i,i}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,i)=>{if("audio"===s.kind)return;const n=s,o=e[i-1];let r;o&&"audio"===o.kind&&(r=o);const a=this._generateStream(n,r);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession("channels")}sendChannels({inputChannels:e,outputChannels:t}){const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}}const A=e=>1e6*e,I=A(64),M=A(6144),P=i(),U=e=>{P.add(e),P().catch((e=>{console.debug("videoSendingBalancer: error",e)}))},k=(e,t,s,i)=>{U((()=>h(e,{scaleResolutionDownBy:t,maxBitrate:s},i)))},q=(e,{track:t,resolution:s},i)=>{const n=t.getSettings(),o=n.width,r=n.height,[a,c]=s.split("x"),h=o/+a,d=r/+c,l=Math.max(h,d,1),g=(u=+a)<=64?I:u<=128?A(128):u<=256?A(256):u<=384?A(320):u<=426?A(512):u<=640?A(1024):u<=848?A(1536):u<=1280?A(2048):u<=1920?A(4096):M;var u;k(e,l,g,i)},O=({mainCam:e,resolutionMainCam:t,sender:s,track:i},n)=>{switch(e){case R.PAUSE_MAIN_CAM:((e,t)=>{k(e,200,I,t)})(s,n);break;case R.RESUME_MAIN_CAM:((e,t)=>{k(e,1,M,t)})(s,n);break;case R.MAX_MAIN_CAM_RESOLUTION:q(s,{track:i,resolution:t},n)}},D=(e,{autoSubscription:t=!0,ignoreForCodec:s,onSetParameters:i}={})=>{let r,a;const c=t=>o(void 0,void 0,void 0,(function*(){const{connection:i}=e;if(!i||void 0===r||void 0===a)return;const o=(e=>e.find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)})))(i.getSenders());if(o&&o.track){if(s){const e=yield n(o);if(h=s,(c=e)&&h&&c.toLowerCase().includes(h.toLowerCase()))return}var c,h;O({mainCam:r,resolutionMainCam:a,sender:o,track:o.track},t)}})),h=e=>{r=e.mainCam,a=e.resolutionMainCam,c(i)},d=()=>{e.onSession("main-cam-control",h)};return!0===t&&d(),{balance:c,subscribe:d,unsubscribe:()=>{e.offSession("main-cam-control",h)}}};export{v as causes,y as default,S as eventNames,n as getCodecFromSender,N as hasCanceledCallError,D as resolveVideoSendingBalancer};
16
+ function o(e,t,s,i){return new(s||(s=Promise))((function(n,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}const r=e=>(t,s)=>void 0!==s&&t!==s||void 0===s&&t!==e,a=r(1),c=r(void 0),h=(e,t,s)=>{const i=e.getParameters();i.encodings&&0!==i.encodings.length||(i.encodings=[{}]);const[n]=i.encodings,o=n.scaleResolutionDownBy,r=((e,t)=>{const s=void 0!==e?Math.max(e,1):null;if(null!==s&&a(s,t))return s})(t.scaleResolutionDownBy,o);let h=!1;void 0!==r&&(i.encodings[0].scaleResolutionDownBy=r,h=!0);const d=n.maxBitrate,l=((e,t)=>{if(c(e,t))return e})(t.maxBitrate,d);return void 0!==l&&(i.encodings[0].maxBitrate=l,h=!0),h?(s&&s(i),e.setParameters(i)):Promise.resolve()},d=["incomingCall","declinedIncomingCall","failedIncomingCall"],l=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],g=["availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","shareState","enterRoom","peerconnection:confirmed","peerconnection:ontrack","channels","channels:notify","ended:fromserver","main-cam-control","participant:added-to-list-moderators","participant:removed-from-list-moderators","participant:move-request-to-conference","participant:move-request-to-stream","participant:canceling-word-request","webcast:started","webcast:stopped","account:changed","account:deleted","conference:participant-token-issued"],u=["ended","connecting","sending","reinvite","replaces","refer","progress","accepted","confirmed","peerconnection","failed","muted","unmuted","newDTMF","newInfo","hold","unhold","update","sdp","icecandidate","getusermediafailed","peerconnection:createofferfailed","peerconnection:createanswerfailed","peerconnection:setlocaldescriptionfailed","peerconnection:setremotedescriptionfailed","presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],m=[...l,...d],_=[...u,...g];var S=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:d,UA_JSSIP_EVENT_NAMES:l,SESSION_SYNTHETICS_EVENT_NAMES:g,SESSION_JSSIP_EVENT_NAMES:u,UA_EVENT_NAMES:m,SESSION_EVENT_NAMES:_});const f="Terminated";var v=Object.freeze({__proto__:null,CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:f,WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"});const p=e=>e.trim().replace(/ /g,"_"),E=(C=1e5,T=99999999,()=>Math.floor(Math.random()*(T-C))+C);var C,T;const b=e=>{const t=[...e.getAudioTracks(),...e.getVideoTracks()],s=new MediaStream(t);return s.getTracks=()=>[...s.getAudioTracks(),...s.getVideoTracks()],s};var R;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION"}(R||(R={}));const N=(e=new Error)=>{const{originator:s,cause:i}=e;return!!t(e)||"string"==typeof i&&("Request Timeout"===i||"Rejected"===i||"local"===s&&("Canceled"===i||i===f))},w="SipConnector";class y{constructor({JsSIP:t}){this._isRegisterConfig=!1,this._connectionConfiguration={},this._remoteStreams={},this.getSipServerUrl=e=>e,this.isPendingPresentation=!1,this.connect=e=>(this._cancelRequests(),this._cancelableConnect.request(e)),this.createUa=e=>this._cancelableCreateUa.request(e),this.set=e=>this._cancelableSet.request(e),this.call=e=>this._cancelableCall.request(e),this.disconnect=()=>(this._cancelRequests(),this._disconnectWithoutCancelRequests()),this.answerToIncomingCall=e=>this._cancelableAnswer.request(e),this.sendDTMF=e=>this._cancelableSendDTMF.request(e),this.hangUp=()=>(this._cancelRequests(),this._hangUpWithoutCancelRequests()),this.tryRegister=()=>this.isRegisterConfig?(this._uaEvents.trigger("connecting",void 0),this.unregister().finally((()=>this.register())).finally((()=>{}))):Promise.reject(new Error("Config is not registered")),this.declineToIncomingCall=({statusCode:e=487}={})=>new Promise(((t,s)=>{if(!this.isAvailableIncomingCall)return void s(new Error("no incomingSession"));const i=this.incomingSession,n=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger("declinedIncomingCall",n),t(i.terminate({status_code:e}))})),this.busyIncomingCall=()=>this.declineToIncomingCall({statusCode:486}),this.removeIncomingSession=()=>{delete this.incomingSession},this.handleNewRTCSession=({originator:e,session:t})=>{if("remote"===e){this.incomingSession=t;const e=this.remoteCallerData;this.incomingSession.on("failed",(()=>{this.removeIncomingSession(),this._uaEvents.trigger("failedIncomingCall",e)})),this._uaEvents.trigger("incomingCall",e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:s,register:i=!1,sipServerUrl:n,sipWebSocketServerURL:r,remoteAddress:a,extraHeaders:c=[],sdpSemantics:h="plan-b",sessionTimers:d=!1,registerExpires:g=300,connectionRecoveryMinInterval:u=2,connectionRecoveryMaxInterval:m=6})=>o(this,void 0,void 0,(function*(){if(!n)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(i&&!t)throw new Error("user is required for authorized connection");if(i&&!s)throw new Error("password is required for authorized connection");let o;this._connectionConfiguration={sipServerUrl:n,displayName:e,register:i,user:t,password:s},this._init({sipServerUrl:n,sipWebSocketServerURL:r}),o=i&&t?t.trim():E();let _="Chrome";"unified-plan"===h&&(_="ChromeNew");const S={password:s,register:i,display_name:p(e),user_agent:_,sdp_semantics:h,sockets:[this.socket],uri:this.getSipServerUrl(o),session_timers:d,register_expires:g,connection_recovery_min_interval:u,connection_recovery_max_interval:m};this.ua&&(yield this._disconnectWithoutCancelRequests()),this._isRegisterConfig=!!S.register,this.ua=new this.JsSIP.UA(S),this._uaEvents.eachTriggers(((e,t)=>{const s=l.find((e=>e===t));s&&this.ua.on(s,e)}));const f=(e=>{const t=[];return e&&t.push(`X-Vinteo-Remote: ${e}`),t})(a),v=[...f,...c];return this.ua.registrator().setExtraHeaders(v),this.ua})),this._start=()=>new Promise(((e,t)=>{const s=()=>{n(),e(this.ua)},i=e=>{n(),t(e)},n=()=>{this.off("registered",s),this.off("registrationFailed",i),this.off("connected",s),this.off("disconnected",i)};(()=>{this.isRegisterConfig?(this.on("registered",s),this.on("registrationFailed",i)):this.on("connected",s),this.on("disconnected",i)})(),this.on("newRTCSession",this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((s,i)=>{let n=!1,o=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(n=this.ua.set("display_name",p(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(o=this.ua.set("password",t),this._connectionConfiguration.password=t);const r=n||o;o&&this.isRegisterConfig?this.register().then((()=>s(r))).catch(i):r?s(r):i(r)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>o(this,void 0,void 0,(function*(){this.off("newRTCSession",this.handleNewRTCSession);const e=new Promise((e=>{this.once("disconnected",(()=>{delete this.ua,e()}))}));return this.ua?(yield this._hangUpWithoutCancelRequests(),this.ua?this.ua.stop():this._uaEvents.trigger("disconnected",void 0)):this._uaEvents.trigger("disconnected",void 0),e})),this._call=({number:e,mediaStream:t,extraHeaders:s=[],ontrack:i,iceServers:n})=>new Promise(((o,r)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(o).catch(r),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:s,mediaStream:b(t),eventHandlers:this._sessionEvents.triggers,pcConfig:{iceServers:n}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:s=[],iceServers:i})=>new Promise(((n,o)=>{if(!this.isAvailableIncomingCall)return void o(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession(),this._sessionEvents.eachTriggers(((e,t)=>{const s=u.find((e=>e===t));s&&this.session.on(s,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=this.session.remote_identity.uri.user,this._handleCall({ontrack:t}).then(n).catch(o);const r=e?b(e):void 0;this.session.answer({extraHeaders:s,mediaStream:r,pcConfig:{iceServers:i}})})),this._handleCall=({ontrack:e})=>new Promise(((t,s)=>{const i=()=>{this.offSession("peerconnection",a),this.offSession("confirmed",c)},n=()=>{this.offSession("failed",o),this.offSession("ended",o)},o=e=>{i(),n(),s(e)};let r;const a=({peerconnection:t})=>{r=t,r.ontrack=t=>{this._sessionEvents.trigger("peerconnection:ontrack",r),e&&e(t)}},c=()=>{r&&this._sessionEvents.trigger("peerconnection:confirmed",r),i(),n(),t(r)};(()=>{this.onSession("peerconnection",a),this.onSession("confirmed",c)})(),(()=>{this.onSession("failed",o),this.onSession("ended",o)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,s)=>{this.session?(this.onceSession("newDTMF",(({originator:e})=>{"local"===e&&t()})),this.session.sendDTMF(e,{duration:120,interToneGap:600})):s()})),this._hangUpWithoutCancelRequests=()=>o(this,void 0,void 0,(function*(){if(this.ua&&this.session){const{session:e}=this;this._streamPresentationCurrent&&(yield this.stopPresentation()),this._restoreSession(),e.isEnded()||e.terminate()}})),this._handleShareState=e=>{switch(e){case"YOUCANRECEIVECONTENT":this._sessionEvents.trigger("availableSecondRemoteStream",void 0);break;case"CONTENTEND":this._sessionEvents.trigger("notAvailableSecondRemoteStream",void 0);break;case"YOUMUSTSTOPSENDCONTENT":this._sessionEvents.trigger("mustStopPresentation",void 0)}},this._maybeTriggerChannels=e=>{const t=e.getHeader("X-WEBRTC-INPUT-CHANNELS"),s=e.getHeader("X-WEBRTC-OUTPUT-CHANNELS");if(t&&s){const e={inputChannels:t,outputChannels:s};this._sessionEvents.trigger("channels",e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._maybeTriggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._maybeTriggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._maybeTriggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._maybeTriggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._maybeTriggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._maybeTriggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._maybeTriggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._maybeTriggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._maybeTriggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._maybeTriggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._maybeTriggerConferenceParticipantTokenIssued(t)}},this._maybeTriggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._sessionEvents.trigger("participant:removed-from-list-moderators",t)},this._maybeTriggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._sessionEvents.trigger("participant:added-to-list-moderators",t)},this._maybeTriggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._sessionEvents.trigger("webcast:started",s)},this._maybeTriggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this._sessionEvents.trigger("webcast:stopped",s)},this._maybeTriggerAccountChangedNotify=()=>{this._sessionEvents.trigger("account:changed",void 0)},this._maybeTriggerAccountDeletedNotify=()=>{this._sessionEvents.trigger("account:deleted",void 0)},this._maybeTriggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this._sessionEvents.trigger("conference:participant-token-issued",i)},this._maybeTriggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this.session&&this._sessionEvents.trigger("channels:notify",t)},this._maybeTriggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._sessionEvents.trigger("participant:move-request-to-conference",t)},this._maybeTriggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._sessionEvents.trigger("participant:canceling-word-request",t)},this._maybeTriggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._sessionEvents.trigger("participant:move-request-to-stream",t)},this._triggerEnterRoom=e=>{const t=e.getHeader("x-webrtc-enter-room");this._sessionEvents.trigger("enterRoom",t)},this._triggerShareState=e=>{const t=e.getHeader("x-webrtc-share-state");this._sessionEvents.trigger("shareState",t)},this._triggerMainCamControl=e=>{const t=e.getHeader("X-WEBRTC-MAINCAM"),s=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger("main-cam-control",{mainCam:t,resolutionMainCam:s})},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const s=e.request,i=s.getHeader("content-type");if(i)switch(i){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(s),this._maybeTriggerChannels(s);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(s);break;case"application/vinteo.webrtc.sharedesktop":this._triggerShareState(s);break;case"application/vinteo.webrtc.maincam":this._triggerMainCamControl(s)}},this._handleSipEvent=({request:e})=>{this._maybeHandleNotify(e)},this._maybeHandleNotify=e=>{const t=e.getHeader("X-VINTEO-NOTIFY");if(t){const e=JSON.parse(t);this._handleNotify(e)}},this._handleEnded=e=>{const{originator:t}=e;"remote"===t&&this._sessionEvents.trigger("ended:fromserver",e),this._restoreSession()},this.JsSIP=t,this._sessionEvents=new s(_),this._uaEvents=new s(m),this._cancelableConnect=new e(this._connect,w,(()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()})),this._cancelableCreateUa=new e(this._createUa,w),this._cancelableDisconnect=new e(this._disconnect,w),this._cancelableSet=new e(this._set,w),this._cancelableCall=new e(this._call,w),this._cancelableAnswer=new e(this._answer,w),this._cancelableSendDTMF=new e(this._sendDTMF,w),this.onSession("shareState",this._handleShareState),this.onSession("newInfo",this._handleNewInfo),this.on("sipEvent",this._handleSipEvent),this.onSession("failed",this._handleEnded),this.onSession("ended",this._handleEnded)}register(){return new Promise(((e,t)=>{this.isRegisterConfig?(this.ua.on("registered",e),this.ua.on("registrationFailed",t),this.ua.register()):t(new Error("Config is not registered"))}))}unregister(){return new Promise(((e,t)=>{this.isRegistered?(this.ua.on("unregistered",e),this.ua.unregister()):t(new Error("ua is not registered"))}))}replaceMediaStream(e,t){return this.session.replaceMediaStream(e,t)}startPresentation(e,{isNeedReinvite:t=!0,isP2P:s=!1,maxBitrate:i}={}){this.isPendingPresentation=!0;const n=b(e);this._streamPresentationCurrent=n;let o=Promise.resolve();const r=s?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"];return this.isEstablishedSession&&(o=this.session.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:r}).then((()=>this.session.startPresentation(n,t))).then((()=>{const{connection:t}=this;if(!t||void 0===i)return;return((e,t,s)=>{const i=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return i?h(i,{maxBitrate:s}):Promise.resolve()})(t.getSenders(),e,i)})).then((()=>e)).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e}))),o.finally((()=>{this.isPendingPresentation=!1}))}stopPresentation({isP2P:e=!1}={}){this.isPendingPresentation=!0;const t=this._streamPresentationCurrent;let s=Promise.resolve();const i=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"];return this.isEstablishedSession&&t&&(s=this.session.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:i}).then((()=>this.session.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e}))),!this.isEstablishedSession&&t&&this._sessionEvents.trigger("presentation:ended",t),s.finally((()=>{this._resetPresentation()}))}_resetPresentation(){delete this._streamPresentationCurrent,this.isPendingPresentation=!1}on(e,t){this._uaEvents.on(e,t)}once(e,t){this._uaEvents.once(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){this._sessionEvents.on(e,t)}onceSession(e,t){this._sessionEvents.once(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}isMutedVideo(){if(this.session)return this.session.isMuted().video}isMutedAudio(){if(this.session)return this.session.isMuted().audio}isConfigured(){return!!this.ua}getConnectionConfiguration(){return Object.assign({},this._connectionConfiguration)}getRemoteStreams(){if(!this.connection)return;const e=this.connection.getReceivers().map((({track:e})=>e));return(e=>e.some((e=>{const{kind:t}=e;return"video"===t})))(e)?this._generateStreams(e):this._generateAudioStreams(e)}get connection(){var e;return null===(e=null==this?void 0:this.session)||void 0===e?void 0:e.connection}get remoteCallerData(){var e,t,s,i,n,o;return{displayName:null===(t=null===(e=null==this?void 0:this.incomingSession)||void 0===e?void 0:e.remote_identity)||void 0===t?void 0:t.display_name,host:null===(i=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===i?void 0:i.uri.host,incomingNumber:null===(o=null===(n=null==this?void 0:this.incomingSession)||void 0===n?void 0:n.remote_identity)||void 0===o?void 0:o.uri.user,session:null==this?void 0:this.incomingSession}}get requested(){return this._cancelableConnect.requested||this._cancelableCreateUa.requested||this._cancelableCall.requested||this._cancelableAnswer.requested}get isEstablishedSession(){return this.session&&this.session.isEstablished()}get isRegistered(){return!!this.ua&&this.ua.isRegistered()}get isRegisterConfig(){return!!this.ua&&this._isRegisterConfig}get isCallActive(){return!(!this.ua||!this.session)}get isAvailableIncomingCall(){return!!this.incomingSession}_init({sipServerUrl:e,sipWebSocketServerURL:t}){var s;this.getSipServerUrl=(s=e,e=>`sip:${e}@${s}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const s=e.id,i=this._remoteStreams[s]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[s]=i,i}_generateAudioStream(e){const t=e.id,s=this._remoteStreams[t]||new MediaStream;return s.addTrack(e),this._remoteStreams[t]=s,s}_generateStreams(e){const t=[];return e.forEach(((s,i)=>{if("audio"===s.kind)return;const n=s,o=e[i-1];let r;o&&"audio"===o.kind&&(r=o);const a=this._generateStream(n,r);t.push(a)}),[]),t}_generateAudioStreams(e){return e.map((e=>this._generateAudioStream(e)))}_cancelRequests(){this._cancelActionsRequests(),this._cancelCallRequests(),this._cancelConnectRequests()}_cancelConnectRequests(){this._cancelableConnect.cancelRequest()}_cancelCallRequests(){this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest()}_cancelActionsRequests(){this._cancelableAnswer.cancelRequest(),this._cancelableSendDTMF.cancelRequest()}waitChannels(){return this.waitSession("channels")}sendChannels({inputChannels:e,outputChannels:t}){const s=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:s})}}const A=e=>1e6*e,I=A(.06),M=A(4),P=i(),U=e=>{P.add(e),P().catch((e=>{console.debug("videoSendingBalancer: error",e)}))},k=(e,t,s,i)=>{U((()=>h(e,{scaleResolutionDownBy:t,maxBitrate:s},i)))},q=(e,{track:t,resolution:s},i)=>{const n=t.getSettings(),o=n.width,r=n.height,[a,c]=s.split("x"),h=o/+a,d=r/+c,l=Math.max(h,d,1),g=(u=+a)<=64?I:u<=128?A(.12):u<=256?A(.25):u<=384?A(.32):u<=426?A(.38):u<=640?A(.5):u<=848?A(.7):u<=1280?A(1):u<=1920?A(2):M;var u;k(e,l,g,i)},O=({mainCam:e,resolutionMainCam:t,sender:s,track:i},n)=>{switch(e){case R.PAUSE_MAIN_CAM:((e,t)=>{k(e,200,I,t)})(s,n);break;case R.RESUME_MAIN_CAM:((e,t)=>{k(e,1,M,t)})(s,n);break;case R.MAX_MAIN_CAM_RESOLUTION:q(s,{track:i,resolution:t},n)}},D=(e,{autoSubscription:t=!0,ignoreForCodec:s,onSetParameters:i}={})=>{let r,a;const c=t=>o(void 0,void 0,void 0,(function*(){const{connection:i}=e;if(!i||void 0===r||void 0===a)return;const o=(e=>e.find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)})))(i.getSenders());if(o&&o.track){if(s){const e=yield n(o);if(h=s,(c=e)&&h&&c.toLowerCase().includes(h.toLowerCase()))return}var c,h;O({mainCam:r,resolutionMainCam:a,sender:o,track:o.track},t)}})),h=e=>{r=e.mainCam,a=e.resolutionMainCam,c(i)},d=()=>{e.onSession("main-cam-control",h)};return!0===t&&d(),{balance:c,subscribe:d,unsubscribe:()=>{e.offSession("main-cam-control",h)}}};export{v as causes,y as default,S as eventNames,n as getCodecFromSender,N as hasCanceledCallError,D as resolveVideoSendingBalancer};
17
17
  //# sourceMappingURL=index.es5.js.map