diff --git a/README.md b/README.md index 17f8950..704776d 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,41 @@ # OPLabs Mixer App -A standalone mixer application that connects to PiPedal (at `192.168.0.245:8080`) via WebSocket to discover and display OPLabsBandChannel and OPLabsBandBus LV2 plugin instances loaded on the pedalboard. +A standalone digital mixer application with a C++ real-time audio engine, +Python/FastAPI backend, and React frontend. ## Architecture ``` -Browser (React SPA) ←→ FastAPI Backend (localhost:8081) ←→ PiPedal (192.168.0.245:8080) - │ │ - └── WS /ws/pipedal └── WS /pipedal (upstream) - └── REST /api/discover └── REST proxied via WS + REST / WS +Browser (React SPA) ───────── FastAPI Backend (:8081) + │ │ + │ WS /ws/pipedal │ WS /pipedal (upstream, legacy) + └── PiPedal (192.168.0.245) └── Legacy PiPedal scenes + + │ │ + │ WS /ws/mixer │ Unix Socket IPC + └── Mixer Daemon Relay ──────┴── /tmp/oplabs-mixer.sock + │ + C++ Mixer Daemon + (MixerEngine + JACK) ``` -- **Backend:** FastAPI on port 8081 — serves the SPA, proxies WebSocket connections to PiPedal, and provides a REST API for plugin discovery. -- **Frontend:** Vite + React + TypeScript — connects to the local WS proxy and shows discovered OPLabs plugin instances with their parameter values. +Two parallel backends: + +1. **Mixer Daemon (primary):** C++ daemon running the real-time mixer engine + (MixerEngine, MixerChannelStrip, MixerBus). Communicates with FastAPI + via Unix domain socket IPC. +2. **PiPedal (legacy):** WebSocket proxy to PiPedal pedalboard for backward + compatibility with existing OPLabsBandChannel/Bus LV2 plugins. ## Prerequisites - Python 3.10+ - Node.js 18+ -- PiPedal running at `192.168.0.245:8080` with OPLabs plugin instances loaded on the pedalboard +- C++20 compiler (gcc 11+ or clang 14+) +- CMake 3.16+ +- JACK Audio Connection Kit (libjack-jackd2-dev) +- PiPedal at `192.168.0.245:8080` (optional, for legacy mode) ## Setup @@ -36,92 +53,249 @@ pip install -r requirements.txt ```bash cd frontend npm install +npm run build ``` +### Mixer Daemon (C++) + +```bash +cd daemon +mkdir build && cd build +cmake .. +make +``` + +The daemon requires the MixerEngine sources from the `op-pedal` mixer-engine branch. +Either: +- Build inside the op-pedal CMake tree, or +- Set `-DMIXER_ENGINE_SOURCE_DIR=/path/to/op-pedal/src/` + ## Running -### Development Mode - -Start both backend and frontend: +### 1. Start JACK (if using the daemon with audio I/O) + +```bash +jackd -d alsa -r 48000 -p 512 -n 2 & +``` + +### 2. Start the Mixer Daemon + +```bash +./daemon/build/oplabs-mixer-daemon \ + --socket-path /tmp/oplabs-mixer.sock \ + --sample-rate 48000 \ + --buffer-size 512 +``` + +### 3. Start the Backend ```bash -# Terminal 1: Backend cd backend source venv/bin/activate -python app.py # runs on port 8081 - -# Terminal 2: Frontend (with hot-reload) -cd frontend -npm run dev # runs on port 5173, proxies API/WS to 8081 +python app.py # runs on port 8081 ``` -Then open http://localhost:5173 in your browser. - -### Production Mode - -Build the frontend and serve from the backend: - -```bash -cd frontend -npm run build - -# Then start the backend (it will serve the built SPA): -cd ../backend -source venv/bin/activate -python app.py - -# Open http://localhost:8081 -``` +Open http://localhost:8081 in your browser. Or use the convenience script: - ```bash ./start.sh ``` -## WebSocket Protocol +## IPC Protocol (C++ Mixer Daemon <-> Python FastAPI) -The app uses PiPedal's native WebSocket protocol: +### Transport -- Messages are JSON arrays: `[{"message": "msgName", "replyTo": N}, optionalBody]` -- Replies: `[{"reply": N, "message": "msgName"}, optionalBody]` -- The browser connects to `ws://localhost:8081/ws/pipedal`, which proxies to PiPedal's `ws://192.168.0.245:8080/pipedal` +- **Type:** Unix domain socket (`AF_UNIX`, `SOCK_STREAM`) +- **Path:** `/tmp/oplabs-mixer.sock` +- **Permissions:** 0666 (read/write for owner and group) + +### Framing + +Every message is prefixed with a 4-byte big-endian unsigned integer +(uint32_t) specifying the length of the JSON payload in bytes. + +``` +[4-byte length BE] [UTF-8 JSON payload] +``` + +### Request Format + +```json +{ + "id": 1, + "method": "getState", + "params": {} +} +``` + +### Response Format + +```json +{ + "id": 1, + "result": { ... }, + "error": null +} +``` + +On error, `result` is null and `error` contains a string description. + +### Push Messages (Daemon -> Client) + +Unsolicited messages from the daemon are tagged with `"type": "push"`: + +```json +{ + "type": "push", + "event": "vuMeter", + "data": { + "channels": [{"index": 0, "left": -12.5, "right": -10.2}, ...], + "buses": [{"id": 1, "left": -6.0, "right": -5.8}] + } +} +``` + +### Message Reference + +| Method | Params | Result | +|---------------------|------------------------------------------------------|------------------------------------------------------| +| `getState` | `{}` | Full mixer state object (channels, buses, routes, output routes) | +| `setChannelVolume` | `{"channelIndex": int, "volumeDb": float}` | `{}` | +| `setChannelPan` | `{"channelIndex": int, "pan": float}` | `{}` | +| `setChannelMute` | `{"channelIndex": int, "mute": bool}` | `{}` | +| `setChannelSolo` | `{"channelIndex": int, "solo": bool}` | `{}` | +| `addChannel` | `{"physicalInputIndex": int}` | `{"channelIndex": int}` | +| `removeChannel` | `{"channelIndex": int}` | `{}` | +| `getOutputRoutes` | `{}` | `{"routes": [sourceBusId, sourceStartChannel, targetStartChannel, channels]}` | +| `setOutputRoutes` | `{"routes": [sourceBusId, sourceStartChannel, targetStartChannel, channels]}` | `{}` | +| `saveScene` | `{"name": string}` | `{"id": int, "name": string}` | +| `loadScene` | `{"sceneId": string}` | `{"ok": bool}` | +| `listScenes` | `{}` | `{"scenes": [{"id": int, "name": string}, ...]}` | +| `deleteScene` | `{"sceneId": string}` | `{"ok": bool}` | + +### getState Result Schema + +```json +{ + "channels": [ + { + "channelIndex": 0, + "volume": -6.0, + "pan": 0.0, + "mute": false, + "solo": false, + "type": "Instrument", + "label": "Channel 1", + "hpEnabled": false, + "hpFrequency": 80.0, + "vuLeft": -12.5, + "vuRight": -10.2 + } + ], + "buses": [ + { + "id": 1, + "name": "Master", + "type": "Master", + "volume": 0.0, + "mute": false + } + ], + "routes": [ + { + "sourceId": 1001, + "targetBusId": 1, + "level": 0.0, + "sourceType": "channel" + } + ], + "outputRoutes": [ + { + "sourceBusId": 1, + "sourceStartChannel": 0, + "targetStartChannel": 0, + "channels": 2 + } + ] +} +``` ## REST API -| Endpoint | Method | Description | -|----------|--------|-------------| -| `/api/ping` | GET | Health check + connection status | -| `/api/discover` | GET | Discover OPLabs plugin instances from current pedalboard | -| `/api/plugins` | GET | List all available plugins from PiPedal | +### Mixer Daemon Endpoints (new) -## OPLabs Plugin URIs +| Endpoint | Method | Description | +|-------------------------------------------------------|--------|--------------------------------------| +| `/api/mixer/state` | GET | Get full mixer state | +| `/api/mixer/channel/{index}/volume` | POST | Set channel volume | +| `/api/mixer/channel/{index}/pan` | POST | Set channel pan | +| `/api/mixer/channel/{index}/mute` | POST | Set channel mute | +| `/api/mixer/channel/{index}/solo` | POST | Set channel solo | +| `/api/mixer/channel/add` | POST | Add a new channel | +| `/api/mixer/channel/{index}` | DELETE | Remove a channel | +| `/api/mixer/output-routes` | GET | Get output routing table | +| `/api/mixer/output-routes` | POST | Set output routing table | +| `/api/mixer/scenes` | GET | List all scenes | +| `/api/mixer/scenes` | POST | Save current state as scene | +| `/api/mixer/scenes/{id}/load` | POST | Load (recall) a scene | +| `/api/mixer/scenes/{id}` | DELETE | Delete a scene | -- OPLabsBandChannel: `http://ourpad.casa/plugins/oplabs-band-channel` -- OPLabsBandBus: `http://ourpad.casa/plugins/oplabs-band-bus#` +### PiPedal Endpoints (legacy) + +| Endpoint | Method | Description | +|-------------------|--------|------------------------------------------------| +| `/api/ping` | GET | Health check + connection status | +| `/api/discover` | GET | Discover OPLabs plugin instances from PiPedal | +| `/api/plugins` | GET | List all available plugins from PiPedal | +| `/api/scenes` | GET | List saved scenes (legacy file-based) | +| `/api/scenes` | POST | Create new scene | +| `/api/scenes/{id}`| PUT | Update scene | +| `/api/scenes/{id}`| DELETE | Delete scene | +| `/api/scenes/{id}/recall` | POST | Recall scene via PiPedal | + +## WebSocket Endpoints + +| Endpoint | Description | +|-----------------|-----------------------------------------------------| +| `/ws/pipedal` | Proxy WebSocket: browser <-> FastAPI <-> PiPedal | +| `/ws/mixer` | Direct mixer daemon control (JSON method calls) | + +### `/ws/mixer` Protocol + +The mixer WebSocket accepts JSON messages in the same format as the IPC protocol: + +```json +// Request +{"method": "getState", "id": 1} +{"method": "setChannelVolume", "params": {"channelIndex": 0, "volumeDb": -6.0}, "id": 2} + +// Response +{"id": 1, "result": {...}, "error": null} +{"id": 2, "result": {}, "error": null} +``` ## Project Structure ``` ~/projects/oplabs-mixer-app/ ├── backend/ -│ ├── app.py # FastAPI app (routes, SPA serving, WS proxy) -│ ├── ws_proxy.py # PiPedal WebSocket proxy client +│ ├── app.py # FastAPI app (mixer + legacy PiPedal routes) +│ ├── mixer_ipc.py # Unix socket IPC client for Mixer Daemon +│ ├── ws_proxy.py # PiPedal WebSocket proxy │ └── requirements.txt +├── daemon/ +│ ├── CMakeLists.txt # Build configuration +│ ├── MixerIpcServer.hpp # C++ Unix socket IPC server +│ ├── MixerIpcServer.cpp # IPC server implementation +│ ├── MixerDaemon.cpp # Main entry point +│ └── oplabs-mixer-daemon.service.in # Systemd service template ├── frontend/ │ ├── package.json │ ├── vite.config.ts │ ├── tsconfig.json │ ├── index.html │ └── src/ -│ ├── main.tsx -│ ├── App.tsx -│ ├── App.css -│ ├── hooks/ -│ │ └── usePiPedalWS.ts -│ └── components/ -│ ├── ConnectionStatus.tsx -│ └── PluginList.tsx ├── README.md └── start.sh ``` diff --git a/backend/app.py b/backend/app.py index 42269ff..1eee337 100644 --- a/backend/app.py +++ b/backend/app.py @@ -1,8 +1,12 @@ """ -OPLabs Mixer App — FastAPI Backend +OPLabs Mixer App - FastAPI Backend -Serves the React SPA and proxies WebSocket connections to PiPedal. -Provides REST API for plugin discovery and scene management. +Serves the React SPA and provides REST/WebSocket access to the +C++ Mixer Daemon via Unix domain socket IPC. + +Architecture: Browser <-> FastAPI (:8081) <-> Unix Socket <-> MixerDaemon + +Also retains backward compatibility with PiPedal via WebSocket proxy. """ import asyncio @@ -21,6 +25,7 @@ from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel +from mixer_ipc import MixerIpcClient, MixerIpcError from ws_proxy import PiPedalWSProxy logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s") @@ -34,6 +39,8 @@ PIPEDAL_HOST = "192.168.0.245" PIPEDAL_PORT = 8080 PIPEDAL_WS_PATH = "/pipedal" +MIXER_SOCKET_PATH = "/tmp/oplabs-mixer.sock" + # OPLabs plugin URIs we care about OPLABS_PLUGIN_URIS = { "http://ourpad.casa/plugins/oplabs-band-channel", @@ -45,7 +52,7 @@ FRONTEND_DIR = Path(__file__).resolve().parent.parent / "frontend" / "dist" SCENES_FILE = Path(__file__).resolve().parent / "scenes.json" # --------------------------------------------------------------------------- -# Global proxy state +# Global state # --------------------------------------------------------------------------- pipedal_proxy: Optional[PiPedalWSProxy] = None @@ -56,6 +63,10 @@ pipedal_state: dict = { "oplabs_instances": [], # discovered OPLabs plugin instances } +# Mixer daemon IPC client (set in lifespan) +mixer_client: Optional[MixerIpcClient] = None +mixer_daemon_connected: bool = False + # --------------------------------------------------------------------------- # Scene storage helpers # --------------------------------------------------------------------------- @@ -81,8 +92,7 @@ def _save_scenes(scenes: list[dict]): # --------------------------------------------------------------------------- async def pipedal_request(message_name: str, body=None, timeout: float = 10.0): - """Connect to PiPedal WS, send a request, wait for reply, then disconnect. - Handles interleaved push messages by discarding non-matching messages.""" + """Connect to PiPedal WS, send a request, wait for reply, then disconnect.""" url = f"ws://{PIPEDAL_HOST}:{PIPEDAL_PORT}{PIPEDAL_WS_PATH}" reply_to = hash(message_name + str(time.time())) & 0x7FFFFFFF @@ -92,6 +102,8 @@ async def pipedal_request(message_name: str, body=None, timeout: float = 10.0): try: async with websockets.connect(url, ping_interval=30, ping_timeout=10, close_timeout=5) as ws: + ws.settimeout(timeout) + # Send hello first to register as subscriber hello_reply_to = 0x10000001 hello_msg = json.dumps([{"message": "hello", "replyTo": hello_reply_to}]) @@ -151,8 +163,7 @@ def is_oplabs_plugin(uri: str) -> bool: def discover_oplabs_from_pedalboard(pedalboard: dict) -> list[dict]: - """Extract OPLabs plugin instances from a pedalboard state dict. - Handles split items (which contain nested sub-items).""" + """Extract OPLabs plugin instances from a pedalboard state dict.""" instances = [] if not pedalboard: return instances @@ -200,6 +211,28 @@ def fetch_pedalboard_state(): return False +# --------------------------------------------------------------------------- +# Mixer Daemon IPC helpers +# --------------------------------------------------------------------------- + +async def with_mixer_client(method_name: str, *args, **kwargs): + """Call a method on the MixerIpcClient, handling connection errors.""" + global mixer_client, mixer_daemon_connected + if not mixer_client or not mixer_client.is_connected: + mixer_daemon_connected = False + raise MixerIpcError("Mixer daemon not connected") + + try: + result = await getattr(mixer_client, method_name)(*args, **kwargs) + mixer_daemon_connected = True + return result + except MixerIpcError: + raise + except Exception as e: + mixer_daemon_connected = False + raise MixerIpcError(f"Mixer daemon communication error: {e}") + + # --------------------------------------------------------------------------- # FastAPI app # --------------------------------------------------------------------------- @@ -207,10 +240,26 @@ def fetch_pedalboard_state(): @asynccontextmanager async def lifespan(app: FastAPI): """Startup / shutdown.""" - global pipedal_proxy + global pipedal_proxy, mixer_client + + # Start PiPedal proxy pipedal_proxy = PiPedalWSProxy(host=PIPEDAL_HOST, port=PIPEDAL_PORT, path=PIPEDAL_WS_PATH) - logger.info("Mixer app starting — PiPedal at %s:%d", PIPEDAL_HOST, PIPEDAL_PORT) + logger.info("Mixer app starting - PiPedal at %s:%d", PIPEDAL_HOST, PIPEDAL_PORT) + + # Try connecting to Mixer Daemon + mixer_client = MixerIpcClient(socket_path=MIXER_SOCKET_PATH) + connected = await mixer_client.connect() + if connected: + logger.info("Connected to Mixer Daemon at %s", MIXER_SOCKET_PATH) + else: + logger.warning("Mixer Daemon not available at %s - mixer endpoints disabled", + MIXER_SOCKET_PATH) + yield + + # Shutdown + if mixer_client: + await mixer_client.close() if pipedal_proxy: await pipedal_proxy.close_upstream() logger.info("Mixer app shutting down") @@ -218,13 +267,158 @@ async def lifespan(app: FastAPI): app = FastAPI( title="OPLabs Mixer App", - version="0.1.0", + version="0.2.0", lifespan=lifespan, ) +# --------------------------------------------------------------------------- +# Mixer Daemon REST endpoints (new) +# --------------------------------------------------------------------------- + + +@app.get("/api/mixer/state") +async def mixer_get_state(): + """Get full mixer state from the mixer daemon.""" + try: + state = await with_mixer_client("get_state") + return state + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/channel/{channel_index}/volume") +async def mixer_set_channel_volume(channel_index: int, body: dict): + """Set channel volume in dB.""" + volume_db = body.get("volumeDb", body.get("volume", -96.0)) + try: + await with_mixer_client("set_channel_volume", channel_index, volume_db) + return {"status": "ok"} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/channel/{channel_index}/pan") +async def mixer_set_channel_pan(channel_index: int, body: dict): + """Set channel pan (-1.0 to +1.0).""" + pan = body.get("pan", 0.0) + try: + await with_mixer_client("set_channel_pan", channel_index, pan) + return {"status": "ok"} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/channel/{channel_index}/mute") +async def mixer_set_channel_mute(channel_index: int, body: dict): + """Set channel mute state.""" + mute = body.get("mute", True) + try: + await with_mixer_client("set_channel_mute", channel_index, mute) + return {"status": "ok"} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/channel/{channel_index}/solo") +async def mixer_set_channel_solo(channel_index: int, body: dict): + """Set channel solo state.""" + solo = body.get("solo", True) + try: + await with_mixer_client("set_channel_solo", channel_index, solo) + return {"status": "ok"} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/channel/add") +async def mixer_add_channel(body: dict): + """Add a new channel. Returns {channelIndex: N}.""" + physical_input = body.get("physicalInputIndex", 0) + try: + idx = await with_mixer_client("add_channel", physical_input) + return {"channelIndex": idx} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.delete("/api/mixer/channel/{channel_index}") +async def mixer_remove_channel(channel_index: int): + """Remove a channel by index.""" + try: + await with_mixer_client("remove_channel", channel_index) + return {"status": "ok"} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.get("/api/mixer/output-routes") +async def mixer_get_output_routes(): + """Get output routing table.""" + try: + routes = await with_mixer_client("get_output_routes") + return {"routes": routes} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/output-routes") +async def mixer_set_output_routes(body: dict): + """Set output routing table.""" + routes = body.get("routes", []) + try: + await with_mixer_client("set_output_routes", routes) + return {"status": "ok"} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/scenes") +async def mixer_save_scene(body: dict): + """Save current mixer state as a scene.""" + name = body.get("name", "Unnamed Scene") + try: + result = await with_mixer_client("save_scene", name) + return {"scene": result} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.post("/api/mixer/scenes/{scene_id}/load") +async def mixer_load_scene(scene_id: str): + """Load (recall) a scene by ID.""" + try: + ok = await with_mixer_client("load_scene", scene_id) + if ok: + return {"status": "ok"} + return JSONResponse({"error": "Scene not found"}, status_code=404) + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.get("/api/mixer/scenes") +async def mixer_list_scenes(): + """List available scenes.""" + try: + scenes = await with_mixer_client("list_scenes") + return {"scenes": scenes} + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + + +@app.delete("/api/mixer/scenes/{scene_id}") +async def mixer_delete_scene(scene_id: str): + """Delete a scene by ID.""" + try: + ok = await with_mixer_client("delete_scene", scene_id) + if ok: + return {"status": "deleted"} + return JSONResponse({"error": "Scene not found"}, status_code=404) + except MixerIpcError as e: + return JSONResponse({"error": str(e)}, status_code=503) + # --------------------------------------------------------------------------- -# Scene REST endpoints +# Scene REST endpoints (legacy - file-based, via PiPedal) # --------------------------------------------------------------------------- class SceneStateChannel(BaseModel): @@ -248,14 +442,14 @@ class SceneUpdate(BaseModel): @app.get("/api/scenes") async def list_scenes(): - """List all saved scenes.""" + """List all saved scenes (legacy file-based).""" scenes = _load_scenes() return {"scenes": scenes} @app.post("/api/scenes") async def create_scene(scene: SceneCreate): - """Save a new scene.""" + """Save a new scene (legacy file-based).""" scenes = _load_scenes() new_scene = { "id": str(uuid.uuid4()), @@ -298,9 +492,7 @@ async def delete_scene(scene_id: str): @app.post("/api/scenes/{scene_id}/recall") async def recall_scene(scene_id: str): - """Recall a scene by sending setControlValue messages to PiPedal for each - channel and bus parameter. Connects fresh to PiPedal and sends sequenced - messages.""" + """Recall a scene via PiPedal.""" scenes = _load_scenes() scene = None for sc in scenes: @@ -314,7 +506,6 @@ async def recall_scene(scene_id: str): channels = state.get("channels", []) buses = state.get("buses", []) - # Build all setControlValue messages messages: list[dict] = [] for ch in channels: instance_id = ch["instanceId"] @@ -334,14 +525,11 @@ async def recall_scene(scene_id: str): if not messages: return {"status": "recalled", "message_count": 0} - # Connect to PiPedal and send sequenced messages url = f"ws://{PIPEDAL_HOST}:{PIPEDAL_PORT}{PIPEDAL_WS_PATH}" try: async with websockets.connect(url, ping_interval=30, ping_timeout=10, close_timeout=5) as ws: - # Send hello hello_reply_to = 0x10000001 await ws.send(json.dumps([{"message": "hello", "replyTo": hello_reply_to}])) - # Wait for hello reply (discard push messages) deadline = time.time() + 10.0 got_hello = False while time.time() < deadline: @@ -357,7 +545,6 @@ async def recall_scene(scene_id: str): logger.warning("Recall: hello reply not received") return JSONResponse({"error": "PiPedal not responding"}, status_code=502) - # Send each message with a small delay to let PiPedal process in order sent = 0 for msg in messages: reply_to = (hash(str(msg)) & 0x7FFFFFFF) @@ -367,11 +554,10 @@ async def recall_scene(scene_id: str): ]) await ws.send(wire_msg) sent += 1 - # Small delay between messages to ensure ordering if sent % 5 == 0: await asyncio.sleep(0.01) - logger.info("Recalled scene '%s' — sent %d control messages", scene["name"], sent) + logger.info("Recalled scene '%s' - sent %d control messages", scene["name"], sent) return {"status": "recalled", "message_count": sent} except Exception as e: logger.warning("Recall failed: %s", e) @@ -379,13 +565,13 @@ async def recall_scene(scene_id: str): # --------------------------------------------------------------------------- -# Existing REST endpoints +# PiPedal REST endpoints (legacy) # --------------------------------------------------------------------------- @app.get("/api/discover") async def discover_plugins(): - """Discover OPLabs plugin instances from PiPedal's current pedalboard.""" + """Discover OPLabs plugin instances from PiPedal.""" ok = fetch_pedalboard_state() return { "connected": pipedal_state["connected"], @@ -403,37 +589,39 @@ async def list_pipedal_plugins(): @app.get("/api/ping") async def ping(): - """Health check + connection status.""" + """Health check.""" return { "status": "ok", "pipedal_host": PIPEDAL_HOST, "pipedal_port": PIPEDAL_PORT, - "connected": pipedal_state["connected"], + "pipedal_connected": pipedal_state["connected"], + "mixer_daemon_connected": mixer_daemon_connected if mixer_client else False, } # --------------------------------------------------------------------------- -# WebSocket proxy endpoint +# WebSocket endpoints # --------------------------------------------------------------------------- @app.websocket("/ws/pipedal") async def websocket_proxy(ws: WebSocket): - """Proxy WebSocket: browser ↔ local FastAPI ↔ PiPedal.""" + """Proxy WebSocket: browser <-> local FastAPI <-> PiPedal.""" await ws.accept() - logger.info("Browser WS connected") + logger.info("Browser WS connected (PiPedal proxy)") proxy = PiPedalWSProxy(host=PIPEDAL_HOST, port=PIPEDAL_PORT, path=PIPEDAL_WS_PATH) connected = await proxy.connect_upstream() if not connected: - await ws.send_json({"type": "error", "message": f"Cannot connect to PiPedal at {proxy.upstream_url}"}) + await ws.send_json({ + "type": "error", + "message": f"Cannot connect to PiPedal at {proxy.upstream_url}" + }) await ws.close() return pipedal_state["connected"] = True - - # Notify browser that upstream is connected await ws.send_json({"type": "connected", "pipedal": proxy.upstream_url}) try: @@ -447,6 +635,83 @@ async def websocket_proxy(ws: WebSocket): await proxy.close_upstream() +@app.websocket("/ws/mixer") +async def mixer_websocket(ws: WebSocket): + """WebSocket for direct communication with the Mixer Daemon. + + Messages are JSON objects: + {"method": "getState", "id": 1} + {"method": "setChannelVolume", "params": {"channelIndex": 0, "volumeDb": -6.0}, "id": 2} + + Responses mirror the IPC protocol: + {"id": 1, "result": {...}, "error": null} + """ + await ws.accept() + logger.info("Browser WS connected (Mixer Daemon)") + + if not mixer_client or not mixer_client.is_connected: + await ws.send_json({ + "type": "error", + "message": "Mixer daemon not available" + }) + await ws.close() + return + + await ws.send_json({"type": "connected", "daemon": MIXER_SOCKET_PATH}) + + try: + while True: + raw = await ws.receive_text() + try: + msg = json.loads(raw) + except json.JSONDecodeError: + await ws.send_json({"id": -1, "error": "Invalid JSON"}) + continue + + method = msg.get("method", "") + params = msg.get("params", {}) + req_id = msg.get("id", -1) + + # Map WebSocket methods to MixerIpcClient methods + method_map = { + "getState": ("get_state", None), + "setChannelVolume": ("set_channel_volume", ["channelIndex", "volumeDb"]), + "setChannelPan": ("set_channel_pan", ["channelIndex", "pan"]), + "setChannelMute": ("set_channel_mute", ["channelIndex", "mute"]), + "setChannelSolo": ("set_channel_solo", ["channelIndex", "solo"]), + "addChannel": ("add_channel", ["physicalInputIndex"]), + "removeChannel": ("remove_channel", ["channelIndex"]), + "getOutputRoutes": ("get_output_routes", None), + "setOutputRoutes": ("set_output_routes", ["routes"]), + "saveScene": ("save_scene", ["name"]), + "loadScene": ("load_scene", ["sceneId"]), + "listScenes": ("list_scenes", None), + "deleteScene": ("delete_scene", ["sceneId"]), + } + + if method not in method_map: + await ws.send_json({"id": req_id, "error": f"Unknown method: {method}"}) + continue + + client_method, param_keys = method_map[method] + + try: + if param_keys is None: + result = await getattr(mixer_client, client_method)() + else: + args = [params.get(k) for k in param_keys] + result = await getattr(mixer_client, client_method)(*args) + + await ws.send_json({"id": req_id, "result": result, "error": None}) + except MixerIpcError as e: + await ws.send_json({"id": req_id, "error": str(e)}) + + except WebSocketDisconnect: + logger.info("Mixer WS disconnected") + except Exception as e: + logger.warning("Mixer WS error: %s", e) + + # --------------------------------------------------------------------------- # Serve SPA (must be last, after all API routes) # --------------------------------------------------------------------------- @@ -458,9 +723,8 @@ if FRONTEND_DIR.exists(): @app.get("/{full_path:path}") async def serve_spa(full_path: str): - """Serve the SPA — return index.html for all non-API routes.""" + """Serve the SPA - return index.html for all non-API routes.""" if full_path.startswith("api/") or full_path.startswith("ws/"): - from fastapi.responses import JSONResponse return JSONResponse({"error": "not found"}, status_code=404) if not SPA_INDEX.exists(): return JSONResponse( diff --git a/backend/jack_endpoints.py b/backend/jack_endpoints.py new file mode 100644 index 0000000..a799541 --- /dev/null +++ b/backend/jack_endpoints.py @@ -0,0 +1,420 @@ +""" +JACK port management endpoints. + +Provides REST API for querying and managing JACK audio port connections +via the PiPedal WebSocket API. PiPedal runs on a separate machine (the Pi) +and manages JACK internally, so all JACK operations go through PiPedal's WS. + +PiPedal JACK message name notes: + The message names below are based on common PiPedal / mod-host conventions. + Adjust MSG_* constants if PiPedal uses different names in your version. +""" + +import asyncio +import json +import logging +from typing import Optional + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel + +logger = logging.getLogger("jack-endpoints") + +# --------------------------------------------------------------------------- +# PiPedal JACK message names — adjust these if PiPedal uses different names +# --------------------------------------------------------------------------- + +# Message to list all JACK ports (returns port list with types/directions) +MSG_LIST_PORTS = "getAudioPorts" +# Message to list current JACK connections (returns port→connected mapping) +MSG_LIST_CONNECTIONS = "getAudioConnections" +# Message to connect two JACK ports: body = {"source": "...", "destination": "..."} +MSG_CONNECT = "connectPorts" +# Message to disconnect two JACK ports: body = {"source": "...", "destination": "..."} +MSG_DISCONNECT = "disconnectPorts" +# Alternative message names to try if the primary ones don't work +ALT_MSG_LIST_PORTS = ["getPorts", "jack_get_ports", "listAudioPorts"] +ALT_MSG_LIST_CONNECTIONS = ["getConnections", "jack_get_connections", "listAudioConnections"] +ALT_MSG_CONNECT = ["jack_connect", "connectAudioPorts"] +ALT_MSG_DISCONNECT = ["jack_disconnect", "disconnectAudioPorts"] + +# --------------------------------------------------------------------------- +# Data models +# --------------------------------------------------------------------------- + + +class JackPortModel(BaseModel): + """A single JACK port.""" + name: str # full JACK port name, e.g. "system:capture_1" + client: str # client name, e.g. "system" + port: str # port short name, e.g. "capture_1" + port_type: str # "audio" | "midi" + direction: str # "output" = audio source (produces audio), "input" = destination (receives audio) + is_physical: bool = False + connections: list[str] = [] # names of connected ports + + +class JackConnectRequest(BaseModel): + source: str # source port name (output) + destination: str # destination port name (input) + + +# --------------------------------------------------------------------------- +# Helper: try calling PiPedal with a message name, falling back to alternatives +# --------------------------------------------------------------------------- + +# Import pipedal_request lazily — it's defined in app.py which imports us +_pipedal_request = None + + +async def _get_pipedal_request(): + """Get the pipedal_request function, importing from app on first call.""" + global _pipedal_request + if _pipedal_request is None: + from app import pipedal_request + _pipedal_request = pipedal_request + return _pipedal_request + + +async def _call_pipedal(message: str, body=None, alt_messages: list[str] | None = None) -> Optional[dict]: + """ + Call PiPedal with *message*, falling back to *alt_messages* if None is returned. + + Returns the response body dict, or None if all variants failed. + """ + req = await _get_pipedal_request() + result = await req(message, body) + + if result is not None: + return result + + # Try alternates + if alt_messages: + for alt in alt_messages: + result = await req(alt, body) + if result is not None: + logger.info("Fell back to alternative message: %s (primary was %s)", alt, message) + return result + + return None + + +# --------------------------------------------------------------------------- +# Port / connection parsing (handles various PiPedal response shapes) +# --------------------------------------------------------------------------- + + +def _parse_ports_from_pedalboard() -> list[dict]: + """ + Derive port information from the cached pedalboard state as a fallback + when PiPedal JACK port listing is unavailable. + """ + from app import pipedal_state, discover_oplabs_from_pedalboard + + ports = [] + + # System physical ports (generic — actual ports depend on audio interface) + ports.append({ + "name": "system:capture_1", + "client": "system", + "port": "capture_1", + "port_type": "audio", + "direction": "output", + "is_physical": True, + "connections": [], + }) + ports.append({ + "name": "system:capture_2", + "client": "system", + "port": "capture_2", + "port_type": "audio", + "direction": "output", + "is_physical": True, + "connections": [], + }) + ports.append({ + "name": "system:playback_1", + "client": "system", + "port": "playback_1", + "port_type": "audio", + "direction": "input", + "is_physical": True, + "connections": [], + }) + ports.append({ + "name": "system:playback_2", + "client": "system", + "port": "playback_2", + "port_type": "audio", + "direction": "input", + "is_physical": True, + "connections": [], + }) + + # PiPedal client ports (derived from pedalboard state) + pb = pipedal_state.get("pedalboard") or {} + items = pb.get("items") or [] + seen_clients = set() + + for item in items: + uri = item.get("uri", "") + instance_id = item.get("instanceId") + title = item.get("title", "") or item.get("pluginName", "") or f"plugin_{instance_id}" + client_name = f"pipedal:{instance_id}" if instance_id else f"pipedal:{title}" + + if client_name in seen_clients: + continue + seen_clients.add(client_name) + + audio_ins = item.get("audioInputs", 2) or 2 + audio_outs = item.get("audioOutputs", 2) or 2 + + # Input ports (the plugin's audio inputs = JACK destinations) + for j in range(audio_ins): + pname = f"{client_name}:audio_in_{j + 1}" + ports.append({ + "name": pname, + "client": client_name, + "port": f"audio_in_{j + 1}", + "port_type": "audio", + "direction": "input", + "is_physical": False, + "connections": [], + }) + + # Output ports (the plugin's audio outputs = JACK sources) + for j in range(audio_outs): + pname = f"{client_name}:audio_out_{j + 1}" + ports.append({ + "name": pname, + "client": client_name, + "port": f"audio_out_{j + 1}", + "port_type": "audio", + "direction": "output", + "is_physical": False, + "connections": [], + }) + + # Generic PiPedal engine output ports + engine_client = "pipedal" + for j in range(2): + pname = f"{engine_client}:out_{j + 1}" + ports.append({ + "name": pname, + "client": engine_client, + "port": f"out_{j + 1}", + "port_type": "audio", + "direction": "output", + "is_physical": False, + "connections": [], + }) + + return ports + + +def _normalize_port_entry(raw: dict) -> dict: + """ + Normalize a port entry from PiPedal's response to our standard format. + Handles various key naming conventions. + """ + name = raw.get("name") or raw.get("portName") or raw.get("fullName") or "" + client = raw.get("client") or raw.get("clientName") or name.split(":")[0] if ":" in name else "" + port = raw.get("port") or raw.get("shortName") or (name.split(":", 1)[1] if ":" in name else name) + port_type = raw.get("type") or raw.get("portType") or "audio" + direction = raw.get("direction") or raw.get("mode") or "output" + is_physical = raw.get("isPhysical") or raw.get("physical") or raw.get("is_physical") or False + connections = raw.get("connections") or raw.get("connectedTo") or [] + + return { + "name": name, + "client": client, + "port": port, + "port_type": port_type, + "direction": direction, + "is_physical": bool(is_physical), + "connections": connections if isinstance(connections, list) else [], + } + + +# --------------------------------------------------------------------------- +# Router +# --------------------------------------------------------------------------- + +router = APIRouter(prefix="/api/jack", tags=["jack"]) + + +@router.get("/ports") +async def list_jack_ports(): + """ + List all JACK audio ports and their current connections. + + Returns: + { + "ports": [...], # list of port dicts + "connections": {...}, # port_name → [connected_port_names] + "source": "pipedal" | "fallback" + } + """ + # Try PiPedal for real port data + ports_data = await _call_pipedal( + MSG_LIST_PORTS, + alt_messages=ALT_MSG_LIST_PORTS, + ) + + connections_data = await _call_pipedal( + MSG_LIST_CONNECTIONS, + alt_messages=ALT_MSG_LIST_CONNECTIONS, + ) + + if ports_data is not None: + # Normalize port entries + raw_ports = ports_data if isinstance(ports_data, list) else (ports_data.get("ports") or ports_data.get("items") or []) + ports = [_normalize_port_entry(p) for p in raw_ports] + + # Merge connection info + if connections_data: + conn_map = connections_data + if isinstance(connections_data, dict): + conn_map = connections_data.get("connections") or connections_data.get("items") or connections_data + for port in ports: + pname = port["name"] + port["connections"] = conn_map.get(pname) or conn_map.get(pname, []) + + return { + "ports": ports, + "connections": _build_connection_map(ports), + "source": "pipedal", + } + + # Fallback: derive from cached pedalboard state + from app import pipedal_state + if pipedal_state.get("pedalboard"): + ports = _parse_ports_from_pedalboard() + return { + "ports": ports, + "connections": _build_connection_map(ports), + "source": "fallback", + "note": "PiPedal JACK API unavailable — ports derived from pedalboard state, connections unknown", + } + + # No data available at all + return { + "ports": [], + "connections": {}, + "source": "none", + "note": "PiPedal is unreachable. No JACK port information available.", + } + + +@router.get("/ports/refresh") +async def refresh_jack_ports(): + """ + Force-refresh the pedalboard state and re-query JACK ports. + """ + from app import fetch_pedalboard_state + fetch_pedalboard_state() + return await list_jack_ports() + + +@router.post("/connect") +async def connect_ports(req: JackConnectRequest): + """ + Connect two JACK ports (source → destination). + Body: {"source": "...", "destination": "..."} + """ + result = await _call_pipedal( + MSG_CONNECT, + body={"source": req.source, "destination": req.destination}, + alt_messages=ALT_MSG_CONNECT, + ) + + if result is None: + # If connect message failed, try as positional args + result = await _call_pipedal( + MSG_CONNECT, + body=[req.source, req.destination], + alt_messages=ALT_MSG_CONNECT, + ) + + if result is not None: + logger.info("JACK connect: %s → %s", req.source, req.destination) + return {"status": "connected", "source": req.source, "destination": req.destination} + + raise HTTPException( + status_code=502, + detail=f"Failed to connect {req.source} → {req.destination}: PiPedal did not respond", + ) + + +@router.post("/disconnect") +async def disconnect_ports(req: JackConnectRequest): + """ + Disconnect two JACK ports. + Body: {"source": "...", "destination": "..."} + """ + result = await _call_pipedal( + MSG_DISCONNECT, + body={"source": req.source, "destination": req.destination}, + alt_messages=ALT_MSG_DISCONNECT, + ) + + if result is None: + result = await _call_pipedal( + MSG_DISCONNECT, + body=[req.source, req.destination], + alt_messages=ALT_MSG_DISCONNECT, + ) + + if result is not None: + logger.info("JACK disconnect: %s → %s", req.source, req.destination) + return {"status": "disconnected", "source": req.source, "destination": req.destination} + + raise HTTPException( + status_code=502, + detail=f"Failed to disconnect {req.source} → {req.destination}: PiPedal did not respond", + ) + + +@router.post("/disconnect-all") +async def disconnect_all(): + """ + Disconnect all JACK port connections. + """ + ports_data = await list_jack_ports() + conns = ports_data.get("connections", {}) + disconnected = 0 + + for src, dests in conns.items(): + for dst in dests: + try: + await _call_pipedal( + MSG_DISCONNECT, + body={"source": src, "destination": dst}, + alt_messages=ALT_MSG_DISCONNECT, + ) + disconnected += 1 + except Exception: + pass + + return {"status": "disconnected_all", "count": disconnected} + + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + + +def _build_connection_map(ports: list[dict]) -> dict[str, list[str]]: + """Build a port_name → [connected_port_names] map from port list.""" + conn_map = {} + for p in ports: + pname = p["name"] + if p["connections"]: + conn_map[pname] = p["connections"] + # Also add reverse entries + for c in p.get("connections", []): + if c not in conn_map: + conn_map[c] = [] + if pname not in conn_map[c]: + conn_map[c].append(pname) + return conn_map diff --git a/backend/mixer_ipc.py b/backend/mixer_ipc.py new file mode 100644 index 0000000..f0b1c7b --- /dev/null +++ b/backend/mixer_ipc.py @@ -0,0 +1,305 @@ +""" +OPLabs Mixer — Unix domain socket IPC client. + +Connects to the C++ MixerDaemon over a Unix domain socket using a +length-prefixed JSON protocol. + +Protocol: + Frame: 4-byte big-endian uint32 length prefix + UTF-8 JSON payload + + Request: {"id": , "method": , "params": {}} + Response: {"id": , "result": , "error": } + Push: {"type": "push", "event": , "data": {}} +""" + +import asyncio +import json +import logging +import struct +from typing import Any, Optional + +logger = logging.getLogger("mixer-ipc") + + +class MixerIpcError(Exception): + """Raised when the mixer daemon returns an error response.""" + + +class MixerIpcClient: + """Async Unix socket IPC client for the OPLabs Mixer Daemon. + + Usage: + client = MixerIpcClient(socket_path="/tmp/oplabs-mixer.sock") + await client.connect() + state = await client.get_state() + await client.set_channel_volume(0, -6.0) + await client.close() + """ + + def __init__(self, socket_path: str = "/tmp/oplabs-mixer.sock", + connect_timeout: float = 5.0, + request_timeout: float = 10.0): + self._socket_path = socket_path + self._connect_timeout = connect_timeout + self._request_timeout = request_timeout + self._reader: Optional[asyncio.StreamReader] = None + self._writer: Optional[asyncio.StreamWriter] = None + self._connected = False + self._next_id = 1 + self._pending: dict[int, asyncio.Future] = {} + self._read_task: Optional[asyncio.Task] = None + + # ------------------------------------------------------------------ + # Connection lifecycle + # ------------------------------------------------------------------ + + async def connect(self) -> bool: + """Connect to the Unix domain socket. Returns True on success.""" + try: + loop = asyncio.get_running_loop() + self._reader, self._writer = await asyncio.wait_for( + asyncio.open_unix_connection(self._socket_path), + timeout=self._connect_timeout, + ) + self._connected = True + self._read_task = asyncio.create_task(self._read_loop()) + logger.info("Connected to mixer daemon at %s", self._socket_path) + return True + except (FileNotFoundError, ConnectionRefusedError, asyncio.TimeoutError, + OSError) as exc: + logger.warning("Failed to connect to mixer daemon: %s", exc) + self._connected = False + return False + + async def close(self): + """Close the connection.""" + self._connected = False + if self._read_task: + self._read_task.cancel() + try: + await self._read_task + except asyncio.CancelledError: + pass + self._read_task = None + if self._writer: + try: + self._writer.close() + await self._writer.wait_closed() + except Exception: + pass + self._writer = None + + @property + def is_connected(self) -> bool: + return self._connected + + # ------------------------------------------------------------------ + # Low-level send / receive + # ------------------------------------------------------------------ + + async def _send_frame(self, payload: bytes): + """Send a length-prefixed frame.""" + length = struct.pack("!I", len(payload)) + self._writer.write(length + payload) + await self._writer.drain() + + async def _read_loop(self): + """Background task: read frames and dispatch responses.""" + try: + while self._connected and self._reader: + # Read 4-byte length prefix + header = await self._reader.readexactly(4) + length = struct.unpack("!I", header)[0] + + if length == 0: + continue + + # Read JSON payload + data = await self._reader.readexactly(length) + payload = data.decode("utf-8") + + try: + msg = json.loads(payload) + except json.JSONDecodeError: + logger.warning("Invalid JSON from daemon: %s", payload[:200]) + continue + + # Dispatch + if isinstance(msg, dict): + if "type" in msg and msg["type"] == "push": + # Push message (VU meter updates, state changes) + await self._handle_push(msg) + elif "id" in msg: + # Response to a request + req_id = msg["id"] + future = self._pending.pop(req_id, None) + if future and not future.done(): + if msg.get("error"): + future.set_exception( + MixerIpcError(msg["error"]) + ) + else: + future.set_result(msg.get("result")) + except asyncio.IncompleteReadError: + logger.info("Mixer daemon connection closed") + except asyncio.CancelledError: + pass + except Exception as exc: + logger.warning("Read loop error: %s", exc) + finally: + self._connected = False + # Fail all pending requests + for future in self._pending.values(): + if not future.done(): + future.set_exception(MixerIpcError("Connection closed")) + self._pending.clear() + + async def _send_request(self, method: str, params: dict = None) -> Any: + """Send a request and wait for the response.""" + if not self._connected or not self._writer: + raise MixerIpcError("Not connected to mixer daemon") + + req_id = self._next_id + self._next_id += 1 + + msg = { + "id": req_id, + "method": method, + "params": params or {}, + } + + future: asyncio.Future = asyncio.get_running_loop().create_future() + self._pending[req_id] = future + + try: + payload = json.dumps(msg).encode("utf-8") + await self._send_frame(payload) + + result = await asyncio.wait_for(future, timeout=self._request_timeout) + return result + except asyncio.TimeoutError: + self._pending.pop(req_id, None) + raise MixerIpcError(f"Request '{method}' timed out") + + async def _handle_push(self, msg: dict): + """Handle an unsolicited push message from the daemon. + + Override in subclass or attach a callback. + """ + event = msg.get("event", "unknown") + data = msg.get("data") + logger.debug("Push event: %s", event) + # Subclasses can override to handle VU meter updates, etc. + + # ------------------------------------------------------------------ + # High-level API + # ------------------------------------------------------------------ + + # --- State --- + + async def get_state(self) -> dict: + """Get the full mixer state (channels, buses, routes, output routes).""" + return await self._send_request("getState") + + # --- Channel Control --- + + async def set_channel_volume(self, channel_index: int, volume_db: float): + """Set channel volume in dB (-inf to +12).""" + await self._send_request("setChannelVolume", { + "channelIndex": channel_index, + "volumeDb": volume_db, + }) + + async def set_channel_pan(self, channel_index: int, pan: float): + """Set channel pan (-1.0 left to +1.0 right).""" + await self._send_request("setChannelPan", { + "channelIndex": channel_index, + "pan": pan, + }) + + async def set_channel_mute(self, channel_index: int, mute: bool): + """Set channel mute state.""" + await self._send_request("setChannelMute", { + "channelIndex": channel_index, + "mute": mute, + }) + + async def set_channel_solo(self, channel_index: int, solo: bool): + """Set channel solo state.""" + await self._send_request("setChannelSolo", { + "channelIndex": channel_index, + "solo": solo, + }) + + # --- Channel Lifecycle --- + + async def add_channel(self, physical_input_index: int = 0) -> int: + """Add a new channel. Returns the channel index.""" + result = await self._send_request("addChannel", { + "physicalInputIndex": physical_input_index, + }) + return result.get("channelIndex", -1) + + async def remove_channel(self, channel_index: int): + """Remove a channel by index.""" + await self._send_request("removeChannel", { + "channelIndex": channel_index, + }) + + # --- Output Routing --- + + async def get_output_routes(self) -> list[dict]: + """Get the output routing table.""" + result = await self._send_request("getOutputRoutes") + return result.get("routes", []) + + async def set_output_routes(self, routes: list[dict]): + """Set the output routing table. + + Each route dict: + {"sourceBusId": int, "sourceStartChannel": int, + "targetStartChannel": int, "channels": int} + """ + await self._send_request("setOutputRoutes", { + "routes": routes, + }) + + # --- Scenes --- + + async def save_scene(self, name: str) -> dict: + """Save the current mixer state as a named scene. + Returns {"id": int, "name": str}.""" + return await self._send_request("saveScene", {"name": name}) + + async def load_scene(self, scene_id: str) -> bool: + """Load (recall) a scene by its ID. Returns True on success.""" + result = await self._send_request("loadScene", {"sceneId": scene_id}) + return result.get("ok", False) + + async def list_scenes(self) -> list[dict]: + """List all available scenes.""" + result = await self._send_request("listScenes") + return result.get("scenes", []) + + async def delete_scene(self, scene_id: str) -> bool: + """Delete a scene by ID. Returns True on success.""" + result = await self._send_request("deleteScene", {"sceneId": scene_id}) + return result.get("ok", False) + + +# ------------------------------------------------------------------ +# Convenience context manager +# ------------------------------------------------------------------ + +class MixerIpcContext: + """Async context manager for MixerIpcClient.""" + + def __init__(self, socket_path: str = "/tmp/oplabs-mixer.sock"): + self.client = MixerIpcClient(socket_path=socket_path) + + async def __aenter__(self) -> MixerIpcClient: + await self.client.connect() + return self.client + + async def __aexit__(self, *args): + await self.client.close() diff --git a/daemon/CMakeLists.txt b/daemon/CMakeLists.txt new file mode 100644 index 0000000..18a48ec --- /dev/null +++ b/daemon/CMakeLists.txt @@ -0,0 +1,80 @@ +cmake_minimum_required(VERSION 3.16) +project(oplabs-mixer-daemon + VERSION 1.0.0 + DESCRIPTION "OPLabs Mixer Engine Daemon" + LANGUAGES CXX +) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +# Find dependencies +find_package(PkgConfig QUIET) + +# --- JACK Audio Connection Kit --- +find_library(JACK_LIBRARY jack) +find_path(JACK_INCLUDE_DIR jack/jack.h) + +# --- Source files for the daemon (standalone) --- +set(DAEMON_SOURCES + MixerDaemon.cpp + MixerIpcServer.cpp +) + +# Header-only convenience target for linking to op-pedal sources +# The daemon needs MixerEngine, MixerApi, MixerChannelStrip, MixerBus, etc. +# These are compiled as part of the op-pedal CMake project and linked here. + +add_executable(oplabs-mixer-daemon ${DAEMON_SOURCES}) + +target_include_directories(oplabs-mixer-daemon PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} +) + +if(JACK_LIBRARY AND JACK_INCLUDE_DIR) + target_include_directories(oplabs-mixer-daemon PRIVATE ${JACK_INCLUDE_DIR}) + target_link_libraries(oplabs-mixer-daemon PRIVATE ${JACK_LIBRARY}) + message(STATUS "JACK found: ${JACK_LIBRARY}") + target_compile_definitions(oplabs-mixer-daemon PRIVATE HAS_JACK=1) +else() + message(WARNING "JACK not found — daemon will be built without audio I/O. " + "Install libjack-jackd2-dev or jack-audio-connection-kit.") +endif() + +# When built inside the op-pedal CMake tree, link against op-pedal's libraries. +# When built standalone, the user must point CMAKE_PREFIX_PATH to an op-pedal build. +# For standalone development, provide a build wrapper: + +if(TARGET op-pedal-lib) + # We're inside the op-pedal CMake tree + target_link_libraries(oplabs-mixer-daemon PRIVATE op-pedal-lib) + message(STATUS "Building inside op-pedal tree — linking op-pedal-lib") +else() + message(STATUS "Building standalone — user must provide MixerEngine source") + # In standalone mode, assume the user has checked out the mixer-engine sources + # and set the MIXER_ENGINE_SOURCE_DIR variable. + if(MIXER_ENGINE_SOURCE_DIR) + message(STATUS "Using MixerEngine sources from: ${MIXER_ENGINE_SOURCE_DIR}") + target_include_directories(oplabs-mixer-daemon PRIVATE + ${MIXER_ENGINE_SOURCE_DIR} + ${MIXER_ENGINE_SOURCE_DIR}/../PiPedalCommon + ${MIXER_ENGINE_SOURCE_DIR}/../modules/SQLiteCpp/include + ) + endif() +endif() + +# Install +install(TARGETS oplabs-mixer-daemon RUNTIME DESTINATION bin) + +# Systemd service file +configure_file( + oplabs-mixer-daemon.service.in + oplabs-mixer-daemon.service + @ONLY +) + +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/oplabs-mixer-daemon.service + DESTINATION /etc/systemd/system +) diff --git a/daemon/MixerDaemon.cpp b/daemon/MixerDaemon.cpp new file mode 100644 index 0000000..fea904c --- /dev/null +++ b/daemon/MixerDaemon.cpp @@ -0,0 +1,134 @@ +// Copyright (c) 2026 Ourpad Network +// See LICENSE file in the project root for full license text. +// +// MixerDaemon — Standalone OPLabs Mixer Engine daemon. +// +// This daemon: +// 1. Creates a MixerEngine with JACK audio I/O +// 2. Creates a MixerApi for control +// 3. Starts the MixerIpcServer on a Unix domain socket +// 4. Runs the audio loop until SIGINT/SIGTERM + +#include +#include +#include +#include +#include +#include + +#include "MixerIpcServer.hpp" +#include "MixerApi.hpp" +#include "MixerEngine.hpp" + +using namespace pipedal; + +// Global pointers for signal handler +static MixerIpcServer* g_server = nullptr; +static std::atomic g_running{true}; + +void signalHandler(int sig) { + (void)sig; + fprintf(stderr, "\n[MixerDaemon] Signal received, shutting down...\n"); + g_running.store(false); + if (g_server) { + g_server->stop(); + } +} + +void printUsage(const char* prog) { + fprintf(stderr, "Usage: %s [options]\n", prog); + fprintf(stderr, "Options:\n"); + fprintf(stderr, " --socket-path PATH Unix socket path (default: /tmp/oplabs-mixer.sock)\n"); + fprintf(stderr, " --sample-rate RATE Sample rate in Hz (default: 48000)\n"); + fprintf(stderr, " --buffer-size SIZE Buffer size in frames (default: 512)\n"); + fprintf(stderr, " --input-channels N Number of input channels (default: 8)\n"); + fprintf(stderr, " --output-channels N Number of output channels (default: 8)\n"); + fprintf(stderr, " --help Print this help\n"); +} + +int main(int argc, char* argv[]) { + // Default parameters + std::string socketPath = "/tmp/oplabs-mixer.sock"; + uint32_t sampleRate = 48000; + size_t bufferSize = 512; + uint32_t inputChannels = 8; + uint32_t outputChannels = 8; + + // Parse command line + for (int i = 1; i < argc; i++) { + std::string arg = argv[i]; + if (arg == "--socket-path" && i + 1 < argc) { + socketPath = argv[++i]; + } else if (arg == "--sample-rate" && i + 1 < argc) { + sampleRate = static_cast(std::stoul(argv[++i])); + } else if (arg == "--buffer-size" && i + 1 < argc) { + bufferSize = static_cast(std::stoul(argv[++i])); + } else if (arg == "--input-channels" && i + 1 < argc) { + inputChannels = static_cast(std::stoul(argv[++i])); + } else if (arg == "--output-channels" && i + 1 < argc) { + outputChannels = static_cast(std::stoul(argv[++i])); + } else if (arg == "--help") { + printUsage(argv[0]); + return 0; + } else { + fprintf(stderr, "Unknown option: %s\n", arg.c_str()); + printUsage(argv[0]); + return 1; + } + } + + fprintf(stderr, "[MixerDaemon] Starting OPLabs Mixer Daemon\n"); + fprintf(stderr, "[MixerDaemon] Socket: %s\n", socketPath.c_str()); + fprintf(stderr, "[MixerDaemon] SampleRate: %u Hz\n", sampleRate); + fprintf(stderr, "[MixerDaemon] BufferSize: %zu frames\n", bufferSize); + fprintf(stderr, "[MixerDaemon] Inputs: %u\n", inputChannels); + fprintf(stderr, "[MixerDaemon] Outputs: %u\n", outputChannels); + + // Set up signal handling + signal(SIGINT, signalHandler); + signal(SIGTERM, signalHandler); + + // Create MixerEngine + auto engine = std::make_unique(); + engine->setSampleRate(sampleRate); + engine->setMaxBufferSize(bufferSize); + + // Auto-create channels + engine->autoCreateChannels(inputChannels); + + fprintf(stderr, "[MixerDaemon] MixerEngine created with %zu channels\n", + engine->channelCount()); + + // Create MixerApi and attach engine + auto api = std::make_unique(); + api->setMixerEngine(engine.get()); + + // Create IPC server + auto server = std::make_unique(); + server->setMixerApi(api.get()); + server->setMixerEngine(engine.get()); + g_server = server.get(); + + if (!server->start(socketPath)) { + fprintf(stderr, "[MixerDaemon] Failed to start IPC server on %s\n", + socketPath.c_str()); + return 1; + } + + fprintf(stderr, "[MixerDaemon] IPC server listening on %s\n", socketPath.c_str()); + fprintf(stderr, "[MixerDaemon] Ready. Waiting for connections...\n"); + + // Main loop — keep running until signal + // In a full implementation, this would run the JACK audio processing loop. + // For now, the daemon provides IPC access to the MixerEngine. + while (g_running.load()) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + + // Cleanup + server->stop(); + api->setMixerEngine(nullptr); + + fprintf(stderr, "[MixerDaemon] Shutdown complete.\n"); + return 0; +} diff --git a/daemon/MixerIpcServer.cpp b/daemon/MixerIpcServer.cpp new file mode 100644 index 0000000..7573bf2 --- /dev/null +++ b/daemon/MixerIpcServer.cpp @@ -0,0 +1,753 @@ +// Copyright (c) 2026 Ourpad Network +// See LICENSE file in the project root for full license text. +// +// MixerIpcServer — Unix domain socket IPC server implementation. + +#include "MixerIpcServer.hpp" +#include "MixerApi.hpp" +#include "MixerEngine.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include // for htonl/ntohl + +// JSON writer/reader (inline minimal implementation to avoid heavy dependency) +// In production, use a proper JSON library like nlohmann/json or boost.json. +// Here we use the PiPedal project's own json_writer/json_reader if available, +// but since this is a standalone daemon, we provide a minimal inline version. + +namespace { + +// Write a JSON string with proper escaping +std::string jsonEscape(const std::string& s) { + std::string out; + out.reserve(s.size() + 2); + for (char c : s) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (static_cast(c) < 0x20) { + char buf[8]; + snprintf(buf, sizeof(buf), "\\u%04x", c); + out += buf; + } else { + out += c; + } + } + } + return out; +} + +// Simple JSON object builder +class JsonBuilder { +public: + JsonBuilder() : ss_() { ss_ << "{"; first_ = true; } + + void add(const std::string& key, const std::string& value) { + if (!first_) ss_ << ","; + first_ = false; + ss_ << "\"" << jsonEscape(key) << "\":\"" << jsonEscape(value) << "\""; + } + + void add(const std::string& key, const char* value) { + add(key, std::string(value)); + } + + void add(const std::string& key, int64_t value) { + if (!first_) ss_ << ","; + first_ = false; + ss_ << "\"" << jsonEscape(key) << "\":" << value; + } + + void add(const std::string& key, double value) { + if (!first_) ss_ << ","; + first_ = false; + ss_ << "\"" << jsonEscape(key) << "\":" << value; + } + + void add(const std::string& key, bool value) { + if (!first_) ss_ << ","; + first_ = false; + ss_ << "\"" << jsonEscape(key) << "\":" << (value ? "true" : "false"); + } + + void addRaw(const std::string& key, const std::string& rawJson) { + if (!first_) ss_ << ","; + first_ = false; + ss_ << "\"" << jsonEscape(key) << "\":" << rawJson; + } + + std::string build() { ss_ << "}"; return ss_.str(); } + +private: + std::stringstream ss_; + bool first_ = true; +}; + +// Simple JSON key-value extractor (does not handle nested objects) +// Just enough for our params extraction +class SimpleJsonParser { +public: + SimpleJsonParser(const std::string& json) : data_(json), pos_(0) { + skipWhitespace(); + } + + bool enterObject() { + skipWhitespace(); + if (pos_ < data_.size() && data_[pos_] == '{') { + pos_++; + skipWhitespace(); + return true; + } + return false; + } + + bool enterArray() { + skipWhitespace(); + if (pos_ < data_.size() && data_[pos_] == '[') { + pos_++; + skipWhitespace(); + return true; + } + return false; + } + + void leaveObject() { + skipWhitespace(); + if (pos_ < data_.size() && data_[pos_] == '}') pos_++; + } + + void leaveArray() { + skipWhitespace(); + if (pos_ < data_.size() && data_[pos_] == ']') pos_++; + } + + std::string readKey() { + skipWhitespace(); + std::string key = readString(); + skipWhitespace(); + if (pos_ < data_.size() && data_[pos_] == ':') pos_++; + return key; + } + + std::string readString() { + skipWhitespace(); + if (pos_ >= data_.size() || data_[pos_] != '"') return ""; + pos_++; // skip opening quote + std::string result; + while (pos_ < data_.size() && data_[pos_] != '"') { + if (data_[pos_] == '\\' && pos_ + 1 < data_.size()) { + pos_++; + switch (data_[pos_]) { + case '"': result += '"'; break; + case '\\': result += '\\'; break; + case '/': result += '/'; break; + case 'n': result += '\n'; break; + case 'r': result += '\r'; break; + case 't': result += '\t'; break; + default: result += data_[pos_]; break; + } + } else { + result += data_[pos_]; + } + pos_++; + } + if (pos_ < data_.size() && data_[pos_] == '"') pos_++; // skip closing quote + return result; + } + + int64_t readInt() { + skipWhitespace(); + char* end = nullptr; + int64_t val = strtoll(data_.c_str() + pos_, &end, 10); + if (end) pos_ = end - data_.c_str(); + return val; + } + + double readDouble() { + skipWhitespace(); + char* end = nullptr; + double val = strtod(data_.c_str() + pos_, &end); + if (end) pos_ = end - data_.c_str(); + return val; + } + + bool readBool() { + skipWhitespace(); + if (data_.substr(pos_, 4) == "true") { pos_ += 4; return true; } + if (data_.substr(pos_, 5) == "false") { pos_ += 5; return false; } + return false; + } + + std::string readRaw() { + // Read a raw JSON value (for nested objects/arrays we want to preserve) + skipWhitespace(); + if (pos_ >= data_.size()) return ""; + + char start = data_[pos_]; + if (start == '{' || start == '[') { + // Find matching close brace/bracket + char close = (start == '{') ? '}' : ']'; + int depth = 0; + size_t startPos = pos_; + bool inString = false; + while (pos_ < data_.size()) { + char c = data_[pos_]; + if (c == '"' && (pos_ == 0 || data_[pos_-1] != '\\')) inString = !inString; + if (!inString) { + if (c == start) depth++; + if (c == close) { + depth--; + if (depth == 0) { + pos_++; + return data_.substr(startPos, pos_ - startPos); + } + } + } + pos_++; + } + pos_ = startPos; // reset on failure + } + return ""; + } + + // Skip a single value (for keys we don't care about) + void skipValue() { + skipWhitespace(); + if (pos_ >= data_.size()) return; + char c = data_[pos_]; + if (c == '"') { readString(); } + else if (c == '{' || c == '[') { readRaw(); } + else if (c == 't' || c == 'f') { readBool(); } + else { readDouble(); } // number (also handles int) + skipWhitespace(); + if (pos_ < data_.size() && (data_[pos_] == ',' || data_[pos_] == '}')) { + if (data_[pos_] == ',') pos_++; + } + } + + // Check if we've reached the end of the current object + bool atEnd() { + skipWhitespace(); + return pos_ >= data_.size() || data_[pos_] == '}'; + } + + // Parse a string value for a given key from a flat JSON object + std::string getString(const std::string& key) { + if (!enterObject()) return ""; + while (!atEnd()) { + std::string k = readKey(); + if (k == key) { std::string v = readString(); leaveObject(); return v; } + else { skipValue(); } + } + leaveObject(); + return ""; + } + + int64_t getInt(const std::string& key, int64_t def = 0) { + if (!enterObject()) return def; + while (!atEnd()) { + std::string k = readKey(); + if (k == key) { int64_t v = readInt(); leaveObject(); return v; } + else { skipValue(); } + } + leaveObject(); + return def; + } + + double getDouble(const std::string& key, double def = 0.0) { + if (!enterObject()) return def; + while (!atEnd()) { + std::string k = readKey(); + if (k == key) { double v = readDouble(); leaveObject(); return v; } + else { skipValue(); } + } + leaveObject(); + return def; + } + + bool getBool(const std::string& key, bool def = false) { + if (!enterObject()) return def; + while (!atEnd()) { + std::string k = readKey(); + if (k == key) { bool v = readBool(); leaveObject(); return v; } + else { skipValue(); } + } + leaveObject(); + return def; + } + + std::string getRaw(const std::string& key) { + if (!enterObject()) return ""; + while (!atEnd()) { + std::string k = readKey(); + if (k == key) { std::string v = readRaw(); leaveObject(); return v; } + else { skipValue(); } + } + leaveObject(); + return ""; + } + +private: + const std::string& data_; + size_t pos_; + + void skipWhitespace() { + while (pos_ < data_.size() && (data_[pos_] == ' ' || data_[pos_] == '\t' || + data_[pos_] == '\n' || data_[pos_] == '\r')) + pos_++; + } +}; + +} // anonymous namespace + +using namespace pipedal; + +// --------------------------------------------------------------------------- +// Construction / Destruction +// --------------------------------------------------------------------------- + +MixerIpcServer::MixerIpcServer() {} +MixerIpcServer::~MixerIpcServer() { stop(); } + +// --------------------------------------------------------------------------- +// Start / Stop +// --------------------------------------------------------------------------- + +bool MixerIpcServer::start(const std::string& socketPath) { + if (running_.load()) { + return true; // already running + } + + socketPath_ = socketPath; + + // Remove existing socket file if present + unlink(socketPath_.c_str()); + + // Create socket + serverFd_ = socket(AF_UNIX, SOCK_STREAM, 0); + if (serverFd_ < 0) { + perror("socket"); + return false; + } + + // Bind + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, socketPath_.c_str(), sizeof(addr.sun_path) - 1); + + if (bind(serverFd_, (struct sockaddr*)&addr, sizeof(addr)) < 0) { + perror("bind"); + close(serverFd_); + serverFd_ = -1; + return false; + } + + // Set permissions so the FastAPI process (running as same user) can connect + chmod(socketPath_.c_str(), 0666); + + // Listen + if (listen(serverFd_, 5) < 0) { + perror("listen"); + close(serverFd_); + serverFd_ = -1; + unlink(socketPath_.c_str()); + return false; + } + + running_.store(true); + + // Start accept thread + acceptThread_ = std::thread(&MixerIpcServer::acceptLoop, this); + + return true; +} + +void MixerIpcServer::stop() { + running_.store(false); + + // Close all client connections + for (auto& [id, conn] : clients_) { + if (conn->fd >= 0) { + close(conn->fd); + conn->fd = -1; + } + } + clients_.clear(); + + // Close server socket + if (serverFd_ >= 0) { + close(serverFd_); + serverFd_ = -1; + } + + // Remove socket file + if (!socketPath_.empty()) { + unlink(socketPath_.c_str()); + } + + // Join accept thread + if (acceptThread_.joinable()) { + acceptThread_.join(); + } +} + +// --------------------------------------------------------------------------- +// Communication +// --------------------------------------------------------------------------- + +bool MixerIpcServer::sendFrame(int fd, const std::string& jsonPayload) { + if (fd < 0) return false; + + uint32_t len = static_cast(jsonPayload.size()); + uint32_t lenBe = htonl(len); + + // Write length prefix + ssize_t written = write(fd, &lenBe, sizeof(lenBe)); + if (written != sizeof(lenBe)) return false; + + // Write payload + written = write(fd, jsonPayload.data(), jsonPayload.size()); + if (written != static_cast(jsonPayload.size())) return false; + + return true; +} + +bool MixerIpcServer::sendResponse(int clientFd, const std::string& jsonResponse) { + return sendFrame(clientFd, jsonResponse); +} + +void MixerIpcServer::broadcast(const std::string& jsonMessage) { + auto fds = connectedClientFds(); + for (int fd : fds) { + if (fd >= 0) { + sendFrame(fd, jsonMessage); + } + } +} + +std::vector MixerIpcServer::connectedClientFds() const { + std::vector fds; + for (const auto& [id, conn] : clients_) { + if (conn->active && conn->fd >= 0) { + fds.push_back(conn->fd); + } + } + return fds; +} + +// --------------------------------------------------------------------------- +// Accept loop +// --------------------------------------------------------------------------- + +void MixerIpcServer::acceptLoop() { + while (running_.load()) { + struct sockaddr_un clientAddr; + socklen_t clientLen = sizeof(clientAddr); + + int clientFd = accept(serverFd_, (struct sockaddr*)&clientAddr, &clientLen); + if (clientFd < 0) { + if (errno == EINTR) continue; + if (!running_.load()) break; + perror("accept"); + continue; + } + + // Create client connection + auto conn = std::make_unique(); + conn->fd = clientFd; + conn->active = true; + + int clientId = nextClientId_++; + clients_[clientId] = std::move(conn); + + // Handle this client (blocking per-client) + // In a real implementation, this would be in a separate thread or use event loop. + // For this embedded version, we handle one client at a time per thread. + handleClient(clientId); + } +} + +// --------------------------------------------------------------------------- +// Client handler +// --------------------------------------------------------------------------- + +void MixerIpcServer::handleClient(int clientId) { + auto it = clients_.find(clientId); + if (it == clients_.end()) return; + + auto& conn = it->second; + + while (running_.load() && conn->active) { + if (!readFromClient(*conn)) { + break; + } + } + + // Cleanup + if (conn->fd >= 0) { + close(conn->fd); + conn->fd = -1; + } + conn->active = false; + clients_.erase(clientId); +} + +bool MixerIpcServer::readFromClient(ClientConnection& conn) { + uint8_t buffer[4096]; + + ssize_t n = read(conn.fd, buffer, sizeof(buffer)); + if (n <= 0) { + if (n == 0) { + // Connection closed + return false; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + // No data available yet — yield and retry on next loop iteration + // In a proper impl, use poll()/epoll() + return true; + } + return false; + } + + // Append to read buffer + conn.readBuffer.insert(conn.readBuffer.end(), buffer, buffer + n); + + // Process complete frames + while (true) { + if (conn.readingHeader) { + if (conn.readBuffer.size() < 4) break; + + // Read length prefix (big-endian uint32) + uint32_t lenBe; + memcpy(&lenBe, conn.readBuffer.data(), 4); + conn.expectedLength = ntohl(lenBe); + + // Remove header from buffer + conn.readBuffer.erase(conn.readBuffer.begin(), conn.readBuffer.begin() + 4); + + conn.readingHeader = false; + } + + if (conn.readBuffer.size() < conn.expectedLength) break; + + // We have a complete message + std::string jsonMessage(conn.readBuffer.begin(), + conn.readBuffer.begin() + conn.expectedLength); + conn.readBuffer.erase(conn.readBuffer.begin(), + conn.readBuffer.begin() + conn.expectedLength); + + conn.readingHeader = true; + conn.expectedLength = 0; + + // Process the message + processMessage(conn, jsonMessage); + } + + return true; +} + +// --------------------------------------------------------------------------- +// Message processing +// --------------------------------------------------------------------------- + +void MixerIpcServer::processMessage(ClientConnection& conn, const std::string& jsonMessage) { + if (messageCallback_) { + messageCallback_(jsonMessage); + } + + // Parse the JSON message + SimpleJsonParser parser(jsonMessage); + + // Extract id, method, params + int64_t msgId = 0; + std::string method; + std::string params; + + if (!parser.enterObject()) { + // Invalid message + JsonBuilder err; + err.add("id", 0); + err.add("error", std::string("Invalid JSON: expected object")); + sendResponse(conn.fd, err.build()); + return; + } + + while (!parser.atEnd()) { + std::string key = parser.readKey(); + if (key == "id") { + msgId = parser.readInt(); + } else if (key == "method") { + method = parser.readString(); + } else if (key == "params") { + // Read raw params value (could be object, array, etc.) + params = parser.readRaw(); + } else { + parser.skipValue(); + } + } + parser.leaveObject(); + + if (method.empty()) { + JsonBuilder err; + err.add("id", msgId); + err.add("error", std::string("Missing 'method' field")); + sendResponse(conn.fd, err.build()); + return; + } + + // Dispatch and get response + std::string resultJson = dispatchMethod(method, params); + + // Wrap with response id + std::stringstream ss; + ss << "{\"id\":" << msgId << ","; + // The resultJson starts with {"result": ...} or {"error": ...} + // Strip the outer { and add our id + if (!resultJson.empty() && resultJson[0] == '{') { + ss << resultJson.substr(1); // skip leading { + } else { + ss << "\"result\":" << resultJson << ",\"error\":null"; + } + + sendResponse(conn.fd, ss.str()); +} + +// --------------------------------------------------------------------------- +// Method dispatch +// --------------------------------------------------------------------------- + +std::string MixerIpcServer::dispatchMethod(const std::string& method, const std::string& paramsJson) { + if (!mixerApi_) { + return "{\"error\":\"no mixer api configured\"}"; + } + + try { + if (method == "getState") { + std::string state = mixerApi_->getStateJson(); + return "{\"result\":" + state + ",\"error\":null}"; + } + else if (method == "setChannelVolume") { + SimpleJsonParser p(paramsJson); + int ci = (int)p.getInt("channelIndex", -1); + double vol = p.getDouble("volumeDb", -96.0); + if (ci < 0) return "{\"error\":\"missing channelIndex\"}"; + mixerApi_->setChannelVolume(ci, (float)vol); + return "{\"result\":{},\"error\":null}"; + } + else if (method == "setChannelPan") { + SimpleJsonParser p(paramsJson); + int ci = (int)p.getInt("channelIndex", -1); + double pan = p.getDouble("pan", 0.0); + if (ci < 0) return "{\"error\":\"missing channelIndex\"}"; + mixerApi_->setChannelPan(ci, (float)pan); + return "{\"result\":{},\"error\":null}"; + } + else if (method == "setChannelMute") { + SimpleJsonParser p(paramsJson); + int ci = (int)p.getInt("channelIndex", -1); + bool mute = p.getBool("mute", false); + if (ci < 0) return "{\"error\":\"missing channelIndex\"}"; + mixerApi_->setChannelMute(ci, mute); + return "{\"result\":{},\"error\":null}"; + } + else if (method == "setChannelSolo") { + SimpleJsonParser p(paramsJson); + int ci = (int)p.getInt("channelIndex", -1); + bool solo = p.getBool("solo", false); + if (ci < 0) return "{\"error\":\"missing channelIndex\"}"; + mixerApi_->setChannelSolo(ci, solo); + return "{\"result\":{},\"error\":null}"; + } + else if (method == "addChannel") { + SimpleJsonParser p(paramsJson); + int pi = (int)p.getInt("physicalInputIndex", 0); + int idx = mixerApi_->addChannel(pi); + JsonBuilder resp; + resp.add("channelIndex", (int64_t)idx); + return "{\"result\":" + resp.build() + ",\"error\":null}"; + } + else if (method == "removeChannel") { + SimpleJsonParser p(paramsJson); + int ci = (int)p.getInt("channelIndex", -1); + if (ci < 0) return "{\"error\":\"missing channelIndex\"}"; + mixerApi_->removeChannel(ci); + return "{\"result\":{},\"error\":null}"; + } + else if (method == "getOutputRoutes") { + std::string routes = mixerApi_->getOutputRoutesJson(); + return "{\"result\":{\"routes\":" + routes + "},\"error\":null}"; + } + else if (method == "setOutputRoutes") { + // params is the raw JSON for output routes array + // We need the routes array from params + SimpleJsonParser p(paramsJson); + std::string routesArray = p.getRaw("routes"); + if (!routesArray.empty()) { + mixerApi_->setOutputRoutesFromJson(routesArray); + } + return "{\"result\":{},\"error\":null}"; + } + else if (method == "saveScene") { + SimpleJsonParser p(paramsJson); + std::string name = p.getString("name"); + if (name.empty()) return "{\"error\":\"missing name\"}"; + std::string result = mixerApi_->saveScene(name); + // result from MixerApi is already JSON: {"id": N, "name": "..."} + return "{\"result\":" + result + ",\"error\":null}"; + } + else if (method == "loadScene") { + SimpleJsonParser p(paramsJson); + std::string sceneId = p.getString("sceneId"); + if (sceneId.empty()) { + // Try as integer + int64_t id = p.getInt("sceneId", -1); + if (id < 0) return "{\"error\":\"missing sceneId\"}"; + sceneId = std::to_string(id); + } + bool ok = mixerApi_->loadScene(sceneId); + JsonBuilder resp; + resp.add("ok", ok); + return "{\"result\":" + resp.build() + ",\"error\":null}"; + } + else if (method == "listScenes") { + std::string scenes = mixerApi_->listScenes(); + if (scenes.empty()) scenes = "[]"; + return "{\"result\":{\"scenes\":" + scenes + "},\"error\":null}"; + } + else if (method == "deleteScene") { + SimpleJsonParser p(paramsJson); + std::string sceneId = p.getString("sceneId"); + if (sceneId.empty()) { + int64_t id = p.getInt("sceneId", -1); + if (id < 0) return "{\"error\":\"missing sceneId\"}"; + sceneId = std::to_string(id); + } + bool ok = mixerApi_->deleteScene(sceneId); + JsonBuilder resp; + resp.add("ok", ok); + return "{\"result\":" + resp.build() + ",\"error\":null}"; + } + else { + return "{\"error\":\"unknown method: " + jsonEscape(method) + "\"}"; + } + } + catch (const std::exception& e) { + return "{\"error\":\"" + jsonEscape(e.what()) + "\"}"; + } +} diff --git a/daemon/MixerIpcServer.hpp b/daemon/MixerIpcServer.hpp new file mode 100644 index 0000000..0657a5c --- /dev/null +++ b/daemon/MixerIpcServer.hpp @@ -0,0 +1,128 @@ +// Copyright (c) 2026 Ourpad Network +// See LICENSE file in the project root for full license text. +// +// MixerIpcServer — Unix domain socket IPC server for the OPLabs Mixer Daemon. +// +// Protocol: +// - Transport: Unix domain socket (AF_UNIX, SOCK_STREAM) +// - Socket path: /tmp/oplabs-mixer.sock +// - Framing: 4-byte big-endian length prefix (uint32_t) + JSON payload (UTF-8) +// +// Request: {"id": , "method": , "params": {}} +// Response: {"id": , "result": , "error": } +// Push: {"type": "push", "event": , "data": {}} +// +// Methods: +// getState params: {} result: {full mixer state} +// setChannelVolume params: {channelIndex, volumeDb} result: {} +// setChannelPan params: {channelIndex, pan} result: {} +// setChannelMute params: {channelIndex, mute} result: {} +// setChannelSolo params: {channelIndex, solo} result: {} +// addChannel params: {physicalInputIndex} result: {channelIndex} +// removeChannel params: {channelIndex} result: {} +// getOutputRoutes params: {} result: {routes: [...]} +// setOutputRoutes params: {routes: [...]} result: {} +// saveScene params: {name} result: {id, name} +// loadScene params: {sceneId} result: {ok: bool} +// listScenes params: {} result: {scenes: [...]} +// deleteScene params: {sceneId} result: {ok: bool} + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace pipedal { + +class MixerApi; +class MixerEngine; + +/// Unix domain socket IPC server that dispatches JSON messages to MixerApi. +class MixerIpcServer { +public: + /// Callback signature: clientConnected, clientDisconnected + using ConnectionCallback = std::function; + using MessageCallback = std::function; + + MixerIpcServer(); + ~MixerIpcServer(); + + // Disable copy + MixerIpcServer(const MixerIpcServer&) = delete; + MixerIpcServer& operator=(const MixerIpcServer&) = delete; + + /// Set the MixerApi instance to dispatch to. + void setMixerApi(MixerApi* api) { mixerApi_ = api; } + + /// Set the MixerEngine instance directly (for push messages / VU). + void setMixerEngine(MixerEngine* engine) { mixerEngine_ = engine; } + + /// Start the IPC server on the given socket path. + /// Returns true on success. + bool start(const std::string& socketPath = "/tmp/oplabs-mixer.sock"); + + /// Stop the IPC server and close all connections. + void stop(); + + /// Check if the server is running. + bool isRunning() const { return running_.load(); } + + /// Broadcast a push message to all connected clients. + void broadcast(const std::string& jsonMessage); + + /// Set callback for incoming messages (for logging/monitoring). + void setMessageCallback(MessageCallback cb) { messageCallback_ = std::move(cb); } + +private: + MixerApi* mixerApi_ = nullptr; + MixerEngine* mixerEngine_ = nullptr; + + std::atomic running_{false}; + int serverFd_ = -1; + std::string socketPath_; + std::thread acceptThread_; + + // Per-client state + struct ClientConnection { + int fd = -1; + bool active = false; + std::vector readBuffer; + uint32_t expectedLength = 0; + bool readingHeader = true; + }; + + std::map> clients_; + int nextClientId_ = 1; + + MessageCallback messageCallback_; + + // Accept loop (runs in its own thread) + void acceptLoop(); + + // Handle a single client connection + void handleClient(int clientFd); + + // Read and accumulate data from a client + bool readFromClient(ClientConnection& conn); + + // Process a complete JSON message + void processMessage(ClientConnection& conn, const std::string& jsonMessage); + + // Send a JSON response to a specific client + bool sendResponse(int clientFd, const std::string& jsonResponse); + + // Convenience: send a length-prefixed frame + bool sendFrame(int fd, const std::string& jsonPayload); + + // Dispatch a method call to MixerApi and return JSON result + std::string dispatchMethod(const std::string& method, const std::string& paramsJson); + + // All connected client file descriptors + std::vector connectedClientFds() const; +}; + +} // namespace pipedal diff --git a/daemon/oplabs-mixer-daemon.service.in b/daemon/oplabs-mixer-daemon.service.in new file mode 100644 index 0000000..f3ade5e --- /dev/null +++ b/daemon/oplabs-mixer-daemon.service.in @@ -0,0 +1,25 @@ +[Unit] +Description=OPLabs Mixer Daemon +Documentation=https://git.ourpad.casa/oplabs/oplabs-mixer-app +After=network.target sound.target +Wants=jack.service + +[Service] +Type=simple +User=oplabs +ExecStart=/usr/bin/oplabs-mixer-daemon \ + --socket-path /tmp/oplabs-mixer.sock \ + --sample-rate 48000 \ + --buffer-size 512 \ + --input-channels 8 \ + --output-channels 8 +Restart=on-failure +RestartSec=5 +LimitNOFILE=8192 +Nice=-10 + +# JACK-specific: wait for JACK to be ready +ExecStartPre=/bin/sh -c 'while ! jack_wait -c 2>/dev/null; do sleep 1; done' + +[Install] +WantedBy=multi-user.target diff --git a/frontend/dist/assets/index-58I2yFEM.css b/frontend/dist/assets/index-58I2yFEM.css deleted file mode 100644 index cdeeb58..0000000 --- a/frontend/dist/assets/index-58I2yFEM.css +++ /dev/null @@ -1 +0,0 @@ -.instrument-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:4px;border:1px solid;font-size:.7rem;font-weight:600;letter-spacing:.3px;white-space:nowrap;transition:opacity .2s;-webkit-user-select:none;user-select:none}.instrument-badge:hover{opacity:.85}.instrument-badge[data-size=small]{font-size:.6rem;padding:1px 5px;gap:3px}.instrument-badge[data-size=large]{font-size:.85rem;padding:4px 12px;gap:6px}.instrument-icon{font-size:.8em;line-height:1}.instrument-name{line-height:1}.level-meter{display:flex;flex-direction:column;align-items:center;gap:2px;--meter-green: #4caf50;--meter-yellow: #ff9800;--meter-red: #f44336}.level-meter.mini{gap:1px}.level-meter-stereo-pair{display:flex;gap:2px;flex:1}.level-meter-channel{display:flex;flex-direction:column;align-items:center;gap:1px;width:14px}.level-meter-channel.mini{width:8px}.level-meter-side-label{font-size:.55rem;color:var(--text-dim);font-weight:700;text-transform:uppercase;letter-spacing:.5px}.level-meter-bar-track{position:relative;width:100%;flex:1;min-height:60px;background:#00000080;border-radius:2px;border:1px solid var(--border);overflow:hidden}.level-meter.mini .level-meter-bar-track{min-height:30px}.level-meter-bar-fill{position:absolute;bottom:0;left:0;right:0;transition:height .05s linear;border-radius:1px}.level-meter-peak{position:absolute;left:0;right:0;height:2px;background:#fff;border-radius:1px;transition:bottom .15s ease-out;z-index:2}.level-meter-tick{position:absolute;left:0;right:0;height:1px;background:#ffffff26;z-index:1}.level-meter-tick.mark-yellow{background:#ff98004d}.level-meter-tick.mark-green{background:#4caf5033}.level-meter-label{font-size:.6rem;color:var(--text-dim);text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:60px}.level-meter-db-values{display:flex;gap:4px;font-size:.6rem;font-family:monospace;color:var(--text-dim)}.level-meter-db-values .hot{color:var(--meter-red);font-weight:700}.channel-strip{display:flex;flex-direction:column;align-items:center;gap:6px;padding:10px 8px;background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-top:3px solid #666;border-radius:var(--radius, 8px);min-width:80px;max-width:100px;transition:border-top-color .3s,box-shadow .2s}.channel-strip:hover{box-shadow:0 2px 12px #0000004d}.channel-header{display:flex;flex-direction:column;align-items:center;gap:3px;width:100%}.channel-label{font-size:.7rem;font-weight:600;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;color:var(--text, #eaeaea)}.channel-mute-solo{display:flex;gap:3px;width:100%;justify-content:center}.channel-btn{width:28px;height:22px;border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.65rem;font-weight:700;cursor:pointer;transition:all .15s;background:var(--bg, #1a1a2e);color:var(--text-dim, #9e9e9e);-webkit-user-select:none;user-select:none;line-height:1}.channel-btn.mute.active{background:var(--error, #f44336);color:#fff;border-color:var(--error, #f44336)}.channel-btn.solo.active{background:var(--warning, #ff9800);color:#000;border-color:var(--warning, #ff9800)}.channel-btn:hover{opacity:.85}.channel-meter-section{width:100%;display:flex;justify-content:center;flex:1;min-height:60px}.channel-pan{width:100%;display:flex;flex-direction:column;align-items:center;gap:2px}.channel-pan-label{font-size:.55rem;text-transform:uppercase;color:var(--text-dim, #9e9e9e);letter-spacing:.5px}.channel-pan-control{display:flex;align-items:center;gap:3px;width:100%}.channel-pan-slider{flex:1;-webkit-appearance:none;-moz-appearance:none;appearance:none;height:4px;background:var(--border, #2a2a4a);border-radius:2px;outline:none;cursor:pointer}.channel-pan-slider::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:10px;height:10px;border-radius:50%;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);cursor:pointer}.channel-pan-slider::-moz-range-thumb{width:10px;height:10px;border-radius:50%;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);cursor:pointer}.channel-pan-value{font-size:.55rem;font-family:monospace;color:var(--text-dim, #9e9e9e);min-width:20px;text-align:center}.channel-fader-section{display:flex;flex-direction:column;align-items:center;gap:3px;width:100%}.channel-fader{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:100px;background:linear-gradient(to top,var(--bg, #1a1a2e) 0%,var(--surface-alt, #0f3460) 75%,#4caf50 85%,#ff9800 95%,#f44336 100%);border-radius:4px;outline:none;cursor:pointer;border:1px solid var(--border, #2a2a4a);writing-mode:vertical-lr;direction:rtl}.channel-fader::-webkit-slider-runnable-track{height:100px;border-radius:3px}.channel-fader::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:18px;height:12px;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer;box-shadow:0 1px 3px #0006;margin-left:-3px}.channel-fader::-moz-range-track{height:100px;border-radius:3px}.channel-fader::-moz-range-thumb{width:18px;height:12px;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer;box-shadow:0 1px 3px #0006}.channel-fader-readout{font-size:.6rem;font-family:monospace;color:var(--text-dim, #9e9e9e);text-align:center}.channel-instrument-selector{width:100%}.channel-instrument-select{width:100%;padding:3px 4px;background:var(--bg, #1a1a2e);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.6rem;cursor:pointer;outline:none}.channel-instrument-select:focus{border-color:var(--channel-accent, #666)}.channel-instrument-select option{background:var(--bg, #1a1a2e);color:var(--text, #eaeaea)}.bus-strip{display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-radius:var(--radius, 8px)}.bus-master-section{display:flex;align-items:center;gap:12px;padding-bottom:8px}.bus-master-header{display:flex;flex-direction:column;align-items:center;gap:4px;min-width:50px}.bus-master-label{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--text, #eaeaea)}.bus-master-meter{flex:1;max-width:60px}.bus-master-fader{flex:1;max-width:120px}.bus-btn{width:24px;height:20px;border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.6rem;font-weight:700;cursor:pointer;transition:all .15s;background:var(--bg, #1a1a2e);color:var(--text-dim, #9e9e9e);-webkit-user-select:none;user-select:none;line-height:1;text-align:center}.bus-btn.mute.active{background:var(--error, #f44336);color:#fff;border-color:var(--error, #f44336)}.bus-btn.mini{width:18px;height:16px;font-size:.5rem}.bus-btn:hover{opacity:.85}.bus-divider{height:1px;background:var(--border, #2a2a4a);margin:0 -4px}.bus-channels{display:flex;gap:6px;overflow-x:auto;padding-bottom:4px}.bus-channel{display:flex;flex-direction:column;align-items:center;gap:3px;min-width:36px;max-width:44px;padding:6px 4px;background:var(--bg, #1a1a2e);border-radius:4px;border:1px solid var(--border, #2a2a4a);flex-shrink:0}.bus-channel-label{font-size:.55rem;font-weight:700;color:var(--text-dim, #9e9e9e);text-align:center}.bus-channel-meter{width:100%;height:30px;display:flex;justify-content:center}.bus-channel-fader{width:100%}.bus-channel-db{font-size:.45rem;font-family:monospace;color:var(--text-dim, #9e9e9e);text-align:center}.bus-fader{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:6px;background:var(--border, #2a2a4a);border-radius:3px;outline:none;cursor:pointer;border:none}.bus-fader::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:12px;height:14px;background:#e94560;border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer}.bus-fader::-moz-range-thumb{width:12px;height:14px;background:#e94560;border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer}.bus-fader.mini{height:4px}.bus-fader.mini::-webkit-slider-thumb{width:8px;height:10px}.bus-fader.mini::-moz-range-thumb{width:8px;height:10px}.scene-manager-overlay{position:fixed;top:0;right:0;width:360px;height:100vh;background:var(--surface, #16213e);border-left:1px solid var(--border, #2a2a4a);z-index:200;display:flex;flex-direction:column;box-shadow:-4px 0 20px #0006;animation:scene-slide-in .2s ease-out}@keyframes scene-slide-in{0%{transform:translate(100%)}to{transform:translate(0)}}.scene-manager-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--border, #2a2a4a)}.scene-manager-header h2{font-size:1rem;font-weight:600;color:var(--text, #eaeaea);margin:0}.scene-manager-count{font-size:.7rem;background:var(--surface-alt, #0f3460);color:var(--text-dim, #9e9e9e);padding:1px 7px;border-radius:10px;margin-left:8px}.scene-close-btn{background:transparent;border:none;color:var(--text-dim, #9e9e9e);font-size:1.2rem;cursor:pointer;padding:4px 8px;border-radius:4px;line-height:1}.scene-close-btn:hover{background:#ffffff14;color:var(--text, #eaeaea)}.scene-list{flex:1;overflow-y:auto;padding:8px}.scene-list-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;text-align:center;color:var(--text-dim, #9e9e9e);font-size:.85rem;gap:8px}.scene-list-loading{display:flex;align-items:center;justify-content:center;padding:40px;color:var(--text-dim, #9e9e9e);font-size:.85rem}.scene-card{background:var(--bg, #1a1a2e);border-radius:var(--radius, 8px);margin-bottom:8px;border:1px solid var(--border, #2a2a4a);overflow:hidden;transition:border-color .2s}.scene-card:hover{border-color:var(--accent, #e94560)}.scene-card-content{display:flex;align-items:center;padding:10px 12px;gap:10px;cursor:pointer}.scene-card-content:hover{background:#e945600a}.scene-card-name{flex:1;font-size:.9rem;font-weight:500;color:var(--text, #eaeaea);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.scene-card-midi{font-size:.65rem;color:var(--text-dim, #9e9e9e);background:var(--surface-alt, #0f3460);padding:2px 6px;border-radius:4px;font-weight:500}.scene-card-actions{display:flex;gap:4px}.scene-card-btn{background:transparent;border:none;color:var(--text-dim, #9e9e9e);padding:4px 8px;border-radius:4px;cursor:pointer;font-size:.75rem;transition:all .15s}.scene-card-btn:hover{background:#ffffff14;color:var(--text, #eaeaea)}.scene-card-btn.delete:hover{background:#f4433626;color:var(--error, #f44336)}.scene-card-btn.load:hover{background:#4caf5026;color:var(--success, #4caf50)}.scene-card-btn.recall{font-weight:600}.scene-card-btn.recall:hover{background:#e9456026;color:var(--accent, #e94560)}.scene-save-form{padding:12px 16px;border-top:1px solid var(--border, #2a2a4a);display:flex;flex-direction:column;gap:8px}.scene-save-row{display:flex;gap:8px;align-items:center}.scene-name-input{flex:1;background:var(--bg, #1a1a2e);border:1px solid var(--border, #2a2a4a);border-radius:6px;padding:8px 10px;color:var(--text, #eaeaea);font-size:.85rem;outline:none;transition:border-color .2s}.scene-name-input:focus{border-color:var(--accent, #e94560)}.scene-name-input::placeholder{color:var(--text-dim, #9e9e9e)}.scene-save-btn{background:var(--accent, #e94560);color:#fff;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;font-size:.8rem;font-weight:500;white-space:nowrap;transition:opacity .15s}.scene-save-btn:hover{opacity:.85}.scene-save-btn:disabled{opacity:.4;cursor:not-allowed}.scene-midi-input-group{display:flex;align-items:center;gap:6px}.scene-midi-label{font-size:.7rem;color:var(--text-dim, #9e9e9e);white-space:nowrap}.scene-midi-input{width:48px;background:var(--bg, #1a1a2e);border:1px solid var(--border, #2a2a4a);border-radius:4px;padding:4px 6px;color:var(--text, #eaeaea);font-size:.8rem;text-align:center;outline:none}.scene-midi-input:focus{border-color:var(--accent, #e94560)}.scene-error{padding:8px 16px;background:#f443361a;color:var(--error, #f44336);font-size:.75rem;border-top:1px solid rgba(244,67,54,.2)}.scene-confirm-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:#00000080;z-index:300;display:flex;align-items:center;justify-content:center}.scene-confirm-dialog{background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-radius:var(--radius, 8px);padding:20px 24px;max-width:320px;box-shadow:0 8px 32px #0006}.scene-confirm-dialog p{font-size:.9rem;color:var(--text, #eaeaea);margin-bottom:16px;line-height:1.4}.scene-confirm-actions{display:flex;gap:8px;justify-content:flex-end}.scene-confirm-cancel{background:transparent;border:1px solid var(--border, #2a2a4a);color:var(--text-dim, #9e9e9e);padding:6px 14px;border-radius:6px;cursor:pointer;font-size:.8rem}.scene-confirm-cancel:hover{background:#ffffff0d}.scene-confirm-delete{background:var(--error, #f44336);border:none;color:#fff;padding:6px 14px;border-radius:6px;cursor:pointer;font-size:.8rem;font-weight:500}.scene-confirm-delete:hover{opacity:.85}.scene-recalling{opacity:.6;pointer-events:none}.scene-recalled-flash{animation:scene-flash .6s ease-out}@keyframes scene-flash{0%{border-color:var(--success, #4caf50);box-shadow:0 0 8px #4caf504d}to{border-color:var(--border, #2a2a4a);box-shadow:none}}.mixer-page{display:flex;flex-direction:column;min-height:100vh;background:var(--bg, #1a1a2e);max-width:100%!important}.mixer-header{display:flex;align-items:center;justify-content:space-between;padding:12px 20px;background:var(--surface, #16213e);border-bottom:1px solid var(--border, #2a2a4a);gap:12px;flex-wrap:wrap;position:sticky;top:0;z-index:100}.mixer-header-left{display:flex;align-items:center;gap:16px}.mixer-title{font-size:1.1rem;font-weight:700;color:var(--text, #eaeaea);letter-spacing:.3px}.mixer-header-center{display:flex;align-items:center;gap:12px}.mixer-pedalboard-name{font-size:.8rem;color:var(--accent, #e94560);background:#e945601a;padding:3px 10px;border-radius:var(--radius, 8px)}.mixer-ws-indicator{font-size:.7rem;padding:3px 8px;border-radius:4px;font-weight:500}.mixer-ws-indicator.ready{color:var(--success, #4caf50);background:#4caf501f}.mixer-ws-indicator.pending{color:var(--warning, #ff9800);background:#ff98001f}.mixer-header-right{display:flex;align-items:center;gap:12px}.mixer-update-time{font-size:.7rem;color:var(--text-dim, #9e9e9e)}.mixer-refresh-btn{background:var(--accent, #e94560);color:#fff;border:none;padding:6px 14px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.8rem;font-weight:500;transition:opacity .2s}.mixer-refresh-btn:hover{opacity:.85}.mixer-refresh-btn.large{padding:10px 24px;font-size:.95rem;margin-top:16px}.mixer-scenes-btn{display:flex;align-items:center;gap:6px;background:var(--surface-alt, #0f3460);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);padding:6px 12px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.8rem;font-weight:500;transition:all .2s}.mixer-scenes-btn:hover{border-color:var(--accent, #e94560);background:#e945601a}.mixer-scenes-btn.active{border-color:var(--accent, #e94560);background:#e9456026;color:var(--accent, #e94560)}.mixer-scenes-count{font-size:.65rem;background:var(--accent, #e94560);color:#fff;padding:1px 6px;border-radius:8px;font-weight:600}.mixer-content{flex:1;padding:20px;display:flex;flex-direction:column;gap:24px}.mixer-section-header{display:flex;align-items:center;gap:8px;margin-bottom:4px}.mixer-section-header h2{font-size:.95rem;font-weight:600;color:var(--text, #eaeaea)}.mixer-count{font-size:.7rem;background:var(--surface-alt, #0f3460);color:var(--text-dim, #9e9e9e);padding:1px 7px;border-radius:10px}.mixer-channels-grid{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}.mixer-add-channel{display:flex;align-items:center}.mixer-add-btn{width:40px;height:40px;border-radius:50%;border:2px dashed var(--border, #2a2a4a);background:transparent;color:var(--text-dim, #9e9e9e);font-size:1.3rem;cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center}.mixer-add-btn:hover{border-color:var(--accent, #e94560);color:var(--accent, #e94560);background:#e9456014}.mixer-buses-grid{display:flex;flex-direction:column;gap:10px}.mixer-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:80px 24px;text-align:center;color:var(--text-dim, #9e9e9e);flex:1}.mixer-empty-icon{font-size:3rem;margin-bottom:16px;opacity:.6}.mixer-empty h2{font-size:1.2rem;color:var(--text, #eaeaea);margin-bottom:8px}.mixer-empty p{font-size:.9rem;max-width:400px;line-height:1.5;margin-bottom:4px}.mixer-empty-hint{font-size:.8rem!important;opacity:.7;margin-top:8px!important}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}:root{--bg: #1a1a2e;--surface: #16213e;--surface-alt: #0f3460;--accent: #e94560;--text: #eaeaea;--text-dim: #9e9e9e;--border: #2a2a4a;--success: #4caf50;--warning: #ff9800;--error: #f44336;--radius: 8px}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;background:var(--bg);color:var(--text);line-height:1.5;min-height:100vh}.app{display:flex;flex-direction:column;min-height:100vh}.connection-status{display:flex;flex-direction:column;gap:4px}.status-indicator{display:flex;align-items:center;gap:8px}.status-dot{width:10px;height:10px;border-radius:50%;display:inline-block}.status-label{font-size:.85rem;color:var(--text-dim)}.status-error{display:flex;align-items:center;gap:8px;font-size:.8rem;color:var(--error)}.retry-btn{background:transparent;border:1px solid var(--error);color:var(--error);padding:2px 8px;border-radius:4px;cursor:pointer;font-size:.75rem}.retry-btn:hover{background:var(--error);color:#fff}.app-footer{display:flex;justify-content:space-between;padding:12px 24px;background:var(--surface);border-top:1px solid var(--border);font-size:.75rem;color:var(--text-dim)} diff --git a/frontend/dist/assets/index-BixTWz89.js b/frontend/dist/assets/index-BixTWz89.js new file mode 100644 index 0000000..399b30f --- /dev/null +++ b/frontend/dist/assets/index-BixTWz89.js @@ -0,0 +1,42 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const o of l)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(l){const o={};return l.integrity&&(o.integrity=l.integrity),l.referrerPolicy&&(o.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?o.credentials="include":l.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(l){if(l.ep)return;l.ep=!0;const o=n(l);fetch(l.href,o)}})();function yc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var nu={exports:{}},cl={},ru={exports:{}},$={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var lr=Symbol.for("react.element"),gc=Symbol.for("react.portal"),wc=Symbol.for("react.fragment"),xc=Symbol.for("react.strict_mode"),kc=Symbol.for("react.profiler"),Sc=Symbol.for("react.provider"),Nc=Symbol.for("react.context"),Cc=Symbol.for("react.forward_ref"),Ec=Symbol.for("react.suspense"),jc=Symbol.for("react.memo"),Pc=Symbol.for("react.lazy"),Bs=Symbol.iterator;function _c(e){return e===null||typeof e!="object"?null:(e=Bs&&e[Bs]||e["@@iterator"],typeof e=="function"?e:null)}var lu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ou=Object.assign,su={};function hn(e,t,n){this.props=e,this.context=t,this.refs=su,this.updater=n||lu}hn.prototype.isReactComponent={};hn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};hn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function iu(){}iu.prototype=hn.prototype;function Yo(e,t,n){this.props=e,this.context=t,this.refs=su,this.updater=n||lu}var Xo=Yo.prototype=new iu;Xo.constructor=Yo;ou(Xo,hn.prototype);Xo.isPureReactComponent=!0;var Hs=Array.isArray,uu=Object.prototype.hasOwnProperty,Jo={current:null},au={key:!0,ref:!0,__self:!0,__source:!0};function cu(e,t,n){var r,l={},o=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(o=""+t.key),t)uu.call(t,r)&&!au.hasOwnProperty(r)&&(l[r]=t[r]);var i=arguments.length-2;if(i===1)l.children=n;else if(1>>1,q=P[Q];if(0>>1;Ql(jl,I))Ntl(ar,jl)?(P[Q]=ar,P[Nt]=I,Q=Nt):(P[Q]=jl,P[O]=I,Q=O);else if(Ntl(ar,I))P[Q]=ar,P[Nt]=I,Q=Nt;else break e}}return R}function l(P,R){var I=P.sortIndex-R.sortIndex;return I!==0?I:P.id-R.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var s=Date,i=s.now();e.unstable_now=function(){return s.now()-i}}var u=[],f=[],y=1,m=null,p=3,v=!1,g=!1,w=!1,M=typeof setTimeout=="function"?setTimeout:null,d=typeof clearTimeout=="function"?clearTimeout:null,c=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function h(P){for(var R=n(f);R!==null;){if(R.callback===null)r(f);else if(R.startTime<=P)r(f),R.sortIndex=R.expirationTime,t(u,R);else break;R=n(f)}}function x(P){if(w=!1,h(P),!g)if(n(u)!==null)g=!0,Qe(N);else{var R=n(f);R!==null&&Ke(x,R.startTime-P)}}function N(P,R){g=!1,w&&(w=!1,d(T),T=-1),v=!0;var I=p;try{for(h(R),m=n(u);m!==null&&(!(m.expirationTime>R)||P&&!L());){var Q=m.callback;if(typeof Q=="function"){m.callback=null,p=m.priorityLevel;var q=Q(m.expirationTime<=R);R=e.unstable_now(),typeof q=="function"?m.callback=q:m===n(u)&&r(u),h(R)}else r(u);m=n(u)}if(m!==null)var Vt=!0;else{var O=n(f);O!==null&&Ke(x,O.startTime-R),Vt=!1}return Vt}finally{m=null,p=I,v=!1}}var C=!1,E=null,T=-1,V=5,z=-1;function L(){return!(e.unstable_now()-zP||125Q?(P.sortIndex=I,t(f,P),n(u)===null&&P===n(f)&&(w?(d(T),T=-1):w=!0,Ke(x,I-Q))):(P.sortIndex=q,t(u,P),g||v||(g=!0,Qe(N))),P},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(P){var R=p;return function(){var I=p;p=R;try{return P.apply(this,arguments)}finally{p=I}}}})(vu);hu.exports=vu;var Uc=hu.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Vc=k,Ce=Uc;function S(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),eo=Object.prototype.hasOwnProperty,Ac=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Qs={},Ks={};function Bc(e){return eo.call(Ks,e)?!0:eo.call(Qs,e)?!1:Ac.test(e)?Ks[e]=!0:(Qs[e]=!0,!1)}function Hc(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Wc(e,t,n,r){if(t===null||typeof t>"u"||Hc(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function he(e,t,n,r,l,o,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=s}var ie={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ie[e]=new he(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ie[t]=new he(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ie[e]=new he(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ie[e]=new he(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ie[e]=new he(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ie[e]=new he(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ie[e]=new he(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ie[e]=new he(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ie[e]=new he(e,5,!1,e.toLowerCase(),null,!1,!1)});var qo=/[\-:]([a-z])/g;function bo(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(qo,bo);ie[t]=new he(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(qo,bo);ie[t]=new he(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(qo,bo);ie[t]=new he(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ie[e]=new he(e,1,!1,e.toLowerCase(),null,!1,!1)});ie.xlinkHref=new he("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ie[e]=new he(e,1,!1,e.toLowerCase(),null,!0,!0)});function es(e,t,n,r){var l=ie.hasOwnProperty(t)?ie[t]:null;(l!==null?l.type!==0:r||!(2i||l[s]!==o[i]){var u=` +`+l[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=i);break}}}finally{Tl=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?jn(e):""}function Qc(e){switch(e.tag){case 5:return jn(e.type);case 16:return jn("Lazy");case 13:return jn("Suspense");case 19:return jn("SuspenseList");case 0:case 2:case 15:return e=Ml(e.type,!1),e;case 11:return e=Ml(e.type.render,!1),e;case 1:return e=Ml(e.type,!0),e;default:return""}}function lo(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Wt:return"Fragment";case Ht:return"Portal";case to:return"Profiler";case ts:return"StrictMode";case no:return"Suspense";case ro:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case wu:return(e.displayName||"Context")+".Consumer";case gu:return(e._context.displayName||"Context")+".Provider";case ns:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case rs:return t=e.displayName||null,t!==null?t:lo(e.type)||"Memo";case lt:t=e._payload,e=e._init;try{return lo(e(t))}catch{}}return null}function Kc(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return lo(t);case 8:return t===ts?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function gt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ku(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Gc(e){var t=ku(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(s){r=""+s,o.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function dr(e){e._valueTracker||(e._valueTracker=Gc(e))}function Su(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ku(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Ur(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function oo(e,t){var n=t.checked;return Y({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Ys(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=gt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Nu(e,t){t=t.checked,t!=null&&es(e,"checked",t,!1)}function so(e,t){Nu(e,t);var n=gt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?io(e,t.type,n):t.hasOwnProperty("defaultValue")&&io(e,t.type,gt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Xs(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function io(e,t,n){(t!=="number"||Ur(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Pn=Array.isArray;function tn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=pr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function An(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ln={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Yc=["Webkit","ms","Moz","O"];Object.keys(Ln).forEach(function(e){Yc.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ln[t]=Ln[e]})});function Pu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ln.hasOwnProperty(e)&&Ln[e]?(""+t).trim():t+"px"}function _u(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Pu(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Xc=Y({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function co(e,t){if(t){if(Xc[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(S(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(S(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(S(61))}if(t.style!=null&&typeof t.style!="object")throw Error(S(62))}}function fo(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var po=null;function ls(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var mo=null,nn=null,rn=null;function qs(e){if(e=ir(e)){if(typeof mo!="function")throw Error(S(280));var t=e.stateNode;t&&(t=hl(t),mo(e.stateNode,e.type,t))}}function Tu(e){nn?rn?rn.push(e):rn=[e]:nn=e}function Mu(){if(nn){var e=nn,t=rn;if(rn=nn=null,qs(e),t)for(e=0;e>>=0,e===0?32:31-(sf(e)/uf|0)|0}var mr=64,hr=4194304;function _n(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Hr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,o=e.pingedLanes,s=n&268435455;if(s!==0){var i=s&~l;i!==0?r=_n(i):(o&=s,o!==0&&(r=_n(o)))}else s=n&~l,s!==0?r=_n(s):o!==0&&(r=_n(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,o=t&-t,l>=o||l===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function or(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-De(t),e[t]=n}function df(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=zn),ii=" ",ui=!1;function Ju(e,t){switch(e){case"keyup":return Vf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Zu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Qt=!1;function Bf(e,t){switch(e){case"compositionend":return Zu(t);case"keypress":return t.which!==32?null:(ui=!0,ii);case"textInput":return e=t.data,e===ii&&ui?null:e;default:return null}}function Hf(e,t){if(Qt)return e==="compositionend"||!ds&&Ju(e,t)?(e=Yu(),Mr=as=ut=null,Qt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=di(n)}}function ta(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ta(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function na(){for(var e=window,t=Ur();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ur(e.document)}return t}function ps(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function qf(e){var t=na(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ta(n.ownerDocument.documentElement,n)){if(r!==null&&ps(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=r.end===void 0?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=pi(n,o);var s=pi(n,r);l&&s&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Kt=null,xo=null,On=null,ko=!1;function mi(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ko||Kt==null||Kt!==Ur(r)||(r=Kt,"selectionStart"in r&&ps(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),On&&Gn(On,r)||(On=r,r=Kr(xo,"onSelect"),0Xt||(e.current=Po[Xt],Po[Xt]=null,Xt--)}function A(e,t){Xt++,Po[Xt]=e.current,e.current=t}var wt={},fe=kt(wt),ge=kt(!1),zt=wt;function an(e,t){var n=e.type.contextTypes;if(!n)return wt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},o;for(o in n)l[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function we(e){return e=e.childContextTypes,e!=null}function Yr(){H(ge),H(fe)}function ki(e,t,n){if(fe.current!==wt)throw Error(S(168));A(fe,t),A(ge,n)}function fa(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(S(108,Kc(e)||"Unknown",l));return Y({},n,r)}function Xr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||wt,zt=fe.current,A(fe,e),A(ge,ge.current),!0}function Si(e,t,n){var r=e.stateNode;if(!r)throw Error(S(169));n?(e=fa(e,t,zt),r.__reactInternalMemoizedMergedChildContext=e,H(ge),H(fe),A(fe,e)):H(ge),A(ge,n)}var Ye=null,vl=!1,Wl=!1;function da(e){Ye===null?Ye=[e]:Ye.push(e)}function cd(e){vl=!0,da(e)}function St(){if(!Wl&&Ye!==null){Wl=!0;var e=0,t=U;try{var n=Ye;for(U=1;e>=s,l-=s,Xe=1<<32-De(t)+l|n<T?(V=E,E=null):V=E.sibling;var z=p(d,E,h[T],x);if(z===null){E===null&&(E=V);break}e&&E&&z.alternate===null&&t(d,E),c=o(z,c,T),C===null?N=z:C.sibling=z,C=z,E=V}if(T===h.length)return n(d,E),W&&Et(d,T),N;if(E===null){for(;TT?(V=E,E=null):V=E.sibling;var L=p(d,E,z.value,x);if(L===null){E===null&&(E=V);break}e&&E&&L.alternate===null&&t(d,E),c=o(L,c,T),C===null?N=L:C.sibling=L,C=L,E=V}if(z.done)return n(d,E),W&&Et(d,T),N;if(E===null){for(;!z.done;T++,z=h.next())z=m(d,z.value,x),z!==null&&(c=o(z,c,T),C===null?N=z:C.sibling=z,C=z);return W&&Et(d,T),N}for(E=r(d,E);!z.done;T++,z=h.next())z=v(E,d,T,z.value,x),z!==null&&(e&&z.alternate!==null&&E.delete(z.key===null?T:z.key),c=o(z,c,T),C===null?N=z:C.sibling=z,C=z);return e&&E.forEach(function(j){return t(d,j)}),W&&Et(d,T),N}function M(d,c,h,x){if(typeof h=="object"&&h!==null&&h.type===Wt&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case fr:e:{for(var N=h.key,C=c;C!==null;){if(C.key===N){if(N=h.type,N===Wt){if(C.tag===7){n(d,C.sibling),c=l(C,h.props.children),c.return=d,d=c;break e}}else if(C.elementType===N||typeof N=="object"&&N!==null&&N.$$typeof===lt&&Ei(N)===C.type){n(d,C.sibling),c=l(C,h.props),c.ref=Nn(d,C,h),c.return=d,d=c;break e}n(d,C);break}else t(d,C);C=C.sibling}h.type===Wt?(c=Rt(h.props.children,d.mode,x,h.key),c.return=d,d=c):(x=Fr(h.type,h.key,h.props,null,d.mode,x),x.ref=Nn(d,c,h),x.return=d,d=x)}return s(d);case Ht:e:{for(C=h.key;c!==null;){if(c.key===C)if(c.tag===4&&c.stateNode.containerInfo===h.containerInfo&&c.stateNode.implementation===h.implementation){n(d,c.sibling),c=l(c,h.children||[]),c.return=d,d=c;break e}else{n(d,c);break}else t(d,c);c=c.sibling}c=ql(h,d.mode,x),c.return=d,d=c}return s(d);case lt:return C=h._init,M(d,c,C(h._payload),x)}if(Pn(h))return g(d,c,h,x);if(gn(h))return w(d,c,h,x);Sr(d,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,c!==null&&c.tag===6?(n(d,c.sibling),c=l(c,h),c.return=d,d=c):(n(d,c),c=Zl(h,d.mode,x),c.return=d,d=c),s(d)):n(d,c)}return M}var fn=va(!0),ya=va(!1),qr=kt(null),br=null,qt=null,ys=null;function gs(){ys=qt=br=null}function ws(e){var t=qr.current;H(qr),e._currentValue=t}function Mo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function on(e,t){br=e,ys=qt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ye=!0),e.firstContext=null)}function Le(e){var t=e._currentValue;if(ys!==e)if(e={context:e,memoizedValue:t,next:null},qt===null){if(br===null)throw Error(S(308));qt=e,br.dependencies={lanes:0,firstContext:e}}else qt=qt.next=e;return t}var _t=null;function xs(e){_t===null?_t=[e]:_t.push(e)}function ga(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,xs(t)):(n.next=l.next,l.next=n),t.interleaved=n,et(e,r)}function et(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var ot=!1;function ks(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function wa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ze(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function mt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,F&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,et(e,n)}return l=r.interleaved,l===null?(t.next=t,xs(r)):(t.next=l.next,l.next=t),r.interleaved=t,et(e,n)}function Rr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ss(e,n)}}function ji(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var s={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?l=o=s:o=o.next=s,n=n.next}while(n!==null);o===null?l=o=t:o=o.next=t}else l=o=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function el(e,t,n,r){var l=e.updateQueue;ot=!1;var o=l.firstBaseUpdate,s=l.lastBaseUpdate,i=l.shared.pending;if(i!==null){l.shared.pending=null;var u=i,f=u.next;u.next=null,s===null?o=f:s.next=f,s=u;var y=e.alternate;y!==null&&(y=y.updateQueue,i=y.lastBaseUpdate,i!==s&&(i===null?y.firstBaseUpdate=f:i.next=f,y.lastBaseUpdate=u))}if(o!==null){var m=l.baseState;s=0,y=f=u=null,i=o;do{var p=i.lane,v=i.eventTime;if((r&p)===p){y!==null&&(y=y.next={eventTime:v,lane:0,tag:i.tag,payload:i.payload,callback:i.callback,next:null});e:{var g=e,w=i;switch(p=t,v=n,w.tag){case 1:if(g=w.payload,typeof g=="function"){m=g.call(v,m,p);break e}m=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=w.payload,p=typeof g=="function"?g.call(v,m,p):g,p==null)break e;m=Y({},m,p);break e;case 2:ot=!0}}i.callback!==null&&i.lane!==0&&(e.flags|=64,p=l.effects,p===null?l.effects=[i]:p.push(i))}else v={eventTime:v,lane:p,tag:i.tag,payload:i.payload,callback:i.callback,next:null},y===null?(f=y=v,u=m):y=y.next=v,s|=p;if(i=i.next,i===null){if(i=l.shared.pending,i===null)break;p=i,i=p.next,p.next=null,l.lastBaseUpdate=p,l.shared.pending=null}}while(!0);if(y===null&&(u=m),l.baseState=u,l.firstBaseUpdate=f,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do s|=l.lane,l=l.next;while(l!==t)}else o===null&&(l.shared.lanes=0);$t|=s,e.lanes=s,e.memoizedState=m}}function Pi(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Kl.transition;Kl.transition={};try{e(!1),t()}finally{U=n,Kl.transition=r}}function $a(){return Re().memoizedState}function md(e,t,n){var r=vt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Da(e))Fa(t,n);else if(n=ga(e,t,n,r),n!==null){var l=pe();Fe(n,e,r,l),Ua(n,t,r)}}function hd(e,t,n){var r=vt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Da(e))Fa(t,l);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var s=t.lastRenderedState,i=o(s,n);if(l.hasEagerState=!0,l.eagerState=i,Ue(i,s)){var u=t.interleaved;u===null?(l.next=l,xs(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=ga(e,t,l,r),n!==null&&(l=pe(),Fe(n,e,r,l),Ua(n,t,r))}}function Da(e){var t=e.alternate;return e===G||t!==null&&t===G}function Fa(e,t){$n=nl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ua(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ss(e,n)}}var rl={readContext:Le,useCallback:ue,useContext:ue,useEffect:ue,useImperativeHandle:ue,useInsertionEffect:ue,useLayoutEffect:ue,useMemo:ue,useReducer:ue,useRef:ue,useState:ue,useDebugValue:ue,useDeferredValue:ue,useTransition:ue,useMutableSource:ue,useSyncExternalStore:ue,useId:ue,unstable_isNewReconciler:!1},vd={readContext:Le,useCallback:function(e,t){return Ae().memoizedState=[e,t===void 0?null:t],e},useContext:Le,useEffect:Ti,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ir(4194308,4,La.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ir(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ir(4,2,e,t)},useMemo:function(e,t){var n=Ae();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ae();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=md.bind(null,G,e),[r.memoizedState,e]},useRef:function(e){var t=Ae();return e={current:e},t.memoizedState=e},useState:_i,useDebugValue:Ts,useDeferredValue:function(e){return Ae().memoizedState=e},useTransition:function(){var e=_i(!1),t=e[0];return e=pd.bind(null,e[1]),Ae().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=G,l=Ae();if(W){if(n===void 0)throw Error(S(407));n=n()}else{if(n=t(),le===null)throw Error(S(349));Ot&30||Na(r,t,n)}l.memoizedState=n;var o={value:n,getSnapshot:t};return l.queue=o,Ti(Ea.bind(null,r,o,e),[e]),r.flags|=2048,tr(9,Ca.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=Ae(),t=le.identifierPrefix;if(W){var n=Je,r=Xe;n=(r&~(1<<32-De(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=bn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Be]=t,e[Jn]=r,Xa(e,t,!1,!1),t.stateNode=e;e:{switch(s=fo(n,r),n){case"dialog":B("cancel",e),B("close",e),l=r;break;case"iframe":case"object":case"embed":B("load",e),l=r;break;case"video":case"audio":for(l=0;lmn&&(t.flags|=128,r=!0,Cn(o,!1),t.lanes=4194304)}else{if(!r)if(e=tl(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Cn(o,!0),o.tail===null&&o.tailMode==="hidden"&&!s.alternate&&!W)return ae(t),null}else 2*J()-o.renderingStartTime>mn&&n!==1073741824&&(t.flags|=128,r=!0,Cn(o,!1),t.lanes=4194304);o.isBackwards?(s.sibling=t.child,t.child=s):(n=o.last,n!==null?n.sibling=s:t.child=s,o.last=s)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=J(),t.sibling=null,n=K.current,A(K,r?n&1|2:n&1),t):(ae(t),null);case 22:case 23:return Os(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ke&1073741824&&(ae(t),t.subtreeFlags&6&&(t.flags|=8192)):ae(t),null;case 24:return null;case 25:return null}throw Error(S(156,t.tag))}function Cd(e,t){switch(hs(t),t.tag){case 1:return we(t.type)&&Yr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return dn(),H(ge),H(fe),Cs(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Ns(t),null;case 13:if(H(K),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(S(340));cn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return H(K),null;case 4:return dn(),null;case 10:return ws(t.type._context),null;case 22:case 23:return Os(),null;case 24:return null;default:return null}}var Cr=!1,ce=!1,Ed=typeof WeakSet=="function"?WeakSet:Set,_=null;function bt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){X(e,t,r)}else n.current=null}function Uo(e,t,n){try{n()}catch(r){X(e,t,r)}}var Vi=!1;function jd(e,t){if(So=Wr,e=na(),ps(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var s=0,i=-1,u=-1,f=0,y=0,m=e,p=null;t:for(;;){for(var v;m!==n||l!==0&&m.nodeType!==3||(i=s+l),m!==o||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(v=m.firstChild)!==null;)p=m,m=v;for(;;){if(m===e)break t;if(p===n&&++f===l&&(i=s),p===o&&++y===r&&(u=s),(v=m.nextSibling)!==null)break;m=p,p=m.parentNode}m=v}n=i===-1||u===-1?null:{start:i,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(No={focusedElem:e,selectionRange:n},Wr=!1,_=t;_!==null;)if(t=_,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_=e;else for(;_!==null;){t=_;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var w=g.memoizedProps,M=g.memoizedState,d=t.stateNode,c=d.getSnapshotBeforeUpdate(t.elementType===t.type?w:Ie(t.type,w),M);d.__reactInternalSnapshotBeforeUpdate=c}break;case 3:var h=t.stateNode.containerInfo;h.nodeType===1?h.textContent="":h.nodeType===9&&h.documentElement&&h.removeChild(h.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(S(163))}}catch(x){X(t,t.return,x)}if(e=t.sibling,e!==null){e.return=t.return,_=e;break}_=t.return}return g=Vi,Vi=!1,g}function Dn(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var o=l.destroy;l.destroy=void 0,o!==void 0&&Uo(t,n,o)}l=l.next}while(l!==r)}}function wl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Vo(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function qa(e){var t=e.alternate;t!==null&&(e.alternate=null,qa(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Be],delete t[Jn],delete t[jo],delete t[ud],delete t[ad])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ba(e){return e.tag===5||e.tag===3||e.tag===4}function Ai(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ba(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ao(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Gr));else if(r!==4&&(e=e.child,e!==null))for(Ao(e,t,n),e=e.sibling;e!==null;)Ao(e,t,n),e=e.sibling}function Bo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Bo(e,t,n),e=e.sibling;e!==null;)Bo(e,t,n),e=e.sibling}var oe=null,Oe=!1;function rt(e,t,n){for(n=n.child;n!==null;)ec(e,t,n),n=n.sibling}function ec(e,t,n){if(He&&typeof He.onCommitFiberUnmount=="function")try{He.onCommitFiberUnmount(fl,n)}catch{}switch(n.tag){case 5:ce||bt(n,t);case 6:var r=oe,l=Oe;oe=null,rt(e,t,n),oe=r,Oe=l,oe!==null&&(Oe?(e=oe,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):oe.removeChild(n.stateNode));break;case 18:oe!==null&&(Oe?(e=oe,n=n.stateNode,e.nodeType===8?Hl(e.parentNode,n):e.nodeType===1&&Hl(e,n),Qn(e)):Hl(oe,n.stateNode));break;case 4:r=oe,l=Oe,oe=n.stateNode.containerInfo,Oe=!0,rt(e,t,n),oe=r,Oe=l;break;case 0:case 11:case 14:case 15:if(!ce&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var o=l,s=o.destroy;o=o.tag,s!==void 0&&(o&2||o&4)&&Uo(n,t,s),l=l.next}while(l!==r)}rt(e,t,n);break;case 1:if(!ce&&(bt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(i){X(n,t,i)}rt(e,t,n);break;case 21:rt(e,t,n);break;case 22:n.mode&1?(ce=(r=ce)||n.memoizedState!==null,rt(e,t,n),ce=r):rt(e,t,n);break;default:rt(e,t,n)}}function Bi(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Ed),t.forEach(function(r){var l=Od.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function ze(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=s),r&=~o}if(r=l,r=J()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*_d(r/1960))-r,10e?16:e,at===null)var r=!1;else{if(e=at,at=null,sl=0,F&6)throw Error(S(331));var l=F;for(F|=4,_=e.current;_!==null;){var o=_,s=o.child;if(_.flags&16){var i=o.deletions;if(i!==null){for(var u=0;uJ()-zs?Lt(e,0):Rs|=n),xe(e,t)}function uc(e,t){t===0&&(e.mode&1?(t=hr,hr<<=1,!(hr&130023424)&&(hr=4194304)):t=1);var n=pe();e=et(e,t),e!==null&&(or(e,t,n),xe(e,n))}function Id(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),uc(e,n)}function Od(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(S(314))}r!==null&&r.delete(t),uc(e,n)}var ac;ac=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ge.current)ye=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ye=!1,Sd(e,t,n);ye=!!(e.flags&131072)}else ye=!1,W&&t.flags&1048576&&pa(t,Zr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Or(e,t),e=t.pendingProps;var l=an(t,fe.current);on(t,n),l=js(null,t,r,e,l,n);var o=Ps();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,we(r)?(o=!0,Xr(t)):o=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,ks(t),l.updater=gl,t.stateNode=l,l._reactInternals=t,Ro(t,r,e,n),t=Oo(null,t,r,!0,o,n)):(t.tag=0,W&&o&&ms(t),de(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Or(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Dd(r),e=Ie(r,e),l){case 0:t=Io(null,t,r,e,n);break e;case 1:t=Di(null,t,r,e,n);break e;case 11:t=Oi(null,t,r,e,n);break e;case 14:t=$i(null,t,r,Ie(r.type,e),n);break e}throw Error(S(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ie(r,l),Io(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ie(r,l),Di(e,t,r,l,n);case 3:e:{if(Ka(t),e===null)throw Error(S(387));r=t.pendingProps,o=t.memoizedState,l=o.element,wa(e,t),el(t,r,null,n);var s=t.memoizedState;if(r=s.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){l=pn(Error(S(423)),t),t=Fi(e,t,r,n,l);break e}else if(r!==l){l=pn(Error(S(424)),t),t=Fi(e,t,r,n,l);break e}else for(Se=pt(t.stateNode.containerInfo.firstChild),Ne=t,W=!0,$e=null,n=ya(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(cn(),r===l){t=tt(e,t,n);break e}de(e,t,r,n)}t=t.child}return t;case 5:return xa(t),e===null&&To(t),r=t.type,l=t.pendingProps,o=e!==null?e.memoizedProps:null,s=l.children,Co(r,l)?s=null:o!==null&&Co(r,o)&&(t.flags|=32),Qa(e,t),de(e,t,s,n),t.child;case 6:return e===null&&To(t),null;case 13:return Ga(e,t,n);case 4:return Ss(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=fn(t,null,r,n):de(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ie(r,l),Oi(e,t,r,l,n);case 7:return de(e,t,t.pendingProps,n),t.child;case 8:return de(e,t,t.pendingProps.children,n),t.child;case 12:return de(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,o=t.memoizedProps,s=l.value,A(qr,r._currentValue),r._currentValue=s,o!==null)if(Ue(o.value,s)){if(o.children===l.children&&!ge.current){t=tt(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var i=o.dependencies;if(i!==null){s=o.child;for(var u=i.firstContext;u!==null;){if(u.context===r){if(o.tag===1){u=Ze(-1,n&-n),u.tag=2;var f=o.updateQueue;if(f!==null){f=f.shared;var y=f.pending;y===null?u.next=u:(u.next=y.next,y.next=u),f.pending=u}}o.lanes|=n,u=o.alternate,u!==null&&(u.lanes|=n),Mo(o.return,n,t),i.lanes|=n;break}u=u.next}}else if(o.tag===10)s=o.type===t.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(S(341));s.lanes|=n,i=s.alternate,i!==null&&(i.lanes|=n),Mo(s,n,t),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===t){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}de(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,on(t,n),l=Le(l),r=r(l),t.flags|=1,de(e,t,r,n),t.child;case 14:return r=t.type,l=Ie(r,t.pendingProps),l=Ie(r.type,l),$i(e,t,r,l,n);case 15:return Ha(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ie(r,l),Or(e,t),t.tag=1,we(r)?(e=!0,Xr(t)):e=!1,on(t,n),Va(t,r,l),Ro(t,r,l,n),Oo(null,t,r,!0,e,n);case 19:return Ya(e,t,n);case 22:return Wa(e,t,n)}throw Error(S(156,t.tag))};function cc(e,t){return Du(e,t)}function $d(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Te(e,t,n,r){return new $d(e,t,n,r)}function Ds(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Dd(e){if(typeof e=="function")return Ds(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ns)return 11;if(e===rs)return 14}return 2}function yt(e,t){var n=e.alternate;return n===null?(n=Te(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Fr(e,t,n,r,l,o){var s=2;if(r=e,typeof e=="function")Ds(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case Wt:return Rt(n.children,l,o,t);case ts:s=8,l|=8;break;case to:return e=Te(12,n,t,l|2),e.elementType=to,e.lanes=o,e;case no:return e=Te(13,n,t,l),e.elementType=no,e.lanes=o,e;case ro:return e=Te(19,n,t,l),e.elementType=ro,e.lanes=o,e;case xu:return kl(n,l,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case gu:s=10;break e;case wu:s=9;break e;case ns:s=11;break e;case rs:s=14;break e;case lt:s=16,r=null;break e}throw Error(S(130,e==null?e:typeof e,""))}return t=Te(s,n,t,l),t.elementType=e,t.type=r,t.lanes=o,t}function Rt(e,t,n,r){return e=Te(7,e,r,t),e.lanes=n,e}function kl(e,t,n,r){return e=Te(22,e,r,t),e.elementType=xu,e.lanes=n,e.stateNode={isHidden:!1},e}function Zl(e,t,n){return e=Te(6,e,null,t),e.lanes=n,e}function ql(e,t,n){return t=Te(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Fd(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Rl(0),this.expirationTimes=Rl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Rl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Fs(e,t,n,r,l,o,s,i,u){return e=new Fd(e,t,n,i,u),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Te(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ks(o),e}function Ud(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(mc)}catch(e){console.error(e)}}mc(),mu.exports=Ee;var Wd=mu.exports,Ji=Wd;bl.createRoot=Ji.createRoot,bl.hydrateRoot=Ji.hydrateRoot;function Qd(){const[e,t]=k.useState({status:"disconnected"}),[n,r]=k.useState([]),[l,o]=k.useState(null),[s,i]=k.useState(0),u=k.useRef(null),f=k.useRef(null),y=k.useRef(!1),m=k.useCallback(()=>{var w;if(((w=u.current)==null?void 0:w.readyState)===WebSocket.OPEN)return;const g=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/pipedal`;t({status:"connecting"});try{const M=new WebSocket(g);M.onopen=()=>{t({status:"connected"})},M.onmessage=d=>{try{const c=JSON.parse(d.data);c.type==="connected"?t({status:"connected"}):c.type==="error"&&t({status:"error",error:c.message})}catch{}},M.onerror=()=>{t({status:"error",error:"WebSocket connection error"})},M.onclose=()=>{y.current||(t({status:"disconnected"}),f.current=window.setTimeout(()=>{y.current||m()},3e3))},u.current=M}catch(M){t({status:"error",error:String(M)})}},[]),p=k.useCallback(async()=>{try{const g=await(await fetch("/api/discover")).json();r(g.oplabs_instances||[]),o(g.pedalboard_name),i(Date.now()),g.connected&&t({status:"connected"})}catch(v){t({status:"error",error:`Discover failed: ${String(v)}`})}},[]);return k.useEffect(()=>(y.current=!1,m(),()=>{y.current=!0,f.current&&clearTimeout(f.current),u.current&&u.current.close()}),[m]),k.useEffect(()=>{e.status==="connected"&&p()},[e.status,p]),{connectionState:e,plugins:n,pedalboardName:l,discover:p,lastUpdate:s}}function Kd(){const e=k.useRef(null),[t,n]=k.useState(!1),r=k.useRef(null),l=k.useRef(!1),o=k.useRef(new Map),s=k.useCallback(()=>{var y;if(((y=e.current)==null?void 0:y.readyState)===WebSocket.OPEN)return;const f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/pipedal`;try{const m=new WebSocket(f);m.onopen=()=>{n(!0)},m.onmessage=p=>{try{const v=JSON.parse(p.data);if(Array.isArray(v)&&v.length>=1){const g=v[0];if(g.reply!==void 0){const w=o.current.get(g.reply);w&&(w(v[1]||null),o.current.delete(g.reply))}}}catch{}},m.onerror=()=>{n(!1)},m.onclose=()=>{n(!1),o.current.clear(),l.current||(r.current=window.setTimeout(()=>{l.current||s()},3e3))},e.current=m}catch{n(!1)}},[]);k.useEffect(()=>(l.current=!1,s(),()=>{l.current=!0,r.current&&clearTimeout(r.current),e.current&&e.current.close()}),[s]);const i=k.useCallback((u,f,y)=>{if(!e.current||e.current.readyState!==WebSocket.OPEN)return;const m=(Date.now()&2147483647)+Math.floor(Math.random()*1e3),p=JSON.stringify([{message:"setControlValue",replyTo:m},{instanceId:u,key:f,value:y}]);e.current.send(p)},[]);return{ready:t,setControlValue:i}}function Gd(){const[e,t]=k.useState([]),[n,r]=k.useState(!1),[l,o]=k.useState(null),s=k.useCallback(async()=>{r(!0),o(null);try{const m=await fetch("/api/scenes");if(!m.ok)throw new Error(`Failed to load scenes: ${m.statusText}`);const p=await m.json();t(p.scenes||[])}catch(m){const p=m instanceof Error?m.message:String(m);o(p)}finally{r(!1)}},[]);k.useEffect(()=>{s()},[s]);const i=k.useCallback(async(m,p,v)=>{o(null);try{const g=await fetch("/api/scenes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:m,state:p,midiPc:v??null})});if(!g.ok)throw new Error(`Failed to save scene: ${g.statusText}`);await s()}catch(g){const w=g instanceof Error?g.message:String(g);throw o(w),g}},[s]),u=k.useCallback(async(m,p)=>{o(null);try{const v=await fetch(`/api/scenes/${encodeURIComponent(m)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});if(!v.ok)throw new Error(`Failed to update scene: ${v.statusText}`);await s()}catch(v){const g=v instanceof Error?v.message:String(v);o(g)}},[s]),f=k.useCallback(async m=>{o(null);try{const p=await fetch(`/api/scenes/${encodeURIComponent(m)}`,{method:"DELETE"});if(!p.ok)throw new Error(`Failed to delete scene: ${p.statusText}`);await s()}catch(p){const v=p instanceof Error?p.message:String(p);o(v)}},[s]),y=k.useCallback(async m=>{o(null);try{const p=await fetch(`/api/scenes/${encodeURIComponent(m)}/recall`,{method:"POST"});if(!p.ok){const v=await p.json().catch(()=>({}));throw new Error(v.error||`Recall failed: ${p.statusText}`)}return!0}catch(p){const v=p instanceof Error?p.message:String(p);return o(v),!1}},[]);return{scenes:e,loading:n,error:l,saveScene:i,updateScene:u,deleteScene:f,recallScene:y,refreshScenes:s}}function Yd(){const[e,t]=k.useState({ports:[],connections:{},loading:!0,error:null,source:"none"}),[n,r]=k.useState("idle"),[l,o]=k.useState(null),s=k.useRef(!0);k.useEffect(()=>()=>{s.current=!1},[]);const i=k.useCallback(async()=>{t(m=>({...m,loading:!0,error:null}));try{const m=await fetch("/api/jack/ports");if(!m.ok)throw new Error(`Failed to load JACK ports: ${m.statusText}`);const p=await m.json();s.current&&t({ports:p.ports||[],connections:p.connections||{},loading:!1,error:p.note||null,source:p.source})}catch(m){const p=m instanceof Error?m.message:String(m);s.current&&t(v=>({...v,loading:!1,error:p}))}},[]),u=k.useCallback(async(m,p)=>{r("connecting"),o(null);try{const v=await fetch("/api/jack/connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:m,destination:p})});if(!v.ok){const g=await v.json().catch(()=>({}));throw new Error(g.detail||`Connect failed: ${v.statusText}`)}return await i(),r("idle"),!0}catch(v){const g=v instanceof Error?v.message:String(v);return o(g),r("error"),!1}},[i]),f=k.useCallback(async(m,p)=>{r("disconnecting"),o(null);try{const v=await fetch("/api/jack/disconnect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:m,destination:p})});if(!v.ok){const g=await v.json().catch(()=>({}));throw new Error(g.detail||`Disconnect failed: ${v.statusText}`)}return await i(),r("idle"),!0}catch(v){const g=v instanceof Error?v.message:String(v);return o(g),r("error"),!1}},[i]),y=k.useCallback(async()=>{r("disconnecting"),o(null);try{const m=await fetch("/api/jack/disconnect-all",{method:"POST"});if(!m.ok)throw new Error(`Disconnect all failed: ${m.statusText}`);return await i(),r("idle"),!0}catch(m){const p=m instanceof Error?m.message:String(m);return o(p),r("error"),!1}},[i]);return k.useEffect(()=>{i()},[i]),{portsState:e,refresh:i,connect:u,disconnect:f,disconnectAll:y,actionState:n,actionError:l}}const Mn=32,Go=28,rr=4,Bt="#e94560",Xd=2.5,Jd=4;function Zi(e,t){const n=e.filter(o=>o.direction===t&&o.port_type==="audio").sort((o,s)=>{if(o.is_physical!==s.is_physical)return o.is_physical?-1:1;const i=o.client.localeCompare(s.client);return i!==0?i:o.port.localeCompare(s.port)}),r=[];let l=null;for(const o of n)(!l||l.client!==o.client)&&(l={client:o.client,ports:[],totalHeight:Go+rr},r.push(l)),l.ports.push(o),l.totalHeight+=Mn;return r}function Zd(e,t,n,r){const l={},o={};let s=r;for(const y of e){s+=Go+rr/2;for(const m of y.ports)l[m.name]=s+Mn/2,s+=Mn}let i=r;for(const y of t){i+=Go+rr/2;for(const m of y.ports)o[m.name]=i+Mn/2,i+=Mn}const u=[],f=new Set;for(const[y,m]of Object.entries(l)){const p=n[y]||[];for(const v of p){const g=`${y}→${v}`;if(f.has(g))continue;f.add(g);const w=o[v];w!==void 0&&u.push({source:y,dest:v,y1:m,y2:w})}}return u}function qi(e,t,n,r){const l=r,o=n-r,s=Math.max(60,(o-l)*.4);return`M ${l} ${e} C ${l+s} ${e}, ${o-s} ${t}, ${o} ${t}`}const qd=({portsState:e,onConnect:t,onDisconnect:n,onDisconnectAll:r,onRefresh:l,actionState:o,actionError:s})=>{const{ports:i,connections:u,loading:f,error:y,source:m}=e,[p,v]=k.useState(null),[g,w]=k.useState(null),M=k.useRef(null),[d,c]=k.useState(800),h=k.useMemo(()=>Zi(i,"output"),[i]),x=k.useMemo(()=>Zi(i,"input"),[i]),N=k.useMemo(()=>{const D=h.reduce((Qe,Ke)=>Qe+Ke.totalHeight,rr),Z=x.reduce((Qe,Ke)=>Qe+Ke.totalHeight,rr),ee=Math.max(D,Z)+40+20;return{headerH:40,leftH:D,rightH:Z,totalH:ee}},[h,x]),C=280,E=k.useMemo(()=>Zd(h,x,u,N.headerH+12),[h,x,u,N.headerH]);k.useEffect(()=>{const j=M.current;if(!j)return;const D=new ResizeObserver(Z=>{for(const ee of Z)c(ee.contentRect.width)});return D.observe(j),()=>D.disconnect()},[]),k.useEffect(()=>{o==="idle"&&v(null)},[o]);const T=k.useCallback(async j=>{if(j.direction==="output")if(j.connections.length>0)for(const D of j.connections)await n(j.name,D);else v(p===j.name?null:j.name);else if(p)await t(p,j.name),v(null);else if(j.connections.length>0)for(const D of j.connections)await n(D,j.name)},[p,t,n]),V=k.useCallback(j=>{const D=["patch-port"];return j.connections.length>0&&D.push("connected"),p===j.name&&D.push("armed"),j.direction==="output"&&p&&p!==j.name&&D.push("available"),D.join(" ")},[p]),z=k.useMemo(()=>{let j=0;for(const[,D]of Object.entries(u))j+=D.length;return j},[u]),L=(j,D)=>a.jsx("div",{className:`patch-column patch-column-${D}`,children:j.map(Z=>a.jsxs("div",{className:"patch-group",children:[a.jsxs("div",{className:"patch-group-header",children:[a.jsx("span",{className:`patch-group-dot ${Z.client==="system"?"physical":""}`}),a.jsx("span",{className:"patch-group-name",children:Z.client==="system"?Z.client:Z.client.replace(/^pipedal:/,"").replace(/^pipedal/,"PiPedal")})]}),Z.ports.map(ee=>a.jsxs("div",{className:V(ee),onClick:()=>T(ee),title:`${ee.name}${ee.connections.length>0?` +Connected to: ${ee.connections.join(", ")}`:` +Click to connect`}`,children:[D==="left"&&a.jsx("span",{className:"patch-port-indicator"}),a.jsx("span",{className:`patch-port-name ${ee.is_physical?"physical":""}`,children:ee.port}),ee.connections.length>0&&a.jsx("span",{className:"patch-port-conn-count",children:ee.connections.length})]},ee.name))]},Z.client))});return f?a.jsx("div",{className:"patch-bay",children:a.jsxs("div",{className:"patch-bay-loading",children:[a.jsx("div",{className:"patch-spinner"}),a.jsx("span",{children:"Loading JACK ports..."})]})}):i.length===0?a.jsx("div",{className:"patch-bay",children:a.jsxs("div",{className:"patch-bay-empty",children:[a.jsx("div",{className:"patch-empty-icon",children:"🔌"}),a.jsx("h3",{children:"No JACK Ports Available"}),a.jsx("p",{children:m==="none"?"PiPedal is unreachable. Ensure the PiPedal server is running on 192.168.0.245:8080.":"No ports found in the current pedalboard."}),y&&a.jsx("p",{className:"patch-empty-note",children:y}),a.jsx("button",{className:"patch-refresh-btn",onClick:l,children:"↻ Retry"})]})}):a.jsxs("div",{className:"patch-bay",ref:M,children:[a.jsxs("div",{className:"patch-bay-header",children:[a.jsxs("div",{className:"patch-bay-title",children:[a.jsx("span",{className:"patch-icon",children:"🔌"}),a.jsx("span",{children:"Patch Bay"}),a.jsx("span",{className:"patch-conn-count",children:z})]}),a.jsxs("div",{className:"patch-bay-actions",children:[p&&a.jsxs("span",{className:"patch-armed-info",children:["Armed: ",a.jsx("code",{children:p.split(":").pop()})]}),o!=="idle"&&a.jsx("span",{className:`patch-action-state ${o}`,children:o==="connecting"?"Connecting...":o==="disconnecting"?"Disconnecting...":s||"Error"}),a.jsx("button",{className:"patch-action-btn",onClick:r,disabled:z===0||o!=="idle",title:"Disconnect all",children:"✕ Disconnect All"}),a.jsx("button",{className:"patch-refresh-btn",onClick:l,disabled:o!=="idle",title:"Refresh ports",children:"↻"})]})]}),a.jsxs("div",{className:"patch-bay-body",style:{minHeight:N.totalH},children:[a.jsxs("svg",{className:"patch-cables-svg",width:d,height:N.totalH,style:{position:"absolute",top:0,left:0,pointerEvents:"none"},children:[a.jsxs("defs",{children:[a.jsxs("linearGradient",{id:"cableGrad",x1:"0",y1:"0",x2:"1",y2:"0",children:[a.jsx("stop",{offset:"0%",stopColor:Bt,stopOpacity:.15}),a.jsx("stop",{offset:"50%",stopColor:Bt,stopOpacity:.6}),a.jsx("stop",{offset:"100%",stopColor:Bt,stopOpacity:.15})]}),a.jsxs("filter",{id:"cableGlow",children:[a.jsx("feGaussianBlur",{stdDeviation:"2",result:"blur"}),a.jsxs("feMerge",{children:[a.jsx("feMergeNode",{in:"blur"}),a.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),E.map(j=>a.jsx("path",{d:qi(j.y1,j.y2,d,C),fill:"none",stroke:"transparent",strokeWidth:14,style:{pointerEvents:"stroke",cursor:"pointer"},onMouseEnter:()=>w({source:j.source,dest:j.dest}),onMouseLeave:()=>w(null),onClick:()=>{n(j.source,j.dest)}},`bg-${j.source}→${j.dest}`)),E.map(j=>{const D=(g==null?void 0:g.source)===j.source&&(g==null?void 0:g.dest)===j.dest;return a.jsx("path",{d:qi(j.y1,j.y2,d,C),fill:"none",stroke:D?"#ff6b81":Bt,strokeWidth:D?Jd:Xd,strokeLinecap:"round",opacity:D?.9:.5,filter:D?"url(#cableGlow)":void 0,style:{pointerEvents:"none"}},`cable-${j.source}→${j.dest}`)}),E.map(j=>a.jsx("circle",{cx:C,cy:j.y1,r:3,fill:Bt,opacity:.8},`dot-${j.source}→${j.dest}`)),E.map(j=>a.jsx("circle",{cx:d-C,cy:j.y2,r:3,fill:Bt,opacity:.8},`dot2-${j.source}→${j.dest}`))]}),L(h,"left"),L(x,"right"),m!=="pipedal"&&m!=="none"&&a.jsxs("div",{className:"patch-source-note",children:["Port data from pedalboard state (source: ",m,")"]})]}),y&&a.jsxs("div",{className:"patch-bay-error",children:[a.jsxs("span",{children:["⚠ ",y]}),a.jsx("button",{className:"patch-dismiss-btn",onClick:l,children:"↻"})]}),s&&a.jsx("div",{className:"patch-bay-error action",children:a.jsxs("span",{children:["⚠ ",s]})})]})},hc={0:"Guitar",1:"Bass",2:"Keys",3:"Vocals",4:"Backing"},vc={0:"#ff8c00",1:"#2196f3",2:"#9c27b0",3:"#e91e63",4:"#009688"},bd={0:"🎸",1:"🎸",2:"🎹",3:"🎤",4:"🎵"},ep=({instrument:e,size:t="medium",showIcon:n=!0})=>{const r=hc[e]??`Unknown (${e})`,l=vc[e]??"#666",o=bd[e]??"";return a.jsxs("span",{className:"instrument-badge","data-size":t,style:{backgroundColor:`${l}22`,color:l,borderColor:l},title:r,children:[n&&a.jsx("span",{className:"instrument-icon",children:o}),a.jsx("span",{className:"instrument-name",children:r})]})},Mt=-60,bi=0;function Ct(e){const n=(Math.max(Mt,Math.min(bi,e))-Mt)/(bi-Mt);return Math.sqrt(n)*100}const al=({levelL:e,levelR:t,label:n,mini:r=!1,peakHold:l=1500})=>{const o=k.useRef(Mt),s=k.useRef(Mt),i=k.useRef(null),u=k.useRef(null),[,f]=du.useState(0);k.useEffect(()=>{e>o.current&&(o.current=e,i.current&&clearTimeout(i.current),i.current=window.setTimeout(()=>{o.current=Math.max(e,Mt),f(M=>M+1)},l)),t>s.current&&(s.current=t,u.current&&clearTimeout(u.current),u.current=window.setTimeout(()=>{s.current=Math.max(t,Mt),f(M=>M+1)},l))},[e,t,l]);const y=Ct(e),m=Ct(t),p=Ct(o.current),v=Ct(s.current),g=M=>M<60?"var(--meter-green, #4caf50)":M<85?"var(--meter-yellow, #ff9800)":"var(--meter-red, #f44336)",w=(M,d,c)=>a.jsxs("div",{className:`level-meter-channel ${r?"mini":""}`,children:[!r&&a.jsx("span",{className:"level-meter-side-label",children:c}),a.jsxs("div",{className:"level-meter-bar-track",children:[a.jsx("div",{className:"level-meter-bar-fill",style:{height:`${Math.min(100,M)}%`,backgroundColor:g(M)}}),a.jsx("div",{className:"level-meter-peak",style:{bottom:`${Math.min(100,d)}%`}}),!r&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"level-meter-tick",style:{bottom:`${Ct(-6)}%`}}),a.jsx("div",{className:"level-meter-tick mark-yellow",style:{bottom:`${Ct(-20)}%`}}),a.jsx("div",{className:"level-meter-tick mark-green",style:{bottom:`${Ct(-40)}%`}})]})]})]});return a.jsxs("div",{className:`level-meter ${r?"mini":""}`,children:[a.jsxs("div",{className:"level-meter-stereo-pair",children:[w(y,p,"L"),w(m,v,"R")]}),n&&a.jsx("div",{className:"level-meter-label",children:n}),!r&&a.jsxs("div",{className:"level-meter-db-values",children:[a.jsx("span",{className:e>-10?"hot":"",children:e.toFixed(1)}),a.jsx("span",{className:t>-10?"hot":"",children:t.toFixed(1)})]})]})},tp=[0,1,2,3,4];function np(e){if(e<=0)return-60;if(e>=1)return 6;const t=e/.75;if(t<=.001)return-60;const n=20*Math.log10(t);return Math.max(-60,Math.min(6,n))}function rp(e){if(e<=-60)return 0;if(e>=6)return 1;const t=Math.pow(10,e/20);return Math.min(1,t*.75)}const lp=({plugin:e,onSetControl:t})=>{const n=e.controlValues,r=n.volume??0,l=n.pan??0,o=(n.mute??0)>=.5,s=(n.solo??0)>=.5,i=Math.round(n.instrument??0)||0,u=n.levelL??-60,f=n.levelR??-60,y=vc[i]??"#666",m=k.useCallback(d=>{const c=parseFloat(d.target.value)/100,h=np(c);t(e.instanceId,"volume",parseFloat(h.toFixed(1)))},[e.instanceId,t]),p=k.useCallback(d=>{const c=parseFloat(d.target.value);t(e.instanceId,"pan",c)},[e.instanceId,t]),v=k.useCallback(()=>{t(e.instanceId,"mute",o?0:1)},[e.instanceId,o,t]),g=k.useCallback(()=>{t(e.instanceId,"solo",s?0:1)},[e.instanceId,s,t]),w=k.useCallback(d=>{const c=parseInt(d.target.value,10);t(e.instanceId,"instrument",c)},[e.instanceId,t]),M=rp(r)*100;return a.jsxs("div",{className:"channel-strip",style:{borderTopColor:y,"--channel-accent":y},children:[a.jsxs("div",{className:"channel-header",children:[a.jsx("span",{className:"channel-label",title:e.title||e.pluginName,children:e.title||e.pluginName||`Ch ${e.instanceId}`}),a.jsx(ep,{instrument:i,size:"small"})]}),a.jsxs("div",{className:"channel-mute-solo",children:[a.jsx("button",{className:`channel-btn mute ${o?"active":""}`,onClick:v,title:"Mute",children:"M"}),a.jsx("button",{className:`channel-btn solo ${s?"active":""}`,onClick:g,title:"Solo",children:"S"})]}),a.jsx("div",{className:"channel-meter-section",children:a.jsx(al,{levelL:u,levelR:f,mini:!1})}),a.jsxs("div",{className:"channel-pan",children:[a.jsx("label",{className:"channel-pan-label",children:"Pan"}),a.jsxs("div",{className:"channel-pan-control",children:[a.jsx("input",{type:"range",min:"-1",max:"1",step:"0.01",value:l,onChange:p,className:"channel-pan-slider",title:`Pan: ${l.toFixed(2)}`}),a.jsx("span",{className:"channel-pan-value",children:l===0?"C":l<0?`L${Math.abs(Math.round(l*100))}`:`R${Math.round(l*100)}`})]})]}),a.jsxs("div",{className:"channel-fader-section",children:[a.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:M,onChange:m,className:"channel-fader",title:`Volume: ${r.toFixed(1)} dB`,orient:"vertical"}),a.jsx("span",{className:"channel-fader-readout",children:r>-60?`${r>=0?"+":""}${r.toFixed(1)}`:"-∞"})]}),a.jsx("div",{className:"channel-instrument-selector",children:a.jsx("select",{value:i,onChange:w,className:"channel-instrument-select",style:{borderColor:y},children:tp.map(d=>a.jsx("option",{value:d,children:hc[d]},d))})})]})},op=[{value:1,label:"Main"},{value:2,label:"Bus 2"},{value:3,label:"Bus 3"},{value:4,label:"Bus 4"},{value:5,label:"Bus 5"},{value:6,label:"Bus 6"},{value:7,label:"Bus 7"},{value:8,label:"Bus 8"}];function eu(e){return(Math.max(-60,Math.min(6,e))+60)/66*100}function tu(e){return e/100*66-60}const sp=({plugin:e,onSetControl:t})=>{const n=e.controlValues,r=n.masterVol??0,l=(n.masterMute??0)>=.5,o=n.masterLevelL??-60,s=n.masterLevelR??-60,i=Array.from({length:8},(v,g)=>{const w=g+1;return{index:w,vol:n[`ch${w}Vol`]??0,mute:(n[`ch${w}Mute`]??0)>=.5,route:Math.round(n[`ch${w}Route`]??1),levelL:n[`ch${w}LevelL`]??-60,levelR:n[`ch${w}LevelR`]??-60,volKey:`ch${w}Vol`,muteKey:`ch${w}Mute`,routeKey:`ch${w}Route`}}),u=k.useCallback(v=>{const g=tu(parseFloat(v.target.value));t(e.instanceId,"masterVol",parseFloat(g.toFixed(1)))},[e.instanceId,t]),f=k.useCallback(()=>{t(e.instanceId,"masterMute",l?0:1)},[e.instanceId,l,t]),y=k.useCallback((v,g,w)=>{const M=tu(parseFloat(w.target.value));t(e.instanceId,g,parseFloat(M.toFixed(1)))},[e.instanceId,t]),m=k.useCallback((v,g,w)=>{t(e.instanceId,g,w?0:1)},[e.instanceId,t]),p=k.useCallback((v,g,w)=>{const M=parseInt(w.target.value,10);t(e.instanceId,g,M)},[e.instanceId,t]);return a.jsxs("div",{className:"bus-strip",children:[a.jsxs("div",{className:"bus-master-section",children:[a.jsxs("div",{className:"bus-master-header",children:[a.jsx("span",{className:"bus-master-label",children:"Master"}),a.jsx("button",{className:`bus-btn mute ${l?"active":""}`,onClick:f,title:"Master Mute",children:"M"})]}),a.jsx("div",{className:"bus-master-meter",children:a.jsx(al,{levelL:o,levelR:s,mini:!0,label:r>-60?`${r.toFixed(1)}dB`:"-∞"})}),a.jsx("div",{className:"bus-master-fader",children:a.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:eu(r),onChange:u,className:"bus-fader",title:`Master Volume: ${r.toFixed(1)} dB`})})]}),a.jsx("div",{className:"bus-divider"}),a.jsx("div",{className:"bus-channels",children:i.map(v=>a.jsxs("div",{className:"bus-channel",children:[a.jsxs("span",{className:"bus-channel-label",children:["Ch ",v.index]}),a.jsx("button",{className:`bus-btn mute mini ${v.mute?"active":""}`,onClick:()=>m(v.index,v.muteKey,v.mute),title:`Ch ${v.index} Mute`,children:"M"}),a.jsx("select",{className:"bus-channel-route",value:v.route,onChange:g=>p(v.index,v.routeKey,g),title:`Ch ${v.index} route`,children:op.map(g=>a.jsx("option",{value:g.value,children:g.label},g.value))}),a.jsx("div",{className:"bus-channel-meter",children:a.jsx(al,{levelL:v.levelL,levelR:v.levelR,mini:!0})}),a.jsx("div",{className:"bus-channel-fader",children:a.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:eu(v.vol),onChange:g=>y(v.index,v.volKey,g),className:"bus-fader mini",title:`Ch ${v.index} Volume: ${v.vol.toFixed(1)} dB`})}),a.jsx("span",{className:"bus-channel-db",children:v.vol>-60?v.vol.toFixed(1):"-∞"})]},v.index))})]})};function ip(e){if(e<=0)return-60;if(e>=1)return 6;const t=e/.75;if(t<=.001)return-60;const n=20*Math.log10(t);return Math.max(-60,Math.min(6,n))}function up(e){if(e<=-60)return 0;if(e>=6)return 1;const t=Math.pow(10,e/20);return Math.min(1,t*.75)}const ap=({volume:e,mute:t,levelL:n,levelR:r,onVolumeChange:l,onMuteToggle:o,label:s="Master"})=>{const i=up(e)*100,u=k.useCallback(y=>{const m=parseFloat(y.target.value)/100,p=ip(m);l(parseFloat(p.toFixed(1)))},[l]),f=k.useCallback(()=>{o(!t)},[t,o]);return a.jsxs("div",{className:`master-bus ${t?"muted":""}`,children:[a.jsxs("div",{className:"master-bus-header",children:[a.jsx("span",{className:"master-bus-label",children:s}),a.jsx("span",{className:"master-bus-type",children:"Main Out"})]}),a.jsx("div",{className:"master-bus-meters",children:a.jsx(al,{levelL:n,levelR:r,mini:!1})}),a.jsx("div",{className:"master-bus-controls",children:a.jsx("button",{className:`master-bus-btn mute ${t?"active":""}`,onClick:f,title:"Master Mute",children:"M"})}),a.jsxs("div",{className:"master-bus-fader-section",children:[a.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:i,onChange:u,className:"master-bus-fader",title:`Master Volume: ${e.toFixed(1)} dB`,orient:"vertical"}),a.jsx("span",{className:"master-bus-fader-readout",children:t?"MUTED":e>-60?`${e>=0?"+":""}${e.toFixed(1)}`:"-∞"})]}),a.jsxs("div",{className:"master-bus-db-values",children:[a.jsx("span",{className:n>-10?"hot":"",children:n.toFixed(1)}),a.jsx("span",{className:r>-10?"hot":"",children:r.toFixed(1)})]})]})},cp=({scenes:e,loading:t,error:n,onClose:r,onSaveScene:l,onDeleteScene:o,onRecallScene:s,getCurrentState:i})=>{const[u,f]=k.useState(""),[y,m]=k.useState(""),[p,v]=k.useState(!1),[g,w]=k.useState(null),[M,d]=k.useState(null),[c,h]=k.useState(null),[x,N]=k.useState(null),C=n||x,E=k.useCallback(async()=>{const L=u.trim();if(!L)return;const j=i();if(!j){N("No plugin state available. Refresh plugins first.");return}v(!0),N(null);try{const D=y.trim()!==""?parseInt(y.trim(),10):null;await l(L,j,D),f(""),m("")}catch{N("Failed to save scene")}finally{v(!1)}},[u,y,i,l]),T=k.useCallback(async L=>{w(L),N(null);try{await s(L)?(d(L),setTimeout(()=>d(null),700)):N("Recall failed — check PiPedal connection")}catch{N("Recall failed")}finally{w(null)}},[s]),V=k.useCallback(async L=>{N(null),h(null);try{await o(L)}catch{N("Failed to delete scene")}},[o]),z=k.useCallback(L=>{L.key==="Enter"&&E()},[E]);return a.jsxs("div",{className:"scene-manager-overlay",children:[a.jsxs("div",{className:"scene-manager-header",children:[a.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[a.jsx("h2",{children:"Scenes"}),a.jsx("span",{className:"scene-manager-count",children:e.length})]}),a.jsx("button",{className:"scene-close-btn",onClick:r,title:"Close",children:"✕"})]}),a.jsxs("div",{className:"scene-list",children:[t&&e.length===0&&a.jsx("div",{className:"scene-list-loading",children:"Loading scenes..."}),!t&&e.length===0&&a.jsxs("div",{className:"scene-list-empty",children:[a.jsx("span",{children:"No saved scenes yet"}),a.jsx("span",{children:"Use the form below to save the current mixer state."})]}),e.map(L=>a.jsx("div",{className:`scene-card ${M===L.id?"scene-recalled-flash":""} ${g===L.id?"scene-recalling":""}`,children:a.jsxs("div",{className:"scene-card-content",children:[a.jsx("span",{className:"scene-card-name",onClick:()=>T(L.id),title:`Recall "${L.name}"`,children:L.name}),L.midiPc!==null&&L.midiPc!==void 0&&a.jsxs("span",{className:"scene-card-midi",children:["PC#",L.midiPc]}),a.jsxs("div",{className:"scene-card-actions",children:[a.jsx("button",{className:"scene-card-btn recall",onClick:()=>T(L.id),disabled:g===L.id,title:"Recall scene",children:"▶ Recall"}),a.jsx("button",{className:"scene-card-btn delete",onClick:()=>h(L.id),title:"Delete scene",children:"✕"})]})]})},L.id))]}),a.jsxs("div",{className:"scene-save-form",children:[a.jsxs("div",{className:"scene-save-row",children:[a.jsx("input",{className:"scene-name-input",type:"text",placeholder:"Scene name...",value:u,onChange:L=>f(L.target.value),onKeyDown:z,maxLength:60}),a.jsx("button",{className:"scene-save-btn",onClick:E,disabled:p||!u.trim(),children:p?"Saving...":"Save"})]}),a.jsx("div",{className:"scene-save-row",children:a.jsxs("div",{className:"scene-midi-input-group",children:[a.jsx("span",{className:"scene-midi-label",children:"MIDI PC:"}),a.jsx("input",{className:"scene-midi-input",type:"number",min:"0",max:"127",placeholder:"—",value:y,onChange:L=>m(L.target.value)})]})})]}),C&&a.jsx("div",{className:"scene-error",children:C}),c!==null&&a.jsx("div",{className:"scene-confirm-overlay",onClick:()=>h(null),children:a.jsxs("div",{className:"scene-confirm-dialog",onClick:L=>L.stopPropagation(),children:[a.jsx("p",{children:"Delete this scene permanently?"}),a.jsxs("div",{className:"scene-confirm-actions",children:[a.jsx("button",{className:"scene-confirm-cancel",onClick:()=>h(null),children:"Cancel"}),a.jsx("button",{className:"scene-confirm-delete",onClick:()=>V(c),children:"Delete"})]})]})})]})},fp={connected:"#4caf50",connecting:"#ff9800",disconnected:"#9e9e9e",error:"#f44336"},dp={connected:"Connected to PiPedal",connecting:"Connecting...",disconnected:"Disconnected",error:"Connection Error"},pp=({state:e,onRetry:t})=>a.jsxs("div",{className:"connection-status",children:[a.jsxs("div",{className:"status-indicator",children:[a.jsx("span",{className:"status-dot",style:{backgroundColor:fp[e.status]||"#9e9e9e"}}),a.jsx("span",{className:"status-label",children:dp[e.status]||e.status})]}),e.error&&a.jsxs("div",{className:"status-error",children:[a.jsx("span",{children:e.error}),t&&a.jsx("button",{className:"retry-btn",onClick:t,children:"Retry"})]})]}),mp=({plugins:e,connectionState:t,pedalboardName:n,lastUpdate:r,onRefresh:l})=>{const{ready:o,setControlValue:s}=Kd(),{scenes:i,loading:u,error:f,saveScene:y,deleteScene:m,recallScene:p}=Gd(),{portsState:v,refresh:g,connect:w,disconnect:M,disconnectAll:d,actionState:c,actionError:h}=Yd(),[x,N]=k.useState(!1),[C,E]=k.useState(!1),[T,V]=k.useState(!1),z="http://192.168.0.245:8080/",L=k.useMemo(()=>e.filter(O=>!O.uri.includes("band-bus")&&O.uri.includes("band-channel")),[e]),j=k.useMemo(()=>e.filter(O=>O.uri.includes("band-bus")),[e]),D=L.length>0,Z=j.length>0,ee=e.length>0,Qe=k.useMemo(()=>Z?Math.max(...j.map(O=>O.controlValues.masterLevelL??-60)):-60,[j,Z]),Ke=k.useMemo(()=>Z?Math.max(...j.map(O=>O.controlValues.masterLevelR??-60)):-60,[j,Z]),[P,R]=k.useState(0),[I,Q]=k.useState(!1),q=k.useCallback(()=>e.length===0?null:{channels:L.map(O=>({instanceId:O.instanceId,params:{...O.controlValues}})),buses:j.map(O=>({instanceId:O.instanceId,params:{...O.controlValues}}))},[e,L,j]),Vt=k.useCallback(()=>{N(O=>!O)},[]);return a.jsxs("div",{className:"mixer-page",children:[a.jsxs("header",{className:"mixer-header",children:[a.jsxs("div",{className:"mixer-header-left",children:[a.jsx("h1",{className:"mixer-title",children:"OPLabs Mixer"}),a.jsx(pp,{state:t,onRetry:l})]}),a.jsxs("div",{className:"mixer-header-center",children:[n&&a.jsxs("span",{className:"mixer-pedalboard-name",children:["Pedalboard: ",n]}),t.status==="connected"&&a.jsx("span",{className:`mixer-ws-indicator ${o?"ready":"pending"}`,children:o?"Controls Ready":"Connecting Controls..."})]}),a.jsxs("div",{className:"mixer-header-right",children:[a.jsx("span",{className:"mixer-update-time",children:r>0?`Updated ${new Date(r).toLocaleTimeString()}`:""}),a.jsxs("button",{className:`mixer-scenes-btn ${x?"active":""}`,onClick:Vt,title:"Scene Manager",children:["🎬 Scenes",i.length>0&&a.jsx("span",{className:"mixer-scenes-count",children:i.length})]}),a.jsx("button",{className:"mixer-scenes-btn",onClick:l,children:"↻ Refresh"}),a.jsx("button",{className:`mixer-pipedal-btn ${C?"active":""}`,onClick:()=>E(O=>!O),title:"Toggle PiPedal view",children:"🎛️ PiPedal"}),a.jsx("button",{className:`mixer-patch-btn ${T?"active":""}`,onClick:()=>V(O=>!O),title:"Toggle Patch Bay",children:"🔌 Patch"})]})]}),a.jsxs("div",{className:`mixer-content ${C?"mixer-content-split":""}`,children:[a.jsxs("div",{className:"mixer-content-main",children:[!ee&&a.jsxs("div",{className:"mixer-empty",children:[a.jsx("div",{className:"mixer-empty-icon",children:"🎛️"}),a.jsx("h2",{children:"No OPLabs Plugins Found"}),a.jsx("p",{children:"Load OPLabsBandChannel or OPLabsBandBus plugins on the PiPedal pedalboard, then click Refresh."}),t.status!=="connected"&&a.jsxs("p",{className:"mixer-empty-hint",children:["Status: ",a.jsx("strong",{children:t.status}),t.error&&` — ${t.error}`]}),a.jsx("button",{className:"mixer-refresh-btn large",onClick:l,children:"↻ Refresh Now"})]}),D&&a.jsxs("div",{className:"mixer-channels",children:[a.jsxs("div",{className:"mixer-section-header",children:[a.jsx("h2",{children:"Channels"}),a.jsx("span",{className:"mixer-count",children:L.length})]}),a.jsxs("div",{className:"mixer-channels-grid",children:[L.map(O=>a.jsx(lp,{plugin:O,onSetControl:s},O.instanceId)),a.jsx("div",{className:"mixer-add-channel",children:a.jsx("button",{className:"mixer-add-btn",title:"Add channel (future)",children:"+"})})]})]}),Z&&a.jsxs("div",{className:"mixer-buses",children:[a.jsxs("div",{className:"mixer-section-header",children:[a.jsx("h2",{children:"Bus"}),a.jsx("span",{className:"mixer-count",children:j.length})]}),a.jsx("div",{className:"mixer-buses-grid",children:j.map(O=>a.jsx(sp,{plugin:O,onSetControl:s},O.instanceId))})]}),ee&&a.jsxs("div",{className:"mixer-master-section",children:[a.jsx("div",{className:"mixer-section-header",children:a.jsx("h2",{children:"Master"})}),a.jsx("div",{className:"mixer-master-layout",children:a.jsx(ap,{volume:P,mute:I,levelL:Qe,levelR:Ke,onVolumeChange:O=>R(O),onMuteToggle:O=>Q(O)})})]})]})," ",C&&a.jsx("div",{className:"mixer-pipedal-pane",children:a.jsx("iframe",{src:z,title:"PiPedal",className:"mixer-pipedal-iframe",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})})]})," ",T&&a.jsx("div",{className:"mixer-patch-pane",children:a.jsx(qd,{portsState:v,onConnect:w,onDisconnect:M,onDisconnectAll:d,onRefresh:g,actionState:c,actionError:h})}),x&&a.jsx(cp,{scenes:i,loading:u,error:f,onClose:()=>N(!1),onSaveScene:y,onDeleteScene:m,onRecallScene:p,getCurrentState:q})]})},hp=()=>{const{connectionState:e,plugins:t,pedalboardName:n,discover:r,lastUpdate:l}=Qd();return a.jsx("div",{className:"app",children:a.jsx(mp,{plugins:t,connectionState:e,pedalboardName:n,lastUpdate:l,onRefresh:r})})};bl.createRoot(document.getElementById("root")).render(a.jsx(du.StrictMode,{children:a.jsx(hp,{})})); diff --git a/frontend/dist/assets/index-BwT15WG7.css b/frontend/dist/assets/index-BwT15WG7.css new file mode 100644 index 0000000..20a4c2d --- /dev/null +++ b/frontend/dist/assets/index-BwT15WG7.css @@ -0,0 +1 @@ +.patch-bay{background:var(--bg, #1a1a2e);border:1px solid var(--border, #2a2a4a);border-radius:var(--radius, 8px);overflow:hidden;display:flex;flex-direction:column}.patch-bay-header{display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:var(--surface, #16213e);border-bottom:1px solid var(--border, #2a2a4a);gap:12px;flex-wrap:wrap}.patch-bay-title{display:flex;align-items:center;gap:8px;font-size:.95rem;font-weight:600;color:var(--text, #eaeaea)}.patch-icon{font-size:1rem}.patch-conn-count{font-size:.65rem;background:var(--accent, #e94560);color:#fff;padding:1px 6px;border-radius:8px;font-weight:600;min-width:18px;text-align:center}.patch-bay-actions{display:flex;align-items:center;gap:8px}.patch-armed-info{font-size:.72rem;color:var(--accent, #e94560);background:#e945601a;padding:3px 8px;border-radius:4px;white-space:nowrap}.patch-armed-info code{font-weight:600}.patch-action-state{font-size:.7rem;padding:3px 8px;border-radius:4px}.patch-action-state.connecting,.patch-action-state.disconnecting{color:var(--warning, #ff9800);background:#ff98001f}.patch-action-state.error{color:var(--error, #f44336);background:#f443361f}.patch-action-btn{display:flex;align-items:center;gap:4px;background:transparent;color:var(--text-dim, #9e9e9e);border:1px solid var(--border, #2a2a4a);padding:4px 10px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.72rem;transition:all .15s}.patch-action-btn:hover:not(:disabled){border-color:var(--error, #f44336);color:var(--error, #f44336);background:#f4433614}.patch-action-btn:disabled{opacity:.4;cursor:default}.patch-refresh-btn{background:var(--surface-alt, #0f3460);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);padding:4px 10px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.85rem;transition:all .15s}.patch-refresh-btn:hover:not(:disabled){border-color:var(--accent, #e94560);background:#e945601a}.patch-refresh-btn:disabled{opacity:.4;cursor:default}.patch-bay-body{position:relative;display:flex;gap:0;padding:0;overflow-x:auto}.patch-column{display:flex;flex-direction:column;gap:2px;padding:8px 4px;z-index:2;min-width:240px;max-width:300px}.patch-column-left{padding-right:8px;border-right:1px solid var(--border, #2a2a4a)}.patch-column-right{padding-left:8px}.patch-group{margin-bottom:1px}.patch-group-header{display:flex;align-items:center;gap:6px;padding:4px 8px;font-size:.68rem;font-weight:600;text-transform:uppercase;letter-spacing:.8px;color:var(--text-dim, #9e9e9e);background:#ffffff05;border-radius:4px;height:28px}.patch-group-dot{width:6px;height:6px;border-radius:50%;background:var(--text-dim, #9e9e9e)}.patch-group-dot.physical{background:#4fc3f7}.patch-group-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.patch-port{display:flex;align-items:center;gap:6px;padding:5px 8px;height:32px;border-radius:4px;cursor:pointer;transition:all .12s;border-left:2px solid transparent;position:relative}.patch-port:hover{background:#ffffff0d}.patch-port.connected{border-left-color:var(--accent, #e94560);background:#e945600f}.patch-port.armed{border-left-color:#4fc3f7;background:#4fc3f71a;box-shadow:inset 0 0 0 1px #4fc3f74d}.patch-port.available{border-left-color:transparent}.patch-port.available:hover{border-left-color:var(--accent, #e94560);background:#e9456014}.patch-port-indicator{width:4px;height:4px;border-radius:50%;background:var(--accent, #e94560);flex-shrink:0}.patch-port-name{font-size:.78rem;color:var(--text, #eaeaea);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;font-family:SF Mono,Fira Code,Cascadia Code,monospace}.patch-port-name.physical{color:#4fc3f7}.patch-port-conn-count{font-size:.6rem;background:var(--accent, #e94560);color:#fff;padding:0 5px;border-radius:6px;font-weight:600;min-width:14px;text-align:center;flex-shrink:0}.patch-cables-svg{z-index:1;pointer-events:none}.patch-source-note{position:absolute;bottom:4px;right:8px;font-size:.6rem;color:var(--text-dim, #9e9e9e);opacity:.5;z-index:3}.patch-bay-error{display:flex;align-items:center;justify-content:space-between;padding:6px 12px;background:#f4433614;border-top:1px solid rgba(244,67,54,.2);font-size:.72rem;color:var(--error, #f44336)}.patch-bay-error.action{background:#f443361f}.patch-dismiss-btn{background:transparent;border:none;color:var(--error, #f44336);cursor:pointer;font-size:.85rem;padding:2px 6px;border-radius:4px}.patch-dismiss-btn:hover{background:#f4433626}.patch-bay-loading,.patch-bay-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:60px 24px;text-align:center;color:var(--text-dim, #9e9e9e);gap:12px}.patch-empty-icon{font-size:2.5rem;opacity:.5}.patch-bay-empty h3{font-size:1rem;color:var(--text, #eaeaea)}.patch-bay-empty p{font-size:.82rem;max-width:400px;line-height:1.5}.patch-empty-note{font-size:.72rem;opacity:.6}.patch-spinner{width:24px;height:24px;border:2px solid var(--border, #2a2a4a);border-top-color:var(--accent, #e94560);border-radius:50%;animation:patch-spin .8s linear infinite}@keyframes patch-spin{to{transform:rotate(360deg)}}.mixer-patch-btn{display:flex;align-items:center;gap:6px;background:var(--surface-alt, #0f3460);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);padding:6px 12px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.8rem;font-weight:500;transition:all .2s}.mixer-patch-btn:hover{border-color:var(--accent, #e94560);background:#e945601a}.mixer-patch-btn.active{border-color:var(--accent, #e94560);background:#e9456026;color:var(--accent, #e94560)}.mixer-patch-pane{width:100%;padding:12px;overflow-y:auto}.instrument-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:4px;border:1px solid;font-size:.7rem;font-weight:600;letter-spacing:.3px;white-space:nowrap;transition:opacity .2s;-webkit-user-select:none;user-select:none}.instrument-badge:hover{opacity:.85}.instrument-badge[data-size=small]{font-size:.6rem;padding:1px 5px;gap:3px}.instrument-badge[data-size=large]{font-size:.85rem;padding:4px 12px;gap:6px}.instrument-icon{font-size:.8em;line-height:1}.instrument-name{line-height:1}.level-meter{display:flex;flex-direction:column;align-items:center;gap:2px;--meter-green: #4caf50;--meter-yellow: #ff9800;--meter-red: #f44336}.level-meter.mini{gap:1px}.level-meter-stereo-pair{display:flex;gap:2px;flex:1}.level-meter-channel{display:flex;flex-direction:column;align-items:center;gap:1px;width:14px}.level-meter-channel.mini{width:8px}.level-meter-side-label{font-size:.55rem;color:var(--text-dim);font-weight:700;text-transform:uppercase;letter-spacing:.5px}.level-meter-bar-track{position:relative;width:100%;flex:1;min-height:60px;background:#00000080;border-radius:2px;border:1px solid var(--border);overflow:hidden}.level-meter.mini .level-meter-bar-track{min-height:30px}.level-meter-bar-fill{position:absolute;bottom:0;left:0;right:0;transition:height .05s linear;border-radius:1px}.level-meter-peak{position:absolute;left:0;right:0;height:2px;background:#fff;border-radius:1px;transition:bottom .15s ease-out;z-index:2}.level-meter-tick{position:absolute;left:0;right:0;height:1px;background:#ffffff26;z-index:1}.level-meter-tick.mark-yellow{background:#ff98004d}.level-meter-tick.mark-green{background:#4caf5033}.level-meter-label{font-size:.6rem;color:var(--text-dim);text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:60px}.level-meter-db-values{display:flex;gap:4px;font-size:.6rem;font-family:monospace;color:var(--text-dim)}.level-meter-db-values .hot{color:var(--meter-red);font-weight:700}.channel-strip{display:flex;flex-direction:column;align-items:center;gap:6px;padding:10px 8px;background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-top:3px solid #666;border-radius:var(--radius, 8px);min-width:80px;max-width:100px;transition:border-top-color .3s,box-shadow .2s}.channel-strip:hover{box-shadow:0 2px 12px #0000004d}.channel-header{display:flex;flex-direction:column;align-items:center;gap:3px;width:100%}.channel-label{font-size:.7rem;font-weight:600;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;color:var(--text, #eaeaea)}.channel-mute-solo{display:flex;gap:3px;width:100%;justify-content:center}.channel-btn{width:28px;height:22px;border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.65rem;font-weight:700;cursor:pointer;transition:all .15s;background:var(--bg, #1a1a2e);color:var(--text-dim, #9e9e9e);-webkit-user-select:none;user-select:none;line-height:1}.channel-btn.mute.active{background:var(--error, #f44336);color:#fff;border-color:var(--error, #f44336)}.channel-btn.solo.active{background:var(--warning, #ff9800);color:#000;border-color:var(--warning, #ff9800)}.channel-btn:hover{opacity:.85}.channel-meter-section{width:100%;display:flex;justify-content:center;flex:1;min-height:60px}.channel-pan{width:100%;display:flex;flex-direction:column;align-items:center;gap:2px}.channel-pan-label{font-size:.55rem;text-transform:uppercase;color:var(--text-dim, #9e9e9e);letter-spacing:.5px}.channel-pan-control{display:flex;align-items:center;gap:3px;width:100%}.channel-pan-slider{flex:1;-webkit-appearance:none;-moz-appearance:none;appearance:none;height:4px;background:var(--border, #2a2a4a);border-radius:2px;outline:none;cursor:pointer}.channel-pan-slider::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:10px;height:10px;border-radius:50%;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);cursor:pointer}.channel-pan-slider::-moz-range-thumb{width:10px;height:10px;border-radius:50%;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);cursor:pointer}.channel-pan-value{font-size:.55rem;font-family:monospace;color:var(--text-dim, #9e9e9e);min-width:20px;text-align:center}.channel-fader-section{display:flex;flex-direction:column;align-items:center;gap:3px;width:100%}.channel-fader{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:100px;background:linear-gradient(to top,var(--bg, #1a1a2e) 0%,var(--surface-alt, #0f3460) 75%,#4caf50 85%,#ff9800 95%,#f44336 100%);border-radius:4px;outline:none;cursor:pointer;border:1px solid var(--border, #2a2a4a);writing-mode:vertical-lr;direction:rtl}.channel-fader::-webkit-slider-runnable-track{height:100px;border-radius:3px}.channel-fader::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:18px;height:12px;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer;box-shadow:0 1px 3px #0006;margin-left:-3px}.channel-fader::-moz-range-track{height:100px;border-radius:3px}.channel-fader::-moz-range-thumb{width:18px;height:12px;background:var(--channel-accent, #666);border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer;box-shadow:0 1px 3px #0006}.channel-fader-readout{font-size:.6rem;font-family:monospace;color:var(--text-dim, #9e9e9e);text-align:center}.channel-instrument-selector{width:100%}.channel-instrument-select{width:100%;padding:3px 4px;background:var(--bg, #1a1a2e);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.6rem;cursor:pointer;outline:none}.channel-instrument-select:focus{border-color:var(--channel-accent, #666)}.channel-instrument-select option{background:var(--bg, #1a1a2e);color:var(--text, #eaeaea)}.bus-strip{display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-radius:var(--radius, 8px)}.bus-master-section{display:flex;align-items:center;gap:12px;padding-bottom:8px}.bus-master-header{display:flex;flex-direction:column;align-items:center;gap:4px;min-width:50px}.bus-master-label{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--text, #eaeaea)}.bus-master-meter{flex:1;max-width:60px}.bus-master-fader{flex:1;max-width:120px}.bus-btn{width:24px;height:20px;border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.6rem;font-weight:700;cursor:pointer;transition:all .15s;background:var(--bg, #1a1a2e);color:var(--text-dim, #9e9e9e);-webkit-user-select:none;user-select:none;line-height:1;text-align:center}.bus-btn.mute.active{background:var(--error, #f44336);color:#fff;border-color:var(--error, #f44336)}.bus-btn.mini{width:18px;height:16px;font-size:.5rem}.bus-btn:hover{opacity:.85}.bus-divider{height:1px;background:var(--border, #2a2a4a);margin:0 -4px}.bus-channels{display:flex;gap:6px;overflow-x:auto;padding-bottom:4px}.bus-channel{display:flex;flex-direction:column;align-items:center;gap:3px;min-width:36px;max-width:44px;padding:6px 4px;background:var(--bg, #1a1a2e);border-radius:4px;border:1px solid var(--border, #2a2a4a);flex-shrink:0}.bus-channel-label{font-size:.55rem;font-weight:700;color:var(--text-dim, #9e9e9e);text-align:center}.bus-channel-meter{width:100%;height:30px;display:flex;justify-content:center}.bus-channel-fader{width:100%}.bus-channel-db{font-size:.45rem;font-family:monospace;color:var(--text-dim, #9e9e9e);text-align:center}.bus-fader{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:6px;background:var(--border, #2a2a4a);border-radius:3px;outline:none;cursor:pointer;border:none}.bus-fader::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:12px;height:14px;background:#e94560;border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer}.bus-fader::-moz-range-thumb{width:12px;height:14px;background:#e94560;border:1px solid rgba(255,255,255,.3);border-radius:2px;cursor:pointer}.bus-fader.mini{height:4px}.bus-fader.mini::-webkit-slider-thumb{width:8px;height:10px}.bus-fader.mini::-moz-range-thumb{width:8px;height:10px}.bus-channel-route{width:100%;padding:1px 2px;background:var(--bg, #1a1a2e);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.5rem;font-weight:600;cursor:pointer;outline:none;text-align:center;text-align-last:center;-moz-text-align-last:center;min-height:16px;max-height:18px}.bus-channel-route:focus{border-color:var(--accent, #e94560)}.bus-channel-route option{background:var(--bg, #1a1a2e);color:var(--text, #eaeaea);font-size:.55rem}.master-bus{display:flex;flex-direction:column;align-items:center;gap:6px;padding:12px 10px;background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-top:3px solid #a770e4;border-radius:var(--radius, 8px);min-width:90px;max-width:110px;position:relative;transition:border-top-color .3s,opacity .2s}.master-bus:hover{box-shadow:0 2px 16px #a770e426}.master-bus.muted{opacity:.6}.master-bus-header{display:flex;flex-direction:column;align-items:center;gap:2px;width:100%}.master-bus-label{font-size:.75rem;font-weight:700;text-align:center;color:var(--text, #eaeaea);text-transform:uppercase;letter-spacing:.5px}.master-bus-type{font-size:.55rem;text-transform:uppercase;letter-spacing:1px;color:#a770e4;font-weight:600}.master-bus-meters{width:100%;display:flex;justify-content:center;min-height:70px}.master-bus-controls{display:flex;gap:3px;width:100%;justify-content:center}.master-bus-btn{width:32px;height:24px;border:1px solid var(--border, #2a2a4a);border-radius:3px;font-size:.65rem;font-weight:700;cursor:pointer;transition:all .15s;background:var(--bg, #1a1a2e);color:var(--text-dim, #9e9e9e);-webkit-user-select:none;user-select:none;line-height:1}.master-bus-btn.mute.active{background:var(--error, #f44336);color:#fff;border-color:var(--error, #f44336)}.master-bus-btn:hover{opacity:.85}.master-bus-fader-section{display:flex;flex-direction:column;align-items:center;gap:3px;width:100%}.master-bus-fader{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:100%;height:110px;background:linear-gradient(to top,var(--bg, #1a1a2e) 0%,#a770e4 75%,#c084fc 85%,#e94560 95%,#f44336 100%);border-radius:4px;outline:none;cursor:pointer;border:1px solid var(--border, #2a2a4a);writing-mode:vertical-lr;direction:rtl}.master-bus-fader::-webkit-slider-runnable-track{height:110px;border-radius:3px}.master-bus-fader::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:20px;height:14px;background:#a770e4;border:1px solid rgba(255,255,255,.4);border-radius:2px;cursor:pointer;box-shadow:0 1px 4px #00000080;margin-left:-4px}.master-bus-fader::-moz-range-track{height:110px;border-radius:3px}.master-bus-fader::-moz-range-thumb{width:20px;height:14px;background:#a770e4;border:1px solid rgba(255,255,255,.4);border-radius:2px;cursor:pointer;box-shadow:0 1px 4px #00000080}.master-bus-fader-readout{font-size:.6rem;font-family:monospace;color:var(--text-dim, #9e9e9e);text-align:center;min-height:1em}.master-bus-db-values{display:flex;gap:4px;font-size:.6rem;font-family:monospace;color:var(--text-dim, #9e9e9e)}.master-bus-db-values .hot{color:var(--meter-red, #f44336);font-weight:700}.scene-manager-overlay{position:fixed;top:0;right:0;width:360px;height:100vh;background:var(--surface, #16213e);border-left:1px solid var(--border, #2a2a4a);z-index:200;display:flex;flex-direction:column;box-shadow:-4px 0 20px #0006;animation:scene-slide-in .2s ease-out}@keyframes scene-slide-in{0%{transform:translate(100%)}to{transform:translate(0)}}.scene-manager-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--border, #2a2a4a)}.scene-manager-header h2{font-size:1rem;font-weight:600;color:var(--text, #eaeaea);margin:0}.scene-manager-count{font-size:.7rem;background:var(--surface-alt, #0f3460);color:var(--text-dim, #9e9e9e);padding:1px 7px;border-radius:10px;margin-left:8px}.scene-close-btn{background:transparent;border:none;color:var(--text-dim, #9e9e9e);font-size:1.2rem;cursor:pointer;padding:4px 8px;border-radius:4px;line-height:1}.scene-close-btn:hover{background:#ffffff14;color:var(--text, #eaeaea)}.scene-list{flex:1;overflow-y:auto;padding:8px}.scene-list-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;text-align:center;color:var(--text-dim, #9e9e9e);font-size:.85rem;gap:8px}.scene-list-loading{display:flex;align-items:center;justify-content:center;padding:40px;color:var(--text-dim, #9e9e9e);font-size:.85rem}.scene-card{background:var(--bg, #1a1a2e);border-radius:var(--radius, 8px);margin-bottom:8px;border:1px solid var(--border, #2a2a4a);overflow:hidden;transition:border-color .2s}.scene-card:hover{border-color:var(--accent, #e94560)}.scene-card-content{display:flex;align-items:center;padding:10px 12px;gap:10px;cursor:pointer}.scene-card-content:hover{background:#e945600a}.scene-card-name{flex:1;font-size:.9rem;font-weight:500;color:var(--text, #eaeaea);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.scene-card-midi{font-size:.65rem;color:var(--text-dim, #9e9e9e);background:var(--surface-alt, #0f3460);padding:2px 6px;border-radius:4px;font-weight:500}.scene-card-actions{display:flex;gap:4px}.scene-card-btn{background:transparent;border:none;color:var(--text-dim, #9e9e9e);padding:4px 8px;border-radius:4px;cursor:pointer;font-size:.75rem;transition:all .15s}.scene-card-btn:hover{background:#ffffff14;color:var(--text, #eaeaea)}.scene-card-btn.delete:hover{background:#f4433626;color:var(--error, #f44336)}.scene-card-btn.load:hover{background:#4caf5026;color:var(--success, #4caf50)}.scene-card-btn.recall{font-weight:600}.scene-card-btn.recall:hover{background:#e9456026;color:var(--accent, #e94560)}.scene-save-form{padding:12px 16px;border-top:1px solid var(--border, #2a2a4a);display:flex;flex-direction:column;gap:8px}.scene-save-row{display:flex;gap:8px;align-items:center}.scene-name-input{flex:1;background:var(--bg, #1a1a2e);border:1px solid var(--border, #2a2a4a);border-radius:6px;padding:8px 10px;color:var(--text, #eaeaea);font-size:.85rem;outline:none;transition:border-color .2s}.scene-name-input:focus{border-color:var(--accent, #e94560)}.scene-name-input::placeholder{color:var(--text-dim, #9e9e9e)}.scene-save-btn{background:var(--accent, #e94560);color:#fff;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;font-size:.8rem;font-weight:500;white-space:nowrap;transition:opacity .15s}.scene-save-btn:hover{opacity:.85}.scene-save-btn:disabled{opacity:.4;cursor:not-allowed}.scene-midi-input-group{display:flex;align-items:center;gap:6px}.scene-midi-label{font-size:.7rem;color:var(--text-dim, #9e9e9e);white-space:nowrap}.scene-midi-input{width:48px;background:var(--bg, #1a1a2e);border:1px solid var(--border, #2a2a4a);border-radius:4px;padding:4px 6px;color:var(--text, #eaeaea);font-size:.8rem;text-align:center;outline:none}.scene-midi-input:focus{border-color:var(--accent, #e94560)}.scene-error{padding:8px 16px;background:#f443361a;color:var(--error, #f44336);font-size:.75rem;border-top:1px solid rgba(244,67,54,.2)}.scene-confirm-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:#00000080;z-index:300;display:flex;align-items:center;justify-content:center}.scene-confirm-dialog{background:var(--surface, #16213e);border:1px solid var(--border, #2a2a4a);border-radius:var(--radius, 8px);padding:20px 24px;max-width:320px;box-shadow:0 8px 32px #0006}.scene-confirm-dialog p{font-size:.9rem;color:var(--text, #eaeaea);margin-bottom:16px;line-height:1.4}.scene-confirm-actions{display:flex;gap:8px;justify-content:flex-end}.scene-confirm-cancel{background:transparent;border:1px solid var(--border, #2a2a4a);color:var(--text-dim, #9e9e9e);padding:6px 14px;border-radius:6px;cursor:pointer;font-size:.8rem}.scene-confirm-cancel:hover{background:#ffffff0d}.scene-confirm-delete{background:var(--error, #f44336);border:none;color:#fff;padding:6px 14px;border-radius:6px;cursor:pointer;font-size:.8rem;font-weight:500}.scene-confirm-delete:hover{opacity:.85}.scene-recalling{opacity:.6;pointer-events:none}.scene-recalled-flash{animation:scene-flash .6s ease-out}@keyframes scene-flash{0%{border-color:var(--success, #4caf50);box-shadow:0 0 8px #4caf504d}to{border-color:var(--border, #2a2a4a);box-shadow:none}}.mixer-page{display:flex;flex-direction:column;min-height:100vh;background:var(--bg, #1a1a2e);max-width:100%!important}.mixer-header{display:flex;align-items:center;justify-content:space-between;padding:12px 20px;background:var(--surface, #16213e);border-bottom:1px solid var(--border, #2a2a4a);gap:12px;flex-wrap:wrap;position:sticky;top:0;z-index:100}.mixer-header-left{display:flex;align-items:center;gap:16px}.mixer-title{font-size:1.1rem;font-weight:700;color:var(--text, #eaeaea);letter-spacing:.3px}.mixer-header-center{display:flex;align-items:center;gap:12px}.mixer-pedalboard-name{font-size:.8rem;color:var(--accent, #e94560);background:#e945601a;padding:3px 10px;border-radius:var(--radius, 8px)}.mixer-ws-indicator{font-size:.7rem;padding:3px 8px;border-radius:4px;font-weight:500}.mixer-ws-indicator.ready{color:var(--success, #4caf50);background:#4caf501f}.mixer-ws-indicator.pending{color:var(--warning, #ff9800);background:#ff98001f}.mixer-header-right{display:flex;align-items:center;gap:12px}.mixer-update-time{font-size:.7rem;color:var(--text-dim, #9e9e9e)}.mixer-refresh-btn{background:var(--accent, #e94560);color:#fff;border:none;padding:6px 14px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.8rem;font-weight:500;transition:opacity .2s}.mixer-refresh-btn:hover{opacity:.85}.mixer-refresh-btn.large{padding:10px 24px;font-size:.95rem;margin-top:16px}.mixer-scenes-btn{display:flex;align-items:center;gap:6px;background:var(--surface-alt, #0f3460);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);padding:6px 12px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.8rem;font-weight:500;transition:all .2s}.mixer-scenes-btn:hover{border-color:var(--accent, #e94560);background:#e945601a}.mixer-scenes-btn.active{border-color:var(--accent, #e94560);background:#e9456026;color:var(--accent, #e94560)}.mixer-scenes-count{font-size:.65rem;background:var(--accent, #e94560);color:#fff;padding:1px 6px;border-radius:8px;font-weight:600}.mixer-content{flex:1;padding:20px;display:flex;flex-direction:column;gap:24px}.mixer-section-header{display:flex;align-items:center;gap:8px;margin-bottom:4px}.mixer-section-header h2{font-size:.95rem;font-weight:600;color:var(--text, #eaeaea)}.mixer-count{font-size:.7rem;background:var(--surface-alt, #0f3460);color:var(--text-dim, #9e9e9e);padding:1px 7px;border-radius:10px}.mixer-channels-grid{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}.mixer-add-channel{display:flex;align-items:center}.mixer-add-btn{width:40px;height:40px;border-radius:50%;border:2px dashed var(--border, #2a2a4a);background:transparent;color:var(--text-dim, #9e9e9e);font-size:1.3rem;cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center}.mixer-add-btn:hover{border-color:var(--accent, #e94560);color:var(--accent, #e94560);background:#e9456014}.mixer-buses-grid{display:flex;flex-direction:column;gap:10px}.mixer-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:80px 24px;text-align:center;color:var(--text-dim, #9e9e9e);flex:1}.mixer-empty-icon{font-size:3rem;margin-bottom:16px;opacity:.6}.mixer-empty h2{font-size:1.2rem;color:var(--text, #eaeaea);margin-bottom:8px}.mixer-empty p{font-size:.9rem;max-width:400px;line-height:1.5;margin-bottom:4px}.mixer-empty-hint{font-size:.8rem!important;opacity:.7;margin-top:8px!important}.mixer-content-split{display:flex;flex-direction:row;gap:0;padding:0;height:calc(100vh - 60px);overflow:hidden}.mixer-content-split .mixer-content-main{flex:1;overflow-y:auto;padding:20px;border-right:1px solid var(--border, #2a2a4a)}.mixer-pipedal-pane{flex:1;display:flex;flex-direction:column;background:var(--bg, #1a1a2e);min-width:400px}.mixer-pipedal-iframe{width:100%;height:100%;border:none;background:#fff}.mixer-pipedal-btn{display:flex;align-items:center;gap:6px;background:var(--surface-alt, #0f3460);color:var(--text, #eaeaea);border:1px solid var(--border, #2a2a4a);padding:6px 12px;border-radius:var(--radius, 8px);cursor:pointer;font-size:.8rem;font-weight:500;transition:all .2s}.mixer-pipedal-btn:hover{border-color:var(--accent, #e94560);background:#e945601a}.mixer-pipedal-btn.active{border-color:var(--accent, #e94560);background:#e9456026;color:var(--accent, #e94560)}.mixer-master-section{margin-top:12px;padding-top:12px;border-top:1px solid var(--border, #2a2a4a)}.mixer-master-layout{display:flex;gap:10px;justify-content:flex-start}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}:root{--bg: #1a1a2e;--surface: #16213e;--surface-alt: #0f3460;--accent: #e94560;--text: #eaeaea;--text-dim: #9e9e9e;--border: #2a2a4a;--success: #4caf50;--warning: #ff9800;--error: #f44336;--radius: 8px}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;background:var(--bg);color:var(--text);line-height:1.5;min-height:100vh}.app{display:flex;flex-direction:column;min-height:100vh}.connection-status{display:flex;flex-direction:column;gap:4px}.status-indicator{display:flex;align-items:center;gap:8px}.status-dot{width:10px;height:10px;border-radius:50%;display:inline-block}.status-label{font-size:.85rem;color:var(--text-dim)}.status-error{display:flex;align-items:center;gap:8px;font-size:.8rem;color:var(--error)}.retry-btn{background:transparent;border:1px solid var(--error);color:var(--error);padding:2px 8px;border-radius:4px;cursor:pointer;font-size:.75rem}.retry-btn:hover{background:var(--error);color:#fff}.app-footer{display:flex;justify-content:space-between;padding:12px 24px;background:var(--surface);border-top:1px solid var(--border);font-size:.75rem;color:var(--text-dim)} diff --git a/frontend/dist/assets/index-DDgWDHTC.js b/frontend/dist/assets/index-DDgWDHTC.js deleted file mode 100644 index 0d0a6a5..0000000 --- a/frontend/dist/assets/index-DDgWDHTC.js +++ /dev/null @@ -1,40 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const u of l)if(u.type==="childList")for(const o of u.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(l){const u={};return l.integrity&&(u.integrity=l.integrity),l.referrerPolicy&&(u.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?u.credentials="include":l.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function r(l){if(l.ep)return;l.ep=!0;const u=n(l);fetch(l.href,u)}})();function fc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Gi={exports:{}},nl={},Zi={exports:{}},I={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Zn=Symbol.for("react.element"),dc=Symbol.for("react.portal"),pc=Symbol.for("react.fragment"),mc=Symbol.for("react.strict_mode"),hc=Symbol.for("react.profiler"),vc=Symbol.for("react.provider"),yc=Symbol.for("react.context"),gc=Symbol.for("react.forward_ref"),wc=Symbol.for("react.suspense"),kc=Symbol.for("react.memo"),Sc=Symbol.for("react.lazy"),Do=Symbol.iterator;function xc(e){return e===null||typeof e!="object"?null:(e=Do&&e[Do]||e["@@iterator"],typeof e=="function"?e:null)}var Ji={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},qi=Object.assign,bi={};function an(e,t,n){this.props=e,this.context=t,this.refs=bi,this.updater=n||Ji}an.prototype.isReactComponent={};an.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};an.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function es(){}es.prototype=an.prototype;function Au(e,t,n){this.props=e,this.context=t,this.refs=bi,this.updater=n||Ji}var Bu=Au.prototype=new es;Bu.constructor=Au;qi(Bu,an.prototype);Bu.isPureReactComponent=!0;var $o=Array.isArray,ts=Object.prototype.hasOwnProperty,Wu={current:null},ns={key:!0,ref:!0,__self:!0,__source:!0};function rs(e,t,n){var r,l={},u=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(u=""+t.key),t)ts.call(t,r)&&!ns.hasOwnProperty(r)&&(l[r]=t[r]);var i=arguments.length-2;if(i===1)l.children=n;else if(1>>1,J=N[K];if(0>>1;Kl(kl,R))wtl(nr,kl)?(N[K]=nr,N[wt]=R,K=wt):(N[K]=kl,N[gt]=R,K=gt);else if(wtl(nr,R))N[K]=nr,N[wt]=R,K=wt;else break e}}return z}function l(N,z){var R=N.sortIndex-z.sortIndex;return R!==0?R:N.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;e.unstable_now=function(){return u.now()}}else{var o=Date,i=o.now();e.unstable_now=function(){return o.now()-i}}var s=[],c=[],v=1,m=null,d=3,y=!1,g=!1,S=!1,T=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,a=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function p(N){for(var z=n(c);z!==null;){if(z.callback===null)r(c);else if(z.startTime<=N)r(c),z.sortIndex=z.expirationTime,t(s,z);else break;z=n(c)}}function w(N){if(S=!1,p(N),!g)if(n(s)!==null)g=!0,gl(E);else{var z=n(c);z!==null&&wl(w,z.startTime-N)}}function E(N,z){g=!1,S&&(S=!1,f(j),j=-1),y=!0;var R=d;try{for(p(z),m=n(s);m!==null&&(!(m.expirationTime>z)||N&&!L());){var K=m.callback;if(typeof K=="function"){m.callback=null,d=m.priorityLevel;var J=K(m.expirationTime<=z);z=e.unstable_now(),typeof J=="function"?m.callback=J:m===n(s)&&r(s),p(z)}else r(s);m=n(s)}if(m!==null)var tr=!0;else{var gt=n(c);gt!==null&&wl(w,gt.startTime-z),tr=!1}return tr}finally{m=null,d=R,y=!1}}var x=!1,_=null,j=-1,A=5,M=-1;function L(){return!(e.unstable_now()-MN||125K?(N.sortIndex=R,t(c,N),n(s)===null&&N===n(c)&&(S?(f(j),j=-1):S=!0,wl(w,R-K))):(N.sortIndex=J,t(s,N),g||y||(g=!0,gl(E))),N},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(N){var z=d;return function(){var R=d;d=z;try{return N.apply(this,arguments)}finally{d=R}}}})(as);ss.exports=as;var Mc=ss.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Ic=P,we=Mc;function k(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Xl=Object.prototype.hasOwnProperty,Oc=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Vo={},Ao={};function Fc(e){return Xl.call(Ao,e)?!0:Xl.call(Vo,e)?!1:Oc.test(e)?Ao[e]=!0:(Vo[e]=!0,!1)}function Dc(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $c(e,t,n,r){if(t===null||typeof t>"u"||Dc(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ce(e,t,n,r,l,u,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=u,this.removeEmptyString=o}var ne={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ne[e]=new ce(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ne[t]=new ce(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ne[e]=new ce(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ne[e]=new ce(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ne[e]=new ce(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ne[e]=new ce(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ne[e]=new ce(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ne[e]=new ce(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ne[e]=new ce(e,5,!1,e.toLowerCase(),null,!1,!1)});var Qu=/[\-:]([a-z])/g;function Ku(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Qu,Ku);ne[t]=new ce(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Qu,Ku);ne[t]=new ce(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Qu,Ku);ne[t]=new ce(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ne[e]=new ce(e,1,!1,e.toLowerCase(),null,!1,!1)});ne.xlinkHref=new ce("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ne[e]=new ce(e,1,!1,e.toLowerCase(),null,!0,!0)});function Yu(e,t,n,r){var l=ne.hasOwnProperty(t)?ne[t]:null;(l!==null?l.type!==0:r||!(2i||l[o]!==u[i]){var s=` -`+l[o].replace(" at new "," at ");return e.displayName&&s.includes("")&&(s=s.replace("",e.displayName)),s}while(1<=o&&0<=i);break}}}finally{El=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?kn(e):""}function Uc(e){switch(e.tag){case 5:return kn(e.type);case 16:return kn("Lazy");case 13:return kn("Suspense");case 19:return kn("SuspenseList");case 0:case 2:case 15:return e=Cl(e.type,!1),e;case 11:return e=Cl(e.type.render,!1),e;case 1:return e=Cl(e.type,!0),e;default:return""}}function ql(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case $t:return"Fragment";case Dt:return"Portal";case Gl:return"Profiler";case Xu:return"StrictMode";case Zl:return"Suspense";case Jl:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ds:return(e.displayName||"Context")+".Consumer";case fs:return(e._context.displayName||"Context")+".Provider";case Gu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Zu:return t=e.displayName||null,t!==null?t:ql(e.type)||"Memo";case qe:t=e._payload,e=e._init;try{return ql(e(t))}catch{}}return null}function Vc(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ql(t);case 8:return t===Xu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function dt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ms(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ac(e){var t=ms(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,u=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,u.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ur(e){e._valueTracker||(e._valueTracker=Ac(e))}function hs(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ms(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Rr(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function bl(e,t){var n=t.checked;return H({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Wo(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=dt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function vs(e,t){t=t.checked,t!=null&&Yu(e,"checked",t,!1)}function eu(e,t){vs(e,t);var n=dt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?tu(e,t.type,n):t.hasOwnProperty("defaultValue")&&tu(e,t.type,dt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ho(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function tu(e,t,n){(t!=="number"||Rr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Sn=Array.isArray;function Gt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=or.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function In(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Cn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Bc=["Webkit","ms","Moz","O"];Object.keys(Cn).forEach(function(e){Bc.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Cn[t]=Cn[e]})});function ks(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Cn.hasOwnProperty(e)&&Cn[e]?(""+t).trim():t+"px"}function Ss(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ks(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Wc=H({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lu(e,t){if(t){if(Wc[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(k(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(k(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(k(61))}if(t.style!=null&&typeof t.style!="object")throw Error(k(62))}}function uu(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ou=null;function Ju(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var iu=null,Zt=null,Jt=null;function Yo(e){if(e=bn(e)){if(typeof iu!="function")throw Error(k(280));var t=e.stateNode;t&&(t=il(t),iu(e.stateNode,e.type,t))}}function xs(e){Zt?Jt?Jt.push(e):Jt=[e]:Zt=e}function Es(){if(Zt){var e=Zt,t=Jt;if(Jt=Zt=null,Yo(e),t)for(e=0;e>>=0,e===0?32:31-(ef(e)/tf|0)|0}var ir=64,sr=4194304;function xn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Fr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,u=e.pingedLanes,o=n&268435455;if(o!==0){var i=o&~l;i!==0?r=xn(i):(u&=o,u!==0&&(r=xn(u)))}else o=n&~l,o!==0?r=xn(o):u!==0&&(r=xn(u));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,u=t&-t,l>=u||l===16&&(u&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Jn(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Re(t),e[t]=n}function uf(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=_n),ni=" ",ri=!1;function Ws(e,t){switch(e){case"keyup":return If.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hs(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ut=!1;function Ff(e,t){switch(e){case"compositionend":return Hs(t);case"keypress":return t.which!==32?null:(ri=!0,ni);case"textInput":return e=t.data,e===ni&&ri?null:e;default:return null}}function Df(e,t){if(Ut)return e==="compositionend"||!uo&&Ws(e,t)?(e=As(),Er=no=nt=null,Ut=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=ii(n)}}function Xs(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Xs(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Gs(){for(var e=window,t=Rr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Rr(e.document)}return t}function oo(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Kf(e){var t=Gs(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Xs(n.ownerDocument.documentElement,n)){if(r!==null&&oo(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,u=Math.min(r.start,l);r=r.end===void 0?u:Math.min(r.end,l),!e.extend&&u>r&&(l=r,r=u,u=l),l=si(n,u);var o=si(n,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),u>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Vt=null,pu=null,jn=null,mu=!1;function ai(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;mu||Vt==null||Vt!==Rr(r)||(r=Vt,"selectionStart"in r&&oo(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),jn&&Vn(jn,r)||(jn=r,r=Ur(pu,"onSelect"),0Wt||(e.current=ku[Wt],ku[Wt]=null,Wt--)}function D(e,t){Wt++,ku[Wt]=e.current,e.current=t}var pt={},oe=ht(pt),pe=ht(!1),Tt=pt;function nn(e,t){var n=e.type.contextTypes;if(!n)return pt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},u;for(u in n)l[u]=t[u];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function me(e){return e=e.childContextTypes,e!=null}function Ar(){U(pe),U(oe)}function vi(e,t,n){if(oe.current!==pt)throw Error(k(168));D(oe,t),D(pe,n)}function la(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(k(108,Vc(e)||"Unknown",l));return H({},n,r)}function Br(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||pt,Tt=oe.current,D(oe,e),D(pe,pe.current),!0}function yi(e,t,n){var r=e.stateNode;if(!r)throw Error(k(169));n?(e=la(e,t,Tt),r.__reactInternalMemoizedMergedChildContext=e,U(pe),U(oe),D(oe,e)):U(pe),D(pe,n)}var Be=null,sl=!1,$l=!1;function ua(e){Be===null?Be=[e]:Be.push(e)}function ld(e){sl=!0,ua(e)}function vt(){if(!$l&&Be!==null){$l=!0;var e=0,t=F;try{var n=Be;for(F=1;e>=o,l-=o,We=1<<32-Re(t)+l|n<j?(A=_,_=null):A=_.sibling;var M=d(f,_,p[j],w);if(M===null){_===null&&(_=A);break}e&&_&&M.alternate===null&&t(f,_),a=u(M,a,j),x===null?E=M:x.sibling=M,x=M,_=A}if(j===p.length)return n(f,_),V&&St(f,j),E;if(_===null){for(;jj?(A=_,_=null):A=_.sibling;var L=d(f,_,M.value,w);if(L===null){_===null&&(_=A);break}e&&_&&L.alternate===null&&t(f,_),a=u(L,a,j),x===null?E=L:x.sibling=L,x=L,_=A}if(M.done)return n(f,_),V&&St(f,j),E;if(_===null){for(;!M.done;j++,M=p.next())M=m(f,M.value,w),M!==null&&(a=u(M,a,j),x===null?E=M:x.sibling=M,x=M);return V&&St(f,j),E}for(_=r(f,_);!M.done;j++,M=p.next())M=y(_,f,j,M.value,w),M!==null&&(e&&M.alternate!==null&&_.delete(M.key===null?j:M.key),a=u(M,a,j),x===null?E=M:x.sibling=M,x=M);return e&&_.forEach(function(Ve){return t(f,Ve)}),V&&St(f,j),E}function T(f,a,p,w){if(typeof p=="object"&&p!==null&&p.type===$t&&p.key===null&&(p=p.props.children),typeof p=="object"&&p!==null){switch(p.$$typeof){case lr:e:{for(var E=p.key,x=a;x!==null;){if(x.key===E){if(E=p.type,E===$t){if(x.tag===7){n(f,x.sibling),a=l(x,p.props.children),a.return=f,f=a;break e}}else if(x.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===qe&&ki(E)===x.type){n(f,x.sibling),a=l(x,p.props),a.ref=yn(f,x,p),a.return=f,f=a;break e}n(f,x);break}else t(f,x);x=x.sibling}p.type===$t?(a=jt(p.props.children,f.mode,w,p.key),a.return=f,f=a):(w=zr(p.type,p.key,p.props,null,f.mode,w),w.ref=yn(f,a,p),w.return=f,f=w)}return o(f);case Dt:e:{for(x=p.key;a!==null;){if(a.key===x)if(a.tag===4&&a.stateNode.containerInfo===p.containerInfo&&a.stateNode.implementation===p.implementation){n(f,a.sibling),a=l(a,p.children||[]),a.return=f,f=a;break e}else{n(f,a);break}else t(f,a);a=a.sibling}a=Kl(p,f.mode,w),a.return=f,f=a}return o(f);case qe:return x=p._init,T(f,a,x(p._payload),w)}if(Sn(p))return g(f,a,p,w);if(dn(p))return S(f,a,p,w);hr(f,p)}return typeof p=="string"&&p!==""||typeof p=="number"?(p=""+p,a!==null&&a.tag===6?(n(f,a.sibling),a=l(a,p),a.return=f,f=a):(n(f,a),a=Ql(p,f.mode,w),a.return=f,f=a),o(f)):n(f,a)}return T}var ln=aa(!0),ca=aa(!1),Qr=ht(null),Kr=null,Kt=null,co=null;function fo(){co=Kt=Kr=null}function po(e){var t=Qr.current;U(Qr),e._currentValue=t}function Eu(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function bt(e,t){Kr=e,co=Kt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(de=!0),e.firstContext=null)}function _e(e){var t=e._currentValue;if(co!==e)if(e={context:e,memoizedValue:t,next:null},Kt===null){if(Kr===null)throw Error(k(308));Kt=e,Kr.dependencies={lanes:0,firstContext:e}}else Kt=Kt.next=e;return t}var Ct=null;function mo(e){Ct===null?Ct=[e]:Ct.push(e)}function fa(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,mo(t)):(n.next=l.next,l.next=n),t.interleaved=n,Xe(e,r)}function Xe(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var be=!1;function ho(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function da(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Qe(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function st(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,O&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Xe(e,n)}return l=r.interleaved,l===null?(t.next=t,mo(r)):(t.next=l.next,l.next=t),r.interleaved=t,Xe(e,n)}function Nr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bu(e,n)}}function Si(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,u=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};u===null?l=u=o:u=u.next=o,n=n.next}while(n!==null);u===null?l=u=t:u=u.next=t}else l=u=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:u,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Yr(e,t,n,r){var l=e.updateQueue;be=!1;var u=l.firstBaseUpdate,o=l.lastBaseUpdate,i=l.shared.pending;if(i!==null){l.shared.pending=null;var s=i,c=s.next;s.next=null,o===null?u=c:o.next=c,o=s;var v=e.alternate;v!==null&&(v=v.updateQueue,i=v.lastBaseUpdate,i!==o&&(i===null?v.firstBaseUpdate=c:i.next=c,v.lastBaseUpdate=s))}if(u!==null){var m=l.baseState;o=0,v=c=s=null,i=u;do{var d=i.lane,y=i.eventTime;if((r&d)===d){v!==null&&(v=v.next={eventTime:y,lane:0,tag:i.tag,payload:i.payload,callback:i.callback,next:null});e:{var g=e,S=i;switch(d=t,y=n,S.tag){case 1:if(g=S.payload,typeof g=="function"){m=g.call(y,m,d);break e}m=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=S.payload,d=typeof g=="function"?g.call(y,m,d):g,d==null)break e;m=H({},m,d);break e;case 2:be=!0}}i.callback!==null&&i.lane!==0&&(e.flags|=64,d=l.effects,d===null?l.effects=[i]:d.push(i))}else y={eventTime:y,lane:d,tag:i.tag,payload:i.payload,callback:i.callback,next:null},v===null?(c=v=y,s=m):v=v.next=y,o|=d;if(i=i.next,i===null){if(i=l.shared.pending,i===null)break;d=i,i=d.next,d.next=null,l.lastBaseUpdate=d,l.shared.pending=null}}while(!0);if(v===null&&(s=m),l.baseState=s,l.firstBaseUpdate=c,l.lastBaseUpdate=v,t=l.shared.interleaved,t!==null){l=t;do o|=l.lane,l=l.next;while(l!==t)}else u===null&&(l.shared.lanes=0);Rt|=o,e.lanes=o,e.memoizedState=m}}function xi(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Vl.transition;Vl.transition={};try{e(!1),t()}finally{F=n,Vl.transition=r}}function Ta(){return Pe().memoizedState}function sd(e,t,n){var r=ct(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},La(e))za(t,n);else if(n=fa(e,t,n,r),n!==null){var l=se();Me(n,e,r,l),Ra(n,t,r)}}function ad(e,t,n){var r=ct(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(La(e))za(t,l);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var o=t.lastRenderedState,i=u(o,n);if(l.hasEagerState=!0,l.eagerState=i,Ie(i,o)){var s=t.interleaved;s===null?(l.next=l,mo(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=fa(e,t,l,r),n!==null&&(l=se(),Me(n,e,r,l),Ra(n,t,r))}}function La(e){var t=e.alternate;return e===W||t!==null&&t===W}function za(e,t){Tn=Gr=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ra(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bu(e,n)}}var Zr={readContext:_e,useCallback:re,useContext:re,useEffect:re,useImperativeHandle:re,useInsertionEffect:re,useLayoutEffect:re,useMemo:re,useReducer:re,useRef:re,useState:re,useDebugValue:re,useDeferredValue:re,useTransition:re,useMutableSource:re,useSyncExternalStore:re,useId:re,unstable_isNewReconciler:!1},cd={readContext:_e,useCallback:function(e,t){return Fe().memoizedState=[e,t===void 0?null:t],e},useContext:_e,useEffect:Ci,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pr(4194308,4,Ca.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pr(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pr(4,2,e,t)},useMemo:function(e,t){var n=Fe();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Fe();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=sd.bind(null,W,e),[r.memoizedState,e]},useRef:function(e){var t=Fe();return e={current:e},t.memoizedState=e},useState:Ei,useDebugValue:Eo,useDeferredValue:function(e){return Fe().memoizedState=e},useTransition:function(){var e=Ei(!1),t=e[0];return e=id.bind(null,e[1]),Fe().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=W,l=Fe();if(V){if(n===void 0)throw Error(k(407));n=n()}else{if(n=t(),b===null)throw Error(k(349));zt&30||va(r,t,n)}l.memoizedState=n;var u={value:n,getSnapshot:t};return l.queue=u,Ci(ga.bind(null,r,u,e),[e]),r.flags|=2048,Xn(9,ya.bind(null,r,u,n,t),void 0,null),n},useId:function(){var e=Fe(),t=b.identifierPrefix;if(V){var n=He,r=We;n=(r&~(1<<32-Re(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Kn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[De]=t,e[Wn]=r,Ba(e,t,!1,!1),t.stateNode=e;e:{switch(o=uu(n,r),n){case"dialog":$("cancel",e),$("close",e),l=r;break;case"iframe":case"object":case"embed":$("load",e),l=r;break;case"video":case"audio":for(l=0;lsn&&(t.flags|=128,r=!0,gn(u,!1),t.lanes=4194304)}else{if(!r)if(e=Xr(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),gn(u,!0),u.tail===null&&u.tailMode==="hidden"&&!o.alternate&&!V)return le(t),null}else 2*Y()-u.renderingStartTime>sn&&n!==1073741824&&(t.flags|=128,r=!0,gn(u,!1),t.lanes=4194304);u.isBackwards?(o.sibling=t.child,t.child=o):(n=u.last,n!==null?n.sibling=o:t.child=o,u.last=o)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Y(),t.sibling=null,n=B.current,D(B,r?n&1|2:n&1),t):(le(t),null);case 22:case 23:return To(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ve&1073741824&&(le(t),t.subtreeFlags&6&&(t.flags|=8192)):le(t),null;case 24:return null;case 25:return null}throw Error(k(156,t.tag))}function gd(e,t){switch(so(t),t.tag){case 1:return me(t.type)&&Ar(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return un(),U(pe),U(oe),go(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return yo(t),null;case 13:if(U(B),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(k(340));rn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return U(B),null;case 4:return un(),null;case 10:return po(t.type._context),null;case 22:case 23:return To(),null;case 24:return null;default:return null}}var yr=!1,ue=!1,wd=typeof WeakSet=="function"?WeakSet:Set,C=null;function Yt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Q(e,t,r)}else n.current=null}function Ru(e,t,n){try{n()}catch(r){Q(e,t,r)}}var Oi=!1;function kd(e,t){if(hu=Dr,e=Gs(),oo(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,u=r.focusNode;r=r.focusOffset;try{n.nodeType,u.nodeType}catch{n=null;break e}var o=0,i=-1,s=-1,c=0,v=0,m=e,d=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(i=o+l),m!==u||r!==0&&m.nodeType!==3||(s=o+r),m.nodeType===3&&(o+=m.nodeValue.length),(y=m.firstChild)!==null;)d=m,m=y;for(;;){if(m===e)break t;if(d===n&&++c===l&&(i=o),d===u&&++v===r&&(s=o),(y=m.nextSibling)!==null)break;m=d,d=m.parentNode}m=y}n=i===-1||s===-1?null:{start:i,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(vu={focusedElem:e,selectionRange:n},Dr=!1,C=t;C!==null;)if(t=C,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,C=e;else for(;C!==null;){t=C;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var S=g.memoizedProps,T=g.memoizedState,f=t.stateNode,a=f.getSnapshotBeforeUpdate(t.elementType===t.type?S:Te(t.type,S),T);f.__reactInternalSnapshotBeforeUpdate=a}break;case 3:var p=t.stateNode.containerInfo;p.nodeType===1?p.textContent="":p.nodeType===9&&p.documentElement&&p.removeChild(p.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(w){Q(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,C=e;break}C=t.return}return g=Oi,Oi=!1,g}function Ln(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var u=l.destroy;l.destroy=void 0,u!==void 0&&Ru(t,n,u)}l=l.next}while(l!==r)}}function fl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Mu(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Qa(e){var t=e.alternate;t!==null&&(e.alternate=null,Qa(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[De],delete t[Wn],delete t[wu],delete t[nd],delete t[rd])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ka(e){return e.tag===5||e.tag===3||e.tag===4}function Fi(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ka(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Iu(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Vr));else if(r!==4&&(e=e.child,e!==null))for(Iu(e,t,n),e=e.sibling;e!==null;)Iu(e,t,n),e=e.sibling}function Ou(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ou(e,t,n),e=e.sibling;e!==null;)Ou(e,t,n),e=e.sibling}var ee=null,Le=!1;function Je(e,t,n){for(n=n.child;n!==null;)Ya(e,t,n),n=n.sibling}function Ya(e,t,n){if($e&&typeof $e.onCommitFiberUnmount=="function")try{$e.onCommitFiberUnmount(rl,n)}catch{}switch(n.tag){case 5:ue||Yt(n,t);case 6:var r=ee,l=Le;ee=null,Je(e,t,n),ee=r,Le=l,ee!==null&&(Le?(e=ee,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ee.removeChild(n.stateNode));break;case 18:ee!==null&&(Le?(e=ee,n=n.stateNode,e.nodeType===8?Dl(e.parentNode,n):e.nodeType===1&&Dl(e,n),$n(e)):Dl(ee,n.stateNode));break;case 4:r=ee,l=Le,ee=n.stateNode.containerInfo,Le=!0,Je(e,t,n),ee=r,Le=l;break;case 0:case 11:case 14:case 15:if(!ue&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var u=l,o=u.destroy;u=u.tag,o!==void 0&&(u&2||u&4)&&Ru(n,t,o),l=l.next}while(l!==r)}Je(e,t,n);break;case 1:if(!ue&&(Yt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(i){Q(n,t,i)}Je(e,t,n);break;case 21:Je(e,t,n);break;case 22:n.mode&1?(ue=(r=ue)||n.memoizedState!==null,Je(e,t,n),ue=r):Je(e,t,n);break;default:Je(e,t,n)}}function Di(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new wd),t.forEach(function(r){var l=Td.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function je(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~u}if(r=l,r=Y()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*xd(r/1960))-r,10e?16:e,rt===null)var r=!1;else{if(e=rt,rt=null,br=0,O&6)throw Error(k(331));var l=O;for(O|=4,C=e.current;C!==null;){var u=C,o=u.child;if(C.flags&16){var i=u.deletions;if(i!==null){for(var s=0;sY()-Po?Pt(e,0):_o|=n),he(e,t)}function tc(e,t){t===0&&(e.mode&1?(t=sr,sr<<=1,!(sr&130023424)&&(sr=4194304)):t=1);var n=se();e=Xe(e,t),e!==null&&(Jn(e,t,n),he(e,n))}function jd(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),tc(e,n)}function Td(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(t),tc(e,n)}var nc;nc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||pe.current)de=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return de=!1,vd(e,t,n);de=!!(e.flags&131072)}else de=!1,V&&t.flags&1048576&&oa(t,Hr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;jr(e,t),e=t.pendingProps;var l=nn(t,oe.current);bt(t,n),l=ko(null,t,r,e,l,n);var u=So();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,me(r)?(u=!0,Br(t)):u=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,ho(t),l.updater=cl,t.stateNode=l,l._reactInternals=t,Nu(t,r,e,n),t=ju(null,t,r,!0,u,n)):(t.tag=0,V&&u&&io(t),ie(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(jr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=zd(r),e=Te(r,e),l){case 0:t=Pu(null,t,r,e,n);break e;case 1:t=Ri(null,t,r,e,n);break e;case 11:t=Li(null,t,r,e,n);break e;case 14:t=zi(null,t,r,Te(r.type,e),n);break e}throw Error(k(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),Pu(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),Ri(e,t,r,l,n);case 3:e:{if(Ua(t),e===null)throw Error(k(387));r=t.pendingProps,u=t.memoizedState,l=u.element,da(e,t),Yr(t,r,null,n);var o=t.memoizedState;if(r=o.element,u.isDehydrated)if(u={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=u,t.memoizedState=u,t.flags&256){l=on(Error(k(423)),t),t=Mi(e,t,r,n,l);break e}else if(r!==l){l=on(Error(k(424)),t),t=Mi(e,t,r,n,l);break e}else for(ye=it(t.stateNode.containerInfo.firstChild),ge=t,V=!0,ze=null,n=ca(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(rn(),r===l){t=Ge(e,t,n);break e}ie(e,t,r,n)}t=t.child}return t;case 5:return pa(t),e===null&&xu(t),r=t.type,l=t.pendingProps,u=e!==null?e.memoizedProps:null,o=l.children,yu(r,l)?o=null:u!==null&&yu(r,u)&&(t.flags|=32),$a(e,t),ie(e,t,o,n),t.child;case 6:return e===null&&xu(t),null;case 13:return Va(e,t,n);case 4:return vo(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ln(t,null,r,n):ie(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),Li(e,t,r,l,n);case 7:return ie(e,t,t.pendingProps,n),t.child;case 8:return ie(e,t,t.pendingProps.children,n),t.child;case 12:return ie(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,u=t.memoizedProps,o=l.value,D(Qr,r._currentValue),r._currentValue=o,u!==null)if(Ie(u.value,o)){if(u.children===l.children&&!pe.current){t=Ge(e,t,n);break e}}else for(u=t.child,u!==null&&(u.return=t);u!==null;){var i=u.dependencies;if(i!==null){o=u.child;for(var s=i.firstContext;s!==null;){if(s.context===r){if(u.tag===1){s=Qe(-1,n&-n),s.tag=2;var c=u.updateQueue;if(c!==null){c=c.shared;var v=c.pending;v===null?s.next=s:(s.next=v.next,v.next=s),c.pending=s}}u.lanes|=n,s=u.alternate,s!==null&&(s.lanes|=n),Eu(u.return,n,t),i.lanes|=n;break}s=s.next}}else if(u.tag===10)o=u.type===t.type?null:u.child;else if(u.tag===18){if(o=u.return,o===null)throw Error(k(341));o.lanes|=n,i=o.alternate,i!==null&&(i.lanes|=n),Eu(o,n,t),o=u.sibling}else o=u.child;if(o!==null)o.return=u;else for(o=u;o!==null;){if(o===t){o=null;break}if(u=o.sibling,u!==null){u.return=o.return,o=u;break}o=o.return}u=o}ie(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,bt(t,n),l=_e(l),r=r(l),t.flags|=1,ie(e,t,r,n),t.child;case 14:return r=t.type,l=Te(r,t.pendingProps),l=Te(r.type,l),zi(e,t,r,l,n);case 15:return Fa(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Te(r,l),jr(e,t),t.tag=1,me(r)?(e=!0,Br(t)):e=!1,bt(t,n),Ma(t,r,l),Nu(t,r,l,n),ju(null,t,r,!0,e,n);case 19:return Aa(e,t,n);case 22:return Da(e,t,n)}throw Error(k(156,t.tag))};function rc(e,t){return Ls(e,t)}function Ld(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ce(e,t,n,r){return new Ld(e,t,n,r)}function zo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function zd(e){if(typeof e=="function")return zo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Gu)return 11;if(e===Zu)return 14}return 2}function ft(e,t){var n=e.alternate;return n===null?(n=Ce(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function zr(e,t,n,r,l,u){var o=2;if(r=e,typeof e=="function")zo(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case $t:return jt(n.children,l,u,t);case Xu:o=8,l|=8;break;case Gl:return e=Ce(12,n,t,l|2),e.elementType=Gl,e.lanes=u,e;case Zl:return e=Ce(13,n,t,l),e.elementType=Zl,e.lanes=u,e;case Jl:return e=Ce(19,n,t,l),e.elementType=Jl,e.lanes=u,e;case ps:return pl(n,l,u,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case fs:o=10;break e;case ds:o=9;break e;case Gu:o=11;break e;case Zu:o=14;break e;case qe:o=16,r=null;break e}throw Error(k(130,e==null?e:typeof e,""))}return t=Ce(o,n,t,l),t.elementType=e,t.type=r,t.lanes=u,t}function jt(e,t,n,r){return e=Ce(7,e,r,t),e.lanes=n,e}function pl(e,t,n,r){return e=Ce(22,e,r,t),e.elementType=ps,e.lanes=n,e.stateNode={isHidden:!1},e}function Ql(e,t,n){return e=Ce(6,e,null,t),e.lanes=n,e}function Kl(e,t,n){return t=Ce(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Rd(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=_l(0),this.expirationTimes=_l(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=_l(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Ro(e,t,n,r,l,u,o,i,s){return e=new Rd(e,t,n,i,s),t===1?(t=1,u===!0&&(t|=8)):t=0,u=Ce(3,null,null,t),e.current=u,u.stateNode=e,u.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ho(u),e}function Md(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ic)}catch(e){console.error(e)}}ic(),is.exports=ke;var $d=is.exports,Qi=$d;Yl.createRoot=Qi.createRoot,Yl.hydrateRoot=Qi.hydrateRoot;function Ud(){const[e,t]=P.useState({status:"disconnected"}),[n,r]=P.useState([]),[l,u]=P.useState(null),[o,i]=P.useState(0),s=P.useRef(null),c=P.useRef(null),v=P.useRef(!1),m=P.useCallback(()=>{var S;if(((S=s.current)==null?void 0:S.readyState)===WebSocket.OPEN)return;const g=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/pipedal`;t({status:"connecting"});try{const T=new WebSocket(g);T.onopen=()=>{t({status:"connected"})},T.onmessage=f=>{try{const a=JSON.parse(f.data);a.type==="connected"?t({status:"connected"}):a.type==="error"&&t({status:"error",error:a.message})}catch{}},T.onerror=()=>{t({status:"error",error:"WebSocket connection error"})},T.onclose=()=>{v.current||(t({status:"disconnected"}),c.current=window.setTimeout(()=>{v.current||m()},3e3))},s.current=T}catch(T){t({status:"error",error:String(T)})}},[]),d=P.useCallback(async()=>{try{const g=await(await fetch("/api/discover")).json();r(g.oplabs_instances||[]),u(g.pedalboard_name),i(Date.now()),g.connected&&t({status:"connected"})}catch(y){t({status:"error",error:`Discover failed: ${String(y)}`})}},[]);return P.useEffect(()=>(v.current=!1,m(),()=>{v.current=!0,c.current&&clearTimeout(c.current),s.current&&s.current.close()}),[m]),P.useEffect(()=>{e.status==="connected"&&d()},[e.status,d]),{connectionState:e,plugins:n,pedalboardName:l,discover:d,lastUpdate:o}}function Vd(){const e=P.useRef(null),[t,n]=P.useState(!1),r=P.useRef(null),l=P.useRef(!1),u=P.useRef(new Map),o=P.useCallback(()=>{var v;if(((v=e.current)==null?void 0:v.readyState)===WebSocket.OPEN)return;const c=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/pipedal`;try{const m=new WebSocket(c);m.onopen=()=>{n(!0)},m.onmessage=d=>{try{const y=JSON.parse(d.data);if(Array.isArray(y)&&y.length>=1){const g=y[0];if(g.reply!==void 0){const S=u.current.get(g.reply);S&&(S(y[1]||null),u.current.delete(g.reply))}}}catch{}},m.onerror=()=>{n(!1)},m.onclose=()=>{n(!1),u.current.clear(),l.current||(r.current=window.setTimeout(()=>{l.current||o()},3e3))},e.current=m}catch{n(!1)}},[]);P.useEffect(()=>(l.current=!1,o(),()=>{l.current=!0,r.current&&clearTimeout(r.current),e.current&&e.current.close()}),[o]);const i=P.useCallback((s,c,v)=>{if(!e.current||e.current.readyState!==WebSocket.OPEN)return;const m=(Date.now()&2147483647)+Math.floor(Math.random()*1e3),d=JSON.stringify([{message:"setControlValue",replyTo:m},{instanceId:s,key:c,value:v}]);e.current.send(d)},[]);return{ready:t,setControlValue:i}}function Ad(){const[e,t]=P.useState([]),[n,r]=P.useState(!1),[l,u]=P.useState(null),o=P.useCallback(async()=>{r(!0),u(null);try{const m=await fetch("/api/scenes");if(!m.ok)throw new Error(`Failed to load scenes: ${m.statusText}`);const d=await m.json();t(d.scenes||[])}catch(m){const d=m instanceof Error?m.message:String(m);u(d)}finally{r(!1)}},[]);P.useEffect(()=>{o()},[o]);const i=P.useCallback(async(m,d,y)=>{u(null);try{const g=await fetch("/api/scenes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:m,state:d,midiPc:y??null})});if(!g.ok)throw new Error(`Failed to save scene: ${g.statusText}`);await o()}catch(g){const S=g instanceof Error?g.message:String(g);throw u(S),g}},[o]),s=P.useCallback(async(m,d)=>{u(null);try{const y=await fetch(`/api/scenes/${encodeURIComponent(m)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!y.ok)throw new Error(`Failed to update scene: ${y.statusText}`);await o()}catch(y){const g=y instanceof Error?y.message:String(y);u(g)}},[o]),c=P.useCallback(async m=>{u(null);try{const d=await fetch(`/api/scenes/${encodeURIComponent(m)}`,{method:"DELETE"});if(!d.ok)throw new Error(`Failed to delete scene: ${d.statusText}`);await o()}catch(d){const y=d instanceof Error?d.message:String(d);u(y)}},[o]),v=P.useCallback(async m=>{u(null);try{const d=await fetch(`/api/scenes/${encodeURIComponent(m)}/recall`,{method:"POST"});if(!d.ok){const y=await d.json().catch(()=>({}));throw new Error(y.error||`Recall failed: ${d.statusText}`)}return!0}catch(d){const y=d instanceof Error?d.message:String(d);return u(y),!1}},[]);return{scenes:e,loading:n,error:l,saveScene:i,updateScene:s,deleteScene:c,recallScene:v,refreshScenes:o}}const sc={0:"Guitar",1:"Bass",2:"Keys",3:"Vocals",4:"Backing"},ac={0:"#ff8c00",1:"#2196f3",2:"#9c27b0",3:"#e91e63",4:"#009688"},Bd={0:"🎸",1:"🎸",2:"🎹",3:"🎤",4:"🎵"},Wd=({instrument:e,size:t="medium",showIcon:n=!0})=>{const r=sc[e]??`Unknown (${e})`,l=ac[e]??"#666",u=Bd[e]??"";return h.jsxs("span",{className:"instrument-badge","data-size":t,style:{backgroundColor:`${l}22`,color:l,borderColor:l},title:r,children:[n&&h.jsx("span",{className:"instrument-icon",children:u}),h.jsx("span",{className:"instrument-name",children:r})]})},_t=-60,Ki=0;function kt(e){const n=(Math.max(_t,Math.min(Ki,e))-_t)/(Ki-_t);return Math.sqrt(n)*100}const Vu=({levelL:e,levelR:t,label:n,mini:r=!1,peakHold:l=1500})=>{const u=P.useRef(_t),o=P.useRef(_t),i=P.useRef(null),s=P.useRef(null),[,c]=us.useState(0);P.useEffect(()=>{e>u.current&&(u.current=e,i.current&&clearTimeout(i.current),i.current=window.setTimeout(()=>{u.current=Math.max(e,_t),c(T=>T+1)},l)),t>o.current&&(o.current=t,s.current&&clearTimeout(s.current),s.current=window.setTimeout(()=>{o.current=Math.max(t,_t),c(T=>T+1)},l))},[e,t,l]);const v=kt(e),m=kt(t),d=kt(u.current),y=kt(o.current),g=T=>T<60?"var(--meter-green, #4caf50)":T<85?"var(--meter-yellow, #ff9800)":"var(--meter-red, #f44336)",S=(T,f,a)=>h.jsxs("div",{className:`level-meter-channel ${r?"mini":""}`,children:[!r&&h.jsx("span",{className:"level-meter-side-label",children:a}),h.jsxs("div",{className:"level-meter-bar-track",children:[h.jsx("div",{className:"level-meter-bar-fill",style:{height:`${Math.min(100,T)}%`,backgroundColor:g(T)}}),h.jsx("div",{className:"level-meter-peak",style:{bottom:`${Math.min(100,f)}%`}}),!r&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"level-meter-tick",style:{bottom:`${kt(-6)}%`}}),h.jsx("div",{className:"level-meter-tick mark-yellow",style:{bottom:`${kt(-20)}%`}}),h.jsx("div",{className:"level-meter-tick mark-green",style:{bottom:`${kt(-40)}%`}})]})]})]});return h.jsxs("div",{className:`level-meter ${r?"mini":""}`,children:[h.jsxs("div",{className:"level-meter-stereo-pair",children:[S(v,d,"L"),S(m,y,"R")]}),n&&h.jsx("div",{className:"level-meter-label",children:n}),!r&&h.jsxs("div",{className:"level-meter-db-values",children:[h.jsx("span",{className:e>-10?"hot":"",children:e.toFixed(1)}),h.jsx("span",{className:t>-10?"hot":"",children:t.toFixed(1)})]})]})},Hd=[0,1,2,3,4];function Qd(e){if(e<=0)return-60;if(e>=1)return 6;const t=e/.75;if(t<=.001)return-60;const n=20*Math.log10(t);return Math.max(-60,Math.min(6,n))}function Kd(e){if(e<=-60)return 0;if(e>=6)return 1;const t=Math.pow(10,e/20);return Math.min(1,t*.75)}const Yd=({plugin:e,onSetControl:t})=>{const n=e.controlValues,r=n.volume??0,l=n.pan??0,u=(n.mute??0)>=.5,o=(n.solo??0)>=.5,i=Math.round(n.instrument??0)||0,s=n.levelL??-60,c=n.levelR??-60,v=ac[i]??"#666",m=P.useCallback(f=>{const a=parseFloat(f.target.value)/100,p=Qd(a);t(e.instanceId,"volume",parseFloat(p.toFixed(1)))},[e.instanceId,t]),d=P.useCallback(f=>{const a=parseFloat(f.target.value);t(e.instanceId,"pan",a)},[e.instanceId,t]),y=P.useCallback(()=>{t(e.instanceId,"mute",u?0:1)},[e.instanceId,u,t]),g=P.useCallback(()=>{t(e.instanceId,"solo",o?0:1)},[e.instanceId,o,t]),S=P.useCallback(f=>{const a=parseInt(f.target.value,10);t(e.instanceId,"instrument",a)},[e.instanceId,t]),T=Kd(r)*100;return h.jsxs("div",{className:"channel-strip",style:{borderTopColor:v,"--channel-accent":v},children:[h.jsxs("div",{className:"channel-header",children:[h.jsx("span",{className:"channel-label",title:e.title||e.pluginName,children:e.title||e.pluginName||`Ch ${e.instanceId}`}),h.jsx(Wd,{instrument:i,size:"small"})]}),h.jsxs("div",{className:"channel-mute-solo",children:[h.jsx("button",{className:`channel-btn mute ${u?"active":""}`,onClick:y,title:"Mute",children:"M"}),h.jsx("button",{className:`channel-btn solo ${o?"active":""}`,onClick:g,title:"Solo",children:"S"})]}),h.jsx("div",{className:"channel-meter-section",children:h.jsx(Vu,{levelL:s,levelR:c,mini:!1})}),h.jsxs("div",{className:"channel-pan",children:[h.jsx("label",{className:"channel-pan-label",children:"Pan"}),h.jsxs("div",{className:"channel-pan-control",children:[h.jsx("input",{type:"range",min:"-1",max:"1",step:"0.01",value:l,onChange:d,className:"channel-pan-slider",title:`Pan: ${l.toFixed(2)}`}),h.jsx("span",{className:"channel-pan-value",children:l===0?"C":l<0?`L${Math.abs(Math.round(l*100))}`:`R${Math.round(l*100)}`})]})]}),h.jsxs("div",{className:"channel-fader-section",children:[h.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:T,onChange:m,className:"channel-fader",title:`Volume: ${r.toFixed(1)} dB`,orient:"vertical"}),h.jsx("span",{className:"channel-fader-readout",children:r>-60?`${r>=0?"+":""}${r.toFixed(1)}`:"-∞"})]}),h.jsx("div",{className:"channel-instrument-selector",children:h.jsx("select",{value:i,onChange:S,className:"channel-instrument-select",style:{borderColor:v},children:Hd.map(f=>h.jsx("option",{value:f,children:sc[f]},f))})})]})};function Yi(e){return(Math.max(-60,Math.min(6,e))+60)/66*100}function Xi(e){return e/100*66-60}const Xd=({plugin:e,onSetControl:t})=>{const n=e.controlValues,r=n.masterVol??0,l=(n.masterMute??0)>=.5,u=n.masterLevelL??-60,o=n.masterLevelR??-60,i=Array.from({length:8},(d,y)=>{const g=y+1;return{index:g,vol:n[`ch${g}Vol`]??0,mute:(n[`ch${g}Mute`]??0)>=.5,levelL:n[`ch${g}LevelL`]??-60,levelR:n[`ch${g}LevelR`]??-60,volKey:`ch${g}Vol`,muteKey:`ch${g}Mute`}}),s=P.useCallback(d=>{const y=Xi(parseFloat(d.target.value));t(e.instanceId,"masterVol",parseFloat(y.toFixed(1)))},[e.instanceId,t]),c=P.useCallback(()=>{t(e.instanceId,"masterMute",l?0:1)},[e.instanceId,l,t]),v=P.useCallback((d,y,g)=>{const S=Xi(parseFloat(g.target.value));t(e.instanceId,y,parseFloat(S.toFixed(1)))},[e.instanceId,t]),m=P.useCallback((d,y,g)=>{t(e.instanceId,y,g?0:1)},[e.instanceId,t]);return h.jsxs("div",{className:"bus-strip",children:[h.jsxs("div",{className:"bus-master-section",children:[h.jsxs("div",{className:"bus-master-header",children:[h.jsx("span",{className:"bus-master-label",children:"Master"}),h.jsx("button",{className:`bus-btn mute ${l?"active":""}`,onClick:c,title:"Master Mute",children:"M"})]}),h.jsx("div",{className:"bus-master-meter",children:h.jsx(Vu,{levelL:u,levelR:o,mini:!0,label:r>-60?`${r.toFixed(1)}dB`:"-∞"})}),h.jsx("div",{className:"bus-master-fader",children:h.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:Yi(r),onChange:s,className:"bus-fader",title:`Master Volume: ${r.toFixed(1)} dB`})})]}),h.jsx("div",{className:"bus-divider"}),h.jsx("div",{className:"bus-channels",children:i.map(d=>h.jsxs("div",{className:"bus-channel",children:[h.jsx("span",{className:"bus-channel-label",children:d.index}),h.jsx("button",{className:`bus-btn mute mini ${d.mute?"active":""}`,onClick:()=>m(d.index,d.muteKey,d.mute),title:`Ch ${d.index} Mute`,children:"M"}),h.jsx("div",{className:"bus-channel-meter",children:h.jsx(Vu,{levelL:d.levelL,levelR:d.levelR,mini:!0})}),h.jsx("div",{className:"bus-channel-fader",children:h.jsx("input",{type:"range",min:"0",max:"100",step:"0.5",value:Yi(d.vol),onChange:y=>v(d.index,d.volKey,y),className:"bus-fader mini",title:`Ch ${d.index} Volume: ${d.vol.toFixed(1)} dB`})}),h.jsx("span",{className:"bus-channel-db",children:d.vol>-60?d.vol.toFixed(1):"-∞"})]},d.index))})]})},Gd=({scenes:e,loading:t,error:n,onClose:r,onSaveScene:l,onDeleteScene:u,onRecallScene:o,getCurrentState:i})=>{const[s,c]=P.useState(""),[v,m]=P.useState(""),[d,y]=P.useState(!1),[g,S]=P.useState(null),[T,f]=P.useState(null),[a,p]=P.useState(null),[w,E]=P.useState(null),x=n||w,_=P.useCallback(async()=>{const L=s.trim();if(!L)return;const Ve=i();if(!Ve){E("No plugin state available. Refresh plugins first.");return}y(!0),E(null);try{const yt=v.trim()!==""?parseInt(v.trim(),10):null;await l(L,Ve,yt),c(""),m("")}catch{E("Failed to save scene")}finally{y(!1)}},[s,v,i,l]),j=P.useCallback(async L=>{S(L),E(null);try{await o(L)?(f(L),setTimeout(()=>f(null),700)):E("Recall failed — check PiPedal connection")}catch{E("Recall failed")}finally{S(null)}},[o]),A=P.useCallback(async L=>{E(null),p(null);try{await u(L)}catch{E("Failed to delete scene")}},[u]),M=P.useCallback(L=>{L.key==="Enter"&&_()},[_]);return h.jsxs("div",{className:"scene-manager-overlay",children:[h.jsxs("div",{className:"scene-manager-header",children:[h.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[h.jsx("h2",{children:"Scenes"}),h.jsx("span",{className:"scene-manager-count",children:e.length})]}),h.jsx("button",{className:"scene-close-btn",onClick:r,title:"Close",children:"✕"})]}),h.jsxs("div",{className:"scene-list",children:[t&&e.length===0&&h.jsx("div",{className:"scene-list-loading",children:"Loading scenes..."}),!t&&e.length===0&&h.jsxs("div",{className:"scene-list-empty",children:[h.jsx("span",{children:"No saved scenes yet"}),h.jsx("span",{children:"Use the form below to save the current mixer state."})]}),e.map(L=>h.jsx("div",{className:`scene-card ${T===L.id?"scene-recalled-flash":""} ${g===L.id?"scene-recalling":""}`,children:h.jsxs("div",{className:"scene-card-content",children:[h.jsx("span",{className:"scene-card-name",onClick:()=>j(L.id),title:`Recall "${L.name}"`,children:L.name}),L.midiPc!==null&&L.midiPc!==void 0&&h.jsxs("span",{className:"scene-card-midi",children:["PC#",L.midiPc]}),h.jsxs("div",{className:"scene-card-actions",children:[h.jsx("button",{className:"scene-card-btn recall",onClick:()=>j(L.id),disabled:g===L.id,title:"Recall scene",children:"▶ Recall"}),h.jsx("button",{className:"scene-card-btn delete",onClick:()=>p(L.id),title:"Delete scene",children:"✕"})]})]})},L.id))]}),h.jsxs("div",{className:"scene-save-form",children:[h.jsxs("div",{className:"scene-save-row",children:[h.jsx("input",{className:"scene-name-input",type:"text",placeholder:"Scene name...",value:s,onChange:L=>c(L.target.value),onKeyDown:M,maxLength:60}),h.jsx("button",{className:"scene-save-btn",onClick:_,disabled:d||!s.trim(),children:d?"Saving...":"Save"})]}),h.jsx("div",{className:"scene-save-row",children:h.jsxs("div",{className:"scene-midi-input-group",children:[h.jsx("span",{className:"scene-midi-label",children:"MIDI PC:"}),h.jsx("input",{className:"scene-midi-input",type:"number",min:"0",max:"127",placeholder:"—",value:v,onChange:L=>m(L.target.value)})]})})]}),x&&h.jsx("div",{className:"scene-error",children:x}),a!==null&&h.jsx("div",{className:"scene-confirm-overlay",onClick:()=>p(null),children:h.jsxs("div",{className:"scene-confirm-dialog",onClick:L=>L.stopPropagation(),children:[h.jsx("p",{children:"Delete this scene permanently?"}),h.jsxs("div",{className:"scene-confirm-actions",children:[h.jsx("button",{className:"scene-confirm-cancel",onClick:()=>p(null),children:"Cancel"}),h.jsx("button",{className:"scene-confirm-delete",onClick:()=>A(a),children:"Delete"})]})]})})]})},Zd={connected:"#4caf50",connecting:"#ff9800",disconnected:"#9e9e9e",error:"#f44336"},Jd={connected:"Connected to PiPedal",connecting:"Connecting...",disconnected:"Disconnected",error:"Connection Error"},qd=({state:e,onRetry:t})=>h.jsxs("div",{className:"connection-status",children:[h.jsxs("div",{className:"status-indicator",children:[h.jsx("span",{className:"status-dot",style:{backgroundColor:Zd[e.status]||"#9e9e9e"}}),h.jsx("span",{className:"status-label",children:Jd[e.status]||e.status})]}),e.error&&h.jsxs("div",{className:"status-error",children:[h.jsx("span",{children:e.error}),t&&h.jsx("button",{className:"retry-btn",onClick:t,children:"Retry"})]})]}),bd=({plugins:e,connectionState:t,pedalboardName:n,lastUpdate:r,onRefresh:l})=>{const{ready:u,setControlValue:o}=Vd(),{scenes:i,loading:s,error:c,saveScene:v,deleteScene:m,recallScene:d}=Ad(),[y,g]=P.useState(!1),S=P.useMemo(()=>e.filter(x=>!x.uri.includes("band-bus")&&x.uri.includes("band-channel")),[e]),T=P.useMemo(()=>e.filter(x=>x.uri.includes("band-bus")),[e]),f=S.length>0,a=T.length>0,p=e.length>0,w=P.useCallback(()=>e.length===0?null:{channels:S.map(x=>({instanceId:x.instanceId,params:{...x.controlValues}})),buses:T.map(x=>({instanceId:x.instanceId,params:{...x.controlValues}}))},[e,S,T]),E=P.useCallback(()=>{g(x=>!x)},[]);return h.jsxs("div",{className:"mixer-page",children:[h.jsxs("header",{className:"mixer-header",children:[h.jsxs("div",{className:"mixer-header-left",children:[h.jsx("h1",{className:"mixer-title",children:"OPLabs Mixer"}),h.jsx(qd,{state:t,onRetry:l})]}),h.jsxs("div",{className:"mixer-header-center",children:[n&&h.jsxs("span",{className:"mixer-pedalboard-name",children:["Pedalboard: ",n]}),t.status==="connected"&&h.jsx("span",{className:`mixer-ws-indicator ${u?"ready":"pending"}`,children:u?"Controls Ready":"Connecting Controls..."})]}),h.jsxs("div",{className:"mixer-header-right",children:[h.jsx("span",{className:"mixer-update-time",children:r>0?`Updated ${new Date(r).toLocaleTimeString()}`:""}),h.jsxs("button",{className:`mixer-scenes-btn ${y?"active":""}`,onClick:E,title:"Scene Manager",children:["🎬 Scenes",i.length>0&&h.jsx("span",{className:"mixer-scenes-count",children:i.length})]}),h.jsx("button",{className:"mixer-refresh-btn",onClick:l,children:"↻ Refresh"})]})]}),h.jsxs("div",{className:"mixer-content",children:[!p&&h.jsxs("div",{className:"mixer-empty",children:[h.jsx("div",{className:"mixer-empty-icon",children:"🎛️"}),h.jsx("h2",{children:"No OPLabs Plugins Found"}),h.jsx("p",{children:"Load OPLabsBandChannel or OPLabsBandBus plugins on the PiPedal pedalboard, then click Refresh."}),t.status!=="connected"&&h.jsxs("p",{className:"mixer-empty-hint",children:["Status: ",h.jsx("strong",{children:t.status}),t.error&&` — ${t.error}`]}),h.jsx("button",{className:"mixer-refresh-btn large",onClick:l,children:"↻ Refresh Now"})]}),f&&h.jsxs("div",{className:"mixer-channels",children:[h.jsxs("div",{className:"mixer-section-header",children:[h.jsx("h2",{children:"Channels"}),h.jsx("span",{className:"mixer-count",children:S.length})]}),h.jsxs("div",{className:"mixer-channels-grid",children:[S.map(x=>h.jsx(Yd,{plugin:x,onSetControl:o},x.instanceId)),h.jsx("div",{className:"mixer-add-channel",children:h.jsx("button",{className:"mixer-add-btn",title:"Add channel (future)",children:"+"})})]})]}),a&&h.jsxs("div",{className:"mixer-buses",children:[h.jsxs("div",{className:"mixer-section-header",children:[h.jsx("h2",{children:"Bus"}),h.jsx("span",{className:"mixer-count",children:T.length})]}),h.jsx("div",{className:"mixer-buses-grid",children:T.map(x=>h.jsx(Xd,{plugin:x,onSetControl:o},x.instanceId))})]})]}),y&&h.jsx(Gd,{scenes:i,loading:s,error:c,onClose:()=>g(!1),onSaveScene:v,onDeleteScene:m,onRecallScene:d,getCurrentState:w})]})},ep=()=>{const{connectionState:e,plugins:t,pedalboardName:n,discover:r,lastUpdate:l}=Ud();return h.jsx("div",{className:"app",children:h.jsx(bd,{plugins:t,connectionState:e,pedalboardName:n,lastUpdate:l,onRefresh:r})})};Yl.createRoot(document.getElementById("root")).render(h.jsx(us.StrictMode,{children:h.jsx(ep,{})})); diff --git a/frontend/dist/index.html b/frontend/dist/index.html index b4eb695..fdef174 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -4,8 +4,8 @@ OPLabs Mixer - - + +
diff --git a/frontend/src/components/MixerPage/BusStrip.css b/frontend/src/components/MixerPage/BusStrip.css index f7cc137..1b16155 100644 --- a/frontend/src/components/MixerPage/BusStrip.css +++ b/frontend/src/components/MixerPage/BusStrip.css @@ -180,3 +180,33 @@ width: 8px; height: 10px; } + +/* ---- Routing Selector ---- */ + +.bus-channel-route { + width: 100%; + padding: 1px 2px; + background: var(--bg, #1a1a2e); + color: var(--text, #eaeaea); + border: 1px solid var(--border, #2a2a4a); + border-radius: 3px; + font-size: 0.5rem; + font-weight: 600; + cursor: pointer; + outline: none; + text-align: center; + text-align-last: center; + -moz-text-align-last: center; + min-height: 16px; + max-height: 18px; +} + +.bus-channel-route:focus { + border-color: var(--accent, #e94560); +} + +.bus-channel-route option { + background: var(--bg, #1a1a2e); + color: var(--text, #eaeaea); + font-size: 0.55rem; +} diff --git a/frontend/src/components/MixerPage/BusStrip.tsx b/frontend/src/components/MixerPage/BusStrip.tsx index c61f649..d4f4d5e 100644 --- a/frontend/src/components/MixerPage/BusStrip.tsx +++ b/frontend/src/components/MixerPage/BusStrip.tsx @@ -10,6 +10,18 @@ interface Props { onSetControl: (instanceId: number, key: string, value: number) => void; } +/** Available routing targets for bus channels */ +const ROUTE_TARGETS = [ + { value: 1, label: 'Main' }, + { value: 2, label: 'Bus 2' }, + { value: 3, label: 'Bus 3' }, + { value: 4, label: 'Bus 4' }, + { value: 5, label: 'Bus 5' }, + { value: 6, label: 'Bus 6' }, + { value: 7, label: 'Bus 7' }, + { value: 8, label: 'Bus 8' }, +]; + /** * Converts a dB value to a mini-fader position (0-100). */ @@ -23,10 +35,12 @@ function sliderPosToDb(pos: number): number { } /** - * Bus meter bridge: per-channel mini faders and mute buttons + master section. + * Bus meter bridge: per-channel mini faders, mute buttons, routing selector, + * and master section. * - * The OPLabsBandBus plugin has 62 ports: + * The OPLabsBandBus plugin has 70 ports: * - ch1Vol..ch8Vol, ch1Pan..ch8Pan, ch1Mute..ch8Mute + * - ch1Route..ch8Route (routing: 1=Main, 2-8=sub-buses) * - ch1LevelL..ch8LevelL, ch1LevelR..ch8LevelR * - masterVol, masterMute, masterLevelL, masterLevelR */ @@ -44,10 +58,12 @@ export const BusStrip: React.FC = ({ plugin, onSetControl }) => { index: idx, vol: cv[`ch${idx}Vol`] ?? 0, mute: (cv[`ch${idx}Mute`] ?? 0) >= 0.5, + route: Math.round(cv[`ch${idx}Route`] ?? 1) as 1|2|3|4|5|6|7|8, levelL: cv[`ch${idx}LevelL`] ?? -60, levelR: cv[`ch${idx}LevelR`] ?? -60, volKey: `ch${idx}Vol` as const, muteKey: `ch${idx}Mute` as const, + routeKey: `ch${idx}Route` as const, }; }); @@ -78,6 +94,14 @@ export const BusStrip: React.FC = ({ plugin, onSetControl }) => { [plugin.instanceId, onSetControl] ); + const handleChannelRoute = useCallback( + (chIdx: number, routeKey: string, e: React.ChangeEvent) => { + const val = parseInt(e.target.value, 10); + onSetControl(plugin.instanceId, routeKey, val); + }, + [plugin.instanceId, onSetControl] + ); + return (
{/* Master section */} @@ -122,7 +146,7 @@ export const BusStrip: React.FC = ({ plugin, onSetControl }) => { {channels.map((ch) => (
- {ch.index} + Ch {ch.index} + {/* Routing selector */} +
void; +// ── Types ────────────────────────────────────────────────────────── + +/** Channel type matching the daemon's MixerChannelType enum. */ +export type ChannelType = 'instrument' | 'mic' | 'line' | 'auxReturn'; + +export const CHANNEL_TYPE_LABELS: Record = { + instrument: 'Instrument', + mic: 'Mic', + line: 'Line', + auxReturn: 'Aux Return', +}; + +export const CHANNEL_TYPE_COLORS: Record = { + instrument: '#ff8c00', // orange + mic: '#e91e63', // pink + line: '#2196f3', // blue + auxReturn: '#9c27b0', // purple +}; + +export const CHANNEL_TYPE_ICONS: Record = { + instrument: '🎸', + mic: '🎤', + line: '🔌', + auxReturn: '📥', +}; + +export const CHANNEL_TYPES: ChannelType[] = ['instrument', 'mic', 'line', 'auxReturn']; + +export interface ChannelStripProps { + /** Unique mixer-engine instance id. */ + instanceId: number; + /** 0-based channel index (displayed as N+1). */ + channelIndex: number; + /** User-assignable label shown at the top of the strip. */ + label: string; + /** Volume in dB (-96 to +12). */ + volume: number; + /** Pan: -1.0 (L) to +1.0 (R). 0.0 = centre. */ + pan: number; + /** Mute state. */ + mute: boolean; + /** Solo state. */ + solo: boolean; + /** Channel type classification (controls accent colour). */ + channelType: ChannelType; + /** High-pass filter enabled. */ + hpEnabled: boolean; + /** High-pass filter corner frequency in Hz (20–400). */ + hpFrequency: number; + /** Left-channel VU level in dB (-96 to 0). */ + levelL: number; + /** Right-channel VU level in dB (-96 to 0). */ + levelR: number; + + // ── Callbacks ───────────────────────────────────────────────── + + onChangeVolume: (instanceId: number, db: number) => void; + onChangePan: (instanceId: number, pan: number) => void; + onToggleMute: (instanceId: number, mute: boolean) => void; + onToggleSolo: (instanceId: number, solo: boolean) => void; + onChangeChannelType: (instanceId: number, type: ChannelType) => void; + onToggleHp: (instanceId: number, enabled: boolean) => void; + onChangeHpFrequency: (instanceId: number, freq: number) => void; + onChangeLabel: (instanceId: number, label: string) => void; } -const INSTRUMENT_VALUES: Instrument[] = [0, 1, 2, 3, 4]; +// ── dB ↔ Slider position (logarithmic) ──────────────────────────── /** - * Map a dB slider position (0-1) to a dB value (-60..+6). - * 75% position = 0 dB (unity). + * Map slider position (0–100) to dB value (-60..+6). + * 75% position = 0 dB (unity), logarithmic taper. */ function posToDb(pos: number): number { if (pos <= 0) return -60; - if (pos >= 1) return 6; - // Logarithmic taper: 0.75 = 0 dB - const scaled = pos / 0.75; + if (pos >= 100) return 6; + const scaled = (pos / 100) / 0.75; if (scaled <= 0.001) return -60; const db = 20 * Math.log10(scaled); return Math.max(-60, Math.min(6, db)); } /** - * Map a dB value (-60..+6) to a slider position (0-1). + * Map dB value (-60..+6) to slider position (0–100). */ function dbToPos(db: number): number { if (db <= -60) return 0; - if (db >= 6) return 1; - // Inverse of posToDb + if (db >= 6) return 100; const linear = Math.pow(10, db / 20); - return Math.min(1, linear * 0.75); + return Math.min(100, linear * 0.75 * 100); } /** - * Full channel strip with fader, pan, mute/solo, instrument selector, level meter. + * Format dB for display. */ -export const ChannelStrip: React.FC = ({ plugin, onSetControl }) => { - const cv = plugin.controlValues; +function formatDb(db: number): string { + if (db <= -60) return '-∞'; + return `${db >= 0 ? '+' : ''}${db.toFixed(1)}`; +} - const volume = cv.volume ?? 0; - const pan = cv.pan ?? 0; - const mute = (cv.mute ?? 0) >= 0.5; - const solo = (cv.solo ?? 0) >= 0.5; - const instrument = (Math.round(cv.instrument ?? 0) || 0) as Instrument; - const levelL = cv.levelL ?? -60; - const levelR = cv.levelR ?? -60; +/** + * Format pan for display. + */ +function formatPan(pan: number): string { + if (pan === 0) return 'C'; + if (pan < 0) return `L${Math.abs(Math.round(pan * 100))}`; + return `R${Math.round(pan * 100)}`; +} - const instrumentColor = INSTRUMENT_COLORS[instrument] ?? '#666'; +// ── Component ────────────────────────────────────────────────────── - const handleVolumeChange = useCallback( +const ChannelStrip: React.FC = ({ + instanceId, + channelIndex, + label, + volume, + pan, + mute, + solo, + channelType, + hpEnabled, + hpFrequency, + levelL, + levelR, + onChangeVolume, + onChangePan, + onToggleMute, + onToggleSolo, + onChangeChannelType, + onToggleHp, + onChangeHpFrequency, + onChangeLabel, +}) => { + const accentColor = CHANNEL_TYPE_COLORS[channelType] ?? '#666'; + const [editingLabel, setEditingLabel] = useState(false); + const [labelDraft, setLabelDraft] = useState(label); + const labelInputRef = useRef(null); + + const volumeSliderPos = Math.round(dbToPos(volume)); + + // ── Handlers ───────────────────────────────────────────────── + + const handleVolChange = useCallback( (e: React.ChangeEvent) => { - const pos = parseFloat(e.target.value) / 100; - const db = posToDb(pos); - onSetControl(plugin.instanceId, 'volume', parseFloat(db.toFixed(1))); + const db = posToDb(parseFloat(e.target.value)); + onChangeVolume(instanceId, parseFloat(db.toFixed(1))); }, - [plugin.instanceId, onSetControl] + [instanceId, onChangeVolume], ); const handlePanChange = useCallback( (e: React.ChangeEvent) => { - const val = parseFloat(e.target.value); - onSetControl(plugin.instanceId, 'pan', val); + onChangePan(instanceId, parseFloat(e.target.value)); }, - [plugin.instanceId, onSetControl] + [instanceId, onChangePan], ); - const toggleMute = useCallback(() => { - onSetControl(plugin.instanceId, 'mute', mute ? 0 : 1); - }, [plugin.instanceId, mute, onSetControl]); + const handleMuteClick = useCallback(() => { + onToggleMute(instanceId, !mute); + }, [instanceId, mute, onToggleMute]); - const toggleSolo = useCallback(() => { - onSetControl(plugin.instanceId, 'solo', solo ? 0 : 1); - }, [plugin.instanceId, solo, onSetControl]); + const handleSoloClick = useCallback(() => { + onToggleSolo(instanceId, !solo); + }, [instanceId, solo, onToggleSolo]); - const handleInstrumentChange = useCallback( + const handleTypeChange = useCallback( (e: React.ChangeEvent) => { - const val = parseInt(e.target.value, 10); - onSetControl(plugin.instanceId, 'instrument', val); + onChangeChannelType(instanceId, e.target.value as ChannelType); }, - [plugin.instanceId, onSetControl] + [instanceId, onChangeChannelType], ); - const volumeSliderPos = dbToPos(volume) * 100; + const handleHpToggle = useCallback(() => { + onToggleHp(instanceId, !hpEnabled); + }, [instanceId, hpEnabled, onToggleHp]); + + const handleHpFreqChange = useCallback( + (e: React.ChangeEvent) => { + onChangeHpFrequency(instanceId, parseFloat(e.target.value)); + }, + [instanceId, onChangeHpFrequency], + ); + + const handleLabelClick = useCallback(() => { + setLabelDraft(label); + setEditingLabel(true); + // Focus input on next tick + requestAnimationFrame(() => labelInputRef.current?.focus()); + }, [label]); + + const handleLabelSubmit = useCallback(() => { + const trimmed = labelDraft.trim(); + if (trimmed && trimmed !== label) { + onChangeLabel(instanceId, trimmed); + } + setEditingLabel(false); + }, [labelDraft, label, instanceId, onChangeLabel]); + + const handleLabelKeyDown = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === 'Enter') { + handleLabelSubmit(); + } else if (e.key === 'Escape') { + setEditingLabel(false); + } + }, + [handleLabelSubmit], + ); + + // Format HPF frequency for display + const hzLabel = hpFrequency >= 100 + ? `${Math.round(hpFrequency)} Hz` + : `${hpFrequency.toFixed(0)} Hz`; return (
- {/* Header: channel label + instrument */} + {/* ── Header: editable label + type badge ── */}
- - {plugin.title || plugin.pluginName || `Ch ${plugin.instanceId}`} + {editingLabel ? ( + setLabelDraft(e.target.value)} + onBlur={handleLabelSubmit} + onKeyDown={handleLabelKeyDown} + maxLength={32} + /> + ) : ( + + {label || `Ch ${channelIndex + 1}`} + + )} + + {CHANNEL_TYPE_ICONS[channelType]} + {CHANNEL_TYPE_LABELS[channelType]} -
- {/* Mute & Solo buttons */} + {/* ── HPF Section ── */} +
+ + {hpEnabled && ( +
+ + {hzLabel} +
+ )} +
+ + {/* ── Level Meter ── */} +
+ +
+ + {/* ── Mute & Solo ── */}
- {/* Level Meter */} -
- -
- - {/* Pan control */} + {/* ── Pan Control ── */}
@@ -140,15 +333,13 @@ export const ChannelStrip: React.FC = ({ plugin, onSetControl }) => { value={pan} onChange={handlePanChange} className="channel-pan-slider" - title={`Pan: ${pan.toFixed(2)}`} + title={`Pan: ${formatPan(pan)}`} /> - - {pan === 0 ? 'C' : pan < 0 ? `L${Math.abs(Math.round(pan * 100))}` : `R${Math.round(pan * 100)}`} - + {formatPan(pan)}
- {/* Volume fader */} + {/* ── Volume Fader ── */}
= ({ plugin, onSetControl }) => { max="100" step="0.5" value={volumeSliderPos} - onChange={handleVolumeChange} + onChange={handleVolChange} className="channel-fader" - title={`Volume: ${volume.toFixed(1)} dB`} + title={`Volume: ${formatDb(volume)}`} {...({ orient: 'vertical' } as React.InputHTMLAttributes)} /> - - {volume > -60 ? `${volume >= 0 ? '+' : ''}${volume.toFixed(1)}` : '-∞'} - + {formatDb(volume)}
- {/* Instrument selector */} -
+ {/* ── Channel Type Selector ── */} +
@@ -184,3 +373,5 @@ export const ChannelStrip: React.FC = ({ plugin, onSetControl }) => {
); }; + +export default ChannelStrip; diff --git a/frontend/src/components/MixerPage/MasterBus.css b/frontend/src/components/MixerPage/MasterBus.css new file mode 100644 index 0000000..aa182c4 --- /dev/null +++ b/frontend/src/components/MixerPage/MasterBus.css @@ -0,0 +1,183 @@ +/* ---- Master Bus ---- */ +/* Styled in PiPedal theme with purple accent to differentiate from channels */ + +.master-bus { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + padding: 12px 10px; + background: var(--surface, #16213e); + border: 1px solid var(--border, #2a2a4a); + border-top: 3px solid #a770e4; + border-radius: var(--radius, 8px); + min-width: 90px; + max-width: 110px; + position: relative; + transition: border-top-color 0.3s, opacity 0.2s; +} + +.master-bus:hover { + box-shadow: 0 2px 16px rgba(167, 112, 228, 0.15); +} + +.master-bus.muted { + opacity: 0.6; +} + +/* ---- Header ---- */ + +.master-bus-header { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + width: 100%; +} + +.master-bus-label { + font-size: 0.75rem; + font-weight: 700; + text-align: center; + color: var(--text, #eaeaea); + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.master-bus-type { + font-size: 0.55rem; + text-transform: uppercase; + letter-spacing: 1px; + color: #a770e4; + font-weight: 600; +} + +/* ---- Level Meters ---- */ + +.master-bus-meters { + width: 100%; + display: flex; + justify-content: center; + min-height: 70px; +} + +/* ---- Controls ---- */ + +.master-bus-controls { + display: flex; + gap: 3px; + width: 100%; + justify-content: center; +} + +.master-bus-btn { + width: 32px; + height: 24px; + border: 1px solid var(--border, #2a2a4a); + border-radius: 3px; + font-size: 0.65rem; + font-weight: 700; + cursor: pointer; + transition: all 0.15s; + background: var(--bg, #1a1a2e); + color: var(--text-dim, #9e9e9e); + user-select: none; + line-height: 1; +} + +.master-bus-btn.mute.active { + background: var(--error, #f44336); + color: #fff; + border-color: var(--error, #f44336); +} + +.master-bus-btn:hover { + opacity: 0.85; +} + +/* ---- Fader ---- */ + +.master-bus-fader-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 3px; + width: 100%; +} + +.master-bus-fader { + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 110px; + background: linear-gradient( + to top, + var(--bg, #1a1a2e) 0%, + #a770e4 75%, + #c084fc 85%, + #e94560 95%, + #f44336 100% + ); + border-radius: 4px; + outline: none; + cursor: pointer; + border: 1px solid var(--border, #2a2a4a); + writing-mode: vertical-lr; + direction: rtl; +} + +.master-bus-fader::-webkit-slider-runnable-track { + height: 110px; + border-radius: 3px; +} + +.master-bus-fader::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 20px; + height: 14px; + background: #a770e4; + border: 1px solid rgba(255, 255, 255, 0.4); + border-radius: 2px; + cursor: pointer; + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5); + margin-left: -4px; +} + +.master-bus-fader::-moz-range-track { + height: 110px; + border-radius: 3px; +} + +.master-bus-fader::-moz-range-thumb { + width: 20px; + height: 14px; + background: #a770e4; + border: 1px solid rgba(255, 255, 255, 0.4); + border-radius: 2px; + cursor: pointer; + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5); +} + +.master-bus-fader-readout { + font-size: 0.6rem; + font-family: monospace; + color: var(--text-dim, #9e9e9e); + text-align: center; + min-height: 1em; +} + +/* ---- dB values ---- */ + +.master-bus-db-values { + display: flex; + gap: 4px; + font-size: 0.6rem; + font-family: monospace; + color: var(--text-dim, #9e9e9e); +} + +.master-bus-db-values .hot { + color: var(--meter-red, #f44336); + font-weight: 700; +} diff --git a/frontend/src/components/MixerPage/MasterBus.tsx b/frontend/src/components/MixerPage/MasterBus.tsx new file mode 100644 index 0000000..6341771 --- /dev/null +++ b/frontend/src/components/MixerPage/MasterBus.tsx @@ -0,0 +1,126 @@ +import React, { useCallback } from 'react'; +import { LevelMeter } from './LevelMeter'; +import './MasterBus.css'; + +interface Props { + /** Current volume in dB (-60 .. +6) */ + volume: number; + /** Whether master is muted */ + mute: boolean; + /** Left channel level in dB */ + levelL: number; + /** Right channel level in dB */ + levelR: number; + /** Callback when volume changes */ + onVolumeChange: (db: number) => void; + /** Callback when mute toggles */ + onMuteToggle: (muted: boolean) => void; + /** Optional label (defaults to "Master") */ + label?: string; +} + +/** + * Map a dB slider position (0-1) to a dB value (-60..+6). + * 75% position = 0 dB (unity). + */ +function posToDb(pos: number): number { + if (pos <= 0) return -60; + if (pos >= 1) return 6; + const scaled = pos / 0.75; + if (scaled <= 0.001) return -60; + const db = 20 * Math.log10(scaled); + return Math.max(-60, Math.min(6, db)); +} + +/** + * Map a dB value (-60..+6) to a slider position (0-1). + */ +function dbToPos(db: number): number { + if (db <= -60) return 0; + if (db >= 6) return 1; + const linear = Math.pow(10, db / 20); + return Math.min(1, linear * 0.75); +} + +/** + * Master bus — final stereo mix output with fader, mute, and level meters. + * Styled in PiPedal theme, visually distinct from channel strips. + */ +export const MasterBus: React.FC = ({ + volume, + mute, + levelL, + levelR, + onVolumeChange, + onMuteToggle, + label = 'Master', +}) => { + const volumeSliderPos = dbToPos(volume) * 100; + + const handleVolumeChange = useCallback( + (e: React.ChangeEvent) => { + const pos = parseFloat(e.target.value) / 100; + const db = posToDb(pos); + onVolumeChange(parseFloat(db.toFixed(1))); + }, + [onVolumeChange] + ); + + const handleMuteClick = useCallback(() => { + onMuteToggle(!mute); + }, [mute, onMuteToggle]); + + return ( +
+ {/* Header */} +
+ {label} + Main Out +
+ + {/* Level meters */} +
+ +
+ + {/* Mute button */} +
+ +
+ + {/* Volume fader */} +
+ )} + /> + + {mute + ? 'MUTED' + : volume > -60 + ? `${volume >= 0 ? '+' : ''}${volume.toFixed(1)}` + : '-∞'} + +
+ + {/* dB values under meter */} +
+ -10 ? 'hot' : ''}>{levelL.toFixed(1)} + -10 ? 'hot' : ''}>{levelR.toFixed(1)} +
+
+ ); +}; diff --git a/frontend/src/components/MixerPage/MixerPage.css b/frontend/src/components/MixerPage/MixerPage.css index 6f670c7..8070468 100644 --- a/frontend/src/components/MixerPage/MixerPage.css +++ b/frontend/src/components/MixerPage/MixerPage.css @@ -252,3 +252,79 @@ opacity: 0.7; margin-top: 8px !important; } + +/* ---- Split Layout (when PiPedal iframe is shown) ---- */ + +.mixer-content-split { + display: flex; + flex-direction: row; + gap: 0; + padding: 0; + height: calc(100vh - 60px); + overflow: hidden; +} + +.mixer-content-split .mixer-content-main { + flex: 1; + overflow-y: auto; + padding: 20px; + border-right: 1px solid var(--border, #2a2a4a); +} + +/* ---- PiPedal Iframe Pane ---- */ + +.mixer-pipedal-pane { + flex: 1; + display: flex; + flex-direction: column; + background: var(--bg, #1a1a2e); + min-width: 400px; +} + +.mixer-pipedal-iframe { + width: 100%; + height: 100%; + border: none; + background: #fff; +} + +/* PiPedal toggle button */ +.mixer-pipedal-btn { + display: flex; + align-items: center; + gap: 6px; + background: var(--surface-alt, #0f3460); + color: var(--text, #eaeaea); + border: 1px solid var(--border, #2a2a4a); + padding: 6px 12px; + border-radius: var(--radius, 8px); + cursor: pointer; + font-size: 0.8rem; + font-weight: 500; + transition: all 0.2s; +} + +.mixer-pipedal-btn:hover { + border-color: var(--accent, #e94560); + background: rgba(233, 69, 96, 0.1); +} + +.mixer-pipedal-btn.active { + border-color: var(--accent, #e94560); + background: rgba(233, 69, 96, 0.15); + color: var(--accent, #e94560); +} + +/* ---- Master Section ---- */ + +.mixer-master-section { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid var(--border, #2a2a4a); +} + +.mixer-master-layout { + display: flex; + gap: 10px; + justify-content: flex-start; +} diff --git a/frontend/src/components/MixerPage/MixerPage.tsx b/frontend/src/components/MixerPage/MixerPage.tsx index a9a6756..f82a23e 100644 --- a/frontend/src/components/MixerPage/MixerPage.tsx +++ b/frontend/src/components/MixerPage/MixerPage.tsx @@ -3,8 +3,11 @@ import type { PluginInstance } from '../../hooks/usePiPedalWS'; import type { SceneState } from '../../hooks/useScenes'; import { useMixerControls } from '../../hooks/useMixerControls'; import { useScenes } from '../../hooks/useScenes'; +import { useJackPorts } from '../../hooks/useJackPorts'; +import { PatchBay } from '../PatchBay/PatchBay'; import { ChannelStrip } from './ChannelStrip'; import { BusStrip } from './BusStrip'; +import { MasterBus } from './MasterBus'; import { SceneManager } from '../Scenes/SceneManager'; import { ConnectionStatus } from '../ConnectionStatus'; import type { ConnectionState } from '../../hooks/usePiPedalWS'; @@ -13,6 +16,10 @@ import './ChannelStrip.css'; import './BusStrip.css'; import './LevelMeter.css'; import './InstrumentBadge.css'; +import '../PatchBay/PatchBay.css'; +import './LevelMeter.css'; +import './InstrumentBadge.css'; +import './MasterBus.css'; interface Props { plugins: PluginInstance[]; @@ -24,9 +31,9 @@ interface Props { /** * Main mixer page layout. - * - Header with connection status and scene selector - * - Sidebar of channel strips (left) - * - Bus meter bridge (right) + * - Header with connection status, PiPedal toggle, scene selector + * - Left pane: channel strips + bus strips + * - Right pane: PiPedal iframe (when toggled) * - Scene management sidebar */ export const MixerPage: React.FC = ({ @@ -46,7 +53,22 @@ export const MixerPage: React.FC = ({ recallScene, } = useScenes(); + const { + portsState, + refresh: refreshJack, + connect, + disconnect, + disconnectAll, + actionState, + actionError, + } = useJackPorts(); + const [scenePanelOpen, setScenePanelOpen] = useState(false); + const [showPiPedal, setShowPiPedal] = useState(false); + const [showPatchBay, setShowPatchBay] = useState(false); + + // PiPedal iframe URL — use the Pi's IP since the browser accesses this from another machine + const pipedalUrl = `http://192.168.0.245:8080/`; // Separate plugins by type const channels = useMemo( @@ -67,6 +89,22 @@ export const MixerPage: React.FC = ({ const hasBuses = buses.length > 0; const hasAny = plugins.length > 0; + // Derive master bus state from bus plugin data + // For now, use average of bus master levels as master levels; + // volume/mute are local-state placeholders until backend exposes master output. + const masterLevelL = useMemo(() => { + if (!hasBuses) return -60; + return Math.max(...buses.map((b) => b.controlValues.masterLevelL ?? -60)); + }, [buses, hasBuses]); + + const masterLevelR = useMemo(() => { + if (!hasBuses) return -60; + return Math.max(...buses.map((b) => b.controlValues.masterLevelR ?? -60)); + }, [buses, hasBuses]); + + const [masterVolume, setMasterVolume] = useState(0); + const [masterMute, setMasterMute] = useState(false); + /** * Capture current plugin state for saving as a scene. * Returns channels and buses with their instanceIds and current controlValues. @@ -126,79 +164,142 @@ export const MixerPage: React.FC = ({ {scenes.length} )} - + +
- {/* Main content */} -
- {/* Empty state */} - {!hasAny && ( -
-
🎛️
-

No OPLabs Plugins Found

-

- Load OPLabsBandChannel or OPLabsBandBus plugins on the PiPedal - pedalboard, then click Refresh. -

- {connectionState.status !== 'connected' && ( -

- Status: {connectionState.status} - {connectionState.error && ` — ${connectionState.error}`} + {/* Main content — splits into two panes when PiPedal is shown */} +

+ {/* Left pane: mixer controls */} +
+ {/* Empty state */} + {!hasAny && ( +
+
🎛️
+

No OPLabs Plugins Found

+

+ Load OPLabsBandChannel or OPLabsBandBus plugins on the PiPedal + pedalboard, then click Refresh.

- )} - -
- )} - - {/* Channel strips */} - {hasChannels && ( -
-
-

Channels

- {channels.length} + {connectionState.status !== 'connected' && ( +

+ Status: {connectionState.status} + {connectionState.error && ` — ${connectionState.error}`} +

+ )} +
-
- {channels.map((plugin) => ( - - ))} - {/* Add channel button */} -
- + )} + + {/* Channel strips */} + {hasChannels && ( +
+
+

Channels

+ {channels.length} +
+
+ {channels.map((plugin) => ( + + ))} + {/* Add channel button */} +
+ +
-
- )} + )} - {/* Bus strips */} - {hasBuses && ( -
-
-

Bus

- {buses.length} + {/* Bus strips */} + {hasBuses && ( +
+
+

Bus

+ {buses.length} +
+
+ {buses.map((plugin) => ( + + ))} +
-
- {buses.map((plugin) => ( - +
+

Master

+
+
+ setMasterVolume(db)} + onMuteToggle={(muted: boolean) => setMasterMute(muted)} /> - ))} +
+ )} +
{/* end mixer-content-main */} + + {/* Right pane: PiPedal iframe (when toggled) */} + {showPiPedal && ( +
+