autoglm-gui 0.4.2__tar.gz → 0.4.3__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 (45) hide show
  1. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/scrcpy_stream.py +80 -36
  2. autoglm_gui-0.4.2/AutoGLM_GUI/static/assets/about-C9954kpk.js → autoglm_gui-0.4.3/AutoGLM_GUI/static/assets/about-B8Uhchgz.js +1 -1
  3. autoglm_gui-0.4.2/AutoGLM_GUI/static/assets/chat-CSgek5Xo.js → autoglm_gui-0.4.3/AutoGLM_GUI/static/assets/chat-CCzEYvEh.js +7 -7
  4. autoglm_gui-0.4.2/AutoGLM_GUI/static/assets/index-CCRJFa_5.js → autoglm_gui-0.4.3/AutoGLM_GUI/static/assets/index-BifYNxwo.js +1 -1
  5. autoglm_gui-0.4.3/AutoGLM_GUI/static/assets/index-C5w8tQiR.css +1 -0
  6. autoglm_gui-0.4.2/AutoGLM_GUI/static/assets/index-DZmNavz6.js → autoglm_gui-0.4.3/AutoGLM_GUI/static/assets/index-CVkp0My_.js +1 -1
  7. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/static/index.html +2 -2
  8. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/PKG-INFO +1 -1
  9. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/pyproject.toml +1 -1
  10. autoglm_gui-0.4.2/AutoGLM_GUI/static/assets/index-7WS8sURE.css +0 -1
  11. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/.gitignore +0 -0
  12. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/__init__.py +0 -0
  13. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/__main__.py +0 -0
  14. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/adb_plus/__init__.py +0 -0
  15. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/adb_plus/screenshot.py +0 -0
  16. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/adb_plus/touch.py +0 -0
  17. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/api/__init__.py +0 -0
  18. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/api/agents.py +0 -0
  19. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/api/control.py +0 -0
  20. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/api/devices.py +0 -0
  21. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/api/media.py +0 -0
  22. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/schemas.py +0 -0
  23. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/server.py +0 -0
  24. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/state.py +0 -0
  25. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/AutoGLM_GUI/version.py +0 -0
  26. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/LICENSE +0 -0
  27. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/README.md +0 -0
  28. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/__init__.py +0 -0
  29. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/actions/__init__.py +0 -0
  30. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/actions/handler.py +0 -0
  31. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/adb/__init__.py +0 -0
  32. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/adb/connection.py +0 -0
  33. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/adb/device.py +0 -0
  34. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/adb/input.py +0 -0
  35. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/adb/screenshot.py +0 -0
  36. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/agent.py +0 -0
  37. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/config/__init__.py +0 -0
  38. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/config/apps.py +0 -0
  39. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/config/i18n.py +0 -0
  40. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/config/prompts.py +0 -0
  41. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/config/prompts_en.py +0 -0
  42. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/config/prompts_zh.py +0 -0
  43. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/model/__init__.py +0 -0
  44. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/phone_agent/model/client.py +0 -0
  45. {autoglm_gui-0.4.2 → autoglm_gui-0.4.3}/scrcpy-server-v3.3.3 +0 -0
@@ -2,6 +2,7 @@
2
2
 
3
3
  import asyncio
4
4
  import os
5
+ import platform
5
6
  import socket
6
7
  import subprocess
7
8
  from pathlib import Path
@@ -118,29 +119,50 @@ class ScrcpyStreamer:
118
119
  if self.device_id:
119
120
  cmd_base.extend(["-s", self.device_id])
120
121
 
121
- # Method 1: Try pkill
122
- cmd = cmd_base + ["shell", "pkill", "-9", "-f", "app_process.*scrcpy"]
123
- process = await asyncio.create_subprocess_exec(
124
- *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
125
- )
126
- await process.wait()
122
+ # On Windows, use subprocess.run instead of asyncio.create_subprocess_exec
123
+ # to avoid NotImplementedError in some Windows environments
124
+ if platform.system() == "Windows":
125
+ # Method 1: Try pkill
126
+ cmd = cmd_base + ["shell", "pkill", "-9", "-f", "app_process.*scrcpy"]
127
+ subprocess.run(cmd, capture_output=True, check=False)
127
128
 
128
- # Method 2: Find and kill by PID (more reliable)
129
- cmd = cmd_base + [
130
- "shell",
131
- "ps -ef | grep 'app_process.*scrcpy' | grep -v grep | awk '{print $2}' | xargs kill -9",
132
- ]
133
- process = await asyncio.create_subprocess_exec(
134
- *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
135
- )
136
- await process.wait()
129
+ # Method 2: Find and kill by PID (more reliable)
130
+ cmd = cmd_base + [
131
+ "shell",
132
+ "ps -ef | grep 'app_process.*scrcpy' | grep -v grep | awk '{print $2}' | xargs kill -9",
133
+ ]
134
+ subprocess.run(cmd, capture_output=True, check=False)
135
+
136
+ # Method 3: Remove port forward if exists
137
+ cmd_remove_forward = cmd_base + ["forward", "--remove", f"tcp:{self.port}"]
138
+ subprocess.run(cmd_remove_forward, capture_output=True, check=False)
139
+ else:
140
+ # Original asyncio-based implementation for Unix systems
141
+ # Method 1: Try pkill
142
+ cmd = cmd_base + ["shell", "pkill", "-9", "-f", "app_process.*scrcpy"]
143
+ process = await asyncio.create_subprocess_exec(
144
+ *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
145
+ )
146
+ await process.wait()
137
147
 
138
- # Method 3: Remove port forward if exists
139
- cmd_remove_forward = cmd_base + ["forward", "--remove", f"tcp:{self.port}"]
140
- process = await asyncio.create_subprocess_exec(
141
- *cmd_remove_forward, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
142
- )
143
- await process.wait()
148
+ # Method 2: Find and kill by PID (more reliable)
149
+ cmd = cmd_base + [
150
+ "shell",
151
+ "ps -ef | grep 'app_process.*scrcpy' | grep -v grep | awk '{print $2}' | xargs kill -9",
152
+ ]
153
+ process = await asyncio.create_subprocess_exec(
154
+ *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
155
+ )
156
+ await process.wait()
157
+
158
+ # Method 3: Remove port forward if exists
159
+ cmd_remove_forward = cmd_base + ["forward", "--remove", f"tcp:{self.port}"]
160
+ process = await asyncio.create_subprocess_exec(
161
+ *cmd_remove_forward,
162
+ stdout=subprocess.DEVNULL,
163
+ stderr=subprocess.DEVNULL,
164
+ )
165
+ await process.wait()
144
166
 
145
167
  # Wait longer for resources to be released
146
168
  print("[ScrcpyStreamer] Waiting for cleanup to complete...")
@@ -153,10 +175,13 @@ class ScrcpyStreamer:
153
175
  cmd.extend(["-s", self.device_id])
154
176
  cmd.extend(["push", self.scrcpy_server_path, "/data/local/tmp/scrcpy-server"])
155
177
 
156
- process = await asyncio.create_subprocess_exec(
157
- *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
158
- )
159
- await process.wait()
178
+ if platform.system() == "Windows":
179
+ subprocess.run(cmd, capture_output=True, check=False)
180
+ else:
181
+ process = await asyncio.create_subprocess_exec(
182
+ *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
183
+ )
184
+ await process.wait()
160
185
 
161
186
  async def _setup_port_forward(self) -> None:
162
187
  """Setup ADB port forwarding."""
@@ -165,10 +190,13 @@ class ScrcpyStreamer:
165
190
  cmd.extend(["-s", self.device_id])
166
191
  cmd.extend(["forward", f"tcp:{self.port}", "localabstract:scrcpy"])
167
192
 
168
- process = await asyncio.create_subprocess_exec(
169
- *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
170
- )
171
- await process.wait()
193
+ if platform.system() == "Windows":
194
+ subprocess.run(cmd, capture_output=True, check=False)
195
+ else:
196
+ process = await asyncio.create_subprocess_exec(
197
+ *cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
198
+ )
199
+ await process.wait()
172
200
  self.forward_cleanup_needed = True
173
201
 
174
202
  async def _start_server(self) -> None:
@@ -203,19 +231,35 @@ class ScrcpyStreamer:
203
231
  cmd.extend(server_args)
204
232
 
205
233
  # Capture stderr to see error messages
206
- self.scrcpy_process = await asyncio.create_subprocess_exec(
207
- *cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
208
- )
234
+ if platform.system() == "Windows":
235
+ # On Windows, use subprocess.Popen for async-like behavior
236
+ self.scrcpy_process = subprocess.Popen(
237
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
238
+ )
239
+ else:
240
+ self.scrcpy_process = await asyncio.create_subprocess_exec(
241
+ *cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
242
+ )
209
243
 
210
244
  # Wait for server to start
211
245
  await asyncio.sleep(2)
212
246
 
213
247
  # Check if process is still running
214
- if self.scrcpy_process.returncode is not None:
215
- # Process has exited
216
- stdout, stderr = await self.scrcpy_process.communicate()
217
- error_msg = stderr.decode() if stderr else stdout.decode()
248
+ error_msg = None
249
+ if platform.system() == "Windows":
250
+ # For Windows Popen, check returncode directly
251
+ if self.scrcpy_process.poll() is not None:
252
+ # Process has exited
253
+ stdout, stderr = self.scrcpy_process.communicate()
254
+ error_msg = stderr.decode() if stderr else stdout.decode()
255
+ else:
256
+ # For asyncio subprocess
257
+ if self.scrcpy_process.returncode is not None:
258
+ # Process has exited
259
+ stdout, stderr = await self.scrcpy_process.communicate()
260
+ error_msg = stderr.decode() if stderr else stdout.decode()
218
261
 
262
+ if error_msg is not None:
219
263
  # Check if it's an "Address already in use" error
220
264
  if "Address already in use" in error_msg:
221
265
  if attempt < max_retries - 1:
@@ -1 +1 @@
1
- import{j as o}from"./index-DZmNavz6.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-CVkp0My_.js";function t(){return o.jsx("div",{className:"p-2",children:o.jsx("h3",{children:"About"})})}export{t as component};
@@ -1,12 +1,12 @@
1
- import{j as u,g as Ie,a as Oe,r as y,s as Pe,b as Ee,c as He,d as Te,e as $e,f as Ye,i as ze,h as Ve,k as Xe,l as Ge}from"./index-DZmNavz6.js";function We({id:m,model:oe,status:T,isInitialized:R,isActive:k,onClick:X}){const G=T==="device";return u.jsx("button",{onClick:X,className:`w-full text-left px-4 py-3 rounded-lg transition-all ${k?"bg-blue-500 text-white shadow-md":"bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"}`,children:u.jsxs("div",{className:"flex items-center justify-between gap-2",children:[u.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[u.jsx("div",{className:`w-2.5 h-2.5 rounded-full flex-shrink-0 ${G?"bg-green-400 shadow-[0_0_4px_rgba(74,222,128,0.6)]":"bg-gray-400"}`,title:G?"在线":"离线"}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:`font-medium text-sm truncate ${k?"text-white":"text-gray-900 dark:text-gray-100"}`,children:oe||"未知设备"}),u.jsx("div",{className:`text-xs truncate ${k?"text-blue-100":"text-gray-500 dark:text-gray-400"}`,children:m})]})]}),R&&u.jsx("div",{className:`flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center ${k?"bg-white/20":"bg-green-100 dark:bg-green-900"}`,children:u.jsx("svg",{className:`w-3 h-3 ${k?"text-white":"text-green-600 dark:text-green-400"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})})]})})}function Ke({devices:m,currentDeviceId:oe,onSelectDevice:T,onOpenConfig:R}){return u.jsxs("div",{className:"w-64 h-full bg-gray-50 dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700 flex flex-col",children:[u.jsxs("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700",children:[u.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[u.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),"设备列表"]}),u.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["共 ",m.length," 个设备"]})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:m.length===0?u.jsxs("div",{className:"text-center py-8 text-gray-500 dark:text-gray-400",children:[u.jsx("svg",{className:"w-12 h-12 mx-auto mb-2 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),u.jsx("p",{className:"text-sm",children:"未检测到设备"}),u.jsx("p",{className:"text-xs mt-1",children:"请连接 ADB 设备"})]}):m.map(k=>u.jsx(We,{id:k.id,model:k.model,status:k.status,isInitialized:k.is_initialized,isActive:k.id===oe,onClick:()=>T(k.id)},k.id))}),u.jsx("div",{className:"p-3 border-t border-gray-200 dark:border-gray-700 space-y-2",children:u.jsxs("button",{onClick:R,className:"w-full px-4 py-2 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg transition-colors text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center justify-center gap-2",children:[u.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),"全局配置"]})})]})}var Fe={exports:{}};const qe={},Je=Object.freeze(Object.defineProperty({__proto__:null,default:qe},Symbol.toStringTag,{value:"Module"})),Ze=Ie(Je);var Qe=Fe.exports,_e;function et(){return _e||(_e=1,(function(m,oe){(function(T,R){m.exports=R(Ze)})(Qe,(function(T){function R(n,a){(a==null||a>n.length)&&(a=n.length);for(var e=0,t=Array(a);e<a;e++)t[e]=n[e];return t}function k(n){if(Array.isArray(n))return n}function X(n){if(Array.isArray(n))return R(n)}function G(n){if(n===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}function D(n,a){if(!(n instanceof a))throw new TypeError("Cannot call a class as a function")}function U(n,a){for(var e=0;e<a.length;e++){var t=a[e];t.enumerable=t.enumerable||!1,t.configurable=!0,"value"in t&&(t.writable=!0),Object.defineProperty(n,fe(t.key),t)}}function _(n,a,e){return a&&U(n.prototype,a),e&&U(n,e),Object.defineProperty(n,"prototype",{writable:!1}),n}function x(n,a){var e=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!e){if(Array.isArray(n)||(e=O(n))||a){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(l){throw l},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,s=!0,o=!1;return{s:function(){e=e.call(n)},n:function(){var l=e.next();return s=l.done,l},e:function(l){o=!0,i=l},f:function(){try{s||e.return==null||e.return()}finally{if(o)throw i}}}}function j(n){var a=ee();return function(){var e,t=E(n);if(a){var r=E(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return ge(this,e)}}function C(n,a,e){return(a=fe(a))in n?Object.defineProperty(n,a,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[a]=e,n}function E(n){return E=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},E(n)}function Y(n,a){if(typeof a!="function"&&a!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(a&&a.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"prototype",{writable:!1}),a&&de(n,a)}function ee(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ee=function(){return!!n})()}function ve(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function te(n,a){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var t,r,i,s,o=[],l=!0,c=!1;try{if(i=(e=e.call(n)).next,a!==0)for(;!(l=(t=i.call(e)).done)&&(o.push(t.value),o.length!==a);l=!0);}catch(d){c=!0,r=d}finally{try{if(!l&&e.return!=null&&(s=e.return(),Object(s)!==s))return}finally{if(c)throw r}}return o}}function re(){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 z(){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 ge(n,a){if(a&&(typeof a=="object"||typeof a=="function"))return a;if(a!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return G(n)}function de(n,a){return de=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},de(n,a)}function $(n,a){return k(n)||te(n,a)||O(n,a)||re()}function F(n){return X(n)||ve(n)||O(n)||z()}function V(n,a){if(typeof n!="object"||!n)return n;var e=n[Symbol.toPrimitive];if(e!==void 0){var t=e.call(n,a);if(typeof t!="object")return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}function fe(n){var a=V(n,"string");return typeof a=="symbol"?a:a+""}function ne(n){"@babel/helpers - typeof";return ne=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},ne(n)}function O(n,a){if(n){if(typeof n=="string")return R(n,a);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)?R(n,a):void 0}}var ie,se;function q(n,a){ie=n,se=a}function b(n){if(ie){for(var a=arguments.length,e=new Array(a>1?a-1:0),t=1;t<a;t++)e[t-1]=arguments[t];ie.apply(void 0,[n].concat(e))}}function W(n){if(se){for(var a=arguments.length,e=new Array(a>1?a-1:0),t=1;t<a;t++)e[t-1]=arguments[t];se.apply(void 0,[n].concat(e))}}var ce=(function(){function n(a){D(this,n),this.listener={},this.type=a|""}return _(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(s){s.apply(null,r)}),!0):!1}}]),n})(),v=(function(){function n(){D(this,n)}return _(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]),s=new Uint8Array([0,0,0,0,0,0,0,0]);n.STTS=n.STSC=n.STCO=s,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]),l=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);n.FTYP=n.box(n.types.ftyp,o,c,o,l),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 s=8,o=r.length,l=o,c;o--;)s+=r[o].byteLength;for(c=new Uint8Array(s),c[0]=s>>24&255,c[1]=s>>16&255,c[2]=s>>8&255,c[3]=s&255,c.set(e,4),o=0,s=8;o<l;++o)c.set(r[o],s),s+=r[o].byteLength;return c}},{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,s=[];i--;)s[i]=n.trak(e[i]);return n.box.apply(null,[n.types.moov,n.mvhd(r,t)].concat(s).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,s;for(s=0;s<t.length;s++)i=t[s].flags,r[s+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,s,o;for(i=0;i<e.sps.length;i++)s=e.sps[i],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(i=0;i<e.pps.length;i++)s=e.pps[i],o=s.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(s));var l=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))),c=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,c>>8&255,c&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]),l,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=[],s,o,l=0;l<(((c=e.vps)===null||c===void 0?void 0:c.length)||0);l++){var c;s=e.vps[l],o=s.byteLength,t.push(o>>>8&255,o&255),t=t.concat(Array.prototype.slice.call(s))}for(var d=0;d<(((f=e.sps)===null||f===void 0?void 0:f.length)||0);d++){var f;s=e.sps[d],o=s.byteLength,r.push(o>>>8&255,o&255),r=r.concat(Array.prototype.slice.call(s))}for(var h=0;h<(((p=e.pps)===null||p===void 0?void 0:p.length)||0);h++){var p;s=e.pps[h],o=s.byteLength,i.push(o>>>8&255,o&255),i=i.concat(Array.prototype.slice.call(s))}var w=e.hvcC,N=w.profile_space,L=w.tier_flag,B=w.profile_idc,I=w.profile_compatibility_flags,A=w.constraint_indicator_flags,xe=w.level_idc,K=w.chroma_format_idc,ye=n.box(n.types.hvcC,new Uint8Array([1,N<<6|L<<5|B,I>>24&255,I>>16&255,I>>8&255,I&255].concat(F(A),[xe,240,0,252,252|K,248,248,0,0,3,3,32,0,1],F(t),[33,0,1],F(r),[34,0,1],F(i)))),ue=e.width,S=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,ue>>8&255,ue&255,S>>8&255,S&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]),ye,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,s=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,s>>8&255,s&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,s=12+16*i,o=new Uint8Array(s),l,c,d,f,h,p;for(t+=8+s,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),l=0;l<i;l++)c=r[l],d=c.duration,f=c.size,h=c.flags,p=c.cts,o.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,p>>>24&255,p>>>16&255,p>>>8&255,p&255],12+16*l);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),s;return s=new Uint8Array(n.FTYP.byteLength+i.byteLength),s.set(n.FTYP),s.set(i,n.FTYP.byteLength),s}}]),n})(),J=(function(){function n(){D(this,n)}return _(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=[],s,o;if(!n.isAACPattern(e))return W("Invalid ADTS audio format"),{valid:!1};s=n.getHeaderLength(e);for(var l=e.subarray(0,s);t<r;)o=n.getFrameLength(e),i.push(e.subarray(s,o)),e=e.slice(o),t+=o;return{valid:!0,header:l,slices:i}}}]),n})(),Z=1,M=(function(n){Y(e,n);var a=j(e);function e(){return D(this,e),a.apply(this,arguments)}return _(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 Z++}}]),e})(ce),le=(function(n){Y(e,n);var a=j(e);function e(t,r,i){var s;return D(this,e),s=a.call(this,"AACRemuxer"),s.frameDuration=i,s.readyToDecode=!1,s.header=null,s.nextDts=0,s.dts=0,s.mp4track={id:M.getTrackID(),type:"audio",channelCount:0,len:0,fragmented:!0,timescale:t,duration:r,samples:[],config:"",codec:""},s.samples=[],s}return _(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 s=J.extractAAC(r),o=s.valid,l=s.header,c=s.slices;return this.header||(this.header=l),o&&c.length>0?(this.remux(this.getAudioFrames(c,i)),!0):(W("Failed to extract audio data from:",r),this.dispatch("outOfData"),!1)}},{key:"getAudioFrames",value:function(r,i){var s=[],o=0,l=0,c=x(r),d;try{for(c.s();!(d=c.n()).done;){var f=d.value;s.push({units:f})}}catch(h){c.e(h)}finally{c.f()}return o=i?i/s.length|0:this.frameDuration,l=i?i-o*s.length:0,s.map(function(h){h.duration=o,l>0&&(h.duration++,l--)}),s}},{key:"remux",value:function(r){if(r.length>0)for(var i=0;i<r.length;i++){var s=r[i],o=s.units,l=o.byteLength;this.samples.push({units:o,size:l,duration:s.duration}),this.mp4track.len+=l,this.readyToDecode||this.setAACConfig()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,s=this.mp4track.samples,o,l;for(this.dts=this.nextDts;this.samples.length;){var c=this.samples.shift();if(c.units,l=c.duration,l<=0){b("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(l)),this.mp4track.len-=c.size;continue}this.nextDts+=l,o={size:c.size,duration:l,cts:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},r.set(c.units,i),i+=c.size,s.push(o)}return s.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"setAACConfig",value:function(){var r,i,s,o=new Uint8Array(2);this.header&&(r=((this.header[2]&192)>>>6)+1,i=(this.header[2]&60)>>>2,s=(this.header[2]&1)<<2,s|=(this.header[3]&192)>>>6,o[0]=r<<3,o[0]|=(i&14)>>1,o[1]|=(i&1)<<7,o[1]|=s<<3,this.mp4track.codec="mp4a.40."+r,this.mp4track.channelCount=s,this.mp4track.config=o,this.readyToDecode=!0)}}]),e})(M),ae=(function(){function n(a){D(this,n),this.data=a,this.index=0,this.bitLength=a.byteLength*8}return _(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,s=this.data[t/8|0]&255>>>i,o=8-i;if(o>=e)return r&&(this.index+=e),s>>o-e;r&&(this.index+=o);var l=e-o;return s<<l|this.getBits(l,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})(),be=(function(){function n(){D(this,n)}return _(n,null,[{key:"extractNALu",value:function(e){for(var t=0,r=e.byteLength,i=[],s=0,o=0;t<r;){var l=e[t++];if(l===0)o++;else if(l===1&&o>=2){var c=o+1;s!==t-c&&i.push(e.subarray(s,t-c)),s=t,o=0}else o=0}var d=null;return s<r&&(d=e.subarray(s,r)),[i,d]}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,s,o=0;o<t;o++)i!==0&&(s=e.readEG(),i=(r+s+256)%256),r=i===0?r:i}},{key:"readSPS",value:function(e){var t=new ae(e),r=0,i=0,s=0,o=0,l=1,c,d,f,h,p,w,N=0;t.readUByte();for(var L=[],B=1,I=e.byteLength,A=B;A<I;A++)A+2<I&&t.readBits(24,!1)===3?(L.push(t.readBits(8)),L.push(t.readBits(8)),A+=2,t.readBits(8)):L.push(t.readBits(8));if(t.setData(new Uint8Array(L)),c=t.readUByte(),t.readBits(5),t.skipBits(3),t.readUByte(),t.skipUEG(),c===100||c===110||c===122||c===244||c===44||c===83||c===86||c===118||c===128){var xe=t.readUEG();if(xe===3&&t.skipBits(1),t.skipUEG(),t.skipUEG(),t.skipBits(1),t.readBoolean()){w=xe!==3?8:12;for(var K=0;K<w;++K)t.readBoolean()&&(K<6?n.skipScalingList(t,16):n.skipScalingList(t,64))}}t.skipUEG();var ye=t.readUEG();if(ye===0)t.readUEG();else if(ye===1){t.skipBits(1),t.skipEG(),t.skipEG(),d=t.readUEG();for(var ue=0;ue<d;++ue)t.skipEG()}if(t.skipUEG(),t.skipBits(1),f=t.readUEG(),h=t.readUEG(),p=t.readBits(1),p===0&&t.skipBits(1),t.skipBits(1),t.readBoolean()&&(r=t.readUEG(),i=t.readUEG(),s=t.readUEG(),o=t.readUEG()),t.readBoolean()){if(t.readBoolean()){var S,me=t.readUByte();switch(me){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[t.readUByte()<<8|t.readUByte(),t.readUByte()<<8|t.readUByte()];break}}S&&S[0]>0&&S[1]>0&&(l=S[0]/S[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 we=t.readUInt(),Ae=t.readUInt(),Se=t.readBoolean(),Ue=Ae/(2*we);Se&&(N=Ue)}}return{fps:N>0?N:void 0,width:Math.ceil(((f+1)*16-r*2-i*2)*l),height:(2-p)*(h+1)*16-(p?2:4)*(s+o)}}}]),n})(),P=(function(){function n(a){D(this,n),this.payload=a,this.nri=(this.payload[0]&96)>>5,this.nalUnitType=this.payload[0]&31,this._sliceType=null,this._isFirstSlice=!1}return _(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 ae(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 Q(n,a){var e=new Uint8Array((n.byteLength|0)+(a.byteLength|0));return e.set(n,0),e.set(a,n.byteLength|0),e}function H(n){var a,e,t,r="";return a=Math.floor(n),e=parseInt(a/3600,10)%24,t=parseInt(a/60,10)%60,a=a<0?0:a%60,e>0&&(r+=(e<10?"0"+e:e)+":"),r+=(t<10?"0"+t:t)+":"+(a<10?"0"+a:a),r}var pe=(function(n){Y(e,n);var a=j(e);function e(t,r,i){var s;return D(this,e),s=a.call(this,"H264Remuxer"),s.frameDuration=i,s.readyToDecode=!1,s.nextDts=0,s.dts=0,s.mp4track={id:M.getTrackID(),type:"video",len:0,fragmented:!0,sps:"",pps:"",fps:30,width:0,height:0,timescale:t,duration:r,samples:[]},s.samples=[],s.remainingData=new Uint8Array,s.kfCounter=0,s.pendingUnits={},s}return _(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,s){var o=[],l;r=Q(this.remainingData,r);var c=be.extractNALu(r),d=$(c,2);return o=d[0],l=d[1],this.remainingData=l||new Uint8Array,o.length>0?(this.remux(this.getVideoFrames(o,i,s)),!0):(W("Failed to extract any NAL units from video data:",l),this.dispatch("outOfData"),!1)}},{key:"getVideoFrames",value:function(r,i,s){var o=this,l=[],c=[],d=0,f=0,h=!1,p=!1;this.pendingUnits.units&&(l=this.pendingUnits.units,p=this.pendingUnits.vcl,h=this.pendingUnits.keyFrame,this.pendingUnits={});var w=x(r),N;try{for(w.s();!(N=w.n()).done;){var L=N.value,B=new P(L);l.length&&p&&(B.isFirstSlice||!B.isVCL)&&(c.push({units:l,keyFrame:h}),l=[],h=!1,p=!1),l.push(B),h=h||B.isKeyframe,p=p||B.isVCL}}catch(A){w.e(A)}finally{w.f()}if(l.length)if(!i)this.pendingUnits={units:l,keyFrame:h,vcl:p};else if(p)c.push({units:l,keyFrame:h});else{var I=c.length-1;I>=0&&(c[I].units=c[I].units.concat(l))}return d=i?i/c.length|0:this.frameDuration,f=i?i-d*c.length:0,c.map(function(A){A.duration=d,A.compositionTimeOffset=s,f>0&&(A.duration++,f--),o.kfCounter++,A.keyFrame&&o.dispatch("keyframePosition",o.kfCounter*d/1e3)}),b("jmuxer: No. of H264 frames of the last chunk: ".concat(c.length)),c}},{key:"remux",value:function(r){var i=x(r),s;try{for(i.s();!(s=i.n()).done;){var o=s.value,l=[],c=0,d=x(o.units),f;try{for(d.s();!(f=d.n()).done;){var h=f.value;this.parseNAL(h)&&(l.push(h),c+=h.getSize())}}catch(p){d.e(p)}finally{d.f()}l.length>0&&this.readyToDecode&&(this.mp4track.len+=c,this.samples.push({units:l,size:c,keyFrame:o.keyFrame,duration:o.duration,compositionTimeOffset:o.compositionTimeOffset}))}}catch(p){i.e(p)}finally{i.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,s=this.mp4track.samples,o,l;for(this.dts=this.nextDts;this.samples.length;){var c=this.samples.shift(),d=c.units;if(l=c.duration,l<=0){b("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(l)),this.mp4track.len-=c.size;continue}this.nextDts+=l,o={size:c.size,duration:l,cts:c.compositionTimeOffset||0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:c.keyFrame?0:1,dependsOn:c.keyFrame?2:1}};var f=x(d),h;try{for(f.s();!(h=f.n()).done;){var p=h.value;r.set(p.getData(),i),i+=p.getSize()}}catch(w){f.e(w)}finally{f.f()}s.push(o)}return s.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"parseSPS",value:function(r){var i=be.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 s=new DataView(r.buffer,r.byteOffset+1,4),o=0;o<3;++o){var l=s.getUint8(o).toString(16);l.length<2&&(l="0"+l),this.mp4track.codec+=l}}},{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 P.PPS:this.mp4track.pps||this.parsePPS(r.getPayload()),i=!0;break;case P.SPS:this.mp4track.sps||this.parseSPS(r.getPayload()),i=!0;break;case P.AUD:b("AUD - ignoing");break;case P.SEI:b("SEI - ignoing");break}return!this.readyToDecode&&this.mp4track.pps&&this.mp4track.sps&&(this.readyToDecode=!0),i}}]),e})(M),ke=(function(){function n(){D(this,n)}return _(n,null,[{key:"extractNALu",value:function(e){for(var t=0,r=e.byteLength,i=[],s=0,o=0;t<r;){var l=e[t++];if(l===0)o++;else if(l===1&&o>=2){var c=o+1;s!==t-c&&i.push(e.subarray(s,t-c)),s=t,o=0}else o=0}var d=null;return s<r&&(d=e.subarray(s,r)),[i,d]}},{key:"removeEmulationPreventionBytes",value:function(e){for(var t=[],r=0,i=0;i<e.length;i++){var s=e[i];if(r===2&&s===3){r=0;continue}t.push(s),s===0?r++:r=0}return new Uint8Array(t)}},{key:"readSPS",value:function(e){var t=new ae(e);t.readUByte(),t.readUByte(),t.readBits(4),t.readBits(3),t.readBits(1);for(var r=t.readBits(2),i=t.readBits(1),s=t.readBits(5),o=t.readUInt(),l=new Uint8Array(6),c=0;c<6;c++)l[c]=t.readUByte();var d=t.readUByte();t.readUEG();var f=t.readUEG();f===3&&t.readBits(1);var h=t.readUEG(),p=t.readUEG(),w=t.readBoolean(),N=0,L=0,B=0,I=0;w&&(N=t.readUEG(),L=t.readUEG(),B=t.readUEG(),I=t.readUEG());var A=null,xe=t.readBoolean();if(xe){var K=t.readBoolean();if(K){var ye=t.readUByte();ye===255&&(t.readUShort(),t.readUShort())}var ue=t.readBoolean();ue&&t.readBoolean();var S=t.readBoolean();if(S){t.readBits(3),t.readBoolean();var me=t.readBoolean();me&&(t.readUByte(),t.readUByte(),t.readUByte())}var we=t.readBoolean();we&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean();var Ae=t.readBoolean();if(Ae){var Se=t.readUInt(),Ue=t.readUInt();t.readBoolean(),Se&&(A=Ue/(2*Se))}}var Ne=f===1||f===2?2:1,Re=f===1?2:1,Me=h-Ne*(L+N),Le=p-Re*(B+I);return{width:Me,height:Le,profile_space:r,tier_flag:i,profile_idc:s,profile_compatibility_flags:o,constraint_indicator_flags:l,level_idc:d,chroma_format_idc:f,fps:A}}}]),n})(),he=(function(){function n(a){D(this,n),this.payload=a,this.nalUnitType=(a[0]&126)>>1,this.nuhLayerId=(a[0]&1)<<5|(a[1]&248)>>3,this.nuhTemporalIdPlus1=a[1]&7,this._isFirstSlice=null,this._sliceType=null}return _(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 ae(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})(),Ce=(function(n){Y(e,n);var a=j(e);function e(t,r,i){var s;return D(this,e),s=a.call(this,"H264Remuxer"),s.frameDuration=i,s.readyToDecode=!1,s.nextDts=0,s.dts=0,s.mp4track={id:M.getTrackID(),type:"video",len:0,fragmented:!0,vps:"",sps:"",pps:"",hvcC:{},fps:30,width:0,height:0,timescale:t,duration:r,samples:[]},s.samples=[],s.remainingData=new Uint8Array,s.kfCounter=0,s.pendingUnits={},s}return _(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,s){var o=[],l;r=Q(this.remainingData,r);var c=ke.extractNALu(r),d=$(c,2);return o=d[0],l=d[1],this.remainingData=l||new Uint8Array,o.length>0?(this.remux(this.getVideoFrames(o,i,s)),!0):(W("Failed to extract any NAL units from video data:",l),this.dispatch("outOfData"),!1)}},{key:"getVideoFrames",value:function(r,i,s){var o=this,l=[],c=[],d=0,f=0,h=!1,p=!1;this.pendingUnits.units&&(l=this.pendingUnits.units,p=this.pendingUnits.vcl,h=this.pendingUnits.keyFrame,this.pendingUnits={});var w=x(r),N;try{for(w.s();!(N=w.n()).done;){var L=N.value,B=new he(L);l.length&&p&&(B.isFirstSlice||!B.isVCL)&&(c.push({units:l,keyFrame:h}),l=[],h=!1,p=!1),l.push(B),h=h||B.isKeyframe,p=p||B.isVCL}}catch(A){w.e(A)}finally{w.f()}if(l.length)if(!i)this.pendingUnits={units:l,keyFrame:h,vcl:p};else if(p)c.push({units:l,keyFrame:h});else{var I=c.length-1;I>=0&&(c[I].units=c[I].units.concat(l))}return d=i?i/c.length|0:this.frameDuration,f=i?i-d*c.length:0,c.map(function(A){A.duration=d,A.compositionTimeOffset=s,f>0&&(A.duration++,f--),o.kfCounter++,A.keyFrame&&o.dispatch("keyframePosition",o.kfCounter*d/1e3)}),b("jmuxer: No. of H265 frames of the last chunk: ".concat(c.length)),c}},{key:"remux",value:function(r){var i=x(r),s;try{for(i.s();!(s=i.n()).done;){var o=s.value,l=[],c=0,d=x(o.units),f;try{for(d.s();!(f=d.n()).done;){var h=f.value;this.parseNAL(h)&&(l.push(h),c+=h.getSize())}}catch(p){d.e(p)}finally{d.f()}l.length>0&&this.readyToDecode&&(this.mp4track.len+=c,this.samples.push({units:l,size:c,keyFrame:o.keyFrame,duration:o.duration,compositionTimeOffset:o.compositionTimeOffset}))}}catch(p){i.e(p)}finally{i.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,s=this.mp4track.samples,o,l;for(this.dts=this.nextDts;this.samples.length;){var c=this.samples.shift(),d=c.units;if(l=c.duration,l<=0){b("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(l)),this.mp4track.len-=c.size;continue}this.nextDts+=l,o={size:c.size,duration:l,cts:c.compositionTimeOffset||0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:c.keyFrame?0:1,dependsOn:c.keyFrame?2:1}};var f=x(d),h;try{for(f.s();!(h=f.n()).done;){var p=h.value;r.set(p.getData(),i),i+=p.getSize()}}catch(w){f.e(w)}finally{f.f()}s.push(o)}return s.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"parseSPS",value:function(r){this.mp4track.sps=[new Uint8Array(r)],r=ke.removeEmulationPreventionBytes(r);var i=ke.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(s){return s.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 he.VPS:this.mp4track.vps||this.parseVPS(r.getPayload()),i=!0;break;case he.SPS:this.mp4track.sps||this.parseSPS(r.getPayload()),i=!0;break;case he.PPS:this.mp4track.pps||this.parsePPS(r.getPayload()),i=!0;break;case he.AUD:b("AUD - ignoing");break;case he.SEI:case he.SEI2:b("SEI - ignoing");break}return!this.readyToDecode&&this.mp4track.vps&&this.mp4track.sps&&this.mp4track.pps&&(this.readyToDecode=!0),i}}]),e})(M),De=(function(n){Y(e,n);var a=j(e);function e(t,r,i,s){var o;return D(this,e),o=a.call(this,"remuxer"),o.videoCodec=i,o.frameDuration=s,o.initialized=!1,o.tracks={},o.seq=1,o.env=t,o.timescale=1e3,o.mediaDuration=r?4294967295:0,o}return _(e,[{key:"addTrack",value:function(r){var i=this;if((r==="video"||r==="both")&&(this.videoCodec=="H265"?this.tracks.video=new Ce(this.timescale,this.mediaDuration,this.frameDuration):this.tracks.video=new pe(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 s=new le(this.timescale,this.mediaDuration,this.frameDuration);this.tracks.audio=s,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],s=i.getPayload();if(s&&s.byteLength){var o=v.moof(this.seq,i.dts,i.mp4track),l=v.mdat(s),c=Q(o,l),d={type:r,payload:c,dts:i.dts};r==="video"&&(d.fps=i.mp4track.fps),this.dispatch("buffer",d);var f=H(i.dts/this.timescale);b("put segment (".concat(r,"): dts: ").concat(i.dts," frames: ").concat(i.mp4track.samples.length," second: ").concat(f)),i.flush(),this.seq++}}}},{key:"initSegment",value:function(){var r=[];for(var i in this.tracks){var s=this.tracks[i];if(this.env=="browser"){var o={type:i,payload:v.initSegment([s.mp4track],this.mediaDuration,this.timescale)};this.dispatch("buffer",o)}else r.push(s.mp4track)}if(this.env=="node"){var l={type:"all",payload:v.initSegment(r,this.mediaDuration,this.timescale)};this.dispatch("buffer",l)}b("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){W("Input object must have video and/or audio property. Make sure it is a valid typed array");return}this.flush()}}]),e})(ce),je=(function(n){Y(e,n);var a=j(e);function e(t,r){var i;return D(this,e),i=a.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 _(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();b("".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 s=this.sourceBuffer.buffered.start(i),o=this.sourceBuffer.buffered.end(i);r-s>this.cleanOffset&&(o=r-this.cleanOffset,s<o&&this.cleanRanges.push([s,o]))}this.doCleanup()}}catch(l){W("Error occured while cleaning ".concat(this.type," buffer - ").concat(l.name,": ").concat(l.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"?(b("".concat(this.type," buffer quota full")),r="QuotaExceeded"):(W("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=Q(this.queue,r)}}]),e})(ce),g=(function(n){Y(e,n);var a=j(e);function e(t){var r;D(this,e),r=a.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&&q(r.options.onLoggerLog,r.options.onLoggerErr),r.options.fps||(r.options.fps=30),r.frameDuration=1e3/r.options.fps|0,r.remuxController=new De(r.env,t.live,r.options.videoCodec,r.frameDuration),r.remuxController.addTrack(r.options.mode),r.initData(),r.remuxController.on("buffer",r.onBuffer.bind(G(r))),r.env=="browser"&&(r.remuxController.on("ready",r.createBuffer.bind(G(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(s){r.kfPosition.push(s)}),typeof r.options.onKeyframePosition=="function"&&r.remuxController.on("keyframePosition",function(s){r.options.onKeyframePosition.call(null,s)}),r}return _(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==""&&W("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 T.Duplex({writableObjectMode:!0,read:function(o){},write:function(o,l,c){r(o),c()},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{W("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(),b("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 W("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 s=this.mediaSource.addSourceBuffer("".concat(r,'/mp4; codecs="').concat(i.mp4track.codec,'"'));this.bufferControllers[r]=new je(s,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&&(b("delay"),this.node.paused&&this.node.play().catch(W),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,s,o=0;o<this.kfPosition.length&&!(this.kfPosition[o]>=r);o++)s=this.kfPosition[o];return s&&(this.kfPosition=this.kfPosition.filter(function(l){return l<s&&(i=l),l>=s})),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),b("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"){b("JMuxer cleaning ".concat(r.type," buffer due to QuotaExceeded error")),this.bufferControllers[r.type].initCleanup(this.node.currentTime);return}else r.name=="InvalidStateError"?(b("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})(ce);return g}))})(Fe)),Fe.exports}var tt=et();const rt=Oe(tt),nt=400,Be=50;function it({deviceId:m,className:oe,onFallback:T,fallbackTimeout:R=5e3,enableControl:k=!1,onTapSuccess:X,onTapError:G,onSwipeSuccess:D,onSwipeError:U,onStreamReady:_}){const x=y.useRef(null),j=y.useRef(null),C=y.useRef(null),E=y.useRef(m),[Y,ee]=y.useState("connecting"),[ve,te]=y.useState(null),re=y.useRef(null),z=y.useRef(!1),[ge,de]=y.useState([]),$=y.useRef(!1),F=y.useRef(null),[V,fe]=y.useState(null),ne=y.useRef(null),O=y.useRef(null),ie=y.useRef(0),se=y.useRef(null),q=y.useRef(null),[b,W]=y.useState(null),ce=y.useRef(0),v=y.useRef(0),J=y.useRef(0),Z=y.useRef(0),M=y.useRef(0),le=y.useRef(0),ae=3,be=1e3,P=y.useRef(T),Q=y.useRef(R),H=y.useRef(_),pe=(g,n,a)=>{const e=a.getBoundingClientRect(),t=e.width,r=e.height,i=a.videoWidth,s=a.videoHeight;if(i===0||s===0)return console.warn("[ScrcpyPlayer] Video dimensions not available yet"),null;const o=i/s,l=t/r;let c,d,f,h;l>o?(d=r,c=o*r,f=(t-c)/2,h=0):(c=t,d=t/o,f=0,h=(r-d)/2);const p=g-f,w=n-h;if(p<0||p>c||w<0||w>d)return console.warn("[ScrcpyPlayer] Click outside video area (in letterbox)"),null;const N=Math.round(p/c*i),L=Math.round(w/d*s);return console.log(`[ScrcpyPlayer] Coordinate transform:
5
- Click: (${g}, ${n})
1
+ import{j as u,r as p,g as Ie,a as Oe,s as Pe,b as Ne,c as He,d as Te,e as $e,f as Ye,i as ze,h as Ve,k as Xe,l as Ge}from"./index-CVkp0My_.js";function We({id:g,model:oe,status:T,isInitialized:R,isActive:k,onClick:$}){const Y=T==="device";return u.jsx("button",{onClick:$,className:`w-full text-left px-4 py-3 rounded-lg transition-all duration-500 ease-[cubic-bezier(0.4,0.0,0.2,1)] h-12 shrink-0 ${k?"bg-blue-500 text-white shadow-md":"bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"}`,children:u.jsxs("div",{className:"flex items-center justify-between gap-2",children:[u.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[u.jsx("div",{className:`w-2.5 h-2.5 rounded-full flex-shrink-0 ${Y?"bg-green-400 shadow-[0_0_4px_rgba(74,222,128,0.6)]":"bg-gray-400"}`,title:Y?"在线":"离线"}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:`font-medium text-sm truncate ${k?"text-white":"text-gray-900 dark:text-gray-100"}`,children:oe||"未知设备"}),u.jsx("div",{className:`text-xs truncate ${k?"text-blue-100":"text-gray-500 dark:text-gray-400"}`,children:g})]})]}),R&&u.jsx("div",{className:`flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center ${k?"bg-white/20":"bg-green-100 dark:bg-green-900"}`,children:u.jsx("svg",{className:`w-3 h-3 ${k?"text-white":"text-green-600 dark:text-green-400"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})})]})})}const Ke=()=>{try{const g=localStorage.getItem("sidebar-collapsed");return g!==null?JSON.parse(g):!1}catch(g){return console.warn("Failed to load sidebar collapsed state:",g),!1}};function qe({devices:g,currentDeviceId:oe,onSelectDevice:T,onOpenConfig:R}){const[k,$]=p.useState(Ke);p.useEffect(()=>{localStorage.setItem("sidebar-collapsed",JSON.stringify(k))},[k]),p.useEffect(()=>{const w=D=>{(D.metaKey||D.ctrlKey)&&D.key==="b"&&(D.preventDefault(),$(!k))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[k]);const Y=()=>{$(!k)};return u.jsxs(u.Fragment,{children:[k&&u.jsx("button",{onClick:Y,className:"fixed left-0 top-20 w-8 h-16 bg-blue-500 hover:bg-blue-600 text-white rounded-r-full shadow-lg transition-all duration-300 z-50 flex items-center justify-center",title:"展开侧边栏",children:u.jsx("svg",{className:"w-4 h-4 transition-transform duration-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}),u.jsxs("div",{className:`${k?"w-0 -ml-8":"w-64"} transition-all duration-500 ease-[cubic-bezier(0.4,0.0,0.2,1)] h-full bg-gray-50 dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700 flex flex-col overflow-hidden`,children:[u.jsxs("div",{className:"border-b border-gray-200 dark:border-gray-700 flex items-center justify-between p-4 whitespace-nowrap",children:[u.jsxs("div",{children:[u.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[u.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),"设备列表"]}),u.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["共 ",g.length," 个设备"]})]}),u.jsx("button",{onClick:Y,className:"p-1.5 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-all duration-300 ease-[cubic-bezier(0.4,0.0,0.2,1)]",title:"收缩侧边栏",children:u.jsx("svg",{className:"w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform duration-500 ease-[cubic-bezier(0.4,0.0,0.2,1)]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})})]}),u.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:g.length===0?u.jsxs("div",{className:"text-center py-8 text-gray-500 dark:text-gray-400",children:[u.jsx("svg",{className:"w-12 h-12 mx-auto mb-2 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),u.jsx("p",{className:"text-sm",children:"未检测到设备"}),u.jsx("p",{className:"text-xs mt-1",children:"请连接 ADB 设备"})]}):g.map(w=>u.jsx(We,{id:w.id,model:w.model,status:w.status,isInitialized:w.is_initialized,isActive:w.id===oe,onClick:()=>T(w.id)},w.id))}),u.jsx("div",{className:"p-3 border-t border-gray-200 dark:border-gray-700 space-y-2 whitespace-nowrap",children:u.jsxs("button",{onClick:R,className:"w-full px-4 py-2 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg transition-all duration-500 ease-[cubic-bezier(0.4,0.0,0.2,1)] font-medium text-gray-700 dark:text-gray-300 flex items-center justify-center gap-2",children:[u.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),"全局配置"]})})]})]})}var Fe={exports:{}};const Je={},Ze=Object.freeze(Object.defineProperty({__proto__:null,default:Je},Symbol.toStringTag,{value:"Module"})),Qe=Ie(Ze);var et=Fe.exports,_e;function tt(){return _e||(_e=1,(function(g,oe){(function(T,R){g.exports=R(Qe)})(et,(function(T){function R(n,a){(a==null||a>n.length)&&(a=n.length);for(var e=0,t=Array(a);e<a;e++)t[e]=n[e];return t}function k(n){if(Array.isArray(n))return n}function $(n){if(Array.isArray(n))return R(n)}function Y(n){if(n===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}function w(n,a){if(!(n instanceof a))throw new TypeError("Cannot call a class as a function")}function D(n,a){for(var e=0;e<a.length;e++){var t=a[e];t.enumerable=t.enumerable||!1,t.configurable=!0,"value"in t&&(t.writable=!0),Object.defineProperty(n,fe(t.key),t)}}function _(n,a,e){return a&&D(n.prototype,a),e&&D(n,e),Object.defineProperty(n,"prototype",{writable:!1}),n}function x(n,a){var e=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!e){if(Array.isArray(n)||(e=O(n))||a){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(l){throw l},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,s=!0,o=!1;return{s:function(){e=e.call(n)},n:function(){var l=e.next();return s=l.done,l},e:function(l){o=!0,i=l},f:function(){try{s||e.return==null||e.return()}finally{if(o)throw i}}}}function A(n){var a=ee();return function(){var e,t=N(n);if(a){var r=N(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return ge(this,e)}}function j(n,a,e){return(a=fe(a))in n?Object.defineProperty(n,a,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[a]=e,n}function N(n){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},N(n)}function V(n,a){if(typeof a!="function"&&a!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(a&&a.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"prototype",{writable:!1}),a&&de(n,a)}function ee(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ee=function(){return!!n})()}function ve(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function te(n,a){var e=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(e!=null){var t,r,i,s,o=[],l=!0,c=!1;try{if(i=(e=e.call(n)).next,a!==0)for(;!(l=(t=i.call(e)).done)&&(o.push(t.value),o.length!==a);l=!0);}catch(d){c=!0,r=d}finally{try{if(!l&&e.return!=null&&(s=e.return(),Object(s)!==s))return}finally{if(c)throw r}}return o}}function re(){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 X(){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 ge(n,a){if(a&&(typeof a=="object"||typeof a=="function"))return a;if(a!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Y(n)}function de(n,a){return de=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},de(n,a)}function z(n,a){return k(n)||te(n,a)||O(n,a)||re()}function C(n){return $(n)||ve(n)||O(n)||X()}function G(n,a){if(typeof n!="object"||!n)return n;var e=n[Symbol.toPrimitive];if(e!==void 0){var t=e.call(n,a);if(typeof t!="object")return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(n)}function fe(n){var a=G(n,"string");return typeof a=="symbol"?a:a+""}function ne(n){"@babel/helpers - typeof";return ne=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},ne(n)}function O(n,a){if(n){if(typeof n=="string")return R(n,a);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)?R(n,a):void 0}}var ie,se;function q(n,a){ie=n,se=a}function b(n){if(ie){for(var a=arguments.length,e=new Array(a>1?a-1:0),t=1;t<a;t++)e[t-1]=arguments[t];ie.apply(void 0,[n].concat(e))}}function W(n){if(se){for(var a=arguments.length,e=new Array(a>1?a-1:0),t=1;t<a;t++)e[t-1]=arguments[t];se.apply(void 0,[n].concat(e))}}var ce=(function(){function n(a){w(this,n),this.listener={},this.type=a|""}return _(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(s){s.apply(null,r)}),!0):!1}}]),n})(),v=(function(){function n(){w(this,n)}return _(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]),s=new Uint8Array([0,0,0,0,0,0,0,0]);n.STTS=n.STSC=n.STCO=s,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]),l=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);n.FTYP=n.box(n.types.ftyp,o,c,o,l),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 s=8,o=r.length,l=o,c;o--;)s+=r[o].byteLength;for(c=new Uint8Array(s),c[0]=s>>24&255,c[1]=s>>16&255,c[2]=s>>8&255,c[3]=s&255,c.set(e,4),o=0,s=8;o<l;++o)c.set(r[o],s),s+=r[o].byteLength;return c}},{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,s=[];i--;)s[i]=n.trak(e[i]);return n.box.apply(null,[n.types.moov,n.mvhd(r,t)].concat(s).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,s;for(s=0;s<t.length;s++)i=t[s].flags,r[s+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,s,o;for(i=0;i<e.sps.length;i++)s=e.sps[i],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(i=0;i<e.pps.length;i++)s=e.pps[i],o=s.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(s));var l=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))),c=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,c>>8&255,c&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]),l,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=[],s,o,l=0;l<(((c=e.vps)===null||c===void 0?void 0:c.length)||0);l++){var c;s=e.vps[l],o=s.byteLength,t.push(o>>>8&255,o&255),t=t.concat(Array.prototype.slice.call(s))}for(var d=0;d<(((f=e.sps)===null||f===void 0?void 0:f.length)||0);d++){var f;s=e.sps[d],o=s.byteLength,r.push(o>>>8&255,o&255),r=r.concat(Array.prototype.slice.call(s))}for(var h=0;h<(((y=e.pps)===null||y===void 0?void 0:y.length)||0);h++){var y;s=e.pps[h],o=s.byteLength,i.push(o>>>8&255,o&255),i=i.concat(Array.prototype.slice.call(s))}var S=e.hvcC,B=S.profile_space,M=S.tier_flag,E=S.profile_idc,I=S.profile_compatibility_flags,U=S.constraint_indicator_flags,xe=S.level_idc,K=S.chroma_format_idc,ye=n.box(n.types.hvcC,new Uint8Array([1,B<<6|M<<5|E,I>>24&255,I>>16&255,I>>8&255,I&255].concat(C(U),[xe,240,0,252,252|K,248,248,0,0,3,3,32,0,1],C(t),[33,0,1],C(r),[34,0,1],C(i)))),ue=e.width,F=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,ue>>8&255,ue&255,F>>8&255,F&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]),ye,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,s=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,s>>8&255,s&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,s=12+16*i,o=new Uint8Array(s),l,c,d,f,h,y;for(t+=8+s,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),l=0;l<i;l++)c=r[l],d=c.duration,f=c.size,h=c.flags,y=c.cts,o.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,y>>>24&255,y>>>16&255,y>>>8&255,y&255],12+16*l);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),s;return s=new Uint8Array(n.FTYP.byteLength+i.byteLength),s.set(n.FTYP),s.set(i,n.FTYP.byteLength),s}}]),n})(),J=(function(){function n(){w(this,n)}return _(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=[],s,o;if(!n.isAACPattern(e))return W("Invalid ADTS audio format"),{valid:!1};s=n.getHeaderLength(e);for(var l=e.subarray(0,s);t<r;)o=n.getFrameLength(e),i.push(e.subarray(s,o)),e=e.slice(o),t+=o;return{valid:!0,header:l,slices:i}}}]),n})(),Z=1,L=(function(n){V(e,n);var a=A(e);function e(){return w(this,e),a.apply(this,arguments)}return _(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 Z++}}]),e})(ce),le=(function(n){V(e,n);var a=A(e);function e(t,r,i){var s;return w(this,e),s=a.call(this,"AACRemuxer"),s.frameDuration=i,s.readyToDecode=!1,s.header=null,s.nextDts=0,s.dts=0,s.mp4track={id:L.getTrackID(),type:"audio",channelCount:0,len:0,fragmented:!0,timescale:t,duration:r,samples:[],config:"",codec:""},s.samples=[],s}return _(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 s=J.extractAAC(r),o=s.valid,l=s.header,c=s.slices;return this.header||(this.header=l),o&&c.length>0?(this.remux(this.getAudioFrames(c,i)),!0):(W("Failed to extract audio data from:",r),this.dispatch("outOfData"),!1)}},{key:"getAudioFrames",value:function(r,i){var s=[],o=0,l=0,c=x(r),d;try{for(c.s();!(d=c.n()).done;){var f=d.value;s.push({units:f})}}catch(h){c.e(h)}finally{c.f()}return o=i?i/s.length|0:this.frameDuration,l=i?i-o*s.length:0,s.map(function(h){h.duration=o,l>0&&(h.duration++,l--)}),s}},{key:"remux",value:function(r){if(r.length>0)for(var i=0;i<r.length;i++){var s=r[i],o=s.units,l=o.byteLength;this.samples.push({units:o,size:l,duration:s.duration}),this.mp4track.len+=l,this.readyToDecode||this.setAACConfig()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,s=this.mp4track.samples,o,l;for(this.dts=this.nextDts;this.samples.length;){var c=this.samples.shift();if(c.units,l=c.duration,l<=0){b("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(l)),this.mp4track.len-=c.size;continue}this.nextDts+=l,o={size:c.size,duration:l,cts:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},r.set(c.units,i),i+=c.size,s.push(o)}return s.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"setAACConfig",value:function(){var r,i,s,o=new Uint8Array(2);this.header&&(r=((this.header[2]&192)>>>6)+1,i=(this.header[2]&60)>>>2,s=(this.header[2]&1)<<2,s|=(this.header[3]&192)>>>6,o[0]=r<<3,o[0]|=(i&14)>>1,o[1]|=(i&1)<<7,o[1]|=s<<3,this.mp4track.codec="mp4a.40."+r,this.mp4track.channelCount=s,this.mp4track.config=o,this.readyToDecode=!0)}}]),e})(L),ae=(function(){function n(a){w(this,n),this.data=a,this.index=0,this.bitLength=a.byteLength*8}return _(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,s=this.data[t/8|0]&255>>>i,o=8-i;if(o>=e)return r&&(this.index+=e),s>>o-e;r&&(this.index+=o);var l=e-o;return s<<l|this.getBits(l,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})(),be=(function(){function n(){w(this,n)}return _(n,null,[{key:"extractNALu",value:function(e){for(var t=0,r=e.byteLength,i=[],s=0,o=0;t<r;){var l=e[t++];if(l===0)o++;else if(l===1&&o>=2){var c=o+1;s!==t-c&&i.push(e.subarray(s,t-c)),s=t,o=0}else o=0}var d=null;return s<r&&(d=e.subarray(s,r)),[i,d]}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,s,o=0;o<t;o++)i!==0&&(s=e.readEG(),i=(r+s+256)%256),r=i===0?r:i}},{key:"readSPS",value:function(e){var t=new ae(e),r=0,i=0,s=0,o=0,l=1,c,d,f,h,y,S,B=0;t.readUByte();for(var M=[],E=1,I=e.byteLength,U=E;U<I;U++)U+2<I&&t.readBits(24,!1)===3?(M.push(t.readBits(8)),M.push(t.readBits(8)),U+=2,t.readBits(8)):M.push(t.readBits(8));if(t.setData(new Uint8Array(M)),c=t.readUByte(),t.readBits(5),t.skipBits(3),t.readUByte(),t.skipUEG(),c===100||c===110||c===122||c===244||c===44||c===83||c===86||c===118||c===128){var xe=t.readUEG();if(xe===3&&t.skipBits(1),t.skipUEG(),t.skipUEG(),t.skipBits(1),t.readBoolean()){S=xe!==3?8:12;for(var K=0;K<S;++K)t.readBoolean()&&(K<6?n.skipScalingList(t,16):n.skipScalingList(t,64))}}t.skipUEG();var ye=t.readUEG();if(ye===0)t.readUEG();else if(ye===1){t.skipBits(1),t.skipEG(),t.skipEG(),d=t.readUEG();for(var ue=0;ue<d;++ue)t.skipEG()}if(t.skipUEG(),t.skipBits(1),f=t.readUEG(),h=t.readUEG(),y=t.readBits(1),y===0&&t.skipBits(1),t.skipBits(1),t.readBoolean()&&(r=t.readUEG(),i=t.readUEG(),s=t.readUEG(),o=t.readUEG()),t.readBoolean()){if(t.readBoolean()){var F,me=t.readUByte();switch(me){case 1:F=[1,1];break;case 2:F=[12,11];break;case 3:F=[10,11];break;case 4:F=[16,11];break;case 5:F=[40,33];break;case 6:F=[24,11];break;case 7:F=[20,11];break;case 8:F=[32,11];break;case 9:F=[80,33];break;case 10:F=[18,11];break;case 11:F=[15,11];break;case 12:F=[64,33];break;case 13:F=[160,99];break;case 14:F=[4,3];break;case 15:F=[3,2];break;case 16:F=[2,1];break;case 255:{F=[t.readUByte()<<8|t.readUByte(),t.readUByte()<<8|t.readUByte()];break}}F&&F[0]>0&&F[1]>0&&(l=F[0]/F[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 we=t.readUInt(),Ae=t.readUInt(),Se=t.readBoolean(),Ue=Ae/(2*we);Se&&(B=Ue)}}return{fps:B>0?B:void 0,width:Math.ceil(((f+1)*16-r*2-i*2)*l),height:(2-y)*(h+1)*16-(y?2:4)*(s+o)}}}]),n})(),P=(function(){function n(a){w(this,n),this.payload=a,this.nri=(this.payload[0]&96)>>5,this.nalUnitType=this.payload[0]&31,this._sliceType=null,this._isFirstSlice=!1}return _(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 ae(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={},j(e,n.IDR,"IDR"),j(e,n.SEI,"SEI"),j(e,n.SPS,"SPS"),j(e,n.PPS,"PPS"),j(e,n.NDR,"NDR"),j(e,n.AUD,"AUD"),e}}]),n})();function Q(n,a){var e=new Uint8Array((n.byteLength|0)+(a.byteLength|0));return e.set(n,0),e.set(a,n.byteLength|0),e}function H(n){var a,e,t,r="";return a=Math.floor(n),e=parseInt(a/3600,10)%24,t=parseInt(a/60,10)%60,a=a<0?0:a%60,e>0&&(r+=(e<10?"0"+e:e)+":"),r+=(t<10?"0"+t:t)+":"+(a<10?"0"+a:a),r}var pe=(function(n){V(e,n);var a=A(e);function e(t,r,i){var s;return w(this,e),s=a.call(this,"H264Remuxer"),s.frameDuration=i,s.readyToDecode=!1,s.nextDts=0,s.dts=0,s.mp4track={id:L.getTrackID(),type:"video",len:0,fragmented:!0,sps:"",pps:"",fps:30,width:0,height:0,timescale:t,duration:r,samples:[]},s.samples=[],s.remainingData=new Uint8Array,s.kfCounter=0,s.pendingUnits={},s}return _(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,s){var o=[],l;r=Q(this.remainingData,r);var c=be.extractNALu(r),d=z(c,2);return o=d[0],l=d[1],this.remainingData=l||new Uint8Array,o.length>0?(this.remux(this.getVideoFrames(o,i,s)),!0):(W("Failed to extract any NAL units from video data:",l),this.dispatch("outOfData"),!1)}},{key:"getVideoFrames",value:function(r,i,s){var o=this,l=[],c=[],d=0,f=0,h=!1,y=!1;this.pendingUnits.units&&(l=this.pendingUnits.units,y=this.pendingUnits.vcl,h=this.pendingUnits.keyFrame,this.pendingUnits={});var S=x(r),B;try{for(S.s();!(B=S.n()).done;){var M=B.value,E=new P(M);l.length&&y&&(E.isFirstSlice||!E.isVCL)&&(c.push({units:l,keyFrame:h}),l=[],h=!1,y=!1),l.push(E),h=h||E.isKeyframe,y=y||E.isVCL}}catch(U){S.e(U)}finally{S.f()}if(l.length)if(!i)this.pendingUnits={units:l,keyFrame:h,vcl:y};else if(y)c.push({units:l,keyFrame:h});else{var I=c.length-1;I>=0&&(c[I].units=c[I].units.concat(l))}return d=i?i/c.length|0:this.frameDuration,f=i?i-d*c.length:0,c.map(function(U){U.duration=d,U.compositionTimeOffset=s,f>0&&(U.duration++,f--),o.kfCounter++,U.keyFrame&&o.dispatch("keyframePosition",o.kfCounter*d/1e3)}),b("jmuxer: No. of H264 frames of the last chunk: ".concat(c.length)),c}},{key:"remux",value:function(r){var i=x(r),s;try{for(i.s();!(s=i.n()).done;){var o=s.value,l=[],c=0,d=x(o.units),f;try{for(d.s();!(f=d.n()).done;){var h=f.value;this.parseNAL(h)&&(l.push(h),c+=h.getSize())}}catch(y){d.e(y)}finally{d.f()}l.length>0&&this.readyToDecode&&(this.mp4track.len+=c,this.samples.push({units:l,size:c,keyFrame:o.keyFrame,duration:o.duration,compositionTimeOffset:o.compositionTimeOffset}))}}catch(y){i.e(y)}finally{i.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,s=this.mp4track.samples,o,l;for(this.dts=this.nextDts;this.samples.length;){var c=this.samples.shift(),d=c.units;if(l=c.duration,l<=0){b("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(l)),this.mp4track.len-=c.size;continue}this.nextDts+=l,o={size:c.size,duration:l,cts:c.compositionTimeOffset||0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:c.keyFrame?0:1,dependsOn:c.keyFrame?2:1}};var f=x(d),h;try{for(f.s();!(h=f.n()).done;){var y=h.value;r.set(y.getData(),i),i+=y.getSize()}}catch(S){f.e(S)}finally{f.f()}s.push(o)}return s.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"parseSPS",value:function(r){var i=be.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 s=new DataView(r.buffer,r.byteOffset+1,4),o=0;o<3;++o){var l=s.getUint8(o).toString(16);l.length<2&&(l="0"+l),this.mp4track.codec+=l}}},{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 P.PPS:this.mp4track.pps||this.parsePPS(r.getPayload()),i=!0;break;case P.SPS:this.mp4track.sps||this.parseSPS(r.getPayload()),i=!0;break;case P.AUD:b("AUD - ignoing");break;case P.SEI:b("SEI - ignoing");break}return!this.readyToDecode&&this.mp4track.pps&&this.mp4track.sps&&(this.readyToDecode=!0),i}}]),e})(L),ke=(function(){function n(){w(this,n)}return _(n,null,[{key:"extractNALu",value:function(e){for(var t=0,r=e.byteLength,i=[],s=0,o=0;t<r;){var l=e[t++];if(l===0)o++;else if(l===1&&o>=2){var c=o+1;s!==t-c&&i.push(e.subarray(s,t-c)),s=t,o=0}else o=0}var d=null;return s<r&&(d=e.subarray(s,r)),[i,d]}},{key:"removeEmulationPreventionBytes",value:function(e){for(var t=[],r=0,i=0;i<e.length;i++){var s=e[i];if(r===2&&s===3){r=0;continue}t.push(s),s===0?r++:r=0}return new Uint8Array(t)}},{key:"readSPS",value:function(e){var t=new ae(e);t.readUByte(),t.readUByte(),t.readBits(4),t.readBits(3),t.readBits(1);for(var r=t.readBits(2),i=t.readBits(1),s=t.readBits(5),o=t.readUInt(),l=new Uint8Array(6),c=0;c<6;c++)l[c]=t.readUByte();var d=t.readUByte();t.readUEG();var f=t.readUEG();f===3&&t.readBits(1);var h=t.readUEG(),y=t.readUEG(),S=t.readBoolean(),B=0,M=0,E=0,I=0;S&&(B=t.readUEG(),M=t.readUEG(),E=t.readUEG(),I=t.readUEG());var U=null,xe=t.readBoolean();if(xe){var K=t.readBoolean();if(K){var ye=t.readUByte();ye===255&&(t.readUShort(),t.readUShort())}var ue=t.readBoolean();ue&&t.readBoolean();var F=t.readBoolean();if(F){t.readBits(3),t.readBoolean();var me=t.readBoolean();me&&(t.readUByte(),t.readUByte(),t.readUByte())}var we=t.readBoolean();we&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean();var Ae=t.readBoolean();if(Ae){var Se=t.readUInt(),Ue=t.readUInt();t.readBoolean(),Se&&(U=Ue/(2*Se))}}var Be=f===1||f===2?2:1,Re=f===1?2:1,Le=h-Be*(M+B),Me=y-Re*(E+I);return{width:Le,height:Me,profile_space:r,tier_flag:i,profile_idc:s,profile_compatibility_flags:o,constraint_indicator_flags:l,level_idc:d,chroma_format_idc:f,fps:U}}}]),n})(),he=(function(){function n(a){w(this,n),this.payload=a,this.nalUnitType=(a[0]&126)>>1,this.nuhLayerId=(a[0]&1)<<5|(a[1]&248)>>3,this.nuhTemporalIdPlus1=a[1]&7,this._isFirstSlice=null,this._sliceType=null}return _(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 ae(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={},j(e,n.TRAIL_N,"TRAIL_N"),j(e,n.TRAIL_R,"TRAIL_R"),j(e,n.IDR_W_RADL,"IDR"),j(e,n.IDR_N_LP,"IDR2"),j(e,n.CRA,"CRA"),j(e,n.VPS,"VPS"),j(e,n.SPS,"SPS"),j(e,n.PPS,"PPS"),j(e,n.AUD,"AUD"),j(e,n.SEI,"SEI"),j(e,n.SEI2,"SEI2"),e}}]),n})(),Ce=(function(n){V(e,n);var a=A(e);function e(t,r,i){var s;return w(this,e),s=a.call(this,"H264Remuxer"),s.frameDuration=i,s.readyToDecode=!1,s.nextDts=0,s.dts=0,s.mp4track={id:L.getTrackID(),type:"video",len:0,fragmented:!0,vps:"",sps:"",pps:"",hvcC:{},fps:30,width:0,height:0,timescale:t,duration:r,samples:[]},s.samples=[],s.remainingData=new Uint8Array,s.kfCounter=0,s.pendingUnits={},s}return _(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,s){var o=[],l;r=Q(this.remainingData,r);var c=ke.extractNALu(r),d=z(c,2);return o=d[0],l=d[1],this.remainingData=l||new Uint8Array,o.length>0?(this.remux(this.getVideoFrames(o,i,s)),!0):(W("Failed to extract any NAL units from video data:",l),this.dispatch("outOfData"),!1)}},{key:"getVideoFrames",value:function(r,i,s){var o=this,l=[],c=[],d=0,f=0,h=!1,y=!1;this.pendingUnits.units&&(l=this.pendingUnits.units,y=this.pendingUnits.vcl,h=this.pendingUnits.keyFrame,this.pendingUnits={});var S=x(r),B;try{for(S.s();!(B=S.n()).done;){var M=B.value,E=new he(M);l.length&&y&&(E.isFirstSlice||!E.isVCL)&&(c.push({units:l,keyFrame:h}),l=[],h=!1,y=!1),l.push(E),h=h||E.isKeyframe,y=y||E.isVCL}}catch(U){S.e(U)}finally{S.f()}if(l.length)if(!i)this.pendingUnits={units:l,keyFrame:h,vcl:y};else if(y)c.push({units:l,keyFrame:h});else{var I=c.length-1;I>=0&&(c[I].units=c[I].units.concat(l))}return d=i?i/c.length|0:this.frameDuration,f=i?i-d*c.length:0,c.map(function(U){U.duration=d,U.compositionTimeOffset=s,f>0&&(U.duration++,f--),o.kfCounter++,U.keyFrame&&o.dispatch("keyframePosition",o.kfCounter*d/1e3)}),b("jmuxer: No. of H265 frames of the last chunk: ".concat(c.length)),c}},{key:"remux",value:function(r){var i=x(r),s;try{for(i.s();!(s=i.n()).done;){var o=s.value,l=[],c=0,d=x(o.units),f;try{for(d.s();!(f=d.n()).done;){var h=f.value;this.parseNAL(h)&&(l.push(h),c+=h.getSize())}}catch(y){d.e(y)}finally{d.f()}l.length>0&&this.readyToDecode&&(this.mp4track.len+=c,this.samples.push({units:l,size:c,keyFrame:o.keyFrame,duration:o.duration,compositionTimeOffset:o.compositionTimeOffset}))}}catch(y){i.e(y)}finally{i.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var r=new Uint8Array(this.mp4track.len),i=0,s=this.mp4track.samples,o,l;for(this.dts=this.nextDts;this.samples.length;){var c=this.samples.shift(),d=c.units;if(l=c.duration,l<=0){b("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(l)),this.mp4track.len-=c.size;continue}this.nextDts+=l,o={size:c.size,duration:l,cts:c.compositionTimeOffset||0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:c.keyFrame?0:1,dependsOn:c.keyFrame?2:1}};var f=x(d),h;try{for(f.s();!(h=f.n()).done;){var y=h.value;r.set(y.getData(),i),i+=y.getSize()}}catch(S){f.e(S)}finally{f.f()}s.push(o)}return s.length?new Uint8Array(r.buffer,0,this.mp4track.len):null}},{key:"parseSPS",value:function(r){this.mp4track.sps=[new Uint8Array(r)],r=ke.removeEmulationPreventionBytes(r);var i=ke.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(s){return s.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 he.VPS:this.mp4track.vps||this.parseVPS(r.getPayload()),i=!0;break;case he.SPS:this.mp4track.sps||this.parseSPS(r.getPayload()),i=!0;break;case he.PPS:this.mp4track.pps||this.parsePPS(r.getPayload()),i=!0;break;case he.AUD:b("AUD - ignoing");break;case he.SEI:case he.SEI2:b("SEI - ignoing");break}return!this.readyToDecode&&this.mp4track.vps&&this.mp4track.sps&&this.mp4track.pps&&(this.readyToDecode=!0),i}}]),e})(L),De=(function(n){V(e,n);var a=A(e);function e(t,r,i,s){var o;return w(this,e),o=a.call(this,"remuxer"),o.videoCodec=i,o.frameDuration=s,o.initialized=!1,o.tracks={},o.seq=1,o.env=t,o.timescale=1e3,o.mediaDuration=r?4294967295:0,o}return _(e,[{key:"addTrack",value:function(r){var i=this;if((r==="video"||r==="both")&&(this.videoCodec=="H265"?this.tracks.video=new Ce(this.timescale,this.mediaDuration,this.frameDuration):this.tracks.video=new pe(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 s=new le(this.timescale,this.mediaDuration,this.frameDuration);this.tracks.audio=s,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],s=i.getPayload();if(s&&s.byteLength){var o=v.moof(this.seq,i.dts,i.mp4track),l=v.mdat(s),c=Q(o,l),d={type:r,payload:c,dts:i.dts};r==="video"&&(d.fps=i.mp4track.fps),this.dispatch("buffer",d);var f=H(i.dts/this.timescale);b("put segment (".concat(r,"): dts: ").concat(i.dts," frames: ").concat(i.mp4track.samples.length," second: ").concat(f)),i.flush(),this.seq++}}}},{key:"initSegment",value:function(){var r=[];for(var i in this.tracks){var s=this.tracks[i];if(this.env=="browser"){var o={type:i,payload:v.initSegment([s.mp4track],this.mediaDuration,this.timescale)};this.dispatch("buffer",o)}else r.push(s.mp4track)}if(this.env=="node"){var l={type:"all",payload:v.initSegment(r,this.mediaDuration,this.timescale)};this.dispatch("buffer",l)}b("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){W("Input object must have video and/or audio property. Make sure it is a valid typed array");return}this.flush()}}]),e})(ce),je=(function(n){V(e,n);var a=A(e);function e(t,r){var i;return w(this,e),i=a.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 _(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();b("".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 s=this.sourceBuffer.buffered.start(i),o=this.sourceBuffer.buffered.end(i);r-s>this.cleanOffset&&(o=r-this.cleanOffset,s<o&&this.cleanRanges.push([s,o]))}this.doCleanup()}}catch(l){W("Error occured while cleaning ".concat(this.type," buffer - ").concat(l.name,": ").concat(l.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"?(b("".concat(this.type," buffer quota full")),r="QuotaExceeded"):(W("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=Q(this.queue,r)}}]),e})(ce),m=(function(n){V(e,n);var a=A(e);function e(t){var r;w(this,e),r=a.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&&q(r.options.onLoggerLog,r.options.onLoggerErr),r.options.fps||(r.options.fps=30),r.frameDuration=1e3/r.options.fps|0,r.remuxController=new De(r.env,t.live,r.options.videoCodec,r.frameDuration),r.remuxController.addTrack(r.options.mode),r.initData(),r.remuxController.on("buffer",r.onBuffer.bind(Y(r))),r.env=="browser"&&(r.remuxController.on("ready",r.createBuffer.bind(Y(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(s){r.kfPosition.push(s)}),typeof r.options.onKeyframePosition=="function"&&r.remuxController.on("keyframePosition",function(s){r.options.onKeyframePosition.call(null,s)}),r}return _(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==""&&W("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 T.Duplex({writableObjectMode:!0,read:function(o){},write:function(o,l,c){r(o),c()},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{W("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(),b("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 W("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 s=this.mediaSource.addSourceBuffer("".concat(r,'/mp4; codecs="').concat(i.mp4track.codec,'"'));this.bufferControllers[r]=new je(s,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&&(b("delay"),this.node.paused&&this.node.play().catch(W),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,s,o=0;o<this.kfPosition.length&&!(this.kfPosition[o]>=r);o++)s=this.kfPosition[o];return s&&(this.kfPosition=this.kfPosition.filter(function(l){return l<s&&(i=l),l>=s})),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),b("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"){b("JMuxer cleaning ".concat(r.type," buffer due to QuotaExceeded error")),this.bufferControllers[r.type].initCleanup(this.node.currentTime);return}else r.name=="InvalidStateError"?(b("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})(ce);return m}))})(Fe)),Fe.exports}var rt=tt();const nt=Oe(rt),it=400,Ee=50;function st({deviceId:g,className:oe,onFallback:T,fallbackTimeout:R=5e3,enableControl:k=!1,onTapSuccess:$,onTapError:Y,onSwipeSuccess:w,onSwipeError:D,onStreamReady:_}){const x=p.useRef(null),A=p.useRef(null),j=p.useRef(null),N=p.useRef(g),[V,ee]=p.useState("connecting"),[ve,te]=p.useState(null),re=p.useRef(null),X=p.useRef(!1),[ge,de]=p.useState([]),z=p.useRef(!1),C=p.useRef(null),[G,fe]=p.useState(null),ne=p.useRef(null),O=p.useRef(null),ie=p.useRef(0),se=p.useRef(null),q=p.useRef(null),[b,W]=p.useState(null),ce=p.useRef(0),v=p.useRef(0),J=p.useRef(0),Z=p.useRef(0),L=p.useRef(0),le=p.useRef(0),ae=3,be=1e3,P=p.useRef(T),Q=p.useRef(R),H=p.useRef(_),pe=(m,n,a)=>{const e=a.getBoundingClientRect(),t=e.width,r=e.height,i=a.videoWidth,s=a.videoHeight;if(i===0||s===0)return console.warn("[ScrcpyPlayer] Video dimensions not available yet"),null;const o=i/s,l=t/r;let c,d,f,h;l>o?(d=r,c=o*r,f=(t-c)/2,h=0):(c=t,d=t/o,f=0,h=(r-d)/2);const y=m-f,S=n-h;if(y<0||y>c||S<0||S>d)return console.warn("[ScrcpyPlayer] Click outside video area (in letterbox)"),null;const B=Math.round(y/c*i),M=Math.round(S/d*s);return console.log(`[ScrcpyPlayer] Coordinate transform:
5
+ Click: (${m}, ${n})
6
6
  Display: ${t}x${r}
7
7
  Video: ${i}x${s}
8
8
  Rendered: ${c}x${d} at offset (${f}, ${h})
9
- Device: (${N}, ${L})`),{x:N,y:L}},ke=async g=>{if(!k||!x.current||Y!=="connected")return;$.current=!0,F.current={x:g.clientX,y:g.clientY,time:Date.now()};const n=x.current.getBoundingClientRect(),a=g.clientX-n.left,e=g.clientY-n.top,t=pe(a,e,x.current);if(!t||!b)return;const r=x.current.videoWidth,i=x.current.videoHeight,s=b.width/r,o=b.height/i,l=Math.round(t.x*s),c=Math.round(t.y*o);try{await $e(l,c,m),console.log(`[Touch] DOWN: (${l}, ${c}) for device ${m}`)}catch(d){console.error("[Touch] DOWN failed:",d)}},he=g=>{if(!$.current||!F.current)return;fe({id:Date.now(),startX:F.current.x,startY:F.current.y,endX:g.clientX,endY:g.clientY});const n=x.current?.getBoundingClientRect();if(!n||!x.current||!b)return;const a=g.clientX-n.left,e=g.clientY-n.top,t=pe(a,e,x.current);if(!t)return;const r=x.current.videoWidth,i=x.current.videoHeight,s=b.width/r,o=b.height/i,l=Math.round(t.x*s),c=Math.round(t.y*o),d=Date.now();d-ie.current>=Be?(ie.current=d,Te(l,c,m).catch(f=>{console.error("[Touch] MOVE failed:",f)})):(se.current={x:l,y:c},q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{if(se.current){const{x:f,y:h}=se.current;ie.current=Date.now(),Te(f,h,m).catch(p=>{console.error("[Touch] MOVE (throttled) failed:",p)}),se.current=null}},Be-(d-ie.current)))},Ce=async g=>{if(!$.current||!F.current)return;const n=g.clientX-F.current.x,a=g.clientY-F.current.y,e=Date.now()-F.current.time;if(fe(null),$.current=!1,q.current&&(clearTimeout(q.current),q.current=null),se.current=null,Math.sqrt(n*n+a*a)<10&&e<200){je(g),F.current=null;return}const r=x.current?.getBoundingClientRect();if(!r||!x.current||!b){F.current=null;return}const i=g.clientX-r.left,s=g.clientY-r.top,o=pe(i,s,x.current);if(!o){F.current=null;return}const l=x.current.videoWidth,c=x.current.videoHeight,d=b.width/l,f=b.height/c,h=Math.round(o.x*d),p=Math.round(o.y*f);try{await Pe(h,p,m),console.log(`[Touch] UP: (${h}, ${p}) for device ${m}`),X?.()}catch(w){console.error("[Touch] UP failed:",w),G?.(String(w))}F.current=null},De=async g=>{if(!k||!x.current||Y!=="connected")return;const n=Date.now(),a=g.deltaY;O.current||(O.current={deltaY:0,lastTime:n,mouseX:g.clientX,mouseY:g.clientY}),O.current.deltaY+=a,O.current.lastTime=n;const e=.3;O.current.mouseX=Math.round(O.current.mouseX*(1-e)+g.clientX*e),O.current.mouseY=Math.round(O.current.mouseY*(1-e)+g.clientY*e),ne.current&&clearTimeout(ne.current),ne.current=setTimeout(async()=>{if(!O.current||!x.current)return;const t=O.current;if(O.current=null,t.mouseX===void 0||t.mouseY===void 0)return;const r=x.current.getBoundingClientRect(),i=t.mouseX,s=t.mouseY,o=Math.abs(t.deltaY),l=Math.min(Math.max(300,o),800),c=pe(i-r.left,s-r.top,x.current);if(!c||!b){console.warn("[ScrcpyPlayer] Cannot execute scroll: coordinate transformation failed");return}const d=x.current.videoWidth,f=x.current.videoHeight,h=b.width/d,p=b.height/f,w=Math.round(c.x*h),N=Math.round(c.y*p);let L,B;t.deltaY>0?(L=N,B=N-o):(L=N,B=N+o);const I=Math.abs(B-L),A=Math.max(I/b.height*r.height,20),xe=Math.min(Math.max(l*.8,200),800),K=document.createElement("div");K.style.cssText=`
9
+ Device: (${B}, ${M})`),{x:B,y:M}},ke=async m=>{if(!k||!x.current||V!=="connected")return;z.current=!0,C.current={x:m.clientX,y:m.clientY,time:Date.now()};const n=x.current.getBoundingClientRect(),a=m.clientX-n.left,e=m.clientY-n.top,t=pe(a,e,x.current);if(!t||!b)return;const r=x.current.videoWidth,i=x.current.videoHeight,s=b.width/r,o=b.height/i,l=Math.round(t.x*s),c=Math.round(t.y*o);try{await $e(l,c,g),console.log(`[Touch] DOWN: (${l}, ${c}) for device ${g}`)}catch(d){console.error("[Touch] DOWN failed:",d)}},he=m=>{if(!z.current||!C.current)return;fe({id:Date.now(),startX:C.current.x,startY:C.current.y,endX:m.clientX,endY:m.clientY});const n=x.current?.getBoundingClientRect();if(!n||!x.current||!b)return;const a=m.clientX-n.left,e=m.clientY-n.top,t=pe(a,e,x.current);if(!t)return;const r=x.current.videoWidth,i=x.current.videoHeight,s=b.width/r,o=b.height/i,l=Math.round(t.x*s),c=Math.round(t.y*o),d=Date.now();d-ie.current>=Ee?(ie.current=d,Te(l,c,g).catch(f=>{console.error("[Touch] MOVE failed:",f)})):(se.current={x:l,y:c},q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{if(se.current){const{x:f,y:h}=se.current;ie.current=Date.now(),Te(f,h,g).catch(y=>{console.error("[Touch] MOVE (throttled) failed:",y)}),se.current=null}},Ee-(d-ie.current)))},Ce=async m=>{if(!z.current||!C.current)return;const n=m.clientX-C.current.x,a=m.clientY-C.current.y,e=Date.now()-C.current.time;if(fe(null),z.current=!1,q.current&&(clearTimeout(q.current),q.current=null),se.current=null,Math.sqrt(n*n+a*a)<10&&e<200){je(m),C.current=null;return}const r=x.current?.getBoundingClientRect();if(!r||!x.current||!b){C.current=null;return}const i=m.clientX-r.left,s=m.clientY-r.top,o=pe(i,s,x.current);if(!o){C.current=null;return}const l=x.current.videoWidth,c=x.current.videoHeight,d=b.width/l,f=b.height/c,h=Math.round(o.x*d),y=Math.round(o.y*f);try{await Pe(h,y,g),console.log(`[Touch] UP: (${h}, ${y}) for device ${g}`),$?.()}catch(S){console.error("[Touch] UP failed:",S),Y?.(String(S))}C.current=null},De=async m=>{if(!k||!x.current||V!=="connected")return;const n=Date.now(),a=m.deltaY;O.current||(O.current={deltaY:0,lastTime:n,mouseX:m.clientX,mouseY:m.clientY}),O.current.deltaY+=a,O.current.lastTime=n;const e=.3;O.current.mouseX=Math.round(O.current.mouseX*(1-e)+m.clientX*e),O.current.mouseY=Math.round(O.current.mouseY*(1-e)+m.clientY*e),ne.current&&clearTimeout(ne.current),ne.current=setTimeout(async()=>{if(!O.current||!x.current)return;const t=O.current;if(O.current=null,t.mouseX===void 0||t.mouseY===void 0)return;const r=x.current.getBoundingClientRect(),i=t.mouseX,s=t.mouseY,o=Math.abs(t.deltaY),l=Math.min(Math.max(300,o),800),c=pe(i-r.left,s-r.top,x.current);if(!c||!b){console.warn("[ScrcpyPlayer] Cannot execute scroll: coordinate transformation failed");return}const d=x.current.videoWidth,f=x.current.videoHeight,h=b.width/d,y=b.height/f,S=Math.round(c.x*h),B=Math.round(c.y*y);let M,E;t.deltaY>0?(M=B,E=B-o):(M=B,E=B+o);const I=Math.abs(E-M),U=Math.max(I/b.height*r.height,20),xe=Math.min(Math.max(l*.8,200),800),K=document.createElement("div");K.style.cssText=`
10
10
  position: fixed;
11
11
  left: ${i}px;
12
12
  top: ${s}px;
@@ -22,4 +22,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
22
22
  rgba(59, 130, 246, 0) 100%);
23
23
  border-radius: 50%;
24
24
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.6);
25
- `;const ye=Date.now(),ue=setInterval(()=>{const S=Date.now()-ye,me=Math.min(S/xe,1),we=t.deltaY>0?s-A*me:s+A*me;K.style.top=we+"px",me>=1&&clearInterval(ue)},16);document.body.appendChild(K),setTimeout(()=>{K.parentNode&&K.parentNode.removeChild(K),clearInterval(ue)},xe);try{const S=await He(w,L,w,B,l,m);S.success?D?.():U?.(S.error||"Scroll failed")}catch(S){U?.(String(S))}},nt)},je=async g=>{if(!k||!x.current||Y!=="connected"||x.current.videoWidth===0||x.current.videoHeight===0||!b)return;const n=x.current.getBoundingClientRect(),a=g.clientX-n.left,e=g.clientY-n.top,t=pe(a,e,x.current);if(!t)return;const r=x.current.videoWidth,i=x.current.videoHeight,s=b.width/r,o=b.height/i,l=Math.round(t.x*s),c=Math.round(t.y*o),d=Date.now();de(f=>[...f,{id:d,x:g.clientX,y:g.clientY}]),setTimeout(()=>{de(f=>f.filter(h=>h.id!==d))},500);try{const f=await Ye(l,c,m);f.success?X?.():G?.(f.error||"Unknown error")}catch(f){G?.(String(f))}};return y.useEffect(()=>{P.current=T,Q.current=R,H.current=_},[T,R,_]),y.useEffect(()=>{(async()=>{try{const n=await Ee(m);n.success&&(W({width:n.width,height:n.height}),console.log(`[ScrcpyPlayer] Device actual resolution: ${n.width}x${n.height} for device ${m}`))}catch(n){console.error("[ScrcpyPlayer] Failed to fetch device resolution:",n)}})()},[m]),y.useEffect(()=>{E.current=m;let g=null,n=null;const a=async()=>{if(x.current){if(console.log("[ScrcpyPlayer] connect() called"),Z.current=Date.now(),ee("connecting"),te(null),C.current){console.log("[ScrcpyPlayer] Closing existing WebSocket");try{C.current.onclose=null,C.current.onerror=null,C.current.onmessage=null,C.current.close()}catch(e){console.error("[ScrcpyPlayer] Error closing old WebSocket:",e)}C.current=null}if(j.current){console.log("[ScrcpyPlayer] Destroying old jMuxer instance");try{j.current.destroy()}catch(e){console.error("[ScrcpyPlayer] Error destroying old jMuxer:",e)}j.current=null}x.current&&(x.current.src="",x.current.load()),await new Promise(e=>setTimeout(e,300));try{console.log("[ScrcpyPlayer] Creating new jMuxer instance (after cleanup delay)"),j.current=new rt({node:x.current,mode:"video",flushingTime:0,fps:30,debug:!1,clearBuffer:!0,onError:i=>{if(console.error("[jMuxer] Decoder error:",i),i.name==="InvalidStateError"&&i.error==="buffer error"){const s=Date.now(),o=s-le.current;if(o<be){console.warn(`[jMuxer] Reset debounced (${o}ms since last reset)`);return}if(le.current=s,M.current++,console.warn(`[jMuxer] ⚠️ Buffer error detected (attempt ${M.current}/${ae})`),M.current<=ae&&j.current)try{console.log("[jMuxer] Attempting lightweight reset()..."),j.current.reset(),console.log("[jMuxer] ✓ Reset successful");return}catch(c){console.error("[jMuxer] Reset failed:",c)}M.current>ae&&(console.warn(`[jMuxer] Max reset attempts (${ae}) exceeded, doing full reconnect...`),M.current=0),J.current=s;const l=e;n&&setTimeout(()=>{E.current===l?n&&n():console.log(`[jMuxer] Device changed (${l} -> ${E.current}), skip reconnect`)},100)}},onMissingVideoFrames:i=>{console.warn("[jMuxer] Missing video frames detected:",i)}});const e=E.current,t=`ws://localhost:8000/api/video/stream?device_id=${encodeURIComponent(e)}`,r=new WebSocket(t);C.current=r,r.binaryType="arraybuffer",r.onopen=()=>{console.log(`[ScrcpyPlayer] WebSocket connected for device ${e}`),ee("connected"),M.current=0,le.current=0,H.current&&H.current({close:()=>{r.close()}}),re.current=setTimeout(()=>{z.current||(console.log("[ScrcpyPlayer] No data received within timeout, triggering fallback"),ee("error"),te("Video stream timeout"),r.close(),P.current&&P.current())},Q.current)},r.onmessage=i=>{if(typeof i.data=="string"){try{const s=JSON.parse(i.data);console.error("[ScrcpyPlayer] Server error:",s),te(s.error||"Unknown error"),ee("error"),P.current&&!z.current&&P.current()}catch{console.error("[ScrcpyPlayer] Received non-JSON string:",i.data)}return}z.current||(z.current=!0,console.log("[ScrcpyPlayer] First video data received, canceling fallback timer"),re.current&&(clearTimeout(re.current),re.current=null));try{if(j.current&&i.data.byteLength>0){j.current.feed({video:new Uint8Array(i.data)}),ce.current++;const s=Date.now(),o=s-v.current;if(o>5e3){const l=ce.current/o*1e3,c=x.current,d=c&&c.buffered.length>0?c.buffered.end(0)-c.currentTime:0;console.log(`[ScrcpyPlayer] Stats: ${l.toFixed(1)} fps, buffer: ${d.toFixed(2)}s`),d>2&&console.warn(`[ScrcpyPlayer] ⚠ High latency detected: ${d.toFixed(2)}s buffer`),ce.current=0,v.current=s}}}catch(s){console.error("[ScrcpyPlayer] Feed error:",s)}},r.onerror=i=>{console.error("[ScrcpyPlayer] WebSocket error:",i),te("Connection error"),ee("error")},r.onclose=()=>{console.log("[ScrcpyPlayer] WebSocket closed"),ee("disconnected"),H.current&&H.current(null);const i=e;g=setTimeout(()=>{E.current===i?(console.log("[ScrcpyPlayer] Attempting to reconnect..."),a()):console.log(`[ScrcpyPlayer] Device changed (${i} -> ${E.current}), skip reconnect`)},3e3)}}catch(e){console.error("[ScrcpyPlayer] Initialization error:",e),te("Initialization failed"),ee("error")}}};return n=a,a(),()=>{if(g&&clearTimeout(g),re.current&&(clearTimeout(re.current),re.current=null),C.current&&(C.current.close(),C.current=null),q.current&&(clearTimeout(q.current),q.current=null),j.current){try{j.current.destroy()}catch(e){console.error("[ScrcpyPlayer] Cleanup error:",e)}j.current=null}}},[m]),u.jsxs("div",{className:`relative w-full h-full flex items-center justify-center ${oe||""}`,children:[u.jsx("video",{ref:x,autoPlay:!0,muted:!0,playsInline:!0,onMouseDown:ke,onMouseMove:he,onMouseUp:Ce,onMouseLeave:async()=>{if($.current&&x.current&&b){if(F.current){const g=x.current.getBoundingClientRect(),n=pe(F.current.x-g.left,F.current.y-g.top,x.current);if(n){const a=b.width/x.current.videoWidth,e=b.height/x.current.videoHeight,t=Math.round(n.x*a),r=Math.round(n.y*e);try{await Pe(t,r,m),console.log(`[Touch] UP (mouse leave) for device ${m}`)}catch(i){console.error("[Touch] UP (mouse leave) failed:",i)}}}$.current=!1,fe(null),F.current=null}},onWheel:De,className:`max-w-full max-h-full object-contain ${k?"cursor-pointer":""}`,style:{backgroundColor:"#000"}}),k&&V&&u.jsxs("svg",{className:"fixed inset-0 pointer-events-none z-40",children:[u.jsx("line",{x1:V.startX,y1:V.startY,x2:V.endX,y2:V.endY,stroke:"rgba(59, 130, 246, 0.8)",strokeWidth:"3",strokeLinecap:"round"}),u.jsx("circle",{cx:V.startX,cy:V.startY,r:"6",fill:"rgba(59, 130, 246, 0.8)"}),u.jsx("circle",{cx:V.endX,cy:V.endY,r:"6",fill:"rgba(239, 68, 68, 0.8)"})]}),k&&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)),Y!=="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:[Y==="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:"正在连接..."})]}),Y==="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:"连接断开,正在重连..."})]}),Y==="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:"连接失败"}),ve&&u.jsx("p",{className:"text-sm text-gray-400 mt-1",children:ve})]})]})})]})}function st({deviceId:m,deviceName:oe,config:T}){const[R,k]=y.useState([]),[X,G]=y.useState(""),[D,U]=y.useState(!1),[_,x]=y.useState(null),[j,C]=y.useState(!1),[E,Y]=y.useState(null),[ee,ve]=y.useState(!0),[te,re]=y.useState(!1),[z,ge]=y.useState("auto"),[de,$]=y.useState(null),F=y.useRef(null),V=y.useRef(null),fe=y.useRef(null),ne=y.useRef(!1),O=y.useCallback(async()=>{if(!T){console.warn("[DevicePanel] config is required for handleInit");return}try{await ze({model_config:{base_url:T.baseUrl||void 0,api_key:T.apiKey||void 0,model_name:T.modelName||void 0},agent_config:{device_id:m}}),C(!0),x(null)}catch(v){const J=v instanceof Error?v.message:"初始化失败,请检查配置";x(J)}},[m,T]),ie=y.useCallback(async()=>{const v=X.trim();if(!v||D)return;j||await O();const J={id:Date.now().toString(),role:"user",content:v,timestamp:new Date};k(P=>[...P,J]),G(""),U(!0),x(null);const Z=[],M=[],le=(Date.now()+1).toString(),ae={id:le,role:"agent",content:"",timestamp:new Date,thinking:[],actions:[],isStreaming:!0};k(P=>[...P,ae]);const be=Ve(J.content,m,P=>{Z.push(P.thinking),M.push(P.action),k(Q=>Q.map(H=>H.id===le?{...H,thinking:[...Z],actions:[...M],steps:P.step}:H))},P=>{k(Q=>Q.map(H=>H.id===le?{...H,content:P.message,success:P.success,isStreaming:!1}:H)),U(!1),F.current=null},P=>{k(Q=>Q.map(H=>H.id===le?{...H,content:`错误: ${P.message}`,success:!1,isStreaming:!1}:H)),U(!1),x(P.message),F.current=null});F.current=be},[X,D,j,m,O]),se=y.useCallback(async()=>{F.current&&F.current.close(),k([]),U(!1),x(null),F.current=null,await Xe(m)},[m]),q=()=>{fe.current?.scrollIntoView({behavior:"smooth"})};y.useEffect(()=>{q()},[R]),y.useEffect(()=>()=>{console.log(`[DevicePanel] 设备 ${m} 卸载,清理资源`),F.current&&(F.current.close(),F.current=null),V.current&&(V.current.close(),V.current=null)},[m]),y.useEffect(()=>{if(!m||!(z==="screenshot"||z==="auto"&&te))return;const J=async()=>{if(!ne.current){ne.current=!0;try{const M=await Ee(m);M.success&&Y(M)}catch(M){console.error("Failed to fetch screenshot:",M)}finally{ne.current=!1}}};J();const Z=setInterval(J,500);return()=>clearInterval(Z)},[m,te,z]);const b=v=>{v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),ie())},W=y.useCallback(v=>{V.current=v},[]),ce=y.useCallback(()=>{re(!0),ve(!1)},[]);return u.jsxs("div",{className:"flex-1 flex gap-4 p-4 items-center justify-center",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.jsxs("div",{children:[u.jsx("h2",{className:"text-lg font-semibold",children:oe}),u.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:m})]}),u.jsxs("div",{className:"flex gap-2",children:[j?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",children:"已初始化"}):u.jsx("button",{onClick:O,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm",children:"初始化设备"}),u.jsx("button",{onClick:se,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 text-sm",children:"重置"})]})]}),_&&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 text-sm",children:_}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[R.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:"设备已选择"}),u.jsx("p",{className:"text-sm mt-2",children:"输入任务描述,让 AI 帮你操作手机"})]}):null,R.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((J,Z)=>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:["💭 步骤 ",Z+1," - 思考过程"]}),u.jsx("p",{className:"text-sm whitespace-pre-wrap",children:J}),v.actions?.[Z]&&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[Z],null,2)})]})]},Z)),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:fe})]}),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:X,onChange:v=>G(v.target.value),onKeyDown:b,placeholder:j?"输入任务描述...":"请先初始化设备",disabled:D,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:ie,disabled:D||!X.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",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:()=>ge("auto"),className:`px-3 py-1 text-xs rounded transition-colors ${z==="auto"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,children:"自动"}),u.jsx("button",{onClick:()=>ge("video"),className:`px-3 py-1 text-xs rounded transition-colors ${z==="video"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,children:"视频流"}),u.jsx("button",{onClick:()=>ge("screenshot"),className:`px-3 py-1 text-xs rounded transition-colors ${z==="screenshot"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,children:"截图"})]}),z==="video"||z==="auto"&&ee&&!te?u.jsxs(u.Fragment,{children:[de&&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",children:de}),u.jsx(it,{deviceId:m,className:"w-full h-full",enableControl:!0,onFallback:ce,onTapSuccess:()=>{$("Tap executed"),setTimeout(()=>$(null),2e3)},onTapError:v=>{$(`Tap failed: ${v}`),setTimeout(()=>$(null),3e3)},onSwipeSuccess:()=>{$("Swipe executed"),setTimeout(()=>$(null),2e3)},onSwipeError:v=>{$(`Swipe failed: ${v}`),setTimeout(()=>$(null),3e3)},onStreamReady:W,fallbackTimeout:1e5})]}):u.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-900",children:E&&E.success?u.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[u.jsx("img",{src:`data:image/png;base64,${E.image}`,alt:"Device Screenshot",className:"max-w-full max-h-full object-contain",style:{width:E.width>E.height?"100%":"auto",height:E.width>E.height?"auto":"100%"}}),E.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 刷新)",z==="auto"&&te&&" - 视频流不可用"]})]}):E?.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:E.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:"加载中..."})]})})]})]})}function ot(){const[m,oe]=y.useState([]),[T,R]=y.useState(""),[k,X]=y.useState({baseUrl:"",apiKey:"",modelName:""}),[G,D]=y.useState(!1);return y.useEffect(()=>{const U=async()=>{try{const x=await Ge();oe(x.devices),x.devices.length>0&&!T&&R(x.devices[0].id),T&&!x.devices.find(j=>j.id===T)&&R(x.devices[0]?.id||"")}catch(x){console.error("Failed to load devices:",x)}};U();const _=setInterval(U,3e3);return()=>clearInterval(_)},[T]),u.jsxs("div",{className:"h-full flex relative",children:[G&&u.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50",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:k.baseUrl,onChange:U=>X({...k,baseUrl:U.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:k.apiKey,onChange:U=>X({...k,apiKey:U.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:k.modelName,onChange:U=>X({...k,modelName:U.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:()=>D(!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:()=>D(!1),className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"确认配置"})]})]})]})}),u.jsx(Ke,{devices:m,currentDeviceId:T,onSelectDevice:R,onOpenConfig:()=>D(!0)}),u.jsx("div",{className:"flex-1 relative flex items-center justify-center",children:m.length===0?u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gray-50 dark:bg-gray-900",children:u.jsxs("div",{className:"text-center text-gray-500 dark:text-gray-400",children:[u.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),u.jsx("h3",{className:"text-lg font-medium mb-2",children:"欢迎使用 AutoGLM Chat"}),u.jsx("p",{className:"text-sm",children:"未检测到设备,请连接 ADB 设备"})]})}):m.map(U=>u.jsx("div",{className:`w-full h-full flex items-center justify-center ${U.id===T?"":"hidden"}`,children:u.jsx(st,{deviceId:U.id,deviceName:U.model,config:k,isVisible:U.id===T})},U.id))})]})}export{ot as component};
25
+ `;const ye=Date.now(),ue=setInterval(()=>{const F=Date.now()-ye,me=Math.min(F/xe,1),we=t.deltaY>0?s-U*me:s+U*me;K.style.top=we+"px",me>=1&&clearInterval(ue)},16);document.body.appendChild(K),setTimeout(()=>{K.parentNode&&K.parentNode.removeChild(K),clearInterval(ue)},xe);try{const F=await He(S,M,S,E,l,g);F.success?w?.():D?.(F.error||"Scroll failed")}catch(F){D?.(String(F))}},it)},je=async m=>{if(!k||!x.current||V!=="connected"||x.current.videoWidth===0||x.current.videoHeight===0||!b)return;const n=x.current.getBoundingClientRect(),a=m.clientX-n.left,e=m.clientY-n.top,t=pe(a,e,x.current);if(!t)return;const r=x.current.videoWidth,i=x.current.videoHeight,s=b.width/r,o=b.height/i,l=Math.round(t.x*s),c=Math.round(t.y*o),d=Date.now();de(f=>[...f,{id:d,x:m.clientX,y:m.clientY}]),setTimeout(()=>{de(f=>f.filter(h=>h.id!==d))},500);try{const f=await Ye(l,c,g);f.success?$?.():Y?.(f.error||"Unknown error")}catch(f){Y?.(String(f))}};return p.useEffect(()=>{P.current=T,Q.current=R,H.current=_},[T,R,_]),p.useEffect(()=>{(async()=>{try{const n=await Ne(g);n.success&&(W({width:n.width,height:n.height}),console.log(`[ScrcpyPlayer] Device actual resolution: ${n.width}x${n.height} for device ${g}`))}catch(n){console.error("[ScrcpyPlayer] Failed to fetch device resolution:",n)}})()},[g]),p.useEffect(()=>{N.current=g;let m=null,n=null;const a=async()=>{if(x.current){if(console.log("[ScrcpyPlayer] connect() called"),Z.current=Date.now(),ee("connecting"),te(null),j.current){console.log("[ScrcpyPlayer] Closing existing WebSocket");try{j.current.onclose=null,j.current.onerror=null,j.current.onmessage=null,j.current.close()}catch(e){console.error("[ScrcpyPlayer] Error closing old WebSocket:",e)}j.current=null}if(A.current){console.log("[ScrcpyPlayer] Destroying old jMuxer instance");try{A.current.destroy()}catch(e){console.error("[ScrcpyPlayer] Error destroying old jMuxer:",e)}A.current=null}x.current&&(x.current.src="",x.current.load()),await new Promise(e=>setTimeout(e,300));try{console.log("[ScrcpyPlayer] Creating new jMuxer instance (after cleanup delay)"),A.current=new nt({node:x.current,mode:"video",flushingTime:0,fps:30,debug:!1,clearBuffer:!0,onError:i=>{if(console.error("[jMuxer] Decoder error:",i),i.name==="InvalidStateError"&&i.error==="buffer error"){const s=Date.now(),o=s-le.current;if(o<be){console.warn(`[jMuxer] Reset debounced (${o}ms since last reset)`);return}if(le.current=s,L.current++,console.warn(`[jMuxer] ⚠️ Buffer error detected (attempt ${L.current}/${ae})`),L.current<=ae&&A.current)try{console.log("[jMuxer] Attempting lightweight reset()..."),A.current.reset(),console.log("[jMuxer] ✓ Reset successful");return}catch(c){console.error("[jMuxer] Reset failed:",c)}L.current>ae&&(console.warn(`[jMuxer] Max reset attempts (${ae}) exceeded, doing full reconnect...`),L.current=0),J.current=s;const l=e;n&&setTimeout(()=>{N.current===l?n&&n():console.log(`[jMuxer] Device changed (${l} -> ${N.current}), skip reconnect`)},100)}},onMissingVideoFrames:i=>{console.warn("[jMuxer] Missing video frames detected:",i)}});const e=N.current,t=`ws://localhost:8000/api/video/stream?device_id=${encodeURIComponent(e)}`,r=new WebSocket(t);j.current=r,r.binaryType="arraybuffer",r.onopen=()=>{console.log(`[ScrcpyPlayer] WebSocket connected for device ${e}`),ee("connected"),L.current=0,le.current=0,H.current&&H.current({close:()=>{r.close()}}),re.current=setTimeout(()=>{X.current||(console.log("[ScrcpyPlayer] No data received within timeout, triggering fallback"),ee("error"),te("Video stream timeout"),r.close(),P.current&&P.current())},Q.current)},r.onmessage=i=>{if(typeof i.data=="string"){try{const s=JSON.parse(i.data);console.error("[ScrcpyPlayer] Server error:",s),te(s.error||"Unknown error"),ee("error"),P.current&&!X.current&&P.current()}catch{console.error("[ScrcpyPlayer] Received non-JSON string:",i.data)}return}X.current||(X.current=!0,console.log("[ScrcpyPlayer] First video data received, canceling fallback timer"),re.current&&(clearTimeout(re.current),re.current=null));try{if(A.current&&i.data.byteLength>0){A.current.feed({video:new Uint8Array(i.data)}),ce.current++;const s=Date.now(),o=s-v.current;if(o>5e3){const l=ce.current/o*1e3,c=x.current,d=c&&c.buffered.length>0?c.buffered.end(0)-c.currentTime:0;console.log(`[ScrcpyPlayer] Stats: ${l.toFixed(1)} fps, buffer: ${d.toFixed(2)}s`),d>2&&console.warn(`[ScrcpyPlayer] ⚠ High latency detected: ${d.toFixed(2)}s buffer`),ce.current=0,v.current=s}}}catch(s){console.error("[ScrcpyPlayer] Feed error:",s)}},r.onerror=i=>{console.error("[ScrcpyPlayer] WebSocket error:",i),te("Connection error"),ee("error")},r.onclose=()=>{console.log("[ScrcpyPlayer] WebSocket closed"),ee("disconnected"),H.current&&H.current(null);const i=e;m=setTimeout(()=>{N.current===i?(console.log("[ScrcpyPlayer] Attempting to reconnect..."),a()):console.log(`[ScrcpyPlayer] Device changed (${i} -> ${N.current}), skip reconnect`)},3e3)}}catch(e){console.error("[ScrcpyPlayer] Initialization error:",e),te("Initialization failed"),ee("error")}}};return n=a,a(),()=>{if(m&&clearTimeout(m),re.current&&(clearTimeout(re.current),re.current=null),j.current&&(j.current.close(),j.current=null),q.current&&(clearTimeout(q.current),q.current=null),A.current){try{A.current.destroy()}catch(e){console.error("[ScrcpyPlayer] Cleanup error:",e)}A.current=null}}},[g]),u.jsxs("div",{className:`relative w-full h-full flex items-center justify-center ${oe||""}`,children:[u.jsx("video",{ref:x,autoPlay:!0,muted:!0,playsInline:!0,onMouseDown:ke,onMouseMove:he,onMouseUp:Ce,onMouseLeave:async()=>{if(z.current&&x.current&&b){if(C.current){const m=x.current.getBoundingClientRect(),n=pe(C.current.x-m.left,C.current.y-m.top,x.current);if(n){const a=b.width/x.current.videoWidth,e=b.height/x.current.videoHeight,t=Math.round(n.x*a),r=Math.round(n.y*e);try{await Pe(t,r,g),console.log(`[Touch] UP (mouse leave) for device ${g}`)}catch(i){console.error("[Touch] UP (mouse leave) failed:",i)}}}z.current=!1,fe(null),C.current=null}},onWheel:De,className:`max-w-full max-h-full object-contain ${k?"cursor-pointer":""}`,style:{backgroundColor:"#000"}}),k&&G&&u.jsxs("svg",{className:"fixed inset-0 pointer-events-none z-40",children:[u.jsx("line",{x1:G.startX,y1:G.startY,x2:G.endX,y2:G.endY,stroke:"rgba(59, 130, 246, 0.8)",strokeWidth:"3",strokeLinecap:"round"}),u.jsx("circle",{cx:G.startX,cy:G.startY,r:"6",fill:"rgba(59, 130, 246, 0.8)"}),u.jsx("circle",{cx:G.endX,cy:G.endY,r:"6",fill:"rgba(239, 68, 68, 0.8)"})]}),k&&ge.map(m=>u.jsx("div",{className:"fixed pointer-events-none z-50",style:{left:m.x,top:m.y},children:u.jsx("div",{className:"ripple-circle"})},m.id)),V!=="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:[V==="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:"正在连接..."})]}),V==="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:"连接断开,正在重连..."})]}),V==="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:"连接失败"}),ve&&u.jsx("p",{className:"text-sm text-gray-400 mt-1",children:ve})]})]})})]})}function at({deviceId:g,deviceName:oe,config:T}){const[R,k]=p.useState([]),[$,Y]=p.useState(""),[w,D]=p.useState(!1),[_,x]=p.useState(null),[A,j]=p.useState(!1),[N,V]=p.useState(null),[ee,ve]=p.useState(!0),[te,re]=p.useState(!1),[X,ge]=p.useState("auto"),[de,z]=p.useState(null),C=p.useRef(null),G=p.useRef(null),fe=p.useRef(null),ne=p.useRef(!1),O=p.useCallback(async()=>{if(!T){console.warn("[DevicePanel] config is required for handleInit");return}try{await ze({model_config:{base_url:T.baseUrl||void 0,api_key:T.apiKey||void 0,model_name:T.modelName||void 0},agent_config:{device_id:g}}),j(!0),x(null)}catch(v){const J=v instanceof Error?v.message:"初始化失败,请检查配置";x(J)}},[g,T]),ie=p.useCallback(async()=>{const v=$.trim();if(!v||w)return;A||await O();const J={id:Date.now().toString(),role:"user",content:v,timestamp:new Date};k(P=>[...P,J]),Y(""),D(!0),x(null);const Z=[],L=[],le=(Date.now()+1).toString(),ae={id:le,role:"agent",content:"",timestamp:new Date,thinking:[],actions:[],isStreaming:!0};k(P=>[...P,ae]);const be=Ve(J.content,g,P=>{Z.push(P.thinking),L.push(P.action),k(Q=>Q.map(H=>H.id===le?{...H,thinking:[...Z],actions:[...L],steps:P.step}:H))},P=>{k(Q=>Q.map(H=>H.id===le?{...H,content:P.message,success:P.success,isStreaming:!1}:H)),D(!1),C.current=null},P=>{k(Q=>Q.map(H=>H.id===le?{...H,content:`错误: ${P.message}`,success:!1,isStreaming:!1}:H)),D(!1),x(P.message),C.current=null});C.current=be},[$,w,A,g,O]),se=p.useCallback(async()=>{C.current&&C.current.close(),k([]),D(!1),x(null),C.current=null,await Xe(g)},[g]),q=()=>{fe.current?.scrollIntoView({behavior:"smooth"})};p.useEffect(()=>{q()},[R]),p.useEffect(()=>()=>{console.log(`[DevicePanel] 设备 ${g} 卸载,清理资源`),C.current&&(C.current.close(),C.current=null),G.current&&(G.current.close(),G.current=null)},[g]),p.useEffect(()=>{if(!g||!(X==="screenshot"||X==="auto"&&te))return;const J=async()=>{if(!ne.current){ne.current=!0;try{const L=await Ne(g);L.success&&V(L)}catch(L){console.error("Failed to fetch screenshot:",L)}finally{ne.current=!1}}};J();const Z=setInterval(J,500);return()=>clearInterval(Z)},[g,te,X]);const b=v=>{v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),ie())},W=p.useCallback(v=>{G.current=v},[]),ce=p.useCallback(()=>{re(!0),ve(!1)},[]);return u.jsxs("div",{className:"flex-1 flex gap-4 p-4 items-center justify-center",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.jsxs("div",{children:[u.jsx("h2",{className:"text-lg font-semibold",children:oe}),u.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g})]}),u.jsxs("div",{className:"flex gap-2",children:[A?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",children:"已初始化"}):u.jsx("button",{onClick:O,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm",children:"初始化设备"}),u.jsx("button",{onClick:se,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 text-sm",children:"重置"})]})]}),_&&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 text-sm",children:_}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[R.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:"设备已选择"}),u.jsx("p",{className:"text-sm mt-2",children:"输入任务描述,让 AI 帮你操作手机"})]}):null,R.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((J,Z)=>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:["💭 步骤 ",Z+1," - 思考过程"]}),u.jsx("p",{className:"text-sm whitespace-pre-wrap",children:J}),v.actions?.[Z]&&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[Z],null,2)})]})]},Z)),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:fe})]}),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:$,onChange:v=>Y(v.target.value),onKeyDown:b,placeholder:A?"输入任务描述...":"请先初始化设备",disabled:w,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:ie,disabled:w||!$.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",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:()=>ge("auto"),className:`px-3 py-1 text-xs rounded transition-colors ${X==="auto"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,children:"自动"}),u.jsx("button",{onClick:()=>ge("video"),className:`px-3 py-1 text-xs rounded transition-colors ${X==="video"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,children:"视频流"}),u.jsx("button",{onClick:()=>ge("screenshot"),className:`px-3 py-1 text-xs rounded transition-colors ${X==="screenshot"?"bg-blue-500 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"}`,children:"截图"})]}),X==="video"||X==="auto"&&ee&&!te?u.jsxs(u.Fragment,{children:[de&&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",children:de}),u.jsx(st,{deviceId:g,className:"w-full h-full",enableControl:!0,onFallback:ce,onTapSuccess:()=>{z("Tap executed"),setTimeout(()=>z(null),2e3)},onTapError:v=>{z(`Tap failed: ${v}`),setTimeout(()=>z(null),3e3)},onSwipeSuccess:()=>{z("Swipe executed"),setTimeout(()=>z(null),2e3)},onSwipeError:v=>{z(`Swipe failed: ${v}`),setTimeout(()=>z(null),3e3)},onStreamReady:W,fallbackTimeout:1e5})]}):u.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gray-900",children:N&&N.success?u.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[u.jsx("img",{src:`data:image/png;base64,${N.image}`,alt:"Device Screenshot",className:"max-w-full max-h-full object-contain",style:{width:N.width>N.height?"100%":"auto",height:N.width>N.height?"auto":"100%"}}),N.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 刷新)",X==="auto"&&te&&" - 视频流不可用"]})]}):N?.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:N.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:"加载中..."})]})})]})]})}function ct(){const[g,oe]=p.useState([]),[T,R]=p.useState(""),[k,$]=p.useState({baseUrl:"",apiKey:"",modelName:""}),[Y,w]=p.useState(!1);return p.useEffect(()=>{const D=async()=>{try{const x=await Ge();oe(x.devices),x.devices.length>0&&!T&&R(x.devices[0].id),T&&!x.devices.find(A=>A.id===T)&&R(x.devices[0]?.id||"")}catch(x){console.error("Failed to load devices:",x)}};D();const _=setInterval(D,3e3);return()=>clearInterval(_)},[T]),u.jsxs("div",{className:"h-full flex relative",children:[Y&&u.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50",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:k.baseUrl,onChange:D=>$({...k,baseUrl:D.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:k.apiKey,onChange:D=>$({...k,apiKey:D.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:k.modelName,onChange:D=>$({...k,modelName:D.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:()=>w(!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:()=>w(!1),className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"确认配置"})]})]})]})}),u.jsx(qe,{devices:g,currentDeviceId:T,onSelectDevice:R,onOpenConfig:()=>w(!0)}),u.jsx("div",{className:"flex-1 relative flex items-center justify-center",children:g.length===0?u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gray-50 dark:bg-gray-900",children:u.jsxs("div",{className:"text-center text-gray-500 dark:text-gray-400",children:[u.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),u.jsx("h3",{className:"text-lg font-medium mb-2",children:"欢迎使用 AutoGLM Chat"}),u.jsx("p",{className:"text-sm",children:"未检测到设备,请连接 ADB 设备"})]})}):g.map(D=>u.jsx("div",{className:`w-full h-full flex items-center justify-center ${D.id===T?"":"hidden"}`,children:u.jsx(at,{deviceId:D.id,deviceName:D.model,config:k,isVisible:D.id===T})},D.id))})]})}export{ct as component};
@@ -1 +1 @@
1
- import{u as o,r as s,j as t}from"./index-DZmNavz6.js";function n(){const e=o();return s.useEffect(()=>{e({to:"/chat"})},[e]),t.jsx("div",{className:"p-2",children:t.jsx("h3",{children:"Welcome Home!"})})}export{n as component};
1
+ import{u as o,r as s,j as t}from"./index-CVkp0My_.js";function n(){const e=o();return s.useEffect(()=>{e({to:"/chat"})},[e]),t.jsx("div",{className:"p-2",children:t.jsx("h3",{children:"Welcome Home!"})})}export{n as component};