diff --git a/.agents/skills/formrec-harness/SKILL.md b/.agents/skills/formrec-harness/SKILL.md index 96dd6ea..4228f62 100644 --- a/.agents/skills/formrec-harness/SKILL.md +++ b/.agents/skills/formrec-harness/SKILL.md @@ -60,7 +60,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr - **Recordings are the person's.** They are private (folders 0700, files 0600). Never delete one without being asked; `formrec_delete` is the only core tool that removes anything, and it wants the id twice. - **Trust the annotations.** A tool marked read only changes nothing; one marked destructive or open world (it reaches FormCut, the network or a website) needs the person's go-ahead when they did not ask for exactly that. - **Studio takes need a person.** Cameras, microphones and guests are the person's, in the FormRec window; an agent can explain, list and read them back but does not start one. -- **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); they carry the run's token and open while `formrec serve` or the desktop app runs. +- **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); a recording's link carries that recording's player key (never the run's token), opens its player only, and works while `formrec serve` or the desktop app runs and until the person rotates player links in Settings. ## References diff --git a/.agents/skills/formrec-harness/references/concepts.md b/.agents/skills/formrec-harness/references/concepts.md index b28670b..ed22657 100644 --- a/.agents/skills/formrec-harness/references/concepts.md +++ b/.agents/skills/formrec-harness/references/concepts.md @@ -97,7 +97,7 @@ A target is `{ "role": "button", "name": "New Project" }` (best: survives restyl - `video.webm` for walkthroughs, `track-.webm` per source for studio takes. - `captions.vtt`, `chapters.vtt`; `walkthrough.json` for agent-made recordings. -The player opens a recording at `#/f/` and a demo at `#/demo/`. `formrec url` prints the player base with the run's token. +The player opens a recording at `#/f/` and a demo at `#/demo/`. A link a tool returns for a recording is `/?player=#/f/`: the key opens that recording's player and nothing else, and Settings, Agents, Player links, Rotate (or `formrec url --rotate-player-links`) stops every link given so far. `formrec url` prints the app's own address with the run's token, for the person at the computer. ## Variables diff --git a/.agents/skills/formrec-harness/references/feature-tools.md b/.agents/skills/formrec-harness/references/feature-tools.md index ff94a49..e4b1a0e 100644 --- a/.agents/skills/formrec-harness/references/feature-tools.md +++ b/.agents/skills/formrec-harness/references/feature-tools.md @@ -4,7 +4,7 @@ Generated from the FormRec MCP server by `formrec agents sync` (`npm run agents: The tools FormRec's feature modules add next to the core tools in tools.md: editing, transcripts, sharing, comments, the library, documents, integrations and the rest. Each carries a title and annotations; trust "Changes anything" and ask the person before a tool that removes or reaches outside FormRec. They take a recording id from `formrec_list` or `formrec_record` unless they say otherwise. -112 tools. +113 tools. ## Tools @@ -108,6 +108,7 @@ The tools FormRec's feature modules add next to the core tools in tools.md: edit | `formrec_share_stop` | Stop sharing a recording | yes, removes or overwrites | Stop sharing: the link stops working for everyone at once and cannot be brought back (a new share gets a new link). The recording itself is kept. | | `formrec_shares` | List shared recordings | no | Every shared recording with its privacy, links, expiry, views and available qualities (`qualities`). Give query to filter by title. | | `formrec_signed_in_states` | Signed-in states | no | The signed-in states the person saved with `formrec login URL --name NAME` (names and when they were saved, never their contents), and whether the recorder browsers and FFmpeg are installed. Use a name as "auth": {"state": NAME}. If the site you need is missing, ask the person to run formrec login for it. | +| `formrec_studio_refresh_devices` | Refresh the studio devices | yes | Rebuild the open studio's microphone and camera lists (after a device is plugged in, or when they show generic names such as "Microphone 1") and return what it found: the names, which one is chosen, and whether the browser still needs permission. The studio must be open on this computer. askPermission: true lets the studio briefly ask the person for microphone (and camera, when the layout uses it) permission so real names appear; nothing is recorded and the devices are released at once. Without it, a list that needs permission is reported as permission: needed. | | `formrec_studio_state` | Studio state | no | What the FormRec studio is doing now: idle, ready, countdown, recording, paused, rewind, stopped or saved; the layout (screen-camera, screen, camera, audio, meeting, presentation, canvas), capture target, quality, the open take id and its elapsed time. Read it before telling a person to record, or to check a take is running. | | `formrec_task_add` | Add a task to a recording | yes | Add a task (an action item viewers can check off), optionally at a moment of the recording. | | `formrec_task_done` | Check a task off | yes | Mark a recording's task done, or not done with done: false. | @@ -743,6 +744,10 @@ Returns structured content: `removed`. No parameters. +### formrec_studio_refresh_devices + +- `askPermission` (optional): boolean. briefly ask the person for permission when the names are hidden (default false) + ### formrec_studio_state No parameters. diff --git a/.agents/skills/formrec-harness/references/tools.md b/.agents/skills/formrec-harness/references/tools.md index d68311c..43ecebb 100644 --- a/.agents/skills/formrec-harness/references/tools.md +++ b/.agents/skills/formrec-harness/references/tools.md @@ -42,7 +42,7 @@ Returns structured content: `note`, `demos`. - `id`: string. recording id from formrec_list or formrec_record -Returns structured content: `formrec`, `id`, `title`, `summary`, `source`, `owner`, `createdAt`, `updatedAt`, `version`, `mode`, `video`, `tracks`, `pauses`, `durationMs`, `viewport`, `codebase`, `chapters`, `keys`, `clipOf`, `variantOf`, `files`, `player`. +Returns structured content: `formrec`, `id`, `title`, `summary`, `source`, `owner`, `createdAt`, `updatedAt`, `version`, `mode`, `video`, `tracks`, `pauses`, `durationMs`, `viewport`, `codebase`, `chapters`, `keys`, `clipOf`, `variantOf`, `capture`, `files`, `player`. ### formrec_guide @@ -90,7 +90,7 @@ Returns structured content: `valid`, `title`, `steps`, `commit`, `problems`, `de ## Demos -Open one at `#/demo/` while FormRec runs (`formrec_demos` returns the full link with the run's token). +Open one at `#/demo/` while FormRec runs (`formrec_demos` returns the full link; demos need no token). | Id | Title | Kind | Chapters | Point a person at it for | | --- | --- | --- | --- | --- | @@ -99,4 +99,4 @@ Open one at `#/demo/` while FormRec runs (`formrec_demos` retur ## Command line equivalents -`formrec validate FILE`, `record FILE [--base-url URL] [--headed]`, `list`, `url` (the player base with the token), `serve [--codebase DIR] [--repo-url URL] [--open]`, `agents install|status|sync`. Output is the same JSON the tools return. The guide, the demos and the feature tools are MCP only. +`formrec validate FILE`, `record FILE [--base-url URL] [--headed]`, `list`, `url` (the app's address with the run's token; `--rotate-player-links` stops every player link given so far), `serve [--codebase DIR] [--repo-url URL] [--open]`, `agents install|status|sync`. Output is the same JSON the tools return. The guide, the demos and the feature tools are MCP only. diff --git a/.agents/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md b/.agents/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md index d7b877e..e70f4e4 100644 --- a/.agents/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md +++ b/.agents/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md @@ -7,7 +7,7 @@ description: Points a person at the demos that ship with FormRec. Use when the p ## Find them -`formrec_demos` lists every demo that ships with FormRec: `id`, `title`, `kind` (`walkthrough` or `studio`), `shows` (what is in it), `pointAt` (who it is for), `chapters` (id, title, start), `durationMs`, `tracks`, the `route` (`#/demo/`) and `player`, the full link with the run's token. `references/tools.md` has the same list as a table. +`formrec_demos` lists every demo that ships with FormRec: `id`, `title`, `kind` (`walkthrough` or `studio`), `shows` (what is in it), `pointAt` (who it is for), `chapters` (id, title, start), `durationMs`, `tracks`, the `route` (`#/demo/`) and `player`, the full link (demos need no token). `references/tools.md` has the same list as a table. Never invent a demo id: take it from `formrec_demos`. diff --git a/.claude/skills/formrec-harness/SKILL.md b/.claude/skills/formrec-harness/SKILL.md index 96dd6ea..4228f62 100644 --- a/.claude/skills/formrec-harness/SKILL.md +++ b/.claude/skills/formrec-harness/SKILL.md @@ -60,7 +60,7 @@ Its MCP server, named `formrec`, is `formrec mcp` (or the installed app's `formr - **Recordings are the person's.** They are private (folders 0700, files 0600). Never delete one without being asked; `formrec_delete` is the only core tool that removes anything, and it wants the id twice. - **Trust the annotations.** A tool marked read only changes nothing; one marked destructive or open world (it reaches FormCut, the network or a website) needs the person's go-ahead when they did not ask for exactly that. - **Studio takes need a person.** Cameras, microphones and guests are the person's, in the FormRec window; an agent can explain, list and read them back but does not start one. -- **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); they carry the run's token and open while `formrec serve` or the desktop app runs. +- **Give links, not guesses.** Player links come from the tools (`player` in `formrec_record`, `formrec_get`, `formrec_demos`); a recording's link carries that recording's player key (never the run's token), opens its player only, and works while `formrec serve` or the desktop app runs and until the person rotates player links in Settings. ## References diff --git a/.claude/skills/formrec-harness/references/concepts.md b/.claude/skills/formrec-harness/references/concepts.md index b28670b..ed22657 100644 --- a/.claude/skills/formrec-harness/references/concepts.md +++ b/.claude/skills/formrec-harness/references/concepts.md @@ -97,7 +97,7 @@ A target is `{ "role": "button", "name": "New Project" }` (best: survives restyl - `video.webm` for walkthroughs, `track-.webm` per source for studio takes. - `captions.vtt`, `chapters.vtt`; `walkthrough.json` for agent-made recordings. -The player opens a recording at `#/f/` and a demo at `#/demo/`. `formrec url` prints the player base with the run's token. +The player opens a recording at `#/f/` and a demo at `#/demo/`. A link a tool returns for a recording is `/?player=#/f/`: the key opens that recording's player and nothing else, and Settings, Agents, Player links, Rotate (or `formrec url --rotate-player-links`) stops every link given so far. `formrec url` prints the app's own address with the run's token, for the person at the computer. ## Variables diff --git a/.claude/skills/formrec-harness/references/feature-tools.md b/.claude/skills/formrec-harness/references/feature-tools.md index ff94a49..e4b1a0e 100644 --- a/.claude/skills/formrec-harness/references/feature-tools.md +++ b/.claude/skills/formrec-harness/references/feature-tools.md @@ -4,7 +4,7 @@ Generated from the FormRec MCP server by `formrec agents sync` (`npm run agents: The tools FormRec's feature modules add next to the core tools in tools.md: editing, transcripts, sharing, comments, the library, documents, integrations and the rest. Each carries a title and annotations; trust "Changes anything" and ask the person before a tool that removes or reaches outside FormRec. They take a recording id from `formrec_list` or `formrec_record` unless they say otherwise. -112 tools. +113 tools. ## Tools @@ -108,6 +108,7 @@ The tools FormRec's feature modules add next to the core tools in tools.md: edit | `formrec_share_stop` | Stop sharing a recording | yes, removes or overwrites | Stop sharing: the link stops working for everyone at once and cannot be brought back (a new share gets a new link). The recording itself is kept. | | `formrec_shares` | List shared recordings | no | Every shared recording with its privacy, links, expiry, views and available qualities (`qualities`). Give query to filter by title. | | `formrec_signed_in_states` | Signed-in states | no | The signed-in states the person saved with `formrec login URL --name NAME` (names and when they were saved, never their contents), and whether the recorder browsers and FFmpeg are installed. Use a name as "auth": {"state": NAME}. If the site you need is missing, ask the person to run formrec login for it. | +| `formrec_studio_refresh_devices` | Refresh the studio devices | yes | Rebuild the open studio's microphone and camera lists (after a device is plugged in, or when they show generic names such as "Microphone 1") and return what it found: the names, which one is chosen, and whether the browser still needs permission. The studio must be open on this computer. askPermission: true lets the studio briefly ask the person for microphone (and camera, when the layout uses it) permission so real names appear; nothing is recorded and the devices are released at once. Without it, a list that needs permission is reported as permission: needed. | | `formrec_studio_state` | Studio state | no | What the FormRec studio is doing now: idle, ready, countdown, recording, paused, rewind, stopped or saved; the layout (screen-camera, screen, camera, audio, meeting, presentation, canvas), capture target, quality, the open take id and its elapsed time. Read it before telling a person to record, or to check a take is running. | | `formrec_task_add` | Add a task to a recording | yes | Add a task (an action item viewers can check off), optionally at a moment of the recording. | | `formrec_task_done` | Check a task off | yes | Mark a recording's task done, or not done with done: false. | @@ -743,6 +744,10 @@ Returns structured content: `removed`. No parameters. +### formrec_studio_refresh_devices + +- `askPermission` (optional): boolean. briefly ask the person for permission when the names are hidden (default false) + ### formrec_studio_state No parameters. diff --git a/.claude/skills/formrec-harness/references/tools.md b/.claude/skills/formrec-harness/references/tools.md index d68311c..43ecebb 100644 --- a/.claude/skills/formrec-harness/references/tools.md +++ b/.claude/skills/formrec-harness/references/tools.md @@ -42,7 +42,7 @@ Returns structured content: `note`, `demos`. - `id`: string. recording id from formrec_list or formrec_record -Returns structured content: `formrec`, `id`, `title`, `summary`, `source`, `owner`, `createdAt`, `updatedAt`, `version`, `mode`, `video`, `tracks`, `pauses`, `durationMs`, `viewport`, `codebase`, `chapters`, `keys`, `clipOf`, `variantOf`, `files`, `player`. +Returns structured content: `formrec`, `id`, `title`, `summary`, `source`, `owner`, `createdAt`, `updatedAt`, `version`, `mode`, `video`, `tracks`, `pauses`, `durationMs`, `viewport`, `codebase`, `chapters`, `keys`, `clipOf`, `variantOf`, `capture`, `files`, `player`. ### formrec_guide @@ -90,7 +90,7 @@ Returns structured content: `valid`, `title`, `steps`, `commit`, `problems`, `de ## Demos -Open one at `#/demo/` while FormRec runs (`formrec_demos` returns the full link with the run's token). +Open one at `#/demo/` while FormRec runs (`formrec_demos` returns the full link; demos need no token). | Id | Title | Kind | Chapters | Point a person at it for | | --- | --- | --- | --- | --- | @@ -99,4 +99,4 @@ Open one at `#/demo/` while FormRec runs (`formrec_demos` retur ## Command line equivalents -`formrec validate FILE`, `record FILE [--base-url URL] [--headed]`, `list`, `url` (the player base with the token), `serve [--codebase DIR] [--repo-url URL] [--open]`, `agents install|status|sync`. Output is the same JSON the tools return. The guide, the demos and the feature tools are MCP only. +`formrec validate FILE`, `record FILE [--base-url URL] [--headed]`, `list`, `url` (the app's address with the run's token; `--rotate-player-links` stops every player link given so far), `serve [--codebase DIR] [--repo-url URL] [--open]`, `agents install|status|sync`. Output is the same JSON the tools return. The guide, the demos and the feature tools are MCP only. diff --git a/.claude/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md b/.claude/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md index d7b877e..e70f4e4 100644 --- a/.claude/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md +++ b/.claude/skills/formrec-harness/sub-skills/demos/SUB-SKILL.md @@ -7,7 +7,7 @@ description: Points a person at the demos that ship with FormRec. Use when the p ## Find them -`formrec_demos` lists every demo that ships with FormRec: `id`, `title`, `kind` (`walkthrough` or `studio`), `shows` (what is in it), `pointAt` (who it is for), `chapters` (id, title, start), `durationMs`, `tracks`, the `route` (`#/demo/`) and `player`, the full link with the run's token. `references/tools.md` has the same list as a table. +`formrec_demos` lists every demo that ships with FormRec: `id`, `title`, `kind` (`walkthrough` or `studio`), `shows` (what is in it), `pointAt` (who it is for), `chapters` (id, title, start), `durationMs`, `tracks`, the `route` (`#/demo/`) and `player`, the full link (demos need no token). `references/tools.md` has the same list as a table. Never invent a demo id: take it from `formrec_demos`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea6de30..9478307 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,9 +13,17 @@ permissions: contents: read jobs: - test: + # The suite (real recordings, the studio in Chromium, FFmpeg media and live tests) takes about an hour as one + # run: a hosted Linux runner for a private repository has two cores, so vitest runs one test file at a time. + # Four runners each take a quarter of the files and write a blob report with their coverage; `test` merges them. + test-shard: + name: test shard ${{ matrix.shard }}/4 runs-on: ubuntu-latest - timeout-minutes: 20 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3, 4] steps: - name: Apt mirror fallback if: runner.os == 'Linux' @@ -36,9 +44,53 @@ jobs: cache: npm - run: npm ci - run: npx playwright install --with-deps chromium + # The media tests make and read their files with FFmpeg and FFprobe; the picture guide's PDF test reads the + # PDF with pdftotext and pdfimages (poppler-utils). Tesseract, Xvfb and the phone tools skip when absent. + - name: FFmpeg and poppler for the media tests + run: sudo apt-get update && sudo apt-get install -y ffmpeg poppler-utils + - run: npm run build + - name: Tests and coverage for this shard + run: >- + npx vitest run --coverage --shard=${{ matrix.shard }}/4 + --reporter=default --reporter=blob --outputFile.blob=.vitest-reports/blob-${{ matrix.shard }}.json + - uses: actions/upload-artifact@v4 + if: ${{ !cancelled() }} + with: + name: vitest-blob-${{ matrix.shard }} + path: .vitest-reports/ + include-hidden-files: true + retention-days: 1 + if-no-files-found: error + + # Type checks, then every shard's results and coverage as one report (what `npm run coverage` prints). + test: + needs: test-shard + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci - run: npm run check - run: npm run build - - run: npm run coverage + - uses: actions/download-artifact@v4 + with: + pattern: vitest-blob-* + path: .vitest-reports + merge-multiple: true + - name: Merged results and coverage + run: npx vitest run --mergeReports=.vitest-reports --coverage + - name: Every shard finished + if: ${{ needs.test-shard.result != 'success' }} + run: | + echo "A test shard did not pass: ${{ needs.test-shard.result }}" + exit 1 # The desktop shell compiles (as formcut's checks.yml does): FormCompiler builds the real app from # setup/build_release; this only proves src-tauri still compiles, is formatted and passes its unit test. diff --git a/.gitignore b/.gitignore index 0828de6..c26e3c8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ node_modules/ dist/ coverage/ +.vitest-reports/ .formrec-test/ *.log .DS_Store diff --git a/CLAUDE.md b/CLAUDE.md index 5431115..f1b2f59 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ The app is FormRec (window title, brand, docs headings). The CLI and package `fo - The main server listens on 127.0.0.1 only and answers only loopback host names (DNS rebinding). The guest listener is the one thing on the network: HTTPS, on only while guests are turned on, serving the guest page and the guest API and nothing else. A guest writes only its own tracks, only in the room's current session, and signals only the host. Every loopback `/api` route needs the run's token; media take it as `?token=` because the video element fetches them itself. The loopback server sets no cookies; the guest listener's only cookie is the paired device's (HttpOnly, Secure, SameSite=Strict). Public share servers (the tunnel's origin on 127.0.0.1:8776, the relay on `$PORT` or 8780) answer the share routes only, through `handleShareRequest` with `hardened` limits, plus the routes they add in `before`; they trust a forwarded address only where they can (the tunnel listens on loopback only; the relay only with FORMREC_RELAY_TRUST_PROXY=1). Every inbound request from another product is verified before its body is trusted. Ports: 8770 command line, 8771 guests, 8772 desktop, 8773 share, 8774 recorder SDK (LAN), 8775 MCP over HTTP, 8776 the tunnel's origin, 8780 the relay. - Code anchors and walkthroughs are untrusted input from agents and people. The codebase root a walkthrough names must sit inside a root the operator gave (`anchors/codebase.ts`); never read a file outside it, including through symlinks; never show secret-looking files (`looksSecret`); never serve a file by a name the request chose (library files come from a fixed list). - Recordings are private: data folders 0700, files 0600. A saved recording is never overwritten by an upload. -- The relay's bridge never returns the owner's token: its tools are built with no player base, so no answer holds a `?token=` link, and a tool offered through the bridge must not return one (`tests/bridgescope-audit.test.ts`). A stream key is held in memory by the live forwarder only, never in an argument list, an environment or a log. +- The relay's bridge never returns the owner's token: its tools are built with no player base, so no answer holds a `?token=` link, and a tool offered through the bridge must not return one (`tests/bridgescope-audit.test.ts`). No link handed out (MCP answers, the command line's JSON) carries the run's token: `buildServer` gives a recording's link its player key (`server/player-link.ts`, `mcp/player-links.ts`), which opens `/api/player/` only and is replaced by Settings, Agents, Player links, Rotate (`tests/player-link.test.ts`). A stream key is held in memory by the live forwarder only, never in an argument list, an environment or a log. - Every play goes through `startPlay` (`web/src/player-controls.ts`): a play the browser refuses leaves the bar and the frame paused (`playrefused`, `data-play-error`). Do not add a `play().catch(() => undefined)` (the follow and seek in `web/src/sync.ts` still have two; that is open). - A recording has a deadline and every overlay call is bounded: the toured page can tamper with the overlay, so its calls never fail or hang a step. - The headless runner opens http and https only. diff --git a/NOTICE.md b/NOTICE.md index 3e9ddbd..a857177 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -24,6 +24,7 @@ Development only: typescript (Apache-2.0), vitest and @vitest/coverage-v8 (MIT), | Node.js 22 runtime | MIT, with the licences of the libraries it bundles (shipped as `app/NODE_LICENSE`) | runs `formrec serve --desktop` inside the app; downloaded from nodejs.org by `setup/stage_desktop` and checked against `setup/node-runtime.sha256` | | tauri (with its tray-icon feature), tauri-build and the Tauri plugins in `src-tauri/Cargo.toml` (single-instance, shell, dialog, opener, deep-link, notification, global-shortcut) | MIT or Apache-2.0 | the desktop window, the sidecar, the native menu, the tray, `formrec://` links and file associations, native notifications, global shortcuts | | objc2, objc2-app-kit (macOS only) | MIT or Apache-2.0 (or Zlib) | the floating windows' macOS behaviour (above full-screen apps, left out of screen capture) | +| objc2-foundation, block2 (macOS only; already in the lock through tauri and wry) | MIT or Apache-2.0 (or Zlib) | recording an iPhone or iPad on USB through AVFoundation and CoreMediaIO, system frameworks (`src-tauri/src/phone.rs`) | | the crates in `src-tauri/Cargo.lock` | MIT or Apache-2.0 (each crate's own) | linked into the desktop shell | | the production npm dependencies above | as listed | staged into the app's resources without install scripts or browsers | @@ -41,6 +42,8 @@ Development only: typescript (Apache-2.0), vitest and @vitest/coverage-v8 (MIT), | `tests/fixtures/saml/onelogin-2014-05-28.*`, `tests/fixtures/saml/verizon-idp-hub-2014-06-05.*` (tests only, not shipped) | signed SAML responses and their certificates from node-saml's test suite, github.com/node-saml/node-saml `test/tests.spec.ts` and `test/types.ts` | MIT (Copyright (c) 2012 Henri Bergius, (c) 2011 Michael Bosworth) | | `apps/android/gradlew`, `apps/android/gradlew.bat`, `apps/android/gradle/wrapper/*` (gradle-wrapper.jar SHA-256 7d3a4ac4de1c32b59bc6a4eb8ecb8e612ccd0cf1ae1e99f66902da64df296172) | the Gradle Wrapper 8.10.2 from gradle.org | Apache-2.0 | | Robolectric 4.14.1, androidx.test:core 1.6.1, androidx.work:work-testing 2.10.0, com.vaadin.external.google:android-json 0.0.20131108.vaadin1 (the Android app's tests only, fetched by Gradle, not shipped in the app) | Maven Central and Google Maven | MIT (Robolectric), Apache-2.0 (the others) | +| scrcpy server 3.3.1 (`scrcpy-server-v3.3.1`, not shipped) | Apache-2.0 (Copyright (C) 2018 Genymobile, Copyright (C) 2018-2025 Romain Vimont; github.com/Genymobile/scrcpy) | recording an Android phone or emulator: downloaded once, at first use, from the scrcpy release on github.com into `/phone/scrcpy/`, accepted only with SHA-256 a0f70b20aa4998fbf658c94118cd6c8dab6abbb0647a3bdab344d70bc1ebcbb8 (the value the release publishes), pushed to the phone over adb and run there; the client side of its protocol is FormRec's own (`src/features/phone/scrcpy.ts`, `mkv.ts`) | +| adb, Android SDK Platform-Tools (not shipped) | Android Software Development Kit License (Google's terms) | talking to an Android phone; used only when the person has installed it (PATH, ANDROID_HOME, ANDROID_SDK_ROOT or the SDK's usual folder) | | cloudflared (not shipped) | Apache-2.0 | the public-link tunnel, when the person installs it or clicks Download cloudflared (fetched from github.com/cloudflare/cloudflared releases into `/bin`); Tailscale and ngrok are used only when the person has them | | `apps/*` (the other products' halves of the integration apps) | written for FormRec | Apache-2.0. They name packages installed in the vendor's own tooling when the owner deploys them, not shipped by FormRec: `@hubspot/ui-extensions` (HubSpot's) and react (MIT) for the HubSpot card; `@forge/api`, `@forge/resolver`, `@forge/bridge` (Atlassian's Forge terms) and esbuild (MIT) for the Jira app; AndroidX, Jetpack Compose, WorkManager and kotlinx-coroutines (Apache-2.0) and Google Play services' code scanner (Google's terms) for the Android app; the iOS app uses system frameworks only; Zendesk's app SDK loads from Zendesk's CDN at run time | | `relay/Dockerfile` | written for FormRec, built on the official `node:22-slim` image (Node.js MIT; the image's Debian packages under their own licences) | Apache-2.0 | diff --git a/README.md b/README.md index c504fab..f511df4 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ FormRec records anything on your screen and finishes it itself; FormCut and FormWav are there when you want the family's full editors. -- **Studio.** Screen, camera and microphone, camera and microphone, or audio only. Every source is its own track, uploaded in two-second chunks while it records, so a closed tab loses at most one chunk. Pause and resume. Marks become chapters. +- **Studio.** Screen, camera and microphone, camera and microphone, or audio only. Every source is its own track, uploaded in two-second chunks while it records, so a closed tab loses at most one chunk. Pause and resume. Marks become chapters. A dBFS level meter is always on screen (target band, peak hold, a clip light and count, plain hints), with a level check before the take and the clips listed after it. The Voice master preset turns off every browser process on the microphone and writes a lossless 48 kHz 24-bit WAV beside the Opus track, with room tone first; script mode shows a script one paragraph at a time and Space drops a chapter for each. Export with sound joins the camera or the screen with the microphone in one MP4. - **Guests on this network.** Turn on guests and a phone or computer on the same Wi-Fi opens the link, enters a six-digit code and joins the call. Each guest records their own camera and microphone at full quality and sends it as it goes; the call is only for talking (each guest hears everyone but themselves). Nothing leaves the network: HTTPS with a certificate this computer makes, no tunnel, no outside server. - **Open in FormCut.** One button places every track on its own FormCut timeline track at the right offset. - **Settings.** System, dark or light theme (applied before the window draws), the default recording mode, how guests join, the library folder, and the lines that connect Claude Code, Codex or Cursor. Open it from the gear, the sidebar, Home's Settings menu or Ctrl+, (Cmd+, on a Mac). @@ -182,6 +182,8 @@ Connect an agent in one of three ways: - **Over HTTP:** the app serves the same tools at `/mcp` (Streamable HTTP, with a bearer token), and `formrec mcp --http` runs them on port 8775. An agent somewhere else connects to your relay with OAuth 2.1: its `/mcp` works over what is published there, as the person who approved the agent, and when you turn the bridge on, `/mcp/bridge` passes every call to this computer while it is online. +**Player links.** A link an agent gives you for a recording opens that recording's player and nothing else: it carries a key for that one recording, never the app's own token, so it cannot open your library, Settings or any other part of FormRec. To stop every player link given so far, choose Settings, Agents, Player links, Rotate (or run `formrec url --rotate-player-links`); agents give new links in their next answers. `formrec url` still prints the app's own address for you. + By hand, any MCP client: ```json @@ -208,7 +210,7 @@ The feature modules add their own tools (editing, transcripts, sharing, comments ## What it writes -`~/formrec/recordings//` (or `FORMREC_DATA`, folders 0700, files 0600): `recording.json`, one `track-.webm` per source (studio) or `video.webm` (walkthroughs), `captions.vtt`, `chapters.vtt`, `session.json` while recording and, for agent-made recordings, `walkthrough.json`; feature modules add their own files beside them. The video and the tracks are plain WebM: export or share them from FormRec, or open them in FormCut. +`~/formrec/recordings//` (or `FORMREC_DATA`, folders 0700, files 0600): `recording.json`, one `track-.webm` per source (studio; the camera and screen files are pictures only, with no sound) or `video.webm` (walkthroughs), `master-host-mic.wav` for a Voice master take, `captions.vtt`, `chapters.vtt`, `session.json` while recording and, for agent-made recordings, `walkthrough.json`; feature modules add their own files beside them. The video and the tracks are plain WebM: export or share them from FormRec, or open them in FormCut. ## Settings diff --git a/docs/api.md b/docs/api.md index e38175b..7dac9f0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -28,6 +28,7 @@ From `src/server/http.ts`: | GET | `/api/recordings` | list | | GET | `/api/recordings/:id` | one recording | | GET | `/api/recordings/:id/:file` | video.webm, captions.vtt, chapters.vtt | +| GET | `/api/player/:id[/:file]?key=` | one recording's player with its player key, not the run's token (player-link.ts) | | POST | `/api/uploads` | body = webm from the recorder; returns { id } | | PUT | `/api/uploads/:id` | body = PersonRecording JSON; saves the recording | | DELETE | `/api/recordings/:id` | | @@ -47,6 +48,7 @@ From `src/server/studio-routes.ts`: | POST | `/api/sessions/:id/recover` | { title?, summary? } -> recording (an unsaved take, closed at its last write) | | DELETE | `/api/sessions/:id[?cancel=1]` | discard an unsaved take explicitly (cancel=1: the studio's own live take) | | POST | `/api/sessions/:id/tracks?source=system` | the computer's sound as its own track (host-system) | +| POST | `/api/sessions/:id/tracks?source=phone` | a phone's sound as its own track (host-phone) | | GET | `/api/rtc?after=n` | | | POST | `/api/rtc` | the host's signalling | | GET | `/api/guests` | | @@ -98,6 +100,7 @@ From `src/features/agents/index.ts`: | GET | `/api/agents` | { server, clients: [{ id, name, config, found, state, snippet, http? }], tools: [names], | | POST | `/api/agents/install` | { client, transport?: "stdio" \| "http" \| "relay" } -> { said: [lines], clients, relay } | | POST | `/api/agents/mcp-token/rotate` | -> { http, clients } a new MCP token; the old one stops working at once | +| POST | `/api/agents/player-links/rotate` | -> { rotated: true } every player link given so far stops working at once | From `src/features/ai/index.ts`: @@ -428,6 +431,14 @@ From `src/features/meetings/index.ts`: | POST | `/api/meetings/recordings/:id/recap` | make the recap document (meeting-recap.md) | | POST | `/api/meetings/recordings/:id/email` | { to? } email the recap through src/mail | +From `src/features/phone/files.ts`: + +| method | path | what it does | +|---|---|---| +| POST | `/api/phone/files?name= body = the video -> { id, name, bytes, durationMs? } | +| GET | `/api/phone/files/:id` | the video (ranged), for the stage | +| DELETE | `/api/phone/files/:id` | | + From `src/features/phone/handler.ts`: | method | path | what it does | @@ -461,6 +472,21 @@ From `src/features/phone/native.ts`: | POST | `/uploads/:id/complete` | { title?, durationMs? } -> { id, title, durationMs } (repeating it answers the same) | | POST | `/uploads/:id/discard` | remove the unfinished upload | +From `src/features/phone/routes.ts`: + +| method | path | what it does | +|---|---|---| +| GET | `/api/phone/sources` | what can be recorded here: Android devices and emulators (adb), | +| POST | `/api/phone/feed/start` | { sessionId, source } the phone becomes the take's picture (feed.ts) | +| POST | `/api/phone/feed/begin` | { sessionId } the shell started recording the iPhone: its tracks start now | +| POST | `/api/phone/feed/pause` | \| resume { sessionId } | +| POST | `/api/phone/feed/stop` | { sessionId, durationMs? } -> { durationMs, tracks, notes } | +| GET | `/api/phone/feed?sessionId=` | the feed's state | +| POST | `/api/phone/files?name=` | a phone recording to narrate over (files.ts) | +| GET | `/api/phone/files/:id` | | +| POST | `/api/phone/recordings/:id/export` | { layout } a portrait or framed copy of a phone take (export.ts) | +| GET | `/api/phone/recordings/:id/export/:layout` | that copy, as a download | + From `src/features/redact/index.ts`: | method | path | what it does | @@ -591,12 +617,18 @@ From `src/features/studio/index.ts`: | DELETE | `/api/studio/takes/:id/trims` | restore every trimmed range | | GET | `/api/studio/takes/:id/preview` | the take's lead track as written so far (Live Rewind's look back; ?token=) | | POST | `/api/studio/takes/:id/camera` | { on } the camera turned on or off now, on the take's timeline | +| POST | `/api/studio/takes/:id/master` | ?seq=n, body = WAV bytes: the Voice master, in order like a track's chunks (src/studio/master.ts) | +| POST | `/api/studio/takes/:id/master/end` | { durationMs } the master is complete: its sizes are written | | GET | `/api/studio/screenshots` | the screenshots, newest first | | POST | `/api/studio/screenshots?title=&source=` | body = PNG bytes -> the screenshot | | GET | `/api/studio/screenshots/:id` | one screenshot's details | | GET | `/api/studio/screenshots/:id/image` | the PNG (?token= for ) | | PATCH | `/api/studio/screenshots/:id` | { title } | | DELETE | `/api/studio/screenshots/:id` | | +| GET | `/api/studio/devices` | the microphone and camera names the studio last found (labels only) | +| PUT | `/api/studio/devices` | { mics, cameras, cameraInUse, permission, text, requestId? } the studio's report | +| POST | `/api/studio/devices/refresh` | { askPermission? } ask the open studio to rebuild its lists | +| GET | `/api/studio/devices/request` | the refresh request still waiting (the studio polls it), or {} | From `src/features/teamsync/routes.ts`: @@ -820,6 +852,13 @@ From `src/relay/team.ts`: | GET | `/relay-api/team/recordings/:id/files/:name` | one of those files (unsealed), for "Save a copy" | | POST | `/relay-api/team/transfer` | { from, to, revoke? } (owner key) a leaving person's recordings change hands, their keys are revoked | +From `src/server/player-link.ts`: + +| method | path | what it does | +|---|---|---| +| GET | `/api/player/:id?key=` | the recording (what the player draws) | +| GET | `/api/player/:id/:file?key=` | its video, tracks, captions and chapters (the core media names, server/http.ts MEDIA) | + ## The guest listener HTTPS on the local network, on only while guests are turned on in the studio. A guest pairs with a six-digit code diff --git a/docs/parity/studio.md b/docs/parity/studio.md index 5b79b37..8e59225 100644 --- a/docs/parity/studio.md +++ b/docs/parity/studio.md @@ -32,6 +32,7 @@ Tests: `tests/sessions-recovery.test.ts` (recovery), `tests/studio-feature.test. | R1-53 | Screenshots | A still of the stage (composed picture, screen or camera) saved as a recording-like item with its own API; listed in the studio's Screenshots panel. Annotating the still is not done here. | `src/studio/screenshots.ts`, `/api/studio/screenshots`, `[data-studio-shots-panel]` | `studio-feature.test.ts`; e2e canvas test | | R1-56, P-04 | Local backup and recovery | A take is written to disk as it records; it is never swept. Unsaved takes are listed (studio panel, `GET /api/sessions?unsaved=1`, MCP) and recovered through the save path (closed at the last write, unfinished tracks marked incomplete) or discarded explicitly. | `Sessions.list/closeForRecovery/discard`, `recoverSession`, `sweepOrphans`, `[data-studio-recover-panel]`, MCP `formrec_unsaved_takes`, `formrec_recover_take`, `formrec_discard_take` (destructiveHint) | `sessions-recovery.test.ts` (incl. the sweep); `studio-feature.test.ts`; e2e "recovers it into a recording" | | R1-57 | Presentation recording | Slides layout: image slides drawn straight into the picture with the camera beside them (previous, next), or a captured tab or window (a PDF opens in a tab to capture). | `[data-mode="presentation"]`, `[data-studio-slides]`, `Compositor` | `studio-logic.test.ts` (the layout's sources); `studio-proof-e2e.test.ts` "R1-57 Slides layout": three coloured image slides, Next, Next, Previous, the composed stage shows each slide's colour with the camera beside it, and the saved track decoded with FFmpeg follows the slides (image slides never drew before 0.5.0: the page's CSP allowed no `blob:` images). Since 0.6.0 each slide change while recording adds a mark titled by the image's file name (else "Slide N"), so the chapters follow the slides, and PageDown, ArrowRight and Space or PageUp and ArrowLeft step the slides in this layout (never from a text field, a dialog, a held key, the countdown or a Live Rewind); a slide changed while paused still makes its chapter, and a Live Rewind that trims off a slide change starts the kept footage with the chapter of the slide still shown: `studio-slides-e2e.test.ts` (chapters at the stamped times within 1 s, the composed track's colour per chapter, keys in the title field ignored, the paused change, a dialog and a held key, the rewind, CLS 0 at 4x throttling). | -| (agents) | Studio state over MCP | `formrec_studio_state` reads the state the open studio reports on every change. | `PUT/GET /api/studio/state` | `studio-feature.test.ts` | +| (agents) | Studio state over MCP | `formrec_studio_state` reads the state the open studio reports on every change, with the device names it last found. | `PUT/GET /api/studio/state` | `studio-feature.test.ts` | +| (devices) | Microphone and camera lists that follow the hardware | The lists refill on `devicechange` (debounced), when the window is shown or focused again and when a permission is granted, keeping the current choice, then the saved one, then the system default. Refresh devices beside the pickers rebuilds both and, when names are hidden, asks for permission once and stops those tracks at once. `formrec_studio_refresh_devices` asks the open studio for the same refresh. | `web/src/studio-devices.ts`, `studio-devices-ui.ts`, `src/studio/devices.ts`, `/api/studio/devices` | `studio-devices.test.ts`, `studio-feature.test.ts`, `studio-e2e.test.ts` | Layout shift: Chromium layout-shift observer, 4x CPU throttling on load and Get ready, then recording, camera switch and pause: see the report for the measured value (`tests/studio-e2e.test.ts`, written to `layout-shift.txt` when `FORMREC_SHOTS` is set). diff --git a/shared/wav.ts b/shared/wav.ts new file mode 100644 index 0000000..5903714 --- /dev/null +++ b/shared/wav.ts @@ -0,0 +1,103 @@ +/** + * The lossless microphone master's file format: a canonical 44-byte RIFF/WAVE header (PCM, one fmt chunk, then data) + * and little-endian 24-bit samples. The studio writes it while it records (web/src/wav-recorder.ts), so the header goes + * first with its two sizes unknown (0xFFFFFFFF, which readers take as "to the end of the file"); the server checks the + * header on the first chunk and writes the real sizes when the take ends (src/studio/master.ts). Pure, so the client + * and the server use the same layout; tests/wav.test.ts covers it. + */ + +export const WAV_HEADER_BYTES = 44 +/** The size fields' value while the length is not known yet. */ +export const UNKNOWN_SIZE = 0xffffffff +/** The largest data a 32-bit RIFF size can describe. */ +export const MAX_WAV_DATA = UNKNOWN_SIZE - (WAV_HEADER_BYTES - 8) + +export interface WavFormat { + sampleRate: number + channels: number + bitsPerSample: 16 | 24 | 32 +} + +const ascii = (view: DataView, at: number, text: string): void => { + for (let i = 0; i < text.length; i += 1) view.setUint8(at + i, text.charCodeAt(i)) +} +const readAscii = (view: DataView, at: number, length: number): string => { + let out = '' + for (let i = 0; i < length; i += 1) out += String.fromCharCode(view.getUint8(at + i)) + return out +} + +/** The header for PCM samples in this format; dataBytes undefined writes the unknown size into both size fields. */ +export function wavHeader(format: WavFormat, dataBytes?: number): Uint8Array { + const out = new Uint8Array(WAV_HEADER_BYTES) + const view = new DataView(out.buffer) + const blockAlign = format.channels * (format.bitsPerSample / 8) + ascii(view, 0, 'RIFF') + view.setUint32(4, dataBytes === undefined ? UNKNOWN_SIZE : dataBytes + WAV_HEADER_BYTES - 8, true) + ascii(view, 8, 'WAVE') + ascii(view, 12, 'fmt ') + view.setUint32(16, 16, true) + view.setUint16(20, 1, true) + view.setUint16(22, format.channels, true) + view.setUint32(24, format.sampleRate, true) + view.setUint32(28, format.sampleRate * blockAlign, true) + view.setUint16(32, blockAlign, true) + view.setUint16(34, format.bitsPerSample, true) + ascii(view, 36, 'data') + view.setUint32(40, dataBytes === undefined ? UNKNOWN_SIZE : dataBytes, true) + return out +} + +/** The format of a canonical header, or undefined when the bytes are not one this app writes (PCM, mono or stereo). */ +export function parseWavHeader(bytes: Uint8Array): (WavFormat & { dataBytes: number }) | undefined { + if (bytes.length < WAV_HEADER_BYTES) return undefined + const view = new DataView(bytes.buffer, bytes.byteOffset, WAV_HEADER_BYTES) + if (readAscii(view, 0, 4) !== 'RIFF' || readAscii(view, 8, 4) !== 'WAVE' || readAscii(view, 12, 4) !== 'fmt ' || readAscii(view, 36, 4) !== 'data') return undefined + if (view.getUint32(16, true) !== 16 || view.getUint16(20, true) !== 1) return undefined + const channels = view.getUint16(22, true) + const sampleRate = view.getUint32(24, true) + const bits = view.getUint16(34, true) + if (channels < 1 || channels > 2 || sampleRate < 8000 || sampleRate > 192_000) return undefined + if (bits !== 16 && bits !== 24 && bits !== 32) return undefined + const blockAlign = channels * (bits / 8) + if (view.getUint16(32, true) !== blockAlign || view.getUint32(28, true) !== sampleRate * blockAlign) return undefined + return { sampleRate, channels, bitsPerSample: bits, dataBytes: view.getUint32(40, true) } +} + +/** The two size fields for a file of fileBytes in all (header included), capped at what 32 bits can hold. */ +export function sizeFields(fileBytes: number): { riff: number; data: number } { + const data = Math.max(0, Math.min(MAX_WAV_DATA, fileBytes - WAV_HEADER_BYTES)) + return { riff: data + WAV_HEADER_BYTES - 8, data } +} + +/** Float samples (-1 to 1; anything beyond is clipped, as a converter would) as little-endian signed 24-bit PCM. */ +export function encodePcm24(samples: ArrayLike): Uint8Array { + const out = new Uint8Array(samples.length * 3) + for (let i = 0; i < samples.length; i += 1) { + const s = Math.max(-1, Math.min(1, samples[i]! || 0)) + // Negative full scale is -8388608, positive full scale 8388607: scale each side to its own limit. + const v = s < 0 ? Math.round(s * 8_388_608) : Math.round(s * 8_388_607) + const u = v < 0 ? v + 0x1000000 : v + out[i * 3] = u & 0xff + out[i * 3 + 1] = (u >> 8) & 0xff + out[i * 3 + 2] = (u >> 16) & 0xff + } + return out +} + +/** Back from 24-bit PCM to floats (the tests' round trip, and checking a file's level). */ +export function decodePcm24(bytes: Uint8Array): Float32Array { + const out = new Float32Array(Math.floor(bytes.length / 3)) + for (let i = 0; i < out.length; i += 1) { + const u = bytes[i * 3]! | (bytes[i * 3 + 1]! << 8) | (bytes[i * 3 + 2]! << 16) + const v = u & 0x800000 ? u - 0x1000000 : u + out[i] = v < 0 ? v / 8_388_608 : v / 8_388_607 + } + return out +} + +/** How long data of this many bytes plays, in ms. */ +export function wavDurationMs(format: WavFormat, dataBytes: number): number { + const frame = format.channels * (format.bitsPerSample / 8) + return Math.round((Math.floor(dataBytes / frame) / format.sampleRate) * 1000) +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 19fc244..f728505 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1073,8 +1073,10 @@ dependencies = [ name = "formrec-desktop" version = "0.9.0" dependencies = [ + "block2", "objc2", "objc2-app-kit", + "objc2-foundation", "serde", "serde_json", "tauri", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b4d53b6..baad71e 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -30,6 +30,10 @@ serde_json = "1" [target.'cfg(target_os = "macos")'.dependencies] objc2 = "0.6" objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWindow", "NSView", "NSResponder", "objc2-core-foundation", "NSColor"] } +# An iPhone or iPad over USB (src/phone.rs): AVFoundation through objc2, the same versions tauri and wry already +# use, so the lock gains no package. +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString", "NSURL", "NSArray"] } +block2 = "0.6" # The web view's settings and permission request (src/media.rs): WebKitGTK has media stream off and wry never turns it # on. The same crate and version wry already uses (features as wry's), so the lock gains no package. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 8280126..da4ee12 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -10,6 +10,11 @@ const APP_COMMANDS: &[&str] = &[ "desktop_quiet_setup", "desktop_bubble_fill", "desktop_install_cli", + "phone_ios_devices", + "phone_ios_start", + "phone_ios_pause", + "phone_ios_resume", + "phone_ios_stop", ]; fn main() { diff --git a/src-tauri/capabilities/main.json b/src-tauri/capabilities/main.json index 368d9a8..ee6d603 100644 --- a/src-tauri/capabilities/main.json +++ b/src-tauri/capabilities/main.json @@ -1,7 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "main-ready", - "description": "The main window shows the page the bundled formrec server serves on 127.0.0.1, a remote origin to Tauri. It may call app_ready, which the shell's start-up script sends once the page has drawn its first content, and the desktop commands web/src/features/desktop.ts uses (take state, settings, displays, notifications, the click log, the formrec command).", + "description": "The main window shows the page the bundled formrec server serves on 127.0.0.1, a remote origin to Tauri. It may call app_ready, which the shell's start-up script sends once the page has drawn its first content, and the desktop commands web/src/features/desktop.ts uses (take state, settings, displays, notifications, the click log, the formrec command) and web/src/features/phone-capture.ts uses (an iPhone or iPad on USB: list, start, pause, resume, stop).", "windows": ["main"], "remote": { "urls": ["http://127.0.0.1:*"] }, "permissions": [ @@ -14,6 +14,11 @@ "allow-desktop-notify", "allow-desktop-displays", "allow-desktop-quiet-setup", - "allow-desktop-install-cli" + "allow-desktop-install-cli", + "allow-phone-ios-devices", + "allow-phone-ios-start", + "allow-phone-ios-pause", + "allow-phone-ios-resume", + "allow-phone-ios-stop" ] } diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 7112e94..7e02cfa 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -12,6 +12,7 @@ mod links; mod media; mod menu; mod packaged; +mod phone; mod reveal; mod system; @@ -216,6 +217,7 @@ fn start(handle: AppHandle) { match event { CommandEvent::Stdout(bytes) if !opened => { let line = String::from_utf8_lossy(&bytes); + phone::note_ready(&handle, &line); if let Some((url, port)) = window_url(&line) { opened = true; if let Err(err) = open_main(&handle, url, port) { @@ -403,6 +405,7 @@ fn main() { quitting: AtomicBool::new(false), }) .manage(desktop::Desktop::::default()) + .manage(phone::Phone::default()) .on_menu_event(menu::handle) .invoke_handler(tauri::generate_handler![ reveal::app_ready, @@ -416,8 +419,17 @@ fn main() { desktop::desktop_quiet_setup, desktop::desktop_bubble_fill, desktop::desktop_install_cli, + phone::phone_ios_devices, + phone::phone_ios_start, + phone::phone_ios_pause, + phone::phone_ios_resume, + phone::phone_ios_stop, ]) .setup(|app| { + // An iPhone or iPad on USB is listed as a capture device only after this opt-in (src/phone.rs). + if cfg!(target_os = "macos") && !phone::allow_screen_devices() { + eprintln!("formrec-desktop: iPhone capture over USB is not available (CoreMediaIO refused the opt-in)"); + } reveal::round_splash(app.handle()); if cfg!(target_os = "macos") { let bar = menu::build(app.handle())?; @@ -437,6 +449,7 @@ fn main() { app.run(|handle, event| match event { RunEvent::Exit => { + phone::stop_all(handle); desktop::restore_all(handle); stop_server(handle); } diff --git a/src-tauri/src/phone.rs b/src-tauri/src/phone.rs new file mode 100644 index 0000000..26bf4a2 --- /dev/null +++ b/src-tauri/src/phone.rs @@ -0,0 +1,682 @@ +//! An iPhone or iPad over USB as a studio source (issue #7), macOS only. macOS lists an attached, unlocked and +//! trusted iOS device as a capture device once a process opts in to CoreMediaIO's screen capture devices +//! (`kCMIOHardwarePropertyAllowScreenCaptureDevices`, the switch QuickTime's New Movie Recording uses); the device is +//! then an AVFoundation "muxed" device that carries the phone's screen and its sound. The shell turns the switch on +//! at start (`allow_screen_devices`), lists those devices (`phone_ios_devices`) and records one with an +//! AVCaptureSession and an AVCaptureMovieFileOutput (`phone_ios_start`, `_pause`, `_resume`, `_stop`) at the size +//! and frame rate the phone sends, into `/phone/captures//capture.mov`: the capture id comes from the +//! server, the folder from the data folder the server named in its ready line, so the page never names a path. The +//! server then splits the file into the take's picture and phone-sound tracks (src/features/phone/feed.ts). +//! +//! The switch is set inside this process; whether the window's web view (WebKit captures in its own processes) also +//! lists the device as a camera is something the studio's Phone panel reports, not something this file relies on. +//! Every reply is `{ ok, error?, value? }` so the page sees the reason when something fails. Windows and Linux answer +//! that iPhone capture over USB needs a Mac. + +use std::path::PathBuf; +use std::sync::Mutex; + +use serde::Serialize; +use tauri::{AppHandle, Manager, Runtime}; + +#[derive(Serialize)] +pub struct Reply { + ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, + #[serde(skip_serializing_if = "Option::is_none")] + value: Option, +} + +impl Reply { + fn ok(value: T) -> Self { + Reply { + ok: true, + error: None, + value: Some(value), + } + } + fn fail(error: impl Into) -> Self { + Reply { + ok: false, + error: Some(error.into()), + value: None, + } + } +} + +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct IosDevice { + pub id: String, + pub name: String, + pub model: String, +} + +#[derive(Serialize)] +pub struct DeviceList { + mac: bool, + devices: Vec, +} + +#[derive(Default)] +pub struct Phone { + data: Mutex>, + #[cfg(target_os = "macos")] + capture: Mutex>, +} + +/// The data folder from the server's ready line (`{"formrec":"desktop",...,"data":""}`). +pub fn data_from_ready(line: &str) -> Option { + let ready: serde_json::Value = serde_json::from_str(line.trim()).ok()?; + if ready.get("formrec")?.as_str()? != "desktop" { + return None; + } + let data = PathBuf::from(ready.get("data")?.as_str()?); + data.is_absolute().then_some(data) +} + +pub fn note_ready(handle: &AppHandle, line: &str) { + if let Some(data) = data_from_ready(line) { + *handle.state::().data.lock().unwrap() = Some(data); + } +} + +/// A capture id the server made: `c` and 24 hex digits. +pub fn valid_capture(id: &str) -> bool { + id.len() == 25 + && id.starts_with('c') + && id[1..] + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// Where the shell writes a capture: only inside the data folder's capture area, under the id the server chose. +pub fn capture_path(data: &std::path::Path, capture: &str) -> Option { + valid_capture(capture).then(|| data.join("phone").join("captures").join(capture).join("capture.mov")) +} + +/// Opt this process in to screen capture devices; true when CoreMediaIO accepted it. +pub fn allow_screen_devices() -> bool { + #[cfg(target_os = "macos")] + { + mac::allow_screen_devices() + } + #[cfg(not(target_os = "macos"))] + { + false + } +} + +#[cfg(not(target_os = "macos"))] +const NEEDS_MAC: &str = "iPhone and iPad capture over USB needs a Mac."; + +#[tauri::command] +pub async fn phone_ios_devices() -> Reply { + #[cfg(target_os = "macos")] + { + match tauri::async_runtime::spawn_blocking(mac::devices).await { + Ok(devices) => Reply::ok(DeviceList { mac: true, devices }), + Err(err) => Reply::fail(format!("listing devices failed: {err}")), + } + } + #[cfg(not(target_os = "macos"))] + { + Reply::ok(DeviceList { + mac: false, + devices: Vec::new(), + }) + } +} + +#[tauri::command] +pub async fn phone_ios_start(app: AppHandle, device: String, capture: String) -> Reply { + let Some(data) = app.state::().data.lock().unwrap().clone() else { + return Reply::fail("the FormRec server has not said where its data folder is"); + }; + let Some(path) = capture_path(&data, &capture) else { + return Reply::fail("not a capture id from the FormRec server"); + }; + if device.is_empty() || device.len() > 200 { + return Reply::fail("not a device id"); + } + #[cfg(target_os = "macos")] + { + if app.state::().capture.lock().unwrap().is_some() { + return Reply::fail("an iPhone is already being recorded"); + } + if !path.parent().is_some_and(|p| p.is_dir()) { + return Reply::fail("the capture folder is missing; start the take again"); + } + let target = path.clone(); + match tauri::async_runtime::spawn_blocking(move || mac::Capture::start(&device, &target)).await { + Ok(Ok(started)) => { + *app.state::().capture.lock().unwrap() = Some(started); + Reply::ok(path.to_string_lossy().into_owned()) + } + Ok(Err(err)) => Reply::fail(err), + Err(err) => Reply::fail(format!("the recorder stopped: {err}")), + } + } + #[cfg(not(target_os = "macos"))] + { + let _ = path; + Reply::fail(NEEDS_MAC) + } +} + +#[tauri::command] +pub fn phone_ios_pause(app: AppHandle) -> Reply { + control(&app, true) +} + +#[tauri::command] +pub fn phone_ios_resume(app: AppHandle) -> Reply { + control(&app, false) +} + +fn control(app: &AppHandle, pause: bool) -> Reply { + #[cfg(target_os = "macos")] + { + match app.state::().capture.lock().unwrap().as_ref() { + Some(capture) => match capture.pause(pause) { + Ok(()) => Reply::ok(true), + Err(err) => Reply::fail(err), + }, + None => Reply::fail("no iPhone is being recorded"), + } + } + #[cfg(not(target_os = "macos"))] + { + let _ = (app, pause); + Reply::fail(NEEDS_MAC) + } +} + +#[tauri::command] +pub async fn phone_ios_stop(app: AppHandle) -> Reply { + #[cfg(target_os = "macos")] + { + let Some(capture) = app.state::().capture.lock().unwrap().take() else { + return Reply::fail("no iPhone is being recorded"); + }; + match tauri::async_runtime::spawn_blocking(move || capture.stop()).await { + Ok(Ok(())) => Reply::ok(true), + Ok(Err(err)) => Reply::fail(err), + Err(err) => Reply::fail(format!("the recorder stopped: {err}")), + } + } + #[cfg(not(target_os = "macos"))] + { + let _ = app; + Reply::fail(NEEDS_MAC) + } +} + +/// The app quits: a recording still running is finished so its file is readable. +pub fn stop_all(app: &AppHandle) { + #[cfg(target_os = "macos")] + if let Some(capture) = app.state::().capture.lock().unwrap().take() { + let _ = capture.stop(); + } + #[cfg(not(target_os = "macos"))] + let _ = app; +} + +#[cfg(target_os = "macos")] +mod mac { + use std::ffi::c_void; + use std::path::{Path, PathBuf}; + use std::sync::mpsc::{channel, Receiver, RecvTimeoutError, Sender}; + use std::sync::Mutex; + use std::thread::JoinHandle; + use std::time::Duration; + + use block2::RcBlock; + use objc2::rc::{autoreleasepool, Retained}; + use objc2::runtime::{AnyClass, AnyObject, AnyProtocol, Bool, NSObject, NSObjectProtocol}; + use objc2::{class, define_class, msg_send, AllocAnyThread, ClassType, DefinedClass}; + use objc2_foundation::{NSArray, NSString, NSURL}; + + use super::IosDevice; + + #[repr(C)] + struct PropertyAddress { + selector: u32, + scope: u32, + element: u32, + } + + #[link(name = "CoreMediaIO", kind = "framework")] + extern "C" { + fn CMIOObjectSetPropertyData( + object: u32, + address: *const PropertyAddress, + qualifier_size: u32, + qualifier: *const c_void, + data_size: u32, + data: *const c_void, + ) -> i32; + } + + #[link(name = "AVFoundation", kind = "framework")] + extern "C" { + static AVMediaTypeMuxed: &'static NSString; + static AVMediaTypeVideo: &'static NSString; + static AVMediaTypeAudio: &'static NSString; + static AVCaptureDeviceTypeExternal: &'static NSString; + } + + const fn fourcc(s: &[u8; 4]) -> u32 { + ((s[0] as u32) << 24) | ((s[1] as u32) << 16) | ((s[2] as u32) << 8) | s[3] as u32 + } + /// kCMIOObjectSystemObject + const SYSTEM_OBJECT: u32 = 1; + const START_WAIT: Duration = Duration::from_secs(20); + const STOP_WAIT: Duration = Duration::from_secs(30); + + pub fn allow_screen_devices() -> bool { + let address = PropertyAddress { + // kCMIOHardwarePropertyAllowScreenCaptureDevices, kCMIOObjectPropertyScopeGlobal, kCMIOObjectPropertyElementMain + selector: fourcc(b"yes "), + scope: fourcc(b"glob"), + element: 0, + }; + let allow: u32 = 1; + // SAFETY: the address and the 4-byte value outlive the call; no qualifier is passed. + let status = unsafe { + CMIOObjectSetPropertyData( + SYSTEM_OBJECT, + &address, + 0, + std::ptr::null(), + 4, + (&allow as *const u32).cast(), + ) + }; + status == 0 + } + + fn text(object: &AnyObject, selector: &str) -> String { + // SAFETY: each selector named here is an NSString property of AVCaptureDevice. + let value: Option> = unsafe { + match selector { + "uniqueID" => msg_send![object, uniqueID], + "localizedName" => msg_send![object, localizedName], + _ => msg_send![object, modelID], + } + }; + value.map(|s| s.to_string()).unwrap_or_default() + } + + fn array_items(list: &AnyObject) -> Vec> { + // SAFETY: `list` is an NSArray of AVCaptureDevice. + unsafe { + let count: usize = msg_send![list, count]; + (0..count).map(|i| msg_send![list, objectAtIndex: i]).collect() + } + } + + /// The muxed external devices: iPhones and iPads (and other screen capture devices) that carry picture and sound. + pub fn devices() -> Vec { + autoreleasepool(|_| { + let mut found: Vec> = Vec::new(); + // SAFETY: class methods of AVCaptureDeviceDiscoverySession and AVCaptureDevice with their documented + // argument types; the statics are AVFoundation's constant strings. + unsafe { + let types = NSArray::from_slice(&[AVCaptureDeviceTypeExternal]); + let session: Option> = msg_send![ + class!(AVCaptureDeviceDiscoverySession), + discoverySessionWithDeviceTypes: &*types, + mediaType: AVMediaTypeMuxed, + position: 0isize + ]; + if let Some(session) = session { + let list: Option> = msg_send![&*session, devices]; + if let Some(list) = list { + found.extend(array_items(&list)); + } + } + // The older call lists the same devices on systems where discovery leaves them out. + let older: Option> = + msg_send![class!(AVCaptureDevice), devicesWithMediaType: AVMediaTypeMuxed]; + if let Some(list) = older { + found.extend(array_items(&list)); + } + } + let mut out: Vec = Vec::new(); + for d in found { + let device = IosDevice { + id: text(&d, "uniqueID"), + name: text(&d, "localizedName"), + model: text(&d, "modelID"), + }; + if !device.id.is_empty() && !out.iter().any(|o| o.id == device.id) { + out.push(device); + } + } + out + }) + } + + /// Ask for the camera and microphone the first time (an iPhone's screen counts as a camera, its sound as a microphone). + fn authorize(media: &NSString) -> Result<(), String> { + // SAFETY: AVCaptureDevice's authorization class methods with an AVMediaType. + let status: isize = unsafe { msg_send![class!(AVCaptureDevice), authorizationStatusForMediaType: media] }; + match status { + 3 => Ok(()), + 0 => { + let (tx, rx) = channel::(); + let tx = Mutex::new(Some(tx)); + let block = RcBlock::new(move |granted: Bool| { + if let Some(tx) = tx.lock().unwrap().take() { + let _ = tx.send(granted.as_bool()); + } + }); + // SAFETY: the block is retained by AVFoundation for the duration of the request. + let _: () = unsafe { + msg_send![class!(AVCaptureDevice), requestAccessForMediaType: media, completionHandler: &*block] + }; + match rx.recv_timeout(Duration::from_secs(120)) { + Ok(true) => Ok(()), + _ => Err(denied(media)), + } + } + _ => Err(denied(media)), + } + } + + fn denied(media: &NSString) -> String { + let what = if media.to_string() == "soun" { + "Microphone" + } else { + "Camera" + }; + format!( + "FormRec may not use the {what}: allow it in System Settings, Privacy and Security, {what}, then try again" + ) + } + + struct Ivars { + started: Mutex>>, + done: Mutex>>>, + } + + define_class!( + // SAFETY: NSObject has no subclassing requirements; the delegate holds only channels. + #[unsafe(super(NSObject))] + #[name = "FormRecPhoneRecordingDelegate"] + #[ivars = Ivars] + struct Delegate; + + impl Delegate { + #[unsafe(method(captureOutput:didStartRecordingToOutputFileAtURL:fromConnections:))] + fn did_start(&self, _output: &AnyObject, _url: &AnyObject, _connections: &AnyObject) { + if let Some(tx) = self.ivars().started.lock().unwrap().take() { + let _ = tx.send(()); + } + } + + #[unsafe(method(captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:))] + fn did_finish(&self, _output: &AnyObject, _url: &AnyObject, _connections: &AnyObject, error: *mut AnyObject) { + // SAFETY: a non-null error is an NSError. + let message = (!error.is_null()).then(|| unsafe { + let text: Option> = msg_send![&*error, localizedDescription]; + text.map(|t| t.to_string()).unwrap_or_else(|| "the recording ended with an error".into()) + }); + if let Some(tx) = self.ivars().done.lock().unwrap().take() { + let _ = tx.send(message); + } + } + } + + unsafe impl NSObjectProtocol for Delegate {} + ); + + impl Delegate { + fn new(started: Sender<()>, done: Sender>) -> Retained { + let class = Self::class(); + if let Some(protocol) = AnyProtocol::get(c"AVCaptureFileOutputRecordingDelegate") { + // SAFETY: adding a protocol AVFoundation declares to a class this file defined; repeating it is a no-op. + unsafe { objc2::ffi::class_addProtocol(class as *const AnyClass as *mut AnyClass, protocol) }; + } + let this = Self::alloc().set_ivars(Ivars { + started: Mutex::new(Some(started)), + done: Mutex::new(Some(done)), + }); + // SAFETY: NSObject's init. + unsafe { msg_send![super(this), init] } + } + } + + enum Command { + Pause(bool, Sender>), + Stop(Sender>), + } + + pub struct Capture { + tx: Sender, + thread: Option>, + } + + impl Capture { + /// Starts recording `device` to `path`; returns once the movie file output says it has started. + pub fn start(device: &str, path: &Path) -> Result { + authorize(unsafe { AVMediaTypeVideo })?; + authorize(unsafe { AVMediaTypeAudio })?; + let (ready_tx, ready_rx) = channel::>(); + let (tx, rx) = channel::(); + let id = device.to_string(); + let file = path.to_path_buf(); + let thread = std::thread::Builder::new() + .name("formrec-iphone".into()) + .spawn(move || record(id, file, ready_tx, rx)) + .map_err(|e| format!("could not start the recorder: {e}"))?; + match ready_rx.recv_timeout(START_WAIT + Duration::from_secs(2)) { + Ok(Ok(())) => Ok(Capture { + tx, + thread: Some(thread), + }), + Ok(Err(err)) => Err(err), + Err(_) => Err("the phone did not start recording; unlock it and check it trusts this Mac".into()), + } + } + + pub fn pause(&self, pause: bool) -> Result<(), String> { + let (tx, rx) = channel(); + self.tx + .send(Command::Pause(pause, tx)) + .map_err(|_| "the recorder has stopped".to_string())?; + rx.recv_timeout(Duration::from_secs(5)) + .unwrap_or_else(|_| Err("the recorder did not answer".into())) + } + + pub fn stop(mut self) -> Result<(), String> { + let (tx, rx) = channel(); + let sent = self.tx.send(Command::Stop(tx)).is_ok(); + let result = if sent { + rx.recv_timeout(STOP_WAIT + Duration::from_secs(2)) + .unwrap_or_else(|_| Err("the recorder did not finish the file".into())) + } else { + Err("the recorder had already stopped".into()) + }; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + result + } + } + + /// A running recording: the session, its movie file output, the delegate, and where the delegate says it finished. + type Running = ( + Retained, + Retained, + Retained, + Receiver>, + ); + + fn record(id: String, path: PathBuf, ready: Sender>, commands: Receiver) { + autoreleasepool(|_| { + let setup = (|| -> Result { + // SAFETY: AVFoundation calls with their documented types; every object is checked before use, and an + // input or output is added only after canAddInput / canAddOutput said yes (adding one that cannot be + // added raises an Objective-C exception). + unsafe { + let device: Option> = + msg_send![class!(AVCaptureDevice), deviceWithUniqueID: &*NSString::from_str(&id)]; + let device = device.ok_or("the phone is no longer connected")?; + let mut error: *mut AnyObject = std::ptr::null_mut(); + let input: Option> = + msg_send![class!(AVCaptureDeviceInput), deviceInputWithDevice: &*device, error: &mut error]; + let input = input.ok_or_else(|| { + if error.is_null() { + "the phone could not be opened".to_string() + } else { + let text: Option> = msg_send![&*error, localizedDescription]; + format!( + "the phone could not be opened: {}", + text.map(|t| t.to_string()).unwrap_or_default() + ) + } + })?; + let session: Retained = msg_send![class!(AVCaptureSession), new]; + let can: Bool = msg_send![&*session, canAddInput: &*input]; + if !can.as_bool() { + return Err("the phone is in use by another app (QuickTime?)".into()); + } + let _: () = msg_send![&*session, addInput: &*input]; + let output: Retained = msg_send![class!(AVCaptureMovieFileOutput), new]; + let can: Bool = msg_send![&*session, canAddOutput: &*output]; + if !can.as_bool() { + return Err("the phone cannot be recorded to a file".into()); + } + let _: () = msg_send![&*session, addOutput: &*output]; + let _: () = msg_send![&*session, startRunning]; + let (started_tx, started_rx) = channel(); + let (done_tx, done_rx) = channel(); + let delegate = Delegate::new(started_tx, done_tx); + let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy())); + let _: () = + msg_send![&*output, startRecordingToOutputFileURL: &*url, recordingDelegate: &*delegate]; + match started_rx.recv_timeout(START_WAIT) { + Ok(()) => Ok((session, output, delegate, done_rx)), + Err(_) => { + let _: () = msg_send![&*output, stopRecording]; + let _: () = msg_send![&*session, stopRunning]; + Err("the phone sent no picture; unlock it and keep the screen on".into()) + } + } + } + })(); + let (session, output, _delegate, done) = match setup { + Ok(parts) => { + let _ = ready.send(Ok(())); + parts + } + Err(err) => { + let _ = ready.send(Err(err)); + return; + } + }; + let finish = |reply: Option>>| { + // SAFETY: the output and session made above. + unsafe { + let _: () = msg_send![&*output, stopRecording]; + } + let result = match done.recv_timeout(STOP_WAIT) { + Ok(error) => { + let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); + if size > 0 { + Ok(()) + } else { + Err(error.unwrap_or_else(|| "the recording is empty".into())) + } + } + Err(RecvTimeoutError::Timeout) => Err("the phone's file was not finished in time".into()), + Err(RecvTimeoutError::Disconnected) => Err("the recorder went away".into()), + }; + // SAFETY: as above. + unsafe { + let _: () = msg_send![&*session, stopRunning]; + } + if let Some(reply) = reply { + let _ = reply.send(result); + } + }; + loop { + match commands.recv() { + Ok(Command::Pause(pause, reply)) => { + // SAFETY: AVCaptureFileOutput's pause and resume (macOS). + unsafe { + if pause { + let _: () = msg_send![&*output, pauseRecording]; + } else { + let _: () = msg_send![&*output, resumeRecording]; + } + } + let _ = reply.send(Ok(())); + } + Ok(Command::Stop(reply)) => { + finish(Some(reply)); + return; + } + Err(_) => { + finish(None); + return; + } + } + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn takes_the_data_folder_only_from_the_servers_ready_line() { + let ok = r#"{"formrec":"desktop","url":"http://127.0.0.1:8772/","port":8772,"data":"/Users/x/formrec"}"#; + assert_eq!(data_from_ready(ok), Some(PathBuf::from("/Users/x/formrec"))); + assert_eq!(data_from_ready(r#"{"formrec":"desktop","data":"relative/dir"}"#), None); + assert_eq!(data_from_ready(r#"{"formrec":"other","data":"/x"}"#), None); + assert_eq!(data_from_ready("not json"), None); + } + + #[test] + fn writes_only_under_a_capture_id_the_server_made() { + let data = std::path::Path::new("/d"); + let id = format!("c{}", "a1".repeat(12)); + assert_eq!( + capture_path(data, &id), + Some(PathBuf::from(format!("/d/phone/captures/{id}/capture.mov"))) + ); + assert!(capture_path(data, "../../etc").is_none()); + assert!(capture_path(data, &format!("c{}", "A1".repeat(12))).is_none()); + assert!(capture_path(data, "c123").is_none()); + assert!(!valid_capture(&format!("x{}", "a".repeat(24)))); + } + + #[test] + fn replies_carry_the_reason() { + let fail = serde_json::to_string(&Reply::::fail("no")).unwrap(); + assert_eq!(fail, r#"{"ok":false,"error":"no"}"#); + assert_eq!( + serde_json::to_string(&Reply::ok(true)).unwrap(), + r#"{"ok":true,"value":true}"# + ); + } + + /// On a Mac: the opt-in is accepted and the device list answers (an iPhone on USB, unlocked and trusted, is listed). + /// Run by hand with `cargo test -- --ignored --nocapture`; it reads no camera, so it asks for no permission. + #[cfg(target_os = "macos")] + #[test] + #[ignore] + fn opts_in_and_lists_screen_capture_devices() { + assert!(allow_screen_devices(), "CoreMediaIO refused the opt-in"); + // Devices appear a moment after the opt-in. + std::thread::sleep(std::time::Duration::from_secs(3)); + let devices = mac::devices(); + println!("screen capture devices: {devices:?}"); + assert!(devices.iter().all(|d| !d.id.is_empty())); + } +} diff --git a/src/HASHOUT_LOG.md b/src/HASHOUT_LOG.md index 584e0c5..92cbf46 100644 --- a/src/HASHOUT_LOG.md +++ b/src/HASHOUT_LOG.md @@ -415,3 +415,36 @@ The desktop app is a WebKit webview, and WebKitGTK's MediaRecorder writes only M - logged: v0.9.0 · 2026-11-11 Building and running the Linux app found that its webview had no microphone or camera: WebKitGTK leaves media streams off and wry never turns them on, so every studio layout failed to get ready. The app now turns on media streams and WebRTC through `with_webview` and answers the webview's permission request for the microphone and camera only for its own `http://127.0.0.1:` page; anything else, screen sharing included, keeps WebKit's default, which denies. This needed `webkit2gtk` as a direct dependency for Linux, at the version and features wry already uses, so the lock gained an edge and no package. Tauri's AppImage step failed here because patchelf was missing (not FUSE), so `setup/build_release` now stops early with a clear message when patchelf or file is missing. The AppImage bundles the build host's GStreamer plugins; the machine running it needs a sound server. + +## unreleased · the Voice master's WAV and recording.json's capture {#voice-master-server} + +- refers-to: studio/master.ts `Masters` `fixSizes` `finishMaster`, ../shared/wav.ts, model/capture.ts `CaptureSchema` `CaptureInputSchema`, model/person.ts `PersonRecordingSchema.capture`, model/recording.ts `RecordingSchema.capture`, studio/finish.ts, features/studio/index.ts (the master routes, `files`); ../tests/master.test.ts, wav.test.ts, voice-master-e2e.test.ts +- logged: unreleased · 2026-11-29 + +A 19-minute take for voice training came out lossy and with no record of what the browser did to it. The Voice master preset writes a 48 kHz 24-bit mono WAV beside the Opus track. It is not a session track: every reader of `tracks` (the player, the exports, transcripts, FormCut, shares) would have played or mixed it a second time, so it is a file of its own with one fixed name, `master-host-mic.wav`, uploaded through the studio feature in ordered chunks with the same rules as a track's (seq, a repeat taken without writing, a gap refused with the chunk expected; the refusal now carries `next` and `final` as the core routes' do). The first chunk must be the canonical 44-byte PCM header from shared/wav.ts. The client cannot know the length while it records, so the header goes out with both sizes 0xFFFFFFFF ("to the end of the file", which FFmpeg reads) and the end of the take writes the real ones; a take that never ended still plays. At save the master is described from the server's own file (bytes, length from the bytes, whether its end arrived); a client's claim to a master is dropped by `CaptureInputSchema`. `capture` in recording.json also keeps each track's getSettings() (known keys only, never a device id), the quality asked for, whether the microphone went through Effects, the room tone and the clips with their take times. The master is served with the recording through the studio feature's `files` pattern; Export with sound is edit's one exporter with the picture alone, so it applies the edits and needs nothing new on the server. + +## unreleased · a phone as the take's picture {#phone-capture} + +- refers-to: features/phone/discover.ts, adb.ts, scrcpy.ts, mkv.ts, producers.ts, feed.ts, files.ts, export.ts, routes.ts, index.ts; server/studio-routes.ts (`?source=phone`); ../src-tauri/src/phone.rs, main.rs, build.rs, capabilities/main.json; ../web/src/features/phone-capture.ts, phone-capture-logic.ts, phone-send.ts, phone.ts, phone-sw.ts; ../web/styles/phone-capture.css; ../tests/phone-sources.test.ts, phone-scrcpy.test.ts, phone-feed.test.ts, phone-capture-client.test.ts +- logged: unreleased · 2026-11-29 (issue #7) + +A phone replaces the screen as the take's picture through the studio's existing native-recorder slot, so the studio itself is unchanged: the phone's tracks are registered on the studio's own track routes when the take starts (a track can only be added while it records) and filled when it stops, after the segments are joined. A pause ends a segment and a resume starts the next, so the tracks hold recorded time only, as a browser track does; a recorder that writes frames only on change (the Simulator) leaves a segment shorter than its time, so such a segment's last picture is held to its length before the join, or every later segment would play early. The picture is stream copied (native size and frame rate); the phone's sound is `host-phone`, "Phone audio", a microphone-kind track of its own. + +The iPhone on USB: the cheap path was checked first. The CoreMediaIO opt-in is per process and WebKit captures in its own processes, so the window's getUserMedia cannot be relied on to see the phone; FFmpeg's avfoundation input does not opt in either (it imports no CoreMediaIO symbol). The shell opts in at start and records with AVFoundation through objc2 (crates already in the lock), into a capture folder whose id the server makes and whose root is the data folder from the server's ready line, so the page never names a path. It was verified here that the opt-in is accepted and the device list answers; no phone was attached, so a phone take was not. + +Android: the scrcpy server 3.3.1 is downloaded at first use and accepted only with its published SHA-256; Google's adb is never shipped. The client side is written here from scrcpy's develop.md. A raw H.264 stream has no timestamps and FFmpeg cannot stream-copy one with wall-clock times (tried: "Can't write packet with unknown timestamp"), so the pictures go into Matroska written here with the device's own PTS (`mkv.ts`, proved by FFmpeg reading a real H.264 stream framed as scrcpy frames it). The sound is raw PCM, encoded to AAC by FFmpeg. When the server cannot be had, `screenrecord` on the phone is the fallback (no sound, files pulled after each segment). Show taps and SystemUI demo mode are read first and put back after the take and at the app's stop. + +AirPlay: the mirror window is found by its owner in the window list (JXA; no other window's title leaves the script) and recorded by FFmpeg's avfoundation screen input cropped to it, so it is one click and no screen picker; the window must stay where it is. A phone recording to narrate over is uploaded to `/phone/files/` and played on the stage with the take; the take keeps the part that played. The phone page's "Send a video from this phone" reuses the native apps' upload on the guest listener, so it adds no route, port or permission. Phone layouts (portrait with blurred fill, device frame, beside the camera) are made only on export. + +## unreleased · player links carry a player key, not the run's token {#player-links} + +- refers-to: server/player-link.ts `playerKey` `playerKeyMatches` `rotatePlayerLinks` `playerLinkGate`, mcp/player-links.ts `keyLinksIn` `keyLinks` `keyReply`, mcp/server.ts `buildServer` (every handler's answer), app.ts (the token-free player base and the gate), cli.ts `playerBase` `appUrl` `keyed`, features/agents/index.ts (`POST /api/agents/player-links/rotate`) +- logged: unreleased · 2026-11-29 + +Links in MCP answers used to be the player base with the run's token, so a link an agent pasted anywhere opened the whole app. The owner chose a separate key that opens one recording's player and nothing else, and that can be replaced. The key is an HMAC-SHA256 of the recording id under one secret in `/player-links/key` (0600 in a 0700 folder), made on first use. Nothing per link is stored: rotating the secret stops every link given so far, and a key cannot name another recording because the id is part of what it signs. + +The key is checked by a gate in front of the main token check that answers `/api/player/:id` (the recording) and `/api/player/:id/:file` (only the core media names the main server already allows), GET only, and nothing else; every other route still asks for the run's token, so a key cannot reach the library, Settings, uploads or `/mcp`. + +Tools keep building `#/f/`, about twenty of them across the features. Rather than change each one, the base no longer carries the token and `buildServer` wraps every registered handler: the answer's text and structured value are walked, any link on the base loses the base's query (so no token can ride along whatever base a caller passes), and a `#/f/` link gains `?player=`. Other routes on the base (`#/demo/`, `#/edit/`) keep no secret; demos need none and the other views open only in the owner's window. With no base (the relay's bridge) nothing is changed. The command line's `record`, `check`, `rerecord` and `variants` print through the same function; `formrec url` still prints the app's address with the run's token, for the person at the keyboard, and `--rotate-player-links` rotates. + +A secret file that holds no secret (cut short, edited by hand) is replaced rather than read again, and a data folder on a file system with no hard links (exFAT, FAT32, some network shares) places the first secret with an exclusive copy instead. When no secret can be kept at all, a recording's link keeps its route with no key and no token, so a tool's answer (a finished recording, say) is never lost to the link (`tests/player-link-store.test.ts`). diff --git a/src/agents/clients.ts b/src/agents/clients.ts index 8f7286f..0c7934d 100644 --- a/src/agents/clients.ts +++ b/src/agents/clients.ts @@ -8,11 +8,11 @@ * it is on this computer, else this Node (process.execPath, an absolute path, so GUI clients started outside a shell * still find it) running this build's cli.js. A codebase is optional: name one only to let code anchors read it. */ -import { spawnSync } from 'node:child_process' import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' +import { LaunchRefused, runTool, type LaunchEnv } from './win-launch.js' export const NAME = 'formrec' export const SKILLS = ['formrec-harness', 'formrec-skillset'] as const @@ -180,6 +180,22 @@ export function which(bin: string, env: NodeJS.ProcessEnv = process.env, platfor return undefined } +/** + * Replace a user-scope entry with the claude command: remove `name`, then add with `addArgs`. Bounded, because Settings' + * Connect runs this inside the server, which must never hang on a stuck claude command. Returns why the add failed. + */ +export function claudeReplace(bin: string, name: string, addArgs: string[], e: Env): string | undefined { + const le: LaunchEnv = { platform: e.platform, env: e.env, exists: e.exists, which: (b) => which(b, e.env, e.platform) } + try { + runTool(bin, ['mcp', 'remove', name, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000 }, le) + const add = runTool(bin, ['mcp', 'add', ...addArgs], { encoding: 'utf8', timeout: 15_000 }, le) + return add.status === 0 ? undefined : (add.stderr || add.stdout || add.error?.message || '').trim() + } catch (err) { + if (err instanceof LaunchRefused) return err.message + throw err + } +} + function readJson(file: string): Record { if (!existsSync(file)) return {} const raw = readFileSync(file, 'utf8') @@ -337,10 +353,8 @@ export function installClient(id: ClientId, o: InstallOptions): string[] { if (!dry) { const saved = backup(claudeJson(e)) if (saved) said.push(` backup ${saved}`) - // Bounded: Settings' Connect runs this inside the server, which must never hang on a stuck claude command. - spawnSync(bin, ['mcp', 'remove', NAME, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000 }) - const add = spawnSync(bin, ['mcp', 'add', '--scope', 'user', NAME, '--', ...line], { encoding: 'utf8', timeout: 15_000 }) - if (add.status !== 0) said.push(` claude mcp add failed: ${(add.stderr || add.stdout || '').trim()}`) + const failed = claudeReplace(bin, NAME, ['--scope', 'user', NAME, '--', ...line], e) + if (failed !== undefined) said.push(` claude mcp add failed: ${failed}`) } } if (skills) copySkills(o.root, path.join(e.home, '.claude', 'skills'), dry, said) @@ -464,9 +478,8 @@ export function installHttpClient(id: HttpClientId, o: { ep: HttpEndpoint; e: En if (!dry) { const saved = backup(claudeJson(e)) if (saved) said.push(` backup ${saved}`) - spawnSync(bin, ['mcp', 'remove', NAME, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000 }) - const add = spawnSync(bin, ['mcp', 'add', '--scope', 'user', '--transport', 'http', NAME, ep.url, '--header', `Authorization: Bearer ${ep.token}`], { encoding: 'utf8', timeout: 15_000 }) - if (add.status !== 0) said.push(` claude mcp add failed: ${(add.stderr || add.stdout || '').trim()}`) + const failed = claudeReplace(bin, NAME, ['--scope', 'user', '--transport', 'http', NAME, ep.url, '--header', `Authorization: Bearer ${ep.token}`], e) + if (failed !== undefined) said.push(` claude mcp add failed: ${failed}`) } } } else if (id === 'codex') { diff --git a/src/agents/relay-clients.ts b/src/agents/relay-clients.ts index 9a49d3e..e8a2c90 100644 --- a/src/agents/relay-clients.ts +++ b/src/agents/relay-clients.ts @@ -8,10 +8,9 @@ * Cursor https://cursor.com/docs/context/mcp mcpServers.NAME { url }, OAuth with dynamic client registration * VS Code https://code.visualstudio.com/docs/agents/reference/mcp-configuration servers.NAME { type: "http", url } */ -import { spawnSync } from 'node:child_process' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { backup, claudeJson, codexToml, cursorJson, quote, vscodeConfig, which, type Env, type HttpClientId } from './clients.js' +import { backup, claudeJson, claudeReplace, codexToml, cursorJson, quote, vscodeConfig, which, type Env, type HttpClientId } from './clients.js' export const RELAY_NAME = 'formrec-relay' const LABELS: Record = { claude: 'Claude Code', codex: 'Codex', cursor: 'Cursor', vscode: 'VS Code' } @@ -104,9 +103,8 @@ export function installRelayClient(id: HttpClientId, o: { url: string; e: Env; d if (!dry) { const saved = backup(claudeJson(e)) if (saved) said.push(` backup ${saved}`) - spawnSync(bin, ['mcp', 'remove', RELAY_NAME, '--scope', 'user'], { encoding: 'utf8', timeout: 10_000 }) - const add = spawnSync(bin, ['mcp', 'add', '--scope', 'user', '--transport', 'http', RELAY_NAME, url], { encoding: 'utf8', timeout: 15_000 }) - if (add.status !== 0) said.push(` claude mcp add failed: ${(add.stderr || add.stdout || '').trim()}`) + const failed = claudeReplace(bin, RELAY_NAME, ['--scope', 'user', '--transport', 'http', RELAY_NAME, url], e) + if (failed !== undefined) said.push(` claude mcp add failed: ${failed}`) } } } else if (id === 'codex') { diff --git a/src/agents/sync.ts b/src/agents/sync.ts index ffb86e5..f1bc541 100644 --- a/src/agents/sync.ts +++ b/src/agents/sync.ts @@ -106,14 +106,14 @@ export function toolsMarkdown(tools: ToolInfo[], demos: DemoInfo[]): string { const out = ['# FormRec MCP tools', '', HEAD, '', '## Contents', '', '- The core tools, below (the feature tools are in feature-tools.md)', '- Parameters and results, one heading per tool', '- The demos, as formrec_demos returns them', '- Command line equivalents', ''] out.push('## Tools', '') toolSections(core, out) - out.push('## Demos', '', 'Open one at `#/demo/` while FormRec runs (`formrec_demos` returns the full link with the run\'s token).', '') + out.push('## Demos', '', 'Open one at `#/demo/` while FormRec runs (`formrec_demos` returns the full link; demos need no token).', '') out.push('| Id | Title | Kind | Chapters | Point a person at it for |', '| --- | --- | --- | --- | --- |') for (const d of demos) { const chapters = (d.chapters ?? []).map((c) => c.title).join(', ') || 'none' out.push(`| \`${d.id}\` | ${oneLine(d.title)} | ${d.kind} | ${oneLine(chapters)} | ${oneLine(d.pointAt)} |`) } out.push('', '## Command line equivalents', '') - out.push('`formrec validate FILE`, `record FILE [--base-url URL] [--headed]`, `list`, `url` (the player base with the token), `serve [--codebase DIR] [--repo-url URL] [--open]`, `agents install|status|sync`. Output is the same JSON the tools return. The guide, the demos and the feature tools are MCP only.') + out.push('`formrec validate FILE`, `record FILE [--base-url URL] [--headed]`, `list`, `url` (the app\'s address with the run\'s token; `--rotate-player-links` stops every player link given so far), `serve [--codebase DIR] [--repo-url URL] [--open]`, `agents install|status|sync`. Output is the same JSON the tools return. The guide, the demos and the feature tools are MCP only.') return out.join('\n') + '\n' } diff --git a/src/agents/win-launch.ts b/src/agents/win-launch.ts new file mode 100644 index 0000000..68490b9 --- /dev/null +++ b/src/agents/win-launch.ts @@ -0,0 +1,98 @@ +/** + * How an agent client's command (the `claude` CLI and the like) is started. On Windows such a command is often an npm + * `.cmd` shim, which Node cannot start without cmd.exe, and cmd.exe reads its line again (the shim passes `%*` on), so + * quoting does not keep an argument literal. The shim is therefore resolved to the program it wraps (a Node script or + * an .exe) and that runs with a plain argument list. Only when a shim cannot be resolved does cmd.exe run it, and then + * every argument must be free of the characters cmd.exe treats specially; anything else is refused. + */ +import { spawnSync, type SpawnSyncOptionsWithStringEncoding, type SpawnSyncReturns } from 'node:child_process' +import { existsSync, readFileSync } from 'node:fs' +import path from 'node:path' + +/** The launch was refused: the command would go through cmd.exe with an argument it cannot keep literal. */ +export class LaunchRefused extends Error {} + +export interface LaunchEnv { + platform: NodeJS.Platform + env: NodeJS.ProcessEnv + exists?: (file: string) => boolean + /** A shim's text, or undefined when it cannot be read. */ + read?: (file: string) => string | undefined + /** A command on the PATH. */ + which?: (bin: string) => string | undefined +} + +export interface Launch { + command: string + args: string[] + /** True only for cmd.exe, whose line is passed as written. */ + verbatim: boolean +} + +/** What cmd.exe reads as syntax even inside quotes, plus the quote itself and control characters. */ +const CMD_SPECIAL = /[&|<>^()!%"\x00-\x1f\x7f]/ +/** The same set for the program's own path, where parentheses are allowed (Program Files (x86)) inside its quotes. */ +const CMD_SPECIAL_PATH = /[&|<>^!%"\x00-\x1f\x7f]/ +const SHIM_EXT = /\.(cmd|bat)$/i +const SCRIPT_EXT = /\.(c|m)?js$/i +const win = path.win32 + +function readText(file: string): string | undefined { + try { + return readFileSync(file, 'utf8') + } catch { + return undefined + } +} + +/** The program an npm-style shim runs: the last quoted path under the shim's folder on the line that passes `%*`. */ +export function shimTarget(text: string, shimDir: string): string | undefined { + const line = text.split(/\r?\n/).reverse().find((l) => l.includes('%*')) + if (!line) return undefined + const quoted = [...line.matchAll(/"([^"]*)"/g)].map((m) => m[1] ?? '').filter((q) => /%~?dp0%?/i.test(q) && !/%_prog%/i.test(q)) + const last = quoted.at(-1) + if (!last) return undefined + const target = win.normalize(last.replace(/%~dp0|%dp0%/gi, `${shimDir}\\`)) + const rel = win.relative(shimDir, target) + if (!rel || rel.startsWith('..') || win.isAbsolute(rel)) return undefined + return target +} + +function viaShim(bin: string, args: string[], le: LaunchEnv): Launch | undefined { + const exists = le.exists ?? existsSync + const dir = win.dirname(bin) + const text = (le.read ?? readText)(bin) + const target = text === undefined ? undefined : shimTarget(text, dir) + if (!target || !exists(target)) return undefined + if (/\.exe$/i.test(target)) return { command: target, args, verbatim: false } + if (!SCRIPT_EXT.test(target)) return undefined + const local = win.join(dir, 'node.exe') + const node = exists(local) ? local : le.which?.('node') + return node ? { command: node, args: [target, ...args], verbatim: false } : undefined +} + +/** The cmd.exe line for a shim that could not be resolved, refusing any argument cmd.exe would read as syntax. */ +export function cmdLaunch(bin: string, args: string[], env: NodeJS.ProcessEnv): Launch { + if (CMD_SPECIAL_PATH.test(bin)) throw new LaunchRefused(`${bin} cannot be started through cmd.exe: its path holds a character cmd.exe treats specially`) + args.forEach((arg, i) => { + if (CMD_SPECIAL.test(arg)) { + throw new LaunchRefused( + `argument ${i + 1} for ${win.basename(bin)} holds a character cmd.exe treats specially (& | < > ^ ( ) ! % " or a control character), so it is not passed; pass long text through stdin or a file if the tool supports it`, + ) + } + }) + const line = [bin, ...args].map((w) => `"${w}"`).join(' ') + return { command: env.ComSpec ?? env.COMSPEC ?? 'cmd.exe', args: ['/d', '/s', '/c', `"${line}"`], verbatim: true } +} + +/** The program and argument list that start `bin` with `args` on this platform. Throws LaunchRefused. */ +export function launchArgv(bin: string, args: string[], le: LaunchEnv): Launch { + if (le.platform !== 'win32' || !SHIM_EXT.test(bin)) return { command: bin, args, verbatim: false } + return viaShim(bin, args, le) ?? cmdLaunch(bin, args, le.env) +} + +/** spawnSync through launchArgv. Throws LaunchRefused. */ +export function runTool(bin: string, args: string[], options: SpawnSyncOptionsWithStringEncoding, le: LaunchEnv): SpawnSyncReturns { + const launch = launchArgv(bin, args, le) + return spawnSync(launch.command, launch.args, { ...options, windowsVerbatimArguments: launch.verbatim }) +} diff --git a/src/app.ts b/src/app.ts index 3c963c3..f9d4b56 100644 --- a/src/app.ts +++ b/src/app.ts @@ -14,6 +14,7 @@ import { mailGate } from './features/mail/index.js' import { createMcpHttp } from './mcp/http.js' import { buildServer } from './mcp/server.js' import { mcpToken } from './mcp/token.js' +import { playerLinkGate } from './server/player-link.js' import { version } from './version.js' export interface AppOptions { @@ -82,7 +83,8 @@ export function createApp(opts: AppOptions): App { buildServer( { library, - playerBase: async () => `${origin()[0] ?? 'http://127.0.0.1:8770'}/?token=${opts.token}`, + // No run token: buildServer gives each recording's link its own player key (mcp/player-links.ts). + playerBase: async () => `${origin()[0] ?? 'http://127.0.0.1:8770'}/`, allowedRoots: opts.codebase ? [opts.codebase.root] : undefined, }, version(), @@ -101,7 +103,7 @@ export function createApp(opts: AppOptions): App { ...FEATURES.flatMap((f) => (f.routes ? [f.routes(ctx)] : [])), ], mediaFile: featureFile, - gates: [extensionGate(ctx), mailGate()], + gates: [playerLinkGate(library), extensionGate(ctx), mailGate()], }) // Features start once the server exists; one that fails to start is reported and left out, never fatal. const started = FEATURES.filter((f) => f.start).map((f) => diff --git a/src/cli.ts b/src/cli.ts index 1b00b62..ebef735 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -13,6 +13,8 @@ import { startServe, type Serving } from './serve.js' import { serveMcp } from './mcp/server.js' import { DEFAULT_MCP_PORT, serveMcpHttp } from './mcp/http.js' import { rotateMcpToken } from './mcp/token.js' +import { keyLinks } from './mcp/player-links.js' +import { rotatePlayerLinks } from './server/player-link.js' import { listTool, recordTool, validateTool } from './mcp/tools.js' import { version } from './version.js' import { allowedRoots } from './anchors/codebase.js' @@ -46,7 +48,9 @@ or have an agent record a walkthrough of any website over MCP. formrec list saved recordings formrec url the player's address with its token (the running server's, the desktop app's first; else FORMREC_PORT) - formrec mcp [--codebase DIR] MCP server on stdio, for Claude Code, Codex, Cursor... + formrec url --rotate-player-links make every player link given so far stop working (links + in tool answers open one recording's player only) + formrec mcp [--codebase DIR] MCP server on stdio, for Claude Code, Codex, Cursor... formrec mcp --http [--port 8775] [--host 127.0.0.1] [--json-response] the same tools over Streamable HTTP at /mcp, with a bearer token (/mcp/token); --rotate-token makes a new one @@ -73,13 +77,25 @@ function print(value: unknown): void { /** * The player's address for links: the running server this data folder published (the desktop app's first, checked - * live with the token; see store/server-file.ts), else FORMREC_PORT. Always 127.0.0.1. + * live with the token; see store/server-file.ts), else FORMREC_PORT. Always 127.0.0.1. It carries no run token: a + * recording's link gets its player key from `keyed` (MCP answers get theirs in buildServer). */ async function playerBase(): Promise { const config = loadConfig() const token = await loadToken(config.dataDir) const port = await linkPort(config.dataDir, token, config.port) - return `http://${config.host}:${port}/?token=${token}` + return `http://${config.host}:${port}/` +} + +/** The app's own address with the run's token, for `formrec url`: the person running the command opens the whole app. */ +async function appUrl(): Promise { + const config = loadConfig() + return `${await playerBase()}?token=${await loadToken(config.dataDir)}` +} + +/** A tool's JSON with its player links keyed, as an MCP answer's are (mcp/player-links.ts). */ +async function keyed(value: T): Promise { + return keyLinks(value, await playerBase().catch(() => undefined), loadConfig().dataDir) } async function serve(args: Args): Promise { @@ -193,11 +209,11 @@ async function main(argv: readonly string[]): Promise { if (!file) throw new Error('formrec record needs a walkthrough file') // The person named this file on the command line, so its folder may be read even when formrec runs from the // home folder (where no codebase is allowed by default): a walkthrough of a website needs no codebase. - return print(await recordTool({ library: library(), playerBase: await playerBase(), allowedRoots: roots.length > 0 ? roots : [path.dirname(path.resolve(file))] }, { file, headed: args.flags.headed === true, baseUrl: stringFlag(args, 'base-url'), ...(args.flags['no-redact'] === true ? { autoRedact: false } : {}) })) + return print(await keyed(await recordTool({ library: library(), playerBase: await playerBase(), allowedRoots: roots.length > 0 ? roots : [path.dirname(path.resolve(file))] }, { file, headed: args.flags.headed === true, baseUrl: stringFlag(args, 'base-url'), ...(args.flags['no-redact'] === true ? { autoRedact: false } : {}) }))) case 'check': { if (!file) throw new Error('formrec check needs a walkthrough file') const { checkTool } = await import('./wtdiff/tools.js') - const report = await checkTool({ library: library(), playerBase: await playerBase().catch(() => undefined), allowedRoots: roots.length > 0 ? roots : [path.dirname(path.resolve(file))] }, { file, recording: stringFlag(args, 'recording'), baseUrl: stringFlag(args, 'base-url') }) + const report = await keyed(await checkTool({ library: library(), playerBase: await playerBase().catch(() => undefined), allowedRoots: roots.length > 0 ? roots : [path.dirname(path.resolve(file))] }, { file, recording: stringFlag(args, 'recording'), baseUrl: stringFlag(args, 'base-url') })) const { text, ...json } = report print(args.flags.json === true ? json : text) process.exitCode = report.status === 'fresh' ? 0 : 1 @@ -208,7 +224,7 @@ async function main(argv: readonly string[]): Promise { const { rerecordTool } = await import('./wtdiff/tools.js') const named = stringFlag(args, 'steps') const done = await rerecordTool({ library: library(), playerBase: await playerBase().catch(() => undefined), allowedRoots: roots.length > 0 ? roots : undefined }, { recording: file, steps: args.flags.all === true ? 'all' : named ? named.split(',').map((s) => s.trim()).filter(Boolean) : undefined }) - return print({ id: done.recording.id, version: done.version, rerecorded: done.steps, kept: done.kept, durationMs: done.recording.durationMs, chapters: done.recording.chapters.length, player: done.player }) + return print(await keyed({ id: done.recording.id, version: done.version, rerecorded: done.steps, kept: done.kept, durationMs: done.recording.durationMs, chapters: done.recording.chapters.length, player: done.player })) } case 'variants': { const recording = stringFlag(args, 'recording') @@ -223,7 +239,7 @@ async function main(argv: readonly string[]): Promise { { file: file || undefined, recording, valuesFile, headed: args.flags.headed === true }, { onProgress: (p) => { if (p.state === 'start') process.stderr.write(`formrec: variant ${p.index + 1} of ${p.total}: ${p.title}\n`) } }, ) - print(done) + print(await keyed(done)) process.exitCode = done.cancelled || done.results.some((r) => !r.ok) ? 1 : 0 return } @@ -240,7 +256,11 @@ async function main(argv: readonly string[]): Promise { case 'list': return print(await listTool({ library: library() })) case 'url': - return print(await playerBase()) + if (args.flags['rotate-player-links'] === true) { + await rotatePlayerLinks(loadConfig().dataDir) + return print('Player links replaced: every player link given so far stops working.') + } + return print(await appUrl()) case 'mcp': if (args.flags['rotate-token'] === true) return print(await rotateMcpToken(loadConfig().dataDir)) if (args.flags.http === true) return serveHttp(args, roots) diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index 02def4c..e25a336 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -10,6 +10,8 @@ * POST /api/agents/install { client, transport?: "stdio" | "http" | "relay" } -> { said: [lines], clients, relay } * writes that client's config, with a backup ("relay": the relay's /mcp as formrec-relay) * POST /api/agents/mcp-token/rotate -> { http, clients } a new MCP token; the old one stops working at once + * POST /api/agents/player-links/rotate -> { rotated: true } every player link given so far stops working at once + * (server/player-link.ts); Settings and the window's command call it on demand * * The logic is src/agents/clients.ts, shared with `formrec agents` (src/cli.ts). */ @@ -20,6 +22,7 @@ import type { Feature, FeatureContext } from '../types.js' import { CLIENT_IDS, clientStatus, currentEnv, findRoot, HTTP_CLIENT_IDS, installClient, installHttpClient, isHttpClient, serverEntry, type HttpEndpoint } from '../../agents/clients.js' import { installRelayClient, relaySnippet, relayState } from '../../agents/relay-clients.js' import { mcpToken, rotateMcpToken } from '../../mcp/token.js' +import { rotatePlayerLinks } from '../../server/player-link.js' import { readConnection } from '../relay/state.js' import { readJsonBody } from '../../server/files.js' import { version } from '../../version.js' @@ -91,6 +94,11 @@ export const feature: Feature = { sendJson(res, 200, { http, clients: state(http).clients }) return true } + if (parts.length === 4 && parts[2] === 'player-links' && parts[3] === 'rotate' && method === 'POST') { + await rotatePlayerLinks(ctx.dataDir) + sendJson(res, 200, { rotated: true }) + return true + } if (parts.length === 3 && parts[2] === 'install' && method === 'POST') { const parsed = InstallBody.safeParse(await readJsonBody(req, 4096).catch(() => undefined)) if (!parsed.success) { diff --git a/src/features/library/sync-folder.ts b/src/features/library/sync-folder.ts index f605271..170025d 100644 --- a/src/features/library/sync-folder.ts +++ b/src/features/library/sync-folder.ts @@ -17,8 +17,8 @@ * hash before they are used, so a file Dropbox is still writing is picked up on the next pass. */ import { createHash, randomBytes } from 'node:crypto' -import { createReadStream } from 'node:fs' -import { cp, lstat, mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises' +import { constants, createReadStream } from 'node:fs' +import { copyFile, link, lstat, mkdir, mkdtemp, open, readdir, readFile, rename, rm, stat, unlink, type FileHandle } from 'node:fs/promises' import { hostname } from 'node:os' import path from 'node:path' import { z } from 'zod' @@ -31,13 +31,25 @@ import { checkDirectory, LibraryError, trash, type LibraryStore } from './store. const SYNC_DIR = '.formrec-sync' /** What stays on the computer that made it: shares, relay state, comments, per-video view settings, the link record. */ -const LOCAL_ONLY = /^(share|relay|teamsync|engage|workspace)\.json$|^relay-manifest\.json$|^share-events\.jsonl$|\.(part|tmp|chunk)$/ +const LOCAL_ONLY = /^(share|relay|teamsync|engage|workspace)\.json$|^relay-manifest\.json$|^share-events\.jsonl$|\.(part|tmp|chunk)$/i +/** A synced file is one plain name inside its recording's folder: no separators, no leading dot, nothing a path would read as a folder. */ +const FILE_NAME = /^[^.<>:"/\\|?*\x00-\x1f\x7f][^<>:"/\\|?*\x00-\x1f\x7f]{0,119}$/ +/** Names Windows reads as something other than the file written: a trailing dot or space, or a device name. */ +const WINDOWS_ALIAS = /[. ]$|^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i +/** A Windows 8.3 short name (SHARE~1.JSO): it can stand for a longer name, so it is never synced. */ +const SHORT_NAME = /~\d/ +/** Synced names are printable ASCII, so no file system maps one onto another name by Unicode case or normalization. */ +const PRINTABLE_ASCII = /^[\x20-\x7e]+$/ +const syncName = (name: string): boolean => PRINTABLE_ASCII.test(name) && FILE_NAME.test(name) && !WINDOWS_ALIAS.test(name) && !SHORT_NAME.test(name) && !LOCAL_ONLY.test(name) +/** Where a computer keeps its files of a recording in the share: the recording's own folder, or its `.by-` folder. */ +const FILE_DIR = /^(\.|\.by-d-[0-9a-f]{8})$/ +const dirOf = (entry: { dir: string }, device: string): string | undefined => (entry.dir === '.' || entry.dir === `.by-${device}` ? entry.dir : undefined) const EntrySchema = z.object({ vector: VectorSchema, hash: z.string(), - files: z.record(z.string().max(120), z.string()), - dir: z.string().max(80), + files: z.record(z.string().refine(syncName), z.string()), + dir: z.string().regex(FILE_DIR), updatedAt: z.string(), title: z.string().max(300), }) @@ -109,7 +121,7 @@ async function shaOf(file: string): Promise { async function syncFiles(dir: string): Promise { const out: string[] = [] for (const name of await readdir(dir).catch(() => [] as string[])) { - if (LOCAL_ONLY.test(name) || name.startsWith('.')) continue + if (!syncName(name)) continue if ((await lstat(path.join(dir, name)).catch(() => undefined))?.isFile()) out.push(name) } return out.sort() @@ -131,24 +143,179 @@ async function hashFolder(dir: string, cache: z.infer): const contentHash = (files: Record): string => createHash('sha256').update(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)).map(([n, s]) => `${n}\0${s}\n`).join('')).digest('hex') -/** Copy files from `from` into `to`, skipping any already there with the same hash; each lands by rename, so a reader never sees half a file. */ -async function copyVerified(from: string, to: string, files: Record, have: Record = {}): Promise { - await mkdir(to, { recursive: true, mode: 0o700 }) - for (const [name, sha] of Object.entries(files)) { - if (have[name] === sha) continue - const tmp = path.join(to, `.${name}.tmp`) +/** Two names a case-folding file system may treat as one entry (compared in NFC, upper and lower case). */ +function sameFolded(a: string, b: string): boolean { + const x = a.normalize('NFC') + const y = b.normalize('NFC') + return x.toUpperCase() === y.toUpperCase() || x.toLowerCase() === y.toLowerCase() +} + +/** Link failures that mean the file system cannot hard-link here, not that the name is taken. */ +const NO_LINK = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'EMLINK', 'ENOSYS']) +const NO_FOLLOW = constants.O_NOFOLLOW ?? 0 + +/** A verified file in a folder only this computer writes: where it is, which file it is, and what it holds. */ +interface Staged { path: string; dev: number; ino: number; sha: string } + +/** SHA-256 of what a file handle holds, read from the start. */ +async function shaOfHandle(handle: FileHandle): Promise { + const h = createHash('sha256') + const buf = Buffer.alloc(1 << 16) + for (let at = 0; ;) { + const { bytesRead } = await handle.read(buf, 0, buf.length, at) + if (bytesRead === 0) return h.digest('hex') + h.update(buf.subarray(0, bytesRead)) + at += bytesRead + } +} + +/** SHA-256 of a regular file, opened without following a link. */ +async function shaNoFollow(file: string): Promise { + const handle = await open(file, constants.O_RDONLY | NO_FOLLOW) + try { + return (await handle.stat()).isFile() ? await shaOfHandle(handle) : '' + } finally { + await handle.close() + } +} + +/** True while the staged path still holds the regular file that was written and hashed. */ +async function stillStaged(staged: Staged): Promise { + const now = await lstat(staged.path).catch(() => undefined) + return now !== undefined && now.isFile() && now.dev === staged.dev && now.ino === staged.ino +} + +/** + * stillStaged, and the bytes at the staged path still hash to what was verified. The device and inode alone do not + * prove it is the same file: Linux file systems hand a freed inode number to the next file created, so a file deleted + * and written again under the same name can carry the identity of the one staged. + */ +async function stillVerified(staged: Staged): Promise { + if (!(await stillStaged(staged))) return false + const handle = await open(staged.path, constants.O_RDONLY | NO_FOLLOW).catch(() => undefined) + if (!handle) return false + try { + const now = await handle.stat() + return now.isFile() && now.dev === staged.dev && now.ino === staged.ino && (await shaOfHandle(handle)) === staged.sha + } finally { + await handle.close() + } +} + +/** A file already in a private staging folder, taken as staged when it is a regular file. */ +async function stagedAt(file: string, sha: string): Promise { + const info = await lstat(file).catch(() => undefined) + return info?.isFile() ? { path: file, dev: info.dev, ino: info.ino, sha } : undefined +} + +/** + * Copy one file into a private staging folder under a new name and confirm its hash. The file is created fresh (never + * opened through an entry already there) and hashed through the handle that wrote it. + */ +async function stageFile(source: string, tmp: string, sha: string): Promise { + const handle = await open(tmp, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | NO_FOLLOW, 0o600) + try { + const src = await open(source, constants.O_RDONLY | NO_FOLLOW) try { - await cp(path.join(from, name), tmp) - if ((await shaOf(tmp)) !== sha) throw new Error(`${name} is not complete yet`) - await rename(tmp, path.join(to, name)) - } catch { - await rm(tmp, { force: true }) - return false + for await (const part of src.createReadStream({ autoClose: false })) await handle.write(part as Buffer) + } finally { + await src.close() } + if ((await shaOfHandle(handle)) !== sha) return undefined + const mine = await handle.stat() + const staged = { path: tmp, dev: mine.dev, ino: mine.ino, sha } + return (await stillStaged(staged)) ? staged : undefined + } finally { + await handle.close() + } +} + +/** Whether a name can be placed in a folder: 'exact' when a file is there under exactly that name, 'absent' when nothing is, undefined when another entry folds to it or a folder holds it. */ +async function nameState(dir: string, name: string): Promise<'exact' | 'absent' | undefined> { + const entries = await readdir(dir) + if (entries.some((entry) => entry !== name && sameFolded(entry, name))) return undefined + if (!entries.includes(name)) return 'absent' + return (await lstat(path.join(dir, name))).isDirectory() ? undefined : 'exact' +} + +/** Move a staged file into a folder on the same volume: one rename over an earlier version, a hard link for a new name. */ +async function moveStaged(staged: Staged, to: string, state: 'exact' | 'absent'): Promise { + if (state === 'exact') { + await rename(staged.path, to) + return true } + try { + await link(staged.path, to) + } catch (error) { + const code = (error as NodeJS.ErrnoException).code ?? '' + if (code === 'EEXIST' || !NO_LINK.has(code) || !(await stillVerified(staged))) return false + await rename(staged.path, to) + return true + } + await unlink(staged.path) return true } +/** Copy a staged file into a folder on another volume, never over an entry that appeared meanwhile, and check what landed. */ +async function copyStaged(staged: Staged, to: string, state: 'exact' | 'absent'): Promise { + if (state === 'exact') await unlink(to) + try { + await copyFile(staged.path, to, constants.COPYFILE_EXCL) + } catch { + return false + } + if ((await shaNoFollow(to).catch(() => '')) === staged.sha) return true + await rm(to, { force: true }) + return false +} + +/** + * Put a staged file in place under exactly the name given, never over another entry. The target folder is read first + * and an entry that differs from the name but folds to it refuses the move, and the staged file is checked to be the + * one verified right before it moves. Returns false when the file was not placed. + */ +async function placeExact(staged: Staged, to: string): Promise { + const dir = path.dirname(to) + const state = await nameState(dir, path.basename(to)) + if (!state || !(await stillVerified(staged))) return false + const sameVolume = (await stat(path.dirname(staged.path))).dev === (await stat(dir)).dev + if (!(await (sameVolume ? moveStaged(staged, to, state) : copyStaged(staged, to, state)))) return false + return (await readdir(dir)).includes(path.basename(to)) +} + +/** + * Copy files from `from` into `to`, skipping any already there with the same hash. Each is verified in a private + * staging folder under `scratch` (FormRec's own data folder, which the share cannot write) and then placed whole + * (placeExact), so a reader never sees half a file. + */ +async function copyVerified(scratch: string, from: string, to: string, files: Record, have: Record = {}): Promise { + await mkdir(to, { recursive: true, mode: 0o700 }) + await mkdir(scratch, { recursive: true, mode: 0o700 }) + const work = await mkdtemp(path.join(scratch, 'stage-')) + try { + for (const [name, sha] of Object.entries(files)) { + if (!syncName(name)) return false + if (have[name] === sha) continue + if (!(await lstat(path.join(from, name)).catch(() => undefined))?.isFile()) return false + const tmp = path.join(work, `.${name}.${randomBytes(6).toString('hex')}.tmp`) + const staged = await stageFile(path.join(from, name), tmp, sha).catch(() => undefined) + if (!staged || !(await placeExact(staged, path.join(to, name)).catch(() => false))) return false + } + return true + } finally { + await rm(work, { recursive: true, force: true }) + } +} + +/** This computer's private working folder for the sync, inside FormRec's data folder. */ +const scratchOf = (store: LibraryStore): string => path.join(store.dataDir, 'teamsync') + +/** Move a file from a private staging folder into a recording folder, under exactly its name. */ +async function moveFromStaging(staging: string, into: string, name: string, sha: string): Promise { + const staged = await stagedAt(path.join(staging, name), sha) + return staged !== undefined && (await placeExact(staged, path.join(into, name)).catch(() => false)) +} + // State ------------------------------------------------------------------------------------------------------------ const stateName = (spaceId: string): string => `folder-${spaceId}` @@ -178,6 +345,17 @@ async function writeDeviceFile(root: string, file: DeviceFile): Promise { interface Remote { device: string; name: string; entry: Entry; dir: string } +/** A folder inside the share reached without passing through a link: undefined when a part of it is a link or a file. */ +async function plainFolder(root: string, parts: string[]): Promise { + let at = root + for (const part of parts) { + at = path.join(at, part) + const info = await lstat(at).catch(() => undefined) + if (info && !info.isDirectory()) return undefined + } + return at +} + async function readOutside(dir: string, name: string): Promise { if (!REC_ID.test(name)) return undefined if (!(await lstat(path.join(dir, name)).catch(() => undefined))?.isDirectory()) return undefined @@ -195,9 +373,11 @@ async function remotesOf(root: string, devices: DeviceFile[], ownHeads: Iterable const add = (id: string, r: Remote): void => { out.set(id, [...(out.get(id) ?? []), r]) } const headOwned = new Set(ownHeads) for (const d of devices) for (const [id, entry] of Object.entries(d.recordings)) { - if (!REC_ID.test(id)) continue - if (entry.dir === '.') headOwned.add(id) - add(id, { device: d.device, name: d.name, entry, dir: path.join(root, id, entry.dir) }) + const dir = dirOf(entry, d.device) + if (!REC_ID.test(id) || dir === undefined) continue + if (dir === '.') headOwned.add(id) + const from = await plainFolder(root, dir === '.' ? [id] : [id, dir]) + if (from) add(id, { device: d.device, name: d.name, entry, dir: from }) } for (const name of await readdir(root).catch(() => [] as string[])) { if (name.startsWith('.') || headOwned.has(name)) continue @@ -213,9 +393,9 @@ async function remotesOf(root: string, devices: DeviceFile[], ownHeads: Iterable // One pass --------------------------------------------------------------------------------------------------------- /** Bring a remote version's files into a recording folder, removing syncable files it does not have. */ -async function applyRemote(from: Remote, folder: string): Promise { +async function applyRemote(scratch: string, from: Remote, folder: string): Promise { const here = (await hashFolder(folder, {})).files - if (!(await copyVerified(from.dir, folder, from.entry.files, here))) return false + if (!(await copyVerified(scratch, from.dir, folder, from.entry.files, here))) return false for (const name of Object.keys(here)) if (!(name in from.entry.files)) await rm(path.join(folder, name), { force: true }) return true } @@ -233,11 +413,11 @@ async function writeRecording(store: LibraryStore, rec: Recording): Promise { const staging = path.join(store.dataDir, 'teamsync', `incoming-${randomBytes(4).toString('hex')}`) try { - if (!(await copyVerified(from.dir, staging, from.entry.files))) return undefined + if (!(await copyVerified(scratchOf(store), from.dir, staging, from.entry.files))) return undefined const rec = RecordingSchema.parse(JSON.parse(await readFile(path.join(staging, 'recording.json'), 'utf8'))) const copyId = newId(rec.title, now) const folder = await store.library.prepare(copyId) - for (const name of Object.keys(from.entry.files)) await rename(path.join(staging, name), path.join(folder, name)) + for (const [name, sha] of Object.entries(from.entry.files)) if (!(await moveFromStaging(staging, folder, name, sha))) return undefined const next: Recording = { ...rec, id: copyId, title: `${rec.title} (conflicted copy from ${from.name})` } delete next.owner await writeRecording(store, next) @@ -274,7 +454,7 @@ export async function syncFolder(store: LibraryStore, space: Space): Promise DeviceFileSchema.parse(JSON.parse(t))).catch(() => undefined)) ?? { formrecSync: 1, device: me.id, name: me.name, updatedAt: now.toISOString(), recordings: {} } - const ownHeads = Object.entries(mineFile.recordings).filter(([, e]) => e.dir === '.').map(([id]) => id) + const ownHeads = Object.entries(mineFile.recordings).filter(([, e]) => dirOf(e, me.id) === '.').map(([id]) => id) const remotes = await remotesOf(root, await readDevices(root, me.id), ownHeads) const org = await store.org() const result: FolderSync = { pushed: [], pulled: [], conflicts: [] } @@ -305,10 +485,12 @@ export async function syncFolder(store: LibraryStore, space: Space): Promise o.dir === path.join(root, id)) || (await readOutside(root, id)) ? `.by-${me.id}` : '.') - const target = dir === '.' ? path.join(root, id) : path.join(root, id, dir) + const mine = mineFile.recordings[id] + const dir = (mine && dirOf(mine, me.id)) ?? (others.some((o) => o.dir === path.join(root, id)) || (await readOutside(root, id)) ? `.by-${me.id}` : '.') + const target = await plainFolder(root, dir === '.' ? [id] : [id, dir]) + if (!target) continue const have = (await hashFolder(target, {})).files - if (!(await copyVerified(folder, target, files, have))) continue + if (!(await copyVerified(scratchOf(store), folder, target, files, have))) continue for (const name of Object.keys(have)) if (!(name in files)) await rm(path.join(target, name), { force: true }) const title = (await store.library.get(id).catch(() => undefined))?.title ?? id mineFile.recordings[id] = { vector, hash, files, dir, updatedAt: now.toISOString(), title } @@ -325,11 +507,13 @@ export async function syncFolder(store: LibraryStore, space: Space): Promise ['-s', serial, ...args] + +export const readShowTouches = (serial: string): string[] => onDevice(serial, 'shell', 'settings', 'get', 'system', 'show_touches') +export const writeShowTouches = (serial: string, value: string): string[] => + value === 'null' ? onDevice(serial, 'shell', 'settings', 'delete', 'system', 'show_touches') : onDevice(serial, 'shell', 'settings', 'put', 'system', 'show_touches', value) +export const readDemoAllowed = (serial: string): string[] => onDevice(serial, 'shell', 'settings', 'get', 'global', 'sysui_demo_allowed') +export const readSdk = (serial: string): string[] => onDevice(serial, 'shell', 'getprop', 'ro.build.version.sdk') + +const demo = (serial: string, command: string, extras: [string, string][] = []): string[] => + onDevice(serial, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', command, ...extras.flatMap(([k, v]) => ['-e', k, v])) + +/** Demo mode on: the clock at 9:41, the battery full and not charging, full Wi-Fi and mobile bars, no notification icons. */ +export function demoModeOn(serial: string): string[][] { + return [ + onDevice(serial, 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', '1'), + demo(serial, 'enter'), + demo(serial, 'clock', [['hhmm', '0941']]), + demo(serial, 'battery', [['level', '100'], ['plugged', 'false']]), + demo(serial, 'network', [['wifi', 'show'], ['level', '4']]), + demo(serial, 'network', [['mobile', 'show'], ['datatype', 'none'], ['level', '4']]), + demo(serial, 'notifications', [['visible', 'false']]), + ] +} + +/** Demo mode off, and the setting that allows it put back as it was. */ +export function demoModeOff(serial: string, allowedBefore: string): string[][] { + const put = allowedBefore === 'null' + ? onDevice(serial, 'shell', 'settings', 'delete', 'global', 'sysui_demo_allowed') + : onDevice(serial, 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', allowedBefore) + return [demo(serial, 'exit'), put] +} + +/** "1\n" -> "1"; anything that is not a short token reads as unset. */ +export function settingValue(out: string): string { + const v = out.trim() + return /^[\w.-]{1,16}$/.test(v) ? v : 'null' +} + +export type Runner = (cmd: string, args: string[]) => Promise + +/** Applies and restores the helpers for the takes running now; one entry per device. */ +export class AdbHelpers { + private readonly held = new Map() + + constructor(private readonly adb: () => Promise, private readonly run: Runner = (c, a) => runFor(c, a, 10_000)) {} + + async apply(serial: string, want: { showTaps: boolean; demoMode: boolean }): Promise { + const adb = await this.adb() + if (!adb) return ['adb is not installed'] + const problems: string[] = [] + const state: AdbSettingsState = { ...(this.held.get(serial) ?? { serial }) } + if (want.showTaps && state.showTouches === undefined) { + try { + state.showTouches = settingValue(await this.run(adb, readShowTouches(serial))) + await this.run(adb, writeShowTouches(serial, '1')) + } catch (error) { + delete state.showTouches + problems.push(`show taps: ${(error as Error).message}`) + } + } + if (want.demoMode && state.demoAllowed === undefined) { + try { + state.demoAllowed = settingValue(await this.run(adb, readDemoAllowed(serial))) + for (const args of demoModeOn(serial)) await this.run(adb, args) + } catch (error) { + problems.push(`clean status bar: ${(error as Error).message}`) + } + } + this.held.set(serial, state) + return problems + } + + async restore(serial: string): Promise { + const state = this.held.get(serial) + if (!state) return + this.held.delete(serial) + const adb = await this.adb() + if (!adb) return + if (state.showTouches !== undefined) await this.run(adb, writeShowTouches(serial, state.showTouches)).catch(() => undefined) + if (state.demoAllowed !== undefined) for (const args of demoModeOff(serial, state.demoAllowed)) await this.run(adb, args).catch(() => undefined) + } + + async restoreAll(): Promise { + for (const serial of [...this.held.keys()]) await this.restore(serial) + } + + holding(): string[] { + return [...this.held.keys()] + } +} diff --git a/src/features/phone/discover.ts b/src/features/phone/discover.ts new file mode 100644 index 0000000..4664daf --- /dev/null +++ b/src/features/phone/discover.ts @@ -0,0 +1,229 @@ +/** + * Phone capture sources, found on this computer (issue #7): Android phones and emulators that adb lists, iOS + * Simulators that are booted, and the window macOS's AirPlay receiver mirrors a phone into. An iPhone or iPad on USB + * is found by the desktop app's shell (src-tauri/src/phone.rs), not here: only a process that opts in to CoreMediaIO's + * screen capture devices sees it. + * + * The parsers are pure and unit tested (tests/phone-sources.test.ts); the finders run a program each, bounded by a + * timeout, and answer an empty list when the program is missing. Google's adb is never bundled (the Android SDK + * licence): it is looked for on the PATH, in ANDROID_HOME or ANDROID_SDK_ROOT, and in the SDK's usual folders. + */ +import { execFile } from 'node:child_process' +import { access, constants } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { z } from 'zod' + +export type AndroidLink = 'usb' | 'wifi' | 'emulator' +export type AndroidState = 'device' | 'unauthorized' | 'offline' | 'no permissions' | 'other' + +export interface AndroidDevice { + serial: string + state: AndroidState + link: AndroidLink + /** The model adb reports (underscores as spaces), else the serial. */ + name: string + model?: string +} + +export interface Simulator { + udid: string + name: string + /** For example "iOS 26.4". */ + runtime: string +} + +export interface AirPlayWindow { + id: number + owner: string + /** The window's rectangle in points, global coordinates with the origin at the main display's top left. */ + bounds: { x: number; y: number; width: number; height: number } + /** Where it sits: the display (as FFmpeg's avfoundation names it) and the crop in pixels on that display. */ + screen: number + crop: { x: number; y: number; width: number; height: number } +} + +/** `adb devices -l`: one line per device after the header, the serial, its state, then key:value details. */ +export function parseAdbDevices(text: string): AndroidDevice[] { + const out: AndroidDevice[] = [] + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim() + if (!line || line.startsWith('List of devices') || line.startsWith('*')) continue + const m = /^(\S+)\s+(device|unauthorized|offline|no permissions|bootloader|recovery|sideload|authorizing|connecting|host)\b(.*)$/.exec(line) + if (!m) continue + const serial = m[1]! + const details = Object.fromEntries([...m[3]!.matchAll(/(\w+):(\S+)/g)].map((d) => [d[1]!, d[2]!])) + const model = details['model']?.replace(/_/g, ' ') + const state: AndroidState = (['device', 'unauthorized', 'offline', 'no permissions'] as const).find((s) => s === m[2]) ?? 'other' + out.push({ serial, state, link: linkOf(serial), name: model ?? serial, ...(model ? { model } : {}) }) + } + return out +} + +export function linkOf(serial: string): AndroidLink { + if (/^emulator-\d+$/.test(serial)) return 'emulator' + if (serial.includes(':') || serial.includes('._adb-tls-connect._tcp') || serial.includes('._adb._tcp')) return 'wifi' + return 'usb' +} + +const SimctlSchema = z.object({ + devices: z.record(z.string(), z.array(z.object({ udid: z.string(), name: z.string(), state: z.string(), isAvailable: z.boolean().optional() }))), +}) + +/** `xcrun simctl list devices booted -j`: the booted simulators, with the runtime from its identifier. */ +export function parseSimctl(text: string): Simulator[] { + let json: unknown + try { + json = JSON.parse(text) + } catch { + return [] + } + const parsed = SimctlSchema.safeParse(json) + if (!parsed.success) return [] + const out: Simulator[] = [] + for (const [runtime, devices] of Object.entries(parsed.data.devices)) { + for (const d of devices) { + if (d.state !== 'Booted' || d.isAvailable === false || !/^[0-9A-F-]{36}$/i.test(d.udid)) continue + out.push({ udid: d.udid, name: d.name.slice(0, 80), runtime: runtimeName(runtime) }) + } + } + return out +} + +/** com.apple.CoreSimulator.SimRuntime.iOS-26-4 -> iOS 26.4 */ +export function runtimeName(id: string): string { + const m = /SimRuntime\.([A-Za-z]+)-([\d-]+)$/.exec(id) + return m ? `${m[1]} ${m[2]!.replace(/-/g, '.')}` : id +} + +const WindowListSchema = z.object({ + windows: z.array(z.object({ id: z.number(), owner: z.string(), bounds: z.object({ X: z.number(), Y: z.number(), Width: z.number(), Height: z.number() }) })), + screens: z.array(z.object({ x: z.number(), y: z.number(), width: z.number(), height: z.number(), scale: z.number() })), +}) + +/** The owner names macOS's AirPlay receiver draws its mirror under (macOS 12 and later). */ +export const AIRPLAY_OWNER = /airplay/i + +/** + * The AirPlay mirror windows from the window list (AIRPLAY_SCRIPT's answer). Screen frames come in AppKit + * coordinates (origin bottom left of the main display), window bounds in Quartz ones (origin top left); the crop is + * in the display's pixels, even sized, clamped to the display, as FFmpeg's crop filter takes it. + */ +export function parseAirPlayWindows(text: string): AirPlayWindow[] { + let json: unknown + try { + json = JSON.parse(text) + } catch { + return [] + } + const parsed = WindowListSchema.safeParse(json) + if (!parsed.success || parsed.data.screens.length === 0) return [] + const { windows, screens } = parsed.data + const mainHeight = screens[0]!.height + const quartz = screens.map((s) => ({ ...s, top: mainHeight - (s.y + s.height) })) + const out: AirPlayWindow[] = [] + for (const w of windows) { + if (!AIRPLAY_OWNER.test(w.owner) || w.bounds.Width < 64 || w.bounds.Height < 64) continue + const cx = w.bounds.X + w.bounds.Width / 2 + const cy = w.bounds.Y + w.bounds.Height / 2 + const screen = quartz.findIndex((s) => cx >= s.x && cx < s.x + s.width && cy >= s.top && cy < s.top + s.height) + if (screen < 0) continue + const s = quartz[screen]! + const even = (n: number): number => Math.max(2, Math.floor(n / 2) * 2) + const left = Math.max(0, w.bounds.X - s.x) + const top = Math.max(0, w.bounds.Y - s.top) + const width = Math.min(w.bounds.Width, s.width - left) + const height = Math.min(w.bounds.Height, s.height - top) + out.push({ + id: w.id, owner: w.owner.slice(0, 80), screen, + bounds: { x: w.bounds.X, y: w.bounds.Y, width: w.bounds.Width, height: w.bounds.Height }, + crop: { x: even(left * s.scale), y: even(top * s.scale), width: even(width * s.scale), height: even(height * s.scale) }, + }) + } + return out +} + +/** + * JXA run by osascript: the on-screen windows whose owner looks like the AirPlay receiver (no other window's title or + * owner leaves the script) and every display's frame and scale. + */ +export const AIRPLAY_SCRIPT = `ObjC.import('CoreGraphics'); ObjC.import('AppKit'); +const raw = $.CGWindowListCopyWindowInfo($.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements, $.kCGNullWindowID); +const list = ObjC.deepUnwrap(ObjC.castRefToObject(raw)) || []; +const windows = list.filter(w => /airplay/i.test(w.kCGWindowOwnerName || '')).map(w => ({ id: w.kCGWindowNumber, owner: w.kCGWindowOwnerName, bounds: w.kCGWindowBounds })); +const screens = $.NSScreen.screens.js.map(s => { const f = s.frame; return { x: f.origin.x, y: f.origin.y, width: f.size.width, height: f.size.height, scale: s.backingScaleFactor } }); +JSON.stringify({ windows, screens });` + +async function executable(file: string): Promise { + try { + await access(file, os.platform() === 'win32' ? constants.F_OK : constants.X_OK) + return true + } catch { + return false + } +} + +/** Where adb may be, in order: FORMREC_ADB, the PATH, ANDROID_HOME, ANDROID_SDK_ROOT, then the SDK's default folders. */ +export function adbCandidates(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, home: string = os.homedir()): string[] { + const exe = platform === 'win32' ? 'adb.exe' : 'adb' + const sep = platform === 'win32' ? ';' : ':' + const join = platform === 'win32' ? path.win32.join : path.posix.join + const list: string[] = [] + if (env['FORMREC_ADB']) list.push(env['FORMREC_ADB']) + for (const dir of (env['PATH'] ?? env['Path'] ?? '').split(sep).filter(Boolean)) list.push(join(dir, exe)) + for (const sdk of [env['ANDROID_HOME'], env['ANDROID_SDK_ROOT']]) if (sdk) list.push(join(sdk, 'platform-tools', exe)) + if (platform === 'darwin') list.push(join(home, 'Library', 'Android', 'sdk', 'platform-tools', exe), '/opt/homebrew/bin/adb', '/usr/local/bin/adb') + else if (platform === 'win32') list.push(join(env['LOCALAPPDATA'] ?? join(home, 'AppData', 'Local'), 'Android', 'Sdk', 'platform-tools', exe)) + else list.push(join(home, 'Android', 'Sdk', 'platform-tools', exe), '/usr/bin/adb', '/usr/local/bin/adb') + return [...new Set(list)] +} + +export async function findAdb(env: NodeJS.ProcessEnv = process.env): Promise { + for (const file of adbCandidates(env)) if (await executable(file)) return file + return undefined +} + +/** FFmpeg for phone capture: FORMREC_FFMPEG, the PATH, then the usual Homebrew folders (an app opened from the Finder has a short PATH). */ +export async function findPhoneFfmpeg(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): Promise { + if (env['FORMREC_FFMPEG']) return (await executable(env['FORMREC_FFMPEG'])) ? env['FORMREC_FFMPEG'] : undefined + const exe = platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg' + const dirs = (env['PATH'] ?? env['Path'] ?? '').split(platform === 'win32' ? ';' : ':').filter(Boolean) + if (platform === 'darwin') dirs.push('/opt/homebrew/bin', '/usr/local/bin') + for (const dir of dirs) { + const file = path.join(dir, exe) + if (await executable(file)) return file + } + return undefined +} + +/** How to get adb, for the panel when it is missing. */ +export function adbHowTo(platform: NodeJS.Platform = process.platform): string { + if (platform === 'darwin') return 'Install Android platform-tools (brew install --cask android-platform-tools, or Android Studio), then click Refresh. FormRec does not ship adb.' + if (platform === 'win32') return 'Install Android SDK Platform-Tools from developer.android.com/tools/releases/platform-tools (or Android Studio) and add the folder to PATH, then click Refresh. FormRec does not ship adb.' + return 'Install adb (for example sudo apt install adb, or Android SDK Platform-Tools), then click Refresh. FormRec does not ship adb.' +} + +/** Run a program for its standard output, bounded; rejects with the program's last error line. */ +export function runFor(cmd: string, args: string[], timeoutMs = 8000): Promise { + return new Promise((resolve, reject) => { + execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => { + if (error) reject(new Error(String(stderr || error.message).trim().split('\n').pop() || 'failed')) + else resolve(String(stdout)) + }) + }) +} + +export async function listAndroid(adb: string | undefined): Promise { + if (!adb) return [] + return parseAdbDevices(await runFor(adb, ['devices', '-l']).catch(() => '')) +} + +export async function listSimulators(platform: NodeJS.Platform = process.platform): Promise { + if (platform !== 'darwin') return [] + return parseSimctl(await runFor('xcrun', ['simctl', 'list', 'devices', 'booted', '-j']).catch(() => '')) +} + +export async function listAirPlay(platform: NodeJS.Platform = process.platform): Promise { + if (platform !== 'darwin') return [] + return parseAirPlayWindows(await runFor('osascript', ['-l', 'JavaScript', '-e', AIRPLAY_SCRIPT]).catch(() => '')) +} diff --git a/src/features/phone/export.ts b/src/features/phone/export.ts new file mode 100644 index 0000000..3257d42 --- /dev/null +++ b/src/features/phone/export.ts @@ -0,0 +1,100 @@ +/** + * Walkthrough layouts for a phone take, made on export only (the master keeps the phone's picture at its native size + * and frame rate): the phone centred on a blurred fill of itself (portrait, 1080 x 1920), the phone in a plain device + * frame (portrait, or centred in 1920 x 1080), or the phone beside the presenter's camera (1920 x 1080). The sound is + * every sound track of the take (microphone, phone audio) mixed at its place on the timeline. FFmpeg does the work; + * the copy is written beside the recording as phone-export-.mp4 and downloaded from the phone routes. + */ +import { spawn } from 'node:child_process' +import { rename, rm, stat } from 'node:fs/promises' +import path from 'node:path' +import type { Library } from '../../store/library.js' +import type { Recording } from '../../model/recording.js' +import { findPhoneFfmpeg } from './discover.js' + +export const LAYOUTS = ['portrait-blur', 'portrait-frame', 'landscape-frame', 'beside-camera'] as const +export type PhoneLayout = (typeof LAYOUTS)[number] +export const EXPORT_FILES = /^phone-export-(portrait-blur|portrait-frame|landscape-frame|beside-camera)\.mp4$/ + +export class ExportError extends Error { + constructor(readonly status: number, message: string) { + super(message) + } +} + +export function exportFile(library: Library, id: string, layout: PhoneLayout): string { + return path.join(library.folder(id), `phone-export-${layout}.mp4`) +} + +const BG = '0x1d1f24' +/** A plain device frame: a dark bezel and a thin lighter edge around the picture. */ +const frame = (w: number, h: number): string => `scale=w=${w}:h=${h}:force_original_aspect_ratio=decrease,pad=iw+44:ih+44:22:22:color=0x0c0c0e,pad=iw+6:ih+6:3:3:color=0x3b3d44` + +/** The video filter graph for a layout; input 0 is the phone picture, input 1 the camera when there is one. Output [v]. */ +export function videoGraph(layout: PhoneLayout, camera: boolean): string { + switch (layout) { + case 'portrait-blur': + return '[0:v]split[a][b];[a]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,boxblur=28:2,eq=brightness=-0.08[bg];' + + '[b]scale=1080:1920:force_original_aspect_ratio=decrease[fg];[bg][fg]overlay=(W-w)/2:(H-h)/2,format=yuv420p[v]' + case 'portrait-frame': + return `[0:v]${frame(960, 1740)}[ph];color=c=${BG}:s=1080x1920:r=30[bg];[bg][ph]overlay=(W-w)/2:(H-h)/2:shortest=1,format=yuv420p[v]` + case 'landscape-frame': + return `[0:v]${frame(1600, 960)}[ph];color=c=${BG}:s=1920x1080:r=30[bg];[bg][ph]overlay=(W-w)/2:(H-h)/2:shortest=1,format=yuv420p[v]` + case 'beside-camera': + return camera + ? `[0:v]${frame(900, 960)}[ph];[1:v]scale=840:-2[cam];color=c=${BG}:s=1920x1080:r=30[bg];[bg][ph]overlay=(960-w)/2:(H-h)/2:shortest=1[l];[l][cam]overlay=960+(960-w)/2:(H-h)/2:eof_action=pass,format=yuv420p[v]` + : videoGraph('landscape-frame', false) + } +} + +interface Input { file: string; offsetMs: number } + +/** The FFmpeg arguments: inputs placed on the phone picture's timeline, sound tracks mixed, H.264 and AAC out. */ +export function exportArgs(phone: Input, camera: Input | undefined, sounds: Input[], layout: PhoneLayout, durationMs: number, out: string): string[] { + const shift = (i: Input): string[] => (i.offsetMs === phone.offsetMs ? [] : ['-itsoffset', ((i.offsetMs - phone.offsetMs) / 1000).toFixed(3)]) + const useCamera = layout === 'beside-camera' && camera !== undefined + const inputs = [phone, ...(useCamera ? [camera!] : []), ...sounds] + const args = ['-hide_banner', '-v', 'error', '-y', '-protocol_whitelist', 'file'] + for (const i of inputs) args.push(...shift(i), '-i', i.file) + const first = useCamera ? 2 : 1 + const mix = sounds.length + ? `;${sounds.map((_, k) => `[${first + k}:a]`).join('')}amix=inputs=${sounds.length}:duration=longest:normalize=0[a]` + : '' + args.push('-filter_complex', videoGraph(layout, useCamera) + mix, '-map', '[v]', ...(sounds.length ? ['-map', '[a]', '-c:a', 'aac', '-b:a', '192k'] : [])) + args.push('-c:v', 'libx264', '-preset', 'medium', '-crf', '20', '-r', '30', '-t', (durationMs / 1000).toFixed(3), '-movflags', '+faststart', '-f', 'mp4', out) + return args +} + +/** The phone's picture in a recording: the screen track a phone wrote ("Phone"), else the first screen track. */ +export function phoneTracks(rec: Recording): { phone?: Recording['tracks'][number]; camera?: Recording['tracks'][number]; sounds: Recording['tracks'] } { + const tracks = rec.tracks ?? [] + const phone = tracks.find((t) => t.kind === 'screen' && t.person === 'Phone') ?? tracks.find((t) => t.kind === 'screen') + return { phone, camera: tracks.find((t) => t.kind === 'camera'), sounds: tracks.filter((t) => t.kind === 'mic') } +} + +export async function exportPhoneTake(library: Library, id: string, layout: PhoneLayout): Promise<{ layout: PhoneLayout; bytes: number; url: string }> { + const rec = await library.get(id) + if (!rec) throw new ExportError(404, 'no such recording') + const { phone, camera, sounds } = phoneTracks(rec) + if (!phone) throw new ExportError(409, 'this recording has no phone or screen picture to lay out') + const ffmpeg = await findPhoneFfmpeg() + if (!ffmpeg) throw new ExportError(424, 'phone layouts need FFmpeg (brew install ffmpeg, or set FORMREC_FFMPEG)') + const dir = library.folder(id) + const at = (t: { file: string; offsetMs: number }): Input => ({ file: path.join(dir, t.file), offsetMs: t.offsetMs }) + const out = exportFile(library, id, layout) + const part = `${out}.part.mp4` + const args = exportArgs(at(phone), camera && at(camera), sounds.map(at), layout, phone.durationMs || rec.durationMs, part) + const failure = await new Promise((resolve) => { + let err = '' + const p = spawn(ffmpeg, args, { stdio: ['ignore', 'ignore', 'pipe'] }) + p.stderr.on('data', (d: Buffer) => { err = (err + d.toString()).slice(-2000) }) + p.on('error', (e) => resolve(e.message)) + p.on('close', (code) => resolve(code === 0 ? undefined : err.trim().split('\n').pop() || `FFmpeg exited with ${code}`)) + }) + if (failure) { + await rm(part, { force: true }) + throw new ExportError(502, `the layout could not be made: ${failure}`) + } + await rename(part, out) + return { layout, bytes: (await stat(out)).size, url: `/api/phone/recordings/${encodeURIComponent(id)}/export/${layout}` } +} diff --git a/src/features/phone/feed.ts b/src/features/phone/feed.ts new file mode 100644 index 0000000..0a4a256 --- /dev/null +++ b/src/features/phone/feed.ts @@ -0,0 +1,478 @@ +/** + * A phone as the take's picture (issue #7): started, paused, resumed and stopped with the studio's take, like the + * desktop feature's native display feed. The phone's picture becomes the take's screen track at the size and frame + * rate the phone sent (stream copied, never scaled), and its sound, when it has any, a track of its own + * (`?source=phone`, "Phone audio"), apart from the microphone. Both tracks are registered on the studio's own routes + * when the take starts (a track can be added only while the take records) and filled when it stops, after the + * segments are joined, so the one writer per track stays src/store/sessions.ts and the take's offsets, limits and + * crash recovery apply as they do to a browser track. + * + * Sources recorded here are producers.ts's. Two arrive as finished files instead: the iPhone or iPad on USB (the + * desktop app's shell writes /phone/captures//capture.mov, a name the server chose) and a phone + * recording file uploaded to narrate over (files.ts), trimmed to the time the take played it. + */ +import { spawn } from 'node:child_process' +import { mkdir, open, rm, stat, writeFile } from 'node:fs/promises' +import { randomBytes } from 'node:crypto' +import path from 'node:path' +import { z } from 'zod' +import { AdbHelpers } from './adb.js' +import { findAdb, findPhoneFfmpeg, listAirPlay, runFor } from './discover.js' +import { AirPlayProducer, pickEncoder, ProducerError, ScrcpyProducer, ScreenrecordProducer, SimulatorProducer, type Producer, type SegmentResult } from './producers.js' +import { phoneFilePath } from './files.js' + +const SERIAL = /^[A-Za-z0-9][\w.:@-]{0,119}$/ +export const PhoneSourceSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('android'), serial: z.string().regex(SERIAL), showTaps: z.boolean().default(true), demoMode: z.boolean().default(false), audio: z.boolean().default(true) }), + z.object({ kind: z.literal('simulator'), udid: z.string().regex(/^[0-9A-F-]{36}$/i) }), + z.object({ kind: z.literal('airplay'), window: z.number().int().min(0) }), + z.object({ kind: z.literal('ios-usb'), name: z.string().trim().min(1).max(120) }), + z.object({ kind: z.literal('file'), file: z.string().regex(/^f[a-f0-9]{24}$/) }), +]) +export type PhoneSource = z.infer + +export const CAPTURE_ID = /^c[a-f0-9]{24}$/ +/** What the shell writes for an iPhone on USB, inside the capture folder the server made. */ +export const IOS_CAPTURE_FILE = 'capture.mov' +const CHUNK_BYTES = 8 * 1024 * 1024 +const RETRIES = 4 + +export class PhoneFeedError extends Error { + constructor(readonly status: number, message: string) { + super(message) + } +} + +export interface FeedOptions { + port(): number | undefined + token: string + dataDir: string + clock?: () => number + /** Seams for tests. */ + ffmpeg?: () => Promise + adb?: () => Promise + producer?: (source: PhoneSource) => Promise +} + +export interface PhoneFeedStatus { + sessionId: string + source: PhoneSource['kind'] + captureId: string + state: 'recording' | 'paused' | 'ended' + audio: boolean + notes: string[] + /** For ios-usb: the folder the shell writes capture.mov in. */ + captureDir?: string +} + +interface Run { + sessionId: string + source: PhoneSource + captureId: string + dir: string + producer?: Producer + segments: (SegmentResult & { wallMs?: number })[] + /** When the current segment's first picture came (this clock). */ + segStart: number + n: number + startedAt: number + pausedAt?: number + pausedMs: number + screenTrack: string + audioTrack?: string + notes: string[] + ended?: boolean +} + +export class PhoneFeed { + private readonly runs = new Map() + private readonly starting = new Set() + private readonly clock: () => number + readonly helpers: AdbHelpers + private generation = 0 + + constructor(private readonly opts: FeedOptions) { + this.clock = opts.clock ?? Date.now + this.helpers = new AdbHelpers(() => this.adb()) + } + + private ffmpeg(): Promise { + return (this.opts.ffmpeg ?? (() => findPhoneFfmpeg()))() + } + + private adb(): Promise { + return (this.opts.adb ?? (() => findAdb()))() + } + + status(sessionId: string): PhoneFeedStatus | undefined { + const run = this.runs.get(sessionId) + return run && this.view(run) + } + + active(): string | null { + return [...this.runs.values()].find((r) => !r.ended)?.sessionId ?? null + } + + private view(run: Run): PhoneFeedStatus { + return { + sessionId: run.sessionId, source: run.source.kind, captureId: run.captureId, + state: run.ended ? 'ended' : run.pausedAt !== undefined ? 'paused' : 'recording', + audio: Boolean(run.audioTrack), notes: [...run.notes, ...(run.producer?.problem ? [run.producer.problem] : [])], + ...(run.source.kind === 'ios-usb' ? { captureDir: run.dir } : {}), + } + } + + async start(sessionId: string, source: PhoneSource): Promise { + if (this.runs.get(sessionId) && !this.runs.get(sessionId)!.ended) throw new PhoneFeedError(409, 'this take already records a phone') + if (this.starting.has(sessionId)) throw new PhoneFeedError(409, 'this take is already starting a phone') + this.starting.add(sessionId) + const generation = this.generation + try { + const { session } = await this.api<{ session: { state: string } }>('GET', `/api/sessions/${encodeURIComponent(sessionId)}`) + if (session.state !== 'recording' && session.state !== 'paused') throw new PhoneFeedError(409, `the take is ${session.state}; start it first`) + const captureId = `c${randomBytes(12).toString('hex')}` + const dir = path.join(this.opts.dataDir, 'phone', 'captures', captureId) + await mkdir(dir, { recursive: true, mode: 0o700 }) + const run: Run = { sessionId, source, captureId, dir, segments: [], segStart: 0, n: 0, startedAt: 0, pausedMs: 0, screenTrack: '', notes: [] } + try { + await this.open(run) + if (generation !== this.generation) throw new PhoneFeedError(503, 'the app is closing') + // The shell's recording of an iPhone starts after this answer (it needs the capture folder): begin() registers its tracks. + if (source.kind !== 'ios-usb') await this.register(run) + } catch (error) { + await run.producer?.close().catch(() => undefined) + if (source.kind === 'android') await this.helpers.restore(source.serial) + await rm(dir, { recursive: true, force: true }) + throw error instanceof ProducerError ? new PhoneFeedError(error.status, error.message) : error + } + this.runs.set(sessionId, run) + return this.view(run) + } finally { + this.starting.delete(sessionId) + } + } + + /** The producer for a recorded-here source, its first segment, and the take's start on this clock. */ + private async open(run: Run): Promise { + const source = run.source + if (source.kind === 'ios-usb' || source.kind === 'file') { + if (source.kind === 'file') await stat(phoneFilePath(this.opts.dataDir, source.file)).catch(() => { throw new PhoneFeedError(404, 'that phone recording is no longer here; choose it again') }) + run.startedAt = this.clock() + return + } + if (source.kind === 'android') run.notes.push(...(await this.helpers.apply(source.serial, { showTaps: source.showTaps, demoMode: source.demoMode }))) + const producer = await (this.opts.producer ?? ((s) => this.makeProducer(s, run)))(source) + if (!producer) throw new PhoneFeedError(404, 'that phone source is not here any more') + run.producer = producer + run.startedAt = await producer.begin(run.dir, run.n) + run.segStart = run.startedAt + if (producer.audioNote && !producer.audio) run.notes.push(`No phone sound: ${producer.audioNote}.`) + } + + private async makeProducer(source: PhoneSource, run: Run): Promise { + const ffmpeg = await this.ffmpeg() + if (source.kind === 'simulator') return new SimulatorProducer(source.udid, this.clock) + if (source.kind === 'airplay') { + if (!ffmpeg) throw new PhoneFeedError(424, 'recording the AirPlay mirror needs FFmpeg (brew install ffmpeg, or set FORMREC_FFMPEG)') + const window = (await listAirPlay()).find((w) => w.id === source.window) + if (!window) return undefined + return new AirPlayProducer(ffmpeg, window, await pickEncoder(ffmpeg), this.clock) + } + if (source.kind !== 'android') return undefined + const adb = await this.adb() + if (!adb) throw new PhoneFeedError(424, 'adb is not installed') + if (!ffmpeg) throw new PhoneFeedError(424, 'recording an Android phone needs FFmpeg (brew install ffmpeg, or set FORMREC_FFMPEG)') + const scrcpy = new ScrcpyProducer(adb, source.serial, ffmpeg, this.opts.dataDir, source.audio, this.clock) + try { + await scrcpy.open() + return scrcpy + } catch (error) { + run.notes.push(`Recorded with screenrecord instead of the scrcpy server (${(error as Error).message}).`) + return new ScreenrecordProducer(adb, source.serial, this.clock) + } + } + + private async register(run: Run): Promise { + const base = `/api/sessions/${encodeURIComponent(run.sessionId)}/tracks` + const nonce = run.captureId.slice(1, 21) + const screen = await this.api<{ id: string }>('POST', base, { kind: 'screen', mime: 'video/mp4', startedAt: run.startedAt, person: 'Phone', nonce: `ps${nonce}` }) + run.screenTrack = screen.id + if (await this.wantsAudio(run)) { + const audio = await this.api<{ id: string }>('POST', `${base}?source=phone`, { kind: 'mic', mime: 'audio/mp4', startedAt: run.startedAt, nonce: `pa${nonce}` }) + run.audioTrack = audio.id + } + } + + private async wantsAudio(run: Run): Promise { + if (run.producer) return run.producer.audio + if (!(await this.ffmpeg())) { + run.notes.push('Without FFmpeg the phone\'s sound stays inside the picture track instead of a track of its own.') + return false + } + if (run.source.kind === 'file') return hasAudio((await this.ffmpeg())!, phoneFilePath(this.opts.dataDir, run.source.file)) + return true + } + + /** The shell has started recording the iPhone: its tracks start now. */ + async begin(sessionId: string): Promise { + const run = this.live(sessionId) + if (!run.screenTrack) { + run.startedAt = this.clock() + await this.register(run) + } + return this.view(run) + } + + async pause(sessionId: string): Promise { + const run = this.live(sessionId) + if (run.pausedAt !== undefined) return this.view(run) + run.pausedAt = this.clock() + if (run.producer) run.segments.push(await this.endSegment(run)) + return this.view(run) + } + + async resume(sessionId: string): Promise { + const run = this.live(sessionId) + if (run.pausedAt === undefined) return this.view(run) + run.pausedMs += this.clock() - run.pausedAt + run.pausedAt = undefined + if (run.producer) { + run.n += 1 + run.segStart = await run.producer.begin(run.dir, run.n).catch((error: Error) => { run.notes.push(`The phone did not resume: ${error.message}`); return this.clock() }) + } + return this.view(run) + } + + /** End the phone's part of the take: join, split, send and end its tracks. `durationMs` is the played length of a file source. */ + async stop(sessionId: string, input: { durationMs?: number } = {}): Promise<{ durationMs: number; tracks: string[]; notes: string[] }> { + const run = this.runs.get(sessionId) + if (!run || run.ended) throw new PhoneFeedError(404, 'this take records no phone') + if (!run.screenTrack) { + this.runs.delete(sessionId) + await rm(run.dir, { recursive: true, force: true }).catch(() => undefined) + throw new PhoneFeedError(409, 'the phone never started recording') + } + run.ended = true + const at = this.clock() + if (run.pausedAt !== undefined) run.pausedMs += at - run.pausedAt + else if (run.producer) run.segments.push(await this.endSegment(run).catch(() => ({ video: [], audio: [] }))) + if (run.producer?.problem) run.notes.push(run.producer.problem) + await run.producer?.close().catch(() => undefined) + if (run.source.kind === 'android') await this.helpers.restore(run.source.serial) + const wall = Math.max(0, at - run.startedAt - run.pausedMs) + try { + const { video, audio } = this.inputs(run) + const lengthMs = run.source.kind === 'file' && input.durationMs !== undefined ? input.durationMs : undefined + const made = await this.ingest(run, video, audio, lengthMs) + const tracks: string[] = [] + if (made.video) tracks.push(await this.send(run, run.screenTrack, made.video, made.videoMs ?? lengthMs ?? wall)) + if (run.audioTrack && made.audio) tracks.push(await this.send(run, run.audioTrack, made.audio, made.audioMs ?? lengthMs ?? wall)) + if (!made.video) run.notes.push('The phone gave no picture for this take.') + return { durationMs: made.videoMs ?? lengthMs ?? wall, tracks, notes: run.notes } + } finally { + this.runs.delete(sessionId) + await rm(run.dir, { recursive: true, force: true }).catch(() => undefined) + } + } + + private async endSegment(run: Run): Promise { + const result = await run.producer!.end() + return { ...result, wallMs: Math.max(0, this.clock() - run.segStart) } + } + + /** + * A recorder that writes frames only when the screen changes (the Simulator) can leave a segment shorter than the + * time it recorded; joined as it is, every later segment would play early. Such a segment's last picture is held + * to its recorded length (re-encoded at the same size; only these segments). + */ + private async padded(run: Run, ffmpeg: string): Promise { + const out: string[] = [] + let encoder: string | undefined + for (const [k, seg] of run.segments.entries()) { + if (seg.video.length !== 1 || seg.wallMs === undefined) { out.push(...seg.video); continue } + const file = seg.video[0]! + const ms = await probeMs(ffmpeg, file) + if (ms === undefined || seg.wallMs - ms < PAD_SLACK_MS) { out.push(file); continue } + encoder ??= await pickEncoder(ffmpeg) + const target = path.join(run.dir, `held-${k}.mkv`) + const ok = await runFor(ffmpeg, padArgs(file, target, seg.wallMs - ms, encoder), 30 * 60_000).then(() => true, () => false) + out.push(ok ? target : file) + } + return out + } + + private inputs(run: Run): { video: string[]; audio: string[] } { + if (run.source.kind === 'ios-usb') { + const file = path.join(run.dir, IOS_CAPTURE_FILE) + return { video: [file], audio: [file] } + } + if (run.source.kind === 'file') { + const file = phoneFilePath(this.opts.dataDir, run.source.file) + return { video: [file], audio: [file] } + } + return { video: run.segments.flatMap((s) => s.video), audio: run.segments.flatMap((s) => s.audio) } + } + + /** The take's MP4 picture and M4A sound from the inputs (joined, picture stream copied, sound in AAC). */ + private async ingest(run: Run, video: string[], audio: string[], lengthMs?: number): Promise<{ video?: string; audio?: string; videoMs?: number; audioMs?: number }> { + const present = async (files: string[]): Promise => { + const out: string[] = [] + for (const f of files) if (((await stat(f).catch(() => undefined))?.size ?? 0) > 0) out.push(f) + return out + } + const ffmpegFirst = await this.ffmpeg() + if (ffmpegFirst && run.producer) video = await this.padded(run, ffmpegFirst) + const pictures = await present(video) + const sounds = await present(audio) + if (!pictures.length) return {} + const ffmpeg = await this.ffmpeg() + if (!ffmpeg) { + // Without FFmpeg only one finished MP4 or MOV file can be the track (it starts with ftyp), sound inside. + if (pictures.length > 1) run.notes.push('Without FFmpeg only the part before the first pause is kept.') + return { video: pictures[0]! } + } + const out: { video?: string; audio?: string; videoMs?: number; audioMs?: number } = {} + const v = path.join(run.dir, 'phone-video.mp4') + if (await join(ffmpeg, run.dir, pictures, v, 'video', lengthMs)) out.video = v + else run.notes.push('FFmpeg could not join the phone\'s picture.') + if (run.audioTrack && sounds.length) { + const a = path.join(run.dir, 'phone-audio.m4a') + if (await join(ffmpeg, run.dir, sounds, a, 'audio', lengthMs)) out.audio = a + } + if (out.video) { const ms = await probeMs(ffmpeg, out.video); if (ms !== undefined) out.videoMs = ms } + if (out.audio) { const ms = await probeMs(ffmpeg, out.audio); if (ms !== undefined) out.audioMs = ms } + return out + } + + /** Post a finished file to a registered track in chunks, then end it. */ + private async send(run: Run, trackId: string, file: string, durationMs: number): Promise { + const base = `/api/sessions/${encodeURIComponent(run.sessionId)}/tracks/${encodeURIComponent(trackId)}` + const size = (await stat(file)).size + const handle = await open(file, 'r') + try { + for (let seq = 0, at = 0; at < size; seq += 1, at += CHUNK_BYTES) { + const body = Buffer.alloc(Math.min(CHUNK_BYTES, size - at)) + await handle.read(body, 0, body.length, at) + await this.withRetries(() => this.api('POST', `${base}/chunks?seq=${seq}`, body)) + } + } finally { + await handle.close() + } + await this.withRetries(() => this.api('POST', `${base}/end`, { durationMs: Math.round(durationMs) })) + return trackId + } + + private async withRetries(work: () => Promise): Promise { + for (let attempt = 0; ; attempt += 1) { + try { + return await work() + } catch (error) { + const status = error instanceof PhoneFeedError ? error.status : 0 + if ((status >= 400 && status < 500 && status !== 429) || attempt >= RETRIES) throw error + await new Promise((r) => setTimeout(r, 300 * 2 ** attempt)) + } + } + } + + /** The app closes: every producer stops and every phone setting is put back; the takes stay for crash recovery. */ + async stopAll(): Promise { + this.generation += 1 + const all = [...this.runs.values()] + this.runs.clear() + for (const run of all) { + await run.producer?.close().catch(() => undefined) + await rm(run.dir, { recursive: true, force: true }).catch(() => undefined) + } + await this.helpers.restoreAll() + } + + private live(sessionId: string): Run { + const run = this.runs.get(sessionId) + if (!run || run.ended) throw new PhoneFeedError(404, 'this take records no phone') + return run + } + + private async api(method: string, route: string, body?: unknown): Promise { + const port = this.opts.port() + if (!port) throw new PhoneFeedError(503, 'the server is not listening yet') + const raw = Buffer.isBuffer(body) + let res: Response + try { + res = await fetch(`http://127.0.0.1:${port}${route}`, { + method, + headers: { Authorization: `Bearer ${this.opts.token}`, ...(body === undefined ? {} : { 'Content-Type': raw ? 'application/octet-stream' : 'application/json' }) }, + ...(body === undefined ? {} : { body: raw ? new Uint8Array(body) : JSON.stringify(body) }), + }) + } catch (error) { + throw new PhoneFeedError(0, (error as Error).message) + } + const json = (await res.json().catch(() => ({}))) as T & { error?: string } + if (!res.ok) throw new PhoneFeedError(res.status, json.error ?? res.statusText) + return json + } +} + +/** A segment whose picture ends this much before its recorded time gets its last picture held. */ +export const PAD_SLACK_MS = 400 + +/** Hold the last picture for `extraMs` more (tpad), re-encoded at the same size, no sound. */ +export function padArgs(file: string, out: string, extraMs: number, encoder: string): string[] { + const enc = encoder === 'h264_videotoolbox' ? ['-c:v', 'h264_videotoolbox', '-q:v', '70'] : ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '16'] + return ['-hide_banner', '-v', 'error', '-y', '-protocol_whitelist', 'file', '-i', file, '-an', '-vf', `tpad=stop_mode=clone:stop_duration=${(extraMs / 1000).toFixed(3)},format=yuv420p`, ...enc, '-f', 'matroska', out] +} + +/** FFmpeg's concat list: one `file ''` line per input, quotes escaped as the demuxer reads them. */ +export function concatList(files: string[]): string { + return files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join('\n') + '\n' +} + +/** The arguments that join inputs into one picture (stream copied, MP4, index first) or one sound (AAC in M4A). */ +export function joinArgs(list: string | undefined, single: string | undefined, out: string, what: 'video' | 'audio', lengthMs?: number): string[] { + const input = list ? ['-f', 'concat', '-safe', '0', '-i', list] : ['-i', single!] + const length = lengthMs !== undefined && lengthMs > 0 ? ['-t', (lengthMs / 1000).toFixed(3)] : [] + const streams = what === 'video' + ? ['-map', '0:v:0', '-c:v', 'copy', '-an', '-movflags', '+faststart', '-f', 'mp4'] + : ['-map', '0:a:0', '-vn', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-f', 'ipod'] + return ['-hide_banner', '-v', 'error', '-y', '-protocol_whitelist', 'file,pipe,concat', ...input, ...length, ...streams, out] +} + +async function join(ffmpeg: string, dir: string, files: string[], out: string, what: 'video' | 'audio', lengthMs?: number): Promise { + let list: string | undefined + if (files.length > 1) { + list = path.join(dir, `${what}-list.txt`) + await writeFile(list, concatList(files), { mode: 0o600 }) + } + try { + await runFor(ffmpeg, joinArgs(list, files[0], out, what, lengthMs), 30 * 60_000) + return ((await stat(out).catch(() => undefined))?.size ?? 0) > 0 + } catch { + return false + } +} + +/** FFmpeg's log for reading a file's header (it exits with an error when given no output; the log is what is wanted). */ +function headerLog(ffmpeg: string, file: string): Promise { + return new Promise((resolve) => { + let err = '' + const p = spawn(ffmpeg, ['-hide_banner', '-protocol_whitelist', 'file', '-i', file], { stdio: ['ignore', 'ignore', 'pipe'] }) + const timer = setTimeout(() => p.kill('SIGKILL'), 60_000) + p.stderr.on('data', (d: Buffer) => { if (err.length < 64_000) err += d.toString() }) + p.on('close', () => { clearTimeout(timer); resolve(err) }) + p.on('error', () => { clearTimeout(timer); resolve(err) }) + }) +} + +/** A file's length from FFmpeg's reading of its header. */ +export async function probeMs(ffmpeg: string, file: string): Promise { + return durationOf(await headerLog(ffmpeg, file)) +} + +export function durationOf(ffmpegLog: string): number | undefined { + const m = /Duration: (\d+):(\d\d):(\d\d(?:\.\d+)?)/.exec(ffmpegLog) + return m ? Math.round((Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3])) * 1000) : undefined +} + +/** True when the file holds a sound stream. */ +export async function hasAudio(ffmpeg: string, file: string): Promise { + return /Stream #\d+:\d+.*: Audio:/.test(await headerLog(ffmpeg, file)) +} diff --git a/src/features/phone/files.ts b/src/features/phone/files.ts new file mode 100644 index 0000000..e612b2a --- /dev/null +++ b/src/features/phone/files.ts @@ -0,0 +1,80 @@ +/** + * Phone recording files to narrate over (issue #7, "Import a phone recording"): a screen recording made on the phone + * (iOS Control Center, Android's recorder), brought over by AirDrop, Files or a shared folder, is uploaded to + * /phone/files//source and played on the studio's stage while the take records; the take keeps the part + * that played as its picture and the file's own sound as the phone audio track (feed.ts). The id is the server's, + * the file is served only to the run's token, and files left behind are removed after a day. + * POST /api/phone/files?name= body = the video -> { id, name, bytes, durationMs? } + * GET /api/phone/files/:id the video (ranged), for the stage + * DELETE /api/phone/files/:id + */ +import { randomBytes } from 'node:crypto' +import { mkdir, open, readdir, rm, stat } from 'node:fs/promises' +import path from 'node:path' +import { receiveFile, UploadTooLarge } from '../../server/files.js' +import { UPLOAD_LIMIT } from '../../server/http.js' + +export const FILE_ID = /^f[a-f0-9]{24}$/ +const DAY = 24 * 60 * 60 * 1000 + +export function phoneFilePath(dataDir: string, id: string): string { + if (!FILE_ID.test(id)) throw new Error('not a phone file id') + return path.join(dataDir, 'phone', 'files', id, 'source') +} + +/** MP4 and MOV start with an ftyp box, WebM with the EBML magic; nothing else is a phone recording. */ +export function videoKind(head: Buffer): 'mp4' | 'webm' | undefined { + if (head.length >= 8 && head.toString('latin1', 4, 8) === 'ftyp') return 'mp4' + if (head.length >= 4 && head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) return 'webm' + return undefined +} + +export class PhoneFileError extends Error { + constructor(readonly status: number, message: string) { + super(message) + } +} + +export async function receivePhoneFile(dataDir: string, body: import('node:http').IncomingMessage, limit = UPLOAD_LIMIT): Promise<{ id: string; file: string; bytes: number; kind: 'mp4' | 'webm' }> { + const id = `f${randomBytes(12).toString('hex')}` + const file = phoneFilePath(dataDir, id) + await mkdir(path.dirname(file), { recursive: true, mode: 0o700 }) + try { + const bytes = await receiveFile(body, file, limit) + const handle = await open(file, 'r') + const head = Buffer.alloc(12) + try { + await handle.read(head, 0, 12, 0) + } finally { + await handle.close() + } + const kind = videoKind(head) + if (!kind) throw new PhoneFileError(415, 'not a video FormRec can narrate over (MP4, MOV or WebM)') + return { id, file, bytes, kind } + } catch (error) { + await rm(path.dirname(file), { recursive: true, force: true }) + if (error instanceof UploadTooLarge) throw new PhoneFileError(413, error.message) + throw error + } +} + +export async function removePhoneFile(dataDir: string, id: string): Promise { + await rm(path.dirname(phoneFilePath(dataDir, id)), { recursive: true, force: true }) +} + +/** Files and capture folders older than a day: a take that never stopped, a file never recorded over. */ +export async function sweepPhoneFiles(dataDir: string, now = Date.now()): Promise { + let removed = 0 + for (const sub of ['files', 'captures']) { + const root = path.join(dataDir, 'phone', sub) + for (const name of await readdir(root).catch(() => [] as string[])) { + if (!/^[fc][a-f0-9]{24}$/.test(name)) continue + const info = await stat(path.join(root, name)).catch(() => undefined) + if (info && now - info.mtimeMs > DAY) { + await rm(path.join(root, name), { recursive: true, force: true }) + removed += 1 + } + } + } + return removed +} diff --git a/src/features/phone/handler.ts b/src/features/phone/handler.ts index e550207..3537686 100644 --- a/src/features/phone/handler.ts +++ b/src/features/phone/handler.ts @@ -44,6 +44,7 @@ export const PAGE_FILES: Readonly> = { 'phone-upload.js': 'phone-upload.js', 'phone-queue.js': 'phone-queue.js', 'phone-install.js': 'phone-install.js', + 'phone-send.js': 'phone-send.js', 'sw.js': 'phone-sw.js', 'dom.js': 'dom.js', 'icon-192.png': 'brand/phone-icon-192.png', diff --git a/src/features/phone/index.ts b/src/features/phone/index.ts index 2b4c0ad..3c2cb6d 100644 --- a/src/features/phone/index.ts +++ b/src/features/phone/index.ts @@ -3,6 +3,8 @@ * install (Loom's iOS and Android apps, R1-11 to R1-13). The phone's page and API live on the guest listener under * /phone/ (handler.ts); this module adds the loopback status route and the MCP tool. * GET /api/phone { enabled, links, codeLive, devices, fingerprint } (behind the run's token) + * Phone capture as a take's picture (an iPhone on USB, Android over adb, the iOS Simulator, an AirPlay mirror, a + * phone recording to narrate over) is under /api/phone/sources, /feed, /files and /recordings: routes.ts. */ import { z } from 'zod' import { sendJson } from '../../server/http.js' @@ -10,6 +12,9 @@ import { loadToken } from '../../server/token.js' import { liveServers } from '../../store/server-file.js' import type { Feature } from '../types.js' import { phoneHost, phoneLinks } from './host.js' +import { phoneRoutes, stopFeed } from './routes.js' +import { sweepPhoneFiles } from './files.js' +import { EXPORT_FILES } from './export.js' export interface PhoneStatus { enabled: boolean @@ -61,11 +66,22 @@ export async function phoneTool(dataDir: string, input: { enable?: boolean; newC export const feature: Feature = { id: 'phone', - routes: (ctx) => async (req, res, parts) => { - if (parts[1] !== 'phone' || parts.length !== 2) return false - if ((req.method ?? 'GET') !== 'GET') return false - sendJson(res, 200, await phoneStatus(ctx.dataDir)) - return true + files: EXPORT_FILES, + routes: (ctx) => { + const capture = phoneRoutes(ctx) + return async (req, res, parts, url) => { + if (parts[1] !== 'phone') return false + if (parts.length > 2) return capture(req, res, parts, url) + if ((req.method ?? 'GET') !== 'GET') return false + sendJson(res, 200, await phoneStatus(ctx.dataDir)) + return true + } + }, + async start(ctx) { + await sweepPhoneFiles(ctx.dataDir).catch(() => undefined) + }, + async stop() { + await stopFeed() }, mcp(server, deps) { server.registerTool( diff --git a/src/features/phone/mkv.ts b/src/features/phone/mkv.ts new file mode 100644 index 0000000..d10f469 --- /dev/null +++ b/src/features/phone/mkv.ts @@ -0,0 +1,156 @@ +/** + * A small Matroska writer for one H.264 video track, so the pictures scrcpy sends keep the device's own timestamps + * (a raw H.264 stream carries none, and FFmpeg's wall-clock option cannot stream-copy one). The packets arrive in + * Annex B form (start codes); the config packet holds the SPS and PPS, which become the track's avcC CodecPrivate, + * and every frame is written as length-prefixed NAL units in a SimpleBlock. Clusters start at key frames (or every + * 20 s), timestamps in milliseconds from the first frame. The file is written as it goes with unknown sizes for the + * Segment and each Cluster, which Matroska allows for live files, so a file cut short still reads up to its end. + * FFmpeg then stream-copies it into the take's MP4 track. Pure byte building plus a sink; unit tested by parsing + * the result back with FFmpeg when it is present (tests/phone-scrcpy.test.ts). + */ + +/** An EBML variable-size integer for an element size. */ +export function vintSize(n: number): Buffer { + for (let len = 1; len <= 8; len += 1) { + if (n < 2 ** (7 * len) - 1) { + const out = Buffer.alloc(len) + let v = n + for (let i = len - 1; i >= 0; i -= 1) { + out[i] = v & 0xff + v = Math.floor(v / 256) + } + out[0]! |= 1 << (8 - len) + return out + } + } + throw new Error('EBML size too large') +} + +const UNKNOWN = Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) + +function id(hex: number): Buffer { + const bytes: number[] = [] + for (let v = hex; v > 0; v = Math.floor(v / 256)) bytes.unshift(v & 0xff) + return Buffer.from(bytes) +} + +export function el(tag: number, body: Buffer): Buffer { + return Buffer.concat([id(tag), vintSize(body.length), body]) +} + +function uint(tag: number, value: number): Buffer { + const bytes: number[] = [] + let v = value + do { + bytes.unshift(v & 0xff) + v = Math.floor(v / 256) + } while (v > 0) + return el(tag, Buffer.from(bytes)) +} + +const str = (tag: number, value: string): Buffer => el(tag, Buffer.from(value, 'utf8')) +function float(tag: number, value: number): Buffer { + const b = Buffer.alloc(8) + b.writeDoubleBE(value) + return el(tag, b) +} + +/** NAL units of an Annex B buffer (00 00 01 or 00 00 00 01 start codes), without the start codes. */ +export function splitAnnexB(data: Buffer): Buffer[] { + const starts: { at: number; len: number }[] = [] + for (let i = 0; i + 2 < data.length; i += 1) { + if (data[i] === 0 && data[i + 1] === 0) { + if (data[i + 2] === 1) { starts.push({ at: i, len: 3 }); i += 2 } + else if (data[i + 2] === 0 && data[i + 3] === 1) { starts.push({ at: i, len: 4 }); i += 3 } + } + } + if (starts.length === 0) return data.length ? [data] : [] + const out: Buffer[] = [] + for (let k = 0; k < starts.length; k += 1) { + const begin = starts[k]!.at + starts[k]!.len + const end = k + 1 < starts.length ? starts[k + 1]!.at : data.length + if (end > begin) out.push(data.subarray(begin, end)) + } + return out +} + +/** The avcC record (ISO 14496-15) from a config packet's SPS and PPS. */ +export function avcC(config: Buffer): Buffer { + const nals = splitAnnexB(config) + const sps = nals.filter((n) => (n[0]! & 0x1f) === 7) + const pps = nals.filter((n) => (n[0]! & 0x1f) === 8) + if (!sps.length || !pps.length || sps[0]!.length < 4) throw new Error('the config packet has no SPS and PPS') + const parts: Buffer[] = [Buffer.from([1, sps[0]![1]!, sps[0]![2]!, sps[0]![3]!, 0xff, 0xe0 | sps.length])] + for (const s of sps) parts.push(u16(s.length), s) + parts.push(Buffer.from([pps.length])) + for (const p of pps) parts.push(u16(p.length), p) + return Buffer.concat(parts) +} + +function u16(n: number): Buffer { + const b = Buffer.alloc(2) + b.writeUInt16BE(n) + return b +} + +/** Annex B to 4-byte length-prefixed NAL units; access unit delimiters are left out, parameter sets kept in band (a rotated phone sends new ones). */ +export function toLengthPrefixed(data: Buffer): Buffer { + const parts: Buffer[] = [] + for (const nal of splitAnnexB(data)) { + const type = nal[0]! & 0x1f + if (type === 9) continue + const len = Buffer.alloc(4) + len.writeUInt32BE(nal.length) + parts.push(len, nal) + } + return Buffer.concat(parts) +} + +export function header(config: Buffer, width: number, height: number): Buffer { + const ebml = el(0x1a45dfa3, Buffer.concat([ + uint(0x4286, 1), uint(0x42f7, 1), uint(0x42f2, 4), uint(0x42f3, 8), str(0x4282, 'matroska'), uint(0x4287, 4), uint(0x4285, 2), + ])) + const info = el(0x1549a966, Buffer.concat([uint(0x2ad7b1, 1_000_000), str(0x4d80, 'formrec'), str(0x5741, 'formrec'), float(0x4489, 0)])) + const video = el(0xe0, Buffer.concat([uint(0xb0, width), uint(0xba, height)])) + const track = el(0xae, Buffer.concat([uint(0xd7, 1), uint(0x73c5, 1), uint(0x83, 1), uint(0x9c, 0), str(0x86, 'V_MPEG4/ISO/AVC'), el(0x63a2, avcC(config)), video])) + return Buffer.concat([ebml, id(0x18538067), UNKNOWN, info, el(0x1654ae6b, track)]) +} + +/** One video segment written as packets arrive. `write` receives the bytes in order. */ +export class MkvVideoWriter { + private started = false + private firstUs = 0 + private clusterMs = -1 + private lastMs = -1 + + constructor(private readonly write: (b: Buffer) => void, private readonly size: { width: number; height: number }) {} + + /** A frame with its PTS; the first one written must be a key frame (earlier ones are dropped). Returns whether it was written. */ + frame(config: Buffer, ptsUs: number, key: boolean, data: Buffer): boolean { + if (!this.started) { + if (!key) return false + this.write(header(config, this.size.width, this.size.height)) + this.started = true + this.firstUs = ptsUs + } + // Timestamps only go forward in a cluster's frame order; a frame from before the last one is placed just after it. + const ms = Math.max(this.lastMs + (this.lastMs < 0 ? 1 : 0), Math.round((ptsUs - this.firstUs) / 1000)) + this.lastMs = ms + if (this.clusterMs < 0 || key || ms - this.clusterMs > 20_000) { + this.write(Buffer.concat([id(0x1f43b675), UNKNOWN, uint(0xe7, ms)])) + this.clusterMs = ms + } + const payload = toLengthPrefixed(data) + if (payload.length === 0) return false + const block = Buffer.alloc(4) + block[0] = 0x81 + block.writeInt16BE(ms - this.clusterMs, 1) + block[3] = key ? 0x80 : 0 + this.write(el(0xa3, Buffer.concat([block, payload]))) + return true + } + + get wrote(): boolean { + return this.started + } +} diff --git a/src/features/phone/producers.ts b/src/features/phone/producers.ts new file mode 100644 index 0000000..40c1d03 --- /dev/null +++ b/src/features/phone/producers.ts @@ -0,0 +1,362 @@ +/** + * What records a phone source on this computer, one segment at a time (a pause ends a segment, a resume starts the + * next; the take's tracks are the segments joined, so they hold recorded time only, as a browser track does): + * - AndroidScrcpy: the scrcpy server over adb (USB, Wi-Fi or an emulator), the device's H.264 at its native size and + * frame rate into Matroska with the device's timestamps (mkv.ts), and on Android 11 and later its sound as raw PCM, + * encoded to AAC by FFmpeg; + * - AndroidScreenrecord: the fallback when the scrcpy server cannot be had, `screenrecord` on the device (no sound; + * it stops itself after three minutes, so one segment may hold several files), pulled after each segment; + * - Simulator: `xcrun simctl io recordVideo --codec=h264` (the iOS Simulator has no sound capture); + * - AirPlayMirror: FFmpeg's avfoundation screen input cropped to the AirPlay receiver's mirror window. + * The iPhone on USB is recorded by the desktop app's shell and the phone recording file is uploaded; feed.ts takes + * those as finished files. + */ +import { spawn, type ChildProcess } from 'node:child_process' +import { createWriteStream, type WriteStream } from 'node:fs' +import { stat } from 'node:fs/promises' +import type net from 'node:net' +import path from 'node:path' +import { runFor, type AirPlayWindow } from './discover.js' +import { onDevice } from './adb.js' +import { MkvVideoWriter } from './mkv.js' +import { connectFirst, connectNext, DEVICE_JAR, ensureServer, freePort, newScid, readAudioHandshake, serverCommand, socketName, type ByteReader, type Packet } from './scrcpy.js' + +export interface SegmentResult { video: string[]; audio: string[] } + +export interface Producer { + /** True when this source records sound to its own track. */ + readonly audio: boolean + /** Why there is no sound, when audio is false for a source that could have had it. */ + readonly audioNote?: string + /** Start a segment written under `dir` as segment `n`; resolves with the moment (ms, this clock) of its first picture. */ + begin(dir: string, n: number): Promise + /** End the segment; resolves with its finished files. */ + end(): Promise + /** Release everything this source holds. */ + close(): Promise + /** Set when the source stopped by itself. */ + problem?: string +} + +export class ProducerError extends Error { + constructor(readonly status: number, message: string) { + super(message) + } +} + +const FIRST_PICTURE_MS = 20_000 +const QUIT_MS = 8000 + +function exited(proc: ChildProcess): Promise { + return proc.exitCode !== null || proc.signalCode !== null ? Promise.resolve() : new Promise((r) => proc.once('close', () => r())) +} + +async function stopProcess(proc: ChildProcess, how: () => void): Promise { + if (proc.exitCode !== null || proc.signalCode !== null) return + how() + const timer = setTimeout(() => proc.kill('SIGKILL'), QUIT_MS) + await exited(proc) + clearTimeout(timer) +} + +async function nonEmpty(files: string[]): Promise { + const out: string[] = [] + for (const f of files) if (((await stat(f).catch(() => undefined))?.size ?? 0) > 0) out.push(f) + return out +} + +/** The iOS Simulator's own recorder. */ +export class SimulatorProducer implements Producer { + readonly audio = false + readonly audioNote = 'the iOS Simulator records no sound' + private proc: ChildProcess | undefined + private file = '' + problem?: string + + constructor(private readonly udid: string, private readonly clock: () => number = Date.now) { + if (!/^[0-9A-F-]{36}$/i.test(udid)) throw new ProducerError(400, 'not a simulator id') + } + + async begin(dir: string, n: number): Promise { + this.file = path.join(dir, `seg-${n}.mov`) + const proc = spawn('xcrun', ['simctl', 'io', this.udid, 'recordVideo', '--codec=h264', '--force', this.file], { stdio: ['ignore', 'pipe', 'pipe'] }) + this.proc = proc + let said = '' + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new ProducerError(502, 'the Simulator did not start recording')), FIRST_PICTURE_MS) + const look = (d: Buffer): void => { + said = (said + d.toString()).slice(-2000) + if (/recording started/i.test(said)) { clearTimeout(timer); resolve() } + } + proc.stdout!.on('data', look) + proc.stderr!.on('data', look) + proc.once('error', (e) => { clearTimeout(timer); reject(new ProducerError(502, `simctl could not start: ${e.message}`)) }) + proc.once('close', () => { clearTimeout(timer); reject(new ProducerError(502, `simctl stopped: ${said.trim().split('\n').pop() || 'no reason given'}`)) }) + }) + proc.once('close', () => { if (this.proc === proc) this.problem = 'the Simulator stopped recording' }) + return this.clock() + } + + async end(): Promise { + const proc = this.proc + this.proc = undefined + if (proc) await stopProcess(proc, () => proc.kill('SIGINT')) + return { video: await nonEmpty([this.file]), audio: [] } + } + + async close(): Promise { + if (this.proc) await this.end() + } +} + +/** FFmpeg's avfoundation screen input over the display the mirror window is on, cropped to the window. */ +export class AirPlayProducer implements Producer { + readonly audio = false + readonly audioNote = 'the mirror window is recorded as a picture; the phone\'s sound plays through this computer' + private proc: ChildProcess | undefined + private file = '' + problem?: string + + constructor(private readonly ffmpeg: string, private readonly window: AirPlayWindow, private readonly encoder: string, private readonly clock: () => number = Date.now) {} + + async begin(dir: string, n: number): Promise { + this.file = path.join(dir, `seg-${n}.mkv`) + const proc = spawn(this.ffmpeg, airplayArgs(this.window, this.encoder, this.file), { stdio: ['pipe', 'pipe', 'pipe'] }) + this.proc = proc + proc.stdin!.on('error', () => undefined) + let said = '' + proc.stderr!.on('data', (d: Buffer) => { said = (said + d.toString()).slice(-2000) }) + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new ProducerError(502, 'FFmpeg produced no picture of the mirror window')), FIRST_PICTURE_MS) + proc.stdout!.on('data', (d: Buffer) => { if (/frame=[1-9]/.test(d.toString())) { clearTimeout(timer); resolve() } }) + proc.once('error', (e) => { clearTimeout(timer); reject(new ProducerError(502, `FFmpeg could not start: ${e.message}`)) }) + proc.once('close', () => { clearTimeout(timer); reject(new ProducerError(502, `FFmpeg stopped: ${said.trim().split('\n').pop() || 'no reason given'} (FormRec needs Screen Recording permission in System Settings, Privacy and Security)`)) }) + }) + proc.once('close', () => { if (this.proc === proc) this.problem = 'FFmpeg stopped recording the mirror window' }) + return this.clock() + } + + async end(): Promise { + const proc = this.proc + this.proc = undefined + if (proc) await stopProcess(proc, () => proc.stdin!.end('q\n')) + return { video: await nonEmpty([this.file]), audio: [] } + } + + async close(): Promise { + if (this.proc) await this.end() + } +} + +export function airplayArgs(w: AirPlayWindow, encoder: string, out: string): string[] { + const enc = encoder === 'h264_videotoolbox' ? ['-c:v', 'h264_videotoolbox', '-b:v', '12M', '-realtime', '1'] : ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18'] + return [ + '-hide_banner', '-nostats', '-progress', 'pipe:1', '-y', + '-f', 'avfoundation', '-capture_cursor', '0', '-framerate', '30', '-i', `Capture screen ${w.screen}:none`, + '-vf', `crop=${w.crop.width}:${w.crop.height}:${w.crop.x}:${w.crop.y},format=yuv420p`, ...enc, '-f', 'matroska', out, + ] +} + +/** `screenrecord` on the phone, files pulled after each segment. */ +export class ScreenrecordProducer implements Producer { + readonly audio = false + readonly audioNote = 'screenrecord records no sound (the scrcpy server was not available)' + private proc: ChildProcess | undefined + private parts: string[] = [] + private dir = '' + private n = 0 + private ending = false + problem?: string + + constructor(private readonly adb: string, private readonly serial: string, private readonly clock: () => number = Date.now, private readonly run = runFor) {} + + private remote(k: number): string { + return `/sdcard/formrec-seg-${this.n}-${k}.mp4` + } + + private next(): void { + const k = this.parts.length + this.parts.push(this.remote(k)) + const proc = spawn(this.adb, onDevice(this.serial, 'shell', 'screenrecord', '--time-limit', '180', this.remote(k)), { stdio: 'ignore' }) + this.proc = proc + // screenrecord ends itself at its time limit: the segment goes on in a new file. + proc.once('close', () => { if (this.proc === proc && !this.ending) this.next() }) + } + + async begin(dir: string, n: number): Promise { + this.dir = dir + this.n = n + this.parts = [] + this.ending = false + this.next() + await new Promise((r) => setTimeout(r, 800)) + if (this.proc?.exitCode !== null && this.proc?.exitCode !== undefined) throw new ProducerError(502, 'screenrecord did not start on the phone') + return this.clock() - 800 + } + + async end(): Promise { + this.ending = true + const proc = this.proc + this.proc = undefined + if (proc) await stopProcess(proc, () => { void this.run(this.adb, onDevice(this.serial, 'shell', 'pkill', '-2', 'screenrecord')).catch(() => proc.kill('SIGINT')) }) + // The phone finishes writing the file after the signal. + await new Promise((r) => setTimeout(r, 1000)) + const local: string[] = [] + for (const [k, remote] of this.parts.entries()) { + const file = path.join(this.dir, `seg-${this.n}-${k}.mp4`) + await this.run(this.adb, onDevice(this.serial, 'pull', remote, file), 120_000).catch(() => undefined) + await this.run(this.adb, onDevice(this.serial, 'shell', 'rm', '-f', remote)).catch(() => undefined) + local.push(file) + } + return { video: await nonEmpty(local), audio: [] } + } + + async close(): Promise { + if (this.proc) await this.end() + } +} + +/** The scrcpy server: one connection for the whole take, segment files switched on begin and end. */ +export class ScrcpyProducer implements Producer { + audio = false + audioNote?: string + problem?: string + private shell: ChildProcess | undefined + private port = 0 + private sockets: net.Socket[] = [] + private config: Buffer | undefined + private size = { width: 0, height: 0 } + private video: { out: WriteStream; mkv: MkvVideoWriter; file: string; first?: (at: number) => void; inject?: Buffer } | undefined + private sound: { proc: ChildProcess; file: string } | undefined + private closed = false + + constructor( + private readonly adb: string, + private readonly serial: string, + private readonly ffmpeg: string, + private readonly dataDir: string, + private readonly wantAudio: boolean, + private readonly clock: () => number = Date.now, + private readonly run = runFor, + ) {} + + /** Push the server, open the tunnel, start it and read both handshakes. */ + async open(): Promise { + const server = await ensureServer(this.dataDir) + await this.run(this.adb, onDevice(this.serial, 'push', server, DEVICE_JAR), 60_000) + const scid = newScid() + this.port = await freePort() + await this.run(this.adb, onDevice(this.serial, 'forward', `tcp:${this.port}`, socketName(scid))) + let said = '' + const shell = spawn(this.adb, onDevice(this.serial, 'shell', ...serverCommand({ scid, audio: this.wantAudio })), { stdio: ['ignore', 'pipe', 'pipe'] }) + this.shell = shell + const keep = (d: Buffer): void => { said = (said + d.toString()).slice(-4000) } + shell.stdout!.on('data', keep) + shell.stderr!.on('data', keep) + shell.once('close', () => { if (!this.closed) this.problem = `the scrcpy server stopped: ${lastError(said)}` }) + try { + const first = await connectFirst(this.port) + this.sockets.push(first.socket) + if (first.meta.codec !== 'h264') throw new ProducerError(502, `the phone sent ${first.meta.codec}, not H.264`) + this.size = { width: first.meta.width, height: first.meta.height } + if (this.wantAudio) { + const next = await connectNext(this.port) + this.sockets.push(next.socket) + const audio = await readAudioHandshake(next.reader) + if ('none' in audio) this.audioNote = audio.none + else if (audio.codec !== 'raw') this.audioNote = `the phone sent ${audio.codec} sound, not raw PCM` + else this.audio = true + void this.pump(next.reader, (p) => this.onAudio(p)) + } + void this.pump(first.reader, (p) => this.onVideo(p)) + } catch (error) { + await this.close() + throw error instanceof ProducerError ? error : new ProducerError(502, `${(error as Error).message}${said ? ` (${lastError(said)})` : ''}`) + } + } + + private async pump(reader: ByteReader, take: (p: Packet) => void): Promise { + try { + for (;;) take(await reader.packet()) + } catch (error) { + if (!this.closed) this.problem = `the phone stopped sending: ${(error as Error).message}` + } + } + + private onVideo(p: Packet): void { + if (p.config) { + // A new config mid-segment (the phone rotated, the encoder restarted): its parameter sets go in band before the next frame. + if (this.video && this.config && !this.config.equals(p.data)) this.video.inject = p.data + this.config = p.data + return + } + const v = this.video + if (!v || !this.config) return + const data = v.inject ? Buffer.concat([v.inject, p.data]) : p.data + if (v.inject && p.key) v.inject = undefined + if (v.mkv.frame(this.config, p.ptsUs ?? 0, p.key, data) && v.first) { + v.first(this.clock()) + v.first = undefined + } + } + + private onAudio(p: Packet): void { + // Sound is kept from the segment's first picture on, so the two tracks start together. + if (p.config || !this.sound || !this.video || this.video.first) return + this.sound.proc.stdin!.write(p.data) + } + + async begin(dir: string, n: number): Promise { + const file = path.join(dir, `seg-${n}.mkv`) + const out = createWriteStream(file, { mode: 0o600 }) + const at = new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new ProducerError(502, 'the phone sent no picture (unlock it and keep the screen on)')), FIRST_PICTURE_MS) + this.video = { out, file, mkv: new MkvVideoWriter((b) => out.write(b), this.size), first: (t) => { clearTimeout(timer); resolve(t) } } + }) + if (this.audio) { + const audioFile = path.join(dir, `seg-${n}.mka`) + const proc = spawn(this.ffmpeg, ['-hide_banner', '-v', 'error', '-y', '-f', 's16le', '-ar', '48000', '-ac', '2', '-i', 'pipe:0', '-c:a', 'aac', '-b:a', '192k', '-f', 'matroska', audioFile], { stdio: ['pipe', 'ignore', 'ignore'] }) + proc.stdin!.on('error', () => undefined) + this.sound = { proc, file: audioFile } + } + return at + } + + async end(): Promise { + const v = this.video + const s = this.sound + this.video = undefined + this.sound = undefined + const result: SegmentResult = { video: [], audio: [] } + if (v) { + await new Promise((r) => v.out.end(() => r())) + if (v.mkv.wrote) result.video.push(v.file) + } + if (s) { + await stopProcess(s.proc, () => s.proc.stdin!.end()) + result.audio.push(...(await nonEmpty([s.file]))) + } + return result + } + + async close(): Promise { + if (this.closed) return + this.closed = true + if (this.video || this.sound) await this.end().catch(() => undefined) + for (const s of this.sockets) s.destroy() + const shell = this.shell + if (shell) await stopProcess(shell, () => shell.kill('SIGTERM')) + if (this.port) await this.run(this.adb, onDevice(this.serial, 'forward', '--remove', `tcp:${this.port}`)).catch(() => undefined) + } +} + +function lastError(text: string): string { + const lines = text.trim().split('\n').map((l) => l.trim()).filter(Boolean) + return (lines.reverse().find((l) => /error|exception|denied/i.test(l)) ?? lines[0] ?? 'no reason given').slice(0, 300) +} + +/** h264_videotoolbox when FFmpeg has it (macOS), else libx264. */ +export async function pickEncoder(ffmpeg: string): Promise { + const list = await runFor(ffmpeg, ['-hide_banner', '-encoders'], 10_000).catch(() => '') + return /\bh264_videotoolbox\b/.test(list) ? 'h264_videotoolbox' : 'libx264' +} diff --git a/src/features/phone/routes.ts b/src/features/phone/routes.ts new file mode 100644 index 0000000..9ea19fe --- /dev/null +++ b/src/features/phone/routes.ts @@ -0,0 +1,128 @@ +/** + * The phone capture routes on the loopback server (behind the run's token), issue #7: + * GET /api/phone/sources what can be recorded here: Android devices and emulators (adb), + * booted iOS Simulators, AirPlay mirror windows, and what is missing + * POST /api/phone/feed/start { sessionId, source } the phone becomes the take's picture (feed.ts) + * POST /api/phone/feed/begin { sessionId } the shell started recording the iPhone: its tracks start now + * POST /api/phone/feed/pause | resume { sessionId } + * POST /api/phone/feed/stop { sessionId, durationMs? } -> { durationMs, tracks, notes } + * GET /api/phone/feed?sessionId= the feed's state + * POST /api/phone/files?name= a phone recording to narrate over (files.ts) + * GET /api/phone/files/:id | DELETE it, for the stage | gone + * POST /api/phone/recordings/:id/export { layout } a portrait or framed copy of a phone take (export.ts) + * GET /api/phone/recordings/:id/export/:layout that copy, as a download + */ +import type { IncomingMessage, ServerResponse } from 'node:http' +import { stat } from 'node:fs/promises' +import { z } from 'zod' +import { readJsonBody, sendFile } from '../../server/files.js' +import { sendJson } from '../../server/http.js' +import type { FeatureContext } from '../types.js' +import { adbHowTo, findAdb, findPhoneFfmpeg, listAirPlay, listAndroid, listSimulators } from './discover.js' +import { PhoneFeed, PhoneFeedError, PhoneSourceSchema, probeMs } from './feed.js' +import { FILE_ID, PhoneFileError, phoneFilePath, receivePhoneFile, removePhoneFile } from './files.js' +import { SCRCPY_VERSION } from './scrcpy.js' +import { exportFile, exportPhoneTake, ExportError, LAYOUTS } from './export.js' + +const SESSION_ID = /^[a-z0-9][a-z0-9-]{0,80}$/ +const SessionSchema = z.object({ sessionId: z.string().regex(SESSION_ID) }) +const StartSchema = SessionSchema.extend({ source: PhoneSourceSchema }) +const StopSchema = SessionSchema.extend({ durationMs: z.number().min(0).max(12 * 3_600_000).optional() }) +const ExportSchema = z.object({ layout: z.enum(LAYOUTS) }) + +let feed: PhoneFeed | undefined + +export function feedFor(ctx: FeatureContext): PhoneFeed { + feed ??= new PhoneFeed({ port: () => ctx.port(), token: ctx.token, dataDir: ctx.dataDir }) + return feed +} + +export async function stopFeed(): Promise { + const running = feed + feed = undefined + await running?.stopAll() +} + +async function json(req: IncomingMessage, schema: z.ZodType): Promise { + const parsed = schema.safeParse(await readJsonBody(req)) + if (!parsed.success) throw new PhoneFeedError(400, parsed.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; ')) + return parsed.data +} + +export async function sourcesView(platform: NodeJS.Platform = process.platform) { + const [adb, ffmpeg] = await Promise.all([findAdb(), findPhoneFfmpeg()]) + const [android, simulators, airplay] = await Promise.all([listAndroid(adb), listSimulators(platform), listAirPlay(platform)]) + return { + platform, + adb: { found: Boolean(adb), howTo: adb ? '' : adbHowTo(platform) }, + ffmpeg: Boolean(ffmpeg), + scrcpy: SCRCPY_VERSION, + android, + simulators, + airplay: airplay.map((w) => ({ id: w.id, owner: w.owner, width: w.crop.width, height: w.crop.height })), + } +} + +async function answer(res: ServerResponse, work: () => Promise): Promise { + try { + sendJson(res, 200, await work()) + } catch (error) { + const status = error instanceof PhoneFeedError || error instanceof PhoneFileError || error instanceof ExportError ? error.status : 500 + sendJson(res, status || 502, { error: (error as Error).message }) + } + return true +} + +export function phoneRoutes(ctx: FeatureContext) { + return async (req: IncomingMessage, res: ServerResponse, parts: string[], url: URL): Promise => { + if (parts[1] !== 'phone' || parts.length < 3) return false + const method = req.method ?? 'GET' + const [, , area, a, b, c] = parts + if (area === 'sources' && parts.length === 3 && method === 'GET') return answer(res, () => sourcesView()) + if (area === 'feed') { + const running = feedFor(ctx) + if (parts.length === 3 && method === 'GET') { + const id = url.searchParams.get('sessionId') ?? '' + return answer(res, async () => ({ feed: SESSION_ID.test(id) ? running.status(id) ?? null : null, active: running.active() })) + } + if (parts.length !== 4 || method !== 'POST') return false + if (a === 'start') return answer(res, async () => { const i = await json(req, StartSchema); return running.start(i.sessionId, i.source) }) + if (a === 'begin') return answer(res, async () => running.begin((await json(req, SessionSchema)).sessionId)) + if (a === 'pause') return answer(res, async () => running.pause((await json(req, SessionSchema)).sessionId)) + if (a === 'resume') return answer(res, async () => running.resume((await json(req, SessionSchema)).sessionId)) + if (a === 'stop') return answer(res, async () => { const i = await json(req, StopSchema); return running.stop(i.sessionId, { durationMs: i.durationMs }) }) + return false + } + if (area === 'files') { + if (parts.length === 3 && method === 'POST') { + return answer(res, async () => { + const name = (url.searchParams.get('name') ?? 'Phone recording').replace(/[\u0000-\u001f]/g, '').slice(0, 200) + const got = await receivePhoneFile(ctx.dataDir, req) + const ffmpeg = await findPhoneFfmpeg() + const durationMs = ffmpeg ? await probeMs(ffmpeg, got.file) : undefined + return { id: got.id, name, bytes: got.bytes, ...(durationMs !== undefined ? { durationMs } : {}) } + }) + } + if (parts.length !== 4 || !a || !FILE_ID.test(a)) return false + if (method === 'GET') { + await sendFile(req, res, phoneFilePath(ctx.dataDir, a), 'video/mp4') + return true + } + if (method === 'DELETE') return answer(res, async () => { await removePhoneFile(ctx.dataDir, a); return { removed: a } }) + return false + } + if (area === 'recordings' && a && /^[a-z0-9][a-z0-9-]{0,80}$/.test(a) && b === 'export') { + if (parts.length === 5 && method === 'POST') { + return answer(res, async () => exportPhoneTake(ctx.library, a, (await json(req, ExportSchema)).layout)) + } + if (parts.length === 6 && method === 'GET' && c && (LAYOUTS as readonly string[]).includes(c)) { + const file = exportFile(ctx.library, a, c as (typeof LAYOUTS)[number]) + if (!(await stat(file).catch(() => undefined))) { sendJson(res, 404, { error: 'make the export first' }); return true } + res.setHeader('Content-Disposition', `attachment; filename="phone-${c}.mp4"`) + await sendFile(req, res, file, 'video/mp4') + return true + } + } + return false + } +} diff --git a/src/features/phone/scrcpy.ts b/src/features/phone/scrcpy.ts new file mode 100644 index 0000000..7c49b79 --- /dev/null +++ b/src/features/phone/scrcpy.ts @@ -0,0 +1,238 @@ +/** + * Android screen and sound through the scrcpy server (Genymobile/scrcpy, Apache-2.0), against one pinned version. + * FormRec does not bundle the server: it downloads the release asset once, at first use, into /phone/scrcpy/ + * and accepts it only when its SHA-256 is the one below (the value scrcpy publishes with the release). The client + * side is written here from scrcpy's doc/develop.md for that version: + * adb push /data/local/tmp/formrec-scrcpy.jar + * adb forward tcp: localabstract:scrcpy_ + * adb shell CLASSPATH=... app_process / com.genymobile.scrcpy.Server 3.3.1 scid= tunnel_forward=true ... + * then a video socket and an audio socket are opened, in that order. On the first one the device sends a dummy byte + * (forward tunnel) and its name (64 bytes); each socket then sends its codec metadata (video: codec id, width, height, + * 12 bytes; audio: codec id, 4 bytes, where 0 means the device has no audio capture, Android 10 and earlier, and 1 + * that it failed), then packets, each behind a 12-byte header: a u64 whose top bit marks a config packet, the next a + * key frame, the rest the PTS in microseconds, and a u32 size. Control is off: FormRec only records. + */ +import { createHash, randomInt } from 'node:crypto' +import { createWriteStream } from 'node:fs' +import { mkdir, readFile, rename, rm } from 'node:fs/promises' +import net from 'node:net' +import path from 'node:path' +import { Readable } from 'node:stream' +import { pipeline } from 'node:stream/promises' + +export const SCRCPY_VERSION = '3.3.1' +export const SCRCPY_SERVER_URL = `https://github.com/Genymobile/scrcpy/releases/download/v${SCRCPY_VERSION}/scrcpy-server-v${SCRCPY_VERSION}` +export const SCRCPY_SERVER_SHA256 = 'a0f70b20aa4998fbf658c94118cd6c8dab6abbb0647a3bdab344d70bc1ebcbb8' +export const DEVICE_JAR = '/data/local/tmp/formrec-scrcpy.jar' +/** The server is about 90 KB; anything much larger is not it. */ +const SERVER_MAX_BYTES = 4 * 1024 * 1024 + +export const CODEC = { h264: 0x68323634, h265: 0x68323635, av1: 0x61763031, opus: 0x6f707573, aac: 0x00616163, flac: 0x666c6163, raw: 0x00726177 } as const +export const AUDIO_DISABLED = 0 +export const AUDIO_FAILED = 1 +export const DEVICE_NAME_BYTES = 64 +export const HEADER_BYTES = 12 +const FLAG_CONFIG = 1n << 63n +const FLAG_KEY = 1n << 62n +const PTS_MASK = FLAG_KEY - 1n +/** A packet larger than this is a broken stream, not a picture. */ +export const PACKET_LIMIT = 32 * 1024 * 1024 + +export interface Packet { + config: boolean + key: boolean + /** Microseconds, from the device's encoder; undefined for config packets. */ + ptsUs?: number + data: Buffer +} + +export function parseHeader(head: Buffer): { config: boolean; key: boolean; ptsUs: number; size: number } { + if (head.length < HEADER_BYTES) throw new Error('a frame header is 12 bytes') + const word = head.readBigUInt64BE(0) + const size = head.readUInt32BE(8) + return { config: (word & FLAG_CONFIG) !== 0n, key: (word & FLAG_KEY) !== 0n, ptsUs: Number(word & PTS_MASK), size } +} + +export function frameHeader(p: { config?: boolean; key?: boolean; ptsUs?: number; size: number }): Buffer { + const head = Buffer.alloc(HEADER_BYTES) + let word = BigInt(p.ptsUs ?? 0) & PTS_MASK + if (p.config) word |= FLAG_CONFIG + if (p.key) word |= FLAG_KEY + head.writeBigUInt64BE(word, 0) + head.writeUInt32BE(p.size, 8) + return head +} + +/** The device name: NUL-padded UTF-8 in 64 bytes. */ +export function deviceName(raw: Buffer): string { + const end = raw.indexOf(0) + return raw.subarray(0, end < 0 ? raw.length : end).toString('utf8').replace(/[\u0000-\u001f]/g, '').slice(0, 63) +} + +export function codecName(id: number): string { + const found = Object.entries(CODEC).find(([, v]) => v === id) + return found ? found[0] : `0x${id.toString(16)}` +} + +export interface ServerOptions { + scid: string + audio: boolean + /** Longest side in pixels; 0 keeps the device's native size. */ + maxSize?: number + maxFps?: number +} + +/** A scid is 31 random bits, written as eight hex digits (the server reads it in base 16). */ +export function newScid(): string { + return randomInt(1, 0x7fffffff).toString(16).padStart(8, '0') +} + +/** The shell command that starts the pinned server: H.264 video, raw 48 kHz stereo PCM sound, no control. */ +export function serverCommand(o: ServerOptions): string[] { + if (!/^[0-9a-f]{8}$/.test(o.scid)) throw new Error('scid must be eight hex digits') + return [ + `CLASSPATH=${DEVICE_JAR}`, 'app_process', '/', 'com.genymobile.scrcpy.Server', SCRCPY_VERSION, + `scid=${o.scid}`, 'log_level=info', 'tunnel_forward=true', 'control=false', 'cleanup=true', + 'video_codec=h264', 'video_codec_options=i-frame-interval=1', + `audio=${o.audio ? 'true' : 'false'}`, ...(o.audio ? ['audio_codec=raw'] : []), + `max_size=${Math.max(0, Math.floor(o.maxSize ?? 0))}`, ...(o.maxFps ? [`max_fps=${Math.floor(o.maxFps)}`] : []), + 'stay_awake=true', 'power_off_on_close=false', + ] +} + +export const socketName = (scid: string): string => `localabstract:scrcpy_${scid}` + +/** Reads exact byte counts from a stream; a read past the end rejects. */ +export class ByteReader { + private chunks: Buffer[] = [] + private held = 0 + private ended = false + private failure: Error | undefined + private wake: (() => void) | undefined + + constructor(stream: NodeJS.ReadableStream) { + stream.on('data', (d: Buffer) => { this.chunks.push(d); this.held += d.length; this.poke() }) + stream.on('end', () => { this.ended = true; this.poke() }) + stream.on('close', () => { this.ended = true; this.poke() }) + stream.on('error', (e: Error) => { this.failure = e; this.poke() }) + } + + private poke(): void { + const wake = this.wake + this.wake = undefined + wake?.() + } + + async take(n: number): Promise { + while (this.held < n) { + if (this.failure) throw this.failure + if (this.ended) throw new Error(this.held === 0 ? 'the stream closed' : 'the stream closed in the middle of a packet') + await new Promise((resolve) => { this.wake = resolve }) + } + const all = this.chunks.length === 1 ? this.chunks[0]! : Buffer.concat(this.chunks) + const out = all.subarray(0, n) + const rest = all.subarray(n) + this.chunks = rest.length ? [rest] : [] + this.held = rest.length + return out + } + + async packet(): Promise { + const head = parseHeader(await this.take(HEADER_BYTES)) + if (head.size > PACKET_LIMIT) throw new Error(`a ${head.size}-byte packet is not a picture`) + const data = await this.take(head.size) + return { config: head.config, key: head.key, ...(head.config ? {} : { ptsUs: head.ptsUs }), data } + } +} + +export interface VideoMeta { name: string; codec: string; width: number; height: number } + +/** The first socket: the dummy byte, the device name, the video codec metadata. */ +export async function readVideoHandshake(r: ByteReader): Promise { + await r.take(1) + const name = deviceName(await r.take(DEVICE_NAME_BYTES)) + const meta = await r.take(12) + return { name, codec: codecName(meta.readUInt32BE(0)), width: meta.readUInt32BE(4), height: meta.readUInt32BE(8) } +} + +/** The audio socket's codec id: 'raw', or why there is no sound. */ +export async function readAudioHandshake(r: ByteReader): Promise<{ codec: string } | { none: string }> { + const id = (await r.take(4)).readUInt32BE(0) + if (id === AUDIO_DISABLED) return { none: 'this phone cannot share its sound (Android 11 or later is needed)' } + if (id === AUDIO_FAILED) return { none: 'the phone could not start sound capture' } + return { codec: codecName(id) } +} + +/** The pinned server, downloaded once and checked; a file that does not match is removed and refused. */ +export async function ensureServer(dataDir: string, fetcher: typeof fetch = fetch): Promise { + const dir = path.join(dataDir, 'phone', 'scrcpy') + const file = path.join(dir, `scrcpy-server-v${SCRCPY_VERSION}`) + const have = await readFile(file).catch(() => undefined) + if (have && sha256(have) === SCRCPY_SERVER_SHA256) return file + await mkdir(dir, { recursive: true, mode: 0o700 }) + const part = `${file}.part` + const res = await fetcher(SCRCPY_SERVER_URL, { redirect: 'follow' }) + if (!res.ok || !res.body) throw new Error(`the scrcpy server could not be downloaded (HTTP ${res.status})`) + const declared = Number(res.headers.get('content-length') ?? 0) + if (declared > SERVER_MAX_BYTES) throw new Error('the scrcpy server download is larger than expected') + await pipeline(Readable.fromWeb(res.body as import('node:stream/web').ReadableStream), createWriteStream(part, { mode: 0o600 })) + const got = await readFile(part) + if (got.length > SERVER_MAX_BYTES || sha256(got) !== SCRCPY_SERVER_SHA256) { + await rm(part, { force: true }) + throw new Error('the downloaded scrcpy server does not match its published SHA-256; it was not used') + } + await rename(part, file) + return file +} + +export function sha256(data: Buffer): string { + return createHash('sha256').update(data).digest('hex') +} + +/** A free loopback port for the adb forward. */ +export function freePort(): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer() + srv.once('error', reject) + srv.listen(0, '127.0.0.1', () => { + const port = (srv.address() as net.AddressInfo).port + srv.close(() => resolve(port)) + }) + }) +} + +/** + * Connect to the forwarded port until the server answers. adb accepts a forward connection before the device side + * listens and then closes it, so a socket that closes without its first byte is tried again. + */ +export async function connectFirst(port: number, deadlineMs = 10_000, sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))): Promise<{ socket: net.Socket; reader: ByteReader; meta: VideoMeta }> { + const until = Date.now() + deadlineMs + let last: Error = new Error('the phone did not answer') + while (Date.now() < until) { + const socket = await new Promise((resolve) => { + const s = net.connect(port, '127.0.0.1') + s.once('connect', () => resolve(s)) + s.once('error', (e) => { last = e; resolve(undefined) }) + }) + if (socket) { + const reader = new ByteReader(socket) + try { + return { socket, reader, meta: await readVideoHandshake(reader) } + } catch (error) { + last = error as Error + socket.destroy() + } + } + await sleep(200) + } + throw new Error(`the scrcpy server did not start on the phone: ${last.message}`) +} + +export async function connectNext(port: number): Promise<{ socket: net.Socket; reader: ByteReader }> { + const socket = await new Promise((resolve, reject) => { + const s = net.connect(port, '127.0.0.1') + s.once('connect', () => resolve(s)) + s.once('error', reject) + }) + return { socket, reader: new ByteReader(socket) } +} diff --git a/src/features/studio/index.ts b/src/features/studio/index.ts index 08a8938..a59f756 100644 --- a/src/features/studio/index.ts +++ b/src/features/studio/index.ts @@ -10,6 +10,8 @@ * DELETE /api/studio/takes/:id/trims restore every trimmed range * GET /api/studio/takes/:id/preview the take's lead track as written so far (Live Rewind's look back; ?token=) * POST /api/studio/takes/:id/camera { on } the camera turned on or off now, on the take's timeline + * POST /api/studio/takes/:id/master ?seq=n, body = WAV bytes: the Voice master, in order like a track's chunks (src/studio/master.ts) + * POST /api/studio/takes/:id/master/end { durationMs } the master is complete: its sizes are written * GET /api/studio/screenshots the screenshots, newest first * POST /api/studio/screenshots?title=&source= body = PNG bytes -> the screenshot * GET /api/studio/screenshots/:id one screenshot's details @@ -17,7 +19,14 @@ * PATCH /api/studio/screenshots/:id { title } * DELETE /api/studio/screenshots/:id * - * MCP: formrec_studio_state, formrec_unsaved_takes, formrec_recover_take, formrec_discard_take. + * GET /api/studio/devices the microphone and camera names the studio last found (labels only) + * PUT /api/studio/devices { mics, cameras, cameraInUse, permission, text, requestId? } the studio's report + * POST /api/studio/devices/refresh { askPermission? } ask the open studio to rebuild its lists + * GET /api/studio/devices/request the refresh request still waiting (the studio polls it), or {} + * + * The master is served with the recording as master-host-mic.wav (`files`). + * + * MCP: formrec_studio_state, formrec_studio_refresh_devices, formrec_unsaved_takes, formrec_recover_take, formrec_discard_take. */ import type { IncomingMessage, ServerResponse } from 'node:http' import { z } from 'zod' @@ -30,6 +39,10 @@ import { BadId, type Library } from '../../store/library.js' import { addTrim, MetaInputSchema, mergeRanges, StudioMetaSchema, LAYOUTS, QUALITIES, TARGETS, type StudioMeta } from '../../studio/meta.js' import { NewShotSchema, Screenshots, SHOT_LIMIT, ShotError } from '../../studio/screenshots.js' import { recoverSession } from '../../studio/recover.js' +import { Masters } from '../../studio/master.js' +import { EndTrackSchema } from '../../model/session.js' +import { seqOf } from '../../server/studio-routes.js' +import { DevicesReportSchema, pendingRequest, readReport, RefreshInputSchema, requestRefresh, writeReport, writeRequest } from '../../studio/devices.js' const ID = 'studio' @@ -117,6 +130,7 @@ async function readBody(req: IncomingMessage, limit: number): Promise { function routes(ctx: FeatureContext) { const sessions = new Sessions(ctx.library) const shots = new Screenshots(ctx.dataDir) + const masters = new Masters(sessions) return async (req: IncomingMessage, res: ServerResponse, parts: string[], url: URL): Promise => { if (parts[1] !== ID) return false const [, , what, id, sub] = parts @@ -133,6 +147,26 @@ function routes(ctx: FeatureContext) { return true } } + if (what === 'devices') { + if (!id && method === 'GET') { + sendJson(res, 200, (await readReport(ctx.dataDir)) ?? {}) + return true + } + if (!id && method === 'PUT') { + const input = DevicesReportSchema.parse(await readJsonBody(req, 32 * 1024)) + sendJson(res, 200, await writeReport(ctx.dataDir, input, ctx.now())) + return true + } + if (id === 'request' && !sub && method === 'GET') { + sendJson(res, 200, (await pendingRequest(ctx.dataDir, ctx.now())) ?? {}) + return true + } + if (id === 'refresh' && !sub && method === 'POST') { + const { askPermission } = RefreshInputSchema.parse(await readJsonBody(req, 4096)) + sendJson(res, 200, await writeRequest(ctx.dataDir, askPermission, ctx.now())) + return true + } + } if (what === 'unsaved' && !id && method === 'GET') { sendJson(res, 200, { takes: await sessions.list() }) return true @@ -166,6 +200,15 @@ function routes(ctx: FeatureContext) { await sendFile(req, res, ctx.library.trackFile(id, lead.id, lead.format), lead.format === 'mp4' ? 'video/mp4' : 'video/webm') return true } + if (sub === 'master' && method === 'POST' && !parts[5]) { + sendJson(res, 200, await masters.append(id, seqOf(url), req)) + return true + } + if (sub === 'master' && parts[5] === 'end' && method === 'POST') { + const { durationMs } = EndTrackSchema.parse(await readJsonBody(req, 4096)) + sendJson(res, 200, await masters.end(id, durationMs)) + return true + } if (sub === 'camera' && method === 'POST') { const { on } = CameraSchema.parse(await readJsonBody(req, 4096)) sendJson(res, 200, await recordCamera(sessions, id, on)) @@ -204,7 +247,8 @@ function routes(ctx: FeatureContext) { } return false } catch (error) { - sendJson(res, statusOf(error), { error: (error as Error).message }) + // A chunk route's refusal carries what the uploader needs (the chunk expected, or that it is final). + sendJson(res, statusOf(error), { error: (error as Error).message, ...(error instanceof SessionError ? error.extra : {}) }) return true } } @@ -222,6 +266,7 @@ async function reply(work: () => Promise): Promise { export const feature: Feature = { id: ID, routes, + files: /^master-host-mic\.wav$/, mcp(server, deps) { const sessions = new Sessions(deps.library) server.registerTool( @@ -234,9 +279,20 @@ export const feature: Feature = { }, () => reply(async () => { const live = (await readFeatureJson(deps.dataDir, ID, 'state', LiveStateSchema)) ?? { state: 'idle' } - return { ...live, unsaved: (await sessions.list()).length } + const devices = await readReport(deps.dataDir).catch(() => undefined) + return { ...live, unsaved: (await sessions.list()).length, ...(devices ? { devices } : {}) } }), ) + server.registerTool( + 'formrec_studio_refresh_devices', + { + title: 'Refresh the studio devices', + description: 'Rebuild the open studio\'s microphone and camera lists (after a device is plugged in, or when they show generic names such as "Microphone 1") and return what it found: the names, which one is chosen, and whether the browser still needs permission. The studio must be open on this computer. askPermission: true lets the studio briefly ask the person for microphone (and camera, when the layout uses it) permission so real names appear; nothing is recorded and the devices are released at once. Without it, a list that needs permission is reported as permission: needed.', + inputSchema: { askPermission: z.boolean().optional().describe('briefly ask the person for permission when the names are hidden (default false)') }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + }, + (input, extra) => reply(() => requestRefresh(deps.dataDir, { askPermission: input.askPermission }, { signal: extra?.signal })), + ) server.registerTool( 'formrec_unsaved_takes', { diff --git a/src/features/types.ts b/src/features/types.ts index a4084f6..f976266 100644 --- a/src/features/types.ts +++ b/src/features/types.ts @@ -56,7 +56,10 @@ export interface FeatureContext { codebase?: { root: string; repoUrl?: string } } -/** What MCP tools get: the library, and a function for player links on the running server (see store/server-file.ts). */ +/** + * What MCP tools get: the library, and a function for player links on the running server (see store/server-file.ts). + * The base carries no run token; buildServer gives each `#/f/` in an answer that recording's player key. + */ export interface FeatureMcpDeps { library: Library dataDir: string diff --git a/src/mcp/player-links.ts b/src/mcp/player-links.ts new file mode 100644 index 0000000..051a55c --- /dev/null +++ b/src/mcp/player-links.ts @@ -0,0 +1,56 @@ +/** + * Player links in what FormRec hands out (MCP answers and the command line's JSON). Tools build links on the player + * base, `#/f/`; this is the one place those links get their form: the base's query is dropped (so no run + * token can ride along, whatever base a caller gave), and a link to a recording's player gets that recording's player + * key (server/player-link.ts), which opens that player and nothing else. Other links on the base (#/demo/, #/edit/) + * keep their route with no secret: a demo needs none, and the other views open only in the owner's own window. + */ +import { playerKey } from '../server/player-link.js' +import type { ToolReply } from './reply.js' + +const RECORDING = /^#\/f\/([a-z0-9][a-z0-9-]{0,80})/ + +function escape(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** Every link on `base` in `text`, as a link with no run token (and a player key for a recording's player). */ +export async function keyLinksIn(text: string, base: string, dataDir: string): Promise { + if (!text.includes(base)) return text + const origin = new URL(base).origin + const found = new RegExp(`${escape(base)}(#[^\\s"'<>]*)?`, 'g') + const out: string[] = [] + let last = 0 + for (const match of text.matchAll(found)) { + const hash = match[1] ?? '' + const id = RECORDING.exec(hash)?.[1] + const key = id ? await playerKey(dataDir, id).catch(() => undefined) : undefined + // No key (the data folder cannot hold the secret): the link keeps its route and no secret, and the answer still arrives. + const keyed = key ? `${origin}/?player=${key}${hash}` : `${origin}/${hash}` + out.push(text.slice(last, match.index), keyed) + last = match.index + match[0].length + } + out.push(text.slice(last)) + return out.join('') +} + +/** A JSON value with every string's links keyed (a new value; the one given is not changed). */ +export async function keyLinks(value: T, base: string | undefined, dataDir: string): Promise { + if (!base) return value + const walk = async (v: unknown): Promise => { + if (typeof v === 'string') return keyLinksIn(v, base, dataDir) + if (Array.isArray(v)) return Promise.all(v.map(walk)) + if (v && typeof v === 'object') { + const entries = await Promise.all(Object.entries(v).map(async ([k, x]) => [k, await walk(x)] as const)) + return Object.fromEntries(entries) + } + return v + } + return (await walk(value)) as T +} + +/** A tool reply with its links keyed: the text blocks and the structured value, the same way. */ +export async function keyReply(reply: ToolReply, base: () => Promise, dataDir: string): Promise { + if (!JSON.stringify(reply).includes('#/')) return reply + return keyLinks(reply, await base(), dataDir) +} diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 3ebfdbe..f6320ed 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -16,7 +16,8 @@ import { validateTool, type ToolDeps, } from './tools.js' -import { DESTRUCTIVE, OPEN_WORLD, READ_ONLY, UPDATES, reply } from './reply.js' +import { DESTRUCTIVE, OPEN_WORLD, READ_ONLY, UPDATES, reply, type ToolReply } from './reply.js' +import { keyReply } from './player-links.js' import { DeleteOutput, DemosOutput, FormcutOutput, GetOutput, ListOutput, RecordOutput, RenameOutput, ValidateOutput } from './schemas.js' import { FEATURES } from '../features/index.js' @@ -69,8 +70,12 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {} const server = new McpServer({ name: 'formrec', version }) const registered = new Map() const register = server.registerTool.bind(server) + const base = (): Promise => resolvePlayerBase(deps.playerBase) server.registerTool = ((name: string, ...rest: unknown[]) => { - const tool = (register as (n: string, ...r: unknown[]) => RegisteredTool)(name, ...rest) + // Every answer's player links get their form in one place (player-links.ts): no run token, a player key per recording. + const handler = rest[rest.length - 1] as (...args: unknown[]) => unknown + const keyed = async (...args: unknown[]): Promise => keyReply((await handler(...args)) as ToolReply, base, deps.library.dataDir) + const tool = (register as (n: string, ...r: unknown[]) => RegisteredTool)(name, ...rest.slice(0, -1), keyed) registered.set(name, tool) return tool }) as typeof server.registerTool @@ -217,7 +222,7 @@ export function buildServer(deps: ToolDeps, version: string, tools: ToolSet = {} } } // Each feature registers its own tools (src/features//index.ts `mcp`). - const featureDeps = { library: deps.library, dataDir: deps.library.dataDir, playerBase: () => resolvePlayerBase(deps.playerBase) } + const featureDeps = { library: deps.library, dataDir: deps.library.dataDir, playerBase: base } for (const feature of FEATURES) if (!tools.features || tools.features.includes(feature.id)) feature.mcp?.(server, featureDeps) const refused = new Map() for (const [name, tool] of registered) { diff --git a/src/model/capture.ts b/src/model/capture.ts new file mode 100644 index 0000000..5232182 --- /dev/null +++ b/src/model/capture.ts @@ -0,0 +1,68 @@ +/** + * How a studio take was captured, kept in recording.json as `capture`: the microphone preset, the quality asked for, + * what the browser reported it applied to each track (MediaStreamTrack.getSettings(), known keys only), whether the + * microphone went through the Effects chain, the room tone at the start, the lossless master beside the Opus track, + * and the clips counted while recording with their take times. The client sends it with Save; the server fills the + * master from the file it holds, never from the client's word (src/studio/finish.ts). + */ +import { z } from 'zod' + +export const TrackSettingsSchema = z.object({ + width: z.number().optional(), + height: z.number().optional(), + frameRate: z.number().optional(), + aspectRatio: z.number().optional(), + sampleRate: z.number().optional(), + sampleSize: z.number().optional(), + channelCount: z.number().optional(), + latency: z.number().optional(), + echoCancellation: z.boolean().optional(), + noiseSuppression: z.boolean().optional(), + autoGainControl: z.boolean().optional(), + displaySurface: z.string().max(40).optional(), + facingMode: z.string().max(40).optional(), + resizeMode: z.string().max(40).optional(), +}) + +export const CaptureTrackSchema = z.object({ + kind: z.enum(['screen', 'camera', 'mic', 'system']), + label: z.string().max(200), + settings: TrackSettingsSchema, +}) + +export const MasterSchema = z.object({ + file: z.literal('master-host-mic.wav'), + sampleRate: z.number().int().min(8000).max(192_000), + bitsPerSample: z.number().int(), + channels: z.number().int().min(1).max(2), + bytes: z.number().int().min(0), + durationMs: z.number().min(0), + /** False when the take ended before the master's last chunk arrived (a crash, a closed tab). */ + complete: z.boolean(), +}) + +export const ClipSchema = z.object({ atMs: z.number().min(0), peakDb: z.number() }) + +export const LevelCheckSchema = z.object({ + peakDb: z.number().nullable(), + maxDb: z.number().nullable(), + clips: z.number().int().min(0), + advice: z.enum(['up', 'down', 'ok', 'silent']), + byDb: z.number(), +}) + +export const CaptureSchema = z.object({ + preset: z.enum(['standard', 'voice-master']), + requested: z.object({ quality: z.string().max(20), width: z.number().int().min(0), height: z.number().int().min(0) }), + tracks: z.array(CaptureTrackSchema).max(12), + micEffects: z.boolean().default(false), + roomToneMs: z.number().min(0).max(60_000).optional(), + master: MasterSchema.optional(), + levels: z.object({ clips: z.array(ClipSchema).max(5000), check: LevelCheckSchema.optional() }).optional(), +}) + +/** What Save may carry: everything but the master, which the server reads from its own file. */ +export const CaptureInputSchema = CaptureSchema.omit({ master: true }) + +export type Capture = z.infer +export type CaptureInput = z.infer diff --git a/src/model/person.ts b/src/model/person.ts index fc3522a..afeefbd 100644 --- a/src/model/person.ts +++ b/src/model/person.ts @@ -6,6 +6,7 @@ import { z } from 'zod' import { CodeAnchorSchema, UiAnchorSchema } from './walkthrough.js' import type { ResolvedAnchor } from './recording.js' import { parseAnchorText } from './anchor-text.js' +import { CaptureInputSchema } from './capture.js' /** A code anchor as an object or as typed text (see parseAnchorText). */ export const MarkAnchorSchema = z.union([ @@ -33,6 +34,8 @@ export const PersonRecordingSchema = z.object({ summary: z.string().max(4000).default(''), durationMs: z.number().min(0).max(6 * 60 * 60 * 1000), marks: z.array(MarkSchema).max(500).default([]), + /** A studio take's capture (src/model/capture.ts); the master is filled in by the server. */ + capture: CaptureInputSchema.optional(), }) export type Mark = z.infer diff --git a/src/model/recording.ts b/src/model/recording.ts index d766c94..deae07c 100644 --- a/src/model/recording.ts +++ b/src/model/recording.ts @@ -5,6 +5,7 @@ */ import { z } from 'zod' import { UiAnchorSchema } from './walkthrough.js' +import { CaptureSchema } from './capture.js' export const ResolvedAnchorSchema = z.object({ path: z.string(), @@ -109,6 +110,8 @@ export const RecordingSchema = z.object({ clipOf: ClipOfSchema.optional(), /** Present on a variant: where it came from and the values it was recorded with. */ variantOf: VariantOfSchema.optional(), + /** A studio take's capture: the preset, what the browser applied to each track, the master WAV, the clips (src/model/capture.ts). */ + capture: CaptureSchema.optional(), }) export type VariantOf = z.infer diff --git a/src/runner/capture.ts b/src/runner/capture.ts index 79babfe..db06ef0 100644 --- a/src/runner/capture.ts +++ b/src/runner/capture.ts @@ -31,6 +31,40 @@ export function ffmpegAvailable(env: NodeJS.ProcessEnv = process.env): boolean { return ok } +/** + * What Chromium says about a screencast frame (Page.ScreencastFrameMetadata): the size it was drawn at, in CSS pixels, + * and when it was drawn, in seconds since the epoch. + */ +export interface FrameMeta { + deviceWidth?: number + deviceHeight?: number + timestamp?: number +} + +/** How far around a held span a frame's own time may be and still count as drawn in it (the two clocks differ a little). */ +export const HOLD_SLACK_MS = 100 + +/** + * Whether a frame was drawn while the capture was held (Screencast.during): its own timestamp inside a held span, with + * HOLD_SLACK_MS on either side. A frame can arrive well after it was drawn under load, so its arrival time is not enough. + */ +export function drawnWhileHeld(meta: FrameMeta, held: readonly { from: number; until: number }[]): boolean { + if (meta.timestamp === undefined) return false + const at = meta.timestamp * 1000 + return held.some((h) => at >= h.from - HOLD_SLACK_MS && at <= h.until + HOLD_SLACK_MS) +} + +/** + * Whether a screencast frame shows the page as the viewer sees it. A clipped screenshot (the walkthrough baseline's + * page.screenshot({ clip })) makes Chromium draw just the clip for a moment, and the screencast sends that frame too, at + * the clip's size; written into the video it is a zoomed flash that reads as a page change. Such a frame is left out. + * Without a fixed viewport (or a size in the metadata) every frame is kept. + */ +export function isPageFrame(meta: FrameMeta, viewport: { width: number; height: number } | null): boolean { + if (!viewport || meta.deviceWidth === undefined || meta.deviceHeight === undefined) return true + return Math.abs(meta.deviceWidth - viewport.width) < 1 && Math.abs(meta.deviceHeight - viewport.height) < 1 +} + export interface ScreencastOptions { file: string /** Output size in device pixels; made even. */ @@ -49,6 +83,9 @@ export class Screencast { private timer: NodeJS.Timeout private session: CDPSession | undefined private stderr = '' + /** Spans (Date.now()) in which the page was drawn for something other than the viewer, and how many are open. */ + private held: { from: number; until: number }[] = [] + private holding = 0 readonly fps: number readonly width: number readonly height: number @@ -87,7 +124,8 @@ export class Screencast { if (previous) await previous.detach().catch(() => undefined) const session = await page.context().newCDPSession(page) session.on('Page.screencastFrame', (frame) => { - if (this.session === session) this.latest = Buffer.from(frame.data, 'base64') + const shown = this.holding === 0 && isPageFrame(frame.metadata, page.viewportSize()) && !drawnWhileHeld(frame.metadata, this.held) + if (this.session === session && shown) this.latest = Buffer.from(frame.data, 'base64') session.send('Page.screencastFrameAck', { sessionId: frame.sessionId }).catch(() => undefined) }) this.session = session @@ -100,6 +138,23 @@ export class Screencast { }) } + /** + * Run work that makes Chromium draw the page for something other than the viewer (a clipped screenshot), keeping + * the frames drawn meanwhile out of the video: the last frame before it is repeated instead. Not every such frame + * says so by its size (isPageFrame), so the span is held by time as well. + */ + async during(work: () => Promise): Promise { + const span = { from: Date.now(), until: Infinity } + this.held = [...this.held.filter((h) => h.until > span.from - 10_000), span] + this.holding += 1 + try { + return await work() + } finally { + this.holding -= 1 + this.held = this.held.map((h) => (h === span ? { ...h, until: Date.now() } : h)) + } + } + /** Write as many frames as the clock says are due, repeating the latest. */ private pump(): void { if (!this.latest) return diff --git a/src/runner/headless.ts b/src/runner/headless.ts index d5142f2..094f4c2 100644 --- a/src/runner/headless.ts +++ b/src/runner/headless.ts @@ -374,7 +374,11 @@ async function perform(run: Run, step: Step, t0: number, seen: StepSeen): Promis await run.page.goto(resolveUrl(action.url, walk.baseUrl), { waitUntil: 'load' }) } const page = run.page - if (run.observe) await withDeadline(run.observe(page, step), OBSERVE_DEADLINE_MS, 'looking at the step took too long').catch(() => undefined) + if (run.observe) { + // The baseline's clipped screenshot makes Chromium draw the clip for a moment: the capture keeps those frames out. + const look = (): Promise => run.observe!(page, step) + await withDeadline(run.cast ? run.cast.during(look) : look(), OBSERVE_DEADLINE_MS, 'looking at the step took too long').catch(() => undefined) + } await overlay(page, 'caption', run.masker.text(step.say)) const focus = step.highlight ?? (action && 'target' in action ? action.target : undefined) const box = focus ? await locate(page, focus).boundingBox({ timeout: ACTION_TIMEOUT_MS }) : null diff --git a/src/server/http.ts b/src/server/http.ts index 3efc665..023fa6c 100644 --- a/src/server/http.ts +++ b/src/server/http.ts @@ -9,6 +9,7 @@ * GET /api/recordings list * GET /api/recordings/:id one recording * GET /api/recordings/:id/:file video.webm, captions.vtt, chapters.vtt + * GET /api/player/:id[/:file]?key= one recording's player with its player key, not the run's token (player-link.ts) * POST /api/uploads body = webm from the recorder; returns { id } * PUT /api/uploads/:id body = PersonRecording JSON; saves the recording * DELETE /api/recordings/:id @@ -30,7 +31,7 @@ import { version } from '../version.js' export const UPLOAD_LIMIT = 4 * 1024 * 1024 * 1024 /** Uploads whose details never arrive are swept after this long. */ export const ORPHAN_AGE_MS = 24 * 60 * 60 * 1000 -const MEDIA = /^(video\.webm|captions\.vtt|chapters\.vtt|track-[a-z0-9][a-z0-9-]{0,40}\.(webm|mp4))$/ +export const MEDIA = /^(video\.webm|captions\.vtt|chapters\.vtt|track-[a-z0-9][a-z0-9-]{0,40}\.(webm|mp4))$/ /** The client's files: top level, or the features' modules and styles one folder down (fixed folder names). */ const CLIENT_FILE = /^(?:(?:features|styles)\/)?[a-z0-9-]+\.(html|js|css)$/ const VENDOR_WASM = 'rnnoise.wasm' diff --git a/src/server/player-link.ts b/src/server/player-link.ts new file mode 100644 index 0000000..ac1aed4 --- /dev/null +++ b/src/server/player-link.ts @@ -0,0 +1,161 @@ +/** + * Player links: what a link handed out of the app (an MCP answer, `formrec record`) carries instead of the run's token. + * Each recording's player key is an HMAC of its id under one secret, /player-links/key (0600 in a 0700 folder), + * so a key opens that one recording's player and nothing else. `rotatePlayerLinks` replaces the secret, which makes every + * player link given so far stop working at once. + * + * The key is checked by `playerLinkGate`, which answers two routes before the main token check, and nothing else: + * GET /api/player/:id?key= the recording (what the player draws) + * GET /api/player/:id/:file?key= its video, tracks, captions and chapters (the core media names, server/http.ts MEDIA) + * A player key never reaches any other route: the main server still asks for the run's token there. + */ +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto' +import { constants } from 'node:fs' +import { chmod, copyFile, link, mkdir, readFile, unlink, writeFile } from 'node:fs/promises' +import path from 'node:path' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { atomicWrite, type Library } from '../store/library.js' +import { sendFile, TYPES } from './files.js' +import { MEDIA, sendJson as send } from './http.js' + +const SECRET = /^[A-Za-z0-9_-]{43,128}$/ +const ID = /^[a-z0-9][a-z0-9-]{0,80}$/ + +export function playerSecretFile(dataDir: string): string { + return path.join(dataDir, 'player-links', 'key') +} + +async function secretDir(dataDir: string): Promise { + const dir = path.dirname(playerSecretFile(dataDir)) + await mkdir(dir, { recursive: true, mode: 0o700 }) + await chmod(dir, 0o700) +} + +const fresh = (): string => randomBytes(32).toString('base64url') + +/** A new secret in place of the old one (a rename, so a reader sees the old or the new, never part of one). */ +async function writeSecret(dataDir: string): Promise { + await secretDir(dataDir) + const secret = fresh() + await atomicWrite(playerSecretFile(dataDir), `${secret}\n`) + return secret +} + +/** + * The first secret. Several links are keyed at once (an answer's text and its structured value, another process on + * the same folder), so only one secret may win: the file is linked into place, which fails when one is already there, + * and then that one is read. + */ +async function createSecret(dataDir: string): Promise { + await secretDir(dataDir) + const file = playerSecretFile(dataDir) + const temp = `${file}.${randomBytes(4).toString('hex')}.tmp` + const secret = fresh() + await writeFile(temp, `${secret}\n`, { mode: 0o600 }) + try { + await placeNew(temp, file) + return secret + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error + // A file that is there but holds no secret (cut short, edited) opens no link; a new one takes its place. + return (await readSecret(dataDir)) ?? (await writeSecret(dataDir)) + } finally { + await unlink(temp).catch(() => undefined) + } +} + +/** Codes for a file system with no hard links (exFAT, FAT32, some network shares). */ +const NO_LINKS = new Set(['ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EPERM', 'EXDEV']) + +/** Put temp at file only when nothing is there (EEXIST otherwise): a hard link, else an exclusive copy. */ +async function placeNew(temp: string, file: string): Promise { + try { + await link(temp, file) + } catch (error) { + if (!NO_LINKS.has((error as NodeJS.ErrnoException).code ?? '')) throw error + await copyFile(temp, file, constants.COPYFILE_EXCL) + } +} + +const creating = new Map>() + +async function secretFor(dataDir: string): Promise { + const found = await readSecret(dataDir) + if (found) return found + let pending = creating.get(dataDir) + if (!pending) { + pending = createSecret(dataDir).finally(() => creating.delete(dataDir)) + creating.set(dataDir, pending) + } + return pending +} + +async function readSecret(dataDir: string): Promise { + try { + const text = (await readFile(playerSecretFile(dataDir), 'utf8')).trim() + return SECRET.test(text) ? text : undefined + } catch { + return undefined + } +} + +function keyOf(secret: string, id: string): string { + return createHmac('sha256', secret).update(`formrec-player\0${id}`).digest('base64url') +} + +/** The player key for one recording, making the secret on first use. */ +export async function playerKey(dataDir: string, id: string): Promise { + if (!ID.test(id)) throw new Error(`not a recording id: ${id}`) + return keyOf(await secretFor(dataDir), id) +} + +/** Whether a key opens this recording's player. With no secret yet, nothing does. */ +export async function playerKeyMatches(dataDir: string, id: string, given: string | null | undefined): Promise { + if (!given || !ID.test(id)) return false + const secret = await readSecret(dataDir) + if (!secret) return false + const a = Buffer.from(keyOf(secret, id)) + const b = Buffer.from(given) + return a.length === b.length && timingSafeEqual(a, b) +} + +/** A new secret: every player link given so far stops working on its next request. */ +export async function rotatePlayerLinks(dataDir: string): Promise { + await writeSecret(dataDir) +} + +/** The link that opens one recording's player at `origin` (http://127.0.0.1:), with its key and no run token. */ +export async function playerLinkFor(dataDir: string, origin: string, id: string): Promise { + return `${origin.replace(/\/+$/, '')}/?player=${await playerKey(dataDir, id)}#/f/${id}` +} + +/** The player link's door (a gate in server/http.ts): /api/player/ only, answered here whatever the outcome. */ +export function playerLinkGate(library: Library) { + return async (req: IncomingMessage, res: ServerResponse, parts: string[], url: URL): Promise => { + if (parts[1] !== 'player') return false + const [, , id, file] = parts + if (req.method !== 'GET' || !id || parts.length > 4 || (file !== undefined && !MEDIA.test(file))) { + send(res, 404, { error: 'no such route' }) + return true + } + const bearer = /^Bearer (.+)$/.exec(req.headers.authorization ?? '')?.[1] + if (!(await playerKeyMatches(library.dataDir, id, bearer ?? url.searchParams.get('key')))) { + send(res, 401, { error: 'this player link is not valid (it may have been replaced in Settings)' }) + return true + } + let rec + try { + rec = await library.get(id) + } catch { + rec = undefined + } + if (!rec) { + send(res, 404, { error: `no recording ${id}` }) + return true + } + res.setHeader('Referrer-Policy', 'no-referrer') + if (file === undefined) send(res, 200, rec) + else await sendFile(req, res, path.join(library.folder(id), file), TYPES[path.extname(file)] ?? 'application/octet-stream') + return true + } +} diff --git a/src/server/studio-routes.ts b/src/server/studio-routes.ts index 1ff0258..5563de2 100644 --- a/src/server/studio-routes.ts +++ b/src/server/studio-routes.ts @@ -11,6 +11,7 @@ * POST /api/sessions/:id/recover { title?, summary? } -> recording (an unsaved take, closed at its last write) * DELETE /api/sessions/:id[?cancel=1] discard an unsaved take explicitly (cancel=1: the studio's own live take) * POST /api/sessions/:id/tracks?source=system the computer's sound as its own track (host-system) + * POST /api/sessions/:id/tracks?source=phone a phone's sound as its own track (host-phone) * GET /api/rtc?after=n | POST /api/rtc the host's signalling * GET /api/guests | PUT /api/guests the guest listener: state, { enabled } * POST /api/guests/code a one-time pairing code @@ -125,10 +126,12 @@ async function sessionRoute(deps: StudioDeps, req: IncomingMessage, res: ServerR const input = await json(req, NewTrackSchema) // ?source=system: the computer's own sound (a call, a video), a microphone-kind track of its own (R1-29, R1-46). const system = url.searchParams.get('source') === 'system' && input.kind === 'mic' + // ?source=phone: a phone's own sound (the phone feature's capture), apart from the microphone (issue #7). + const phone = url.searchParams.get('source') === 'phone' && input.kind === 'mic' const track = await sessions.addTrack(id, { ...input, - id: system ? 'host-system' : `host-${input.kind}`, - person: system ? 'System audio' : input.person ?? 'Host', + id: system ? 'host-system' : phone ? 'host-phone' : `host-${input.kind}`, + person: system ? 'System audio' : phone ? 'Phone audio' : input.person ?? 'Host', host: true, owner: 'host', }) diff --git a/src/studio/devices.ts b/src/studio/devices.ts new file mode 100644 index 0000000..f257d39 --- /dev/null +++ b/src/studio/devices.ts @@ -0,0 +1,82 @@ +/** + * The studio's microphone and camera lists as agents see them, and the one way an agent asks the open studio to + * rebuild them (formrec_studio_refresh_devices). The studio is a page, so the request is a small file in the studio + * feature's folder that the page polls (GET /api/studio/devices/request); the page answers with what it found + * (PUT /api/studio/devices). Only labels and the chosen flag are kept: no device ids, nothing that identifies the + * hardware beyond the names the browser shows the person. + */ +import { randomUUID } from 'node:crypto' +import { z } from 'zod' +import { readFeatureJson, writeFeatureJson } from '../features/store.js' + +const ID = 'studio' +const REPORT = 'devices' +const REQUEST = 'devices-request' +/** A request the studio has not picked up within this time is dropped, so a studio opened later never acts on it. */ +export const REQUEST_TTL_MS = 30_000 +/** How long the tool waits for the studio's answer: two polls of the page and a permission prompt. */ +export const ANSWER_WAIT_MS = 12_000 + +const DeviceSchema = z.object({ label: z.string().max(200), chosen: z.boolean().default(false) }) +export const DevicesReportSchema = z.object({ + requestId: z.string().max(64).optional(), + mics: z.array(DeviceSchema).max(64), + cameras: z.array(DeviceSchema).max(64), + cameraInUse: z.boolean().default(false), + permission: z.enum(['granted', 'needed', 'refused', 'unavailable']), + text: z.string().max(300).default(''), + reportedAt: z.string().optional(), +}) +export type DevicesReport = z.infer + +export const DevicesRequestSchema = z.object({ id: z.string().max(64), askPermission: z.boolean().default(false), at: z.string() }) +export type DevicesRequest = z.infer +export const RefreshInputSchema = z.object({ askPermission: z.boolean().default(false) }) + +export function readReport(dataDir: string): Promise { + return readFeatureJson(dataDir, ID, REPORT, DevicesReportSchema) +} + +export function writeReport(dataDir: string, report: DevicesReport, now: Date): Promise { + return writeFeatureJson(dataDir, ID, REPORT, DevicesReportSchema, { ...report, reportedAt: now.toISOString() }) +} + +export function writeRequest(dataDir: string, askPermission: boolean, now: Date): Promise { + return writeFeatureJson(dataDir, ID, REQUEST, DevicesRequestSchema, { id: randomUUID(), askPermission, at: now.toISOString() }) +} + +/** The request still waiting for the studio, or undefined when there is none or it is older than REQUEST_TTL_MS. */ +export async function pendingRequest(dataDir: string, now: Date): Promise { + const request = await readFeatureJson(dataDir, ID, REQUEST, DevicesRequestSchema) + if (!request) return undefined + const age = now.getTime() - Date.parse(request.at) + return age >= 0 && age <= REQUEST_TTL_MS ? request : undefined +} + +export interface RefreshOutcome { + refreshed: boolean + reason?: string + devices?: DevicesReport +} + +/** Ask the open studio to rebuild its lists and wait for its answer; without one, say so and give the last report. */ +export async function requestRefresh( + dataDir: string, + input: { askPermission?: boolean }, + opts: { now?: () => Date; waitMs?: number; everyMs?: number; signal?: AbortSignal } = {}, +): Promise { + const now = opts.now ?? (() => new Date()) + const request = await writeRequest(dataDir, input.askPermission === true, now()) + const until = Date.now() + (opts.waitMs ?? ANSWER_WAIT_MS) + while (Date.now() < until && !opts.signal?.aborted) { + await new Promise((r) => setTimeout(r, opts.everyMs ?? 250)) + const report = await readReport(dataDir).catch(() => undefined) + if (report?.requestId === request.id) return { refreshed: true, devices: report } + } + const last = await readReport(dataDir).catch(() => undefined) + return { + refreshed: false, + reason: 'The studio did not answer: open the FormRec studio (Record) on this computer, then ask again.', + ...(last ? { devices: last } : {}), + } +} diff --git a/src/studio/finish.ts b/src/studio/finish.ts index ac14670..73920ae 100644 --- a/src/studio/finish.ts +++ b/src/studio/finish.ts @@ -10,6 +10,7 @@ import { resolveAnchors, type CodebaseContext } from '../anchors/resolve.js' import type { Library } from '../store/library.js' import { makeSeekable } from './remux.js' import { SessionError } from '../store/sessions.js' +import { finishMaster } from './master.js' export function takeDurationMs(session: Session, now: number): number { const take = session.take @@ -77,6 +78,9 @@ export async function finishSession(input: FinishInput): Promise { code: await resolveAnchors(span.mark.code, input.codebase), }) } + // The master WAV is described from the file this server holds; a client's claim to one is never taken. + const master = details.capture ? await finishMaster(library, session.id) : undefined + const capture = details.capture ? { ...details.capture, ...(master ? { master } : {}) } : undefined return library.save({ formrec: 1, id: session.id, @@ -91,5 +95,6 @@ export async function finishSession(input: FinishInput): Promise { durationMs, codebase: input.codebase.root ? { root: input.codebase.root, commit: input.codebase.commit, repoUrl: input.codebase.repoUrl } : undefined, chapters, + ...(capture ? { capture } : {}), }) } diff --git a/src/studio/master.ts b/src/studio/master.ts new file mode 100644 index 0000000..284cc8f --- /dev/null +++ b/src/studio/master.ts @@ -0,0 +1,170 @@ +/** + * The host microphone's lossless master (the studio's Voice master preset): a 24-bit WAV written beside the Opus + * track while the take records. It is not one of the session's tracks, so the player, the exports and the transcript + * keep using the Opus track and nothing plays twice; it is the file for voice training and for a later mix. + * + * Chunks arrive in order like a track's (seq, a repeat accepted without writing, a gap refused with the number + * expected) and are appended to one fixed file name in the take's folder; the request never names a file. The first + * chunk must start with the canonical header shared/wav.ts writes. The header goes out with its sizes unknown, so the + * end of the take writes the real ones; a take that never ended still reads to the end of the file. + */ +import { createWriteStream } from 'node:fs' +import { open, stat } from 'node:fs/promises' +import path from 'node:path' +import { pipeline } from 'node:stream/promises' +import { Transform, type Readable } from 'node:stream' +import { z } from 'zod' +import { readSidecar, writeSidecar } from '../features/store.js' +import type { Library } from '../store/library.js' +import { CHUNK_LIMIT, SessionError, type ChunkResult, type Sessions } from '../store/sessions.js' +import { MAX_WAV_DATA, parseWavHeader, sizeFields, WAV_HEADER_BYTES, wavDurationMs, type WavFormat } from '../../shared/wav.js' + +export const MASTER_FILE = 'master-host-mic.wav' as const +/** The sidecar that follows the master's upload (master.json beside session.json). */ +const SIDECAR = 'master' + +export const MasterStateSchema = z.object({ + chunks: z.number().int().min(0), + bytes: z.number().int().min(0), + ended: z.boolean(), + durationMs: z.number().min(0).optional(), + format: z.object({ sampleRate: z.number().int(), channels: z.number().int(), bitsPerSample: z.union([z.literal(16), z.literal(24), z.literal(32)]) }).optional(), +}) +export type MasterState = z.infer + +const EMPTY: MasterState = { chunks: 0, bytes: 0, ended: false } + +/** What recording.json says about the master once the take is saved. */ +export interface MasterInfo { file: typeof MASTER_FILE; bytes: number; durationMs: number; complete: boolean; sampleRate: number; bitsPerSample: number; channels: number } + +export async function readMasterState(library: Library, id: string): Promise { + return readSidecar(library, id, SIDECAR, MasterStateSchema) +} + +/** Writes per take are serialised, so chunks land in order and the state file follows them. */ +export class Masters { + private readonly locks = new Map>() + + constructor(private readonly sessions: Sessions) {} + + private get library(): Library { + return this.sessions.library + } + + file(id: string): string { + return path.join(this.library.folder(id), MASTER_FILE) + } + + append(id: string, seq: number, body: Readable): Promise { + return this.serial(id, async () => { + await this.writable(id) + const state = (await readMasterState(this.library, id)) ?? EMPTY + if (seq < state.chunks) { + body.resume() + return { accepted: false, next: state.chunks, bytes: state.bytes } + } + if (seq > state.chunks) { + body.resume() + throw new SessionError(409, `expected chunk ${state.chunks}, got ${seq}`, { next: state.chunks }) + } + if (state.ended) { + body.resume() + throw new SessionError(409, 'the master has ended', { final: true }) + } + const room = WAV_HEADER_BYTES + MAX_WAV_DATA - state.bytes + const data = await readLimited(body, Math.min(CHUNK_LIMIT, room)) + if (data.length === 0) return { accepted: false, next: state.chunks, bytes: state.bytes } + let format = state.format + if (state.bytes === 0) { + const head = parseWavHeader(new Uint8Array(data.buffer, data.byteOffset, data.length)) + if (!head) throw new SessionError(415, 'the master must start with a PCM WAV header') + format = { sampleRate: head.sampleRate, channels: head.channels, bitsPerSample: head.bitsPerSample } + } + await appendTo(this.file(id), data) + const next: MasterState = { ...state, chunks: state.chunks + 1, bytes: state.bytes + data.length, ...(format ? { format } : {}) } + await writeSidecar(this.library, id, SIDECAR, MasterStateSchema, next) + return { accepted: true, next: next.chunks, bytes: next.bytes } + }) + } + + /** The take's master is complete: write its real sizes and remember its length. */ + end(id: string, durationMs: number): Promise { + return this.serial(id, async () => { + await this.writable(id) + const state = (await readMasterState(this.library, id)) ?? EMPTY + if (state.bytes > 0) await fixSizes(this.file(id)) + const next: MasterState = { ...state, ended: true, durationMs: Math.round(durationMs) } + return writeSidecar(this.library, id, SIDECAR, MasterStateSchema, next) + }) + } + + private async writable(id: string): Promise { + const s = await this.sessions.get(id) + if (s.state === 'saved' || s.state === 'saving') throw new SessionError(409, 'this session is saved; nothing more can be added', { final: true }) + if (s.state === 'ready') throw new SessionError(409, 'the take has not started') + } + + private serial(key: string, work: () => Promise): Promise { + const run = (this.locks.get(key) ?? Promise.resolve()).catch(() => undefined).then(work) + const tail = run.catch(() => undefined) + this.locks.set(key, tail) + void tail.then(() => { if (this.locks.get(key) === tail) this.locks.delete(key) }) + return run + } +} + +/** Write the RIFF and data sizes of a WAV file from its length on disk. */ +export async function fixSizes(file: string): Promise { + const handle = await open(file, 'r+') + try { + const { size } = await handle.stat() + if (size < WAV_HEADER_BYTES) return size + const { riff, data } = sizeFields(size) + const field = Buffer.alloc(4) + field.writeUInt32LE(riff) + await handle.write(field, 0, 4, 4) + field.writeUInt32LE(data) + await handle.write(field, 0, 4, 40) + return size + } finally { + await handle.close() + } +} + +/** + * At save: the master as it is on disk (its sizes written, whether its end arrived), or undefined when the take has + * none. The length is the file's own, from its bytes, not the client's word. + */ +export async function finishMaster(library: Library, id: string): Promise { + const state = await readMasterState(library, id).catch(() => undefined) + if (!state?.format || state.bytes === 0) return undefined + const file = path.join(library.folder(id), MASTER_FILE) + const size = await stat(file).then((s) => s.size, () => 0) + if (size <= WAV_HEADER_BYTES) return undefined + await fixSizes(file) + const format: WavFormat = state.format + return { file: MASTER_FILE, bytes: size, durationMs: wavDurationMs(format, size - WAV_HEADER_BYTES), complete: state.ended, ...format } +} + +async function readLimited(body: Readable, limit: number): Promise { + const chunks: Buffer[] = [] + let size = 0 + const counter = new Transform({ + transform(chunk: Buffer, _enc, done) { + size += chunk.length + if (size > limit) return done(new SessionError(413, `a chunk may be at most ${limit} bytes`)) + chunks.push(chunk) + done() + }, + }) + await pipeline(body, counter) + return Buffer.concat(chunks) +} + +function appendTo(file: string, data: Buffer): Promise { + return new Promise((resolve, reject) => { + const out = createWriteStream(file, { flags: 'a', mode: 0o600 }) + out.on('error', reject) + out.end(data, resolve) + }) +} diff --git a/src/wtdiff/replay.ts b/src/wtdiff/replay.ts index 2f00be0..fe2889d 100644 --- a/src/wtdiff/replay.ts +++ b/src/wtdiff/replay.ts @@ -78,7 +78,7 @@ export async function openRun(walk: Walkthrough, opts: Pick undefined } as unknown as Screencast, + cast: { follow: async () => undefined, during: (work: () => Promise) => work() } as unknown as Screencast, followNewTabs: setup.followNewTabs, uploadDir: opts.uploadDir ?? uploadDir(opts.dataDir, opts.env), page: undefined as unknown as Page, diff --git a/tests/agents-win-launch.test.ts b/tests/agents-win-launch.test.ts new file mode 100644 index 0000000..569f545 --- /dev/null +++ b/tests/agents-win-launch.test.ts @@ -0,0 +1,115 @@ +/** + * Starting an agent client's command on Windows (src/agents/win-launch.ts), tested through the argument builder with a + * stand-in file system, so it runs on any operating system. An npm `.cmd` shim is resolved to the program it wraps and + * run without cmd.exe; when cmd.exe is still needed, an argument holding a character cmd.exe treats specially is refused. + */ +import { describe, expect, it } from 'vitest' +import { cmdLaunch, launchArgv, LaunchRefused, shimTarget, type LaunchEnv } from '../src/agents/win-launch.js' + +const DIR = 'C:\\Users\\me\\AppData\\Roaming\\npm' +const SHIM = `${DIR}\\claude.cmd` +const SCRIPT = `${DIR}\\node_modules\\@anthropic-ai\\claude-code\\cli.js` +const EXE = `${DIR}\\node_modules\\tool\\bin\\tool.exe` + +const nodeShim = [ + '@ECHO off', + 'GOTO start', + ':find_dp0', + 'SET dp0=%~dp0', + 'EXIT /b', + ':start', + 'SETLOCAL', + 'CALL :find_dp0', + 'IF EXIST "%dp0%\\node.exe" (', + ' SET "_prog=%dp0%\\node.exe"', + ') ELSE (', + ' SET "_prog=node"', + ' SET PATHEXT=%PATHEXT:;.JS;=;%', + ')', + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*', +].join('\r\n') +const exeShim = '@ECHO off\r\n"%~dp0\\node_modules\\tool\\bin\\tool.exe" %*\r\n' + +function fake(files: Record, extra: Partial = {}): LaunchEnv { + return { + platform: 'win32', + env: { ComSpec: 'C:\\Windows\\System32\\cmd.exe' }, + exists: (f) => f in files, + read: (f) => files[f], + which: (b) => (b === 'node' ? 'C:\\Program Files\\nodejs\\node.exe' : undefined), + ...extra, + } +} + +describe('resolving an npm shim', () => { + it('finds the Node script a shim runs', () => { + expect(shimTarget(nodeShim, DIR)).toBe(SCRIPT) + }) + + it('finds the program an exe shim runs', () => { + expect(shimTarget(exeShim, DIR)).toBe(EXE) + }) + + it('does not follow a shim to a program outside its folder', () => { + expect(shimTarget('"%~dp0\\..\\..\\elsewhere\\x.exe" %*\r\n', DIR)).toBeUndefined() + }) + + it('runs a Node shim with Node and an argument list, keeping special characters literal', () => { + const args = ['mcp', 'add', 'a & b', '100%', '(x)', 'say "hi"!'] + const launch = launchArgv(SHIM, args, fake({ [SHIM]: nodeShim, [SCRIPT]: '' })) + expect(launch).toEqual({ command: 'C:\\Program Files\\nodejs\\node.exe', args: [SCRIPT, ...args], verbatim: false }) + }) + + it('prefers the node.exe next to the shim', () => { + const local = `${DIR}\\node.exe` + const launch = launchArgv(SHIM, ['mcp'], fake({ [SHIM]: nodeShim, [SCRIPT]: '', [local]: '' })) + expect(launch.command).toBe(local) + }) + + it('runs an exe shim\'s program directly', () => { + const launch = launchArgv(`${DIR}\\tool.cmd`, ['a|b'], fake({ [`${DIR}\\tool.cmd`]: exeShim, [EXE]: '' })) + expect(launch).toEqual({ command: EXE, args: ['a|b'], verbatim: false }) + }) + + it('leaves a program that is not a shim, and every other platform, alone', () => { + expect(launchArgv('C:\\bin\\claude.exe', ['a & b'], fake({}))).toEqual({ command: 'C:\\bin\\claude.exe', args: ['a & b'], verbatim: false }) + expect(launchArgv('/usr/local/bin/claude', ['a & b'], fake({}, { platform: 'linux' }))).toEqual({ command: '/usr/local/bin/claude', args: ['a & b'], verbatim: false }) + }) +}) + +describe('through cmd.exe', () => { + it('falls back to cmd.exe for a shim it cannot resolve, quoting every word', () => { + const launch = launchArgv(SHIM, ['mcp', 'add', 'C:\\Program Files\\x y.exe'], fake({ [SHIM]: '@echo off\r\nsomething %*\r\n' })) + expect(launch).toEqual({ + command: 'C:\\Windows\\System32\\cmd.exe', + args: ['/d', '/s', '/c', `""${SHIM}" "mcp" "add" "C:\\Program Files\\x y.exe""`], + verbatim: true, + }) + }) + + it('falls back when the wrapped script is missing or Node is not found', () => { + expect(launchArgv(SHIM, ['mcp'], fake({ [SHIM]: nodeShim })).verbatim).toBe(true) + expect(launchArgv(SHIM, ['mcp'], fake({ [SHIM]: nodeShim, [SCRIPT]: '' }, { which: () => undefined })).verbatim).toBe(true) + }) + + it.each(['a&b', 'a|b', 'ab', 'a^b', '(a)', 'a!', '50%', 'say "hi"', 'nospace&', 'line\nbreak', 'tab\there', 'bell\u0007', 'del\u007f', 'nul\u0000'])( + 'refuses the argument %j, with or without spaces', + (arg) => { + expect(() => cmdLaunch(SHIM, ['mcp', arg], {})).toThrow(LaunchRefused) + expect(() => launchArgv(SHIM, [arg], fake({}))).toThrow(/stdin or a file/) + }, + ) + + it('accepts plain arguments with spaces, colons and slashes', () => { + expect(() => cmdLaunch(SHIM, ['mcp', 'add', '--scope', 'user', 'Authorization: Bearer abc-123_x', 'http://127.0.0.1:8775/mcp', 'C:\\a b\\c'], {})).not.toThrow() + }) + + it('uses cmd.exe when ComSpec is not set', () => { + expect(cmdLaunch(SHIM, [], {}).command).toBe('cmd.exe') + }) + + it('refuses a program path cmd.exe would read as syntax', () => { + expect(() => cmdLaunch('C:\\a&b\\claude.cmd', [], {})).toThrow(LaunchRefused) + expect(() => cmdLaunch('C:\\Program Files (x86)\\npm\\claude.cmd', [], {})).not.toThrow() + }) +}) diff --git a/tests/avatar-share-e2e.test.ts b/tests/avatar-share-e2e.test.ts index bbc4ce0..5b7a2a4 100644 --- a/tests/avatar-share-e2e.test.ts +++ b/tests/avatar-share-e2e.test.ts @@ -15,6 +15,7 @@ import type { AddressInfo } from 'node:net' import { chromium, type Browser, type BrowserContext, type Page } from 'playwright' import { createApp, type App } from '../src/app.js' import { runtimeFor } from '../src/features/share/index.js' +import { queueFor } from '../src/features/share/renditions.js' import { AiEngine } from '../src/features/ai/engine.js' import { writeSidecar } from '../src/features/store.js' import { AiFileSchema } from '../src/features/ai/schema.js' @@ -57,10 +58,16 @@ const headShape = (page: Page): Promise => page.locator('[data-av beforeAll(async () => { if (!existsSync(path.join(WEB, 'share-view.js'))) throw new Error('run npm run build first') await mkdir(SHOTS, { recursive: true }) + // No automatic poster after each save: with the avatar on, edit's thumbnail decodes the recording up to the + // middle through the avatar's per-pixel mask filter, seconds of every core while the first page loads. + process.env['FORMREC_EDIT_POSTERS'] = '0' dataDir = await tempDir('formrec-avatar-share-') app = createApp({ dataDir, token: TOKEN, webDir: WEB }) await new Promise((r) => app.server.listen(0, '127.0.0.1', r)) base = `http://127.0.0.1:${(app.server.address() as AddressInfo).port}` + // No background share renditions either: each share below would start FFmpeg encodes of the whole ladder, which this file + // never looks at, and on a 2-vCPU runner they starve the share listener and Chromium (a page.goto timed out). + queueFor(app.features.library).stop() // No automatic AI outputs after a save: they would write ai.json while the test writes its own. await owner('/api/ai/settings', 'PUT', { auto: [] }) const rec = JSON.parse(await readFile(path.join(DEMO, 'recording.json'), 'utf8')) @@ -82,6 +89,7 @@ beforeAll(async () => { }, 180_000) afterAll(async () => { + delete process.env['FORMREC_EDIT_POSTERS'] await browser?.close() if (app) await runtimeFor(app.features).stop() await app?.close() @@ -111,10 +119,24 @@ describe('the avatar on a share page', () => { // Paused and at rest the mouth is closed; playing through the loud vowel opens it. await expect.poll(() => mouthLevel(page)).toBe('0') - await page.evaluate(() => { const v = document.querySelector('[data-sv-video]') as HTMLVideoElement; v.currentTime = 0.9; void v.play() }) - await expect.poll(() => mouthLevel(page), { timeout: 8000 }).not.toBe('0') + // The voice is three seconds long, so from 0.9 s it plays for about two: the mouth and the voice are recorded as + // they change, so a check that runs late on a slow machine still sees what happened. + await page.evaluate(() => { + const a = document.querySelector('[data-avatar-voice]') as HTMLAudioElement + const w = window as unknown as { __voiceFurthest: number } + const m = window as unknown as { __mouthOpened: boolean } + m.__mouthOpened = false + const face = document.querySelector('[data-avatar]') as HTMLElement + new MutationObserver(() => { if (face.getAttribute('data-avatar-mouth') !== '0') m.__mouthOpened = true }).observe(face, { attributes: true, attributeFilter: ['data-avatar-mouth'] }) + w.__voiceFurthest = 0 + a.addEventListener('timeupdate', () => { if (!a.paused) w.__voiceFurthest = Math.max(w.__voiceFurthest, a.currentTime) }) + const v = document.querySelector('[data-sv-video]') as HTMLVideoElement + v.currentTime = 0.9 + void v.play() + }) + await expect.poll(() => page.evaluate(() => (window as unknown as { __mouthOpened: boolean }).__mouthOpened), { timeout: 15_000 }).toBe(true) // The voice plays with the video. - await expect.poll(() => page.evaluate(() => { const a = document.querySelector('[data-avatar-voice]') as HTMLAudioElement; return !a.paused && a.currentTime > 0.5 }), { timeout: 8000 }).toBe(true) + await expect.poll(() => page.evaluate(() => (window as unknown as { __voiceFurthest: number }).__voiceFurthest), { timeout: 15_000 }).toBeGreaterThan(1.2) await page.screenshot({ path: path.join(SHOTS, 'avatar-share-page.png') }) // Pausing the video pauses the voice and closes the mouth. await page.evaluate(() => (document.querySelector('[data-sv-video]') as HTMLVideoElement).pause()) diff --git a/tests/capture-meta.test.ts b/tests/capture-meta.test.ts new file mode 100644 index 0000000..dff9818 --- /dev/null +++ b/tests/capture-meta.test.ts @@ -0,0 +1,62 @@ +/** What a take writes about its capture (web/src/capture-meta.ts) and the microphone presets (web/src/voice-master.ts). */ +import { describe, expect, it } from 'vitest' +import { captureTrack, checkForJson, deliveredNote, jsonDb, trackSettings } from '../web/src/capture-meta.js' +import { cleanSound, micConstraints, SOUND_DEFAULTS } from '../web/src/voice-master.js' +import { levelCheck } from '../web/src/levels.js' + +const requested = { quality: '1080p', width: 1920, height: 1080 } + +describe('track settings', () => { + it('keeps the known keys of plain types and drops the rest, device ids included', () => { + expect(trackSettings({ + sampleRate: 48_000, channelCount: 1, sampleSize: 24, echoCancellation: false, noiseSuppression: false, autoGainControl: false, + latency: 0.0106666666, deviceId: 'abc', groupId: 'def', width: 'wide', facingMode: 'user', + })).toEqual({ sampleRate: 48_000, channelCount: 1, sampleSize: 24, echoCancellation: false, noiseSuppression: false, autoGainControl: false, latency: 0.011, facingMode: 'user' }) + }) + + it('reads a track through getSettings', () => { + const track = { label: 'Built-in microphone', getSettings: () => ({ sampleRate: 48_000, echoCancellation: false, deviceId: 'x' }) as MediaTrackSettings } + expect(captureTrack('mic', track)).toEqual({ kind: 'mic', label: 'Built-in microphone', settings: { sampleRate: 48_000, echoCancellation: false } }) + }) +}) + +describe('the delivered size', () => { + it('says when the camera delivers less than the preset', () => { + expect(deliveredNote('camera', requested, { width: 1280, height: 720 })).toBe('The camera delivers 1280 x 720, less than 1080p asks for (1920 x 1080).') + expect(deliveredNote('camera', requested, { width: 1920, height: 1080 })).toBeUndefined() + expect(deliveredNote('camera', requested, { width: 1080, height: 1920 })).toBeUndefined() + expect(deliveredNote('screen', requested, { width: 1440, height: 900 })).toMatch(/^The screen delivers/) + expect(deliveredNote('mic', requested, { width: 1, height: 1 })).toBeUndefined() + expect(deliveredNote('camera', requested, {})).toBeUndefined() + }) +}) + +describe('levels for JSON', () => { + it('rounds dBFS and writes silence as null', () => { + expect(jsonDb(-12.345)).toBe(-12.3) + expect(jsonDb(-Infinity)).toBeNull() + expect(checkForJson(levelCheck([0]))).toEqual({ peakDb: null, maxDb: null, clips: 0, advice: 'silent', byDb: 0 }) + }) +}) + +describe('microphone presets', () => { + const dsp = { echoCancellation: true, noiseSuppression: true, autoGainControl: true } + + it('turns every browser DSP off for voice master and asks for mono 48 kHz 24-bit', () => { + expect(micConstraints('voice-master', dsp, 'mic-1')).toEqual({ + echoCancellation: false, noiseSuppression: false, autoGainControl: false, + channelCount: { ideal: 1 }, sampleRate: { ideal: 48_000 }, sampleSize: { ideal: 24 }, deviceId: { exact: 'mic-1' }, + }) + }) + + it('opens the standard microphone with the Effects switches, echo cancellation included', () => { + expect(micConstraints('standard', { ...dsp, echoCancellation: false })).toEqual({ echoCancellation: false, noiseSuppression: true, autoGainControl: true, channelCount: 1 }) + expect(micConstraints('standard', dsp).echoCancellation).toBe(true) + }) + + it('keeps only well-formed stored choices', () => { + expect(cleanSound({ preset: 'voice-master', roomTone: false })).toEqual({ preset: 'voice-master', roomTone: false }) + expect(cleanSound({ preset: 'studio', roomTone: 'yes' })).toEqual(SOUND_DEFAULTS) + expect(cleanSound(null)).toEqual(SOUND_DEFAULTS) + }) +}) diff --git a/tests/documents-routes.test.ts b/tests/documents-routes.test.ts index 8baae7b..b5f4bfe 100644 --- a/tests/documents-routes.test.ts +++ b/tests/documents-routes.test.ts @@ -5,6 +5,7 @@ import path from 'node:path' import type { AddressInfo } from 'node:net' import { createApp, type App } from '../src/app.js' import { buildServer } from '../src/mcp/server.js' +import { playerKey } from '../src/server/player-link.js' import { Library } from '../src/store/library.js' import { tempDir } from './helpers.js' import { revealCommand } from '../src/features/documents/service.js' @@ -195,7 +196,7 @@ describe('documents MCP tools', () => { const imported = await call('formrec_import', { path: webm }) expect(imported).toMatchObject({ kind: 'webm', title: 'My clip', deepLink: `formrec://f/${imported.id as string}` }) const opened = await call('formrec_open', { id: imported.id }) - expect(opened.player).toBe(`http://127.0.0.1:1/?token=x#/f/${imported.id as string}`) + expect(opened.player).toBe(`http://127.0.0.1:1/?player=${await playerKey(library.dataDir, imported.id as string)}#/f/${imported.id as string}`) const out = path.join(work, `mcp-${Date.now()}.frec`) const exported = await call('formrec_package_export', { id: imported.id, path: out }) expect(exported.file).toBe(out) diff --git a/tests/effects-noise-media.ts b/tests/effects-noise-media.ts index e6583a5..780d67e 100644 --- a/tests/effects-noise-media.ts +++ b/tests/effects-noise-media.ts @@ -60,7 +60,8 @@ export async function noisyWebm(dir: string, name: string, seconds = 6, noise = /** The noise floor of a file's sound in dB: FFmpeg astats "RMS trough", the quietest 50 ms window (the gaps between bursts). */ export function noiseFloorDb(file: string): number { const r = spawnSync(FFMPEG, ['-hide_banner', '-nostats', '-i', file, '-vn', '-af', 'astats=measure_perchannel=none:measure_overall=RMS_trough', '-f', 'null', '-'], { encoding: 'utf8' }) - const m = /RMS trough dB: (-?[\d.]+|-inf)/.exec(r.stderr) + // FFmpeg 8 prints the same measure as "RMS through dB"; earlier versions print "RMS trough dB". + const m = /RMS th?rough dB: (-?[\d.]+|-inf)/.exec(r.stderr) if (!m) throw new Error(`astats gave no RMS trough for ${file}: ${r.stderr.slice(-300)}`) return m[1] === '-inf' ? -120 : Number(m[1]) } diff --git a/tests/integrations-sdk.test.ts b/tests/integrations-sdk.test.ts index 894da3b..0fe1840 100644 --- a/tests/integrations-sdk.test.ts +++ b/tests/integrations-sdk.test.ts @@ -10,6 +10,7 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' import { Library } from '../src/store/library.js' import { createSdkServer, SdkPairing } from '../src/features/integrations/sdk.js' import { buildServer } from '../src/mcp/server.js' +import { playerKey } from '../src/server/player-link.js' import { saveService, addWebhook } from '../src/features/integrations/connections.js' import { apiDoc, routeLines } from '../src/features/integrations/api-doc.js' import { fakeServices, type Fake } from './integrations-fake.js' @@ -137,7 +138,7 @@ describe('MCP tools', () => { const hookId = (JSON.parse(list) as { webhooks: { id: string }[] }).webhooks[0]!.id fake.on('POST /slack-hook-secret', { text: 'ok' }) const posted = await client.callTool({ name: 'formrec_post_message', arguments: { recording: 'tour-2026-11-10', to: 'slack', note: 'From the agent' } }) - expect(JSON.parse(text(posted))).toMatchObject({ posted: true, link: 'http://127.0.0.1:8770/#/f/tour-2026-11-10', local: true }) + expect(JSON.parse(text(posted))).toMatchObject({ posted: true, link: `http://127.0.0.1:8770/?player=${await playerKey(library.dataDir, 'tour-2026-11-10')}#/f/tour-2026-11-10`, local: true }) expect(JSON.stringify(fake.seen.at(-1)!.json)).toContain('From the agent') const issue = JSON.parse(text(await client.callTool({ name: 'formrec_create_issue', arguments: { recording: 'tour-2026-11-10', service: 'github' } }))) expect(issue.created).toBe(false) diff --git a/tests/interactive-audit-browser.test.ts b/tests/interactive-audit-browser.test.ts index 7ca9f8e..d10b92a 100644 --- a/tests/interactive-audit-browser.test.ts +++ b/tests/interactive-audit-browser.test.ts @@ -1,9 +1,11 @@ /** * Audit of the interactive demo in real browsers: the share page's player walks in Chromium and Firefox (Firefox has * no layout-shift entries, so its page elements are sampled every frame instead), and pressing Build then Rebuild in - * the app's editor moves nothing at 4x CPU throttling. Needs `npm run build` and FFmpeg. + * the app's editor moves nothing at 4x CPU throttling. Needs `npm run build` and FFmpeg; the Firefox half skips when + * Playwright's Firefox is not installed. */ import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { existsSync } from 'node:fs' import { copyFile } from 'node:fs/promises' import type { AddressInfo } from 'node:net' import path from 'node:path' @@ -17,6 +19,8 @@ let shareId = '' let chrome: Browser let fox: Browser let appUrl = '' +const FOX = ((): boolean => { try { return existsSync(firefox.executablePath()) } catch { return false } })() +if (!FOX) console.warn('interactive-audit-browser: the Firefox walks skip, Playwright Firefox is not installed') beforeAll(async () => { w = await world() @@ -38,7 +42,7 @@ beforeAll(async () => { shareId = await w.share(ID, { privacy: 'link' }) appUrl = `http://127.0.0.1:${(w.app.server.address() as AddressInfo).port}/?token=${TOKEN}#/interactive/${FRESH}` chrome = await chromium.launch() - fox = await firefox.launch() + if (FOX) fox = await firefox.launch() }, 120_000) afterAll(async () => { await chrome?.close() @@ -94,7 +98,7 @@ describe('the player', () => { await context.close() }, 90_000) - it('walks in Firefox and no element of the page moves', async () => { + it.skipIf(!FOX)('walks in Firefox and no element of the page moves', async () => { const context = await fox.newContext({ viewport: { width: 1200, height: 800 } }) const page = await context.newPage() const errors: string[] = [] @@ -106,7 +110,7 @@ describe('the player', () => { await context.close() }, 90_000) - it('the embed walks in Firefox too', async () => { + it.skipIf(!FOX)('the embed walks in Firefox too', async () => { const context = await fox.newContext({ viewport: { width: 900, height: 700 } }) const page = await context.newPage() await walk(page, `${w.origin}/i/${shareId}?embed=1`) diff --git a/tests/levels.test.ts b/tests/levels.test.ts new file mode 100644 index 0000000..d2b3600 --- /dev/null +++ b/tests/levels.test.ts @@ -0,0 +1,155 @@ +/** The input level's arithmetic (web/src/levels.ts): dBFS, zones, the peak hold, clip counting, hints and the level check. */ +import { describe, expect, it } from 'vitest' +import { + adviceText, blockPeak, CLIP_LEVEL, clipReport, clipStep, dbfs, dbText, dbToFraction, EMPTY_CLIPS, EMPTY_HINT, hintStep, holdStep, + levelCheck, QUIET_HINT_MS, takeClock, zoneOf, type ClipLog, type HintState, +} from '../web/src/levels.js' +import { loudness } from '../web/src/effects-audio.js' + +const fromDb = (db: number): number => 10 ** (db / 20) + +describe('dBFS', () => { + it('turns linear peaks into dBFS', () => { + expect(dbfs(1)).toBe(0) + expect(dbfs(0.5)).toBeCloseTo(-6.02, 2) + expect(dbfs(0.1)).toBeCloseTo(-20, 6) + expect(dbfs(0)).toBe(-Infinity) + expect(dbfs(-1)).toBe(-Infinity) + expect(blockPeak([0.1, -0.7, 0.3])).toBe(0.7) + expect(blockPeak(new Float32Array(0))).toBe(0) + }) + + it('places peaks in zones around the -18 to -12 dBFS band', () => { + expect(zoneOf(-70)).toBe('silent') + expect(zoneOf(-31)).toBe('quiet') + expect(zoneOf(-24)).toBe('low') + expect(zoneOf(-18)).toBe('target') + expect(zoneOf(-12)).toBe('target') + expect(zoneOf(-11.9)).toBe('high') + expect(zoneOf(-3)).toBe('red') + expect(zoneOf(0)).toBe('red') + }) + + it('maps the scale and writes the readout', () => { + expect(dbToFraction(-60)).toBe(0) + expect(dbToFraction(0)).toBe(1) + expect(dbToFraction(-15)).toBeCloseTo(0.75) + expect(dbToFraction(-Infinity)).toBe(0) + expect(dbToFraction(3)).toBe(1) + expect(dbText(-Infinity)).toBe('-inf') + expect(dbText(-75)).toBe('-inf') + expect(dbText(-12.34)).toBe('-12.3') + expect(dbText(1.2)).toBe('0.0') + }) + + it('reads the effects meter against the same zones', () => { + expect(loudness(fromDb(-31))).toBe('quiet') + expect(loudness(fromDb(-15))).toBe('ok') + expect(loudness(fromDb(-1))).toBe('loud') + }) +}) + +describe('peak hold', () => { + it('holds the highest peak for 1.5 s, then follows the level', () => { + let hold = holdStep(undefined, -10, 0) + hold = holdStep(hold, -20, 1000) + expect(hold).toEqual({ db: -10, atMs: 0 }) + hold = holdStep(hold, -20, 1501) + expect(hold).toEqual({ db: -20, atMs: 1501 }) + hold = holdStep(hold, -5, 1600) + expect(hold).toEqual({ db: -5, atMs: 1600 }) + }) +}) + +describe('clip counting', () => { + it('counts one clip per burst, with the take time it began at', () => { + let log: ClipLog = EMPTY_CLIPS + log = clipStep(log, 0.5, 100) + expect(log.clips).toHaveLength(0) + log = clipStep(log, 1, 19_000) + log = clipStep(log, 1.2, 19_050) + log = clipStep(log, 1, 19_200) + expect(log.clips).toEqual([{ atMs: 19_000, peakDb: dbfs(1.2) }]) + log = clipStep(log, 1, 56_400) + expect(log.clips.map((c) => c.atMs)).toEqual([19_000, 56_400]) + }) + + it('counts a sample just under full scale, not one well under it', () => { + expect(clipStep(EMPTY_CLIPS, CLIP_LEVEL, 0).clips).toHaveLength(1) + expect(clipStep(EMPTY_CLIPS, fromDb(-0.5), 0).clips).toHaveLength(0) + }) + + it('never changes the log it was given', () => { + const before = clipStep(EMPTY_CLIPS, 1, 10) + const after = clipStep(before, 1, 5000) + expect(before.clips).toHaveLength(1) + expect(after.clips).toHaveLength(2) + }) + + it('reports the clips with their times', () => { + expect(clipReport([])).toBe('No clipping.') + expect(clipReport([{ atMs: 3200, peakDb: 0 }])).toBe('Clipped once, at 0:03.') + expect(clipReport([{ atMs: 19_000, peakDb: 0 }, { atMs: 56_000, peakDb: 0 }])).toBe('Clipped 2 times, at 0:19, 0:56.') + const many = Array.from({ length: 14 }, (_, i) => ({ atMs: i * 1000, peakDb: 0 })) + expect(clipReport(many, 3)).toBe('Clipped 14 times, at 0:00, 0:01, 0:02 and 11 more.') + expect(takeClock(3_725_000)).toBe('1:02:05') + }) +}) + +describe('hints', () => { + const feed = (blocks: [number, number][]): { state: HintState; hint: string } => { + let state = EMPTY_HINT + let hint = 'none' + for (const [db, at] of blocks) ({ state, hint } = hintStep(state, db, at)) + return { state, hint } + } + + it('asks to come closer after a few seconds of quiet speech, with silence between words', () => { + const blocks: [number, number][] = [] + for (let t = 0; t <= QUIET_HINT_MS; t += 50) blocks.push([t % 500 < 250 ? -30 : -70, t]) + expect(feed(blocks.slice(0, 20)).hint).toBe('none') + expect(feed(blocks).hint).toBe('quiet') + }) + + it('ends the quiet stretch on speech in the band', () => { + expect(feed([[-30, 0], [-30, 2000], [-15, 2500], [-30, 3200]]).hint).toBe('none') + }) + + it('asks to back off after repeated red, one hit per burst', () => { + expect(feed([[-1, 0], [-1, 50], [-1, 100]]).hint).toBe('none') + expect(feed([[-1, 0], [-15, 500], [-1, 1000], [-15, 1500], [-2, 2000]]).hint).toBe('loud') + expect(feed([[-1, 0], [-1, 1000], [-1, 12_000]]).hint).toBe('none') + }) +}) + +describe('the pre-roll level check', () => { + const speech = (db: number, n = 40): number[] => Array.from({ length: n }, (_, i) => fromDb(db - (i % 10))) + + it('says turn it up below the band, by about how much', () => { + const check = levelCheck([...speech(-28), ...Array(20).fill(0.0001)]) + expect(check.advice).toBe('up') + expect(check.byDb).toBeGreaterThanOrEqual(12) + expect(adviceText(check)).toMatch(/^Turn your input up about \d+ dB/) + }) + + it('says good inside the band', () => { + const check = levelCheck(speech(-13)) + expect(check.advice).toBe('ok') + expect(check.peakDb).toBeGreaterThanOrEqual(-18) + expect(adviceText(check)).toMatch(/^Good/) + }) + + it('says turn it down above the band or after a clip', () => { + expect(levelCheck(speech(-6)).advice).toBe('down') + const clipped = levelCheck([...speech(-15), 1]) + expect(clipped).toMatchObject({ advice: 'down', clips: 1 }) + expect(adviceText(clipped)).toMatch(/clipped once/) + expect(levelCheck([...speech(-15), 1, 1, 0.1, 1]).clips).toBe(2) + }) + + it('says when nothing was heard', () => { + const check = levelCheck(Array(50).fill(0.0005)) + expect(check.advice).toBe('silent') + expect(adviceText(check)).toMatch(/Nothing was heard/) + }) +}) diff --git a/tests/live-audit3.test.ts b/tests/live-audit3.test.ts index aef468b..33680c0 100644 --- a/tests/live-audit3.test.ts +++ b/tests/live-audit3.test.ts @@ -125,6 +125,32 @@ function rtmpServer(port: number, name: string): { out: string; proc: ChildProce return { out, proc, done: new Promise((r) => proc.on('close', () => r())) } } +/** + * An ingest server that takes a publisher again after a connection ends, as a real one does (FFmpeg's -listen 1 serves + * one connection, so an attempt the sender retries would find the port closed). Each connection writes its own file, + * -1.flv, -2.flv and so on. last() takes no new connection after the current one ends. + */ +function rtmpIngest(port: number, name: string): { files: () => string[]; alive: () => boolean; last: () => void; done: () => Promise; kill: () => void } { + let more = true + let n = 0 + let proc: ChildProcess | undefined + let closed: Promise = Promise.resolve() + const listen = (): void => { + n += 1 + const p = spawn('ffmpeg', ['-y', '-hide_banner', '-loglevel', 'error', '-listen', '1', '-i', `rtmp://127.0.0.1:${port}/live/${KEY}`, '-c', 'copy', path.join(work, `${name}-${n}.flv`)], { stdio: 'ignore' }) + proc = p + closed = new Promise((r) => p.on('close', () => { r(); if (more) listen() })) + } + listen() + return { + files: () => Array.from({ length: n }, (_, i) => path.join(work, `${name}-${i + 1}.flv`)), + alive: () => proc?.exitCode === null && proc.signalCode === null, + last: () => { more = false }, + done: () => closed, + kill: () => { more = false; proc?.kill('SIGKILL') }, + } +} + /** dts (seconds) of every packet by stream, in file order. */ function dtsOf(file: string): Map { const r = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'packet=stream_index,dts_time', '-of', 'csv=p=0', file], { encoding: 'utf8' }) @@ -329,16 +355,19 @@ maybe('one take with an RTMP destination and a live link at once', () => { // Start them again: the same feed goes to a fresh server, and the link's playlist keeps moving. const port2 = await freePort() - const second = rtmpServer(port2, 'a3-e') + const second = rtmpIngest(port2, 'a3-e') await call('/api/live/destinations', 'PUT', { id: dest, name: 'Local3', url: `rtmp://127.0.0.1:${port2}/live`, enabled: true }) await new Promise((r) => setTimeout(r, 1500)) - expect(second.proc.exitCode, 'the second server listens').toBeNull() + expect(second.alive(), 'the second server listens').toBe(true) const at = sequenceOf(await playlist()) const again = await call(`/api/live/${id}`, 'POST', {}) expect(again.status, again.text).toBe(202) await until('the destination live again', async () => (await call(`/api/live/${id}`)).json.status?.destinations[0]?.state === 'live', 60_000).catch(async (e: Error) => { - throw new Error(`${e.message}: ${JSON.stringify((await call(`/api/live/${id}`)).json)} server exit ${second.proc.exitCode} sent ${sent}`) + throw new Error(`${e.message}: ${JSON.stringify((await call(`/api/live/${id}`)).json)} server connections ${second.files().length} sent ${sent}`) }) + // The stream that went live is the last connection: the server takes no other after it ends. + second.last() + process.stdout.write(`live-audit3: the restarted destination went live on connection ${second.files().length}\n`) expect((await call(`/api/live/${id}`)).json.status.destinations).toHaveLength(1) await until('the link moving on', async () => sequenceOf(await playlist()) > at + 1, 40_000) expect(JSON.parse((await viewer(`/s-api/${liveId}/live/state`)).body).state).toBe('live') @@ -350,9 +379,9 @@ maybe('one take with an RTMP destination and a live link at once', () => { for (const t of tracks) await call(`/api/sessions/${id}/tracks/${t.id}/end`, 'POST', { durationMs: 20000 }) await call(`/api/sessions/${id}/control`, 'POST', { action: 'stop' }) await until('no ffmpeg child', () => ffmpegChildren().length === 0, 40_000) - await Promise.race([second.done, new Promise((r) => setTimeout(r, 15_000))]) - second.proc.kill('SIGKILL') - const seconds = Math.max(0, ...[...dtsOf(path.join(work, 'a3-e.flv')).values()].map((l) => l.length > 0 ? l[l.length - 1]! : 0)) + await Promise.race([second.done(), new Promise((r) => setTimeout(r, 15_000))]) + second.kill() + const seconds = Math.max(0, ...[...dtsOf(second.files().at(-1)!).values()].map((l) => l.length > 0 ? l[l.length - 1]! : 0)) expect(seconds, 'the second server received the feed').toBeGreaterThan(2) await call(`/api/live/destinations/${dest}`, 'DELETE') }, 240_000) diff --git a/tests/live-link-e2e.test.ts b/tests/live-link-e2e.test.ts index 6d46ca4..0cf33ad 100644 --- a/tests/live-link-e2e.test.ts +++ b/tests/live-link-e2e.test.ts @@ -27,6 +27,9 @@ const ffmpegOk = (() => { return e.status === 0 && e.stdout.includes('libx264') })() const maybe = ffmpegOk ? describe : describe.skip +// The latency check reads the clock burned into the host's picture with Tesseract; without it that part is skipped. +const ocrOk = spawnSync('tesseract', ['--version'], { encoding: 'utf8' }).status === 0 +if (!ocrOk) console.warn('live-link-e2e: the latency check skips, tesseract is not installed') let app: App let browser: Browser @@ -218,22 +221,24 @@ maybe('the live link in Chromium', () => { // The latency, glass to glass: from the host's screen to the viewer's video. const screenAt = await studio.page.evaluate(() => (window as unknown as { __screenAt?: number }).__screenAt) expect(screenAt).toBeGreaterThan(0) - const work = await tempDir('formrec-live-clock-') - const seen: number[] = [] - for (let i = 0; i < 24 && seen.length < 6; i += 1) { - const c = await pictureClock(viewer.page, work) - if (c) seen.push(Math.round(c.at - screenAt! - c.shownMs)) - await viewer.page.waitForTimeout(700) + if (ocrOk) { + const work = await tempDir('formrec-live-clock-') + const seen: number[] = [] + for (let i = 0; i < 24 && seen.length < 6; i += 1) { + const c = await pictureClock(viewer.page, work) + if (c) seen.push(Math.round(c.at - screenAt! - c.shownMs)) + await viewer.page.waitForTimeout(700) + } + expect(seen.length).toBeGreaterThanOrEqual(2) + seen.sort((a, b) => a - b) + const median = seen[Math.floor(seen.length / 2)]! + // The bound only holds on a machine that is not oversubscribed: this suite runs on shared two-core boxes where the + // load average has been past 20, and every stage (the recorder, the composing FFmpeg, the viewer) then runs slow. + const load = os.loadavg()[0]! / os.cpus().length + console.log(`live link latency (host screen to viewer video), ms: median ${median}, min ${seen[0]}, max ${seen[seen.length - 1]}, samples ${JSON.stringify(seen)}; load per core ${load.toFixed(1)}`) + expect(median).toBeGreaterThan(500) + if (load < 3) expect(median).toBeLessThan(12_000) } - expect(seen.length).toBeGreaterThanOrEqual(2) - seen.sort((a, b) => a - b) - const median = seen[Math.floor(seen.length / 2)]! - // The bound only holds on a machine that is not oversubscribed: this suite runs on shared two-core boxes where the - // load average has been past 20, and every stage (the recorder, the composing FFmpeg, the viewer) then runs slow. - const load = os.loadavg()[0]! / os.cpus().length - console.log(`live link latency (host screen to viewer video), ms: median ${median}, min ${seen[0]}, max ${seen[seen.length - 1]}, samples ${JSON.stringify(seen)}; load per core ${load.toFixed(1)}`) - expect(median).toBeGreaterThan(500) - if (load < 3) expect(median).toBeLessThan(12_000) // The window moves: old segments are deleted, the names are the fixed ones, the pictures are in the take's live folder. await expect.poll(async () => seqOf(await liveFiles(sessionId))[0] ?? 0, { timeout: 60_000 }).toBeGreaterThan(0) diff --git a/tests/master.test.ts b/tests/master.test.ts new file mode 100644 index 0000000..170f4c4 --- /dev/null +++ b/tests/master.test.ts @@ -0,0 +1,138 @@ +/** + * The Voice master's WAV on the server (src/studio/master.ts): ordered chunks into one fixed file, the header checked, + * the sizes written at the end, and recording.json's `capture` filled from the file at save (src/studio/finish.ts), + * through the studio feature's routes as well. + */ +import { describe, expect, it } from 'vitest' +import { readFile, stat } from 'node:fs/promises' +import path from 'node:path' +import { Readable } from 'node:stream' +import type { AddressInfo } from 'node:net' +import { Library } from '../src/store/library.js' +import { EBML_MAGIC, SessionError, Sessions } from '../src/store/sessions.js' +import { finishMaster, fixSizes, MASTER_FILE, Masters, readMasterState } from '../src/studio/master.js' +import { finishSession } from '../src/studio/finish.js' +import { PersonRecordingSchema } from '../src/model/person.js' +import { RecordingSchema } from '../src/model/recording.js' +import { createApp } from '../src/app.js' +import { encodePcm24, parseWavHeader, wavHeader } from '../shared/wav.js' +import { tempDir } from './helpers.js' + +const FORMAT = { sampleRate: 48_000, channels: 1, bitsPerSample: 24 } as const +const body = (bytes: Uint8Array): Readable => Readable.from([Buffer.from(bytes)]) +const tone = (n: number): Uint8Array => encodePcm24(Float32Array.from({ length: n }, (_, i) => Math.sin(i / 10) * 0.5)) +const firstChunk = (n: number): Uint8Array => Buffer.concat([wavHeader(FORMAT), tone(n)]) + +async function take() { + let now = 2_000_000 + const sessions = new Sessions(new Library(await tempDir()), () => now) + const s = await sessions.create('Voice', 'audio') + await sessions.control(s.id, 'start') + return { sessions, masters: new Masters(sessions), id: s.id, tick: (ms: number) => { now += ms } } +} + +const DETAILS = { + title: 'Voice', durationMs: 0, + capture: { + preset: 'voice-master', requested: { quality: '1080p', width: 1920, height: 1080 }, micEffects: false, roomToneMs: 8000, + tracks: [{ kind: 'mic', label: 'Built-in microphone', settings: { sampleRate: 48_000, channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false } }], + // A client's word about the master is never taken: the server fills it from its own file. + master: { file: MASTER_FILE, sampleRate: 1, bitsPerSample: 1, channels: 1, bytes: 1, durationMs: 1, complete: true }, + levels: { clips: [{ atMs: 3200, peakDb: 0 }] }, + }, +} + +describe('the master WAV', () => { + it('appends chunks in order, refuses gaps, takes repeats, and writes the sizes at the end', async () => { + const { masters, id, sessions } = await take() + expect(await masters.append(id, 0, body(firstChunk(4800)))).toEqual({ accepted: true, next: 1, bytes: 44 + 14_400 }) + expect(await masters.append(id, 0, body(tone(10)))).toEqual({ accepted: false, next: 1, bytes: 44 + 14_400 }) + await expect(masters.append(id, 3, body(tone(10)))).rejects.toMatchObject({ status: 409, extra: { next: 1 } }) + await masters.append(id, 1, body(tone(4800))) + const file = path.join(sessions.library.folder(id), MASTER_FILE) + expect(parseWavHeader(await readFile(file))?.dataBytes).toBe(0xffffffff) + const state = await masters.end(id, 200) + expect(state).toMatchObject({ chunks: 2, bytes: 44 + 28_800, ended: true, durationMs: 200, format: FORMAT }) + const bytes = await readFile(file) + expect(bytes.readUInt32LE(4)).toBe(36 + 28_800) + expect(bytes.readUInt32LE(40)).toBe(28_800) + expect((await stat(file)).mode & 0o777).toBe(0o600) + await expect(masters.append(id, 2, body(tone(10)))).rejects.toMatchObject({ status: 409, extra: { final: true } }) + }) + + it('refuses a first chunk that is not a PCM WAV, and a take that has not started or is saved', async () => { + const { masters, id, sessions } = await take() + await expect(masters.append(id, 0, body(Buffer.concat([EBML_MAGIC, Buffer.alloc(100)])))).rejects.toMatchObject({ status: 415 }) + expect(await readMasterState(sessions.library, id)).toBeUndefined() + const fresh = await sessions.create('Later', 'audio') + await expect(masters.append(fresh.id, 0, body(firstChunk(10)))).rejects.toBeInstanceOf(SessionError) + }) + + it('leaves a short file alone when fixing sizes', async () => { + const dir = await tempDir() + const file = path.join(dir, 'x.wav') + await (await import('node:fs/promises')).writeFile(file, Buffer.alloc(10)) + expect(await fixSizes(file)).toBe(10) + }) +}) + +describe('the capture in recording.json', () => { + it('saves the capture with the master described from the file, DSP flags and clips as sent', async () => { + const { masters, id, sessions, tick } = await take() + await masters.append(id, 0, body(firstChunk(48_000))) + tick(1000) + const stopped = await sessions.control(id, 'stop') + const rec = await finishSession({ session: stopped, details: PersonRecordingSchema.parse(DETAILS), library: sessions.library, codebase: {}, now: 0, remux: async () => false }) + expect(rec.capture?.master).toEqual({ file: MASTER_FILE, bytes: 44 + 144_000, durationMs: 1000, complete: false, ...FORMAT }) + expect(rec.capture?.tracks[0]?.settings).toMatchObject({ echoCancellation: false, noiseSuppression: false, autoGainControl: false }) + expect(rec.capture?.levels?.clips).toEqual([{ atMs: 3200, peakDb: 0 }]) + const saved = RecordingSchema.parse(JSON.parse(await readFile(path.join(sessions.library.folder(id), 'recording.json'), 'utf8'))) + expect(saved.capture?.preset).toBe('voice-master') + expect((await readFile(path.join(sessions.library.folder(id), MASTER_FILE))).readUInt32LE(40)).toBe(144_000) + }) + + it('writes no master when the take has none, and no capture when Save sent none', async () => { + const { id, sessions } = await take() + expect(await finishMaster(sessions.library, id)).toBeUndefined() + const stopped = await sessions.control(id, 'stop') + const rec = await finishSession({ session: stopped, details: PersonRecordingSchema.parse(DETAILS), library: sessions.library, codebase: {}, now: 0, remux: async () => false }) + expect(rec.capture?.master).toBeUndefined() + const { id: other, sessions: s2 } = await take() + const plain = await finishSession({ session: await s2.control(other, 'stop'), details: PersonRecordingSchema.parse({ title: 'Plain', durationMs: 0 }), library: s2.library, codebase: {}, now: 0, remux: async () => false }) + expect(plain.capture).toBeUndefined() + }) +}) + +describe('the studio feature routes', () => { + it('takes the master over HTTP and serves it with the recording', async () => { + const TOKEN = 'm'.repeat(40) + const app = createApp({ dataDir: await tempDir(), token: TOKEN, guestPort: 0, guestHost: '127.0.0.1', addresses: () => ['127.0.0.1'] }) + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)) + const base = `http://127.0.0.1:${(app.server.address() as AddressInfo).port}` + const auth = { Authorization: `Bearer ${TOKEN}` } + const json = async (p: string, method: string, data?: unknown): Promise => { + const res = await fetch(`${base}${p}`, { method, headers: { ...auth, 'Content-Type': 'application/json' }, ...(data === undefined ? {} : { body: JSON.stringify(data) }) }) + return { status: res.status, body: await res.json() } + } + try { + const s = (await json('/api/sessions', 'POST', { title: 'Voice', mode: 'audio' })).body + await json(`/api/sessions/${s.id}/control`, 'POST', { action: 'start' }) + const chunk = await fetch(`${base}/api/studio/takes/${s.id}/master?seq=0`, { method: 'POST', headers: auth, body: Buffer.from(firstChunk(4800)) }) + expect(await chunk.json()).toMatchObject({ accepted: true, next: 1 }) + const gap = await fetch(`${base}/api/studio/takes/${s.id}/master?seq=5`, { method: 'POST', headers: auth, body: Buffer.from(tone(10)) }) + expect(gap.status).toBe(409) + expect(await gap.json()).toMatchObject({ next: 1 }) + expect((await json(`/api/studio/takes/${s.id}/master/end`, 'POST', { durationMs: 100 })).body).toMatchObject({ ended: true }) + await json(`/api/sessions/${s.id}/control`, 'POST', { action: 'stop' }) + const saved = await json(`/api/sessions/${s.id}/save`, 'POST', DETAILS) + expect(saved.body.capture.master).toMatchObject({ file: MASTER_FILE, bytes: 44 + 14_400, complete: true }) + const wav = await fetch(`${base}/api/recordings/${s.id}/${MASTER_FILE}?token=${TOKEN}`) + expect(wav.status).toBe(200) + expect(wav.headers.get('content-type')).toBe('audio/wav') + expect(Buffer.from(await wav.arrayBuffer()).readUInt32LE(40)).toBe(14_400) + expect((await fetch(`${base}/api/recordings/${s.id}/${MASTER_FILE}`)).status).toBe(401) + } finally { + await app.close() + } + }) +}) diff --git a/tests/mcp-tools.test.ts b/tests/mcp-tools.test.ts index 4c2d4bd..f7aa03a 100644 --- a/tests/mcp-tools.test.ts +++ b/tests/mcp-tools.test.ts @@ -20,6 +20,7 @@ import { GUIDE } from '../src/mcp/guide.js' import { parseWalkthrough } from '../src/model/walkthrough.js' import { recordWalkthrough, withAbort } from '../src/runner/headless.js' import { Library } from '../src/store/library.js' +import { playerKey } from '../src/server/player-link.js' import type { Recording } from '../src/model/recording.js' import { tempDir, walk } from './helpers.js' @@ -90,7 +91,7 @@ describe('structured output', () => { const agents = (await client.callTool({ name: 'formrec_list', arguments: { source: 'agent', limit: 1 } })) as Reply expect((agents.structuredContent?.recordings as { id: string }[]).map((r) => r.id)).toEqual(['tour-1']) const got = (await client.callTool({ name: 'formrec_get', arguments: { id: 'tour-1' } })) as Reply - expect(got.structuredContent).toMatchObject({ id: 'tour-1', player: 'http://127.0.0.1:1/?token=t#/f/tour-1', files: { video: library.file('tour-1', 'video.webm') } }) + expect(got.structuredContent).toMatchObject({ id: 'tour-1', player: `http://127.0.0.1:1/?player=${await playerKey(library.dataDir, 'tour-1')}#/f/tour-1`, files: { video: library.file('tour-1', 'video.webm') } }) const missing = (await client.callTool({ name: 'formrec_get', arguments: { id: 'nope' } })) as Reply expect(missing).toMatchObject({ isError: true }) expect(missing.structuredContent).toBeUndefined() diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index 54da03b..37b0cd7 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -41,7 +41,7 @@ describe('mcp server', () => { const result = JSON.parse(text(await client.callTool({ name: 'formrec_demos', arguments: {} }))) expect(result.demos.map((d: { id: string }) => d.id).sort()).toEqual([...DEMO_IDS].sort()) const tour = result.demos.find((d: { id: string }) => d.id === 'self-tour') - expect(tour).toMatchObject({ kind: 'walkthrough', route: '#/demo/self-tour', player: 'http://127.0.0.1:8770/?token=x#/demo/self-tour' }) + expect(tour).toMatchObject({ kind: 'walkthrough', route: '#/demo/self-tour', player: 'http://127.0.0.1:8770/#/demo/self-tour' }) expect(tour.chapters[0]).toMatchObject({ id: 'home', startMs: 0 }) expect(tour.durationMs).toBeGreaterThan(0) const take = result.demos.find((d: { id: string }) => d.id === 'studio-guest') @@ -90,7 +90,8 @@ describe('mcp server', () => { const deps: ToolDeps = { library, playerBase: 'http://127.0.0.1:8770/?token=x', record: async () => library.save(fake) } const client = await connect(deps) const recorded = JSON.parse(text(await client.callTool({ name: 'formrec_record', arguments: { walkthrough: walk() } }))) - expect(recorded).toMatchObject({ id: 'tour-1', failedSteps: ['one'], player: 'http://127.0.0.1:8770/?token=x#/f/tour-1' }) + expect(recorded).toMatchObject({ id: 'tour-1', failedSteps: ['one'] }) + expect(recorded.player).toMatch(/^http:\/\/127\.0\.0\.1:8770\/\?player=[A-Za-z0-9_-]{43}#\/f\/tour-1$/) expect(recorded.chapters[0].code).toEqual(['a.ts:3 ok']) const list = JSON.parse(text(await client.callTool({ name: 'formrec_list', arguments: {} }))) expect(list.recordings).toEqual([expect.objectContaining({ id: 'tour-1', chapters: 1 })]) diff --git a/tests/mp4-ingest-browser.test.ts b/tests/mp4-ingest-browser.test.ts index 3e7998e..d31ce0a 100644 --- a/tests/mp4-ingest-browser.test.ts +++ b/tests/mp4-ingest-browser.test.ts @@ -117,6 +117,11 @@ describe('MP4 takes in a browser', () => { }, 120_000) it("Playwright's WebKit: a studio take with fake devices, when that build can record", async (ctx) => { + if (!existsSync(webkit.executablePath())) { + console.log("Playwright's WebKit is not installed (npx playwright install webkit); skipped") + ctx.skip() + return + } const wk = await webkit.launch() try { const context = await wk.newContext({ permissions: ['camera', 'microphone'], viewport: { width: 1440, height: 900 } }) diff --git a/tests/phone-android-e2e.test.ts b/tests/phone-android-e2e.test.ts index d5fa974..ed8f5c6 100644 --- a/tests/phone-android-e2e.test.ts +++ b/tests/phone-android-e2e.test.ts @@ -7,7 +7,7 @@ * everywhere else it is skipped with a message. The MediaProjection capture itself is not covered: it needs a device. */ import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { execFileSync, spawn } from 'node:child_process' +import { execFileSync, spawn, spawnSync } from 'node:child_process' import { existsSync, readdirSync, readFileSync } from 'node:fs' import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' import path from 'node:path' @@ -24,8 +24,24 @@ function tool(cmd: string, args: string[]): boolean { try { execFileSync(cmd, args, { stdio: 'ignore' }); return true } catch { return false } } +/** The major version of the JDK at `home` (or the one on the PATH), from `java -version`; 0 when there is none. */ +function javaMajor(home: string | undefined): number { + const r = spawnSync(home ? path.join(home, 'bin', 'java') : 'java', ['-version'], { encoding: 'utf8' }) + const m = /version "(\d+)(?:\.(\d+))?/.exec(`${r.stderr ?? ''}${r.stdout ?? ''}`) + if (r.status !== 0 || !m) return 0 + return m[1] === '1' ? Number(m[2]) : Number(m[1]) +} + +// apps/android's Gradle wrapper (8.10) runs on Java 17 to 23 (the Android Gradle Plugin needs 17). A machine whose +// default JDK is newer often has a supported one beside it (CI runners name them JAVA_HOME__). +const JDK = [process.env['JAVA_HOME'], ...['21', '17'].flatMap((v) => [process.env[`JAVA_HOME_${v}_X64`], process.env[`JAVA_HOME_${v}_ARM64`]]), undefined] + .filter((home, i, all) => home !== '' && all.indexOf(home) === i) + .map((home) => ({ home, major: javaMajor(home) })) +const jdk = JDK.find((j) => j.major >= 17 && j.major <= 23) + const missing = !SDK || !existsSync(path.join(SDK, 'platforms')) ? 'no Android SDK (set ANDROID_HOME; see apps/android/README.md)' - : !tool('java', ['-version']) ? 'no JDK on the PATH' + : !JDK.some((j) => j.major > 0) ? 'no JDK on the PATH' + : !jdk ? `no JDK that Gradle 8.10 runs on (17 to 23; found Java ${JDK.map((j) => j.major).filter(Boolean).join(', ')})` : !tool('ffmpeg', ['-version']) ? 'no ffmpeg' : '' if (missing) console.warn(`phone-android-e2e skipped: ${missing}`) @@ -45,7 +61,8 @@ function runGradle(env: Record): Promise<{ code: number; log: st const wrap = process.env.FORMREC_BUILD_WRAPPER const [cmd, argv] = wrap ? [wrap, ['./gradlew', ...args]] : ['./gradlew', args] return new Promise((resolve) => { - const child = spawn(cmd!, argv as string[], { cwd: ANDROID, env: { ...process.env, ANDROID_HOME: SDK, ...env } }) + const java = jdk?.home ? { JAVA_HOME: jdk.home } : {} + const child = spawn(cmd!, argv as string[], { cwd: ANDROID, env: { ...process.env, ANDROID_HOME: SDK, ...java, ...env } }) let log = '' child.stdout.on('data', (d: Buffer) => { log += d.toString('utf8') }) child.stderr.on('data', (d: Buffer) => { log += d.toString('utf8') }) diff --git a/tests/phone-capture-client.test.ts b/tests/phone-capture-client.test.ts new file mode 100644 index 0000000..b0cecf5 --- /dev/null +++ b/tests/phone-capture-client.test.ts @@ -0,0 +1,104 @@ +/** + * The studio's Phone panel as data, and the phone page's "Send a video from this phone" (issue #7), in Node: which + * sources are offered and why one cannot be used, the notes for what is missing, and the upload's order of calls. + */ +import { describe, expect, it } from 'vitest' +import { clockText, IOS_TOUCH_NOTE, missingNotes, sourceOptions, stillOffered, touchNote, type ServerSources, type ShellView } from '../web/src/phone-capture-logic.js' +import { SEND_CHUNK, sendVideo, titleOf, type Poster } from '../web/src/phone-send.js' + +const server = (over: Partial = {}): ServerSources => ({ + platform: 'darwin', adb: { found: true, howTo: '' }, ffmpeg: true, scrcpy: '3.3.1', android: [], simulators: [], airplay: [], ...over, +}) +const mac: ShellView = { desktop: true, mac: true, devices: [] } + +describe('the sources the Phone panel offers', () => { + it('lists an iPhone on USB first, then Android, simulators, the AirPlay mirror and a phone recording', () => { + const list = sourceOptions(server({ + android: [{ serial: 'R58M', state: 'device', link: 'usb', name: 'SM G973F' }, { serial: 'emulator-5554', state: 'device', link: 'emulator', name: 'sdk gphone64' }], + simulators: [{ udid: 'B1EF7B37-C466-47B6-AD70-6C4A270406FD', name: 'iPhone 17', runtime: 'iOS 26.4' }], + airplay: [{ id: 77, owner: 'AirPlayUIAgent', width: 786, height: 1704 }], + }), { ...mac, devices: [{ id: 'abc-123', name: 'Ana\'s iPhone', model: 'iOS Device' }] }) + expect(list.map((o) => [o.kind, o.label, o.blocked])).toEqual([ + ['ios-usb', 'Phone (Ana\'s iPhone)', ''], + ['android', 'Phone (SM G973F)', ''], + ['android', 'Phone (sdk gphone64)', ''], + ['simulator', 'Simulator (iPhone 17)', ''], + ['airplay', 'AirPlay mirror', ''], + ['file', 'A phone recording', ''], + ]) + expect(list[0]!.source).toEqual({ kind: 'ios-usb', name: 'Ana\'s iPhone' }) + expect(list[1]!.source).toEqual({ kind: 'android', serial: 'R58M' }) + expect(list[2]!.detail).toContain('emulator') + expect(list[4]!.source).toEqual({ kind: 'airplay', window: 77 }) + }) + + it('says what to do for a phone that cannot be recorded yet', () => { + const list = sourceOptions(server({ ffmpeg: false, android: [{ serial: 'A', state: 'unauthorized', link: 'usb', name: 'A' }, { serial: 'B', state: 'device', link: 'wifi', name: 'B' }] }), mac) + expect(list[0]!.blocked).toContain('Allow USB debugging') + expect(list[1]!.blocked).toContain('FFmpeg') + expect(stillOffered(list, 'android:A')).toBeUndefined() + expect(stillOffered(list, 'file')).toBe('file') + expect(stillOffered(list, 'gone')).toBeUndefined() + }) + + it('notes what is missing on each system', () => { + expect(missingNotes(server({ platform: 'win32', adb: { found: false, howTo: 'Install it.' } }), { desktop: true, mac: false, devices: [] })).toEqual([ + expect.stringContaining('needs a Mac'), 'Android: Install it.', + ]) + const browser = missingNotes(server(), { desktop: false, mac: true, devices: [] }) + expect(browser[0]).toContain('FormRec app') + expect(browser.some((l) => l.includes('USB debugging'))).toBe(true) + expect(browser.some((l) => l.includes('Screen Mirroring'))).toBe(true) + expect(missingNotes(server(), { ...mac, error: 'no access' })[0]).toBe('iPhone over USB: no access') + }) + + it('says how touches show', () => { + const [ios, android, sim] = sourceOptions(server({ android: [{ serial: 'A', state: 'device', link: 'usb', name: 'A' }], simulators: [{ udid: 'B1EF7B37-C466-47B6-AD70-6C4A270406FD', name: 'S', runtime: 'iOS 26' }] }), { ...mac, devices: [{ id: 'x', name: 'P', model: '' }] }) + expect(touchNote(ios, true)).toBe(IOS_TOUCH_NOTE) + expect(touchNote(android, true)).toContain('put back') + expect(touchNote(android, false)).toContain('not shown') + expect(touchNote(sim, true)).toContain('Simulator') + expect(touchNote(undefined, true)).toBe('') + expect(clockText(61_400)).toBe('1:01') + }) +}) + +describe('sending a video from the phone', () => { + it('creates an upload, sends it in order and completes it', async () => { + const calls: string[] = [] + const send: Poster = async (path, body) => { + calls.push(`${path} ${body instanceof Blob ? body.size : body ?? ''}`) + if (path.endsWith('/uploads')) return { status: 201, body: { id: 'n1' } } + if (path.includes('/chunks')) return { status: 200, body: { accepted: true } } + return { status: 200, body: { id: 'rec-1', title: 'ScreenRecording 1' } } + } + const file = Object.assign(new Blob([new Uint8Array(SEND_CHUNK + 10)]), { name: 'ScreenRecording 1.MOV' }) + const seen: number[] = [] + const rec = await sendVideo(file, (f) => seen.push(f), send) + expect(rec).toEqual({ id: 'rec-1', title: 'ScreenRecording 1' }) + expect(calls).toEqual([ + '/phone/api/native/uploads {"mode":"screen","source":"other","title":"ScreenRecording 1"}', + `/phone/api/native/uploads/n1/chunks?seq=0 ${SEND_CHUNK}`, + '/phone/api/native/uploads/n1/chunks?seq=1 10', + '/phone/api/native/uploads/n1/complete {"title":"ScreenRecording 1"}', + ]) + expect(seen.at(-1)).toBe(1) + }) + + it('discards the upload when the computer refuses a part, and says why', async () => { + const calls: string[] = [] + const send: Poster = async (path) => { + calls.push(path) + if (path.endsWith('/uploads')) return { status: 201, body: { id: 'n2' } } + if (path.includes('/chunks')) return { status: 415, body: { error: 'the first chunk must start an MP4 file (ftyp box)' } } + return { status: 200, body: {} } + } + await expect(sendVideo(Object.assign(new Blob(['text']), { name: 'a.txt' }), () => undefined, send)).rejects.toThrow(/ftyp/) + expect(calls.at(-1)).toBe('/phone/api/native/uploads/n2/discard') + }) + + it('titles a video by its file name', () => { + expect(titleOf('RPReplay_Final1700000000.MP4')).toBe('RPReplay_Final1700000000') + expect(titleOf('')).toBe('Phone recording') + }) +}) diff --git a/tests/phone-feed.test.ts b/tests/phone-feed.test.ts new file mode 100644 index 0000000..fb687ee --- /dev/null +++ b/tests/phone-feed.test.ts @@ -0,0 +1,220 @@ +/** + * A phone as the take's picture (issue #7), on a real server (port 0, a temp data folder): the routes need the token, + * a phone recording file is uploaded and narrated over (the take keeps the part that played, picture and sound on + * their own tracks), a recorded-here source is joined across a pause, the source list answers, and the export + * layouts are built. Media are made with FFmpeg; the tests that need it skip without it. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { execFileSync } from 'node:child_process' +import { copyFile, readFile } from 'node:fs/promises' +import path from 'node:path' +import type { AddressInfo } from 'node:net' +import { createApp, type App } from '../src/app.js' +import { concatList, durationOf, joinArgs, PhoneFeed, PhoneSourceSchema } from '../src/features/phone/feed.js' +import { exportArgs, phoneTracks, videoGraph } from '../src/features/phone/export.js' +import { sweepPhoneFiles, videoKind } from '../src/features/phone/files.js' +import { airplayArgs, type Producer } from '../src/features/phone/producers.js' +import { tempDir } from './helpers.js' + +const TOKEN = 'p'.repeat(40) +const ffmpeg = (() => { + try { + execFileSync(process.env.FORMREC_FFMPEG || 'ffmpeg', ['-version'], { stdio: 'ignore' }) + return process.env.FORMREC_FFMPEG || 'ffmpeg' + } catch { + return undefined + } +})() +let app: App +let dataDir: string +let base: string +let port = 0 +let media = '' + +async function call(p: string, method = 'GET', body?: unknown): Promise<{ status: number; json: any }> { + const raw = body instanceof Uint8Array + const res = await fetch(`${base}${p}`, { + method, + headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': raw ? 'application/octet-stream' : 'application/json' }, + ...(body === undefined ? {} : { body: raw ? body : JSON.stringify(body) }), + }) + return { status: res.status, json: await res.json().catch(() => ({})) } +} + +async function newTake(title: string): Promise { + const { json: session } = await call('/api/sessions', 'POST', { title, mode: 'screen' }) + await call(`/api/sessions/${session.id}/control`, 'POST', { action: 'start' }) + return session.id as string +} + +async function saveTake(id: string, durationMs: number): Promise { + await call(`/api/sessions/${id}/control`, 'POST', { action: 'stop' }) + const { status, json } = await call(`/api/sessions/${id}/save`, 'POST', { title: 'Phone take', durationMs }) + expect(status).toBe(200) + return json +} + +beforeAll(async () => { + dataDir = await tempDir('formrec-phone-feed-') + app = createApp({ dataDir, token: TOKEN, webDir: path.resolve(import.meta.dirname, '..', 'dist', 'web'), guestPort: 0, guestHost: '127.0.0.1', addresses: () => ['127.0.0.1'] }) + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)) + port = (app.server.address() as AddressInfo).port + base = `http://127.0.0.1:${port}` + if (ffmpeg) { + media = path.join(dataDir, 'phone-made.mp4') + execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc=size=390x844:rate=60', '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', '-t', '4', '-c:v', 'libx264', '-g', '30', '-c:a', 'aac', '-shortest', media]) + } +}, 60_000) +afterAll(async () => { + await app?.close() +}) + +describe('phone capture routes', () => { + it('need the token', async () => { + expect((await fetch(`${base}/api/phone/sources`)).status).toBe(401) + expect((await fetch(`${base}/api/phone/feed/start`, { method: 'POST' })).status).toBe(401) + }) + + it('list what can be recorded here and what is missing', async () => { + const { status, json } = await call('/api/phone/sources') + expect(status).toBe(200) + expect(json).toMatchObject({ platform: process.platform, scrcpy: '3.3.1' }) + expect(Array.isArray(json.android)).toBe(true) + expect(Array.isArray(json.simulators)).toBe(true) + expect(Array.isArray(json.airplay)).toBe(true) + expect(typeof json.adb.found).toBe('boolean') + if (!json.adb.found) expect(json.adb.howTo).toContain('adb') + }, 30_000) + + it('refuse a source they do not know, a take that is not recording, and a file that is not a video', async () => { + expect((await call('/api/phone/feed/start', 'POST', { sessionId: 'x', source: { kind: 'android', serial: '-s evil' } })).status).toBe(400) + const { json: session } = await call('/api/sessions', 'POST', { title: 'Not started', mode: 'screen' }) + const r = await call('/api/phone/feed/start', 'POST', { sessionId: session.id, source: { kind: 'file', file: `f${'0'.repeat(24)}` } }) + expect(r.status).toBe(409) + const bad = await call('/api/phone/files?name=notes.txt', 'POST', new TextEncoder().encode('hello, not a video')) + expect(bad.status).toBe(415) + expect((await call('/api/phone/feed/stop', 'POST', { sessionId: session.id })).status).toBe(404) + }) + + it.skipIf(!ffmpeg)('narrate over a phone recording: the take keeps what played, picture and phone sound on their own tracks', async () => { + const up = await call('/api/phone/files?name=ScreenRecording.mp4', 'POST', new Uint8Array(await readFile(media))) + expect(up.status).toBe(200) + expect(up.json.id).toMatch(/^f[a-f0-9]{24}$/) + expect(up.json.durationMs).toBeGreaterThan(3500) + const served = await fetch(`${base}/api/phone/files/${up.json.id}?token=${TOKEN}`, { headers: { Range: 'bytes=0-11' } }) + expect(served.status).toBe(206) + const id = await newTake('Narrated') + const started = await call('/api/phone/feed/start', 'POST', { sessionId: id, source: { kind: 'file', file: up.json.id } }) + expect(started.status).toBe(200) + expect(started.json).toMatchObject({ source: 'file', state: 'recording', audio: true }) + expect((await call(`/api/phone/feed?sessionId=${id}`)).json.feed.state).toBe('recording') + const stopped = await call('/api/phone/feed/stop', 'POST', { sessionId: id, durationMs: 2500 }) + expect(stopped.status).toBe(200) + expect(stopped.json.tracks).toEqual(['host-screen', 'host-phone']) + expect(stopped.json.durationMs).toBeGreaterThan(2000) + expect(stopped.json.durationMs).toBeLessThan(3200) + const rec = await saveTake(id, 2500) + const screen = rec.tracks.find((t: any) => t.id === 'host-screen') + const sound = rec.tracks.find((t: any) => t.id === 'host-phone') + expect(screen).toMatchObject({ kind: 'screen', person: 'Phone', file: 'track-host-screen.mp4', complete: true }) + expect(sound).toMatchObject({ kind: 'mic', person: 'Phone audio', file: 'track-host-phone.mp4', complete: true }) + // Native size and frame rate, picture stream copied. + let log = '' + try { execFileSync(ffmpeg!, ['-hide_banner', '-i', path.join(dataDir, 'recordings', rec.id, screen.file)], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) { log = String((e as { stderr: Buffer }).stderr) } + expect(log).toMatch(/390x844/) + expect(log).toMatch(/60 fps/) + expect(log).not.toMatch(/Audio:/) + }, 60_000) + + it.skipIf(!ffmpeg)('build the phone layouts on export', async () => { + const id = await newTake('Layouts') + const up = await call('/api/phone/files?name=a.mp4', 'POST', new Uint8Array(await readFile(media))) + await call('/api/phone/feed/start', 'POST', { sessionId: id, source: { kind: 'file', file: up.json.id } }) + await call('/api/phone/feed/stop', 'POST', { sessionId: id, durationMs: 1000 }) + const rec = await saveTake(id, 1000) + const made = await call(`/api/phone/recordings/${rec.id}/export`, 'POST', { layout: 'portrait-blur' }) + expect(made.status).toBe(200) + expect(made.json.bytes).toBeGreaterThan(1000) + const got = await fetch(`${base}${made.json.url}?token=${TOKEN}`) + expect(got.status).toBe(200) + expect(got.headers.get('content-disposition')).toContain('phone-portrait-blur.mp4') + let log = '' + try { execFileSync(ffmpeg!, ['-hide_banner', '-i', path.join(dataDir, 'recordings', rec.id, 'phone-export-portrait-blur.mp4')], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) { log = String((e as { stderr: Buffer }).stderr) } + expect(log).toMatch(/1080x1920/) + expect((await call(`/api/phone/recordings/${rec.id}/export`, 'POST', { layout: 'sideways' })).status).toBe(400) + }, 120_000) +}) + +describe('a recorded-here phone source', () => { + it.skipIf(!ffmpeg)('is joined across a pause into one picture track', async () => { + const segment = path.join(dataDir, 'seg-src.mkv') + execFileSync(ffmpeg!, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc=size=320x640:rate=30', '-t', '1', '-c:v', 'libx264', '-f', 'matroska', segment]) + const begun: number[] = [] + const fake: Producer & { segment: string } = { + audio: false, audioNote: 'a test source has no sound', segment: '', + async begin(dir, n) { this.segment = path.join(dir, `seg-${n}.mkv`); await copyFile(segment, this.segment); begun.push(n); return Date.now() }, + async end() { return { video: [this.segment], audio: [] } }, + async close() {}, + } + const feed = new PhoneFeed({ port: () => port, token: TOKEN, dataDir, ffmpeg: async () => ffmpeg, producer: async () => fake }) + const id = await newTake('Joined') + const started = await feed.start(id, PhoneSourceSchema.parse({ kind: 'simulator', udid: 'B1EF7B37-C466-47B6-AD70-6C4A270406FD' })) + expect(started.notes).toEqual(['No phone sound: a test source has no sound.']) + await feed.pause(id) + expect(feed.status(id)!.state).toBe('paused') + await feed.resume(id) + const done = await feed.stop(id) + expect(begun).toEqual([0, 1]) + expect(done.tracks).toEqual(['host-screen']) + expect(done.durationMs).toBeGreaterThan(1800) + expect(done.durationMs).toBeLessThan(2300) + await expect(feed.stop(id)).rejects.toThrow(/no phone/) + const rec = await saveTake(id, done.durationMs) + expect(rec.tracks.map((t: any) => t.id)).toEqual(['host-screen']) + }, 60_000) +}) + +describe('pure parts', () => { + it('validate sources strictly', () => { + expect(PhoneSourceSchema.safeParse({ kind: 'android', serial: 'R58M123ABC' }).success).toBe(true) + expect(PhoneSourceSchema.parse({ kind: 'android', serial: '192.168.1.20:5555' })).toMatchObject({ showTaps: true, demoMode: false, audio: true }) + expect(PhoneSourceSchema.safeParse({ kind: 'android', serial: '--help' }).success).toBe(false) + expect(PhoneSourceSchema.safeParse({ kind: 'simulator', udid: 'booted; rm' }).success).toBe(false) + expect(PhoneSourceSchema.safeParse({ kind: 'file', file: '../../etc/passwd' }).success).toBe(false) + }) + + it('join with FFmpeg arguments that copy the picture and keep only local files', () => { + expect(concatList(["/a/seg-0.mkv", "/a/it's.mkv"])).toBe("file '/a/seg-0.mkv'\nfile '/a/it'\\''s.mkv'\n") + const v = joinArgs('/a/list.txt', undefined, '/a/out.mp4', 'video', 2500) + expect(v).toEqual(expect.arrayContaining(['-f', 'concat', '-safe', '0', '-t', '2.500', '-c:v', 'copy', '-an'])) + const a = joinArgs(undefined, '/a/in.mov', '/a/out.m4a', 'audio') + expect(a).toEqual(expect.arrayContaining(['-i', '/a/in.mov', '-vn', '-c:a', 'aac'])) + expect(a).not.toContain('-t') + expect(durationOf(' Duration: 00:01:02.50, start: 0')).toBe(62_500) + expect(durationOf('nothing')).toBeUndefined() + }) + + it('crop the AirPlay window on the display it is on', () => { + const args = airplayArgs({ id: 1, owner: 'AirPlayUIAgent', screen: 1, bounds: { x: 0, y: 0, width: 1, height: 1 }, crop: { x: 10, y: 20, width: 300, height: 600 } }, 'h264_videotoolbox', '/a/seg.mkv') + expect(args).toEqual(expect.arrayContaining(['-f', 'avfoundation', '-i', 'Capture screen 1:none', '-vf', 'crop=300:600:10:20,format=yuv420p', '-c:v', 'h264_videotoolbox'])) + }) + + it('lay out the export', () => { + expect(videoGraph('portrait-blur', false)).toContain('1080:1920') + expect(videoGraph('beside-camera', false)).toBe(videoGraph('landscape-frame', false)) + expect(videoGraph('beside-camera', true)).toContain('[1:v]') + const args = exportArgs({ file: '/r/phone.mp4', offsetMs: 500 }, { file: '/r/cam.webm', offsetMs: 0 }, [{ file: '/r/mic.webm', offsetMs: 0 }, { file: '/r/phone-a.mp4', offsetMs: 500 }], 'beside-camera', 3000, '/r/out.mp4') + expect(args).toEqual(expect.arrayContaining(['-itsoffset', '-0.500', '-i', '/r/cam.webm', '-t', '3.000'])) + expect(args.join(' ')).toContain('[2:a][3:a]amix=inputs=2') + const rec = { tracks: [{ kind: 'mic', person: 'Host' }, { kind: 'screen', person: 'Screen' }, { kind: 'screen', person: 'Phone' }] } as any + expect(phoneTracks(rec).phone.person).toBe('Phone') + }) + + it('know a video by its first bytes and sweep what was left', async () => { + expect(videoKind(Buffer.from('\0\0\0\x20ftypqt ', 'latin1'))).toBe('mp4') + expect(videoKind(Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0, 0, 0, 0]))).toBe('webm') + expect(videoKind(Buffer.from('hello world!'))).toBeUndefined() + const dir = await tempDir('formrec-phone-sweep-') + expect(await sweepPhoneFiles(dir)).toBe(0) + }) +}) diff --git a/tests/phone-pwa-offline.test.ts b/tests/phone-pwa-offline.test.ts index 2d902ab..19ce3be 100644 --- a/tests/phone-pwa-offline.test.ts +++ b/tests/phone-pwa-offline.test.ts @@ -92,8 +92,8 @@ describe('the phone page as an installed web app', () => { // The service worker is active and has taken the shell into its cache. await expect.poll(() => root.getAttribute('data-phone-worker')).toBe('on') await page.evaluate(() => navigator.serviceWorker.ready) - const cached = await page.evaluate(async () => (await (await caches.open('formrec-phone-shell-1')).keys()).map((r) => new URL(r.url).pathname)) - for (const p of ['/phone/', '/phone/phone.js', '/phone/phone-queue.js', '/phone/manifest.webmanifest', '/app.css', '/styles/phone.css']) expect(cached, p).toContain(p) + const cached = await page.evaluate(async () => (await (await caches.open('formrec-phone-shell-2')).keys()).map((r) => new URL(r.url).pathname)) + for (const p of ['/phone/', '/phone/phone.js', '/phone/phone-queue.js', '/phone/phone-send.js', '/phone/manifest.webmanifest', '/app.css', '/styles/phone.css']) expect(cached, p).toContain(p) expect(cached.some((p) => p.startsWith('/phone/api/'))).toBe(false) // Add to Home Screen guidance for Android, closed, with its steps. const install = page.locator('[data-phone-install]:visible') diff --git a/tests/phone-scrcpy.test.ts b/tests/phone-scrcpy.test.ts new file mode 100644 index 0000000..ce3e443 --- /dev/null +++ b/tests/phone-scrcpy.test.ts @@ -0,0 +1,177 @@ +/** + * The scrcpy client side (issue #7): the frame header, the handshakes, the server command for the pinned version, the + * download check, and the Matroska writer the pictures go through. With FFmpeg present, a real H.264 stream is cut + * into access units, sent through a fake scrcpy socket exactly as the server frames it, written by MkvVideoWriter, + * and read back by FFmpeg with its timestamps. + */ +import { describe, expect, it } from 'vitest' +import { execFileSync } from 'node:child_process' +import { readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { PassThrough } from 'node:stream' +import { + ByteReader, CODEC, DEVICE_JAR, deviceName, ensureServer, frameHeader, newScid, parseHeader, readAudioHandshake, readVideoHandshake, + SCRCPY_SERVER_SHA256, SCRCPY_SERVER_URL, SCRCPY_VERSION, serverCommand, sha256, socketName, +} from '../src/features/phone/scrcpy.js' +import { avcC, MkvVideoWriter, splitAnnexB, toLengthPrefixed, vintSize } from '../src/features/phone/mkv.js' +import { tempDir } from './helpers.js' + +const ffmpeg = (() => { + try { + execFileSync(process.env.FORMREC_FFMPEG || 'ffmpeg', ['-version'], { stdio: 'ignore' }) + return process.env.FORMREC_FFMPEG || 'ffmpeg' + } catch { + return undefined + } +})() + +describe('the frame header', () => { + it('carries the config and key flags above a 62-bit PTS, and the size', () => { + const h = frameHeader({ key: true, ptsUs: 123_456_789, size: 4321 }) + expect(h.length).toBe(12) + expect(h[0]! & 0x40).toBe(0x40) + expect(parseHeader(h)).toEqual({ config: false, key: true, ptsUs: 123_456_789, size: 4321 }) + expect(parseHeader(frameHeader({ config: true, size: 30 }))).toMatchObject({ config: true, key: false, size: 30 }) + expect(() => parseHeader(Buffer.alloc(4))).toThrow() + }) +}) + +describe('the handshakes', () => { + it('read the dummy byte, the name and the video size, then packets split anywhere', async () => { + const wire = new PassThrough() + const reader = new ByteReader(wire) + const name = Buffer.alloc(64) + name.write('Pixel 8 Pro') + const meta = Buffer.alloc(12) + meta.writeUInt32BE(CODEC.h264, 0) + meta.writeUInt32BE(1080, 4) + meta.writeUInt32BE(2400, 8) + const payload = Buffer.from([0, 0, 0, 1, 0x65, 1, 2, 3]) + const all = Buffer.concat([Buffer.from([0]), name, meta, frameHeader({ config: true, size: 4 }), Buffer.from([0, 0, 0, 1]), frameHeader({ key: true, ptsUs: 5000, size: payload.length }), payload]) + // One byte at a time: nothing may depend on how the socket cuts the stream. + void (async () => { for (const b of all) { wire.write(Buffer.from([b])); await new Promise((r) => setImmediate(r)) } wire.end() })() + expect(await readVideoHandshake(reader)).toEqual({ name: 'Pixel 8 Pro', codec: 'h264', width: 1080, height: 2400 }) + expect(await reader.packet()).toMatchObject({ config: true, key: false }) + const frame = await reader.packet() + expect(frame).toMatchObject({ config: false, key: true, ptsUs: 5000 }) + expect(frame.data.equals(payload)).toBe(true) + await expect(reader.packet()).rejects.toThrow(/closed/) + }) + + it('say why there is no sound', async () => { + for (const [id, want] of [[0, { none: expect.stringContaining('Android 11') }], [1, { none: expect.stringContaining('could not') }], [CODEC.raw, { codec: 'raw' }]] as const) { + const wire = new PassThrough() + const reader = new ByteReader(wire) + const b = Buffer.alloc(4) + b.writeUInt32BE(id) + wire.end(b) + expect(await readAudioHandshake(reader)).toEqual(want) + } + }) + + it('refuse an oversized packet', async () => { + const wire = new PassThrough() + const reader = new ByteReader(wire) + wire.end(frameHeader({ size: 0xffffffff })) + await expect(reader.packet()).rejects.toThrow(/not a picture/) + }) + + it('clean a device name', () => { + expect(deviceName(Buffer.from('Galaxy\u0007 S24\u0000junk'))).toBe('Galaxy S24') + }) +}) + +describe('the pinned server', () => { + it('is started with the version, H.264, raw sound and no control', () => { + const scid = newScid() + expect(scid).toMatch(/^[0-9a-f]{8}$/) + const cmd = serverCommand({ scid, audio: true }) + expect(cmd.slice(0, 5)).toEqual([`CLASSPATH=${DEVICE_JAR}`, 'app_process', '/', 'com.genymobile.scrcpy.Server', SCRCPY_VERSION]) + expect(cmd).toEqual(expect.arrayContaining([`scid=${scid}`, 'tunnel_forward=true', 'control=false', 'video_codec=h264', 'audio=true', 'audio_codec=raw', 'max_size=0'])) + expect(serverCommand({ scid, audio: false })).not.toContain('audio_codec=raw') + expect(() => serverCommand({ scid: '1; rm -rf /', audio: false })).toThrow() + expect(socketName(scid)).toBe(`localabstract:scrcpy_${scid}`) + expect(SCRCPY_SERVER_URL).toBe('https://github.com/Genymobile/scrcpy/releases/download/v3.3.1/scrcpy-server-v3.3.1') + expect(SCRCPY_SERVER_SHA256).toMatch(/^[0-9a-f]{64}$/) + }) + + it('is refused when the download does not match the published SHA-256, and nothing is kept', async () => { + const dir = await tempDir('formrec-scrcpy-') + const junk = new Response(new Uint8Array([1, 2, 3]), { status: 200 }) + await expect(ensureServer(dir, (async () => junk) as unknown as typeof fetch)).rejects.toThrow(/SHA-256/) + await expect(readFile(path.join(dir, 'phone', 'scrcpy', `scrcpy-server-v${SCRCPY_VERSION}`))).rejects.toThrow() + await expect(ensureServer(dir, (async () => new Response('no', { status: 404 })) as unknown as typeof fetch)).rejects.toThrow(/404/) + }) + + it('is used without a download once it is there and matches', async () => { + const dir = await tempDir('formrec-scrcpy-') + let fetched = 0 + const fake = (async () => { fetched += 1; return new Response('x') }) as unknown as typeof fetch + // A file that is there but does not match is fetched again (and refused here). + await import('node:fs/promises').then(async (fs) => { + await fs.mkdir(path.join(dir, 'phone', 'scrcpy'), { recursive: true }) + await writeFile(path.join(dir, 'phone', 'scrcpy', `scrcpy-server-v${SCRCPY_VERSION}`), 'tampered') + }) + await expect(ensureServer(dir, fake)).rejects.toThrow(/SHA-256/) + expect(fetched).toBe(1) + expect(sha256(Buffer.from('abc'))).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') + }) +}) + +describe('the Matroska writer', () => { + it('writes EBML sizes and splits Annex B', () => { + expect(vintSize(1)).toEqual(Buffer.from([0x81])) + expect(vintSize(200)).toEqual(Buffer.from([0x40, 200])) + const nals = splitAnnexB(Buffer.from([0, 0, 0, 1, 0x67, 1, 0, 0, 1, 0x68, 2, 0, 0, 0, 1, 0x65, 3, 4])) + expect(nals.map((n) => [...n])).toEqual([[0x67, 1], [0x68, 2], [0x65, 3, 4]]) + expect([...toLengthPrefixed(Buffer.from([0, 0, 0, 1, 0x09, 0xf0, 0, 0, 0, 1, 0x65, 7]))]).toEqual([0, 0, 0, 2, 0x65, 7]) + const record = avcC(Buffer.from([0, 0, 0, 1, 0x67, 0x64, 0x00, 0x28, 0xac, 0, 0, 0, 1, 0x68, 0xee])) + expect([...record.subarray(0, 6)]).toEqual([1, 0x64, 0x00, 0x28, 0xff, 0xe1]) + expect(() => avcC(Buffer.from([0, 0, 0, 1, 0x65]))).toThrow(/SPS/) + }) + + it.skipIf(!ffmpeg)('keeps the device timestamps through FFmpeg (real H.264 framed as scrcpy sends it)', async () => { + const dir = await tempDir('formrec-mkv-') + const raw = path.join(dir, 'in.h264') + execFileSync(ffmpeg!, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc=size=360x640:rate=30', '-t', '2', '-c:v', 'libx264', '-g', '30', '-bf', '0', '-x264-params', 'aud=1', '-f', 'h264', raw]) + const stream = await readFile(raw) + // Cut at access unit delimiters, as MediaCodec hands over one frame per buffer. + const aud = Buffer.from([0, 0, 0, 1, 0x09]) + const units: Buffer[] = [] + for (let at = stream.indexOf(aud); at >= 0;) { + const next = stream.indexOf(aud, at + 5) + units.push(stream.subarray(at, next < 0 ? stream.length : next)) + at = next + } + const nalsOf = (u: Buffer) => splitAnnexB(u).map((n) => n[0]! & 0x1f) + const configNals = splitAnnexB(units[0]!).filter((n) => [7, 8].includes(n[0]! & 0x1f)) + const config = Buffer.concat(configNals.flatMap((n) => [Buffer.from([0, 0, 0, 1]), n])) + // Frames at a doubled spacing (15 fps of device time): the output's length must follow the timestamps, not a rate. + const wire = new PassThrough() + const reader = new ByteReader(wire) + for (const [i, u] of units.entries()) wire.write(Buffer.concat([frameHeader({ key: nalsOf(u).includes(5), ptsUs: 1_000_000 + i * 66_667, size: u.length }), u])) + wire.end() + const parts: Buffer[] = [] + const mkv = new MkvVideoWriter((b) => parts.push(b), { width: 360, height: 640 }) + for (let i = 0; i < units.length; i += 1) { + const p = await reader.packet() + mkv.frame(config, p.ptsUs!, p.key, p.data) + } + const file = path.join(dir, 'seg.mkv') + await writeFile(file, Buffer.concat(parts)) + const mp4 = path.join(dir, 'out.mp4') + execFileSync(ffmpeg!, ['-v', 'error', '-y', '-i', file, '-c', 'copy', '-movflags', '+faststart', mp4]) + const probe = (f: string) => { + try { execFileSync(ffmpeg!, ['-hide_banner', '-i', f], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) { return String((e as { stderr: Buffer }).stderr) } + return '' + } + const log = probe(mp4) + expect(log).toMatch(/Video: h264/) + expect(log).toMatch(/360x640/) + const m = /Duration: 00:00:(\d\d\.\d+)/.exec(log) + expect(Number(m![1])).toBeGreaterThan(3.5) + expect(Number(m![1])).toBeLessThan(4.5) + // The whole file decodes. + execFileSync(ffmpeg!, ['-v', 'error', '-i', mp4, '-f', 'null', '-']) + }, 60_000) +}) diff --git a/tests/phone-sources.test.ts b/tests/phone-sources.test.ts new file mode 100644 index 0000000..200e6a5 --- /dev/null +++ b/tests/phone-sources.test.ts @@ -0,0 +1,166 @@ +/** + * Phone capture sources (issue #7): what adb, simctl and the window list say, parsed; where adb is looked for; and + * the adb commands for show taps and the clean status bar, applied and put back through a recording runner. + */ +import { describe, expect, it } from 'vitest' +import { adbCandidates, adbHowTo, linkOf, parseAdbDevices, parseAirPlayWindows, parseSimctl, runtimeName } from '../src/features/phone/discover.js' +import { AdbHelpers, demoModeOff, demoModeOn, readShowTouches, settingValue, writeShowTouches } from '../src/features/phone/adb.js' + +describe('adb devices -l', () => { + const out = [ + '* daemon not running; starting now at tcp:5037', + '* daemon started successfully', + 'List of devices attached', + 'R58M123ABC device usb:1-1 product:beyond1lteeea model:SM_G973F device:beyond1 transport_id:1', + 'emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:2', + '192.168.1.20:5555 device product:panther model:Pixel_7 device:panther transport_id:3', + 'adb-2A111FDH20009Y-abcDEF._adb-tls-connect._tcp\tdevice product:husky model:Pixel_8_Pro device:husky transport_id:5', + '0123456789ABCDEF unauthorized usb:1-2 transport_id:4', + 'ZY22ABC offline', + 'XYZ no permissions (user in plugdev group; are your udev rules wrong?); see [http://developer.android.com/tools/device.html]', + '', + ].join('\r\n') + + it('lists every device with its state, link and model', () => { + const list = parseAdbDevices(out) + expect(list.map((d) => [d.serial, d.state, d.link, d.name])).toEqual([ + ['R58M123ABC', 'device', 'usb', 'SM G973F'], + ['emulator-5554', 'device', 'emulator', 'sdk gphone64 arm64'], + ['192.168.1.20:5555', 'device', 'wifi', 'Pixel 7'], + ['adb-2A111FDH20009Y-abcDEF._adb-tls-connect._tcp', 'device', 'wifi', 'Pixel 8 Pro'], + ['0123456789ABCDEF', 'unauthorized', 'usb', '0123456789ABCDEF'], + ['ZY22ABC', 'offline', 'usb', 'ZY22ABC'], + ['XYZ', 'no permissions', 'usb', 'XYZ'], + ]) + }) + + it('answers nothing for an empty list or noise', () => { + expect(parseAdbDevices('List of devices attached\n\n')).toEqual([]) + expect(parseAdbDevices('adb: command not found')).toEqual([]) + }) + + it('tells a wireless device from a USB one by its serial', () => { + expect(linkOf('10.0.0.5:37099')).toBe('wifi') + expect(linkOf('emulator-5556')).toBe('emulator') + expect(linkOf('HT7A1B2C3')).toBe('usb') + }) +}) + +describe('simctl list devices booted -j', () => { + it('keeps the booted, available simulators with their runtime', () => { + const json = JSON.stringify({ + devices: { + 'com.apple.CoreSimulator.SimRuntime.iOS-26-4': [ + { udid: 'B1EF7B37-C466-47B6-AD70-6C4A270406FD', name: 'iPhone 17', state: 'Booted', isAvailable: true }, + { udid: '11111111-2222-3333-4444-555555555555', name: 'iPhone Air', state: 'Shutdown', isAvailable: true }, + ], + 'com.apple.CoreSimulator.SimRuntime.watchOS-12-0': [{ udid: 'AAAAAAAA-2222-3333-4444-555555555555', name: 'Watch', state: 'Booted', isAvailable: false }], + }, + }) + expect(parseSimctl(json)).toEqual([{ udid: 'B1EF7B37-C466-47B6-AD70-6C4A270406FD', name: 'iPhone 17', runtime: 'iOS 26.4' }]) + }) + + it('refuses what is not its output', () => { + expect(parseSimctl('')).toEqual([]) + expect(parseSimctl('{"devices": 3}')).toEqual([]) + expect(parseSimctl(JSON.stringify({ devices: { x: [{ udid: '../../etc', name: 'n', state: 'Booted' }] } }))).toEqual([]) + }) + + it('names runtimes', () => { + expect(runtimeName('com.apple.CoreSimulator.SimRuntime.iOS-18-2')).toBe('iOS 18.2') + expect(runtimeName('odd')).toBe('odd') + }) +}) + +describe('the AirPlay mirror window', () => { + const screens = [{ x: 0, y: 0, width: 1512, height: 982, scale: 2 }, { x: 1512, y: -200, width: 1920, height: 1080, scale: 1 }] + + it('is found by its owner and cropped in the pixels of its display', () => { + const text = JSON.stringify({ + windows: [ + { id: 77, owner: 'AirPlayUIAgent', bounds: { X: 600, Y: 100, Width: 393, Height: 852 } }, + { id: 78, owner: 'AirPlay Receiver', bounds: { X: 1612, Y: 150, Width: 400, Height: 800 } }, + { id: 79, owner: 'Terminal', bounds: { X: 0, Y: 0, Width: 800, Height: 600 } }, + { id: 80, owner: 'AirPlayUIAgent', bounds: { X: 10, Y: 10, Width: 20, Height: 20 } }, + ], + screens, + }) + const found = parseAirPlayWindows(text) + expect(found.map((w) => w.id)).toEqual([77, 78]) + expect(found[0]).toMatchObject({ screen: 0, crop: { x: 1200, y: 200, width: 786, height: 1704 } }) + // The second display sits right of the main one; in AppKit its frame starts at y -200, so its top in Quartz is 102. + expect(found[1]).toMatchObject({ screen: 1, crop: { x: 100, y: 48, width: 400, height: 800 } }) + }) + + it('clamps a window that runs past its display and keeps sizes even', () => { + const text = JSON.stringify({ windows: [{ id: 1, owner: 'AirPlayUIAgent', bounds: { X: 1300, Y: 700, Width: 301, Height: 401 } }], screens: [screens[0]] }) + const [w] = parseAirPlayWindows(text) + expect(w!.crop).toEqual({ x: 2600, y: 1400, width: 424, height: 564 }) + }) + + it('answers nothing for bad input', () => { + expect(parseAirPlayWindows('nope')).toEqual([]) + expect(parseAirPlayWindows(JSON.stringify({ windows: [], screens: [] }))).toEqual([]) + }) +}) + +describe('finding adb', () => { + it('looks on the PATH, in the SDK variables and the usual folders, never bundled', () => { + const mac = adbCandidates({ PATH: '/usr/bin:/opt/x', ANDROID_HOME: '/sdk' }, 'darwin', '/Users/u') + expect(mac).toEqual(['/usr/bin/adb', '/opt/x/adb', '/sdk/platform-tools/adb', '/Users/u/Library/Android/sdk/platform-tools/adb', '/opt/homebrew/bin/adb', '/usr/local/bin/adb']) + const win = adbCandidates({ Path: 'C:\\tools', LOCALAPPDATA: 'C:\\Users\\u\\AppData\\Local' }, 'win32', 'C:\\Users\\u') + expect(win).toEqual(['C:\\tools\\adb.exe', 'C:\\Users\\u\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe']) + expect(adbCandidates({ FORMREC_ADB: '/x/adb', PATH: '' }, 'linux', '/home/u')[0]).toBe('/x/adb') + }) + + it('says how to install it on each system', () => { + expect(adbHowTo('darwin')).toContain('android-platform-tools') + expect(adbHowTo('win32')).toContain('Platform-Tools') + expect(adbHowTo('linux')).toContain('apt install adb') + }) +}) + +describe('show taps and the clean status bar', () => { + it('are exact adb commands', () => { + expect(readShowTouches('S1')).toEqual(['-s', 'S1', 'shell', 'settings', 'get', 'system', 'show_touches']) + expect(writeShowTouches('S1', '1')).toEqual(['-s', 'S1', 'shell', 'settings', 'put', 'system', 'show_touches', '1']) + expect(writeShowTouches('S1', 'null')).toEqual(['-s', 'S1', 'shell', 'settings', 'delete', 'system', 'show_touches']) + const on = demoModeOn('S1') + expect(on[0]).toEqual(['-s', 'S1', 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', '1']) + expect(on[2]).toEqual(['-s', 'S1', 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'clock', '-e', 'hhmm', '0941']) + expect(demoModeOff('S1', '0')).toEqual([ + ['-s', 'S1', 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'exit'], + ['-s', 'S1', 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', '0'], + ]) + expect(settingValue('1\n')).toBe('1') + expect(settingValue('null')).toBe('null') + expect(settingValue('Exception occurred while executing')).toBe('null') + }) + + it('are put back as they were after the take, once', async () => { + const ran: string[] = [] + const answers: Record = { 'settings get system show_touches': '0\n', 'settings get global sysui_demo_allowed': 'null\n' } + const helpers = new AdbHelpers(async () => '/sdk/adb', async (_cmd, args) => { + const line = args.slice(3).join(' ') + ran.push(line) + return answers[line] ?? '' + }) + expect(await helpers.apply('S1', { showTaps: true, demoMode: true })).toEqual([]) + expect(helpers.holding()).toEqual(['S1']) + expect(ran).toContain('settings put system show_touches 1') + expect(ran.filter((l) => l.includes('com.android.systemui.demo')).length).toBe(6) + ran.length = 0 + await helpers.restore('S1') + await helpers.restore('S1') + expect(ran).toEqual(['settings put system show_touches 0', 'am broadcast -a com.android.systemui.demo -e command exit', 'settings delete global sysui_demo_allowed']) + expect(helpers.holding()).toEqual([]) + }) + + it('report a device that refuses and leave nothing to restore for it', async () => { + const helpers = new AdbHelpers(async () => '/sdk/adb', async () => { throw new Error('device unauthorized') }) + const problems = await helpers.apply('S2', { showTaps: true, demoMode: false }) + expect(problems).toEqual(['show taps: device unauthorized']) + const none = new AdbHelpers(async () => undefined) + expect(await none.apply('S3', { showTaps: true, demoMode: true })).toEqual(['adb is not installed']) + }) +}) diff --git a/tests/player-link-browser.test.ts b/tests/player-link-browser.test.ts new file mode 100644 index 0000000..f6360f1 --- /dev/null +++ b/tests/player-link-browser.test.ts @@ -0,0 +1,88 @@ +/** + * A player link in Chromium: opened in a browser that has no run token, it shows that recording's player under a + * Player link bar, takes the key out of the address, plays media through /api/player only, and makes no call that + * succeeds anywhere else. Settings, Agents, Player links, Rotate stops the link. Needs `npm run build` (serves dist/web). + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { existsSync } from 'node:fs' +import { writeFile } from 'node:fs/promises' +import path from 'node:path' +import type { AddressInfo } from 'node:net' +import { chromium, type Browser } from 'playwright' +import { createApp, type App } from '../src/app.js' +import { playerLinkFor } from '../src/server/player-link.js' +import type { Recording } from '../src/model/recording.js' +import { tempDir } from './helpers.js' + +const WEB = path.join(path.resolve(import.meta.dirname, '..'), 'dist', 'web') +const TOKEN = 'q'.repeat(40) +let app: App +let browser: Browser +let base: string + +beforeAll(async () => { + if (!existsSync(path.join(WEB, 'player-link.js'))) throw new Error('run npm run build first') + app = createApp({ dataDir: await tempDir('formrec-plink-web-'), token: TOKEN, webDir: WEB, guestPort: 0 }) + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)) + base = `http://127.0.0.1:${(app.server.address() as AddressInfo).port}` + const lib = app.features.library + await lib.save({ + formrec: 1, id: 'tour', title: 'Linked tour', summary: '', source: 'agent', createdAt: '2026-11-28T00:00:00.000Z', video: 'video.webm', durationMs: 1000, + chapters: [{ stepId: 'a', title: 'First step', say: '', startMs: 0, endMs: 1000, code: [] }], + } as Recording) + await writeFile(lib.file('tour', 'video.webm'), Buffer.alloc(16)) + browser = await chromium.launch() +}) +afterAll(async () => { + await browser?.close() + await app?.close() +}) + +describe('a player link in the browser', () => { + it('opens only that recording, read only, with the key out of the address', async () => { + const link = await playerLinkFor(app.features.dataDir, base, 'tour') + const context = await browser.newContext({ viewport: { width: 1280, height: 800 } }) + const page = await context.newPage() + const errors: Error[] = [] + page.on('pageerror', (e) => errors.push(e)) + const ok: string[] = [] + page.on('response', (r) => { + const u = new URL(r.url()) + if (u.pathname.startsWith('/api/') && r.status() < 400) ok.push(u.pathname) + }) + await page.goto(link) + await page.waitForSelector('[data-view="link"] [data-link-bar="tour"]') + expect(await page.locator('[data-view="link"] h1').textContent()).toBe('Linked tour') + expect(await page.locator('[data-chapter="a"]').count()).toBe(1) + expect(page.url()).toBe(`${base}/#/f/tour`) + const src = await page.locator('[data-player-stage] video').first().getAttribute('src') + expect(src).toMatch(/^\/api\/player\/tour\/video\.webm\?key=[A-Za-z0-9_-]{43}$/) + expect(await page.locator('[data-player-delete], [data-player-formcut], [data-player-more]').count()).toBe(0) + expect(ok.every((p) => p.startsWith('/api/player/tour')), ok.join(', ')).toBe(true) + expect(errors).toEqual([]) + await context.close() + }) + + it('Settings, Agents, Player links, Rotate stops the link', async () => { + const link = await playerLinkFor(app.features.dataDir, base, 'tour') + const key = new URL(link).searchParams.get('player')! + const context = await browser.newContext({ viewport: { width: 1280, height: 800 } }) + const page = await context.newPage() + await page.goto(`${base}/?token=${TOKEN}#/`) + await page.evaluate(() => { const b = document.createElement('button'); b.dataset['settingsOpen'] = 'agents'; document.body.append(b); b.click(); b.remove() }) + const row = page.locator('[data-agents-player-links]') + await row.waitFor() + const box = await row.boundingBox() + await page.locator('[data-agents-rotate-player-links]').click() + await expect.poll(() => page.locator('[data-agents-result]').textContent(), { timeout: 30_000 }).toMatch(/Player links replaced/) + expect((await fetch(`${base}/api/player/tour?key=${key}`)).status).toBe(401) + const after = await row.boundingBox() + expect([after?.width, after?.height]).toEqual([box?.width, box?.height]) + + const stale = await context.newPage() + await stale.goto(link.replace('127.0.0.1', 'localhost')) + await stale.waitForSelector('#view .error') + expect(await stale.locator('#view .error').textContent()).toMatch(/not valid/) + await context.close() + }) +}) diff --git a/tests/player-link-store.test.ts b/tests/player-link-store.test.ts new file mode 100644 index 0000000..b2878b4 --- /dev/null +++ b/tests/player-link-store.test.ts @@ -0,0 +1,54 @@ +/** + * The player link secret on folders that are not ideal: a damaged secret file, a file system with no hard links, and a + * data folder that cannot hold the secret at all. A tool's answer must still arrive, and never with the run's token. + */ +import { describe, expect, it, vi } from 'vitest' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { tempDir } from './helpers.js' + +const noLinks = vi.hoisted(() => ({ on: false })) +vi.mock('node:fs/promises', async (original) => { + const real = await original() + return { + ...real, + link: async (from: string, to: string) => { + if (noLinks.on) throw Object.assign(new Error('operation not supported'), { code: 'ENOTSUP' }) + return real.link(from, to) + }, + } +}) + +const { playerKey, playerKeyMatches, playerSecretFile } = await import('../src/server/player-link.js') +const { keyLinksIn } = await import('../src/mcp/player-links.js') + +describe('the player link secret', () => { + it('a damaged secret file is replaced, and the new key opens the player', async () => { + const dir = await tempDir('formrec-plink-store-') + await mkdir(path.dirname(playerSecretFile(dir)), { recursive: true }) + await writeFile(playerSecretFile(dir), 'cut\n') + const key = await playerKey(dir, 'tour') + expect(await playerKeyMatches(dir, 'tour', key)).toBe(true) + expect((await readFile(playerSecretFile(dir), 'utf8')).trim()).not.toBe('cut') + }) + + it('a file system with no hard links still gets one secret', async () => { + const dir = await tempDir('formrec-plink-store-') + noLinks.on = true + try { + const keys = await Promise.all(Array.from({ length: 4 }, () => playerKey(dir, 'tour'))) + expect(new Set(keys).size).toBe(1) + expect(await playerKeyMatches(dir, 'tour', keys[0])).toBe(true) + } finally { + noLinks.on = false + } + }) + + it('an answer is still given when no secret can be kept, with no key and no run token', async () => { + const root = await tempDir('formrec-plink-store-') + const file = path.join(root, 'not-a-folder') + await writeFile(file, 'x') + const out = await keyLinksIn('open http://127.0.0.1:9/?token=secret#/f/tour now', 'http://127.0.0.1:9/?token=secret', file) + expect(out).toBe('open http://127.0.0.1:9/#/f/tour now') + }) +}) diff --git a/tests/player-link.test.ts b/tests/player-link.test.ts new file mode 100644 index 0000000..a03d711 --- /dev/null +++ b/tests/player-link.test.ts @@ -0,0 +1,147 @@ +/** + * Player links: the links in MCP answers carry no run token, only a player key that opens that one recording's player + * (/api/player/ and its media) and no other route, and Settings' Rotate makes every link given so far stop working. + * Real app on a temp data folder, its /mcp endpoint over Streamable HTTP. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { writeFile } from 'node:fs/promises' +import type { AddressInfo } from 'node:net' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' +import { createApp, type App } from '../src/app.js' +import type { Recording } from '../src/model/recording.js' +import { keyLinks, keyLinksIn } from '../src/mcp/player-links.js' +import { playerKey, playerKeyMatches, rotatePlayerLinks } from '../src/server/player-link.js' +import { tempDir } from './helpers.js' + +const TOKEN = 'p'.repeat(40) +let app: App +let base: string +let client: Client + +function sample(id: string): Recording { + return { + formrec: 1, id, title: 'Tour', summary: '', source: 'agent', createdAt: '2026-11-28T00:00:00.000Z', video: 'video.webm', durationMs: 1000, + chapters: [{ stepId: 'a', title: 'A', say: '', startMs: 0, endMs: 1000, code: [] }], + } as Recording +} + +beforeAll(async () => { + app = createApp({ dataDir: await tempDir('formrec-plink-'), token: TOKEN, guestPort: 0, guestHost: '127.0.0.1', addresses: () => ['127.0.0.1'] }) + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)) + base = `http://127.0.0.1:${(app.server.address() as AddressInfo).port}` + const lib = app.features.library + for (const id of ['tour', 'other']) { + await lib.save(sample(id)) + await writeFile(lib.file(id, 'video.webm'), Buffer.from('not really a video')) + } + client = new Client({ name: 'player-link-test', version: '1' }) + await client.connect(new StreamableHTTPClientTransport(new URL(`${base}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${TOKEN}` } } })) +}) +afterAll(async () => { + await client?.close().catch(() => undefined) + await app?.close() +}) + +const answer = async (name: string, args: Record): Promise => + ((await client.callTool({ name, arguments: args })) as { content: { text: string }[] }).content[0]?.text ?? '' + +async function linkOf(id: string): Promise { + const got = JSON.parse(await answer('formrec_get', { id })) as { player: string } + return new URL(got.player) +} + +const get = (p: string, auth?: string) => fetch(`${base}${p}`, auth ? { headers: { Authorization: `Bearer ${auth}` } } : {}) + +describe('player links in MCP answers', () => { + it('carry no run token, only a player key for that recording', async () => { + const text = await answer('formrec_get', { id: 'tour' }) + expect(text).not.toContain(TOKEN) + expect(text).not.toMatch(/token=/) + const link = await linkOf('tour') + expect(link.origin).toBe(base) + expect(link.hash).toBe('#/f/tour') + expect(link.searchParams.get('token')).toBeNull() + expect(link.searchParams.get('player')).toMatch(/^[A-Za-z0-9_-]{43}$/) + }) + + it('the key opens that recording and its media through /api/player', async () => { + const key = (await linkOf('tour')).searchParams.get('player')! + const rec = await get(`/api/player/tour?key=${key}`) + expect(rec.status).toBe(200) + expect(((await rec.json()) as Recording).id).toBe('tour') + expect((await get('/api/player/tour', key)).status).toBe(200) + const video = await get(`/api/player/tour/video.webm?key=${key}`) + expect(video.status).toBe(200) + expect(await video.text()).toBe('not really a video') + }) + + it('the key reaches no other route and no other recording', async () => { + const key = (await linkOf('tour')).searchParams.get('player')! + for (const p of ['/api/info', '/api/recordings', '/api/recordings/tour', '/api/recordings/tour/video.webm', '/api/agents', '/api/sessions']) { + expect((await get(`${p}?token=${key}`)).status, p).toBe(401) + expect((await get(p, key)).status, p).toBe(401) + } + expect((await get(`/api/player/other?key=${key}`)).status).toBe(401) + expect((await get(`/api/player/other/video.webm?key=${key}`)).status).toBe(401) + expect((await get(`/api/player/tour/recording.json?key=${key}`)).status).toBe(404) + expect((await get(`/api/player/tour/a/b?key=${key}`)).status).toBe(404) + expect((await fetch(`${base}/api/player/tour?key=${key}`, { method: 'DELETE' })).status).toBe(404) + expect((await fetch(`${base}/mcp`, { method: 'POST', headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' }, body: '{}' })).status).toBe(401) + expect((await get('/api/player/tour')).status).toBe(401) + expect((await get('/api/player/tour', TOKEN)).status).toBe(401) + }) + + it('Rotate in Settings stops every player link given so far, and new answers carry working ones', async () => { + const old = (await linkOf('tour')).searchParams.get('player')! + expect((await fetch(`${base}/api/agents/player-links/rotate`, { method: 'POST', headers: { Authorization: `Bearer ${old}` } })).status).toBe(401) + const rotated = await fetch(`${base}/api/agents/player-links/rotate`, { method: 'POST', headers: { Authorization: `Bearer ${TOKEN}` } }) + expect(rotated.status).toBe(200) + expect(await rotated.json()).toEqual({ rotated: true }) + expect((await get(`/api/player/tour?key=${old}`)).status).toBe(401) + const fresh = (await linkOf('tour')).searchParams.get('player')! + expect(fresh).not.toBe(old) + expect((await get(`/api/player/tour?key=${fresh}`)).status).toBe(200) + }) +}) + +describe('keying links', () => { + it('drops the base query, keys a recording link, and leaves other links without a secret', async () => { + const dir = await tempDir('formrec-plink-unit-') + const b = 'http://127.0.0.1:9/?token=secret' + const out = await keyLinksIn(`see ${b}#/f/tour and ${b}#/demo/self-tour or ${b}#/edit/tour.`, b, dir) + expect(out).not.toContain('secret') + expect(out).toContain(`http://127.0.0.1:9/?player=${await playerKey(dir, 'tour')}#/f/tour and`) + expect(out).toContain('http://127.0.0.1:9/#/demo/self-tour or') + expect(out).toContain('http://127.0.0.1:9/#/edit/tour.') + }) + + it('walks a JSON value without changing it, and changes nothing with no base', async () => { + const dir = await tempDir('formrec-plink-unit-') + const value = { list: [{ player: 'http://127.0.0.1:9/#/f/a' }], n: 3, none: null } + const out = await keyLinks(value, 'http://127.0.0.1:9/', dir) + expect(value.list[0]!.player).toBe('http://127.0.0.1:9/#/f/a') + expect(out.list[0]!.player).toBe(`http://127.0.0.1:9/?player=${await playerKey(dir, 'a')}#/f/a`) + expect(out.n).toBe(3) + expect(await keyLinks(value, undefined, dir)).toBe(value) + }) + + it('keys asked for at once on a new folder share one secret', async () => { + const dir = await tempDir('formrec-plink-unit-') + const keys = await Promise.all(Array.from({ length: 8 }, () => playerKey(dir, 'a'))) + expect(new Set(keys).size).toBe(1) + expect(await playerKeyMatches(dir, 'a', keys[0])).toBe(true) + }) + + it('a key matches only its recording, never with no secret, and not after a rotation', async () => { + const dir = await tempDir('formrec-plink-unit-') + expect(await playerKeyMatches(dir, 'a', 'x'.repeat(43))).toBe(false) + const key = await playerKey(dir, 'a') + expect(await playerKeyMatches(dir, 'a', key)).toBe(true) + expect(await playerKeyMatches(dir, 'b', key)).toBe(false) + expect(await playerKeyMatches(dir, '../a', key)).toBe(false) + await rotatePlayerLinks(dir) + expect(await playerKeyMatches(dir, 'a', key)).toBe(false) + await expect(playerKey(dir, 'Bad/Id')).rejects.toThrow(/not a recording id/) + }) +}) diff --git a/tests/renditions-browser.test.ts b/tests/renditions-browser.test.ts index 3d8c12b..8a0849d 100644 --- a/tests/renditions-browser.test.ts +++ b/tests/renditions-browser.test.ts @@ -187,6 +187,43 @@ describe('the quality control on the share page', () => { await ctx.close() }, 240_000) + it('a pause or a play pressed while a quality loads is the one that holds when it has loaded', async () => { + const ctx = await context() + const page = await ctx.newPage() + page.setDefaultTimeout(60_000) + // The new quality's file is held back until the test lets it go, so the press lands inside the swap every time. + let letGo: () => void = () => undefined + const gate = (): Promise => new Promise((r) => { letGo = r }) + let held = gate() + await page.route(/media\/video\?q=(1080|720)/, async (route) => { await held; await route.continue() }) + await page.goto(page1) + await page.locator('[data-sv-quality]').selectOption('360') + await loaded(page, '360') + await page.locator('[data-pc-play]').click() + await page.waitForFunction(() => (document.querySelector('[data-sv-video]') as HTMLVideoElement).currentTime > 0.5) + + // Playing, a swap starts, and the person pauses during it: paused once the new source shows. + await page.locator('[data-sv-quality]').selectOption('1080') + await page.waitForFunction(() => (document.querySelector('[data-sv-video]') as HTMLVideoElement).dataset['svHeight'] === '1080') + await page.locator('[data-pc-play]').click() + letGo() + await loaded(page, '1080') + await page.waitForTimeout(600) + expect((await state(page)).paused).toBe(true) + + // Paused, a swap starts, and the person presses play during it: playing once the new source shows. + held = gate() + await page.locator('[data-sv-quality]').selectOption('720') + await page.waitForFunction(() => (document.querySelector('[data-sv-video]') as HTMLVideoElement).dataset['svHeight'] === '720') + await page.locator('[data-pc-play]').click() + letGo() + await loaded(page, '720') + await page.waitForFunction(() => !(document.querySelector('[data-sv-video]') as HTMLVideoElement).paused) + const t = (await state(page)).t + await page.waitForFunction((from) => (document.querySelector('[data-sv-video]') as HTMLVideoElement).currentTime > from + 0.3, t) + await ctx.close() + }, 240_000) + it('remembers the choice in this browser, and works when storage refuses', async () => { const ctx = await context() const page = await ctx.newPage() diff --git a/tests/runner-screencast.test.ts b/tests/runner-screencast.test.ts new file mode 100644 index 0000000..d26d210 --- /dev/null +++ b/tests/runner-screencast.test.ts @@ -0,0 +1,86 @@ +/** + * The high-quality capture (src/runner/capture.ts) keeps a clipped screenshot out of the video. The walkthrough + * baseline takes page.screenshot({ clip }) while the screencast runs, Chromium draws just the clip for a moment and + * sends that frame to the screencast too; in the video it was a zoomed flash that scene detection took for a page change. + * Such a frame is dropped by its size, but one still reached the video on a Linux runner, so the runner also holds the + * capture while it takes the picture (Screencast.during) and drops what was drawn meanwhile by the frame's own time. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { spawnSync } from 'node:child_process' +import path from 'node:path' +import { chromium, type Browser } from 'playwright' +import { drawnWhileHeld, ffmpegAvailable, HOLD_SLACK_MS, isPageFrame, Screencast } from '../src/runner/capture.js' +import { ffmpegPath } from '../src/studio/remux.js' +import { tempDir } from './helpers.js' + +const withFfmpeg = ffmpegAvailable() ? it : it.skip +const W = 800 +const H = 450 + +describe('which screencast frames are the page', () => { + it('keeps a frame at the viewport size and drops one at a clip size', () => { + expect(isPageFrame({ deviceWidth: 800, deviceHeight: 450 }, { width: 800, height: 450 })).toBe(true) + expect(isPageFrame({ deviceWidth: 300, deviceHeight: 80 }, { width: 800, height: 450 })).toBe(false) + expect(isPageFrame({ deviceWidth: 800, deviceHeight: 80 }, { width: 800, height: 450 })).toBe(false) + }) + + it('keeps every frame when there is no fixed viewport or no size in the metadata', () => { + expect(isPageFrame({ deviceWidth: 300, deviceHeight: 80 }, null)).toBe(true) + expect(isPageFrame({}, { width: 800, height: 450 })).toBe(true) + }) + + it('drops a frame drawn inside a held span, by the frame\'s own time, with the slack on either side', () => { + const held = [{ from: 10_000, until: 10_050 }] + expect(drawnWhileHeld({ timestamp: 10.02 }, held)).toBe(true) + expect(drawnWhileHeld({ timestamp: (10_000 - HOLD_SLACK_MS) / 1000 }, held)).toBe(true) + expect(drawnWhileHeld({ timestamp: (10_050 + HOLD_SLACK_MS) / 1000 }, held)).toBe(true) + expect(drawnWhileHeld({ timestamp: (10_050 + HOLD_SLACK_MS + 1) / 1000 }, held)).toBe(false) + expect(drawnWhileHeld({ timestamp: 9.5 }, held)).toBe(false) + expect(drawnWhileHeld({}, held)).toBe(false) + expect(drawnWhileHeld({ timestamp: 10.02 }, [])).toBe(false) + }) +}) + +describe('a clipped screenshot during a capture', () => { + let browser: Browser + beforeAll(async () => { browser = await chromium.launch() }) + afterAll(async () => { await browser?.close() }) + + withFfmpeg('never reaches the video', async () => { + const dir = await tempDir('formrec-screencast-') + const file = path.join(dir, 'video.webm') + const ctx = await browser.newContext({ viewport: { width: W, height: H } }) + const page = await ctx.newPage() + // White above, black below; the clip is inside the black half, so a leaked clip frame is black from the top. + await page.setContent('
') + // Something paints four times a second, as the runner's pulse does, so frames keep coming. + await page.evaluate(() => { const p = document.getElementById('p')!; setInterval(() => { p.style.opacity = p.style.opacity === '0' ? '1' : '0' }, 250) }) + const cast = new Screencast({ file, width: W, height: H }) + try { + await cast.follow(page) + await page.waitForTimeout(400) + for (let i = 0; i < 6; i++) { + // As the runner takes the baseline's picture (headless.ts perform). + await cast.during(() => page.screenshot({ clip: { x: 100, y: 300, width: 300, height: 80 }, type: 'png', animations: 'allow', caret: 'initial' })) + await page.waitForTimeout(150) + } + await page.waitForTimeout(300) + await cast.stop() + } finally { + await ctx.close() + } + // Every frame of the video, 80 by 45 in gray: the top rows stay white throughout. + const raw = spawnSync(ffmpegPath(), ['-hide_banner', '-loglevel', 'error', '-i', file, '-vf', 'scale=80:45,format=gray', '-f', 'rawvideo', '-'], { maxBuffer: 64 * 1024 * 1024 }) + expect(raw.status).toBe(0) + const size = 80 * 45 + const frames = Math.floor(raw.stdout.length / size) + expect(frames).toBeGreaterThan(20) + const dark: number[] = [] + for (let f = 0; f < frames; f++) { + let sum = 0 + for (let i = 0; i < 80 * 8; i++) sum += raw.stdout[f * size + i]! + if (sum / (80 * 8) < 200) dark.push(f) + } + expect(dark, `frames whose top is not white: ${dark.join(', ')}`).toEqual([]) + }, 60_000) +}) diff --git a/tests/script-logic.test.ts b/tests/script-logic.test.ts new file mode 100644 index 0000000..e4476b5 --- /dev/null +++ b/tests/script-logic.test.ts @@ -0,0 +1,70 @@ +/** Script mode (web/src/script-logic.ts): paragraphs from Markdown or text, and the chapter each Space drops. */ +import { describe, expect, it } from 'vitest' +import { advance, beginReading, paragraphTitle, parseScript, progressText, startScript, type ScriptMark } from '../web/src/script-logic.js' + +const SCRIPT = [ + '---', + '# Welcome', + '', + 'This is the **first** paragraph,', + 'over two lines.', + '', + '- a point to make', + '', + '```', + 'const code = "not read aloud"', + '```', + '', + 'The last paragraph.', + '', +].join('\n') + +describe('parsing a script', () => { + it('splits on blank lines, keeps headings as their own paragraph and drops code and rules', () => { + expect(parseScript(SCRIPT)).toEqual(['Welcome', 'This is the first paragraph, over two lines.', 'a point to make', 'The last paragraph.']) + }) + + it('reads plain text and Windows line ends', () => { + expect(parseScript('One.\r\n\r\nTwo\r\nand more.')).toEqual(['One.', 'Two and more.']) + expect(parseScript(' \n\n')).toEqual([]) + }) + + it('titles a paragraph by its first words', () => { + expect(paragraphTitle('Short one.')).toBe('Short one.') + const long = 'This paragraph is far too long to be a chapter title as it stands, so it is cut at a word.' + const title = paragraphTitle(long) + expect(title.length).toBeLessThanOrEqual(63) + expect(title.endsWith('...')).toBe(true) + expect(long.startsWith(title.slice(0, -3))).toBe(true) + }) +}) + +describe('reading through it', () => { + it('drops a chapter at the start, at each Space, and closes after the last paragraph', () => { + const marks: ScriptMark[] = [] + let state = startScript(['First.', 'Second.', 'Third.']) + expect(advance(state, 100).mark).toBeUndefined() + let step = beginReading(state, 8000) + state = step.state + marks.push(step.mark!) + expect(beginReading(state, 9000).mark).toBeUndefined() + for (const at of [15_000, 22_500, 30_000, 31_000]) { + step = advance(state, at) + state = step.state + if (step.mark) marks.push(step.mark) + } + expect(marks).toEqual([ + { title: '1. First.', say: 'First.', atMs: 8000 }, + { title: '2. Second.', say: 'Second.', atMs: 15_000 }, + { title: '3. Third.', say: 'Third.', atMs: 22_500 }, + { title: 'End of script', say: '', atMs: 30_000 }, + ]) + expect(progressText(state)).toBe('Done') + }) + + it('says where the reader is', () => { + expect(progressText(startScript([]))).toBe('No script') + expect(progressText(startScript(['a', 'b']))).toBe('1 of 2') + expect(beginReading(startScript([]), 0).mark).toBeUndefined() + }) +}) diff --git a/tests/share-bar-e2e.test.ts b/tests/share-bar-e2e.test.ts index 17e1e0d..0605ade 100644 --- a/tests/share-bar-e2e.test.ts +++ b/tests/share-bar-e2e.test.ts @@ -233,7 +233,16 @@ describe.each(ENGINES)('the share page in %s', { timeout: 300_000 }, (engine) => await page.mouse.move(size.width / 2, 2) const key = async (k: string): Promise => { await page.keyboard.press(k); await page.waitForTimeout(250) } // A key toggles the play state; the check waits on the state it asked for, not on a fixed pause after the key. + // A timeout says what the player was doing, so a failure on a slow machine names its cause. const paused = (want: boolean): Promise => f.waitForFunction((w) => (document.querySelector('[data-sv-video]') as HTMLVideoElement).paused === w, want, { timeout: 10_000 }) + .catch(async (error: unknown) => { + const state = await f.evaluate(() => { + const v = document.querySelector('[data-sv-video]') as HTMLVideoElement + const a = document.activeElement + return { paused: v.paused, ended: v.ended, t: v.currentTime, d: v.duration, readyState: v.readyState, networkState: v.networkState, error: v.error?.code ?? null, src: v.currentSrc.replace(/^.*\/media\//, 'media/'), height: v.dataset['svHeight'] ?? null, playError: document.querySelector('[data-pc-frame]')?.getAttribute('data-play-error') ?? null, active: a ? `${a.tagName.toLowerCase()}${a.getAttribute('data-pc-seek') !== null ? '[data-pc-seek]' : ''}` : null } + }) + throw new Error(`the video did not become ${want ? 'paused' : 'playing'}: ${JSON.stringify(state)}`, { cause: error }) + }) await key('k') await paused(true) expect((await video(f)).paused).toBe(true) diff --git a/tests/studio-devices.test.ts b/tests/studio-devices.test.ts new file mode 100644 index 0000000..81bc008 --- /dev/null +++ b/tests/studio-devices.test.ts @@ -0,0 +1,230 @@ +/** The studio's device lists without a browser: the choice kept, the fallback order, the permission path, the debounce, the agent request. */ +import { describe, expect, it } from 'vitest' +import { + debounce, DeviceWatcher, needsPermission, pickDevice, planList, resultText, splitDevices, + type DeviceEntry, type DeviceLists, type Timers, type WatchDeps, +} from '../web/src/studio-devices.js' +import { pendingRequest, readReport, requestRefresh, writeReport, REQUEST_TTL_MS } from '../src/studio/devices.js' +import { tempDir } from './helpers.js' + +const mic = (deviceId: string, label = `Mic ${deviceId}`): DeviceEntry => ({ deviceId, kind: 'audioinput', label }) +const cam = (deviceId: string, label = `Cam ${deviceId}`): DeviceEntry => ({ deviceId, kind: 'videoinput', label }) + +/** Timers run by hand. */ +function manualTimers(): Timers & { pending: () => number; flush: () => void } { + let next = 1 + const waiting = new Map void>() + return { + set: (fn) => { const id = next++; waiting.set(id, fn); return id }, + clear: (id) => { waiting.delete(id as number) }, + pending: () => waiting.size, + flush: () => { const fns = [...waiting.values()]; waiting.clear(); fns.forEach((f) => f()) }, + } +} + +/** A fake mediaDevices: a device list that can change, a permission that gives names, a count of prompts. */ +function fakeMedia(start: DeviceEntry[], opts: { refuse?: boolean; noCamera?: boolean; hideUntilAsked?: boolean } = {}) { + let devices = start + let granted = !opts.hideUntilAsked + const asked: MediaStreamConstraints[] = [] + const stopped: string[] = [] + const target = new EventTarget() + const media = Object.assign(target, { + enumerateDevices: async () => devices.map((d) => ({ ...d, label: granted ? d.label : '', toJSON: () => d })) as unknown as MediaDeviceInfo[], + getUserMedia: async (c?: MediaStreamConstraints) => { + asked.push(c ?? {}) + if (opts.refuse) throw Object.assign(new Error('denied'), { name: 'NotAllowedError' }) + if (c?.video && opts.noCamera) throw Object.assign(new Error('none'), { name: 'NotFoundError' }) + granted = true + const tracks = [c?.audio ? 'audio' : '', c?.video ? 'video' : ''].filter(Boolean).map((k) => ({ stop: () => stopped.push(k) })) + return { getTracks: () => tracks } as unknown as MediaStream + }, + }) + return { media, asked, stopped, set: (d: DeviceEntry[]) => { devices = d }, change: () => target.dispatchEvent(new Event('devicechange')) } +} + +function watcher(media: WatchDeps['media'], extra: Partial = {}) { + const applied: DeviceLists[] = [] + const life = new AbortController() + const timers = manualTimers() + const w = new DeviceWatcher({ media, apply: (l) => applied.push(l), cameraInUse: () => true, signal: life.signal, timers, ...extra }) + return { w, applied, life, timers } +} + +const tick = () => new Promise((r) => setTimeout(r, 0)) + +describe('picking a device', () => { + const list = [mic('default', 'Default'), mic('a'), mic('b')] + it('keeps the current choice while it is connected', () => { + expect(pickDevice(list, 'b', 'a')).toBe('b') + }) + it('falls back to the saved device, then the system default, then the first', () => { + expect(pickDevice(list, 'gone', 'a')).toBe('a') + expect(pickDevice(list, 'gone', 'also-gone')).toBe('default') + expect(pickDevice([mic('x'), mic('y')], '', '')).toBe('x') + expect(pickDevice([], 'a', 'b')).toBe('') + }) + it('never treats an empty id (WebKit before permission) as a choice', () => { + expect(pickDevice([mic(''), mic('z')], '', '')).toBe('') + expect(pickDevice([mic('z')], '', '')).toBe('z') + }) + it('names unnamed devices by their place in the list', () => { + expect(planList([mic('a', ''), mic('b', 'Desk mic')], 'Microphone', '', 'b')).toEqual({ + options: [{ value: 'a', label: 'Microphone 1' }, { value: 'b', label: 'Desk mic' }], value: 'b', + }) + }) +}) + +describe('permission and the status line', () => { + it('needs permission when names are hidden or nothing is listed', () => { + expect(needsPermission({ mics: [mic('a', '')], cameras: [cam('c')] }, true)).toBe(true) + expect(needsPermission({ mics: [], cameras: [] }, false)).toBe(true) + expect(needsPermission({ mics: [mic('a')], cameras: [cam('c', '')] }, false)).toBe(false) + expect(needsPermission({ mics: [mic('a')], cameras: [cam('c', '')] }, true)).toBe(true) + expect(needsPermission({ mics: [mic('a')], cameras: [cam('c')] }, true)).toBe(false) + }) + it('counts in plain words', () => { + const lists = splitDevices([mic('a'), mic('b'), mic('c'), cam('d')]) + expect(resultText(lists, 'granted', true)).toBe('Found 3 microphones and 1 camera.') + expect(resultText(lists, 'granted', false)).toBe('Found 3 microphones.') + expect(resultText({ mics: [mic('a')], cameras: [] }, 'granted', true)).toBe('Found 1 microphone and no cameras.') + expect(resultText(lists, 'needed', true)).toMatch(/Names appear once you allow access/) + expect(resultText(lists, 'refused', true)).toMatch(/^Permission was refused/) + }) +}) + +describe('debounce', () => { + it('runs once after the calls stop, and cancel drops it', () => { + const timers = manualTimers() + let runs = 0 + const d = debounce(() => { runs++ }, 100, timers) + d(); d(); d() + expect(timers.pending()).toBe(1) + timers.flush() + expect(runs).toBe(1) + d() + d.cancel() + timers.flush() + expect(runs).toBe(1) + }) +}) + +describe('DeviceWatcher', () => { + it('refills on devicechange, debounced, and stops listening when the studio closes', async () => { + const fake = fakeMedia([mic('a')]) + const { applied, life, timers } = watcher(fake.media) + fake.set([mic('a'), mic('usb', 'USB mic')]) + fake.change(); fake.change(); fake.change() + expect(timers.pending()).toBe(1) + timers.flush() + await tick(); await tick() + expect(applied).toHaveLength(1) + expect(applied[0]!.mics.map((d) => d.deviceId)).toEqual(['a', 'usb']) + life.abort() + fake.change() + expect(timers.pending()).toBe(0) + }) + + it('refills when the window is shown or focused again', async () => { + const fake = fakeMedia([mic('a')]) + const doc = Object.assign(new EventTarget(), { visibilityState: 'hidden' }) + const win = new EventTarget() + const { applied, timers } = watcher(fake.media, { page: { doc, win } }) + doc.dispatchEvent(new Event('visibilitychange')) + expect(timers.pending()).toBe(0) + doc.visibilityState = 'visible' + doc.dispatchEvent(new Event('visibilitychange')) + win.dispatchEvent(new Event('focus')) + timers.flush() + await tick(); await tick() + expect(applied).toHaveLength(1) + }) + + it('refills when a permission becomes granted', async () => { + const fake = fakeMedia([mic('a')]) + const status = Object.assign(new EventTarget(), { state: 'prompt' }) + const { timers } = watcher(fake.media, { permissions: { query: async () => status } }) + await tick() + status.state = 'granted' + status.dispatchEvent(new Event('change')) + expect(timers.pending()).toBe(1) + }) + + it('asks for permission when names are hidden, stops the tracks at once and lists the real names', async () => { + const fake = fakeMedia([mic('a', 'Desk mic'), cam('c', 'FaceTime camera')], { hideUntilAsked: true }) + const { w, applied } = watcher(fake.media) + const result = await w.refresh({ ask: true }) + expect(fake.asked).toEqual([{ audio: true, video: true }]) + expect(fake.stopped.sort()).toEqual(['audio', 'video']) + expect(result).toMatchObject({ permission: 'granted', asked: true, text: 'Found 1 microphone and 1 camera.' }) + expect(applied.at(-1)!.mics[0]!.label).toBe('Desk mic') + }) + + it('asks for audio only when the camera picker is not in use, and falls back to audio when no camera is plugged in', async () => { + const noCam = fakeMedia([mic('a')], { hideUntilAsked: true }) + await watcher(noCam.media, { cameraInUse: () => false }).w.refresh({ ask: true }) + expect(noCam.asked).toEqual([{ audio: true, video: false }]) + const missing = fakeMedia([mic('a')], { hideUntilAsked: true, noCamera: true }) + const r = await watcher(missing.media).w.refresh({ ask: true }) + expect(missing.asked).toEqual([{ audio: true, video: true }, { audio: true, video: false }]) + expect(r.lists.mics[0]!.label).toBe('Mic a') + }) + + it('does not prompt when names already show, or when not asked to', async () => { + const shown = fakeMedia([mic('a'), cam('c')]) + expect((await watcher(shown.media).w.refresh({ ask: true })).asked).toBe(false) + expect(shown.asked).toEqual([]) + const hidden = fakeMedia([mic('a')], { hideUntilAsked: true }) + expect((await watcher(hidden.media).w.refresh({ ask: false })).permission).toBe('needed') + expect(hidden.asked).toEqual([]) + }) + + it('reports a refusal in plain words and keeps the generic lists', async () => { + const fake = fakeMedia([mic('a')], { hideUntilAsked: true, refuse: true }) + const result = await watcher(fake.media).w.refresh({ ask: true }) + expect(result.permission).toBe('refused') + expect(result.text).toMatch(/^Permission was refused/) + expect(result.lists.mics).toHaveLength(1) + }) + + it('says so where the page has no device list', async () => { + const result = await watcher(undefined).w.refresh({ ask: true }) + expect(result.permission).toBe('unavailable') + }) + + it('runs one more fill when a change arrives during one', async () => { + const fake = fakeMedia([mic('a')]) + const { w, applied } = watcher(fake.media) + const first = w.fill() + fake.set([mic('a'), mic('b')]) + void w.fill() + await first + expect(applied).toHaveLength(1) + expect(applied[0]!.mics).toHaveLength(2) + }) +}) + +describe('the agent request', () => { + it('waits for the studio to answer the request it wrote', async () => { + const dir = await tempDir() + const asking = requestRefresh(dir, { askPermission: true }, { waitMs: 5000, everyMs: 20 }) + let request + for (let i = 0; i < 50 && !request; i++) { await new Promise((r) => setTimeout(r, 10)); request = await pendingRequest(dir, new Date()) } + expect(request).toMatchObject({ askPermission: true }) + await writeReport(dir, { requestId: request!.id, mics: [{ label: 'Desk mic', chosen: true }], cameras: [], cameraInUse: false, permission: 'granted', text: 'Found 1 microphone.' }, new Date()) + const outcome = await asking + expect(outcome.refreshed).toBe(true) + expect(outcome.devices?.mics).toEqual([{ label: 'Desk mic', chosen: true }]) + }) + + it('says the studio did not answer, with the last report, and drops a stale request', async () => { + const dir = await tempDir() + await writeReport(dir, { mics: [], cameras: [], cameraInUse: false, permission: 'needed', text: '' }, new Date()) + const outcome = await requestRefresh(dir, {}, { waitMs: 60, everyMs: 20 }) + expect(outcome.refreshed).toBe(false) + expect(outcome.reason).toMatch(/open the FormRec studio/) + expect(outcome.devices?.permission).toBe('needed') + expect(await pendingRequest(dir, new Date(Date.now() + REQUEST_TTL_MS + 1000))).toBeUndefined() + expect((await readReport(dir))?.reportedAt).toBeTypeOf('string') + }) +}) diff --git a/tests/studio-e2e.test.ts b/tests/studio-e2e.test.ts index 66a12ba..a5060e8 100644 --- a/tests/studio-e2e.test.ts +++ b/tests/studio-e2e.test.ts @@ -248,4 +248,81 @@ describe('the 0.4.0 studio', () => { await context.close() } }, 60_000) + + it('refills the device lists on devicechange, by Refresh devices and for an agent, keeping the choice and the layout', async () => { + await withStudio({}, async (page) => { + const micSel = page.locator('[data-studio-mic]') + await expect.poll(() => micSel.locator('option').count(), { timeout: 10_000 }).toBeGreaterThan(0) + const chosen = await micSel.inputValue() + const source = page.locator('[data-studio-source]') + const before = await source.boundingBox() + // A microphone is plugged in: the page's list grows and the browser fires devicechange. + await page.evaluate(() => { + const md = navigator.mediaDevices + const real = md.enumerateDevices.bind(md) + md.enumerateDevices = async () => [...await real(), { deviceId: 'usb-test-mic', groupId: 'usb', kind: 'audioinput', label: 'USB test microphone', toJSON() { return this } } as MediaDeviceInfo] + md.dispatchEvent(new Event('devicechange')) + }) + await expect.poll(() => micSel.locator('option[value="usb-test-mic"]').textContent(), { timeout: 10_000 }).toBe('USB test microphone') + expect(await micSel.inputValue()).toBe(chosen) + // The button, by keyboard: a plain count in the status line, and nothing in the panel moves. + const refresh = page.locator('[data-studio-devices-refresh]') + expect(await refresh.getAttribute('title')).toBeTruthy() + await refresh.focus() + await page.keyboard.press('Enter') + const line = page.locator('[data-studio-devices-status]') + await expect.poll(() => line.textContent(), { timeout: 10_000 }).toMatch(/^Found \d+ microphones? and \d+ cameras?\.$/) + expect(await line.getAttribute('data-permission')).toBe('granted') + expect(await source.boundingBox()).toEqual(before) + // An agent's refresh (formrec_studio_refresh_devices writes the same request): the studio answers with the names. + const request = await api('/api/studio/devices/refresh', 'POST', {}) + await expect.poll(async () => (await api('/api/studio/devices')).requestId, { timeout: 15_000 }).toBe(request.id) + const report = await api('/api/studio/devices') + expect(report.mics.map((m: { label: string }) => m.label)).toContain('USB test microphone') + expect(report.mics.filter((m: { chosen: boolean }) => m.chosen)).toHaveLength(1) + await shot(page, 'studio-devices') + }) + }, 60_000) + + it('asks for permission once when the names are hidden, then shows the real names', async () => { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 }) + try { + const page = await context.newPage() + await page.addInitScript(() => { + localStorage.setItem('formrec.studio', JSON.stringify({ countdownS: 0 })) + // A browser before permission: the fake devices' names stay hidden until getUserMedia has succeeded once. + const md = navigator.mediaDevices + const list = md.enumerateDevices.bind(md) + const open = md.getUserMedia.bind(md) + const w = window as unknown as { allowed: boolean; asked: MediaStreamConstraints[]; opened: MediaStream[] } + w.allowed = false + w.asked = [] + w.opened = [] + md.enumerateDevices = async () => (await list()).map((d) => (w.allowed ? d : { deviceId: d.deviceId, groupId: d.groupId, kind: d.kind, label: '', toJSON() { return this } } as MediaDeviceInfo)) + md.getUserMedia = async (c?: MediaStreamConstraints) => { + w.asked.push(c ?? {}) + const s = await open(c) + w.allowed = true + w.opened.push(s) + return s + } + }) + await page.goto(`${base}/?token=${TOKEN}#/record`) + await page.locator('[data-view="studio"]').waitFor() + const micSel = page.locator('[data-studio-mic]') + await expect.poll(() => micSel.locator('option').count(), { timeout: 10_000 }).toBeGreaterThan(0) + expect((await micSel.locator('option').allTextContents()).every((l) => /^Microphone \d+$/.test(l))).toBe(true) + await page.locator('[data-studio-devices-refresh]').click() + await expect.poll(() => page.locator('[data-studio-devices-status]').textContent(), { timeout: 10_000 }).toMatch(/^Found \d+ microphones? and \d+ cameras?\.$/) + const labels = await micSel.locator('option').allTextContents() + expect(labels.length).toBeGreaterThan(0) + expect(labels.every((l) => !/^Microphone \d+$/.test(l))).toBe(true) + // One prompt, for the microphone and the camera (the default layout records both), and its tracks are stopped at once. + const asked = await page.evaluate(() => (window as unknown as { asked: MediaStreamConstraints[] }).asked) + expect(asked).toEqual([{ audio: true, video: true }]) + expect(await page.evaluate(() => (window as unknown as { opened: MediaStream[] }).opened.flatMap((s) => s.getTracks()).every((t) => t.readyState === 'ended'))).toBe(true) + } finally { + await context.close() + } + }, 60_000) }) diff --git a/tests/studio-feature.test.ts b/tests/studio-feature.test.ts index be2fba7..20c0709 100644 --- a/tests/studio-feature.test.ts +++ b/tests/studio-feature.test.ts @@ -57,6 +57,18 @@ describe('studio routes', () => { expect((await call('/api/studio/state', 'PUT', { state: 'dancing' })).status).toBe(400) }) + it('keeps the device report and hands a refresh request to the studio', async () => { + expect((await call('/api/studio/devices/request')).json).toEqual({}) + const asked = await call('/api/studio/devices/refresh', 'POST', { askPermission: true }) + expect(asked.status).toBe(200) + const pending = (await call('/api/studio/devices/request')).json + expect(pending).toMatchObject({ id: asked.json.id, askPermission: true }) + const report = { requestId: pending.id, mics: [{ label: 'Desk mic', chosen: true }], cameras: [{ label: 'Camera', chosen: true }], cameraInUse: true, permission: 'granted', text: 'Found 1 microphone and 1 camera.' } + expect((await call('/api/studio/devices', 'PUT', report)).status).toBe(200) + expect((await call('/api/studio/devices')).json).toMatchObject({ ...report, reportedAt: expect.any(String) }) + expect((await call('/api/studio/devices', 'PUT', { mics: 'many' })).status).toBe(400) + }) + it('records the take meta, Live Rewind trims and camera ranges on the take timeline', async () => { const s = (await call('/api/sessions', 'POST', { title: 'Rewind me', mode: 'screen' })).json expect((await call(`/api/studio/takes/${s.id}`, 'PUT', { layout: 'presentation', target: 'current-tab', quality: '2160p', systemAudio: false, composedCamera: true })).json) @@ -120,7 +132,8 @@ describe('studio MCP tools', () => { const seen: Record = {} const server = { registerTool: (name: string, def: any) => { seen[name] = def } } as unknown as McpServer feature.mcp!(server, { library: app.features.library, dataDir, playerBase: async () => undefined }) - expect(Object.keys(seen).sort()).toEqual(['formrec_discard_take', 'formrec_recover_take', 'formrec_studio_state', 'formrec_unsaved_takes']) + expect(Object.keys(seen).sort()).toEqual(['formrec_discard_take', 'formrec_recover_take', 'formrec_studio_refresh_devices', 'formrec_studio_state', 'formrec_unsaved_takes']) + expect(seen['formrec_studio_refresh_devices'].annotations).toMatchObject({ readOnlyHint: false, destructiveHint: false, openWorldHint: false }) expect(seen['formrec_discard_take'].annotations.destructiveHint).toBe(true) expect(seen['formrec_unsaved_takes'].annotations.readOnlyHint).toBe(true) expect(seen['formrec_recover_take'].annotations.destructiveHint).toBe(false) diff --git a/tests/teamsync-folder-names.test.ts b/tests/teamsync-folder-names.test.ts new file mode 100644 index 0000000..5b777cf --- /dev/null +++ b/tests/teamsync-folder-names.test.ts @@ -0,0 +1,228 @@ +/** + * The folder sync reads lists other computers wrote into the shared folder. A file name in such a list is one plain + * name inside the recording's folder, and a recording's folder in the share is its own `/` or `/.by-/`: + * a list that names anything else is not followed, and no file outside those folders is written or removed. + */ +import { createHash } from 'node:crypto' +import { describe, expect, it } from 'vitest' +import { lstat, mkdir, readFile, readdir, rename, rm, stat, symlink, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { Library } from '../src/store/library.js' +import { LibraryStore } from '../src/features/library/store.js' +import { deviceIdentity, SYNC_FOLDER, syncFolder } from '../src/features/library/sync-folder.js' +import { tempDir } from './helpers.js' + +interface Computer { store: LibraryStore; lib: Library; spaceId: string; dataDir: string } + +async function computer(shared: string): Promise { + const dataDir = await tempDir('formrec-names-') + const lib = new Library(dataDir) + const store = new LibraryStore(lib, dataDir, lib.events) + const space = await store.createSpace({ name: 'Design team', visibility: 'open', kind: 'synced', syncPath: shared }) + return { store, lib, spaceId: space.id, dataDir } +} + +const run = async (c: Computer) => syncFolder(c.store, (await c.store.org()).spaces.find((s) => s.id === c.spaceId)!) +const sha = (b: Buffer | string): string => createHash('sha256').update(b).digest('hex') +const present = async (p: string): Promise => (await stat(p).catch(() => undefined)) !== undefined + +function recordingJson(id: string): string { + return JSON.stringify({ formrec: 1, id, title: 'Shared', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', durationMs: 1, chapters: [] }) +} + +async function writeList(shared: string, device: string, id: string, files: Record, dir = '.', vector: Record = { [device]: 1 }): Promise { + await mkdir(path.join(shared, SYNC_FOLDER), { recursive: true }) + const entry = { vector, hash: sha(JSON.stringify(files)), files, dir, updatedAt: '2026-11-05T00:00:00Z', title: 'Shared' } + await writeFile(path.join(shared, SYNC_FOLDER, `${device}.json`), JSON.stringify({ formrecSync: 1, device, name: 'Other', updatedAt: '2026-11-05T00:00:00Z', recordings: { [id]: entry } })) +} + +describe('file names in another computer\'s list', () => { + it('keeps every file it brings in inside the recording\'s folder', async () => { + const shared = await tempDir('formrec-names-shared-') + const me = await computer(shared) + const id = 'shared-2026-11-05-aaaaaa' + const payload = '{"placed":true}\n' + const name = 'x/../../desktop/placed.json' + await mkdir(path.join(shared, id), { recursive: true }) + await writeFile(path.join(shared, id, 'recording.json'), recordingJson(id)) + await mkdir(path.join(shared, 'desktop'), { recursive: true }) + await writeFile(path.join(shared, 'desktop', 'placed.json'), payload) + await writeList(shared, 'd-0000abcd', id, { 'recording.json': sha(recordingJson(id)), [name]: sha(payload) }) + await run(me) + expect(await present(path.join(me.dataDir, 'desktop', 'placed.json'))).toBe(false) + expect(await present(path.join(me.dataDir, 'teamsync', 'desktop', 'placed.json'))).toBe(false) + const teamsync = await readdir(path.join(me.dataDir, 'teamsync')).catch(() => [] as string[]) + expect(teamsync.filter((n) => !n.endsWith('.json'))).toEqual([]) + }) + + it('does not read a version from a folder outside the recording\'s own', async () => { + const shared = await tempDir('formrec-names-shared-') + const elsewhere = await tempDir('formrec-names-elsewhere-') + const me = await computer(shared) + const id = 'shared-2026-11-05-bbbbbb' + await writeFile(path.join(elsewhere, 'recording.json'), recordingJson(id)) + const rel = path.relative(path.join(shared, id), elsewhere) + await writeList(shared, 'd-0000abcd', id, { 'recording.json': sha(recordingJson(id)) }, rel) + expect((await run(me)).pulled).toEqual([]) + expect(await me.lib.exists(id)).toBe(false) + }) +}) + +describe('where this computer publishes', () => { + it('never removes files outside the share when its own list was changed', async () => { + const shared = await tempDir('formrec-names-shared-') + const elsewhere = await tempDir('formrec-names-elsewhere-') + const me = await computer(shared) + const id = 'mine-2026-11-05-cccccc' + const dir = await me.lib.prepare(id) + await writeFile(path.join(dir, 'video.webm'), 'bytes') + await me.lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', mode: 'walkthrough', video: 'video.webm', durationMs: 5000, chapters: [] }) + await me.store.place([id], { spaceId: me.spaceId, mode: 'add' }) + expect((await run(me)).pushed).toEqual([id]) + await writeFile(path.join(elsewhere, 'keep.txt'), 'keep me') + const mine = path.join(shared, SYNC_FOLDER, `${(await deviceIdentity(me.dataDir)).id}.json`) + const list = JSON.parse(await readFile(mine, 'utf8')) + list.recordings[id].dir = path.relative(path.join(shared, id), elsewhere) + await writeFile(mine, JSON.stringify(list)) + await me.lib.save({ ...(await me.lib.get(id))!, title: 'Mine, renamed' }) + expect((await run(me)).pushed).toEqual([id]) + expect(await readFile(path.join(elsewhere, 'keep.txt'), 'utf8')).toBe('keep me') + expect(await present(path.join(elsewhere, 'recording.json'))).toBe(false) + }) +}) + +describe('names and folders that stay local', () => { + it.each(['share.json', 'Share.JSON', 'workspace.json', 'notes.txt.', 'notes.txt ', 'CON', 'nul.txt', 'a\u0007b', 'a|b', 'SHARE~1.JSO', 'notes~2.txt', 'RELAY-~1.JSO', '\u017fhare.json', 'n\u043etes.txt', '\u212aeys.txt', 'cafe\u0301.txt', 'notes\u00a0.txt'])('does not bring in a file named %j', async (name) => { + const shared = await tempDir('formrec-names-shared-') + const me = await computer(shared) + const id = 'shared-2026-11-05-dddddd' + const from = path.join(shared, id, '.by-d-0000abcd') + await mkdir(from, { recursive: true }) + await writeFile(path.join(from, 'recording.json'), recordingJson(id)) + await writeFile(path.join(from, name), '{"local":false}\n') + await writeList(shared, 'd-0000abcd', id, { 'recording.json': sha(recordingJson(id)), [name]: sha('{"local":false}\n') }, '.by-d-0000abcd') + await run(me) + const here = await readdir(me.lib.folder(id)).catch(() => [] as string[]) + expect(here.map((n) => n.toLowerCase())).not.toContain(name.toLowerCase()) + }) + + it('does not count a file as published when the share lists it under another name', async () => { + const shared = await tempDir('formrec-names-shared-') + const probe = path.join(shared, 'Probe.txt') + await writeFile(probe, 'probe') + const foldsCase = await present(path.join(shared, 'probe.txt')) + await rm(probe) + if (!foldsCase) return + const me = await computer(shared) + const id = 'mine-2026-11-05-hhhhhh' + const dir = await me.lib.prepare(id) + await writeFile(path.join(dir, 'notes.txt'), 'mine') + await me.lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', durationMs: 1, chapters: [] }) + await me.store.place([id], { spaceId: me.spaceId, mode: 'add' }) + await mkdir(path.join(shared, id), { recursive: true }) + await writeFile(path.join(shared, id, 'Notes.txt'), 'theirs') + expect((await run(me)).pushed).toEqual([]) + expect(await readdir(path.join(shared, id))).toContain('Notes.txt') + }) + + it('does not read a recording folder in the share that is a link', async () => { + const shared = await tempDir('formrec-names-shared-') + const elsewhere = await tempDir('formrec-names-elsewhere-') + const me = await computer(shared) + const id = 'shared-2026-11-05-eeeeee' + await writeFile(path.join(elsewhere, 'recording.json'), recordingJson(id)) + await symlink(elsewhere, path.join(shared, id)) + await writeList(shared, 'd-0000abcd', id, { 'recording.json': sha(recordingJson(id)) }) + expect((await run(me)).pulled).toEqual([]) + expect(await me.lib.exists(id)).toBe(false) + }) + + it('does not bring in a file that is a link', async () => { + const shared = await tempDir('formrec-names-shared-') + const elsewhere = await tempDir('formrec-names-elsewhere-') + const me = await computer(shared) + const id = 'shared-2026-11-05-ffffff' + const from = path.join(shared, id, '.by-d-0000abcd') + await mkdir(from, { recursive: true }) + await writeFile(path.join(from, 'recording.json'), recordingJson(id)) + await writeFile(path.join(elsewhere, 'notes.txt'), 'outside') + await symlink(path.join(elsewhere, 'notes.txt'), path.join(from, 'notes.txt')) + await writeList(shared, 'd-0000abcd', id, { 'recording.json': sha(recordingJson(id)), 'notes.txt': sha('outside') }, '.by-d-0000abcd') + await run(me) + expect(await lstat(path.join(me.lib.folder(id), 'notes.txt')).catch(() => undefined)).toBeUndefined() + }) + + it('does not publish through a recording folder in the share that became a link', async () => { + const shared = await tempDir('formrec-names-shared-') + const elsewhere = await tempDir('formrec-names-elsewhere-') + const moved = await tempDir('formrec-names-moved-') + const me = await computer(shared) + const id = 'mine-2026-11-05-gggggg' + const dir = await me.lib.prepare(id) + await writeFile(path.join(dir, 'video.webm'), 'bytes') + await me.lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', mode: 'walkthrough', video: 'video.webm', durationMs: 5000, chapters: [] }) + await me.store.place([id], { spaceId: me.spaceId, mode: 'add' }) + expect((await run(me)).pushed).toEqual([id]) + await rename(path.join(shared, id), path.join(moved, id)) + await writeFile(path.join(elsewhere, 'keep.txt'), 'keep me') + await symlink(elsewhere, path.join(shared, id)) + await me.lib.save({ ...(await me.lib.get(id))!, title: 'Mine, renamed' }) + expect((await run(me)).pushed).toEqual([]) + expect(await readFile(path.join(elsewhere, 'keep.txt'), 'utf8')).toBe('keep me') + expect(await present(path.join(elsewhere, 'recording.json'))).toBe(false) + }) +}) + +describe('placing a file next to one whose name folds to the same', () => { + it('does not publish over a file in the share whose name differs only in case', async () => { + const shared = await tempDir('formrec-names-shared-') + const me = await computer(shared) + const id = 'mine-2026-11-05-iiiiii' + const dir = await me.lib.prepare(id) + await writeFile(path.join(dir, 'notes.txt'), 'mine') + await me.lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', durationMs: 1, chapters: [] }) + await me.store.place([id], { spaceId: me.spaceId, mode: 'add' }) + await mkdir(path.join(shared, id), { recursive: true }) + await writeFile(path.join(shared, id, 'NOTES.TXT'), 'theirs') + expect((await run(me)).pushed).toEqual([]) + expect(await readdir(path.join(shared, id))).not.toContain('notes.txt') + expect(await readFile(path.join(shared, id, 'NOTES.TXT'), 'utf8')).toBe('theirs') + }) + + it('keeps a local-only file when a newer version lists a name that folds to it', async () => { + const shared = await tempDir('formrec-names-shared-') + const me = await computer(shared) + const id = 'mine-2026-11-05-jjjjjj' + const dir = await me.lib.prepare(id) + await me.lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', durationMs: 1, chapters: [] }) + await me.store.place([id], { spaceId: me.spaceId, mode: 'add' }) + await writeFile(path.join(dir, 'share.json'), '{"local":true}\n') + expect((await run(me)).pushed).toEqual([id]) + const self = (await deviceIdentity(me.dataDir)).id + const alias = 'ſhare.json' + const from = path.join(shared, id, '.by-d-0000abcd') + const rec = await readFile(path.join(dir, 'recording.json'), 'utf8') + await mkdir(from, { recursive: true }) + await writeFile(path.join(from, 'recording.json'), rec) + await writeFile(path.join(from, alias), '{"local":false}\n') + await writeList(shared, 'd-0000abcd', id, { 'recording.json': sha(rec), [alias]: sha('{"local":false}\n') }, '.by-d-0000abcd', { [self]: 1, 'd-0000abcd': 1 }) + expect((await run(me)).pulled).toEqual([]) + expect(await readdir(dir)).not.toContain(alias) + expect(await readFile(path.join(dir, 'share.json'), 'utf8')).toBe('{"local":true}\n') + }) + + it('still replaces an earlier version of the same file under exactly its name', async () => { + const shared = await tempDir('formrec-names-shared-') + const me = await computer(shared) + const id = 'mine-2026-11-05-kkkkkk' + const dir = await me.lib.prepare(id) + await writeFile(path.join(dir, 'notes.txt'), 'first') + await me.lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', durationMs: 1, chapters: [] }) + await me.store.place([id], { spaceId: me.spaceId, mode: 'add' }) + expect((await run(me)).pushed).toEqual([id]) + await writeFile(path.join(dir, 'notes.txt'), 'second') + expect((await run(me)).pushed).toEqual([id]) + expect(await readFile(path.join(shared, id, 'notes.txt'), 'utf8')).toBe('second') + expect((await readdir(path.join(shared, id))).filter((n) => n.endsWith('.tmp'))).toEqual([]) + }) +}) diff --git a/tests/teamsync-folder-place.test.ts b/tests/teamsync-folder-place.test.ts new file mode 100644 index 0000000..0e453ad --- /dev/null +++ b/tests/teamsync-folder-place.test.ts @@ -0,0 +1,137 @@ +/** + * How the folder sync puts a file in place: every file is verified in a private staging folder, an earlier version + * under the same name is replaced in one step, a file system that cannot hard-link or a share on another volume still + * gets the file, and a staged file that is no longer the one written is never placed. The file system calls are + * wrapped so a test can make one of them fail, change what sits at a path, or report another volume. + */ +import type * as FsPromises from 'node:fs/promises' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const hooks = vi.hoisted(() => ({ + link: undefined as undefined | ((from: string, to: string) => Promise), + lstatTmp: undefined as undefined | ((p: string) => Promise), + otherVolume: undefined as undefined | string, +})) + +vi.mock('node:fs/promises', async (importOriginal) => { + const real = await importOriginal() + const wrapped = { + ...real, + link: async (from: string, to: string) => (hooks.link ? hooks.link(from, to) : real.link(from, to)), + lstat: async (p: string) => { + if (hooks.lstatTmp && /\.[0-9a-f]{12}\.tmp$/.test(String(p))) await hooks.lstatTmp(String(p)) + return real.lstat(p) + }, + stat: async (p: string) => { + const info = await real.stat(p) + if (!hooks.otherVolume || !String(p).startsWith(hooks.otherVolume)) return info + return Object.assign(Object.create(Object.getPrototypeOf(info)), info, { dev: info.dev + 1 }) + }, + } + return { ...wrapped, default: wrapped } +}) + +const { readFile, readdir, rm, symlink, writeFile } = await import('node:fs/promises') +const path = (await import('node:path')).default +const { Library } = await import('../src/store/library.js') +const { LibraryStore } = await import('../src/features/library/store.js') +const { syncFolder } = await import('../src/features/library/sync-folder.js') +const { tempDir } = await import('./helpers.js') + +const failWith = (code: string) => async (): Promise => { + throw Object.assign(new Error(code), { code }) +} + +async function mine(id: string, notes: string): Promise<{ run: () => ReturnType; dir: string; shared: string }> { + const shared = await tempDir('formrec-place-shared-') + const dataDir = await tempDir('formrec-place-') + const lib = new Library(dataDir) + const store = new LibraryStore(lib, dataDir, lib.events) + const space = await store.createSpace({ name: 'Design team', visibility: 'open', kind: 'synced', syncPath: shared }) + const dir = await lib.prepare(id) + await writeFile(path.join(dir, 'notes.txt'), notes) + await lib.save({ formrec: 1, id, title: 'Mine', summary: '', source: 'person', createdAt: '2026-11-05T00:00:00Z', durationMs: 1, chapters: [] }) + await store.place([id], { spaceId: space.id, mode: 'add' }) + const run = async () => syncFolder(store, (await store.org()).spaces.find((s) => s.id === space.id)!) + return { run, dir, shared } +} + +beforeEach(() => { + hooks.link = undefined + hooks.lstatTmp = undefined + hooks.otherVolume = undefined +}) + +/** Replace the staged notes.txt on its `nth` check with a link to `outside` (or a new file), before it would be placed. */ +function swapOnCheck(nth: number, outside: string, asLink: boolean): void { + let seen = 0 + hooks.lstatTmp = async (p) => { + if (!path.basename(p).startsWith('.notes.txt.')) return + seen += 1 + if (seen !== nth) return + hooks.lstatTmp = undefined + await rm(p, { force: true }) + if (asLink) await symlink(outside, p) + else await writeFile(p, 'swapped') + } +} + +describe('placing a file in the shared folder', () => { + it('replaces an earlier version in one step, so a failing link cannot lose it', async () => { + const id = 'mine-2026-11-05-pppppp' + const c = await mine(id, 'first') + expect((await c.run()).pushed).toEqual([id]) + hooks.link = failWith('EIO') + await writeFile(path.join(c.dir, 'notes.txt'), 'second') + expect((await c.run()).pushed).toEqual([id]) + expect(await readFile(path.join(c.shared, id, 'notes.txt'), 'utf8')).toBe('second') + }) + + it('still places a new file on a file system that cannot hard-link', async () => { + const id = 'mine-2026-11-05-qqqqqq' + const c = await mine(id, 'only') + hooks.link = failWith('EPERM') + expect((await c.run()).pushed).toEqual([id]) + expect(await readFile(path.join(c.shared, id, 'notes.txt'), 'utf8')).toBe('only') + expect((await readdir(path.join(c.shared, id))).filter((n) => n.endsWith('.tmp'))).toEqual([]) + }) + + it.each([ + [1, true, false], [2, true, false], [2, false, false], [1, true, true], [2, true, true], [2, false, true], + ])('never places a staged file swapped on check %i (as a link: %s, other volume: %s)', async (nth, asLink, otherVolume) => { + const id = `mine-2026-11-05-s${nth}${asLink ? 'l' : 'f'}${otherVolume ? 'v' : 's'}aaa` + const c = await mine(id, 'mine') + const elsewhere = await tempDir('formrec-place-elsewhere-') + const outside = path.join(elsewhere, 'keep.txt') + await writeFile(outside, 'keep me') + if (otherVolume) hooks.otherVolume = c.shared + swapOnCheck(nth, outside, asLink) + expect((await c.run()).pushed).toEqual([]) + expect(hooks.lstatTmp).toBeUndefined() + const there = await readdir(path.join(c.shared, id)).catch(() => [] as string[]) + expect(there).not.toContain('notes.txt') + expect(await readFile(outside, 'utf8')).toBe('keep me') + }) + + it('stages in a private folder, not in the share', async () => { + const id = 'mine-2026-11-05-tttttt' + const c = await mine(id, 'mine') + const seen: string[] = [] + hooks.lstatTmp = async (p) => { seen.push(p) } + expect((await c.run()).pushed).toEqual([id]) + expect(seen.length).toBeGreaterThan(0) + for (const p of seen) expect(p.startsWith(c.shared)).toBe(false) + }) + + it('publishes and replaces a file in a share on another volume, checking what landed', async () => { + const id = 'mine-2026-11-05-uuuuuu' + const c = await mine(id, 'first') + hooks.otherVolume = c.shared + expect((await c.run()).pushed).toEqual([id]) + expect(await readFile(path.join(c.shared, id, 'notes.txt'), 'utf8')).toBe('first') + await writeFile(path.join(c.dir, 'notes.txt'), 'second') + expect((await c.run()).pushed).toEqual([id]) + expect(await readFile(path.join(c.shared, id, 'notes.txt'), 'utf8')).toBe('second') + expect((await readdir(path.join(c.shared, id))).filter((n) => n.endsWith('.tmp'))).toEqual([]) + }) +}) diff --git a/tests/voice-master-e2e.test.ts b/tests/voice-master-e2e.test.ts new file mode 100644 index 0000000..7b99090 --- /dev/null +++ b/tests/voice-master-e2e.test.ts @@ -0,0 +1,219 @@ +/** + * The Voice master preset in a real browser. Chromium's fake microphone plays a WAV made here: quiet speech-like tone + * at about -30 dBFS with one full-scale burst every four seconds. The take runs with every browser DSP off and + * leaves a 48 kHz 24-bit mono WAV beside the Opus track; the meter's clip light latches, the too-quiet hint shows, the + * save screen lists the clips with their times, the level check says turn it up, and Space in script mode drops a + * chapter per paragraph. Needs `npm run build` (the test serves dist/web); the ffprobe check skips without FFmpeg. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { execFileSync } from 'node:child_process' +import { existsSync } from 'node:fs' +import { readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import type { AddressInfo } from 'node:net' +import { chromium, type Browser, type Page } from 'playwright' +import { createApp, type App } from '../src/app.js' +import { wavHeader } from '../shared/wav.js' +import { tempDir } from './helpers.js' + +const WEB = path.resolve(import.meta.dirname, '..', 'dist', 'web') +const TOKEN = 'v'.repeat(40) +const RATE = 48_000 +let app: App +let browser: Browser +let base: string +let dataDir: string + +/** Four seconds: a 220 Hz tone at -30 dBFS, and at 2 s a 40 ms full-scale square (a clap). */ +async function fakeVoice(dir: string): Promise { + const n = RATE * 4 + const samples = new Float32Array(n) + const quiet = 10 ** (-30 / 20) + for (let i = 0; i < n; i += 1) samples[i] = Math.sin((2 * Math.PI * 220 * i) / RATE) * quiet + // A slow square (25 Hz), so a resampler on the way in cannot smooth it away. + for (let i = RATE * 2; i < RATE * 2 + RATE * 0.04; i += 1) samples[i] = i < RATE * 2 + RATE * 0.02 ? 1 : -1 + const file = path.join(dir, 'voice.wav') + // Chromium reads 16-bit WAV for its fake microphone: write it as 16-bit. + const pcm16 = Buffer.alloc(n * 2) + for (let i = 0; i < n; i += 1) pcm16.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(samples[i]! * 32767))), i * 2) + await writeFile(file, Buffer.concat([wavHeader({ sampleRate: RATE, channels: 1, bitsPerSample: 16 }, pcm16.length), pcm16])) + return file +} + +beforeAll(async () => { + if (!existsSync(path.join(WEB, 'capture-tap-worklet.js'))) throw new Error('run npm run build first') + dataDir = await tempDir() + app = createApp({ dataDir, token: TOKEN, webDir: WEB, guestPort: 0, guestHost: '127.0.0.1', addresses: () => ['127.0.0.1'] }) + await new Promise((r) => app.server.listen(0, '127.0.0.1', r)) + base = `http://127.0.0.1:${(app.server.address() as AddressInfo).port}` + const wav = await fakeVoice(await tempDir()) + browser = await chromium.launch({ + args: ['--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream', `--use-file-for-fake-audio-capture=${wav}`, '--autoplay-policy=no-user-gesture-required'], + }) +}) +afterAll(async () => { + await browser?.close() + await app?.close() +}) + +async function studio(): Promise { + const context = await browser.newContext({ permissions: ['camera', 'microphone'] }) + const page = await context.newPage() + page.on('pageerror', (e) => { throw e }) + await page.goto(`${base}/?token=${TOKEN}#/record`) + await page.getByRole('heading', { name: 'Studio' }).waitFor() + return page +} + +function ffprobe(file: string): Record | undefined { + try { + const out = execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_name,sample_rate,channels', '-of', 'default=nw=1', file], { encoding: 'utf8' }) + return Object.fromEntries(out.trim().split('\n').map((l) => l.split('=') as [string, string])) + } catch { + return undefined + } +} + +describe('Voice master in a browser', () => { + it('shows the meter before the take, from the first frame', async () => { + const page = await studio() + await page.locator('[data-levels="large"]').waitFor() + await page.locator('[data-recbar] [data-levels="compact"]').waitFor() + expect(await page.locator('[data-sound-preset] option[value="voice-master"]').count()).toBe(1) + await page.context().close() + }) + + it('records a lossless master with no processing, counts the clips and drops script chapters', async () => { + const page = await studio() + await page.locator('[data-mode="audio"]').click() + await page.locator('[data-sound-preset]').selectOption('voice-master') + await page.locator('[data-sound-roomtone-field]').click() + expect(await page.locator('[data-sound-roomtone]').isChecked()).toBe(false) + await page.locator('[data-studio-script-panel] summary').click() + await page.locator('[data-script-text]').fill('First paragraph to read.\n\nSecond paragraph to read.') + await page.getByRole('button', { name: 'Get ready' }).click() + await page.getByText(/^Ready\. Guests can join now\./).waitFor({ timeout: 15_000 }) + + // The pre-roll check hears -30 dBFS peaks (and a clap), so it asks for a change. + await page.locator('[data-sound-check]').click() + await expect.poll(async () => page.locator('[data-sound-check-result]').getAttribute('data-advice'), { timeout: 15_000 }).toMatch(/^(up|down)$/) + // The clap latches the clip light; a click clears it. + await expect.poll(async () => page.locator('[data-levels="large"]').getAttribute('data-lit'), { timeout: 10_000 }).toBe('true') + await page.locator('[data-levels="large"] [data-levels-clip]').click() + await expect.poll(async () => page.locator('[data-levels="large"]').getAttribute('data-lit'), { timeout: 1500, interval: 50 }).toBe('false') + // Quiet speech for a few seconds brings up the hint. + await expect.poll(async () => page.locator('[data-levels="large"]').getAttribute('data-hint'), { timeout: 10_000 }).toBe('quiet') + expect(await page.locator('[data-levels-hint]').textContent()).toMatch(/you are quiet: move closer or turn the input up/i) + + await page.getByPlaceholder('What this recording is').fill('Voice master') + await page.getByRole('button', { name: 'Record', exact: true }).click() + await page.locator('[data-view="studio"][data-state="recording"]').waitFor({ timeout: 15_000 }) + await page.waitForTimeout(2500) + await page.keyboard.press('Space') + await page.waitForTimeout(4500) + await page.getByRole('button', { name: 'Stop' }).click() + await page.getByText(/^Stopped\. Clipped/).waitFor({ timeout: 20_000 }) + expect(await page.locator('[data-levels="large"]').getAttribute('data-hint')).toBe('report') + expect(await page.locator('[data-levels-hint]').textContent()).toMatch(/^Clipped (once|\d+ times), at \d:\d\d/) + const save = page.getByRole('button', { name: /^Save/ }) + await expect.poll(async () => (await save.textContent()) ?? '', { timeout: 20_000 }).toBe('Save') + await save.click() + await page.waitForURL(/#\/f\//, { timeout: 30_000 }) + const id = decodeURIComponent(page.url().split('#/f/')[1]!) + const rec = JSON.parse(await readFile(path.join(dataDir, 'recordings', id, 'recording.json'), 'utf8')) + + expect(rec.capture.preset).toBe('voice-master') + expect(rec.capture.micEffects).toBe(false) + const mic = rec.capture.tracks.find((t: any) => t.kind === 'mic') + expect(mic.settings).toMatchObject({ echoCancellation: false, noiseSuppression: false, autoGainControl: false }) + expect(rec.capture.levels.clips.length).toBeGreaterThanOrEqual(1) + expect(rec.capture.levels.check.advice).toMatch(/^(up|down)$/) + expect(rec.capture.master).toMatchObject({ file: 'master-host-mic.wav', sampleRate: 48_000, bitsPerSample: 24, channels: 1, complete: true }) + const opus = rec.tracks.find((t: any) => t.id === 'host-mic') + expect(rec.capture.master.durationMs).toBeGreaterThan(5000) + expect(Math.abs(rec.capture.master.durationMs - opus.durationMs)).toBeLessThan(600) + expect(rec.tracks.map((t: any) => t.id)).toEqual(['host-mic']) + expect(rec.chapters.map((c: any) => c.title)).toEqual(['1. First paragraph to read.', '2. Second paragraph to read.']) + expect(rec.chapters[1].say).toBe('Second paragraph to read.') + + const wav = path.join(dataDir, 'recordings', id, 'master-host-mic.wav') + const head = await readFile(wav) + expect(head.toString('ascii', 0, 4)).toBe('RIFF') + expect(head.readUInt16LE(34)).toBe(24) + expect(head.readUInt32LE(40)).toBe(head.length - 44) + const probe = ffprobe(wav) + if (probe) expect(probe).toEqual({ codec_name: 'pcm_s24le', sample_rate: '48000', channels: '1' }) + + // The player labels the files and offers the master. + await page.locator('[data-view="player"] [data-tab="capture"], [data-view="player"] [data-side-tab="capture"]').first().click().catch(() => undefined) + await page.locator('[data-capture-file="master-host-mic.wav"]').waitFor({ state: 'attached' }) + await page.context().close() + }, 120_000) + + it('opens Standard with echo cancellation off when Effects says so, notes the delivered size, and exports the camera with sound', async () => { + const context = await browser.newContext({ permissions: ['camera', 'microphone'], acceptDownloads: true }) + const page = await context.newPage() + page.on('pageerror', (e) => { throw e }) + await page.addInitScript(() => { + localStorage.setItem('formrec.studio', JSON.stringify({ countdownS: 0, quality: '1080p' })) + localStorage.setItem('formrec.sound', JSON.stringify({ preset: 'standard', roomTone: true })) + localStorage.setItem('formrec.effects', JSON.stringify({ echoCancellation: false })) + }) + await page.goto(`${base}/?token=${TOKEN}#/record`) + await page.locator('[data-view="studio"]').waitFor() + await page.evaluate(() => { + ;(window as any).__cls = 0 + ;(window as any).__shifts = [] + new PerformanceObserver((list) => { + for (const e of list.getEntries() as any[]) { + if (e.hadRecentInput) continue + ;(window as any).__cls += e.value + ;(window as any).__shifts.push(e.sources.map((s: any) => `${s.node?.nodeName}.${s.node?.className} ${JSON.stringify(s.previousRect)} -> ${JSON.stringify(s.currentRect)}`)) + } + }).observe({ type: 'layout-shift', buffered: true }) + }) + const cdp = await context.newCDPSession(page) + await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 }) + await page.locator('[data-mode="camera"]').click() + await page.getByRole('button', { name: 'Get ready' }).click() + const status = page.locator('[data-studio-status]') + await expect.poll(async () => (await status.textContent()) ?? '', { timeout: 20_000 }).toMatch(/^Ready\. Guests can join now\./) + const ready = (await status.textContent()) ?? '' + await page.getByRole('button', { name: 'Record', exact: true }).click() + await page.locator('[data-view="studio"][data-state="recording"]').waitFor({ timeout: 15_000 }) + await page.waitForTimeout(3000) + await page.getByRole('button', { name: 'Stop' }).click() + await page.getByText(/^Stopped\./).waitFor({ timeout: 20_000 }) + const shifts = await page.evaluate(() => ({ cls: (window as any).__cls as number, shifts: (window as any).__shifts })) + expect(shifts.cls, JSON.stringify(shifts.shifts)).toBe(0) + await cdp.send('Emulation.setCPUThrottlingRate', { rate: 1 }) + const save = page.getByRole('button', { name: /^Save/ }) + await expect.poll(async () => (await save.textContent()) ?? '', { timeout: 20_000 }).toBe('Save') + await save.click() + await page.waitForURL(/#\/f\//, { timeout: 30_000 }) + const id = decodeURIComponent(page.url().split('#/f/')[1]!) + const rec = JSON.parse(await readFile(path.join(dataDir, 'recordings', id, 'recording.json'), 'utf8')) + expect(rec.capture.preset).toBe('standard') + expect(rec.capture.master).toBeUndefined() + expect(rec.capture.roomToneMs).toBeUndefined() + expect(rec.capture.tracks.find((t: any) => t.kind === 'mic').settings.echoCancellation).toBe(false) + const cam = rec.capture.tracks.find((t: any) => t.kind === 'camera').settings + expect(rec.capture.requested).toEqual({ quality: '1080p', width: 1920, height: 1080 }) + expect(cam.width).toBeGreaterThan(0) + // Chromium's fake camera gives less than 1080p: the studio said so when it got ready. + if (Math.min(cam.width, cam.height) < 1080) expect(ready).toContain(`The camera delivers ${cam.width} x ${cam.height}, less than 1080p asks for (1920 x 1080).`) + else expect(ready).toBe('Ready. Guests can join now.') + + const button = page.locator('[data-player-actions] [data-export-with-sound="camera"], [data-export-with-sound="camera"]').first() + await button.waitFor() + if (!ffprobe(path.join(dataDir, 'recordings', id, 'track-host-mic.webm'))) return + const download = page.waitForEvent('download', { timeout: 120_000 }) + await button.click() + const file = path.join(await tempDir(), 'with-sound.mp4') + await (await download).saveAs(file) + const out = execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,pix_fmt', '-of', 'csv=p=0', file], { encoding: 'utf8' }) + expect(out).toMatch(/^h264,video,yuvj?420p$/m) + expect(out).toMatch(/aac,audio/) + await context.close() + }, 180_000) +}) diff --git a/tests/wav.test.ts b/tests/wav.test.ts new file mode 100644 index 0000000..64d45d1 --- /dev/null +++ b/tests/wav.test.ts @@ -0,0 +1,72 @@ +/** The microphone master's WAV layout (shared/wav.ts): the header, 24-bit samples and the sizes written at the end. */ +import { describe, expect, it } from 'vitest' +import { decodePcm24, encodePcm24, MAX_WAV_DATA, parseWavHeader, sizeFields, UNKNOWN_SIZE, WAV_HEADER_BYTES, wavDurationMs, wavHeader } from '../shared/wav.js' + +const format = { sampleRate: 48_000, channels: 1, bitsPerSample: 24 } as const + +describe('the WAV header', () => { + it('writes a canonical 44-byte PCM header for 48 kHz 24-bit mono', () => { + const head = Buffer.from(wavHeader(format, 288_000)) + expect(head.length).toBe(WAV_HEADER_BYTES) + expect(head.toString('ascii', 0, 4)).toBe('RIFF') + expect(head.readUInt32LE(4)).toBe(288_036) + expect(head.toString('ascii', 8, 16)).toBe('WAVEfmt ') + expect(head.readUInt32LE(16)).toBe(16) + expect(head.readUInt16LE(20)).toBe(1) + expect(head.readUInt16LE(22)).toBe(1) + expect(head.readUInt32LE(24)).toBe(48_000) + expect(head.readUInt32LE(28)).toBe(144_000) + expect(head.readUInt16LE(32)).toBe(3) + expect(head.readUInt16LE(34)).toBe(24) + expect(head.toString('ascii', 36, 40)).toBe('data') + expect(head.readUInt32LE(40)).toBe(288_000) + }) + + it('writes the unknown size while recording and reads its own headers back', () => { + const head = wavHeader(format) + expect(Buffer.from(head).readUInt32LE(4)).toBe(UNKNOWN_SIZE) + expect(parseWavHeader(head)).toEqual({ ...format, dataBytes: UNKNOWN_SIZE }) + expect(parseWavHeader(wavHeader({ sampleRate: 44_100, channels: 2, bitsPerSample: 16 }, 4))).toMatchObject({ sampleRate: 44_100, channels: 2, bitsPerSample: 16, dataBytes: 4 }) + }) + + it('refuses what is not a canonical PCM header', () => { + expect(parseWavHeader(new Uint8Array(10))).toBeUndefined() + const bad = wavHeader(format) + bad[20] = 3 + expect(parseWavHeader(bad)).toBeUndefined() + const webm = new Uint8Array(64) + webm.set([0x1a, 0x45, 0xdf, 0xa3]) + expect(parseWavHeader(webm)).toBeUndefined() + const tooFast = wavHeader({ ...format, sampleRate: 400_000 }) + expect(parseWavHeader(tooFast)).toBeUndefined() + }) + + it('sizes a finished file, capped at what 32 bits hold', () => { + expect(sizeFields(44 + 300)).toEqual({ riff: 336, data: 300 }) + expect(sizeFields(10)).toEqual({ riff: 36, data: 0 }) + expect(sizeFields(8 * 1024 ** 3).data).toBe(MAX_WAV_DATA) + expect(wavDurationMs(format, 144_000)).toBe(1000) + }) +}) + +describe('24-bit samples', () => { + it('encodes little-endian signed 24-bit with each side at its own full scale', () => { + const bytes = encodePcm24([0, 1, -1, 0.5, 2, -2]) + expect([...bytes.slice(0, 3)]).toEqual([0, 0, 0]) + expect([...bytes.slice(3, 6)]).toEqual([0xff, 0xff, 0x7f]) + expect([...bytes.slice(6, 9)]).toEqual([0x00, 0x00, 0x80]) + expect([...bytes.slice(12, 15)]).toEqual([0xff, 0xff, 0x7f]) + expect([...bytes.slice(15, 18)]).toEqual([0x00, 0x00, 0x80]) + }) + + it('round-trips within one step of 24 bits', () => { + const samples = Float32Array.from({ length: 480 }, (_, i) => Math.sin(i / 7) * 0.8) + const back = decodePcm24(encodePcm24(samples)) + expect(back).toHaveLength(480) + for (let i = 0; i < samples.length; i += 1) expect(Math.abs(back[i]! - samples[i]!)).toBeLessThan(2 / 8_388_607) + }) + + it('writes silence for a missing sample rather than noise', () => { + expect([...encodePcm24([Number.NaN])]).toEqual([0, 0, 0]) + }) +}) diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index c823bab..47e9054 100644 --- a/web/HASHOUT_LOG.md +++ b/web/HASHOUT_LOG.md @@ -134,3 +134,21 @@ Each new view is built once in the first frame at its final size and changed onl - logged: v0.9.0 · 2026-11-11 The live link's viewer page is the share page's own frame (same tokens, same slot and bar sizes) with the notes for waiting, connecting, paused and ended all drawn in the first frame; the server's state is one attribute on the page, so a change of state moves nothing. The picture is played by our own loader (`live-hls.ts`): fMP4 segments appended in sequence mode into one source buffer, so the feed's pauses and restarts, which jump the segments' own clock, play on without a gap; the viewer joins two segments back and is moved to the edge if the buffer grows. The bar is the app's `controlBar` with a `live` form (play, mute, picture in picture and full screen; a LIVE button takes the scrubber's place and grows to the same width, and no seek keys), so it is the same size either way. The studio's link section is built once with every field in place (privacy, password, people, address, note), filled in place by attributes and text. The Variants panel exists in its first frame at a fixed size: the variables list, the values box, the progress bar, the status line and the variants list each scroll inside their own box, and the progress is a custom property read by a transform. The demo's language picker and the insights block (four tiles at zero and a list of a fixed height) are in the first frame, and switching language changes text and the address in place. The Guide dialog is built before `showModal`, with its summary written first, so it opens complete, and only the status text and the links change. The bridge's choice and deny list are static controls with a fixed-height note under the field for names that are no tool. The Redaction row in Settings starts in its default so the saved value moves nothing. A play the browser refuses is drawn by `startPlay` as an event on the media element that every bar listens to; the reason is an attribute on the frame, not a node. Each view except the play one measured 0 layout shift at 4x CPU throttling in Chromium; `play-refused-e2e` runs Chromium and Firefox, and the rest ran in Chromium only. + +## unreleased · Voice master, levels that are always there, script mode {#voice-master-levels} + +- refers-to: src/studio-sound.ts `studioSound`, voice-master.ts `micConstraints`, levels.ts, meter.ts `dbMeter`, level-engine.ts `openEngine`, capture-tap-worklet.ts, wav-recorder.ts `WavRecorder`, capture-meta.ts, studio-script.ts, script-logic.ts, capture-player.ts, capture.ts `Want.micConstraints`, effects-audio.ts `loudness`, studio.ts (the calls into sound and script), marks.ts `add(title, atMs, say)`, player.ts (track labels); ../styles/levels.css; ../../tests/levels.test.ts, capture-meta.test.ts, script-logic.test.ts, voice-master-e2e.test.ts +- logged: unreleased · 2026-11-29 + +The microphone used to open with echo cancellation hard-coded on, whatever Effects said; it now opens with the constraints of the chosen preset. Standard takes Effects' three switches as they are; Voice master turns all three off, asks for mono at 48 kHz and 24 bits, and skips every studio plugin's `mic` hook, so no Effects chain or noise filter touches it. WebKit's MediaRecorder cannot write PCM, so the master comes from an AudioWorklet tap (`/capture-tap-worklet.js`, like the live captions' tap because the CSP allows no blob workers) that hands every sample to the page in 50 ms blocks; the same blocks feed the meters, the clip count, the hints and the level check, so clips are counted even when the tab is in the background and no frame is drawn. Where worklets are missing an AnalyserNode is polled for the meters and no master is written, and the studio says so. + +The old meter read "quiet" only below -40 dBFS and "loud" at -1, so speech at -31 LUFS looked fine and a clip was a flash. The meter is now in dBFS from -60 to 0 with the too-quiet zone (under -24), the green band (-18 to -12) and the red zone (from -3) painted on its track from the same numbers the code uses (custom properties set from levels.ts), a 1.5 s peak hold with its number, a clip light that stays red until clicked with the running count, and a plain-words hint after three seconds of quiet speech or three red hits in ten seconds. A large one sits under the stage and a compact one in the record bar, in every layout, from the first frame; both change only by transforms, attributes and text. The stage's old meter pill went. After the take the hint line holds "Clipped N times, at ..." until the next take, and the status line says it too. Effects' preview meter keeps its own bar but reads the same zones through `loudness`. + +The strip's height first came out of the stage (a larger `--stage-room`), which shrank the 16:9 stage enough at 720 px for the annotation toolbar to cover Live Rewind's Trim button; the stage keeps its size and the page is 92 px taller instead. Script mode drops a chapter per paragraph through `marks.add` with the paragraph as the chapter's words; Space is taken from a focused button while a script is read, keyup included, so it never presses Pause or Stop. Measured: Get ready, recording and stop in the camera layout with the meters live shift 0 at 4x CPU throttling in Chromium. + +## unreleased · the player link view {#player-link-view} + +- refers-to: src/player-link.ts `takePlayerKey` `playerKeyFor` `playerLinkApi`, player.ts `linkView` (view's `kind`), app.ts (the route), features/agents.ts (Player links, Rotate, and the `agents.rotate-player-links` command), meetings-settings.ts (a refused first read), ../index.html (the Player links row) +- logged: unreleased · 2026-11-29 + +A player link is `/?player=#/f/`. On load the key leaves the address for the tab's storage, as the run's token does. When the tab has no run token and holds a key for that recording, `#/f/` draws `linkView`: the player as a demo draws it (read only, only the features marked for demos, which read files through `src`), under a Player link bar in the demo bar's slot, with media from `/api/player//?key=`. A tab that has the run's token opens the full player as before. The other boot reads fail quietly without the token; meetings' Settings read was the one that threw, now caught. The Player links row in Settings, Agents uses the MCP token row's sizes and a spacer in the copy button's place, so it moves nothing. diff --git a/web/index.html b/web/index.html index 9001cf6..e58c4aa 100644 --- a/web/index.html +++ b/web/index.html @@ -10,6 +10,7 @@ + @@ -30,6 +31,7 @@ + @@ -286,10 +288,11 @@

Agents

}

Over HTTP

-

The same tools at a URL, for agents that connect by address instead of starting a program. Every request needs the MCP token as Authorization: Bearer; the endpoint answers on this computer only. Connect over HTTP replaces the client's formrec entry, so a client uses one way at a time. Rotate makes a new token and stops the old one at once.

+

The same tools at a URL, for agents that connect by address instead of starting a program. Every request needs the MCP token as Authorization: Bearer; the endpoint answers on this computer only. Connect over HTTP replaces the client's formrec entry, so a client uses one way at a time. Rotate makes a new token and stops the old one at once. A link an agent gives you opens that recording's player only, never the rest of FormRec; Rotate on Player links stops every link given so far.

EndpointStreamable HTTP, also formrec mcp --http on port 8775.
http://127.0.0.1:8770/mcp
MCP tokenKept in the data folder, private to you.
Loading
+
Player linksLinks in agents' answers open one recording's player and nothing else.
One recording each
Claude Code
Checking
Codex
Checking
Cursor
Checking
diff --git a/web/src/api.ts b/web/src/api.ts index 2f9243b..b04104d 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1,3 +1,5 @@ +import type { Capture } from './capture-meta.js' + export interface Anchor { path: string; line?: number; endLine?: number; symbol?: string; note?: string status: string; snippet?: string; commit?: string; url?: string @@ -24,6 +26,8 @@ export interface Recording { clipOf?: { id: string; startMs: number; endMs: number; shape: '9:16' | '1:1' | '16:9' } /** Set on a variant (src/variants): its source recording (absent when it came from a file) and its variables' values, without the private ones. */ variantOf?: { id?: string; values: Record } + /** A studio take's capture: preset, what the browser applied to each track, the master WAV, clips (src/model/capture.ts). */ + capture?: Capture & { master?: Capture['master'] & { bytes: number; complete: boolean } } } export interface SessionTrack { id: string; kind: Kind; person: string; host: boolean; chunks: number; bytes: number; ended: boolean } export interface Session { @@ -82,7 +86,7 @@ export const api = { control: (id: string, action: 'start' | 'pause' | 'resume' | 'stop') => api.json(`/api/sessions/${encodeURIComponent(id)}/control`, 'POST', { action }), addTrack: (id: string, kind: Kind, mime: string, startedAt: number, nonce: string) => api.json(`/api/sessions/${encodeURIComponent(id)}/tracks`, 'POST', { kind, mime, startedAt, nonce }), - save: (id: string, body: { title: string; summary: string; durationMs: number; marks: MarkInput[] }) => + save: (id: string, body: { title: string; summary: string; durationMs: number; marks: MarkInput[]; capture?: Capture }) => api.json(`/api/sessions/${encodeURIComponent(id)}/save`, 'POST', body), guests: () => call('/api/guests'), setGuests: (enabled: boolean) => api.json('/api/guests', 'PUT', { enabled }), diff --git a/web/src/app.ts b/web/src/app.ts index be05772..d2ca4d2 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -4,7 +4,8 @@ import { h } from './dom.js' import { homeView } from './home.js' import { libraryView } from './library.js' import { markRoute, wireChrome } from './menus.js' -import { demoView, playerView } from './player.js' +import { demoView, linkView, playerView } from './player.js' +import { playerKeyFor, takePlayerKey } from './player-link.js' import { defaultMode } from './prefs.js' import { wireSettings } from './settings.js' import { studioView, type Mode } from './studio.js' @@ -61,6 +62,7 @@ async function route(): Promise { const record = /^\/record(?:\?mode=(screen|camera|audio))?$/.exec(hash) const own = viewRoutes.all().map((r) => [r, r.pattern.exec(hash)] as const).find(([, m]) => m !== null) if (own?.[1]) next = await own[0].view(own[1]) + else if (player?.[1] && !token() && playerKeyFor(player[1])) next = await linkView(player[1], playerKeyFor(player[1])!) else if (player?.[1]) next = await playerView(player[1]) else if (demo?.[1] && DEMOS.some((d) => d.id === demo[1])) next = await demoView(demo[1]) else if (record) next = studioView((record[1] as Mode | undefined) ?? defaultMode()) @@ -83,6 +85,8 @@ export function countRecordings(): void { }, () => undefined) } +// A player link's key leaves the address first (player-link.ts), then the run's token, when the address has one. +takePlayerKey() token() wireTheme() wireChrome() diff --git a/web/src/capture-meta.ts b/web/src/capture-meta.ts new file mode 100644 index 0000000..8a5353d --- /dev/null +++ b/web/src/capture-meta.ts @@ -0,0 +1,65 @@ +/** + * What a take records about its own capture, for recording.json's `capture`: each track's getSettings() (the + * processing the browser actually applied, the sample rate, the size it delivered), the quality asked for, and a + * plain note when a source delivered less than the preset. Only known keys of plain types are kept, so nothing a + * browser adds later (or a device id) is written. Pure; tests/capture-meta.test.ts covers it. + */ +import type { SoundPreset } from './voice-master.js' +import type { Clip, LevelCheck } from './levels.js' + +export type CaptureKind = 'screen' | 'camera' | 'mic' | 'system' + +const NUMBERS = ['width', 'height', 'frameRate', 'aspectRatio', 'sampleRate', 'sampleSize', 'channelCount', 'latency'] as const +const BOOLEANS = ['echoCancellation', 'noiseSuppression', 'autoGainControl'] as const +const STRINGS = ['displaySurface', 'facingMode', 'resizeMode'] as const + +export type TrackSettings = Partial & Record<(typeof BOOLEANS)[number], boolean> & Record<(typeof STRINGS)[number], string>> + +export interface CaptureTrack { kind: CaptureKind; label: string; settings: TrackSettings } + +export interface Capture { + preset: SoundPreset + requested: { quality: string; width: number; height: number } + tracks: CaptureTrack[] + /** The microphone went through the Effects chain (Standard with a noise filter); never in Voice master. */ + micEffects: boolean + roomToneMs?: number + master?: { file: string; sampleRate: number; bitsPerSample: number; channels: number; durationMs: number } + levels?: { clips: Clip[]; check?: { peakDb: number | null; maxDb: number | null; clips: number; advice: LevelCheck['advice']; byDb: number } } +} + +/** The keys of getSettings() this app writes down, rounded where a float would be noise. */ +export function trackSettings(raw: Record): TrackSettings { + const out: Record = {} + for (const k of NUMBERS) { + const v = raw[k] + if (typeof v === 'number' && Number.isFinite(v)) out[k] = Math.round(v * 1000) / 1000 + } + for (const k of BOOLEANS) if (typeof raw[k] === 'boolean') out[k] = raw[k] as boolean + for (const k of STRINGS) if (typeof raw[k] === 'string') out[k] = (raw[k] as string).slice(0, 40) + return out as TrackSettings +} + +export function captureTrack(kind: CaptureKind, track: { label: string; getSettings(): MediaTrackSettings }): CaptureTrack { + return { kind, label: track.label.slice(0, 200), settings: trackSettings(track.getSettings() as unknown as Record) } +} + +/** "The camera delivers 1280 x 720, less than 1080p asks for (1920 x 1080)." or undefined when it delivered the preset. */ +export function deliveredNote(kind: CaptureKind, requested: Capture['requested'], settings: TrackSettings): string | undefined { + const { width, height } = settings + if (kind !== 'camera' && kind !== 'screen') return undefined + if (typeof width !== 'number' || typeof height !== 'number') return undefined + // Compare the shorter sides, so a portrait camera at the preset's size counts as delivering it. + if (Math.min(width, height) >= Math.min(requested.width, requested.height)) return undefined + const name = kind === 'camera' ? 'The camera' : 'The screen' + return `${name} delivers ${width} x ${height}, less than ${requested.quality} asks for (${requested.width} x ${requested.height}).` +} + +/** A dBFS number for JSON: rounded to a tenth, null for silence. */ +export function jsonDb(db: number): number | null { + return Number.isFinite(db) ? Math.round(db * 10) / 10 : null +} + +export function checkForJson(check: LevelCheck): NonNullable['check'] { + return { peakDb: jsonDb(check.peakDb), maxDb: jsonDb(check.maxDb), clips: check.clips, advice: check.advice, byDb: check.byDb } +} diff --git a/web/src/capture-player.ts b/web/src/capture-player.ts new file mode 100644 index 0000000..7e226d2 --- /dev/null +++ b/web/src/capture-player.ts @@ -0,0 +1,137 @@ +/** + * The player's view of how a studio take was captured: "Export with sound" (the camera or the screen with the + * microphone in one MP4 that QuickTime plays, at the size it was recorded), and the Capture panel (the preset, what the + * browser applied to each track, the size asked for and delivered, the clips with their times, and every file of the + * take labelled with what it holds, so nobody opens the silent camera file expecting sound). The export is edit's one + * exporter (src/features/edit) with the picture alone and no bubble; this only picks the picture and its size. + * Registered by features/studio.ts. + */ +import type { Recording, Track } from './api.js' +import { clock, h } from './dom.js' +import { editApi, follow } from './edit-api.js' +import { button, icon } from './view-kit.js' +import { playerActions, playerPanels, type PlayerContext } from './features/registry.js' +import { clipReport } from './levels.js' +import type { Capture } from './capture-meta.js' + +/** The heights edit's exporter renders. */ +const HEIGHTS = [360, 480, 720, 1080, 1280, 1920, 2160] as const + +/** The export size for a picture: its delivered height rounded down to one the exporter makes, its own shape kept. */ +export function exportSize(delivered: { width?: number; height?: number } | undefined): { height: number; width?: number } { + const w = delivered?.width + const hgt = delivered?.height + if (!w || !hgt) return { height: 1080 } + const height = [...HEIGHTS].reverse().find((x) => x <= hgt) ?? 360 + const width = Math.max(64, Math.round((height * w) / hgt / 2) * 2) + return { height, width } +} + +/** What each file of a take holds, in words: the camera and screen files are pictures only. */ +export function fileLabel(t: Pick): string { + if (t.kind === 'mic') return t.id.endsWith('-system') ? `${t.person}: sound only (Opus)` : `${t.person} microphone: sound only (Opus)` + return `${t.person} ${t.kind}: picture only, no sound` +} + +const pictures = (rec: Recording): Track[] => (rec.tracks ?? []).filter((t) => t.host && (t.kind === 'camera' || t.kind === 'screen')) +const hasSound = (rec: Recording): boolean => (rec.tracks ?? []).some((t) => t.kind === 'mic') + +function deliveredOf(rec: Recording, kind: 'camera' | 'screen'): { width?: number; height?: number } | undefined { + return rec.capture?.tracks.find((t) => t.kind === kind)?.settings +} + +/** Render, follow and download one picture with the sound; the button says how far it is. */ +async function exportWithSound(ctx: PlayerContext, kind: 'camera' | 'screen', btn: HTMLButtonElement): Promise { + const label = btn.querySelector('.rv-label') + const say = (text: string): void => { if (label) label.textContent = text } + btn.disabled = true + try { + const size = exportSize(deliveredOf(ctx.rec, kind)) + const job = await follow(await editApi.export(ctx.rec.id, { format: 'mp4', ...size, layout: kind }), (j) => say(`Rendering ${j.percent}%`)) + if (job.state !== 'done' || !job.file) throw new Error(job.error ?? 'The export failed.') + h('a', { href: ctx.src(job.file), download: `${ctx.rec.id}-${kind}-with-sound.mp4` }).click() + say(`${kind === 'camera' ? 'Camera' : 'Screen'} with sound`) + btn.title = '' + } catch (error) { + say('Export failed') + btn.title = (error as Error).message + } finally { + btn.disabled = false + } +} + +function exportButton(ctx: PlayerContext, kind: 'camera' | 'screen', text: string, attrs: Record = {}): HTMLButtonElement { + const b = button(text, 'download', { class: 'rv-btn rv-with-sound', 'data-export-with-sound': kind, title: `One MP4 with the ${kind} and the microphone, at the size it was recorded`, ...attrs }) + b.addEventListener('click', () => void exportWithSound(ctx, kind, b)) + return b +} + +playerActions.add({ + id: 'with-sound', + order: 22, + render(ctx) { + const main = (ctx.rec.tracks ?? []).find((t) => t.file === ctx.rec.video) + if (ctx.demo || !main || (main.kind !== 'camera' && main.kind !== 'screen') || !hasSound(ctx.rec)) return h('span', { hidden: true }) + return exportButton(ctx, main.kind, 'Export with sound') + }, +}) + +const flag = (v: boolean | undefined): string => (v === undefined ? 'not reported' : v ? 'on' : 'off') + +function settingsLine(t: Capture['tracks'][number]): string { + const s = t.settings + if (t.kind === 'mic' || t.kind === 'system') { + const rate = s.sampleRate ? `${s.sampleRate} Hz` : 'rate not reported' + const ch = s.channelCount ? `${s.channelCount} ch` : '' + return [rate, ch, `echo cancellation ${flag(s.echoCancellation)}`, `noise suppression ${flag(s.noiseSuppression)}`, `auto gain ${flag(s.autoGainControl)}`].filter(Boolean).join(', ') + } + return [s.width && s.height ? `${s.width} x ${s.height}` : 'size not reported', s.frameRate ? `${Math.round(s.frameRate)} fps` : ''].filter(Boolean).join(', ') +} + +function capturePanel(ctx: PlayerContext): HTMLElement { + const rec = ctx.rec + const cap = rec.capture + const rows: HTMLElement[] = [] + const row = (name: string, value: Node | string, attr: string): HTMLElement => h('li', { class: 'rv-cap-row', [attr]: '' }, h('span', { class: 'rv-cap-name' }, name), h('span', { class: 'rv-cap-value' }, value)) + if (cap) { + rows.push(row('Preset', cap.preset === 'voice-master' ? 'Voice master: no processing, lossless master' : 'Standard', 'data-capture-preset')) + rows.push(row('Asked for', `${cap.requested.quality} (${cap.requested.width} x ${cap.requested.height})`, 'data-capture-requested')) + for (const t of cap.tracks) rows.push(row(`${t.kind === 'system' ? 'System audio' : t.kind[0]!.toUpperCase() + t.kind.slice(1)}${t.label ? `, ${t.label}` : ''}`, settingsLine(t), `data-capture-track-${t.kind}`)) + if (cap.micEffects) rows.push(row('Effects', 'The microphone went through the Effects chain.', 'data-capture-effects')) + if (cap.roomToneMs) rows.push(row('Room tone', `The first ${cap.roomToneMs / 1000} s`, 'data-capture-roomtone')) + const clips = cap.levels?.clips ?? [] + const times = clips.slice(0, 40).map((c) => { + const a = h('a', { href: '#', class: 'rv-cap-clip', 'data-capture-clip': String(c.atMs) }, clock(c.atMs)) + a.addEventListener('click', (e) => { e.preventDefault(); ctx.seek(c.atMs) }) + return a + }) + rows.push(row('Clipping', h('span', {}, clipReport(clips).replace(/, at .*$/, clips.length ? ':' : ''), ...times.flatMap((a) => [' ', a])), 'data-capture-clips')) + const check = cap.levels?.check + if (check) rows.push(row('Level check', `${check.advice === 'ok' ? 'in the band' : check.advice === 'up' ? 'too quiet' : check.advice === 'down' ? 'too loud' : 'nothing heard'}${check.peakDb === null ? '' : `, peaks about ${check.peakDb} dBFS`}`, 'data-capture-check')) + } else { + rows.push(row('Capture', 'This recording was made before FormRec wrote down how it was captured.', 'data-capture-none')) + } + const files: HTMLElement[] = (rec.tracks ?? []).map((t) => h('li', { class: 'rv-cap-file', 'data-capture-file': t.file }, + icon(t.kind, 14), h('span', { class: 'rv-cap-file-name' }, t.file), h('span', { class: 'rv-cap-file-what' }, fileLabel(t)))) + if (rec.capture?.master) { + const m = rec.capture.master + files.push(h('li', { class: 'rv-cap-file', 'data-capture-file': m.file }, + icon('wave', 14), h('a', { class: 'rv-cap-file-name', href: ctx.src(m.file), download: `${rec.id}-mic-master.wav` }, m.file), + h('span', { class: 'rv-cap-file-what' }, `Microphone master: lossless ${m.bitsPerSample}-bit ${m.sampleRate / 1000} kHz WAV, sound only`))) + } + const exports = pictures(rec).filter(() => hasSound(rec)).map((t) => exportButton(ctx, t.kind as 'camera' | 'screen', `${t.kind === 'camera' ? 'Camera' : 'Screen'} with sound`, { 'data-capture-export': t.kind })) + return h('div', { class: 'rv-cap', 'data-capture-panel': '' }, + h('ul', { class: 'rv-cap-list' }, ...rows), + h('h3', { class: 'rv-cap-head' }, 'Files'), + h('ul', { class: 'rv-cap-files' }, ...files), + exports.length ? h('div', { class: 'rv-row rv-cap-exports' }, ...exports) : null, + ) +} + +playerPanels.add({ + id: 'capture', + title: 'Capture', + order: 74, + when: (ctx) => ctx.rec.source === 'person' && (ctx.rec.tracks?.length ?? 0) > 0, + render: capturePanel, +}) diff --git a/web/src/capture-tap-worklet.ts b/web/src/capture-tap-worklet.ts new file mode 100644 index 0000000..6e87c89 --- /dev/null +++ b/web/src/capture-tap-worklet.ts @@ -0,0 +1,33 @@ +/** + * The microphone tap behind the level meter and the WAV master, as an AudioWorklet module (served as + * /capture-tap-worklet.js, loaded by level-engine.ts): hands the first channel to the page in blocks of a twentieth of + * a second, every sample, so clips are counted and the master is written even while the tab is in the background and + * frames are not drawn. It changes nothing about the sound and outputs silence. + */ +declare const registerProcessor: ((name: string, ctor: unknown) => void) | undefined +declare const sampleRate: number +declare class AudioWorkletProcessor { readonly port: { postMessage(message: unknown, transfer?: unknown[]): void } } + +if (typeof registerProcessor === 'function') { + class CaptureTap extends AudioWorkletProcessor { + private readonly size = Math.max(128, Math.round(sampleRate / 20)) + private block = new Float32Array(this.size) + private filled = 0 + process(inputs: Float32Array[][]): boolean { + const first = inputs[0]?.[0] + if (!first) return true + for (let i = 0; i < first.length; i += 1) { + this.block[this.filled] = first[i]! + this.filled += 1 + if (this.filled === this.size) { + const full = this.block + this.block = new Float32Array(this.size) + this.filled = 0 + this.port.postMessage(full, [full.buffer]) + } + } + return true + } + } + registerProcessor('formrec-capture-tap', CaptureTap) +} diff --git a/web/src/capture.ts b/web/src/capture.ts index fdbb5de..ded3da6 100644 --- a/web/src/capture.ts +++ b/web/src/capture.ts @@ -1,8 +1,8 @@ /** * Opening sources and recording each one to its own track. The microphone is - * opened with the browser's gain and noise processing off, so the track keeps - * the voice as it was; echo cancellation stays on because a call may be - * running through speakers. + * opened with the constraints the studio's sound preset gives (voice-master.ts + * micConstraints): Effects' own echo cancellation, noise suppression and gain + * switches for Standard, every one of them off for Voice master. */ import { ChunkUploader, type UploadState, type UploadTarget } from './uploader.js' @@ -32,6 +32,8 @@ export interface Want { micId?: string /** The quality preset's camera constraints (studio-logic.ts cameraConstraints), device included. */ cameraConstraints?: MediaTrackConstraints + /** The sound preset's microphone constraints (voice-master.ts micConstraints), device included. */ + micConstraints?: MediaTrackConstraints } export async function openSources(want: Want): Promise { @@ -50,7 +52,7 @@ export async function openSources(want: Want): Promise { } if (want.mic) { sources.mic = await navigator.mediaDevices.getUserMedia({ - audio: { echoCancellation: true, noiseSuppression: false, autoGainControl: false, channelCount: 1, ...(want.micId ? { deviceId: { exact: want.micId } } : {}) }, + audio: want.micConstraints ?? { echoCancellation: true, noiseSuppression: false, autoGainControl: false, channelCount: 1, ...(want.micId ? { deviceId: { exact: want.micId } } : {}) }, }) opened.push(sources.mic) } diff --git a/web/src/edit-api.ts b/web/src/edit-api.ts index 12ee81b..2d02229 100644 --- a/web/src/edit-api.ts +++ b/web/src/edit-api.ts @@ -52,7 +52,7 @@ export const editApi = { gif: (id: string) => post<{ file: string }>(`${enc(id)}/gif`, {}), peaks: (id: string) => call<{ peaks: number[] }>(`${enc(id)}/peaks`), filmstrip: (id: string) => post<{ file: string; frames: number }>(`${enc(id)}/filmstrip`, {}), - export: (id: string, body: { format: string; height: number; captions?: boolean; noiseFilter?: boolean }) => post(`${enc(id)}/export`, body), + export: (id: string, body: { format: string; height: number; width?: number; layout?: 'bubble' | 'screen' | 'camera' | 'side' | 'stack'; captions?: boolean; noiseFilter?: boolean }) => post(`${enc(id)}/export`, body), duplicate: (id: string) => post<{ id: string; title: string }>(`${enc(id)}/duplicate`, {}), send: (id: string, to: 'formencoder' | 'formwav') => post<{ file: string; text: string }>(`${enc(id)}/send`, { to }), } diff --git a/web/src/effects-audio.ts b/web/src/effects-audio.ts index b9ad598..7bb1999 100644 --- a/web/src/effects-audio.ts +++ b/web/src/effects-audio.ts @@ -10,6 +10,7 @@ * render thread is overloaded (the CPU guard in effects-noise-node.ts), the chain uses the gate instead. */ import { createNoiseNode, noiseSupported, type NoiseHandle } from './effects-noise-node.js' +import { dbfs, QUIET_DB, RED_DB } from './levels.js' import type { NoiseMode } from './effects-layout.js' @@ -36,10 +37,15 @@ export function micConstraints(fx: MicEffects): MediaTrackConstraints { return { noiseSuppression: fx.noiseSuppression, echoCancellation: fx.echoCancellation, autoGainControl: fx.autoGainControl } } -/** The meter's reading: quiet (barely picked up), ok, or loud (close to clipping, the meter turns red). */ +/** + * The Effects preview meter's reading, on the studio meter's zones (levels.ts): quiet when speech peaks stay under + * -24 dBFS, loud from the red zone at -3 dBFS, ok between. The 0.9 thresholds (-40 and -1 dBFS) read speech at -31 + * LUFS as fine and showed clipping only as it happened. + */ export function loudness(peak: number): 'quiet' | 'ok' | 'loud' { - if (peak >= 0.89) return 'loud' - if (peak < 0.01) return 'quiet' + const db = dbfs(peak) + if (db >= RED_DB) return 'loud' + if (db < QUIET_DB) return 'quiet' return 'ok' } diff --git a/web/src/features/agents.ts b/web/src/features/agents.ts index a6754b1..c0eb56b 100644 --- a/web/src/features/agents.ts +++ b/web/src/features/agents.ts @@ -5,6 +5,7 @@ * Connect buttons with POST /api/agents/install. settings.ts calls refreshAgents when the dialog opens. */ import { api } from '../api.js' +import { commands } from './registry.js' export interface AgentClient { id: string @@ -260,6 +261,31 @@ async function rotate(root: ParentNode, button: HTMLButtonElement): Promise { + return api.json<{ rotated: boolean }>('/api/agents/player-links/rotate', 'POST', {}) +} + +async function rotateLinks(root: ParentNode, button: HTMLButtonElement): Promise { + const result = root.querySelector('[data-agents-result]') + if (button.getAttribute('aria-busy') === 'true') return + button.setAttribute('aria-busy', 'true') + try { + await rotatePlayerLinks() + if (result) { + delete result.dataset.error + setText(result, 'Player links replaced. Every player link given so far stops working; agents give new ones in their next answers.') + } + } catch (error) { + if (result) { + result.dataset.error = '' + setText(result, (error as Error).message) + } + } finally { + button.removeAttribute('aria-busy') + } +} + async function connect(root: ParentNode, button: HTMLButtonElement): Promise { const http = button.dataset.agentsConnectHttp const relay = button.dataset.agentsConnectRelay @@ -293,6 +319,8 @@ export function wireAgents(root: Document = document): void { const target = e.target as HTMLElement const rotating = target.closest('[data-agents-rotate]') if (rotating) return void rotate(page, rotating) + const links = target.closest('[data-agents-rotate-player-links]') + if (links) return void rotateLinks(page, links) const saving = target.closest('[data-agents-bridge-save]') if (saving) return void saveBridge(page, saving) const revoking = target.closest('[data-agents-revoke]') @@ -301,3 +329,6 @@ export function wireAgents(root: Document = document): void { if (button) void connect(page, button) }) } + +// On demand from the window (the desktop menu and the extension run commands by id): the same route Settings calls. +commands.add({ id: 'agents.rotate-player-links', label: 'Replace player links', run: async () => { await rotatePlayerLinks() } }) diff --git a/web/src/features/index.ts b/web/src/features/index.ts index 3822045..7727bf0 100644 --- a/web/src/features/index.ts +++ b/web/src/features/index.ts @@ -22,6 +22,7 @@ import './desktop.js' import './agents.js' import './runner.js' import './phone.js' +import './phone-capture.js' import './tunnel.js' import './relay.js' import './sso.js' diff --git a/web/src/features/phone-capture.ts b/web/src/features/phone-capture.ts new file mode 100644 index 0000000..75e7bbb --- /dev/null +++ b/web/src/features/phone-capture.ts @@ -0,0 +1,363 @@ +/** + * Phone capture in the studio (issue #7): the Phone panel picks a phone as the take's picture, in place of this + * computer's screen, and the studio records it the way it records the desktop feature's native display (the + * nativeScreen and nativeRecorder slots of ./registry.ts): no screen picker, and the server or the desktop app's + * shell records the phone. Sources: + * - an iPhone or iPad on USB (macOS, the FormRec app): the shell records it through AVFoundation after opting in to + * CoreMediaIO's screen capture devices (src-tauri/src/phone.rs) into the capture folder the server named; + * - an Android phone or emulator over adb, on USB or Wi-Fi, with show taps and an optional clean status bar; + * - a booted iOS Simulator; the AirPlay mirror window on a Mac; + * - a recording made on the phone, played on the stage while the person narrates. + * The picture is used when the layout records the screen with Capture set to Entire screen. Also here: "Import a + * phone recording" (the library's importer) and the Phone layouts action on a recording with a phone picture. + * + * The panel's parts exist from its first frame (web/styles/phone-capture.css reserves their room); lists and text + * change in place. + */ +import { authHeaders, token } from '../api.js' +import { h } from '../dom.js' +import { icon, toggle } from '../view-kit.js' +import { inDesktop, invoke } from '../desktop-logic.js' +import { uploadVideo } from '../library-model.js' +import { clockText, missingNotes, sourceOptions, stillOffered, touchNote, type ServerSources, type ShellView, type SourceOption } from '../phone-capture-logic.js' +import { recordingActions, studioPlugins, type NativeScreenRecorder } from './registry.js' +import { debounce, DEBOUNCE_MS } from '../studio-devices.js' + +interface ShellReply { ok: boolean; error?: string; value?: T } +interface FileChoice { id: string; name: string; durationMs?: number } + +let server: ServerSources | undefined +let shell: ShellView = { desktop: inDesktop(), mac: /Mac/i.test(navigator.platform || navigator.userAgent), devices: [] } +let options: SourceOption[] = [] +let chosen: string | undefined +let showTaps = true +let demoMode = false +let file: FileChoice | undefined +let note = '' +let loading: Promise | undefined +const listeners = new Set<() => void>() +/** The stage's player for a phone recording (one per studio view). */ +let stageVideo: HTMLVideoElement | undefined + +function changed(): void { + for (const fn of [...listeners]) fn() +} + +async function call(method: string, url: string, body?: unknown): Promise { + const raw = body instanceof Blob + const res = await fetch(url, { + method, + headers: { ...authHeaders(), ...(body === undefined || raw ? {} : { 'Content-Type': 'application/json' }) }, + ...(body === undefined ? {} : { body: raw ? body : JSON.stringify(body) }), + }) + const json = (await res.json().catch(() => ({}))) as T & { error?: string } + if (!res.ok) throw new Error(json.error ?? res.statusText) + return json +} + +async function shellCall(cmd: string, args?: Record): Promise { + const reply = await invoke>(cmd, args) + if (!reply) throw new Error('the FormRec app did not answer') + if (!reply.ok) throw new Error(reply.error ?? 'the FormRec app refused') + return reply.value as T +} + +/** + * Whether the window's own camera list names each device the shell found (labels are there once the page has camera + * permission). This answers, on a real phone, whether the web view sees an iPhone after the shell's CoreMediaIO + * opt-in; the recording itself always goes through the shell. + */ +async function markSeen(devices: ShellView['devices']): Promise { + if (!devices.length || !navigator.mediaDevices?.enumerateDevices) return devices + const labels = new Set((await navigator.mediaDevices.enumerateDevices().catch(() => [] as MediaDeviceInfo[])).filter((d) => d.kind === 'videoinput').map((d) => d.label)) + return devices.map((d) => ({ ...d, seenByWindow: labels.has(d.name) })) +} + +/** Ask the server and the shell what is plugged in. */ +export function loadSources(again = false): Promise { + if (loading && !again) return loading + loading = (async () => { + const [s, devices] = await Promise.all([ + call('GET', '/api/phone/sources').catch(() => undefined), + inDesktop() + ? invoke>('phone_ios_devices').then((r) => r ?? { ok: false, error: 'this FormRec app has no iPhone capture' }) + : Promise.resolve(undefined), + ]) + server = s + if (devices) shell = { desktop: true, mac: devices.ok ? Boolean(devices.value?.mac) : shell.mac, devices: await markSeen(devices.value?.devices ?? []), ...(devices.ok ? {} : { error: devices.error }) } + if (s) shell = { ...shell, mac: s.platform === 'darwin' } + options = sourceOptions(server, shell) + chosen = chosen === 'file' ? chosen : stillOffered(options, chosen) + note = s ? '' : 'FormRec could not ask this computer for phones.' + changed() + })() + return loading +} + +const current = (): SourceOption | undefined => options.find((o) => o.key === chosen) + +/** True when the take's picture is a phone (and a phone recording has been chosen when that is the source). */ +export function phoneWanted(): boolean { + const o = current() + return Boolean(o && !o.blocked && (o.kind !== 'file' || file)) +} + +function sourceBody(o: SourceOption): Record { + if (o.kind === 'android') return { ...o.source, showTaps, demoMode } + if (o.kind === 'file') return { kind: 'file', file: file!.id } + return o.source +} + +/** The take's phone recorder: the studio starts, pauses, resumes and stops it with the take. */ +export function phoneRecorder(sessionId: string, onError: (message: string) => void): NativeScreenRecorder | undefined { + const o = current() + if (!o || !phoneWanted()) return undefined + const body = { sessionId } + let tail: Promise = Promise.resolve() + const step = (work: () => Promise): Promise => { + const next = tail.then(work) + tail = next.catch((error: Error) => { onError(`The phone: ${error.message}`) }) + return next + } + const video = stageVideo + return { + start: () => void step(async () => { + const started = await call<{ captureId: string }>('POST', '/api/phone/feed/start', { sessionId, source: sourceBody(o) }) + if (o.kind === 'ios-usb') { + await shellCall('phone_ios_start', { device: o.key.slice(4), capture: started.captureId }) + await call('POST', '/api/phone/feed/begin', body) + } + if (o.kind === 'file' && video) { video.currentTime = 0; video.muted = true; await video.play() } + }).catch(() => undefined), + pause: () => void step(async () => { + if (o.kind === 'ios-usb') await shellCall('phone_ios_pause') + if (o.kind === 'file') video?.pause() + await call('POST', '/api/phone/feed/pause', body) + }).catch(() => undefined), + resume: () => void step(async () => { + if (o.kind === 'ios-usb') await shellCall('phone_ios_resume') + if (o.kind === 'file' && video) await video.play() + await call('POST', '/api/phone/feed/resume', body) + }).catch(() => undefined), + stop: () => step(async () => { + if (o.kind === 'ios-usb') await shellCall('phone_ios_stop').catch((error: Error) => onError(`The phone: ${error.message}`)) + const played = o.kind === 'file' && video ? Math.round(video.currentTime * 1000) : undefined + video?.pause() + const done = await call<{ durationMs: number; notes: string[] }>('POST', '/api/phone/feed/stop', { ...body, ...(played !== undefined ? { durationMs: played } : {}) }) + if (done.notes.length) onError(done.notes.join(' ')) + return done.durationMs + }), + } +} + +async function chooseFile(input: HTMLInputElement): Promise { + const picked = input.files?.[0] + input.value = '' + if (!picked) return + note = `Sending ${picked.name} to FormRec...` + changed() + try { + const got = await call('POST', `/api/phone/files?name=${encodeURIComponent(picked.name)}`, picked) + if (file) void call('DELETE', `/api/phone/files/${file.id}`).catch(() => undefined) + file = { id: got.id, name: picked.name, ...(got.durationMs !== undefined ? { durationMs: got.durationMs } : {}) } + chosen = 'file' + note = '' + } catch (error) { + note = (error as Error).message + } + changed() +} + +async function importRecording(input: HTMLInputElement): Promise { + const picked = input.files?.[0] + input.value = '' + if (!picked) return + try { + const rec = await uploadVideo(picked, (f) => { note = `Importing ${picked.name}: ${Math.round(f * 100)}%`; changed() }) + note = '' + location.hash = `#/f/${encodeURIComponent(rec.id)}` + } catch (error) { + note = `The import did not work: ${(error as Error).message}` + } + changed() +} + +/** The studio's Phone panel. */ +export function phonePanel(signal?: AbortSignal): HTMLElement { + const list = h('div', { class: 'phone-cap-list', role: 'radiogroup', 'aria-label': 'Phone to record', 'data-phone-cap-list': '' }) + const none = h('button', { type: 'button', role: 'radio', class: 'phone-cap-row', 'data-phone-cap-source': '', 'aria-checked': 'true' }, + h('strong', {}, 'This computer\'s screen'), h('span', {}, 'No phone: the studio records the screen as usual')) + none.addEventListener('click', () => { chosen = undefined; changed() }) + const rows = new Map() + const tapsInput = h('input', { 'data-phone-cap-taps': '', 'aria-label': 'Show taps' }) as HTMLInputElement + tapsInput.checked = showTaps + tapsInput.addEventListener('change', () => { showTaps = tapsInput.checked; changed() }) + const demoInput = h('input', { 'data-phone-cap-demo': '', 'aria-label': 'Clean status bar' }) as HTMLInputElement + demoInput.addEventListener('change', () => { demoMode = demoInput.checked; changed() }) + const androidOptions = h('div', { class: 'phone-cap-options', 'data-phone-cap-android': '' }, + h('label', { class: 'phone-cap-switch' }, toggle(tapsInput), h('span', {}, 'Show taps during the take')), + h('label', { class: 'phone-cap-switch' }, toggle(demoInput), h('span', {}, 'Clean status bar (9:41, full battery and signal)'))) + const fileInput = h('input', { type: 'file', accept: 'video/*,.mov,.mp4,.webm', class: 'phone-cap-hidden', 'data-phone-cap-file': '' }) as HTMLInputElement + fileInput.addEventListener('change', () => void chooseFile(fileInput)) + const importInput = h('input', { type: 'file', accept: 'video/*,.mov,.mp4,.webm', class: 'phone-cap-hidden', 'data-phone-cap-import-file': '' }) as HTMLInputElement + importInput.addEventListener('change', () => void importRecording(importInput)) + const fileName = h('span', { class: 'phone-cap-file-name', 'data-phone-cap-file-name': '' }) + const fileRow = h('div', { class: 'phone-cap-file', 'data-phone-cap-file-row': '' }, + h('button', { type: 'button', class: 'btn btn-ghost', 'data-phone-cap-pick': '', onclick: () => fileInput.click() }, icon('film', 14), 'Choose the video'), fileName) + const touches = h('p', { class: 'phone-cap-touch', 'data-phone-cap-touch': '' }) + const status = h('p', { class: 'phone-cap-status', 'data-phone-cap-status': '', 'aria-live': 'polite' }) + const missing = h('ul', { class: 'phone-cap-missing', 'data-phone-cap-missing': '' }) + const refresh = h('button', { type: 'button', class: 'btn btn-ghost', 'data-phone-cap-refresh': '', onclick: () => void loadSources(true) }, icon('refresh', 14), 'Refresh') + const importButton = h('button', { type: 'button', class: 'btn btn-ghost', 'data-phone-cap-import': '', onclick: () => importInput.click() }, icon('film', 14), 'Import a phone recording') + const root = h('section', { class: 'rv-panel phone-cap', 'data-phone-cap': 'loading' }, + h('header', { class: 'rv-panel-head' }, icon('screen', 14), h('span', { class: 'rv-panel-title' }, 'Phone')), + h('div', { class: 'rv-panel-body' }, list, fileRow, androidOptions, touches, status, + h('div', { class: 'phone-cap-actions' }, refresh, importButton), missing, fileInput, importInput, + h('p', { class: 'phone-cap-foot' }, 'The phone is the take\'s picture when the layout records the screen and Capture is Entire screen. Its picture keeps its own size and frame rate; its sound is a track of its own. Phone layouts (portrait, device frame) are made on export.'))) + list.append(none) + const draw = (): void => { + const o = current() + root.dataset['phoneCap'] = server ? (o ? o.kind : 'none') : 'loading' + none.setAttribute('aria-checked', String(!o)) + for (const [key, row] of rows) if (!options.some((x) => x.key === key)) { row.remove(); rows.delete(key) } + for (const opt of options) { + let row = rows.get(opt.key) + if (!row) { + row = h('button', { type: 'button', role: 'radio', class: 'phone-cap-row', 'data-phone-cap-source': opt.key }, + h('strong', {}), h('span', {})) as HTMLButtonElement + const key = opt.key + row.addEventListener('click', () => { + const pick = options.find((x) => x.key === key) + if (!pick || pick.blocked) return + chosen = key + if (pick.kind === 'file' && !file) fileInput.click() + changed() + }) + rows.set(opt.key, row) + list.append(row) + } + const [strong, span] = [row.children[0]!, row.children[1]!] + if (strong.textContent !== opt.label) strong.textContent = opt.label + const detail = opt.blocked || opt.detail + if (span.textContent !== detail) span.textContent = detail + row.setAttribute('aria-checked', String(opt.key === chosen)) + row.dataset['blocked'] = String(Boolean(opt.blocked)) + } + fileRow.dataset['shown'] = String(o?.kind === 'file') + const fileText = file ? `${file.name}${file.durationMs ? ` (${clockText(file.durationMs)})` : ''}` : 'No video chosen yet' + if (fileName.textContent !== fileText) fileName.textContent = fileText + androidOptions.dataset['shown'] = String(o?.kind === 'android') + tapsInput.checked = showTaps + demoInput.checked = demoMode + const t = touchNote(o, showTaps) + if (touches.textContent !== t) touches.textContent = t + if (status.textContent !== note) status.textContent = note + const lines = missingNotes(server, shell) + if (missing.dataset['lines'] !== lines.join('|')) { + missing.dataset['lines'] = lines.join('|') + missing.replaceChildren(...lines.map((l) => h('li', {}, l))) + } + } + let attached = false + const redraw = (): void => { + if (root.isConnected) attached = true + else if (attached) return void listeners.delete(redraw) + draw() + } + listeners.add(redraw) + draw() + void loadSources() + // A phone plugged in or out (or permission given, which shows the names markSeen compares) lists the sources again. + if (signal) { + const media = navigator.mediaDevices + const again = debounce(() => void loadSources(true), DEBOUNCE_MS) + media?.addEventListener('devicechange', again, { signal }) + signal.addEventListener('abort', () => again.cancel()) + } + return root +} + +/** Over the stage: what the phone source records (the phone recording itself plays here). */ +function phoneStage(): HTMLElement { + const video = h('video', { class: 'phone-cap-stage-video', playsinline: true, preload: 'auto', 'data-phone-cap-video': '' }) as HTMLVideoElement + video.muted = true + stageVideo = video + const title = h('strong', { 'data-phone-cap-stage-title': '' }) + const text = h('span', { 'data-phone-cap-stage-text': '' }) + const card = h('div', { class: 'phone-cap-stage-card rv-stage-empty' }, icon('screen', 40), title, text) + const root = h('div', { class: 'phone-cap-stage', 'data-phone-cap-stage': 'off' }, video, card) + let src = '' + const draw = (): void => { + const o = phoneWanted() ? current() : undefined + root.dataset['phoneCapStage'] = !o ? 'off' : o.kind === 'file' ? 'file' : 'device' + const wanted = o?.kind === 'file' && file ? `/api/phone/files/${file.id}?token=${encodeURIComponent(token())}` : '' + if (wanted !== src) { + src = wanted + if (wanted) video.src = wanted + else video.removeAttribute('src') + } + const t = o ? `Recording ${o.label}` : '' + if (title.textContent !== t) title.textContent = t + const d = !o ? '' : o.kind === 'ios-usb' ? 'The FormRec app records the phone over USB at its own size; keep it unlocked. QuickTime must not be recording it at the same time.' + : o.kind === 'android' ? 'Recorded over adb at the phone\'s own size and frame rate; keep the screen on.' + : o.kind === 'simulator' ? 'Recorded by the Simulator itself.' : 'The mirror window is recorded; keep it where it is during the take.' + if (text.textContent !== d) text.textContent = d + } + listeners.add(draw) + draw() + return root +} + +studioPlugins.add({ + id: 'phone-capture', + // Before the desktop feature's display panel, so a chosen phone wins over the native display feed. + order: 880, + panel: (ctx) => phonePanel(ctx.signal), + stage: () => phoneStage(), + nativeScreen: () => phoneWanted(), + nativeRecorder: (_ctx, sessionId) => phoneRecorder(sessionId, (message) => { note = message; changed() }), +}) + +/** Phone layouts on export: a recording whose picture is a phone. */ +const LAYOUT_LABELS: [string, string][] = [ + ['portrait-blur', 'Portrait, blurred fill'], + ['portrait-frame', 'Portrait, device frame'], + ['landscape-frame', 'Landscape, device frame'], + ['beside-camera', 'Beside the presenter camera'], +] + +function layoutDialog(id: string): void { + const say = h('p', { class: 'phone-cap-status', 'aria-live': 'polite', 'data-phone-export-status': '' }) + const dialog = h('dialog', { class: 'rv phone-cap-dialog', 'data-phone-export': '' }) as HTMLDialogElement + const buttons = LAYOUT_LABELS.map(([layout, label]) => { + const b = h('button', { type: 'button', class: 'btn', 'data-phone-export-layout': layout }, label) as HTMLButtonElement + b.addEventListener('click', async () => { + buttons.forEach((x) => { x.disabled = true }) + say.textContent = 'Making it with FFmpeg...' + try { + const made = await call<{ url: string }>('POST', `/api/phone/recordings/${encodeURIComponent(id)}/export`, { layout }) + const a = h('a', { href: `${made.url}?token=${encodeURIComponent(token())}`, download: `phone-${layout}.mp4` }) as HTMLAnchorElement + a.click() + say.textContent = 'Done: the file is in Downloads.' + } catch (error) { + say.textContent = (error as Error).message + } + buttons.forEach((x) => { x.disabled = false }) + }) + return b + }) + dialog.append(h('h3', {}, 'Phone layout'), h('p', {}, 'A copy for sharing; the recording keeps the phone at its own size.'), + h('div', { class: 'phone-cap-layouts' }, ...buttons), say, + h('button', { type: 'button', class: 'btn btn-ghost', 'data-phone-export-close': '', onclick: () => dialog.close() }, 'Close')) + dialog.addEventListener('close', () => dialog.remove()) + document.body.append(dialog) + dialog.showModal() +} + +recordingActions.add({ + id: 'phone-layout', + label: 'Phone layout', + order: 64, + when: (rec) => (rec.tracks ?? []).some((t) => t.kind === 'screen' && t.person === 'Phone'), + run: (rec) => layoutDialog(rec.id), +}) diff --git a/web/src/features/studio.ts b/web/src/features/studio.ts index 0a7a435..35ea1f7 100644 --- a/web/src/features/studio.ts +++ b/web/src/features/studio.ts @@ -16,6 +16,8 @@ import { runStudio } from '../studio-control.js' import { loadSettings, saveSettings, TWO_HOURS } from '../studio-settings.js' import { sicon } from '../studio-icons.js' import { studioView } from '../studio.js' +// The player's Export with sound and Capture panel register themselves. +import '../capture-player.js' for (const s of SHORTCUTS) { commands.add({ diff --git a/web/src/level-engine.ts b/web/src/level-engine.ts new file mode 100644 index 0000000..fee1294 --- /dev/null +++ b/web/src/level-engine.ts @@ -0,0 +1,77 @@ +/** + * One microphone's samples for everything that reads them: the meters, the clip count, the hints, the level check and + * the WAV master. An AudioContext at the master's rate (48 kHz when the browser allows it) with the capture tap + * worklet; where worklets are missing an AnalyserNode is polled instead, which serves the meters but cannot make a + * master (`lossless` is false then). + */ +import { blockPeak } from './levels.js' + +export type BlockListener = (samples: Float32Array, peak: number) => void + +export interface LevelEngine { + readonly sampleRate: number + /** True when every sample reaches the listeners (the worklet runs), so a lossless master can be written. */ + readonly lossless: boolean + /** The last block's peak, 0 to 1. */ + peak(): number + listen(listener: BlockListener): () => void + stop(): void +} + +const POLL_MS = 50 + +export async function openEngine(stream: MediaStream, sampleRate?: number): Promise { + let ctx: AudioContext + try { + ctx = sampleRate ? new AudioContext({ sampleRate }) : new AudioContext() + } catch { + // This engine refused the rate (WebKit with a microphone at another rate): its own rate, recorded as such. + ctx = new AudioContext() + } + const listeners = new Set() + let last = 0 + const emit = (samples: Float32Array): void => { + last = blockPeak(samples) + for (const l of listeners) { + try { l(samples, last) } catch { /* one reader must not stop the others */ } + } + } + const source = ctx.createMediaStreamSource(stream) + let lossless = false + let poll: ReturnType | undefined + let node: AudioNode | undefined + try { + await ctx.audioWorklet.addModule('/capture-tap-worklet.js') + const tap = new AudioWorkletNode(ctx, 'formrec-capture-tap', { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1] }) + tap.port.onmessage = (e: MessageEvent) => emit(e.data) + source.connect(tap) + // Connected to the output so the graph pulls it; it outputs silence. + tap.connect(ctx.destination) + node = tap + lossless = true + } catch { + const analyser = ctx.createAnalyser() + analyser.fftSize = 2048 + source.connect(analyser) + const buf = new Float32Array(analyser.fftSize) + poll = setInterval(() => { analyser.getFloatTimeDomainData(buf); emit(buf.slice()) }, POLL_MS) + node = analyser + } + await ctx.resume().catch(() => undefined) + return { + sampleRate: ctx.sampleRate, + lossless, + peak: () => last, + listen(listener) { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + stop() { + clearInterval(poll) + listeners.clear() + source.disconnect() + node?.disconnect() + void ctx.close().catch(() => undefined) + }, + } +} diff --git a/web/src/levels.ts b/web/src/levels.ts new file mode 100644 index 0000000..fdf9ae9 --- /dev/null +++ b/web/src/levels.ts @@ -0,0 +1,191 @@ +/** + * The input level's arithmetic, with no browser in it: sample peaks in dBFS, the zone a peak falls in, the peak hold, + * clip counting with take times, the plain-words hints and the pre-roll level check. The meter (meter.ts) and the + * studio read these; tests/levels.test.ts covers them. + * + * The target is speech peaks between -18 and -12 dBFS: loud enough to sit well above the room, with 12 dB of room + * before the converter runs out for a laugh or a plosive. + */ + +/** The meter's scale runs from FLOOR_DB to 0 dBFS. */ +export const FLOOR_DB = -60 +/** Below this a block is the room, not a voice. */ +export const SILENCE_DB = -50 +/** Speech peaks below this are too quiet. */ +export const QUIET_DB = -24 +/** The target band for speech peaks. */ +export const BAND_LOW_DB = -18 +export const BAND_HIGH_DB = -12 +/** From here up the meter is red: one more step and the converter clips. */ +export const RED_DB = -3 +/** A sample at or above this is counted as a clip (a full-scale sample, with a little slack for converters that stop at 0.9999). */ +export const CLIP_DB = -0.1 +export const CLIP_LEVEL = 10 ** (CLIP_DB / 20) +/** How long the peak hold mark stays before it falls. */ +export const HOLD_MS = 1500 +/** Clipped samples closer than this belong to one clip (a clap is a burst of full-scale samples). */ +export const CLIP_GAP_MS = 250 +/** Quiet speech for this long brings up the too-quiet hint. */ +export const QUIET_HINT_MS = 3000 +/** This many red-zone hits inside RED_WINDOW_MS bring up the too-loud hint. */ +export const RED_HITS = 3 +export const RED_WINDOW_MS = 10_000 + +export type Zone = 'silent' | 'quiet' | 'low' | 'target' | 'high' | 'red' + +/** A linear peak (0 to 1, or above 1 for a float source) in dBFS; -Infinity for silence. */ +export function dbfs(peak: number): number { + if (!(peak > 0)) return -Infinity + return 20 * Math.log10(peak) +} + +/** The largest absolute sample of a block. */ +export function blockPeak(samples: ArrayLike): number { + let top = 0 + for (let i = 0; i < samples.length; i += 1) { + const s = Math.abs(samples[i]!) + if (s > top) top = s + } + return top +} + +/** Where a peak in dBFS sits on the meter. */ +export function zoneOf(db: number): Zone { + if (db < SILENCE_DB) return 'silent' + if (db < QUIET_DB) return 'quiet' + if (db < BAND_LOW_DB) return 'low' + if (db <= BAND_HIGH_DB) return 'target' + if (db < RED_DB) return 'high' + return 'red' +} + +/** A dBFS value as a fraction of the meter's width (FLOOR_DB at 0, 0 dBFS at 1). */ +export function dbToFraction(db: number): number { + if (!Number.isFinite(db)) return 0 + return Math.max(0, Math.min(1, (db - FLOOR_DB) / -FLOOR_DB)) +} + +/** The numeric readout: one decimal, "-inf" for silence, never wider than "-60.0". */ +export function dbText(db: number): string { + if (!Number.isFinite(db) || db < FLOOR_DB) return '-inf' + return Math.min(0, db).toFixed(1) +} + +/** The peak hold: the highest peak of the last HOLD_MS. A value, so each step returns the next one. */ +export interface Hold { db: number; atMs: number } + +export function holdStep(hold: Hold | undefined, db: number, nowMs: number, holdMs = HOLD_MS): Hold { + if (!hold || db >= hold.db || nowMs - hold.atMs > holdMs) return { db, atMs: nowMs } + return hold +} + +/** One clip: where it began on the take's timeline, and the highest sample in it. */ +export interface Clip { atMs: number; peakDb: number } + +/** The clips of a take so far, and the last moment a clipped sample was seen (to merge bursts). */ +export interface ClipLog { clips: readonly Clip[]; lastMs: number } + +export const EMPTY_CLIPS: ClipLog = { clips: [], lastMs: -Infinity } + +/** Feed a block's peak at a take time: a clipped block starts a new clip unless the last one was under CLIP_GAP_MS ago. */ +export function clipStep(log: ClipLog, peak: number, atMs: number, gapMs = CLIP_GAP_MS): ClipLog { + if (peak < CLIP_LEVEL) return log + const db = dbfs(peak) + const last = log.clips[log.clips.length - 1] + if (last && atMs - log.lastMs < gapMs) { + const merged = { atMs: last.atMs, peakDb: Math.max(last.peakDb, db) } + return { clips: [...log.clips.slice(0, -1), merged], lastMs: atMs } + } + return { clips: [...log.clips, { atMs: Math.max(0, Math.round(atMs)), peakDb: db }], lastMs: atMs } +} + +/** m:ss (or h:mm:ss) for a take time. */ +export function takeClock(ms: number): string { + const s = Math.max(0, Math.floor(ms / 1000)) + const h = Math.floor(s / 3600) + const m = Math.floor((s % 3600) / 60) + const ss = String(s % 60).padStart(2, '0') + return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}` +} + +/** The save screen's line: "No clipping.", or "Clipped 3 times, at 0:19, 0:56, 1:02." (the first `max` times listed). */ +export function clipReport(clips: readonly Clip[], max = 12): string { + if (clips.length === 0) return 'No clipping.' + const times = clips.slice(0, max).map((c) => takeClock(c.atMs)) + const more = clips.length > max ? ` and ${clips.length - max} more` : '' + return `Clipped ${clips.length === 1 ? 'once' : `${clips.length} times`}, at ${times.join(', ')}${more}.` +} + +export type Hint = 'none' | 'quiet' | 'loud' + +/** What the hint follows: when speech has stayed quiet since, and the recent red-zone hits. */ +export interface HintState { quietSince?: number; redHits: readonly number[]; lastRed: number } + +export const EMPTY_HINT: HintState = { redHits: [], lastRed: -Infinity } + +/** + * Feed a block's peak in dBFS at nowMs. Speech peaking in the quiet zone for QUIET_HINT_MS asks to come closer; + * RED_HITS separate red-zone hits within RED_WINDOW_MS ask to back off. Silence (the room between sentences) neither + * starts nor ends the quiet stretch; a block at the band or above ends it. + */ +export function hintStep(state: HintState, db: number, nowMs: number): { state: HintState; hint: Hint } { + const zone = zoneOf(db) + let quietSince = state.quietSince + if (zone === 'quiet') quietSince = quietSince ?? nowMs + else if (zone !== 'silent') quietSince = undefined + let { redHits, lastRed } = state + if (zone === 'red') { + // One hit per burst: a red stretch counts once. + if (nowMs - lastRed > CLIP_GAP_MS) redHits = [...redHits, nowMs] + lastRed = nowMs + } + redHits = redHits.filter((t) => nowMs - t <= RED_WINDOW_MS) + const next: HintState = { quietSince, redHits, lastRed } + if (redHits.length >= RED_HITS) return { state: next, hint: 'loud' } + if (quietSince !== undefined && nowMs - quietSince >= QUIET_HINT_MS) return { state: next, hint: 'quiet' } + return { state: next, hint: 'none' } +} + +export const HINT_TEXT: Record = { + none: 'Aim for speech peaks in the green band, -18 to -12 dBFS.', + quiet: 'You are quiet: move closer or turn the input up.', + loud: 'You keep hitting the red: move back or turn the input down.', +} + +export type Advice = 'up' | 'down' | 'ok' | 'silent' + +export interface LevelCheck { + /** The typical speech peak (the 90th percentile of the speaking blocks), in dBFS. */ + peakDb: number + /** The loudest block. */ + maxDb: number + clips: number + advice: Advice + /** How far to move the input, in whole dB (0 when it is fine). */ + byDb: number +} + +/** + * The pre-roll check over the block peaks of a few seconds of speech: the speaking blocks' 90th percentile stands for + * the speech peaks (the single loudest block is a plosive), compared with the band. A clip always says turn it down. + */ +export function levelCheck(peaks: readonly number[]): LevelCheck { + const dbs = peaks.map(dbfs) + const maxDb = dbs.reduce((m, d) => Math.max(m, d), -Infinity) + // Consecutive clipped blocks are one clip, as during the take. + const clips = peaks.filter((p, i) => p >= CLIP_LEVEL && !((peaks[i - 1] ?? 0) >= CLIP_LEVEL)).length + const speech = dbs.filter((d) => d >= SILENCE_DB).sort((a, b) => a - b) + if (speech.length === 0) return { peakDb: maxDb, maxDb, clips, advice: 'silent', byDb: 0 } + const peakDb = speech[Math.min(speech.length - 1, Math.floor(speech.length * 0.9))]! + if (clips > 0 || peakDb > BAND_HIGH_DB) return { peakDb, maxDb, clips, advice: 'down', byDb: Math.max(1, Math.ceil(peakDb - (BAND_LOW_DB + BAND_HIGH_DB) / 2)) } + if (peakDb < BAND_LOW_DB) return { peakDb, maxDb, clips, advice: 'up', byDb: Math.ceil((BAND_LOW_DB + BAND_HIGH_DB) / 2 - peakDb) } + return { peakDb, maxDb, clips, advice: 'ok', byDb: 0 } +} + +export function adviceText(check: LevelCheck): string { + const at = `your speech peaks at about ${dbText(check.peakDb)} dBFS` + if (check.advice === 'silent') return 'Nothing was heard: check the microphone is the one you speak into.' + if (check.advice === 'up') return `Turn your input up about ${check.byDb} dB: ${at}.` + if (check.advice === 'down') return check.clips > 0 ? `Turn it down: it clipped ${check.clips === 1 ? 'once' : `${check.clips} times`} (${at}).` : `Turn it down about ${check.byDb} dB: ${at}.` + return `Good: ${at}, inside the green band.` +} diff --git a/web/src/marks.ts b/web/src/marks.ts index fc035fd..135e033 100644 --- a/web/src/marks.ts +++ b/web/src/marks.ts @@ -7,8 +7,8 @@ export interface MarksPanel { el: HTMLElement marks(): MarkInput[] mark(): void - /** Add a titled mark without touching the fields (a slide change, R1-57); atMs defaults to now. No effect when not recording. */ - add(title: string, atMs?: number): void + /** Add a titled mark without touching the fields (a slide change, R1-57, a script's paragraph); atMs defaults to now. No effect when not recording. */ + add(title: string, atMs?: number, say?: string): void /** Keep only the marks before atMs (Live Rewind trimmed the rest), or none (a restarted take). */ keepBefore(atMs: number): void } @@ -43,10 +43,10 @@ export function marksPanel(now: () => number | undefined, signal: AbortSignal): }) for (const input of [title, say, route, code]) input.value = '' } - const add = (name: string, atMs?: number): void => { + const add = (name: string, atMs?: number, words = ''): void => { const at = now() if (at === undefined) return - push({ title: name, say: '', atMs: Math.round(atMs ?? at), code: [] }) + push({ title: name.slice(0, 120), say: words.slice(0, 2000), atMs: Math.round(atMs ?? at), code: [] }) } document.addEventListener('keydown', (e) => { const typing = e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLSelectElement diff --git a/web/src/meetings-settings.ts b/web/src/meetings-settings.ts index 82c102d..a925c48 100644 --- a/web/src/meetings-settings.ts +++ b/web/src/meetings-settings.ts @@ -128,7 +128,8 @@ export function meetingsSettings(): HTMLElement { on('data-mt-set-recap', (c) => meetings.settings({ recap: { make: c } })) on('data-mt-set-email', (c) => meetings.settings({ recap: { email: c } })) on('data-mt-policy', async (c) => { await policyCall({ method: 'PATCH', body: JSON.stringify({ notetaker: c }) }); setAllowNotetaker(c) }) - void refresh() + // A refused read (a page opened by a player link has no run token) leaves the section as drawn. + void refresh().catch(() => undefined) }) return view } diff --git a/web/src/meter.ts b/web/src/meter.ts index 7de87ea..bada7eb 100644 --- a/web/src/meter.ts +++ b/web/src/meter.ts @@ -1,13 +1,14 @@ /** - * A microphone level meter: one AnalyserNode read once per frame, drawn as a - * fixed-size bar scaled with a transform, so it never moves the layout. + * The input level meter, in dBFS: a large one for the studio and a compact one for the record bar. Both are built at + * their final size and changed only through transforms, attributes and text, so they never move the layout. The scale + * runs from -60 to 0 dBFS with the too-quiet zone, the green target band (-18 to -12) and the red zone marked; a hold + * mark shows the highest peak of the last 1.5 s with its number, and the clip light stays red until it is clicked. + * The numbers come from levels.ts; what feeds them is studio-sound.ts. `peak` and `toBar` are the older bar's maths, + * still used by the Effects panel's preview. */ import { h } from './dom.js' - -export interface Meter { - el: HTMLElement - stop(): void -} +import { icon } from './view-kit.js' +import { BAND_HIGH_DB, BAND_LOW_DB, dbText, dbToFraction, FLOOR_DB, HINT_TEXT, QUIET_DB, RED_DB, zoneOf, type Hint } from './levels.js' /** Peak level of a block of time-domain samples, 0 to 1. */ export function peak(samples: Float32Array): number { @@ -23,37 +24,99 @@ export function toBar(level: number): number { return Math.max(0, Math.min(1, (db + 60) / 60)) } -export function levelMeter(stream: MediaStream | undefined, label: string): Meter { - const fill = h('span', { class: 'rv-meter-fill' }) - const el = h('div', { class: 'rv-meter', 'data-meter': '', role: 'meter', 'aria-label': label, 'aria-valuemin': '0', 'aria-valuemax': '1' }, - h('span', { class: 'rv-meter-track' }, fill)) - if (!stream || stream.getAudioTracks().length === 0) return { el, stop: () => undefined } - let ctx: AudioContext | undefined - let frame = 0 - try { - ctx = new AudioContext() - const analyser = ctx.createAnalyser() - analyser.fftSize = 1024 - ctx.createMediaStreamSource(stream).connect(analyser) - const buf = new Float32Array(analyser.fftSize) - let shown = 0 - const draw = (): void => { - analyser.getFloatTimeDomainData(buf) - // Rise at once, fall gently: easier to read than the raw peak. - shown = Math.max(toBar(peak(buf)), shown * 0.9) - fill.style.transform = `scaleX(${shown.toFixed(3)})` - frame = requestAnimationFrame(draw) +export interface MeterReading { + db: number + holdDb: number + clips: number + /** The clip light is lit (a clip happened since it was last clicked). */ + lit: boolean + hint: Hint +} + +export interface DbMeter { + el: HTMLElement + show(reading: MeterReading): void + /** Waiting for a microphone: the bar empties and says so. */ + idle(text: string): void + /** Hold a line in the hint's place (the take's clip report) until undefined clears it; the meter keeps moving. */ + pin(text: string | undefined): void + onClipClick(listener: () => void): void +} + +const TICKS = [-48, -36, -24, -18, -12, -6, -3, 0] + +/** The zone edges as custom properties, so the track's painted zones and the numbers agree. */ +function zoneVars(el: HTMLElement): void { + el.style.setProperty('--lv-quiet', String(dbToFraction(QUIET_DB))) + el.style.setProperty('--lv-band-lo', String(dbToFraction(BAND_LOW_DB))) + el.style.setProperty('--lv-band-hi', String(dbToFraction(BAND_HIGH_DB))) + el.style.setProperty('--lv-red', String(dbToFraction(RED_DB))) +} + +export function dbMeter(size: 'large' | 'compact', label: string): DbMeter { + const fill = h('span', { class: 'rv-lv-fill' }) + const hold = h('span', { class: 'rv-lv-hold', 'aria-hidden': 'true' }, h('span', { class: 'rv-lv-hold-mark' })) + const bar = h('span', { + class: 'rv-lv-bar', role: 'meter', 'aria-label': label, 'aria-valuemin': String(FLOOR_DB), 'aria-valuemax': '0', 'aria-valuenow': String(FLOOR_DB), 'data-levels-bar': '', + }, h('span', { class: 'rv-lv-zones', 'aria-hidden': 'true' }), fill, hold) + const read = h('span', { class: 'rv-lv-read', 'data-levels-peak': '' }, '-inf') + const count = h('span', { class: 'rv-lv-count', 'data-levels-clips': '' }, '0') + const clip = h('button', { type: 'button', class: 'rv-lv-clip', 'aria-pressed': 'false', title: 'Clip light: click to clear', 'data-levels-clip': '' }, + h('span', { class: 'rv-lv-led', 'aria-hidden': 'true' }), count, size === 'large' ? h('span', { class: 'rv-lv-unit' }, 'clips') : null) as HTMLButtonElement + const hint = h('p', { class: 'rv-lv-hint', 'aria-live': 'polite', 'data-levels-hint': '' }, 'Get ready to see your microphone level.') + let el: HTMLElement + if (size === 'large') { + const scale = h('span', { class: 'rv-lv-scale', 'aria-hidden': 'true' }, ...TICKS.map((db) => { + const tick = h('span', { class: 'rv-lv-tick', 'data-db': String(db) }, String(db)) + tick.style.setProperty('--at', String(dbToFraction(db))) + return tick + })) + el = h('div', { class: 'rv-lv is-large', 'data-levels': 'large', 'data-zone': 'silent', 'data-lit': 'false', 'data-hint': 'idle' }, + h('div', { class: 'rv-lv-head' }, + h('span', { class: 'rv-lv-title' }, icon('mic', 14), 'Input level'), + h('span', { class: 'rv-lv-readout' }, read, h('span', { class: 'rv-lv-unit' }, 'dBFS peak')), + clip), + bar, scale, hint) + } else { + el = h('span', { class: 'rv-lv is-compact', 'data-levels': 'compact', 'data-zone': 'silent', 'data-lit': 'false', 'data-hint': 'idle' }, icon('mic', 12), bar, read, clip) + } + zoneVars(el) + let shown = { fill: '', hold: '', read: '', zone: '', clips: -1, lit: '', hint: '' } + let pinned: string | undefined + const show = (r: MeterReading): void => { + const f = dbToFraction(r.db).toFixed(3) + if (f !== shown.fill) fill.style.transform = `scaleX(${f})` + const hf = dbToFraction(r.holdDb).toFixed(3) + if (hf !== shown.hold) hold.style.transform = `translateX(${(Number(hf) * 100 - 100).toFixed(1)}%)` + const text = dbText(r.holdDb) + if (text !== shown.read) { + read.textContent = text + bar.setAttribute('aria-valuenow', Number.isFinite(r.holdDb) ? String(Math.max(FLOOR_DB, Math.round(r.holdDb))) : String(FLOOR_DB)) + bar.setAttribute('aria-valuetext', `${text} dBFS`) } - frame = requestAnimationFrame(draw) - } catch { - // No audio graph in this browser: the meter stays empty. + const zone = zoneOf(r.db) + if (zone !== shown.zone) el.dataset['zone'] = zone + if (r.clips !== shown.clips) count.textContent = String(r.clips) + const lit = String(r.lit) + if (lit !== shown.lit) { el.dataset['lit'] = lit; clip.setAttribute('aria-pressed', lit) } + if (r.hint !== shown.hint && pinned === undefined) { el.dataset['hint'] = r.hint; hint.textContent = HINT_TEXT[r.hint] } + shown = { fill: f, hold: hf, read: text, zone, clips: r.clips, lit, hint: r.hint } } return { el, - stop: () => { - cancelAnimationFrame(frame) - void ctx?.close().catch(() => undefined) - ctx = undefined + show, + idle(text) { + show({ db: -Infinity, holdDb: -Infinity, clips: 0, lit: false, hint: 'none' }) + el.dataset['hint'] = 'idle' + hint.textContent = text + shown = { ...shown, hint: 'idle' } + }, + pin(text) { + pinned = text + if (text === undefined) { shown = { ...shown, hint: '' }; return } + el.dataset['hint'] = 'report' + hint.textContent = text }, + onClipClick(listener) { clip.addEventListener('click', listener) }, } } diff --git a/web/src/phone-capture-logic.ts b/web/src/phone-capture-logic.ts new file mode 100644 index 0000000..094525f --- /dev/null +++ b/web/src/phone-capture-logic.ts @@ -0,0 +1,103 @@ +/** + * The studio's Phone panel as data (issue #7): what the server (GET /api/phone/sources) and the desktop app's shell + * (phone_ios_devices) found, turned into the list of sources the panel offers, with a note for each that cannot be + * used yet and what to do about it. No DOM: tests/phone-capture-client.test.ts runs it in Node. + */ + +export interface AndroidDevice { serial: string; state: string; link: 'usb' | 'wifi' | 'emulator'; name: string } +export interface Simulator { udid: string; name: string; runtime: string } +export interface AirPlayWindow { id: number; owner: string; width: number; height: number } +export interface ServerSources { + platform: string + adb: { found: boolean; howTo: string } + ffmpeg: boolean + scrcpy: string + android: AndroidDevice[] + simulators: Simulator[] + airplay: AirPlayWindow[] +} +/** An iPhone or iPad the shell sees as a capture device (macOS, the desktop app). */ +export interface IosDevice { + id: string + name: string + model: string + /** The window's own camera list (getUserMedia) shows it too: the web view sees the device after the shell's opt-in. */ + seenByWindow?: boolean +} +export interface ShellView { desktop: boolean; mac: boolean; devices: IosDevice[]; error?: string } + +export type SourceKey = string +export interface SourceOption { + key: SourceKey + kind: 'ios-usb' | 'android' | 'simulator' | 'airplay' | 'file' + label: string + detail: string + /** Empty when it can be recorded now; else why not and what to do. */ + blocked: string + /** What the server's feed/start takes (the file source's id is added when a file is chosen). */ + source: Record + /** Touches show in the picture (Android with show taps); iOS mirrors never show them. */ + touches: 'shown' | 'never' | 'optional' +} + +export const IOS_TOUCH_NOTE = 'iPhone and iPad mirrors never show touches: point at what you tap with words, or tap slowly.' + +const androidState = (state: string): string => + state === 'unauthorized' ? 'Unlock the phone and accept "Allow USB debugging" for this computer, then click Refresh.' + : state === 'offline' ? 'adb sees the phone but it is offline: unplug and plug it in again, or restart adb.' + : state === 'no permissions' ? 'This computer may not open the phone: on Linux add a udev rule for it (see the adb documentation).' + : state === 'device' ? '' : `adb says the phone is "${state}".` + +/** The sources in the order the panel lists them. */ +export function sourceOptions(server: ServerSources | undefined, shell: ShellView): SourceOption[] { + const out: SourceOption[] = [] + for (const d of shell.devices) { + out.push({ key: `ios:${d.id}`, kind: 'ios-usb', label: `Phone (${d.name})`, detail: `${d.model || 'iPhone or iPad'} on USB, screen and sound${d.seenByWindow ? ' (the window lists it as a camera too)' : ''}`, blocked: '', source: { kind: 'ios-usb', name: d.name }, touches: 'never' }) + } + for (const d of server?.android ?? []) { + const link = d.link === 'emulator' ? 'Android emulator' : d.link === 'wifi' ? 'Android over Wi-Fi' : 'Android on USB' + const blocked = androidState(d.state) || (server?.ffmpeg ? '' : 'Recording an Android phone needs FFmpeg: install it (brew install ffmpeg on a Mac), then click Refresh.') + out.push({ key: `android:${d.serial}`, kind: 'android', label: `Phone (${d.name})`, detail: `${link}, screen and sound on Android 11 and later`, blocked, source: { kind: 'android', serial: d.serial }, touches: 'optional' }) + } + for (const s of server?.simulators ?? []) { + out.push({ key: `sim:${s.udid}`, kind: 'simulator', label: `Simulator (${s.name})`, detail: `${s.runtime}, picture only`, blocked: '', source: { kind: 'simulator', udid: s.udid }, touches: 'never' }) + } + for (const w of server?.airplay ?? []) { + out.push({ key: `airplay:${w.id}`, kind: 'airplay', label: 'AirPlay mirror', detail: `The mirror window, ${w.width} x ${w.height} px`, blocked: server?.ffmpeg ? '' : 'Recording the mirror window needs FFmpeg: install it, then click Refresh.', source: { kind: 'airplay', window: w.id }, touches: 'never' }) + } + out.push({ key: 'file', kind: 'file', label: 'A phone recording', detail: 'A video made on the phone, played here while you narrate', blocked: '', source: { kind: 'file' }, touches: 'shown' }) + return out +} + +/** The panel's notes about what is not there, one line each. */ +export function missingNotes(server: ServerSources | undefined, shell: ShellView): string[] { + const notes: string[] = [] + if (!shell.mac) notes.push('An iPhone or iPad over USB needs a Mac (the FormRec app on macOS). Use AirPlay to a Mac, or import a recording made on the phone.') + else if (!shell.desktop) notes.push('An iPhone or iPad over USB is recorded by the FormRec app: open it, plug the phone in, unlock it and tap Trust.') + else if (shell.error) notes.push(`iPhone over USB: ${shell.error}`) + else if (!shell.devices.length) notes.push('No iPhone or iPad on USB: plug it in, unlock it, tap Trust, wait a few seconds, then click Refresh.') + if (server && !server.adb.found) notes.push(`Android: ${server.adb.howTo}`) + else if (server && server.android.length === 0) notes.push('No Android phone: turn on USB debugging (Settings, About phone, tap Build number seven times, then Developer options, USB debugging), plug it in and accept the prompt. Over Wi-Fi: adb pair, then adb connect.') + if (server?.platform === 'darwin' && server.airplay.length === 0) notes.push('AirPlay: on the iPhone open Control Center, Screen Mirroring, and pick this Mac (System Settings, General, AirDrop and Handoff, AirPlay Receiver must be on).') + return notes +} + +/** The note on touches for a chosen source. */ +export function touchNote(option: SourceOption | undefined, showTaps: boolean): string { + if (!option) return '' + if (option.kind === 'simulator') return 'The Simulator does not draw touches: say what you tap.' + if (option.touches === 'never') return IOS_TOUCH_NOTE + if (option.touches === 'optional') return showTaps ? 'Show taps is turned on for the take and put back afterwards.' : 'Touches are not shown.' + return '' +} + +/** Keeps the chosen source when it is still offered after a refresh. */ +export function stillOffered(options: SourceOption[], key: SourceKey | undefined): SourceKey | undefined { + return key && options.some((o) => o.key === key && !o.blocked) ? key : undefined +} + +/** mm:ss of a length in ms. */ +export function clockText(ms: number): string { + const s = Math.max(0, Math.round(ms / 1000)) + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}` +} diff --git a/web/src/phone-send.ts b/web/src/phone-send.ts new file mode 100644 index 0000000..aa48a88 --- /dev/null +++ b/web/src/phone-send.ts @@ -0,0 +1,48 @@ +/** + * "Send a video from this phone" on the phone page (issue #7): a screen recording already on the phone (iOS Control + * Center, Android's recorder, the Photos or Files app) is sent to the computer over the same network and becomes a + * recording in its library. It goes through the native apps' upload (src/features/phone/native.ts, + * /phone/api/native/uploads) with the paired device's cookie, in order, a chunk at a time, so it needs no new route, + * port or permission: an MP4 or MOV file (it must start with an ftyp box, as both do). No DOM. + */ + +export const SEND_CHUNK = 8 * 1024 * 1024 +const API = '/phone/api/native/uploads' + +export type Poster = (path: string, body: Blob | string | undefined, json: boolean) => Promise<{ status: number; body: Record }> + +const post: Poster = async (path, body, json) => { + const res = await fetch(path, { + method: 'POST', + credentials: 'same-origin', + ...(json ? { headers: { 'Content-Type': 'application/json' } } : {}), + ...(body === undefined ? {} : { body }), + }) + return { status: res.status, body: (await res.json().catch(() => ({}))) as Record } +} + +/** The title a sent video gets: its file name without the extension. */ +export function titleOf(name: string): string { + return (name.replace(/\.[A-Za-z0-9]{1,5}$/, '').trim() || 'Phone recording').slice(0, 200) +} + +/** Send the file; resolves with the new recording's title, or rejects with the computer's reason. */ +export async function sendVideo(file: Blob & { name?: string }, onProgress: (fraction: number) => void, send: Poster = post): Promise<{ id: string; title: string }> { + const title = titleOf(file.name ?? '') + const made = await send(API, JSON.stringify({ mode: 'screen', source: 'other', title }), true) + if (made.status !== 201 && made.status !== 200) throw new Error(String(made.body['error'] ?? `the computer refused (${made.status})`)) + const id = String(made.body['id']) + for (let seq = 0, at = 0; at < file.size; seq += 1, at += SEND_CHUNK) { + let reply = await send(`${API}/${id}/chunks?seq=${seq}`, file.slice(at, at + SEND_CHUNK), false).catch(() => undefined) + // One retry after a dropped connection; a refusal (wrong format, too large) ends the upload. + if (!reply || reply.status >= 500) reply = await send(`${API}/${id}/chunks?seq=${seq}`, file.slice(at, at + SEND_CHUNK), false) + if (reply.status !== 200) { + await send(`${API}/${id}/discard`, undefined, false).catch(() => undefined) + throw new Error(String(reply.body['error'] ?? `the computer refused part ${seq + 1} (${reply.status})`)) + } + onProgress(Math.min(1, (at + SEND_CHUNK) / file.size)) + } + const done = await send(`${API}/${id}/complete`, JSON.stringify({ title }), true) + if (done.status !== 200) throw new Error(String(done.body['error'] ?? `the computer could not make the recording (${done.status})`)) + return { id: String(done.body['id']), title: String(done.body['title'] ?? title) } +} diff --git a/web/src/phone-sw.ts b/web/src/phone-sw.ts index 6e3a82a..49799d9 100644 --- a/web/src/phone-sw.ts +++ b/web/src/phone-sw.ts @@ -16,10 +16,10 @@ interface Scope { } const sw = self as unknown as Scope -export const CACHE = 'formrec-phone-shell-1' +export const CACHE = 'formrec-phone-shell-2' export const SYNC_TAG = 'formrec-phone-replay' export const SHELL = [ - '/phone/', '/phone/phone.js', '/phone/phone-upload.js', '/phone/phone-queue.js', '/phone/phone-install.js', '/phone/dom.js', + '/phone/', '/phone/phone.js', '/phone/phone-upload.js', '/phone/phone-queue.js', '/phone/phone-install.js', '/phone/phone-send.js', '/phone/dom.js', '/phone/manifest.webmanifest', '/phone/icon-192.png', '/phone/icon-512.png', '/phone/apple-touch-icon.png', '/app.css', '/views.css', '/styles/phone.css', ] diff --git a/web/src/phone.ts b/web/src/phone.ts index 18f09be..b324421 100644 --- a/web/src/phone.ts +++ b/web/src/phone.ts @@ -18,6 +18,7 @@ import { h } from './dom.js' import { codeFromHash, phoneAbilities, ResumableUpload, timer, type ChunkTransport, type SendResult, type UploadProgress } from './phone-upload.js' import { PhoneQueue, queueSink, replayPending } from './phone-queue.js' import { featureFlags, installGuide } from './phone-install.js' +import { sendVideo } from './phone-send.js' type Mode = 'camera' | 'audio' | 'screen' type Kind = 'camera' | 'screen' | 'mic' @@ -159,6 +160,10 @@ const flipButton = h('button', { type: 'button', class: 'rv-phone-round', 'data- const recordButton = h('button', { type: 'button', class: 'rv-phone-rec', 'data-phone-action': 'record', 'aria-label': 'Record' }, h('span', { class: 'rv-phone-rec-core' })) as HTMLButtonElement const pauseButton = h('button', { type: 'button', class: 'rv-phone-round', 'data-phone-action': 'pause', 'aria-label': 'Pause', disabled: true }, glyph('pause'), glyph('play')) as HTMLButtonElement const uploadLine = h('p', { class: 'rv-phone-line', 'data-phone-upload': '', 'data-state': 'idle', 'aria-live': 'polite' }, 'Pick what to record, then tap the red button.') +// A screen recording already on this phone, sent to the computer's library (phone-send.ts). +const sendInput = h('input', { type: 'file', accept: 'video/mp4,video/quicktime,.mp4,.mov', hidden: true, 'data-phone-send-file': '' }) as HTMLInputElement +const sendButton = h('button', { type: 'button', class: 'rv-phone-ghost', 'data-phone-send': '' }, 'Send a video from this phone') as HTMLButtonElement +const sendLine = h('p', { class: 'rv-phone-line', 'data-phone-send-note': '', 'data-state': 'idle', 'aria-live': 'polite' }, 'A screen recording you already made (MP4 or MOV) becomes a recording on the computer.') // Saving const titleInput = h('input', { placeholder: 'What this recording is', maxlength: '200', 'data-phone-title': '' }) as HTMLInputElement @@ -191,6 +196,9 @@ root.append( modeNote, h('div', { class: 'rv-phone-controls', 'data-phone-controls': '' }, flipButton, recordButton, pauseButton), uploadLine, + sendButton, + sendInput, + sendLine, installBlock(), ), h('section', { class: 'rv-panel rv-phone-card', 'data-phone-section': 'save' }, @@ -691,6 +699,18 @@ pairButton.addEventListener('click', () => void pair()) saveButton.addEventListener('click', () => void save()) discardButton.addEventListener('click', () => void discard()) againButton.addEventListener('click', ready) +sendButton.addEventListener('click', () => { if (!live) sendInput.click() }) +sendInput.addEventListener('change', () => { + const picked = sendInput.files?.[0] + sendInput.value = '' + if (!picked) return + sendButton.disabled = true + sendLine.dataset['state'] = 'idle' + void sendVideo(picked, (f) => setText(sendLine, `Sending ${picked.name}: ${Math.round(f * 100)}%`)).then( + (rec) => { sendLine.dataset['state'] = 'sent'; setText(sendLine, `Saved in the library on your computer: ${rec.title}`) }, + (error: Error) => { sendLine.dataset['state'] = 'failed'; setText(sendLine, error.message) }, + ).finally(() => { sendButton.disabled = false }) +}) window.addEventListener('online', () => { live?.sources.forEach((s) => s.upload.wake()) if (root.dataset['phoneOffline'] === 'on') void load() diff --git a/web/src/player-controls.ts b/web/src/player-controls.ts index 31ac313..39a2668 100644 --- a/web/src/player-controls.ts +++ b/web/src/player-controls.ts @@ -52,6 +52,11 @@ export interface ControlsOptions { * and volume, picture in picture and full screen stay. */ live?: boolean + /** + * Play or pause the way the page means it, used by the play button, the picture and the keys. The share page passes + * one that knows a source swap is under way, when the element reads paused although the person's choice is to play. + */ + toggle?: () => void } export interface Controls { @@ -161,7 +166,7 @@ export function controlBar(o: ControlsOptions): Controls { const surface = h('div', { class: 'rv-pc-surface', 'data-pc-surface': '', 'aria-hidden': 'true' }) // ---- actions ---- - const toggle = (): void => { if (lead.paused || lead.ended) void startPlay(lead); else lead.pause() } + const toggle = o.toggle ?? ((): void => { if (lead.paused || lead.ended) void startPlay(lead); else lead.pause() }) const placeAt = (ms: number): void => timeline.place(Math.max(0, Math.min(totalMs(), ms))) const by = (s: number): void => placeAt(timeline.ms + s * 1000) const setMuted = (m: boolean): void => { for (const el of timeline.elements) el.muted = m } diff --git a/web/src/player-link.ts b/web/src/player-link.ts new file mode 100644 index 0000000..ca26393 --- /dev/null +++ b/web/src/player-link.ts @@ -0,0 +1,54 @@ +/** + * A player link (`/?player=#/f/`, what agents hand out): the key opens that one recording's player through + * /api/player/ and nothing else (src/server/player-link.ts). On load the key is moved out of the address into this + * tab's storage, as the run's token is, and the player reads the recording and its media with it. + */ +import type { Recording } from './api.js' + +const STORE = 'formrec.player-links' +const RECORDING = /^#\/f\/([a-z0-9][a-z0-9-]{0,80})$/ +/** Keys kept here when the tab's storage refuses them. */ +const memory = new Map() + +function saved(): Record { + try { + const value = JSON.parse(sessionStorage.getItem(STORE) ?? '{}') as unknown + return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {} + } catch { + return {} + } +} + +/** Keep the key a player link carries for this tab, and take it out of the address bar. */ +export function takePlayerKey(): void { + const params = new URLSearchParams(location.search) + const key = params.get('player') + if (!key) return + const id = RECORDING.exec(location.hash)?.[1] + if (id && /^[A-Za-z0-9_-]{16,128}$/.test(key)) { + try { + sessionStorage.setItem(STORE, JSON.stringify({ ...saved(), [id]: key })) + } catch { + // storage refused: the key is still used for this view below + memory.set(id, key) + } + } + params.delete('player') + const rest = params.toString() + history.replaceState(null, '', `/${rest ? `?${rest}` : ''}${location.hash}`) +} + +/** The player key this tab was given for a recording, if any. */ +export function playerKeyFor(id: string): string | undefined { + return saved()[id] ?? memory.get(id) +} + +export const playerLinkApi = { + get: async (id: string, key: string): Promise => { + const res = await fetch(`/api/player/${encodeURIComponent(id)}`, { headers: { Authorization: `Bearer ${key}` } }) + const body = (await res.json().catch(() => ({}))) as Recording & { error?: unknown } + if (!res.ok) throw new Error(typeof body.error === 'string' ? body.error : `The recording could not be opened (${res.status}).`) + return body + }, + media: (id: string, file: string, key: string): string => `/api/player/${encodeURIComponent(id)}/${file}?key=${encodeURIComponent(key)}`, +} diff --git a/web/src/player.ts b/web/src/player.ts index bcd552d..017c709 100644 --- a/web/src/player.ts +++ b/web/src/player.ts @@ -1,5 +1,6 @@ import { api, type Anchor, type Chapter, type Recording, type Track } from './api.js' import { DEMOS, demoFile } from './demos.js' +import { playerLinkApi } from './player-link.js' import { scanDuration, Timeline, type Lane } from './sync.js' import { clock, h, safeHref } from './dom.js' import { button, icon, length, panel, when } from './view-kit.js' @@ -55,7 +56,23 @@ export async function demoView(id: string): Promise { return view(rec, (file) => demoFile(id, file), true, h('div', {}, bar, heading(rec, null)), null) } -function view(rec: Recording, src: Src, demo: boolean, head: HTMLElement, actions: HTMLElement | null): HTMLElement { +/** + * A player link: one recording opened with its player key (player-link.ts), read only like a demo, with no library + * actions, since the key reaches nothing else. + */ +export async function linkView(id: string, key: string): Promise { + const rec = await playerLinkApi.get(id, key) + const bar = h('div', { class: 'demo-bar', 'data-link-bar': id }, + h('span', { class: 'demo-flag' }, 'Player link'), + h('span', {}, 'This link opens this recording only. Open FormRec itself for your library and the rest.'), + ) + return view(rec, (file) => playerLinkApi.media(id, file, key), true, h('div', {}, bar, heading(rec, null)), null, 'link') +} + +/** The view's kind: the library's player, a demo, or a player link (both of the last two read only, like a demo). */ +type Kind = 'player' | 'demo' | 'link' + +function view(rec: Recording, src: Src, demo: boolean, head: HTMLElement, actions: HTMLElement | null, kind: Kind = demo ? 'demo' : 'player'): HTMLElement { const { stage, timeline, extra } = rec.tracks && rec.tracks.length > 0 ? tracksStage(rec, src, demo, actions) : walkthroughStage(rec, src) const items = rec.chapters.map((c) => chapterItem(rec, c, (ms) => timeline.seek(ms))) // Only the chapter whose state changed is touched, so the list does not repaint four times a second. @@ -116,14 +133,14 @@ function view(rec: Recording, src: Src, demo: boolean, head: HTMLElement, action } const panels = shown(playerPanels.all()).filter((p) => !p.when || p.when(ctx)) const tabs = panels.length === 0 ? null : sideTabs(rec, panels.map((p) => ({ id: p.id, title: p.title, body: p.render(ctx) }))) - return h('section', { class: 'rv rv-player', 'data-view': demo ? 'demo' : 'player' }, + return h('section', { class: 'rv rv-player', 'data-view': kind }, head, rec.summary ? h('p', { class: 'rv-sub rv-summary' }, rec.summary) : null, h('div', { class: 'player rv-player-grid' }, h('div', { class: 'rv-player-main' }, frame, ...below, extra), h('aside', { class: 'rv-panel rv-chapters-panel', 'data-player-chapters-panel': '' }, tabs?.strip ?? h('header', { class: 'rv-panel-head' }, icon('chapters', 14), h('span', { class: 'rv-panel-title' }, 'Chapters'), h('span', { class: 'rv-count' }, String(rec.chapters.length))), - h('div', { class: 'rv-side-page', 'data-player-side': 'chapters' }, codebaseLine(rec, demo), chapters), + h('div', { class: 'rv-side-page', 'data-player-side': 'chapters' }, codebaseLine(rec, kind === 'demo'), chapters), ...(tabs?.pages ?? []), ), ), @@ -233,10 +250,10 @@ function tracksStage(rec: Recording, src: Src, demo: boolean, actions: HTMLEleme const list = h('ul', { class: 'tracks rv-tracklist', 'data-player-tracks': '' }, ...tracks.map((t) => h('li', { class: 'rv-trackrow', 'data-track': t.id }, h('span', { class: `rv-track-kind is-${t.kind}` }, icon(t.kind, 14)), - h('span', { class: 'rv-track-name' }, h('strong', {}, t.person), h('span', {}, KIND_LABEL[t.kind])), + h('span', { class: 'rv-track-name' }, h('strong', {}, t.person), h('span', {}, `${KIND_LABEL[t.kind]}, ${HOLDS[t.kind]}`)), h('span', { class: 'rv-track-time' }, length(t.durationMs), t.offsetMs > 50 ? h('span', {}, `starts at ${clock(t.offsetMs)}`) : null), t.complete ? h('span', { class: 'rv-badge is-ok' }, icon('check', 11), 'complete') : h('span', { class: 'rv-badge is-warn' }, icon('warn', 11), 'incomplete'), - h('a', { class: 'rv-iconbtn', href: src(t.file), download: `${rec.id}-${t.id}.${t.file.endsWith('.mp4') ? 'mp4' : 'webm'}`, title: `Download ${t.person} ${KIND_LABEL[t.kind].toLowerCase()}`, 'aria-label': `Download ${t.person} ${t.kind}` }, icon('download', 14)), + h('a', { class: 'rv-iconbtn', href: src(t.file), download: `${rec.id}-${t.id}-${t.kind === 'mic' ? 'sound-only' : 'no-sound'}.${t.file.endsWith('.mp4') ? 'mp4' : 'webm'}`, title: `Download ${t.person} ${KIND_LABEL[t.kind].toLowerCase()} (${HOLDS[t.kind]})`, 'aria-label': `Download ${t.person} ${t.kind}` }, icon('download', 14)), ))) const extra = h('div', { class: 'rv-player-extra' }, tiles.length > 0 ? h('div', { class: 'tiles rv-tiles' }, ...tiles) : null, @@ -247,6 +264,8 @@ function tracksStage(rec: Recording, src: Src, demo: boolean, actions: HTMLEleme } const KIND_LABEL: Record = { screen: 'Screen', camera: 'Camera', mic: 'Microphone' } +/** What each track file holds: the camera and screen files have no sound; Export with sound joins them. */ +const HOLDS: Record = { screen: 'picture only, no sound', camera: 'picture only, no sound', mic: 'sound only' } function codebaseLine(rec: Recording, demo: boolean): HTMLElement | null { const cb = rec.codebase diff --git a/web/src/script-logic.ts b/web/src/script-logic.ts new file mode 100644 index 0000000..348fc36 --- /dev/null +++ b/web/src/script-logic.ts @@ -0,0 +1,93 @@ +/** + * Script mode's decisions, with no page in them: a script (Markdown or plain text) split into paragraphs, a chapter + * title for each, and the walk through them. Each Space marks the shown paragraph done; the chapter of the next one + * starts at that moment, so every paragraph's words sit on its own span of the timeline (for training data and for + * editing). A value: each step returns the next state and the mark to add. tests/script-logic.test.ts covers it. + */ + +export interface ScriptMark { title: string; say: string; atMs: number } + +export interface ScriptState { + paragraphs: readonly string[] + /** The paragraph on screen; paragraphs.length once the last is done. */ + at: number + /** True once the first paragraph's chapter has been placed (the take started reading). */ + started: boolean +} + +/** Markdown's block markers that are not words: heading hashes, quotes, list bullets and numbers, emphasis marks. */ +function plain(line: string): string { + return line + .replace(/^\s{0,3}#{1,6}\s+/, '') + .replace(/^\s*>\s?/, '') + .replace(/^\s*(?:[-*+]|\d+[.)])\s+/, '') + .replace(/(\*\*|__|\*|_|`)(.+?)\1/g, '$2') + .trim() +} + +/** Paragraphs are separated by blank lines; code fences, rules and front matter are not read aloud, so they are left out. */ +export function parseScript(text: string): string[] { + const lines = text.replace(/\r\n?/g, '\n').split('\n') + const out: string[] = [] + let current: string[] = [] + let fenced = false + const flush = (): void => { + const joined = current.join(' ').replace(/\s+/g, ' ').trim() + if (joined) out.push(joined.slice(0, 2000)) + current = [] + } + for (const line of lines) { + if (/^\s*(```|~~~)/.test(line)) { flush(); fenced = !fenced; continue } + if (fenced) continue + if (/^\s*$/.test(line) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { flush(); continue } + // A heading is its own paragraph. + if (/^\s{0,3}#{1,6}\s/.test(line)) { flush(); current.push(plain(line)); flush(); continue } + current.push(plain(line)) + } + flush() + return out.slice(0, 500) +} + +/** A chapter title: the paragraph's first words, cut at a word under 60 characters. */ +export function paragraphTitle(paragraph: string, max = 60): string { + const text = paragraph.trim() + if (text.length <= max) return text || 'Paragraph' + const cut = text.slice(0, max) + const space = cut.lastIndexOf(' ') + return `${(space > 20 ? cut.slice(0, space) : cut).replace(/[\s,;:.]+$/, '')}...` +} + +export function startScript(paragraphs: readonly string[]): ScriptState { + return { paragraphs, at: 0, started: false } +} + +const markFor = (state: ScriptState, index: number, atMs: number): ScriptMark => ({ + title: `${index + 1}. ${paragraphTitle(state.paragraphs[index]!, 54)}`, + say: state.paragraphs[index]!, + atMs: Math.max(0, Math.round(atMs)), +}) + +/** The take began reading at atMs (Record, or the end of room tone): the first paragraph's chapter starts there. */ +export function beginReading(state: ScriptState, atMs: number): { state: ScriptState; mark?: ScriptMark } { + if (state.started || state.paragraphs.length === 0) return { state } + return { state: { ...state, started: true }, mark: markFor(state, 0, atMs) } +} + +/** + * Space at atMs: the shown paragraph is done. The next paragraph's chapter starts now; after the last one a closing + * chapter "End of script" starts, so the last paragraph's span ends where it was read. Nothing after that. + */ +export function advance(state: ScriptState, atMs: number): { state: ScriptState; mark?: ScriptMark } { + if (!state.started || state.at >= state.paragraphs.length) return { state } + const next = state.at + 1 + const moved = { ...state, at: next } + if (next < state.paragraphs.length) return { state: moved, mark: markFor(state, next, atMs) } + return { state: moved, mark: { title: 'End of script', say: '', atMs: Math.max(0, Math.round(atMs)) } } +} + +/** "3 of 12", or "Done" past the last paragraph. */ +export function progressText(state: ScriptState): string { + if (state.paragraphs.length === 0) return 'No script' + if (state.at >= state.paragraphs.length) return 'Done' + return `${state.at + 1} of ${state.paragraphs.length}` +} diff --git a/web/src/share-view.ts b/web/src/share-view.ts index 60ce883..bfe8515 100644 --- a/web/src/share-view.ts +++ b/web/src/share-view.ts @@ -357,7 +357,7 @@ function downlinkKbps(): number | undefined { * was shown yet), and nothing in the layout moves (the control has a fixed width, the canvas is absolutely placed). * `swapping` is read by the player's own painters and event reports so a swap looks like nothing happened. */ -function wireQuality(boot: Boot, video: HTMLVideoElement, stage: HTMLElement, swapping: { on: boolean }, applyRate: (r: number) => void): void { +function wireQuality(boot: Boot, video: HTMLVideoElement, stage: HTMLElement, swapping: { on: boolean; playing: boolean }, applyRate: (r: number) => void): void { const select = $('[data-sv-quality]') const hold = $('[data-sv-hold]') // The control is made with the bar (qualityControl); a page with none has nothing to wire. @@ -391,7 +391,8 @@ function wireQuality(boot: Boot, video: HTMLVideoElement, stage: HTMLElement, sw } const swap = (height: number): void => { const at = video.currentTime - const playing = !video.paused && !video.ended + // A swap that replaces one still loading keeps the choice made before it. + if (!swapping.on) swapping.playing = !video.paused && !video.ended const mine = ++token if (hold && video.readyState >= 2 && video.videoWidth > 0) { hold.width = video.videoWidth @@ -411,7 +412,7 @@ function wireQuality(boot: Boot, video: HTMLVideoElement, stage: HTMLElement, sw if (video.readyState < 2 || Math.abs(video.currentTime - at) > 1) return cleanup() release() - if (playing) void startPlay(video) + if (swapping.playing) void startPlay(video) } video.addEventListener('loadedmetadata', () => { if (mine !== token) return @@ -473,7 +474,18 @@ function wireViewer(boot: Boot): void { const network = boot.mode === 'network' || boot.mode === 'embed' const visit = Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(36).padStart(2, '0')).join('').slice(0, 20) // True while the quality control swaps the source: the player's painters and event reports sit still meanwhile. - const swapping = { on: false } + // `playing` is the person's choice during a swap: the element reads paused while the new source loads, so play and + // pause change the choice and the swap starts playing at its end only when the choice is still to play. + const swapping = { on: false, playing: false } + const toggle = (): void => { + if (swapping.on) { + swapping.playing = !swapping.playing + if (!swapping.playing) video.pause() + return + } + if (video.paused || video.ended) void startPlay(video) + else video.pause() + } const send = (type: string, extra: Record = {}): void => { if (!network || !boot.api || swapping.on) return const height = Number(video.dataset['svHeight']) @@ -506,7 +518,7 @@ function wireViewer(boot: Boot): void { const controls = controlBar({ lead: video, timeline: lane, durationMs, chapters: chapterList, frame, stage, video, host, extra: [cc, theatreBtn, qualitySelect].filter((e): e is HTMLElement => e !== null), signal: new AbortController().signal, - speed: boot.hideSpeed !== true, onCaptions: () => captions(), onTheatre: () => theatre(), + speed: boot.hideSpeed !== true, onCaptions: () => captions(), onTheatre: () => theatre(), toggle, }) // Over the picture, under the avatar, the captions and the held frame: a click plays or pauses, a double click goes full screen. video.after(controls.surface, controls.bigPlay) @@ -551,7 +563,6 @@ function wireViewer(boot: Boot): void { for (let i = 0; i < starts.length; i++) if (starts[i]! <= ms) now = i rows.forEach((r, i) => { if (r.classList.contains('is-now') !== (i === now)) r.classList.toggle('is-now', i === now) }) } - const toggle = (): void => { if (video.paused) void startPlay(video); else video.pause() } // Captions are drawn in the page's own box over the picture (absolutely placed, so nothing moves), from the track's // active cues; the browser's own caption rendering is never used. const cueBox = $('[data-sv-cue-box]') diff --git a/web/src/studio-devices-ui.ts b/web/src/studio-devices-ui.ts new file mode 100644 index 0000000..29690cd --- /dev/null +++ b/web/src/studio-devices-ui.ts @@ -0,0 +1,116 @@ +/** + * The studio's device row: the microphone and camera lists kept filled by DeviceWatcher (studio-devices.ts), the + * Refresh devices button with its status line, the report agents read (formrec_studio_state's `devices`) and the + * refresh an agent asks for (formrec_studio_refresh_devices, polled at /api/studio/devices/request while the studio + * is open and shown). The row exists from the first frame with its status line's height reserved, so nothing moves. + */ +import { h } from './dom.js' +import { icon } from './view-kit.js' +import { studioApi } from './studio-panels.js' +import { DeviceWatcher, needsPermission, planList, type DeviceLists, type Permission, type RefreshResult } from './studio-devices.js' + +const AGENT_POLL_MS = 2000 + +export interface StudioDevices { + /** The button and status line, for beside the pickers. */ + el: HTMLElement + /** List again (no permission prompt): at load, and after the studio opens its devices. */ + fill(): Promise +} + +export interface StudioDevicesOptions { + camera: HTMLSelectElement + mic: HTMLSelectElement + /** True when the chosen layout records the camera. */ + cameraInUse(): boolean + saved(): { cameraId: string; micId: string } + signal: AbortSignal +} + +function applyPlan(select: HTMLSelectElement, plan: ReturnType): void { + const same = select.options.length === plan.options.length + && plan.options.every((o, i) => select.options[i]!.value === o.value && select.options[i]!.textContent === o.label) + if (!same) select.replaceChildren(...plan.options.map((o) => h('option', { value: o.value }, o.label))) + if (select.value !== plan.value) select.value = plan.value +} + +export function studioDevices(o: StudioDevicesOptions): StudioDevices { + let permission: Permission = 'needed' + const line = h('p', { class: 'rv-hint studio-devices-line', 'data-studio-devices-status': '', 'aria-live': 'polite' }, '') + const button = h('button', { + type: 'button', class: 'rv-btn rv-ghost studio-devices-refresh', 'data-studio-devices-refresh': '', + title: 'List the microphones and cameras again. When their names are hidden, the browser asks for permission first.', + }, icon('refresh', 14), h('span', { class: 'rv-label' }, 'Refresh devices')) as HTMLButtonElement + // Reports go one after another, so the last one written is the last one made (an agent waits for its request id). + let sent: Promise = Promise.resolve() + // The last agent request answered rides on every later report, so a refill right after it never hides the answer. + let answered = '' + const report = (lists: DeviceLists, text: string, answering?: string): void => { + if (answering) answered = answering + const requestId = answered + const named = (list: DeviceLists['mics'], chosen: string) => list.map((d, i) => ({ label: d.label || `Device ${i + 1}`, chosen: d.deviceId === chosen })) + const body = { + ...(requestId ? { requestId } : {}), mics: named(lists.mics, o.mic.value), cameras: named(lists.cameras, o.camera.value), + cameraInUse: o.cameraInUse(), permission, text, + } + sent = sent.then(() => studioApi('/api/studio/devices', 'PUT', body)).catch(() => undefined) + } + const watcher = new DeviceWatcher({ + media: navigator.mediaDevices, + cameraInUse: o.cameraInUse, + signal: o.signal, + page: { doc: document, win: window }, + permissions: navigator.permissions, + apply: (lists) => { + const saved = o.saved() + applyPlan(o.camera, planList(lists.cameras, 'Camera', o.camera.value, saved.cameraId)) + applyPlan(o.mic, planList(lists.mics, 'Microphone', o.mic.value, saved.micId)) + // Names showing means access was given; hidden names keep a refusal until the person changes it. + if (!needsPermission(lists, o.cameraInUse())) permission = 'granted' + else if (permission !== 'refused') permission = 'needed' + report(lists, line.textContent ?? '') + }, + }) + + const run = async (ask: boolean, requestId?: string): Promise => { + button.disabled = true + button.setAttribute('aria-busy', 'true') + line.textContent = ask ? 'Looking for devices...' : line.textContent + try { + const result = await watcher.refresh({ ask }) + permission = result.permission + line.textContent = result.text + line.dataset['permission'] = result.permission + report(result.lists, result.text, requestId) + return result + } finally { + button.disabled = false + button.removeAttribute('aria-busy') + } + } + button.addEventListener('click', () => void run(true).catch((error: Error) => { line.textContent = `The devices could not be listed: ${error.message}` })) + + // An agent's refresh: one at a time, only while the studio is shown, each request once. + let handled = '' + let polling = false + const poll = async (): Promise => { + if (polling || document.visibilityState !== 'visible' || o.signal.aborted) return + polling = true + try { + const request = await studioApi<{ id?: string; askPermission?: boolean }>('/api/studio/devices/request') + if (request.id && request.id !== handled) { + handled = request.id + await run(request.askPermission === true, request.id) + } + } catch { /* the next poll tries again */ } finally { + polling = false + } + } + const timer = setInterval(() => void poll(), AGENT_POLL_MS) + o.signal.addEventListener('abort', () => clearInterval(timer)) + + return { + el: h('div', { class: 'studio-devices', 'data-studio-devices': '' }, button, line), + fill: async () => { await watcher.fill() }, + } +} diff --git a/web/src/studio-devices.ts b/web/src/studio-devices.ts new file mode 100644 index 0000000..5153adf --- /dev/null +++ b/web/src/studio-devices.ts @@ -0,0 +1,165 @@ +/** + * The studio's microphone and camera lists, kept true to the hardware. Before the person grants permission, WebKit + * and Chromium list devices with empty labels (or only a default entry), and nothing tells the page when a device + * is plugged in while it is open. DeviceWatcher refills both lists on `devicechange` (debounced), when the window is + * shown or focused again, and when a permission changes; refresh() rebuilds them on demand and, when the names are + * hidden, briefly asks for permission, stops those tracks at once and lists again so the real names appear. + * + * No DOM here: the studio applies the lists (studio-devices-ui.ts), so this module runs in tests without a browser. + */ + +export interface DeviceEntry { deviceId: string; kind: string; label: string } +export interface DeviceLists { mics: DeviceEntry[]; cameras: DeviceEntry[] } +export interface ListPlan { options: { value: string; label: string }[]; value: string } +export type Permission = 'granted' | 'needed' | 'refused' | 'unavailable' +export interface RefreshResult { lists: DeviceLists; permission: Permission; asked: boolean; text: string } + +export const DEBOUNCE_MS = 400 +/** The id Chromium gives the system default device in each list. */ +const SYSTEM_DEFAULT = 'default' + +export function splitDevices(all: readonly DeviceEntry[]): DeviceLists { + return { mics: all.filter((d) => d.kind === 'audioinput'), cameras: all.filter((d) => d.kind === 'videoinput') } +} + +/** Which device a refilled list selects: the current choice while it is there, else the saved one, else the system default, else the first. */ +export function pickDevice(list: readonly DeviceEntry[], current: string, saved: string): string { + const has = (id: string): boolean => id !== '' && list.some((d) => d.deviceId === id) + if (has(current)) return current + if (has(saved)) return saved + if (has(SYSTEM_DEFAULT)) return SYSTEM_DEFAULT + return list[0]?.deviceId ?? '' +} + +/** A list's options and its selected value; a device with no name yet is shown by its place in the list. */ +export function planList(list: readonly DeviceEntry[], noun: 'Microphone' | 'Camera', current: string, saved: string): ListPlan { + return { options: list.map((d, i) => ({ value: d.deviceId, label: d.label || `${noun} ${i + 1}` })), value: pickDevice(list, current, saved) } +} + +/** True when the browser is hiding names (or every device) until the person grants permission. */ +export function needsPermission(lists: DeviceLists, cameraInUse: boolean): boolean { + const hidden = (list: DeviceEntry[]): boolean => list.length === 0 || list.some((d) => d.label === '') + return hidden(lists.mics) || (cameraInUse && hidden(lists.cameras)) +} + +const count = (n: number, one: string, many: string): string => (n === 0 ? `no ${many}` : `${n} ${n === 1 ? one : many}`) + +/** The status line after a refresh: "Found 3 microphones and 1 camera", or a plain sentence about permission. */ +export function resultText(lists: DeviceLists, permission: Permission, cameraInUse: boolean): string { + if (permission === 'refused') return 'Permission was refused, so device names stay hidden. Allow the microphone and camera in the browser or system settings, then refresh.' + if (permission === 'unavailable') return 'This browser cannot list devices here.' + const found = `Found ${count(lists.mics.length, 'microphone', 'microphones')}${cameraInUse ? ` and ${count(lists.cameras.length, 'camera', 'cameras')}` : ''}` + return permission === 'needed' ? `${found}. Names appear once you allow access.` : `${found}.` +} + +export interface Timers { set(fn: () => void, ms: number): unknown; clear(handle: unknown): void } +const realTimers: Timers = { set: (fn, ms) => setTimeout(fn, ms), clear: (t) => clearTimeout(t as ReturnType) } + +/** One call after the calls stop for `ms`; cancel() drops a waiting one. */ +export function debounce(fn: () => void, ms: number, timers: Timers = realTimers): { (): void; cancel(): void } { + let handle: unknown + const run = (): void => { + if (handle !== undefined) timers.clear(handle) + handle = timers.set(() => { handle = undefined; fn() }, ms) + } + run.cancel = (): void => { if (handle !== undefined) timers.clear(handle); handle = undefined } + return run +} + +export interface WatchDeps { + /** navigator.mediaDevices, or undefined where the page has none (an insecure origin). */ + media?: Pick & EventTarget + apply(lists: DeviceLists): void + cameraInUse(): boolean + signal: AbortSignal + /** Fires `visibilitychange` (with visibilityState) and `focus`: the document and the window. */ + page?: { doc: EventTarget & { visibilityState: string }; win: EventTarget } + permissions?: { query(d: { name: string }): Promise } + timers?: Timers + debounceMs?: number +} + +const isError = (e: unknown, ...names: string[]): boolean => names.includes((e as { name?: string })?.name ?? '') + +export class DeviceWatcher { + private running: Promise | undefined + private again = false + readonly schedule: { (): void; cancel(): void } + + constructor(private readonly deps: WatchDeps) { + this.schedule = debounce(() => void this.fill().catch(() => undefined), deps.debounceMs ?? DEBOUNCE_MS, deps.timers) + const { signal } = deps + signal.addEventListener('abort', () => this.schedule.cancel()) + deps.media?.addEventListener('devicechange', this.schedule, { signal }) + if (deps.page) { + const { doc, win } = deps.page + doc.addEventListener('visibilitychange', () => { if (doc.visibilityState === 'visible') this.schedule() }, { signal }) + win.addEventListener('focus', this.schedule, { signal }) + } + for (const name of ['microphone', 'camera']) { + // Safari and Firefox refuse some names; a permission that cannot be watched is simply not watched. + void deps.permissions?.query({ name }).then((status) => { + if (!signal.aborted) status.addEventListener('change', () => { if (status.state === 'granted') this.schedule() }, { signal }) + }).catch(() => undefined) + } + } + + private async list(): Promise { + if (!this.deps.media) return { mics: [], cameras: [] } + return splitDevices(await this.deps.media.enumerateDevices()) + } + + /** List and apply; calls that arrive during a fill run once more after it, so the last change always lands. */ + fill(): Promise { + if (this.running) { this.again = true; return this.running } + this.running = (async () => { + try { + let lists = await this.list() + while (this.again && !this.deps.signal.aborted) { this.again = false; lists = await this.list() } + if (!this.deps.signal.aborted) this.deps.apply(lists) + return lists + } finally { + this.running = undefined + } + })() + return this.running + } + + /** The permission prompt: audio, and video only when the camera picker is in use; the tracks stop at once. */ + private async ask(video: boolean): Promise { + const media = this.deps.media! + let stream: MediaStream + try { + stream = await media.getUserMedia({ audio: true, video }) + } catch (error) { + // No camera plugged in: the microphone alone still gives the microphone names. + if (!video || !isError(error, 'NotFoundError', 'OverconstrainedError', 'NotReadableError')) throw error + stream = await media.getUserMedia({ audio: true, video: false }) + } + for (const t of stream.getTracks()) t.stop() + } + + /** Rebuild both lists now; with `ask`, a list whose names are hidden asks for permission first. */ + async refresh(opts: { ask: boolean }): Promise { + const cameraInUse = this.deps.cameraInUse() + if (!this.deps.media) { + const lists = { mics: [], cameras: [] } + return { lists, permission: 'unavailable', asked: false, text: resultText(lists, 'unavailable', cameraInUse) } + } + this.schedule.cancel() + let lists = await this.fill() + let permission: Permission = needsPermission(lists, cameraInUse) ? 'needed' : 'granted' + let asked = false + if (permission === 'needed' && opts.ask) { + asked = true + try { + await this.ask(cameraInUse) + lists = await this.fill() + permission = needsPermission(lists, cameraInUse) ? 'needed' : 'granted' + } catch (error) { + permission = isError(error, 'NotAllowedError', 'SecurityError') ? 'refused' : 'needed' + } + } + return { lists, permission, asked, text: resultText(lists, permission, cameraInUse) } + } +} diff --git a/web/src/studio-script.ts b/web/src/studio-script.ts new file mode 100644 index 0000000..86faa51 --- /dev/null +++ b/web/src/studio-script.ts @@ -0,0 +1,131 @@ +/** + * Script mode: a script (Markdown or plain text, loaded from a file or pasted) shown on the stage one paragraph at a + * time. While the take records, Space (or Done) marks the shown paragraph done and drops a chapter mark at that moment + * into the take's marks, which become chapters.vtt, so the audio lines up with the text for training and editing. The + * decisions are script-logic.ts; this is the panel, the stage overlay and the key. + */ +import { h } from './dom.js' +import { button, field, icon, toggle } from './view-kit.js' +import { advance, beginReading, parseScript, progressText, startScript, type ScriptMark, type ScriptState } from './script-logic.js' + +const SCRIPT_LIMIT = 1024 * 1024 + +export interface ScriptHooks { + signal: AbortSignal + /** True while the take records (Space does nothing before or after). */ + recording(): boolean + takeMs(): number | undefined + /** The Slides layout keeps Space for its own next slide. */ + spaceTaken(): boolean + mark(mark: ScriptMark): void +} + +export interface StudioScript { + panel: HTMLElement + stage: HTMLElement + /** The take began reading at atMs (Record, or the end of room tone); true when the script placed its first chapter. */ + begin(atMs: number): boolean + /** A new take: back to the first paragraph. */ + reset(): void +} + +/** + * A field or a widget that uses Space keeps it. A button does not: while a script is read, Space must never press the + * focused Pause or Stop, so the key is taken from buttons (keydown and keyup both, since a button acts on keyup). + */ +function keyBelongsToPage(e: KeyboardEvent): boolean { + const t = e.target instanceof HTMLElement ? e.target : undefined + if (!t) return false + if (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT|SUMMARY|DIALOG)$/.test(t.tagName)) return true + return Boolean(t.closest('dialog[open], [role="dialog"], [role="menu"], [role="slider"], [role="tab"], [role="radio"], [role="listbox"], [role="textbox"], [role="combobox"]')) +} + +export function studioScript(hooks: ScriptHooks): StudioScript { + let paragraphs: string[] = [] + let state: ScriptState = startScript([]) + const file = h('input', { type: 'file', accept: '.md,.markdown,.txt,text/plain,text/markdown', 'data-script-file': '' }) as HTMLInputElement + const text = h('textarea', { rows: '4', placeholder: 'Or paste the script here; a blank line starts a new paragraph.', 'data-script-text': '', maxlength: String(SCRIPT_LIMIT) }) as HTMLTextAreaElement + const on = h('input', { 'data-script-on': '' }) as HTMLInputElement + const count = h('span', { class: 'studio-mono', 'data-script-count': '' }, 'No script') + const done = button('Done (Space)', 'check', { class: 'rv-ghost', disabled: true, 'data-script-done': '' }) + const progress = h('span', { class: 'studio-script-progress', 'data-script-progress': '' }, '') + const words = h('p', { class: 'studio-script-text', 'data-script-paragraph': '' }, '') + const stage = h('div', { class: 'studio-script', 'data-studio-script': '', 'data-shown': 'false', 'aria-live': 'polite' }, + h('div', { class: 'studio-script-head' }, progress, h('span', { class: 'studio-script-key' }, 'Space: done, next paragraph')), words) + + const draw = (): void => { + const shown = on.checked && paragraphs.length > 0 + stage.dataset['shown'] = String(shown) + const line = state.at < paragraphs.length ? paragraphs[state.at]! : 'End of the script.' + if (words.textContent !== line) words.textContent = line + progress.textContent = progressText(state) + count.textContent = paragraphs.length ? `${paragraphs.length} paragraphs` : 'No script' + done.disabled = !shown || !hooks.recording() || !state.started || state.at >= paragraphs.length + } + const load = (raw: string): void => { + paragraphs = parseScript(raw.slice(0, SCRIPT_LIMIT)) + state = startScript(paragraphs) + on.checked = paragraphs.length > 0 + draw() + } + file.addEventListener('change', () => void (async () => { + const f = file.files?.[0] + if (!f) return + const raw = f.size > SCRIPT_LIMIT ? (await f.slice(0, SCRIPT_LIMIT).text()) : await f.text() + text.value = raw + load(raw) + })()) + text.addEventListener('input', () => load(text.value)) + on.addEventListener('change', draw) + + const next = (): void => { + const at = hooks.takeMs() + if (at === undefined || !hooks.recording() || !on.checked) return + const step = advance(state, at) + state = step.state + if (step.mark) hooks.mark(step.mark) + draw() + } + done.addEventListener('click', next) + let took = false + document.addEventListener('keydown', (e) => { + if (e.key !== ' ' || e.defaultPrevented || e.repeat || e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return + if (!on.checked || paragraphs.length === 0 || !hooks.recording() || hooks.spaceTaken() || keyBelongsToPage(e)) return + e.preventDefault() + took = true + next() + }, { signal: hooks.signal }) + document.addEventListener('keyup', (e) => { + if (e.key === ' ' && took) { e.preventDefault(); took = false } + }, { signal: hooks.signal }) + // The take's state changes elsewhere; Done follows it. + const watch = setInterval(draw, 500) + hooks.signal.addEventListener('abort', () => clearInterval(watch)) + + const panel = h('details', { class: 'rv-panel rv-disclose', 'data-studio-script-panel': '' }, + h('summary', { class: 'rv-panel-head' }, icon('chapters', 14), h('span', { class: 'rv-panel-title' }, 'Script'), h('span', { class: 'rv-chev', 'aria-hidden': 'true' }, icon('back', 14))), + h('div', { class: 'rv-panel-body' }, + h('p', { class: 'rv-hint' }, 'One paragraph at a time on the stage. While recording, Space marks it done and starts the next paragraph\'s chapter.'), + field('Script file (Markdown or text)', file), + text, + h('div', { class: 'rv-row studio-row' }, h('label', { class: 'studio-inline' }, toggle(on), h('span', {}, 'Show on the stage')), count, done), + ), + ) + draw() + return { + panel, + stage, + begin(atMs) { + if (!on.checked) return false + const step = beginReading(state, atMs) + state = step.state + if (step.mark) hooks.mark(step.mark) + draw() + return Boolean(step.mark) + }, + reset() { + state = startScript(paragraphs) + draw() + }, + } +} diff --git a/web/src/studio-sound.ts b/web/src/studio-sound.ts new file mode 100644 index 0000000..c51dc64 --- /dev/null +++ b/web/src/studio-sound.ts @@ -0,0 +1,320 @@ +/** + * The studio's sound: the capture preset (Standard or Voice master), the always-visible level meters (a large one under + * the stage, a compact one in the record bar), the pre-roll level check, clip counting during the take, the room tone + * prompt, the WAV master, and what the take writes about its capture (recording.json `capture`). The studio calls it + * at a few points (getReady, start, stop, save, release); everything else lives here, so the studio view itself and + * its source picker barely change. + */ +import { authHeaders } from './api.js' +import { h } from './dom.js' +import { captureTrack, checkForJson, deliveredNote, type Capture, type CaptureKind, type CaptureTrack } from './capture-meta.js' +import { openEngine, type LevelEngine } from './level-engine.js' +import { + adviceText, CLIP_LEVEL, clipReport, clipStep, dbfs, EMPTY_CLIPS, EMPTY_HINT, hintStep, holdStep, levelCheck, + type ClipLog, type Hint, type HintState, type Hold, type LevelCheck, +} from './levels.js' +import { dbMeter } from './meter.js' +import { field, icon, panel, toggle } from './view-kit.js' +import { loadSound, MASTER_FILE, MASTER_RATE, micConstraints, PRESET_LABEL, ROOM_TONE_MS, saveSound, type Dsp, type SoundPreset } from './voice-master.js' +import { WavRecorder } from './wav-recorder.js' + +const CHECK_MS = 6000 + +/** Where the take is: not started, recording (clips are counted at their take time), or paused or stopped (nothing is recorded). */ +type Phase = { state: 'before' } | { state: 'live'; atMs: number } | { state: 'held' } + +export interface Opened { + /** The streams as the devices gave them, before any plugin changed them. */ + raw: Partial> + /** The microphone stream that is recorded (Effects' output in Standard, the device's own in Voice master). */ + mic?: MediaStream + system?: MediaStream + quality: { quality: string; width: number; height: number } +} + +export interface TakeHooks { + sessionId: string + /** The take's time on the server's clock, undefined before it runs. */ + takeMs(): number | undefined + /** True while the take records (not paused). */ + live(): boolean + /** Add a chapter mark at a take time. */ + mark(title: string, atMs: number): void + onMasterState(text: string, failed: boolean): void +} + +export interface StudioSound { + panel: HTMLElement + strip: HTMLElement + mini: HTMLElement + stage: HTMLElement + preset(): SoundPreset + /** The microphone's getUserMedia constraints for the chosen preset. */ + micConstraints(dsp: Dsp, micId?: string): MediaTrackConstraints + /** Plugins must leave the microphone alone (Voice master: no Effects chain, no noise filter). */ + raw(): boolean + lock(on: boolean): void + /** The devices are open: watch the recorded microphone, note what each source delivered. Returns a note for the status line. */ + attach(opened: Opened): Promise + /** Recording starts: clip counting from zero, room tone, the WAV master. Returns the master's recorder when there is one. */ + startTake(hooks: TakeHooks): WavRecorder | undefined + /** Where reading starts on the take's timeline (after room tone). */ + readingStartsAt(): number + /** The take stopped: the clip line for the save screen. */ + stopTake(): string + capture(): Capture | undefined + /** The take was thrown away or restarted: clips and room tone start again. */ + resetTake(): void + detach(): void +} + +/** The large meter, the compact one and the loops that feed them. */ +function meters(): { + strip: HTMLElement; mini: HTMLElement; report(text: string | undefined): void + watch(engine: LevelEngine | undefined, phase: () => Phase): void + resetClips(): void; clips(): ClipLog['clips']; stop(): void; collect(ms: number): Promise +} { + const large = dbMeter('large', 'Microphone level, dBFS') + const compact = dbMeter('compact', 'Microphone level, dBFS') + const strip = h('div', { class: 'rv-lv-strip', 'data-levels-strip': '' }, large.el) + large.idle('Get ready to see your microphone level.') + compact.idle('') + let engine: LevelEngine | undefined + let unlisten = (): void => undefined + let frame = 0 + let db = -Infinity + let hold: Hold | undefined + let hint: Hint = 'none' + let hintState: HintState = EMPTY_HINT + let log: ClipLog = EMPTY_CLIPS + let preroll = 0 + let lit = false + let collector: number[] | undefined + let phase: () => Phase = () => ({ state: 'before' }) + const clear = (): void => { lit = false } + large.onClipClick(clear) + compact.onClipClick(clear) + const draw = (): void => { + const now = performance.now() + const holdDb = hold && now - hold.atMs <= 1500 ? hold.db : db + const reading = { db, holdDb, clips: phase().state === 'before' ? preroll : log.clips.length, lit, hint } + large.show(reading) + compact.show(reading) + frame = requestAnimationFrame(draw) + } + return { + strip, mini: compact.el, + report: (text) => large.pin(text), + watch(next, takeOf) { + unlisten() + cancelAnimationFrame(frame) + engine = next + phase = takeOf + if (!engine) { large.idle('Get ready to see your microphone level.'); compact.idle(''); return } + unlisten = engine.listen((_samples, peak) => { + const now = performance.now() + db = dbfs(peak) + hold = holdStep(hold, db, now) + ;({ state: hintState, hint } = hintStep(hintState, db, now)) + collector?.push(peak) + if (peak < CLIP_LEVEL) return + lit = true + const at = phase() + if (at.state === 'before') preroll += 1 + else if (at.state === 'live') log = clipStep(log, peak, at.atMs) + }) + frame = requestAnimationFrame(draw) + }, + resetClips() { log = EMPTY_CLIPS; lit = false; preroll = 0; large.pin(undefined) }, + clips: () => log.clips, + stop() { + unlisten() + cancelAnimationFrame(frame) + engine = undefined + db = -Infinity + hold = undefined + hintState = EMPTY_HINT + hint = 'none' + large.pin(undefined) + large.idle('Get ready to see your microphone level.') + compact.idle('') + }, + async collect(ms) { + collector = [] + await new Promise((r) => setTimeout(r, ms)) + const got = collector + collector = undefined + return got + }, + } +} + +export function studioSound(): StudioSound { + let settings = loadSound() + const m = meters() + const preset = h('select', { 'data-sound-preset': '' }, + ...(['standard', 'voice-master'] as SoundPreset[]).map((p) => h('option', { value: p }, PRESET_LABEL[p]))) as HTMLSelectElement + preset.value = settings.preset + const roomTone = h('input', { 'data-sound-roomtone': '' }) as HTMLInputElement + const roomField = h('label', { class: 'studio-inline', 'data-sound-roomtone-field': '' }, toggle(roomTone), h('span', {}, 'Start with 8 s of room tone')) + roomTone.checked = settings.roomTone + const presetNote = h('p', { class: 'rv-hint rv-sound-note', 'data-sound-preset-note': '' }, '') + const check = h('button', { type: 'button', class: 'rv-btn rv-ghost rv-sound-check', disabled: true, 'data-sound-check': '' }, icon('wave', 14), h('span', { class: 'rv-label' }, 'Check level')) as HTMLButtonElement + const checkLine = h('p', { class: 'rv-hint rv-sound-line', 'data-sound-check-result': '' }, 'Get ready, then speak for six seconds as you will in the take.') + const note = h('p', { class: 'rv-hint rv-sound-line', 'data-sound-note': '' }, '') + const describe = (): void => { + presetNote.textContent = preset.value === 'voice-master' + ? 'Echo cancellation, noise suppression, automatic gain and Effects are off; a 48 kHz 24-bit WAV is written beside the Opus track.' + : 'The microphone as Effects sets it, recorded as Opus. For voice training or a later mix, choose Voice master.' + roomField.classList.toggle('is-off', preset.value !== 'voice-master') + } + describe() + preset.addEventListener('change', () => { settings = saveSound({ preset: preset.value as SoundPreset }); describe() }) + roomTone.addEventListener('change', () => { settings = saveSound({ roomTone: roomTone.checked }) }) + + const toneCount = h('strong', { class: 'studio-roomtone-count', 'data-sound-roomtone-count': '' }, '8') + const stage = h('div', { class: 'studio-roomtone', 'data-sound-roomtone-overlay': '', 'data-shown': 'false', 'aria-live': 'polite' }, + h('span', {}, 'Room tone: stay quiet'), toneCount) + + let engine: LevelEngine | undefined + let opened: Opened | undefined + let tracks: CaptureTrack[] = [] + let lastCheck: LevelCheck | undefined + let master: WavRecorder | undefined + let masterRate = 0 + let toneTimer: ReturnType | undefined + let toned = false + let takeHooks: TakeHooks | undefined + + check.addEventListener('click', () => void (async () => { + if (!engine) return + check.disabled = true + checkLine.textContent = 'Listening: speak now, as you will in the take...' + const peaks = await m.collect(CHECK_MS) + lastCheck = levelCheck(peaks) + checkLine.textContent = adviceText(lastCheck) + checkLine.dataset['advice'] = lastCheck.advice + check.disabled = !engine + })()) + + const kindOf = (k: 'screen' | 'camera' | 'mic'): CaptureKind => k + const stopTone = (): void => { + clearInterval(toneTimer) + toneTimer = undefined + stage.dataset['shown'] = 'false' + } + + const api: StudioSound = { + panel: panel('Sound', 'wave', [ + field('Microphone preset', preset), presetNote, roomField, + h('div', { class: 'rv-row studio-row' }, check), checkLine, note, + ], { 'data-studio-sound': '' }), + strip: m.strip, + mini: m.mini, + stage, + preset: () => preset.value as SoundPreset, + micConstraints: (dsp, micId) => micConstraints(preset.value as SoundPreset, dsp, micId), + raw: () => preset.value === 'voice-master', + lock(on) { preset.disabled = on; roomTone.disabled = on }, + async attach(o) { + opened = o + tracks = [] + for (const [k, stream] of Object.entries(o.raw) as ['screen' | 'camera' | 'mic', MediaStream | undefined][]) { + const t = (k === 'mic' ? stream?.getAudioTracks() : stream?.getVideoTracks())?.[0] + if (t) tracks = [...tracks, captureTrack(kindOf(k), t)] + } + const sys = o.system?.getAudioTracks()[0] + if (sys) tracks = [...tracks, captureTrack('system', sys)] + const notes = tracks.map((t) => deliveredNote(t.kind, o.quality, t.settings)).filter((n): n is string => Boolean(n)) + const mic = tracks.find((t) => t.kind === 'mic')?.settings + if (preset.value === 'voice-master' && mic && (mic.echoCancellation || mic.noiseSuppression || mic.autoGainControl)) { + notes.push('The browser kept some processing on the microphone it says it turned off; recording.json records what it applied.') + } + note.textContent = notes.join(' ') + engine?.stop() + engine = undefined + if (o.mic && typeof AudioContext !== 'undefined') { + try { + engine = await openEngine(o.mic, preset.value === 'voice-master' ? MASTER_RATE : undefined) + } catch { + engine = undefined + } + } + m.watch(engine, () => { + const at = takeHooks?.takeMs() + if (!takeHooks || at === undefined) return { state: 'before' } + return takeHooks.live() ? { state: 'live', atMs: at } : { state: 'held' } + }) + check.disabled = !engine + if (preset.value === 'voice-master' && engine && !engine.lossless) notes.push('This browser cannot tap the microphone sample by sample, so no WAV master is written.') + if (preset.value === 'voice-master' && engine && engine.sampleRate !== MASTER_RATE) notes.push(`The master is written at ${engine.sampleRate} Hz, the rate this browser runs at.`) + note.textContent = notes.join(' ') + return notes.join(' ') + }, + startTake(hooks) { + takeHooks = hooks + m.resetClips() + toned = false + master = undefined + if (preset.value === 'voice-master' && engine?.lossless) { + const id = encodeURIComponent(hooks.sessionId) + masterRate = engine.sampleRate + master = new WavRecorder(engine, async () => ({ + chunkUrl: (seq) => `/api/studio/takes/${id}/master?seq=${seq}`, + endUrl: `/api/studio/takes/${id}/master/end`, + headers: authHeaders(), + }), (s) => hooks.onMasterState(`${s.sent} chunks, ${(s.bytes / 1e6).toFixed(1)} MB${s.pending ? `, ${s.pending} waiting` : ''}${s.error ? ` (${s.failed ? 'not sent' : 'retrying'}: ${s.error})` : ''}`, Boolean(s.failed))) + } + if (preset.value === 'voice-master' && roomTone.checked) { + toned = true + hooks.mark('Room tone', 0) + stage.dataset['shown'] = 'true' + toneCount.textContent = String(ROOM_TONE_MS / 1000) + toneTimer = setInterval(() => { + const at = hooks.takeMs() ?? 0 + const left = Math.max(0, Math.ceil((ROOM_TONE_MS - at) / 1000)) + if (toneCount.textContent !== String(left)) toneCount.textContent = String(left) + if (at >= ROOM_TONE_MS) stopTone() + }, 200) + } + return master + }, + readingStartsAt: () => (toned ? ROOM_TONE_MS : 0), + stopTake() { + stopTone() + const text = clipReport(m.clips()) + m.report(text) + return text + }, + capture() { + if (!opened) return undefined + const clips = [...m.clips()] + return { + preset: preset.value as SoundPreset, + requested: opened.quality, + tracks, + micEffects: preset.value !== 'voice-master' && Boolean(opened.mic && opened.raw.mic && opened.mic !== opened.raw.mic), + ...(toned ? { roomToneMs: ROOM_TONE_MS } : {}), + ...(master ? { master: { file: MASTER_FILE, sampleRate: masterRate, bitsPerSample: 24, channels: 1, durationMs: 0 } } : {}), + levels: { clips, ...(lastCheck ? { check: checkForJson(lastCheck) } : {}) }, + } + }, + resetTake() { + stopTone() + m.resetClips() + toned = false + master = undefined + }, + detach() { + stopTone() + m.stop() + engine?.stop() + engine = undefined + opened = undefined + takeHooks = undefined + check.disabled = true + note.textContent = '' + }, + } + return api +} diff --git a/web/src/studio.ts b/web/src/studio.ts index 1a34a76..934d55a 100644 --- a/web/src/studio.ts +++ b/web/src/studio.ts @@ -4,13 +4,15 @@ * call and record themselves the same way. Editing happens in FormCut. */ import { api, authHeaders, type Kind, type Session } from './api.js' -import { clockOffset, listDevices, openDisplay, openSources, stopSources, TrackRecorder, type Sources } from './capture.js' +import { clockOffset, openDisplay, openSources, stopSources, TrackRecorder, type Sources } from './capture.js' import { token } from './api.js' import { clock, h } from './dom.js' import { HostCall } from './rtc.js' import { marksPanel } from './marks.js' import { guestsPanel } from './studio-guests.js' -import { levelMeter, type Meter } from './meter.js' +import { studioSound } from './studio-sound.js' +import { studioScript } from './studio-script.js' +import { loadPrefs } from './effects-layout.js' import { button, field, icon, panel, relabel, toggle, type IconName } from './view-kit.js' import { studioPlugins, type NativeScreenRecorder, type StudioContext } from './features/registry.js' import { @@ -22,6 +24,7 @@ import { checkIn, countdown, notesPanel, recoverPanel, rewindSheet, shotsPanel, import { loadSettings, saveSettings } from './studio-settings.js' import { sicon, type StudioIcon } from './studio-icons.js' import { setActiveStudio } from './studio-control.js' +import { studioDevices } from './studio-devices-ui.js' const LEAVE = 'formrec:leave' const POLL_MS = 1000 @@ -83,8 +86,8 @@ export function studioView(preset?: Mode | Layout): HTMLElement { /** True while this page's own last chunks are still on their way. */ let sending = false - let meter: Meter | undefined const settings = loadSettings() + const sound = studioSound() /** The 0.4.0 parts of a take: the computer's sound, the compositor, the rewind preview, the camera switch. */ let system: MediaStream | undefined let rawStreams: MediaStream[] = [] @@ -209,13 +212,12 @@ export function studioView(preset?: Mode | Layout): HTMLElement { // The stage keeps one 16:9 box from first paint: the placeholder, the preview and the audio view all fill it. const screenBox = h('div', { class: 'rv-stage-screen', 'data-stage-screen': '' }) const stateChip = h('span', { class: 'rv-rec-chip', 'data-rec-chip': '' }, h('span', { class: 'rec-dot', 'aria-hidden': 'true' }), h('span', { 'data-rec-chip-text': '' }, STATE_LABEL['idle']!)) - const meterSlot = h('div', { class: 'rv-stage-meter', 'data-stage-meter': '' }) const notes = notesPanel(life.signal) const counter = countdown() const asker = checkIn() const rewinder = rewindSheet() - const stage = h('div', { class: 'stage rv-stage', 'data-stage': '' }, screenBox, h('div', { class: 'rv-stage-top' }, stateChip), meterSlot, - notes.prompter, counter.el, asker.el, rewinder.el) + const stage = h('div', { class: 'stage rv-stage', 'data-stage': '' }, screenBox, h('div', { class: 'rv-stage-top' }, stateChip), + notes.prompter, counter.el, asker.el, rewinder.el, sound.stage) const placeholder = (): void => { const chosen = MODES.find((m) => m.layout === mode.value())! screenBox.replaceChildren(h('div', { class: 'rv-stage-empty' }, @@ -262,6 +264,11 @@ export function studioView(preset?: Mode | Layout): HTMLElement { return Math.max(0, end - take.startedAt - paused) } const marks = marksPanel(() => (session?.state === 'recording' || session?.state === 'paused' ? takeMs() : undefined), life.signal) + const script = studioScript({ + signal: life.signal, recording: () => session?.state === 'recording', takeMs, spaceTaken: () => mode.value() === 'presentation', + mark: (m) => marks.add(m.title, m.atMs, m.say), + }) + stage.append(script.stage) const say = (text: string): void => { status.textContent = text } const buttons = (): void => { @@ -269,6 +276,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { ready.disabled = Boolean(session) camera.disabled = mic.disabled = Boolean(session) mode.disable(Boolean(session)) + sound.lock(Boolean(session)) record.disabled = state !== 'ready' pause.disabled = state !== 'recording' && state !== 'paused' relabel(pause, state === 'paused' ? 'Resume' : 'Pause') @@ -310,16 +318,13 @@ export function studioView(preset?: Mode | Layout): HTMLElement { lastState = state } - const fillDevices = async (): Promise => { - const { cameras, mics } = await listDevices() - const keepCam = camera.value || loadSettings().cameraId - const keepMic = mic.value || loadSettings().micId - camera.replaceChildren(...cameras.map((d, i) => h('option', { value: d.deviceId }, d.label || `Camera ${i + 1}`))) - mic.replaceChildren(...mics.map((d, i) => h('option', { value: d.deviceId }, d.label || `Microphone ${i + 1}`))) - // The last devices chosen stay the defaults (R1-26), when they are still connected. - if (keepCam && cameras.some((d) => d.deviceId === keepCam)) camera.value = keepCam - if (keepMic && mics.some((d) => d.deviceId === keepMic)) mic.value = keepMic - } + // The lists refill on devicechange, on focus, on a permission grant and by Refresh devices (studio-devices-ui.ts); + // the current choice stays while it is connected, then the last one chosen (R1-26), then the system default. + const deviceRow = studioDevices({ + camera, mic, signal: life.signal, cameraInUse: () => layoutInfo(mode.value()).camera, + saved: () => { const s = loadSettings(); return { cameraId: s.cameraId, micId: s.micId } }, + }) + const fillDevices = (): Promise => deviceRow.fill() camera.addEventListener('change', () => saveSettings({ cameraId: camera.value })) mic.addEventListener('change', () => saveSettings({ micId: mic.value })) @@ -393,13 +398,16 @@ export function studioView(preset?: Mode | Layout): HTMLElement { cameraId: camera.value || undefined, micId: mic.value || undefined, cameraConstraints: cameraConstraints(q, camera.value || undefined), + micConstraints: sound.micConstraints(loadPrefs(), mic.value || undefined), }) rawStreams.push(...(Object.values(devices) as MediaStream[])) + const raw = { ...devices, ...(screen ? { screen } : {}) } // The plugins see each captured stream before it is previewed or recorded (effects, annotations, noise). for (const p of studioPlugins.all()) { if (devices.camera && p.camera) devices.camera = await p.camera(devices.camera, ctx) if (screen && p.screen) screen = await p.screen(screen, ctx) - if (devices.mic && p.mic) devices.mic = await p.mic(devices.mic, ctx) + // Voice master: nothing touches the microphone, no Effects chain and no noise filter. + if (devices.mic && p.mic && !sound.raw()) devices.mic = await p.mic(devices.mic, ctx) } const composedCamera = info.composed && place.value !== 'none' if (info.composed || tgt === 'region' && capture) { @@ -427,8 +435,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { screenBox.replaceChildren(preview(info.composed ? { screen: sources.screen } : sources, native)) cameraOn = true relabel(camToggle, 'Camera off') - meter = levelMeter(sources.mic, 'Your microphone level') - meterSlot.replaceChildren(icon('mic', 14), meter.el) + const delivered = await sound.attach({ raw, mic: sources.mic, system, quality: { quality: q, width: QUALITY[q].width, height: QUALITY[q].height } }) call = new HostCall( { fetch: async (after) => (await api.json<{ signals: { n: number; from: string; data: unknown }[] }>(`/api/rtc?after=${after}`, 'GET')).signals, @@ -439,7 +446,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { ) poll = setInterval(() => void refresh().catch(() => undefined), POLL_MS) await refresh() - say('Ready. Guests can join now.') + say(`Ready. Guests can join now.${delivered ? ` ${delivered}` : ''}`) } catch (error) { release() sources = {} @@ -468,11 +475,15 @@ export function studioView(preset?: Mode | Layout): HTMLElement { const id = session.id lastCheckIn = 0 const bits = QUALITY[quality.value as Quality].videoBits - const recorderFor = (kind: Kind, stream: MediaStream, label: string, source = ''): TrackRecorder => { + const uploadLine = (kind: Kind, label: string, source: string): { detail: HTMLElement; line: HTMLElement } => { const detail = h('span', { class: 'rv-upload-detail' }, 'starting') const line = h('li', { class: 'rv-upload', 'data-upload': source || kind }, icon(kind, 14), h('span', { class: 'rv-upload-kind' }, label), detail) uploadsEmpty.hidden = true uploads.append(line) + return { detail, line } + } + const recorderFor = (kind: Kind, stream: MediaStream, label: string, source = ''): TrackRecorder => { + const { detail, line } = uploadLine(kind, label, source) return new TrackRecorder( kind, stream, @@ -492,6 +503,16 @@ export function studioView(preset?: Mode | Layout): HTMLElement { } recorders = (Object.entries(sources) as [Kind, MediaStream][]).map(([kind, stream]) => recorderFor(kind, stream, KIND_LABEL[kind])) if (system) recorders.push(recorderFor('mic', system, 'System audio', 'system')) + let masterLine: { detail: HTMLElement; line: HTMLElement } | undefined + const master = sound.startTake({ + sessionId: id, takeMs, live: () => session?.state === 'recording', mark: (t, at) => marks.add(t, at), + onMasterState: (text, failed) => { + masterLine ??= uploadLine('mic', 'Microphone master (WAV)', 'master') + masterLine.detail.textContent = text + masterLine.line.classList.toggle('is-retrying', failed) + }, + }) + if (master) recorders.push(master) if (native) { for (const p of studioPlugins.all()) { const feed = p.nativeRecorder?.(pluginCtx(), id) @@ -501,6 +522,9 @@ export function studioView(preset?: Mode | Layout): HTMLElement { recorders.forEach((r) => r.start()) slideMarks = [] if (mode.value() === 'presentation' && slides.length) markSlide(0) + // Room tone first (Voice master): the take's words start after it, with the script's first paragraph when there is one. + const reading = sound.readingStartsAt() + if (!script.begin(reading) && reading > 0) marks.add('Take', reading) say('Recording') buttons() } @@ -573,6 +597,8 @@ export function studioView(preset?: Mode | Layout): HTMLElement { await Promise.allSettled(recorders.map((r) => r.stop())) recorders = [] await studioApi(`/api/sessions/${encodeURIComponent(id)}`, 'DELETE') + sound.resetTake() + script.reset() uploads.replaceChildren(uploadsEmpty) uploadsEmpty.hidden = false marks.keepBefore(0) @@ -611,7 +637,6 @@ export function studioView(preset?: Mode | Layout): HTMLElement { sources = {} session = undefined placeholder() - meterSlot.replaceChildren() say('Take discarded.') buttons() } @@ -631,7 +656,8 @@ export function studioView(preset?: Mode | Layout): HTMLElement { } const lost = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected') const failed = lost.length - say(failed ? `${failed} of your tracks did not finish sending (${(lost[0]!.reason as Error).message}); save keeps what arrived.` : 'Stopped. Save when the guests\' uploads are in.') + const clipped = sound.stopTake() + say(failed ? `${failed} of your tracks did not finish sending (${(lost[0]!.reason as Error).message}); save keeps what arrived. ${clipped}` : `Stopped. ${clipped} Save when the guests' uploads are in.`) await refresh().catch(() => undefined) } @@ -639,7 +665,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { if (!session) return save.disabled = true try { - const saved = await api.save(session.id, { title: title.value.trim() || session.title, summary: '', durationMs: takeMs() ?? 0, marks: marks.marks() }) + const saved = await api.save(session.id, { title: title.value.trim() || session.title, summary: '', durationMs: takeMs() ?? 0, marks: marks.marks(), capture: sound.capture() }) for (const p of studioPlugins.all()) { try { p.onState?.('saved', pluginCtx(), saved.id) } catch { /* a plugin must not break the studio */ } } void studioApi('/api/studio/state', 'PUT', { state: 'saved', layout: mode.value(), target: target.value, quality: quality.value, sessionId: saved.id, elapsedMs: Math.round(takeMs() ?? 0) }).catch(() => undefined) release() @@ -655,8 +681,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { poll = undefined call?.close() call = undefined - meter?.stop() - meter = undefined + sound.detach() compositor?.stop() compositor = undefined stopSources([...Object.values(sources), ...rawStreams, system]) @@ -744,7 +769,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { h('div', { class: 'rv-recbar-row' }, h('div', { class: 'rv-recbar-group' }, ready, record, pause, stop), h('span', { class: 'rv-timer', 'data-studio-clock': '' }, h('span', { class: 'rec-dot', 'aria-hidden': 'true' }), timer), - h('div', { class: 'rv-recbar-group rv-recbar-end' }, save), + h('div', { class: 'rv-recbar-group rv-recbar-end' }, sound.mini, save), ), h('div', { class: 'rv-recbar-row studio-tools', 'data-studio-tools': '' }, h('div', { class: 'rv-recbar-group' }, restart, cancel, rewind), @@ -765,7 +790,7 @@ export function studioView(preset?: Mode | Layout): HTMLElement { h('div', {}, h('h1', {}, 'Studio'), h('p', { class: 'rv-sub' }, 'Every source records to its own track and uploads as it goes.')), ), h('div', { class: 'studio-grid rv-studio' }, - h('div', { class: 'rv-studio-main' }, stage, recbar, tiles, marks.el), + h('div', { class: 'rv-studio-main' }, stage, sound.strip, recbar, tiles, marks.el), h('aside', { class: 'rv-studio-side' }, panel('Source', 'film', [ field('Title', title), @@ -774,11 +799,14 @@ export function studioView(preset?: Mode | Layout): HTMLElement { regionField, systemField, h('div', { class: 'rv-field-pair' }, cameraField, field('Microphone', mic)), + deviceRow.el, ], { 'data-studio-source': '' }), + sound.panel, h('details', { class: 'rv-panel rv-disclose', 'data-studio-scene': '' }, h('summary', { class: 'rv-panel-head' }, sicon('canvas', 14), h('span', { class: 'rv-panel-title' }, 'Canvas and slides'), h('span', { class: 'rv-chev', 'aria-hidden': 'true' }, icon('back', 14))), h('div', { class: 'rv-panel-body' }, slideBits, ...canvasBits)), notes.el, + script.panel, recover.el, guests.el, ...pluginPanels, diff --git a/web/src/voice-master.ts b/web/src/voice-master.ts new file mode 100644 index 0000000..7d84f61 --- /dev/null +++ b/web/src/voice-master.ts @@ -0,0 +1,70 @@ +/** + * The capture presets for the microphone. "Standard" is what a quick share wants: the browser's echo cancellation, + * noise suppression and gain as Effects sets them, the Effects chain, an Opus track. "Voice master" is what voice + * training, on-camera explainers and walkthroughs that will be mixed later want: every browser DSP off, no Web Audio + * chain, mono at 48 kHz, a lossless 24-bit WAV beside the Opus track and room tone first. The choice is kept on this + * computer (localStorage formrec.sound). Pure apart from the store; tests/voice-master.test.ts covers it. + */ + +export type SoundPreset = 'standard' | 'voice-master' + +export interface SoundSettings { + preset: SoundPreset + /** Voice master only: hold the first ROOM_TONE_MS quiet so the take starts with the room alone. */ + roomTone: boolean +} + +export const ROOM_TONE_MS = 8000 +export const MASTER_RATE = 48_000 +export const MASTER_BITS = 24 +export const MASTER_FILE = 'master-host-mic.wav' + +export const PRESET_LABEL: Record = { + standard: 'Standard (Opus, Effects apply)', + 'voice-master': 'Voice master (lossless WAV, no processing)', +} + +const KEY = 'formrec.sound' +export const SOUND_DEFAULTS: SoundSettings = { preset: 'standard', roomTone: true } + +/** The browser's three processing switches, as Effects keeps them. */ +export interface Dsp { echoCancellation: boolean; noiseSuppression: boolean; autoGainControl: boolean } + +/** getUserMedia's audio constraints for a preset. Voice master turns every switch off whatever Effects says. */ +export function micConstraints(preset: SoundPreset, dsp: Dsp, micId?: string): MediaTrackConstraints { + const device = micId ? { deviceId: { exact: micId } } : {} + if (preset === 'voice-master') { + return { + echoCancellation: false, noiseSuppression: false, autoGainControl: false, + channelCount: { ideal: 1 }, sampleRate: { ideal: MASTER_RATE }, sampleSize: { ideal: MASTER_BITS }, ...device, + } + } + return { echoCancellation: dsp.echoCancellation, noiseSuppression: dsp.noiseSuppression, autoGainControl: dsp.autoGainControl, channelCount: 1, ...device } +} + +/** Only well-formed values survive. */ +export function cleanSound(raw: unknown): SoundSettings { + const r = (raw && typeof raw === 'object' ? raw : {}) as Record + return { + preset: r['preset'] === 'voice-master' ? 'voice-master' : 'standard', + roomTone: typeof r['roomTone'] === 'boolean' ? r['roomTone'] : SOUND_DEFAULTS.roomTone, + } +} + +export function loadSound(): SoundSettings { + try { + return cleanSound(JSON.parse(localStorage.getItem(KEY) ?? '{}')) + } catch { + return { ...SOUND_DEFAULTS } + } +} + +export function saveSound(change: Partial): SoundSettings { + const next = cleanSound({ ...loadSound(), ...change }) + try { + localStorage.setItem(KEY, JSON.stringify(next)) + } catch { + // Not kept on this computer. + } + return next +} diff --git a/web/src/wav-recorder.ts b/web/src/wav-recorder.ts new file mode 100644 index 0000000..95fb62b --- /dev/null +++ b/web/src/wav-recorder.ts @@ -0,0 +1,70 @@ +/** + * The Voice master's lossless track: every sample the level engine's worklet hands over, as 24-bit PCM in a WAV, + * uploaded in two-second chunks through the same ChunkUploader as the other tracks (to the studio feature's master + * route, src/studio/master.ts). WebKit's MediaRecorder cannot write PCM, so this does not use one. Started, paused, + * resumed and stopped with the take like a TrackRecorder; a paused stretch is left out, as the recorders leave it out. + */ +import { CHUNK_MS, withRetries } from './capture.js' +import type { LevelEngine } from './level-engine.js' +import { ChunkUploader, type UploadState, type UploadTarget } from './uploader.js' +import { encodePcm24, wavHeader } from './wav.js' +import { MASTER_BITS } from './voice-master.js' + +export class WavRecorder { + readonly uploader: ChunkUploader + private pending: Float32Array[] = [] + private pendingSamples = 0 + private samples = 0 + private state: 'idle' | 'recording' | 'paused' | 'stopped' = 'idle' + private unlisten: () => void = () => undefined + private readonly chunkSamples: number + + constructor(private readonly engine: LevelEngine, target: () => Promise, onState: (s: UploadState) => void) { + const settled = withRetries(target) + settled.catch(() => undefined) // reported through the uploader's state + this.uploader = new ChunkUploader(settled, onState) + this.chunkSamples = Math.round((engine.sampleRate * CHUNK_MS) / 1000) + } + + start(): void { + if (this.state !== 'idle') return + this.state = 'recording' + this.uploader.push(new Blob([wavHeader({ sampleRate: this.engine.sampleRate, channels: 1, bitsPerSample: MASTER_BITS })], { type: 'audio/wav' })) + this.unlisten = this.engine.listen((block) => { + if (this.state !== 'recording') return + this.pending = [...this.pending, block] + this.pendingSamples += block.length + this.samples += block.length + if (this.pendingSamples >= this.chunkSamples) this.flush() + }) + } + + pause(): void { + if (this.state === 'recording') this.state = 'paused' + } + + resume(): void { + if (this.state === 'paused') this.state = 'recording' + } + + /** Send what is left and end the master; resolves with its length in ms. */ + async stop(): Promise { + if (this.state === 'idle') return 0 + this.state = 'stopped' + this.unlisten() + this.flush() + const durationMs = Math.round((this.samples / this.engine.sampleRate) * 1000) + await this.uploader.finish(durationMs) + return durationMs + } + + private flush(): void { + if (this.pendingSamples === 0) return + const all = new Float32Array(this.pendingSamples) + let at = 0 + for (const b of this.pending) { all.set(b, at); at += b.length } + this.pending = [] + this.pendingSamples = 0 + this.uploader.push(new Blob([encodePcm24(all)], { type: 'audio/wav' })) + } +} diff --git a/web/styles/levels.css b/web/styles/levels.css new file mode 100644 index 0000000..5880c6b --- /dev/null +++ b/web/styles/levels.css @@ -0,0 +1,91 @@ +/* + * The input level meters (web/src/meter.ts dbMeter), the studio's Sound panel, room tone and script overlays + * (studio-sound.ts, studio-script.ts) and the player's Capture panel (capture-player.ts). Tokens only. Every box has its + * final size from the first frame; only transforms, attributes and text change, so nothing shifts. + */ +.rv { + --lv-h: 14px; + --lv-h-compact: 8px; + --lv-w-compact: 96px; + --lv-read-w: 5ch; + --lv-quiet-fill: color-mix(in srgb, var(--warn) 22%, transparent); + --lv-band-fill: color-mix(in srgb, var(--ok) 34%, transparent); + --lv-red-fill: color-mix(in srgb, var(--bad) 40%, transparent); + --lv-hold-ink: var(--text-primary); + --lv-strip-h: 92px; + --lv-script-h: 30%; +} +.rv .rv-lv { --lv-quiet: .6; --lv-band-lo: .7; --lv-band-hi: .8; --lv-red: .95; } +.rv .rv-lv-bar { position: relative; display: block; overflow: hidden; border-radius: var(--radius-sm); background: var(--meter-track); } +.rv .rv-lv.is-large .rv-lv-bar { height: var(--lv-h); } +.rv .rv-lv.is-compact .rv-lv-bar { width: var(--lv-w-compact); height: var(--lv-h-compact); flex: none; } +.rv .rv-lv-zones { + position: absolute; inset: 0; + background: linear-gradient(to right, + var(--lv-quiet-fill) 0 calc(var(--lv-quiet) * 100%), + transparent calc(var(--lv-quiet) * 100%) calc(var(--lv-band-lo) * 100%), + var(--lv-band-fill) calc(var(--lv-band-lo) * 100%) calc(var(--lv-band-hi) * 100%), + transparent calc(var(--lv-band-hi) * 100%) calc(var(--lv-red) * 100%), + var(--lv-red-fill) calc(var(--lv-red) * 100%) 100%); +} +.rv .rv-lv-fill { position: absolute; inset: 0; background: var(--text-secondary); transform: scaleX(0); transform-origin: left center; will-change: transform; opacity: .85; } +.rv .rv-lv[data-zone="quiet"] .rv-lv-fill { background: var(--warn); } +.rv .rv-lv[data-zone="target"] .rv-lv-fill { background: var(--ok); } +.rv .rv-lv[data-zone="red"] .rv-lv-fill { background: var(--bad); } +.rv .rv-lv-hold { position: absolute; inset: 0; transform: translateX(-100%); will-change: transform; pointer-events: none; } +.rv .rv-lv-hold-mark { position: absolute; top: 0; right: 0; width: 2px; height: 100%; background: var(--lv-hold-ink); } +.rv .rv-lv-read { display: inline-block; width: var(--lv-read-w); text-align: right; font: 600 var(--fs-12)/1 var(--mono); font-variant-numeric: tabular-nums; color: var(--text-primary); } +.rv .rv-lv-unit { font-size: var(--fs-11); color: var(--text-muted); } +.rv .rv-lv-clip { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--ctl-sm); padding: 0 var(--space-2); border-radius: var(--radius-pill); font: 600 var(--fs-11)/1 var(--mono); font-variant-numeric: tabular-nums; } +.rv .rv-lv-count { display: inline-block; min-width: 3ch; text-align: right; } +.rv .rv-lv-led { width: 10px; height: 10px; border-radius: var(--radius-pill); background: var(--meter-track); } +.rv .rv-lv[data-lit="true"] .rv-lv-led { background: var(--bad); box-shadow: 0 0 0 2px var(--rec-wash); } +.rv .rv-lv[data-lit="true"] .rv-lv-clip { color: var(--bad); border-color: var(--bad); } + +.rv .rv-lv-strip { display: flex; flex-direction: column; height: var(--lv-strip-h); padding: 6px var(--space-3); background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-lg); box-sizing: border-box; } +.rv .rv-lv.is-large { display: grid; gap: var(--space-1); } +.rv .rv-lv-head { display: flex; align-items: center; gap: var(--space-3); height: var(--ctl-sm); } +.rv .rv-lv-title { display: inline-flex; align-items: center; gap: var(--space-1); font-size: var(--fs-12); font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: .04em; } +.rv .rv-lv-readout { display: inline-flex; align-items: baseline; gap: var(--space-1); margin-left: auto; } +.rv .rv-lv-scale { position: relative; display: block; height: var(--fs-11); font: var(--fs-10)/1 var(--mono); color: var(--text-muted); } +.rv .rv-lv-tick { position: absolute; top: 0; left: calc(var(--at) * 100%); transform: translateX(-50%); } +.rv .rv-lv-tick[data-db="0"] { transform: translateX(-100%); } +.rv .rv-lv-tick[data-db="-18"], .rv .rv-lv-tick[data-db="-12"] { color: var(--ok); } +.rv .rv-lv-hint { margin: 0; height: 1.4em; font-size: var(--fs-12); line-height: 1.4; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.rv .rv-lv[data-hint="quiet"] .rv-lv-hint { color: var(--warn); } +.rv .rv-lv[data-hint="loud"] .rv-lv-hint { color: var(--bad); } +.rv .rv-lv[data-hint="report"] .rv-lv-hint { color: var(--text-primary); } + +.rv .rv-lv.is-compact { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--ctl); padding: 0 var(--space-2); border-radius: var(--radius-md); background: var(--bg-input); color: var(--text-secondary); } +.rv .rv-lv.is-compact .rv-lv-clip { height: var(--ctl-xs); padding: 0 var(--space-1); } + +/* The Sound panel: its notes reserve two lines each, so a check result or a camera note arriving moves nothing. */ +.rv .rv-sound-note, .rv .rv-sound-line { margin: 0; min-height: 2.8em; max-height: 2.8em; overflow: hidden; } +.rv .rv-sound-line[data-advice="up"], .rv .rv-sound-line[data-advice="silent"] { color: var(--warn); } +.rv .rv-sound-line[data-advice="down"] { color: var(--bad); } +.rv .rv-sound-line[data-advice="ok"] { color: var(--ok); } +.rv .rv-sound-check { width: 140px; } +[data-sound-roomtone-field].is-off { opacity: .45; pointer-events: none; } + +/* Room tone, over the stage while the first seconds record. */ +.rv .studio-roomtone { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: var(--space-2); background: var(--veil); color: var(--veil-ink); font-size: var(--fs-20); z-index: var(--studio-z-overlay); visibility: hidden; pointer-events: none; } +.rv .studio-roomtone[data-shown="true"] { visibility: visible; } +.rv .studio-roomtone-count { font: 600 var(--studio-count-size)/1 var(--mono); font-variant-numeric: tabular-nums; } + +/* Script mode: one paragraph at a time in a fixed band at the foot of the stage. */ +.rv .studio-script { position: absolute; left: var(--space-4); right: var(--space-4); bottom: var(--space-4); height: var(--lv-script-h); display: grid; grid-template-rows: auto 1fr; gap: var(--space-1); padding: var(--space-2) var(--space-3); border-radius: var(--radius-lg); background: var(--veil); color: var(--veil-ink); z-index: var(--studio-z-prompter); visibility: hidden; overflow: hidden; } +.rv .studio-script[data-shown="true"] { visibility: visible; } +.rv .studio-script-head { display: flex; justify-content: space-between; font: var(--fs-11)/1.4 var(--mono); opacity: .8; } +.rv .studio-script-text { margin: 0; font-size: var(--fs-20); line-height: 1.4; overflow: auto; } + +/* The player's Capture panel. */ +.rv .rv-cap { display: grid; gap: var(--space-2); font-size: var(--fs-12); } +.rv .rv-cap-list, .rv .rv-cap-files { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-1); } +.rv .rv-cap-row { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: var(--space-2); } +.rv .rv-cap-name { color: var(--text-secondary); overflow-wrap: anywhere; } +.rv .rv-cap-value { overflow-wrap: anywhere; } +.rv .rv-cap-head { margin: var(--space-2) 0 0; font-size: var(--fs-12); text-transform: uppercase; letter-spacing: .04em; color: var(--text-secondary); } +.rv .rv-cap-file { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 0 var(--space-2); align-items: center; } +.rv .rv-cap-file-name { font-family: var(--mono); overflow-wrap: anywhere; } +.rv .rv-cap-file-what { grid-column: 2; color: var(--text-secondary); } +.rv .rv-cap-exports { flex-wrap: wrap; gap: var(--space-2); } diff --git a/web/styles/phone-capture.css b/web/styles/phone-capture.css new file mode 100644 index 0000000..08f08a1 --- /dev/null +++ b/web/styles/phone-capture.css @@ -0,0 +1,43 @@ +/* The studio's Phone panel, its stage overlay and the Phone layout dialog (web/src/features/phone-capture.ts, issue + #7). Every part has its room before the server answers: rows have a fixed height, the notes reserve their lines, + and parts that belong to one source are kept in place and dimmed instead of added or removed. */ +.phone-cap { + --phone-cap-row-h: calc(var(--fs-13) * 1.5 + var(--fs-12) * 1.5 + var(--space-2) * 2); + --phone-cap-note-h: calc(var(--fs-12) * 1.5 * 2); +} +.phone-cap .phone-cap-list { display: flex; flex-direction: column; gap: var(--space-1); } +.phone-cap .phone-cap-row { + display: flex; flex-direction: column; align-items: flex-start; justify-content: center; gap: 0; + min-height: var(--phone-cap-row-h); padding: var(--space-2) var(--space-3); + border: 1px solid var(--border-light); border-radius: var(--radius); background: var(--bg-input); color: var(--text); + text-align: left; cursor: pointer; +} +.phone-cap .phone-cap-row strong { font-size: var(--fs-13); } +.phone-cap .phone-cap-row span { font-size: var(--fs-12); color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; } +.phone-cap .phone-cap-row[aria-checked="true"] { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } +.phone-cap .phone-cap-row[data-blocked="true"] { cursor: default; } +.phone-cap .phone-cap-row[data-blocked="true"] strong { color: var(--text-muted); } +.phone-cap .phone-cap-row[data-blocked="true"] span { white-space: normal; } +.phone-cap .phone-cap-file, +.phone-cap .phone-cap-options { display: flex; flex-direction: column; gap: var(--space-2); margin-top: var(--space-2); } +.phone-cap .phone-cap-file[data-shown="false"], +.phone-cap .phone-cap-options[data-shown="false"] { opacity: 0.45; pointer-events: none; } +.phone-cap .phone-cap-file-name { font-size: var(--fs-12); color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.phone-cap .phone-cap-switch { display: flex; align-items: center; gap: var(--space-2); font-size: var(--fs-12); } +.phone-cap .phone-cap-touch, +.phone-cap .phone-cap-status { margin: var(--space-2) 0 0; min-height: var(--phone-cap-note-h); font-size: var(--fs-12); color: var(--text-muted); } +.phone-cap .phone-cap-actions { display: flex; flex-wrap: wrap; gap: var(--space-2); margin-top: var(--space-2); } +.phone-cap .phone-cap-missing { margin: var(--space-2) 0 0; padding-left: var(--space-4); font-size: var(--fs-12); color: var(--text-muted); } +.phone-cap .phone-cap-missing li + li { margin-top: var(--space-1); } +.phone-cap .phone-cap-foot { margin: var(--space-3) 0 0; font-size: var(--fs-12); color: var(--text-muted); } +.phone-cap .phone-cap-hidden { display: none; } + +.rv .phone-cap-stage { position: absolute; inset: 0; z-index: var(--z-raised); display: flex; align-items: center; justify-content: center; background: var(--media-bg); } +.rv .phone-cap-stage[data-phone-cap-stage="off"] { display: none; } +.rv .phone-cap-stage-video { width: 100%; height: 100%; object-fit: contain; } +.rv .phone-cap-stage[data-phone-cap-stage="device"] .phone-cap-stage-video { display: none; } +.rv .phone-cap-stage[data-phone-cap-stage="file"] .phone-cap-stage-card { display: none; } + +.phone-cap-dialog { max-width: min(92vw, 420px); padding: var(--space-4); border: 1px solid var(--border-light); border-radius: var(--radius-lg); background: var(--bg-secondary); color: var(--text); } +.phone-cap-dialog .phone-cap-layouts { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-2); margin: var(--space-3) 0; } +.phone-cap-dialog .phone-cap-status { min-height: calc(var(--fs-12) * 1.5 * 2); font-size: var(--fs-12); color: var(--text-muted); } diff --git a/web/styles/studio.css b/web/styles/studio.css index ad7cb02..a2970f8 100644 --- a/web/styles/studio.css +++ b/web/styles/studio.css @@ -28,6 +28,12 @@ .rv .studio-region.is-off, .rv .studio-inline.is-off { opacity: .45; pointer-events: none; } .rv .studio-inline { display: inline-flex; align-items: center; gap: var(--space-2); font-size: var(--fs-12); color: var(--text-secondary); } .rv .studio-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); } +/* Refresh devices and its status line under the pickers: the line keeps two lines' height, so a message never moves the panel. */ +.rv .studio-devices { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: var(--space-2); } +.rv .studio-devices-refresh { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--ctl-sm); padding: 0 var(--space-2); font-size: var(--fs-12); white-space: nowrap; } +.rv .studio-devices-refresh[aria-busy="true"] { cursor: progress; } +.rv .studio-devices-line { margin: 0; min-height: 2.9em; max-height: 2.9em; overflow: hidden; font-size: var(--fs-11); } +.rv .studio-devices-line[data-permission="refused"] { color: var(--warn); } .rv .studio-mono { font-family: var(--mono); font-size: var(--fs-11); color: var(--text-secondary); } .rv .studio-icon-btn { display: inline-grid; place-items: center; width: var(--ctl-sm); height: var(--ctl-sm); padding: 0; border-radius: var(--radius); } diff --git a/web/views.css b/web/views.css index 0ae4f42..0de54aa 100644 --- a/web/views.css +++ b/web/views.css @@ -181,11 +181,6 @@ .rv[data-state="recording"] .rv-stage { border-color: var(--rec); } @keyframes rv-pulse { 50% { opacity: .35; } } @media (prefers-reduced-motion: reduce) { .rv[data-state="recording"] .rec-dot { animation: none; } } -.rv .rv-stage-meter { position: absolute; left: var(--space-3); bottom: var(--space-3); display: flex; align-items: center; gap: 6px; width: 200px; height: var(--ctl-sm); padding: 0 var(--space-2); border-radius: var(--radius-pill); background: var(--veil); color: var(--veil-ink); } -.rv .rv-stage-meter:empty { visibility: hidden; } -.rv .rv-meter { flex: 1; min-width: 0; } -.rv .rv-meter-track { display: block; height: 6px; border-radius: var(--radius-pill); background: var(--meter-track); overflow: hidden; } -.rv .rv-meter-fill { display: block; width: 100%; height: 100%; background: var(--ok); transform: scaleX(0); transform-origin: left center; will-change: transform; } /* ── tiles: a reserved strip; a guest joining fills a slot, nothing moves ── */ .rv .rv-tiles { display: flex; gap: var(--space-2); min-height: var(--tile-h); margin-top: var(--space-3); overflow-x: auto; overflow-y: hidden; }