UNPKG

wowza-webrtc-player

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