UNPKG

wowza-webrtc-player

Version:
7 lines (6 loc) 14.9 kB
/** * @license wowza-webrtc-player 1.1.0 * Copyright (c) 2018-2024 Koala Interactive, Inc. * License: MIT */ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("sdp-transform");function t(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function r(e){return function(){var r=this,n=arguments;return new Promise((function(i,s){var o=e.apply(r,n);function a(e){t(o,i,s,a,c,"next",e)}function c(e){t(o,i,s,a,c,"throw",e)}a(void 0)}))}}function n(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?i(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function o(){}function a(){a.init.call(this)}function c(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function d(e,t,r){if(t)e.call(r);else for(var n=e.length,i=g(e,n),s=0;s<n;++s)i[s].call(r)}function l(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=g(e,i),o=0;o<i;++o)s[o].call(r,n)}function u(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=g(e,s),a=0;a<s;++a)o[a].call(r,n,i)}function p(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=g(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}function f(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=g(e,i),o=0;o<i;++o)s[o].apply(r,n)}function h(e,t,r,n){var i,s,a,d;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),a=s[t]):(s=e._events=new o,e._eventsCount=0),a){if("function"==typeof a?a=s[t]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),!a.warned&&(i=c(e))&&i>0&&a.length>i){a.warned=!0;var l=Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,d=l,"function"==typeof console.warn?console.warn(d):console.log(d)}}else a=s[t]=r,++e._eventsCount;return e}function m(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function v(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function g(e,t){for(var r=Array(t);t--;)r[t]=e[t];return r}o.prototype=Object.create(null),a.EventEmitter=a,a.usingDomains=!1,a.prototype.domain=void 0,a.prototype._events=void 0,a.prototype._maxListeners=void 0,a.defaultMaxListeners=10,a.init=function(){this.domain=null,a.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new o,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var h=Error('Uncaught, unspecified "error" event. ('+t+")");throw h.context=t,h}return t||(t=Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var m="function"==typeof r;switch(n=arguments.length){case 1:d(r,m,this);break;case 2:l(r,m,this,arguments[1]);break;case 3:u(r,m,this,arguments[1],arguments[2]);break;case 4:p(r,m,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];f(r,m,this,i)}return!0},a.prototype.addListener=function(e,t){return h(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return h(this,e,t,!0)},a.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,m(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,m(this,e,t)),this},a.prototype.removeListener=function(e,t){var r,n,i,s,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new o:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){a=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new o,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,a||t)}return this},a.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new o,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new o:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new o,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},a.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):v.call(e,t)},a.prototype.listenerCount=v,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var y=window.RTCPeerConnection,w=window.RTCIceCandidate,b=window.RTCSessionDescription;class C extends a{constructor(e){super(),n(this,"pc",void 0),this.pc=new y({iceServers:e}),"ontrack"in this.pc?this.pc.ontrack=this.handleTrackEvent.bind(this):this.pc.onaddstream=this.handleNewStreamEvent.bind(this)}getPeerConnection(){return this.pc}close(){this.pc.close()}setRemoteDescription(e){return this.pc.setRemoteDescription(new b(e))}setLocalDescription(e){return this.pc.setLocalDescription(new b(e))}createAnswer(){var e=this;return r((function*(){return e.pc.createAnswer()}))()}createOffer(){var e=this;return r((function*(){return e.pc.createOffer()}))()}attachIceCandidate(e){return this.pc.addIceCandidate(new w(e))}attachMediaStream(e){var t=this.pc,r=t.getSenders(),n=e.getTracks();r.length?n.forEach(e=>{r.filter(t=>{var r;return(null===(r=t.track)||void 0===r?void 0:r.kind)===e.kind}).forEach(t=>{t.replaceTrack(e)})}):n.forEach(r=>{t.addTrack(r,e)})}handleNewStreamEvent(e){var{stream:t}=e;this.emit("addstream",t)}handleTrackEvent(e){e.streams.forEach(e=>{this.emit("addstream",e)})}}class S{constructor(e,t,r){this.url=e,this.streamInfo=t,this.userData=r,n(this,"ws",null),n(this,"pendingCommands",new Map)}connect(){return this.ws?Promise.resolve(this.ws):new Promise((e,t)=>{var r=new WebSocket(this.url);r.binaryType="arraybuffer",r.onopen=()=>e(r),r.onerror=()=>t(),r.onclose=()=>t(),r.onmessage=this.handleSocketData.bind(this),this.ws=r})}disconnect(){this.ws&&(this.ws.close(),this.ws=null)}getOffer(){var e={direction:"play",command:"getOffer"};return this.streamInfo.secureToken&&(e.secureToken=this.streamInfo.secureToken),this.send(e)}sendOffer(e){return this.send({direction:"publish",command:"sendOffer",sdp:e})}sendResponse(e){return this.send({direction:"play",command:"sendResponse",sdp:e})}getAvailableStreams(){return this.send({direction:"play",command:"getAvailableStreams"})}send(e){var t=this;return r((function*(){var r,n=t.ws||(yield t.connect());return t.pendingCommands.has(e.command)||t.pendingCommands.set(e.command,((r={}).promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r)),n.send(JSON.stringify(s(s({},e),{},{streamInfo:t.streamInfo,userData:t.userData}))),t.pendingCommands.get(e.command).promise}))()}handleSocketData(e){var t,r=JSON.parse(e.data);200===r.status?(null!==(t=r.streamInfo)&&void 0!==t&&t.sessionId&&(this.streamInfo.sessionId=r.streamInfo.sessionId),this.pendingCommands.has(r.command)&&(this.pendingCommands.get(r.command).resolve(r),this.pendingCommands.delete(r.command))):this.pendingCommands.has(r.command)&&(this.pendingCommands.get(r.command).reject(r),this.pendingCommands.delete(r.command))}}var L="mozGetUserMedia"in navigator?"firefox":"webkitGetUserMedia"in navigator||!1===window.isSecureContext&&"webkitRTCPeerConnection"in window&&!("RTCIceGatherer"in window)?"chrome":navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)?"edge":window.RTCPeerConnection&&navigator.userAgent.match(/AppleWebKit\/(\d+)\./)?"safari":"unknown",O=["opus","isac","g722","pcmu","pcma","cn"],P=["vp9","vp8","h264","red","ulpfec","rtx","av1"];class _{constructor(e,t){this.videoOptions=e,this.audioOptions=t}transformPlay(t){if(!t.sdp)return t;var r=e.parse(t.sdp);return r.media.forEach(e=>{e.fmtp.forEach(e=>{e.config=e.config.replace(/profile-level-id=(\w+)/gi,(e,t)=>{var r=parseInt(t,16),n=r>>16&255,i=r>>8&255,s=255&r;return n>66?(n=66,i=224,s=31):0===i&&(i=224),"profile-level-id=".concat((n<<16|i<<8|s).toString(16))})})}),t.sdp=e.write(r),t}transformPublish(t){if(!t.sdp)return t;var r=e.parse(t.sdp),n={audio:{config:this.audioOptions,supportedFormats:O},video:{config:this.videoOptions,supportedFormats:P}};return r.media.forEach(e=>{var t="video"===e.type?n.video:"audio"===e.type?n.audio:null;if(t){var r=t.config;r.bitRate&&["firefox","safari"].includes(L)&&(e.bandwidth=(e.bandwidth||[]).filter(e=>!["TIAS","AS","CT"].includes(e.type)).concat({type:"TIAS",limit:1e3*r.bitRate*.95-16e3},{type:"AS",limit:1e3*r.bitRate},{type:"CT",limit:1e3*r.bitRate})),"frameRate"in r&&(e.framerate=r.frameRate);for(var i=function(n){var i,o=e.rtp[n];if(!t.supportedFormats.includes(o.codec.toLowerCase()))return e.rtp.splice(n,1),e.fmtp=e.fmtp.filter(e=>e.payload!==o.payload),e.payloads=e.rtp.map(e=>e.payload).join(" "),e.rtcpFb=null===(i=e.rtcpFb)||void 0===i?void 0:i.filter(e=>e.payload!==o.payload),s=n,1;r.bitRate&&"chrome"===L&&e.fmtp.filter(e=>e.payload===o.payload).forEach(e=>{e.config=e.config.replace(/;?x-google-(min|max)-bitrate=(\d+)/g,""),e.config+=";x-google-min-bitrate=".concat(r.bitRate,";x-google-max-bitrate=").concat(r.bitRate)}),n++,s=n},s=0;s<e.rtp.length;)i(s)}}),t.sdp=e.write(r),t}}exports.WowzaWebRTCPlayer=class extends a{constructor(e,t){super(),this.video=e,n(this,"sdpUrl",""),n(this,"applicationName",""),n(this,"streamName",""),n(this,"userData",null),n(this,"sdpHandler",void 0),n(this,"secureToken",void 0),n(this,"constraints",{audio:!0,video:!0}),n(this,"videoConfigs",{bitRate:360,codec:"42e01f",frameRate:29.97}),n(this,"audioConfigs",{codec:"opus",bitRate:64}),n(this,"iceServers",[]),n(this,"mediaStream",null),n(this,"pc",null),t&&this.setConfigurations(t)}setConfigurations(e){e.constraints&&(this.constraints=e.constraints),e.videoConfigs&&(this.videoConfigs=e.videoConfigs),e.audioConfigs&&(this.audioConfigs=e.audioConfigs),e.applicationName&&(this.applicationName=e.applicationName),e.streamName&&(this.streamName=e.streamName),e.sdpUrl&&(this.sdpUrl=e.sdpUrl),void 0!==e.userData&&(this.userData=e.userData),e.iceServers&&(this.iceServers=e.iceServers),e.sdpHandler&&(this.sdpHandler=e.sdpHandler),e.secureToken&&(this.secureToken=e.secureToken)}stop(){this.pc&&(this.pc.close(),this.pc=null)}getMediaStream(){return this.mediaStream}getPeerConnection(){return this.pc?this.pc.getPeerConnection():null}playLocal(e){var t=this;return r((function*(){e&&(t.constraints=e);var r=yield function(e){var t;return null!==(t=navigator.mediaDevices)&&void 0!==t&&t.getUserMedia?navigator.mediaDevices.getUserMedia(e):"getUserMedia"in navigator?new Promise((t,r)=>{navigator.getUserMedia(e,t,r)}):Promise.reject("Your browser does not support getUserMedia API")}(t.constraints);return t.attachStream(r),r}))()}stopLocal(){this.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop()}),this.mediaStream=null)}playRemote(e){var t=this;return r((function*(){e&&t.setConfigurations(e);var r=t.createWowzaInstance();try{var{sdp:n}=yield r.getOffer(),i=t.createPeerConnection();i.on("addstream",t.attachStream.bind(t)),yield i.setRemoteDescription(n);var s=yield i.createAnswer(),o=new _(t.videoConfigs,t.audioConfigs),a=t.sdpHandler?t.sdpHandler(s,e=>o.transformPlay(e),"play"):o.transformPlay(s);yield i.setLocalDescription(a);var{iceCandidates:c}=yield r.sendResponse(a);c.forEach(e=>{i.attachIceCandidate(e)})}finally{r.disconnect()}}))()}publish(e){var t=this;return r((function*(){e&&t.setConfigurations(e);var r=t.createWowzaInstance();try{var n=t.mediaStream||(yield t.playLocal()),i=t.createPeerConnection();i.attachMediaStream(n);var s=new _(t.videoConfigs,t.audioConfigs),o=yield i.createOffer(),a=t.sdpHandler?t.sdpHandler(o,e=>s.transformPublish(e),"publish"):s.transformPublish(o);yield i.setLocalDescription(a);var{sdp:c,iceCandidates:d}=yield r.sendOffer(a);yield i.setRemoteDescription(c),d.forEach(e=>{i.attachIceCandidate(e)})}finally{r.disconnect()}}))()}getAvailableStreams(){var e=this;return r((function*(){var t=e.createWowzaInstance();try{var{availableStreams:r}=yield t.getAvailableStreams();return r||[]}catch(e){return[]}finally{t.disconnect()}}))()}createWowzaInstance(){return new S(this.sdpUrl,{applicationName:this.applicationName,sessionId:"[empty]",streamName:this.streamName,secureToken:this.secureToken},this.userData)}createPeerConnection(){return this.pc=new C(this.iceServers),this.pc}attachStream(e){this.mediaStream=e;try{var t=this.video.srcObject instanceof MediaStream&&this.video.srcObject;t&&t.id===e.id||(this.video.srcObject=e)}catch(t){this.video.src=window.URL.createObjectURL(e)}this.pc&&this.pc.attachMediaStream(e),this.video.play()}};