@voicenter-team/opensips-js 1.0.103 → 1.0.105

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.
@@ -18330,7 +18330,7 @@ return a / b;`,packedOpSnippet:`
18330
18330
  }
18331
18331
  `};return mb().compileAndRun(oe,[r,E,te])}function SO(){return fb()==="webgl"}function Cle(r,e,t,n,i,s,a,o,u,c,d,p){var m=a[0],_=a[1];return u===void 0&&(u=.2),c===void 0&&(c=8),d===void 0&&(d=.3),p===void 0&&(p=10),Mt(this,void 0,void 0,function(){var y,b,S,w,x;return Lt(this,function(E){switch(E.label){case 0:return y=t.filter(function(I){return I.score>=u}),SO()?(S=bt(function(){var I=bO(r,e,y,n,i,s,[m,_],o,c,d,p),R=Ci().makeTensorFromDataId(I.dataId,I.shape,I.dtype);return y.map(function(P,B){return function(O,F){return bt(function(){return Yt(bf(O,Nt(F)),"int32")})}(R,B)})}),[4,Promise.all(S.map(function(I){return I.data()}))]):[3,2];case 1:return b=E.sent(),S.forEach(function(I){return I.dispose()}),[3,5];case 2:return[4,r.data()];case 3:return w=E.sent(),[4,e.data()];case 4:x=E.sent(),b=function(I,R,P,B,O,F,D,L,G,j){var te=D[0],W=D[1];j===void 0&&(j=5);for(var Q=P.map(function(q){return new Uint8Array(B*O).fill(0)}),oe=L.top,Ce=L.left,fe=qT([B,O],[te,W],L),ne=fe[0],ae=fe[1],be=vO([te,W],F)[0],Se=0;Se<B;Se+=1)for(var Me=0;Me<O;Me+=1){var ot=Se*O+Me;if(I[ot]===1){var Ve=yO({x:Me,y:Se},R,P,j,[oe,Ce],[ne,ae],be,[B,O],F,G);Ve>=0&&(Q[Ve][ot]=1)}}return Q}(w,x,y,n,i,s,[m,_],o,c),E.label=5;case 5:return[2,b.map(function(I,R){return{data:I,pose:y[R],width:i,height:n}})]}})})}function Ele(r,e,t,n,i,s,a,o,u,c,d,p,m){var _=o[0],y=o[1];return c===void 0&&(c=.2),d===void 0&&(d=8),p===void 0&&(p=.3),m===void 0&&(m=10),Mt(this,void 0,void 0,function(){var b,S,w,x,E,I;return Lt(this,function(R){switch(R.label){case 0:return b=n.filter(function(P){return P.score>=c}),SO()?(w=bt(function(){var P=bO(r,e,b,i,s,a,[_,y],u,d,p,m),B=Ci().makeTensorFromDataId(P.dataId,P.shape,P.dtype);return b.map(function(O,F){return function(D,L,G){return bt(function(){return At(Ye(Yt(bf(D,Nt(G)),"int32"),St(L,1)),1)})}(B,t,F)})}),[4,Promise.all(w.map(function(P){return P.data()}))]):[3,2];case 1:return S=R.sent(),w.forEach(function(P){return P.dispose()}),[3,6];case 2:return[4,r.data()];case 3:return x=R.sent(),[4,e.data()];case 4:return E=R.sent(),[4,t.data()];case 5:I=R.sent(),S=function(P,B,O,F,D,L,G,j,te,W,Q){var oe=j[0],Ce=j[1];Q===void 0&&(Q=5);for(var fe=F.map(function(mt){return new Int32Array(D*L).fill(-1)}),ne=te.top,ae=te.left,be=qT([D,L],[oe,Ce],te),Se=be[0],Me=be[1],ot=vO([oe,Ce],G)[0],Ve=0;Ve<D;Ve+=1)for(var q=0;q<L;q+=1){var ue=Ve*L+q;if(P[ue]===1){var Ue=yO({x:q,y:Ve},B,F,Q,[ne,ae],[Se,Me],ot,[D,L],G,W);Ue>=0&&(fe[Ue][ue]=O[ue])}}return fe}(x,E,I,b,i,s,a,[_,y],u,d),R.label=6;case 6:return[2,S.map(function(P,B){return{pose:b[B],data:P,height:i,width:s}})]}})})}function KT(r){return Math.floor(r/2)}var xle=function(){function r(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}return r.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)},r.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e},r.prototype.empty=function(){return this.numberOfElements===-1},r.prototype.size=function(){return this.numberOfElements+1},r.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},r.prototype.max=function(){return this.priorityQueue[0]},r.prototype.swim=function(e){for(;e>0&&this.less(KT(e),e);)this.exchange(e,KT(e)),e=KT(e)},r.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(t<this.numberOfElements&&this.less(t,t+1)&&t++,!this.less(e,t))break;this.exchange(e,t),e=t}},r.prototype.getValueAt=function(e){return this.getElementValue(this.priorityQueue[e])},r.prototype.less=function(e,t){return this.getValueAt(e)<this.getValueAt(t)},r.prototype.exchange=function(e,t){var n=this.priorityQueue[e];this.priorityQueue[e]=this.priorityQueue[t],this.priorityQueue[t]=n},r}();function Ile(r,e,t,n,i,s){for(var a=s.shape,o=a[0],u=a[1],c=!0,d=Math.max(t-i,0),p=Math.min(t+i+1,o),m=d;m<p;++m){for(var _=Math.max(n-i,0),y=Math.min(n+i+1,u),b=_;b<y;++b)if(s.get(m,b,r)>e){c=!1;break}if(!c)break}return c}var TO=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]].map(function(r){var e=r[0],t=r[1];return[w0[e],w0[t]]}),XT=TO.map(function(r){return r[1]}),wO=TO.map(function(r){return r[0]});function YT(r,e,t,n){return{y:gO(Math.round(r.y/e),0,t-1),x:gO(Math.round(r.x/e),0,n-1)}}function CO(r,e,t,n,i,s,a,o){o===void 0&&(o=2);for(var u=n.shape,c=u[0],d=u[1],p=function(x,E,I){var R=I.shape[2]/2;return{y:I.get(E.y,E.x,x),x:I.get(E.y,E.x,R+x)}}(r,YT(e.position,s,c,d),a),m=_O(e.position,p),_=0;_<o;_++){var y=YT(m,s,c,d),b=pO(y.y,y.x,t,i);m=_O({x:y.x*s,y:y.y*s},{x:b.x,y:b.y})}var S=YT(m,s,c,d),w=n.get(S.y,S.x,t);return{position:m,part:T0[t],score:w}}function Ale(r,e,t,n,i,s){var a=e.shape[2],o=XT.length,u=new Array(a),c=r.part,d=r.score,p=mO(c,n,t);u[c.id]={score:d,part:T0[c.id],position:p};for(var m=o-1;m>=0;--m){var _=XT[m],y=wO[m];u[_]&&!u[y]&&(u[y]=CO(m,u[_],y,e,t,n,s))}for(m=0;m<o;++m)_=wO[m],y=XT[m],u[_]&&!u[y]&&(u[y]=CO(m,u[_],y,e,t,n,i));return u}function EO(r,e,t,n){var i=t.x,s=t.y;return r.some(function(a){var o,u,c,d,p,m,_=a.keypoints[n].position;return o=s,u=i,c=_.y,d=_.x,(p=c-o)*p+(m=d-u)*m<=e})}function Rle(r,e,t){var n=t.reduce(function(i,s,a){var o=s.position,u=s.score;return EO(r,e,o,a)||(i+=u),i},0);return n/t.length}function C0(r,e,t,n,i,s,a,o){a===void 0&&(a=.5),o===void 0&&(o=20);for(var u=[],c=function(y,b,S){for(var w=S.shape,x=w[0],E=w[1],I=w[2],R=new xle(x*E*I,function(D){return D.score}),P=0;P<x;++P)for(var B=0;B<E;++B)for(var O=0;O<I;++O){var F=S.get(P,B,O);F<y||Ile(O,F,P,B,b,S)&&R.enqueue({score:F,part:{heatmapY:P,heatmapX:B,id:O}})}return R}(a,1,r),d=o*o;u.length<s&&!c.empty();){var p=c.dequeue();if(!EO(u,d,mO(p.part,i,e),p.part.id)){var m=Ale(p,r,e,i,t,n),_=Rle(u,d,m);u.push({keypoints:m,score:_})}}return u}var Jf,Nle=[-123.15,-115.9,-103.06],kle=function(r){function e(){return r!==null&&r.apply(this,arguments)||this}return uO(e,r),e.prototype.preprocessInput=function(t){return St(t,Nle)},e.prototype.nameOutputResults=function(t){var n=t[0],i=t[1],s=t[2],a=t[3],o=t[4],u=t[5];return{offsets:o,segmentation:t[6],partHeatmaps:u,longOffsets:a,heatmap:s,displacementFwd:i,displacementBwd:n,partOffsets:t[7]}},e}(fO),xO="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/resnet50/",IO="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/mobilenet/";function Qf(r){if(typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return function(e){if("offsetHeight"in e&&e.offsetHeight!==0&&"offsetWidth"in e&&e.offsetWidth!==0)return[e.offsetHeight,e.offsetWidth];if(e.height!=null&&e.width!=null)return[e.height,e.width];throw new Error("HTMLImageElement must have height and width attributes set.")}(r);if(typeof ImageData<"u"&&r instanceof ImageData)return[r.height,r.width];if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return function(e){return e.hasAttribute("height")&&e.hasAttribute("width")?[e.height,e.width]:[e.videoHeight,e.videoWidth]}(r);if(r instanceof tn)return[r.shape[0],r.shape[1]];throw new Error("error: Unknown input type: "+r+".")}function AO(r,e){return function(t,n){return(t-1)%n==0}(r,e)?r:Math.floor(r/e)*e+1}var Zf={low:"low",medium:"medium",high:"high",full:"full"},Ole=((Jf={})[Zf.low]=.25,Jf[Zf.medium]=.5,Jf[Zf.high]=.75,Jf[Zf.full]=1,Jf);function E0(r,e,t){var n=t[0],i=t[1],s=function(a){if(typeof a=="string"){var o=Ole[a];return V(typeof o=="number",function(){return"string value of inputResolution must be one of "+Object.values(Zf).join(",")+" but was "+a+"."}),o}return V(typeof a=="number"&&a<=2&&a>=.1,function(){return"inputResolution must be a string or number between 0.1 and 2, but was "+a}),a}(r);return[AO(n*s,e),AO(i*s,e)]}function Yc(r,e,t,n,i){var s=e[0],a=e[1],o=t[0],u=t[1],c=n[0],d=c[0],p=c[1],m=n[1],_=m[0],y=m[1];return i===void 0&&(i=!1),bt(function(){var b=Au.resizeBilinear(r,[o,u],!0);return i&&(b=Oa(b)),function(S,w,x){var E=w[0],I=w[1],R=x[0],P=R[0],B=R[1],O=x[1],F=O[0],D=O[1];return bt(function(){var L=kr(S);return Ai(Au.cropAndResize(L,[[P/(E+P+B-1),F/(I+F+D-1),(P+E-1)/(E+P+B-1),(F+I-1)/(I+F+D-1)]],[0],[E,I]),[0])})}(b,[s,a],[[d,p],[_,y]])})}function x0(r,e){var t=e[0],n=e[1],i=Qf(r),s=i[0],a=i[1],o=n/t,u=[0,0,0,0],c=u[0],d=u[1],p=u[2],m=u[3];a/s<o?(c=0,d=0,p=Math.round(.5*(o*s-a)),m=Math.round(.5*(o*s-a))):(c=Math.round(.5*(1/o*a-s)),d=Math.round(.5*(1/o*a-s)),p=0,m=0);var _=bt(function(){var y=function(b){return b instanceof tn?b:G_(b)}(r);return y=Kb(y,[[c,d],[p,m],[0,0]]),Au.resizeBilinear(y,[t,n])});return{resized:_,padding:{top:c,left:p,right:m,bottom:d}}}function I0(r){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,Promise.all(r.map(function(t){return t.buffer()}))]})})}function A0(r,e,t,n,i){var s=e[0],a=e[1],o=t[0],u=t[1],c=function(d,p,m,_,y){return _===void 0&&(_=0),y===void 0&&(y=0),m===1&&p===1&&_===0&&y===0?d:d.map(function(b){return function(S,w,x,E,I){return E===void 0&&(E=0),I===void 0&&(I=0),{score:S.score,keypoints:S.keypoints.map(function(R){var P=R.score,B=R.part,O=R.position;return{score:P,part:B,position:{x:O.x*x+I,y:O.y*w+E}}})}}(b,p,m,_,y)})}(r,(s+n.top+n.bottom)/o,(a+n.left+n.right)/u,-n.top,-n.left);return i?function(d,p){return p<=0?d:d.map(function(m){return function(_,y){return{score:_.score,keypoints:_.keypoints.map(function(b){var S=b.score,w=b.part,x=b.position;return{score:S,part:w,position:{x:y-1-x.x,y:x.y}}})}}(m,p)})}(c,a):c}var RO={architecture:"MobileNetV1",outputStride:16,quantBytes:4,multiplier:.75},NO=["MobileNetV1","ResNet50"],kO={MobileNetV1:[8,16,32],ResNet50:[32,16]},OO={MobileNetV1:[.5,.75,1],ResNet50:[1]},$O=[1,2,4],R0={flipHorizontal:!1,internalResolution:"medium",segmentationThreshold:.7,maxDetections:10,scoreThreshold:.4,nmsRadius:20},N0={flipHorizontal:!1,internalResolution:"medium",segmentationThreshold:.7,maxDetections:10,scoreThreshold:.4,nmsRadius:20,minKeypointScore:.3,refineSteps:10};function DO(r){var e=r.segmentationThreshold,t=r.maxDetections,n=r.scoreThreshold,i=r.nmsRadius;if(e<0||e>1)throw new Error("segmentationThreshold "+e+". Should be in range [0.0, 1.0]");if(t<=0)throw new Error("Invalid maxDetections "+t+". Should be > 0");if(n<0||n>1)throw new Error("Invalid scoreThreshold "+n+". Should be in range [0.0, 1.0]");if(i<=0)throw new Error("Invalid nmsRadius "+i+".")}function PO(r){var e=r.segmentationThreshold,t=r.maxDetections,n=r.scoreThreshold,i=r.nmsRadius,s=r.minKeypointScore,a=r.refineSteps;if(e<0||e>1)throw new Error("segmentationThreshold "+e+". Should be in range [0.0, 1.0]");if(t<=0)throw new Error("Invalid maxDetections "+t+". Should be > 0");if(n<0||n>1)throw new Error("Invalid scoreThreshold "+n+". Should be in range [0.0, 1.0]");if(i<=0)throw new Error("Invalid nmsRadius "+i+".");if(s<0||s>1)throw new Error("Invalid minKeypointScore "+s+".Should be in range [0.0, 1.0]");if(a<=0||a>20)throw new Error("Invalid refineSteps "+a+".Should be in range [1, 20]")}var FO=function(){function r(e){this.baseModel=e}return r.prototype.predictForPersonSegmentation=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},r.prototype.predictForPersonSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,partHeatmapLogits:t.partHeatmaps,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd}},r.prototype.predictForMultiPersonInstanceSegmentationAndPart=function(e){var t=this.baseModel.predict(e);return{segmentLogits:t.segmentation,longOffsets:t.longOffsets,heatmapScores:t.heatmapScores,offsets:t.offsets,displacementFwd:t.displacementFwd,displacementBwd:t.displacementBwd,partHeatmaps:t.partHeatmaps}},r.prototype.segmentPersonActivation=function(e,t,n){var i=this;n===void 0&&(n=.5);var s=Qf(e),a=s[0],o=s[1],u=E0(t,this.baseModel.outputStride,[a,o]),c=x0(e,u),d=c.resized,p=c.padding,m=bt(function(){var x=i.predictForPersonSegmentation(d),E=x.segmentLogits,I=x.heatmapScores,R=x.offsets,P=x.displacementFwd,B=x.displacementBwd,O=d.shape,F=O[0],D=O[1],L=Yc(E,[a,o],[F,D],[[p.top,p.bottom],[p.left,p.right]],!0);return{segmentation:S0(Ai(L),n),heatmapScores:I,offsets:R,displacementFwd:P,displacementBwd:B}}),_=m.segmentation,y=m.heatmapScores,b=m.offsets,S=m.displacementFwd,w=m.displacementBwd;return d.dispose(),{segmentation:_,heatmapScores:y,offsets:b,displacementFwd:S,displacementBwd:w,padding:p,internalResolutionHeightAndWidth:u}},r.prototype.segmentPerson=function(e,t){return t===void 0&&(t=R0),Mt(this,void 0,void 0,function(){var n,i,s,a,o,u,c,d,p,m,_,y,b,S,w,x,E,I;return Lt(this,function(R){switch(R.label){case 0:return DO(t=gr(gr({},R0),t)),n=this.segmentPersonActivation(e,t.internalResolution,t.segmentationThreshold),i=n.segmentation,s=n.heatmapScores,a=n.offsets,o=n.displacementFwd,u=n.displacementBwd,c=n.padding,d=n.internalResolutionHeightAndWidth,p=i.shape,m=p[0],_=p[1],[4,i.data()];case 1:return y=R.sent(),i.dispose(),[4,I0([s,a,o,u])];case 2:return b=R.sent(),S=b[0],w=b[1],x=b[2],E=b[3],I=A0(I=C0(S,w,x,E,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[m,_],d,c,!1),s.dispose(),a.dispose(),o.dispose(),u.dispose(),[2,{height:m,width:_,data:y,allPoses:I}]}})})},r.prototype.segmentMultiPerson=function(e,t){return t===void 0&&(t=N0),Mt(this,void 0,void 0,function(){var n,i,s,a,o,u,c,d,p,m,_,y,b,S,w,x,E,I,R,P,B,O=this;return Lt(this,function(F){switch(F.label){case 0:return PO(t=gr(gr({},N0),t)),n=Qf(e),i=n[0],s=n[1],a=E0(t.internalResolution,this.baseModel.outputStride,[i,s]),o=x0(e,a),u=o.resized,c=o.padding,d=bt(function(){var D,L=O.predictForMultiPersonInstanceSegmentationAndPart(u),G=L.segmentLogits,j=L.longOffsets,te=L.heatmapScores,W=L.offsets,Q=L.displacementFwd,oe=L.displacementBwd,Ce=Yc(G,[i,s],a,[[c.top,c.bottom],[c.left,c.right]],!0);return D=j,{segmentation:S0(Ai(Ce),t.segmentationThreshold),longOffsets:D,heatmapScoresRaw:te,offsetsRaw:W,displacementFwdRaw:Q,displacementBwdRaw:oe}}),p=d.segmentation,m=d.longOffsets,_=d.heatmapScoresRaw,y=d.offsetsRaw,b=d.displacementFwdRaw,S=d.displacementBwdRaw,[4,I0([_,y,b,S])];case 1:return w=F.sent(),x=w[0],E=w[1],I=w[2],R=w[3],P=A0(P=C0(x,E,I,R,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[i,s],a,c,!1),[4,Cle(p,m,P,i,s,this.baseModel.outputStride,a,c,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return B=F.sent(),u.dispose(),p.dispose(),m.dispose(),_.dispose(),y.dispose(),b.dispose(),S.dispose(),[2,B]}})})},r.prototype.segmentPersonPartsActivation=function(e,t,n){var i=this;n===void 0&&(n=.5);var s=Qf(e),a=s[0],o=s[1],u=E0(t,this.baseModel.outputStride,[a,o]),c=x0(e,u),d=c.resized,p=c.padding,m=bt(function(){var x=i.predictForPersonSegmentationAndPart(d),E=x.segmentLogits,I=x.partHeatmapLogits,R=x.heatmapScores,P=x.offsets,B=x.displacementFwd,O=x.displacementBwd,F=d.shape,D=F[0],L=F[1],G=Yc(E,[a,o],[D,L],[[p.top,p.bottom],[p.left,p.right]],!0),j=Yc(I,[a,o],[D,L],[[p.top,p.bottom],[p.left,p.right]],!0);return{partSegmentation:ble(S0(Ai(G),n),j),heatmapScores:R,offsets:P,displacementFwd:B,displacementBwd:O}}),_=m.partSegmentation,y=m.heatmapScores,b=m.offsets,S=m.displacementFwd,w=m.displacementBwd;return d.dispose(),{partSegmentation:_,heatmapScores:y,offsets:b,displacementFwd:S,displacementBwd:w,padding:p,internalResolutionHeightAndWidth:u}},r.prototype.segmentPersonParts=function(e,t){return t===void 0&&(t=R0),Mt(this,void 0,void 0,function(){var n,i,s,a,o,u,c,d,p,m,_,y,b,S,w,x,E,I;return Lt(this,function(R){switch(R.label){case 0:return DO(t=gr(gr({},R0),t)),n=this.segmentPersonPartsActivation(e,t.internalResolution,t.segmentationThreshold),i=n.partSegmentation,s=n.heatmapScores,a=n.offsets,o=n.displacementFwd,u=n.displacementBwd,c=n.padding,d=n.internalResolutionHeightAndWidth,p=i.shape,m=p[0],_=p[1],[4,i.data()];case 1:return y=R.sent(),i.dispose(),[4,I0([s,a,o,u])];case 2:return b=R.sent(),S=b[0],w=b[1],x=b[2],E=b[3],I=A0(I=C0(S,w,x,E,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[m,_],d,c,!1),s.dispose(),a.dispose(),o.dispose(),u.dispose(),[2,{height:m,width:_,data:y,allPoses:I}]}})})},r.prototype.segmentMultiPersonParts=function(e,t){return t===void 0&&(t=N0),Mt(this,void 0,void 0,function(){var n,i,s,a,o,u,c,d,p,m,_,y,b,S,w,x,E,I,R,P,B,O,F=this;return Lt(this,function(D){switch(D.label){case 0:return PO(t=gr(gr({},N0),t)),n=Qf(e),i=n[0],s=n[1],a=E0(t.internalResolution,this.baseModel.outputStride,[i,s]),o=x0(e,a),u=o.resized,c=o.padding,d=bt(function(){var L=F.predictForMultiPersonInstanceSegmentationAndPart(u),G=L.segmentLogits,j=L.longOffsets,te=L.heatmapScores,W=L.offsets,Q=L.displacementFwd,oe=L.displacementBwd,Ce=L.partHeatmaps,fe=Yc(G,[i,s],a,[[c.top,c.bottom],[c.left,c.right]],!0),ne=Yc(Ce,[i,s],a,[[c.top,c.bottom],[c.left,c.right]],!0),ae=j,be=S0(Ai(fe),t.segmentationThreshold),Se=function(Me){var ot=Me.shape,Ve=ot[0],q=ot[1],ue=ot[2];return bt(function(){var Ue=hO(Me),mt=kr(hl(0,ue,1,"int32"),1),$e=Yt(en(Ue,mt),"int32");return Te($e,[Ve,q])})}(ne);return{segmentation:be,longOffsets:ae,heatmapScoresRaw:te,offsetsRaw:W,displacementFwdRaw:Q,displacementBwdRaw:oe,partSegmentation:Se}}),p=d.segmentation,m=d.longOffsets,_=d.heatmapScoresRaw,y=d.offsetsRaw,b=d.displacementFwdRaw,S=d.displacementBwdRaw,w=d.partSegmentation,[4,I0([_,y,b,S])];case 1:return x=D.sent(),E=x[0],I=x[1],R=x[2],P=x[3],B=A0(B=C0(E,I,R,P,this.baseModel.outputStride,t.maxDetections,t.scoreThreshold,t.nmsRadius),[i,s],a,c,!1),[4,Ele(p,m,w,B,i,s,this.baseModel.outputStride,a,c,t.scoreThreshold,t.refineSteps,t.minKeypointScore,t.maxDetections)];case 2:return O=D.sent(),u.dispose(),p.dispose(),m.dispose(),_.dispose(),y.dispose(),b.dispose(),S.dispose(),w.dispose(),[2,O]}})})},r.prototype.dispose=function(){this.baseModel.dispose()},r}();function $le(r){return Mt(this,void 0,void 0,function(){var e,t,n,i,s,a;return Lt(this,function(o){switch(o.label){case 0:if(e=r.outputStride,t=r.quantBytes,n=r.multiplier,PR==null)throw new Error(`Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this
18332
18332
  model.`);return i=function(u,c,d){var p={1:"100",.75:"075",.5:"050"},m="model-stride"+u+".json";return d===4?IO+"float/"+p[c]+"/"+m:IO+"quant"+d+"/"+p[c]+"/"+m}(e,n,t),[4,WT(r.modelUrl||i)];case 1:return s=o.sent(),a=new Sle(s,e),[2,new FO(a)]}})})}function Dle(r){return Mt(this,void 0,void 0,function(){var e,t,n,i,s;return Lt(this,function(a){switch(a.label){case 0:if(e=r.outputStride,t=r.quantBytes,PR==null)throw new Error(`Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this
18333
- model.`);return n=function(o,u){var c="model-stride"+o+".json";return u===4?xO+"float/"+c:xO+"quant"+u+"/"+c}(e,t),[4,WT(r.modelUrl||n)];case 1:return i=a.sent(),s=new kle(i,e),[2,new FO(s)]}})})}function Ple(r){return r===void 0&&(r=RO),Mt(this,void 0,void 0,function(){return Lt(this,function(e){return(r=function(t){if((t=t||RO).architecture==null&&(t.architecture="MobileNetV1"),NO.indexOf(t.architecture)<0)throw new Error("Invalid architecture "+t.architecture+". Should be one of "+NO);if(t.outputStride==null&&(t.outputStride=16),kO[t.architecture].indexOf(t.outputStride)<0)throw new Error("Invalid outputStride "+t.outputStride+". Should be one of "+kO[t.architecture]+" for architecture "+t.architecture+".");if(t.multiplier==null&&(t.multiplier=1),OO[t.architecture].indexOf(t.multiplier)<0)throw new Error("Invalid multiplier "+t.multiplier+". Should be one of "+OO[t.architecture]+" for architecture "+t.architecture+".");if(t.quantBytes==null&&(t.quantBytes=4),$O.indexOf(t.quantBytes)<0)throw new Error("Invalid quantBytes "+t.quantBytes+". Should be one of "+$O+" for architecture "+t.architecture+".");return t}(r)).architecture==="ResNet50"?[2,Dle(r)]:r.architecture==="MobileNetV1"?[2,$le(r)]:[2,null]})})}var JT=["left_face","right_face","left_upper_arm_front","left_upper_arm_back","right_upper_arm_front","right_upper_arm_back","left_lower_arm_front","left_lower_arm_back","right_lower_arm_front","right_lower_arm_back","left_hand","right_hand","torso_front","torso_back","left_upper_leg_front","left_upper_leg_back","right_upper_leg_front","right_upper_leg_back","left_lower_leg_front","left_lower_leg_back","right_lower_leg_front","right_lower_leg_back","left_feet","right_feet"],MO=function(){function r(e){this.mask=e}return r.prototype.toCanvasImageSource=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,jT(this.mask)]})})},r.prototype.toImageData=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,this.mask]})})},r.prototype.toTensor=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,dO(this.mask)]})})},r.prototype.getUnderlyingType=function(){return"imagedata"},r}();function Fle(r){if(b0(r),r!==255)throw new Error("Foreground id must be 255 but got "+r);return"person"}function Mle(r){if(b0(r),r>=JT.length)throw new Error("Invalid body part value "+r);return JT[r]}var Lle=function(){function r(e){this.bodyPixModel=e}return r.prototype.segmentPeople=function(e,t){return Mt(this,void 0,void 0,function(){var n,i,s,a;return Lt(this,function(o){switch(o.label){case 0:return e instanceof ImageBitmap&&((n=document.createElement("canvas")).getContext("2d").drawImage(e,0,0),e=n),t.segmentBodyParts?t.multiSegmentation?[4,this.bodyPixModel.segmentMultiPersonParts(e,t)]:[3,2]:[3,5];case 1:return s=o.sent(),[3,4];case 2:return[4,this.bodyPixModel.segmentPersonParts(e,t)];case 3:s=[o.sent()],o.label=4;case 4:return i=s.map(function(u){var c=u.data,d=u.width,p=u.height,m=new Uint8ClampedArray(d*p*4).fill(0);return c.forEach(function(_,y){_===-1?(m[4*y]=JT.length,m[4*y+3]=0):(m[4*y]=_,m[4*y+3]=255)}),{maskValueToLabel:Mle,mask:new MO(new ImageData(m,d,p))}}),[3,10];case 5:return t.multiSegmentation?[4,this.bodyPixModel.segmentMultiPerson(e,t)]:[3,7];case 6:return a=o.sent(),[3,9];case 7:return[4,this.bodyPixModel.segmentPerson(e,t)];case 8:a=[o.sent()],o.label=9;case 9:i=a.map(function(u){var c=u.data,d=u.width,p=u.height,m=new Uint8ClampedArray(d*p*4).fill(0);return c.forEach(function(_,y){_===0?(m[4*y]=0,m[4*y+3]=0):(m[4*y]=255,m[4*y+3]=255)}),{maskValueToLabel:Fle,mask:new MO(new ImageData(m,d,p))}}),o.label=10;case 10:return[2,i]}})})},r.prototype.dispose=function(){this.bodyPixModel.dispose()},r.prototype.reset=function(){},r}();function Ule(r){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,Ple(r).then(function(t){return new Lle(t)})]})})}var LO={runtime:"mediapipe",modelType:"general"},Ble=function(){function r(e){this.mask=e}return r.prototype.toCanvasImageSource=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,this.mask]})})},r.prototype.toImageData=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,cO(this.mask)]})})},r.prototype.toTensor=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,dO(this.mask)]})})},r.prototype.getUnderlyingType=function(){return"canvasimagesource"},r}();function Hle(r){return b0(r),"person"}var Vle=function(){function r(e){var t,n=this;this.selfieMode=!1;var i;this.selfieSegmentationSolution=new vle.SelfieSegmentation({locateFile:(t=e.locateFile)!==null&&t!==void 0?t:function(s,a){return e.solutionPath?e.solutionPath.replace(/\/+$/,"")+"/"+s:a+"/"+s}}),e.modelType==="landscape"?i=1:i=0,this.selfieSegmentationSolution.setOptions({modelSelection:i,selfieMode:this.selfieMode}),this.selfieSegmentationSolution.onResults(function(s){n.segmentation=[{maskValueToLabel:Hle,mask:new Ble(s.segmentationMask)}]})}return r.prototype.segmentPeople=function(e,t){return Mt(this,void 0,void 0,function(){var n,i;return Lt(this,function(s){switch(s.label){case 0:return t&&t.flipHorizontal&&t.flipHorizontal!==this.selfieMode&&(this.selfieMode=t.flipHorizontal,this.selfieSegmentationSolution.setOptions({selfieMode:this.selfieMode})),e instanceof tn?(i=ImageData.bind,[4,kf(e)]):[3,2];case 1:return n=new(i.apply(ImageData,[void 0,s.sent(),e.shape[1],e.shape[0]])),[3,3];case 2:n=e,s.label=3;case 3:return e=n,[4,this.selfieSegmentationSolution.send({image:e})];case 4:return s.sent(),[2,this.segmentation]}})})},r.prototype.dispose=function(){this.selfieSegmentationSolution.close()},r.prototype.reset=function(){this.selfieSegmentationSolution.reset(),this.segmentation=null,this.selfieMode=!1},r.prototype.initialize=function(){return this.selfieSegmentationSolution.initialize()},r}();function Gle(r){return Mt(this,void 0,void 0,function(){var e,t;return Lt(this,function(n){switch(n.label){case 0:return e=function(i){if(i==null)return gr({},LO);var s=gr({},i);return s.runtime="mediapipe",s.modelType==null&&(s.modelType=LO.modelType),s}(r),[4,(t=new Vle(e)).initialize()];case 1:return n.sent(),[2,t]}})})}function Wle(r,e,t,n){var i=r.width,s=r.height,a=n?-1:1,o=Math.cos(r.rotation),u=Math.sin(r.rotation),c=r.xCenter,d=r.yCenter,p=1/e,m=1/t,_=new Array(16);return _[0]=i*o*a*p,_[1]=-s*u*p,_[2]=0,_[3]=(-.5*i*o*a+.5*s*u+c)*p,_[4]=i*u*a*m,_[5]=s*o*m,_[6]=0,_[7]=(-.5*s*o-.5*i*u*a+d)*m,_[8]=0,_[9]=0,_[10]=i*p,_[11]=0,_[12]=0,_[13]=0,_[14]=0,_[15]=1,function(y){if(y.length!==16)throw new Error("Array length must be 16 but got "+y.length);return[[y[0],y[1],y[2],y[3]],[y[4],y[5],y[6],y[7]],[y[8],y[9],y[10],y[11]],[y[12],y[13],y[14],y[15]]]}(_)}function UO(r){return r instanceof tn?{height:r.shape[0],width:r.shape[1]}:{height:r.height,width:r.width}}function QT(r,e){V(r.width!==0,function(){return e+" width cannot be 0."}),V(r.height!==0,function(){return e+" height cannot be 0."})}function zle(r,e){var t=function(n,i,s,a){var o=i-n,u=a-s;if(o===0)throw new Error("Original min and max are both "+n+", range cannot be 0.");var c=u/o;return{scale:c,offset:s-n*c}}(0,255,e[0],e[1]);return bt(function(){return St(Ye(r,t.scale),t.offset)})}function jle(r,e,t){var n=e.outputTensorSize,i=e.keepAspectRatio,s=e.borderMode,a=e.outputTensorFloatRange,o=UO(r),u=function(m,_){return _?{xCenter:_.xCenter*m.width,yCenter:_.yCenter*m.height,width:_.width*m.width,height:_.height*m.height,rotation:_.rotation}:{xCenter:.5*m.width,yCenter:.5*m.height,width:m.width,height:m.height,rotation:0}}(o,t),c=function(m,_,y){if(y===void 0&&(y=!1),!y)return{top:0,left:0,right:0,bottom:0};var b=_.height,S=_.width;QT(_,"targetSize"),QT(m,"roi");var w,x,E=b/S,I=m.height/m.width,R=0,P=0;return E>I?(w=m.width,x=m.width*E,P=(1-I/E)/2):(w=m.height/E,x=m.height,R=(1-E/I)/2),m.width=w,m.height=x,{top:P,left:R,right:R,bottom:P}}(u,n,i),d=Wle(u,o.width,o.height,!1),p=bt(function(){var m,_=(m=r)instanceof tn?m:G_(m),y=Iu(function(w,x,E){return QT(E,"inputResolution"),[1/E.width*w[0][0]*x.width,1/E.height*w[0][1]*x.width,w[0][3]*x.width,1/E.width*w[1][0]*x.height,1/E.height*w[1][1]*x.height,w[1][3]*x.height,0,0]}(d,o,n),[1,8]),b=s==="zero"?"constant":"nearest",S=Au.transform(kr(Yt(_,"float32")),y,"bilinear",b,0,[n.height,n.width]);return a!=null?zle(S,a):S});return{imageTensor:p,padding:c,transformationMatrix:d}}function qle(r,e,t){return bt(function(){var n=Ai(r,[0]),i=n.shape[2];if(i===1){var s=n;switch(e.activation){case"none":break;case"sigmoid":s=Oa(s);break;case"softmax":throw new Error("Softmax activation requires two channels.");default:throw new Error("Activation not supported ("+e.activation+")")}var a=t?Au.resizeBilinear(s,[t.height,t.width]):s;return Ai(a,[2])}throw new Error("Unsupported number of tensor channels "+i)})}var BO={runtime:"tfjs",modelType:"general",modelUrl:"https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1"},HO={flipHorizontal:!1},Kle={outputTensorSize:{width:256,height:256},keepAspectRatio:!1,borderMode:"zero",outputTensorFloatRange:[0,1]},Xle={outputTensorSize:{width:256,height:144},keepAspectRatio:!1,borderMode:"zero",outputTensorFloatRange:[0,1]},Yle={activation:"none"},Jle=function(){function r(e){this.mask=e}return r.prototype.toCanvasImageSource=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,jT(this.mask)]})})},r.prototype.toImageData=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,cO(this.mask)]})})},r.prototype.toTensor=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,this.mask]})})},r.prototype.getUnderlyingType=function(){return"tensor"},r}();function Qle(r){return b0(r),"person"}var ep,Zle=function(){function r(e,t){this.modelType=e,this.model=t}return r.prototype.segmentPeople=function(e,t){return Mt(this,void 0,void 0,function(){var n,i=this;return Lt(this,function(s){return t=function(a){if(a==null)return gr({},HO);var o=gr({},a);return o.flipHorizontal==null&&(o.flipHorizontal=HO.flipHorizontal),o}(t),e==null?(this.reset(),[2,[]]):(n=bt(function(){var a=jle(e,i.modelType==="general"?Kle:Xle).imageTensor,o=un(i.model.predict(a),[0,0,0,1],-1),u=UO(e),c=qle(o,Yle,u),d=kr(c,2),p=Eu(d,[[0,0],[0,0],[0,1]]);return jb(p,[[0,0],[0,0],[0,2]],"symmetric")}),[2,[{maskValueToLabel:Qle,mask:new Jle(n)}]])})})},r.prototype.dispose=function(){this.model.dispose()},r.prototype.reset=function(){},r}();function eue(r){return Mt(this,void 0,void 0,function(){var e,t,n;return Lt(this,function(i){switch(i.label){case 0:return e=function(s){if(s==null)return gr({},BO);var a=gr({},s);if(a.runtime="tfjs",a.modelType==null&&(a.modelType=BO.modelType),a.modelType!=="general"&&a.modelType!=="landscape")throw new Error("Model type must be one of general or landscape, but got "+a.modelType);return a.modelUrl==null&&(a.modelType==="general"?a.modelUrl="https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1":a.modelUrl="https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/landscape/1"),a}(r),t=typeof e.modelUrl=="string"&&e.modelUrl.indexOf("https://tfhub.dev")>-1,[4,WT(e.modelUrl,{fromTFHub:t})];case 1:return n=i.sent(),[2,new Zle(e.modelType,n)]}})})}function tue(r,e){return Mt(this,void 0,void 0,function(){var t,n;return Lt(this,function(i){switch(r){case ep.MediaPipeSelfieSegmentation:if(t=void 0,(n=e)!=null){if(n.runtime==="tfjs")return[2,eue(n)];if(n.runtime==="mediapipe")return[2,Gle(n)];t=n.runtime}throw new Error("Expect modelConfig.runtime to be either 'tfjs' or 'mediapipe', but got "+t);case ep.BodyPix:return[2,Ule(n=e)];default:throw new Error(r+" is not a supported model name.")}})})}(function(r){r.BodyPix="BodyPix",r.MediaPipeSelfieSegmentation="MediaPipeSelfieSegmentation"})(ep||(ep={}));var nue="blurred",sue="blurred-mask",rue="mask",iue="draw-image",ZT={};function k0(r){if(typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return function(e){if("offsetHeight"in e&&e.offsetHeight!==0&&"offsetWidth"in e&&e.offsetWidth!==0)return[e.offsetHeight,e.offsetWidth];if(e.height!=null&&e.width!=null)return[e.height,e.width];throw new Error("HTMLImageElement must have height and width attributes set.")}(r);if(typeof ImageData<"u"&&r instanceof ImageData)return[r.height,r.width];if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return function(e){return e.hasAttribute("height")&&e.hasAttribute("width")?[e.height,e.width]:[e.videoHeight,e.videoWidth]}(r);if(r instanceof tn)return[r.shape[0],r.shape[1]];throw new Error("error: Unknown input type: "+r+".")}function VO(r){return ZT[r]||(ZT[r]=function(){if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(0,0);throw new Error("Cannot create a canvas in this context")}()),ZT[r]}function GO(r,e){var t=VO(e);return function(n,i){i.width=n.width,i.height=n.height,i.getContext("2d").putImageData(n,0,0)}(r,t),t}function tp(r,e,t,n,i,s){return Mt(this,void 0,void 0,function(){var a,o,u,c;return Lt(this,function(d){switch(d.label){case 0:return e instanceof tn?[4,kf(e)]:[3,2];case 1:a=d.sent(),o=k0(e),u=o[0],c=o[1],e=new ImageData(a,c,u),d.label=2;case 2:return e instanceof ImageData&&(e=GO(e,iue)),i==null||s==null?r.drawImage(e,t,n):r.drawImage(e,t,n,i,s),[2]}})})}function aue(r,e){return Mt(this,void 0,void 0,function(){var t,n,i;return Lt(this,function(s){switch(s.label){case 0:return t=k0(r),n=t[0],i=t[1],e.width=i,e.height=n,[4,tp(e.getContext("2d"),r,0,0,i,n)];case 1:return s.sent(),[2]}})})}function oue(r){var e=r.getContext("2d");e.scale(-1,1),e.translate(-r.width,0)}function WO(r,e,t){return Mt(this,void 0,void 0,function(){return Lt(this,function(n){switch(n.label){case 0:return r.globalCompositeOperation=t,[4,tp(r,e,0,0)];case 1:return n.sent(),[2]}})})}function lue(r,e,t){return Mt(this,void 0,void 0,function(){var n,i,s,a,o,u,c,d;return Lt(this,function(p){switch(p.label){case 0:for(n=r.getContext("2d"),i=0,s=5,a=1/(2*Math.PI*s*s),o=t<3?1:2,c=-t;c<=t;c+=o)for(d=-t;d<=t;d+=o)u=a*Math.exp(-(d*d+c*c)/(2*s*s)),i+=u;c=-t,p.label=1;case 1:if(!(c<=t))return[3,6];d=-t,p.label=2;case 2:return d<=t?(n.globalAlpha=a*Math.exp(-(d*d+c*c)/(2*s*s))/i*t,[4,tp(n,e,d,c)]):[3,5];case 3:p.sent(),p.label=4;case 4:return d+=o,[3,2];case 5:return c+=o,[3,1];case 6:return n.globalAlpha=1,[2]}})})}function uue(r,e,t){return Mt(this,void 0,void 0,function(){var n,i,s,a;return Lt(this,function(o){switch(o.label){case 0:return n=k0(r),i=n[0],s=n[1],a=t.getContext("2d"),t.width=s,t.height=i,a.clearRect(0,0,s,i),a.save(),/^((?!chrome|android).)*safari/i.test(navigator.userAgent)?[4,lue(t,r,e)]:[3,2];case 1:return o.sent(),[3,4];case 2:return a.filter="blur("+e+"px)",[4,tp(a,r,0,0,s,i)];case 3:o.sent(),o.label=4;case 4:return a.restore(),[2]}})})}function zO(r,e,t){return Mt(this,void 0,void 0,function(){var n;return Lt(this,function(i){switch(i.label){case 0:return n=VO(t),e!==0?[3,2]:[4,aue(r,n)];case 1:return i.sent(),[3,4];case 2:return[4,uue(r,e,n)];case 3:i.sent(),i.label=4;case 4:return[2,n]}})})}function cue(r,e,t,n,i,s){s===void 0&&(s={r:0,g:255,b:255,a:255});for(var a=-i;a<=i;a++)for(var o=-i;o<=i;o++)if(a!==0&&o!==0){var u=(e+a)*n+(t+o);r[4*u+0]=s.r,r[4*u+1]=s.g,r[4*u+2]=s.b,r[4*u+3]=s.a}}function due(r,e,t,n,i,s,a){a===void 0&&(a=1);for(var o=0,u=-a;u<=a;u++)for(var c=-a;c<=a;c++)if(u!==0&&c!==0){var d=(e+u)*n+(t+c);(!i[r[4*d]]||r[4*d+3]<s)&&(o+=1)}return o>0}function jO(r,e,t,n,i,s){return e===void 0&&(e={r:0,g:0,b:0,a:0}),t===void 0&&(t={r:0,g:0,b:0,a:255}),n===void 0&&(n=!1),i===void 0&&(i=.5),s===void 0&&(s=Array.from(Array(256).keys())),Mt(this,void 0,void 0,function(){var a,o,u,c,d,p,m,_,y,b,S,w,x,E;return Lt(this,function(I){switch(I.label){case 0:return(a=Array.isArray(r)?r:[r]).length===0?[2,null]:[4,Promise.all(a.map(function(R){return R.mask.toImageData()}))];case 1:for(o=I.sent(),u=o[0],c=u.width,d=u.height,p=new Uint8ClampedArray(c*d*4),m=Math.round(255*i),_=new Array(256).fill(!1),s.forEach(function(R){return _[R]=!0}),y=0;y<d;y++)for(b=0;b<c;b++)for(p[4*(S=y*c+b)+0]=t.r,p[4*S+1]=t.g,p[4*S+2]=t.b,p[4*S+3]=t.a,w=0,x=o;w<x.length;w++)E=x[w],_[E.data[4*S]]&&E.data[4*S+3]>=m&&(p[4*S]=e.r,p[4*S+1]=e.g,p[4*S+2]=e.b,p[4*S+3]=e.a,n&&y-1>=0&&y+1<d&&b-1>=0&&b+1<c&&due(E.data,y,b,c,_,m)&&cue(p,y,b,c,1));return[2,new ImageData(p,c,d)]}})})}function hue(r,e,t){return Mt(this,void 0,void 0,function(){var n,i;return Lt(this,function(s){switch(s.label){case 0:return[4,jO(r,{r:0,g:0,b:0,a:255},{r:0,g:0,b:0,a:0},!1,e)];case 1:return n=s.sent(),i=GO(n,rue),t===0?[2,i]:[2,zO(i,t,sue)]}})})}function fue(r,e,t,n,i,s,a){return n===void 0&&(n=.5),i===void 0&&(i=3),s===void 0&&(s=3),a===void 0&&(a=!1),Mt(this,void 0,void 0,function(){var o,u,c,d,p,m;return Lt(this,function(_){switch(_.label){case 0:return[4,zO(e,i,nue)];case 1:return o=_.sent(),r.width=o.width,r.height=o.height,u=r.getContext("2d"),Array.isArray(t)&&t.length===0?(u.drawImage(o,0,0),[2]):[4,hue(t,n,s)];case 2:return c=_.sent(),u.save(),a&&oue(r),d=k0(e),p=d[0],m=d[1],[4,tp(u,e,0,0,m,p)];case 3:return _.sent(),[4,WO(u,c,"destination-in")];case 4:return _.sent(),[4,WO(u,o,"destination-over")];case 5:return _.sent(),u.restore(),[2]}})})}const qO={runtime:"mediapipe",modelType:"general"},pue={WEBGL_PACK:!0,WEBGL_VERSION:2,WEBGL_CPU_FORWARD:!1},mue={targetFPS:60},gue={foregroundThreshold:.5,maskOpacity:.7,maskBlur:0,pixelCellWidth:10,backgroundBlur:15,edgeBlur:3},ew={WEBGL_VERSION:[1,2],WASM_HAS_SIMD_SUPPORT:[!0,!1],WASM_HAS_MULTITHREAD_SUPPORT:[!0,!1],WEBGL_CPU_FORWARD:[!0,!1],WEBGL_PACK:[!0,!1],WEBGL_FORCE_F16_TEXTURES:[!0,!1],WEBGL_RENDER_FLOAT32_CAPABLE:[!0,!1],WEBGL_FLUSH_THRESHOLD:[-1,0,.25,.5,.75,1,1.25,1.5,1.75,2],CHECK_COMPUTATION_FOR_ERRORS:[!0,!1]},tw={bokehEffect:"bokehEffect",backgroundImageEffect:"backgroundImageEffect"};async function _ue(r){if(r!=null){if(typeof r!="object")throw new Error(`An object is expected, while a(n) ${typeof r} is found.`);for(const e in r){if(!(e in ew))throw new Error(`${e} is not a tunable or valid environment flag.`);if(ew[e].indexOf(r[e])===-1)throw new Error(`${e} value is expected to be in the range [${ew[e]}], while ${r[e]} is found.`)}de().setFlags(r)}}class nw{constructor(){this.video=null,this.canvas=null,this.wrapperEl=null,this.ctx=null;const e=document.createElement("video");e.setAttribute("id","video"),e.setAttribute("playsinline",""),e.style.setProperty("visibility","hidden"),e.style.setProperty("width","auto"),e.style.setProperty("height","auto"),this.video=e;const t=document.createElement("canvas");t.setAttribute("id","output"),t.style.setProperty("visibility","hidden"),this.canvas=t;const n=document.createElement("div");n.classList.add("canvas-wrapper"),n.style.setProperty("display","none"),n.appendChild(e),n.appendChild(t),this.wrapperEl=n,document.body.appendChild(n),this.ctx=this.canvas.getContext("2d")}static async setupCamera(e){e.getAudioTracks().forEach(s=>{s.stop(),e.removeTrack(s)});const t=new nw;t.video.srcObject=e,t.video.volume=0,await new Promise(s=>{t.video.onloadedmetadata=()=>{s(t.video)}}),t.video.play();const n=t.video.videoWidth,i=t.video.videoHeight;return t.video.width=n,t.video.height=i,t.canvas.width=n,t.canvas.height=i,t.wrapperEl.style.setProperty("width",`${n}px`),t.wrapperEl.style.setProperty("height",`${i}px`),t}cleanCamera(){this.ctx=null,this.wrapperEl.remove()}drawToCanvas(e){this.ctx.drawImage(e,0,0,this.video.videoWidth,this.video.videoHeight)}drawFromVideo(e){e.drawImage(this.video,0,0,this.video.videoWidth,this.video.videoHeight)}clearCtx(){this.ctx.clearRect(0,0,this.video.videoWidth,this.video.videoHeight)}}function KO(r,e={}){const t={};return Object.keys(r).forEach(n=>{t[n]=e[n]!==void 0?e[n]:r[n]}),t}function yue(r){return new Promise((e,t)=>{const n=new Image;n.onload=()=>{e(n)},n.onerror=i=>{t(i)},n.src=r})}function vue(r){return setTimeout(r,1e3/30)}class XO{constructor(e){this.opensips=null,this.session=null,this.name=null,this.name=e}setOpensips(e){this.opensips=e}setSession(e){this.session=e}kill(){this.opensips.kill(this.name)}}class O0 extends XO{constructor(e,t,n={}){super(e),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=n.immediate||!1,this.type=t}start(e){return e}stop(){throw new Error("stop method is not implemented")}async process(e){if(this.immediate){const t=await this.start(e);return this.running=!0,t}return e}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}loe(`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${coe}/dist/`);class bue extends O0{constructor(e,t){super("StreamMask","video",t),this.visualizationConfig={},this.maskEffectType=null,this.base64ImageMask=null,this.rafId=null,this.timeoutId=null,this.segmenter=null,this.visibilityState=null;const{visualizationConfig:n,effect:i,base64Image:s}=e;if(this.visualizationConfig=KO(gue,n),i===tw.backgroundImageEffect&&!s)throw new Error("Error when starting mask effect: base64Image option is required for backgroundImageEffect effect type");s&&(this.base64ImageMask=s),this.maskEffectType=i}async start(e){this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.camera=await nw.setupCamera(e),this.canvas.width=this.camera.canvas.width,this.canvas.height=this.camera.canvas.height,await _ue(pue),this.segmenter=await this.createSegmenter(),this.processVisibilityChange(),this.renderPrediction();const t=this.canvas.captureStream(mue.targetFPS);return await this.populateWithAudioTracks(t,e.getAudioTracks())}processVisibilityChange(){document&&(this.visibilityState=document.visibilityState,document.addEventListener("visibilitychange",()=>{this.visibilityState=document.visibilityState,document.visibilityState==="hidden"&&this.renderPrediction()}))}async populateWithAudioTracks(e,t){const n=new MediaStream;return e.getVideoTracks().forEach(i=>{n.addTrack(i)}),t.forEach(i=>{n.addTrack(i)}),n}stop(){this.rafId&&window.cancelAnimationFrame(this.rafId),this.timeoutId&&clearTimeout(this.timeoutId),this.segmenter&&this.segmenter.dispose(),this.camera&&this.camera.cleanCamera(),this.rafId=null,this.timeoutId=null,this.segmenter=null,this.camera=null,this.canvas=null,this.ctx=null}setupVisualizationConfig(e){this.visualizationConfig=KO(this.visualizationConfig,e)}async renderPrediction(){await this.renderResult(),this.visibilityState==="visible"?(this.timeoutId&&clearTimeout(this.timeoutId),this.rafId=requestAnimationFrame(this.renderPrediction.bind(this))):(this.rafId&&window.cancelAnimationFrame(this.rafId),this.timeoutId=vue(this.renderPrediction.bind(this)))}async createSegmenter(){return tue(ep.MediaPipeSelfieSegmentation,{runtime:qO.runtime,modelType:qO.modelType,solutionPath:"https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation@0.1.1675465747"})}async renderResult(){this.camera.video.readyState<2&&await new Promise(t=>{this.camera.video.onloadeddata=()=>{t(this.camera.video)}});let e=null;if(this.segmenter!=null){try{this.segmenter.segmentPeople!=null?e=await this.segmenter.segmentPeople(this.camera.video,{flipHorizontal:!1,multiSegmentation:!1,segmentBodyParts:!0,segmentationThreshold:this.visualizationConfig.foregroundThreshold}):(e=await this.segmenter.estimatePoses(this.camera.video,{flipHorizontal:!1}),e=e.map(n=>n.segmentation))}catch(n){this.segmenter.dispose(),this.segmenter=null,alert(n)}const t=window.exposedContext;t&&t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array(4))}if(e&&e.length>0)switch(this.maskEffectType){case tw.bokehEffect:console.log("applyBokehEffect"),await this.applyBokehEffect(e);break;case tw.backgroundImageEffect:await this.applyBackgroundImageEffect(e);break;default:console.error("Error when applying mask effect: such mask effect doesn't exist")}this.camera.drawToCanvas(this.canvas)}async applyBokehEffect(e){const t=this.visualizationConfig;await fue(this.canvas,this.camera.video,e,t.foregroundThreshold,t.backgroundBlur,t.edgeBlur)}async applyBackgroundImageEffect(e){const t=this.base64ImageMask,n=new Image;n.src=t;const i=this.canvas.getContext("2d"),a=await jO(e,{r:0,g:0,b:0,a:0},{r:0,g:0,b:0,a:255});a&&(i.putImageData(a,0,0),i.globalCompositeOperation="source-in",n.complete?i.drawImage(n,0,0,this.canvas.width,this.canvas.height):n.onload=()=>{i.drawImage(n,0,0,this.canvas.width,this.canvas.height)},i.globalCompositeOperation="destination-over",i.drawImage(this.camera.video,0,0,this.canvas.width,this.canvas.height),i.globalCompositeOperation="source-over")}}const Ie=new fm("JanusSession"),Sue="/opt/recordings/",Oe={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},$0=["audio","video"];class D0 extends Is.EventEmitter{static get C(){return Oe}constructor(e){Ie.debug("new"),super(),console.log("constructor call"),this._id=null,this._ua=e,this._status=Oe.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:ye.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0}get C(){return Oe}get causes(){return ye.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(e){this._data=e}get status(){return this._status}isInProgress(){switch(this._status){case Oe.STATUS_NULL:case Oe.STATUS_INVITE_SENT:case Oe.STATUS_1XX_RECEIVED:case Oe.STATUS_INVITE_RECEIVED:case Oe.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case Oe.STATUS_ANSWERED:case Oe.STATUS_WAITING_FOR_ACK:case Oe.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case Oe.STATUS_CANCELED:case Oe.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(e){return`PTYPE: ${e}`}generateOpaqueId(){return`videoroomtest-${bE().replace(/-/g,"").slice(0,12)}`}connect(e,t,n={},i){Ie.debug("connect()"),this.display_name=t;const s=e,a=Xt.cloneObject(n.eventHandlers),o=Xt.cloneArray(n.extraHeaders),u=Xt.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),c=n.mediaStream||null,d=Xt.cloneObject(n.pcConfig,{iceServers:[]}),p=n.rtcConstraints||null,m=n.rtcOfferConstraints||null;if(this._rtcOfferConstraints=m,this._rtcAnswerConstraints=n.rtcAnswerConstraints||null,this._data=n.data||this._data,e===void 0)throw new TypeError("Not enough arguments");if(this._status!==Oe.STATUS_NULL)throw new Xo.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Xo.NotSupportedError("WebRTC not supported");if(console.log("target",e),e=this._ua.normalizeTarget(e),console.log("normalizeTarget target",e),this.room_id=e.user,this.target=e,!e)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&Xt.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=ye.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=ye.SESSION_EXPIRES);for(const b in a)Object.prototype.hasOwnProperty.call(a,b)&&this.on(b,a[b]);this._from_tag=Xt.newTag();const _=n.anonymous||!1,y={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:_,outbound:!0}),_?(y.from_display_name="Anonymous",y.from_uri=new Zo("sip","anonymous","anonymous.invalid"),o.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),o.push("Privacy: id")):n.fromUserName&&(y.from_uri=new Zo("sip",n.fromUserName,this._ua.configuration.uri.host),o.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(y.from_display_name=n.fromDisplayName),o.push(`Contact: ${this._contact}`),o.push("Content-Type: application/json"),this._sessionTimers.enabled&&o.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Rs.InitialOutgoingInviteRequest(e,this._ua,y,o),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(d,p),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,console.log("this._remote_identity",this._remote_identity),i&&i(this),this._newJanusSession("local",this._request),this._sendInitialRequest(u,m,c)}connectScreenShare(e={}){new f8(this).connect(e)}_overrideSenderTracks(e,t){e.getTracks().forEach(n=>{t.getSenders().forEach(async s=>{s.track.kind===n.kind&&(n.kind==="audio"&&!this.isAudioOn&&(n.enabled=!1),n.kind==="video"&&!this.isVideoOn&&(n.enabled=!1),await s.replaceTrack(n))})})}init_incoming(e,t){Ie.debug("init_incoming()");let n;const i=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0;if(e.body&&i!=="application/sdp"){e.reply(415);return}if(this._status=Oe.STATUS_INVITE_RECEIVED,this._from_tag=e.from_tag,this._id=e.call_id+this._from_tag,this._request=e,this._contact=this._ua.contact.toString(),e.hasHeader("expires")&&(n=e.getHeader("expires")*1e3),e.to_tag=Xt.newTag(),!this._createDialog(e,"UAS",!0)){e.reply(500,"Missing Contact header field");return}e.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Oe.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{e.reply(408),this._failed("local",null,ye.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),n&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Oe.STATUS_WAITING_FOR_ANSWER&&(e.reply(487),this._failed("system",null,ye.causes.EXPIRES))},n)),this._direction="incoming",this._local_identity=e.to,this._remote_identity=e.from,t&&t(this),this._newJanusSession("remote",e),this._status!==Oe.STATUS_TERMINATED&&(e.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(e={}){Ie.debug("answer()");const t=this._request,n=Xt.cloneArray(e.extraHeaders),i=Xt.cloneObject(e.mediaConstraints),s=e.mediaStream||null,a=Xt.cloneObject(e.pcConfig,{iceServers:[]}),o=e.rtcConstraints||null,u=e.rtcAnswerConstraints||null,c=Xt.cloneObject(e.rtcOfferConstraints);let d,p=!1,m=!1,_=!1,y=!1;if(this._rtcAnswerConstraints=u,this._rtcOfferConstraints=e.rtcOfferConstraints||null,this._data=e.data||this._data,this._direction!=="incoming")throw new Xo.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Oe.STATUS_WAITING_FOR_ANSWER)throw new Xo.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Xt.isDecimal(e.sessionTimersExpires)&&(e.sessionTimersExpires>=ye.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=e.sessionTimersExpires:this._sessionTimers.defaultExpires=ye.SESSION_EXPIRES),this._status=Oe.STATUS_ANSWERED,!this._createDialog(t,"UAS")){t.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),n.unshift(`Contact: ${this._contact}`);const b=t.parseSDP();Array.isArray(b.media)||(b.media=[b.media]);for(const S of b.media)S.type==="audio"&&(p=!0,(!S.direction||S.direction==="sendrecv")&&(_=!0)),S.type==="video"&&(m=!0,(!S.direction||S.direction==="sendrecv")&&(y=!0));if(s&&i.audio===!1){d=s.getAudioTracks();for(const S of d)s.removeTrack(S)}if(s&&i.video===!1){d=s.getVideoTracks();for(const S of d)s.removeTrack(S)}!s&&i.audio===void 0&&(i.audio=_),!s&&i.video===void 0&&(i.video=y),!s&&!p&&!c.offerToReceiveAudio&&(i.audio=!1),!s&&!m&&!c.offerToReceiveVideo&&(i.video=!1),this._createRTCConnection(a,o),Promise.resolve().then(()=>{if(s)return s;if(i.audio||i.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(i).catch(S=>{throw this._status===Oe.STATUS_TERMINATED?new Error("terminated"):(t.reply(480),this._failed("local",null,ye.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',S),this.emit("getusermediafailed",S),new Error("getUserMedia() failed"))})}).then(S=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=S,S&&S.getTracks().forEach(w=>{this._connection.addTrack(w,S)})}).then(()=>{if(this._late_sdp)return;const S={originator:"remote",type:"offer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",S);const w=new RTCSessionDescription({type:"offer",sdp:S.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(w)).catch(x=>{throw t.reply(488),this._failed("system",null,ye.causes.WEBRTC_ERROR),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',x),this.emit("peerconnection:setremotedescriptionfailed",x),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(t),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw t.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",u).catch(()=>{throw t.reply(500),new Error("_createLocalDescription() failed")})}).then(S=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(t,n),t.reply(200,null,n,S,()=>{this._status=Oe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,S),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,ye.causes.CONNECTION_ERROR)})}).catch(S=>{this._status!==Oe.STATUS_TERMINATED&&Ie.warn(S)})}terminate(e={}){Ie.debug("terminate()");const t=e.cause||ye.causes.BYE,n=Xt.cloneArray(e.extraHeaders),i=e.body;let s,a=e.status_code,o=e.reason_phrase;if(this._status===Oe.STATUS_TERMINATED)throw new Xo.InvalidStateError(this._status);switch(this._status){case Oe.STATUS_NULL:case Oe.STATUS_INVITE_SENT:case Oe.STATUS_1XX_RECEIVED:if(Ie.debug("canceling session"),a&&(a<200||a>=700))throw new TypeError(`Invalid status_code: ${a}`);a&&(o=o||ye.REASON_PHRASE[a]||"",s=`SIP ;cause=${a} ;text="${o}"`),this._status===Oe.STATUS_NULL||this._status===Oe.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Oe.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Oe.STATUS_CANCELED,this._failed("local",null,ye.causes.CANCELED);break;case Oe.STATUS_WAITING_FOR_ANSWER:case Oe.STATUS_ANSWERED:if(Ie.debug("rejecting session"),a=a||480,a<300||a>=700)throw new TypeError(`Invalid status_code: ${a}`);this._request.reply(a,o,n,i),this._failed("local",null,ye.causes.REJECTED);break;case Oe.STATUS_WAITING_FOR_ACK:case Oe.STATUS_CONFIRMED:if(Ie.debug("terminating session"),o=e.reason_phrase||ye.REASON_PHRASE[a]||"",a&&(a<200||a>=700))throw new TypeError(`Invalid status_code: ${a}`);if(a&&n.push(`Reason: SIP ;cause=${a}; text="${o}"`),this._status===Oe.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==yi.C.STATUS_TERMINATED){const u=this._dialog;this.receiveRequest=({method:c})=>{c===ye.ACK&&(this.sendRequest(ye.BYE,{extraHeaders:n,body:i}),u.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===yi.C.STATUS_TERMINATED&&(this.sendRequest(ye.BYE,{extraHeaders:n,body:i}),u.terminate(),this.closeSession())}),this._ended("local",null,t),this._dialog=u,console.log("SET DIALOG terminate"),this._ua.newDialog(u)}else{const u={janus:"leave"},c=["Content-Type: application/json",this.getPTypeHeader(lr.LEAVE)];this.sendRequest(ye.BYE,{extraHeaders:c,body:JSON.stringify(u)}),this.closeSession(),this._ended("local",null,t)}}}configureMedia(e){this.isAudioOn=e.audio,this.isVideoOn=e.video}enableAudio(e){const t={janus:"message",body:{audio:e},handle_id:this.handle_id,session_id:this.session_id},n=["Content-Type: application/json",this.getPTypeHeader(lr.AUDIO_CHANGE)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t),eventHandlers:{onSuccessResponse:async i=>{i.status_code===200&&(this._ua.emit("changeAudioState",e),this.sendStateMessage({audio:e}))}}})}startAudio(){Xi.toggleAudioMute(this.stream),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Xi.toggleAudioMute(this.stream),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(e){const t={janus:"message",body:{video:e},handle_id:this.handle_id,session_id:this.session_id},n=["Content-Type: application/json",this.getPTypeHeader(lr.VIDEO_CHANGE)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t),eventHandlers:{onSuccessResponse:async i=>{i.status_code===200&&(this._ua.emit("changeVideoState",e),this.sendStateMessage({video:e}))}}})}startVideo(){Xi.toggleVideoMute(this.stream),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Xi.toggleVideoMute(this.stream),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(e){const t={janus:"message",body:{request:"state",data:e},handle_id:this.handle_id,session_id:this.session_id},n=["Content-Type: application/json",this.getPTypeHeader(lr.STATE)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t)})}sendInfo(e,t,n={}){if(Ie.debug("sendInfo()"),this._status!==Oe.STATUS_CONFIRMED&&this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_1XX_RECEIVED)throw new Xo.InvalidStateError(this._status);new nv(this).send(e,t,n)}mute(e={audio:!0,video:!1}){Ie.debug("mute()");let t=!1,n=!1;this._audioMuted===!1&&e.audio&&(t=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&e.video&&(n=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(t===!0||n===!0)&&this._onmute({audio:t,video:n})}unmute(e={audio:!0,video:!0}){Ie.debug("unmute()");let t=!1,n=!1;this._audioMuted===!0&&e.audio&&(t=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&e.video&&(n=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(t===!0||n===!0)&&this._onunmute({audio:t,video:n})}hold(e={},t){if(Ie.debug("hold()"),this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:ye.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}unhold(e={},t){if(Ie.debug("unhold()"),this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:ye.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}renegotiate(e={},t){Ie.debug("renegotiate()");const n=e.rtcOfferConstraints||null;if(this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const i={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:ye.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:i,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:i,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}),!0}refer(e,t){Ie.debug("refer()");const n=e;if(this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED)return!1;if(e=this._ua.normalizeTarget(e),!e)throw new TypeError(`Invalid target: ${n}`);const i=new uF(this);i.sendRefer(e,t);const s=i.id;return this._referSubscribers[s]=i,i.on("requestFailed",()=>{delete this._referSubscribers[s]}),i.on("accepted",()=>{delete this._referSubscribers[s]}),i.on("failed",()=>{delete this._referSubscribers[s]}),i}sendRequest(e,t){return Ie.debug("sendRequest()"),this._dialog.sendRequest(e,t)}receiveNotify(e){Ie.debug("receiveRequest()")}receiveRequest(e){if(console.log("mmm receiveRequest 1",e),Ie.debug("receiveRequest()"),e.method===ye.CANCEL)(this._status===Oe.STATUS_WAITING_FOR_ANSWER||this._status===Oe.STATUS_ANSWERED)&&(this._status=Oe.STATUS_CANCELED,this._request.reply(487),this._failed("remote",e,ye.causes.CANCELED));else switch(e.method){case ye.ACK:if(this._status!==Oe.STATUS_WAITING_FOR_ACK)return;if(this._status=Oe.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!e.body){this.terminate({cause:ye.causes.MISSING_SDP,status_code:400});break}const t={originator:"remote",type:"answer",sdp:e.body};Ie.debug('emit "sdp"'),this.emit("sdp",t);const n=new RTCSessionDescription({type:"answer",sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>{this._is_confirmed||this._confirmed("remote",e)}).catch(i=>{this.terminate({cause:ye.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',i),this.emit("peerconnection:setremotedescriptionfailed",i)})}else this._is_confirmed||this._confirmed("remote",e);break;case ye.BYE:this._status===Oe.STATUS_CONFIRMED||this._status===Oe.STATUS_WAITING_FOR_ACK?(e.reply(200),this._ended("remote",e,ye.causes.BYE)):this._status===Oe.STATUS_INVITE_RECEIVED||this._status===Oe.STATUS_WAITING_FOR_ANSWER?(e.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",e,ye.causes.BYE)):e.reply(403,"Wrong Status");break;case ye.INVITE:console.log("mmm invite 1"),this._status===Oe.STATUS_CONFIRMED?e.hasHeader("replaces")?this._receiveReplaces(e):this._receiveReinvite(e):e.reply(403,"Wrong Status");break;case ye.INFO:if(this._status===Oe.STATUS_1XX_RECEIVED||this._status===Oe.STATUS_WAITING_FOR_ANSWER||this._status===Oe.STATUS_ANSWERED||this._status===Oe.STATUS_WAITING_FOR_ACK||this._status===Oe.STATUS_CONFIRMED){const t=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0;t&&t.match(/^application\/dtmf-relay/i)?new Q6(this).init_incoming(e):t!==void 0?new nv(this).init_incoming(e):e.reply(415)}else e.reply(403,"Wrong Status");break;case ye.UPDATE:this._status===Oe.STATUS_CONFIRMED?this._receiveUpdate(e):e.reply(403,"Wrong Status");break;case ye.REFER:this._status===Oe.STATUS_CONFIRMED?this._receiveRefer(e):e.reply(403,"Wrong Status");break;case ye.NOTIFY:this._status===Oe.STATUS_CONFIRMED?this._receiveNotify(e):e.reply(403,"Wrong Status");break;default:e.reply(501)}}onTransportError(){Ie.warn("onTransportError()"),this._status!==Oe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ye.causes.CONNECTION_ERROR,cause:ye.causes.CONNECTION_ERROR})}onRequestTimeout(){Ie.warn("onRequestTimeout()"),this._status!==Oe.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ye.causes.REQUEST_TIMEOUT,cause:ye.causes.REQUEST_TIMEOUT})}onDialogError(){Ie.warn("onDialogError()"),this._status!==Oe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ye.causes.DIALOG_ERROR,cause:ye.causes.DIALOG_ERROR})}newDTMF(e){Ie.debug("newDTMF()"),this.emit("newDTMF",e)}newInfo(e){Ie.debug("newInfo()"),this.emit("newInfo",e)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ie.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ie.debug("_isReadyToReOffer() | session not established yet"),!1):(Ie.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Ie.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ie.debug("close() | closing local MediaStream"),Xt.closeMediaStream(this._localMediaStream)),this._status!==Oe.STATUS_TERMINATED){if(this._status=Oe.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(e){Ie.warn("close() | error closing the RTCPeerConnection: %o",e)}for(const e in this._timers)Object.prototype.hasOwnProperty.call(this._timers,e)&&clearTimeout(this._timers[e]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const e in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,e)&&(this._earlyDialogs[e].terminate(),delete this._earlyDialogs[e]);for(const e in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,e)&&delete this._referSubscribers[e];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(e,t){let n=Vd.T1;function i(){this._status===Oe.STATUS_WAITING_FOR_ACK&&(e.reply(200,null,[`Contact: ${this._contact}`],t),n<Vd.T2&&(n=n*2,n>Vd.T2&&(n=Vd.T2)),this._timers.invite2xxTimer=setTimeout(i.bind(this),n))}this._timers.invite2xxTimer=setTimeout(i.bind(this),n)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===Oe.STATUS_WAITING_FOR_ACK&&(Ie.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(ye.BYE),this._ended("remote",null,ye.causes.NO_ACK))},Vd.TIMER_H)}_createRTCConnection(e,t){console.log("pcConfig",e),console.log("rtcConstraints",t),this.stunServers,this._connection=new RTCPeerConnection(e,t),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:ye.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ye.causes.RTP_TIMEOUT})});let n;const i=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(n),n=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=i,Ie.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(e,t){if(Ie.debug("createLocalDescription()"),e!=="offer"&&e!=="answer")throw new Error(`createLocalDescription() | invalid type "${e}"`);const n=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>e==="offer"?(console.log("AAA createOffer",t),n.createOffer(t).catch(i=>(Ie.warn('emit "peerconnection:createofferfailed" [error:%o]',i),this.emit("peerconnection:createofferfailed",i),Promise.reject(i)))):n.createAnswer(t).catch(i=>(Ie.warn('emit "peerconnection:createanswerfailed" [error:%o]',i),this.emit("peerconnection:createanswerfailed",i),Promise.reject(i)))).then(i=>(console.log("AAA setLocalDescription",i),this.jsepOffer=i,n.setLocalDescription(i).catch(s=>(this._rtcReady=!0,Ie.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const i=t&&t.iceRestart;if(n.iceGatheringState==="complete"&&!i||n.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:e,sdp:n.localDescription.sdp};return Ie.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let a=!1,o,u;this._iceReady=!1;const c=()=>{n.removeEventListener("icecandidate",o),n.removeEventListener("icegatheringstatechange",u),a=!0,this._rtcReady=!0,this._iceReady=!0;const d={originator:"local",type:e,sdp:n.localDescription.sdp};Ie.debug('emit "sdp"'),this.emit("sdp",d),s(d.sdp)};n.addEventListener("icecandidate",o=d=>{const p=d.candidate;p?this.emit("icecandidate",{candidate:p,ready:c}):a||c()}),n.addEventListener("icegatheringstatechange",u=()=>{n.iceGatheringState==="complete"&&!a&&c()})})})}_createDialog(e,t,n){console.log("_createDialog",e);const i=t==="UAS"?e.to_tag:e.from_tag,s=t==="UAS"?e.from_tag:e.to_tag,a=e.call_id+i+s;console.log("remote_tag",s);let o=this._earlyDialogs[a];if(n)return o?!0:(o=new Am(this,e,t,Am.C.STATUS_EARLY),console.log("SET DIALOG early"),o.error?(console.log("early_dialog error",o.error),Ie.debug(o.error),this._failed("remote",e,ye.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[a]=o,!0));{if(this._from_tag=e.from_tag,this._to_tag=e.to_tag,o)return o.update(e,t),console.log("SET DIALOG 1"),this._dialog=o,delete this._earlyDialogs[a],!0;const u=new Am(this,e,t);return u.error?(console.log("dialog.error",u.error),Ie.debug(u.error),this._failed("remote",e,ye.causes.INTERNAL_ERROR),!1):(console.log("AAA SET DIALOG 2"),this._dialog=u,!0)}}_receiveReinvite(e){Ie.debug("receiveReinvite()");const t=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0,n={request:e,callback:void 0,reject:s.bind(this)};let i=!1;function s(o={}){i=!0;const u=o.status_code||403,c=o.reason_phrase||"",d=Xt.cloneArray(o.extraHeaders);if(this._status!==Oe.STATUS_CONFIRMED)return!1;if(u<300||u>=700)throw new TypeError(`Invalid status_code: ${u}`);e.reply(u,c,d)}if(this.emit("reinvite",n),i)return;if(this._late_sdp=!1,!e.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(o=>{a.call(this,o)}).catch(()=>{e.reply(500)});return}if(t!=="application/sdp"){Ie.debug("invalid Content-Type"),e.reply(415);return}this._processInDialogSdpOffer(e).then(o=>{this._status!==Oe.STATUS_TERMINATED&&a.call(this,o)}).catch(o=>{Ie.warn(o)});function a(o){const u=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,u),this._late_sdp&&(o=this._mangleOffer(o)),e.reply(200,null,u,o,()=>{this._status=Oe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(e,o),this._setACKTimer()}),typeof n.callback=="function"&&n.callback()}}_receiveUpdate(e){Ie.debug("receiveUpdate()");const t=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0,n={request:e,callback:void 0,reject:s.bind(this)};let i=!1;function s(o={}){i=!0;const u=o.status_code||403,c=o.reason_phrase||"",d=Xt.cloneArray(o.extraHeaders);if(this._status!==Oe.STATUS_CONFIRMED)return!1;if(u<300||u>=700)throw new TypeError(`Invalid status_code: ${u}`);e.reply(u,c,d)}if(this.emit("update",n),i)return;if(!e.body){a.call(this,null);return}if(t!=="application/sdp"){Ie.debug("invalid Content-Type"),e.reply(415);return}this._processInDialogSdpOffer(e).then(o=>{this._status!==Oe.STATUS_TERMINATED&&a.call(this,o)}).catch(o=>{Ie.warn(o)});function a(o){const u=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,u),e.reply(200,null,u,o),typeof n.callback=="function"&&n.callback()}}_processInDialogSdpOffer(e){Ie.debug("_processInDialogSdpOffer()");const t=e.parseSDP();let n=!1;for(const a of t.media){if($0.indexOf(a.type)===-1)continue;const o=a.direction||t.direction||"sendrecv";if(o==="sendonly"||o==="inactive")n=!0;else{n=!1;break}}const i={originator:"remote",type:"offer",sdp:e.body};Ie.debug('emit "sdp"'),this.emit("sdp",i);const s=new RTCSessionDescription({type:"offer",sdp:i.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(a=>{throw e.reply(488),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a),a})}).then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&n===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&n===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(a=>{throw e.reply(500),Ie.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',a),a})}).catch(a=>{Ie.warn("_processInDialogSdpOffer() failed [error: %o]",a)}),this._connectionPromiseQueue}_receiveRefer(e){if(Ie.debug("receiveRefer()"),!e.refer_to){Ie.debug("no Refer-To header field present in REFER"),e.reply(400);return}if(e.refer_to.uri.scheme!==ye.SIP){Ie.debug("Refer-To header field points to a non-SIP URI scheme"),e.reply(416);return}e.reply(202);const t=new iF(this,e.cseq);Ie.debug('emit "refer"'),this.emit("refer",{request:e,accept:(s,a)=>{n.call(this,s,a)},reject:()=>{i.call(this)}});function n(s,a={}){if(s=typeof s=="function"?s:null,this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED)return!1;const o=new D0(this._ua);if(o.on("progress",({response:u})=>{t.notify(u.status_code,u.reason_phrase)}),o.on("accepted",({response:u})=>{t.notify(u.status_code,u.reason_phrase)}),o.on("_failed",({message:u,cause:c})=>{u?t.notify(u.status_code,u.reason_phrase):t.notify(487,c)}),e.refer_to.uri.hasHeader("replaces")){const u=decodeURIComponent(e.refer_to.uri.getHeader("replaces"));a.extraHeaders=Xt.cloneArray(a.extraHeaders),a.extraHeaders.push(`Replaces: ${u}`)}o.connect(e.refer_to.uri.toAor(),a,s)}function i(){t.notify(603)}}_receiveNotify(e){switch(Ie.debug("receiveNotify()"),e.event||e.reply(400),e.event.event){case"refer":{let t,n;if(e.event.params&&e.event.params.id)t=e.event.params.id,n=this._referSubscribers[t];else if(Object.keys(this._referSubscribers).length===1)n=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{e.reply(400,"Missing event id parameter");return}if(!n){e.reply(481,"Subscription does not exist");return}n.receiveNotify(e),e.reply(200);break}default:e.reply(489)}}_receiveReplaces(e){Ie.debug("receiveReplaces()");function t(i){if(this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED)return!1;const s=new D0(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(e,i)}function n(){Ie.debug("Replaced INVITE rejected by the user"),e.reply(486)}this.emit("replaces",{request:e,accept:i=>{t.call(this,i)},reject:()=>{n.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(e,t,n){this.ackSent=!1,this.publisherSubscribeSent=!1;const i=new mc(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(n)return n;if(e.audio||e.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(e).catch(s=>{throw this._status===Oe.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,ye.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(a=>{this._connection.addTrack(a,s)}),this._connecting(this._request),this._createLocalDescription("offer",t).catch(a=>{throw this._failed("local",null,ye.causes.WEBRTC_ERROR),a})}).then(s=>{if(this._is_canceled||this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},o=JSON.stringify(a);this._request.body=o,this._status=Oe.STATUS_INVITE_SENT,Ie.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),i.send()}).catch(s=>{this._status!==Oe.STATUS_TERMINATED&&Ie.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async loadStream(){const e={audio:this.isAudioOn,video:this.isVideoOn};let t=null;try{t=await navigator.mediaDevices.getUserMedia(e)}catch{try{e.video=!1,t=await navigator.mediaDevices.getUserMedia(e)}catch{e.audio=!1,e.video=!1,t=await navigator.mediaDevices.getUserMedia(e)}}return t}addTracks(e){e.forEach(t=>{this._connection.addTrack(t)})}getRecordFileName(){return Sue+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let e=0;e<this.iceCandidates.length;e++)await this._connection.addIceCandidate(this.iceCandidates[e]);this.iceCandidates=[]}async _sendConfigureMessage(e){const t=this._candidates.map(a=>({janus:"trickle",candidate:a,handle_id:this.handle_id,session_id:this.session_id})),i={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...e},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...t]},s=["Content-Type: application/json",this.getPTypeHeader(lr.ICE)];this.sendRequest(ye.INFO,{extraHeaders:s,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async a=>{this.isConfigureSent=!0;const u=a.data.split(`\r
18333
+ model.`);return n=function(o,u){var c="model-stride"+o+".json";return u===4?xO+"float/"+c:xO+"quant"+u+"/"+c}(e,t),[4,WT(r.modelUrl||n)];case 1:return i=a.sent(),s=new kle(i,e),[2,new FO(s)]}})})}function Ple(r){return r===void 0&&(r=RO),Mt(this,void 0,void 0,function(){return Lt(this,function(e){return(r=function(t){if((t=t||RO).architecture==null&&(t.architecture="MobileNetV1"),NO.indexOf(t.architecture)<0)throw new Error("Invalid architecture "+t.architecture+". Should be one of "+NO);if(t.outputStride==null&&(t.outputStride=16),kO[t.architecture].indexOf(t.outputStride)<0)throw new Error("Invalid outputStride "+t.outputStride+". Should be one of "+kO[t.architecture]+" for architecture "+t.architecture+".");if(t.multiplier==null&&(t.multiplier=1),OO[t.architecture].indexOf(t.multiplier)<0)throw new Error("Invalid multiplier "+t.multiplier+". Should be one of "+OO[t.architecture]+" for architecture "+t.architecture+".");if(t.quantBytes==null&&(t.quantBytes=4),$O.indexOf(t.quantBytes)<0)throw new Error("Invalid quantBytes "+t.quantBytes+". Should be one of "+$O+" for architecture "+t.architecture+".");return t}(r)).architecture==="ResNet50"?[2,Dle(r)]:r.architecture==="MobileNetV1"?[2,$le(r)]:[2,null]})})}var JT=["left_face","right_face","left_upper_arm_front","left_upper_arm_back","right_upper_arm_front","right_upper_arm_back","left_lower_arm_front","left_lower_arm_back","right_lower_arm_front","right_lower_arm_back","left_hand","right_hand","torso_front","torso_back","left_upper_leg_front","left_upper_leg_back","right_upper_leg_front","right_upper_leg_back","left_lower_leg_front","left_lower_leg_back","right_lower_leg_front","right_lower_leg_back","left_feet","right_feet"],MO=function(){function r(e){this.mask=e}return r.prototype.toCanvasImageSource=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,jT(this.mask)]})})},r.prototype.toImageData=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,this.mask]})})},r.prototype.toTensor=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,dO(this.mask)]})})},r.prototype.getUnderlyingType=function(){return"imagedata"},r}();function Fle(r){if(b0(r),r!==255)throw new Error("Foreground id must be 255 but got "+r);return"person"}function Mle(r){if(b0(r),r>=JT.length)throw new Error("Invalid body part value "+r);return JT[r]}var Lle=function(){function r(e){this.bodyPixModel=e}return r.prototype.segmentPeople=function(e,t){return Mt(this,void 0,void 0,function(){var n,i,s,a;return Lt(this,function(o){switch(o.label){case 0:return e instanceof ImageBitmap&&((n=document.createElement("canvas")).getContext("2d").drawImage(e,0,0),e=n),t.segmentBodyParts?t.multiSegmentation?[4,this.bodyPixModel.segmentMultiPersonParts(e,t)]:[3,2]:[3,5];case 1:return s=o.sent(),[3,4];case 2:return[4,this.bodyPixModel.segmentPersonParts(e,t)];case 3:s=[o.sent()],o.label=4;case 4:return i=s.map(function(u){var c=u.data,d=u.width,p=u.height,m=new Uint8ClampedArray(d*p*4).fill(0);return c.forEach(function(_,y){_===-1?(m[4*y]=JT.length,m[4*y+3]=0):(m[4*y]=_,m[4*y+3]=255)}),{maskValueToLabel:Mle,mask:new MO(new ImageData(m,d,p))}}),[3,10];case 5:return t.multiSegmentation?[4,this.bodyPixModel.segmentMultiPerson(e,t)]:[3,7];case 6:return a=o.sent(),[3,9];case 7:return[4,this.bodyPixModel.segmentPerson(e,t)];case 8:a=[o.sent()],o.label=9;case 9:i=a.map(function(u){var c=u.data,d=u.width,p=u.height,m=new Uint8ClampedArray(d*p*4).fill(0);return c.forEach(function(_,y){_===0?(m[4*y]=0,m[4*y+3]=0):(m[4*y]=255,m[4*y+3]=255)}),{maskValueToLabel:Fle,mask:new MO(new ImageData(m,d,p))}}),o.label=10;case 10:return[2,i]}})})},r.prototype.dispose=function(){this.bodyPixModel.dispose()},r.prototype.reset=function(){},r}();function Ule(r){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,Ple(r).then(function(t){return new Lle(t)})]})})}var LO={runtime:"mediapipe",modelType:"general"},Ble=function(){function r(e){this.mask=e}return r.prototype.toCanvasImageSource=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,this.mask]})})},r.prototype.toImageData=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,cO(this.mask)]})})},r.prototype.toTensor=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,dO(this.mask)]})})},r.prototype.getUnderlyingType=function(){return"canvasimagesource"},r}();function Hle(r){return b0(r),"person"}var Vle=function(){function r(e){var t,n=this;this.selfieMode=!1;var i;this.selfieSegmentationSolution=new vle.SelfieSegmentation({locateFile:(t=e.locateFile)!==null&&t!==void 0?t:function(s,a){return e.solutionPath?e.solutionPath.replace(/\/+$/,"")+"/"+s:a+"/"+s}}),e.modelType==="landscape"?i=1:i=0,this.selfieSegmentationSolution.setOptions({modelSelection:i,selfieMode:this.selfieMode}),this.selfieSegmentationSolution.onResults(function(s){n.segmentation=[{maskValueToLabel:Hle,mask:new Ble(s.segmentationMask)}]})}return r.prototype.segmentPeople=function(e,t){return Mt(this,void 0,void 0,function(){var n,i;return Lt(this,function(s){switch(s.label){case 0:return t&&t.flipHorizontal&&t.flipHorizontal!==this.selfieMode&&(this.selfieMode=t.flipHorizontal,this.selfieSegmentationSolution.setOptions({selfieMode:this.selfieMode})),e instanceof tn?(i=ImageData.bind,[4,kf(e)]):[3,2];case 1:return n=new(i.apply(ImageData,[void 0,s.sent(),e.shape[1],e.shape[0]])),[3,3];case 2:n=e,s.label=3;case 3:return e=n,[4,this.selfieSegmentationSolution.send({image:e})];case 4:return s.sent(),[2,this.segmentation]}})})},r.prototype.dispose=function(){this.selfieSegmentationSolution.close()},r.prototype.reset=function(){this.selfieSegmentationSolution.reset(),this.segmentation=null,this.selfieMode=!1},r.prototype.initialize=function(){return this.selfieSegmentationSolution.initialize()},r}();function Gle(r){return Mt(this,void 0,void 0,function(){var e,t;return Lt(this,function(n){switch(n.label){case 0:return e=function(i){if(i==null)return gr({},LO);var s=gr({},i);return s.runtime="mediapipe",s.modelType==null&&(s.modelType=LO.modelType),s}(r),[4,(t=new Vle(e)).initialize()];case 1:return n.sent(),[2,t]}})})}function Wle(r,e,t,n){var i=r.width,s=r.height,a=n?-1:1,o=Math.cos(r.rotation),u=Math.sin(r.rotation),c=r.xCenter,d=r.yCenter,p=1/e,m=1/t,_=new Array(16);return _[0]=i*o*a*p,_[1]=-s*u*p,_[2]=0,_[3]=(-.5*i*o*a+.5*s*u+c)*p,_[4]=i*u*a*m,_[5]=s*o*m,_[6]=0,_[7]=(-.5*s*o-.5*i*u*a+d)*m,_[8]=0,_[9]=0,_[10]=i*p,_[11]=0,_[12]=0,_[13]=0,_[14]=0,_[15]=1,function(y){if(y.length!==16)throw new Error("Array length must be 16 but got "+y.length);return[[y[0],y[1],y[2],y[3]],[y[4],y[5],y[6],y[7]],[y[8],y[9],y[10],y[11]],[y[12],y[13],y[14],y[15]]]}(_)}function UO(r){return r instanceof tn?{height:r.shape[0],width:r.shape[1]}:{height:r.height,width:r.width}}function QT(r,e){V(r.width!==0,function(){return e+" width cannot be 0."}),V(r.height!==0,function(){return e+" height cannot be 0."})}function zle(r,e){var t=function(n,i,s,a){var o=i-n,u=a-s;if(o===0)throw new Error("Original min and max are both "+n+", range cannot be 0.");var c=u/o;return{scale:c,offset:s-n*c}}(0,255,e[0],e[1]);return bt(function(){return St(Ye(r,t.scale),t.offset)})}function jle(r,e,t){var n=e.outputTensorSize,i=e.keepAspectRatio,s=e.borderMode,a=e.outputTensorFloatRange,o=UO(r),u=function(m,_){return _?{xCenter:_.xCenter*m.width,yCenter:_.yCenter*m.height,width:_.width*m.width,height:_.height*m.height,rotation:_.rotation}:{xCenter:.5*m.width,yCenter:.5*m.height,width:m.width,height:m.height,rotation:0}}(o,t),c=function(m,_,y){if(y===void 0&&(y=!1),!y)return{top:0,left:0,right:0,bottom:0};var b=_.height,S=_.width;QT(_,"targetSize"),QT(m,"roi");var w,x,E=b/S,I=m.height/m.width,R=0,P=0;return E>I?(w=m.width,x=m.width*E,P=(1-I/E)/2):(w=m.height/E,x=m.height,R=(1-E/I)/2),m.width=w,m.height=x,{top:P,left:R,right:R,bottom:P}}(u,n,i),d=Wle(u,o.width,o.height,!1),p=bt(function(){var m,_=(m=r)instanceof tn?m:G_(m),y=Iu(function(w,x,E){return QT(E,"inputResolution"),[1/E.width*w[0][0]*x.width,1/E.height*w[0][1]*x.width,w[0][3]*x.width,1/E.width*w[1][0]*x.height,1/E.height*w[1][1]*x.height,w[1][3]*x.height,0,0]}(d,o,n),[1,8]),b=s==="zero"?"constant":"nearest",S=Au.transform(kr(Yt(_,"float32")),y,"bilinear",b,0,[n.height,n.width]);return a!=null?zle(S,a):S});return{imageTensor:p,padding:c,transformationMatrix:d}}function qle(r,e,t){return bt(function(){var n=Ai(r,[0]),i=n.shape[2];if(i===1){var s=n;switch(e.activation){case"none":break;case"sigmoid":s=Oa(s);break;case"softmax":throw new Error("Softmax activation requires two channels.");default:throw new Error("Activation not supported ("+e.activation+")")}var a=t?Au.resizeBilinear(s,[t.height,t.width]):s;return Ai(a,[2])}throw new Error("Unsupported number of tensor channels "+i)})}var BO={runtime:"tfjs",modelType:"general",modelUrl:"https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1"},HO={flipHorizontal:!1},Kle={outputTensorSize:{width:256,height:256},keepAspectRatio:!1,borderMode:"zero",outputTensorFloatRange:[0,1]},Xle={outputTensorSize:{width:256,height:144},keepAspectRatio:!1,borderMode:"zero",outputTensorFloatRange:[0,1]},Yle={activation:"none"},Jle=function(){function r(e){this.mask=e}return r.prototype.toCanvasImageSource=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,jT(this.mask)]})})},r.prototype.toImageData=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,cO(this.mask)]})})},r.prototype.toTensor=function(){return Mt(this,void 0,void 0,function(){return Lt(this,function(e){return[2,this.mask]})})},r.prototype.getUnderlyingType=function(){return"tensor"},r}();function Qle(r){return b0(r),"person"}var ep,Zle=function(){function r(e,t){this.modelType=e,this.model=t}return r.prototype.segmentPeople=function(e,t){return Mt(this,void 0,void 0,function(){var n,i=this;return Lt(this,function(s){return t=function(a){if(a==null)return gr({},HO);var o=gr({},a);return o.flipHorizontal==null&&(o.flipHorizontal=HO.flipHorizontal),o}(t),e==null?(this.reset(),[2,[]]):(n=bt(function(){var a=jle(e,i.modelType==="general"?Kle:Xle).imageTensor,o=un(i.model.predict(a),[0,0,0,1],-1),u=UO(e),c=qle(o,Yle,u),d=kr(c,2),p=Eu(d,[[0,0],[0,0],[0,1]]);return jb(p,[[0,0],[0,0],[0,2]],"symmetric")}),[2,[{maskValueToLabel:Qle,mask:new Jle(n)}]])})})},r.prototype.dispose=function(){this.model.dispose()},r.prototype.reset=function(){},r}();function eue(r){return Mt(this,void 0,void 0,function(){var e,t,n;return Lt(this,function(i){switch(i.label){case 0:return e=function(s){if(s==null)return gr({},BO);var a=gr({},s);if(a.runtime="tfjs",a.modelType==null&&(a.modelType=BO.modelType),a.modelType!=="general"&&a.modelType!=="landscape")throw new Error("Model type must be one of general or landscape, but got "+a.modelType);return a.modelUrl==null&&(a.modelType==="general"?a.modelUrl="https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/general/1":a.modelUrl="https://tfhub.dev/mediapipe/tfjs-model/selfie_segmentation/landscape/1"),a}(r),t=typeof e.modelUrl=="string"&&e.modelUrl.indexOf("https://tfhub.dev")>-1,[4,WT(e.modelUrl,{fromTFHub:t})];case 1:return n=i.sent(),[2,new Zle(e.modelType,n)]}})})}function tue(r,e){return Mt(this,void 0,void 0,function(){var t,n;return Lt(this,function(i){switch(r){case ep.MediaPipeSelfieSegmentation:if(t=void 0,(n=e)!=null){if(n.runtime==="tfjs")return[2,eue(n)];if(n.runtime==="mediapipe")return[2,Gle(n)];t=n.runtime}throw new Error("Expect modelConfig.runtime to be either 'tfjs' or 'mediapipe', but got "+t);case ep.BodyPix:return[2,Ule(n=e)];default:throw new Error(r+" is not a supported model name.")}})})}(function(r){r.BodyPix="BodyPix",r.MediaPipeSelfieSegmentation="MediaPipeSelfieSegmentation"})(ep||(ep={}));var nue="blurred",sue="blurred-mask",rue="mask",iue="draw-image",ZT={};function k0(r){if(typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return function(e){if("offsetHeight"in e&&e.offsetHeight!==0&&"offsetWidth"in e&&e.offsetWidth!==0)return[e.offsetHeight,e.offsetWidth];if(e.height!=null&&e.width!=null)return[e.height,e.width];throw new Error("HTMLImageElement must have height and width attributes set.")}(r);if(typeof ImageData<"u"&&r instanceof ImageData)return[r.height,r.width];if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return function(e){return e.hasAttribute("height")&&e.hasAttribute("width")?[e.height,e.width]:[e.videoHeight,e.videoWidth]}(r);if(r instanceof tn)return[r.shape[0],r.shape[1]];throw new Error("error: Unknown input type: "+r+".")}function VO(r){return ZT[r]||(ZT[r]=function(){if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(0,0);throw new Error("Cannot create a canvas in this context")}()),ZT[r]}function GO(r,e){var t=VO(e);return function(n,i){i.width=n.width,i.height=n.height,i.getContext("2d").putImageData(n,0,0)}(r,t),t}function tp(r,e,t,n,i,s){return Mt(this,void 0,void 0,function(){var a,o,u,c;return Lt(this,function(d){switch(d.label){case 0:return e instanceof tn?[4,kf(e)]:[3,2];case 1:a=d.sent(),o=k0(e),u=o[0],c=o[1],e=new ImageData(a,c,u),d.label=2;case 2:return e instanceof ImageData&&(e=GO(e,iue)),i==null||s==null?r.drawImage(e,t,n):r.drawImage(e,t,n,i,s),[2]}})})}function aue(r,e){return Mt(this,void 0,void 0,function(){var t,n,i;return Lt(this,function(s){switch(s.label){case 0:return t=k0(r),n=t[0],i=t[1],e.width=i,e.height=n,[4,tp(e.getContext("2d"),r,0,0,i,n)];case 1:return s.sent(),[2]}})})}function oue(r){var e=r.getContext("2d");e.scale(-1,1),e.translate(-r.width,0)}function WO(r,e,t){return Mt(this,void 0,void 0,function(){return Lt(this,function(n){switch(n.label){case 0:return r.globalCompositeOperation=t,[4,tp(r,e,0,0)];case 1:return n.sent(),[2]}})})}function lue(r,e,t){return Mt(this,void 0,void 0,function(){var n,i,s,a,o,u,c,d;return Lt(this,function(p){switch(p.label){case 0:for(n=r.getContext("2d"),i=0,s=5,a=1/(2*Math.PI*s*s),o=t<3?1:2,c=-t;c<=t;c+=o)for(d=-t;d<=t;d+=o)u=a*Math.exp(-(d*d+c*c)/(2*s*s)),i+=u;c=-t,p.label=1;case 1:if(!(c<=t))return[3,6];d=-t,p.label=2;case 2:return d<=t?(n.globalAlpha=a*Math.exp(-(d*d+c*c)/(2*s*s))/i*t,[4,tp(n,e,d,c)]):[3,5];case 3:p.sent(),p.label=4;case 4:return d+=o,[3,2];case 5:return c+=o,[3,1];case 6:return n.globalAlpha=1,[2]}})})}function uue(r,e,t){return Mt(this,void 0,void 0,function(){var n,i,s,a;return Lt(this,function(o){switch(o.label){case 0:return n=k0(r),i=n[0],s=n[1],a=t.getContext("2d"),t.width=s,t.height=i,a.clearRect(0,0,s,i),a.save(),/^((?!chrome|android).)*safari/i.test(navigator.userAgent)?[4,lue(t,r,e)]:[3,2];case 1:return o.sent(),[3,4];case 2:return a.filter="blur("+e+"px)",[4,tp(a,r,0,0,s,i)];case 3:o.sent(),o.label=4;case 4:return a.restore(),[2]}})})}function zO(r,e,t){return Mt(this,void 0,void 0,function(){var n;return Lt(this,function(i){switch(i.label){case 0:return n=VO(t),e!==0?[3,2]:[4,aue(r,n)];case 1:return i.sent(),[3,4];case 2:return[4,uue(r,e,n)];case 3:i.sent(),i.label=4;case 4:return[2,n]}})})}function cue(r,e,t,n,i,s){s===void 0&&(s={r:0,g:255,b:255,a:255});for(var a=-i;a<=i;a++)for(var o=-i;o<=i;o++)if(a!==0&&o!==0){var u=(e+a)*n+(t+o);r[4*u+0]=s.r,r[4*u+1]=s.g,r[4*u+2]=s.b,r[4*u+3]=s.a}}function due(r,e,t,n,i,s,a){a===void 0&&(a=1);for(var o=0,u=-a;u<=a;u++)for(var c=-a;c<=a;c++)if(u!==0&&c!==0){var d=(e+u)*n+(t+c);(!i[r[4*d]]||r[4*d+3]<s)&&(o+=1)}return o>0}function jO(r,e,t,n,i,s){return e===void 0&&(e={r:0,g:0,b:0,a:0}),t===void 0&&(t={r:0,g:0,b:0,a:255}),n===void 0&&(n=!1),i===void 0&&(i=.5),s===void 0&&(s=Array.from(Array(256).keys())),Mt(this,void 0,void 0,function(){var a,o,u,c,d,p,m,_,y,b,S,w,x,E;return Lt(this,function(I){switch(I.label){case 0:return(a=Array.isArray(r)?r:[r]).length===0?[2,null]:[4,Promise.all(a.map(function(R){return R.mask.toImageData()}))];case 1:for(o=I.sent(),u=o[0],c=u.width,d=u.height,p=new Uint8ClampedArray(c*d*4),m=Math.round(255*i),_=new Array(256).fill(!1),s.forEach(function(R){return _[R]=!0}),y=0;y<d;y++)for(b=0;b<c;b++)for(p[4*(S=y*c+b)+0]=t.r,p[4*S+1]=t.g,p[4*S+2]=t.b,p[4*S+3]=t.a,w=0,x=o;w<x.length;w++)E=x[w],_[E.data[4*S]]&&E.data[4*S+3]>=m&&(p[4*S]=e.r,p[4*S+1]=e.g,p[4*S+2]=e.b,p[4*S+3]=e.a,n&&y-1>=0&&y+1<d&&b-1>=0&&b+1<c&&due(E.data,y,b,c,_,m)&&cue(p,y,b,c,1));return[2,new ImageData(p,c,d)]}})})}function hue(r,e,t){return Mt(this,void 0,void 0,function(){var n,i;return Lt(this,function(s){switch(s.label){case 0:return[4,jO(r,{r:0,g:0,b:0,a:255},{r:0,g:0,b:0,a:0},!1,e)];case 1:return n=s.sent(),i=GO(n,rue),t===0?[2,i]:[2,zO(i,t,sue)]}})})}function fue(r,e,t,n,i,s,a){return n===void 0&&(n=.5),i===void 0&&(i=3),s===void 0&&(s=3),a===void 0&&(a=!1),Mt(this,void 0,void 0,function(){var o,u,c,d,p,m;return Lt(this,function(_){switch(_.label){case 0:return[4,zO(e,i,nue)];case 1:return o=_.sent(),r.width=o.width,r.height=o.height,u=r.getContext("2d"),Array.isArray(t)&&t.length===0?(u.drawImage(o,0,0),[2]):[4,hue(t,n,s)];case 2:return c=_.sent(),u.save(),a&&oue(r),d=k0(e),p=d[0],m=d[1],[4,tp(u,e,0,0,m,p)];case 3:return _.sent(),[4,WO(u,c,"destination-in")];case 4:return _.sent(),[4,WO(u,o,"destination-over")];case 5:return _.sent(),u.restore(),[2]}})})}const qO={runtime:"mediapipe",modelType:"general"},pue={WEBGL_PACK:!0,WEBGL_VERSION:2,WEBGL_CPU_FORWARD:!1},mue={targetFPS:60},gue={foregroundThreshold:.5,maskOpacity:.7,maskBlur:0,pixelCellWidth:10,backgroundBlur:15,edgeBlur:3},ew={WEBGL_VERSION:[1,2],WASM_HAS_SIMD_SUPPORT:[!0,!1],WASM_HAS_MULTITHREAD_SUPPORT:[!0,!1],WEBGL_CPU_FORWARD:[!0,!1],WEBGL_PACK:[!0,!1],WEBGL_FORCE_F16_TEXTURES:[!0,!1],WEBGL_RENDER_FLOAT32_CAPABLE:[!0,!1],WEBGL_FLUSH_THRESHOLD:[-1,0,.25,.5,.75,1,1.25,1.5,1.75,2],CHECK_COMPUTATION_FOR_ERRORS:[!0,!1]},tw={bokehEffect:"bokehEffect",backgroundImageEffect:"backgroundImageEffect"};async function _ue(r){if(r!=null){if(typeof r!="object")throw new Error(`An object is expected, while a(n) ${typeof r} is found.`);for(const e in r){if(!(e in ew))throw new Error(`${e} is not a tunable or valid environment flag.`);if(ew[e].indexOf(r[e])===-1)throw new Error(`${e} value is expected to be in the range [${ew[e]}], while ${r[e]} is found.`)}de().setFlags(r)}}class nw{constructor(){this.video=null,this.canvas=null,this.wrapperEl=null,this.ctx=null;const e=document.createElement("video");e.setAttribute("id","video"),e.setAttribute("playsinline",""),e.style.setProperty("visibility","hidden"),e.style.setProperty("width","auto"),e.style.setProperty("height","auto"),this.video=e;const t=document.createElement("canvas");t.setAttribute("id","output"),t.style.setProperty("visibility","hidden"),this.canvas=t;const n=document.createElement("div");n.classList.add("canvas-wrapper"),n.style.setProperty("display","none"),n.appendChild(e),n.appendChild(t),this.wrapperEl=n,document.body.appendChild(n),this.ctx=this.canvas.getContext("2d")}static async setupCamera(e){e.getAudioTracks().forEach(s=>{s.stop(),e.removeTrack(s)});const t=new nw;t.video.srcObject=e,t.video.volume=0,await new Promise(s=>{t.video.onloadedmetadata=()=>{s(t.video)}}),t.video.play();const n=t.video.videoWidth,i=t.video.videoHeight;return t.video.width=n,t.video.height=i,t.canvas.width=n,t.canvas.height=i,t.wrapperEl.style.setProperty("width",`${n}px`),t.wrapperEl.style.setProperty("height",`${i}px`),t}cleanCamera(){this.ctx=null,this.wrapperEl.remove()}drawToCanvas(e){this.ctx.drawImage(e,0,0,this.video.videoWidth,this.video.videoHeight)}drawFromVideo(e){e.drawImage(this.video,0,0,this.video.videoWidth,this.video.videoHeight)}clearCtx(){this.ctx.clearRect(0,0,this.video.videoWidth,this.video.videoHeight)}}function KO(r,e={}){const t={};return Object.keys(r).forEach(n=>{t[n]=e[n]!==void 0?e[n]:r[n]}),t}function yue(r){return new Promise((e,t)=>{const n=new Image;n.onload=()=>{e(n)},n.onerror=i=>{t(i)},n.src=r})}function vue(r){return setTimeout(r,1e3/30)}class XO{constructor(e){this.opensips=null,this.session=null,this.name=null,this.name=e}setOpensips(e){this.opensips=e}setSession(e){this.session=e}kill(){this.opensips.kill(this.name)}}class O0 extends XO{constructor(e,t,n={}){super(e),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=n.immediate||!1,this.type=t}start(e){return e}stop(){throw new Error("stop method is not implemented")}async process(e){if(this.immediate){const t=await this.start(e);return this.running=!0,t}return e}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}loe(`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${coe}/dist/`);class bue extends O0{constructor(e,t){super("StreamMask","video",t),this.visualizationConfig={},this.maskEffectType=null,this.base64ImageMask=null,this.rafId=null,this.timeoutId=null,this.segmenter=null,this.visibilityState=null;const{visualizationConfig:n,effect:i,base64Image:s}=e;if(this.visualizationConfig=KO(gue,n),i===tw.backgroundImageEffect&&!s)throw new Error("Error when starting mask effect: base64Image option is required for backgroundImageEffect effect type");s&&(this.base64ImageMask=s),this.maskEffectType=i}async start(e){this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.camera=await nw.setupCamera(e),this.canvas.width=this.camera.canvas.width,this.canvas.height=this.camera.canvas.height,await _ue(pue),this.segmenter=await this.createSegmenter(),this.processVisibilityChange(),this.renderPrediction();const t=this.canvas.captureStream(mue.targetFPS);return await this.populateWithAudioTracks(t,e.getAudioTracks())}processVisibilityChange(){document&&(this.visibilityState=document.visibilityState,document.addEventListener("visibilitychange",()=>{this.visibilityState=document.visibilityState,document.visibilityState==="hidden"&&this.renderPrediction()}))}async populateWithAudioTracks(e,t){const n=new MediaStream;return e.getVideoTracks().forEach(i=>{n.addTrack(i)}),t.forEach(i=>{n.addTrack(i)}),n}stop(){this.rafId&&window.cancelAnimationFrame(this.rafId),this.timeoutId&&clearTimeout(this.timeoutId),this.segmenter&&this.segmenter.dispose(),this.camera&&this.camera.cleanCamera(),this.rafId=null,this.timeoutId=null,this.segmenter=null,this.camera=null,this.canvas=null,this.ctx=null}setupVisualizationConfig(e){this.visualizationConfig=KO(this.visualizationConfig,e)}async renderPrediction(){await this.renderResult(),this.visibilityState==="visible"?(this.timeoutId&&clearTimeout(this.timeoutId),this.rafId=requestAnimationFrame(this.renderPrediction.bind(this))):(this.rafId&&window.cancelAnimationFrame(this.rafId),this.timeoutId=vue(this.renderPrediction.bind(this)))}async createSegmenter(){return tue(ep.MediaPipeSelfieSegmentation,{runtime:qO.runtime,modelType:qO.modelType})}async renderResult(){this.camera.video.readyState<2&&await new Promise(t=>{this.camera.video.onloadeddata=()=>{t(this.camera.video)}});let e=null;if(this.segmenter!=null){try{this.segmenter.segmentPeople!=null?e=await this.segmenter.segmentPeople(this.camera.video,{flipHorizontal:!1,multiSegmentation:!1,segmentBodyParts:!0,segmentationThreshold:this.visualizationConfig.foregroundThreshold}):(e=await this.segmenter.estimatePoses(this.camera.video,{flipHorizontal:!1}),e=e.map(n=>n.segmentation))}catch(n){this.segmenter.dispose(),this.segmenter=null,alert(n)}const t=window.exposedContext;t&&t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array(4))}if(e&&e.length>0)switch(this.maskEffectType){case tw.bokehEffect:console.log("applyBokehEffect"),await this.applyBokehEffect(e);break;case tw.backgroundImageEffect:await this.applyBackgroundImageEffect(e);break;default:console.error("Error when applying mask effect: such mask effect doesn't exist")}this.camera.drawToCanvas(this.canvas)}async applyBokehEffect(e){const t=this.visualizationConfig;await fue(this.canvas,this.camera.video,e,t.foregroundThreshold,t.backgroundBlur,t.edgeBlur)}async applyBackgroundImageEffect(e){const t=this.base64ImageMask,n=new Image;n.src=t;const i=this.canvas.getContext("2d"),a=await jO(e,{r:0,g:0,b:0,a:0},{r:0,g:0,b:0,a:255});a&&(i.putImageData(a,0,0),i.globalCompositeOperation="source-in",n.complete?i.drawImage(n,0,0,this.canvas.width,this.canvas.height):n.onload=()=>{i.drawImage(n,0,0,this.canvas.width,this.canvas.height)},i.globalCompositeOperation="destination-over",i.drawImage(this.camera.video,0,0,this.canvas.width,this.canvas.height),i.globalCompositeOperation="source-over")}}const Ie=new fm("JanusSession"),Sue="/opt/recordings/",Oe={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},$0=["audio","video"];class D0 extends Is.EventEmitter{static get C(){return Oe}constructor(e){Ie.debug("new"),super(),console.log("constructor call"),this._id=null,this._ua=e,this._status=Oe.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:ye.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0}get C(){return Oe}get causes(){return ye.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(e){this._data=e}get status(){return this._status}isInProgress(){switch(this._status){case Oe.STATUS_NULL:case Oe.STATUS_INVITE_SENT:case Oe.STATUS_1XX_RECEIVED:case Oe.STATUS_INVITE_RECEIVED:case Oe.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case Oe.STATUS_ANSWERED:case Oe.STATUS_WAITING_FOR_ACK:case Oe.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case Oe.STATUS_CANCELED:case Oe.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(e){return`PTYPE: ${e}`}generateOpaqueId(){return`videoroomtest-${bE().replace(/-/g,"").slice(0,12)}`}connect(e,t,n={},i){Ie.debug("connect()"),this.display_name=t;const s=e,a=Xt.cloneObject(n.eventHandlers),o=Xt.cloneArray(n.extraHeaders),u=Xt.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),c=n.mediaStream||null,d=Xt.cloneObject(n.pcConfig,{iceServers:[]}),p=n.rtcConstraints||null,m=n.rtcOfferConstraints||null;if(this._rtcOfferConstraints=m,this._rtcAnswerConstraints=n.rtcAnswerConstraints||null,this._data=n.data||this._data,e===void 0)throw new TypeError("Not enough arguments");if(this._status!==Oe.STATUS_NULL)throw new Xo.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Xo.NotSupportedError("WebRTC not supported");if(console.log("target",e),e=this._ua.normalizeTarget(e),console.log("normalizeTarget target",e),this.room_id=e.user,this.target=e,!e)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&Xt.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=ye.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=ye.SESSION_EXPIRES);for(const b in a)Object.prototype.hasOwnProperty.call(a,b)&&this.on(b,a[b]);this._from_tag=Xt.newTag();const _=n.anonymous||!1,y={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:_,outbound:!0}),_?(y.from_display_name="Anonymous",y.from_uri=new Zo("sip","anonymous","anonymous.invalid"),o.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),o.push("Privacy: id")):n.fromUserName&&(y.from_uri=new Zo("sip",n.fromUserName,this._ua.configuration.uri.host),o.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(y.from_display_name=n.fromDisplayName),o.push(`Contact: ${this._contact}`),o.push("Content-Type: application/json"),this._sessionTimers.enabled&&o.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Rs.InitialOutgoingInviteRequest(e,this._ua,y,o),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(d,p),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,console.log("this._remote_identity",this._remote_identity),i&&i(this),this._newJanusSession("local",this._request),this._sendInitialRequest(u,m,c)}connectScreenShare(e={}){new f8(this).connect(e)}_overrideSenderTracks(e,t){e.getTracks().forEach(n=>{t.getSenders().forEach(async s=>{s.track.kind===n.kind&&(n.kind==="audio"&&!this.isAudioOn&&(n.enabled=!1),n.kind==="video"&&!this.isVideoOn&&(n.enabled=!1),await s.replaceTrack(n))})})}init_incoming(e,t){Ie.debug("init_incoming()");let n;const i=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0;if(e.body&&i!=="application/sdp"){e.reply(415);return}if(this._status=Oe.STATUS_INVITE_RECEIVED,this._from_tag=e.from_tag,this._id=e.call_id+this._from_tag,this._request=e,this._contact=this._ua.contact.toString(),e.hasHeader("expires")&&(n=e.getHeader("expires")*1e3),e.to_tag=Xt.newTag(),!this._createDialog(e,"UAS",!0)){e.reply(500,"Missing Contact header field");return}e.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Oe.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{e.reply(408),this._failed("local",null,ye.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),n&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Oe.STATUS_WAITING_FOR_ANSWER&&(e.reply(487),this._failed("system",null,ye.causes.EXPIRES))},n)),this._direction="incoming",this._local_identity=e.to,this._remote_identity=e.from,t&&t(this),this._newJanusSession("remote",e),this._status!==Oe.STATUS_TERMINATED&&(e.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(e={}){Ie.debug("answer()");const t=this._request,n=Xt.cloneArray(e.extraHeaders),i=Xt.cloneObject(e.mediaConstraints),s=e.mediaStream||null,a=Xt.cloneObject(e.pcConfig,{iceServers:[]}),o=e.rtcConstraints||null,u=e.rtcAnswerConstraints||null,c=Xt.cloneObject(e.rtcOfferConstraints);let d,p=!1,m=!1,_=!1,y=!1;if(this._rtcAnswerConstraints=u,this._rtcOfferConstraints=e.rtcOfferConstraints||null,this._data=e.data||this._data,this._direction!=="incoming")throw new Xo.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Oe.STATUS_WAITING_FOR_ANSWER)throw new Xo.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Xt.isDecimal(e.sessionTimersExpires)&&(e.sessionTimersExpires>=ye.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=e.sessionTimersExpires:this._sessionTimers.defaultExpires=ye.SESSION_EXPIRES),this._status=Oe.STATUS_ANSWERED,!this._createDialog(t,"UAS")){t.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),n.unshift(`Contact: ${this._contact}`);const b=t.parseSDP();Array.isArray(b.media)||(b.media=[b.media]);for(const S of b.media)S.type==="audio"&&(p=!0,(!S.direction||S.direction==="sendrecv")&&(_=!0)),S.type==="video"&&(m=!0,(!S.direction||S.direction==="sendrecv")&&(y=!0));if(s&&i.audio===!1){d=s.getAudioTracks();for(const S of d)s.removeTrack(S)}if(s&&i.video===!1){d=s.getVideoTracks();for(const S of d)s.removeTrack(S)}!s&&i.audio===void 0&&(i.audio=_),!s&&i.video===void 0&&(i.video=y),!s&&!p&&!c.offerToReceiveAudio&&(i.audio=!1),!s&&!m&&!c.offerToReceiveVideo&&(i.video=!1),this._createRTCConnection(a,o),Promise.resolve().then(()=>{if(s)return s;if(i.audio||i.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(i).catch(S=>{throw this._status===Oe.STATUS_TERMINATED?new Error("terminated"):(t.reply(480),this._failed("local",null,ye.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',S),this.emit("getusermediafailed",S),new Error("getUserMedia() failed"))})}).then(S=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=S,S&&S.getTracks().forEach(w=>{this._connection.addTrack(w,S)})}).then(()=>{if(this._late_sdp)return;const S={originator:"remote",type:"offer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",S);const w=new RTCSessionDescription({type:"offer",sdp:S.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(w)).catch(x=>{throw t.reply(488),this._failed("system",null,ye.causes.WEBRTC_ERROR),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',x),this.emit("peerconnection:setremotedescriptionfailed",x),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(t),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw t.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",u).catch(()=>{throw t.reply(500),new Error("_createLocalDescription() failed")})}).then(S=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(t,n),t.reply(200,null,n,S,()=>{this._status=Oe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,S),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,ye.causes.CONNECTION_ERROR)})}).catch(S=>{this._status!==Oe.STATUS_TERMINATED&&Ie.warn(S)})}terminate(e={}){Ie.debug("terminate()");const t=e.cause||ye.causes.BYE,n=Xt.cloneArray(e.extraHeaders),i=e.body;let s,a=e.status_code,o=e.reason_phrase;if(this._status===Oe.STATUS_TERMINATED)throw new Xo.InvalidStateError(this._status);switch(this._status){case Oe.STATUS_NULL:case Oe.STATUS_INVITE_SENT:case Oe.STATUS_1XX_RECEIVED:if(Ie.debug("canceling session"),a&&(a<200||a>=700))throw new TypeError(`Invalid status_code: ${a}`);a&&(o=o||ye.REASON_PHRASE[a]||"",s=`SIP ;cause=${a} ;text="${o}"`),this._status===Oe.STATUS_NULL||this._status===Oe.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Oe.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Oe.STATUS_CANCELED,this._failed("local",null,ye.causes.CANCELED);break;case Oe.STATUS_WAITING_FOR_ANSWER:case Oe.STATUS_ANSWERED:if(Ie.debug("rejecting session"),a=a||480,a<300||a>=700)throw new TypeError(`Invalid status_code: ${a}`);this._request.reply(a,o,n,i),this._failed("local",null,ye.causes.REJECTED);break;case Oe.STATUS_WAITING_FOR_ACK:case Oe.STATUS_CONFIRMED:if(Ie.debug("terminating session"),o=e.reason_phrase||ye.REASON_PHRASE[a]||"",a&&(a<200||a>=700))throw new TypeError(`Invalid status_code: ${a}`);if(a&&n.push(`Reason: SIP ;cause=${a}; text="${o}"`),this._status===Oe.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==yi.C.STATUS_TERMINATED){const u=this._dialog;this.receiveRequest=({method:c})=>{c===ye.ACK&&(this.sendRequest(ye.BYE,{extraHeaders:n,body:i}),u.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===yi.C.STATUS_TERMINATED&&(this.sendRequest(ye.BYE,{extraHeaders:n,body:i}),u.terminate(),this.closeSession())}),this._ended("local",null,t),this._dialog=u,console.log("SET DIALOG terminate"),this._ua.newDialog(u)}else{const u={janus:"leave"},c=["Content-Type: application/json",this.getPTypeHeader(lr.LEAVE)];this.sendRequest(ye.BYE,{extraHeaders:c,body:JSON.stringify(u)}),this.closeSession(),this._ended("local",null,t)}}}configureMedia(e){this.isAudioOn=e.audio,this.isVideoOn=e.video}enableAudio(e){const t={janus:"message",body:{audio:e},handle_id:this.handle_id,session_id:this.session_id},n=["Content-Type: application/json",this.getPTypeHeader(lr.AUDIO_CHANGE)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t),eventHandlers:{onSuccessResponse:async i=>{i.status_code===200&&(this._ua.emit("changeAudioState",e),this.sendStateMessage({audio:e}))}}})}startAudio(){Xi.toggleAudioMute(this.stream),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Xi.toggleAudioMute(this.stream),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(e){const t={janus:"message",body:{video:e},handle_id:this.handle_id,session_id:this.session_id},n=["Content-Type: application/json",this.getPTypeHeader(lr.VIDEO_CHANGE)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t),eventHandlers:{onSuccessResponse:async i=>{i.status_code===200&&(this._ua.emit("changeVideoState",e),this.sendStateMessage({video:e}))}}})}startVideo(){Xi.toggleVideoMute(this.stream),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Xi.toggleVideoMute(this.stream),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(e){const t={janus:"message",body:{request:"state",data:e},handle_id:this.handle_id,session_id:this.session_id},n=["Content-Type: application/json",this.getPTypeHeader(lr.STATE)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t)})}sendInfo(e,t,n={}){if(Ie.debug("sendInfo()"),this._status!==Oe.STATUS_CONFIRMED&&this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_1XX_RECEIVED)throw new Xo.InvalidStateError(this._status);new nv(this).send(e,t,n)}mute(e={audio:!0,video:!1}){Ie.debug("mute()");let t=!1,n=!1;this._audioMuted===!1&&e.audio&&(t=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&e.video&&(n=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(t===!0||n===!0)&&this._onmute({audio:t,video:n})}unmute(e={audio:!0,video:!0}){Ie.debug("unmute()");let t=!1,n=!1;this._audioMuted===!0&&e.audio&&(t=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&e.video&&(n=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(t===!0||n===!0)&&this._onunmute({audio:t,video:n})}hold(e={},t){if(Ie.debug("hold()"),this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:ye.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}unhold(e={},t){if(Ie.debug("unhold()"),this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const n={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:ye.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:n,extraHeaders:e.extraHeaders}),!0}renegotiate(e={},t){Ie.debug("renegotiate()");const n=e.rtcOfferConstraints||null;if(this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const i={succeeded:()=>{t&&t()},failed:()=>{this.terminate({cause:ye.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),e.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:i,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}):this._sendReinvite({eventHandlers:i,rtcOfferConstraints:n,extraHeaders:e.extraHeaders}),!0}refer(e,t){Ie.debug("refer()");const n=e;if(this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED)return!1;if(e=this._ua.normalizeTarget(e),!e)throw new TypeError(`Invalid target: ${n}`);const i=new uF(this);i.sendRefer(e,t);const s=i.id;return this._referSubscribers[s]=i,i.on("requestFailed",()=>{delete this._referSubscribers[s]}),i.on("accepted",()=>{delete this._referSubscribers[s]}),i.on("failed",()=>{delete this._referSubscribers[s]}),i}sendRequest(e,t){return Ie.debug("sendRequest()"),this._dialog.sendRequest(e,t)}receiveNotify(e){Ie.debug("receiveRequest()")}receiveRequest(e){if(console.log("mmm receiveRequest 1",e),Ie.debug("receiveRequest()"),e.method===ye.CANCEL)(this._status===Oe.STATUS_WAITING_FOR_ANSWER||this._status===Oe.STATUS_ANSWERED)&&(this._status=Oe.STATUS_CANCELED,this._request.reply(487),this._failed("remote",e,ye.causes.CANCELED));else switch(e.method){case ye.ACK:if(this._status!==Oe.STATUS_WAITING_FOR_ACK)return;if(this._status=Oe.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!e.body){this.terminate({cause:ye.causes.MISSING_SDP,status_code:400});break}const t={originator:"remote",type:"answer",sdp:e.body};Ie.debug('emit "sdp"'),this.emit("sdp",t);const n=new RTCSessionDescription({type:"answer",sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>{this._is_confirmed||this._confirmed("remote",e)}).catch(i=>{this.terminate({cause:ye.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',i),this.emit("peerconnection:setremotedescriptionfailed",i)})}else this._is_confirmed||this._confirmed("remote",e);break;case ye.BYE:this._status===Oe.STATUS_CONFIRMED||this._status===Oe.STATUS_WAITING_FOR_ACK?(e.reply(200),this._ended("remote",e,ye.causes.BYE)):this._status===Oe.STATUS_INVITE_RECEIVED||this._status===Oe.STATUS_WAITING_FOR_ANSWER?(e.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",e,ye.causes.BYE)):e.reply(403,"Wrong Status");break;case ye.INVITE:console.log("mmm invite 1"),this._status===Oe.STATUS_CONFIRMED?e.hasHeader("replaces")?this._receiveReplaces(e):this._receiveReinvite(e):e.reply(403,"Wrong Status");break;case ye.INFO:if(this._status===Oe.STATUS_1XX_RECEIVED||this._status===Oe.STATUS_WAITING_FOR_ANSWER||this._status===Oe.STATUS_ANSWERED||this._status===Oe.STATUS_WAITING_FOR_ACK||this._status===Oe.STATUS_CONFIRMED){const t=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0;t&&t.match(/^application\/dtmf-relay/i)?new Q6(this).init_incoming(e):t!==void 0?new nv(this).init_incoming(e):e.reply(415)}else e.reply(403,"Wrong Status");break;case ye.UPDATE:this._status===Oe.STATUS_CONFIRMED?this._receiveUpdate(e):e.reply(403,"Wrong Status");break;case ye.REFER:this._status===Oe.STATUS_CONFIRMED?this._receiveRefer(e):e.reply(403,"Wrong Status");break;case ye.NOTIFY:this._status===Oe.STATUS_CONFIRMED?this._receiveNotify(e):e.reply(403,"Wrong Status");break;default:e.reply(501)}}onTransportError(){Ie.warn("onTransportError()"),this._status!==Oe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ye.causes.CONNECTION_ERROR,cause:ye.causes.CONNECTION_ERROR})}onRequestTimeout(){Ie.warn("onRequestTimeout()"),this._status!==Oe.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ye.causes.REQUEST_TIMEOUT,cause:ye.causes.REQUEST_TIMEOUT})}onDialogError(){Ie.warn("onDialogError()"),this._status!==Oe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ye.causes.DIALOG_ERROR,cause:ye.causes.DIALOG_ERROR})}newDTMF(e){Ie.debug("newDTMF()"),this.emit("newDTMF",e)}newInfo(e){Ie.debug("newInfo()"),this.emit("newInfo",e)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ie.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ie.debug("_isReadyToReOffer() | session not established yet"),!1):(Ie.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Ie.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ie.debug("close() | closing local MediaStream"),Xt.closeMediaStream(this._localMediaStream)),this._status!==Oe.STATUS_TERMINATED){if(this._status=Oe.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(e){Ie.warn("close() | error closing the RTCPeerConnection: %o",e)}for(const e in this._timers)Object.prototype.hasOwnProperty.call(this._timers,e)&&clearTimeout(this._timers[e]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const e in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,e)&&(this._earlyDialogs[e].terminate(),delete this._earlyDialogs[e]);for(const e in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,e)&&delete this._referSubscribers[e];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(e,t){let n=Vd.T1;function i(){this._status===Oe.STATUS_WAITING_FOR_ACK&&(e.reply(200,null,[`Contact: ${this._contact}`],t),n<Vd.T2&&(n=n*2,n>Vd.T2&&(n=Vd.T2)),this._timers.invite2xxTimer=setTimeout(i.bind(this),n))}this._timers.invite2xxTimer=setTimeout(i.bind(this),n)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===Oe.STATUS_WAITING_FOR_ACK&&(Ie.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(ye.BYE),this._ended("remote",null,ye.causes.NO_ACK))},Vd.TIMER_H)}_createRTCConnection(e,t){console.log("pcConfig",e),console.log("rtcConstraints",t),this.stunServers,this._connection=new RTCPeerConnection(e,t),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:ye.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ye.causes.RTP_TIMEOUT})});let n;const i=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(n),n=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=i,Ie.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(e,t){if(Ie.debug("createLocalDescription()"),e!=="offer"&&e!=="answer")throw new Error(`createLocalDescription() | invalid type "${e}"`);const n=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>e==="offer"?(console.log("AAA createOffer",t),n.createOffer(t).catch(i=>(Ie.warn('emit "peerconnection:createofferfailed" [error:%o]',i),this.emit("peerconnection:createofferfailed",i),Promise.reject(i)))):n.createAnswer(t).catch(i=>(Ie.warn('emit "peerconnection:createanswerfailed" [error:%o]',i),this.emit("peerconnection:createanswerfailed",i),Promise.reject(i)))).then(i=>(console.log("AAA setLocalDescription",i),this.jsepOffer=i,n.setLocalDescription(i).catch(s=>(this._rtcReady=!0,Ie.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const i=t&&t.iceRestart;if(n.iceGatheringState==="complete"&&!i||n.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:e,sdp:n.localDescription.sdp};return Ie.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let a=!1,o,u;this._iceReady=!1;const c=()=>{n.removeEventListener("icecandidate",o),n.removeEventListener("icegatheringstatechange",u),a=!0,this._rtcReady=!0,this._iceReady=!0;const d={originator:"local",type:e,sdp:n.localDescription.sdp};Ie.debug('emit "sdp"'),this.emit("sdp",d),s(d.sdp)};n.addEventListener("icecandidate",o=d=>{const p=d.candidate;p?this.emit("icecandidate",{candidate:p,ready:c}):a||c()}),n.addEventListener("icegatheringstatechange",u=()=>{n.iceGatheringState==="complete"&&!a&&c()})})})}_createDialog(e,t,n){console.log("_createDialog",e);const i=t==="UAS"?e.to_tag:e.from_tag,s=t==="UAS"?e.from_tag:e.to_tag,a=e.call_id+i+s;console.log("remote_tag",s);let o=this._earlyDialogs[a];if(n)return o?!0:(o=new Am(this,e,t,Am.C.STATUS_EARLY),console.log("SET DIALOG early"),o.error?(console.log("early_dialog error",o.error),Ie.debug(o.error),this._failed("remote",e,ye.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[a]=o,!0));{if(this._from_tag=e.from_tag,this._to_tag=e.to_tag,o)return o.update(e,t),console.log("SET DIALOG 1"),this._dialog=o,delete this._earlyDialogs[a],!0;const u=new Am(this,e,t);return u.error?(console.log("dialog.error",u.error),Ie.debug(u.error),this._failed("remote",e,ye.causes.INTERNAL_ERROR),!1):(console.log("AAA SET DIALOG 2"),this._dialog=u,!0)}}_receiveReinvite(e){Ie.debug("receiveReinvite()");const t=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0,n={request:e,callback:void 0,reject:s.bind(this)};let i=!1;function s(o={}){i=!0;const u=o.status_code||403,c=o.reason_phrase||"",d=Xt.cloneArray(o.extraHeaders);if(this._status!==Oe.STATUS_CONFIRMED)return!1;if(u<300||u>=700)throw new TypeError(`Invalid status_code: ${u}`);e.reply(u,c,d)}if(this.emit("reinvite",n),i)return;if(this._late_sdp=!1,!e.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(o=>{a.call(this,o)}).catch(()=>{e.reply(500)});return}if(t!=="application/sdp"){Ie.debug("invalid Content-Type"),e.reply(415);return}this._processInDialogSdpOffer(e).then(o=>{this._status!==Oe.STATUS_TERMINATED&&a.call(this,o)}).catch(o=>{Ie.warn(o)});function a(o){const u=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,u),this._late_sdp&&(o=this._mangleOffer(o)),e.reply(200,null,u,o,()=>{this._status=Oe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(e,o),this._setACKTimer()}),typeof n.callback=="function"&&n.callback()}}_receiveUpdate(e){Ie.debug("receiveUpdate()");const t=e.hasHeader("Content-Type")?e.getHeader("Content-Type").toLowerCase():void 0,n={request:e,callback:void 0,reject:s.bind(this)};let i=!1;function s(o={}){i=!0;const u=o.status_code||403,c=o.reason_phrase||"",d=Xt.cloneArray(o.extraHeaders);if(this._status!==Oe.STATUS_CONFIRMED)return!1;if(u<300||u>=700)throw new TypeError(`Invalid status_code: ${u}`);e.reply(u,c,d)}if(this.emit("update",n),i)return;if(!e.body){a.call(this,null);return}if(t!=="application/sdp"){Ie.debug("invalid Content-Type"),e.reply(415);return}this._processInDialogSdpOffer(e).then(o=>{this._status!==Oe.STATUS_TERMINATED&&a.call(this,o)}).catch(o=>{Ie.warn(o)});function a(o){const u=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(e,u),e.reply(200,null,u,o),typeof n.callback=="function"&&n.callback()}}_processInDialogSdpOffer(e){Ie.debug("_processInDialogSdpOffer()");const t=e.parseSDP();let n=!1;for(const a of t.media){if($0.indexOf(a.type)===-1)continue;const o=a.direction||t.direction||"sendrecv";if(o==="sendonly"||o==="inactive")n=!0;else{n=!1;break}}const i={originator:"remote",type:"offer",sdp:e.body};Ie.debug('emit "sdp"'),this.emit("sdp",i);const s=new RTCSessionDescription({type:"offer",sdp:i.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(a=>{throw e.reply(488),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a),a})}).then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&n===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&n===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(a=>{throw e.reply(500),Ie.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',a),a})}).catch(a=>{Ie.warn("_processInDialogSdpOffer() failed [error: %o]",a)}),this._connectionPromiseQueue}_receiveRefer(e){if(Ie.debug("receiveRefer()"),!e.refer_to){Ie.debug("no Refer-To header field present in REFER"),e.reply(400);return}if(e.refer_to.uri.scheme!==ye.SIP){Ie.debug("Refer-To header field points to a non-SIP URI scheme"),e.reply(416);return}e.reply(202);const t=new iF(this,e.cseq);Ie.debug('emit "refer"'),this.emit("refer",{request:e,accept:(s,a)=>{n.call(this,s,a)},reject:()=>{i.call(this)}});function n(s,a={}){if(s=typeof s=="function"?s:null,this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED)return!1;const o=new D0(this._ua);if(o.on("progress",({response:u})=>{t.notify(u.status_code,u.reason_phrase)}),o.on("accepted",({response:u})=>{t.notify(u.status_code,u.reason_phrase)}),o.on("_failed",({message:u,cause:c})=>{u?t.notify(u.status_code,u.reason_phrase):t.notify(487,c)}),e.refer_to.uri.hasHeader("replaces")){const u=decodeURIComponent(e.refer_to.uri.getHeader("replaces"));a.extraHeaders=Xt.cloneArray(a.extraHeaders),a.extraHeaders.push(`Replaces: ${u}`)}o.connect(e.refer_to.uri.toAor(),a,s)}function i(){t.notify(603)}}_receiveNotify(e){switch(Ie.debug("receiveNotify()"),e.event||e.reply(400),e.event.event){case"refer":{let t,n;if(e.event.params&&e.event.params.id)t=e.event.params.id,n=this._referSubscribers[t];else if(Object.keys(this._referSubscribers).length===1)n=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{e.reply(400,"Missing event id parameter");return}if(!n){e.reply(481,"Subscription does not exist");return}n.receiveNotify(e),e.reply(200);break}default:e.reply(489)}}_receiveReplaces(e){Ie.debug("receiveReplaces()");function t(i){if(this._status!==Oe.STATUS_WAITING_FOR_ACK&&this._status!==Oe.STATUS_CONFIRMED)return!1;const s=new D0(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(e,i)}function n(){Ie.debug("Replaced INVITE rejected by the user"),e.reply(486)}this.emit("replaces",{request:e,accept:i=>{t.call(this,i)},reject:()=>{n.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(e,t,n){this.ackSent=!1,this.publisherSubscribeSent=!1;const i=new mc(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(n)return n;if(e.audio||e.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(e).catch(s=>{throw this._status===Oe.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,ye.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(a=>{this._connection.addTrack(a,s)}),this._connecting(this._request),this._createLocalDescription("offer",t).catch(a=>{throw this._failed("local",null,ye.causes.WEBRTC_ERROR),a})}).then(s=>{if(this._is_canceled||this._status===Oe.STATUS_TERMINATED)throw new Error("terminated");const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},o=JSON.stringify(a);this._request.body=o,this._status=Oe.STATUS_INVITE_SENT,Ie.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),i.send()}).catch(s=>{this._status!==Oe.STATUS_TERMINATED&&Ie.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async loadStream(){const e={audio:this.isAudioOn,video:this.isVideoOn};let t=null;try{t=await navigator.mediaDevices.getUserMedia(e)}catch{try{e.video=!1,t=await navigator.mediaDevices.getUserMedia(e)}catch{e.audio=!1,e.video=!1,t=await navigator.mediaDevices.getUserMedia(e)}}return t}addTracks(e){e.forEach(t=>{this._connection.addTrack(t)})}getRecordFileName(){return Sue+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let e=0;e<this.iceCandidates.length;e++)await this._connection.addIceCandidate(this.iceCandidates[e]);this.iceCandidates=[]}async _sendConfigureMessage(e){const t=this._candidates.map(a=>({janus:"trickle",candidate:a,handle_id:this.handle_id,session_id:this.session_id})),i={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...e},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...t]},s=["Content-Type: application/json",this.getPTypeHeader(lr.ICE)];this.sendRequest(ye.INFO,{extraHeaders:s,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async a=>{this.isConfigureSent=!0;const u=a.data.split(`\r
18334
18334
  `),c=u[u.length-1],d=JSON.parse(c);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendMemberStartMessage(e,t){const n={janus:"message",body:{request:"start",room:this.room_id},handle_id:e.handleId,session_id:this.session_id,jsep:t},i=["Content-Type: application/json",this.getPTypeHeader(lr.CONFIGURE)];this.sendRequest(ye.INFO,{extraHeaders:i,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await e.rtcpPeer.setLocalDescription(t)}}})}_sendTrickleMessage(e){const n={trickles:[...e.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},i=[this.getPTypeHeader(lr.TRICKLE)];this.sendRequest(ye.INFO,{extraHeaders:i,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async s=>{console.log("_sendTrickleMessage",s)}}})}async _answerAttachedStream(e,t){let n=null;const i=async u=>{if(!e.rtcpPeer||e.loaded)return;{e.loaded=!0;const _={audio:!0,video:!0};await new Promise(y=>{setTimeout(y,100)}),n=await e.rtcpPeer.createAnswer(_),this._sendMemberStartMessage(e,n)}const c=u.streams[0].getAudioTracks(),d=u.streams[0].getVideoTracks(),p=[];c[0]&&p.push(c[0]),d[0]&&p.push(d[0]);const m=new MediaStream(p);e.stream=m,this._ua.emit("memberJoin",e.memberInfo)};let s,a=[];const o=u=>{e.rtcpPeer.signalingState!=="stable"&&e.rtcpPeer.signalingState!=="have-local-offer"||(a.push(u.candidate||null),clearTimeout(s),s=setTimeout(()=>{this._sendTrickleMessage(a)},500))};e.rtcpPeer=new RTCPeerConnection,e.rtcpPeer.ontrack=i,e.rtcpPeer.onicecandidate=o,e.rtcpPeer.sender=t.sender,await e.rtcpPeer.setRemoteDescription(t.jsep)}_sendJoinMemberRequest(e){const t={janus:"message",body:{request:"join",room:this.room_id,feed:e.info.id,ptype:"subscriber"},handle_id:e.handleId,session_id:this.session_id},n=[this.getPTypeHeader(lr.SUBSCRIBER)];this.sendRequest(ye.SUBSCRIBE,{extraHeaders:n,body:JSON.stringify(t),eventHandlers:{onSuccessResponse:async i=>{var s,a;if(i.status_code===200){const o=JSON.parse(i.body);(a=(s=o==null?void 0:o.plugindata)==null?void 0:s.data)!=null&&a.id&&await this._answerAttachedStream(e,o)}}}})}_attachMember(e){const t={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},n=[this.getPTypeHeader(lr.SUBSCRIBER)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t),eventHandlers:{onSuccessResponse:async i=>{if(i.status_code===200){const a=JSON.parse(i.body).data.id;e.handleId=a,this._sendJoinMemberRequest(e)}}}})}_detachMember(e){const t={janus:"detach",handle_id:e.handleId,session_id:this.session_id},n=[this.getPTypeHeader(lr.SUBSCRIBER)];this.sendRequest(ye.INFO,{extraHeaders:n,body:JSON.stringify(t)}),Xi.stopStreamTracks(e.memberInfo.stream),this._ua.emit("memberHangup",e.memberInfo)}receivePublishers(e){var n,i,s,a,o,u,c,d;console.log("AAA receivePublishers",e);const t={...this.memberList};(i=(n=e==null?void 0:e.plugindata)==null?void 0:n.data)==null||i.publishers.forEach(p=>{delete t[p.id],!this.memberList[p.id]&&!this.myFeedList.includes(p.id)&&p.clientID!==this.client_id&&(console.log("AAA attachMember",p),this.memberList[p.id]=new d8(p,this),this._attachMember(this.memberList[p.id]))}),((a=(s=e==null?void 0:e.plugindata)==null?void 0:s.data)==null?void 0:a.videoroom)==="synced"&&Object.keys(t).forEach(p=>{t[p].hangup(),delete this.memberList[p]}),this.publishers=(u=(o=e==null?void 0:e.plugindata)==null?void 0:o.data)==null?void 0:u.publishers,this.private_id=(d=(c=e==null?void 0:e.plugindata)==null?void 0:c.data)==null?void 0:d.private_id}receiveUnpublished(e){const t=this.memberList[e];t&&(t.hangup(),this._detachMember(t),delete this.memberList[e])}closeSession(){this.stream&&this.stream.getTracks().forEach(t=>{t.stop()}),Object.values(this.memberList).forEach(t=>{t.hangup(),this._detachMember(t)})}async processPlugins(){const e=this._ua.processStreamPlugins;let t=await this.loadStream();for(const n of e)t=await n.process(t);this.stream.getTracks().forEach(n=>{this.stream.removeTrack(n),n.stop()}),t.getTracks().forEach(n=>{this.stream.addTrack(n)})}async resyncPlugins(e){const t=this._ua.processStreamPlugins.filter(n=>n.type===e);for(const n of t)n.running&&n.terminate();if(e==="video"){let n=await this.loadStream();for(const i of t)i.running&&(n=await i.start(n));this.stream.getTracks().forEach(i=>{this.stream.removeTrack(i),i.stop()}),n.getTracks().forEach(i=>{this.stream.addTrack(i)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const n=this._ua.newStreamPlugins.find(o=>o.type===e),i=n.getStream();let s=i.clone();for(const o of t)o.running&&(s=await o.start(s));i.getTracks().forEach(o=>{i.removeTrack(o),o.stop()}),s.getTracks().forEach(o=>{i.addTrack(o.clone()),s.removeTrack(o),o.stop()});const a=n.getConnection();this._overrideSenderTracks(i,a),this._ua.emit("changePluginStream",{type:e,stream:i})}}stopProcessPlugins(e){const t=this._ua.processStreamPlugins.filter(n=>n.type===e);for(const n of t)n.running&&n.terminate()}_receiveInviteResponse(e){if(Ie.debug("receiveInviteResponse()"),console.log("_receiveInviteResponse response",e),console.log("dialog",this._dialog),this._dialog&&e.status_code>=200&&e.status_code<=299&&!this.ackSent)if(console.log("IF 1 dialog"),this._dialog.id.call_id===e.call_id&&this._dialog.id.local_tag===e.from_tag&&this._dialog.id.remote_tag===e.to_tag){this.ackSent=!0,this.sendRequest(ye.ACK);return}else{const t=new Am(this,e,"UAC");if(t.error!==void 0){Ie.debug(t.error);return}this.sendRequest(ye.ACK),this.sendRequest(ye.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const t=JSON.parse(e.body);this.setupMediaStream().then(()=>{this.session_id=t.session_id,this.handle_id=t.data.id,this.client_id=bE();const n={janus:"message",body:{request:"join",room:this.room_id,ptype:"publisher",display:this.display_name,clientID:this.client_id,opaque_id:this.opaque_id},handle_id:this.handle_id},i=[this.getPTypeHeader(lr.PUBLISHER)];this.sendRequest(ye.SUBSCRIBE,{extraHeaders:i,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async s=>{var a,o,u,c;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const d=JSON.parse(s.body)||{};((o=(a=d.plugindata)==null?void 0:a.data)==null?void 0:o.videoroom)==="joined"&&this.myFeedList.push(d.plugindata.data.id),(c=(u=d.plugindata)==null?void 0:u.data)!=null&&c.publishers&&this.receivePublishers(d)}catch(d){console.error(d)}this.lastTrickleReceived&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{})),this._ua.emit("conferenceStart")}}}}),this.publisherSubscribeSent=!0})}if(this._is_canceled){e.status_code>=100&&e.status_code<200?this._request.cancel(this._cancel_reason):e.status_code>=200&&e.status_code<299&&this._acceptAndTerminate(e);return}if(!(this._status!==Oe.STATUS_INVITE_SENT&&this._status!==Oe.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(e.status_code):this._status=Oe.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(e.status_code):{if(!e.to_tag){Ie.debug("1xx response received without to tag");break}if(e.hasHeader("contact")&&!this._createDialog(e,"UAC",!0))break;if(this._status=Oe.STATUS_1XX_RECEIVED,!e.body){this._progress("remote",e);break}const t={originator:"remote",type:"answer",sdp:e.body};Ie.debug('emit "sdp"'),this.emit("sdp",t);const n=new RTCSessionDescription({type:"answer",sdp:t.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(n)).then(()=>this._progress("remote",e)).catch(i=>{Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',i),this.emit("peerconnection:setremotedescriptionfailed",i)});break}case/^2[0-9]{2}$/.test(e.status_code):{if(this._status=Oe.STATUS_CONFIRMED,!e.body){this._acceptAndTerminate(e,400,ye.causes.MISSING_SDP),this._failed("remote",e,ye.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(e,"UAC"))break;break}default:{const t=Xt.sipErrorCause(e.status_code);this._failed("remote",e,t)}}}_sendReinvite(e={}){Ie.debug("sendReinvite()");const t=Xt.cloneArray(e.extraHeaders),n=Xt.cloneObject(e.eventHandlers),i=e.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;t.push(`Contact: ${this._contact}`),t.push("Content-Type: application/sdp"),this._sessionTimers.running&&t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",i)).then(u=>{u=this._mangleOffer(u);const c={originator:"local",type:"offer",sdp:u};Ie.debug('emit "sdp"'),this.emit("sdp",c),console.log("AAA invite 2"),this.sendRequest(ye.INVITE,{extraHeaders:t,body:u,eventHandlers:{onSuccessResponse:d=>{a.call(this,d),s=!0},onErrorResponse:d=>{o.call(this,d)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{o()});function a(u){if(this._status===Oe.STATUS_TERMINATED||(this.sendRequest(ye.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(u),u.body){if(!u.hasHeader("Content-Type")||u.getHeader("Content-Type").toLowerCase()!=="application/sdp"){o.call(this);return}}else{o.call(this);return}const c={originator:"remote",type:"answer",sdp:u.body};Ie.debug('emit "sdp"'),this.emit("sdp",c);const d=new RTCSessionDescription({type:"answer",sdp:c.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(d)).then(()=>{n.succeeded&&n.succeeded(u)}).catch(p=>{o.call(this),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',p),this.emit("peerconnection:setremotedescriptionfailed",p)})}function o(u){n.failed&&n.failed(u)}}_sendUpdate(e={}){Ie.debug("sendUpdate()");const t=Xt.cloneArray(e.extraHeaders),n=Xt.cloneObject(e.eventHandlers),i=e.rtcOfferConstraints||this._rtcOfferConstraints||null,s=e.sdpOffer||!1;let a=!1;t.push(`Contact: ${this._contact}`),this._sessionTimers.running&&t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(t.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",i)).then(c=>{c=this._mangleOffer(c);const d={originator:"local",type:"offer",sdp:c};Ie.debug('emit "sdp"'),this.emit("sdp",d),this.sendRequest(ye.UPDATE,{extraHeaders:t,body:c,eventHandlers:{onSuccessResponse:p=>{o.call(this,p),a=!0},onErrorResponse:p=>{u.call(this,p)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{u.call(this)})):this.sendRequest(ye.UPDATE,{extraHeaders:t,eventHandlers:{onSuccessResponse:c=>{o.call(this,c)},onErrorResponse:c=>{u.call(this,c)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function o(c){if(this._status!==Oe.STATUS_TERMINATED&&!a)if(this._handleSessionTimersInIncomingResponse(c),s){if(c.body){if(!c.hasHeader("Content-Type")||c.getHeader("Content-Type").toLowerCase()!=="application/sdp"){u.call(this);return}}else{u.call(this);return}const d={originator:"remote",type:"answer",sdp:c.body};Ie.debug('emit "sdp"'),this.emit("sdp",d);const p=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(p)).then(()=>{n.succeeded&&n.succeeded(c)}).catch(m=>{u.call(this),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',m),this.emit("peerconnection:setremotedescriptionfailed",m)})}else n.succeeded&&n.succeeded(c)}function u(c){n.failed&&n.failed(c)}}_acceptAndTerminate(e,t,n){Ie.debug("acceptAndTerminate()");const i=[];t&&(n=n||ye.REASON_PHRASE[t]||"",i.push(`Reason: SIP ;cause=${t}; text="${n}"`)),(this._dialog||this._createDialog(e,"UAC"))&&(this.sendRequest(ye.ACK),this.sendRequest(ye.BYE,{extraHeaders:i})),this._status=Oe.STATUS_TERMINATED}_mangleOffer(e){if(!this._localHold&&!this._remoteHold)return e;if(e=Vr.parse(e),this._localHold&&!this._remoteHold){Ie.debug("mangleOffer() | me on hold, mangling offer");for(const t of e.media)$0.indexOf(t.type)!==-1&&(t.direction?t.direction==="sendrecv"?t.direction="sendonly":t.direction==="recvonly"&&(t.direction="inactive"):t.direction="sendonly")}else if(this._localHold&&this._remoteHold){Ie.debug("mangleOffer() | both on hold, mangling offer");for(const t of e.media)$0.indexOf(t.type)!==-1&&(t.direction="inactive")}else if(this._remoteHold){Ie.debug("mangleOffer() | remote on hold, mangling offer");for(const t of e.media)$0.indexOf(t.type)!==-1&&(t.direction?t.direction==="sendrecv"?t.direction="recvonly":t.direction==="recvonly"&&(t.direction="inactive"):t.direction="recvonly")}return Vr.write(e)}_setLocalMediaStatus(){let e=!0,t=!0;(this._localHold||this._remoteHold)&&(e=!1,t=!1),this._audioMuted&&(e=!1),this._videoMuted&&(t=!1),this._toggleMuteAudio(!e),this._toggleMuteVideo(!t)}_handleSessionTimersInIncomingRequest(e,t){if(!this._sessionTimers.enabled)return;let n;e.session_expires&&e.session_expires>=ye.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=e.session_expires,n=e.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uas"),t.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${n}`),this._sessionTimers.refresher=n==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(e){if(!this._sessionTimers.enabled)return;let t;e.session_expires&&e.session_expires>=ye.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=e.session_expires,t=e.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,t="uac"),this._sessionTimers.refresher=t==="uac",this._runSessionTimer()}_runSessionTimer(){const e=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==Oe.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Ie.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===ye.UPDATE?this._sendUpdate():this._sendReinvite())},e*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==Oe.STATUS_TERMINATED&&(Ie.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:ye.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},e*1100)}_toggleMuteAudio(e){const t=this._connection.getSenders().filter(n=>n.track&&n.track.kind==="audio");for(const n of t)n.track.enabled=!e}_toggleMuteVideo(e){const t=this._connection.getSenders().filter(n=>n.track&&n.track.kind==="video");for(const n of t)n.track.enabled=!e}_newJanusSession(e,t){Ie.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:e,session:this,request:t})}_connecting(e){Ie.debug("session connecting"),Ie.debug('emit "connecting"'),this.emit("connecting",{request:e})}_progress(e,t){Ie.debug("session progress"),Ie.debug('emit "progress"'),this.emit("progress",{originator:e,response:t||null})}_accepted(e,t){Ie.debug("session accepted"),this._start_time=new Date,Ie.debug('emit "accepted"'),this.emit("accepted",{originator:e,response:t||null})}_confirmed(e,t){Ie.debug("session confirmed"),this._is_confirmed=!0,Ie.debug('emit "confirmed"'),this.emit("confirmed",{originator:e,ack:t||null})}_ended(e,t,n){Ie.debug("session ended"),this._end_time=new Date,this._close(),Ie.debug('emit "ended"'),this.emit("ended",{originator:e,message:t||null,cause:n})}_failed(e,t,n){Ie.debug("session failed"),Ie.debug('emit "_failed"'),this.emit("_failed",{originator:e,message:t||null,cause:n}),this._close(),Ie.debug('emit "failed"'),this.emit("failed",{originator:e,message:t||null,cause:n})}_onhold(e){Ie.debug("session onhold"),this._setLocalMediaStatus(),Ie.debug('emit "hold"'),this.emit("hold",{originator:e})}_onunhold(e){Ie.debug("session onunhold"),this._setLocalMediaStatus(),Ie.debug('emit "unhold"'),this.emit("unhold",{originator:e})}_onmute({audio:e,video:t}){Ie.debug("session onmute"),this._setLocalMediaStatus(),Ie.debug('emit "muted"'),this.emit("muted",{audio:e,video:t})}_onunmute({audio:e,video:t}){Ie.debug("session onunmute"),this._setLocalMediaStatus(),Ie.debug('emit "unmuted"'),this.emit("unmuted",{audio:e,video:t})}}class Jc{constructor(e){if(this.headers={},e.length>0){let t=!1;const n=e.split(`\r
18335
18335
  `),i=n.shift().split(/\s/);this.protocol=i[0],this.ident=i[1],this.code=i.length>3?parseInt(i[2]):0,this.method=i.length>3?i[3]:i[2],this.body="";for(const s of n){if(s==`-------${this.ident}$`)break;if(s===""){t=!0;continue}if(s&&t)this.body+=`${s}\r
18336
18336
  `;else{const a=s.split(": ");this.addHeader(a[0],a[1].trim())}}}else this.ident=Xt.createRandomToken(12),this.protocol="MSRP"}addHeader(e,t){this.headers[e]=t}getHeader(e){return this.headers[e]}toString(){let e=`${this.protocol} ${this.ident} ${this.code} ${this.method}`.replaceAll(/null\s|undefined\s/ig,"")+`\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicenter-team/opensips-js",
3
- "version": "1.0.103",
3
+ "version": "1.0.105",
4
4
  "description": "The JS package for opensips",
5
5
  "default": "src/index.ts",
6
6
  "jsdelivr": "dist/opensips-js.iife.js",
@@ -43,8 +43,8 @@
43
43
  "@typescript-eslint/eslint-plugin": "^5.53.0",
44
44
  "@typescript-eslint/parser": "^5.53.0",
45
45
  "@vitejs/plugin-vue": "^4.2.3",
46
- "@voicenter-team/eslint-config-ts": "^1.0.21",
47
46
  "@voicenter-team/aws-uploader": "^1.0.10",
47
+ "@voicenter-team/eslint-config-ts": "^1.0.21",
48
48
  "cross-env": "^7.0.3",
49
49
  "dotenv": "^16.0.3",
50
50
  "eslint": "^8.35.0",
@@ -61,6 +61,7 @@
61
61
  "dependencies": {
62
62
  "@mediapipe/selfie_segmentation": "^0.1.1675465747",
63
63
  "@tensorflow-models/body-segmentation": "^1.0.2",
64
+ "@tensorflow/tfjs": "^4.22.0",
64
65
  "@tensorflow/tfjs-backend-wasm": "^4.22.0",
65
66
  "@tensorflow/tfjs-backend-webgl": "^4.22.0",
66
67
  "@tensorflow/tfjs-backend-webgpu": "^4.22.0",