# Calls

Sound, pictures, a shared screen and small messages between the people in a
room, browser to browser. The page says which room and what it brings; the
back end says who may be in it; the runtime does the rest.

```mote
// docs: whole
// Who may be in a room's call: here, anyone in the lobby and nobody anywhere else.
server call(room: string): bool = room == "lobby"

state call: call? = none
state name = "Guest"
state notes: string[] = []

action join
  call = rtc.join("lobby", {audio: true, video: true, name, levels: true})?

action leave
  call?.leave()
  call = none

action mute
  if call
    call.mute(call.me.audio)?

action camera
  if call
    call.camera(!call.me.video)?

action share
  if call
    call.share(!call.me.screen)?

action wave
  call?.send({wave: name})

on rtc.message(m: {room: string, from: string, data: json})
  notes.push(`${call?.peers?.find(p => p.id == m.from)?.name ?? "someone"} waved`)

component Tile(who: peer)
  column gap=6 padding=8 border-radius=12 background=card border=(who.speaking ? "2px solid #0a84ff" : "2px solid transparent")
    if who.video
      video of=who width=224 border-radius=8
    else
      row width=224 height=126 align-items=center justify-content=center background=line border-radius=8
        text who.name.slice(0, 1) font-size=40
    if who.screen
      video of=who screen width=224 border-radius=8
    row gap=6 align-items=center
      text (who.me ? `${who.name} (you)` : who.name)
      if !who.audio
        icon "mic-off" size=14
      if who.state != "connected"
        text who.state color=dim font-size=12

column gap=12 padding=16
  if call
    row gap=8 flex-wrap=wrap
      Tile who=call.me
      for p in call.peers key=p.id
        Tile who=p
    row gap=8
      button (call.me.audio ? "Mute" : "Unmute") press=mute
      button (call.me.video ? "Camera off" : "Camera on") press=camera
      button (call.me.screen ? "Stop sharing" : "Share screen") press=share
      button "Wave" press=wave
      button "Leave" press=leave
    text (call.error ?? failure(mute) ?? failure(camera) ?? failure(share) ?? "") color=danger
    for n in notes
      text n color=dim
  else
    row gap=8
      input value=name placeholder="Your name"
      button "Join the call" press=join disabled=pending(join)
    text (failure(join) ?? "") color=danger
```

Open it in two windows and press "Join the call" in both: each shows the
other's tile and plays the other's sound. There is no element for sound, no
offer, no answer and no candidate anywhere in the program.

## Mental model

- **A call is a room.** `rtc.join(room, {…})` gives a `call`: a handle the
  page keeps in state. Everyone who has joined the same room is in
  `call.peers`. A room is a text of the program's choosing (a channel's id,
  say); it exists while someone is in it.
- **Each pair is connected directly** (a mesh), over the browser's own
  WebRTC: sound and pictures go from browser to browser, encrypted, and never
  through the back end. So a room has a practical size:
  [how many](#how-many).
- **The back end lets people in and passes their notes.** To reach each
  other, two browsers exchange offers, answers and candidates. Those ride the
  open line the page already has (`/live`, the one `live` values and events
  use), through the back end, to the room's members only.
- **Who may be in a room is the program's decision**: one
  `server call(room: string): bool`, asked as the person on the line. With
  none declared every room is refused, as a model with no rules is closed.
- **Everything of a call is reactive.** `call.peers`, a peer's `audio`,
  `speaking`, `state`: a binding that reads one follows it.

## The guard: server call

```mote
server call(room: string): bool
  let u = auth.me()?
  if u == none return false
  return ChannelMember.has({channel: room, user: u.id})?
```

- One per program (`H116`), taking the room and answering a `bool`. It runs
  on the back end like a `server fn`, as whoever is asking (`auth.me()`), and
  may read models, `sql`, anything a `server fn` can. The page cannot call it.
- It is asked when someone joins, again each time their line opens again
  (after a drop, after signing in or out), and **again every half minute**
  while they are in the room. Someone it no longer admits is put out: the
  others see them leave, and their `call.state` becomes `"left"` with
  `call.error` "you are no longer in this call".
- A guard that fails (a `?` that passes a failure on, a fault) refuses.
- **Someone refused learns nothing.** They are told "the call was refused",
  the same for a room full of people, an empty one and one that never was;
  nothing about a room (who is in it, their names, what they say to each
  other) is ever sent to a line that is not in it, and what such a line sends
  to a room is dropped without an answer.

## Joining: rtc.join

`rtc.join(room, options)` waits and can fail. The options, all optional:

| Option | |
|---|---|
| `audio: true` | Bring the microphone. The browser asks leave the first time. |
| `video: true` | Bring the camera. |
| `name: "Ada"` | What the others see as this peer's `name`. It is the page's word: for who someone *is*, read `user`. |
| `levels: true` | Measure how loud everyone is (`level`, `speaking`). Off unless asked for: it costs a little work five times a second. |
| `mic`, `camera`, `speaker` | A device to use, by its id from `rtc.devices()`. |
| `verify: key` | A key the members share and the back end does not have (`bytes`, 16 or more): each connection is [proved](#proving-the-peers-verify) with it before anything is sent on it. |
| `relay: true` | Every connection goes [through the TURN server](#only-through-a-relay-relay), so no peer learns this page's address. |

With neither `audio` nor `video` the page joins to listen, watch and send
messages; either can be turned on later.

It fails, with the reason as the failure's words, when:

| | |
|---|---|
| the guard says no, or there is no guard | `rtc: the call was refused` |
| the room is full ([how many](#how-many)) | `rtc: the call is full` |
| the microphone or camera is refused | `rtc: the microphone was not allowed` |
| there is none | `rtc: there is no camera` |
| another program holds it | `rtc: the camera could not be started (is something else using it?)` |
| the page is not on https (or localhost) | `rtc: this page cannot use a microphone, a camera or a screen (it needs https, or localhost)` |
| the back end does not answer within ten seconds | `rtc: the back end did not answer` |
| the page is in that room already | `rtc: this page is in that call already` |
| `verify` is not `bytes` of 16 or more | `rtc: verify is a key of 16 bytes or more` |
| `relay: true`, and the back end gives no TURN server | `rtc: relay was asked for, and the back end gives no TURN server (MOTE_TURN)` |

The devices are asked for first, so someone who refuses them was never in
the room. A page may be in several rooms at once, each its own `call`.

## The call

`state call: call? = none` holds one (`call` is a type, like `image`).

| | |
|---|---|
| `call.room` | The room. |
| `call.peers` | The others: a list of [peers](#a-peer), in the order they came. |
| `call.me` | This page, as a peer (`me` is true). |
| `call.state` | `"joined"`, or `"left"` once it is over (left, refused when the line came back, no longer admitted). |
| `call.error` | Why it ended, if that was not the page's doing: a `string?`. |
| `call.mute(on)?` | Mutes the microphone (`true`, or nothing) or unmutes it. A microphone that was never asked for is asked for when first unmuted. The others see `audio` change. |
| `call.camera(on)?` | The camera on or off. Off lets the camera go (its light goes out). |
| `call.share(on)?` | Shares the screen: the browser asks which screen, window or tab. `call.share(false)` stops; so does the browser's own "Stop sharing". |
| `call.use({mic, camera, speaker})?` | Other devices, by id. Any of the three. |
| `call.send(data)` | A small message (anything JSON holds, 16 KB at most) to everyone in the room now; `call.send(data, peer.id)` to one. Heard with `on rtc.message`. |
| `call.stats()?` | What has crossed: for each peer `{id, audio, video, sent, rtt, relay}`: bytes received of sound and of pictures, bytes sent, the round trip in ms, and whether it goes through a TURN server. |
| `call.leave()` | Leaves. The others see it at once. A page that closes leaves by itself. |
| `call.ring(accounts, {url})` | Offers the call to people not in the room, by account id: [ringing](#ringing). |
| `call.rings` | Where each ring stands: `{user, state, at}`. |

`mute`, `camera`, `share`, `use` and `stats` wait and can fail (`?` or
`else`); `send` and `leave` do neither.

### A peer

| | |
|---|---|
| `id` | This peer in this room: new each time a page joins. The key for a `for`. |
| `user` | Who is signed in there: their account's id (what `auth.me()` gives), or `none`. The back end says this, not the peer. |
| `name` | The name their page gave when joining. |
| `me` | Whether this is the page itself. |
| `audio`, `video`, `screen` | What they have on: an unmuted microphone, a camera, a shared screen. |
| `level` | How loud they are now, 0 to 1 (with `levels: true`; else 0). |
| `speaking` | Whether they made a sound in the last 600 ms (with `levels: true`). |
| `state` | `"connecting"`, `"connected"`, `"reconnecting"` (the way between the two dropped and is being found again) or `"lost"` (not found for a while: they are dropped from the list soon after). In a call with `verify`, also `"verifying"` (connected, the proofs not yet checked) and `"refused"` (see `error`). |
| `verified` | Whether they proved they hold the call's `verify` key, on the connection there is now. Always `false` in a call without one; `call.me.verified` is whether the call has one. |
| `error` | Why they were refused (`state` `"refused"`), else `none`. |
| `fingerprints` | `{local, remote}`: the DTLS fingerprints of the connection to them, this page's and theirs, as [the proof](#proving-the-peers-verify) writes them; `""` until the connection is up. With or without `verify`: a program may show them to be compared aloud. |

`peer` is a type too: `component Tile(who: peer)`.

### video of=

```mote
video of=p width=320
video of=p screen width=640
```

`video of=peer` shows a peer's camera while they have one on; with the word
`screen`, what they share. `video of=call.me` is the page's own camera (and
`video of=call.me screen` its own shared screen). It is an HTML `video`:
size and style it as one. It is always silent: **a peer's sound is played by
the call**, once, whether or not the page shows that peer at all.

`of` takes a peer or `none` (nothing is shown).

### Messages

```mote
on rtc.message(m: {room: string, from: string, data: json})
  if m.data.kind == "hand"
    hands.push(m.from)
```

A top-level `on rtc.message` hears what any peer of any call of the page
sent with `call.send`: the room, the sender's peer `id`, and the data. Its
body is like an action's. Messages go straight from browser to browser over
the same connection as the sound, in the order sent; they are not kept, and
someone who joins later never hears an earlier one. They come from a member
of the room, not from the back end: treat `data` as you would anything a
person typed.

## Proving the peers: verify

```mote
action join(key: bytes)
  call = rtc.join(room, {audio: true, verify: key})?
```

The sound and pictures between two browsers are encrypted with keys made
in those two browsers (DTLS-SRTP). Each browser checks that the other's
certificate is the one named by a *fingerprint* in what the other sent it,
and those fingerprints travel through the back end. A back end that wanted
to listen could answer each side itself, with fingerprints of its own, and
pass everything on: each side would see a connected peer.

`verify: key` closes that. The members of a conversation hold a key the
back end never sees (one the program derives, `crypto.hkdf` of a
conversation's secret, say), and on every connection each side proves it
holds the same key, over the fingerprints that connection really has:

- **Before the proof, nothing is sent.** The first connection between two
  pages carries only their channel; no track of the page's is added to it,
  and whatever comes in is neither played nor shown by `video of=`. The
  peer's `state` is `"verifying"` once the two are connected. Messages
  (`call.send`, `on rtc.message`) neither go to nor come from such a peer.
- **The proof.** As soon as the channel opens, each side sends
  `{v: <hex of 32 bytes>}` on it: HMAC-SHA-256 under the key of the UTF-8
  bytes of

  ```text
  mote rtc verify 1\n<the sender's fingerprints>\n<the receiver's fingerprints>\n<room>
  ```

  where a side's fingerprints are read from the description this
  connection settled on (`currentLocalDescription` for one's own,
  `currentRemoteDescription` for the other's): every `a=fingerprint:` line,
  of the session and of each media section, written as its algorithm in
  lower case, one space, and its value in upper case with colons
  (`sha-256 AB:CD:…`); each once, sorted (by code point), joined by commas.
  The sender's come first, so a proof sent back to whoever made it does not
  match. The receiver makes the same bytes from its own side, with the two
  swapped, and checks the HMAC (`crypto.subtle.verify`, which takes the
  same time whatever the bytes).
- **A proof that matches**, and the peer is `verified`, its `state`
  `"connected"`; the page's tracks are added (the two settle once more) and
  the call is as any other.
- **A proof that does not match** (another key, or fingerprints changed on
  their way), **or none within ten seconds** of the channel opening, and
  the peer is `"refused"`, with `error` saying which. Its connection is
  closed, it is not tried again, and it stays in `call.peers` until it
  leaves the room; a page that joins again is another peer, and proves
  itself again.
- **A connection built anew** (after a network change: [what the runtime
  takes care of](#what-the-runtime-takes-care-of)) has new certificates, so
  it is proved anew; the peer's pictures are not shown until it is.

The key is turned into a key the browser holds and nothing reads back
(`importKey`, not extractable) when the page joins; the runtime keeps no
copy of its bytes, and neither the key nor a proof is ever sent to the back
end. A key must be the same `bytes` on every member's page. A call with
`verify` and one without, in the same room, refuse each other.

**What it protects against.** A back end (or anything on the signalling
path: a proxy, someone who has the server) that replaces fingerprints to
stand in the middle of a call: both sides refuse, and nothing of either
was sent to it but a proof, which says nothing of the key. A peer in the
room who does not have the key, and someone who joins with an old one.

**What it does not.**
- **Someone who has the key.** Anyone holding it can prove themselves.
  Who gets the key, how it is changed when someone leaves a
  conversation, and how a page comes by it is the program's to decide;
  `verify` only checks that both ends hold the same one.
- **A back end that stops the call.** It can refuse anyone, drop the
  proofs (both sides refuse after ten seconds), or pass nothing on at all:
  `verify` makes a call private, not available.
- **Who is in the room.** `call.peers` and each peer's `user` and `name`
  still come from the back end. The proof says the other end holds the
  key, not which of the key's holders it is: when it matters which person
  it is, show `fingerprints` to be compared, or sign with a key of that
  person's.
- **Each person's network address**: see [relay](#only-through-a-relay-relay).
- **The device itself.** A page with a malicious extension, or a back end
  that serves a page of its own making, is on the inside: the page's code
  must come from somewhere the program trusts ([delivery](delivery.md)).

## Ringing

```mote
// docs: whole
server call(room: string): bool = auth.me()? != none

state call: call? = none
state who = ""

action start
  call = rtc.join("team", {audio: true})?

// The one calling, in the call: offers it to an account.
action ringThem
  call?.ring([who])

// Answering is joining the room, with whatever the page brings.
action answer(room: string)
  call = rtc.join(room, {audio: true})?

action no(id: string)
  rtc.decline(id)

column gap=8 padding=16
  if call
    input value=who placeholder="An account's id"
    button "Ring" press=ringThem
    for r in call.rings key=r.user
      text `${r.user}: ${r.state}`
  else
    button "Start a call" press=start
  // On any page of the app: the calls offered to this person now.
  for r in rtc.rings() key=r.id
    row gap=8
      text `${r.name} is calling`
      button "Answer" press=answer(r.room)
      button "Decline" press=no(r.id)
```

- **`call.ring(accounts)`** (a member's, while in the call) offers the call
  to those accounts (`auth.me()`'s ids; 50 at most). It does not wait.
  Each is rung on **every open line of theirs** (each page of the app
  they have open, signed in) that is not in the room already and that the
  guard, asked as them, admits; a line the guard does not admit is told
  nothing.
- **`rtc.rings()`** is the list of calls offered to this page's person
  now, reactive: `{id, room, from, name, at}` (`from`: the account that
  rang, `name` the name it joined with, `at` when, in ms). An entry leaves
  the list when the ring is over, whichever page answered it.
- **`rtc.decline(id)`** turns one down, for all of that person's pages.
- **`call.rings`**, on the page that rang: one `{user, state, at}` per
  account rung, `at` when it came to that state. The states:

| `state` | |
|---|---|
| `"ringing"` | Offered, on at least one open line or device, and nothing said yet. |
| `"answered"` | They joined the room (from any of their pages, rung or not). |
| `"declined"` | `rtc.decline` on one of the pages it rang. |
| `"missed"` | Nobody answered in 30 s (`MOTE_RING_TIME`, in seconds), or whoever rang left the room (or their line dropped) first. |
| `"offline"` | They had no open line that could be rung, and no device to push it to. |

  The states other than `"ringing"` are final: ringing again is a
  new ring, which replaces that account's entry.

**On their devices too.** A ring reaches every open line, and, where the
program notifies through the back end (`notify.enable()` on the page:
[back-end.md](back-end.md#notifications)) and its pages show rings
(`rtc.rings()`), every device of theirs as well, whether the app is open
there or not. The service worker shows it as "Ada is calling", with
**Answer** and **Decline**, until it is dealt with; the program writes
nothing for that.

```mote
// docs: whole
server call(room: string): bool = auth.me()? != none

state call: call? = none
state who = ""

action allow
  notify.enable()?

action start
  call = rtc.join("team", {audio: true})?

// Answer, on a device, opens the app at this address (or brings its window forward).
action ringThem
  call?.ring([who], {url: "/#/call/team"})

// …and this window is told: it joins.
on rtc.answer(r: {id: string, room: string, from: string, name: string})
  call = rtc.join(r.room, {audio: true})?

column gap=8 padding=16
  button "Ring me on my devices" press=allow
  if call
    input value=who placeholder="An account's id"
    button "Ring" press=ringThem
  else
    button "Start a call" press=start
  for r in rtc.rings() key=r.id
    text `${r.name} is calling`
```

- **Answer** (or a press on the notification itself: a browser that draws no
  buttons has only that) brings a window of the app forward, or opens the
  app at the ring's `url`, and runs `on rtc.answer` there with `{id, room,
  from, name}`. Joining is the program's: it says what the call brings.
  Joining is what makes the ring `"answered"`. A program with no `on
  rtc.answer` is opened at `url`, and what is there is its own.
- **`url`** (`call.ring(accounts, {url})`) is an address of the app's own: a
  path (`/call/x`, `./call/x`) or `#…`. Without one, or with one elsewhere,
  it is the app's start.
- **Decline** is `rtc.decline`, made by the service worker as whoever is
  signed in on that browser: `"declined"`, on every page and device of theirs.
- **When the ring is over** (answered, on any line or device; declined;
  missed; whoever rang left), each device it was pushed to is told, and its
  notification is closed. A browser wants something shown for every push:
  unless a window of the app is in view there, a quiet note says how it
  ended ("Missed call", "Call answered", "Call declined", with the caller's
  name), under a tag of its own.
- **The states stay as above.** `"offline"` is now: no open line and no
  device. `"ringing"` with only devices means it was pushed; whether any
  device showed it, nobody can say.
- **Who is pushed to** is who would be rung on a line: an account the guard,
  asked as them, admits. Nobody else learns a ring was made.
- **What the push carries**: the ring's id, the room's name, the account id of
  whoever rang and the name they joined with, when, and `url`; once over, the
  id, how it ended and the name. Like every push it is sealed to the device's
  own key (RFC 8291) on its way: the push service reads none of it. It is not
  kept in the inbox. A room's name and a person's name do reach the device
  and are shown on its screen, locked or not: a program whose room names say
  something should name rooms by an id of its own (and look the rest up once
  the app is open), and give `rtc.join` the `name` it is happy to have shown.
- Rings on devices need a built app (`mote build`, not `--single`) and a
  browser that takes pushes ([back-end.md](back-end.md#notifications)).
  `tests/all.sh real_rtc_ring_push` checks both halves: the back end with a
  push service of the test's own that opens what it is sent, and the service
  worker and the page in Chrome. A press made by a person, with no window of
  the app open, cannot be made from a test.

**What a ring tells.** Whoever rings learns, for each account, whether
some line of theirs was open and admitted (`"ringing"` or `"offline"`):
presence, to anyone who may be in a room with them. A program that
should not show that rings only people the caller may know it of.

## Devices

```mote
resource found = rtc.devices() else {mics: [], cameras: [], speakers: []}
state mic = ""

action pick(id: string)
  mic = id
  call?.use({mic: id})?
```

`rtc.devices()` gives `{mics, cameras, speakers}`, each a list of
`{id, label}`. It waits and can fail. Until the page has been let use a
microphone or camera, browsers hide the names (the labels read "Microphone
1") and some list nothing: ask after joining, or `refresh(found)` then.
`speakers` is empty where the browser cannot choose one (Safari, Firefox on
some systems); `call.use({speaker})` fails there.

## What the runtime takes care of

- **Both offering at once.** Either side may need to settle things again
  (a camera turned on) at the same moment as the other. One of each pair is
  "polite" (the lesser id) and gives way: the standard *perfect negotiation*.
- **Late joiners.** Whoever joins is told who is there, and each of them is
  told of the newcomer; they connect to everyone.
- **Turning things on and off.** A camera turned on mid-call and a screen
  shared or stopped are settled again between each pair, with nobody
  dropped. Muting sends silence and tells the others; nothing is settled
  again.
- **A network that changes.** When the way between two browsers drops
  (Wi-Fi to cellular, a router restarted), the peer shows `"reconnecting"`
  and the candidates are gathered again (an ICE restart), at once if the
  browser says the way failed, after 4 s if it only went quiet. After 12 s
  the connection is built anew, once. If that has not reached them in
  another 12 s the peer shows `"lost"`, and at 30 s it is dropped from
  `call.peers` (until they join again).
- **Someone vanishing.** A page that closes says so on its way out. A
  browser that dies, or loses its network, says nothing: the back end
  notices its line close, and the others drop that peer as soon as the
  connection to it is seen to be dead too, 12 s later at most.
- **The line to the back end dropping.** The call goes on: the sound does
  not pass through the back end. When the line opens again each page asks to
  be let in again, as the same peer, and is told who else is (still) there.
  The same when the back end itself is restarted (`mote dev` restarts it on
  every save).
- **Signing in or out** opens the line again as the new person, and so asks
  the guard again.

## How many

Every member sends their sound and picture to every other, and receives
from each. With pictures that is comfortable for **about four people** and
strained past six (a laptop encoding the same camera five times, each at a
megabit or so); with sound alone, **about eight**. The back end refuses a
ninth member ("the call is full"); `MOTE_CALL_MAX` sets another limit.
Rooms larger than that need a server that receives each picture once and
passes it on (an SFU), which Mote does not have.

## Deploying

- **https.** A browser gives a page the microphone, camera and screen only
  on https (or on `localhost`). Behind a proxy, `/live` must be passed on as
  a WebSocket, as for [live values](back-end.md#live-values).
- **One process, or Postgres.** Who is in which room is in the back end's
  memory, like the open lines themselves: run one back end, or keep the
  models in Postgres and run as many as you like behind one address
  ([more than one process](#more-than-one-process)).
- **With nothing set, there are no ICE servers.** Browsers on one network
  (or one machine) find each other; across the internet most will not.
- **STUN** lets a browser learn its public address, which is enough for
  most home networks. **TURN** relays everything for the pairs that cannot
  reach each other at all (strict company firewalls, some mobile networks:
  roughly one pair in five to ten), and so carries real traffic. Run one
  (coturn is the usual choice) and tell the back end:

| Setting | |
|---|---|
| `MOTE_STUN` | STUN addresses, with commas between: `stun:turn.example.com:3478` |
| `MOTE_TURN` | TURN addresses: `turn:turn.example.com:3478,turns:turn.example.com:5349?transport=tcp` |
| `MOTE_TURN_SECRET` | The secret shared with the TURN server (coturn: `use-auth-secret` and `static-auth-secret=…`). Each member is then given a name and password of their own that stop working after a while: the name is `<when it ends, in seconds since 1970>:<their account's id, or their peer id>` and the password that name signed with the secret (HMAC-SHA1, in base64). The secret never leaves the back end. |
| `MOTE_TURN_TTL` | How long such a password lasts, in seconds (3600). A page in a call asks for a new one when half that has gone. |
| `MOTE_TURN_USER`, `MOTE_TURN_PASSWORD` | Instead of a secret: one name and password for everybody. Every member can read them, so prefer the secret. |
| `MOTE_CALL_MAX` | The most members a room takes (8). |
| `MOTE_CALL_RECHECK` | How often the guard is asked again about everyone in a call, in seconds (30). |
| `MOTE_RING_TIME` | How long a ring rings before it is missed, in seconds (30). |

  The servers are given only to someone the guard has let into a room.

- **What others can learn.** The members of a room connect to each other
  directly, so each can see the others' network addresses, as in any
  peer-to-peer call, unless they join with [`relay: true`](#only-through-a-relay-relay).

## Only through a relay: relay

```mote
call = rtc.join(room, {audio: true, relay: true})?
```

With `relay: true` the page's connections use only the TURN server the
back end names (`iceTransportPolicy: "relay"`): the browser gathers no
other candidate, so it never tells a peer its own address, on its network
or as the internet sees it, and the sound and pictures go through the
relay. A peer learns the relay's address and nothing else.

- It is each page's own choice, for itself: a page that does not ask for it
  still sends its addresses to the others. For a program where it is never
  to be otherwise, every page joins with `relay: true`.
- Mote does not run a TURN server: it gives the browsers the one the
  settings name (`MOTE_TURN`, below), with a password of their own. Run
  one (coturn) beside the app. With `relay: true` and no `MOTE_TURN`, the
  join fails (`rtc: relay was asked for, and the back end gives no TURN
  server (MOTE_TURN)`) rather than joining a call that could reach nobody.
- Everything of the call then crosses the TURN server, twice (in and out):
  it carries the call's whole traffic and its latency.
- `call.stats()` says `relay: true` for each peer whose connection goes
  through one.
- With `verify` as well, the TURN server sees only encrypted packets, and
  cannot stand in the middle either.

## More than one process

Where the program keeps models in Postgres (`MOTE_SQL=postgres://…`,
[models in Postgres](back-end.md#models-in-postgres)), several back ends
behind one address share their rooms: two people whose open lines are held
by different back ends are in one call, see each other, connect, prove each
other with [`verify`](#proving-the-peers-verify) (the proofs go browser to
browser, so they pass whichever back ends stand between), and ring each
other. Nothing in the program changes. With `MOTE_SQL` unset or `file:`, or
in a program with no models, the rooms are in the one back end's memory as
before, and nothing here applies.

- **The members are in a table.** One row a member, `mote_rtc_member`: the
  room, the peer id, the account, the name, what is on, and which back end
  holds its line. Joining is one transaction that takes a lock of the
  room's (`pg_advisory_xact_lock`), counts the room (`MOTE_CALL_MAX` is
  counted across back ends) and writes the row; leaving deletes it. Each
  back end remembers, for the rooms its own members are in, who the others
  are and which back end holds each.
- **Notes between back ends.** An offer, an answer, a candidate, what is
  on, someone come or gone, a ring: when it is for a member whose line
  another back end holds, it is sent to that back end with Postgres's
  `NOTIFY`, on a channel of that back end's own (`mote_rtc_<its id>`), which
  it `LISTEN`s on, on a connection of its own: `MOTE_SQL`, or
  `MOTE_SQL_DIRECT` behind a transaction pooler, which does not pass
  notifications on (as for [what another back end
  wrote](back-end.md#what-another-back-end-wrote)). A note is sent at once,
  not polled for, so setting up a connection across back ends costs a
  round trip to Postgres a step, not an interval. A note longer than
  `NOTIFY` carries (8000 bytes: an offer with several tracks can be longer)
  goes in a row of `mote_rtc_note`, and the notification names the row,
  which the back end that hears it reads and deletes. The notes to one back
  end are sent one after another and heard one after another, so they come
  in the order they were said.
- **Presence by heartbeats.** Each back end says it is there every
  `MOTE_CALL_BEAT` seconds (5), in `mote_rtc_proc`. One not heard from for
  three beats is taken as gone, with its members: the others' pages are
  told (`gone`, as when a line drops), within about four beats of its
  death. At each beat a back end also reads its rooms again, so a note that
  was lost (sent while a `LISTEN` connection was being made again) costs at
  most a beat's delay in who is shown, never a ghost.
- **A back end that dies or restarts.** Its pages' lines come back on
  another back end and ask to be let in again, as the same peers. An id
  still held by the dead back end's row is taken over by the same account
  (anyone else waits for the row to run out); the others are told the peer
  came back, and a call that was connected never stops: the sound and the
  pictures never passed through any back end. A back end stopped cleanly
  deletes its rows and tells the others at once.
- **Ringing** works whichever back end holds the line or the device rung.
  The back end of the member who rang asks every other one to ring the
  lines it holds of each account rung; each says how many it rang. A ring
  rung nowhere (no line, no [device](#ringing)) is `"offline"` once
  every back end has said, or after two seconds. Declined on a line or a
  device at any back end, answered by joining at any back end, missed, or
  ended by the caller leaving: the back end that holds the ring decides,
  and tells every back end that rang a line. The devices are pushed to by
  that back end, from the devices in Postgres
  ([`notify` in Postgres](back-end.md#models-in-postgres)).
- **The guard's look again** every half minute runs on the back end that
  holds the line, as before.
- **The TURN passwords** need nothing: every back end signs them with the
  same secret.

| Setting | |
|---|---|
| `MOTE_CALL_BEAT` | Seconds between a back end's heartbeats (5). A back end not heard from for three is gone. |
| `poll` (in `MOTE_SQL`) | Behind a transaction pooler with no `MOTE_SQL_DIRECT`, nothing can `LISTEN`: every note is then a row, and each back end looks for its own every `poll` ms (250), which adds that much to each step of a connection being set up. |

```sh
# Three back ends behind one address, at one database:
MOTE_SQL='postgres://app:…@db.example.com:5432/app?sslmode=require' bun dist/server/main.js --port 8001
MOTE_SQL='postgres://app:…@db.example.com:5432/app?sslmode=require' bun dist/server/main.js --port 8002
MOTE_SQL='postgres://app:…@db.example.com:5432/app?sslmode=require' bun dist/server/main.js --port 8003
```

What is not shared: the ICE servers each member is given are its own back
end's settings (give every back end the same), and a ring in flight is
held by the back end of whoever rang: if that one dies, the ring stops
ringing on the others at its time (`MOTE_RING_TIME`, and five seconds) and
the caller, whose line comes back elsewhere, rings again.

## Pitfalls

- **No `server call`, no calls.** Every `rtc.join` is refused until the
  program says who may be in a room.
- **`name` is whatever the page said.** Show it, but decide nothing by it:
  `user` is the account the back end saw.
- **A peer's `id` is not a person.** The same person in two tabs is two
  peers with one `user`; someone who leaves and joins again has a new `id`.
- **Leaving does not clear the state.** `call.leave()` ends the call; the
  page's `call` still holds it (its `state` is `"left"`) until the page
  writes `call = none`.
- **A call that ended by itself is still in the state too**, with
  `call.error` saying why. Show it, or `watch` `call?.state` and clear it.
- **`video of=` shows nothing for a peer with their camera off.** Draw the
  tile's other face under an `else`, as the example does.
- **`level` changes five times a second.** Bind it to one small thing (a
  bar's width), not to a whole list's layout. `speaking` changes far less.
- **Messages are not kept, not for latecomers, and 16 KB at most.** What
  must last goes through a `model` or a `server fn`.
- **The browser may hold sound back until the person has pressed
  something.** Joining from a button, as one does, satisfies it; if it was
  held back anyway the runtime starts it at the next press anywhere.
- **Sharing a screen is desktop browsers only** (phones do not offer it):
  `call.share()` fails there with the reason.
- **Checked in Chrome.** The run that tests this drives headless Chrome;
  Firefox and Safari have the same standard calls the runtime uses, but have
  not been driven through it.

## The wire

For someone debugging. All of it is JSON on `/live`, with `t: "rtc"`:

| From the page | |
|---|---|
| `{o: "join", r, id, n, m}` | Asks to be let into room `r` as peer `id` (the page's choice: 8 to 64 of `a-z0-9`), named `n`, with `m` on. |
| `{o: "sig", r, to, d}` | For one member: an offer or answer (`d.sdp`) or a candidate (`d.ice`), with the connection's generation (`d.g`). |
| `{o: "st", r, m}` | What is on now: `{a, v, s, c, x, n}` (microphone, camera, screen, the ids of their two streams, a count). |
| `{o: "ice", r}` | The ICE servers again. |
| `{o: "leave", r}` | |
| `{o: "ring", r, to}` | Rings accounts `to` into room `r` (a member's to say). |
| `{o: "decline", r, id}` | Turns down ring `id` (from a line it rang). |

| From the back end | |
|---|---|
| `{o: "in", r, u, peers, ice, ttl}` | Let in: the account id it saw, who is there (`{id, u, n, m}` each), the ICE servers. |
| `{o: "no", r}` | Not let in (`e: "full"` for someone admitted to a full room). |
| `{o: "peer", r, p}` | Someone came, or came back. |
| `{o: "gone", r, id, hard}` | Someone left (`hard: 1`) or their line dropped. |
| `{o: "sig", r, from, d}`, `{o: "st", r, id, m}`, `{o: "ice", r, ice, ttl}` | As above, passed on. |
| `{o: "out", r}` | No longer admitted. |
| `{o: "ring", r, id, u, n, at}` | This line's person is offered room `r`'s call by account `u`, named `n`. |
| `{o: "unring", r, id, s}` | That ring is over for them (`s`: answered, declined, missed). |
| `{o: "rung", r, id, u, s, at}` | To whoever rang: the ring to account `u` is now in state `s`. |

Between two browsers, on a data channel named `mote`: `{d: data}` (a
message), `{m: …}` (what is on), `{bye: 1}`, and in a call with `verify`,
first, `{v: proof}` ([the proof](#proving-the-peers-verify), 64 hex digits).

## Where a new call goes

A method of a call: `call_says` in `compiler/src/types.rs` (what it takes
and gives, whether it waits), the method on `call.pub` in
`runtime/page/rtc.mote`, and its row in [the call](#the-call) above. A
peer's field: `peer()` in `types.rs` and `peer.pub` in the runtime.

## In the source

| What | Where |
|---|---|
| The page's side: joining, each pair's connection, tracks, levels, `video of=`, the proof (`prints`, `prove`, `check`) | `runtime/page/rtc.mote`, part `RTC` |
| The back end's side: rooms, the guard, passing notes on, ICE servers and TURN passwords | `runtime/server/rtc.mote`, part `RTS` |
| Rooms across back ends in Postgres: the members' table, notes over `LISTEN`/`NOTIFY`, the beat | `runtime/server/rtc.mote`, part `RTSQ` (what other back ends say, to the members here: `farHeard` in `RTS`); included by `build.rs` where the program has calls and models |
| Where the open line hands a call's messages over | `runtime/page/rpc.mote` (`liveOther`), `runtime/server/live.mote` (`RTSM`, `RTSX`) |
| `server call`, `on rtc.message`, `on rtc.answer` | `compiler/src/parse.rs`; checked in `types.rs` (`H116`); wired in `build.rs` (`RTSG`) and `emit.rs` (`RTCH`, `RTCA`) |
| Rings on devices | `runtime/server/rtc.mote` (part `RTSP`, with `notifyRing` in `push.mote`); the service worker's `RING` in `compiler/src/pwa.rs`; `rtc.decline` put in the table of calls by `build.rs` |
| The types `call` and `peer`, `rtc.join`, a call's methods | `compiler/src/types.rs`: `call`, `peer`, `call_options`, `call_says` |
| `video of=` | `compiler/src/view.rs` (`RTCV`) |
| Recorded behaviour | `tests/rtc` with `tests/rtc.real.mjs` (`tests/all.sh real_rtc`); `tests/rtc_verify` with `tests/rtc_verify.real.mjs` (`real_rtc_verify`: a signalling relay that puts a third page in the middle, and a TURN server of the test's own); `tests/pg_rooms` with `tests/pg_rooms.real.mjs` (`real_pg_rooms`: three back ends at one Postgres, pages on each, a back end killed mid-call, rings across back ends); `compiler/src/tests_rtc.rs` |
