diff --git a/.env.example b/.env.example index f874370f..2b608bc4 100644 --- a/.env.example +++ b/.env.example @@ -55,6 +55,7 @@ MEDIAMTX_RTSP_BASE_URL=rtsp://mediamtx:8554 # fleet: RTSP base the workers read from (private address of MediaMTX) and the capability workers must advertise # (FFFLEET_PROBE=mediamtx=:8554 on the worker gives net:mediamtx). Empty = any worker. # MEDIAMTX_RTSP_FLEET_BASE_URL= +# MEDIAMTX_RTMP_FLEET_BASE_URL= # same for the RTMP address output steps publish to # MEDIAMTX_FLEET_REQUIRES=net:mediamtx # RTMP base URL — where the processing ffmpeg pushes its single output back into MediaMTX. # MediaMTX then fans out via runOnPublish instead of the ffmpeg tee muxer. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index a39c54a4..be199408 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -286,6 +286,8 @@ Used when `RADIO_HLS_SOURCE=mediamtx` or when MediaMTX manages RTMP paths. | `MEDIAMTX_HOOK_SECRET` | _(unset)_ | Shared secret for `POST /internal/mediamtx/path` (header `x-lcyt-hook-secret`). The route is closed while empty. Keep `/internal` off the public proxy | | `MEDIAMTX_FANOUT_POLL_MS` | `0` | Runner mode: reconcile poll against the MediaMTX API (0 = 2 s without a hook secret, 30 s with one) | | `MEDIAMTX_RTSP_FLEET_BASE_URL` | _(unset)_ | RTSP address fleet workers read from when they are on another host (private address of MediaMTX); empty = `MEDIAMTX_RTSP_BASE_URL` | +| `MEDIAMTX_RTMP_FLEET_BASE_URL` | _(unset)_ | RTMP address fleet output steps publish to when they run on another host (private address of MediaMTX); empty = `MEDIAMTX_RTMP_BASE_URL` | +| `MAX_GROUP_MEMBERS` | `4` | Most outputs one lock group may render in the same ffmpeg (each is its own x264 encode) | | `MEDIAMTX_FLEET_REQUIRES` | _(unset)_ | Capabilities fan-out jobs require, e.g. `net:mediamtx` (worker started with `FFFLEET_PROBE=mediamtx=:8554`) | `runner` mode is new (2026-10-13) and has not been run against a real MediaMTX or fleet; `hook` stays the default until it has. Plan: `docs/plans/plan_mediamtx_fanout_fleet.md`. diff --git a/docs/PLANS.md b/docs/PLANS.md index 86ccbb16..5948ecb1 100644 --- a/docs/PLANS.md +++ b/docs/PLANS.md @@ -83,6 +83,7 @@ Where an implemented plan has known unbuilt parts (deferred phases, optional add | [plan_ingest_feeds.md](plans/plan_ingest_feeds.md) | Ingest Feeds — Arbitrary Named Ingestion, Egress, and Mixing | **Implemented.** Generalizes RTMP ingestion from the fixed 'one Video, one DSK' model to arbitrary named, independently-relayable feeds (a new prod_cameras control_type: 'rtmp'), with egress able to select any of them (source_feed_id since plan_feeds_devices.md PR 7) and no cap on target count. Supersedes the earlier, narrower plan_monitors.md. Admin-configurable relay quota and a real lcyt-mixer live Preview bus are explicit non-goals/future work. | | [plan_feeds_devices.md](plans/plan_feeds_devices.md) | Feeds and Devices | **Implemented (PRs 1-9 merged).** Splits the Setup Hub's Ingestion card into Feeds (new `prod_feeds` table: generic/camera/dsk kinds, free label, optional device link) and Devices (cameras, mixers, encoders). Replaces storing named feeds as `control_type: 'rtmp'` cameras; migrates existing ones without changing any key. | | [plan_egress_outputs.md](plans/plan_egress_outputs.md) | Egress Outputs | **Implemented (2026-10-20): PRs 1-5 (#401, #403-#406) and the legacy composite DSK move (#407) merged; nothing verified against a real MediaMTX or fleet.** Planned for later (section 8): PiP layer (premade PNG masks and frames), caption targets per output, per-output delay, STT per audio feed. Feeds stay a plain list of what comes in; an *output* is a named pipeline `source (feed or output) -> DSK viewports -> crop -> destinations`, so each output has its own editing and outputs can chain (Program with DSK, Vertical = crop of Program). Mixing stays in the mixer; audio from a separate audio feed can replace an output's sound; a server-side mixer and an audio mixer are scheduled for later. Five sequential PRs. | +| [plan_locked_outputs.md](plans/plan_locked_outputs.md) | Locked outputs | **v1 built (2026-10-25): DSK and plain outputs only.** Outputs the user locks together are rendered by one ffmpeg (shared composite, one encode per member, written to each member's own MediaMTX path so the relay fan-out stays as is). Crop in a group, a per-group ownership lease and direct mode (tee straight to targets) are not built. Nothing verified against a real MediaMTX or fleet. | | [plan_broadcast_platform_sync_phases.md](plans/plan_broadcast_platform_sync_phases.md) | Phase Plan — Broadcast Platform Sync | Executable 7-phase sequencing for the plan below: foundation → adapter → OAuth → lifecycle routes → wiring → frontend → docs. Records the grounding research that settled two of the source plan's open questions (base64-in-JSON thumbnails, mirroring the legacy `youtube_broadcast_id`). | | [plan_broadcast_platform_sync.md](plans/plan_broadcast_platform_sync.md) | Broadcast Platform Sync — YouTube Live Scheduling, Thumbnails & Stats (Facebook Live, deferred) | Implemented: new `lcyt-platforms` plugin — AES-256-GCM secrets at rest (`PLATFORM_CREDENTIAL_KEY`, the repo's first), server-side Authorization Code OAuth with lazy refresh, schedule/thumbnail/go-live/end tied to `broadcasts`, all three stats tiers, and a quota-aware stats poller publishing `platform.*`. The browser-only surface it replaces (`youtubeAuth.js`, `youtubeApi.js`, `YouTubeTab.jsx`, `GET /youtube/config`) is **deleted**, not deprecated. Went beyond the written plan on one point: multi-channel-per-project shipped (uniqueness on `(api_key, platform, external_account_id)`, credential selector threaded through every route and the UI) rather than being deferred. **Not done:** the Facebook adapter is a non-wired interface skeleton only (Meta App Review is the real long pole); `PLATFORM_CREDENTIAL_KEY` rotation tooling; recurrence-aware sync; automated pre-broadcast checks. **Unverified:** per an explicit scope decision, nothing was tested against the live YouTube API — request shapes are pinned by stubbed-`fetch` tests against the published contracts, and a real-channel smoke test is still owed. | | [plan_project_roles.md](plans/plan_project_roles.md) | Project Roles & Visibility — Setup/Assets/Production Access Tiers | Follow-up to `plan_team_org_backend.md`. Design fully resolved 2026-07-26: a 5-role project vocabulary (owner/admin/editor/operator/viewer, kept separate from the org's owner/admin/member vocabulary), a per-project visibility setting with a configurable org-baseline ceiling (viewer/editor, default viewer) plus an unconditional org-admin override to project `admin` on team-visible projects, page-scoped write gates (Setup = explicit admin/owner only, Assets = editor+, Production = the new `operator` role), and existing `'member'` rows migrating to `editor`. UI home is the existing `ProjectSettingsPage.jsx` (Summary/Team tabs) — no new page. **Implemented** 2026-07-26–2026-07-31 via the phase plan below: schema/resolver/gate middleware, per-plugin route gating (lcyt-backend, lcyt-dsk, lcyt-connectors, lcyt-production), and the `ProjectSettingsPage.jsx` UI (visibility toggle, ceiling picker, 5-role member picker). `GET /keys`'s user-scoped listing was fixed 2026-07-31 to return every accessible project (owned, explicitly-membered, or org-baseline-accessible) with its real effective level. `lcyt-rtmp`'s ingestion/stream/radio-config/crop routes and the `icons.js`/`lcyt-files` storage-config routes — initially left ungated on an auth-model blocker (they only had the plain ephemeral-session middleware, which can't resolve a `userId`) — were migrated onto `scopedAuth()`/`requireProjectRole('setup')` 2026-09-10; see `CONSIDER.md`'s resolved entry for the migration recipe. Three more gaps closed the same day: the DSK live-graphics-operate routes (activate/broadcast/renderer start-stop/graphics-push) are now gated at a new `'production'`-tier `requireProduction()` in `dsk-templates.js` (fails open for the plain caption-session JWT `DskControlPage.jsx`'s sidebar mode uses, closed for a real per-user JWT below operator); `bridge.js`'s `GET /instances/:id/env` now requires `'setup'` explicitly despite being a GET, closing the plaintext-token-disclosure gap; and `CameraStreamPage.jsx`/`LcytMixerPage.jsx`'s WHIP/kiosk routes now accept (and enforce ownership on) the existing device-role JWT when a device is logged in, while staying open for a bare capability URL with none. **Not done:** none of `plan_project_roles.md`'s named gaps remain — see `CONSIDER.md` for lower-priority follow-ups (the shared bypass-middleware refactor for the "unauthenticated despite opts.auth" carve-out pattern, and the broader auth/token-model unification, both explicitly deferred to a separate session). | diff --git a/docs/plans/plan_locked_outputs.md b/docs/plans/plan_locked_outputs.md new file mode 100644 index 00000000..5416d997 --- /dev/null +++ b/docs/plans/plan_locked_outputs.md @@ -0,0 +1,143 @@ +# Locked outputs: several outputs, one ffmpeg + +**Status (2026-10-25): v1 built in one PR (DSK and plain outputs; crop and direct mode left out), nothing verified against a real MediaMTX, fleet or two-instance run.** + +What was built, and where it differs from the plan below: +- `src/output-group-plan.js` (`buildGroupArgs`, pure): one ffmpeg, members with the same leading viewports share the composite and `split`; `buildDskStepArgs` is its one-member case, so an unlocked output is unchanged. +- `output_groups` table and `outputs.group_id` (both schemas, Postgres migration `0015_output_groups.sql`; the group has no `enabled`/`preset` column, dissolving a group is the way to unlock). Lock rules live in `db/outputs.js` (`createGroup`, `checkGroupMembers`, `dissolveGroupIfSmall`): same input path, no crop, same project, at most `outputs.max_group_members` (`MAX_GROUP_MEMBERS`, default 4), a group of fewer than two dissolves. +- `OutputStepManager` groups the DSK steps of one group that read the same input into one process (`desiredSteps` returns units). A group counts as **one step** against `MAX_OUTPUT_STEPS` (the plan counted distinct filter steps; one process is simpler and the member cap bounds the encodes). A graph change (viewport ready or gone, member added) restarts the whole group once. +- `MEDIAMTX_RTMP_FLEET_BASE_URL` (`mediamtx.rtmp_fleet_base_url`): the RTMP base fleet steps publish to, like the RTSP one. +- API: `GET/POST /outputs/groups`, `DELETE /outputs/groups/:id`, `PATCH /outputs/:id { groupId }`. UI: "Render together with" on the output edit dialog of the Outputs card. +- Not built: crop in a group (later phase, section 4.3), ownership lease per group (the step layer still has none, as before), lifecycle wanted-members rule, direct mode (tee straight to destinations, see "Possible future work"). + +**Possible future work: direct mode.** The group's ffmpeg could also tee each member straight to its targets (`[f=flv:onfail=ignore]` per target), skipping the MediaMTX hop; a dropped target is retried by a small separate fan-out. It saves one process and one local hop per member, not CPU, and needs the member path anyway for preview, recording and the retry. Decide after measuring the hop on the Windows stack. A related small follow-up: `onfail=ignore` on the fan-out tee targets so one dropping target does not blink the others. + +--- + +## Original plan (2026-10-20) +Status: planning only, nothing built. Asked by Juha on 2026-10-20 ("outputs should be able to be locked to each other, meaning that the same ffmpeg process handles both"). Builds on the merged egress outputs (#401, #403 to #406; plan `egress-outputs-plan-2026-10-19.md`), the three views of one broadcast (broadcast lifecycle plan, section 3, PR #396), MediaMTX fan-out via fleet (#362, `MEDIAMTX_FANOUT_MODE`) and per-key ownership (`ownership.js`). Checked against `live-captions-yt` main at `18543de`; the legacy DSK move PR #407 was not read, so section 6 step 0 re-checks it. + +## 1. What "locked" means + +Today each output step is its own ffmpeg: DSK step `out--dsk` (`OutputStepManager`, `output-steps.js`), crop `-crop` or `out--crop` (`CropManager`). An output built on another output reads the previous step back from MediaMTX over RTSP. Example: Program (feed + DSK) and Vertical (Program + crop) are two ffmpeg runs, two decodes, one RTSP hop between them. + +A **lock group** is a set of outputs that share one root input and are compiled into **one ffmpeg process**: decode once, build one filter graph with `split`, and write one encoded rendition per member. + +``` +-i rtsp://mtx/ -i rtsp://mtx/dsk/__lower3rd +[1:v]colorkey=..[k]; [k][0:v]..overlay[dsk]; [dsk]split=2[a][b] +[b]crop@vcrop=..,scale=1080:1920[vert] +-map [a] -map 0:a -c:v libx264 .. -f flv rtmp://mtx/out-A-dsk +-map [vert] -map 0:a -c:v libx264 .. -f flv rtmp://mtx/out-V-crop +``` + +Why Juha would want it, in order of value: +1. **Sync.** In a chain, Vertical trails Program by the hop (encode, MediaMTX, RTSP read, encode), probably one to two seconds (not measured). In a lock group both renditions come from the same decoded frame with the same timestamps. That matters for the same congregation watching on two screens, and for captions, which LCYT sends per stream key with one delay setting. +2. **CPU.** One decode, one shared DSK composite and colorkey instead of one per output. Matters on Hetzner burst workers and on the Windows laptops. +3. **One fleet job, one failure domain, one owner.** One lease per group instead of one per step (the step manager has no ownership yet, see 5). +4. **One restart rule.** The group restarts as a whole when its graph changes, so members never run on different versions of the DSK set. + +What it costs: members start, stop and blip together; a graph change in one restarts all (crop position moves stay live, see 4.3); one process uses more CPU than any single step, so it needs a bigger slot. + +## 2. Decisions (recommended; change if you disagree) + +0. **Manual only, crop out of v1 (Juha, 2026-10-20).** The user decides what is grouped; nothing is locked or suggested automatically. Crop is usually not locked with anything, so v1 groups are DSK and plain outputs only. An output with `crop_enabled` is refused by the eligibility check. Sections 4.3 (crop commands through the group's stdin) and the crop parts of 4.1 and 9 describe a later phase, built only if Juha asks for it; v1 needs no shared stdin. + +1. **Lock = a group of outputs, not a new kind of output.** Outputs keep ids, names, relay slots and broadcast membership. Locking only changes which process renders them. Unlocking returns each output to its own step process with no data change. +2. **The group writes each member's normal MediaMTX path** (`out--dsk`, `out--crop` or `-crop` for the default crop). Relay slots, preview, `outputSourcePath`, the broadcast outputs and the fan-out (`FanoutSupervisor`, `-c copy` tee) stay exactly as built. The group does **not** write to YouTube itself. Reason: a YouTube target that rejects or stalls would kill a shared process in ffmpeg (a failed muxer output ends the run), and it would couple the two destinations. With MediaMTX in between, the shared process only fails on local publishing, and destination failures stay in the per-path fan-out ffmpegs as today. The price is one RTMP hop on the local machine per member, small compared with the sync gain. +3. **Eligibility rule (checked on write):** all members must resolve to the **same root input path** (same feed, or the same upstream output outside the group) and be in the same project. Audio can differ per member (`audio_source`, see 4.4). Unrelated feeds are refused: locking gains nothing for them and would only couple their failures. +4. **Plain members allowed:** a member with no step (just the feed) can be in a group and is written as `-c copy` of the root input (video and audio). That gives a "raw + processed in one process" case, though the plain case needs no lock (it is already a fan-out), so the UI offers locking only when at least two members have a step. +5. **Out of v1:** CEA-708 (uses ffmpeg stdin for the SRT pipe; crop already uses stdin for commands, one process has one stdin), per-slot transcode renditions (the relay manager has its own multi-encode tee), several crops fed by different crop source maps in one group (see 4.3), cross-feed groups. + +## 3. Data model (both Prisma schemas, `sqlite/schema.sql`, next Postgres migration after the current highest) + +- New table `output_groups`: `id` (`lg-<12hex>`), `owner_api_key`, `name`, `enabled` (0/1, default 1), `preset` TEXT NULL (x264 preset override, default as steps), `created_at`. Index on `owner_api_key`. +- `outputs.group_id` TEXT NULL (references `output_groups.id`, on delete set null). A group with fewer than two members is dissolved automatically (the row is deleted; the lone member returns to its own step). +- No change to `crop_*`, `rtmp_relays`, `broadcast_outputs`: they key on output id, which does not change. +- Output `enabled` keeps meaning "configured and allowed" (as agreed with the lifecycle plan); running state is runtime, per group. +- Guards on write: same project, same root input (computed with the existing resolver, depth cap 3 already in the egress plan), no member's source is an output outside the group that is itself in a different group (a group may read the final path of another group, which is a normal RTSP read, but not form a cycle), member count cap `MAX_GROUP_MEMBERS` (default 4, setting `outputs.max_group_members`). + +## 4. Compiler and runner + +### 4.1 Pure compiler + +New `lcyt-rtmp/src/output-group-plan.js`, no I/O, golden-tested. `compileGroup(members, ctx) -> { inputs, filterGraph, outputs[], commandTargets, hash, requires }`. + +- Reuse, do not copy: `buildDskStepArgs` and the crop filter in `crop-manager.js` (`crop@vcrop=..,scale=..`) are first refactored into fragment builders (`dskFragment`, `cropFragment`: given an input label, return filter parts and an output label). The existing single-output paths then call the same fragments, so a locked and an unlocked output cannot drift apart. +- Build a tree from the members' step chains (order is always source, DSK, crop, as in the egress plan). Common prefixes are shared: members with the same DSK list share one overlay chain, then `split` where they diverge. Members with a different DSK list diverge at the root of the DSK step. +- Per member output: its own `-map`, `-c:v libx264 -preset .. -tune zerolatency` with member-specific size/bitrate, `-c:a copy` (or the audio override), `-f flv rtmp:///`. +- `hash` of the compiled graph decides restart: unchanged hash = leave the process alone. +- `requires` = union (`encoder:libx264`, `filter:colorkey`, plus `MEDIAMTX_FLEET_REQUIRES`). + +### 4.2 Runner + +`OutputStepManager` becomes the owner of both unlocked steps and groups: a step is just a group of one that is not user-visible. It already has restart with backoff, the reconcile poll, a readiness check on the source path and the "restart when the set of ready viewports changes" rule, so the group reuses all of it with the unit of supervision changed from a step to a group. Source not ready: group stops. A viewport not ready: the group runs without it and restarts when it comes (same rule as today). `MAX_OUTPUT_STEPS` counts a group as steps = number of distinct filter steps in the tree (shared steps count once), so locking visibly saves budget. Process count and encode count are reported separately in status. + +### 4.3 Crop commands + +`CropManager` today sends live position changes to ffmpeg stdin (`C