Spaces:
Paused
Paused
MacBook pro
commited on
Commit
·
e530e72
1
Parent(s):
8dffa70
feat: phase1-2 baseline echo scaffold
Browse files- .gitignore +23 -0
- Dockerfile +8 -0
- README.md +25 -12
- SPEC.md +93 -0
- app.py +62 -0
- requirements.txt +4 -0
- static/app.js +224 -0
- static/index.html +23 -0
- static/worklet.js +86 -0
.gitignore
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pycache/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*.pyo
|
| 4 |
+
*.pyd
|
| 5 |
+
*.so
|
| 6 |
+
*.egg-info/
|
| 7 |
+
dist/
|
| 8 |
+
build/
|
| 9 |
+
.env
|
| 10 |
+
.venv
|
| 11 |
+
venv/
|
| 12 |
+
env/
|
| 13 |
+
node_modules/
|
| 14 |
+
*.log
|
| 15 |
+
.vscode/
|
| 16 |
+
.idea/
|
| 17 |
+
.DS_Store
|
| 18 |
+
Thumbs.db
|
| 19 |
+
pip-wheel-metadata/
|
| 20 |
+
.cache/
|
| 21 |
+
coverage/
|
| 22 |
+
models/
|
| 23 |
+
checkpoints/
|
Dockerfile
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
ENV PYTHONUNBUFFERED=1
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY requirements.txt .
|
| 5 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 6 |
+
COPY . /app
|
| 7 |
+
EXPOSE 7860
|
| 8 |
+
CMD ["uvicorn","app:app","--host","0.0.0.0","--port","7860"]
|
README.md
CHANGED
|
@@ -1,12 +1,25 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Mirage
|
| 2 |
+
|
| 3 |
+
Phase 1–2 FastAPI + WebSocket echo scaffold (no ML models yet).
|
| 4 |
+
|
| 5 |
+
## Current Status
|
| 6 |
+
- CPU baseline
|
| 7 |
+
- `/audio` & `/video` echo
|
| 8 |
+
- Static client
|
| 9 |
+
|
| 10 |
+
## Planned Phases
|
| 11 |
+
- GPU switch
|
| 12 |
+
- Metrics
|
| 13 |
+
- Voice skeleton
|
| 14 |
+
- Video skeleton
|
| 15 |
+
- Adaptation
|
| 16 |
+
- Security
|
| 17 |
+
|
| 18 |
+
## Local Run
|
| 19 |
+
```bash
|
| 20 |
+
pip install -r requirements.txt
|
| 21 |
+
uvicorn app:app --port 7860
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## License
|
| 25 |
+
MIT
|
SPEC.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Goals
|
| 2 |
+
- End-to-end audio latency < 250 ms (capture -> inference -> playback)
|
| 3 |
+
- Video pipeline: 512x512 @ ≥20 FPS target under load
|
| 4 |
+
|
| 5 |
+
## Hardware Target
|
| 6 |
+
- Phase 1–2: CPU basic (development + echo scaffolds)
|
| 7 |
+
- Later phases: Single NVIDIA A10G (24GB) for combined audio + video low-latency inference
|
| 8 |
+
|
| 9 |
+
## Voice Pipeline
|
| 10 |
+
| Item | Planned |
|
| 11 |
+
|------|---------|
|
| 12 |
+
| Framework | TODO |
|
| 13 |
+
| Content Encoder | TODO |
|
| 14 |
+
| F0 Extractor | RMVPE |
|
| 15 |
+
| Chunk Size | 192 ms |
|
| 16 |
+
| Sample Rate | 16 kHz |
|
| 17 |
+
| Precision | FP16 mixed |
|
| 18 |
+
| Overlap-Add | disabled |
|
| 19 |
+
| Accept Threshold | < 0.65 * chunk_ms ratio runtime/real |
|
| 20 |
+
| Fail Condition | > 0.80 * chunk_ms for 40 consecutive chunks |
|
| 21 |
+
|
| 22 |
+
## Video Pipeline
|
| 23 |
+
| Item | Planned |
|
| 24 |
+
|------|---------|
|
| 25 |
+
| Model | TODO |
|
| 26 |
+
| Detector | SCRFD |
|
| 27 |
+
| Detect Interval | 5 frames |
|
| 28 |
+
| Resolution | 512x512 |
|
| 29 |
+
| FPS Target | 20 |
|
| 30 |
+
| Confidence Threshold (stable) | ≥0.85 |
|
| 31 |
+
| Re-detect Threshold | <0.70 confidence triggers re-detect next frame |
|
| 32 |
+
| Quality Degrade Order | quality → fps → resolution |
|
| 33 |
+
|
| 34 |
+
## Transport
|
| 35 |
+
- WebSockets (bi-directional control + media chunks)
|
| 36 |
+
- Audio: PCM16, 16 kHz, mono frames (chunked ~192 ms)
|
| 37 |
+
- Video: JPEG compressed frames (progressive baseline) initially
|
| 38 |
+
|
| 39 |
+
## Sync Strategy
|
| 40 |
+
- Audio clock is master timeline
|
| 41 |
+
- Drop late video frames if video timestamp >150 ms behind audio head
|
| 42 |
+
- Never let audio lead video by more than 150 ms (else request video degrade)
|
| 43 |
+
- If sustained drift (>120 frames) re-align by soft skip (video) not audio stretch
|
| 44 |
+
|
| 45 |
+
## Metrics
|
| 46 |
+
Planned collection (no aggregation service yet):
|
| 47 |
+
- Audio chunks processed (count, accept ratio)
|
| 48 |
+
- Per-stage timings: encode / f0 / convert / post
|
| 49 |
+
- Video frames processed & dropped
|
| 50 |
+
- Detector invoke interval stats
|
| 51 |
+
- GPU memory (allocated / reserved / fragmentation indicator)
|
| 52 |
+
- Queue backlog lengths (audio, video, outbound)
|
| 53 |
+
|
| 54 |
+
## Adaptation Rules
|
| 55 |
+
- Increase audio chunk size if runtime/real ratio >0.75 for last 40 chunks
|
| 56 |
+
- Decrease audio chunk size if runtime/real ratio <0.55 for last 120 chunks
|
| 57 |
+
- Video degrade order:
|
| 58 |
+
1. Lower quality (JPEG quality step down)
|
| 59 |
+
2. Reduce FPS toward 15
|
| 60 |
+
3. Reduce resolution (512 → 384 → 256)
|
| 61 |
+
- Restore in reverse order after 300 stable frames (<0.60 ratio)
|
| 62 |
+
|
| 63 |
+
## Security
|
| 64 |
+
- Planned: JWT token required for WebSocket upgrade
|
| 65 |
+
- Rate limiting (connection + message frequency)
|
| 66 |
+
- Frame size guard (reject > configured max bytes)
|
| 67 |
+
- Basic anomaly detection: abandon session if >30% frames invalid over 200 frame window
|
| 68 |
+
|
| 69 |
+
## Licensing
|
| 70 |
+
- Current: MIT
|
| 71 |
+
- Future: Add `LICENSES.md` enumerating third-party components and model licenses
|
| 72 |
+
|
| 73 |
+
## Phases
|
| 74 |
+
| Phase | Status |
|
| 75 |
+
|-------|--------|
|
| 76 |
+
| 1 | Pending |
|
| 77 |
+
| 2 | Pending |
|
| 78 |
+
| 3 | Pending |
|
| 79 |
+
| 4 | Pending |
|
| 80 |
+
| 5 | Pending |
|
| 81 |
+
| 6 | Pending |
|
| 82 |
+
| 7 | Pending |
|
| 83 |
+
| 8 | Pending |
|
| 84 |
+
| 9 | Pending |
|
| 85 |
+
| 10 | Pending |
|
| 86 |
+
|
| 87 |
+
## Open Questions
|
| 88 |
+
- RVC fork URL to adopt / baseline? (Need candidate repo)
|
| 89 |
+
- Reenact / face animation model repo selection?
|
| 90 |
+
- Alignment expectation: do we need phoneme-level alignment or chunk-level only?
|
| 91 |
+
|
| 92 |
+
## Face Detector Standardization
|
| 93 |
+
Adopt SCRFD as unified face detector. Run detection every 5 frames; reuse boxes otherwise. Force immediate re-detect if last confidence <0.70. Consider face track stable when confidence ≥0.85 for 3 consecutive detections. This reduces detector load while maintaining robustness against drift and occlusion.
|
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 2 |
+
from fastapi.responses import HTMLResponse
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
app = FastAPI(title="Mirage Phase 1+2 Scaffold")
|
| 8 |
+
|
| 9 |
+
# Mount the static directory
|
| 10 |
+
static_dir = Path(__file__).parent / "static"
|
| 11 |
+
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@app.get("/", response_class=HTMLResponse)
|
| 15 |
+
async def root():
|
| 16 |
+
"""Serve the static/index.html file contents as HTML."""
|
| 17 |
+
index_path = static_dir / "index.html"
|
| 18 |
+
try:
|
| 19 |
+
content = index_path.read_text(encoding="utf-8")
|
| 20 |
+
except FileNotFoundError:
|
| 21 |
+
# Minimal fallback to satisfy route even if file not yet present.
|
| 22 |
+
content = "<html><body><h1>Mirage Scaffold</h1><p>Place an index.html in /static.</p></body></html>"
|
| 23 |
+
return HTMLResponse(content)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@app.get("/health")
|
| 27 |
+
async def health():
|
| 28 |
+
return {"status": "ok", "phase": "baseline"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
async def _echo_websocket(websocket: WebSocket, kind: str):
|
| 32 |
+
await websocket.accept()
|
| 33 |
+
while True:
|
| 34 |
+
try:
|
| 35 |
+
data = await websocket.receive_bytes()
|
| 36 |
+
# Echo straight back
|
| 37 |
+
await websocket.send_bytes(data)
|
| 38 |
+
except WebSocketDisconnect:
|
| 39 |
+
# Silent disconnect
|
| 40 |
+
break
|
| 41 |
+
except Exception: # noqa: BLE001
|
| 42 |
+
# Print traceback for unexpected errors, then break loop
|
| 43 |
+
print(f"[{kind} ws] Unexpected error:")
|
| 44 |
+
traceback.print_exc()
|
| 45 |
+
break
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@app.websocket("/audio")
|
| 49 |
+
async def audio_ws(websocket: WebSocket):
|
| 50 |
+
await _echo_websocket(websocket, "audio")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@app.websocket("/video")
|
| 54 |
+
async def video_ws(websocket: WebSocket):
|
| 55 |
+
await _echo_websocket(websocket, "video")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Note: The Dockerfile / README launch with: uvicorn app:app --port 7860
|
| 59 |
+
if __name__ == "__main__": # Optional direct run helper
|
| 60 |
+
import uvicorn # type: ignore
|
| 61 |
+
|
| 62 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
websockets
|
| 4 |
+
jinja2
|
static/app.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Mirage Echo Baseline Client */
|
| 2 |
+
|
| 3 |
+
// Globals (scoped to this module)
|
| 4 |
+
let audioWs = null;
|
| 5 |
+
let videoWs = null;
|
| 6 |
+
let audioContext = null;
|
| 7 |
+
let processorNode = null; // AudioWorkletNode for capturing (pcm-chunker)
|
| 8 |
+
let playerNode = null; // AudioWorkletNode for playback (pcm-player)
|
| 9 |
+
let lastVideoSentTs = 0;
|
| 10 |
+
let remoteImageURL = null;
|
| 11 |
+
|
| 12 |
+
const LOG_EL = document.getElementById('log');
|
| 13 |
+
const START_BTN = document.getElementById('startBtn');
|
| 14 |
+
const LOCAL_VID = document.getElementById('localVid');
|
| 15 |
+
const REMOTE_VID_IMG = document.getElementById('remoteVid');
|
| 16 |
+
const REMOTE_AUDIO = document.getElementById('remoteAudio');
|
| 17 |
+
|
| 18 |
+
function log(msg) {
|
| 19 |
+
const ts = new Date().toISOString().split('T')[1].replace('Z','');
|
| 20 |
+
LOG_EL.textContent += `[${ts}] ${msg}\n`;
|
| 21 |
+
LOG_EL.scrollTop = LOG_EL.scrollHeight;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
function wsURL(path) {
|
| 25 |
+
const proto = (location.protocol === 'https:') ? 'wss:' : 'ws:';
|
| 26 |
+
return `${proto}//${location.host}${path}`;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
async function setupAudio(stream) {
|
| 30 |
+
audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 16000 });
|
| 31 |
+
if (audioContext.state === 'suspended') {
|
| 32 |
+
try { await audioContext.resume(); } catch (e) { log('AudioContext resume failed'); }
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// Worklet loading
|
| 36 |
+
try {
|
| 37 |
+
await audioContext.audioWorklet.addModule('/static/worklet.js');
|
| 38 |
+
} catch (e) {
|
| 39 |
+
log('Failed to load worklet.js (pcm-chunker) - audio sending disabled.');
|
| 40 |
+
console.error(e);
|
| 41 |
+
return;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
const samplesPerChunk = Math.round(audioContext.sampleRate * 0.25); // 250 ms -> spec said 0.25 (192ms earlier spec but instruction uses 0.25 here)
|
| 45 |
+
log(`AudioContext sampleRate=${audioContext.sampleRate}, samplesPerChunk=${samplesPerChunk}`);
|
| 46 |
+
processorNode = new AudioWorkletNode(audioContext, 'pcm-chunker', {
|
| 47 |
+
processorOptions: { samplesPerChunk }
|
| 48 |
+
});
|
| 49 |
+
playerNode = new AudioWorkletNode(audioContext, 'pcm-player');
|
| 50 |
+
|
| 51 |
+
// Capture mic
|
| 52 |
+
const source = audioContext.createMediaStreamSource(stream);
|
| 53 |
+
source.connect(processorNode);
|
| 54 |
+
// Keep worklet active via silent gain path (0 gain) to destination (some browsers optimize away otherwise)
|
| 55 |
+
const gain = audioContext.createGain();
|
| 56 |
+
gain.gain.value = 0;
|
| 57 |
+
processorNode.connect(gain).connect(audioContext.destination);
|
| 58 |
+
// Do NOT connect processorNode to destination to avoid local direct monitor; playback handled by pcm-player.
|
| 59 |
+
|
| 60 |
+
processorNode.port.onmessage = (event) => {
|
| 61 |
+
if (!audioWs || audioWs.readyState !== WebSocket.OPEN) return;
|
| 62 |
+
const ab = event.data;
|
| 63 |
+
if (ab instanceof ArrayBuffer) audioWs.send(ab);
|
| 64 |
+
};
|
| 65 |
+
|
| 66 |
+
// Connect playback node
|
| 67 |
+
playerNode.connect(audioContext.destination);
|
| 68 |
+
log('Audio nodes ready (pcm-chunker + pcm-player)');
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
let _rxChunks = 0;
|
| 72 |
+
let _loopback = false;
|
| 73 |
+
function setupAudioWebSocket() {
|
| 74 |
+
audioWs = new WebSocket(wsURL('/audio'));
|
| 75 |
+
audioWs.binaryType = 'arraybuffer';
|
| 76 |
+
audioWs.onopen = () => log('Audio WS open');
|
| 77 |
+
audioWs.onclose = () => log('Audio WS closed');
|
| 78 |
+
audioWs.onerror = (e) => log('Audio WS error');
|
| 79 |
+
audioWs.onmessage = (evt) => {
|
| 80 |
+
if (!(evt.data instanceof ArrayBuffer)) return;
|
| 81 |
+
// Clone buffer BEFORE transferring to avoid ArrayBuffer detachment errors when reusing
|
| 82 |
+
const src = evt.data;
|
| 83 |
+
const copyBuf = src.slice(0); // shallow copy; original remains intact for stats
|
| 84 |
+
// Amplitude stats (compute on copy or original before transfer)
|
| 85 |
+
const view = new Int16Array(src);
|
| 86 |
+
let min = 32767, max = -32768;
|
| 87 |
+
for (let i=0;i<view.length;i++) { const v=view[i]; if (v<min) min=v; if (v>max) max=v; }
|
| 88 |
+
// Forward copy to player (transfer copy to avoid overhead next GC cycle)
|
| 89 |
+
if (playerNode) playerNode.port.postMessage(copyBuf, [copyBuf]);
|
| 90 |
+
_rxChunks++;
|
| 91 |
+
if ((_rxChunks % 20) === 0) {
|
| 92 |
+
log(`Audio chunks received: ${_rxChunks} amp:[${min},${max}]`);
|
| 93 |
+
}
|
| 94 |
+
if (_loopback && audioWs && audioWs.readyState === WebSocket.OPEN) {
|
| 95 |
+
// echo back again (will double) purely for test; guard to prevent infinite recursion (already from server)
|
| 96 |
+
}
|
| 97 |
+
};
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
async function setupVideo(stream) {
|
| 101 |
+
const track = stream.getVideoTracks()[0];
|
| 102 |
+
if (!track) {
|
| 103 |
+
log('No video track found');
|
| 104 |
+
return;
|
| 105 |
+
}
|
| 106 |
+
const processor = new MediaStreamTrackProcessor({ track });
|
| 107 |
+
const reader = processor.readable.getReader();
|
| 108 |
+
|
| 109 |
+
const canvas = document.createElement('canvas');
|
| 110 |
+
canvas.width = 256;
|
| 111 |
+
canvas.height = 256;
|
| 112 |
+
const ctx = canvas.getContext('2d');
|
| 113 |
+
|
| 114 |
+
async function readLoop() {
|
| 115 |
+
try {
|
| 116 |
+
const { value: frame, done } = await reader.read();
|
| 117 |
+
if (done) return;
|
| 118 |
+
|
| 119 |
+
const now = performance.now();
|
| 120 |
+
const needSend = (now - lastVideoSentTs) >= 100; // ~10 fps
|
| 121 |
+
|
| 122 |
+
if (needSend && frame) {
|
| 123 |
+
try {
|
| 124 |
+
// Draw frame
|
| 125 |
+
if ('displayWidth' in frame && 'displayHeight' in frame) {
|
| 126 |
+
ctx.drawImage(frame, 0, 0, canvas.width, canvas.height);
|
| 127 |
+
} else {
|
| 128 |
+
// Fallback path: createImageBitmap then draw
|
| 129 |
+
const bmp = await createImageBitmap(frame);
|
| 130 |
+
ctx.drawImage(bmp, 0, 0, canvas.width, canvas.height);
|
| 131 |
+
bmp.close && bmp.close();
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
await new Promise((res, rej) => {
|
| 135 |
+
canvas.toBlob((blob) => {
|
| 136 |
+
if (!blob) return res();
|
| 137 |
+
blob.arrayBuffer().then((ab) => {
|
| 138 |
+
if (videoWs && videoWs.readyState === WebSocket.OPEN) {
|
| 139 |
+
videoWs.send(ab);
|
| 140 |
+
}
|
| 141 |
+
res();
|
| 142 |
+
}).catch(rej);
|
| 143 |
+
}, 'image/jpeg', 0.65);
|
| 144 |
+
});
|
| 145 |
+
lastVideoSentTs = now;
|
| 146 |
+
} catch (err) {
|
| 147 |
+
log('Video frame send error');
|
| 148 |
+
console.error(err);
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
frame.close && frame.close();
|
| 153 |
+
readLoop();
|
| 154 |
+
} catch (err) {
|
| 155 |
+
log('Video read loop error');
|
| 156 |
+
console.error(err);
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
readLoop();
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
function setupVideoWebSocket() {
|
| 163 |
+
videoWs = new WebSocket(wsURL('/video'));
|
| 164 |
+
videoWs.binaryType = 'arraybuffer';
|
| 165 |
+
videoWs.onopen = () => log('Video WS open');
|
| 166 |
+
videoWs.onclose = () => log('Video WS closed');
|
| 167 |
+
videoWs.onerror = () => log('Video WS error');
|
| 168 |
+
videoWs.onmessage = (evt) => {
|
| 169 |
+
if (!(evt.data instanceof ArrayBuffer)) return;
|
| 170 |
+
const blob = new Blob([evt.data], { type: 'image/jpeg' });
|
| 171 |
+
if (remoteImageURL) URL.revokeObjectURL(remoteImageURL);
|
| 172 |
+
remoteImageURL = URL.createObjectURL(blob);
|
| 173 |
+
REMOTE_VID_IMG.src = remoteImageURL;
|
| 174 |
+
};
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
async function start() {
|
| 178 |
+
START_BTN.disabled = true;
|
| 179 |
+
log('Requesting media...');
|
| 180 |
+
let stream;
|
| 181 |
+
try {
|
| 182 |
+
stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
|
| 183 |
+
} catch (e) {
|
| 184 |
+
log('getUserMedia failed');
|
| 185 |
+
console.error(e);
|
| 186 |
+
START_BTN.disabled = false;
|
| 187 |
+
return;
|
| 188 |
+
}
|
| 189 |
+
LOCAL_VID.srcObject = stream;
|
| 190 |
+
log('Media acquired');
|
| 191 |
+
|
| 192 |
+
setupAudioWebSocket();
|
| 193 |
+
setupVideoWebSocket();
|
| 194 |
+
await setupAudio(stream);
|
| 195 |
+
await setupVideo(stream);
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
START_BTN.addEventListener('click', start);
|
| 199 |
+
|
| 200 |
+
// Expose for debugging
|
| 201 |
+
function testTone(seconds = 1, freq = 440) {
|
| 202 |
+
if (!audioContext || !playerNode) { log('testTone: audio not ready'); return; }
|
| 203 |
+
const sampleRate = audioContext.sampleRate;
|
| 204 |
+
const total = Math.floor(sampleRate * seconds);
|
| 205 |
+
const int16 = new Int16Array(total);
|
| 206 |
+
for (let i=0;i<total;i++) {
|
| 207 |
+
const s = Math.sin(2 * Math.PI * freq * (i / sampleRate));
|
| 208 |
+
int16[i] = s * 32767;
|
| 209 |
+
}
|
| 210 |
+
// slice into chunk-sized buffers similar to inbound network flow
|
| 211 |
+
const chunk = Math.floor(sampleRate * 0.25);
|
| 212 |
+
for (let off = 0; off < int16.length; off += chunk) {
|
| 213 |
+
const view = int16.subarray(off, Math.min(off + chunk, int16.length));
|
| 214 |
+
// copy to standalone buffer for transfer
|
| 215 |
+
const copy = new Int16Array(view.length);
|
| 216 |
+
copy.set(view);
|
| 217 |
+
playerNode.port.postMessage(copy.buffer, [copy.buffer]);
|
| 218 |
+
}
|
| 219 |
+
log(`Injected test tone ${freq}Hz for ${seconds}s`);
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
window.__mirage = { start, audioWs: () => audioWs, videoWs: () => videoWs, testTone };
|
| 223 |
+
// Diagnostics helpers
|
| 224 |
+
window.__mirage.toggleLoopback = function(on){ _loopback = on !== undefined ? !!on : !_loopback; log('Local loopback=' + _loopback); };
|
static/index.html
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<title>Mirage Echo Baseline</title>
|
| 6 |
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
| 7 |
+
<style>
|
| 8 |
+
video, img { width: 300px; }
|
| 9 |
+
#log { font: 11px/1.3 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif,monospace; white-space: pre-line; }
|
| 10 |
+
</style>
|
| 11 |
+
</head>
|
| 12 |
+
<body>
|
| 13 |
+
<h1>Mirage Echo Baseline</h1>
|
| 14 |
+
<button id="startBtn">Start</button>
|
| 15 |
+
<div>
|
| 16 |
+
<video id="localVid" autoplay muted playsinline></video>
|
| 17 |
+
<img id="remoteVid" alt="remote video frame" />
|
| 18 |
+
</div>
|
| 19 |
+
<audio id="remoteAudio" autoplay></audio>
|
| 20 |
+
<div id="log"></div>
|
| 21 |
+
<script src="/static/app.js"></script>
|
| 22 |
+
</body>
|
| 23 |
+
</html>
|
static/worklet.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class PCMChunker extends AudioWorkletProcessor {
|
| 2 |
+
constructor(options) {
|
| 3 |
+
super();
|
| 4 |
+
this.samplesPerChunk = (options && options.processorOptions && options.processorOptions.samplesPerChunk) || 16000;
|
| 5 |
+
this.buffer = new Float32Array(this.samplesPerChunk);
|
| 6 |
+
this.offset = 0;
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
process(inputs) {
|
| 10 |
+
const input = inputs[0];
|
| 11 |
+
if (input && input[0]) {
|
| 12 |
+
const data = input[0];
|
| 13 |
+
let i = 0;
|
| 14 |
+
while (i < data.length) {
|
| 15 |
+
const space = this.samplesPerChunk - this.offset;
|
| 16 |
+
const toCopy = Math.min(space, data.length - i);
|
| 17 |
+
this.buffer.set(data.subarray(i, i + toCopy), this.offset);
|
| 18 |
+
this.offset += toCopy;
|
| 19 |
+
i += toCopy;
|
| 20 |
+
if (this.offset >= this.samplesPerChunk) {
|
| 21 |
+
const out = new Int16Array(this.samplesPerChunk);
|
| 22 |
+
for (let j = 0; j < this.samplesPerChunk; j++) {
|
| 23 |
+
let s = this.buffer[j];
|
| 24 |
+
if (s > 1) s = 1; else if (s < -1) s = -1;
|
| 25 |
+
out[j] = s < 0 ? s * 32768 : s * 32767;
|
| 26 |
+
}
|
| 27 |
+
const buf = out.buffer;
|
| 28 |
+
this.port.postMessage(buf, [buf]);
|
| 29 |
+
this.offset = 0;
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
return true;
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
registerProcessor('pcm-chunker', PCMChunker);
|
| 38 |
+
|
| 39 |
+
// PCM player pulls Int16 buffers from a queue pushed via port messages and outputs Float32 samples.
|
| 40 |
+
class PCMPlayer extends AudioWorkletProcessor {
|
| 41 |
+
constructor() {
|
| 42 |
+
super();
|
| 43 |
+
this.queue = [];
|
| 44 |
+
this.current = null;
|
| 45 |
+
this.offset = 0;
|
| 46 |
+
this.samplesPerBuffer = 0;
|
| 47 |
+
this.port.onmessage = (e) => {
|
| 48 |
+
const d = e.data;
|
| 49 |
+
if (d instanceof ArrayBuffer) {
|
| 50 |
+
this.queue.push(new Int16Array(d));
|
| 51 |
+
} else if (d instanceof Int16Array) {
|
| 52 |
+
this.queue.push(d);
|
| 53 |
+
}
|
| 54 |
+
};
|
| 55 |
+
}
|
| 56 |
+
process(_inputs, outputs) {
|
| 57 |
+
const output = outputs[0][0];
|
| 58 |
+
if (!output) return true;
|
| 59 |
+
let i = 0;
|
| 60 |
+
while (i < output.length) {
|
| 61 |
+
if (!this.current) {
|
| 62 |
+
this.current = this.queue.shift();
|
| 63 |
+
this.offset = 0;
|
| 64 |
+
if (!this.current) {
|
| 65 |
+
// Fill rest with silence
|
| 66 |
+
while (i < output.length) output[i++] = 0;
|
| 67 |
+
break;
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
const remain = this.current.length - this.offset;
|
| 71 |
+
const needed = output.length - i;
|
| 72 |
+
const toCopy = Math.min(remain, needed);
|
| 73 |
+
for (let j = 0; j < toCopy; j++) {
|
| 74 |
+
output[i + j] = this.current[this.offset + j] / 32768;
|
| 75 |
+
}
|
| 76 |
+
i += toCopy;
|
| 77 |
+
this.offset += toCopy;
|
| 78 |
+
if (this.offset >= this.current.length) {
|
| 79 |
+
this.current = null;
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
return true;
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
registerProcessor('pcm-player', PCMPlayer);
|