JAVASCRIPT   19

webrtc

Guest on 4th July 2022 07:27:44 PM

  1. //
  2.  
  3. class WebRTC
  4.   {
  5.   // from developer.mozilla.org:
  6.   CertExampleRSA =
  7.     { name:     'RSASSA-PKCS1-v1_5'
  8.     , hash:     'SHA-256'
  9.     , modulusLength:    2048
  10.     , publicExponent:   new Uint8Array([1,0,1])
  11.     };
  12.   CertECDSA     =
  13.     { name:             'ECDSA'
  14.     , namedCurve:       'P-256'
  15.     };
  16.  
  17.   constructor()
  18.     {
  19.       this._opt = {};
  20.       this._cb  = [];
  21.     }
  22.   opt(name, def)
  23.     {
  24.       return this._opt[name] || ( this._opt[name] = def );
  25.     }
  26.   async genCert(opt)
  27.     {
  28.       this.opt('certificates', []).push(await RTCPeerConnection.generateCertificate(opt));
  29.     }
  30.   async create()
  31.     {
  32.       const pc = this.pc                = new RTCPeerConnection(this.opt);
  33.       pc.onconnectionstatechange        = _ => this.CB(_, 'constate',   this.pc.connectionState);
  34.       pc.ondatachannel                  = _ => this.CB(_, 'chan',       this.chanAdd(_.channel));
  35.       pc.onicecandidate                 = _ => this.CB(_, 'ice',        this.iceAdd(_.candidate));
  36.       pc.onicecandidateerror            = _ => this.CB(_, 'iceErr',     {err:_.errorCode, url:_.url, txt:_.errorText, address:_.address, port:_.port});
  37.       pc.oniceconnectionstatechange     = _ => this.CB(_, 'iceCState',  this.pc.iceConnectionState);
  38.       pc.onicegatheringstatechange      = _ => this.CB(_, 'iceGather',  this.pc.iceGatheringState);
  39.       pc.onnegotiationneeded            = _ => this.CB(_, 'negotiate',  this.negotiate());
  40.       pc.onsignalingstatechange         = _ => this.CB(_, 'signal',     this.signalingState);
  41.       pc.ontrack                        = _ => this.CB(_, 'track',      this.trackAdd({receiver:_.receiver,streams:_.streams,track:_.track,transceiver:_.transceiver}));
  42.     }
  43.   async CB(e,k,v)
  44.     {
  45.       v = await v;
  46.       console('CB', {k,v,e});
  47.       for (const [fn,a] of this._cb)
  48.         {
  49.           const r = await fn(...a,k,v,e,this);
  50.           if (r === false)
  51.             break;
  52.           if (r !== void 0)
  53.             v = r;
  54.         }
  55.     }
  56.   cb(fn, ...args)
  57.     {
  58.       this._cb.unshift([fn,args]);
  59.     }
  60.   chanAdd(chan)
  61.     {
  62.       return chan;
  63.     }
  64.   iceAdd(cand)
  65.     {
  66.       return cand;
  67.     }
  68.   negotiate()
  69.     {
  70.       const o   = await this.pc.createOffer();
  71.       this.pc.setLocalDescription(await this.pc.createOffer());
  72.       return this.pc.localDescription;
  73.     }
  74.   trackAdd(t)
  75.     {
  76.       return t;
  77.     }
  78.   };

Raw Paste


Login or Register to edit or fork this paste. It's free.