A platform for community discussion. Free, open, simple.
FEATURE: Let Live participants record calls to their own device (#45308)
Rafael dos Santos Silva9d54510ed67f
diff --git a/plugins/live/app/controllers/live/rooms_controller.rb b/plugins/live/app/controllers/live/rooms_controller.rbindex 52d01f20971..d6c6bf19f32 100644--- a/plugins/live/app/controllers/live/rooms_controller.rb+++ b/plugins/live/app/controllers/live/rooms_controller.rb@@ -15,7 +15,7 @@ module Live# flood every participant's MessageBus.REACTIONS_PER_USER = 15 # per 10 seconds- STATE_FIELDS = %i[muted deafened video screen watching transcribing]+ STATE_FIELDS = %i[muted deafened video screen watching transcribing recording_locally]# Anonymous visitors may browse the directory; the guardian still limits the# listing to public rooms, and only when access is open to everyone.@@ -487,6 +487,11 @@ module Liveendend+ if params.key?(:recording_locally) && bool.cast(params[:recording_locally]) &&+ !guardian.can_record_live_locally?+ raise Discourse::InvalidAccess.new(I18n.t("live.errors.local_recording_not_allowed"))+ end+metadata = Live::ParticipantTracker.get_metadata(@room.id, current_user.id)previous_metadata = metadata.dupmetadata[:is_muted] = bool.cast(params[:muted]) if params.key?(:muted)@@ -495,6 +500,9 @@ module Livemetadata[:is_screen_sharing] = bool.cast(params[:screen]) if params.key?(:screen)metadata[:watching_video] = bool.cast(params[:watching]) if params.key?(:watching)metadata[:is_transcribing] = bool.cast(params[:transcribing]) if params.key?(:transcribing)+ if params.key?(:recording_locally)+ metadata[:is_recording_locally] = bool.cast(params[:recording_locally])+ end# A request that changes nothing must not become a full-roster# rebroadcast to every participant.diff --git a/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.js b/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.jsindex 4696f04b460..6d8aaed3b57 100644--- a/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.js+++ b/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.js@@ -16,6 +16,7 @@ import IdleTracker, { idleThresholds } from "../../lib/live/idle-tracker.js";import { consumePendingInviteRef } from "../../lib/live/invite-ref.js";import LivekitCoordinator from "../../lib/live/livekit-coordinator.js";import LocalAudioPipeline from "../../lib/live/local-audio-pipeline.js";+import LocalRecordingCoordinator from "../../lib/live/local-recording-coordinator.js";import LocalVideoManager from "../../lib/live/local-video-manager.js";import {applyOutputDevice,@@ -137,6 +138,7 @@ export default class LiveWebrtcService extends Service {#livekit;#roster;#transcription;+ #localRecording;constructor() {super(...arguments);@@ -220,7 +222,10 @@ export default class LiveWebrtcService extends Service {this.#roomMessageQueue = new RoomMessageQueue();this.#remoteStreamRegistry = new RemoteStreamRegistry({- onChange: () => this.remoteStreamsRevision++,+ onChange: () => {+ this.remoteStreamsRevision++;+ this.#localRecording.sync();+ },onMicTrack: (roomId, userId, stream) => {this.#audioMonitor.ensure(roomId, userId, stream, false);this.#transcription.attachRemote(roomId, userId, stream);@@ -254,6 +259,28 @@ export default class LiveWebrtcService extends Service {}),});+ this.#localRecording = new LocalRecordingCoordinator({+ getCurrentUserId: () => this.currentUser?.id,+ getParticipantSessionId: (roomId) => this.#roomSessions.get(roomId),+ getRoom: (roomId) => this.liveRooms?.roomById(roomId),+ isActiveRoom: (roomId) => this.isActiveRoom(roomId),+ getAudioTracks: (roomId) => this.#localRecordingAudioTracks(roomId),+ setParticipantRecording: (roomId, recording) =>+ this.liveRooms?.setParticipantVideoState(roomId, this.currentUser?.id, {+ is_recording_locally: recording,+ }),+ showNotice: (messageKey) =>+ this.toasts.success({+ duration: 5000,+ data: { message: i18n(messageKey) },+ }),+ showError: (messageKey) =>+ this.toasts.error({+ duration: 8000,+ data: { message: i18n(messageKey) },+ }),+ });+this.#participantAudio = new ParticipantAudio({isDeafened: () => this.deafened,});@@ -444,6 +471,7 @@ export default class LiveWebrtcService extends Service {this.#localVideo.destroy();this.#localAudio.stop();this.#transcription.destroy();+ this.#localRecording.destroy();this.#roomHandlerCallbacks.forEach((callback, roomId) => {this.liveRooms?.unregisterRoomHandler(roomId, callback);@@ -613,6 +641,12 @@ export default class LiveWebrtcService extends Service {return this.#localVideo.screenAudioTrack;}+ // --- Local recording ---++ get localRecordingBusy() {+ return this.#localRecording.busy;+ }+setNoiseSuppressionMode(mode) {return this.#localAudio.setNoiseSuppressionMode(mode);}@@ -654,6 +688,18 @@ export default class LiveWebrtcService extends Service {return this.#transcription.openDraft();}+ isRecordingLocally(roomId) {+ return this.#localRecording.isRecording(roomId);+ }++ startLocalRecording(roomId, displayStream = null) {+ return this.#localRecording.start(roomId, displayStream);+ }++ stopLocalRecording() {+ return this.#localRecording.stop();+ }+captionsFor(roomId) {return this.#transcription.captionsFor(roomId);}@@ -748,6 +794,12 @@ export default class LiveWebrtcService extends Service {liveLog.info(`[live] joining room ${room.id}`);this.#registerRoomHandler(room.id);+ // Recordings already running when we join are shown by the indicator;+ // only ones started afterwards are announced.+ this.#localRecording.trackRecorders(+ room.id,+ this.liveRooms.roomById(room.id)?.active_participants+ );let response;@@ -927,6 +979,7 @@ export default class LiveWebrtcService extends Service {if (this.localVideoKind && (wasConnected || wasConnecting)) {this.#localVideo.stop({ broadcast: false }).catch(() => {});}+ this.#localRecording.stopIfRecording(room.id);if (wasConnecting) {this.#joinRevision++;@@ -1242,6 +1295,7 @@ export default class LiveWebrtcService extends Service {async toggleScreenShare() {const screenWasActive = this.localVideoKind === "screen";const result = await this.#localVideo.toggleScreenShare();+ this.#localRecording.sync();if (screenWasActive && !this.localVideoKind && this.watchingRoomId) {this.#restorePreferredCamera(this.watchingRoomId);@@ -1675,6 +1729,8 @@ export default class LiveWebrtcService extends Service {this.#signaling.clearHttpQueue(roomId);this.#roomMessageQueue.clear(roomId);this.#transcription.stopIfTranscribing(roomId);+ this.#localRecording.stopIfRecording(roomId);+ this.#localRecording.forgetRoom(roomId);this.liveReactions.clearRoom(roomId);}@@ -1734,6 +1790,7 @@ export default class LiveWebrtcService extends Service {await this.#meshSignals.handle(roomId, payload);}} else if (payload.type === "participants") {+ this.#announceLocalRecorders(roomId, payload.participants);await this.#roster.handleParticipants(roomId, payload);} else if (payload.type === "role_change") {await this.#roster.handleRoleChange(roomId, payload);@@ -1758,6 +1815,39 @@ export default class LiveWebrtcService extends Service {}}+ // Everything the call's participants hear: the local mic as sent (after+ // noise suppression, mute and push-to-talk), every remote mic, and any+ // shared screen audio, ours included.+ #localRecordingAudioTracks(roomId) {+ return [+ ...(this.localStream?.getAudioTracks() || []),+ this.localScreenAudioTrack,+ ...this.#remoteStreamRegistry+ .streamsFor(roomId)+ .flatMap((stream) => stream.getAudioTracks()),+ ...this.#remoteStreamRegistry+ .screenAudioStreamsFor(roomId)+ .flatMap((stream) => stream.getAudioTracks()),+ ].filter(Boolean);+ }++ // Server recordings announce themselves with a toast; local ones get the+ // same treatment so nobody is recorded without being told.+ #announceLocalRecorders(roomId, participants) {+ for (const username of this.#localRecording.trackRecorders(+ roomId,+ participants+ )) {+ this.toasts.default({+ duration: 8000,+ data: {+ icon: "record-vinyl",+ message: i18n("live.local_recording.started_toast", { username }),+ },+ });+ }+ }+#handleKicked(roomId) {liveLog.info(`[live] kicked from room ${roomId}`);this.leave({ id: roomId });@@ -1905,6 +1995,7 @@ export default class LiveWebrtcService extends Service {}this.#transcription.syncLocalTap();+ this.#localRecording.sync();}#applyLocalTrackState(stream) {diff --git a/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjs b/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjsindex ca7ced78ac7..7d043ab7337 100644--- a/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjs+++ b/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjs@@ -22,6 +22,7 @@ import LiveInviteAgentButton from "../live-invite-agent-button.gjs";import LiveInviteUsersModal from "../modal/live-invite-users.gjs";import LiveRoomInfoModal from "../modal/live-room-info.gjs";import LiveCallControls from "./call-controls.gjs";+import LiveLocalRecordingMenuItem from "./local-recording-menu-item.gjs";import LiveReactionOverlay from "./reaction-overlay.gjs";import LiveRecordingBadge from "./recording-badge.gjs";import LiveRingingTile from "./ringing-tile.gjs";@@ -794,6 +795,11 @@ export default class LiveCallWidget extends Component {@item={{dropdown.item}}@room={{this.room}}/>+ <LiveLocalRecordingMenuItem+ @closeMenu={{roomMenu.close}}+ @item={{dropdown.item}}+ @room={{this.room}}+ />{{#if this.chatAvailable}}<dropdown.item><DButtondiff --git a/plugins/live/assets/javascripts/discourse/components/live/local-recording-menu-item.gjs b/plugins/live/assets/javascripts/discourse/components/live/local-recording-menu-item.gjsnew file mode 100644index 00000000000..35ee7a5853b--- /dev/null+++ b/plugins/live/assets/javascripts/discourse/components/live/local-recording-menu-item.gjs@@ -0,0 +1,106 @@+import Component from "@glimmer/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import { i18n } from "discourse-i18n";+import {+ localRecordingSupported,+ requestTabCapture,+} from "../../lib/live/local-recorder.js";++// A room menu entry for recording the call to this device. Tries a tab+// capture for video and offers audio only when that isn't possible.+export default class LiveLocalRecordingMenuItem extends Component {+ @service currentUser;+ @service dialog;+ @service liveWebrtc;+ @service siteSettings;++ // One record entry per user: where the server can record the call, that+ // takes precedence.+ get available() {+ return (+ this.currentUser?.live_can_record_locally &&+ localRecordingSupported() &&+ this.liveWebrtc.isActiveRoom(this.args.room.id) &&+ !this.#serverRecordingAvailable+ );+ }++ get active() {+ return this.liveWebrtc.isRecordingLocally(this.args.room.id);+ }++ get disabled() {+ return !this.active && this.liveWebrtc.localRecordingBusy;+ }++ get label() {+ return this.active+ ? i18n("live.local_recording.stop")+ : i18n("live.local_recording.start");+ }++ get #serverRecordingAvailable() {+ return (+ this.args.room.can_manage &&+ this.siteSettings.live_livekit_recording_enabled &&+ this.liveWebrtc.isLivekitRoom(this.args.room.id)+ );+ }++ // Bound with {{on "click"}}, not DButton's @action: that defers via next(),+ // and Firefox only allows getDisplayMedia during the click dispatch itself.+ @action+ toggle() {+ const roomId = this.args.room.id;++ if (this.active) {+ this.args.closeMenu?.();+ this.liveWebrtc.stopLocalRecording();+ return;+ }++ if (!this.liveWebrtc.screenShareSupported) {+ this.args.closeMenu?.();+ this.liveWebrtc.startLocalRecording(roomId);+ return;+ }++ // Closing the menu destroys this component before the capture settles.+ const { dialog, liveWebrtc } = this;+ requestTabCapture().then(+ (displayStream) => liveWebrtc.startLocalRecording(roomId, displayStream),+ () => {+ // Declining the picker is as likely as a failure, so ask rather than+ // silently fall back.+ if (liveWebrtc.isActiveRoom(roomId)) {+ dialog.yesNoConfirm({+ message: i18n("live.local_recording.audio_only_confirm"),+ didConfirm: () => liveWebrtc.startLocalRecording(roomId),+ });+ }+ }+ );+ this.args.closeMenu?.();+ }++ <template>+ {{#if this.available}}+ <@item>+ <DButton+ class={{dConcatClass+ "btn-transparent live-local-recording-toggle"+ (if this.active "--recording")+ }}+ @disabled={{this.disabled}}+ @icon={{if this.active "stop" "record-vinyl"}}+ @translatedLabel={{this.label}}+ {{on "click" this.toggle}}+ />+ </@item>+ {{/if}}+ </template>+}diff --git a/plugins/live/assets/javascripts/discourse/components/live/recording-badge.gjs b/plugins/live/assets/javascripts/discourse/components/live/recording-badge.gjsindex 81e9e25df56..46a0038f522 100644--- a/plugins/live/assets/javascripts/discourse/components/live/recording-badge.gjs+++ b/plugins/live/assets/javascripts/discourse/components/live/recording-badge.gjs@@ -1,24 +1,73 @@+import Component from "@glimmer/component";+import { service } from "@ember/service";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-// The room-wide "this call is being recorded" indicator. Rendered wherever a+// The room-wide "this call is being recorded" indicator, for server+// recordings and participants recording locally alike. Rendered wherever a// room's call is shown (full page, floating widget) so nobody can be in a// recorded call without seeing it.-const LiveRecordingBadge = <template>- {{#if @room.recording}}- <span- class="live-recording-badge"- title={{i18n- "live.room.recording_indicator_title"- [email protected]_by.username- }}- >- {{dIcon "record-vinyl"}}- <span class="live-recording-badge__label">- {{i18n "live.room.recording_indicator"}}- </span>- </span>- {{/if}}-</template>;+export default class LiveRecordingBadge extends Component {+ @service currentUser;+ @service liveWebrtc;++ get selfRecording() {+ return this.liveWebrtc.isRecordingLocally(this.args.room.id);+ }++ get localRecorders() {+ return (this.args.room.active_participants || [])+ .filter(+ (participant) =>+ participant?.is_recording_locally &&+ Number(participant.id) !== this.currentUser?.id+ )+ .map((participant) => participant.username);+ }++ get visible() {+ return (+ !!this.args.room.recording ||+ this.selfRecording ||+ this.localRecorders.length > 0+ );+ }-export default LiveRecordingBadge;+ get title() {+ const lines = [];+ const serverRecording = this.args.room.recording;++ if (serverRecording) {+ lines.push(+ i18n("live.room.recording_indicator_title", {+ username: serverRecording.started_by.username,+ })+ );+ }+ if (this.selfRecording) {+ lines.push(i18n("live.local_recording.indicator_title_self"));+ }+ const recorders = this.localRecorders;+ if (recorders.length > 0) {+ lines.push(+ i18n("live.local_recording.indicator_title", {+ count: recorders.length,+ usernames: recorders.join(", "),+ })+ );+ }++ return lines.join("\n");+ }++ <template>+ {{#if this.visible}}+ <span class="live-recording-badge" title={{this.title}}>+ {{dIcon "record-vinyl"}}+ <span class="live-recording-badge__label">+ {{i18n "live.room.recording_indicator"}}+ </span>+ </span>+ {{/if}}+ </template>+}diff --git a/plugins/live/assets/javascripts/discourse/components/live/room-page.gjs b/plugins/live/assets/javascripts/discourse/components/live/room-page.gjsindex 78be6c37af9..124a8a60e5f 100644--- a/plugins/live/assets/javascripts/discourse/components/live/room-page.gjs+++ b/plugins/live/assets/javascripts/discourse/components/live/room-page.gjs@@ -34,6 +34,7 @@ import LiveCallControls from "./call-controls.gjs";import LiveCallSubmenu from "./call-submenu.gjs";import LiveCaptionOverlay from "./caption-overlay.gjs";import LiveChatPanel from "./chat-panel.gjs";+import LiveLocalRecordingMenuItem from "./local-recording-menu-item.gjs";import LiveReactionOverlay from "./reaction-overlay.gjs";import LiveReactionPicker from "./reaction-picker.gjs";import LiveRingingTile from "./ringing-tile.gjs";@@ -704,6 +705,11 @@ export default class LiveRoomPage extends Component {@item={{dropdown.item}}@room={{this.room}}/>+ <LiveLocalRecordingMenuItem+ @closeMenu={{roomMenu.close}}+ @item={{dropdown.item}}+ @room={{this.room}}+ /><dropdown.item><DButtonclass="btn-transparent live-room-page__layout-trigger"diff --git a/plugins/live/assets/javascripts/discourse/lib/live/local-recorder.js b/plugins/live/assets/javascripts/discourse/lib/live/local-recorder.jsnew file mode 100644index 00000000000..2c9c77cc203--- /dev/null+++ b/plugins/live/assets/javascripts/discourse/lib/live/local-recorder.js@@ -0,0 +1,302 @@+import liveLog from "discourse/plugins/live/discourse/lib/live/logger";++const TIMESLICE_MS = 1000;+const AUDIO_BITS_PER_SECOND = 128_000;+const VIDEO_BITS_PER_SECOND = 2_500_000;+const STORAGE_DIRECTORY = "live-local-recordings";+const STALE_AFTER_MS = 60 * 60 * 1000;++// MP4 first: MediaRecorder's WebM output has no duration or cues, so most+// players can't seek it.+const VIDEO_MIME_TYPES = [+ "video/mp4;codecs=avc1,opus",+ "video/mp4;codecs=avc1,mp4a.40.2",+ "video/webm;codecs=vp9,opus",+ "video/webm;codecs=vp8,opus",+ "video/mp4",+ "video/webm",+];++const AUDIO_MIME_TYPES = [+ "audio/mp4;codecs=opus",+ "audio/mp4;codecs=mp4a.40.2",+ "audio/webm;codecs=opus",+ "audio/ogg;codecs=opus",+ "audio/mp4",+ "audio/webm",+];++export function localRecordingSupported() {+ return (+ typeof window.MediaRecorder === "function" &&+ typeof window.AudioContext === "function"+ );+}++export function pickMimeType(+ withVideo,+ isTypeSupported = (type) => window.MediaRecorder.isTypeSupported(type)+) {+ return (withVideo ? VIDEO_MIME_TYPES : AUDIO_MIME_TYPES).find((type) =>+ isTypeSupported(type)+ );+}++export function recordingFilename(prefix, mimeType, date = new Date()) {+ const pad = (value) => String(value).padStart(2, "0");+ const stamp = [+ date.getFullYear(),+ pad(date.getMonth() + 1),+ pad(date.getDate()),+ `${pad(date.getHours())}${pad(date.getMinutes())}`,+ ].join("-");+ return `${prefix}-${stamp}.${fileExtension(mimeType)}`;+}++function fileExtension(mimeType = "") {+ const [type] = mimeType.split(";");+ switch (type) {+ case "video/mp4":+ return "mp4";+ case "audio/mp4":+ return "m4a";+ case "audio/ogg":+ return "ogg";+ default:+ return "webm";+ }+}++// Must be called synchronously from a click handler: Firefox only allows+// getDisplayMedia during the event dispatch itself.+export function requestTabCapture() {+ return navigator.mediaDevices.getDisplayMedia({+ video: { frameRate: 30 },+ audio: false,+ preferCurrentTab: true,+ selfBrowserSurface: "include",+ surfaceSwitching: "exclude",+ });+}++// Tab audio leaves out the recorder's own microphone and isn't available+// outside Chromium, so the soundtrack is mixed from the call's streams.+class AudioMixer {+ #context;+ #destination;+ #sources = new Map();++ constructor(context) {+ this.#context = context;+ this.#destination = context.createMediaStreamDestination();+ }++ get track() {+ return this.#destination.stream.getAudioTracks()[0];+ }++ sync(tracks) {+ const wanted = new Map(+ tracks+ .filter((track) => track?.readyState === "live")+ .map((track) => [track.id, track])+ );++ for (const [id, node] of this.#sources) {+ if (!wanted.has(id)) {+ node.disconnect();+ this.#sources.delete(id);+ }+ }++ for (const [id, track] of wanted) {+ if (!this.#sources.has(id)) {+ // One stream per track: a source node only reads a stream's first+ // audio track.+ const node = this.#context.createMediaStreamSource(+ new MediaStream([track])+ );+ node.connect(this.#destination);+ this.#sources.set(id, node);+ }+ }+ }++ destroy() {+ this.#sources.forEach((node) => node.disconnect());+ this.#sources.clear();+ }+}++// Chunks go to the origin-private file system when available so a long+// recording doesn't live in memory; otherwise they're kept in memory.+async function openSink(name) {+ try {+ const root = await navigator.storage.getDirectory();+ const directory = await root.getDirectoryHandle(STORAGE_DIRECTORY, {+ create: true,+ });+ await removeStaleFiles(directory);+ const handle = await directory.getFileHandle(name, { create: true });+ const writable = await handle.createWritable();+ return new FileSink(handle, writable);+ } catch {+ return new MemorySink();+ }+}++// A saved recording's download reads its file lazily, so recent files are+// left alone; anything older was saved long ago or lost with its tab.+async function removeStaleFiles(directory) {+ const cutoff = Date.now() - STALE_AFTER_MS;+ for await (const handle of directory.values()) {+ try {+ const file = await handle.getFile();+ if (file.lastModified < cutoff) {+ await directory.removeEntry(handle.name);+ }+ } catch {+ // Still open in another tab's recording.+ }+ }+}++class FileSink {+ #handle;+ #writable;+ #queue = Promise.resolve();+ #discarded = false;++ constructor(handle, writable) {+ this.#handle = handle;+ this.#writable = writable;+ }++ write(chunk) {+ if (this.#discarded) {+ return;+ }+ this.#queue = this.#queue.then(() => this.#writable.write(chunk));+ this.#queue.catch((error) =>+ liveLog.warn("[live] local recording write failed", error)+ );+ }++ async finish(type) {+ await this.#queue;+ await this.#writable.close();+ const file = await this.#handle.getFile();+ return new Blob([file], { type });+ }++ discard() {+ this.#discarded = true;+ this.#writable.abort().catch(() => {});+ }+}++class MemorySink {+ #chunks = [];++ write(chunk) {+ this.#chunks.push(chunk);+ }++ async finish(type) {+ const blob = new Blob(this.#chunks, { type });+ this.#chunks = [];+ return blob;+ }++ discard() {+ this.#chunks = [];+ }+}++// Records a call to a file on this device: the given display capture (if+// any) as video, and every audio track passed to sync() mixed as the+// soundtrack.+export default class LocalRecorder {+ #context;+ #mixer;+ #displayStream;+ #recorder;+ #sink;+ #mimeType;+ #stopped;+ #onEnded;++ constructor({ displayStream = null, onEnded }) {+ this.#displayStream = displayStream;+ this.#onEnded = onEnded;+ this.#context = new AudioContext();+ this.#mixer = new AudioMixer(this.#context);++ // The browser's own "Stop sharing" control ends the recording too.+ displayStream+ ?.getVideoTracks()[0]+ ?.addEventListener("ended", () => this.#onEnded());+ }++ get hasVideo() {+ return !!this.#displayStream;+ }++ sync(tracks) {+ this.#mixer.sync(tracks);+ }++ async start(name) {+ await this.#context.resume();+ this.#mimeType = pickMimeType(this.hasVideo);+ this.#sink = await openSink(name);++ const stream = new MediaStream([+ ...(this.#displayStream?.getVideoTracks() || []),+ this.#mixer.track,+ ]);+ this.#recorder = new MediaRecorder(stream, {+ mimeType: this.#mimeType,+ audioBitsPerSecond: AUDIO_BITS_PER_SECOND,+ videoBitsPerSecond: this.hasVideo ? VIDEO_BITS_PER_SECOND : undefined,+ });+ this.#stopped = new Promise((resolve) => {+ this.#recorder.addEventListener("stop", resolve, { once: true });+ });+ this.#recorder.addEventListener("dataavailable", (event) => {+ if (event.data.size > 0) {+ this.#sink.write(event.data);+ }+ });+ this.#recorder.addEventListener("error", () => this.#onEnded());+ this.#recorder.start(TIMESLICE_MS);+ }++ async stop() {+ try {+ if (this.#recorder && this.#recorder.state !== "inactive") {+ this.#recorder.stop();+ }+ await this.#stopped;+ return await this.#sink.finish(+ this.#recorder.mimeType || this.#mimeType || ""+ );+ } finally {+ this.#release();+ }+ }++ discard() {+ if (this.#recorder && this.#recorder.state !== "inactive") {+ this.#recorder.stop();+ }+ this.#sink?.discard();+ this.#release();+ }++ #release() {+ this.#displayStream?.getTracks().forEach((track) => track.stop());+ this.#mixer.destroy();+ this.#context.close().catch(() => {});+ }+}diff --git a/plugins/live/assets/javascripts/discourse/lib/live/local-recording-coordinator.js b/plugins/live/assets/javascripts/discourse/lib/live/local-recording-coordinator.jsnew file mode 100644index 00000000000..42e5e7dfe31--- /dev/null+++ b/plugins/live/assets/javascripts/discourse/lib/live/local-recording-coordinator.js@@ -0,0 +1,190 @@+import { tracked } from "@glimmer/tracking";+import { ajax } from "discourse/lib/ajax";+import { deliverBlobDownload } from "discourse/lib/download-blob";+import liveLog from "discourse/plugins/live/discourse/lib/live/logger";+import LocalRecorder, { recordingFilename } from "./local-recorder.js";++// Owns the current user's local recording (at most one, of one room) and the+// roster flag that shows everyone else it's running. The webrtc service+// forwards stream changes and room teardown here.+export default class LocalRecordingCoordinator {+ @tracked roomId = null;+ @tracked starting = false;++ #recorder = null;+ // Other participants known to be recording, per room, so only a new+ // recorder triggers a notice.+ #knownRecorders = new Map();++ #getCurrentUserId;+ #getParticipantSessionId;+ #getRoom;+ #isActiveRoom;+ #getAudioTracks;+ #setParticipantRecording;+ #showNotice;+ #showError;++ #confirmUnload = (event) => {+ event.preventDefault();+ event.returnValue = "";+ };++ constructor({+ getCurrentUserId,+ getParticipantSessionId,+ getRoom,+ isActiveRoom,+ getAudioTracks,+ setParticipantRecording,+ showNotice,+ showError,+ }) {+ this.#getCurrentUserId = getCurrentUserId;+ this.#getParticipantSessionId = getParticipantSessionId;+ this.#getRoom = getRoom;+ this.#isActiveRoom = isActiveRoom;+ this.#getAudioTracks = getAudioTracks;+ this.#setParticipantRecording = setParticipantRecording;+ this.#showNotice = showNotice;+ this.#showError = showError;+ }++ get busy() {+ return this.starting || !!this.roomId;+ }++ isRecording(roomId) {+ return !!this.roomId && Number(this.roomId) === Number(roomId);+ }++ async start(roomId, displayStream = null) {+ if (this.busy || !this.#isActiveRoom(roomId)) {+ displayStream?.getTracks().forEach((track) => track.stop());+ return;+ }++ this.starting = true;+ let recorder;+ try {+ recorder = new LocalRecorder({+ displayStream,+ onEnded: () => this.stop(),+ });+ recorder.sync(this.#getAudioTracks(roomId));+ await recorder.start(`${roomId}-${Date.now()}`);+ } catch (error) {+ liveLog.warn("[live] local recording failed to start", error);+ recorder?.discard();+ displayStream?.getTracks().forEach((track) => track.stop());+ this.#showError("live.local_recording.start_failed");+ return;+ } finally {+ this.starting = false;+ }++ // Left the call while the recorder was starting.+ if (!this.#isActiveRoom(roomId)) {+ recorder.discard();+ return;+ }++ this.#recorder = recorder;+ this.roomId = roomId;+ window.addEventListener("beforeunload", this.#confirmUnload);+ this.#broadcast(roomId, true);+ }++ async stop() {+ const recorder = this.#recorder;+ const roomId = this.roomId;+ if (!recorder) {+ return;+ }++ this.#recorder = null;+ this.roomId = null;+ window.removeEventListener("beforeunload", this.#confirmUnload);+ this.#broadcast(roomId, false);++ try {+ const blob = await recorder.stop();+ const prefix = this.#getRoom(roomId)?.slug || "live-call";+ await deliverBlobDownload(blob, {+ fallbackFilename: recordingFilename(prefix, blob.type),+ });+ this.#showNotice("live.local_recording.saved");+ } catch (error) {+ liveLog.warn("[live] local recording failed to save", error);+ this.#showError("live.local_recording.save_failed");+ }+ }++ sync() {+ if (this.#recorder) {+ this.#recorder.sync(this.#getAudioTracks(this.roomId));+ }+ }++ stopIfRecording(roomId) {+ if (this.isRecording(roomId)) {+ this.stop();+ }+ }++ // Records which other participants are recording and returns the+ // usernames of those who weren't before. The first roster seen for a room+ // only sets the baseline.+ trackRecorders(roomId, participants) {+ const currentUserId = this.#getCurrentUserId();+ const recorders = new Map(+ (participants || [])+ .filter(+ (participant) =>+ participant?.is_recording_locally &&+ Number(participant.id) !== currentUserId+ )+ .map((participant) => [Number(participant.id), participant.username])+ );++ const previous = this.#knownRecorders.get(roomId);+ this.#knownRecorders.set(roomId, new Set(recorders.keys()));+ if (!previous) {+ return [];+ }++ return [...recorders]+ .filter(([id]) => !previous.has(id))+ .map(([, username]) => username);+ }++ forgetRoom(roomId) {+ this.#knownRecorders.delete(roomId);+ }++ destroy() {+ window.removeEventListener("beforeunload", this.#confirmUnload);+ this.#recorder?.discard();+ this.#recorder = null;+ this.roomId = null;+ this.#knownRecorders.clear();+ }++ // Best effort, like the transcript's flag: the recording itself never+ // depends on the server. Skipped once the room is gone (leave teardown),+ // since the roster entry dies with the membership.+ #broadcast(roomId, recording) {+ if (!this.#isActiveRoom(roomId)) {+ return;+ }++ this.#setParticipantRecording(roomId, recording);+ ajax(`/live/rooms/${roomId}/state`, {+ type: "POST",+ data: {+ recording_locally: recording,+ participant_session_id: this.#getParticipantSessionId(roomId),+ },+ }).catch(() => {});+ }+}diff --git a/plugins/live/assets/javascripts/discourse/lib/live/remote-stream-registry.js b/plugins/live/assets/javascripts/discourse/lib/live/remote-stream-registry.jsindex 0c0ce872f9e..c27dfc535e7 100644--- a/plugins/live/assets/javascripts/discourse/lib/live/remote-stream-registry.js+++ b/plugins/live/assets/javascripts/discourse/lib/live/remote-stream-registry.js@@ -38,6 +38,12 @@ export default class RemoteStreamRegistry {return (this.#streams.get(roomId) || []).map((entry) => entry.stream);}+ screenAudioStreamsFor(roomId) {+ return (this.#streams.get(roomId) || [])+ .map((entry) => entry.screenAudioStream)+ .filter(Boolean);+ }+streamFor(roomId, userId) {return (this.#streams.get(roomId) || []).find((entry) => Number(entry?.userId) === Number(userId)diff --git a/plugins/live/assets/stylesheets/common/live.scss b/plugins/live/assets/stylesheets/common/live.scssindex 9c2ec64cf41..6145f1d409e 100644--- a/plugins/live/assets/stylesheets/common/live.scss+++ b/plugins/live/assets/stylesheets/common/live.scss@@ -1034,7 +1034,8 @@font-size: var(--font-down-1);}-.live-room-page__transcript-toggle {+.live-room-page__transcript-toggle,+.live-local-recording-toggle {&.--recording {.d-icon {color: var(--danger);diff --git a/plugins/live/config/locales/client.en.yml b/plugins/live/config/locales/client.en.ymlindex b6a3129ba74..d253bc9175b 100644--- a/plugins/live/config/locales/client.en.yml+++ b/plugins/live/config/locales/client.en.yml@@ -201,6 +201,18 @@ en:subtitles:loading: "Preparing subtitles…"downloading: "Downloading subtitles model… %{percent}%"+ local_recording:+ start: "Record to this device"+ stop: "Stop recording and save"+ audio_only_confirm: "The call video couldn't be captured. Record audio only instead?"+ start_failed: "The recording couldn't be started."+ saved: "Recording saved to your downloads."+ save_failed: "The recording couldn't be saved."+ started_toast: "%{username} started recording this call."+ indicator_title_self: "You're recording this call to your device"+ indicator_title:+ one: "%{usernames} is recording this call to their device"+ other: "%{usernames} are recording this call to their devices"transcript:start: "Record transcript"stop: "Stop transcript recording"diff --git a/plugins/live/config/locales/server.en.yml b/plugins/live/config/locales/server.en.ymlindex 347c6a1f181..c257a122838 100644--- a/plugins/live/config/locales/server.en.yml+++ b/plugins/live/config/locales/server.en.yml@@ -20,6 +20,7 @@ en:live_afk_disconnect_threshold_minutes: "Minutes of inactivity before a live room participant is automatically disconnected. Set to 0 to disable."live_video_allowed_groups: "Groups whose members can share their camera in live rooms. Leave empty to turn camera video off site-wide. Rooms can individually opt out of all media via their room settings, and stage room listeners can never publish."live_screen_share_allowed_groups: "Groups whose members can share their screen in live rooms. Leave empty to turn screen sharing off site-wide. Rooms can individually opt out of all media via their room settings, and stage room listeners can never publish."+ live_local_recording_allowed_groups: "Groups whose members can record calls to their own device. The recording happens entirely in the browser and is saved as a file on the recorder's device; nothing is uploaded. Other participants see a recording indicator while it runs. Leave empty to turn local recording off."live_video_max_publishers: "Maximum number of participants who can share video or their screen at the same time in a room. On peer-to-peer rooms, higher values increase CPU and bandwidth load for everyone watching; on rooms using a LiveKit media server, they mainly increase load on that server."live_video_background_blur_enabled: "Allow participants to blur their camera background. Segmentation runs on the publisher's device via MediaPipe, which increases CPU/GPU load while their camera is on."live_subtitles_enabled: "Allow participants to turn on live subtitles for other people's speech. Transcription runs entirely on the viewer's device via an NVIDIA Parakeet speech-to-text model (less than 0.5 GB, downloaded on first use, WebGPU required); no audio leaves the browser."@@ -93,6 +94,7 @@ en:listeners_cannot_unmute: "Listeners cannot unmute in a Stage room."video_not_allowed: "You are not allowed to share your camera in this room."screen_share_not_allowed: "You are not allowed to share your screen in this room."+ local_recording_not_allowed: "You are not allowed to record calls in this room."video_publisher_limit: "The maximum number of simultaneous video streams for this room has been reached."chat_unavailable: "Chat is not available for this room."chat_requires_presence: "Join the live room to use its chat."diff --git a/plugins/live/config/settings.yml b/plugins/live/config/settings.ymlindex fec2260eef3..2ad3983fb72 100644--- a/plugins/live/config/settings.yml+++ b/plugins/live/config/settings.yml@@ -145,6 +145,15 @@ plugins:disallowed_groups: "0|4"depends_on:- live_enabled+ live_local_recording_allowed_groups:+ type: group_list+ list_type: compact+ default: ""+ allow_any: false+ refresh: true+ disallowed_groups: "0|4"+ depends_on:+ - live_enabledlive_video_max_publishers:default: 8min: 2diff --git a/plugins/live/docs/roadmap/local-recording.md b/plugins/live/docs/roadmap/local-recording.mdnew file mode 100644index 00000000000..df667128438--- /dev/null+++ b/plugins/live/docs/roadmap/local-recording.md@@ -0,0 +1,171 @@+# Local (In-Browser) Recording++## Overview++Server-side recording only exists for LiveKit calls (`Live::RecordingManager`+drives LiveKit Egress). Mesh calls have no server in the media path, so there+is nothing to record from. This plan adds **local recording**: a participant+records the call in their own browser with `MediaRecorder`, and the file never+leaves their machine.++Nothing about this is mesh-specific. It also serves LiveKit calls on sites+without Egress configured, or users who can't start server recordings, so it+ships as its own "Record locally" control instead of a mesh workaround.++What the server does get involved in is **visibility**: a local recording+raises the same room-wide "Recording" indicator that LiveKit recordings+already use (`LiveRecordingBadge`).++## Why not just capture the tab with its audio++`getDisplayMedia({ audio: true, preferCurrentTab: true })` looks like a+one-liner, but tab audio is the wrong audio source:++- **The recorder's own mic is missing.** The tab never plays the local user+ back to themselves, so the recording has everyone except the person+ recording.+- **Browser support.** Only Chromium captures tab audio. Firefox has no audio+ in `getDisplayMedia`; Safari can't capture a single tab or its audio. Mobile+ browsers have no `getDisplayMedia` at all.+- **Local output settings leak in.** Per-user volume, deafen, and output-sink+ changes all shape what the tab plays.++So the design splits the two: **audio is mixed by us, video comes from+display capture.**++## Design++### Audio: Web Audio mix++All the inputs are already in the client:++- remote mic streams — `RemoteStreamRegistry#allStreams()`+- remote screen-share audio — `RemoteStreamRegistry#allScreenAudioStreams()`+- the local mic, after noise suppression and the input gate / push-to-talk,+ so the recording matches what other participants actually heard++Each feeds a `MediaStreamAudioSourceNode` into one shared+`createMediaStreamDestination()` (the same pattern as `noise-suppression.js`+and `input-gate.js`). The registry's `onChange` adds and removes sources as+peers join, leave, or start sharing. Both transports feed the registry, so the+mixer is transport-agnostic.++This works in every browser and needs no permission prompt.++### Video: display capture (optional)++```js+navigator.mediaDevices.getDisplayMedia({+ video: true,+ audio: false,+ preferCurrentTab: true,+ selfBrowserSurface: "include",+ surfaceSwitching: "exclude",+});+```++- In Chromium, `preferCurrentTab` reduces the prompt to a single "share this+ tab" confirmation.+- In Firefox and Safari the user picks a window or screen instead.+- If display capture is unavailable or declined, record audio only.++Rejected: compositing video tiles onto a `<canvas>` with `captureStream()`.+Browsers throttle `requestAnimationFrame` in hidden tabs, so the video stalls+as soon as the user switches tabs. Display capture doesn't have that problem.++### Recording and storage++- One `MediaStream` holding the display video track (if any) and the mixed+ audio track goes into `MediaRecorder`.+- Pick the container with `MediaRecorder.isTypeSupported`:+ `video/mp4;codecs=avc1,opus` where available (recent Chromium, Safari),+ otherwise `video/webm;codecs=vp9,opus`; audio-only uses `audio/mp4` or+ `audio/webm;codecs=opus`.+- Don't buffer chunks in memory (an hour of 720p is several hundred MB).+ `start(timeslice)` streams one-second chunks to a file in the origin-private+ file system (OPFS), falling back to memory where OPFS writes aren't+ available. The file is downloaded when the recording stops.+ `showSaveFilePicker()` was rejected: it needs its own user gesture, which+ the capture prompt has already used up.+- WebM from `MediaRecorder` has no duration or cues, so players can't seek it.+ Prefer MP4; if WebM fix-up is needed, the dependency goes into core behind a+ `load-*.js` wrapper (plugins can't import npm modules).++### Lifecycle++Stop and finalize on:++- the record button being pressed again+- the display track's `ended` event (the browser's own "Stop sharing" bar)+- leaving the call or switching rooms++While recording, a `beforeunload` guard warns before a reload, because+anything not yet flushed is lost.++The menu entry binds its handler with `{{on "click"}}` rather than `DButton`'s+`@action`: Firefox only allows `getDisplayMedia` during the click dispatch+itself, and `@action` defers via `next()`.++## Controls++One "Record to this device" entry in the room's overflow (kebab) menu, on both+the room page and the call widget, not separate audio and video entries. The+recording badge already makes a running recording visible, so the control+doesn't need a spot in the call controls.++1. Browsers without `getDisplayMedia` (mobile) record audio only right away.+2. Otherwise the click opens the tab-capture prompt. If it is declined or+ fails, a dialog offers an audio-only recording instead.+3. Choosing the entry again stops the recording and downloads the file+ (through `deliverBlobDownload`, so the mobile app bridge works too).++Where the user can start a server (LiveKit) recording, the entry is hidden, so+nobody sees two ways to record.++## Reusing the recording indicator++`LiveRecordingBadge` already renders wherever a call is shown (room header,+call widget). It now shows for a server recording (`room.recording`), for the+current user's own local recording, or for any participant whose roster entry+has `is_recording_locally`. The tooltip lists each source on its own line.++The flag follows the transcript's `is_transcribing` precedent instead of a new+Redis key:++- `POST /live/rooms/:id/state` takes `recording_locally`. Turning it on+ requires `can_record_live_locally?`; turning it off is always allowed.+- It lives in participant metadata, so leave, kick, rejoin and presence expiry+ clear it with no extra cleanup, and the existing participants broadcast+ carries it.+- Participants who start recording after you joined are announced with a+ toast, as server recordings are. Recordings already running when you join+ are shown by the badge only.+- A server recording and local recordings never block each other.++The indicator is good-faith only. Nothing stops anyone running an OS screen+recorder; the feature makes the built-in path visible.++## Settings++- `live_local_recording_allowed_groups`: empty by default, which turns the+ feature off. Exposed to the client as `current_user.live_can_record_locally`.++## Not built yet++- Cropping the capture to the call area with Element Capture+ (`RestrictionTarget`) or Region Capture (`CropTarget`). The element must+ stay rendered, and the call widget follows the user across pages, so+ restricting to it would freeze the video on navigation. Needs a design for+ the widget case first.+- Recovering a recording left in storage by a crashed tab. Files older than an+ hour are deleted when the next recording starts.++## Testing++- RSpec: the `recording_locally` state flag (allowed, rejected, always+ clearable) and `can_record_live_locally?`.+- QUnit: container and filename choice, new-recorder announcements, the+ record button's audio-only, tab-capture and fallback paths, and the badge's+ titles.+- Not covered automatically: real capture and recording, which headless+ browsers can't exercise. Verify manually in Chromium, Firefox and Safari.diff --git a/plugins/live/lib/live/guardian_extension.rb b/plugins/live/lib/live/guardian_extension.rbindex 475c83c3234..ae009190d18 100644--- a/plugins/live/lib/live/guardian_extension.rb+++ b/plugins/live/lib/live/guardian_extension.rb@@ -183,6 +183,13 @@ module Livelive_media_entitlements(room)[:can_screen_share]end+ # Local recordings never touch the server; this only gates the control+ # and the roster flag that tells everyone else a recording is running.+ def can_record_live_locally?+ return false unless can_access_live?+ user.in_any_groups?(SiteSetting.live_local_recording_allowed_groups_map)+ end+# Only stage-room listeners have anything to request — anyone who can# already speak (including admins and everyone in open rooms) cannot.def can_request_to_speak_in_live_room?(room)diff --git a/plugins/live/plugin.rb b/plugins/live/plugin.rbindex 66253c161e1..ee7c85d722f 100644--- a/plugins/live/plugin.rb+++ b/plugins/live/plugin.rb@@ -150,6 +150,8 @@ after_initialize doinclude_condition: -> { scope.can_start_live_call? },) { scope.can_call_live_user?(object) }+ add_to_serializer(:current_user, :live_can_record_locally) { scope.can_record_live_locally? }+# Lets the client decide whether to render the rooms sidebar for anonymous# visitors without exposing the configured group ids.add_to_serializer(:site, :live_public_access) { scope.live_public_access? }diff --git a/plugins/live/spec/lib/live/guardian_extension_spec.rb b/plugins/live/spec/lib/live/guardian_extension_spec.rbindex ff0785e37ac..9fbecb57024 100644--- a/plugins/live/spec/lib/live/guardian_extension_spec.rb+++ b/plugins/live/spec/lib/live/guardian_extension_spec.rb@@ -91,6 +91,30 @@ RSpec.describe Live::GuardianExtension doendend+ describe "#can_record_live_locally?" do+ before do+ SiteSetting.live_local_recording_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"+ end++ it "is true for users in the local recording groups" do+ expect(member.guardian.can_record_live_locally?).to eq(true)+ end++ it "is false for users outside the local recording groups" do+ expect(low_trust_user.guardian.can_record_live_locally?).to eq(false)+ end++ it "is false for anonymous visitors" do+ expect(anonymous_guardian.can_record_live_locally?).to eq(false)+ end++ it "is false when no group is allowed" do+ SiteSetting.live_local_recording_allowed_groups = ""++ expect(member.guardian.can_record_live_locally?).to eq(false)+ end+ end+describe "#can_invite_live_agents?" doit "is true for admins by default" doexpect(staff.guardian.can_invite_live_agents?).to eq(true)diff --git a/plugins/live/spec/requests/live/rooms_controller_spec.rb b/plugins/live/spec/requests/live/rooms_controller_spec.rbindex 23e4f6b98ce..0ecb80e9d10 100644--- a/plugins/live/spec/requests/live/rooms_controller_spec.rb+++ b/plugins/live/spec/requests/live/rooms_controller_spec.rb@@ -1058,6 +1058,58 @@ RSpec.describe Live::RoomsController doexpect(metadata[:is_transcribing]).to eq(false)end+ context "when recording locally" do+ it "sets and clears the recording flag for allowed users" do+ SiteSetting.live_local_recording_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]++ post "/live/rooms/#{room.id}/state.json",+ params: {+ recording_locally: true,+ participant_session_id: @participant_session_id,+ }++ expect(response.status).to eq(204)+ metadata = Live::ParticipantTracker.get_metadata(room.id, user.id)+ expect(metadata[:is_recording_locally]).to eq(true)++ post "/live/rooms/#{room.id}/state.json",+ params: {+ recording_locally: false,+ participant_session_id: @participant_session_id,+ }++ metadata = Live::ParticipantTracker.get_metadata(room.id, user.id)+ expect(metadata[:is_recording_locally]).to eq(false)+ end++ it "rejects starting when the user's groups can't record" do+ SiteSetting.live_local_recording_allowed_groups = ""++ post "/live/rooms/#{room.id}/state.json",+ params: {+ recording_locally: true,+ participant_session_id: @participant_session_id,+ }++ expect(response.status).to eq(403)+ metadata = Live::ParticipantTracker.get_metadata(room.id, user.id)+ expect(metadata[:is_recording_locally]).to be_nil+ end++ # Losing the permission mid-recording must not strand the indicator.+ it "always allows clearing the flag" do+ SiteSetting.live_local_recording_allowed_groups = ""++ post "/live/rooms/#{room.id}/state.json",+ params: {+ recording_locally: false,+ participant_session_id: @participant_session_id,+ }++ expect(response.status).to eq(204)+ end+ end+it "rejects video when no group is allowed to share a camera" doSiteSetting.live_video_allowed_groups = ""diff --git a/plugins/live/test/javascripts/integration/components/live-room-page-test.gjs b/plugins/live/test/javascripts/integration/components/live-room-page-test.gjsindex 333deefb459..dcf21cf7485 100644--- a/plugins/live/test/javascripts/integration/components/live-room-page-test.gjs+++ b/plugins/live/test/javascripts/integration/components/live-room-page-test.gjs@@ -60,6 +60,10 @@ class LiveWebrtcStub extends Service {return false;}+ isRecordingLocally() {+ return false;+ }+setWatching() {}join() {}leave() {}diff --git a/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjs b/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjsindex 2ab2123e716..0a7b93fb201 100644--- a/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjs+++ b/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjs@@ -75,6 +75,10 @@ class LiveWebrtcStub extends Service {return false;}+ isRecordingLocally() {+ return false;+ }+remoteStreamFor(roomId, userId) {return this.videoStreams.get(`${roomId}:${userId}`);}diff --git a/plugins/live/test/javascripts/integration/components/live/local-recording-test.gjs b/plugins/live/test/javascripts/integration/components/live/local-recording-test.gjsnew file mode 100644index 00000000000..d7b7b33ed8d--- /dev/null+++ b/plugins/live/test/javascripts/integration/components/live/local-recording-test.gjs@@ -0,0 +1,160 @@+import { tracked } from "@glimmer/tracking";+import Service from "@ember/service";+import { click, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DialogHolder from "discourse/dialog-holder/components/dialog-holder";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { logIn } from "discourse/tests/helpers/qunit-helpers";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import LiveLocalRecordingMenuItem from "discourse/plugins/live/discourse/components/live/local-recording-menu-item";+import LiveRecordingBadge from "discourse/plugins/live/discourse/components/live/recording-badge";++class LiveWebrtcStub extends Service {+ @tracked recordingRoomId = null;++ screenShareSupported = false;+ startCalls = [];++ get localRecordingBusy() {+ return !!this.recordingRoomId;+ }++ isActiveRoom() {+ return true;+ }++ isLivekitRoom() {+ return false;+ }++ isRecordingLocally(roomId) {+ return this.recordingRoomId === roomId;+ }++ startLocalRecording(roomId, displayStream = null) {+ this.startCalls.push({ roomId, displayStream });+ this.recordingRoomId = roomId;+ }++ stopLocalRecording() {+ this.recordingRoomId = null;+ }+}++const RECORD_BUTTON = ".live-local-recording-toggle";++const MenuItem = <template>+ <DialogHolder />+ <DDropdownMenu as |dropdown|>+ <LiveLocalRecordingMenuItem @item={{dropdown.item}} @room={{@room}} />+ </DDropdownMenu>+</template>;++module("Integration | Component | live/local-recording", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.currentUser = logIn(this.owner);+ this.currentUser.set("live_can_record_locally", true);++ this.owner.unregister("service:live-webrtc");+ this.owner.register("service:live-webrtc", LiveWebrtcStub);+ this.liveWebrtc = this.owner.lookup("service:live-webrtc");++ this.room = { id: 1, slug: "standup", active_participants: [] };+ });++ test("hides the record entry without the permission", async function (assert) {+ this.currentUser.set("live_can_record_locally", false);+ const room = this.room;++ await render(<template><MenuItem @room={{room}} /></template>);++ assert.dom(RECORD_BUTTON).doesNotExist();+ });++ test("records audio only when the browser can't capture video", async function (assert) {+ const room = this.room;+ await render(<template><MenuItem @room={{room}} /></template>);++ await click(RECORD_BUTTON);+ assert.deepEqual(this.liveWebrtc.startCalls, [+ { roomId: 1, displayStream: null },+ ]);+ assert.dom(RECORD_BUTTON).hasClass("--recording");++ await click(RECORD_BUTTON);+ assert.dom(RECORD_BUTTON).doesNotHaveClass("--recording");+ });++ test("records the tab when the capture succeeds", async function (assert) {+ const displayStream = { id: "tab" };+ this.liveWebrtc.screenShareSupported = true;+ sinon+ .stub(navigator.mediaDevices, "getDisplayMedia")+ .resolves(displayStream);+ const room = this.room;++ await render(<template><MenuItem @room={{room}} /></template>);+ await click(RECORD_BUTTON);++ assert.deepEqual(this.liveWebrtc.startCalls, [+ { roomId: 1, displayStream },+ ]);+ });++ test("offers an audio-only recording when the capture fails", async function (assert) {+ this.liveWebrtc.screenShareSupported = true;+ sinon+ .stub(navigator.mediaDevices, "getDisplayMedia")+ .rejects(new DOMException("denied", "NotAllowedError"));+ const room = this.room;++ await render(<template><MenuItem @room={{room}} /></template>);+ await click(RECORD_BUTTON);++ assert+ .dom(".dialog-body")+ .hasText(+ "The call video couldn't be captured. Record audio only instead?"+ );+ assert.deepEqual(this.liveWebrtc.startCalls, []);++ await click(".dialog-footer .btn-primary");+ assert.deepEqual(this.liveWebrtc.startCalls, [+ { roomId: 1, displayStream: null },+ ]);+ });++ test("the badge covers server and local recordings", async function (assert) {+ const room = {+ id: 1,+ active_participants: [+ { id: 2, username: "alice", is_recording_locally: true },+ { id: 3, username: "bob" },+ ],+ };+ await render(<template><LiveRecordingBadge @room={{room}} /></template>);++ assert+ .dom(".live-recording-badge")+ .hasAttribute("title", "alice is recording this call to their device");++ this.liveWebrtc.recordingRoomId = 1;+ await settled();+ assert+ .dom(".live-recording-badge")+ .hasAttribute(+ "title",+ "You're recording this call to your device\nalice is recording this call to their device"+ );+ });++ test("the badge stays hidden when nobody is recording", async function (assert) {+ const room = { id: 1, active_participants: [{ id: 3, username: "bob" }] };+ await render(<template><LiveRecordingBadge @room={{room}} /></template>);++ assert.dom(".live-recording-badge").doesNotExist();+ });+});diff --git a/plugins/live/test/javascripts/unit/lib/local-recorder-test.js b/plugins/live/test/javascripts/unit/lib/local-recorder-test.jsnew file mode 100644index 00000000000..c8215741ce9--- /dev/null+++ b/plugins/live/test/javascripts/unit/lib/local-recorder-test.js@@ -0,0 +1,51 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import {+ pickMimeType,+ recordingFilename,+} from "discourse/plugins/live/discourse/lib/live/local-recorder";++module("Live | Unit | Lib | local-recorder", function (hooks) {+ setupTest(hooks);++ test("pickMimeType prefers MP4 and falls back to WebM", function (assert) {+ assert.strictEqual(+ pickMimeType(true, () => true),+ "video/mp4;codecs=avc1,opus"+ );+ assert.strictEqual(+ pickMimeType(true, (type) => type.startsWith("video/webm")),+ "video/webm;codecs=vp9,opus"+ );+ assert.strictEqual(+ pickMimeType(false, (type) => type.startsWith("audio/webm")),+ "audio/webm;codecs=opus"+ );+ assert.strictEqual(+ pickMimeType(false, () => false),+ undefined,+ "leaves the choice to the browser when nothing matches"+ );+ });++ test("recordingFilename stamps the local time and matches the container", function (assert) {+ const date = new Date(2026, 9, 28, 9, 5);++ assert.strictEqual(+ recordingFilename("standup", "video/mp4;codecs=avc1,opus", date),+ "standup-2026-10-28-0905.mp4"+ );+ assert.strictEqual(+ recordingFilename("standup", "audio/mp4", date),+ "standup-2026-10-28-0905.m4a"+ );+ assert.strictEqual(+ recordingFilename("standup", "audio/ogg;codecs=opus", date),+ "standup-2026-10-28-0905.ogg"+ );+ assert.strictEqual(+ recordingFilename("standup", "video/webm;codecs=vp9,opus", date),+ "standup-2026-10-28-0905.webm"+ );+ });+});diff --git a/plugins/live/test/javascripts/unit/lib/local-recording-coordinator-test.js b/plugins/live/test/javascripts/unit/lib/local-recording-coordinator-test.jsnew file mode 100644index 00000000000..f35520ebe8f--- /dev/null+++ b/plugins/live/test/javascripts/unit/lib/local-recording-coordinator-test.js@@ -0,0 +1,85 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import LocalRecordingCoordinator from "discourse/plugins/live/discourse/lib/live/local-recording-coordinator";++module("Live | Unit | Lib | local-recording-coordinator", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.activeRoomId = 1;+ this.coordinator = new LocalRecordingCoordinator({+ getCurrentUserId: () => 1,+ getParticipantSessionId: () => "session",+ getRoom: () => ({ slug: "room" }),+ isActiveRoom: (roomId) => roomId === this.activeRoomId,+ getAudioTracks: () => [],+ setParticipantRecording: () => {},+ showNotice: () => {},+ showError: () => {},+ });+ });++ hooks.afterEach(function () {+ this.coordinator.destroy();+ });++ test("trackRecorders announces only recorders who start after the baseline", function (assert) {+ const alice = { id: 2, username: "alice", is_recording_locally: true };+ const bob = { id: 3, username: "bob" };+ const self = { id: 1, username: "me", is_recording_locally: true };++ assert.deepEqual(+ this.coordinator.trackRecorders(1, [alice, bob, self]),+ [],+ "the first roster only sets the baseline"+ );++ assert.deepEqual(+ this.coordinator.trackRecorders(1, [+ alice,+ { ...bob, is_recording_locally: true },+ self,+ ]),+ ["bob"],+ "announces a new recorder, never the current user"+ );++ assert.deepEqual(+ this.coordinator.trackRecorders(1, [alice, bob, self]),+ [],+ "a recorder stopping is not announced"+ );++ assert.deepEqual(+ this.coordinator.trackRecorders(1, [+ alice,+ { ...bob, is_recording_locally: true },+ ]),+ ["bob"],+ "a recorder restarting is announced again"+ );++ this.coordinator.forgetRoom(1);+ assert.deepEqual(+ this.coordinator.trackRecorders(1, [+ alice,+ { ...bob, is_recording_locally: true },+ ]),+ [],+ "forgetting a room resets its baseline"+ );+ });++ test("start releases the capture when the room isn't the active call", async function (assert) {+ let stopped = false;+ const displayStream = {+ getTracks: () => [{ stop: () => (stopped = true) }],+ };++ await this.coordinator.start(2, displayStream);++ assert.true(stopped, "stops the display capture");+ assert.false(this.coordinator.busy);+ assert.false(this.coordinator.isRecording(2));+ });+});