# CareMeet — Caresoft Telemedicine Video Platform
## Technical Specification & Phase 1 Build Plan

*(Working name. Swap freely — no name appears in the schema or API paths.)*

---

## 1. What this is

A standalone, multi-tenant, self-hosted real-time video platform. Every other Caresoft product — MyOPD, Digital IPD, Digital OPD, LabSuite, pharmacy, eICU — consumes it through one API and one SDK. None of them ever touch WebRTC code.

**No vendor in the media path.** No Agora, no Twilio, no Zoom SDK, no per-minute billing, no patient audio or video leaving Caresoft infrastructure. The only external components are open-source software you run on your own servers (mediasoup, coturn, ffmpeg) — the same relationship you have with MySQL or nginx.

---

## 2. Capacity plan — the honest version

Target is 10,000 peak concurrent calls. Here is what that actually costs, so the number is a decision and not an assumption.

| Component | At 500 concurrent | At 10,000 concurrent |
|---|---|---|
| Signaling nodes | 1 | 3 (+ Redis cluster) |
| SFU nodes (mediasoup) | 1 | 12–15 |
| TURN nodes (coturn) | 1 | 8–10 |
| Recorder workers | 1 | 25–30 |
| Sustained TURN egress | ~0.45 Gbps | ~9 Gbps |
| Rough monthly infra | ₹1.5–2.5 lakh | ₹15–20 lakh |

The dominant cost is TURN bandwidth, not compute. Roughly 30% of Indian calls cannot connect peer-to-peer (CGNAT, hospital firewalls) and must relay through your servers at ~1.5 Mbps each way.

**Sanity check on the target:** 10,000 concurrent across 1,000 hospitals means every single hospital running 10 simultaneous video consults continuously. That is more concurrent teleconsultation than the entire Indian private hospital sector currently generates.

### The decision taken

**Architect for 10,000. Deploy for 500.**

Everything below is built horizontally scalable from commit one — stateless signaling, Redis room registry, a node placement table (`media_nodes`), per-tenant region and pool assignment. Growing from 500 to 10,000 is `INSERT INTO media_nodes` plus autoscaling config. It is never a rewrite.

You get the ceiling without paying for empty capacity, and you keep the option to sell "10,000 concurrent capable" honestly, because the architecture genuinely is.

---

## 3. Architecture

```
  MyOPD  ·  Digital IPD  ·  Digital OPD  ·  LabSuite  ·  Pharmacy  ·  eICU
                              │  (REST: create room → join token)
                              ▼
        ┌──────────────────────────────────────────────┐
        │  APPLICATION LAYER — PHP 8.2 / MySQL 8        │
        │  3-level auth · onboarding · plans · minutes  │
        │  reports · CMS · billing · admin consoles     │
        └───────────────┬──────────────────────────────┘
                        │ internal REST (mTLS)
                        ▼
        ┌──────────────────────────────────────────────┐
        │  SIGNALING — Node 20 · Socket.io · Redis      │
        │  rooms · presence · SDP/ICE · node placement  │
        └───────────────┬──────────────────────────────┘
                        ▼
    ┌────────────┬──────────────┬───────────────┬─────────────┐
    │ coturn     │ mediasoup    │ recorder      │ object store│
    │ STUN/TURN  │ SFU (3+ pax) │ ffmpeg copy   │ S3-compat   │
    └────────────┴──────────────┴───────────────┴─────────────┘
```

**Routing rule:** 2 participants → pure peer-to-peer (lowest possible latency, zero server media cost). 3+, or recording enabled → SFU. A 1:1 call that starts recording is upgraded to SFU mid-call transparently.

### Recording — the cost-critical design

Do **not** run headless Chrome per call. At scale that alone is 300+ servers.

Instead: mediasoup `PlainTransport` pipes the raw RTP streams straight into ffmpeg with `-c copy` — no decode, no re-encode. Output lands as a raw file. An async worker queue then transcodes to MP4 and pushes to object storage, minutes or hours later. Nobody needs the recording in real time.

Live cost per stream drops from ~1.5 vCPU to ~0.1 vCPU. This single decision is what makes Phase-1 recording affordable at your target.

---

## 4. Latency targets

| Metric | Target | Notes |
|---|---|---|
| Glass-to-glass, P2P, same city | 120–180 ms | |
| Glass-to-glass, TURN relayed | 180–280 ms | |
| Glass-to-glass, SFU | 200–300 ms | |
| Audio/video sync drift | < 40 ms | Handled natively by RTCP sender reports — not application code |
| Reconnect after network drop | < 3 s | ICE restart |

Lip-sync is not something you implement. WebRTC carries a shared clock across audio and video streams; the browser does the alignment. What you engineer is jitter buffer tuning, bitrate adaptation (`degradationPreference: 'maintain-framerate'` for consults — a doctor needs smooth motion more than 1080p), and Opus DTX for audio.

**The real-world killer in Indian hospitals is not sync — it's a reception PC from 2016 encoding VP8 in software.** Force H.264 hardware encode where available, cap the sender at 640×480/24fps for reception-desk devices, and degrade to audio-only below 150 kbps rather than dropping the call. Most vendors drop. Not dropping is your competitive line.

---

## 5. Integration contract

This is the boundary that makes it a product. Build it right in Phase 1 and every future Caresoft product gets video in a day.

### Create a room (server-to-server)

```http
POST /v1/rooms
X-API-Key: {api_key}
X-Signature: HMAC-SHA256(body, api_secret)

{
  "purpose": "opd_consult",
  "external_ref": "APPT-88213",
  "scheduled_at": "2026-09-08T10:30:00Z",
  "max_participants": 2,
  "recording_mode": "auto",
  "participants": [
    { "call_role": "doctor",  "external_ref": "DOC-119", "display_name": "Dr. Mehta" },
    { "call_role": "patient", "phone": "+9198XXXXXXXX",  "display_name": "R. Sharma" }
  ]
}
```

Returns a `room_uuid` and one short-lived join token per participant.

### Join token (JWT, RS256, 15-min TTL)

```json
{
  "jti":  "uuid-for-revocation",
  "tid":  "tenant id",
  "room": "room uuid",
  "pid":  "participant id",
  "role": "doctor",
  "perm": ["publish","subscribe","record","screen_share","end_room"],
  "sfu":  "sfu-03.in-mum",
  "exp":  1757320200
}
```

Tokens are signed by the PHP layer, verified by the Node signaling layer against the public key. No shared session state between the two.

### Embed — three ways

```html
<!-- 1. iframe: zero-code, for legacy pages -->
<iframe src="https://{tenant}.caremeet.in/r/{room_uuid}?t={token}"
        allow="camera; microphone; display-capture"></iframe>
```

```js
// 2. JS SDK: full control, custom UI
const call = new CareMeet({ token });
call.on('remote-track', t => videoEl.srcObject = t.stream);
call.on('quality',      q => showBars(q.mos));
call.on('degraded',     () => toast('Switched to audio-only'));
await call.join();
```

```kotlin
// 3. Android SDK: for Digital IPD / MyOPD apps — native, not webview
CareMeet.join(token, object : CallListener { ... })
```

### Webhooks back to the calling product

`room.started` · `participant.joined` · `participant.no_show` · `room.ended` · `recording.ready` · `quality.degraded`

---

## 6. Three-level access model

**Level 1 — Caresoft platform admin.** Client onboarding, plan and minute allocation, node pool assignment, global live-call map, cross-tenant quality dashboard, forced call termination, billing, per-tenant feature flags. 2FA mandatory.

**Level 2 — Client admin (hospital).** Doctors/staff/departments, branding and waiting-room screen, recording policy, consultation templates, usage and no-show reports, recording library with access log, API keys for their own integrations.

**Level 3 — End user.** Role determines the toolbar. Doctor: patient history pane, prescription writeback to HIS, recording control, invite specialist, end call. Patient: join, chat, upload report, low-bandwidth toggle. Lab tech / pharmacist: their own narrower surfaces.

---

## 7. Compliance built in, not bolted on

- **Telemedicine Practice Guidelines 2020 (MoHFW/NMC)** — doctor identity and NMC registration number displayed to patient; patient consent captured before consult; prescription rules enforced by drug category; consult record retained.
- **DPDP Act 2023** — consent per participant with hash and version (`recording_consents`); per-tenant retention windows with automated purge; full access log on every recording view or download (`recording_access_log`); India-resident storage.
- **ABDM** — consult linked as a care context; HFR facility ID on the tenant record.

Recordings are encrypted at rest with per-tenant keys; the schema stores a KMS key reference, never a key.

---

## 8. Phase 1 — 10 weeks

**Weeks 1–2 · Foundation**
Schema deploy, PHP skeleton, 3-level auth, tenant onboarding wizard, plans and subscriptions, API client credentials, room-token issuer.

**Weeks 3–4 · Media core** *(Node engineer)*
Signaling server, Redis room registry, coturn deployment, 1:1 P2P call working browser-to-browser with ICE restart and reconnect.

**Weeks 5–6 · SFU + recording** *(Node engineer)*
mediasoup integration, P2P→SFU upgrade path, PlainTransport→ffmpeg raw capture, async transcode worker, consent gate before capture starts.

**Weeks 7–8 · Consult experience**
Waiting room with queue position, pre-call device and bandwidth test, in-call chat and file share, screen share, audio-only degrade, doctor toolbar with HIS patient context.

**Weeks 9–10 · Integration + hardening**
JS SDK, webhooks, MyOPD integration as first consumer, quality telemetry pipeline, admin dashboards, load test to 500 concurrent.

### Team allocation

| Role | Weeks | Scope |
|---|---|---|
| Node/WebRTC engineer (the one you have) | 1–10, full time | Signaling, mediasoup, coturn, recorder pipeline, JS SDK |
| PHP engineer × 2 | 1–10 | Tenancy, 3-level consoles, API layer, reports |
| DevOps | 3–10, half time | Node deployment, TURN, storage, monitoring |
| Frontend | 5–10 | Call UI, waiting room, admin consoles |

**Your Node engineer is the critical path for weeks 3–6 and cannot be interrupted.** Everything in that window is single-threaded through one person. If they take leave or get pulled onto a client escalation, Phase 1 slips week for week. Plan cover for that now, not in week 4.

---

## 9. Deferred to Phase 2 / 3

Phase 2: Android + iOS SDKs, multi-party grid beyond 8, live captions, virtual background, cascading SFU across regions, Digital IPD and LabSuite integration.

Phase 3: landing page with SEO/AEO/GEO, self-serve signup, pricing page, public API docs portal, white-label reseller mode.

---

## 10. Open items before week 1

1. Cloud or colo, and which provider — TURN egress pricing swings the monthly bill by 3×.
2. Object storage choice for recordings (S3-compatible; MinIO self-hosted is viable and cheapest at volume).
3. Whether tenants can bring their own domain in Phase 1 (adds wildcard TLS automation).
4. First pilot hospital — a friendly existing client with real OPD volume beats synthetic load testing.
