sip-connector 6.5.0 → 6.6.1

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.
package/dist/index.es5.js CHANGED
@@ -1,2 +1,2 @@
1
- import{CancelableRequest as e,isCanceledError as t}from"@krivega/cancelable-promise";import i from"events-constructor";import n from"stack-promises";const s=e=>e.getStats().then((e=>{const t=(i="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===i)));var i;return null==t?void 0:t.mimeType}));function r(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}const o=e=>(t,i)=>void 0!==i&&t!==i||void 0===i&&t!==e,a=o(1),c=o(void 0),d=(e,t,i)=>{const n=e.getParameters();n.encodings&&0!==n.encodings.length||(n.encodings=[{}]);const[s]=n.encodings,r=s.scaleResolutionDownBy,o=((e,t)=>{const i=void 0!==e?Math.max(e,1):null;if(null!==i&&a(i,t))return i})(t.scaleResolutionDownBy,r);let d=!1;void 0!==o&&(n.encodings[0].scaleResolutionDownBy=o,d=!0);const h=s.maxBitrate,l=((e,t)=>{if(c(e,t))return e})(t.maxBitrate,h);return void 0!==l&&(n.encodings[0].maxBitrate=l,d=!0),d?(i&&i(n),e.setParameters(n).then((()=>({parameters:n,isChanged:d})))):Promise.resolve({parameters:n,isChanged:d})},h=["incomingCall","declinedIncomingCall","failedIncomingCall","participant:canceling-word-request","participant:move-request-to-stream","participant:move-request-to-conference","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators"],l=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],u=["availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","shareState","enterRoom","peerconnection:confirmed","peerconnection:ontrack","channels","ended:fromserver","main-cam-control","admin-start-main-cam","admin-stop-main-cam","admin-stop-mic","admin-start-mic","admin-force-sync-media-state"],g=["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,...h],_=[...g,...u];var S=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:h,UA_JSSIP_EVENT_NAMES:l,SESSION_SYNTHETICS_EVENT_NAMES:u,SESSION_JSSIP_EVENT_NAMES:g,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 E=e=>e.trim().replace(/ /g,"_"),C=(p=1e5,N=99999999,()=>Math.floor(Math.random()*(N-p))+p);var p,N;const R=(e,{videoMode:t,audioMode:i}={})=>{if(!e||"recvonly"===t&&"recvonly"===i)return;const n=[..."recvonly"===i?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],s=new MediaStream(n);return s.getTracks=()=>[...s.getAudioTracks(),...s.getVideoTracks()],s};var T,M,A;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(T||(T={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(M||(M={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}(A||(A={}));const w=(e=new Error)=>{const{originator:i,cause:n}=e;return!!t(e)||"string"==typeof n&&("Request Timeout"===n||"Rejected"===n||"local"===i&&("Canceled"===n||n===f))},I="SipConnector";class b{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,i)=>{if(!this.isAvailableIncomingCall)return void i(new Error("no incomingSession"));const n=this.incomingSession,s=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger("declinedIncomingCall",s),t(n.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;t.on("failed",(({originator:t})=>{this.removeIncomingSession(),"local"!==t&&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:i,register:n=!1,sipServerUrl:s,sipWebSocketServerURL:o,remoteAddress:a,extraHeaders:c=[],sdpSemantics:d="plan-b",sessionTimers:h=!1,registerExpires:u=300,connectionRecoveryMinInterval:g=2,connectionRecoveryMaxInterval:m=6,userAgent:_})=>r(this,void 0,void 0,(function*(){if(!s)throw new Error("sipServerUrl is required");if(!o)throw new Error("sipWebSocketServerURL is required");if(n&&!t)throw new Error("user is required for authorized connection");if(n&&!i)throw new Error("password is required for authorized connection");let r;this._connectionConfiguration={sipServerUrl:s,displayName:e,register:n,user:t,password:i},this._init({sipServerUrl:s,sipWebSocketServerURL:o}),r=n&&t?t.trim():C();const S={password:i,register:n,display_name:E(e),user_agent:_,sdp_semantics:d,sockets:[this.socket],uri:this.getSipServerUrl(r),session_timers:h,register_expires:u,connection_recovery_min_interval:g,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 i=l.find((e=>e===t));i&&this.ua.on(i,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 i=()=>{s(),e(this.ua)},n=e=>{s(),t(e)},s=()=>{this.off("registered",i),this.off("registrationFailed",n),this.off("connected",i),this.off("disconnected",n)};(()=>{this.isRegisterConfig?(this.on("registered",i),this.on("registrationFailed",n)):this.on("connected",i),this.on("disconnected",n)})(),this.on("newRTCSession",this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((i,n)=>{let s=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(s=this.ua.set("display_name",E(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=s||r;r&&this.isRegisterConfig?this.register().then((()=>i(o))).catch(n):o?i(o):n(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>r(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:i=[],ontrack:n,iceServers:s,videoMode:r,audioMode:o,degradationPreference:a})=>new Promise(((c,d)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:n}).then(c).catch(d),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:i,mediaStream:R(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:s},rtcOfferConstraints:{offerToReceiveAudio:!0,offerToReceiveVideo:!0}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:i=[],iceServers:n,videoMode:s,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const i=g.find((e=>e===t));i&&d.on(i,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const h=R(e,{videoMode:s,audioMode:r});d.answer({extraHeaders:i,videoMode:s,audioMode:r,degradationPreference:o,mediaStream:h,pcConfig:{iceServers:n}})})),this._handleCall=({ontrack:e})=>new Promise(((t,i)=>{const n=()=>{this.offSession("peerconnection",a),this.offSession("confirmed",c)},s=()=>{this.offSession("failed",r),this.offSession("ended",r)},r=e=>{n(),s(),i(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger("peerconnection:ontrack",o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger("peerconnection:confirmed",o),n(),s(),t(o)};(()=>{this.onSession("peerconnection",a),this.onSession("confirmed",c)})(),(()=>{this.onSession("failed",r),this.onSession("ended",r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,i)=>{const n=this.session;n?(this.onceSession("newDTMF",(({originator:e})=>{"local"===e&&t()})),n.sendDTMF(e,{duration:120,interToneGap:600})):i(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>r(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"),i=e.getHeader("X-WEBRTC-OUTPUT-CHANNELS");if(t&&i){const e={inputChannels:t,outputChannels:i};this._sessionEvents.trigger("channels",e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger("participant:removed-from-list-moderators",t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger("participant:added-to-list-moderators",t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const i={conference:e,type:t};this._uaEvents.trigger("webcast:started",i)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const i={conference:e,type:t};this._uaEvents.trigger("webcast:stopped",i)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger("account:changed",void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger("account:deleted",void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:i}})=>{const n={conference:e,participant:t,jwt:i};this._uaEvents.trigger("conference:participant-token-issued",n)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger("channels:notify",t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger("participant:move-request-to-conference",t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger("participant:canceling-word-request",t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.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");if(t===T.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger("admin-start-main-cam",void 0);else if(t===T.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger("admin-stop-main-cam",void 0);else{const i=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger("main-cam-control",{mainCam:t,resolutionMainCam:i})}},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC");t===M.ADMIN_START_MIC?this._sessionEvents.trigger("admin-start-mic",void 0):t===M.ADMIN_STOP_MIC&&this._sessionEvents.trigger("admin-stop-mic",void 0)},this._triggerSyncMediaState=e=>{const t=e.getHeader("X-Vinteo-Sync-Media-State")===A.ADMIN_SYNC_FORCED;this._sessionEvents.trigger("admin-force-sync-media-state",{isSyncForced:t})},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const i=e.request,n=i.getHeader("content-type");if(n)switch(n){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(i),this._maybeTriggerChannels(i);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(i);break;case"application/vinteo.webrtc.sharedesktop":this._triggerShareState(i);break;case"application/vinteo.webrtc.maincam":this._triggerMainCamControl(i);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(i);break;case"application/vinteo.webrtc.syncmediastate":this._triggerSyncMediaState(i)}},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 i(_),this._uaEvents=new i(m),this._cancelableConnect=new e(this._connect,{moduleName:I,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new e(this._createUa,{moduleName:I}),this._cancelableDisconnect=new e(this._disconnect,{moduleName:I}),this._cancelableSet=new e(this._set,{moduleName:I}),this._cancelableCall=new e(this._call,{moduleName:I}),this._cancelableAnswer=new e(this._answer,{moduleName:I}),this._cancelableSendDTMF=new e(this._sendDTMF,{moduleName:I}),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){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo("application/vinteo.webrtc.maincam",void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}startPresentation(e,{isNeedReinvite:t=!0,isP2P:i=!1,maxBitrate:n,degradationPreference:s}={}){const r=this.establishedSession;if(!r)return Promise.reject(new Error("No session established"));this.isPendingPresentation=!0;const o=R(e);this._streamPresentationCurrent=o;let a=Promise.resolve();const c=i?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"];return a=r.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:c}).then((()=>r.startPresentation(o,t,s))).then((()=>{const{connection:t}=this;if(!t||void 0===n)return;return((e,t,i)=>{const n=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return n?d(n,{maxBitrate:i}):Promise.resolve()})(t.getSenders(),e,n)})).then((()=>e)).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e})),a.finally((()=>{this.isPendingPresentation=!1}))}stopPresentation({isP2P:e=!1}={}){this.isPendingPresentation=!0;const t=this._streamPresentationCurrent;let i=Promise.resolve();const n=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],s=this.establishedSession;return s&&t&&(i=s.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:n}).then((()=>s.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e}))),!s&&t&&this._sessionEvents.trigger("presentation:ended",t),i.finally((()=>{this._resetPresentation()}))}_resetPresentation(){delete this._streamPresentationCurrent,this.isPendingPresentation=!1}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}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,i,n,s,r;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===(n=null===(i=null==this?void 0:this.incomingSession)||void 0===i?void 0:i.remote_identity)||void 0===n?void 0:n.uri.host,incomingNumber:null===(r=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===r?void 0:r.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 establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}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 i;this.getSipServerUrl=(i=e,e=>`sip:${e}@${i}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const i=e.id,n=this._remoteStreams[i]||new MediaStream;return t&&n.addTrack(t),n.addTrack(e),this._remoteStreams[i]=n,n}_generateAudioStream(e){const t=e.id,i=this._remoteStreams[t]||new MediaStream;return i.addTrack(e),this._remoteStreams[t]=i,i}_generateStreams(e){const t=[];return e.forEach(((i,n)=>{if("audio"===i.kind)return;const s=i,r=e[n-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(s,o);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")}waitSyncMediaState(){return this.waitSession("admin-force-sync-media-state")}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const i=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:i})}sendMediaState({cam:e,mic:t},i={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const n=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},i),{extraHeaders:n}))}}const P=e=>1e6*e,y=P(.06),D=P(4),O=n(),U=e=>(O.add(e),O().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),k=({sender:e,scaleResolutionDownBy:t,maxBitrate:i,onSetParameters:n})=>U((()=>d(e,{scaleResolutionDownBy:t,maxBitrate:i},n))),q=(e,{track:t,resolution:i},n)=>{const s=t.getSettings(),r=s.width,o=s.height,[a,c]=i.split("x"),d=r/+a,h=o/+c,l=Math.max(d,h,1),u=(g=+a)<=64?y:g<=128?P(.12):g<=256?P(.25):g<=384?P(.32):g<=426?P(.38):g<=640?P(.5):g<=848?P(.7):g<=1280?P(1):g<=1920?P(2):D;var g;return k({sender:e,maxBitrate:u,onSetParameters:n,scaleResolutionDownBy:l})},x=({mainCam:e,resolutionMainCam:t,sender:i,track:n},s)=>{switch(e){case T.PAUSE_MAIN_CAM:return((e,t)=>k({sender:e,maxBitrate:y,onSetParameters:t,scaleResolutionDownBy:200}))(i,s);case T.RESUME_MAIN_CAM:return((e,t)=>k({sender:e,maxBitrate:D,onSetParameters:t,scaleResolutionDownBy:1}))(i,s);case T.MAX_MAIN_CAM_RESOLUTION:if(t)return q(i,{track:n,resolution:t},s)}return Promise.resolve({isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}})},B=(e,{ignoreForCodec:t,onSetParameters:i}={})=>{let n=()=>{};const o=o=>{n=()=>{const{mainCam:n,resolutionMainCam:a}=o,{connection:c}=e;c&&void 0!==n&&(({mainCam:e,resolutionMainCam:t,connection:i,onSetParameters:n,ignoreForCodec:o})=>{r(void 0,void 0,void 0,(function*(){const r=i.getSenders().find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)}));if(r&&r.track){if(o){const e=yield s(r);if(c=o,(a=e)&&c&&a.toLowerCase().includes(c.toLowerCase()))return}var a,c;x({mainCam:e,resolutionMainCam:t,sender:r,track:r.track},n)}}))})({mainCam:n,resolutionMainCam:a,connection:c,onSetParameters:i,ignoreForCodec:t})},n()};return{subscribe:()=>{e.onSession("main-cam-control",o)},unsubscribe:()=>{e.offSession("main-cam-control",o)},reBalance:n}};export{v as causes,b as default,S as eventNames,s as getCodecFromSender,w as hasCanceledCallError,B as resolveVideoSendingBalancer};
1
+ import{CancelableRequest as e,isCanceledError as t}from"@krivega/cancelable-promise";import n from"events-constructor";import i from"stack-promises";const s=e=>e.getStats().then((e=>{const t=(n="codec",(e=>[...e.keys()].map((t=>e.get(t))))(e).find((e=>e.type===n)));var n;return null==t?void 0:t.mimeType}));function r(e,t,n,i){return new(n||(n=Promise))((function(s,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}const o=e=>(t,n)=>void 0!==n&&t!==n||void 0===n&&t!==e,a=o(1),c=o(void 0),d=(e,t,n)=>{const i=e.getParameters();i.encodings&&0!==i.encodings.length||(i.encodings=[{}]);const[s]=i.encodings,r=s.scaleResolutionDownBy,o=((e,t)=>{const n=void 0!==e?Math.max(e,1):null;if(null!==n&&a(n,t))return n})(t.scaleResolutionDownBy,r);let d=!1;void 0!==o&&(i.encodings[0].scaleResolutionDownBy=o,d=!0);const h=s.maxBitrate,l=((e,t)=>{if(c(e,t))return e})(t.maxBitrate,h);return void 0!==l&&(i.encodings[0].maxBitrate=l,d=!0),d?(n&&n(i),e.setParameters(i).then((()=>({parameters:i,isChanged:d})))):Promise.resolve({parameters:i,isChanged:d})},h=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall","participant:canceling-word-request","participant:move-request-to-stream","participant:move-request-to-conference","channels:notify","conference:participant-token-issued","account:changed","account:deleted","webcast:started","webcast:stopped","participant:added-to-list-moderators","participant:removed-from-list-moderators"],l=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],u=["availableSecondRemoteStream","notAvailableSecondRemoteStream","mustStopPresentation","shareState","enterRoom","peerconnection:confirmed","peerconnection:ontrack","channels","ended:fromserver","main-cam-control","admin-start-main-cam","admin-stop-main-cam","admin-stop-mic","admin-start-mic","admin-force-sync-media-state"],g=["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,...h],_=[...g,...u];var S=Object.freeze({__proto__:null,UA_SYNTHETICS_EVENT_NAMES:h,UA_JSSIP_EVENT_NAMES:l,SESSION_SYNTHETICS_EVENT_NAMES:u,SESSION_JSSIP_EVENT_NAMES:g,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 E=e=>e.trim().replace(/ /g,"_"),C=(p=1e5,N=99999999,()=>Math.floor(Math.random()*(N-p))+p);var p,N;const R=(e,{videoMode:t,audioMode:n}={})=>{if(!e||"recvonly"===t&&"recvonly"===n)return;const i=[..."recvonly"===n?[]:e.getAudioTracks(),..."recvonly"===t?[]:e.getVideoTracks()],s=new MediaStream(i);return s.getTracks=()=>[...s.getAudioTracks(),...s.getVideoTracks()],s};var T,M,w;!function(e){e.PAUSE_MAIN_CAM="PAUSEMAINCAM",e.RESUME_MAIN_CAM="RESUMEMAINCAM",e.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",e.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",e.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM"}(T||(T={})),function(e){e.ADMIN_STOP_MIC="ADMINSTOPMIC",e.ADMIN_START_MIC="ADMINSTARTMIC"}(M||(M={})),function(e){e.ADMIN_SYNC_FORCED="1",e.ADMIN_SYNC_NOT_FORCED="0"}(w||(w={}));const A=(e=new Error)=>{const{originator:n,cause:i}=e;return!!t(e)||"string"==typeof i&&("Request Timeout"===i||"Rejected"===i||"local"===n&&("Canceled"===i||i===f))},I="SipConnector";class b{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,n)=>{if(!this.isAvailableIncomingCall)return void n(new Error("no incomingSession"));const i=this.incomingSession,s=this.remoteCallerData;this._cancelableCall.cancelRequest(),this._cancelableAnswer.cancelRequest(),this.removeIncomingSession(),this._uaEvents.trigger("declinedIncomingCall",s),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;t.on("failed",(({originator:t})=>{this.removeIncomingSession(),"local"!==t?this._uaEvents.trigger("failedIncomingCall",e):this._uaEvents.trigger("terminatedIncomingCall",e)})),this._uaEvents.trigger("incomingCall",e)}},this._connect=e=>this.createUa(e).then((()=>this._start())),this._createUa=({displayName:e="",user:t,password:n,register:i=!1,sipServerUrl:s,sipWebSocketServerURL:o,remoteAddress:a,extraHeaders:c=[],sdpSemantics:d="plan-b",sessionTimers:h=!1,registerExpires:u=300,connectionRecoveryMinInterval:g=2,connectionRecoveryMaxInterval:m=6,userAgent:_})=>r(this,void 0,void 0,(function*(){if(!s)throw new Error("sipServerUrl is required");if(!o)throw new Error("sipWebSocketServerURL is required");if(i&&!t)throw new Error("user is required for authorized connection");if(i&&!n)throw new Error("password is required for authorized connection");let r;this._connectionConfiguration={sipServerUrl:s,displayName:e,register:i,user:t,password:n},this._init({sipServerUrl:s,sipWebSocketServerURL:o}),r=i&&t?t.trim():C();const S={password:n,register:i,display_name:E(e),user_agent:_,sdp_semantics:d,sockets:[this.socket],uri:this.getSipServerUrl(r),session_timers:h,register_expires:u,connection_recovery_min_interval:g,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 n=l.find((e=>e===t));n&&this.ua.on(n,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 n=()=>{s(),e(this.ua)},i=e=>{s(),t(e)},s=()=>{this.off("registered",n),this.off("registrationFailed",i),this.off("connected",n),this.off("disconnected",i)};(()=>{this.isRegisterConfig?(this.on("registered",n),this.on("registrationFailed",i)):this.on("connected",n),this.on("disconnected",i)})(),this.on("newRTCSession",this.handleNewRTCSession),this.ua.start()})),this._set=({displayName:e,password:t})=>new Promise(((n,i)=>{let s=!1,r=!1;void 0!==e&&e!==this._connectionConfiguration.displayName&&(s=this.ua.set("display_name",E(e)),this._connectionConfiguration.displayName=e),void 0!==t&&t!==this._connectionConfiguration.password&&(r=this.ua.set("password",t),this._connectionConfiguration.password=t);const o=s||r;r&&this.isRegisterConfig?this.register().then((()=>n(o))).catch(i):o?n(o):i(o)})),this._disconnectWithoutCancelRequests=()=>this._cancelableDisconnect.request(),this._disconnect=()=>r(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:n=[],ontrack:i,iceServers:s,videoMode:r,audioMode:o,degradationPreference:a})=>new Promise(((c,d)=>{this._connectionConfiguration.number=e,this._connectionConfiguration.answer=!1,this._handleCall({ontrack:i}).then(c).catch(d),this.session=this.ua.call(this.getSipServerUrl(e),{extraHeaders:n,mediaStream:R(t,{videoMode:r,audioMode:o}),eventHandlers:this._sessionEvents.triggers,videoMode:r,audioMode:o,degradationPreference:a,pcConfig:{iceServers:s},rtcOfferConstraints:{offerToReceiveAudio:!0,offerToReceiveVideo:!0}})})),this._answer=({mediaStream:e,ontrack:t,extraHeaders:n=[],iceServers:i,videoMode:s,audioMode:r,degradationPreference:o})=>new Promise(((a,c)=>{if(!this.isAvailableIncomingCall)return void c(new Error("no incomingSession"));this.session=this.incomingSession,this.removeIncomingSession();const d=this.session;if(!d)return void c(new Error("No session established"));this._sessionEvents.eachTriggers(((e,t)=>{const n=g.find((e=>e===t));n&&d.on(n,e)})),this._connectionConfiguration.answer=!0,this._connectionConfiguration.number=d.remote_identity.uri.user,this._handleCall({ontrack:t}).then(a).catch(c);const h=R(e,{videoMode:s,audioMode:r});d.answer({extraHeaders:n,videoMode:s,audioMode:r,degradationPreference:o,mediaStream:h,pcConfig:{iceServers:i}})})),this._handleCall=({ontrack:e})=>new Promise(((t,n)=>{const i=()=>{this.offSession("peerconnection",a),this.offSession("confirmed",c)},s=()=>{this.offSession("failed",r),this.offSession("ended",r)},r=e=>{i(),s(),n(e)};let o;const a=({peerconnection:t})=>{o=t,o.ontrack=t=>{this._sessionEvents.trigger("peerconnection:ontrack",o),e&&e(t)}},c=()=>{o&&this._sessionEvents.trigger("peerconnection:confirmed",o),i(),s(),t(o)};(()=>{this.onSession("peerconnection",a),this.onSession("confirmed",c)})(),(()=>{this.onSession("failed",r),this.onSession("ended",r)})()})),this._restoreSession=()=>{this._resetPresentation(),delete this._connectionConfiguration.number,delete this.session,this._remoteStreams={}},this._sendDTMF=e=>new Promise(((t,n)=>{const i=this.session;i?(this.onceSession("newDTMF",(({originator:e})=>{"local"===e&&t()})),i.sendDTMF(e,{duration:120,interToneGap:600})):n(new Error("No session established"))})),this._hangUpWithoutCancelRequests=()=>r(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"),n=e.getHeader("X-WEBRTC-OUTPUT-CHANNELS");if(t&&n){const e={inputChannels:t,outputChannels:n};this._sessionEvents.trigger("channels",e)}},this._handleNotify=e=>{if("channels"===e.cmd){const t=e;this._triggerChannelsNotify(t)}else if("WebcastStarted"===e.cmd){const t=e;this._triggerWebcastStartedNotify(t)}else if("WebcastStopped"===e.cmd){const t=e;this._triggerWebcastStoppedNotify(t)}else if("addedToListModerators"===e.cmd){const t=e;this._triggerAddedToListModeratorsNotify(t)}else if("removedFromListModerators"===e.cmd){const t=e;this._triggerRemovedFromListModeratorsNotify(t)}else if("WebcastParticipationAccepted"===e.cmd){const t=e;this._triggerParticipantMoveRequestToConference(t)}else if("WebcastParticipationRejected"===e.cmd){const t=e;this._triggerParticipantCancelingWordRequest(t)}else if("ParticipantMovedToWebcast"===e.cmd){const t=e;this._triggerParticipantMoveRequestToStream(t)}else if("accountChanged"===e.cmd)this._triggerAccountChangedNotify();else if("accountDeleted"===e.cmd)this._triggerAccountDeletedNotify();else if("ConferenceParticipantTokenIssued"===e.cmd){const t=e;this._triggerConferenceParticipantTokenIssued(t)}},this._triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger("participant:removed-from-list-moderators",t)},this._triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this._uaEvents.trigger("participant:added-to-list-moderators",t)},this._triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger("webcast:started",n)},this._triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const n={conference:e,type:t};this._uaEvents.trigger("webcast:stopped",n)},this._triggerAccountChangedNotify=()=>{this._uaEvents.trigger("account:changed",void 0)},this._triggerAccountDeletedNotify=()=>{this._uaEvents.trigger("account:deleted",void 0)},this._triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:n}})=>{const i={conference:e,participant:t,jwt:n};this._uaEvents.trigger("conference:participant-token-issued",i)},this._triggerChannelsNotify=e=>{const t={inputChannels:e.input,outputChannels:e.output};this._uaEvents.trigger("channels:notify",t)},this._triggerParticipantMoveRequestToConference=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger("participant:move-request-to-conference",t)},this._triggerParticipantCancelingWordRequest=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.trigger("participant:canceling-word-request",t)},this._triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this._uaEvents.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");if(t===T.ADMIN_START_MAIN_CAM)this._sessionEvents.trigger("admin-start-main-cam",void 0);else if(t===T.ADMIN_STOP_MAIN_CAM)this._sessionEvents.trigger("admin-stop-main-cam",void 0);else{const n=e.getHeader("X-WEBRTC-MAINCAM-RESOLUTION");this._sessionEvents.trigger("main-cam-control",{mainCam:t,resolutionMainCam:n})}},this._triggerMicControl=e=>{const t=e.getHeader("X-WEBRTC-MIC");t===M.ADMIN_START_MIC?this._sessionEvents.trigger("admin-start-mic",void 0):t===M.ADMIN_STOP_MIC&&this._sessionEvents.trigger("admin-stop-mic",void 0)},this._triggerSyncMediaState=e=>{const t=e.getHeader("X-Vinteo-Sync-Media-State")===w.ADMIN_SYNC_FORCED;this._sessionEvents.trigger("admin-force-sync-media-state",{isSyncForced:t})},this._handleNewInfo=e=>{const{originator:t}=e;if("remote"!==t)return;const n=e.request,i=n.getHeader("content-type");if(i)switch(i){case"application/vinteo.webrtc.roomname":this._triggerEnterRoom(n),this._maybeTriggerChannels(n);break;case"application/vinteo.webrtc.notify":this._maybeHandleNotify(n);break;case"application/vinteo.webrtc.sharedesktop":this._triggerShareState(n);break;case"application/vinteo.webrtc.maincam":this._triggerMainCamControl(n);break;case"application/vinteo.webrtc.mic":this._triggerMicControl(n);break;case"application/vinteo.webrtc.syncmediastate":this._triggerSyncMediaState(n)}},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 n(_),this._uaEvents=new n(m),this._cancelableConnect=new e(this._connect,{moduleName:I,afterCancelRequest:()=>{this._cancelableCreateUa.cancelRequest(),this._cancelableDisconnect.cancelRequest()}}),this._cancelableCreateUa=new e(this._createUa,{moduleName:I}),this._cancelableDisconnect=new e(this._disconnect,{moduleName:I}),this._cancelableSet=new e(this._set,{moduleName:I}),this._cancelableCall=new e(this._call,{moduleName:I}),this._cancelableAnswer=new e(this._answer,{moduleName:I}),this._cancelableSendDTMF=new e(this._sendDTMF,{moduleName:I}),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"))}))}sendOptions(e,t,n){return this.ua?new Promise(((i,s)=>{try{this.ua.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{i()},failed:e=>{s(e)}}})}catch(e){s(e)}})):Promise.reject(new Error("is not connected"))}ping(e,t){if(!this.ua||!this.ua.configuration||!this.ua.configuration.uri)return Promise.reject(new Error("is not connected"));const n=this.ua.configuration.uri;return this.sendOptions(n,e,t)}replaceMediaStream(e,t){if(!this.session)throw new Error("No session established");return this.session.replaceMediaStream(e,t)}askPermissionToEnableCam(e={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const t=["X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM"];return this.session.sendInfo("application/vinteo.webrtc.maincam",void 0,Object.assign(Object.assign({},e),{extraHeaders:t})).catch((e=>{if((e=>"Error decline with 603"===e.message)(e))throw e}))}startPresentation(e,{isNeedReinvite:t=!0,isP2P:n=!1,maxBitrate:i,degradationPreference:s}={}){const r=this.establishedSession;if(!r)return Promise.reject(new Error("No session established"));this.isPendingPresentation=!0;const o=R(e);this._streamPresentationCurrent=o;let a=Promise.resolve();const c=n?["x-webrtc-share-state: YOUCANRECEIVECONTENT"]:["x-webrtc-share-state: LETMESTARTPRESENTATION"];return a=r.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:c}).then((()=>r.startPresentation(o,t,s))).then((()=>{const{connection:t}=this;if(!t||void 0===i)return;return((e,t,n)=>{const i=((e,t)=>e.find((e=>e.track&&t.getTracks().includes(e.track))))(e,t);return i?d(i,{maxBitrate:n}):Promise.resolve()})(t.getSenders(),e,i)})).then((()=>e)).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e})),a.finally((()=>{this.isPendingPresentation=!1}))}stopPresentation({isP2P:e=!1}={}){this.isPendingPresentation=!0;const t=this._streamPresentationCurrent;let n=Promise.resolve();const i=e?["x-webrtc-share-state: CONTENTEND"]:["x-webrtc-share-state: STOPPRESENTATION"],s=this.establishedSession;return s&&t&&(n=s.sendInfo("application/vinteo.webrtc.sharedesktop",void 0,{extraHeaders:i}).then((()=>s.stopPresentation(t))).catch((e=>{throw this._sessionEvents.trigger("presentation:failed",e),e}))),!s&&t&&this._sessionEvents.trigger("presentation:ended",t),n.finally((()=>{this._resetPresentation()}))}_resetPresentation(){delete this._streamPresentationCurrent,this.isPendingPresentation=!1}on(e,t){return this._uaEvents.on(e,t)}once(e,t){return this._uaEvents.once(e,t)}onceRace(e,t){return this._uaEvents.onceRace(e,t)}wait(e){return this._uaEvents.wait(e)}off(e,t){this._uaEvents.off(e,t)}onSession(e,t){return this._sessionEvents.on(e,t)}onceSession(e,t){return this._sessionEvents.once(e,t)}onceRaceSession(e,t){return this._sessionEvents.onceRace(e,t)}waitSession(e){return this._sessionEvents.wait(e)}offSession(e,t){this._sessionEvents.off(e,t)}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,n,i,s,r;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===(n=null==this?void 0:this.incomingSession)||void 0===n?void 0:n.remote_identity)||void 0===i?void 0:i.uri.host,incomingNumber:null===(r=null===(s=null==this?void 0:this.incomingSession)||void 0===s?void 0:s.remote_identity)||void 0===r?void 0:r.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 establishedSession(){return this.session&&this.session.isEstablished()?this.session:void 0}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 n;this.getSipServerUrl=(n=e,e=>`sip:${e}@${n}`),this.socket=new this.JsSIP.WebSocketInterface(t)}_generateStream(e,t){const n=e.id,i=this._remoteStreams[n]||new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this._remoteStreams[n]=i,i}_generateAudioStream(e){const t=e.id,n=this._remoteStreams[t]||new MediaStream;return n.addTrack(e),this._remoteStreams[t]=n,n}_generateStreams(e){const t=[];return e.forEach(((n,i)=>{if("audio"===n.kind)return;const s=n,r=e[i-1];let o;r&&"audio"===r.kind&&(o=r);const a=this._generateStream(s,o);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")}waitSyncMediaState(){return this.waitSession("admin-force-sync-media-state")}sendChannels({inputChannels:e,outputChannels:t}){if(!this.session)throw new Error("No session established");const n=[`X-WEBRTC-INPUT-CHANNELS: ${e}`,`X-WEBRTC-OUTPUT-CHANNELS: ${t}`];return this.session.sendInfo("application/vinteo.webrtc.channels",void 0,{extraHeaders:n})}sendMediaState({cam:e,mic:t},n={noTerminateWhenError:!0}){if(!this.session)throw new Error("No session established");const i=["X-WEBRTC-MEDIA-STATE: currentstate","X-Vinteo-MainCam-State: "+ +e,"X-Vinteo-Mic-State: "+ +t];return this.session.sendInfo("application/vinteo.webrtc.mediastate",void 0,Object.assign(Object.assign({},n),{extraHeaders:i}))}}const P=e=>1e6*e,y=P(.06),D=P(4),O=i(),U=e=>(O.add(e),O().catch((e=>{console.debug("videoSendingBalancer: error",e)}))),k=({sender:e,scaleResolutionDownBy:t,maxBitrate:n,onSetParameters:i})=>U((()=>d(e,{scaleResolutionDownBy:t,maxBitrate:n},i))),q=(e,{track:t,resolution:n},i)=>{const s=t.getSettings(),r=s.width,o=s.height,[a,c]=n.split("x"),d=r/+a,h=o/+c,l=Math.max(d,h,1),u=(g=+a)<=64?y:g<=128?P(.12):g<=256?P(.25):g<=384?P(.32):g<=426?P(.38):g<=640?P(.5):g<=848?P(.7):g<=1280?P(1):g<=1920?P(2):D;var g;return k({sender:e,maxBitrate:u,onSetParameters:i,scaleResolutionDownBy:l})},x=({mainCam:e,resolutionMainCam:t,sender:n,track:i},s)=>{switch(e){case T.PAUSE_MAIN_CAM:return((e,t)=>k({sender:e,maxBitrate:y,onSetParameters:t,scaleResolutionDownBy:200}))(n,s);case T.RESUME_MAIN_CAM:return((e,t)=>k({sender:e,maxBitrate:D,onSetParameters:t,scaleResolutionDownBy:1}))(n,s);case T.MAX_MAIN_CAM_RESOLUTION:if(t)return q(n,{track:i,resolution:t},s)}return Promise.resolve({isChanged:!1,parameters:{encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}}})},B=(e,{ignoreForCodec:t,onSetParameters:n}={})=>{let i=()=>{};const o=o=>{i=()=>{const{mainCam:i,resolutionMainCam:a}=o,{connection:c}=e;c&&void 0!==i&&(({mainCam:e,resolutionMainCam:t,connection:n,onSetParameters:i,ignoreForCodec:o})=>{r(void 0,void 0,void 0,(function*(){const r=n.getSenders().find((e=>{var t;return"video"===(null===(t=null==e?void 0:e.track)||void 0===t?void 0:t.kind)}));if(r&&r.track){if(o){const e=yield s(r);if(c=o,(a=e)&&c&&a.toLowerCase().includes(c.toLowerCase()))return}var a,c;x({mainCam:e,resolutionMainCam:t,sender:r,track:r.track},i)}}))})({mainCam:i,resolutionMainCam:a,connection:c,onSetParameters:n,ignoreForCodec:t})},i()};return{subscribe:()=>{e.onSession("main-cam-control",o)},unsubscribe:()=>{e.offSession("main-cam-control",o)},reBalance:i}};export{v as causes,b as default,S as eventNames,s as getCodecFromSender,A as hasCanceledCallError,B as resolveVideoSendingBalancer};
2
2
  //# sourceMappingURL=index.es5.js.map