trtc-sdk-v5 5.15.0-beta.20 → 5.15.0-beta.21

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.
Files changed (33) hide show
  1. package/assets/debug-dialog.js +2 -2
  2. package/assets/videodec.wasm +0 -0
  3. package/assets/videodec_simd.wasm +0 -0
  4. package/index.d.ts +8 -2
  5. package/package.json +1 -1
  6. package/plugins/cdn-streaming/package.json +1 -1
  7. package/plugins/chorus/package.json +1 -1
  8. package/plugins/cross-room/package.json +1 -1
  9. package/plugins/custom-encryption/package.json +1 -1
  10. package/plugins/device-detector/package.json +1 -1
  11. package/plugins/fast-webrtc/fast-webrtc.esm.d.ts +27 -0
  12. package/plugins/fast-webrtc/fast-webrtc.esm.js +1 -0
  13. package/plugins/fast-webrtc/fast-webrtc.umd.js +1 -0
  14. package/plugins/fast-webrtc/package.json +29 -0
  15. package/plugins/lebplayer/lebplayer.esm.d.ts +260 -0
  16. package/plugins/lebplayer/lebplayer.esm.js +1 -0
  17. package/plugins/lebplayer/lebplayer.umd.js +1 -0
  18. package/plugins/lebplayer/package.json +29 -0
  19. package/plugins/small-stream-auto-switcher/package.json +1 -1
  20. package/plugins/video-decoder/package.json +1 -1
  21. package/plugins/video-decoder/video-decoder.esm.js +1 -1
  22. package/plugins/video-decoder/video-decoder.umd.js +1 -1
  23. package/plugins/video-effect/basic-beauty/package.json +1 -1
  24. package/plugins/video-effect/beauty/package.json +1 -1
  25. package/plugins/video-effect/video-mixer/package.json +1 -1
  26. package/plugins/video-effect/video-mixer/video-mixer.esm.d.ts +2 -0
  27. package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
  28. package/plugins/video-effect/video-mixer/video-mixer.umd.js +1 -1
  29. package/plugins/video-effect/virtual-background/package.json +1 -1
  30. package/plugins/video-effect/watermark/package.json +1 -1
  31. package/plugins/voice-changer/package.json +1 -1
  32. package/trtc.esm.js +42 -38
  33. package/trtc.js +1 -1
File without changes
File without changes
package/index.d.ts CHANGED
@@ -9,9 +9,10 @@ import { CustomEncryption, EncryptionOptions } from './plugins/custom-encryption
9
9
  import { VideoMixerOptions, UpdateVideoMixerOptions, VideoMixer } from './plugins/video-effect/video-mixer';
10
10
  import { SmallStreamAutoSwitcher, SmallStreamAutoSwitcherOptions } from './plugins/small-stream-auto-switcher';
11
11
  import { Chorus, StartChorusOption, UpdateChorusOption } from './plugins/chorus';
12
+ import { LEBPlayer, StartLEBPlayerOption, UpdateLEBPlayerOption } from './plugins/lebplayer';
12
13
 
13
14
  export { CDNStreamingOptions, DeviceDetectorOptions, VirtualBackgroundOptions, UpdateVirtualBackgroundOptions, WatermarkOptions, BeautyOptions, UpdateBeautyOptions, BasicBeautyOptions, StartCrossRoomOption, UpdateCrossRoomOption, StopCrossRoomOption, SmallStreamAutoSwitcherOptions, VideoMixerOptions, UpdateVideoMixerOptions };
14
- type TRTCPlugin = typeof CrossRoom | typeof CDNStreaming | typeof DeviceDetector | typeof VirtualBackground | typeof Watermark | typeof Beauty | typeof BasicBeauty | typeof CustomEncryption | typeof SmallStreamAutoSwitcher | typeof VideoMixer | typeof Chorus;
15
+ type TRTCPlugin = typeof CrossRoom | typeof CDNStreaming | typeof DeviceDetector | typeof VirtualBackground | typeof Watermark | typeof Beauty | typeof BasicBeauty | typeof CustomEncryption | typeof SmallStreamAutoSwitcher | typeof VideoMixer | typeof Chorus | typeof LEBPlayer;
15
16
  export type ExperimentalAPIFunctionMap = {
16
17
  'enableAudioFrameEvent': EnableAudioFrameEventOptions;
17
18
  'resumeRemotePlayer': RemotePlayerOptions;
@@ -36,6 +37,7 @@ export declare type PluginStartOptionsMap = {
36
37
  'SmallStreamAutoSwitcher': SmallStreamAutoSwitcherOptions;
37
38
  'AudioProcessor': InitAudioProcessorOptions;
38
39
  'Chorus': StartChorusOption;
40
+ 'LEBPlayer': StartLEBPlayerOption;
39
41
  };
40
42
 
41
43
  export declare type PluginUpdateOptionsMap = {
@@ -51,6 +53,7 @@ export declare type PluginUpdateOptionsMap = {
51
53
  'AudioProcessor': UpdateAudioProcessorOptions;
52
54
  'Debug': UpdateDebugOptions;
53
55
  'Chorus': UpdateChorusOption;
56
+ 'LEBPlayer': UpdateLEBPlayerOption;
54
57
  };
55
58
 
56
59
  export declare type PluginStopOptionsMap = {
@@ -69,6 +72,7 @@ export declare type PluginStopOptionsMap = {
69
72
  'AudioProcessor': undefined;
70
73
  'CustomEncryption': undefined;
71
74
  'Chorus': undefined;
75
+ 'LEBPlayer': undefined;
72
76
  };
73
77
 
74
78
  export declare class RtcError extends Error implements RTCErrorInterface {
@@ -338,6 +342,7 @@ export declare type PluginWithAssets = {
338
342
  export declare interface TRTCOptions {
339
343
  plugins?: Array<TRTCPlugin>;
340
344
  enableSEI?: boolean;
345
+ enableAutoPlayDialog?: boolean;
341
346
  assetsPath?: string;
342
347
  volumeType?: number;
343
348
  enableAutoSwitchWhenRecapturing?: boolean;
@@ -411,7 +416,6 @@ export declare interface SwitchRoomConfig {
411
416
  export declare interface ScreenShareConfig {
412
417
  view?: string | HTMLElement | HTMLElement[] | null;
413
418
  publish?: boolean;
414
- streamType?: TRTCStreamType;
415
419
  muteSystemAudio?: boolean;
416
420
  option?: {
417
421
  profile?: keyof typeof screenProfileMap | VideoProfile;
@@ -446,6 +450,8 @@ export declare interface RemoteVideoConfig {
446
450
  canvasRender?: boolean;
447
451
  poster?: string;
448
452
  draggable?:boolean;
453
+ pictureInPicture?: boolean;
454
+ fullScreen?: boolean;
449
455
  };
450
456
  }
451
457
  export declare interface StopRemoteVideoConfig {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trtc-sdk-v5",
3
- "version": "5.15.0-beta.20",
3
+ "version": "5.15.0-beta.21",
4
4
  "description": "Tencent Cloud RTC SDK for Web",
5
5
  "main": "trtc.js",
6
6
  "types": "index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/cdn-streaming",
3
- "version": "5.14.1",
3
+ "version": "5.15.0-beta.21",
4
4
  "description": "TRTC Web SDK 5.x CDN streaming plugin",
5
5
  "main": "./cdn-streaming.esm.js",
6
6
  "module": "./cdn-streaming.esm.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/chorus",
3
- "version": "5.14.1",
3
+ "version": "5.15.0-beta.21",
4
4
  "description": "TRTC Web SDK 5.x Chorus plugin",
5
5
  "main": "./chorus.esm.js",
6
6
  "module": "./chorus.esm.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/cross-room",
3
- "version": "5.14.1",
3
+ "version": "5.15.0-beta.21",
4
4
  "description": "TRTC Web SDK 5.x Cross Room plugin",
5
5
  "main": "./cross-room.esm.js",
6
6
  "module": "./cross-room.esm.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/custom-encryption",
3
- "version": "5.14.1",
3
+ "version": "5.15.0-beta.21",
4
4
  "main": "./custom-encryption.esm.js",
5
5
  "module": "./custom-encryption.esm.js",
6
6
  "types": "./custom-encryption.esm.d.ts"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/device-detector",
3
- "version": "5.14.1",
3
+ "version": "5.15.0-beta.21",
4
4
  "description": "TRTC Web SDK 5.x device detector plugin",
5
5
  "main": "./device-detector.esm.js",
6
6
  "module": "./device-detector.esm.js",
@@ -0,0 +1,27 @@
1
+ export interface StartCrossRoomOption {
2
+ roomId?: number,
3
+ strRoomId?: string,
4
+ userId?: string
5
+ }
6
+
7
+ interface UpdateCrossRoomOptionItem extends StartCrossRoomOption {
8
+ muteAudio: boolean,
9
+ muteVideo: boolean,
10
+ muteSubStream: boolean,
11
+ }
12
+
13
+ export interface UpdateCrossRoomOption {
14
+ updateList: UpdateCrossRoomOptionItem[]
15
+ }
16
+
17
+ export interface StopCrossRoomOption {
18
+ roomId?: number,
19
+ strRoomId?: string,
20
+ }
21
+
22
+
23
+ export declare class CrossRoom {
24
+ start(option: StartCrossRoomOption): Promise<void>;
25
+ update(option: UpdateCrossRoomOption): Promise<void>;
26
+ stop(option?: StopCrossRoomOption): Promise<void>;
27
+ }
@@ -0,0 +1 @@
1
+ var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,r)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__spreadValues=(e,t)=>{for(var r in t||(t={}))__hasOwnProp.call(t,r)&&__defNormalProp(e,r,t[r]);if(__getOwnPropSymbols)for(var r of __getOwnPropSymbols(t))__propIsEnum.call(t,r)&&__defNormalProp(e,r,t[r]);return e},__publicField=(e,t,r)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,r),StartValidateRule={name:"option",required:!0,properties:{view:{type:["string",HTMLElement],required:!0},url:{type:"string",required:!0},licenseConfig:{type:"object",required:!0,properties:{secretKey:{type:"string",required:!0},encrypted:{type:"string",required:!0},signature:{type:"string",required:!0}}}}},updateSdpForFirefox=e=>{if(!navigator.userAgent.includes("Firefox"))return e;const t=e.split("\r\n"),r=[],o=[];t.forEach((e=>{const t=e.toLowerCase();t.includes("a=rtpmap")&&t.includes("h264")&&r.push(e)})),r.length>1&&o.push(...r.slice(1));const s=o.map((e=>{const t=/a=rtpmap:(\d+)\s/.exec(e);return t&&t.length>1?t[1]:null})).filter((e=>null!==e)),i=[];return t.forEach((e=>{let t=e;if(e.includes("a=setup")&&(t="a=setup:passive"),(e.includes("m=audio")||e.includes("m=video"))&&(t=e.split(" ").filter(((e,t)=>t<3||!s.includes(e))).join(" ")),e.includes("a=fmtp")||e.includes("a=rtcp-fb")||e.includes("a=rtpmap")){const t=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(e);if(t&&t.length>1&&s.includes(t[1]))return}i.push(t)})),i.join("\r\n")},updateSdpRestriction=e=>{const t=e.split("\r\n"),r=[];t.forEach((e=>{const t=e.toLowerCase();t.includes("a=rtpmap")&&t.includes("h264")&&r.push(e)}));const o=r.map((e=>{const t=/a=rtpmap:(\d+)\s/.exec(e);return t&&t.length>1?t[1]:null})).filter((e=>null!==e)),s=[];t.forEach((e=>{let t=e;if(e.includes("a=fmtp:111")&&(t=`${e};stereo=1`),e.includes("a=fmtp")){const r=/a=fmtp:(\d+)\s/.exec(e);r&&r.length>1&&o.includes(r[1])&&(t=`${e};sps-pps-idr-in-keyframe=1`)}s.push(t)}));const i=s.join("\r\n");return updateSdpForFirefox(i)},urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=urlAlphabet[63&r[e]];return t},SIGNAL_DOMAIN_NAME_LIST=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],_FastWebRTC=class e{constructor(e){this.core=e,__publicField(this,"disableRandomCall",!0),__publicField(this,"connectedRoomIdSet",new Set),__publicField(this,"updateSeq",0),__publicField(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return e.Name}getAlias(){return"fwrtc"}getGroup(){return""}getValidateRule(e){switch(e){case"start":return StartValidateRule;case"update":case"stop":return{}}}async start(e){const{view:t,url:r,licenseConfig:o}=e}async connect(e){const t=new RTCPeerConnection({iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"});t.addTransceiver("audio",{direction:"recvonly"}),t.addTransceiver("video",{direction:"recvonly"});const r=await t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1});r.sdp=updateSdpRestriction(r.sdp),await t.setLocalDescription(r);const o={sessionId:nanoid(),streamurl:e,clientinfo:"macos chrome115",localsdp:t.localDescription},{remoteSdp:s,svrSig:i}=await this.core.utils.promiseAny(SIGNAL_DOMAIN_NAME_LIST.map((e=>this.exchangeSDP(e,o,3))));await t.setRemoteDescription(s)}async exchangeSDP(e,t,r){const o=`${e}/webrtc/v1/pullstream`,s=await fetchPost(o,t,{timeout:r}),{errcode:i,errmsg:n,remotesdp:a,svrsig:c}=s;if(0!==i){const e=new Error(`errCode:${i}, errMsg:${n}`);throw e.name="RequestSignalError",e}return{url:e,remoteSdp:a,svrSig:c}}async update(e){}async stop(){}destroy(){}};__publicField(_FastWebRTC,"Name","FastWebRTC");var FastWebRTC=_FastWebRTC,fetchPost=async(e,t,r={})=>{const{timeout:o=10}=r;let s,i=0,n={};window.AbortController&&(s=new window.AbortController,n={signal:s.signal},i=window.setTimeout((()=>s.abort()),1e3*o));const a=await fetch(e,__spreadValues({body:JSON.stringify(t),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},n));if(i&&window.clearTimeout(i),200!==a.status)throw new Error(`Network Error, status code:${a.status}`);return a.json()},index_default=FastWebRTC;export{index_default as default};export{FastWebRTC};
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).FastWebRTC=e()}(this,(function(){"use strict";function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function e(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function r(t){return function(){var r=this,n=arguments;return new Promise((function(o,i){var a=t.apply(r,n);function c(t){e(a,o,i,c,u,"next",t)}function u(t){e(a,o,i,c,u,"throw",t)}c(void 0)}))}}function n(t,e,r){return e&&function(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,a(n.key),n)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function o(){o=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,i=Object.defineProperty||function(t,e,r){t[e]=r.value},a="function"==typeof Symbol?Symbol:{},c=a.iterator||"@@iterator",u=a.asyncIterator||"@@asyncIterator",s=a.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function f(t,e,r,n){var o=e&&e.prototype instanceof g?e:g,a=Object.create(o.prototype),c=new _(n||[]);return i(a,"_invoke",{value:O(t,r,c)}),a}function p(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=f;var h="suspendedStart",y="suspendedYield",d="executing",v="completed",m={};function g(){}function w(){}function b(){}var x={};l(x,c,(function(){return this}));var E=Object.getPrototypeOf,S=E&&E(E(C([])));S&&S!==r&&n.call(S,c)&&(x=S);var L=b.prototype=g.prototype=Object.create(x);function j(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=p(t[o],t,i);if("throw"!==u.type){var s=u.arg,l=s.value;return l&&"object"==typeof l&&n.call(l,"__await")?e.resolve(l.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(l).then((function(t){s.value=t,a(s)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var o;i(this,"_invoke",{value:function(t,n){function i(){return new e((function(e,o){r(t,n,e,o)}))}return o=o?o.then(i,i):i()}})}function O(e,r,n){var o=h;return function(i,a){if(o===d)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=T(c,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=d;var s=p(e,r,n);if("normal"===s.type){if(o=n.done?v:y,s.arg===m)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(o=v,n.method="throw",n.arg=s.arg)}}}function T(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,T(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=p(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function A(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function _(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function C(e){if(e||""===e){var r=e[c];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(typeof e+" is not iterable")}return w.prototype=b,i(L,"constructor",{value:b,configurable:!0}),i(b,"constructor",{value:w,configurable:!0}),w.displayName=l(b,s,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===w||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,b):(t.__proto__=b,l(t,s,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},j(k.prototype),l(k.prototype,u,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(f(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},j(L),l(L,s,"Generator"),l(L,c,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=C,_.prototype={constructor:_,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(A),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!s)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,m):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),m},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),A(r),m}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;A(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:C(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),m}},e}function i(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||u(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function c(t){return c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},c(t)}function u(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}var s=Object.defineProperty,l=Object.getOwnPropertySymbols,f=Object.prototype.hasOwnProperty,p=Object.prototype.propertyIsEnumerable,h=function(t,e,r){return e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r},y=function(t,e){for(var r in e||(e={}))f.call(e,r)&&h(t,r,e[r]);if(l){var n,o=function(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=u(t))||e){r&&(t=r);var n=0,o=function(){};return{s:o,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return a=t.done,t},e:function(t){c=!0,i=t},f:function(){try{a||null==r.return||r.return()}finally{if(c)throw i}}}}(l(e));try{for(o.s();!(n=o.n()).done;){r=n.value;p.call(e,r)&&h(t,r,e[r])}}catch(t){o.e(t)}finally{o.f()}}return t},d=function(t,e,r){return h(t,"symbol"!==c(e)?e+"":e,r)},v={name:"option",required:!0,properties:{view:{type:["string",HTMLElement],required:!0},url:{type:"string",required:!0},licenseConfig:{type:"object",required:!0,properties:{secretKey:{type:"string",required:!0},encrypted:{type:"string",required:!0},signature:{type:"string",required:!0}}}}},m=function(t){var e=t.split("\r\n"),r=[];e.forEach((function(t){var e=t.toLowerCase();e.includes("a=rtpmap")&&e.includes("h264")&&r.push(t)}));var n=r.map((function(t){var e=/a=rtpmap:(\d+)\s/.exec(t);return e&&e.length>1?e[1]:null})).filter((function(t){return null!==t})),o=[];return e.forEach((function(t){var e=t;if(t.includes("a=fmtp:111")&&(e="".concat(t,";stereo=1")),t.includes("a=fmtp")){var r=/a=fmtp:(\d+)\s/.exec(t);r&&r.length>1&&n.includes(r[1])&&(e="".concat(t,";sps-pps-idr-in-keyframe=1"))}o.push(e)})),function(t){if(!navigator.userAgent.includes("Firefox"))return t;var e=t.split("\r\n"),r=[],n=[];e.forEach((function(t){var e=t.toLowerCase();e.includes("a=rtpmap")&&e.includes("h264")&&r.push(t)})),r.length>1&&n.push.apply(n,i(r.slice(1)));var o=n.map((function(t){var e=/a=rtpmap:(\d+)\s/.exec(t);return e&&e.length>1?e[1]:null})).filter((function(t){return null!==t})),a=[];return e.forEach((function(t){var e=t;if(t.includes("a=setup")&&(e="a=setup:passive"),(t.includes("m=audio")||t.includes("m=video"))&&(e=t.split(" ").filter((function(t,e){return e<3||!o.includes(t)})).join(" ")),t.includes("a=fmtp")||t.includes("a=rtcp-fb")||t.includes("a=rtpmap")){var r=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(t);if(r&&r.length>1&&o.includes(r[1]))return}a.push(e)})),a.join("\r\n")}(o.join("\r\n"))},g=function(){for(var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:21,e="",r=crypto.getRandomValues(new Uint8Array(t|=0));t--;)e+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&r[t]];return e},w=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],b=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.core=e,d(this,"disableRandomCall",!0),d(this,"connectedRoomIdSet",new Set),d(this,"updateSeq",0),d(this,"_log"),this._log=this.core.log.createChild({id:"".concat(this.getAlias())})}return n(t,[{key:"getName",value:function(){return t.Name}},{key:"getAlias",value:function(){return"fwrtc"}},{key:"getGroup",value:function(){return""}},{key:"getValidateRule",value:function(t){switch(t){case"start":return v;case"update":case"stop":return{}}}},{key:"start",value:(u=r(o().mark((function t(e){return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:e.view,e.url,e.licenseConfig;case 1:case"end":return t.stop()}}),t)}))),function(t){return u.apply(this,arguments)})},{key:"connect",value:(c=r(o().mark((function t(e){var r,n,i,a,c,u,s=this;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return(r=new RTCPeerConnection({iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"})).addTransceiver("audio",{direction:"recvonly"}),r.addTransceiver("video",{direction:"recvonly"}),t.next=5,r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1});case 5:return(n=t.sent).sdp=m(n.sdp),t.next=9,r.setLocalDescription(n);case 9:return i=g(),a={sessionId:i,streamurl:e,clientinfo:"macos chrome115",localsdp:r.localDescription},t.next=13,this.core.utils.promiseAny(w.map((function(t){return s.exchangeSDP(t,a,3)})));case 13:return c=t.sent,u=c.remoteSdp,c.svrSig,t.next=18,r.setRemoteDescription(u);case 18:case"end":return t.stop()}}),t,this)}))),function(t){return c.apply(this,arguments)})},{key:"exchangeSDP",value:(a=r(o().mark((function t(e,r,n){var i,a,c,u,s,l,f;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i="".concat(e,"/webrtc/v1/pullstream"),t.next=3,E(i,r,{timeout:n});case 3:if(a=t.sent,c=a.errcode,u=a.errmsg,s=a.remotesdp,l=a.svrsig,0===c){t.next=9;break}throw(f=new Error("errCode:".concat(c,", errMsg:").concat(u))).name="RequestSignalError",f;case 9:return t.abrupt("return",{url:e,remoteSdp:s,svrSig:l});case 10:case"end":return t.stop()}}),t)}))),function(t,e,r){return a.apply(this,arguments)})},{key:"update",value:(i=r(o().mark((function t(e){return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:case"end":return t.stop()}}),t)}))),function(t){return i.apply(this,arguments)})},{key:"stop",value:(e=r(o().mark((function t(){return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:case"end":return t.stop()}}),t)}))),function(){return e.apply(this,arguments)})},{key:"destroy",value:function(){}}]);var e,i,a,c,u}();d(b,"Name","FastWebRTC");var x=b,E=function(){var t=r(o().mark((function t(e,r){var n,i,a,c,u,s,l=arguments;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=(l.length>2&&void 0!==l[2]?l[2]:{}).timeout,i=void 0===n?10:n,c=0,u={},window.AbortController&&(a=new window.AbortController,u={signal:a.signal},c=window.setTimeout((function(){return a.abort()}),1e3*i)),t.next=7,fetch(e,y({body:JSON.stringify(r),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},u));case 7:if(s=t.sent,c&&window.clearTimeout(c),200===s.status){t.next=11;break}throw new Error("Network Error, status code:".concat(s.status));case 11:return t.abrupt("return",s.json());case 12:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}();return x}));
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@rtc-plugin/lebplayer",
3
+ "version": "5.14.1",
4
+ "description": "TRTC Web SDK 5.x Cross Room plugin",
5
+ "main": "./lebplayer.esm.js",
6
+ "module": "./lebplayer.esm.js",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git@github.com:LiteAVSDK/TRTC_Web.git"
10
+ },
11
+ "homepage": "https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/tutorial-30-advanced-lebplayer-link.html",
12
+ "keywords": [
13
+ "webrtc",
14
+ "TRTC",
15
+ "rtc",
16
+ "call",
17
+ "video call",
18
+ "audio call",
19
+ "javascript",
20
+ "video",
21
+ "audio",
22
+ "camera",
23
+ "microphone",
24
+ "live streaming",
25
+ "real-time communication",
26
+ "lebplayer"
27
+ ],
28
+ "types": "./lebplayer.esm.d.ts"
29
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * LEBPlayer Type Definitions
3
+ * 快直播拉流播放器类型声明
4
+ */
5
+
6
+ /**
7
+ * License 配置
8
+ */
9
+ export interface LicenseConfig {
10
+ /** 密钥 */
11
+ secretKey: string;
12
+ /** 加密数据 */
13
+ encrypted: string;
14
+ /** 签名 */
15
+ signature: string;
16
+ }
17
+
18
+ /**
19
+ * 音频统计信息
20
+ */
21
+ export interface AudioStat {
22
+ /** 接收码率 (kbps) */
23
+ bitrate: number;
24
+ /** 音量 (0-1) */
25
+ volume: number;
26
+ /** 丢包率 (0-100) */
27
+ packetLossRate: number;
28
+ /** jitter buffer 缓冲延迟 (ms) */
29
+ jitterBufferDelay: number;
30
+ /** 总接收字节数 */
31
+ bytesReceived: number;
32
+ /** 总接收包数 */
33
+ packetsReceived: number;
34
+ /** 总丢包数 */
35
+ packetsLost: number;
36
+ }
37
+
38
+ /**
39
+ * 视频统计信息
40
+ */
41
+ export interface VideoStat {
42
+ /** 接收码率 (kbps) */
43
+ bitrate: number;
44
+ /** 解码帧率 (fps) */
45
+ frameRate: number;
46
+ /** 分辨率宽度 */
47
+ width: number;
48
+ /** 分辨率高度 */
49
+ height: number;
50
+ /** 丢包率 (0-100) */
51
+ packetLossRate: number;
52
+ /** jitter buffer 缓冲延迟 (ms) */
53
+ jitterBufferDelay: number;
54
+ /** 总接收字节数 */
55
+ bytesReceived: number;
56
+ /** 总接收包数 */
57
+ packetsReceived: number;
58
+ /** 总丢包数 */
59
+ packetsLost: number;
60
+ /** 总解码帧数 */
61
+ framesDecoded: number;
62
+ }
63
+
64
+ /**
65
+ * 网络统计信息
66
+ */
67
+ export interface NetworkStat {
68
+ /** 往返时延 (ms) */
69
+ rtt: number;
70
+ }
71
+
72
+ /**
73
+ * 媒体统计数据
74
+ */
75
+ export interface MediaStats {
76
+ /** 音频统计 */
77
+ audio: AudioStat;
78
+ /** 视频统计 */
79
+ video: VideoStat;
80
+ /** 网络统计 */
81
+ network: NetworkStat;
82
+ }
83
+
84
+ /**
85
+ * 播放状态
86
+ */
87
+ export type PlayState = 'PLAYING' | 'PAUSED' | 'STOPPED';
88
+
89
+ /**
90
+ * 媒体类型
91
+ */
92
+ export type MediaType = 'audio' | 'video';
93
+
94
+ /**
95
+ * 填充模式
96
+ */
97
+ export type FillMode = 'contain' | 'cover' | 'fill';
98
+
99
+ /**
100
+ * 播放器动作
101
+ */
102
+ export type PlayerAction = 'pause' | 'resume';
103
+
104
+ /**
105
+ * 事件回调接口
106
+ */
107
+ export interface CallBack {
108
+ /**
109
+ * 加载开始回调
110
+ * @param type 媒体类型
111
+ */
112
+ onLoadStart?: (type: MediaType) => void;
113
+
114
+ /**
115
+ * 播放状态变更回调
116
+ * @param event 状态变更事件
117
+ */
118
+ onPlayStateChanged?: (event: {
119
+ /** 媒体类型 */
120
+ type: MediaType;
121
+ /** 播放状态 */
122
+ state: PlayState;
123
+ /** 变更原因 */
124
+ reason?: string;
125
+ }) => void;
126
+
127
+ /**
128
+ * 自动播放失败回调
129
+ * @param event 自动播放失败事件
130
+ */
131
+ onAutoPlayFailed?: (event: {
132
+ /** 媒体类型 */
133
+ type: MediaType;
134
+ /** 恢复播放函数 */
135
+ resume: () => Promise<void>;
136
+ }) => void;
137
+
138
+ /**
139
+ * 错误回调
140
+ * @param error 错误对象
141
+ */
142
+ onError?: (error: any) => void;
143
+
144
+ /**
145
+ * SEI 消息回调
146
+ * @param event SEI 消息事件
147
+ */
148
+ onSEIMessage?: (event: {
149
+ /** SEI 消息数据 */
150
+ data: ArrayBuffer;
151
+ /** SEI payload 类型 */
152
+ seiPayloadType: number;
153
+ }) => void;
154
+
155
+ /**
156
+ * 统计信息回调
157
+ * @param stats 媒体统计数据
158
+ */
159
+ onStats?: (stats: MediaStats) => void;
160
+ }
161
+
162
+ /**
163
+ * 启动 LEBPlayer 配置选项
164
+ */
165
+ export interface StartLEBPlayerOption {
166
+ /** 播放容器,可以是容器 ID 或 HTMLElement */
167
+ view: string | HTMLElement;
168
+
169
+ /** 快直播拉流地址 */
170
+ url: string;
171
+
172
+ /** License 配置(可选) */
173
+ licenseConfig?: LicenseConfig;
174
+
175
+ /** 是否静音,默认 false */
176
+ muted?: boolean;
177
+
178
+ /** 音量大小,范围 0-500,默认 100 */
179
+ volume?: number;
180
+
181
+ /** 填充模式,默认 'contain' */
182
+ fillMode?: FillMode;
183
+
184
+ /** 日志配置 */
185
+ loggerConfig: {
186
+ /** SDK 应用 ID */
187
+ sdkAppId: number;
188
+ /** 用户 ID */
189
+ userId: string;
190
+ };
191
+
192
+ /** 事件回调 */
193
+ callback?: CallBack;
194
+ }
195
+
196
+ /**
197
+ * 更新 LEBPlayer 配置选项
198
+ */
199
+ export interface UpdateLEBPlayerOption {
200
+ /** 播放容器 */
201
+ view?: string | HTMLElement;
202
+
203
+ /** 音量大小,范围 0-500 */
204
+ volume?: number;
205
+
206
+ /** 是否静音 */
207
+ muted?: boolean;
208
+
209
+ /** 填充模式 */
210
+ fillMode?: FillMode;
211
+
212
+ /** 播放器动作 */
213
+ action?: PlayerAction;
214
+
215
+ /** 是否全屏 */
216
+ fullScreen?: boolean;
217
+
218
+ /** 是否画中画 */
219
+ pictureInPicture?: boolean;
220
+ }
221
+
222
+ /**
223
+ * 停止 LEBPlayer 配置选项
224
+ */
225
+ // export interface StopLEBPlayerOption {}
226
+
227
+ /**
228
+ * LEBPlayer 类
229
+ * 快直播拉流播放器
230
+ */
231
+ export declare class LEBPlayer {
232
+ /** 插件名称 */
233
+ static Name: string;
234
+
235
+ /**
236
+ * 启动快直播拉流
237
+ * @param option 启动配置选项
238
+ * @returns Promise
239
+ */
240
+ start(option: StartLEBPlayerOption): Promise<void>;
241
+
242
+ /**
243
+ * 更新播放器配置
244
+ * @param option 更新配置选项
245
+ * @returns Promise
246
+ */
247
+ update(option: UpdateLEBPlayerOption): Promise<void>;
248
+
249
+ /**
250
+ * 停止快直播拉流
251
+ * @param option 停止配置选项
252
+ * @returns Promise
253
+ */
254
+ stop(): Promise<void>;
255
+ }
256
+
257
+ /**
258
+ * 默认导出
259
+ */
260
+ export default LEBPlayer;
@@ -0,0 +1 @@
1
+ var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,__spreadValues=(e,t)=>{for(var i in t||(t={}))__hasOwnProp.call(t,i)&&__defNormalProp(e,i,t[i]);if(__getOwnPropSymbols)for(var i of __getOwnPropSymbols(t))__propIsEnum.call(t,i)&&__defNormalProp(e,i,t[i]);return e},__commonJS=(e,t)=>function(){return t||(0,e[__getOwnPropNames(e)[0]])((t={exports:{}}).exports,t),t.exports},__copyProps=(e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of __getOwnPropNames(t))__hasOwnProp.call(e,s)||s===i||__defProp(e,s,{get:()=>t[s],enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,i)=>(i=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?i:__defProp(i,"default",{value:e,enumerable:!0}),e)),__decorateClass=(e,t,i,r)=>{for(var s,o=r>1?void 0:r?__getOwnPropDesc(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(o=(r?s(t,i,o):s(o))||o);return r&&o&&__defProp(t,i,o),o},__publicField=(e,t,i)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,i),require_eventemitter3=__commonJS({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,t){"use strict";var i=Object.prototype.hasOwnProperty,r="~";function s(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,s,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var n=new o(i,s||e,a),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],n]:e._events[c].push(n):(e._events[c]=n,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function c(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,s=[];if(0===this._eventsCount)return s;for(t in e=this._events)i.call(e,t)&&s.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,o=i.length,a=new Array(o);s<o;s++)a[s]=i[s].fn;return a},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,s,o,a){var n=r?r+e:e;if(!this._events[n])return!1;var c,l,d=this._events[n],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,s),!0;case 5:return d.fn.call(d.context,t,i,s,o),!0;case 6:return d.fn.call(d.context,t,i,s,o,a),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var p,h=d.length;for(l=0;l<h;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,s);break;default:if(!c)for(p=1,c=new Array(u-1);p<u;p++)c[p-1]=arguments[p];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,s){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return n(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||s&&!a.once||i&&a.context!==i||n(this,o);else{for(var c=0,l=[],d=a.length;c<d;c++)(a[c].fn!==t||s&&!a[c].once||i&&a[c].context!==i)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:n(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&n(this,t)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)}}),StartValidateRule={name:"option",required:!0,properties:{view:{type:["string",HTMLElement],required:!0},url:{type:"string",required:!0},muted:{type:"boolean",required:!1},volume:{type:"number",required:!1},fillMode:{type:"string",required:!1,values:["contain","cover","fill"]},loggerConfig:{type:"object",required:!0,properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0}}}}},UpdateValidateRule={name:"option",required:!0,properties:{view:{type:["string",HTMLElement],required:!1},volume:{type:"number",required:!1},muted:{type:"boolean",required:!1},fillMode:{type:"string",required:!1,values:["contain","cover","fill"]},action:{type:"string",required:!1,values:["pause","resume"]},fullScreen:{type:"boolean",required:!1},pictureInPicture:{type:"boolean",required:!1}}},updateSdpForFirefox=e=>{if(!navigator.userAgent.includes("Firefox"))return e;const t=e.split("\r\n"),i=[],r=[];t.forEach((e=>{const t=e.toLowerCase();t.includes("a=rtpmap")&&t.includes("h264")&&i.push(e)})),i.length>1&&r.push(...i.slice(1));const s=r.map((e=>{const t=/a=rtpmap:(\d+)\s/.exec(e);return t&&t.length>1?t[1]:null})).filter((e=>null!==e)),o=[];return t.forEach((e=>{let t=e;if(e.includes("a=setup")&&(t="a=setup:passive"),(e.includes("m=audio")||e.includes("m=video"))&&(t=e.split(" ").filter(((e,t)=>t<3||!s.includes(e))).join(" ")),e.includes("a=fmtp")||e.includes("a=rtcp-fb")||e.includes("a=rtpmap")){const t=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(e);if(t&&t.length>1&&s.includes(t[1]))return}o.push(t)})),o.join("\r\n")},updateSdpRestriction=e=>{const t=e.split("\r\n"),i=[];t.forEach((e=>{const t=e.toLowerCase();t.includes("a=rtpmap")&&t.includes("h264")&&i.push(e)}));const r=i.map((e=>{const t=/a=rtpmap:(\d+)\s/.exec(e);return t&&t.length>1?t[1]:null})).filter((e=>null!==e)),s=[];t.forEach((e=>{let t=e;if(e.includes("a=fmtp:111")&&(t=`${e};stereo=1`),e.includes("a=fmtp")){const i=/a=fmtp:(\d+)\s/.exec(e);i&&i.length>1&&r.includes(i[1])&&(t=`${e};sps-pps-idr-in-keyframe=1`)}s.push(t)}));const o=s.join("\r\n");return updateSdpForFirefox(o)},urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid=(e=21)=>{let t="",i=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=urlAlphabet[63&i[e]];return t},isFunction=e=>"function"==typeof e,RETRY_STATE_NOT_START=0,RETRY_STATE_STARTED=1,RETRY_STATE_STOPPED=2;function promiseRetry({retryFunction:e,settings:t,onError:i,onRetrying:r,onRetryFailed:s,onRetrySuccess:o,context:a}){return function(...n){const{retries:c=5,timeout:l=1e3}=t;let d=0,u=-1,p=RETRY_STATE_NOT_START;const h=async(t,f)=>{const m=a||this;try{const i=await e.apply(m,n);d>0&&o&&o.call(this,d),d=0,t(i)}catch(e){const o=()=>{clearTimeout(u),d=0,p=RETRY_STATE_STOPPED,f(e)},a=()=>{p!==RETRY_STATE_STOPPED&&d<(isFunction(c)?c():c)?(d++,p=RETRY_STATE_STARTED,isFunction(r)&&r.call(this,d,o),u=window.setTimeout((()=>{u=-1,h(t,f)}),isFunction(l)?l(d):l)):(o(),isFunction(s)&&s.call(this,e))};isFunction(i)?i.call(this,{error:e,retry:a,reject:f,retryFuncArgs:n,retriedCount:d}):a()}};return new Promise(h)}}var retry_default=promiseRetry,retryingMap=new WeakMap;function addPromiseRetry({settings:e={retries:5,timeout:2e3},onError:t,onRetrying:i,onRetryFailed:r}){return function(s,o,a){const n=retry_default({retryFunction:a.value,settings:e,onError({error:e,retry:i,reject:r,retryFuncArgs:a}){var n;t?t.call(this,e,(()=>{var t;(null==(t=retryingMap.get(s))?void 0:t.has(o))?i():r(e)}),r,a):(null==(n=retryingMap.get(s))?void 0:n.has(o))?i():r(e)},onRetrying(e,t){var r;isFunction(i)&&i.call(this,e,t),(null==(r=retryingMap.get(s))?void 0:r.has(o))&&(retryingMap.get(s).get(o).stopRetry=t)},onRetryFailed:r});return a.value=function(...e){const t=retryingMap.get(s);return t?t.set(o,{args:e}):retryingMap.set(s,new Map([[o,{args:e}]])),n.apply(this,e).finally((()=>{var e;return null==(e=retryingMap.get(s))?void 0:e.delete(o)}))},a}}function removePromiseRetry({fnName:e,callback:t,validateArgs:i=!0}){return function(r,s,o){const a=o.value;return o.value=function(...s){var o,n;if(null==(o=retryingMap.get(r))?void 0:o.has(e)){const{stopRetry:o,args:a}=retryingMap.get(r).get(e);let c=!0;if(i)for(const e of a)if(!s.find((t=>t===e))){c=!1;break}c&&(t&&t.apply(this,s),o&&o(),null==(n=retryingMap.get(r))||n.delete(e))}return a.apply(this,s)},o}}var Stat=class{constructor(e,t){this.core=t,__publicField(this,"peerConnection"),__publicField(this,"audioTransceiver",null),__publicField(this,"videoTransceiver",null),__publicField(this,"timerId",null),__publicField(this,"callback",null),__publicField(this,"previousRawStats",null),__publicField(this,"_prevReportTime",0),__publicField(this,"_prevDecoderImplementation",""),__publicField(this,"_decodeMap",new Map),this.peerConnection=e,this.findTransceivers()}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const e=this.peerConnection.getTransceivers();for(const t of e)if(t.receiver&&t.receiver.track){const{track:e}=t.receiver;"audio"===e.kind?this.audioTransceiver=t:"video"===e.kind&&(this.videoTransceiver=t)}}start(e,t=2e3){this.stop(),this.callback=e,this.collectStats(),this.timerId=window.setInterval((()=>{this.collectStats()}),t)}stop(){null!==this.timerId&&(clearInterval(this.timerId),this.timerId=null),this.callback=null,this.previousRawStats=null,this._prevReportTime=0}async collectStats(){if(this.callback)try{const e=await this.peerConnection.getStats(),t=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),i=[];e.forEach((e=>t.has(e.type)&&i.push(e)));const r=Date.now(),s=this.parseAudioStats(i),o=this.parseVideoStats(i),a=this.parseNetworkStats(i);this._prevReportTime=r,this.callback({audio:s,video:o,network:a})}catch(e){this.core.log.error("Failed to collect WebRTC stats:",e)}}getDifferenceValue(e,t){if(this.core.utils.isUndefined(e))return t;const i=(t||0)-e;return i<0?0:i}parseAudioStats(e){var t,i,r,s;const o={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const a of e){if("inbound-rtp"===a.type&&("audio"===a.mediaType||"audio"===a.kind)){if(o.bytesReceived=a.bytesReceived||0,o.packetsReceived=a.packetsReceived||0,o.packetsLost=a.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const e=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,o.bytesReceived);o.bitrate=Math.round(8*e/this.statInterval/1e3)}const e=this.getDifferenceValue(null==(t=this.previousRawStats)?void 0:t.audio.packetsLost,o.packetsLost),s=this.getDifferenceValue(null==(i=this.previousRawStats)?void 0:i.audio.packetsReceived,o.packetsReceived)+e;if(s>0&&(o.packetLossRate=Math.round(e/s*100)),this.core.utils.isUndefined(a.audioLevel)||(o.volume=a.audioLevel||0),a.jitterBufferDelay&&a.jitterBufferEmittedCount){let{jitterBufferEmittedCount:e}=a,{jitterBufferDelay:t}=a;(null==(r=this.previousRawStats)?void 0:r.audio)&&(e=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,a.jitterBufferEmittedCount),t=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,a.jitterBufferDelay)),e>0&&(o.jitterBufferDelay=Math.floor(t/e*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=a.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=a.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=o.bytesReceived,this.previousRawStats.audio.packetsReceived=o.packetsReceived,this.previousRawStats.audio.packetsLost=o.packetsLost}!this.core.utils.isUndefined(a.audioLevel)&&(null==(s=this.audioTransceiver)?void 0:s.receiver.track)&&a.trackIdentifier===this.audioTransceiver.receiver.track.id&&(o.volume=a.audioLevel||0)}return o}parseVideoStats(e){var t,i,r,s,o;const a={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const n of e){if("codec"===n.type&&this._decodeMap.set(n.id,n),"inbound-rtp"===n.type&&("video"===n.mediaType||"video"===n.kind)){if(a.bytesReceived=n.bytesReceived||0,a.packetsReceived=n.packetsReceived||0,a.packetsLost=n.packetsLost||0,a.framesDecoded=n.framesDecoded||0,this.core.utils.isUndefined(n.framesPerSecond)||(a.frameRate=Math.round(n.framesPerSecond)),n.decoderImplementation&&this._prevDecoderImplementation!==n.decoderImplementation){const e=this._decodeMap.get(n.codecId),i=(null==(t=null==e?void 0:e.mimeType)?void 0:t.split("/")[1])||"unknown",r=n.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${n.decoderImplementation}(${i}) HWDecoder: ${r}`),this._prevDecoderImplementation=n.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const e=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,a.bytesReceived);a.bitrate=Math.round(8*e/this.statInterval/1e3)}const e=this.getDifferenceValue(null==(i=this.previousRawStats)?void 0:i.video.packetsLost,a.packetsLost),o=this.getDifferenceValue(null==(r=this.previousRawStats)?void 0:r.video.packetsReceived,a.packetsReceived)+e;if(o>0&&(a.packetLossRate=Math.round(e/o*100)),n.jitterBufferDelay&&n.jitterBufferEmittedCount){let{jitterBufferEmittedCount:e}=n,{jitterBufferDelay:t}=n;(null==(s=this.previousRawStats)?void 0:s.video)&&(e=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,n.jitterBufferEmittedCount),t=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,n.jitterBufferDelay)),e>0&&(a.jitterBufferDelay=Math.floor(t/e*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=n.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=n.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=a.bytesReceived,this.previousRawStats.video.packetsReceived=a.packetsReceived,this.previousRawStats.video.packetsLost=a.packetsLost}!this.core.utils.isUndefined(n.frameWidth)&&(null==(o=this.videoTransceiver)?void 0:o.receiver.track)&&n.trackIdentifier===this.videoTransceiver.receiver.track.id&&(a.width=n.frameWidth,a.height=n.frameHeight)}return a}parseNetworkStats(e){const t={rtt:0};for(const i of e)if("candidate-pair"===i.type){if((i.selected||"succeeded"===i.state)&&this.core.utils.isNumber(i.currentRoundTripTime)){t.rtt=Math.floor(1e3*i.currentRoundTripTime);break}}return t}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},import_eventemitter3=__toESM(require_eventemitter3(),1),instance=Symbol("instance"),abortCtrl=Symbol("abortCtrl"),cacheResult=Symbol("cacheResult"),MiddleState=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,setState.call(e,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},FSMError=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};function thenAble(e){return"object"==typeof e&&e&&"then"in e}var stateDiagram=new Map;function ChangeState(e,t,i={}){return(r,s,o)=>{const a=i.action||s;if(!i.context){const i=stateDiagram.get(r)||[];stateDiagram.has(r)||stateDiagram.set(r,i),i.push({from:e,to:t,action:a})}const n=o.value;o.value=function(...r){let s=this;if(i.context&&(s=FSM.get("function"==typeof i.context?i.context.call(this,...r):i.context)),s.state===t)return i.sync?s[cacheResult]:Promise.resolve(s[cacheResult]);s.state instanceof MiddleState&&s.state.action==i.abortAction&&s.state.abort(s);let o=null;Array.isArray(e)?0==e.length?s.state instanceof MiddleState&&s.state.abort(s):"string"==typeof s.state&&e.includes(s.state)||(o=new FSMError(s._state,`${s.name} ${a} to ${t} failed: current state ${s._state} not from ${e.join("|")}`)):e!==s.state&&(o=new FSMError(s._state,`${s.name} ${a} to ${t} failed: current state ${s._state} not from ${e}`));const c=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(o)return c(o);const l=s.state,d=new MiddleState(l,t,a);setState.call(s,d);const u=e=>{var r;return s[cacheResult]=e,d.aborted||(setState.call(s,t),null===(r=i.success)||void 0===r||r.call(this,s[cacheResult])),e},p=e=>(setState.call(s,l,e),c(e));try{const e=n.apply(this,r);return thenAble(e)?e.then(u).catch(p):i.sync?u(e):Promise.resolve(u(e))}catch(i){return p(new FSMError(s._state,`${s.name} ${a} from ${e} to ${t} failed: ${i}`,i instanceof Error?i:new Error(String(i))))}}}}var sendDevTools=(()=>{const e="undefined"!=typeof window&&window.__AFSM__,t="undefined"!=typeof importScripts;return e?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:t?(e,t)=>{postMessage({type:e,payload:t})}:()=>{}})();function setState(e,t){const i=this._state;this._state=e;const r=e.toString();e&&this.emit(r,i),this.emit(FSM.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var FSM=class e extends import_eventemitter3.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=e.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),i||(this.groupName=this.constructor.name);const s=r[instance];s?this.name=s.name+"-"+s.count++:r[instance]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const e=Object.getPrototypeOf(this),t=stateDiagram.get(e)||[];let i=new Set,r=[],s=[];const o=new Set,a=Object.getPrototypeOf(e);stateDiagram.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.allStates.forEach((e=>o.add(e)))),t.forEach((({from:e,to:t,action:i})=>{"string"==typeof e?r.push({from:e,to:t,action:i}):e.length?e.forEach((e=>{r.push({from:e,to:t,action:i})})):s.push({to:t,action:i})})),r.forEach((({from:e,to:t,action:r})=>{o.add(e),o.add(t),o.add(r+"ing"),i.add(`${e} --\x3e ${r}ing : ${r}`),i.add(`${r}ing --\x3e ${t} : ${r} 🟢`),i.add(`${r}ing --\x3e ${e} : ${r} 🔴`)})),s.forEach((({to:e,action:t})=>{i.add(`${t}ing --\x3e ${e} : ${t} 🟢`),o.forEach((r=>{r!==e&&i.add(`${r} --\x3e ${t}ing : ${t}`)}))}));const n=[...i];return Object.defineProperties(e,{stateDiagram:{value:n},allStates:{value:o}}),n}static get(t){let i;return"string"==typeof t?(i=e.instances.get(t),i||e.instances.set(t,i=new e(t,void 0,Object.create(e.prototype)))):(i=e.instances2.get(t),i||e.instances2.set(t,i=new e(t.constructor.name,void 0,Object.create(e.prototype)))),i}static getState(t){var i;return null===(i=e.get(t))||void 0===i?void 0:i.state}updateDevTools(t={}){sendDevTools(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){setState.call(this,e)}};FSM.STATECHANGED="stateChanged",FSM.UPDATEAFSM="updateAFSM",FSM.INIT="[*]",FSM.ON="on",FSM.OFF="off",FSM.instances=new Map,FSM.instances2=new WeakMap;var Player=class extends FSM{constructor(e,t){super(),this.core=e,__publicField(this,"audioPlayer"),__publicField(this,"videoPlayer"),__publicField(this,"callback"),__publicField(this,"_log"),__publicField(this,"lastPausedReason"),__publicField(this,"muted",!1),this._log=t,this.videoPlayer=new e.VideoPlayer({id:"vp",log:this._log.createChild({id:"vp"}),track:null,muted:!1,container:null,enableLogTrackState:!0}),this.audioPlayer=new e.RemoteAudioPlayer({id:"ap",log:this._log.createChild({id:"ap"}),track:null,muted:!1,container:null,enableVolumeControlInIOS:!0,enableLogTrackState:!0}),this.videoPlayer.on("loadstart",(()=>this.handleLoadStart("video"))),this.audioPlayer.on("loadstart",(()=>this.handleLoadStart("audio"))),this.videoPlayer.on("player-state-changed",this.handlePlayerStateChanged,this),this.audioPlayer.on("player-state-changed",this.handlePlayerStateChanged,this)}get isPlaying(){return this.videoPlayer.isPlaying&&this.audioPlayer.isPlaying}get isPaused(){return this.videoPlayer.isPaused&&this.audioPlayer.isPaused}get isStopped(){return this.videoPlayer.isStopped&&this.audioPlayer.isStopped}setCallback(e){this.callback=e}handleLoadStart(e){this.onLoadStart()}handlePlayerStateChanged(e){"PLAYING"===e.state&&this.isPlaying&&this.onPlaying(),"PAUSED"===e.state&&this.isPaused&&this.onPaused(e.reason),"STOPPED"===e.state&&this.isStopped&&this.onStopped()}onLoadStart(){}onPlaying(){}onPaused(e){this.lastPausedReason=e}onStopped(){}setVideoContainer(e){if(this.core.utils.isString(e)){const t=document.getElementById(e);t&&this.videoPlayer.setContainer(t)}else this.videoPlayer.setContainer(e)}setVolume(e){this.core.utils.isUndefined(e)||this.audioPlayer.setVolume(e/100)}setMuted(e){this.core.utils.isUndefined(e)||(this.muted=e,this.audioPlayer.setMuted(e))}setFillMode(e){e&&this.videoPlayer.setObjectFit(e)}setAudioTrack(e){this.audioPlayer.setTrack(e)}setVideoTrack(e){this.videoPlayer.setTrack(e)}async play(){const e=this.videoPlayer.play().catch((e=>{var t,i;this.handleAutoPlayFailed(this.videoPlayer,e),null==(i=null==(t=this.callback)?void 0:t.onAutoPlayFailed)||i.call(t,{type:"video",resume:()=>this.videoPlayer.resume()})})),t=this.audioPlayer.play().catch((e=>{var t,i;this.handleAutoPlayFailed(this.audioPlayer,e),null==(i=null==(t=this.callback)?void 0:t.onAutoPlayFailed)||i.call(t,{type:"audio",resume:()=>this.audioPlayer.resume()})}));await Promise.all([e,t])}handleAutoPlayFailed(e,t){this._log.warn("handleAutoPlayFailed",t);const i=()=>{this.audioPlayer.resume().then((()=>{document.removeEventListener("click",i,!0)}))};document.addEventListener("click",i,!0)}pause(){this.videoPlayer.pause(!1),this.audioPlayer.setMuted(!0),this.audioPlayer.pause()}resume(){this.videoPlayer.resume(!0),this.audioPlayer.setMuted(this.muted),this.audioPlayer.resume()}async enterFullscreen(){await this.videoPlayer.enterFullscreen()}async exitFullscreen(){await this.videoPlayer.exitFullscreen()}async enterPictureInPicture(){await this.videoPlayer.enterPictureInPicture()}async exitPictureInPicture(){await this.videoPlayer.exitPictureInPicture()}stop(){this.videoPlayer&&this.videoPlayer.stop(),this.audioPlayer&&this.audioPlayer.stop()}};__decorateClass([ChangeState([FSM.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var e,t;null==(t=null==(e=this.callback)?void 0:e.onLoadStart)||t.call(e)},fail(e){this._log.warn("onLoadStart",e)}})],Player.prototype,"onLoadStart",1),__decorateClass([ChangeState(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var e,t;null==(t=null==(e=this.callback)?void 0:e.onPlaying)||t.call(e)},fail(e){this._log.warn("onPlaying",e)}})],Player.prototype,"onPlaying",1),__decorateClass([ChangeState("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var e,t;null==(t=null==(e=this.callback)?void 0:e.onPaused)||t.call(e,{reason:this.lastPausedReason})},fail(e){this._log.warn("onPaused",e)}})],Player.prototype,"onPaused",1),__decorateClass([ChangeState([],FSM.INIT,{ignoreError:!0,sync:!0,success(){var e,t;null==(t=null==(e=this.callback)?void 0:e.onStopped)||t.call(e)},fail(e){this._log.warn("onStopped",e)}})],Player.prototype,"onStopped",1);var player_default=Player,SIGNAL_DOMAIN_NAME_LIST=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],_LEBPlayer=class e{constructor(e){this.core=e,__publicField(this,"connectedRoomIdSet",new Set),__publicField(this,"updateSeq",0),__publicField(this,"_log"),__publicField(this,"player"),__publicField(this,"peerConnection"),__publicField(this,"svrSig"),__publicField(this,"streamURL"),__publicField(this,"signalURL"),__publicField(this,"insertableStreamsAbortMap",new Map),__publicField(this,"scriptTransformWorker"),__publicField(this,"connectionState","disconnected"),__publicField(this,"isStarted",!1),__publicField(this,"isStopped",!0),__publicField(this,"isReconnecting",!1),__publicField(this,"callback"),__publicField(this,"isFireWallErrorEmitted",!1),__publicField(this,"stat"),__publicField(this,"isH264DecodeSupported"),__publicField(this,"connectionTimeoutId"),e.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new player_default(e,this._log),e.innerEmitter.on(e.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return e.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(e){switch(e){case"start":return StartValidateRule;case"update":case"stop":return{}}}get enableSEI(){return this.core.room.enableSEI&&(this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED||this.core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED)}async start(e){var t;this.isStopped=!1;const{view:i,url:r,volume:s,muted:o,fillMode:a,loggerConfig:n,callback:c}=e;this.callback=c,this.player.setCallback(c);const{errorModule:{RtcError:l,ErrorCode:d,ErrorCodeDictionary:u},loggerManager:p,rtcDectection:h}=this.core;if(this._log.setSdkAppId(n.sdkAppId),this._log.setUserId(n.userId),p.addJoinedUser(n),!h.isWebRTCSupported()||!h.isAddTransceiverSupported())throw new l({code:d.ENV_NOT_SUPPORTED,extraCode:u.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await h.decodeSupportStatus()).isH264DecodeSupported||!1===this.isH264DecodeSupported)throw this.isH264DecodeSupported=!1,new l({code:d.ENV_NOT_SUPPORTED,extraCode:u.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!h.IS_SEI_SUPPORTED&&(null==c?void 0:c.onSEIMessage)&&(null==(t=c.onError)||t.call(c,new l({code:d.ENV_NOT_SUPPORTED,extraCode:u.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(i),this.player.setMuted(o),this.player.setVolume(s),this.player.setFillMode(a),await this.connect(r),this.stat=new Stat(this.peerConnection,this.core),this.stat.start((e=>{var t,i;return null==(i=null==(t=this.callback)?void 0:t.onStats)?void 0:i.call(t,e)})),await this.player.play(),this.isStarted=!0}connect(e){return new Promise(((t,i)=>{try{this.initScriptTransformWorker();const r={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},s=new RTCPeerConnection(r);this.peerConnection=s,s.onconnectionstatechange=()=>{this.connectionState=s.connectionState,this._log.info("connectionState",s.connectionState),"failed"!==s.connectionState&&"closed"!==s.connectionState||(this.isStarted?this.reconnect(e):i(new Error(`connection is ${s.connectionState}`))),"connected"===s.connectionState&&(this.logSelectedCandidate(),t())},s.ontrack=e=>this.onTrack(e),s.addTransceiver("audio",{direction:"recvonly"}),s.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),s.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then((e=>(e.sdp=updateSdpRestriction(e.sdp),this._log.info("setOffer"),s.setLocalDescription(e)))).then((()=>{const t={sessionId:nanoid(),streamurl:e,clientinfo:this.core.environment.getOSString(),localsdp:s.localDescription};return this.exchangeSDP(e,t)})).then((e=>(this._log.info("setAnswer"),s.setRemoteDescription(e)))).catch(i)}catch(e){i(e)}this.connectionTimeoutId=setTimeout((()=>i(new Error("connection timeout"))),1e4)}))}async exchangeSDP(e,t){let i,r,s;try{this._log.info("exchangeSDP");const o=getStreamDomain(e);if(!o)throw new Error("streamDomain is empty");const{signalDomain:a,cached:n}=await this.fetchSignalDomain(o);if(!a)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",a,n);const e=await this.doExchangeSDP(`https://${a}`,t,3);i=e.url,r=e.remoteSdp,s=e.svrSig}}catch(e){this._log.warn("exchangeSDP failed, fallback",e);const o=await this.core.utils.promiseAny(SIGNAL_DOMAIN_NAME_LIST.map((e=>this.doExchangeSDP(`https://${e}`,t,3))));i=o.url,r=o.remoteSdp,s=o.svrSig}return this.streamURL=e,this.signalURL=i,this.svrSig=s,r}async reconnect(e){if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(e),this._log.warn("reconnect success")}catch(e){this._log.error("reconnect error",e)}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const e=await this.peerConnection.getStats();for(const[t,i]of e)if(this.core.rtcDectection.isSelectedCandidatePair(i)){const t=e.get(i.localCandidateId),r=e.get(i.remoteCandidateId);t&&this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.relayProtocol?`relayProtocol:${t.relayProtocol} url: ${t.url}`:""}`),r&&this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`);break}}async doExchangeSDP(e,t,i){const r=`${e}/webrtc/v1/pullstream`,s=await fetchPost(r,t,{timeout:i}),{errcode:o,errmsg:a,remotesdp:n,svrsig:c}=s;if(0!==o){const e=new Error(`errCode:${o}, errMsg:${a}`);throw e.name="RequestSignalError",e}return{url:e,remoteSdp:n,svrSig:c}}createEncodedStreams(e){var t;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(e)){const i=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:t=>"audio"===e.track.kind?t:this.decodeVideoFrame(t)};i.readable.pipeThrough(new TransformStream({transform:(e,t)=>{const i=s.enqueue(e);i&&t.enqueue(i)}})).pipeTo(i.writable,r).catch((e=>{"destroy"!==e&&this._log.warn(e)})),null==(t=this.insertableStreamsAbortMap.get(e))||t.abort("destroy"),this.insertableStreamsAbortMap.set(e,r)}}catch(t){this._log.warn(`createEncodedStreams ${e.track.kind} failed`,t)}}initReceiverTransform(e,t){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!e.transform&&(e.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:t,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:e,rtcDectection:t,createScriptTransformWorker:i,trtc:r,TRTC:s}=this.core;!this.enableSEI||t.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||t.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=i({videoEncodePipeline:e.videoManager.encodePipeline,videoDecodePipeline:e.videoManager.decodePipeline,audioEncodePipeline:e.audioManager.encodePipeline,audioDecodePipeline:e.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{var t,i;"sei"===e.data.type&&(null==(i=null==(t=this.callback)?void 0:t.onSEIMessage)||i.call(t,{data:e.data.data,seiPayloadType:e.data.seiPayloadType}))},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}decodeVideoFrame(e){if(!this.core.room.videoManager)return e;for(const t of this.core.room.videoManager.decodePipeline)if(t&&!(e=t({frame:e})))return;return e}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const e=`${this.signalURL}/webrtc/v1/stopstream`,t=await fetchPost(e,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:i,errmsg:r}=t;if(0!==i)throw new Error(`errCode:${i}, errmsg:${r}`);return t}catch(e){this._log.error("fetchStopStream error",e)}}onTrack(e){const{track:t}=e;this.createEncodedStreams(e.receiver),this.initReceiverTransform(e.receiver,"audio"===t.kind),"audio"===t.kind?this.player.setAudioTrack(t):this.player.setVideoTrack(t)}async update(e){const{volume:t,muted:i,fillMode:r,action:s,fullScreen:o,pictureInPicture:a}=e;this.player.setMuted(i),this.player.setVolume(t),this.player.setFillMode(r),"pause"===s?this.player.pause():"resume"===s&&this.player.resume(),this.core.utils.isBoolean(o)&&(o?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(a)&&(a?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async stop(){this.isStopped=!0,this.player.stop(),this.peerConnection&&(clearTimeout(this.connectionTimeoutId),this.peerConnection.close(),this.peerConnection.getReceivers().forEach((e=>this.insertableStreamsAbortMap.delete(e))),delete this.peerConnection,await this.fetchStopStream(),delete this.streamURL,delete this.signalURL,delete this.svrSig),this.stat&&(this.stat.stop(),delete this.stat)}destroy(){this.stop(),this.core.innerEmitter.off(this.core.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}onSEIMessage({room:e,nalu:t}){var i,r;e===this.core.room&&(null==(r=null==(i=this.callback)?void 0:i.onSEIMessage)||r.call(i,{data:t.seiPayload.buffer,seiPayloadType:t.seiPayloadType}))}async fetchSignalDomain(e,t=REQUEST_DOMAIN_NAME_LIST[0]){const i=`https://${t}/signal_query`;try{const t=window.localStorage.getItem(SIGNAL_DOMAIN_NAME_DATA_KEY);if(t){const i=JSON.parse(t);if(i[e].expire-(new Date).getTime()>0)return{signalDomain:i[e].signal,cached:!0}}const r=await fetchPost(i,{domain:e,requestid:nanoid(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:s,data:o}=r;if(0===s){const{signal_domain:t,cache_time:i}=o;let r={};const s=window.localStorage.getItem(SIGNAL_DOMAIN_NAME_DATA_KEY);s&&(r=JSON.parse(s)),r[e]={signal:t,expire:(new Date).getTime()+1e3*i};try{window.localStorage.setItem(SIGNAL_DOMAIN_NAME_DATA_KEY,JSON.stringify(r))}catch(e){}return{signalDomain:t,cached:!1}}throw new Error(`errCode:${s}`)}catch(i){return this._log.error("fetchSignalDomain error",i),REQUEST_DOMAIN_NAME_LIST[1]&&t!==REQUEST_DOMAIN_NAME_LIST[1]?this.fetchSignalDomain(e,REQUEST_DOMAIN_NAME_LIST[1]):{signalDomain:"",cached:!1}}}};__publicField(_LEBPlayer,"Name","LEBPlayer"),__decorateClass([addPromiseRetry({settings:{retries:1/0,timeout:2e3},onRetrying(e){var t;if(this._log.warn(`retry connect ${e}`),e>=3&&(null==(t=this.callback)?void 0:t.onError)&&!this.isFireWallErrorEmitted){const{RtcError:e,ErrorCode:t,ErrorCodeDictionary:i}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new e({code:t.OPERATION_FAILED,extraCode:i.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(e,t,i,r){var s;if(this._log.warn("connect failed",e),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&(null==(s=e.message||e)?void 0:s.includes("connection")))t();else{const{RtcError:t,ErrorCode:r}=this.core.errorModule;i(new t({code:r.UNKNOWN_ERROR,message:e.message}))}}})],_LEBPlayer.prototype,"connect",1),__decorateClass([removePromiseRetry({fnName:"connect"})],_LEBPlayer.prototype,"stop",1);var LEBPlayer=_LEBPlayer,fetchPost=async(e,t,i={})=>{const{timeout:r=10}=i;let s,o=0,a={};window.AbortController&&(s=new window.AbortController,a={signal:s.signal},o=window.setTimeout((()=>s.abort()),1e3*r));const n=await fetch(e,__spreadValues({body:JSON.stringify(t),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},a));if(o&&window.clearTimeout(o),200!==n.status)throw new Error(`Network Error, status code:${n.status}`);return n.json()},REQUEST_DOMAIN_NAME_LIST=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],SIGNAL_DOMAIN_NAME_DATA_KEY="LEB_PLAYER_STORAGE_KEY",getStreamDomain=e=>{const t=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(e);return t?t[1]:""},index_default=LEBPlayer;export{index_default as default};export{LEBPlayer};