@jellyfish-dev/membrane-webrtc-js
Version:
JS/TS client library for Membrane RTC Engine.
2 lines (1 loc) • 22.3 kB
JavaScript
(function(h,l){typeof exports=="object"&&typeof module!="undefined"?l(exports,require("uuid"),require("events")):typeof define=="function"&&define.amd?define(["exports","uuid","events"],l):(h=typeof globalThis!="undefined"?globalThis:h||self,l(h["membrane-webrtc-js"]={},h.uuid,h.EventEmitter))})(this,function(h,l,g){"use strict";var x=Object.defineProperty;var A=(h,l,g)=>l in h?x(h,l,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[l]=g;var o=(h,l,g)=>(A(h,typeof l!="symbol"?l+"":l,g),g);function y(m){return JSON.stringify(m)}function b(m){return JSON.parse(m)}function f(m,T){let t={type:m};return T&&(t={...t,data:T}),t}function u(m){return f("custom",m)}const M={direction:"sendonly",sendEncodings:[{rid:"l",active:!1,scaleResolutionDownBy:4},{rid:"m",active:!1,scaleResolutionDownBy:2},{rid:"h",active:!1}]},P={audio:5e4,video:25e5},R={h:25e5,m:5e5,l:15e4};class v{constructor(){o(this,"promise");o(this,"resolveFn",()=>null);o(this,"rejectFn",()=>null);this.promise=new Promise((T,t)=>{this.resolveFn=T,this.rejectFn=t})}resolve(T){this.resolveFn(T)}reject(T){this.rejectFn(T)}}const S=["speech","silence"];class I extends g{constructor(t,a,e,r,n){super();o(this,"endpoint");o(this,"trackId");o(this,"track",null);o(this,"stream",null);o(this,"metadata");o(this,"rawMetadata");o(this,"metadataParsingError");o(this,"simulcastConfig");o(this,"maxBandwidth",0);o(this,"encoding");o(this,"encodingReason");o(this,"vadStatus","silence");o(this,"negotiationStatus","awaiting");o(this,"pendingMetadataUpdate",!1);this.endpoint=t,this.trackId=a;try{this.metadata=n(e)}catch(i){this.metadataParsingError=i}this.rawMetadata=e,this.simulcastConfig=r}}class B extends g{constructor(t){var a,e;super();o(this,"trackIdToTrack",new Map);o(this,"connection");o(this,"idToEndpoint",new Map);o(this,"localEndpoint",{id:"",type:"webrtc",metadata:void 0,rawMetadata:void 0,tracks:new Map});o(this,"localTrackIdToTrack",new Map);o(this,"midToTrackId",new Map);o(this,"disabledTrackEncodings",new Map);o(this,"rtcConfig",{bundlePolicy:"max-bundle",iceServers:[],iceTransportPolicy:"relay"});o(this,"ongoingRenegotiation",!1);o(this,"ongoingTrackReplacement",!1);o(this,"commandsQueue",[]);o(this,"commandResolutionNotifier",null);o(this,"endpointMetadataParser");o(this,"trackMetadataParser");o(this,"connect",t=>{try{this.localEndpoint.metadata=this.endpointMetadataParser(t),this.localEndpoint.metadataParsingError=void 0}catch(e){throw this.localEndpoint.metadata=void 0,this.localEndpoint.metadataParsingError=e,e}this.localEndpoint.rawMetadata=t;const a=f("connect",{metadata:this.localEndpoint.metadata});this.sendMediaEvent(a)});o(this,"receiveMediaEvent",t=>{const a=b(t);switch(a.type){case"connected":{this.localEndpoint.id=a.data.id;const r=a.data.otherEndpoints.map(n=>{const i=this.mapMediaEventTracksToTrackContextImpl(new Map(Object.entries(n.tracks)),n);try{return{id:n.id,type:n.type,metadata:this.endpointMetadataParser(n.metadata),rawMetadata:n.metadata,metadataParsingError:void 0,tracks:i}}catch(s){return{id:n.id,type:n.type,metadata:void 0,rawMetadata:n.metadata,metadataParsingError:s,tracks:i}}});this.emit("connected",a.data.id,r),r.forEach(n=>this.idToEndpoint.set(n.id,n)),r.forEach(n=>{n.tracks.forEach((i,s)=>{this.trackIdToTrack.set(s,i),this.emit("trackAdded",i)})});break}default:this.localEndpoint.id!=null&&this.handleMediaEvent(a)}});o(this,"handleMediaEvent",t=>{let a,e;switch(t.type){case"offerData":{const r=t.data.integratedTurnServers;this.setTurns(r);const n=new Map(Object.entries(t.data.tracksTypes));this.onOfferData(n);break}case"tracksAdded":{if(this.ongoingRenegotiation=!0,e=t.data,this.getEndpointId()===e.endpointId)return;e.tracks=new Map(Object.entries(e.tracks)),a=this.idToEndpoint.get(e.endpointId);const r=a.tracks;e.tracks=this.mapMediaEventTracksToTrackContextImpl(e.tracks,a),a.tracks=new Map([...a.tracks,...e.tracks]),this.idToEndpoint.set(a.id,a),Array.from(a.tracks.entries()).forEach(([n,i])=>{r.has(n)||(this.trackIdToTrack.set(n,i),this.emit("trackAdded",i))});break}case"tracksRemoved":{this.ongoingRenegotiation=!0,e=t.data;const r=e.endpointId;if(this.getEndpointId()===r)return;e.trackIds.forEach(i=>{const s=this.trackIdToTrack.get(i);this.eraseTrack(i,r),this.emit("trackRemoved",s)});break}case"sdpAnswer":this.midToTrackId=new Map(Object.entries(t.data.midToTrackId));for(const r of Object.values(t.data.midToTrackId)){const n=this.localTrackIdToTrack.get(r);if(n){if(n.negotiationStatus="done",n.pendingMetadataUpdate){const i=f("updateTrackMetadata",{trackId:r,trackMetadata:n.metadata});this.sendMediaEvent(i)}n.pendingMetadataUpdate=!1}}this.onAnswer(t.data),this.ongoingRenegotiation=!1,this.processNextCommand();break;case"candidate":this.onRemoteCandidate(t.data);break;case"endpointAdded":if(a=t.data,a.id===this.getEndpointId())return;a.rawMetadata=a.metadata;try{a.metadataParsingError=void 0,a.metadata=this.endpointMetadataParser(a.rawMetadata)}catch(r){a.metadataParsingError=r,a.metadata=void 0}this.addEndpoint(a),this.emit("endpointAdded",a);break;case"endpointRemoved":if(t.data.id===this.localEndpoint.id){this.cleanUp(),this.emit("disconnected");return}if(a=this.idToEndpoint.get(t.data.id),a===void 0)return;Array.from(a.tracks.keys()).forEach(r=>{this.emit("trackRemoved",this.trackIdToTrack.get(r))}),this.eraseEndpoint(a),this.emit("endpointRemoved",a);break;case"endpointUpdated":if(this.getEndpointId()===t.data.id)return;a=this.idToEndpoint.get(t.data.id);try{a.metadata=this.endpointMetadataParser(t.data.metadata),a.metadataParsingError=void 0}catch(r){a.metadata=void 0,a.metadataParsingError=r}a.rawMetadata=t.data.metadata,this.addEndpoint(a),this.emit("endpointUpdated",a);break;case"trackUpdated":{if(this.getEndpointId()===t.data.endpointId)return;if(a=this.idToEndpoint.get(t.data.endpointId),a==null)throw`Endpoint with id: ${t.data.endpointId} doesn't exist`;const r=t.data.trackId,n=t.data.metadata;let i=a.tracks.get(r);const s=this.trackIdToTrack.get(r);try{const c=this.trackMetadataParser(n);i={...i,metadata:c,metadataParsingError:void 0},s.metadata=c,s.metadataParsingError=void 0}catch(c){i={...i,metadata:void 0,metadataParsingError:c},s.metadataParsingError=c,s.metadata=void 0}i={...i,rawMetadata:n},s.rawMetadata=n,a.tracks.set(r,i),this.emit("trackUpdated",s);break}case"trackEncodingDisabled":{if(this.getEndpointId()===t.data.endpointId)return;if(a=this.idToEndpoint.get(t.data.endpointId),a==null)throw`Endpoint with id: ${t.data.endpointId} doesn't exist`;const r=t.data.trackId,n=t.data.encoding,i=a.tracks.get(r);this.emit("trackEncodingDisabled",i,n);break}case"trackEncodingEnabled":{if(this.getEndpointId()===t.data.endpointId)return;if(a=this.idToEndpoint.get(t.data.endpointId),a==null)throw`Endpoint with id: ${t.data.endpointId} doesn't exist`;const r=t.data.trackId,n=t.data.encoding,i=a.tracks.get(r);this.emit("trackEncodingEnabled",i,n);break}case"tracksPriority":{const r=t.data.tracks.map(i=>this.trackIdToTrack.get(i)),n=Array.from(this.trackIdToTrack.values()).filter(i=>!r.includes(i));this.emit("tracksPriorityChanged",r,n);break}case"encodingSwitched":{const r=t.data.trackId,n=this.trackIdToTrack.get(r);n.encoding=t.data.encoding,n.encodingReason=t.data.reason,n.emit("encodingChanged",n);break}case"custom":this.handleMediaEvent(t.data);break;case"error":this.emit("connectionError",t.data.message),this.disconnect();break;case"vadNotification":{const r=t.data.trackId,n=this.trackIdToTrack.get(r),i=t.data.status;S.includes(i)?(n.vadStatus=i,n.emit("voiceActivityChanged",n)):console.warn("Received unknown vad status: ",i);break}case"bandwidthEstimation":{const r=t.data.estimation;this.emit("bandwidthEstimationChanged",r);break}default:console.warn("Received unknown media event: ",t.type);break}});o(this,"addTrackToConnection",t=>{const a=this.createTransceiverConfig(t),e=t.track;this.connection.addTransceiver(e,a)});o(this,"updateEndpointMetadata",t=>{this.localEndpoint.metadata=this.endpointMetadataParser(t),this.localEndpoint.rawMetadata=this.localEndpoint.metadata,this.localEndpoint.metadataParsingError=void 0;const a=f("updateEndpointMetadata",{metadata:this.localEndpoint.metadata});this.sendMediaEvent(a)});o(this,"updateTrackMetadata",(t,a)=>{const e=this.localTrackIdToTrack.get(t),r=this.localEndpoint.tracks.get(t);try{e.metadata=this.trackMetadataParser(a),e.metadataParsingError=void 0,this.localEndpoint.tracks.set(t,{...r,metadata:e.metadata,metadataParsingError:void 0})}catch(i){throw e.metadata=void 0,e.metadataParsingError=i,this.localEndpoint.tracks.set(t,{...r,metadata:void 0,metadataParsingError:i}),i}e.rawMetadata=e.metadata,this.localEndpoint.tracks.set(t,{...r,rawMetadata:e.metadata}),this.localTrackIdToTrack.set(t,e);const n=f("updateTrackMetadata",{trackId:t,trackMetadata:e.metadata});switch(e.negotiationStatus){case"done":this.sendMediaEvent(n);break;case"offered":e.pendingMetadataUpdate=!0;break}});o(this,"getMidToTrackId",()=>{const t={};return this.connection?(this.connection.getTransceivers().forEach(a=>{var n;const e=(n=a.sender.track)==null?void 0:n.id,r=a.mid;if(e&&r){const i=Array.from(this.localTrackIdToTrack.values()).find(s=>s.track.id===e);t[r]=i.trackId}}),t):null});o(this,"disconnect",()=>{const t=f("disconnect");this.sendMediaEvent(t),this.cleanUp()});o(this,"cleanUp",()=>{this.connection&&(this.connection.onicecandidate=null,this.connection.ontrack=null,this.connection.onconnectionstatechange=null,this.connection.onicecandidateerror=null,this.connection.oniceconnectionstatechange=null),this.connection=void 0});o(this,"sendMediaEvent",t=>{const a=y(t);this.emit("sendMediaEvent",a)});o(this,"onAnswer",async t=>{this.connection.ontrack=this.onTrack();try{await this.connection.setRemoteDescription(t),this.disabledTrackEncodings.forEach((a,e)=>{a.forEach(r=>this.disableTrackEncoding(e,r))})}catch(a){console.error(a)}});o(this,"addTransceiversIfNeeded",t=>{var s;const a=this.connection.getTransceivers().filter(c=>c.direction==="recvonly");let e=[];const r=c=>{let d=t.get(c);d=d!==void 0?d:0;const k=a.filter(p=>p.receiver.track.kind===c).length;return Array(d-k).fill(c)},n=r("audio"),i=r("video");e=e.concat(n),e=e.concat(i);for(const c of e)(s=this.connection)==null||s.addTransceiver(c,{direction:"recvonly"})});o(this,"getTrackIdToMetadata",()=>{const t={};return Array.from(this.localEndpoint.tracks.entries()).forEach(([a,{metadata:e}])=>{t[a]=e}),t});o(this,"getTrackBitrates",t=>{const a=this.localTrackIdToTrack.get(t);if(!a)throw"Track with id ${trackId} not present in 'localTrackIdToTrack'";const e=a.track.kind,n=this.findSender(a.track.id).getParameters().encodings;if(n.length==1&&!n[0].rid)return n[0].maxBitrate||P[e];if(e=="audio")throw"Audio track cannot have multiple encodings";const i={};return n.filter(s=>s.rid).forEach(s=>{const c=s.rid;i[c]=s.maxBitrate||R[c]}),i});o(this,"getTrackIdToTrackBitrates",()=>{const t={};return Array.from(this.localEndpoint.tracks.entries()).forEach(([a,e])=>{t[a]=this.getTrackBitrates(a)}),t});o(this,"checkIfTrackBelongToEndpoint",(t,a)=>Array.from(a.tracks.keys()).some(e=>t.startsWith(e)));o(this,"onOfferData",async t=>{this.connection?this.connection.restartIce():(this.connection=new RTCPeerConnection(this.rtcConfig),this.connection.onicecandidate=this.onLocalCandidate(),this.connection.onicecandidateerror=this.onIceCandidateError,this.connection.onconnectionstatechange=this.onConnectionStateChange,this.connection.oniceconnectionstatechange=this.onIceConnectionStateChange,this.connection.onicegatheringstatechange=this.onIceGatheringStateChange,this.connection.onsignalingstatechange=this.onSignalingStateChange,Array.from(this.localTrackIdToTrack.values()).forEach(a=>this.addTrackToConnection(a)),this.connection.getTransceivers().forEach(a=>a.direction="sendonly")),this.addTransceiversIfNeeded(t),await this.createAndSendOffer()});o(this,"onRemoteCandidate",t=>{try{const a=new RTCIceCandidate(t);if(!this.connection)throw new Error("Received new remote candidate but RTCConnection is undefined");this.connection.addIceCandidate(a)}catch(a){console.error(a)}});o(this,"onLocalCandidate",()=>t=>{if(t.candidate){const a=u({type:"candidate",data:{candidate:t.candidate.candidate,sdpMLineIndex:t.candidate.sdpMLineIndex}});this.sendMediaEvent(a)}});o(this,"onIceCandidateError",t=>{console.warn(t)});o(this,"onConnectionStateChange",t=>{var a;switch((a=this.connection)==null?void 0:a.connectionState){case"connected":this.processNextCommand();break;case"failed":this.emit("connectionError","Connection failed");break}});o(this,"onIceConnectionStateChange",t=>{var e;const a="Ice connection failed";switch((e=this.connection)==null?void 0:e.iceConnectionState){case"disconnected":console.warn("ICE connection: disconnected");break;case"failed":this.emit("connectionError",a);break;case"connected":this.processNextCommand();break}});o(this,"onIceGatheringStateChange",t=>{var a;switch((a=this.connection)==null?void 0:a.iceGatheringState){case"complete":this.processNextCommand();break}});o(this,"onSignalingStateChange",t=>{var a;switch((a=this.connection)==null?void 0:a.signalingState){case"stable":this.processNextCommand();break}});o(this,"onTrack",()=>t=>{const[a]=t.streams,e=t.transceiver.mid,r=this.midToTrackId.get(e);if(this.checkIfTrackBelongToEndpoint(r,this.localEndpoint))return;const n=this.trackIdToTrack.get(r);n.stream=a,n.track=t.track,this.emit("trackReady",n)});o(this,"setTurns",t=>{t.forEach(a=>{let e,r;a.transport=="tls"?(e="tcp",r="turns"):(e=a.transport,r="turn");const n={credential:a.password,urls:r.concat(":",a.serverAddr,":",a.serverPort,"?transport=",e),username:a.username};this.rtcConfig.iceServers.push(n)})});o(this,"addEndpoint",t=>{Object.prototype.hasOwnProperty.call(t,"trackIdToMetadata")?t.tracks=new Map(Object.entries(t.tracks)):t.tracks=new Map,this.idToEndpoint.set(t.id,t)});o(this,"eraseEndpoint",t=>{const a=Array.from(t.tracks.keys());a.forEach(e=>this.trackIdToTrack.delete(e)),Array.from(this.midToTrackId.entries()).forEach(([e,r])=>{a.includes(r)&&this.midToTrackId.delete(e)}),this.idToEndpoint.delete(t.id)});o(this,"eraseTrack",(t,a)=>{this.trackIdToTrack.delete(t);const e=Array.from(this.midToTrackId.entries()),[r,n]=e.find(([i,s])=>s===t);this.midToTrackId.delete(r),this.idToEndpoint.get(a).tracks.delete(t),this.disabledTrackEncodings.delete(t)});o(this,"getEndpointId",()=>this.localEndpoint.id);o(this,"mapMediaEventTracksToTrackContextImpl",(t,a)=>{const e=Array.from(t).map(([r,n])=>[r,new I(a,r,n.metadata,n.simulcastConfig,this.trackMetadataParser)]);return new Map(e)});this.endpointMetadataParser=(a=t==null?void 0:t.endpointMetadataParser)!=null?a:r=>r,this.trackMetadataParser=(e=t==null?void 0:t.trackMetadataParser)!=null?e:r=>r}async getStatistics(t){var a,e;return(e=await((a=this.connection)==null?void 0:a.getStats(t)))!=null?e:new Map}getRemoteTracks(){return Object.fromEntries(this.trackIdToTrack.entries())}getRemoteEndpoints(){return Object.fromEntries(this.idToEndpoint.entries())}addTrack(t,a,e,r={enabled:!1,activeEncodings:[],disabledEncodings:[]},n=0){const i=new v,s=this.getTrackId(l.v4());try{const c=this.trackMetadataParser(e);this.pushCommand({commandType:"ADD-TRACK",trackId:s,track:t,stream:a,trackMetadata:c,simulcastConfig:r,maxBandwidth:n,resolutionNotifier:i})}catch(c){i.reject(c)}return i.promise.then(()=>s)}pushCommand(t){this.commandsQueue.push(t),this.processNextCommand()}handleCommand(t){switch(t.commandType){case"ADD-TRACK":this.addTrackHandler(t);break;case"REMOVE-TRACK":this.removeTrackHandler(t);break;case"REPLACE-TRACK":this.replaceTrackHandler(t);break}}processNextCommand(){if(this.ongoingRenegotiation||this.ongoingTrackReplacement||this.connection&&(this.connection.signalingState!=="stable"||this.connection.connectionState!=="connected"||this.connection.iceConnectionState!=="connected"))return;this.resolvePreviousCommand();const t=this.commandsQueue.shift();t&&(this.commandResolutionNotifier=t.resolutionNotifier,this.handleCommand(t))}resolvePreviousCommand(){this.commandResolutionNotifier&&(this.commandResolutionNotifier.resolve(),this.commandResolutionNotifier=null)}addTrackHandler(t){var w,C;const{simulcastConfig:a,maxBandwidth:e,track:r,stream:n,trackMetadata:i,trackId:s}=t,c=(w=this.connection)==null?void 0:w.getSenders().some(E=>E.track===r);let d;if(c&&(d="This track was already added to peerConnection, it can't be added again!"),!a.enabled&&typeof e!="number"&&(d="Invalid type of `maxBandwidth` argument for a non-simulcast track, expected: number"),this.getEndpointId()===""&&(d="Cannot add tracks before being accepted by the server"),d){(C=this.commandResolutionNotifier)==null||C.reject(d),this.commandResolutionNotifier=null,this.processNextCommand();return}this.ongoingRenegotiation=!0;const k=new I(this.localEndpoint,s,i,a,this.trackMetadataParser);k.track=r,k.stream=n,k.maxBandwidth=e,this.localEndpoint.tracks.set(s,k),this.localTrackIdToTrack.set(s,k),this.connection&&(this.addTrackToConnection(k),this.connection.getTransceivers().forEach(E=>E.direction=E.direction==="sendrecv"?"sendonly":E.direction));const p=u({type:"renegotiateTracks"});this.sendMediaEvent(p)}createTransceiverConfig(t){let a;return t.track.kind==="audio"?a=this.createAudioTransceiverConfig(t):a=this.createVideoTransceiverConfig(t),a}createAudioTransceiverConfig(t){return{direction:"sendonly",streams:t.stream?[t.stream]:[]}}createVideoTransceiverConfig(t){var e;let a;if(t.simulcastConfig.enabled){a=M;const r=t.simulcastConfig.activeEncodings,n=[];(e=a.sendEncodings)==null||e.forEach(i=>{r.includes(i.rid)?i.active=!0:n.push(i.rid)}),this.disabledTrackEncodings.set(t.trackId,n)}else a={direction:"sendonly",sendEncodings:[{active:!0}],streams:t.stream?[t.stream]:[]};return t.maxBandwidth&&a.sendEncodings&&this.applyBandwidthLimitation(a.sendEncodings,t.maxBandwidth),a}applyBandwidthLimitation(t,a){typeof a=="number"?this.splitBandwidth(t,a*1024):t.filter(e=>e.rid).forEach(e=>{const r=a.get(e.rid)||0;r>0?e.maxBitrate=r*1024:delete e.maxBitrate})}splitBandwidth(t,a){if(a===0){t.forEach(i=>delete i.maxBitrate);return}if(t.length==0){console.error("Attempted to limit bandwidth of the track that doesn't have any encodings");return}const e=t[0].scaleResolutionDownBy||1,r=t.reduce((i,s)=>i+(e/(s.scaleResolutionDownBy||1))**2,0),n=a/r;t.forEach(i=>{i.maxBitrate=n*(e/(i.scaleResolutionDownBy||1))**2})}async replaceTrack(t,a,e){const r=new v;try{const n=this.trackMetadataParser(e);this.pushCommand({commandType:"REPLACE-TRACK",trackId:t,newTrack:a,newTrackMetadata:n,resolutionNotifier:r})}catch(n){r.reject(n)}return r.promise}replaceTrackHandler(t){const{trackId:a,newTrack:e,newTrackMetadata:r}=t,n=this.localTrackIdToTrack.get(a),i=this.findSender(n.track.id);i&&(this.ongoingTrackReplacement=!0,i.replaceTrack(e).then(()=>{const s=r||this.localTrackIdToTrack.get(a).metadata;n.track=e,this.updateTrackMetadata(a,s)}).finally(()=>{this.resolvePreviousCommand(),this.ongoingTrackReplacement=!1,this.processNextCommand()}))}setTrackBandwidth(t,a){const e=this.localTrackIdToTrack.get(t);if(!e)return Promise.reject(`Track '${t}' doesn't exist`);const r=this.findSender(e.track.id),n=r.getParameters();return n.encodings.length===0?n.encodings=[{}]:this.applyBandwidthLimitation(n.encodings,a),r.setParameters(n).then(()=>{const i=u({type:"trackVariantBitrates",data:{trackId:t,variantBitrates:this.getTrackBitrates(t)}});return this.sendMediaEvent(i),!0}).catch(i=>!1)}setEncodingBandwidth(t,a,e){const r=this.localTrackIdToTrack.get(t);if(!r)return Promise.reject(`Track '${t}' doesn't exist`);const n=this.findSender(r.track.id),i=n.getParameters(),s=i.encodings.find(c=>c.rid===a);if(s)e===0?delete s.maxBitrate:s.maxBitrate=e*1024;else return Promise.reject(`Encoding with rid '${a}' doesn't exist`);return n.setParameters(i).then(()=>{const c=u({type:"trackVariantBitrates",data:{trackId:t,variantBitrates:this.getTrackBitrates(t)}});return this.sendMediaEvent(c),!0}).catch(c=>!1)}removeTrack(t){const a=new v;return this.pushCommand({commandType:"REMOVE-TRACK",trackId:t,resolutionNotifier:a}),a.promise}removeTrackHandler(t){const{trackId:a}=t,e=this.localTrackIdToTrack.get(a),r=this.findSender(e.track.id);this.ongoingRenegotiation=!0,this.connection.removeTrack(r);const n=u({type:"renegotiateTracks"});this.sendMediaEvent(n),this.localTrackIdToTrack.delete(a),this.localEndpoint.tracks.delete(a)}setTargetTrackEncoding(t,a){var n;const e=this.trackIdToTrack.get(t);if(!((n=e==null?void 0:e.simulcastConfig)!=null&&n.enabled)||!e.simulcastConfig.activeEncodings.includes(a)){console.warn("The track does not support changing its target encoding");return}const r=u({type:"setTargetTrackVariant",data:{trackId:t,variant:a}});this.sendMediaEvent(r)}enableTrackEncoding(t,a){var c,d,k;const e=(c=this.localTrackIdToTrack.get(t))==null?void 0:c.track,r=(d=this.disabledTrackEncodings.get(t))==null?void 0:d.filter(p=>p!==a);this.disabledTrackEncodings.set(t,r);const n=(k=this.connection)==null?void 0:k.getSenders().filter(p=>p.track===e)[0],i=n==null?void 0:n.getParameters();i.encodings.filter(p=>p.rid==a)[0].active=!0,n==null||n.setParameters(i);const s=f("enableTrackEncoding",{trackId:t,encoding:a});this.sendMediaEvent(s)}disableTrackEncoding(t,a){var s,c;const e=(s=this.localTrackIdToTrack.get(t))==null?void 0:s.track;this.disabledTrackEncodings.get(t).push(a);const r=(c=this.connection)==null?void 0:c.getSenders().filter(d=>d.track===e)[0],n=r==null?void 0:r.getParameters();n.encodings.filter(d=>d.rid==a)[0].active=!1,r==null||r.setParameters(n);const i=f("disableTrackEncoding",{trackId:t,encoding:a});this.sendMediaEvent(i)}findSender(t){return this.connection.getSenders().find(a=>a.track&&a.track.id===t)}getTrackId(t){return`${this.getEndpointId()}:${t}`}async createAndSendOffer(){if(this.connection)try{const t=await this.connection.createOffer();await this.connection.setLocalDescription(t);const a=u({type:"sdpOffer",data:{sdpOffer:t,trackIdToTrackMetadata:this.getTrackIdToMetadata(),trackIdToTrackBitrates:this.getTrackIdToTrackBitrates(),midToTrackId:this.getMidToTrackId()}});this.sendMediaEvent(a);for(const e of this.localTrackIdToTrack.values())e.negotiationStatus="offered"}catch(t){console.error(t)}}}h.WebRTCEndpoint=B,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});