Files
element-call/src/lotus/lotusAudioInject.ts
T
Lotus CIandClaude Fable 5.1 c6f9727870 merge: upstream v0.25.0 into lotus
Merge upstream element-hq/element-call tag v0.25.0 into the Lotus fork
(previous base: v0.20.1; actual merge-base v0.20.1-rc.1). Every Lotus
feature and all six io.lotus.* widget actions are preserved. Version
bumped to 0.25.0-lotus.1.

Conflict files and how each Lotus hunk was re-expressed:

* src/state/CallViewModel/remoteMembers/ConnectionFactory.ts
  Upstream moved echoCancellation/noiseSuppression/autoGainControl from
  constructor params (fed by URL params) to persisted Settings
  (settings.ts) with a developer-settings UI. The cinny host still drives
  these per call via URL params (noiseSuppression=false /
  autoGainControl=false when the in-source ML denoiser is active, so the
  model gets a raw mic) - taking upstream verbatim would silently break
  the ML denoise tier. Re-wired as AND semantics in generateRoomOption():
  a constraint is enabled only if BOTH the Setting and the URL param
  allow it. Params default to true, so with no params this is
  byte-for-byte upstream behaviour. Upstream's own echoCancellation /
  noiseSuppression URL params (still parsed but dead in v0.25.0) work
  again as a side effect. Lotus autoGainControl URL param kept in
  UrlParams.ts (auto-merged, unchanged).

* src/state/CallViewModel/remoteMembers/ECConnectionFactory.test.ts
  Took upstream (tests now drive via Settings). The lost Lotus coverage
  is restored in a NEW colocated file src/lotus/lotusAudioConstraints.test.ts
  (3 tests) so the upstream test file stays pristine. Verified the new
  test fails against pure-upstream ConnectionFactory and passes with the
  re-wiring.

* src/state/CallViewModel/CallViewModel.ts
  Three small hunks: kept both the Lotus `userMedia$` interface member
  and upstream's new `keyRotationSuppressed$`; dropped the three Lotus
  audio constructor args (mechanism removed upstream, see above); kept
  both in the returned object. The [lotus #4] overrideSpotlight$ routing,
  manualSpotlightUserId$ and setManualSpotlight auto-merged; verified
  against upstream's changed ringingMedia$ (now single-or-null instead
  of array) - the merge correctly took upstream's outer branch and the
  inner screenShares$/spotlightSpeaker$ logic that lotusSpotlight.ts
  mirrors is unchanged upstream.

* src/index.css
  Kept both: Lotus lotus-transparent / lotus-theme blocks and upstream's
  new body[data-background="gradient"]::before full-viewport gradient.
  The naive merge swallowed the closing brace of body.lotus-theme -
  restored. Added a rule hiding the new gradient pseudo-element under
  body.lotus-transparent, since it would otherwise paint over the
  transparent body and hide the host wallpaper.

* src/components/CallFooterViewModel.tsx, src/components/CallFooter.stories.tsx
  No Lotus content - pure upstream-vs-upstream conflicts caused by the
  merge base being v0.20.1-rc.1. Took upstream (layoutMode ->
  layoutSwitchVm; setLayoutMode removed). No Lotus code uses
  setGridMode/layoutMode.

Non-conflicting but reviewed:

* src/widget.ts auto-merged cleanly. Upstream's removal of .well-known
  transport advertisement and the new RTC-transport capability request
  did not touch the action registration loop the LOTUS_TO_WIDGET_ACTIONS
  spread and widget.lazyActions ride on - nothing to re-wire.
* src/room/InCallView.tsx, src/useAudioContext.tsx, src/useTheme.ts,
  src/tile/MediaView.tsx(+.module.css), src/UrlParams.ts(+test),
  all *.module.css and .gitea/workflows/ci.yml auto-merged; each diff
  against v0.25.0 was checked to equal the original Lotus hunk.
* src/button/Button.module.css: the merge appended an exact duplicate
  of upstream's `.rotate`/`@keyframes spin` block (rc.1 merge-base
  artefact) - reset to upstream verbatim.
* src/grid/OneOnOnePortraitLayout.module.css was renamed upstream to
  OneOnOneMobileLayout.module.css; git followed the rename and the Lotus
  safe-area PiP inset fix applies there (the --content-inset-* vars it
  uses still exist upstream).

Tooling changes inherited from upstream that affect the fork:

* eslint + prettier were replaced by oxlint + oxfmt (`pnpm lint:oxlint`,
  `pnpm format:check`). oxlint flagged 10 issues, all in src/lotus/*:
  8x no-meaningless-void-operator (dropped the `void` before void-typed
  widget transport.reply / callbacks - no behaviour change), 1x
  consistent-type-imports (lotusWidget.ts: `import type`), and 2x
  unicorn/no-useless-spread in lotusAudioInject.ts which are FALSE
  POSITIVES - `[...activeClips]` is a required defensive copy because
  abort() deletes from the Set during iteration; suppressed with an
  explanatory eslint-disable-next-line. oxfmt reformatted 7 Lotus
  touched files (whitespace only).
* packageManager bumped by upstream to pnpm@11.21.0, which requires
  Node >= 22.13 (uses node:sqlite). Node 20 cannot run it; pnpm 10.33
  cannot read the new lockfile either (matrix-js-sdk is now a git
  dependency on develop, using a version-union pnpm 10 rejects). Fork CI
  already uses Node 24 (.node-version), so CI is unaffected.
* matrix-js-sdk is now github:matrix-org/matrix-js-sdk#develop (pinned
  by commit in pnpm-lock.yaml).

Lotus behaviour NOT preserved: none found.

Verification (Node 24.11.1, pnpm 11.21.0): pnpm install --frozen-lockfile
OK (lockfile taken from upstream unchanged, no regeneration needed);
tsc clean; oxlint clean; oxfmt --check clean; knip exit 0 (2 config
hints in upstream knip.ts only); vitest unit 84 files / 627 passed /
9 skipped; build:embedded OK, staged to embedded/web/dist (44M), all
six io.lotus.* action strings present in the bundle.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPmy3tPq869XDW4njjVaKA
2026-09-12 11:35:57 -04:00

260 lines
8.8 KiB
TypeScript

/*
Copyright 2026 Lotus Guild
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type Room as LivekitRoom, Track } from "livekit-client";
import { logger } from "matrix-js-sdk/lib/logger";
import { type IWidgetApiRequest } from "matrix-widget-api";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { widget } from "../widget";
import { LotusWidgetActions } from "./lotusActions";
import { lotusFlag } from "./lotusWidget";
/** Hard cap so a malformed/huge clip can't hold a published track open forever. */
const MAX_CLIP_MS = 30_000;
/**
* Handle the host's `io.lotus.inject_audio` toWidget action (#3): mix a
* soundboard clip into the call so other participants hear it.
*
* Rather than splice into the local mic track (which would fight the denoise
* pipeline), we publish the clip as a separate `Unknown`-source LiveKit audio
* track — which `MatrixAudioRenderer` already renders for valid call members —
* and unpublish it when the clip ends. This is the real call-audio injection
* that was impossible against the prebuilt EC bundle (LiveKit's
* LocalParticipant lived in EC's module scope).
*
* Action data: `{ url: string, volume?: number }`. `url` must be an https/blob
* URL (the host resolves mxc → media URL).
*
* No effect unless the host sends the action. Returns a teardown function that
* also aborts any clip still playing.
*/
export function startLotusAudioInject(vm: CallViewModel): () => void {
const w = widget;
if (!w) return () => undefined;
// Track the set of connected LiveKit rooms to publish into. Drive off the
// LOCAL participant's connection(s), not `livekitRoomItems$` — that stream
// omits rooms with no remote members, so inject would no-op while you're
// alone. Map the connections to their livekit rooms like `lotusDenoise.ts`.
let rooms: LivekitRoom[] = [];
const sub = vm.allConnections$.subscribe((data) => {
rooms = data.getConnections().map((c) => c.livekitRoom);
});
// In-flight clips, so we can abort them on teardown (unmount / vm change /
// call leave) instead of leaving audio blasting to peers.
const activeClips = new Set<() => void>();
const handler = (ev: CustomEvent<IWidgetApiRequest>): void => {
// Always ack so the transport doesn't hang, but only act when the host has
// explicitly opted in: audio-inject publishes under the local user's
// identity, so it must not be silently armed for every call.
w.api.transport.reply(ev.detail, {});
if (!lotusFlag("lotusAudioInject")) return;
const data = ev.detail.data as
| { url?: unknown; volume?: unknown }
| undefined;
const url = typeof data?.url === "string" ? safeMediaUrl(data.url) : null;
if (!url) {
logger.warn("[lotus] inject_audio: missing/invalid url");
return;
}
const volume =
typeof data?.volume === "number" && data.volume >= 0 && data.volume <= 1
? data.volume
: 1;
void playInjectedClip(url, volume, rooms, activeClips).catch((e) =>
logger.warn("[lotus] inject_audio failed", e),
);
};
w.lazyActions.on(LotusWidgetActions.InjectAudio, handler);
return () => {
sub.unsubscribe();
w.lazyActions.off(LotusWidgetActions.InjectAudio, handler);
// Abort anything still playing.
// oxlint-disable-next-line unicorn/no-useless-spread -- the spread is a
// required defensive copy: abort() deletes from activeClips while we
// iterate it.
// The spread is a required defensive copy: abort() deletes from
// activeClips while we iterate it.
// eslint-disable-next-line unicorn/no-useless-spread
for (const abort of [...activeClips]) abort();
};
}
/** Only allow fetchable media URLs; never same-origin credentialed GETs etc. */
function safeMediaUrl(raw: string): string | null {
try {
const u = new URL(raw, window.location.href);
return u.protocol === "https:" || u.protocol === "blob:" ? u.href : null;
} catch {
return null;
}
}
async function playInjectedClip(
url: string,
volume: number,
rooms: LivekitRoom[],
activeClips: Set<() => void>,
): Promise<void> {
if (rooms.length === 0) {
logger.warn("[lotus] inject_audio: no connected rooms");
return;
}
// Max ONE clip at a time (replace mode): stop any in-flight or playing clip
// before starting a new one, so clips can't overlap or be spammed.
// The spread is a required defensive copy: abort() deletes from
// activeClips while we iterate it.
// eslint-disable-next-line unicorn/no-useless-spread
for (const abort of [...activeClips]) abort();
// A second inject action can arrive while THIS one is still awaiting its
// fetch/decode/publish — before its real cleanup() exists. Register a
// synchronous placeholder abort NOW, BEFORE the first await, so the
// replace-mode loop above (run by that later action) cancels this one;
// otherwise both clips would sail past their awaits and DOUBLE-PUBLISH. The
// placeholder aborts the in-flight fetch and flips `aborted`, which we check
// after every await; the real cleanup() replaces it once the track is live.
let aborted = false;
const controller = new AbortController();
const placeholder = (): void => {
aborted = true;
controller.abort();
activeClips.delete(placeholder);
};
activeClips.add(placeholder);
let resp: Response;
try {
resp = await fetch(url, {
credentials: "omit",
mode: "cors",
signal: controller.signal,
});
} catch (e) {
// Superseded by a newer clip mid-fetch — expected, not a failure.
if (aborted) return;
throw e;
}
if (aborted) return;
if (!resp.ok) throw new Error(`fetch ${url} -> ${resp.status}`);
const arrayBuffer = await resp.arrayBuffer();
if (aborted) return;
const ctx = new AudioContext();
// The action arrives via host postMessage, not a gesture in this iframe, so
// the context may start suspended — resume it or the clip is silent and
// `onended` never fires.
try {
await ctx.resume();
} catch {
/* best effort */
}
if (aborted) {
void ctx.close();
return;
}
if (ctx.state !== "running")
logger.warn(`[lotus] inject_audio: AudioContext is ${ctx.state}`);
let buffer: AudioBuffer;
try {
buffer = await ctx.decodeAudioData(arrayBuffer);
} catch (e) {
void ctx.close();
throw e;
}
if (aborted) {
void ctx.close();
return;
}
const dest = ctx.createMediaStreamDestination();
const gain = ctx.createGain();
gain.gain.value = volume;
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(gain).connect(dest);
const mst = dest.stream.getAudioTracks()[0];
if (!mst) {
void ctx.close();
throw new Error("no audio track from destination");
}
// Publish (a clone of) the clip track to every connected room.
const publications = await Promise.all(
rooms.map(async (room) => {
const clone = mst.clone();
try {
const pub = await room.localParticipant.publishTrack(clone, {
source: Track.Source.Unknown,
name: "lotus-soundboard",
dtx: false,
red: false,
});
return { room, pub };
} catch (e) {
clone.stop(); // don't leak the clone if publish failed
logger.warn("[lotus] inject_audio: publish failed", e);
return null;
}
}),
);
let cleanedUp = false;
const cleanup = (): void => {
if (cleanedUp) return;
cleanedUp = true;
activeClips.delete(cleanup);
try {
source.stop();
} catch {
/* already stopped */
}
for (const entry of publications) {
if (entry?.pub.track)
void entry.room.localParticipant
.unpublishTrack(entry.pub.track, true)
.catch(() => undefined);
}
void ctx.close().catch(() => undefined);
};
// Swap the synchronous placeholder for the real cleanup: from here an abort
// (teardown or a newer clip) must unpublish the LIVE track, not just cancel a
// fetch. This delete+add is synchronous (no await), so a newer clip's
// replace-mode loop always sees exactly one of {placeholder, cleanup}.
activeClips.delete(placeholder);
activeClips.add(cleanup);
// If a newer clip aborted us WHILE we were publishing, tear down now so we
// don't leave an orphan track published after it ran its replace-mode loop.
if (aborted) {
cleanup();
return;
}
source.onended = cleanup;
// Safety net: clip metadata can lie (NaN/huge duration), so force teardown
// after a sane, capped delay.
const durationMs = Number.isFinite(buffer.duration)
? buffer.duration * 1000 + 500
: MAX_CLIP_MS;
const guard = setTimeout(
cleanup,
Math.min(MAX_CLIP_MS, Math.max(0, durationMs)),
);
source.addEventListener("ended", () => clearTimeout(guard));
source.start();
}