autoglm-gui 0.3.1__tar.gz → 0.3.2__tar.gz

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 (39) hide show
  1. autoglm_gui-0.3.2/AutoGLM_GUI/adb_plus/__init__.py +12 -0
  2. autoglm_gui-0.3.2/AutoGLM_GUI/adb_plus/touch.py +92 -0
  3. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/AutoGLM_GUI/server.py +126 -0
  4. autoglm_gui-0.3.1/AutoGLM_GUI/static/assets/about-C71SI8ZQ.js → autoglm_gui-0.3.2/AutoGLM_GUI/static/assets/about-2K7DgoQw.js +1 -1
  5. autoglm_gui-0.3.2/AutoGLM_GUI/static/assets/chat-DjOHP9wp.js +25 -0
  6. autoglm_gui-0.3.1/AutoGLM_GUI/static/assets/index-RqglIZxV.js → autoglm_gui-0.3.2/AutoGLM_GUI/static/assets/index-BynheeWl.js +6 -6
  7. autoglm_gui-0.3.1/AutoGLM_GUI/static/assets/index-DUCan6m6.js → autoglm_gui-0.3.2/AutoGLM_GUI/static/assets/index-Cc7aUqXq.js +1 -1
  8. autoglm_gui-0.3.2/AutoGLM_GUI/static/assets/index-CrqBLMxN.css +1 -0
  9. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/AutoGLM_GUI/static/index.html +2 -2
  10. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/PKG-INFO +1 -1
  11. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/pyproject.toml +1 -1
  12. autoglm_gui-0.3.1/AutoGLM_GUI/adb_plus/__init__.py +0 -5
  13. autoglm_gui-0.3.1/AutoGLM_GUI/static/assets/chat-C6WtEfKW.js +0 -14
  14. autoglm_gui-0.3.1/AutoGLM_GUI/static/assets/index-Dd1xMRCa.css +0 -1
  15. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/.gitignore +0 -0
  16. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/AutoGLM_GUI/__init__.py +0 -0
  17. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/AutoGLM_GUI/__main__.py +0 -0
  18. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/AutoGLM_GUI/adb_plus/screenshot.py +0 -0
  19. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/AutoGLM_GUI/scrcpy_stream.py +0 -0
  20. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/LICENSE +0 -0
  21. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/README.md +0 -0
  22. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/__init__.py +0 -0
  23. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/actions/__init__.py +0 -0
  24. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/actions/handler.py +0 -0
  25. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/adb/__init__.py +0 -0
  26. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/adb/connection.py +0 -0
  27. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/adb/device.py +0 -0
  28. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/adb/input.py +0 -0
  29. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/adb/screenshot.py +0 -0
  30. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/agent.py +0 -0
  31. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/config/__init__.py +0 -0
  32. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/config/apps.py +0 -0
  33. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/config/i18n.py +0 -0
  34. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/config/prompts.py +0 -0
  35. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/config/prompts_en.py +0 -0
  36. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/config/prompts_zh.py +0 -0
  37. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/model/__init__.py +0 -0
  38. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/phone_agent/model/client.py +0 -0
  39. {autoglm_gui-0.3.1 → autoglm_gui-0.3.2}/scrcpy-server-v3.3.3 +0 -0
@@ -0,0 +1,12 @@
1
+ """Lightweight ADB helpers with a more robust screenshot implementation."""
2
+
3
+ from .screenshot import Screenshot, capture_screenshot
4
+ from .touch import touch_down, touch_move, touch_up
5
+
6
+ __all__ = [
7
+ "Screenshot",
8
+ "capture_screenshot",
9
+ "touch_down",
10
+ "touch_move",
11
+ "touch_up",
12
+ ]
@@ -0,0 +1,92 @@
1
+ """Touch control utilities using ADB motion events for real-time dragging."""
2
+
3
+ import subprocess
4
+ import time
5
+
6
+
7
+ def _get_adb_prefix(device_id: str | None, adb_path: str = "adb") -> list[str]:
8
+ """Get ADB command prefix with optional device specifier."""
9
+ if device_id:
10
+ return [adb_path, "-s", device_id]
11
+ return [adb_path]
12
+
13
+
14
+ def touch_down(
15
+ x: int,
16
+ y: int,
17
+ device_id: str | None = None,
18
+ delay: float = 0.0,
19
+ adb_path: str = "adb",
20
+ ) -> None:
21
+ """
22
+ Send touch DOWN event at specified coordinates.
23
+
24
+ Args:
25
+ x: X coordinate.
26
+ y: Y coordinate.
27
+ device_id: Optional ADB device ID.
28
+ delay: Delay in seconds after event (default: 0.0 for real-time).
29
+ adb_path: Path to adb binary.
30
+ """
31
+ adb_prefix = _get_adb_prefix(device_id, adb_path)
32
+
33
+ subprocess.run(
34
+ adb_prefix + ["shell", "input", "motionevent", "DOWN", str(x), str(y)],
35
+ capture_output=True,
36
+ )
37
+ if delay > 0:
38
+ time.sleep(delay)
39
+
40
+
41
+ def touch_move(
42
+ x: int,
43
+ y: int,
44
+ device_id: str | None = None,
45
+ delay: float = 0.0,
46
+ adb_path: str = "adb",
47
+ ) -> None:
48
+ """
49
+ Send touch MOVE event at specified coordinates.
50
+
51
+ Args:
52
+ x: X coordinate.
53
+ y: Y coordinate.
54
+ device_id: Optional ADB device ID.
55
+ delay: Delay in seconds after event (default: 0.0 for real-time).
56
+ adb_path: Path to adb binary.
57
+ """
58
+ adb_prefix = _get_adb_prefix(device_id, adb_path)
59
+
60
+ subprocess.run(
61
+ adb_prefix + ["shell", "input", "motionevent", "MOVE", str(x), str(y)],
62
+ capture_output=True,
63
+ )
64
+ if delay > 0:
65
+ time.sleep(delay)
66
+
67
+
68
+ def touch_up(
69
+ x: int,
70
+ y: int,
71
+ device_id: str | None = None,
72
+ delay: float = 0.0,
73
+ adb_path: str = "adb",
74
+ ) -> None:
75
+ """
76
+ Send touch UP event at specified coordinates.
77
+
78
+ Args:
79
+ x: X coordinate.
80
+ y: Y coordinate.
81
+ device_id: Optional ADB device ID.
82
+ delay: Delay in seconds after event (default: 0.0 for real-time).
83
+ adb_path: Path to adb binary.
84
+ """
85
+ adb_prefix = _get_adb_prefix(device_id, adb_path)
86
+
87
+ subprocess.run(
88
+ adb_prefix + ["shell", "input", "motionevent", "UP", str(x), str(y)],
89
+ capture_output=True,
90
+ )
91
+ if delay > 0:
92
+ time.sleep(delay)
@@ -121,6 +121,57 @@ class TapResponse(BaseModel):
121
121
  error: str | None = None
122
122
 
123
123
 
124
+ class SwipeRequest(BaseModel):
125
+ start_x: int
126
+ start_y: int
127
+ end_x: int
128
+ end_y: int
129
+ duration_ms: int | None = None
130
+ device_id: str | None = None
131
+ delay: float = 0.0
132
+
133
+
134
+ class SwipeResponse(BaseModel):
135
+ success: bool
136
+ error: str | None = None
137
+
138
+
139
+ class TouchDownRequest(BaseModel):
140
+ x: int
141
+ y: int
142
+ device_id: str | None = None
143
+ delay: float = 0.0
144
+
145
+
146
+ class TouchDownResponse(BaseModel):
147
+ success: bool
148
+ error: str | None = None
149
+
150
+
151
+ class TouchMoveRequest(BaseModel):
152
+ x: int
153
+ y: int
154
+ device_id: str | None = None
155
+ delay: float = 0.0
156
+
157
+
158
+ class TouchMoveResponse(BaseModel):
159
+ success: bool
160
+ error: str | None = None
161
+
162
+
163
+ class TouchUpRequest(BaseModel):
164
+ x: int
165
+ y: int
166
+ device_id: str | None = None
167
+ delay: float = 0.0
168
+
169
+
170
+ class TouchUpResponse(BaseModel):
171
+ success: bool
172
+ error: str | None = None
173
+
174
+
124
175
  # API 端点
125
176
  @app.post("/api/init")
126
177
  def init_agent(request: InitRequest) -> dict:
@@ -366,6 +417,81 @@ def control_tap(request: TapRequest) -> TapResponse:
366
417
  return TapResponse(success=False, error=str(e))
367
418
 
368
419
 
420
+ @app.post("/api/control/swipe", response_model=SwipeResponse)
421
+ def control_swipe(request: SwipeRequest) -> SwipeResponse:
422
+ """Execute swipe from start to end coordinates."""
423
+ try:
424
+ from phone_agent.adb import swipe
425
+
426
+ swipe(
427
+ start_x=request.start_x,
428
+ start_y=request.start_y,
429
+ end_x=request.end_x,
430
+ end_y=request.end_y,
431
+ duration_ms=request.duration_ms,
432
+ device_id=request.device_id,
433
+ delay=request.delay
434
+ )
435
+
436
+ return SwipeResponse(success=True)
437
+ except Exception as e:
438
+ return SwipeResponse(success=False, error=str(e))
439
+
440
+
441
+ @app.post("/api/control/touch/down", response_model=TouchDownResponse)
442
+ def control_touch_down(request: TouchDownRequest) -> TouchDownResponse:
443
+ """Send touch DOWN event at specified device coordinates."""
444
+ try:
445
+ from AutoGLM_GUI.adb_plus import touch_down
446
+
447
+ touch_down(
448
+ x=request.x,
449
+ y=request.y,
450
+ device_id=request.device_id,
451
+ delay=request.delay
452
+ )
453
+
454
+ return TouchDownResponse(success=True)
455
+ except Exception as e:
456
+ return TouchDownResponse(success=False, error=str(e))
457
+
458
+
459
+ @app.post("/api/control/touch/move", response_model=TouchMoveResponse)
460
+ def control_touch_move(request: TouchMoveRequest) -> TouchMoveResponse:
461
+ """Send touch MOVE event at specified device coordinates."""
462
+ try:
463
+ from AutoGLM_GUI.adb_plus import touch_move
464
+
465
+ touch_move(
466
+ x=request.x,
467
+ y=request.y,
468
+ device_id=request.device_id,
469
+ delay=request.delay
470
+ )
471
+
472
+ return TouchMoveResponse(success=True)
473
+ except Exception as e:
474
+ return TouchMoveResponse(success=False, error=str(e))
475
+
476
+
477
+ @app.post("/api/control/touch/up", response_model=TouchUpResponse)
478
+ def control_touch_up(request: TouchUpRequest) -> TouchUpResponse:
479
+ """Send touch UP event at specified device coordinates."""
480
+ try:
481
+ from AutoGLM_GUI.adb_plus import touch_up
482
+
483
+ touch_up(
484
+ x=request.x,
485
+ y=request.y,
486
+ device_id=request.device_id,
487
+ delay=request.delay
488
+ )
489
+
490
+ return TouchUpResponse(success=True)
491
+ except Exception as e:
492
+ return TouchUpResponse(success=False, error=str(e))
493
+
494
+
369
495
  @app.websocket("/api/video/stream")
370
496
  async def video_stream_ws(websocket: WebSocket):
371
497
  """Stream real-time H.264 video from scrcpy server via WebSocket."""
@@ -1 +1 @@
1
- import{j as o}from"./index-RqglIZxV.js";function t(){return o.jsx("div",{className:"p-2",children:o.jsx("h3",{children:"About"})})}export{t as component};
1
+ import{j as o}from"./index-BynheeWl.js";function t(){return o.jsx("div",{className:"p-2",children:o.jsx("h3",{children:"About"})})}export{t as component};
@@ -0,0 +1,25 @@
1
+ import{g as Oe,a as He,r as m,j as u,s as Te,b as Re,c as Ye,d as _e,e as ze,f as Ge,h as Xe,i as Be,k as Ve,l as $e}from"./index-BynheeWl.js";var Ce={exports:{}};const We={},Ke=Object.freeze(Object.defineProperty({__proto__:null,default:We},Symbol.toStringTag,{value:"Module"})),qe=Oe(Ke);var Je=Ce.exports,Ee;function Ze(){return Ee||(Ee=1,(function(ye,se){(function(ae,Z){ye.exports=Z(qe)})(Je,(function(ae){function Z(n,s){(s==null||s>n.length)&&(s=n.length);for(var e=0,t=Array(s);e<s;e++)t[e]=n[e];return t}function xe(n){if(Array.isArray(n))return n}function oe(n){if(Array.isArray(n))return Z(n)}function ce(n){if(n===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}function _(n,s){if(!(n instanceof s))throw new TypeError("Cannot call a class as a function")}function y(n,s){for(var e=0;e<s.length;e++){var t=s[e];t.enumerable=t.enumerable||!1,t.configurable=!0,"value"in t&&(t.writable=!0),Object.defineProperty(n,J(t.key),t)}}function w(n,s,e){return s&&y(n.prototype,s),e&&y(n,e),Object.defineProperty(n,"prototype",{writable:!1}),n}function F(n,s){var e=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!e){if(Array.isArray(n)||(e=X(n))||s){e&&(n=e);var t=0,r=function(){};return{s:r,n:function(){return t>=n.length?{done:!0}:{done:!1,value:n[t++]}},e:function(c){throw c},f:r}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var i,a=!0,o=!1;return{s:function(){e=e.call(n)},n:function(){var c=e.next();return a=c.done,c},e:function(c){o=!0,i=c},f:function(){try{a||e.return==null||e.return()}finally{if(o)throw i}}}}function G(n){var s=ee();return function(){var e,t=te(n);if(s){var r=te(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return E(this,e)}}function C(n,s,e){return(s=J(s))in n?Object.defineProperty(n,s,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[s]=e,n}function te(n){return te=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},te(n)}function B(n,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(s&&s.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"prototype",{writable:!1}),s&&Q(n,s)}function ee(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ee=function(){return!!n})()}function pe(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function ge(n,s){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var t,r,i,a,o=[],c=!0,l=!1;try{if(i=(e=e.call(n)).next,s!==0)for(;!(c=(t=i.call(e)).done)&&(o.push(t.value),o.length!==s);c=!0);}catch(d){l=!0,r=d}finally{try{if(!c&&e.return!=null&&(a=e.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}function ke(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function le(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
4
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function E(n,s){if(s&&(typeof s=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ce(n)}function Q(n,s){return Q=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Q(n,s)}function K(n,s){return xe(n)||ge(n,s)||X(n,s)||ke()}function re(n){return oe(n)||pe(n)||X(n)||le()}function q(n,s){if(typeof n!="object"||!n)return n;var e=n[Symbol.toPrimitive];if(e!==void 0){var t=e.call(n,s);if(typeof t!="object")return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}function J(n){var s=q(n,"string");return typeof s=="symbol"?s:s+""}function ne(n){"@babel/helpers - typeof";return ne=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},ne(n)}function X(n,s){if(n){if(typeof n=="string")return Z(n,s);var e={}.toString.call(n).slice(8,-1);return e==="Object"&&n.constructor&&(e=n.constructor.name),e==="Map"||e==="Set"?Array.from(n):e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?Z(n,s):void 0}}var D,fe;function me(n,s){D=n,fe=s}function j(n){if(D){for(var s=arguments.length,e=new Array(s>1?s-1:0),t=1;t<s;t++)e[t-1]=arguments[t];D.apply(void 0,[n].concat(e))}}function V(n){if(fe){for(var s=arguments.length,e=new Array(s>1?s-1:0),t=1;t<s;t++)e[t-1]=arguments[t];fe.apply(void 0,[n].concat(e))}}var he=(function(){function n(s){_(this,n),this.listener={},this.type=s|""}return w(n,[{key:"on",value:function(e,t){return this.listener[e]||(this.listener[e]=[]),this.listener[e].push(t),!0}},{key:"off",value:function(e,t){if(this.listener[e]){var r=this.listener[e].indexOf(t);return r>-1&&this.listener[e].splice(r,1),!0}return!1}},{key:"offAll",value:function(){this.listener={}}},{key:"dispatch",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.listener[e]?(this.listener[e].map(function(a){a.apply(null,r)}),!0):!1}}]),n})(),ie=(function(){function n(){_(this,n)}return w(n,null,[{key:"init",value:function(){n.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],hev1:[],hvcC:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};var e;for(e in n.types)n.types.hasOwnProperty(e)&&(n.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);var t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);n.HDLR_TYPES={video:t,audio:r};var i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);n.STTS=n.STSC=n.STCO=a,n.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),n.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),n.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),n.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var o=new Uint8Array([105,115,111,109]),c=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);n.FTYP=n.box(n.types.ftyp,o,l,o,c),n.DINF=n.box(n.types.dinf,n.box(n.types.dref,i))}},{key:"box",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var a=8,o=r.length,c=o,l;o--;)a+=r[o].byteLength;for(l=new Uint8Array(a),l[0]=a>>24&255,l[1]=a>>16&255,l[2]=a>>8&255,l[3]=a&255,l.set(e,4),o=0,a=8;o<c;++o)l.set(r[o],a),a+=r[o].byteLength;return l}},{key:"hdlr",value:function(e){return n.box(n.types.hdlr,n.HDLR_TYPES[e])}},{key:"mdat",value:function(e){return n.box(n.types.mdat,e)}},{key:"mdhd",value:function(e,t){return n.box(n.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,85,196,0,0]))}},{key:"mdia",value:function(e){return n.box(n.types.mdia,n.mdhd(e.timescale,e.duration),n.hdlr(e.type),n.minf(e))}},{key:"mfhd",value:function(e){return n.box(n.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}},{key:"minf",value:function(e){return e.type==="audio"?n.box(n.types.minf,n.box(n.types.smhd,n.SMHD),n.DINF,n.stbl(e)):n.box(n.types.minf,n.box(n.types.vmhd,n.VMHD),n.DINF,n.stbl(e))}},{key:"moof",value:function(e,t,r){return n.box(n.types.moof,n.mfhd(e),n.traf(r,t))}},{key:"moov",value:function(e,t,r){for(var i=e.length,a=[];i--;)a[i]=n.trak(e[i]);return n.box.apply(null,[n.types.moov,n.mvhd(r,t)].concat(a).concat(n.mvex(e)))}},{key:"mvex",value:function(e){for(var t=e.length,r=[];t--;)r[t]=n.trex(e[t]);return n.box.apply(null,[n.types.mvex].concat(r))}},{key:"mvhd",value:function(e,t){var r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,e>>24&255,e>>16&255,e>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return n.box(n.types.mvhd,r)}},{key:"sdtp",value:function(e){var t=e.samples||[],r=new Uint8Array(4+t.length),i,a;for(a=0;a<t.length;a++)i=t[a].flags,r[a+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return n.box(n.types.sdtp,r)}},{key:"stbl",value:function(e){return n.box(n.types.stbl,n.stsd(e),n.box(n.types.stts,n.STTS),n.box(n.types.stsc,n.STSC),n.box(n.types.stsz,n.STSZ),n.box(n.types.stco,n.STCO))}},{key:"avc1",value:function(e){var t=[],r=[],i,a,o;for(i=0;i<e.sps.length;i++)a=e.sps[i],o=a.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(a));for(i=0;i<e.pps.length;i++)a=e.pps[i],o=a.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));var c=n.box(n.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(r))),l=e.width,d=e.height;return n.box(n.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,98,105,110,101,108,112,114,111,46,114,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,n.box(n.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])))}},{key:"hev1",value:function(e){for(var t=[],r=[],i=[],a,o,c=0;c<(((l=e.vps)===null||l===void 0?void 0:l.length)||0);c++){var l;a=e.vps[c],o=a.byteLength,t.push(o>>>8&255,o&255),t=t.concat(Array.prototype.slice.call(a))}for(var d=0;d<(((x=e.sps)===null||x===void 0?void 0:x.length)||0);d++){var x;a=e.sps[d],o=a.byteLength,r.push(o>>>8&255,o&255),r=r.concat(Array.prototype.slice.call(a))}for(var f=0;f<(((h=e.pps)===null||h===void 0?void 0:h.length)||0);f++){var h;a=e.pps[f],o=a.byteLength,i.push(o>>>8&255,o&255),i=i.concat(Array.prototype.slice.call(a))}var A=e.hvcC,W=A.profile_space,O=A.tier_flag,M=A.profile_idc,H=A.profile_compatibility_flags,R=A.constraint_indicator_flags,Se=A.level_idc,ve=A.chroma_format_idc,we=n.box(n.types.hvcC,new Uint8Array([1,W<<6|O<<5|M,H>>24&255,H>>16&255,H>>8&255,H&255].concat(re(R),[Se,240,0,252,252|ve,248,248,0,0,3,3,32,0,1],re(t),[33,0,1],re(r),[34,0,1],re(i)))),be=e.width,U=e.height;return n.box(n.types.hev1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,be>>8&255,be&255,U>>8&255,U&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,98,105,110,101,108,112,114,111,46,114,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),we,n.box(n.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])))}},{key:"esds",value:function(e){var t=e.config.byteLength,r=new Uint8Array(26+t+3);return r.set([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5,t]),r.set(e.config,26),r.set([6,1,2],26+t),r}},{key:"mp4a",value:function(e){var t=e.audiosamplerate;return n.box(n.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]),n.box(n.types.esds,n.esds(e)))}},{key:"stsd",value:function(e){return e.type==="audio"?n.box(n.types.stsd,n.STSD,n.mp4a(e)):e.codec.startsWith("hvc1")?n.box(n.types.stsd,n.STSD,n.hev1(e)):n.box(n.types.stsd,n.STSD,n.avc1(e))}},{key:"tkhd",value:function(e){var t=e.id,r=e.duration,i=e.width,a=e.height,o=e.volume;return n.box(n.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,r&255,0,0,0,0,0,0,0,0,0,0,0,0,o>>0&255,o%1*10>>0&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,a>>8&255,a&255,0,0]))}},{key:"traf",value:function(e,t){var r=n.sdtp(e),i=e.id;return n.box(n.types.traf,n.box(n.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),n.box(n.types.tfdt,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255])),n.trun(e,r.length+16+16+8+16+8+8),r)}},{key:"trak",value:function(e){return e.duration=e.duration||4294967295,n.box(n.types.trak,n.tkhd(e),n.mdia(e))}},{key:"trex",value:function(e){var t=e.id;return n.box(n.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(e,t){var r=e.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),c,l,d,x,f,h;for(t+=8+a,o.set([0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),c=0;c<i;c++)l=r[c],d=l.duration,x=l.size,f=l.flags,h=l.cts,o.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,f.isLeading<<2|f.dependsOn,f.isDependedOn<<6|f.hasRedundancy<<4|f.paddingValue<<1|f.isNonSync,f.degradPrio&61440,f.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*c);return n.box(n.types.trun,o)}},{key:"initSegment",value:function(e,t,r){n.types||n.init();var i=n.moov(e,t,r),a;return a=new Uint8Array(n.FTYP.byteLength+i.byteLength),a.set(n.FTYP),a.set(i,n.FTYP.byteLength),a}}]),n})(),v=(function(){function n(){_(this,n)}return w(n,null,[{key:"samplingRateMap",get:function(){return[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350]}},{key:"getHeaderLength",value:function(e){return e[1]&1?7:9}},{key:"getFrameLength",value:function(e){return(e[3]&3)<<11|e[4]<<3|(e[5]&224)>>>5}},{key:"isAACPattern",value:function(e){return e[0]===255&&(e[1]&240)===240&&(e[1]&6)===0}},{key:"extractAAC",value:function(e){var t=0,r=e.byteLength,i=[],a,o;if(!n.isAACPattern(e))return V("Invalid ADTS audio format"),{valid:!1};a=n.getHeaderLength(e);for(var c=e.subarray(0,a);t<r;)o=n.getFrameLength(e),i.push(e.subarray(a,o)),e=e.slice(o),t+=o;return{valid:!0,header:c,slices:i}}}]),n})(),Y=1,$=(function(n){B(e,n);var s=G(e);function e(){return _(this,e),s.apply(this,arguments)}return w(e,[{key:"flush",value:function(){this.mp4track.len=0,this.mp4track.samples=[]}},{key:"isReady",value:function(){return!this.readyToDecode||!this.samples.length?null:!0}}],[{key:"getTrackID",value:function(){return Y++}}]),e})(he),ue=(function(n){B(e,n);var s=G(e);function e(t,r,i){var a;return _(this,e),a=s.call(this,"AACRemuxer"),a.frameDuration=i,a.readyToDecode=!1,a.header=null,a.nextDts=0,a.dts=0,a.mp4track={id:$.getTrackID(),type:"audio",channelCount:0,len:0,fragmented:!0,timescale:t,duration:r,samples:[],config:"",codec:""},a.samples=[],a}return w(e,[{key:"resetTrack",value:function(){this.readyToDecode=!1,this.header=null,this.mp4track.codec="",this.mp4track.channelCount="",this.mp4track.config="",this.mp4track.timescale=this.timescale,this.nextDts=0,this.dts=0}},{key:"feed",value:function(r,i){var a=v.extractAAC(r),o=a.valid,c=a.header,l=a.slices;return this.header||(this.header=c),o&&l.length>0?(this.remux(this.getAudioFrames(l,i)),!0):(V("Failed to extract audio data from:",r),this.dispatch("outOfData"),!1)}},{key:"getAudioFrames",value:function(r,i){var a=[],o=0,c=0,l=F(r),d;try{for(l.s();!(d=l.n()).done;){var x=d.value;a.push({units:x})}}catch(f){l.e(f)}finally{l.f()}return o=i?i/a.length|0:this.frameDuration,c=i?i-o*a.length:0,a.map(function(f){f.duration=o,c>0&&(f.duration++,c--)}),a}},{key:"remux",value:function(r){if(r.length>0)for(var i=0;i<r.length;i++){var a=r[i],o=a.units,c=o.byteLength;this.samples.push({units:o,size:c,duration:a.duration}),this.mp4track.len+=c,this.readyToDecode||this.setAACConfig()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,a=this.mp4track.samples,o,c;for(this.dts=this.nextDts;this.samples.length;){var l=this.samples.shift();if(l.units,c=l.duration,c<=0){j("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(c)),this.mp4track.len-=l.size;continue}this.nextDts+=c,o={size:l.size,duration:c,cts:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},r.set(l.units,i),i+=l.size,a.push(o)}return a.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"setAACConfig",value:function(){var r,i,a,o=new Uint8Array(2);this.header&&(r=((this.header[2]&192)>>>6)+1,i=(this.header[2]&60)>>>2,a=(this.header[2]&1)<<2,a|=(this.header[3]&192)>>>6,o[0]=r<<3,o[0]|=(i&14)>>1,o[1]|=(i&1)<<7,o[1]|=a<<3,this.mp4track.codec="mp4a.40."+r,this.mp4track.channelCount=a,this.mp4track.config=o,this.readyToDecode=!0)}}]),e})($),I=(function(){function n(s){_(this,n),this.data=s,this.index=0,this.bitLength=s.byteLength*8}return w(n,[{key:"setData",value:function(e){this.data=e,this.index=0,this.bitLength=e.byteLength*8}},{key:"bitsAvailable",get:function(){return this.bitLength-this.index}},{key:"skipBits",value:function(e){if(this.bitsAvailable<e)return!1;this.index+=e}},{key:"readBits",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this.getBits(e,this.index,t);return r}},{key:"getBits",value:function(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(this.bitsAvailable<e)return 0;var i=t%8,a=this.data[t/8|0]&255>>>i,o=8-i;if(o>=e)return r&&(this.index+=e),a>>o-e;r&&(this.index+=o);var c=e-o;return a<<c|this.getBits(c,t+o,r)}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitLength-this.index;++e)if(this.getBits(1,this.index+e,!1)!==0)return this.index+=e,e;return e}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return this.readBits(1)===1}},{key:"readUByte",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;return this.readBits(e*8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}}]),n})(),de=(function(){function n(){_(this,n)}return w(n,null,[{key:"extractNALu",value:function(e){for(var t=0,r=e.byteLength,i=[],a=0,o=0;t<r;){var c=e[t++];if(c===0)o++;else if(c===1&&o>=2){var l=o+1;a!==t-l&&i.push(e.subarray(a,t-l)),a=t,o=0}else o=0}var d=null;return a<r&&(d=e.subarray(a,r)),[i,d]}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,a,o=0;o<t;o++)i!==0&&(a=e.readEG(),i=(r+a+256)%256),r=i===0?r:i}},{key:"readSPS",value:function(e){var t=new I(e),r=0,i=0,a=0,o=0,c=1,l,d,x,f,h,A,W=0;t.readUByte();for(var O=[],M=1,H=e.byteLength,R=M;R<H;R++)R+2<H&&t.readBits(24,!1)===3?(O.push(t.readBits(8)),O.push(t.readBits(8)),R+=2,t.readBits(8)):O.push(t.readBits(8));if(t.setData(new Uint8Array(O)),l=t.readUByte(),t.readBits(5),t.skipBits(3),t.readUByte(),t.skipUEG(),l===100||l===110||l===122||l===244||l===44||l===83||l===86||l===118||l===128){var Se=t.readUEG();if(Se===3&&t.skipBits(1),t.skipUEG(),t.skipUEG(),t.skipBits(1),t.readBoolean()){A=Se!==3?8:12;for(var ve=0;ve<A;++ve)t.readBoolean()&&(ve<6?n.skipScalingList(t,16):n.skipScalingList(t,64))}}t.skipUEG();var we=t.readUEG();if(we===0)t.readUEG();else if(we===1){t.skipBits(1),t.skipEG(),t.skipEG(),d=t.readUEG();for(var be=0;be<d;++be)t.skipEG()}if(t.skipUEG(),t.skipBits(1),x=t.readUEG(),f=t.readUEG(),h=t.readBits(1),h===0&&t.skipBits(1),t.skipBits(1),t.readBoolean()&&(r=t.readUEG(),i=t.readUEG(),a=t.readUEG(),o=t.readUEG()),t.readBoolean()){if(t.readBoolean()){var U,Ae=t.readUByte();switch(Ae){case 1:U=[1,1];break;case 2:U=[12,11];break;case 3:U=[10,11];break;case 4:U=[16,11];break;case 5:U=[40,33];break;case 6:U=[24,11];break;case 7:U=[20,11];break;case 8:U=[32,11];break;case 9:U=[80,33];break;case 10:U=[18,11];break;case 11:U=[15,11];break;case 12:U=[64,33];break;case 13:U=[160,99];break;case 14:U=[4,3];break;case 15:U=[3,2];break;case 16:U=[2,1];break;case 255:{U=[t.readUByte()<<8|t.readUByte(),t.readUByte()<<8|t.readUByte()];break}}U&&U[0]>0&&U[1]>0&&(c=U[0]/U[1])}if(t.readBoolean()&&t.skipBits(1),t.readBoolean()&&(t.skipBits(4),t.readBoolean()&&t.skipBits(24)),t.readBoolean()&&(t.skipUEG(),t.skipUEG()),t.readBoolean()){var De=t.readUInt(),Ue=t.readUInt(),Fe=t.readBoolean(),Pe=Ue/(2*De);Fe&&(W=Pe)}}return{fps:W>0?W:void 0,width:Math.ceil(((x+1)*16-r*2-i*2)*c),height:(2-h)*(f+1)*16-(h?2:4)*(a+o)}}}]),n})(),z=(function(){function n(s){_(this,n),this.payload=s,this.nri=(this.payload[0]&96)>>5,this.nalUnitType=this.payload[0]&31,this._sliceType=null,this._isFirstSlice=!1}return w(n,[{key:"toString",value:function(){return"".concat(n.TYPES[this.type()]||"UNKNOWN",": NRI: ").concat(this.getNri())}},{key:"getNri",value:function(){return this.nri}},{key:"type",value:function(){return this.nalUnitType}},{key:"isKeyframe",get:function(){return this.nalUnitType===n.IDR}},{key:"isVCL",get:function(){return this.nalUnitType==n.IDR||this.nalUnitType==n.NDR}},{key:"parseHeader",value:function(){var e=new I(this.getPayload());e.readUByte(),this._isFirstSlice=e.readUEG()===0,this._sliceType=e.readUEG()}},{key:"isFirstSlice",get:function(){return this._isFirstSlice||this.parseHeader(),this._isFirstSlice}},{key:"sliceType",get:function(){return this._sliceType||this.parseHeader(),this._sliceType}},{key:"getPayload",value:function(){return this.payload}},{key:"getPayloadSize",value:function(){return this.payload.byteLength}},{key:"getSize",value:function(){return 4+this.getPayloadSize()}},{key:"getData",value:function(){var e=new Uint8Array(this.getSize()),t=new DataView(e.buffer);return t.setUint32(0,this.getSize()-4),e.set(this.getPayload(),4),e}}],[{key:"NDR",get:function(){return 1}},{key:"IDR",get:function(){return 5}},{key:"SEI",get:function(){return 6}},{key:"SPS",get:function(){return 7}},{key:"PPS",get:function(){return 8}},{key:"AUD",get:function(){return 9}},{key:"TYPES",get:function(){var e;return e={},C(e,n.IDR,"IDR"),C(e,n.SEI,"SEI"),C(e,n.SPS,"SPS"),C(e,n.PPS,"PPS"),C(e,n.NDR,"NDR"),C(e,n.AUD,"AUD"),e}}]),n})();function g(n,s){var e=new Uint8Array((n.byteLength|0)+(s.byteLength|0));return e.set(n,0),e.set(s,n.byteLength|0),e}function k(n){var s,e,t,r="";return s=Math.floor(n),e=parseInt(s/3600,10)%24,t=parseInt(s/60,10)%60,s=s<0?0:s%60,e>0&&(r+=(e<10?"0"+e:e)+":"),r+=(t<10?"0"+t:t)+":"+(s<10?"0"+s:s),r}var N=(function(n){B(e,n);var s=G(e);function e(t,r,i){var a;return _(this,e),a=s.call(this,"H264Remuxer"),a.frameDuration=i,a.readyToDecode=!1,a.nextDts=0,a.dts=0,a.mp4track={id:$.getTrackID(),type:"video",len:0,fragmented:!0,sps:"",pps:"",fps:30,width:0,height:0,timescale:t,duration:r,samples:[]},a.samples=[],a.remainingData=new Uint8Array,a.kfCounter=0,a.pendingUnits={},a}return w(e,[{key:"resetTrack",value:function(){this.readyToDecode=!1,this.mp4track.sps="",this.mp4track.pps="",this.nextDts=0,this.dts=0,this.remainingData=new Uint8Array,this.kfCounter=0,this.pendingUnits={}}},{key:"feed",value:function(r,i,a){var o=[],c;r=g(this.remainingData,r);var l=de.extractNALu(r),d=K(l,2);return o=d[0],c=d[1],this.remainingData=c||new Uint8Array,o.length>0?(this.remux(this.getVideoFrames(o,i,a)),!0):(V("Failed to extract any NAL units from video data:",c),this.dispatch("outOfData"),!1)}},{key:"getVideoFrames",value:function(r,i,a){var o=this,c=[],l=[],d=0,x=0,f=!1,h=!1;this.pendingUnits.units&&(c=this.pendingUnits.units,h=this.pendingUnits.vcl,f=this.pendingUnits.keyFrame,this.pendingUnits={});var A=F(r),W;try{for(A.s();!(W=A.n()).done;){var O=W.value,M=new z(O);c.length&&h&&(M.isFirstSlice||!M.isVCL)&&(l.push({units:c,keyFrame:f}),c=[],f=!1,h=!1),c.push(M),f=f||M.isKeyframe,h=h||M.isVCL}}catch(R){A.e(R)}finally{A.f()}if(c.length)if(!i)this.pendingUnits={units:c,keyFrame:f,vcl:h};else if(h)l.push({units:c,keyFrame:f});else{var H=l.length-1;H>=0&&(l[H].units=l[H].units.concat(c))}return d=i?i/l.length|0:this.frameDuration,x=i?i-d*l.length:0,l.map(function(R){R.duration=d,R.compositionTimeOffset=a,x>0&&(R.duration++,x--),o.kfCounter++,R.keyFrame&&o.dispatch("keyframePosition",o.kfCounter*d/1e3)}),j("jmuxer: No. of H264 frames of the last chunk: ".concat(l.length)),l}},{key:"remux",value:function(r){var i=F(r),a;try{for(i.s();!(a=i.n()).done;){var o=a.value,c=[],l=0,d=F(o.units),x;try{for(d.s();!(x=d.n()).done;){var f=x.value;this.parseNAL(f)&&(c.push(f),l+=f.getSize())}}catch(h){d.e(h)}finally{d.f()}c.length>0&&this.readyToDecode&&(this.mp4track.len+=l,this.samples.push({units:c,size:l,keyFrame:o.keyFrame,duration:o.duration,compositionTimeOffset:o.compositionTimeOffset}))}}catch(h){i.e(h)}finally{i.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,a=this.mp4track.samples,o,c;for(this.dts=this.nextDts;this.samples.length;){var l=this.samples.shift(),d=l.units;if(c=l.duration,c<=0){j("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(c)),this.mp4track.len-=l.size;continue}this.nextDts+=c,o={size:l.size,duration:c,cts:l.compositionTimeOffset||0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:l.keyFrame?0:1,dependsOn:l.keyFrame?2:1}};var x=F(d),f;try{for(x.s();!(f=x.n()).done;){var h=f.value;r.set(h.getData(),i),i+=h.getSize()}}catch(A){x.e(A)}finally{x.f()}a.push(o)}return a.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"parseSPS",value:function(r){var i=de.readSPS(new Uint8Array(r));this.mp4track.fps=i.fps||this.mp4track.fps,this.mp4track.width=i.width,this.mp4track.height=i.height,this.mp4track.sps=[new Uint8Array(r)],this.mp4track.codec="avc1.";for(var a=new DataView(r.buffer,r.byteOffset+1,4),o=0;o<3;++o){var c=a.getUint8(o).toString(16);c.length<2&&(c="0"+c),this.mp4track.codec+=c}}},{key:"parsePPS",value:function(r){this.mp4track.pps=[new Uint8Array(r)]}},{key:"parseNAL",value:function(r){if(!r)return!1;if(r.isVCL)return!0;var i=!1;switch(r.type()){case z.PPS:this.mp4track.pps||this.parsePPS(r.getPayload()),i=!0;break;case z.SPS:this.mp4track.sps||this.parseSPS(r.getPayload()),i=!0;break;case z.AUD:j("AUD - ignoing");break;case z.SEI:j("SEI - ignoing");break}return!this.readyToDecode&&this.mp4track.pps&&this.mp4track.sps&&(this.readyToDecode=!0),i}}]),e})($),b=(function(){function n(){_(this,n)}return w(n,null,[{key:"extractNALu",value:function(e){for(var t=0,r=e.byteLength,i=[],a=0,o=0;t<r;){var c=e[t++];if(c===0)o++;else if(c===1&&o>=2){var l=o+1;a!==t-l&&i.push(e.subarray(a,t-l)),a=t,o=0}else o=0}var d=null;return a<r&&(d=e.subarray(a,r)),[i,d]}},{key:"removeEmulationPreventionBytes",value:function(e){for(var t=[],r=0,i=0;i<e.length;i++){var a=e[i];if(r===2&&a===3){r=0;continue}t.push(a),a===0?r++:r=0}return new Uint8Array(t)}},{key:"readSPS",value:function(e){var t=new I(e);t.readUByte(),t.readUByte(),t.readBits(4),t.readBits(3),t.readBits(1);for(var r=t.readBits(2),i=t.readBits(1),a=t.readBits(5),o=t.readUInt(),c=new Uint8Array(6),l=0;l<6;l++)c[l]=t.readUByte();var d=t.readUByte();t.readUEG();var x=t.readUEG();x===3&&t.readBits(1);var f=t.readUEG(),h=t.readUEG(),A=t.readBoolean(),W=0,O=0,M=0,H=0;A&&(W=t.readUEG(),O=t.readUEG(),M=t.readUEG(),H=t.readUEG());var R=null,Se=t.readBoolean();if(Se){var ve=t.readBoolean();if(ve){var we=t.readUByte();we===255&&(t.readUShort(),t.readUShort())}var be=t.readBoolean();be&&t.readBoolean();var U=t.readBoolean();if(U){t.readBits(3),t.readBoolean();var Ae=t.readBoolean();Ae&&(t.readUByte(),t.readUByte(),t.readUByte())}var De=t.readBoolean();De&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean();var Ue=t.readBoolean();if(Ue){var Fe=t.readUInt(),Pe=t.readUInt();t.readBoolean(),Fe&&(R=Pe/(2*Fe))}}var Ne=x===1||x===2?2:1,Le=x===1?2:1,Me=f-Ne*(O+W),Ie=h-Le*(M+H);return{width:Me,height:Ie,profile_space:r,tier_flag:i,profile_idc:a,profile_compatibility_flags:o,constraint_indicator_flags:c,level_idc:d,chroma_format_idc:x,fps:R}}}]),n})(),p=(function(){function n(s){_(this,n),this.payload=s,this.nalUnitType=(s[0]&126)>>1,this.nuhLayerId=(s[0]&1)<<5|(s[1]&248)>>3,this.nuhTemporalIdPlus1=s[1]&7,this._isFirstSlice=null,this._sliceType=null}return w(n,[{key:"toString",value:function(){return"".concat(n.TYPES[this.type()]||"UNKNOWN ("+this.type()+")",": Layer: ").concat(this.nuhLayerId,", Temporal Id: ").concat(this.nuhTemporalIdPlus1)}},{key:"type",value:function(){return this.nalUnitType}},{key:"isKeyframe",get:function(){return[n.IDR_W_RADL,n.IDR_N_LP,n.CRA].includes(this.nalUnitType)}},{key:"isVCL",get:function(){return this.nalUnitType<=31}},{key:"parseHeader",value:function(){var e=new I(this.getPayload());e.readUByte(),e.readUByte(),this._isFirstSlice=e.readBoolean(),this.isKeyframe&&e.readBits(1),e.readUEG(),this._sliceType=e.readUEG()}},{key:"isFirstSlice",get:function(){return this._isFirstSlice||this.parseHeader(),this._isFirstSlice}},{key:"sliceType",get:function(){return this._sliceType||this.parseHeader(),this._sliceType}},{key:"getPayload",value:function(){return this.payload}},{key:"getPayloadSize",value:function(){return this.payload.byteLength}},{key:"getSize",value:function(){return 4+this.getPayloadSize()}},{key:"getData",value:function(){var e=new Uint8Array(this.getSize()),t=new DataView(e.buffer);return t.setUint32(0,this.getSize()-4),e.set(this.getPayload(),4),e}}],[{key:"TRAIL_N",get:function(){return 0}},{key:"TRAIL_R",get:function(){return 1}},{key:"IDR_W_RADL",get:function(){return 19}},{key:"IDR_N_LP",get:function(){return 20}},{key:"CRA",get:function(){return 21}},{key:"VPS",get:function(){return 32}},{key:"SPS",get:function(){return 33}},{key:"PPS",get:function(){return 34}},{key:"AUD",get:function(){return 35}},{key:"SEI",get:function(){return 39}},{key:"SEI2",get:function(){return 40}},{key:"TYPES",get:function(){var e;return e={},C(e,n.TRAIL_N,"TRAIL_N"),C(e,n.TRAIL_R,"TRAIL_R"),C(e,n.IDR_W_RADL,"IDR"),C(e,n.IDR_N_LP,"IDR2"),C(e,n.CRA,"CRA"),C(e,n.VPS,"VPS"),C(e,n.SPS,"SPS"),C(e,n.PPS,"PPS"),C(e,n.AUD,"AUD"),C(e,n.SEI,"SEI"),C(e,n.SEI2,"SEI2"),e}}]),n})(),S=(function(n){B(e,n);var s=G(e);function e(t,r,i){var a;return _(this,e),a=s.call(this,"H264Remuxer"),a.frameDuration=i,a.readyToDecode=!1,a.nextDts=0,a.dts=0,a.mp4track={id:$.getTrackID(),type:"video",len:0,fragmented:!0,vps:"",sps:"",pps:"",hvcC:{},fps:30,width:0,height:0,timescale:t,duration:r,samples:[]},a.samples=[],a.remainingData=new Uint8Array,a.kfCounter=0,a.pendingUnits={},a}return w(e,[{key:"resetTrack",value:function(){this.readyToDecode=!1,this.mp4track.vps="",this.mp4track.sps="",this.mp4track.pps="",this.mp4track.hvcC={},this.nextDts=0,this.dts=0,this.remainingData=new Uint8Array,this.kfCounter=0,this.pendingUnits={}}},{key:"feed",value:function(r,i,a){var o=[],c;r=g(this.remainingData,r);var l=b.extractNALu(r),d=K(l,2);return o=d[0],c=d[1],this.remainingData=c||new Uint8Array,o.length>0?(this.remux(this.getVideoFrames(o,i,a)),!0):(V("Failed to extract any NAL units from video data:",c),this.dispatch("outOfData"),!1)}},{key:"getVideoFrames",value:function(r,i,a){var o=this,c=[],l=[],d=0,x=0,f=!1,h=!1;this.pendingUnits.units&&(c=this.pendingUnits.units,h=this.pendingUnits.vcl,f=this.pendingUnits.keyFrame,this.pendingUnits={});var A=F(r),W;try{for(A.s();!(W=A.n()).done;){var O=W.value,M=new p(O);c.length&&h&&(M.isFirstSlice||!M.isVCL)&&(l.push({units:c,keyFrame:f}),c=[],f=!1,h=!1),c.push(M),f=f||M.isKeyframe,h=h||M.isVCL}}catch(R){A.e(R)}finally{A.f()}if(c.length)if(!i)this.pendingUnits={units:c,keyFrame:f,vcl:h};else if(h)l.push({units:c,keyFrame:f});else{var H=l.length-1;H>=0&&(l[H].units=l[H].units.concat(c))}return d=i?i/l.length|0:this.frameDuration,x=i?i-d*l.length:0,l.map(function(R){R.duration=d,R.compositionTimeOffset=a,x>0&&(R.duration++,x--),o.kfCounter++,R.keyFrame&&o.dispatch("keyframePosition",o.kfCounter*d/1e3)}),j("jmuxer: No. of H265 frames of the last chunk: ".concat(l.length)),l}},{key:"remux",value:function(r){var i=F(r),a;try{for(i.s();!(a=i.n()).done;){var o=a.value,c=[],l=0,d=F(o.units),x;try{for(d.s();!(x=d.n()).done;){var f=x.value;this.parseNAL(f)&&(c.push(f),l+=f.getSize())}}catch(h){d.e(h)}finally{d.f()}c.length>0&&this.readyToDecode&&(this.mp4track.len+=l,this.samples.push({units:c,size:l,keyFrame:o.keyFrame,duration:o.duration,compositionTimeOffset:o.compositionTimeOffset}))}}catch(h){i.e(h)}finally{i.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,a=this.mp4track.samples,o,c;for(this.dts=this.nextDts;this.samples.length;){var l=this.samples.shift(),d=l.units;if(c=l.duration,c<=0){j("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(c)),this.mp4track.len-=l.size;continue}this.nextDts+=c,o={size:l.size,duration:c,cts:l.compositionTimeOffset||0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:l.keyFrame?0:1,dependsOn:l.keyFrame?2:1}};var x=F(d),f;try{for(x.s();!(f=x.n()).done;){var h=f.value;r.set(h.getData(),i),i+=h.getSize()}}catch(A){x.e(A)}finally{x.f()}a.push(o)}return a.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"parseSPS",value:function(r){this.mp4track.sps=[new Uint8Array(r)],r=b.removeEmulationPreventionBytes(r);var i=b.readSPS(new Uint8Array(r));this.mp4track.fps=i.fps||this.mp4track.fps,this.mp4track.width=i.width,this.mp4track.height=i.height,this.mp4track.codec="hvc1.".concat(i.profile_idc,".").concat(i.profile_compatibility_flags.toString(16))+".L".concat(i.level_idc).concat(i.tier_flag?"H":"L")+".".concat(i.constraint_indicator_flags.map(function(a){return a.toString(16)}).join(".").toUpperCase()),this.mp4track.hvcC={profile_space:i.profile_space,tier_flag:i.tier_flag,profile_idc:i.profile_idc,profile_compatibility_flags:i.profile_compatibility_flags,constraint_indicator_flags:i.constraint_indicator_flags,level_idc:i.level_idc,chroma_format_idc:i.chroma_format_idc}}},{key:"parsePPS",value:function(r){this.mp4track.pps=[r]}},{key:"parseVPS",value:function(r){this.mp4track.vps=[r]}},{key:"parseNAL",value:function(r){if(!r)return!1;if(r.isVCL)return!0;var i=!1;switch(r.type()){case p.VPS:this.mp4track.vps||this.parseVPS(r.getPayload()),i=!0;break;case p.SPS:this.mp4track.sps||this.parseSPS(r.getPayload()),i=!0;break;case p.PPS:this.mp4track.pps||this.parsePPS(r.getPayload()),i=!0;break;case p.AUD:j("AUD - ignoing");break;case p.SEI:case p.SEI2:j("SEI - ignoing");break}return!this.readyToDecode&&this.mp4track.vps&&this.mp4track.sps&&this.mp4track.pps&&(this.readyToDecode=!0),i}}]),e})($),P=(function(n){B(e,n);var s=G(e);function e(t,r,i,a){var o;return _(this,e),o=s.call(this,"remuxer"),o.videoCodec=i,o.frameDuration=a,o.initialized=!1,o.tracks={},o.seq=1,o.env=t,o.timescale=1e3,o.mediaDuration=r?4294967295:0,o}return w(e,[{key:"addTrack",value:function(r){var i=this;if((r==="video"||r==="both")&&(this.videoCodec=="H265"?this.tracks.video=new S(this.timescale,this.mediaDuration,this.frameDuration):this.tracks.video=new N(this.timescale,this.mediaDuration,this.frameDuration),this.tracks.video.on("outOfData",function(){i.dispatch("missingVideoFrames")}),this.tracks.video.on("keyframePosition",function(o){i.dispatch("keyframePosition",o)})),r==="audio"||r==="both"){var a=new ue(this.timescale,this.mediaDuration,this.frameDuration);this.tracks.audio=a,this.tracks.video.on("outOfData",function(){i.dispatch("missingAudioFrames")})}}},{key:"reset",value:function(){for(var r in this.tracks)this.tracks[r].resetTrack();this.initialized=!1}},{key:"destroy",value:function(){this.tracks={},this.offAll()}},{key:"flush",value:function(){if(!this.initialized){if(!this.isReady())return;this.dispatch("ready"),this.initSegment(),this.initialized=!0}for(var r in this.tracks){var i=this.tracks[r],a=i.getPayload();if(a&&a.byteLength){var o=ie.moof(this.seq,i.dts,i.mp4track),c=ie.mdat(a),l=g(o,c),d={type:r,payload:l,dts:i.dts};r==="video"&&(d.fps=i.mp4track.fps),this.dispatch("buffer",d);var x=k(i.dts/this.timescale);j("put segment (".concat(r,"): dts: ").concat(i.dts," frames: ").concat(i.mp4track.samples.length," second: ").concat(x)),i.flush(),this.seq++}}}},{key:"initSegment",value:function(){var r=[];for(var i in this.tracks){var a=this.tracks[i];if(this.env=="browser"){var o={type:i,payload:ie.initSegment([a.mp4track],this.mediaDuration,this.timescale)};this.dispatch("buffer",o)}else r.push(a.mp4track)}if(this.env=="node"){var c={type:"all",payload:ie.initSegment(r,this.mediaDuration,this.timescale)};this.dispatch("buffer",c)}j("Initial segment generated.")}},{key:"isReady",value:function(){for(var r in this.tracks)if(!this.tracks[r].readyToDecode||!this.tracks[r].samples.length)return!1;return!0}},{key:"feed",value:function(r){var i=!1;if(r.video&&this.tracks.video&&(i|=this.tracks.video.feed(r.video,r.duration,r.compositionTimeOffset)),r.audio&&this.tracks.audio&&(i|=this.tracks.audio.feed(r.audio,r.duration)),!i){V("Input object must have video and/or audio property. Make sure it is a valid typed array");return}this.flush()}}]),e})(he),L=(function(n){B(e,n);var s=G(e);function e(t,r){var i;return _(this,e),i=s.call(this,"buffer"),i.type=r,i.queue=new Uint8Array,i.cleaning=!1,i.pendingCleaning=0,i.cleanOffset=30,i.cleanRanges=[],i.sourceBuffer=t,i.sourceBuffer.addEventListener("updateend",function(){if(i.pendingCleaning>0&&(i.initCleanup(i.pendingCleaning),i.pendingCleaning=0),i.cleaning=!1,i.cleanRanges.length){i.doCleanup();return}}),i.sourceBuffer.addEventListener("error",function(){i.dispatch("error",{type:i.type,name:"buffer",error:"buffer error"})}),i}return w(e,[{key:"destroy",value:function(){this.queue=null,this.sourceBuffer=null,this.offAll()}},{key:"doCleanup",value:function(){if(!this.cleanRanges.length){this.cleaning=!1;return}var r=this.cleanRanges.shift();j("".concat(this.type," remove range [").concat(r[0]," - ").concat(r[1],")")),this.cleaning=!0,this.sourceBuffer.remove(r[0],r[1])}},{key:"initCleanup",value:function(r){try{if(this.sourceBuffer.updating){this.pendingCleaning=r;return}if(this.sourceBuffer.buffered&&this.sourceBuffer.buffered.length&&!this.cleaning){for(var i=0;i<this.sourceBuffer.buffered.length;++i){var a=this.sourceBuffer.buffered.start(i),o=this.sourceBuffer.buffered.end(i);r-a>this.cleanOffset&&(o=r-this.cleanOffset,a<o&&this.cleanRanges.push([a,o]))}this.doCleanup()}}catch(c){V("Error occured while cleaning ".concat(this.type," buffer - ").concat(c.name,": ").concat(c.message))}}},{key:"doAppend",value:function(){if(this.queue.length&&!(!this.sourceBuffer||this.sourceBuffer.updating))try{this.sourceBuffer.appendBuffer(this.queue),this.queue=new Uint8Array}catch(i){var r="unexpectedError";i.name==="QuotaExceededError"?(j("".concat(this.type," buffer quota full")),r="QuotaExceeded"):(V("Error occured while appending ".concat(this.type," buffer - ").concat(i.name,": ").concat(i.message)),r="InvalidStateError"),this.dispatch("error",{type:this.type,name:r,error:"buffer error"})}}},{key:"feed",value:function(r){this.queue=g(this.queue,r)}}]),e})(he),T=(function(n){B(e,n);var s=G(e);function e(t){var r;_(this,e),r=s.call(this,"jmuxer"),r.isReset=!1;var i={node:"",mode:"both",videoCodec:"H264",flushingTime:500,maxDelay:500,clearBuffer:!0,fps:30,readFpsFromTrack:!1,debug:!1,onReady:function(){},onData:function(){},onError:function(){},onUnsupportedCodec:function(){},onMissingVideoFrames:function(){},onMissingAudioFrames:function(){},onKeyframePosition:function(){},onLoggerLog:console.log,onLoggerErr:console.error};return r.options=Object.assign({},i,t),r.env=(typeof process>"u"?"undefined":ne(process))==="object"&&typeof window>"u"?"node":"browser",r.options.debug&&me(r.options.onLoggerLog,r.options.onLoggerErr),r.options.fps||(r.options.fps=30),r.frameDuration=1e3/r.options.fps|0,r.remuxController=new P(r.env,t.live,r.options.videoCodec,r.frameDuration),r.remuxController.addTrack(r.options.mode),r.initData(),r.remuxController.on("buffer",r.onBuffer.bind(ce(r))),r.env=="browser"&&(r.remuxController.on("ready",r.createBuffer.bind(ce(r))),r.initBrowser()),r.remuxController.on("missingVideoFrames",function(){typeof r.options.onMissingVideoFrames=="function"&&r.options.onMissingVideoFrames.call(null)}),r.remuxController.on("missingAudioFrames",function(){typeof r.options.onMissingAudioFrames=="function"&&r.options.onMissingAudioFrames.call(null)}),r.clearBuffer&&r.remuxController.on("keyframePosition",function(a){r.kfPosition.push(a)}),typeof r.options.onKeyframePosition=="function"&&r.remuxController.on("keyframePosition",function(a){r.options.onKeyframePosition.call(null,a)}),r}return w(e,[{key:"initData",value:function(){this.lastCleaningTime=Date.now(),this.kfPosition=[],this.pendingUnits={},this.remainingData=new Uint8Array,this.startInterval()}},{key:"initBrowser",value:function(){typeof this.options.node=="string"&&this.options.node==""&&V("no video element were found to render, provide a valid video element"),this.node=typeof this.options.node=="string"?document.getElementById(this.options.node):this.options.node,this.mseReady=!1,this.setupMSE()}},{key:"createStream",value:function(){var r=this.feed.bind(this),i=this.destroy.bind(this);return this.stream=new ae.Duplex({writableObjectMode:!0,read:function(o){},write:function(o,c,l){r(o),l()},final:function(o){i(),o()}}),this.stream}},{key:"setupMSE",value:function(){if(window.MediaSource=window.MediaSource||window.WebKitMediaSource||window.ManagedMediaSource,!window.MediaSource)throw"Oops! Browser does not support Media Source Extension or Managed Media Source (IOS 17+).";if(this.isMSESupported=!!window.MediaSource,this.mediaSource=new window.MediaSource,this.url=URL.createObjectURL(this.mediaSource),window.MediaSource===window.ManagedMediaSource)try{this.node.removeAttribute("src"),this.node.disableRemotePlayback=!0;var r=document.createElement("source");r.type="video/mp4",r.src=this.url,this.node.appendChild(r),this.node.load()}catch{this.node.src=this.url}else this.node.src=this.url;this.mseEnded=!1,this.mediaSource.addEventListener("sourceopen",this.onMSEOpen.bind(this)),this.mediaSource.addEventListener("sourceclose",this.onMSEClose.bind(this)),this.mediaSource.addEventListener("webkitsourceopen",this.onMSEOpen.bind(this)),this.mediaSource.addEventListener("webkitsourceclose",this.onMSEClose.bind(this))}},{key:"endMSE",value:function(){if(!this.mseEnded)try{this.mseEnded=!0,this.mediaSource.endOfStream()}catch{V("mediasource is not available to end")}}},{key:"feed",value:function(r){!r||!this.remuxController||(r.duration=r.duration?parseInt(r.duration):0,this.remuxController.feed(r))}},{key:"destroy",value:function(){if(this.stopInterval(),this.stream&&(this.remuxController.flush(),this.stream.push(null),this.stream=null),this.remuxController&&(this.remuxController.destroy(),this.remuxController=null),this.bufferControllers){for(var r in this.bufferControllers)this.bufferControllers[r].destroy();this.bufferControllers=null,this.endMSE()}this.node=!1,this.mseReady=!1,this.videoStarted=!1,this.mediaSource=null}},{key:"reset",value:function(){if(this.stopInterval(),this.isReset=!0,this.node.pause(),this.remuxController&&this.remuxController.reset(),this.bufferControllers){for(var r in this.bufferControllers)this.bufferControllers[r].destroy();this.bufferControllers=null,this.endMSE()}this.initData(),this.env=="browser"&&this.initBrowser(),j("JMuxer was reset")}},{key:"createBuffer",value:function(){if(!(!this.mseReady||!this.remuxController||!this.remuxController.isReady()||this.bufferControllers)){this.bufferControllers={};for(var r in this.remuxController.tracks){var i=this.remuxController.tracks[r];if(!e.isSupported("".concat(r,'/mp4; codecs="').concat(i.mp4track.codec,'"')))return V("Browser does not support codec: ".concat(r,'/mp4; codecs="').concat(i.mp4track.codec,'"')),typeof this.options.onUnsupportedCodec=="function"&&this.options.onUnsupportedCodec.call(null,i.mp4track.codec),!1;var a=this.mediaSource.addSourceBuffer("".concat(r,'/mp4; codecs="').concat(i.mp4track.codec,'"'));this.bufferControllers[r]=new L(a,r),this.bufferControllers[r].on("error",this.onBufferError.bind(this))}}}},{key:"startInterval",value:function(){var r=this;this.interval=setInterval(function(){r.options.flushingTime?r.applyAndClearBuffer():r.bufferControllers&&r.cancelDelay()},this.options.flushingTime||1e3)}},{key:"stopInterval",value:function(){this.interval&&clearInterval(this.interval)}},{key:"cancelDelay",value:function(){if(this.node.buffered&&this.node.buffered.length>0&&!this.node.seeking){var r=this.node.buffered.end(0);r-this.node.currentTime>this.options.maxDelay/1e3&&(j("delay"),this.node.paused&&this.node.play().catch(V),this.node.currentTime=r-.001)}}},{key:"releaseBuffer",value:function(){for(var r in this.bufferControllers)this.bufferControllers[r].doAppend()}},{key:"applyAndClearBuffer",value:function(){this.bufferControllers&&(this.releaseBuffer(),this.clearBuffer())}},{key:"getSafeClearOffsetOfBuffer",value:function(r){for(var i=this.options.mode==="audio"&&r||0,a,o=0;o<this.kfPosition.length&&!(this.kfPosition[o]>=r);o++)a=this.kfPosition[o];return a&&(this.kfPosition=this.kfPosition.filter(function(c){return c<a&&(i=c),c>=a})),i}},{key:"clearBuffer",value:function(){if(this.options.clearBuffer&&Date.now()-this.lastCleaningTime>1e4){for(var r in this.bufferControllers){var i=this.getSafeClearOffsetOfBuffer(this.node.currentTime);this.bufferControllers[r].initCleanup(i)}this.lastCleaningTime=Date.now()}}},{key:"onBuffer",value:function(r){this.options.readFpsFromTrack&&typeof r.fps<"u"&&this.options.fps!=r.fps&&(this.options.fps=r.fps,this.frameDuration=Math.ceil(1e3/r.fps),j("JMuxer changed FPS to ".concat(r.fps," from track data"))),this.env=="browser"?this.bufferControllers&&this.bufferControllers[r.type]&&this.bufferControllers[r.type].feed(r.payload):this.stream&&this.stream.push(r.payload),this.options.onData&&this.options.onData(r.payload),this.options.flushingTime===0&&this.applyAndClearBuffer()}},{key:"onMSEOpen",value:function(){this.mseReady=!0,URL.revokeObjectURL(this.url),typeof this.options.onReady=="function"&&this.options.onReady.call(null,this.isReset)}},{key:"onMSEClose",value:function(){this.mseReady=!1,this.videoStarted=!1}},{key:"onBufferError",value:function(r){if(r.name=="QuotaExceeded"){j("JMuxer cleaning ".concat(r.type," buffer due to QuotaExceeded error")),this.bufferControllers[r.type].initCleanup(this.node.currentTime);return}else r.name=="InvalidStateError"?(j("JMuxer is reseting due to InvalidStateError"),this.reset()):this.endMSE();typeof this.options.onError=="function"&&this.options.onError.call(null,r)}}],[{key:"isSupported",value:function(r){return window.MediaSource&&window.MediaSource.isTypeSupported(r)}}]),e})(he);return T}))})(Ce)),Ce.exports}var Qe=Ze();const et=He(Qe),tt=400,je=50;function rt({className:ye,onFallback:se,fallbackTimeout:ae=5e3,enableControl:Z=!1,onTapSuccess:xe,onTapError:oe,onSwipeSuccess:ce,onSwipeError:_}){const y=m.useRef(null),w=m.useRef(null),F=m.useRef(null),[G,C]=m.useState("connecting"),[te,B]=m.useState(null),ee=m.useRef(null),pe=m.useRef(!1),[ge,ke]=m.useState([]),le=m.useRef(!1),E=m.useRef(null),[Q,K]=m.useState(null),re=m.useRef(null),q=m.useRef(null),J=m.useRef(0),ne=m.useRef(null),X=m.useRef(null),[D,fe]=m.useState(null),me=m.useRef(0),j=m.useRef(0),V=m.useRef(0),he=m.useRef(0),ie=m.useRef(se),v=m.useRef(ae),Y=(g,k,N)=>{const b=N.getBoundingClientRect(),p=b.width,S=b.height,P=N.videoWidth,L=N.videoHeight;if(P===0||L===0)return console.warn("[ScrcpyPlayer] Video dimensions not available yet"),null;const T=P/L,n=p/S;let s,e,t,r;n>T?(e=S,s=T*S,t=(p-s)/2,r=0):(s=p,e=p/T,t=0,r=(S-e)/2);const i=g-t,a=k-r;if(i<0||i>s||a<0||a>e)return console.warn("[ScrcpyPlayer] Click outside video area (in letterbox)"),null;const o=Math.round(i/s*P),c=Math.round(a/e*L);return console.log(`[ScrcpyPlayer] Coordinate transform:
5
+ Click: (${g}, ${k})
6
+ Display: ${p}x${S}
7
+ Video: ${P}x${L}
8
+ Rendered: ${s}x${e} at offset (${t}, ${r})
9
+ Device: (${o}, ${c})`),{x:o,y:c}},$=async g=>{if(!Z||!y.current||G!=="connected")return;le.current=!0,E.current={x:g.clientX,y:g.clientY,time:Date.now()};const k=y.current.getBoundingClientRect(),N=g.clientX-k.left,b=g.clientY-k.top,p=Y(N,b,y.current);if(!p||!D)return;const S=y.current.videoWidth,P=y.current.videoHeight,L=D.width/S,T=D.height/P,n=Math.round(p.x*L),s=Math.round(p.y*T);try{await ze(n,s),console.log(`[Touch] DOWN: (${n}, ${s})`)}catch(e){console.error("[Touch] DOWN failed:",e)}},ue=g=>{if(!le.current||!E.current)return;K({id:Date.now(),startX:E.current.x,startY:E.current.y,endX:g.clientX,endY:g.clientY});const k=y.current?.getBoundingClientRect();if(!k||!y.current||!D)return;const N=g.clientX-k.left,b=g.clientY-k.top,p=Y(N,b,y.current);if(!p)return;const S=y.current.videoWidth,P=y.current.videoHeight,L=D.width/S,T=D.height/P,n=Math.round(p.x*L),s=Math.round(p.y*T),e=Date.now();e-J.current>=je?(J.current=e,_e(n,s).catch(t=>{console.error("[Touch] MOVE failed:",t)})):(ne.current={x:n,y:s},X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{if(ne.current){const{x:t,y:r}=ne.current;J.current=Date.now(),_e(t,r).catch(i=>{console.error("[Touch] MOVE (throttled) failed:",i)}),ne.current=null}},je-(e-J.current)))},I=async g=>{if(!le.current||!E.current)return;const k=g.clientX-E.current.x,N=g.clientY-E.current.y,b=Date.now()-E.current.time;if(K(null),le.current=!1,X.current&&(clearTimeout(X.current),X.current=null),ne.current=null,Math.sqrt(k*k+N*N)<10&&b<200){z(g),E.current=null;return}const S=y.current?.getBoundingClientRect();if(!S||!y.current||!D){E.current=null;return}const P=g.clientX-S.left,L=g.clientY-S.top,T=Y(P,L,y.current);if(!T){E.current=null;return}const n=y.current.videoWidth,s=y.current.videoHeight,e=D.width/n,t=D.height/s,r=Math.round(T.x*e),i=Math.round(T.y*t);try{await Te(r,i),console.log(`[Touch] UP: (${r}, ${i})`),xe?.()}catch(a){console.error("[Touch] UP failed:",a),oe?.(String(a))}E.current=null},de=async g=>{if(!Z||!y.current||G!=="connected")return;const k=Date.now(),N=g.deltaY;q.current||(q.current={deltaY:0,lastTime:k,mouseX:g.clientX,mouseY:g.clientY}),q.current.deltaY+=N,q.current.lastTime=k;const b=.3;q.current.mouseX=Math.round(q.current.mouseX*(1-b)+g.clientX*b),q.current.mouseY=Math.round(q.current.mouseY*(1-b)+g.clientY*b),re.current&&clearTimeout(re.current),re.current=setTimeout(async()=>{if(!q.current||!y.current)return;const p=q.current;if(q.current=null,p.mouseX===void 0||p.mouseY===void 0)return;const S=y.current.getBoundingClientRect(),P=p.mouseX,L=p.mouseY,T=Math.abs(p.deltaY),n=Math.min(Math.max(300,T),800),s=Y(P-S.left,L-S.top,y.current);if(!s||!D){console.warn("[ScrcpyPlayer] Cannot execute scroll: coordinate transformation failed");return}const e=y.current.videoWidth,t=y.current.videoHeight,r=D.width/e,i=D.height/t,a=Math.round(s.x*r),o=Math.round(s.y*i);let c,l;p.deltaY>0?(c=o,l=o-T):(c=o,l=o+T);const d=Math.abs(l-c),x=Math.max(d/D.height*S.height,20),f=Math.min(Math.max(n*.8,200),800),h=document.createElement("div");h.style.cssText=`
10
+ position: fixed;
11
+ left: ${P}px;
12
+ top: ${L}px;
13
+ width: 20px;
14
+ height: 20px;
15
+ pointer-events: none;
16
+ z-index: 50;
17
+ transform: translateX(-50%) translateY(-50%);
18
+ background: radial-gradient(circle,
19
+ rgba(59, 130, 246, 0.8) 0%,
20
+ rgba(59, 130, 246, 0.4) 30%,
21
+ rgba(59, 130, 246, 0.2) 60%,
22
+ rgba(59, 130, 246, 0) 100%);
23
+ border-radius: 50%;
24
+ box-shadow: 0 0 10px rgba(59, 130, 246, 0.6);
25
+ `;const A=Date.now(),W=setInterval(()=>{const O=Date.now()-A,M=Math.min(O/f,1),H=p.deltaY>0?L-x*M:L+x*M;h.style.top=H+"px",M>=1&&clearInterval(W)},16);document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h),clearInterval(W)},f);try{const O=await Ye(a,c,a,l,n);O.success?ce?.():_?.(O.error||"Scroll failed")}catch(O){_?.(String(O))}},tt)},z=async g=>{if(!Z||!y.current||G!=="connected"||y.current.videoWidth===0||y.current.videoHeight===0||!D)return;const k=y.current.getBoundingClientRect(),N=g.clientX-k.left,b=g.clientY-k.top,p=Y(N,b,y.current);if(!p)return;const S=y.current.videoWidth,P=y.current.videoHeight,L=D.width/S,T=D.height/P,n=Math.round(p.x*L),s=Math.round(p.y*T),e=Date.now();ke(t=>[...t,{id:e,x:g.clientX,y:g.clientY}]),setTimeout(()=>{ke(t=>t.filter(r=>r.id!==e))},500);try{const t=await Ge(n,s);t.success?xe?.():oe?.(t.error||"Unknown error")}catch(t){oe?.(String(t))}};return m.useEffect(()=>{ie.current=se,v.current=ae},[se,ae]),m.useEffect(()=>{(async()=>{try{const k=await Re();k.success&&(fe({width:k.width,height:k.height}),console.log(`[ScrcpyPlayer] Device actual resolution: ${k.width}x${k.height}`))}catch(k){console.error("[ScrcpyPlayer] Failed to fetch device resolution:",k)}})()},[]),m.useEffect(()=>{let g=null,k=null;const N=async()=>{if(y.current){if(console.log("[ScrcpyPlayer] connect() called"),he.current=Date.now(),C("connecting"),B(null),F.current){console.log("[ScrcpyPlayer] Closing existing WebSocket");try{F.current.onclose=null,F.current.onerror=null,F.current.onmessage=null,F.current.close()}catch(b){console.error("[ScrcpyPlayer] Error closing old WebSocket:",b)}F.current=null}if(w.current){console.log("[ScrcpyPlayer] Destroying old jMuxer instance");try{w.current.destroy()}catch(b){console.error("[ScrcpyPlayer] Error destroying old jMuxer:",b)}w.current=null}y.current&&(y.current.src="",y.current.load()),await new Promise(b=>setTimeout(b,300));try{console.log("[ScrcpyPlayer] Creating new jMuxer instance (after cleanup delay)"),w.current=new et({node:y.current,mode:"video",flushingTime:0,fps:30,debug:!1,clearBuffer:!0,onError:p=>{if(console.error("[jMuxer] Decoder error:",p),p.name==="InvalidStateError"&&p.error==="buffer error"){const S=Date.now(),P=S-V.current;(S-he.current<1e3?P>500:P>2e3)?(V.current=S,console.warn("[jMuxer] ⚠️ Buffer error detected, reconnecting..."),k&&setTimeout(()=>{k()},100)):console.warn(`[jMuxer] Reconnect skipped (debounced: ${P}ms since last error)`)}}});const b=new WebSocket("ws://localhost:8000/api/video/stream");F.current=b,b.binaryType="arraybuffer",b.onopen=()=>{console.log("[ScrcpyPlayer] WebSocket connected"),C("connected"),ee.current=setTimeout(()=>{pe.current||(console.log("[ScrcpyPlayer] No data received within timeout, triggering fallback"),C("error"),B("Video stream timeout"),b.close(),ie.current&&ie.current())},v.current)},b.onmessage=p=>{if(typeof p.data=="string"){try{const S=JSON.parse(p.data);console.error("[ScrcpyPlayer] Server error:",S),B(S.error||"Unknown error"),C("error"),ie.current&&!pe.current&&ie.current()}catch{console.error("[ScrcpyPlayer] Received non-JSON string:",p.data)}return}pe.current||(pe.current=!0,console.log("[ScrcpyPlayer] First video data received, canceling fallback timer"),ee.current&&(clearTimeout(ee.current),ee.current=null));try{if(w.current&&p.data.byteLength>0){w.current.feed({video:new Uint8Array(p.data)}),me.current++;const S=Date.now(),P=S-j.current;if(P>5e3){const L=me.current/P*1e3,T=y.current,n=T&&T.buffered.length>0?T.buffered.end(0)-T.currentTime:0;console.log(`[ScrcpyPlayer] Stats: ${L.toFixed(1)} fps, buffer: ${n.toFixed(2)}s`),n>2&&console.warn(`[ScrcpyPlayer] ⚠ High latency detected: ${n.toFixed(2)}s buffer`),me.current=0,j.current=S}}}catch(S){console.error("[ScrcpyPlayer] Feed error:",S)}},b.onerror=p=>{console.error("[ScrcpyPlayer] WebSocket error:",p),B("Connection error"),C("error")},b.onclose=()=>{console.log("[ScrcpyPlayer] WebSocket closed"),C("disconnected"),g=setTimeout(()=>{console.log("[ScrcpyPlayer] Attempting to reconnect..."),N()},3e3)}}catch(b){console.error("[ScrcpyPlayer] Initialization error:",b),B("Initialization failed"),C("error")}}};return k=N,N(),()=>{if(g&&clearTimeout(g),ee.current&&(clearTimeout(ee.current),ee.current=null),F.current&&(F.current.close(),F.current=null),X.current&&(clearTimeout(X.current),X.current=null),w.current){try{w.current.destroy()}catch(b){console.error("[ScrcpyPlayer] Cleanup error:",b)}w.current=null}}},[]),u.jsxs("div",{className:`relative w-full h-full flex items-center justify-center ${ye||""}`,children:[u.jsx("video",{ref:y,autoPlay:!0,muted:!0,playsInline:!0,onMouseDown:$,onMouseMove:ue,onMouseUp:I,onMouseLeave:async()=>{if(le.current&&y.current&&D){if(E.current){const g=y.current.getBoundingClientRect(),k=Y(E.current.x-g.left,E.current.y-g.top,y.current);if(k){const N=D.width/y.current.videoWidth,b=D.height/y.current.videoHeight,p=Math.round(k.x*N),S=Math.round(k.y*b);try{await Te(p,S),console.log("[Touch] UP (mouse leave)")}catch(P){console.error("[Touch] UP (mouse leave) failed:",P)}}}le.current=!1,K(null),E.current=null}},onWheel:de,className:`max-w-full max-h-full object-contain ${Z?"cursor-pointer":""}`,style:{backgroundColor:"#000"}}),Z&&Q&&u.jsxs("svg",{className:"fixed inset-0 pointer-events-none z-40",children:[u.jsx("line",{x1:Q.startX,y1:Q.startY,x2:Q.endX,y2:Q.endY,stroke:"rgba(59, 130, 246, 0.8)",strokeWidth:"3",strokeLinecap:"round"}),u.jsx("circle",{cx:Q.startX,cy:Q.startY,r:"6",fill:"rgba(59, 130, 246, 0.8)"}),u.jsx("circle",{cx:Q.endX,cy:Q.endY,r:"6",fill:"rgba(239, 68, 68, 0.8)"})]}),Z&&ge.map(g=>u.jsx("div",{className:"fixed pointer-events-none z-50",style:{left:g.x,top:g.y},children:u.jsx("div",{className:"ripple-circle"})},g.id)),G!=="connected"&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:u.jsxs("div",{className:"text-center text-white",children:[G==="connecting"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"w-8 h-8 border-4 border-white border-t-transparent rounded-full animate-spin mx-auto mb-2"}),u.jsx("p",{children:"正在连接..."})]}),G==="disconnected"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"w-8 h-8 border-4 border-yellow-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"}),u.jsx("p",{children:"连接断开,正在重连..."})]}),G==="error"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"text-red-500 text-xl mb-2",children:"✗"}),u.jsx("p",{className:"text-red-400",children:"连接失败"}),te&&u.jsx("p",{className:"text-sm text-gray-400 mt-1",children:te})]})]})})]})}function it(){const[ye,se]=m.useState([]),[ae,Z]=m.useState(""),[xe,oe]=m.useState(!1),[ce,_]=m.useState(!1),[y,w]=m.useState(null),[F,G]=m.useState(null),[C,te]=m.useState(null),[B,ee]=m.useState({baseUrl:"",apiKey:"",modelName:""}),[pe,ge]=m.useState(!1),[ke,le]=m.useState(!0),[E,Q]=m.useState(!1),[K,re]=m.useState("auto"),[q,J]=m.useState(null),ne=m.useRef(null),X=m.useRef(!1),D=m.useRef([]),fe=m.useRef([]),me=()=>{ne.current?.scrollIntoView({behavior:"smooth"})};m.useEffect(()=>{me()},[ye]),m.useEffect(()=>{(async()=>{try{if((await Xe()).initialized)_(!0);else try{await Be(),_(!0)}catch{_(!1)}}catch{_(!1),w("无法连接到后端服务")}})()},[]),m.useEffect(()=>{if(!(K==="screenshot"||K==="auto"&&E))return;const Y=async()=>{if(!X.current){X.current=!0;try{const ue=await Re();ue.success&&G(ue)}catch(ue){console.error("Failed to fetch screenshot:",ue)}finally{X.current=!1}}};Y();const $=setInterval(Y,500);return()=>clearInterval($)},[E,K]);const j=async()=>{w(null);try{await Be({model_config:{base_url:B.baseUrl||void 0,api_key:B.apiKey||void 0,model_name:B.modelName||void 0}}),_(!0),ge(!1)}catch{w("初始化失败,请检查配置或确保后端服务正在运行")}},V=async()=>{if(!ae.trim()||xe)return;const v={id:Date.now().toString(),role:"user",content:ae.trim(),timestamp:new Date};se(I=>[...I,v]),Z(""),oe(!0),w(null),D.current=[],fe.current=[];const Y=(Date.now()+1).toString(),$={id:Y,role:"agent",content:"",timestamp:new Date,thinking:[],actions:[],isStreaming:!0};se(I=>[...I,$]);const ue=$e(v.content,I=>{console.log("[Chat] Processing step event:",I),D.current.push(I.thinking),fe.current.push(I.action),se(de=>de.map(z=>z.id===Y?{...z,thinking:[...D.current],actions:[...fe.current],steps:I.step}:z))},I=>{se(de=>de.map(z=>z.id===Y?{...z,content:I.message,success:I.success,isStreaming:!1}:z)),oe(!1),te(null)},I=>{se(de=>de.map(z=>z.id===Y?{...z,content:`错误: ${I.message}`,success:!1,isStreaming:!1}:z)),oe(!1),te(null)});te(ue)},he=async()=>{C&&(C.close(),te(null)),oe(!1),se([]),w(null),await Ve()},ie=v=>{v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),V())};return u.jsxs("div",{className:"h-full flex items-center justify-center p-4 gap-4 relative",children:[pe&&u.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 rounded-2xl",children:u.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-2xl w-96 shadow-xl border border-gray-200 dark:border-gray-700",children:[u.jsx("h2",{className:"text-xl font-bold mb-4 text-gray-900 dark:text-gray-100",children:"Agent 配置"}),u.jsxs("div",{className:"space-y-4",children:[u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300",children:"Base URL"}),u.jsx("input",{type:"text",value:B.baseUrl,onChange:v=>ee({...B,baseUrl:v.target.value}),placeholder:"留空使用默认值",className:"w-full px-3 py-2 border rounded-lg bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300",children:"API Key"}),u.jsx("input",{type:"password",value:B.apiKey,onChange:v=>ee({...B,apiKey:v.target.value}),placeholder:"留空使用默认值",className:"w-full px-3 py-2 border rounded-lg bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 outline-none"})]}),u.jsxs("div",{children:[u.jsx("label",{className:"block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300",children:"Model Name"}),u.jsx("input",{type:"text",value:B.modelName,onChange:v=>ee({...B,modelName:v.target.value}),placeholder:"留空使用默认值",className:"w-full px-3 py-2 border rounded-lg bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 outline-none"})]}),u.jsxs("div",{className:"flex justify-end gap-2 mt-6",children:[u.jsx("button",{onClick:()=>ge(!1),className:"px-4 py-2 text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200",children:"取消"}),u.jsx("button",{onClick:j,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"确认初始化"})]})]})]})}),u.jsxs("div",{className:"flex flex-col w-full max-w-2xl h-[750px] border border-gray-200 dark:border-gray-700 rounded-2xl shadow-lg bg-white dark:bg-gray-800",children:[u.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 rounded-t-2xl",children:[u.jsx("h1",{className:"text-xl font-semibold",children:"AutoGLM Chat"}),u.jsxs("div",{className:"flex gap-2",children:[ce?u.jsx("span",{className:"px-3 py-1 bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200 rounded-full text-sm flex items-center justify-center",children:"已初始化"}):u.jsx("button",{onClick:()=>ge(!0),className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center justify-center",children:"配置 Agent"}),u.jsx("button",{onClick:he,className:"px-4 py-2 bg-gray-200 dark:bg-gray-700 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors flex items-center justify-center",children:"重置"})]})]}),y&&u.jsx("div",{className:"mx-4 mt-4 p-3 bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-200 rounded-lg",children:y}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[ye.length===0&&u.jsxs("div",{className:"text-center text-gray-500 dark:text-gray-400 mt-8",children:[u.jsx("p",{className:"text-lg",children:"欢迎使用 AutoGLM Chat"}),u.jsx("p",{className:"text-sm mt-2",children:"输入任务描述,让 AI 帮你操作手机"})]}),ye.map(v=>u.jsx("div",{className:`flex ${v.role==="user"?"justify-end":"justify-start"}`,children:v.role==="agent"?u.jsxs("div",{className:"max-w-[80%] space-y-2",children:[v.thinking?.map((Y,$)=>u.jsxs("div",{className:"bg-gray-100 dark:bg-gray-700 rounded-2xl px-4 py-3 border-l-4 border-blue-500",children:[u.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:["💭 步骤 ",$+1," - 思考过程"]}),u.jsx("p",{className:"text-sm whitespace-pre-wrap",children:Y}),v.actions?.[$]&&u.jsxs("details",{className:"mt-2 text-xs",children:[u.jsx("summary",{className:"cursor-pointer text-blue-500 hover:text-blue-600",children:"查看动作"}),u.jsx("pre",{className:"mt-1 p-2 bg-gray-800 text-gray-200 rounded overflow-x-auto text-xs",children:JSON.stringify(v.actions[$],null,2)})]})]},$)),v.content&&u.jsxs("div",{className:`rounded-2xl px-4 py-3 ${v.success===!1?"bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200":"bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200"}`,children:[u.jsx("p",{className:"whitespace-pre-wrap",children:v.content}),v.steps!==void 0&&u.jsxs("p",{className:"text-xs mt-2 opacity-70",children:["总步数: ",v.steps]})]}),v.isStreaming&&u.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400 animate-pulse",children:"正在执行..."})]}):u.jsx("div",{className:"max-w-[70%] rounded-2xl px-4 py-3 bg-blue-500 text-white",children:u.jsx("p",{className:"whitespace-pre-wrap",children:v.content})})},v.id)),u.jsx("div",{ref:ne})]}),u.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-700 rounded-b-2xl",children:u.jsxs("div",{className:"flex gap-2",children:[u.jsx("input",{type:"text",value:ae,onChange:v=>Z(v.target.value),onKeyDown:ie,placeholder:ce?"输入任务描述...":"请先初始化 Agent",disabled:!ce||xe,className:"flex-1 px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"}),u.jsx("button",{onClick:V,disabled:!ce||xe||!ae.trim(),className:"px-6 py-3 bg-blue-500 text-white rounded-xl hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"发送"})]})})]}),u.jsxs("div",{className:"w-full max-w-xs h-[750px] border border-gray-200 dark:border-gray-700 rounded-2xl shadow-lg bg-gray-900 overflow-hidden relative",children:[u.jsxs("div",{className:"absolute top-2 right-2 z-10 flex gap-1 bg-black/70 rounded-lg p-1",children:[u.jsx("button",{onClick:()=>re("auto"),className:`px-3 py-1 text-xs rounded transition-colors ${K==="auto"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,title:"自动选择最佳显示模式",children:"自动"}),u.jsx("button",{onClick:()=>re("video"),className:`px-3 py-1 text-xs rounded transition-colors ${K==="video"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,title:"强制使用视频流",children:"视频流"}),u.jsx("button",{onClick:()=>re("screenshot"),className:`px-3 py-1 text-xs rounded transition-colors ${K==="screenshot"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,title:"使用截图模式 (0.5s刷新)",children:"截图"})]}),K==="video"||K==="auto"&&ke&&!E?u.jsxs(u.Fragment,{children:[q&&u.jsx("div",{className:"absolute top-14 right-2 z-20 px-3 py-2 bg-blue-500 text-white text-sm rounded-lg shadow-lg animate-fade-in",children:q}),u.jsx(rt,{className:"w-full h-full",enableControl:!0,onFallback:()=>{Q(!0),le(!1)},onTapSuccess:()=>{J("Tap executed"),setTimeout(()=>J(null),2e3)},onTapError:v=>{J(`Tap failed: ${v}`),setTimeout(()=>J(null),3e3)},onSwipeSuccess:()=>{J("Swipe executed"),setTimeout(()=>J(null),2e3)},onSwipeError:v=>{J(`Swipe failed: ${v}`),setTimeout(()=>J(null),3e3)},fallbackTimeout:1e5})]}):u.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-900",children:F&&F.success?u.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[u.jsx("img",{src:`data:image/png;base64,${F.image}`,alt:"Device Screenshot",className:"max-w-full max-h-full object-contain",style:{width:F.width>F.height?"100%":"auto",height:F.width>F.height?"auto":"100%"}}),F.is_sensitive&&u.jsx("div",{className:"absolute top-12 right-2 px-2 py-1 bg-yellow-500 text-white text-xs rounded",children:"敏感内容"}),u.jsxs("div",{className:"absolute bottom-2 left-2 px-2 py-1 bg-blue-500 text-white text-xs rounded",children:["截图模式 (0.5s 刷新)",K==="auto"&&E&&" - 视频流不可用"]})]}):F?.error?u.jsxs("div",{className:"text-center text-red-500 dark:text-red-400",children:[u.jsx("p",{className:"mb-2",children:"截图失败"}),u.jsx("p",{className:"text-xs",children:F.error})]}):u.jsxs("div",{className:"text-center text-gray-500 dark:text-gray-400",children:[u.jsx("div",{className:"w-8 h-8 border-4 border-gray-300 border-t-blue-500 rounded-full animate-spin mx-auto mb-2"}),u.jsx("p",{children:"加载中..."})]})})]})]})}export{it as component};