diff --git a/CHANGELOG.md b/CHANGELOG.md index 7769f98..d616d4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,4 +20,9 @@ The first release is in preparation. optional H.264 through Cisco's OpenH264, AV1 decoding). - `tsgw`: companion gateway for server admins (presence, channel chat relay, history). +- Chat history: messages are kept on the device and, with a gateway, what + was said while away appears when a chat opens; scrolling back loads older + messages from the gateway. The same message seen twice (over voice and + through the gateway) is shown once. Settings: `chat.store_history`, + `chat.history_page`, `chat.dedupe_tolerance_ms`, `chat.retention_days`. - Opt-in local crash reports; third-party notices in the About page. diff --git a/Cargo.lock b/Cargo.lock index cf15994..5866139 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9176,16 +9176,19 @@ dependencies = [ "openh264", "pipewire", "reqwest", + "rtrb", "rustix 1.1.5", "sha2 0.10.9", "str0m", "thiserror 2.0.21", "tokio", "tracing", + "tracing-subscriber", "wasapi", "wayland-client", "wayland-protocols", "wayland-protocols-wlr", + "windows 0.62.2", "windows-capture", "x11rb", "yuv", diff --git a/README.md b/README.md index 3d1ac09..5ec0e91 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,9 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch with their TeamSpeak identity and get presence, channel chat and history without joining voice, limited by their server permissions ([admin guide](docs/gateway-admin.md)) - `crates/voelin-core`: client engine; sessions merge voice, gateway and query sources, route chat, run audio; - the media pipeline for streams (capture → VP8 + Opus → stream, stream → decoder) + chat history (stored on the device, synced with the gateway when a chat opens); the gateway's pins, + reactions, topics, events, stream directory and administration; the media pipeline for streams + (capture → VP8 + Opus → stream, stream → decoder) - `crates/voelin-ui` (`voelin`): Slint desktop app: servers, channel tree with talking indicators, chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk (in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on @@ -48,9 +50,10 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch clients through a TS6 server - `tools/voelinctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events, `query`, `observe` (invisible presence), `relay` (channel chat without joining) and `gateway` + (also through the engine with `--engine`: chat history, gateway requests, stream directory) - `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh` checks tree, server chat, channel chat, a voice tone round-trip, invisible presence, - relay chat and the gateway on both + relay chat, the gateway, chat history sync, pins/reactions/topics and the stream directory - `fuzz/`: cargo-fuzz targets for packets, commands and the license chain - `android/` + `crates/voelin-android`: the Android app (the same Slint UI in a NativeActivity, voice in a foreground service, screen sharing through MediaProjection, MediaCodec, Keystore @@ -97,6 +100,9 @@ cargo run -p voelinctl -- relay ssh 127.0.0.1:10022 --secret voelin-dev-admin -- # Gateway: users without voice, logging in with their identity cargo run -p voelin-gateway -- --config dev/tsgw-ts6.toml & cargo run -p voelinctl -- gateway ws://127.0.0.1:7788/v1 --identity --presence --open channel:1 +# ... through the engine: stored history synced with the gateway, then a request +cargo run -p voelinctl -- gateway ws://127.0.0.1:7788/v1 --identity --engine \ + --db /tmp/chat.db --chat channel:1 --older 1 --request '{"pins":{"target":{"kind":"channel","id":1}}}' scripts/it-smoke.sh # all of the above, on both servers ``` diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 3004993..6716b43 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -11,6 +11,17 @@ + + + + + + + + diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt index 145f25a..64a199a 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt @@ -2,6 +2,7 @@ package io.github.faumaray.voelin import android.Manifest import android.content.Context +import android.content.Intent import android.content.pm.PackageManager import android.os.Build @@ -62,6 +63,40 @@ object Bridge { ScreenCaptureService.stopAudio() } + /** + * Capture into mixer input `id` (Native.onAudioInput) what `packageName` + * plays, or with null everything but us. False without a running screen + * capture or for a package we cannot see. + */ + @JvmStatic + fun startAudioInput(id: Long, packageName: String?): Boolean = + ScreenCaptureService.startInput(app, id, packageName) + + @JvmStatic + fun stopAudioInput(id: Long) { + ScreenCaptureService.stopInput(id) + } + + /** Launchable apps other than us, as "labelpackage" lines sorted by label. */ + @JvmStatic + fun launchableApps(): String { + val pm = app.packageManager + val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) + val activities = if (Build.VERSION.SDK_INT >= 33) { + pm.queryIntentActivities(launcher, PackageManager.ResolveInfoFlags.of(0)) + } else { + @Suppress("DEPRECATION") + pm.queryIntentActivities(launcher, 0) + } + val separators = Regex("[\t\n]") + return activities + .map { it.activityInfo.packageName to it.loadLabel(pm).toString() } + .filter { it.first != app.packageName } + .distinctBy { it.first } + .sortedBy { it.second.lowercase() } + .joinToString("\n") { (packageName, label) -> label.replace(separators, " ") + "\t" + packageName } + } + @JvmStatic fun secretGet(key: String): String? = SecretStore.get(app, key) diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt index 5f91cea..7aacd8e 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt @@ -35,6 +35,13 @@ object Native { @JvmStatic external fun onSystemAudio(samples: FloatArray, count: Int, channels: Int, timestampNs: Long): Boolean + /** + * `count` interleaved 48 kHz float samples for mixer input `id` + * (Bridge.startAudioInput). Returns false when it is no longer wanted. + */ + @JvmStatic + external fun onAudioInput(id: Long, samples: FloatArray, count: Int, channels: Int): Boolean + /** "Disconnect" in the voice notification. */ @JvmStatic external fun onDisconnectVoice() diff --git a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt index 485f654..0daf999 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt @@ -22,9 +22,11 @@ import android.os.Handler import android.os.HandlerThread import android.os.IBinder import android.os.Looper +import android.os.Process import android.util.Log import android.view.Display import android.view.Surface +import java.util.concurrent.ConcurrentHashMap import kotlin.concurrent.thread import kotlin.math.max import kotlin.math.roundToInt @@ -32,8 +34,9 @@ import kotlin.math.roundToInt /** * Screen sharing: holds the MediaProjection (a `mediaProjection` foreground * service, as Android requires), mirrors the display into an ImageReader and - * hands each RGBA frame to Native.onScreenFrame; optionally captures what the - * device plays (AudioPlaybackCapture) for Native.onSystemAudio. + * hands each RGBA frame to Native.onScreenFrame; optionally captures what + * other apps play (AudioPlaybackCapture: all but us, or one app) for + * Native.onSystemAudio and Native.onAudioInput. */ class ScreenCaptureService : Service() { private var projection: MediaProjection? = null @@ -41,9 +44,17 @@ class ScreenCaptureService : Service() { private var reader: ImageReader? = null private var worker: HandlerThread? = null - @Volatile - private var audioRunning = false - private var audioThread: Thread? = null + /** A running AudioPlaybackCapture recording. */ + private class AudioCapture { + @Volatile + var running = true + + @Volatile + var thread: Thread? = null + } + + /** Recordings by id: SYSTEM_AUDIO, or a mixer input of the Rust side. */ + private val captures = ConcurrentHashMap() private val main = Handler(Looper.getMainLooper()) @@ -148,18 +159,24 @@ class ScreenCaptureService : Service() { ) } - /** Capture media, game and unknown-usage playback as 48 kHz stereo float. */ - private fun startAudioCapture(): Boolean { + /** + * Capture media, game and unknown-usage playback as 48 kHz stereo float: + * of app `uid`, or with null of every app but us (our voices and watched + * streams). Several recordings may run at once. + */ + private fun startAudioCapture(id: Long, uid: Int?): Boolean { val projection = projection ?: return false - if (audioRunning) return true + if (captures[id]?.running == true) return true if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { return false } - val config = AudioPlaybackCaptureConfiguration.Builder(projection) + val builder = AudioPlaybackCaptureConfiguration.Builder(projection) .addMatchingUsage(AudioAttributes.USAGE_MEDIA) .addMatchingUsage(AudioAttributes.USAGE_GAME) .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN) - .build() + // Uid rules cannot mix matching and excluding; one of them. + if (uid != null) builder.addMatchingUid(uid) else builder.excludeUid(Process.myUid()) + val config = builder.build() val format = AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_FLOAT) .setSampleRate(SAMPLE_RATE) @@ -174,22 +191,30 @@ class ScreenCaptureService : Service() { .setBufferSizeInBytes(max(minimum, SAMPLE_RATE / 10 * 2 * 4)) .build() } catch (e: Exception) { - Log.w(TAG, "system audio capture unavailable", e) + Log.w(TAG, "playback capture unavailable", e) return false } - audioRunning = true + val capture = AudioCapture() + captures[id] = capture record.startRecording() - audioThread = thread(name = "voelin-system-audio") { + capture.thread = thread(name = "voelin-audio-$id") { // 10 ms of stereo. val buffer = FloatArray(SAMPLE_RATE / 100 * 2) try { - while (audioRunning) { + while (capture.running) { val read = record.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING) if (read < 0) break - if (read > 0 && !Native.onSystemAudio(buffer, read, 2, System.nanoTime())) break + if (read == 0) continue + val wanted = if (id == SYSTEM_AUDIO) { + Native.onSystemAudio(buffer, read, 2, System.nanoTime()) + } else { + Native.onAudioInput(id, buffer, read, 2) + } + if (!wanted) break } } finally { - audioRunning = false + capture.running = false + captures.remove(id, capture) record.stop() record.release() } @@ -197,15 +222,15 @@ class ScreenCaptureService : Service() { return true } - private fun stopAudioCapture() { - audioRunning = false - audioThread?.join(500) - audioThread = null + private fun stopAudioCapture(id: Long) { + val capture = captures.remove(id) ?: return + capture.running = false + capture.thread?.join(500) } override fun onDestroy() { if (instance === this) instance = null - stopAudioCapture() + captures.keys.toList().forEach { stopAudioCapture(it) } display?.release() display = null reader?.close() @@ -222,6 +247,9 @@ class ScreenCaptureService : Service() { private const val TAG = "ScreenCaptureService" private const val ID = 2 private const val SAMPLE_RATE = 48_000 + + /** The recording for Native.onSystemAudio (Rust input ids start at 1). */ + private const val SYSTEM_AUDIO = 0L private const val ACTION_STOP = "io.github.faumaray.voelin.STOP_SHARING" private const val EXTRA_RESULT = "result" private const val EXTRA_DATA = "data" @@ -247,11 +275,37 @@ class ScreenCaptureService : Service() { fun startAudio(): Boolean { val service = instance ?: return false - return service.startAudioCapture() + return service.startAudioCapture(SYSTEM_AUDIO, null) } fun stopAudio() { - instance?.stopAudioCapture() + instance?.stopAudioCapture(SYSTEM_AUDIO) + } + + /** Capture `packageName` (null: every app but us) into mixer input `id`. */ + fun startInput(context: Context, id: Long, packageName: String?): Boolean { + val service = instance ?: return false + val uid = if (packageName == null) { + null + } else { + try { + val pm = context.packageManager + if (Build.VERSION.SDK_INT >= 33) { + pm.getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(0)).uid + } else { + @Suppress("DEPRECATION") + pm.getApplicationInfo(packageName, 0).uid + } + } catch (e: PackageManager.NameNotFoundException) { + Log.w(TAG, "no package $packageName to capture") + return false + } + } + return service.startAudioCapture(id, uid) + } + + fun stopInput(id: Long) { + instance?.stopAudioCapture(id) } } } diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index 8b5d065..f7d442d 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -111,6 +111,71 @@ pub fn stop_system_audio() -> Result<()> { }) } +/// Capture playback into mixer input `id` (delivered to +/// `Native.onAudioInput`): of the app `package`, or everything but ours. +/// `false` without a running screen capture, or for a package that is not +/// installed (or not visible to us). +pub fn start_audio_input(id: u64, package: Option<&str>) -> Result { + with_bridge(|env, class| { + let package = match package { + Some(package) => JObject::from(env.new_string(package)?), + None => JObject::null(), + }; + env.call_static_method( + class, + jni_str!("startAudioInput"), + jni_sig!((id: jlong, package: java.lang.String) -> jboolean), + &[JValue::Long(id as jlong), JValue::Object(&package)], + )? + .z() + }) +} + +pub fn stop_audio_input(id: u64) -> Result<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("stopAudioInput"), + jni_sig!((id: jlong) -> void), + &[JValue::Long(id as jlong)], + )?; + Ok(()) + }) +} + +/// Launchable apps other than ours, as `(label, package)`, sorted by label. +pub fn launchable_apps() -> Result> { + let lines = with_bridge(|env, class| { + let value = env + .call_static_method( + class, + jni_str!("launchableApps"), + jni_sig!(() -> java.lang.String), + &[], + )? + .l()?; + if value.is_null() { + return Ok(String::new()); + } + let value = env.cast_local::(value)?; + value.try_to_string(env) + })?; + Ok(parse_apps(&lines)) +} + +/// `labelpackage` lines. +fn parse_apps(lines: &str) -> Vec<(String, String)> { + lines + .lines() + .filter_map(|line| { + let (label, package) = line.split_once('\t')?; + let package = package.trim(); + let label = if label.trim().is_empty() { package } else { label.trim() }; + (!package.is_empty()).then(|| (label.to_owned(), package.to_owned())) + }) + .collect() +} + pub fn secret_get(key: &str) -> Result> { with_bridge(|env, class| { let key = JObject::from(env.new_string(key)?); @@ -250,6 +315,36 @@ fn on_system_audio<'local>( Ok(crate::capture::on_audio(buffer, channels.clamp(1, 8) as u16, timestamp_ns)) } +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_audio_input(id: jlong, samples: jfloat[], count: jint, channels: jint) -> jboolean, +}; + +/// Interleaved 48 kHz float samples for mixer input `id` (see +/// [`start_audio_input`]). Returns `false` once the input is gone. +fn on_audio_input<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + id: jlong, + samples: JFloatArray<'local>, + count: jint, + channels: jint, +) -> Result { + thread_local! { + // One per capture thread, reused for every call. + static BUFFER: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let id = id as u64; + if !crate::capture::wants_input(id) { + return Ok(false); + } + BUFFER.with_borrow_mut(|buffer| { + buffer.resize(count.max(0) as usize, 0.0); + samples.get_region(env, 0, buffer)?; + Ok(crate::capture::on_input(id, buffer, channels.clamp(1, 8) as u16)) + }) +} + const _: jni::NativeMethod = native_method! { java_type = "io.github.faumaray.voelin.Native", static extern fn on_disconnect_voice(), diff --git a/crates/voelin-android/src/capture.rs b/crates/voelin-android/src/capture.rs index 9a2a298..a52d8d7 100644 --- a/crates/voelin-android/src/capture.rs +++ b/crates/voelin-android/src/capture.rs @@ -5,15 +5,21 @@ //! asks the Kotlin side for the user's consent; on consent it runs //! `ScreenCaptureService` (a `mediaProjection` foreground service) whose //! `ImageReader` hands RGBA frames to [`on_frame`]. System audio -//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection. +//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection: +//! everything but our own uid, or one app's uid, each into a stream mixer +//! input ([`on_input`]); several captures may run at once. +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use tokio::sync::oneshot; use tracing::warn; use voelin_media::capture::external::{self, AudioProvider, ScreenProvider}; +use voelin_media::capture::playback::{AppMatch, AudioApp, PlaybackFilter}; use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use voelin_media::mix::SourceInput; use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; use crate::bridge; @@ -29,6 +35,8 @@ struct State { /// Answer for the pending `start`. pending: Option>>, audio: Option>, + /// Mixer inputs of [`AudioProvider::start_input`] captures, by id. + inputs: HashMap, /// Clock origin of frame and audio timestamps (both `CLOCK_MONOTONIC` /// nanoseconds: `Image.timestamp`, `System.nanoTime`), so they stay in sync. origin_ns: Option, @@ -135,6 +143,89 @@ impl AudioProvider for PlaybackAudio { warn!("stopping system audio: {e}"); } } + + /// Everything but our uid, or the uid of one app's package. + fn start_input(&self, filter: &PlaybackFilter, input: SourceInput) -> Result { + let package = match filter { + PlaybackFilter::AllButSelf => None, + PlaybackFilter::App(app @ AppMatch::Name(name)) => Some( + self.apps() + .into_iter() + .find(|a| { + app.matches_name([a.name.as_str(), a.binary.as_deref().unwrap_or("")]) + }) + .and_then(|a| a.binary) + // Not launchable (a service, say): maybe the package itself. + .unwrap_or_else(|| name.trim().to_owned()), + ), + PlaybackFilter::App(AppMatch::Pid(_)) => { + return Err(Error::CaptureUnavailable { + backend: AUDIO, + reason: "Android captures apps by package, not by process".into(), + }); + } + }; + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + with_state(|s| s.inputs.insert(id, input)); + let started = bridge::start_audio_input(id, package.as_deref()); + if let Ok(true) = started { + return Ok(id); + } + with_state(|s| s.inputs.remove(&id)); + let reason = match (started, package) { + (Err(e), _) => e.to_string(), + (_, Some(package)) => format!( + "cannot capture {package}: not installed, or no running screen capture (and \ + the microphone permission)" + ), + (_, None) => "needs a running screen capture (and the microphone permission)".into(), + }; + Err(Error::CaptureUnavailable { backend: AUDIO, reason }) + } + + fn stop_input(&self, id: u64) { + with_state(|s| s.inputs.remove(&id)); + if let Err(e) = bridge::stop_audio_input(id) { + warn!("stopping audio capture {id}: {e}"); + } + } + + /// Android cannot tell which apps play: the launchable ones. + fn apps(&self) -> Vec { + match bridge::launchable_apps() { + Ok(apps) => apps + .into_iter() + .map(|(name, package)| AudioApp { + name, + binary: Some(package), + ..AudioApp::default() + }) + .collect(), + Err(e) => { + warn!("listing apps: {e}"); + Vec::new() + } + } + } +} + +pub fn wants_input(id: u64) -> bool { + with_state(|s| s.inputs.get(&id).is_some_and(|i| !i.is_closed())) +} + +/// Captured playback for mixer input `id`. Returns `false` once the input +/// is gone (the capture then stops). +pub fn on_input(id: u64, samples: &[f32], channels: u16) -> bool { + with_state(|s| { + let Some(input) = s.inputs.get_mut(&id) else { return false }; + input.push(samples, channels); + if input.is_closed() { + s.inputs.remove(&id); + return false; + } + true + }) } /// The user answered the consent dialog (or the service failed to start). diff --git a/crates/voelin-audio/src/lib.rs b/crates/voelin-audio/src/lib.rs index 80693e8..0494562 100644 --- a/crates/voelin-audio/src/lib.rs +++ b/crates/voelin-audio/src/lib.rs @@ -10,6 +10,8 @@ //! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the //! vendored `tsclientlib::audio::AudioHandler`) //! - [`settings`]: all user audio settings in one serde struct +//! - [`tap`]: the processed microphone for other consumers (the stream +//! mixer), free while nobody listens //! - `device` (feature `device`): capture and playback through cpal, device //! lists and loss detection @@ -20,6 +22,7 @@ pub mod pcm; pub mod process; pub mod resample; pub mod settings; +pub mod tap; pub mod vad; pub mod wav; diff --git a/crates/voelin-audio/src/tap.rs b/crates/voelin-audio/src/tap.rs new file mode 100644 index 0000000..53d0f54 --- /dev/null +++ b/crates/voelin-audio/src/tap.rs @@ -0,0 +1,217 @@ +//! Taps: the processed microphone for consumers besides the voice +//! connection, such as the audio mixer of our screen share. +//! +//! The voice pipeline publishes every processed chunk (48 kHz mono, after +//! echo cancellation, noise suppression and gain control) to +//! [`microphone()`]. Unused, that is one relaxed atomic load per chunk. +//! With consumers attached ([`Tap::attach`]) the publisher hands the chunk +//! to each [`TapSink`] on its own thread; it never waits: the consumer list +//! is taken with a try-lock that only contends with attaching and +//! detaching, and a chunk that meets such a change is skipped. +//! +//! Several pipelines can run at once (one per server, the microphone +//! test); the tap follows one of them at a time: the first that publishes, +//! until it has been silent for [`HANDOVER`], then whichever publishes next. + +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; +use std::time::{Duration, Instant}; + +/// A publisher silent this long loses the tap to another one. +pub const HANDOVER: Duration = Duration::from_millis(200); + +/// Receives tapped audio on the publisher's thread. Must not block. +pub trait TapSink: Send { + /// 48 kHz mono samples. + fn write(&mut self, samples: &[f32]); + + /// `frames` samples of silence (e.g. while the microphone is muted). + fn silence(&mut self, frames: usize); +} + +/// A publish point that any number of consumers can attach to. +pub struct Tap { + /// Attached sinks: the only thing publishers look at when unused. + active: AtomicUsize, + sinks: Mutex)>>, + next_sink: AtomicU64, + /// The publisher followed now (0: none) and when it last published + /// (milliseconds since `epoch`). + owner: AtomicU64, + owner_seen: AtomicU64, +} + +static MICROPHONE: Tap = Tap::new(); +static NEXT_PUBLISHER: AtomicU64 = AtomicU64::new(1); + +/// Processed microphone audio, 48 kHz mono. +pub fn microphone() -> &'static Tap { + &MICROPHONE +} + +/// An id for a publisher (one per voice pipeline). +pub fn publisher_id() -> u64 { + NEXT_PUBLISHER.fetch_add(1, Ordering::Relaxed) +} + +fn now_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 +} + +impl Default for Tap { + fn default() -> Self { + Self::new() + } +} + +impl Tap { + pub const fn new() -> Self { + Self { + active: AtomicUsize::new(0), + sinks: Mutex::new(Vec::new()), + next_sink: AtomicU64::new(1), + owner: AtomicU64::new(0), + owner_seen: AtomicU64::new(0), + } + } + + /// Whether anyone listens: publishers skip all work otherwise. + #[inline] + pub fn is_active(&self) -> bool { + self.active.load(Ordering::Relaxed) != 0 + } + + /// Attach a consumer until the returned guard is dropped. + pub fn attach(&self, sink: Box) -> TapGuard<'_> { + let id = self.next_sink.fetch_add(1, Ordering::Relaxed); + let mut sinks = self.sinks.lock().unwrap_or_else(PoisonError::into_inner); + sinks.push((id, sink)); + self.active.store(sinks.len(), Ordering::Relaxed); + TapGuard { tap: self, id } + } + + fn detach(&self, id: u64) { + let mut sinks = self.sinks.lock().unwrap_or_else(PoisonError::into_inner); + sinks.retain(|(i, _)| *i != id); + self.active.store(sinks.len(), Ordering::Relaxed); + } + + /// Whether `publisher` is the one followed now (taking over from one + /// that went silent). + fn follows(&self, publisher: u64) -> bool { + let now = now_ms(); + let owner = self.owner.load(Ordering::Acquire); + if owner != publisher { + let stale = now.saturating_sub(self.owner_seen.load(Ordering::Relaxed)) + >= HANDOVER.as_millis() as u64; + if owner != 0 && !stale { + return false; + } + if self + .owner + .compare_exchange(owner, publisher, Ordering::AcqRel, Ordering::Relaxed) + .is_err() + { + return false; + } + } + self.owner_seen.store(now, Ordering::Relaxed); + true + } + + /// Hand `samples` to every consumer (no-op without consumers, or when + /// another publisher is followed). + pub fn publish(&self, publisher: u64, samples: &[f32]) { + if !self.is_active() || samples.is_empty() || !self.follows(publisher) { + return; + } + if let Ok(mut sinks) = self.sinks.try_lock() { + for (_, sink) in sinks.iter_mut() { + sink.write(samples); + } + } + } + + /// Hand `frames` samples of silence to every consumer. + pub fn publish_silence(&self, publisher: u64, frames: usize) { + if !self.is_active() || frames == 0 || !self.follows(publisher) { + return; + } + if let Ok(mut sinks) = self.sinks.try_lock() { + for (_, sink) in sinks.iter_mut() { + sink.silence(frames); + } + } + } +} + +/// Detaches its consumer when dropped. +pub struct TapGuard<'a> { + tap: &'a Tap, + id: u64, +} + +impl Drop for TapGuard<'_> { + fn drop(&mut self) { + self.tap.detach(self.id); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + #[derive(Clone, Default)] + struct Collect(Arc>>); + + impl TapSink for Collect { + fn write(&mut self, samples: &[f32]) { + self.0.lock().unwrap().extend_from_slice(samples); + } + + fn silence(&mut self, frames: usize) { + self.0.lock().unwrap().extend(std::iter::repeat_n(0.0, frames)); + } + } + + #[test] + fn consumers_attach_and_detach() { + let tap = Tap::new(); + let (a, b) = (publisher_id(), publisher_id()); + assert!(!tap.is_active()); + tap.publish(a, &[1.0]); + let first = Collect::default(); + let guard = tap.attach(Box::new(first.clone())); + assert!(tap.is_active()); + tap.publish(a, &[0.5, 0.25]); + tap.publish_silence(a, 2); + // Another publisher is ignored while the first is live. + tap.publish(b, &[9.0]); + let second = Collect::default(); + let guard2 = tap.attach(Box::new(second.clone())); + tap.publish(a, &[0.125]); + drop(guard); + tap.publish(a, &[0.0625]); + assert_eq!(*first.0.lock().unwrap(), [0.5, 0.25, 0.0, 0.0, 0.125]); + assert_eq!(*second.0.lock().unwrap(), [0.125, 0.0625]); + drop(guard2); + assert!(!tap.is_active()); + } + + #[test] + fn a_silent_publisher_hands_over() { + let tap = Tap::new(); + let (a, b) = (publisher_id(), publisher_id()); + let sink = Collect::default(); + let _guard = tap.attach(Box::new(sink.clone())); + tap.publish(a, &[1.0]); + tap.publish(b, &[2.0]); + std::thread::sleep(HANDOVER + Duration::from_millis(20)); + tap.publish(b, &[3.0]); + tap.publish(a, &[4.0]); + assert_eq!(*sink.0.lock().unwrap(), [1.0, 3.0]); + } +} diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 5b507cb..886cf3c 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -43,7 +43,7 @@ tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } [dev-dependencies] -tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "test-util"] } [lints] workspace = true diff --git a/crates/voelin-core/src/audio.rs b/crates/voelin-core/src/audio.rs index 0bc55d2..5d4602f 100644 --- a/crates/voelin-core/src/audio.rs +++ b/crates/voelin-core/src/audio.rs @@ -20,6 +20,7 @@ use tsclientlib::ClientId; use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket}; use voelin_audio::pcm::{self, FRAME_SAMPLES}; use voelin_audio::settings::TransmitMode; +use voelin_audio::tap; use voelin_audio::vad::SILENCE_DB; use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder}; @@ -145,6 +146,10 @@ struct Pipeline { /// Watched streams whose audio plays through the mixer. streams: HashMap, stream_volumes: HashMap, + /// Where processed microphone audio is published (for our screen + /// share's microphone source), and our id as its publisher. + mic_tap: &'static tap::Tap, + tap_id: u64, /// Processed microphone audio, for tests. #[cfg(test)] tap: Vec, @@ -168,6 +173,8 @@ impl Pipeline { level_peak: None, streams: HashMap::new(), stream_volumes: HashMap::new(), + mic_tap: tap::microphone(), + tap_id: tap::publisher_id(), settings, #[cfg(test)] tap: Vec::new(), @@ -276,6 +283,15 @@ impl Pipeline { self.processor.capture(samples, &mut self.processed); #[cfg(test)] self.tap.extend_from_slice(&self.processed); + // Our screen share's microphone source; one atomic load when unused. + let mic = self.mic_tap; + if mic.is_active() { + if self.input_muted { + mic.publish_silence(self.tap_id, self.processed.len()); + } else { + mic.publish(self.tap_id, &self.processed); + } + } let mut frames = Vec::new(); self.framer.push(&self.processed, |f| frames.push(f.to_vec())); for frame in frames { @@ -576,6 +592,41 @@ mod tests { assert_eq!(capture(&mut p, &tone), (0, 0)); } + /// The processed microphone reaches tap consumers (silence while muted, + /// whatever the transmit mode), and nothing is done without one. + #[test] + fn processed_microphone_reaches_the_tap() { + use std::sync::{Arc, Mutex}; + + static TAP: tap::Tap = tap::Tap::new(); + struct Sink(Arc>>); + impl tap::TapSink for Sink { + fn write(&mut self, samples: &[f32]) { + self.0.lock().unwrap().extend_from_slice(samples); + } + fn silence(&mut self, frames: usize) { + self.0.lock().unwrap().extend(std::iter::repeat_n(0.0, frames)); + } + } + + let mut p = pipeline(TransmitMode::PushToTalk); + p.mic_tap = &TAP; + let tone = sine(440.0, 0.1, 0.3); + capture(&mut p, &tone); + let got = Arc::new(Mutex::new(Vec::new())); + let guard = TAP.attach(Box::new(Sink(got.clone()))); + // Not transmitting (push-to-talk released): still tapped. + assert_eq!(capture(&mut p, &tone), (0, 0)); + assert_eq!(*got.lock().unwrap(), tone); + p.handle(AudioIn::InputMuted(true)); + capture(&mut p, &tone); + let got_now = got.lock().unwrap().clone(); + assert_eq!(got_now.len(), 2 * tone.len()); + assert!(got_now[tone.len()..].iter().all(|s| *s == 0.0)); + drop(guard); + assert!(!TAP.is_active()); + } + #[test] fn voice_activation_with_pre_roll() { let mut p = pipeline(TransmitMode::VoiceActivation); diff --git a/crates/voelin-core/src/gateway.rs b/crates/voelin-core/src/gateway.rs index fba4406..f35e14a 100644 --- a/crates/voelin-core/src/gateway.rs +++ b/crates/voelin-core/src/gateway.rs @@ -1,22 +1,59 @@ -//! The gateway source: presence and relayed chat through `tsgw`, and the -//! typed client for everything else a gateway offers (pins, reactions, -//! topics, events, the stream directory, the activity feed, -//! administration). +//! The gateway source: presence and relayed chat through `tsgw`, and +//! everything else a gateway offers (history, pins, reactions, topics, +//! events, the stream directory, the activity feed, administration). //! //! [`GatewayClient`] (from `voelin-gateway-proto`, feature `client`) has one //! async method per request and delivers pushes as [`Push`]; //! [`GatewayClient::capabilities`] says which features the gateway and user -//! have, so the UI can hide the rest. The data types (`HistoryQuery`, -//! `PinInfo`, `EventSpec`, `StreamEntry`, …) are in `voelin_gateway_proto`. -//! [`connect`] logs in with the user's TeamSpeak identity. The engine uses -//! [`run`] for presence and chat. +//! have. The data types (`HistoryQuery`, `PinInfo`, `EventSpec`, +//! `StreamEntry`, …) are in `voelin_gateway_proto`. [`connect`] logs in +//! with the user's TeamSpeak identity. +//! +//! # In the engine +//! +//! [`crate::Command::ObserveGateway`] starts a session's gateway: invisible +//! presence, relayed chat, chat history ([`crate::history`]). The session +//! then takes [`crate::Command::Gateway`] with a [`GatewayRequest`] and +//! reports answers and pushes as [`crate::Event::Gateway`] with a +//! [`GatewayUpdate`]: +//! +//! - [`GatewayUpdate::Connected`] after login, with the capabilities +//! ([`voelin_gateway_proto::feature`]; hide what is missing); +//! [`GatewayUpdate::Capabilities`] when they change; +//! [`GatewayUpdate::Disconnected`] when the gateway is gone. +//! - Each request is answered with its update (e.g. `Pins` for +//! [`GatewayRequest::Pins`]), [`GatewayUpdate::Done`] for requests without +//! data, or [`GatewayUpdate::Failed`] (gateway error code and message). +//! - Pushes: pins, reactions and topic changes of open chats, event +//! changes and reminders, stream directory and activity changes. The +//! engine subscribes to events, streams and activity when the gateway +//! has them (the `Subscribe*` requests turn that off and on). +//! - Messages the gateway returns (posts, pins, topic history) and message +//! changes (pins, reactions) are stored and also emitted as +//! [`crate::Event::ChatHistory`], so the chat view updates by local id. +//! Message ids in requests are the gateway's +//! ([`crate::history::HistoryMessage::remote_id`]). +//! - Our own stream (TeamSpeak 6) registers itself in the directory when it +//! goes live and the gateway has `streams` ([`GatewayUpdate::StreamRegistered`]), +//! and is removed when it ends. The directory is also where the session's +//! streams look for streams that started before we joined, next to the +//! server's `requeststreaminfo`. +use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; use tracing::info; use voelin_gateway_proto::client::Login; pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push}; -use voelin_gateway_proto::{ClientMsg, ErrorCode}; -use voelin_model::{ChatMessage, ChatTarget, Presence}; +use voelin_gateway_proto::{ + Action, ActivityEntry, ClientMsg, ConfigEntry, ErrorCode, EventInfo, EventQuery, EventSpec, + HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry, + StreamSpec, TopicInfo, UserRef, +}; +use voelin_model::{ChannelId, ChatTarget, Presence}; +use voelin_store::WriteOutcome; + +use crate::Event; +use crate::history::{ChatCtx, HistoryMessage, HistorySource, gateway_message, store_target}; pub(crate) enum GatewayCmd { OpenChat(ChatTarget), @@ -26,10 +63,11 @@ pub(crate) enum GatewayCmd { } pub(crate) enum GatewayEvent { - Connected, + /// Logged in; requests go through `client`. + Connected(GatewayClient), Presence(Presence), - Chat(ChatMessage), - Error(String), + /// A push other than presence. + Push(Box), Disconnected(Option), } @@ -54,6 +92,14 @@ pub(crate) async fn run( let _ = events.send(GatewayEvent::Disconnected(reason)); } +/// Features whose pushes for open chats need [`ClientMsg::Enable`]. +const CHAT_EXTENSIONS: [&str; 4] = [ + voelin_gateway_proto::feature::HISTORY, + voelin_gateway_proto::feature::PINS, + voelin_gateway_proto::feature::REACTIONS, + voelin_gateway_proto::feature::TOPICS, +]; + async fn run_inner( url: &str, identity: &tsclientlib::Identity, @@ -63,13 +109,19 @@ async fn run_inner( let (client, mut pushes) = match connect(url, identity).await { Ok(connected) => connected, Err(ClientError::Gateway { code, message }) => { - let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}"))); + let _ = events + .send(GatewayEvent::Push(Box::new(Push::Error { code, message: message.clone() }))); anyhow::bail!("gateway refused login: {message}"); } Err(e) => return Err(e.into()), }; info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected"); - let _ = events.send(GatewayEvent::Connected); + // Messages with their gateway ids, pins, reactions and topics of open + // chats (older gateways answer `unknown_type` as a push; ignored). + if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) { + client.send(ClientMsg::Enable { features: Vec::new() })?; + } + let _ = events.send(GatewayEvent::Connected(client.clone())); client.subscribe_presence()?; let mut presence = Presence::default(); @@ -86,19 +138,18 @@ async fn run_inner( presence.apply(&delta); let _ = events.send(GatewayEvent::Presence(presence.clone())); } - Some(Push::Chat { message, .. }) => { - let _ = events.send(GatewayEvent::Chat(message)); + // Answers to requests sent without waiting. + Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {} + Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => { + let _ = events.send(GatewayEvent::Push(Box::new(Push::Error { + code: ErrorCode::NotAuthenticated, + message: message.clone(), + }))); + anyhow::bail!("gateway session lost: {message}"); } - Some(Push::Message(entry)) => { - let _ = events.send(GatewayEvent::Chat(entry.message)); + Some(push) => { + let _ = events.send(GatewayEvent::Push(Box::new(push))); } - Some(Push::Error { code, message }) => { - let _ = events.send(GatewayEvent::Error(format!("{code:?}: {message}"))); - if code == ErrorCode::NotAuthenticated { - anyhow::bail!("gateway session lost: {message}"); - } - } - Some(_) => {} }, cmd = commands.recv() => match cmd { None | Some(GatewayCmd::Stop) => return Ok(()), @@ -111,3 +162,574 @@ async fn run_inner( } } } + +/// Something to ask a session's gateway ([`crate::Command::Gateway`]). +/// Message ids are the gateway's. Serialized in snake case, e.g. +/// `{"pin":{"message_id":7}}`, `"config_list"`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GatewayRequest { + /// Report the capabilities again ([`GatewayUpdate::Capabilities`]). + Capabilities, + /// What the user may do, server-wide or in `channel` + /// ([`GatewayUpdate::Permissions`]). + Permissions { + #[serde(default)] + channel: Option, + }, + /// Post into a chat, optionally into a topic ([`GatewayUpdate::Posted`]). + Post { + target: ChatTarget, + text: String, + #[serde(default)] + topic: Option, + }, + Pin { + message_id: i64, + }, + Unpin { + message_id: i64, + }, + /// [`GatewayUpdate::Pins`]. + Pins { + target: ChatTarget, + }, + React { + message_id: i64, + emoji: String, + }, + Unreact { + message_id: i64, + emoji: String, + }, + /// Who reacted with `emoji` ([`GatewayUpdate::Reactors`]). + Reactors { + message_id: i64, + emoji: String, + }, + /// Start a topic, from a message or standalone ([`GatewayUpdate::Topic`]). + CreateTopic { + target: ChatTarget, + title: String, + #[serde(default)] + message_id: Option, + }, + /// Rename or (un)archive a topic ([`GatewayUpdate::Topic`]). + UpdateTopic { + topic_id: i64, + #[serde(default)] + title: Option, + #[serde(default)] + archived: Option, + }, + /// [`GatewayUpdate::Topics`], most recently active first. + Topics { + target: ChatTarget, + #[serde(default)] + include_archived: bool, + }, + /// A topic's messages before gateway message `before` (the latest + /// without), `limit` of them (`chat.history_page` without) + /// ([`GatewayUpdate::TopicHistory`]). + TopicHistory { + target: ChatTarget, + topic: i64, + #[serde(default)] + before: Option, + #[serde(default)] + limit: Option, + }, + /// [`GatewayUpdate::Event`]. + CreateEvent { + event: EventSpec, + }, + /// [`GatewayUpdate::Event`]. + UpdateEvent { + id: i64, + event: EventSpec, + }, + DeleteEvent { + id: i64, + }, + /// One event with its attendees ([`GatewayUpdate::Event`]). + GetEvent { + id: i64, + }, + /// [`GatewayUpdate::Events`], by start time. + Events { + #[serde(default)] + query: EventQuery, + }, + /// Answer an invitation; `None` withdraws the answer ([`GatewayUpdate::Event`]). + Rsvp { + event_id: i64, + #[serde(default)] + status: Option, + }, + /// Event changes and reminders as pushes (on by default). + SubscribeEvents { + on: bool, + }, + /// The stream directory ([`GatewayUpdate::Streams`]). + Streams, + /// Directory changes as pushes (on by default). + SubscribeStreams { + on: bool, + }, + /// Add a stream to the directory (our own stream registers itself; + /// [`GatewayUpdate::StreamRegistered`]). + RegisterStream { + stream: StreamSpec, + }, + UpdateStream { + stream_id: String, + #[serde(default)] + title: Option, + #[serde(default)] + viewers: Option, + }, + UnregisterStream { + stream_id: String, + }, + /// Newest first, entries with an id below `before` ([`GatewayUpdate::Activity`]). + Activity { + #[serde(default)] + before: Option, + #[serde(default)] + limit: Option, + }, + /// New activity as pushes (on by default). + SubscribeActivity { + on: bool, + }, + /// Administration (capability `admin`): [`GatewayUpdate::Config`]. + ConfigList, + /// [`GatewayUpdate::ConfigValue`]. + ConfigGet { + key: String, + }, + /// Store a runtime value at the gateway ([`GatewayUpdate::ConfigValue`]). + ConfigSet { + key: String, + value: serde_json::Value, + }, + /// Drop the runtime value ([`GatewayUpdate::ConfigValue`]). + ConfigReset { + key: String, + }, + /// Read the gateway's file again ([`GatewayUpdate::Config`]). + ConfigReload, + /// [`GatewayUpdate::PermRules`]. + PermList, + PermSet { + action: Action, + rule: PermRule, + }, + PermReset { + action: Action, + }, +} + +impl GatewayRequest { + /// The request's name, as in [`GatewayUpdate::Done`] and [`GatewayUpdate::Failed`]. + pub fn name(&self) -> &'static str { + match self { + GatewayRequest::Capabilities => "capabilities", + GatewayRequest::Permissions { .. } => "permissions", + GatewayRequest::Post { .. } => "post", + GatewayRequest::Pin { .. } => "pin", + GatewayRequest::Unpin { .. } => "unpin", + GatewayRequest::Pins { .. } => "pins", + GatewayRequest::React { .. } => "react", + GatewayRequest::Unreact { .. } => "unreact", + GatewayRequest::Reactors { .. } => "reactors", + GatewayRequest::CreateTopic { .. } => "create_topic", + GatewayRequest::UpdateTopic { .. } => "update_topic", + GatewayRequest::Topics { .. } => "topics", + GatewayRequest::TopicHistory { .. } => "topic_history", + GatewayRequest::CreateEvent { .. } => "create_event", + GatewayRequest::UpdateEvent { .. } => "update_event", + GatewayRequest::DeleteEvent { .. } => "delete_event", + GatewayRequest::GetEvent { .. } => "get_event", + GatewayRequest::Events { .. } => "events", + GatewayRequest::Rsvp { .. } => "rsvp", + GatewayRequest::SubscribeEvents { .. } => "subscribe_events", + GatewayRequest::Streams => "streams", + GatewayRequest::SubscribeStreams { .. } => "subscribe_streams", + GatewayRequest::RegisterStream { .. } => "register_stream", + GatewayRequest::UpdateStream { .. } => "update_stream", + GatewayRequest::UnregisterStream { .. } => "unregister_stream", + GatewayRequest::Activity { .. } => "activity", + GatewayRequest::SubscribeActivity { .. } => "subscribe_activity", + GatewayRequest::ConfigList => "config_list", + GatewayRequest::ConfigGet { .. } => "config_get", + GatewayRequest::ConfigSet { .. } => "config_set", + GatewayRequest::ConfigReset { .. } => "config_reset", + GatewayRequest::ConfigReload => "config_reload", + GatewayRequest::PermList => "perm_list", + GatewayRequest::PermSet { .. } => "perm_set", + GatewayRequest::PermReset { .. } => "perm_reset", + } + } +} + +/// A pinned message. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Pin { + /// The message as stored ([`HistoryMessage::id`] is the local id). + pub message: HistoryMessage, + pub by: UserRef, + pub ts_ms: i64, +} + +/// What a session's gateway reports ([`crate::Event::Gateway`]). +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GatewayUpdate { + /// Logged in. + Connected { + gateway_id: String, + server_uid: String, + server_name: String, + /// Our unique id on the server. + uid: String, + /// See [`voelin_gateway_proto::feature`]. + capabilities: Vec, + }, + /// The features available to us changed. + Capabilities { + capabilities: Vec, + }, + /// The gateway connection ended (nothing of it is available). + Disconnected { + reason: Option, + }, + /// A request without data succeeded (e.g. `pin`, `react`, `subscribe_*`). + Done { + request: String, + }, + /// A request failed; `code` is the gateway's (`None`: not connected, + /// connection lost, unexpected answer). + Failed { + request: String, + code: Option, + message: String, + }, + Permissions { + channel: Option, + actions: Vec, + }, + /// Our post, as stored. + Posted { + message: HistoryMessage, + }, + Pins { + target: ChatTarget, + pins: Vec, + }, + /// Push (chat open) or our pin. + Pinned { + target: ChatTarget, + pin: Pin, + }, + /// Push (chat open). + Unpinned { + target: ChatTarget, + message_id: i64, + by: UserRef, + }, + /// Push (chat open): `user` added or removed `emoji`; `count` is the new total. + Reaction { + target: ChatTarget, + message_id: i64, + emoji: String, + user: UserRef, + added: bool, + count: u32, + }, + Reactors { + message_id: i64, + emoji: String, + users: Vec, + }, + /// A topic: created, changed (also as a push), or new activity. + Topic { + topic: TopicInfo, + }, + Topics { + target: ChatTarget, + topics: Vec, + }, + /// A page of a topic's messages, oldest first, stored. + TopicHistory { + target: ChatTarget, + topic: i64, + messages: Vec, + has_more: bool, + }, + /// An event: the answer to create, update, get and rsvp, or a push + /// (created or changed, RSVP counts, going live). + Event { + event: EventInfo, + }, + Events { + events: Vec, + }, + /// Push. + EventDeleted { + id: i64, + }, + /// Push at the gateway's reminder times before an event starts (0: it starts). + EventReminder { + event: EventInfo, + starts_in_ms: i64, + }, + /// The whole directory (answer to `streams`, and after subscribing). + Streams { + streams: Vec, + }, + /// Push. + StreamStarted { + stream: StreamEntry, + }, + /// Push. + StreamUpdated { + stream: StreamEntry, + }, + /// Push. + StreamEnded { + id: String, + reason: String, + }, + /// A stream we registered (our own stream when it goes live). + StreamRegistered { + stream: StreamEntry, + }, + /// Newest first. + Activity { + entries: Vec, + has_more: bool, + }, + /// Push. + ActivityAdded { + entry: ActivityEntry, + }, + Config { + entries: Vec, + }, + ConfigValue { + entry: ConfigEntry, + }, + PermRules { + rules: Vec, + }, +} + +/// Carry out a request and report the answer. +pub(crate) async fn execute(ctx: ChatCtx, client: GatewayClient, request: GatewayRequest) { + let name = request.name(); + let update = match answer(&ctx, &client, request).await { + Ok(Some(update)) => update, + Ok(None) => GatewayUpdate::Done { request: name.into() }, + Err(e) => { + GatewayUpdate::Failed { request: name.into(), code: e.code(), message: e.to_string() } + } + }; + ctx.emit(Event::Gateway { session: ctx.session, update }); +} + +/// Store gateway messages; as stored (local id 0 if storing failed). +async fn stored(ctx: &ChatCtx, entries: &[HistoryEntry]) -> Vec { + match ctx.store_entries(entries).await { + Ok(written) => written.into_iter().map(|w| w.message.into()).collect(), + Err(e) => { + tracing::warn!("cannot store gateway messages: {e}"); + entries.iter().map(HistoryMessage::unstored).collect() + } + } +} + +async fn answer( + ctx: &ChatCtx, + client: &GatewayClient, + request: GatewayRequest, +) -> Result, ClientError> { + use GatewayRequest as R; + use GatewayUpdate as U; + Ok(Some(match request { + R::Capabilities => U::Capabilities { capabilities: client.capabilities() }, + R::Permissions { channel } => { + U::Permissions { channel, actions: client.permissions(channel).await? } + } + R::Post { target, text, topic } => { + let entry = client.post(target.clone(), text, topic).await?; + let message = stored(ctx, std::slice::from_ref(&entry)).await.remove(0); + ctx.emit_batch(&target, vec![message.clone()], HistorySource::Live, false); + U::Posted { message } + } + R::Pin { message_id } => return client.pin(message_id).await.map(|()| None), + R::Unpin { message_id } => return client.unpin(message_id).await.map(|()| None), + R::Pins { target } => { + let pins = client.pins(target.clone()).await?; + let entries: Vec = pins.iter().map(|p| p.entry.clone()).collect(); + let messages = stored(ctx, &entries).await; + let pins = pins + .into_iter() + .zip(messages) + .map(|(p, message)| Pin { message, by: p.by, ts_ms: p.ts_ms }) + .collect(); + U::Pins { target, pins } + } + R::React { message_id, emoji } => { + return client.react(message_id, emoji).await.map(|()| None); + } + R::Unreact { message_id, emoji } => { + return client.unreact(message_id, emoji).await.map(|()| None); + } + R::Reactors { message_id, emoji } => { + let users = client.reactors(message_id, emoji.clone()).await?; + U::Reactors { message_id, emoji, users } + } + R::CreateTopic { target, title, message_id } => { + U::Topic { topic: client.create_topic(target, title, message_id).await? } + } + R::UpdateTopic { topic_id, title, archived } => { + U::Topic { topic: client.update_topic(topic_id, title, archived).await? } + } + R::Topics { target, include_archived } => { + let topics = client.topics(target.clone(), include_archived).await?; + U::Topics { target, topics } + } + R::TopicHistory { target, topic, before, limit } => { + let mut query = HistoryQuery::latest(target.clone(), limit.or(ctx.page_limit())); + query.before = before; + query.topic = Some(topic); + let page = client.history(query).await?; + let messages = stored(ctx, &page.messages).await; + U::TopicHistory { target, topic, messages, has_more: page.has_more } + } + R::CreateEvent { event } => U::Event { event: client.create_event(event).await? }, + R::UpdateEvent { id, event } => U::Event { event: client.update_event(id, event).await? }, + R::DeleteEvent { id } => return client.delete_event(id).await.map(|()| None), + R::GetEvent { id } => U::Event { event: client.event(id).await? }, + R::Events { query } => U::Events { events: client.events(query).await? }, + R::Rsvp { event_id, status } => U::Event { event: client.rsvp(event_id, status).await? }, + R::SubscribeEvents { on: true } => return client.subscribe_events().await.map(|()| None), + R::SubscribeEvents { on: false } => { + return client.unsubscribe_events().await.map(|()| None); + } + R::Streams => U::Streams { streams: client.streams().await? }, + R::SubscribeStreams { on: true } => { + U::Streams { streams: client.subscribe_streams().await? } + } + R::SubscribeStreams { on: false } => { + return client.unsubscribe_streams().await.map(|()| None); + } + R::RegisterStream { stream } => { + U::StreamRegistered { stream: client.register_stream(stream).await? } + } + R::UpdateStream { stream_id, title, viewers } => { + U::StreamUpdated { stream: client.update_stream(stream_id, title, viewers).await? } + } + R::UnregisterStream { stream_id } => { + return client.unregister_stream(stream_id).await.map(|()| None); + } + R::Activity { before, limit } => { + let (entries, has_more) = client.activity(before, limit).await?; + U::Activity { entries, has_more } + } + R::SubscribeActivity { on: true } => { + return client.subscribe_activity().await.map(|()| None); + } + R::SubscribeActivity { on: false } => { + return client.unsubscribe_activity().await.map(|()| None); + } + R::ConfigList => U::Config { entries: client.config_list().await? }, + R::ConfigGet { key } => U::ConfigValue { entry: client.config_get(key).await? }, + R::ConfigSet { key, value } => { + U::ConfigValue { entry: client.config_set(key, value).await? } + } + R::ConfigReset { key } => U::ConfigValue { entry: client.config_reset(key).await? }, + R::ConfigReload => U::Config { entries: client.config_reload().await? }, + R::PermList => U::PermRules { rules: client.perm_list().await? }, + R::PermSet { action, rule } => U::PermRules { rules: client.perm_set(action, rule).await? }, + R::PermReset { action } => U::PermRules { rules: client.perm_reset(action).await? }, + })) +} + +/// Pushes about messages of open chats: stored, then reported, in the +/// order they arrived (the writer thread runs jobs in order). +impl ChatCtx { + pub(crate) fn pinned(&self, target: ChatTarget, pin: PinInfo) { + let mut entry = pin.entry.clone(); + entry.pinned = true; + let ctx = self.clone(); + self.history.write( + self.memory(), + vec![gateway_message(&self.server_uid, &entry)], + self.tolerance_ms(), + move |result| { + let message = match result.ok().and_then(|mut w| w.pop()) { + Some(w) => { + let changed = w.outcome != WriteOutcome::Unchanged; + let message = HistoryMessage::from(w.message); + if changed { + ctx.emit_batch( + &target, + vec![message.clone()], + HistorySource::Live, + false, + ); + } + message + } + None => HistoryMessage::unstored(&entry), + }; + let pin = Pin { message, by: pin.by, ts_ms: pin.ts_ms }; + let update = GatewayUpdate::Pinned { target, pin }; + ctx.emit(Event::Gateway { session: ctx.session, update }); + }, + ); + } + + pub(crate) fn unpinned(&self, target: ChatTarget, message_id: i64, by: UserRef) { + let (uid, key, ctx) = (self.server_uid.clone(), store_target(&target), self.clone()); + self.history.run_then( + self.memory(), + move |s| s.set_pinned(&uid, &key, message_id, false), + move |result| { + ctx.emit_changed(result.ok().flatten()); + let update = GatewayUpdate::Unpinned { target, message_id, by }; + ctx.emit(Event::Gateway { session: ctx.session, update }); + }, + ); + } + + /// A reaction push; `own_uid` tells whether it was ours. + pub(crate) fn reaction(&self, push: ReactionPush, own_uid: Option<&str>) { + let ReactionPush { target, message_id, emoji, user, added, count } = push; + let me = (own_uid == Some(user.uid.as_str())).then_some(added); + let (uid, key, ctx) = (self.server_uid.clone(), store_target(&target), self.clone()); + let e = emoji.clone(); + self.history.run_then( + self.memory(), + move |s| s.set_reaction(&uid, &key, message_id, &e, count, me), + move |result| { + ctx.emit_changed(result.ok().flatten()); + let update = + GatewayUpdate::Reaction { target, message_id, emoji, user, added, count }; + ctx.emit(Event::Gateway { session: ctx.session, update }); + }, + ); + } +} + +/// The fields of [`Push::Reaction`]. +pub(crate) struct ReactionPush { + pub target: ChatTarget, + pub message_id: i64, + pub emoji: String, + pub user: UserRef, + pub added: bool, + pub count: u32, +} diff --git a/crates/voelin-core/src/history.rs b/crates/voelin-core/src/history.rs new file mode 100644 index 0000000..a9d0397 --- /dev/null +++ b/crates/voelin-core/src/history.rs @@ -0,0 +1,812 @@ +//! Chat history: every chat message a session sees is stored, and opening a +//! chat shows what is stored, then what the gateway has that we missed. +//! +//! # Contract for the UI +//! +//! A chat's messages are [`HistoryMessage`]s, keyed by +//! [`HistoryMessage::id`] (the local id, stable on this device) and ordered +//! by `(message.ts_ms, id)`. Every [`Event::ChatHistory`] is an upsert of +//! messages into that list: +//! +//! - [`crate::Command::OpenChat`] (and every (re)connect of a source that +//! tells the server's unique id) emits the newest `chat.history_page` +//! stored messages at once, [`HistorySource::Local`]. If the session has +//! a gateway that keeps history (capability `history`), the gateway's +//! messages we do not have yet follow: everything newer than the chat's +//! sync cursor (the latest page when the chat was never synced), stored +//! and emitted in batches of `chat.history_page`, [`HistorySource::Gateway`]. +//! A last `Gateway` batch, possibly empty, says the chat is in sync. +//! Until one arrives the list holds only what this device saw: label it +//! so ("only messages seen by this device"). +//! - [`crate::Command::LoadOlderHistory`] emits the page before a message: +//! the gateway's page for that time range is fetched and merged first when +//! the session has one (`Gateway`), else the stored one (`Local`). +//! - Live messages (voice, gateway pushes, query relays, our own sends) are +//! stored and emitted one by one as [`HistorySource::Live`]; so are +//! changes of stored messages (pins, reactions, the gateway id arriving +//! for a message seen over voice). A copy of a message that is already +//! there (it arrived over voice and from the gateway) is merged into the +//! existing row: same id, no second message. +//! - `complete: true`: nothing older than the batch exists as far as the +//! engine can tell; stop offering to load older messages. +//! +//! [`Event::Chat`] still reports each live message as before (without ids). +//! +//! Merging copies ("dedupe") is described in [`voelin_store::chat`]: the +//! gateway id when known, else the same text (without a relay's `[nick] ` +//! prefix), author and time within `chat.dedupe_tolerance_ms`, from +//! different sources. +//! +//! # Storage +//! +//! [`History`] owns a database connection on a writer thread: writes are +//! batched into one transaction per wake-up, statements are cached, and the +//! engine's tasks never wait on the disk. `chat.store_history` (read on +//! every write) off keeps messages in memory for this run only; their ids +//! are negative. `chat.retention_days` prunes old messages (pinned ones +//! stay). Without [`crate::Command::AttachHistory`] the engine keeps its +//! history in memory. + +use std::collections::VecDeque; +use std::path::Path; +use std::sync::mpsc as std_mpsc; +use std::sync::{Arc, Mutex, PoisonError, RwLock}; +use std::thread::JoinHandle; + +use serde::Serialize; +use tokio::sync::{broadcast, oneshot}; +use tracing::warn; +use voelin_gateway_proto::{HistoryEntry, HistoryQuery, ReactionCount, feature}; +use voelin_model::{ChatMessage, ChatTarget}; +pub use voelin_store::MessageSource; +use voelin_store::{ChatCursor, WriteOutcome}; +use voelin_store::{NewMessage, PageQuery, Reaction, RemoteInfo, Store, StoredMessage, Written}; + +use crate::gateway::{GatewayClient, GatewayUpdate}; +use crate::settings::{CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_STORE_HISTORY, Settings}; +use crate::{Event, SessionId}; + +/// A chat message with what the engine knows about it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct HistoryMessage { + /// Local id, stable on this device (negative: kept in memory only). + pub id: i64, + pub message: ChatMessage, + /// What delivered it first. + pub source: MessageSource, + /// The gateway's id: pin, react and start topics with it. + pub remote_id: Option, + /// The gateway topic the message belongs to. + pub topic_id: Option, + /// In order of the first reaction. + pub reactions: Vec, + pub pinned: bool, + /// Gateway revision of the last change (0 without a gateway copy). + pub rev: i64, +} + +/// Where the messages of an [`Event::ChatHistory`] come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HistorySource { + /// Stored on this device: only what it saw (or fetched before). + Local, + /// Fetched from the session's gateway (and stored). + Gateway, + /// New or changed just now. + Live, +} + +pub(crate) fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget { + match target { + ChatTarget::Server => voelin_store::ChatTarget::Server, + ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid), + ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()), + } +} + +fn model_target(target: &voelin_store::ChatTarget) -> ChatTarget { + match target { + voelin_store::ChatTarget::Server => ChatTarget::Server, + voelin_store::ChatTarget::Channel(cid) => ChatTarget::Channel(*cid), + voelin_store::ChatTarget::Private(uid) => ChatTarget::Private(uid.clone()), + } +} + +impl From for HistoryMessage { + fn from(m: StoredMessage) -> Self { + Self { + id: m.id, + message: ChatMessage { + target: model_target(&m.target), + author_name: m.author_name, + author_uid: m.author_uid, + author_id: m.author_id, + text: m.text, + ts_ms: m.ts_ms, + via_relay: m.via_relay, + }, + source: m.source, + remote_id: m.remote_id, + topic_id: m.topic_id, + reactions: m + .reactions + .into_iter() + .map(|r| ReactionCount { emoji: r.emoji, count: r.count, me: r.me }) + .collect(), + pinned: m.pinned, + rev: m.rev, + } + } +} + +impl HistoryMessage { + /// A gateway message that could not be stored (local id 0). + pub(crate) fn unstored(entry: &HistoryEntry) -> Self { + Self { + id: 0, + message: entry.message.clone(), + source: MessageSource::Gateway, + remote_id: Some(entry.id), + topic_id: entry.topic_id, + reactions: entry.reactions.clone(), + pinned: entry.pinned, + rev: entry.rev, + } + } +} + +/// A live message (voice, query relay, our own) to store. +pub(crate) fn new_message( + server_uid: &str, + msg: &ChatMessage, + source: MessageSource, +) -> NewMessage { + NewMessage { + server_uid: server_uid.to_owned(), + target: store_target(&msg.target), + ts_ms: msg.ts_ms, + author_uid: msg.author_uid.clone(), + author_name: msg.author_name.clone(), + author_id: msg.author_id, + via_relay: msg.via_relay, + text: msg.text.clone(), + source, + remote: None, + } +} + +/// A gateway message to store. +pub(crate) fn gateway_message(server_uid: &str, entry: &HistoryEntry) -> NewMessage { + let mut m = new_message(server_uid, &entry.message, MessageSource::Gateway); + m.remote = Some(RemoteInfo { + id: entry.id, + rev: entry.rev, + topic_id: entry.topic_id, + reactions: entry + .reactions + .iter() + .map(|r| Reaction { emoji: r.emoji.clone(), count: r.count, me: r.me }) + .collect(), + pinned: entry.pinned, + }); + m +} + +type Done = Box) + Send>; + +enum Job { + Write { memory: bool, messages: Vec, tolerance_ms: i64, done: Done> }, + Run { memory: bool, f: Box }, + Flush(std_mpsc::Sender<()>), +} + +struct Inner { + jobs: Mutex>>, + thread: Mutex>>, + persistent: bool, +} + +impl Drop for Inner { + fn drop(&mut self) { + // Closing the queue ends the writer after the pending jobs. + self.jobs.get_mut().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(thread) = self.thread.get_mut().unwrap_or_else(PoisonError::into_inner).take() + // The last handle may go with a job's callback, on the writer + // itself: it ends on its own once the queue is empty. + && thread.thread().id() != std::thread::current().id() + { + let _ = thread.join(); + } + } +} + +/// The chat history database; see the [module docs](self). Cheap to clone. +#[derive(Clone)] +pub struct History { + inner: Arc, +} + +impl std::fmt::Debug for History { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("History").field("persistent", &self.inner.persistent).finish() + } +} + +impl Default for History { + fn default() -> Self { + Self::in_memory() + } +} + +/// First id of messages kept in memory only (`chat.store_history` off): +/// negative, so they never collide with stored ones. +const MEMORY_IDS: i64 = -(1 << 62); + +impl History { + /// History in the client database at `path` (its own connection). + pub fn open(path: &Path) -> Result { + Ok(Self::start(Store::open(path)?, true)) + } + + /// History kept in memory for this run. + pub fn in_memory() -> Self { + let store = + Store::open_in_memory().and_then(|s| s.start_message_ids_at(MEMORY_IDS).map(|()| s)); + Self::start(store.expect("in-memory database"), false) + } + + /// History in `store`, which moves to the writer thread. + pub fn with_store(store: Store) -> Self { + Self::start(store, true) + } + + fn start(store: Store, persistent: bool) -> Self { + let (tx, rx) = std_mpsc::channel(); + let thread = std::thread::Builder::new() + .name("chat-history".into()) + .spawn(move || writer(store, persistent, rx)) + .expect("history thread"); + Self { + inner: Arc::new(Inner { + jobs: Mutex::new(Some(tx)), + thread: Mutex::new(Some(thread)), + persistent, + }), + } + } + + /// Whether messages go to a database file (else memory). + pub fn is_persistent(&self) -> bool { + self.inner.persistent + } + + fn send(&self, job: Job) { + let jobs = self.inner.jobs.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(tx) = jobs.as_ref() { + let _ = tx.send(job); + } + } + + /// Wait until everything queued so far is done (blocking). + pub fn flush(&self) { + let (tx, rx) = std_mpsc::channel(); + self.send(Job::Flush(tx)); + let _ = rx.recv(); + } + + /// Queue messages; `done` runs on the writer thread after they are stored. + pub(crate) fn write( + &self, + memory: bool, + messages: Vec, + tolerance_ms: i64, + done: impl FnOnce(Result, String>) + Send + 'static, + ) { + self.send(Job::Write { memory, messages, tolerance_ms, done: Box::new(done) }); + } + + pub(crate) async fn write_async( + &self, + memory: bool, + messages: Vec, + tolerance_ms: i64, + ) -> Result, String> { + let (tx, rx) = oneshot::channel(); + self.write(memory, messages, tolerance_ms, move |r| { + let _ = tx.send(r); + }); + rx.await.map_err(|_| "chat history stopped".to_string())? + } + + /// Run `f` on the writer thread, after the jobs queued before. + pub(crate) async fn run( + &self, + memory: bool, + f: impl FnOnce(&mut Store) -> voelin_store::Result + Send + 'static, + ) -> Result { + let (tx, rx) = oneshot::channel(); + self.send(Job::Run { + memory, + f: Box::new(move |store| { + let _ = tx.send(f(store).map_err(|e| e.to_string())); + }), + }); + rx.await.map_err(|_| "chat history stopped".to_string())? + } + + /// Run `f` on the writer thread, then `then` with its result (there too). + pub(crate) fn run_then( + &self, + memory: bool, + f: impl FnOnce(&mut Store) -> voelin_store::Result + Send + 'static, + then: impl FnOnce(Result) + Send + 'static, + ) { + self.send(Job::Run { + memory, + f: Box::new(move |store| then(f(store).map_err(|e| e.to_string()))), + }); + } + + /// Stored messages of a chat, oldest first (from the database; with + /// `memory`, from what was kept in memory while `chat.store_history` + /// was off). + pub async fn page( + &self, + server_uid: &str, + target: &ChatTarget, + query: PageQuery, + memory: bool, + ) -> Result, String> { + let (uid, target) = (server_uid.to_owned(), store_target(target)); + let rows = self.run(memory, move |s| s.messages(&uid, &target, query)).await?; + Ok(rows.into_iter().map(HistoryMessage::from).collect()) + } + + /// Delete messages older than `before_ms` (pinned ones stay). + pub(crate) fn prune(&self, before_ms: i64) { + self.send(Job::Run { + memory: false, + f: Box::new(move |store| { + if let Err(e) = store.prune_messages(before_ms) { + warn!("cannot prune chat history: {e}"); + } + }), + }); + } +} + +/// The writer thread: runs jobs in order; consecutive writes to the same +/// database go into one transaction. +fn writer(store: Store, persistent: bool, rx: std_mpsc::Receiver) { + let mut main = store; + // For `chat.store_history` off while the main store is a file. + let mut ephemeral: Option = None; + while let Ok(first) = rx.recv() { + let mut queue: VecDeque = std::iter::once(first).chain(rx.try_iter()).collect(); + while let Some(job) = queue.pop_front() { + match job { + Job::Write { memory, messages, tolerance_ms, done } => { + let mut batch = vec![(messages, done)]; + while let Some(Job::Write { memory: m, tolerance_ms: t, .. }) = queue.front() + && *m == memory && *t == tolerance_ms + { + let Some(Job::Write { messages, done, .. }) = queue.pop_front() else { + unreachable!() + }; + batch.push((messages, done)); + } + let store = pick(&mut main, &mut ephemeral, persistent, memory); + let all: Vec = + batch.iter().flat_map(|(m, _)| m.iter().cloned()).collect(); + match store.write_messages(&all, tolerance_ms) { + Ok(written) => { + let mut written = written.into_iter(); + for (messages, done) in batch { + done(Ok(written.by_ref().take(messages.len()).collect())); + } + } + Err(e) => { + warn!("cannot store chat messages: {e}"); + for (_, done) in batch { + done(Err(e.to_string())); + } + } + } + } + Job::Run { memory, f } => f(pick(&mut main, &mut ephemeral, persistent, memory)), + Job::Flush(done) => { + let _ = done.send(()); + } + } + } + } +} + +/// The store a job uses: the main one, or with `memory` while the main one +/// is a file, one in memory. +fn pick<'a>( + main: &'a mut Store, + ephemeral: &'a mut Option, + persistent: bool, + memory: bool, +) -> &'a mut Store { + if !(memory && persistent) { + return main; + } + ephemeral.get_or_insert_with(|| { + let store = Store::open_in_memory().expect("in-memory database"); + if let Err(e) = store.start_message_ids_at(MEMORY_IDS) { + warn!("in-memory chat ids: {e}"); + } + store + }) +} + +/// The engine's history: one [`History`] that +/// [`crate::Command::AttachHistory`] can replace, shared by the sessions. +#[derive(Clone, Debug, Default)] +pub(crate) struct SharedHistory(Arc>); + +impl SharedHistory { + pub fn new(history: History) -> Self { + Self(Arc::new(RwLock::new(history))) + } + + pub fn current(&self) -> History { + self.0.read().unwrap_or_else(PoisonError::into_inner).clone() + } + + pub fn replace(&self, history: History) { + *self.0.write().unwrap_or_else(PoisonError::into_inner) = history; + } +} + +/// What the chat history flows of one session need. +#[derive(Clone)] +pub(crate) struct ChatCtx { + pub session: SessionId, + pub events: broadcast::Sender, + pub history: History, + pub settings: Settings, + /// The key of the server's history. + pub server_uid: String, +} + +impl ChatCtx { + /// `chat.store_history` off: memory only. + pub fn memory(&self) -> bool { + !self.settings.get(&CHAT_STORE_HISTORY) + } + + /// `chat.history_page`; `None`: no limit. + pub fn page_limit(&self) -> Option { + Some(self.settings.get(&CHAT_HISTORY_PAGE)).filter(|n| *n > 0) + } + + pub fn tolerance_ms(&self) -> i64 { + self.settings.get(&CHAT_DEDUPE_TOLERANCE_MS).min(i64::MAX as u64) as i64 + } + + pub fn emit(&self, event: Event) { + let _ = self.events.send(event); + } + + pub fn emit_batch( + &self, + target: &ChatTarget, + messages: Vec, + source: HistorySource, + complete: bool, + ) { + self.emit(Event::ChatHistory { + session: self.session, + target: target.clone(), + messages, + source, + complete, + }); + } + + fn gateway_failed(&self, request: &str, error: &crate::gateway::ClientError) { + self.emit(Event::Gateway { + session: self.session, + update: GatewayUpdate::Failed { + request: request.to_owned(), + code: error.code(), + message: error.to_string(), + }, + }); + } + + /// Store live messages; each new or changed one is emitted as + /// [`HistorySource::Live`] from the writer thread. + pub fn store_live(&self, messages: Vec) { + let (session, events) = (self.session, self.events.clone()); + self.history.write(self.memory(), messages, self.tolerance_ms(), move |result| { + for w in result.unwrap_or_default() { + if w.outcome == WriteOutcome::Unchanged { + continue; + } + let message = HistoryMessage::from(w.message); + let _ = events.send(Event::ChatHistory { + session, + target: message.message.target.clone(), + messages: vec![message], + source: HistorySource::Live, + complete: false, + }); + } + }); + } + + /// Store gateway entries; returns the stored rows in input order. + pub async fn store_entries(&self, entries: &[HistoryEntry]) -> Result, String> { + let messages = entries.iter().map(|e| gateway_message(&self.server_uid, e)).collect(); + self.history.write_async(self.memory(), messages, self.tolerance_ms()).await + } + + /// Emit a stored message that changed (e.g. its pin), as `Live`. + pub fn emit_changed(&self, message: Option) { + if let Some(m) = message { + let m = HistoryMessage::from(m); + let target = m.message.target.clone(); + self.emit_batch(&target, vec![m], HistorySource::Live, false); + } + } +} + +/// Whether a gateway keeps the history of `target` (it relays server and +/// channel chat, not private chat). +pub(crate) fn gateway_history(client: &GatewayClient, target: &ChatTarget) -> bool { + !matches!(target, ChatTarget::Private(_)) && client.has(feature::HISTORY) +} + +/// A chat opened (or its session reconnected): the stored page, then what +/// the gateway has that we do not. +pub(crate) async fn open_chat( + ctx: ChatCtx, + target: ChatTarget, + gateway: Option, + gateway_pending: bool, +) { + let gateway = gateway.filter(|g| gateway_history(g, &target)); + let limit = ctx.page_limit(); + let query = PageQuery { limit: limit.map(|l| l as usize), ..Default::default() }; + match ctx.history.page(&ctx.server_uid, &target, query, ctx.memory()).await { + Ok(local) => { + let short = limit.is_none_or(|l| local.len() < l as usize); + let complete = short && gateway.is_none() && !gateway_pending; + ctx.emit_batch(&target, local, HistorySource::Local, complete); + } + Err(e) => warn!("cannot read chat history: {e}"), + } + if let Some(client) = gateway { + sync_chat(&ctx, &client, &target).await; + } +} + +/// Fetch what the gateway has for `target` beyond the chat's cursor. +async fn sync_chat(ctx: &ChatCtx, client: &GatewayClient, target: &ChatTarget) { + let (memory, uid, key) = (ctx.memory(), ctx.server_uid.clone(), store_target(target)); + let gateway_id = client.info().gateway_id.clone(); + let cursor = { + let (uid, key) = (uid.clone(), key.clone()); + ctx.history.run(memory, move |s| s.chat_cursor(&uid, &key)).await.ok().flatten() + }; + let mut cursor = match cursor { + Some(c) if c.gateway_id == gateway_id => Some(c), + // Another gateway numbers messages differently. + Some(_) => { + let (uid, key) = (uid.clone(), key.clone()); + let _ = ctx.history.run(memory, move |s| s.forget_remote_ids(&uid, &key)).await; + None + } + None => None, + }; + let limit = ctx.page_limit(); + let save = |cursor: ChatCursor| { + let (uid, key) = (uid.clone(), key.clone()); + ctx.history.run(memory, move |s| s.set_chat_cursor(&uid, &key, &cursor)) + }; + let mut complete = cursor.as_ref().is_some_and(|c| c.complete); + if cursor.is_none() { + // Never synced: the latest page; older ones when scrolling back. + let page = match client.history(HistoryQuery::latest(target.clone(), limit)).await { + Ok(page) => page, + Err(e) => return ctx.gateway_failed("history", &e), + }; + complete = !page.has_more; + let rev = page.messages.iter().map(|e| e.rev).max().unwrap_or(0); + match ctx.store_entries(&page.messages).await { + Ok(written) => { + let messages = written.into_iter().map(|w| w.message.into()).collect(); + ctx.emit_batch(target, messages, HistorySource::Gateway, complete); + } + Err(e) => return warn!("cannot store chat history: {e}"), + } + let c = ChatCursor { gateway_id: gateway_id.clone(), rev, complete, updated_ms: now_ms() }; + let _ = save(c.clone()).await; + cursor = Some(c); + } + let mut rev = cursor.map_or(0, |c| c.rev); + loop { + let (entries, next, has_more) = match client.sync(target.clone(), rev, limit).await { + Ok(page) => page, + Err(e) => return ctx.gateway_failed("sync", &e), + }; + let changed: Vec = match ctx.store_entries(&entries).await { + Ok(written) => written + .into_iter() + .filter(|w| w.outcome != WriteOutcome::Unchanged) + .map(|w| w.message.into()) + .collect(), + Err(e) => return warn!("cannot store chat history: {e}"), + }; + rev = rev.max(next); + let c = ChatCursor { gateway_id: gateway_id.clone(), rev, complete, updated_ms: now_ms() }; + let _ = save(c).await; + if !has_more || entries.is_empty() { + // The last batch, possibly empty: in sync. + return ctx.emit_batch(target, changed, HistorySource::Gateway, complete); + } + if !changed.is_empty() { + ctx.emit_batch(target, changed, HistorySource::Gateway, false); + } + } +} + +/// The page before the message with local id `before` (the newest page +/// without it): the gateway's page for that range merged in first. +pub(crate) async fn load_older( + ctx: ChatCtx, + target: ChatTarget, + before: Option, + gateway: Option, +) { + let gateway = gateway.filter(|g| gateway_history(g, &target)); + let (memory, uid, key) = (ctx.memory(), ctx.server_uid.clone(), store_target(&target)); + let anchor = match before { + Some(id) => ctx + .history + .run(memory, move |s| s.message(id)) + .await + .ok() + .flatten() + .map(|m| (m.ts_ms, m.id)), + None => None, + }; + let limit = ctx.page_limit(); + // Whether the gateway has nothing older (None: not asked). + let mut gateway_complete = None; + if let Some(client) = &gateway { + let gateway_id = client.info().gateway_id.clone(); + let (cursor, oldest) = { + let (uid, key) = (uid.clone(), key.clone()); + ctx.history + .run(memory, move |s| { + Ok((s.chat_cursor(&uid, &key)?, s.oldest_remote_ts(&uid, &key)?)) + }) + .await + .unwrap_or((None, None)) + }; + let cursor = cursor.filter(|c| c.gateway_id == gateway_id); + let known_complete = cursor.as_ref().is_some_and(|c| c.complete) + && anchor.is_some_and(|(ts, _)| oldest.is_some_and(|o| ts <= o)); + if known_complete { + gateway_complete = Some(true); + } else { + let mut query = HistoryQuery::latest(target.clone(), limit); + // Up to and including the anchor's millisecond (copies merge). + query.before_ms = anchor.map(|(ts, _)| ts.saturating_add(1)); + match client.history(query).await { + Ok(page) => { + if let Err(e) = ctx.store_entries(&page.messages).await { + warn!("cannot store chat history: {e}"); + } + gateway_complete = Some(!page.has_more); + // The gateway's oldest message is stored now. + if let Some(mut c) = cursor.filter(|_| !page.has_more) { + c.complete = true; + let (uid, key) = (uid.clone(), key.clone()); + let _ = ctx + .history + .run(memory, move |s| s.set_chat_cursor(&uid, &key, &c)) + .await; + } + } + Err(e) => ctx.gateway_failed("history", &e), + } + } + } + let query = PageQuery { before: anchor, after: None, limit: limit.map(|l| l as usize) }; + match ctx.history.page(&uid, &target, query, memory).await { + Ok(local) => { + let short = limit.is_none_or(|l| local.len() < l as usize); + let complete = short && gateway_complete.unwrap_or(gateway.is_none()); + let source = if gateway_complete.is_some() { + HistorySource::Gateway + } else { + HistorySource::Local + }; + ctx.emit_batch(&target, local, source, complete); + } + Err(e) => warn!("cannot read chat history: {e}"), + } +} + +pub(crate) fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc as std_mpsc; + + use super::*; + + fn live(text: &str, ts_ms: i64) -> NewMessage { + let msg = ChatMessage { + target: ChatTarget::Channel(1), + author_name: "a".into(), + author_uid: Some("uid-a".into()), + author_id: None, + text: text.into(), + ts_ms, + via_relay: false, + }; + new_message("srv", &msg, MessageSource::Voice) + } + + /// Writes queued together run in one batch, each answered with its own + /// rows, in order; reads see them. + #[tokio::test] + async fn writes_are_batched_and_answered_in_order() { + let path = std::env::temp_dir() + .join(format!("voelin-history-{}", std::process::id())) + .join("client.db"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); + let history = History::open(&path).unwrap(); + let (tx, rx) = std_mpsc::channel(); + for i in 0..50 { + let tx = tx.clone(); + let batch = vec![live(&format!("m{i}"), i), live(&format!("n{i}"), i)]; + history.write(false, batch, 5000, move |r| { + let texts: Vec = r.unwrap().into_iter().map(|w| w.message.text).collect(); + tx.send((i, texts)).unwrap(); + }); + } + history.flush(); + let answers: Vec<_> = rx.try_iter().collect(); + assert_eq!(answers.len(), 50); + for (n, (i, texts)) in answers.into_iter().enumerate() { + assert_eq!(i, n as i64); + assert_eq!(texts, [format!("m{i}"), format!("n{i}")]); + } + let page = history + .page( + "srv", + &ChatTarget::Channel(1), + PageQuery { limit: Some(2), ..Default::default() }, + false, + ) + .await + .unwrap(); + assert_eq!( + page.iter().map(|m| m.message.text.as_str()).collect::>(), + ["m49", "n49"] + ); + assert!(page[0].id > 0); + // Kept in memory only: negative ids, not in the file. + let kept = history.write_async(true, vec![live("secret", 99)], 5000).await.unwrap(); + assert!(kept[0].message.id < 0); + let stored = + history.page("srv", &ChatTarget::Channel(1), PageQuery::default(), false).await; + assert_eq!(stored.unwrap().len(), 100); + drop(history); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } +} diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 460e361..d3ceb1b 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -23,9 +23,19 @@ //! and defaults. The engine reads its own keys from it (e.g. who may watch //! our stream), takes [`Command::SetSetting`] / [`Command::ResetSetting`], //! and reports every change as [`Event::SettingChanged`]. +//! +//! Chat history: every message a session sees is stored under the server's +//! unique id ([`history`], the client database with +//! [`Command::AttachHistory`]). Opening a chat emits the stored messages, +//! then, with a gateway, what we missed ([`Event::ChatHistory`]); +//! [`Command::LoadOlderHistory`] pages back. The gateway's other features +//! (pins, reactions, topics, events, stream directory, activity, +//! administration) are [`Command::Gateway`] requests and +//! [`Event::Gateway`] updates ([`gateway`]). mod audio; -mod gateway; +pub mod gateway; +pub mod history; #[cfg(feature = "media")] pub mod media; mod query; @@ -44,6 +54,9 @@ pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings}; use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor}; use crate::audio::{AudioEvent, AudioHandle, AudioIn}; +pub use gateway::{GatewayRequest, GatewayUpdate}; +use history::SharedHistory; +pub use history::{History, HistoryMessage, HistorySource}; pub use route::{ChatRoute, Dedup, route_chat}; use settings::{SettingChange, Settings, SharedSettings}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; @@ -91,6 +104,21 @@ pub enum Command { target: ChatTarget, text: String, }, + /// The history page before the message with local id `before` + /// ([`HistoryMessage::id`]; the newest page without it), answered with + /// [`Event::ChatHistory`]. With a gateway, its page for that time is + /// fetched and merged first. + LoadOlderHistory { + session: SessionId, + target: ChatTarget, + before: Option, + }, + /// A request to the session's gateway, answered with [`Event::Gateway`] + /// (see [`gateway`]). + Gateway { + session: SessionId, + request: GatewayRequest, + }, MoveToChannel { session: SessionId, channel: ChannelId, @@ -213,6 +241,10 @@ pub enum Command { /// Use these settings from now on (e.g. the ones of the client database, /// for an engine started without). AttachSettings(Settings), + /// Keep chat history here from now on (e.g. [`History::open`] on the + /// client database; without it, history lives in memory). Chats opened + /// later read from it. + AttachHistory(History), } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -252,6 +284,9 @@ pub struct SessionState { pub input_muted: bool, pub output_muted: bool, pub transmitting: bool, + /// The server's unique id once a source told it (the key of its chat + /// history; for query-only sessions the query address). + pub server_uid: Option, } /// What the engine reports. @@ -272,10 +307,29 @@ pub enum Event { session: SessionId, presence: Arc, }, + /// A live message, as it arrives (without ids; see [`Event::ChatHistory`]). Chat { session: SessionId, message: ChatMessage, }, + /// Messages of a chat to add to or update in its list, by + /// [`HistoryMessage::id`], ordered by `(ts_ms, id)`: stored ones when a + /// chat opens, the gateway's, older pages, and live messages and changes. + /// See [`history`] for when each comes. + ChatHistory { + session: SessionId, + target: ChatTarget, + /// Oldest first. + messages: Vec, + source: HistorySource, + /// Nothing older exists as far as the engine can tell. + complete: bool, + }, + /// An answer or push of the session's gateway (see [`gateway`]). + Gateway { + session: SessionId, + update: GatewayUpdate, + }, /// A client in the session started or stopped talking (voice only). Talking { session: SessionId, @@ -360,6 +414,7 @@ pub struct Engine { frames: broadcast::Sender, runtime: tokio::runtime::Handle, settings: SharedSettings, + history: SharedHistory, } impl Engine { @@ -371,13 +426,33 @@ impl Engine { /// Start the engine on the current tokio runtime with `settings`. pub fn start_with_settings(settings: Settings) -> Self { + Self::start_with(settings, History::in_memory()) + } + + /// Start the engine on the current tokio runtime with `settings` and + /// chat `history`. + pub fn start_with(settings: Settings, history: History) -> Self { let (commands, rx) = mpsc::unbounded_channel(); let (events, _) = broadcast::channel(4096); // About a minute of one watched stream. let (frames, _) = broadcast::channel(4096); let settings = SharedSettings::new(settings); - tokio::spawn(run(rx, events.clone(), frames.clone(), settings.clone())); - Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), settings } + let history = SharedHistory::new(history); + let shared = Shared { settings: settings.clone(), history: history.clone() }; + tokio::spawn(run(rx, events.clone(), frames.clone(), shared)); + Self { + commands, + events, + frames, + runtime: tokio::runtime::Handle::current(), + settings, + history, + } + } + + /// The chat history the engine uses. + pub fn history(&self) -> History { + self.history.current() } /// The settings the engine uses (read, watch or change them directly; @@ -412,6 +487,22 @@ enum Input { Setting(SettingChange), /// Changes were missed: the engine re-reads what it uses. SettingsLagged, + /// Time to delete chat history past `chat.retention_days`. + Prune, +} + +/// What the engine and its sessions share and commands can replace. +struct Shared { + settings: SharedSettings, + history: SharedHistory, +} + +/// Delete chat history past `chat.retention_days` (0: keep everything). +fn prune_history(settings: &Settings, history: &History) { + let days = settings.get(&settings::CHAT_RETENTION_DAYS); + if days > 0 { + history.prune(history::now_ms().saturating_sub(i64::from(days) * 86_400_000)); + } } /// A command that applies the stored audio settings if they differ from @@ -425,10 +516,13 @@ async fn run( mut commands: mpsc::UnboundedReceiver, events: broadcast::Sender, frames: broadcast::Sender, - shared: SharedSettings, + shared: Shared, ) { + let Shared { settings: shared, history } = shared; let mut sessions: HashMap = HashMap::new(); let mut current = shared.current(); + // Pruning: at start, then hourly (and when the setting changes). + let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600)); let mut changes = current.subscribe(); let mut settings = AudioSettings::default(); let mut srtp_profiles: Option> = None; @@ -445,10 +539,18 @@ async fn run( // Not while `current` holds the settings. Err(broadcast::error::RecvError::Closed) => continue, }, + _ = prune.tick() => Input::Prune, }; let command = match input { Input::Command(command) => command, + Input::Prune => { + prune_history(¤t, &history.current()); + continue; + } Input::Setting(change) => { + if change.key == settings::CHAT_RETENTION_DAYS.name() { + prune_history(¤t, &history.current()); + } let audio = change.key == settings::AUDIO.name(); let _ = events.send(Event::SettingChanged { key: change.key }); match audio.then(|| stored_audio(¤t, &settings)).flatten() { @@ -501,6 +603,11 @@ async fn run( current = new; continue; } + Command::AttachHistory(new) => { + history.replace(new.clone()); + prune_history(¤t, &new); + continue; + } ref command => command_session(command), }; if matches!(command, Command::CloseSession { .. }) { @@ -518,6 +625,7 @@ async fn run( frames.clone(), settings.clone(), shared.clone(), + history.clone(), ); if let Some(profiles) = &srtp_profiles { s.send(Command::SetSrtpProfiles(profiles.clone())); @@ -558,6 +666,8 @@ fn command_session(command: &Command) -> SessionId { | Command::OpenChat { session, .. } | Command::CloseChat { session, .. } | Command::SendChat { session, .. } + | Command::LoadOlderHistory { session, .. } + | Command::Gateway { session, .. } | Command::MoveToChannel { session, .. } | Command::SetInputMuted { session, .. } | Command::SetOutputMuted { session, .. } @@ -580,7 +690,8 @@ fn command_session(command: &Command) -> SessionId { | Command::TestMicrophone { .. } | Command::SetSetting { .. } | Command::ResetSetting { .. } - | Command::AttachSettings(_) => { + | Command::AttachSettings(_) + | Command::AttachHistory(_) => { unreachable!("engine-wide commands have no session") } } diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index b84dd46..d639daf 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -1,17 +1,19 @@ //! Stream media (feature `media`): capture and encoding for our stream, //! decoding for the streams we watch. //! -//! - [`Streamer`] captures a screen or window (and optionally system audio), -//! encodes the video with the codec our offer carries ([`stream_codec`], -//! VP8 by default) in one or more simulcast layers ([`LayerSpec`]), and -//! the audio with Opus (48 kHz stereo, 20 ms). Capture, conversion and -//! each layer's encoder run on threads of their own, connected by -//! latest-wins handoffs. It hands the frames to a [`MediaSink`]: the -//! [`StreamSink`] of a live stream, or an [`EncodedSource`] for code that -//! drives `voelin_stream::Streams` itself. Keyframe requests of viewers -//! are honoured per layer, and each layer's encoder follows the bitrate -//! the sink allows. [`Streamer::reconfigure`] changes frame rate, -//! bitrate, codec and layers while streaming. +//! - [`Streamer`] captures a screen or window, encodes the video with the +//! codec our offer carries ([`stream_codec`], VP8 by default) in one or +//! more simulcast layers ([`LayerSpec`]), and mixes any number of audio +//! sources ([`AudioSourceSpec`]: desktop audio without Voelin's own +//! playback, single applications, the shared window's application, the +//! microphone) into Opus (48 kHz stereo, 20 ms). Capture, conversion, +//! each layer's encoder and the audio mixer run on threads of their own. +//! It hands the frames to a [`MediaSink`]: the [`StreamSink`] of a live +//! stream, or an [`EncodedSource`] for code that drives +//! `voelin_stream::Streams` itself. Keyframe requests of viewers are +//! honoured per layer, and each layer's encoder follows the bitrate the +//! sink allows. [`Streamer::reconfigure`] changes frame rate, bitrate, +//! codec, layers and audio sources while streaming. //! - [`VideoPipeline`] decodes the video of a watched stream on its own //! thread and hands every picture to a callback. After lost frames or //! decoder errors it skips to the next keyframe and asks for one. @@ -34,26 +36,30 @@ use std::thread::JoinHandle; use std::time::{Duration, Instant}; use tracing::{debug, warn}; +use voelin_audio::tap::{self, TapGuard, TapSink}; use voelin_audio::{VoiceCodec, VoiceEncoder}; pub use voelin_media; +use voelin_media::capture::playback::{self, PlaybackFilter, SourceCapture}; +pub use voelin_media::capture::playback::{AppMatch, AudioApp, AudioApps}; pub use voelin_media::capture::synthetic::Pattern; use voelin_media::capture::synthetic::{SineSource, SyntheticScreen}; use voelin_media::capture::{ - self, AudioCapture, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, - SourceId, + self, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, SourceId, }; use voelin_media::handoff::Handoff; -use voelin_media::scale::Pyramid; -use voelin_media::{ - AudioBuffer, Codec, Codecs, ContentHint, EncoderConfig, FrameReceiver, FrameRef, VideoEncoder, - VideoFrame, +use voelin_media::mix::{ + BlockClock, MIX_RATE, MixerConfig, MixerHandle, SourceHandle, SourceInput, StreamMixer, }; +pub use voelin_media::mix::{Level, SourceState}; +use voelin_media::scale::Pyramid; +use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame}; pub use voelin_media::{EncoderBackend, EncoderPreference}; use voelin_stream::{ EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, }; +use crate::settings::{AudioSourceKindSetting, AudioSourceSetting}; use crate::stream::StreamSink; use crate::{Command, Engine, SessionId}; @@ -322,6 +328,150 @@ impl std::str::FromStr for CaptureBackend { } } +/// What an audio source of our stream captures. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum AudioSourceKind { + /// Everything that plays except this process and its children (the + /// voices and streams we play): PipeWire links from every other + /// playback stream, WASAPI process loopback excluding our process tree, + /// Android playback capture excluding our uid. + DesktopWithoutSelf, + /// One application (see [`AppMatch`]; [`audio_apps`] lists them). + App(AppMatch), + /// The application that owns the shared window ([`SourceId::Window`]), + /// where the platform tells: X11 `_NET_WM_PID`, the owner of a Windows + /// `HWND`. The ScreenCast portal (Wayland) does not say whose window it + /// shares: pick the application from [`audio_apps`] instead. + WindowAudio, + /// Our microphone as the voice connection sends it (after noise + /// suppression and gain control), while a voice connection runs. + Microphone, + /// A quiet sine tone of this many Hz (tests, the test pattern). + Synthetic { hz: u32 }, +} + +impl AudioSourceKind { + /// A name for the mixer and the UI. + pub fn label(&self) -> String { + match self { + AudioSourceKind::DesktopWithoutSelf => "Desktop audio (without Voelin)".into(), + AudioSourceKind::App(app) => format!("App: {app}"), + AudioSourceKind::WindowAudio => "Audio of the shared window".into(), + AudioSourceKind::Microphone => "Microphone".into(), + AudioSourceKind::Synthetic { hz } => format!("Test tone {hz} Hz"), + } + } +} + +/// One audio source of a stream, with its gain and mute. Compared bit for +/// bit (`gain` by its bits), so it is `Eq`. +#[derive(Clone, Debug)] +pub struct AudioSourceSpec { + pub kind: AudioSourceKind, + /// Linear gain (1: unchanged), any value >= 0. + pub gain: f32, + pub muted: bool, +} + +impl PartialEq for AudioSourceSpec { + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + && self.gain.to_bits() == other.gain.to_bits() + && self.muted == other.muted + } +} + +impl Eq for AudioSourceSpec {} + +impl AudioSourceSpec { + /// At gain 1, not muted. + pub fn new(kind: AudioSourceKind) -> Self { + Self { kind, gain: 1.0, muted: false } + } +} + +impl From<&AudioSourceSetting> for AudioSourceSpec { + fn from(setting: &AudioSourceSetting) -> Self { + let kind = match &setting.kind { + AudioSourceKindSetting::Desktop => AudioSourceKind::DesktopWithoutSelf, + // A pid wins: it names one process exactly. + AudioSourceKindSetting::App { pid: Some(pid), .. } => { + AudioSourceKind::App(AppMatch::Pid(*pid)) + } + AudioSourceKindSetting::App { name, pid: None } => { + AudioSourceKind::App(AppMatch::Name(name.clone().unwrap_or_default())) + } + AudioSourceKindSetting::Window => AudioSourceKind::WindowAudio, + AudioSourceKindSetting::Microphone => AudioSourceKind::Microphone, + AudioSourceKindSetting::Synthetic { frequency } => { + AudioSourceKind::Synthetic { hz: *frequency } + } + }; + Self { kind, gain: setting.gain, muted: setting.muted } + } +} + +impl From<&AudioSourceSpec> for AudioSourceSetting { + fn from(spec: &AudioSourceSpec) -> Self { + let kind = match &spec.kind { + AudioSourceKind::DesktopWithoutSelf => AudioSourceKindSetting::Desktop, + AudioSourceKind::App(AppMatch::Pid(pid)) => { + AudioSourceKindSetting::App { name: None, pid: Some(*pid) } + } + AudioSourceKind::App(AppMatch::Name(name)) => { + AudioSourceKindSetting::App { name: Some(name.clone()), pid: None } + } + AudioSourceKind::WindowAudio => AudioSourceKindSetting::Window, + AudioSourceKind::Microphone => AudioSourceKindSetting::Microphone, + AudioSourceKind::Synthetic { hz } => { + AudioSourceKindSetting::Synthetic { frequency: *hz } + } + }; + Self { kind, gain: spec.gain, muted: spec.muted } + } +} + +/// The sources of `settings::STREAM_AUDIO_SOURCES` as [`AudioSourceSpec`]s +/// (for [`StreamerConfig::audio_sources`]; empty: no audio). +pub fn audio_source_specs(settings: &[AudioSourceSetting]) -> Vec { + settings.iter().map(AudioSourceSpec::from).collect() +} + +/// The audio of a stream when none is chosen: a tone with the test +/// pattern, else desktop audio without Voelin. +pub fn default_audio_sources(source: &SourceId) -> Vec { + let kind = match source { + SourceId::Synthetic => AudioSourceKind::Synthetic { hz: 440 }, + _ => AudioSourceKind::DesktopWithoutSelf, + }; + vec![AudioSourceSpec::new(kind)] +} + +/// Applications that play audio now (Android: launchable apps), updated +/// live, for a picker of [`AudioSourceKind::App`]. +pub fn audio_apps() -> Result { + Ok(playback::audio_apps()?) +} + +/// One audio source in [`StreamerStats`]. +#[derive(Clone, Debug, PartialEq)] +pub struct AudioSourceStats { + /// The mixer's id of the source. + pub id: u64, + pub spec: AudioSourceSpec, + pub name: String, + /// After its gain, before its mute. + pub level: Level, + pub state: SourceState, + /// How far behind its capture it is mixed. + pub latency: Duration, + /// Times its capture delivered too late (and the audio broke up). + pub underruns: u64, + /// Why it captures nothing (no PipeWire, the window's process unknown, + /// ...). + pub error: Option, +} + /// What and how to stream. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StreamerConfig { @@ -338,8 +488,12 @@ pub struct StreamerConfig { pub codec: Codec, /// Which encoders to use ([`encoder_preference`] of the settings). pub encoder: EncoderPreference, - /// Capture and send system audio (a sine tone with the test pattern). + /// Send audio: [`audio_sources`](Self::audio_sources) mixed. pub audio: bool, + /// Audio sources mixed into the stream (any number); empty: the + /// [`default_audio_sources`] (a tone with the test pattern, else desktop + /// audio without Voelin). [`Streamer::reconfigure`] changes them live. + pub audio_sources: Vec, pub cursor: bool, /// Size of the test pattern ([`SourceId::Synthetic`]). pub synthetic_size: (u32, u32), @@ -363,6 +517,7 @@ impl Default for StreamerConfig { codec: Codec::Vp8, encoder: EncoderPreference::default(), audio: true, + audio_sources: Vec::new(), cursor: true, synthetic_size: (1280, 720), synthetic_pattern: Pattern::Simple, @@ -400,6 +555,10 @@ pub struct StreamerConfigUpdate { /// Another set of layers (`Some(vec![])`: back to a single layer). Layers /// keep their encoder when their id stays; new ids get new encoders. pub layers: Option>, + /// Other audio sources. Sources whose kind stays keep their capture and + /// just take the new gain and mute; new kinds start capturing, removed + /// ones stop. `Some(vec![])` silences the audio (the track stays). + pub audio_sources: Option>, } /// One simulcast layer in [`StreamerStats`]. Rates are over the last second. @@ -458,6 +617,11 @@ pub struct StreamerStats { pub convert_threads: usize, pub codec: Option, pub layers: Vec, + /// Level of the stream's audio (after the limiter). + pub audio_level: Level, + /// The limiter's lowest gain in the last 20 ms (1: not limiting). + pub audio_limiter: f32, + pub audio_sources: Vec, } /// One simulcast layer while streaming: its encoder thread's inbox and @@ -681,15 +845,23 @@ fn new_encoder( /// buffers). Each layer's newest frame goes through a one-slot handoff to /// that layer's encoder thread; a frame an encoder was too busy for is /// replaced, not queued. +/// +/// Audio sources feed a [`StreamMixer`] from their capture threads; the +/// mixer runs every 20 ms on a thread of its own and its output is encoded +/// with Opus. pub struct Streamer { shared: Arc, screen: Option>, - audio: Option>, + /// The video source (for [`AudioSourceKind::WindowAudio`]). + source: SourceId, + // Boxed: a `Streamer` is held inline by previews. + audio: Mutex>>, threads: Vec>, /// Encoder threads, by layer. encoders: Mutex)>>, backend: &'static str, restore_token: Option, + /// Why the audio did not start at all. audio_error: Option, } @@ -705,7 +877,8 @@ impl Streamer { let mut streamer = Self { shared: shared.clone(), screen: None, - audio: None, + source: config.source.clone(), + audio: Mutex::new(None), threads: Vec::new(), encoders: Mutex::new(Vec::new()), backend: "", @@ -763,13 +936,13 @@ impl Streamer { streamer.screen = Some(screen); streamer.restore_token = restore_token; if config.audio { - match start_audio(&config.source) { - Ok((capture, buffers, encoder)) => { - streamer.audio = Some(capture); - streamer.threads.push(spawn("voelin-stream-audio", move || { - audio_loop(&shared, buffers, encoder) - })?); - } + let sources = if config.audio_sources.is_empty() { + default_audio_sources(&config.source) + } else { + config.audio_sources.clone() + }; + match StreamAudio::start(&shared, &config.source, sources) { + Ok(audio) => *lock(&streamer.audio) = Some(Box::new(audio)), Err(e) => { warn!("streaming without audio: {e}"); streamer.audio_error = Some(e.to_string()); @@ -794,13 +967,16 @@ impl Streamer { Ok(()) } - /// Change frame rate, bitrate, codec, encoders or layers while - /// streaming, without restarting the capture; applies from the next - /// frame. A new codec or encoder preference gets new encoders (the - /// stream codec's at once, those of codecs viewers chose on their next - /// frame), which start with a keyframe; new layers get new encoders; - /// removed layers stop. Fails without changing anything if an encoder - /// cannot be created. + /// Change frame rate, bitrate, codec, encoders, layers or audio + /// sources while streaming, without restarting the capture; applies + /// from the next frame. A new codec or encoder preference gets new + /// encoders (the stream codec's at once, those of codecs viewers chose + /// on their next frame), which start with a keyframe; new layers get + /// new encoders; removed layers stop. Fails without changing anything + /// if an encoder cannot be created. Audio sources that cannot capture + /// (e.g. an application that is not running by pid) do not fail the + /// update: their [`AudioSourceStats::error`] says why. Audio sources on + /// a streamer started without audio start the audio track. pub fn reconfigure( &self, codecs: &Codecs, @@ -880,6 +1056,17 @@ impl Streamer { for thread in finished { let _ = thread.join(); } + if let Some(sources) = update.audio_sources { + let mut audio = lock(&self.audio); + match audio.as_mut() { + Some(audio) => audio.apply(sources), + None if !sources.is_empty() => { + let started = StreamAudio::start(&self.shared, &self.source, sources)?; + *audio = Some(Box::new(started)); + } + None => {} + } + } debug!(?removed, codec_changed, "stream reconfigured"); Ok(()) } @@ -904,14 +1091,28 @@ impl Streamer { self.restore_token.as_deref() } - /// Why system audio is not captured, if it was asked for. - pub fn audio_error(&self) -> Option<&str> { - self.audio_error.as_deref() + /// Why there is no audio, or which audio sources capture nothing and why. + pub fn audio_error(&self) -> Option { + self.audio_error.clone().or_else(|| lock(&self.audio).as_ref().and_then(|a| a.error())) } - /// Whether system audio is captured. + /// Whether the stream has audio (mixed from its audio sources). pub fn has_audio(&self) -> bool { - self.audio.is_some() + lock(&self.audio).is_some() + } + + /// The audio mixer, for lock-free level meters + /// ([`MixerHandle::level`], each source's `level`) and direct control. + pub fn audio_mixer(&self) -> Option { + lock(&self.audio).as_ref().map(|a| a.mixer.clone()) + } + + /// The audio sources now. + pub fn audio_sources(&self) -> Vec { + lock(&self.audio) + .as_ref() + .map(|a| a.active.iter().map(|s| s.spec.clone()).collect()) + .unwrap_or_default() } /// The ids of the layers being encoded. @@ -921,6 +1122,7 @@ impl Streamer { pub fn stats(&self) -> StreamerStats { let shared = &self.shared; + let audio = lock(&self.audio); let size = shared.size.load(Ordering::Relaxed); let codec = lock(&shared.settings).as_ref().map(|s| s.codec); let rates = lock(&shared.rates); @@ -966,6 +1168,9 @@ impl Streamer { convert_threads: shared.convert_threads.load(Ordering::Relaxed), codec, layers, + audio_level: audio.as_ref().map(|a| a.mixer.level()).unwrap_or_default(), + audio_limiter: audio.as_ref().map_or(1.0, |a| a.mixer.limiter_gain()), + audio_sources: audio.as_ref().map(|a| a.stats()).unwrap_or_default(), } } @@ -976,7 +1181,8 @@ impl Streamer { if let Some(mut screen) = self.screen.take() { screen.stop(); } - if let Some(mut audio) = self.audio.take() { + let audio = lock(&self.audio).take(); + if let Some(audio) = audio { audio.stop(); } for layer in lock(&self.shared.layers).iter() { @@ -1043,17 +1249,175 @@ fn screen_backend(backend: &CaptureBackend) -> Result, Me }) } -type AudioStart = (Box, FrameReceiver, VoiceEncoder); +/// The stream's audio: the mixer (running on its own thread) and the +/// captures feeding its sources. +struct StreamAudio { + mixer: MixerHandle, + /// The video source, for [`AudioSourceKind::WindowAudio`]. + video: SourceId, + active: Vec, + thread: Option>, +} -fn start_audio(source: &SourceId) -> Result { - let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?; - encoder.set_bitrate(OPUS_BITRATE)?; - let mut capture: Box = match source { - SourceId::Synthetic => Box::new(SineSource::new(440.0, 0.05)), - _ => capture::default_audio_capture()?, - }; - let buffers = capture.start()?; - Ok((capture, buffers, encoder)) +/// An audio source in the mixer and what feeds it. +struct ActiveSource { + spec: AudioSourceSpec, + handle: SourceHandle, + _feed: Option, + error: Option, +} + +impl Drop for ActiveSource { + fn drop(&mut self) { + // Its captures see the input close and stop. + self.handle.remove(); + } +} + +/// What feeds a source; stops when dropped. +enum Feed { + Capture(#[allow(dead_code)] Box), + Microphone(#[allow(dead_code)] TapGuard<'static>), +} + +/// Processed microphone audio (48 kHz mono) into a mixer input. +struct MicrophoneInput(SourceInput); + +impl TapSink for MicrophoneInput { + fn write(&mut self, samples: &[f32]) { + self.0.push(samples, 1); + } + + fn silence(&mut self, frames: usize) { + self.0.push_silence(frames); + } +} + +impl StreamAudio { + /// Start the mixer thread and `sources`. + fn start( + shared: &Arc, + video: &SourceId, + sources: Vec, + ) -> Result { + let mut encoder = VoiceEncoder::new(VoiceCodec::Music)?; + encoder.set_bitrate(OPUS_BITRATE)?; + let mixer = + StreamMixer::new(MixerConfig { max_block: OPUS_FRAME, ..MixerConfig::default() }); + let handle = mixer.handle(); + let thread = spawn("voelin-stream-audio", { + let shared = shared.clone(); + move || audio_loop(&shared, mixer, encoder) + })?; + let mut audio = + Self { mixer: handle, video: video.clone(), active: Vec::new(), thread: Some(thread) }; + audio.apply(sources); + Ok(audio) + } + + /// Make the sources `specs`: kinds that stay keep their capture and + /// take the new gain and mute, new ones start, the rest stop. + fn apply(&mut self, specs: Vec) { + let mut old: Vec> = self.active.drain(..).map(Some).collect(); + let mut next = Vec::with_capacity(specs.len()); + for spec in specs { + let same = + old.iter().position(|o| o.as_ref().is_some_and(|a| a.spec.kind == spec.kind)); + match same.and_then(|i| old[i].take()) { + Some(mut source) => { + source.handle.set_gain(spec.gain); + source.handle.set_muted(spec.muted); + source.spec = spec; + next.push(source); + } + None => next.push(self.start_source(spec)), + } + } + drop(old); + self.active = next; + } + + fn start_source(&self, spec: AudioSourceSpec) -> ActiveSource { + let handle = self.mixer.add_source(spec.kind.label()); + handle.set_gain(spec.gain); + handle.set_muted(spec.muted); + let (feed, error) = match self.feed(&spec.kind, &handle) { + Ok(feed) => (Some(feed), None), + Err(e) => { + warn!("stream audio source {}: {e}", spec.kind.label()); + (None, Some(e)) + } + }; + ActiveSource { spec, handle, _feed: feed, error } + } + + fn feed(&self, kind: &AudioSourceKind, handle: &SourceHandle) -> Result { + let playback = |filter: PlaybackFilter| { + playback::start_playback(&filter, handle).map(Feed::Capture).map_err(|e| e.to_string()) + }; + match kind { + AudioSourceKind::DesktopWithoutSelf => playback(PlaybackFilter::AllButSelf), + AudioSourceKind::App(app) => playback(PlaybackFilter::App(app.clone())), + AudioSourceKind::WindowAudio => { + let SourceId::Window(window) = self.video else { + return Err("no window is shared; pick the application instead".into()); + }; + let pid = playback::window_pid(window).ok_or( + "the shared window's process is unknown here; pick the application instead", + )?; + playback(PlaybackFilter::App(AppMatch::Pid(pid))) + } + AudioSourceKind::Microphone => { + let input = MicrophoneInput(handle.input(MIX_RATE)); + Ok(Feed::Microphone(tap::microphone().attach(Box::new(input)))) + } + AudioSourceKind::Synthetic { hz } => { + let tone = SineSource::new(*hz as f32, 0.05); + playback::forward_audio(Box::new(tone), handle) + .map(Feed::Capture) + .map_err(|e| e.to_string()) + } + } + } + + /// The sources that capture nothing, and why. + fn error(&self) -> Option { + let errors: Vec = self + .active + .iter() + .filter_map(|s| s.error.as_ref().map(|e| format!("{}: {e}", s.spec.kind.label()))) + .collect(); + (!errors.is_empty()).then(|| errors.join("; ")) + } + + fn stats(&self) -> Vec { + self.active + .iter() + .map(|s| { + let stats = s.handle.stats(); + AudioSourceStats { + id: s.handle.id(), + spec: s.spec.clone(), + name: s.handle.name().to_owned(), + level: s.handle.level(), + state: stats.state, + latency: stats.latency, + underruns: stats.underruns, + error: s.error.clone(), + } + }) + .collect() + } + + /// Stop the captures and the mixer thread (the streamer's stop flag + /// must be set). + fn stop(mut self) { + self.active.clear(); + if let Some(thread) = self.thread.take() { + thread.thread().unpark(); + let _ = thread.join(); + } + } } /// A layer as the capture thread sees it. @@ -1483,66 +1847,37 @@ fn stats_loop(shared: &Shared) { } } -/// Interleaved stereo from any channel count (extra channels are dropped). -fn append_stereo(buffer: &AudioBuffer, out: &mut Vec) { - match buffer.channels { - 0 => {} - 1 => out.extend(buffer.samples.iter().flat_map(|s| [*s, *s])), - 2 => out.extend_from_slice(&buffer.samples), - n => { - for frame in buffer.samples.chunks_exact(usize::from(n)) { - out.extend_from_slice(&frame[..2]); - } - } - } -} - -fn audio_loop(shared: &Shared, mut buffers: FrameReceiver, mut encoder: VoiceEncoder) { - // Interleaved stereo waiting for a whole Opus frame. - let mut pending: Vec = Vec::new(); - // Opus frames since the capture started: the RTP time in 20 ms steps. - let mut frames: u64 = 0; +/// The mixer thread: every 20 ms (on the monotonic clock) one Opus frame +/// of the mix, encoded while a sink is attached. The RTP time is the +/// frame's number since the start, so it follows real time across +/// silences and stalls. +fn audio_loop(shared: &Shared, mut mixer: StreamMixer, mut encoder: VoiceEncoder) { + let mut clock = BlockClock::new(OPUS_FRAME); + let mut block = vec![0.0f32; OPUS_FRAME * 2]; while !shared.stopped() { - let Some(buffer) = buffers.recv_timeout(POLL) else { - if buffers.is_closed() { - debug!("system audio capture ended"); - break; - } + let now = Instant::now(); + let due = clock.due(now); + if due.is_empty() { + std::thread::park_timeout(clock.next().saturating_duration_since(now).min(POLL)); continue; - }; - // Follow the capture clock across gaps (nothing played, sink not - // attached yet), so audio stays in step with video. - let at = buffer.timestamp.as_micros() as u64 * 48 / 1000; - let position = frames * OPUS_FRAME as u64 + (pending.len() / 2) as u64; - if at > position + 10 * OPUS_FRAME as u64 { - pending.clear(); - frames = at / OPUS_FRAME as u64; } - let Some(sink) = shared.sink() else { continue }; - append_stereo(&buffer, &mut pending); - while pending.len() >= OPUS_FRAME * 2 { - let data: Option> = match encoder.encode_to_bytes(&pending[..OPUS_FRAME * 2]) - { - Ok(data) => Some(data.into()), + for frame in due { + // Mixed even without a sink, so the sources' buffers keep moving. + mixer.mix(&mut block); + let Some(sink) = shared.sink() else { continue }; + let data: Arc<[u8]> = match encoder.encode_to_bytes(&block) { + Ok(data) => data.into(), Err(e) => { warn!("audio encoding failed: {e}"); - None + continue; } }; - pending.drain(..OPUS_FRAME * 2); - if let Some(data) = data { - let time = MediaTime::new(frames * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); - if sink.send(EncodedFrame { - kind: MediaKind::Audio, - time, - data, - layer: 0, - keyframe: false, - }) { - shared.audio_frames.fetch_add(1, Ordering::Relaxed); - } + let time = MediaTime::new(frame * OPUS_FRAME as u64, Frequency::FORTY_EIGHT_KHZ); + let frame = + EncodedFrame { kind: MediaKind::Audio, time, data, layer: 0, keyframe: false }; + if sink.send(frame) { + shared.audio_frames.fetch_add(1, Ordering::Relaxed); } - frames += 1; } } } @@ -2398,6 +2733,118 @@ mod tests { assert_eq!(source.streamer().layer_ids(), [0, 7]); } + #[test] + fn audio_sources_from_settings() { + use crate::settings::{AudioSourceKindSetting as K, AudioSourceSetting as S}; + let settings = [ + S::new(K::Desktop), + S { gain: 0.5, ..S::new(K::App { name: Some("firefox".into()), pid: None }) }, + S { muted: true, ..S::new(K::App { name: None, pid: Some(42) }) }, + S::new(K::Window), + S::new(K::Microphone), + S::new(K::Synthetic { frequency: 1000 }), + ]; + let specs = audio_source_specs(&settings); + let kinds: Vec = specs.iter().map(|s| s.kind.clone()).collect(); + assert_eq!( + kinds, + [ + AudioSourceKind::DesktopWithoutSelf, + AudioSourceKind::App(AppMatch::Name("firefox".into())), + AudioSourceKind::App(AppMatch::Pid(42)), + AudioSourceKind::WindowAudio, + AudioSourceKind::Microphone, + AudioSourceKind::Synthetic { hz: 1000 }, + ] + ); + assert_eq!((specs[1].gain, specs[2].muted), (0.5, true)); + let back: Vec = specs.iter().map(S::from).collect(); + assert_eq!(back, settings); + assert_eq!( + default_audio_sources(&SourceId::Monitor(0)), + [AudioSourceSpec::new(AudioSourceKind::DesktopWithoutSelf)] + ); + } + + /// Audio sources mixed, then changed while streaming: gain, mute, one + /// removed, the microphone added; levels in the stats follow. + #[cfg(feature = "media-desktop")] + #[tokio::test(flavor = "multi_thread")] + async fn audio_sources_change_live() { + let codecs = Codecs::new(); + let tone = |hz| AudioSourceSpec::new(AudioSourceKind::Synthetic { hz }); + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (64, 48), + audio_sources: vec![tone(440), AudioSourceSpec { gain: 0.5, ..tone(1000) }], + ..StreamerConfig::default() + }; + let streamer = Streamer::start(&codecs, config).await.unwrap(); + let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let stats = streamer.stats(); + if done(&stats) { + return stats; + } + assert!(Instant::now() < deadline, "{what}: {:#?}", stats.audio_sources); + std::thread::sleep(Duration::from_millis(20)); + } + }; + // The SineSource tone is 0.05; the second at half gain. + let near = |level: f32, want: f32| (level - want).abs() < want * 0.1; + let stats = wait("both tones", &|s| { + s.audio_sources.len() == 2 + && near(s.audio_sources[0].level.peak, 0.05) + && near(s.audio_sources[1].level.peak, 0.025) + }); + assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing)); + assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}"); + let first = stats.audio_sources[0].id; + + // Mute the first (kept: same id), drop the second, add the + // microphone and a window source (the pattern is no window). + let update = StreamerConfigUpdate { + audio_sources: Some(vec![ + AudioSourceSpec { muted: true, ..tone(440) }, + AudioSourceSpec::new(AudioSourceKind::Microphone), + AudioSourceSpec::new(AudioSourceKind::WindowAudio), + ]), + ..StreamerConfigUpdate::default() + }; + streamer.reconfigure(&codecs, update).unwrap(); + assert_eq!(streamer.audio_sources().len(), 3); + let publisher = tap::publisher_id(); + let speak = std::thread::spawn(move || { + // 20 ms of a 0.2 tone every 20 ms, for a second. + let chunk: Vec = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect(); + for _ in 0..50 { + tap::microphone().publish(publisher, &chunk); + std::thread::sleep(Duration::from_millis(20)); + } + }); + let stats = wait("microphone in, tone muted", &|s| { + s.audio_sources.len() == 3 + && s.audio_sources[1].level.peak > 0.15 + && s.audio_level.peak > 0.15 + }); + speak.join().unwrap(); + assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source"); + assert!(stats.audio_sources[0].spec.muted); + // Muted sources are still metered. + assert!(near(stats.audio_sources[0].level.peak, 0.05), "{stats:?}"); + let window = &stats.audio_sources[2]; + assert!(window.error.as_deref().is_some_and(|e| e.contains("no window")), "{window:?}"); + assert!(streamer.audio_error().is_some_and(|e| e.contains("shared window"))); + assert!(streamer.audio_mixer().is_some()); + + // All sources gone: silence, the track stays. + let update = StreamerConfigUpdate { audio_sources: Some(Vec::new()), ..Default::default() }; + streamer.reconfigure(&codecs, update).unwrap(); + wait("silence", &|s| s.audio_sources.is_empty() && s.audio_level.peak < 0.01); + assert!(streamer.has_audio()); + } + /// Audio of the test pattern: 20 ms Opus frames on a 48 kHz clock. #[cfg(feature = "media-desktop")] #[tokio::test(flavor = "multi_thread")] diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 6b92c49..fcbbb50 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -1,4 +1,10 @@ //! One server session: merges its sources and routes commands. +//! +//! Chat messages from every source are stored under the server's unique id +//! ([`crate::history`]); the id comes from the voice connection or the +//! gateway, or, before they connect, from what the database remembers for +//! the address (`voice:
`, `gateway:`). The gateway's features +//! are driven through its client ([`crate::gateway`]). use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; @@ -7,15 +13,23 @@ use tokio::sync::{broadcast, mpsc}; use tracing::debug; use tsclientlib::ClientId; use voelin_audio::AudioSettings; +use voelin_gateway_proto::{HistoryEntry, StreamEntry, StreamSpec, feature}; use voelin_model::{ChatMessage, ChatTarget, Presence}; use voelin_stream::ClientState; use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; -use crate::gateway::{self, GatewayCmd, GatewayEvent}; +use crate::gateway::{ + self, ClientError, GatewayClient, GatewayCmd, GatewayEvent, GatewayRequest, GatewayUpdate, + Push, ReactionPush, +}; +use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; use crate::settings::SharedSettings; -use crate::stream::{LayerSpec, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInput}; +use crate::stream::{ + LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo, + StreamInput, StreamKind, kind_name, parse_kind, +}; use crate::voice::{self, VoiceCmd, VoiceEvent}; use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState}; @@ -30,9 +44,10 @@ impl SessionHandle { frames: broadcast::Sender, audio_settings: AudioSettings, settings: SharedSettings, + history: SharedHistory, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn(Session::new(id, events, frames, audio_settings, settings).run(rx)); + tokio::spawn(Session::new(id, events, frames, audio_settings, settings, history).run(rx)); Self { tx } } @@ -49,6 +64,21 @@ enum SourceEvent { Query(u64, QueryEvent), AudioOut(u64, tsproto_packets::packets::OutPacket), Audio(u64, AudioEvent), + /// Our own stream (from the stream task of that voice connection). + OwnStream(u64, OwnStreamEvent), + /// The gateway's stream directory after subscribing. + Directory(u64, Result, ClientError>), + /// The server's unique id the database remembers for an address. + KnownServer(String), +} + +/// Our live stream, for the gateway's directory. +struct OwnStream { + id: String, + title: String, + kind: StreamKind, + /// Registered in the directory of the connected gateway. + registered: bool, } struct Session { @@ -61,11 +91,19 @@ struct Session { nickname: String, gateway: Option<(u64, mpsc::UnboundedSender)>, gateway_presence: Option, + /// The logged-in gateway, for requests. + gateway_client: Option, query: Option<(u64, mpsc::UnboundedSender)>, query_presence: Option, audio: Option, audio_settings: AudioSettings, settings: SharedSettings, + history: SharedHistory, + /// Our unique id on the server, for the messages we send. + own_uid: Option, + /// Other names of this server (`voice:
`, `gateway:`), + /// remembered with its unique id once a source tells it. + aliases: Vec, /// Streams of the voice connection (TeamSpeak 6 only). streams: Option, stream_peer: PeerConfig, @@ -78,6 +116,9 @@ struct Session { /// Channel and `client_is_streaming` of the voice presence, as last told /// to the streams. streaming_clients: BTreeMap, + /// The gateway's stream directory, by id. + directory: BTreeMap, + own_stream: Option, open_chats: HashSet, dedup: Dedup, sources_tx: mpsc::UnboundedSender, @@ -91,6 +132,7 @@ impl Session { frames: broadcast::Sender, audio_settings: AudioSettings, settings: SharedSettings, + history: SharedHistory, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); Self { @@ -103,17 +145,23 @@ impl Session { nickname: String::new(), gateway: None, gateway_presence: None, + gateway_client: None, query: None, query_presence: None, audio: None, audio_settings, settings, + history, + own_uid: None, + aliases: Vec::new(), streams: None, stream_peer: PeerConfig::default(), stream_layers: Vec::new(), srtp_profiles: None, frames, streaming_clients: BTreeMap::new(), + directory: BTreeMap::new(), + own_stream: None, open_chats: HashSet::new(), dedup: Dedup::default(), sources_tx, @@ -133,6 +181,10 @@ impl Session { self.emit(Event::State { session: self.id, state: self.state.clone() }); } + fn gateway_update(&self, update: GatewayUpdate) { + self.emit(Event::Gateway { session: self.id, update }); + } + async fn run(mut self, mut commands: mpsc::UnboundedReceiver) { let mut sources = self.sources_rx.take().expect("receiver"); loop { @@ -181,6 +233,7 @@ impl Session { if let Some(profiles) = &self.srtp_profiles { self.stream_peer.srtp_profiles = profiles.clone(); } + self.known_server(format!("voice:{}", options.address)); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); self.audio = None; @@ -205,6 +258,7 @@ impl Session { Command::ObserveGateway { url, identity, .. } => { self.stop_observing(); let generation = self.next_generation(); + self.known_server(format!("gateway:{url}")); let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx)); @@ -217,6 +271,13 @@ impl Session { Command::ObserveQuery { connect, .. } => { self.stop_observing(); let generation = self.next_generation(); + // Queries do not tell the server's unique id: without another + // source, the history is kept under the query address. + if self.state.server_uid.is_none() { + let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default(); + self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query); + self.open_histories(); + } let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); tokio::spawn(query::run(*connect, cmd_rx, ev_tx)); @@ -233,6 +294,7 @@ impl Session { Command::OpenChat { target, .. } => { self.open_chats.insert(target.clone()); self.open_relay(&target); + self.open_history(&target); } Command::CloseChat { target, .. } => { self.open_chats.remove(&target); @@ -243,25 +305,42 @@ impl Session { let _ = tx.send(QueryCmd::CloseChat(target)); } } - Command::SendChat { target, text, .. } => match self.route(&target) { - ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)), - ChatRoute::Gateway => { - if let Some((_, tx)) = &self.gateway { - let _ = tx.send(GatewayCmd::SendChat(target, text)); - } + Command::SendChat { target, text, .. } => { + let route = self.route(&target); + if !matches!(route, ChatRoute::Unavailable(_)) { + self.store_own(&target, &text, &route); } - ChatRoute::Query => { - if let Some((_, tx)) = &self.query { - let nick = if self.nickname.is_empty() { - "user".into() - } else { - self.nickname.clone() - }; - let _ = tx.send(QueryCmd::SendChat { target, nick, text }); + match route { + ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)), + ChatRoute::Gateway => { + if let Some((_, tx)) = &self.gateway { + let _ = tx.send(GatewayCmd::SendChat(target, text)); + } } + ChatRoute::Query => { + if let Some((_, tx)) = &self.query { + let nick = self.relay_nick(); + let _ = tx.send(QueryCmd::SendChat { target, nick, text }); + } + } + ChatRoute::Unavailable(reason) => self.error(reason), } - ChatRoute::Unavailable(reason) => self.error(reason), + } + Command::LoadOlderHistory { target, before, .. } => match self.chat_ctx() { + Some(ctx) => { + let gateway = self.gateway_client.clone(); + tokio::spawn(history::load_older(ctx, target, before, gateway)); + } + // Nothing is known about the server yet: nothing stored. + None => self.emit(Event::ChatHistory { + session: self.id, + target, + messages: Vec::new(), + source: history::HistorySource::Local, + complete: true, + }), }, + Command::Gateway { request, .. } => self.gateway_request(request), Command::MoveToChannel { channel, password, .. } => { self.voice_cmd(VoiceCmd::Move(channel, password)); } @@ -353,7 +432,8 @@ impl Session { | Command::TestMicrophone { .. } | Command::SetSetting { .. } | Command::ResetSetting { .. } - | Command::AttachSettings(_) => {} + | Command::AttachSettings(_) + | Command::AttachHistory(_) => {} } } @@ -372,6 +452,8 @@ impl Session { s.send(StreamInput::Shutdown(reason.into())); } self.streaming_clients.clear(); + // The stream task's report comes from a replaced source. + self.own_stream_ended(); } fn voice_cmd(&self, cmd: VoiceCmd) { @@ -389,6 +471,11 @@ impl Session { route_chat(target, voice_channel, self.gateway.is_some(), self.query.is_some()) } + /// The nickname relays post our messages under. + fn relay_nick(&self) -> String { + if self.nickname.is_empty() { "user".into() } else { self.nickname.clone() } + } + /// Chats that are not covered by the voice connection need a relay. fn open_relay(&self, target: &ChatTarget) { match self.route(target) { @@ -412,6 +499,235 @@ impl Session { } } + // Chat history + + /// What the history flows need; `None` until the server's unique id is known. + fn chat_ctx(&self) -> Option { + Some(ChatCtx { + session: self.id, + events: self.events.clone(), + history: self.history.current(), + settings: self.settings.current(), + server_uid: self.state.server_uid.clone()?, + }) + } + + /// `chat.store_history` off: the history (and what it remembers about + /// servers) stays in memory. + fn memory(&self) -> bool { + !self.settings.current().get(&crate::settings::CHAT_STORE_HISTORY) + } + + /// Show a chat's stored messages, then sync it with the gateway. + fn open_history(&self, target: &ChatTarget) { + if let Some(ctx) = self.chat_ctx() { + // A gateway that is still connecting may have more. + let pending = self.gateway.is_some() && self.gateway_client.is_none(); + let gateway = self.gateway_client.clone(); + tokio::spawn(history::open_chat(ctx, target.clone(), gateway, pending)); + } + } + + fn open_histories(&self) { + for target in &self.open_chats { + self.open_history(target); + } + } + + /// Look up the server's unique id remembered for `alias`, and remember + /// it under `alias` once a source tells it. + fn known_server(&mut self, alias: String) { + if !self.aliases.contains(&alias) { + self.aliases.push(alias.clone()); + } + if self.state.server_uid.is_some() { + return; + } + let tx = self.sources_tx.clone(); + self.history.current().run_then( + self.memory(), + move |s| s.server_alias(&alias), + move |uid| { + if let Ok(Some(uid)) = uid { + let _ = tx.send(SourceEvent::KnownServer(uid)); + } + }, + ); + } + + /// A source told the server's unique id. The gateway's wins: its + /// history is the one synced. `true` if the history key changed. + fn learn_server_uid(&mut self, uid: String, from: Source) -> bool { + let gateway_key = self.state.server_uid.clone().filter(|_| self.gateway_client.is_some()); + let keep = from != Source::Gateway && gateway_key.is_some(); + if from != Source::Query { + let aliases = self.aliases.clone(); + let key = gateway_key.filter(|_| keep).unwrap_or_else(|| uid.clone()); + self.history.current().run_then( + self.memory(), + move |s| aliases.iter().try_for_each(|a| s.set_server_alias(a, &key)), + |r| { + if let Err(e) = r { + debug!("cannot remember the server's aliases: {e}"); + } + }, + ); + } + if keep || self.state.server_uid.as_deref() == Some(uid.as_str()) { + return false; + } + self.state.server_uid = Some(uid); + self.emit_state(); + true + } + + /// Store a message we send, at once (the copy that comes back is merged). + fn store_own(&self, target: &ChatTarget, text: &str, route: &ChatRoute) { + let Some(ctx) = self.chat_ctx() else { return }; + let msg = ChatMessage { + target: target.clone(), + author_name: self.relay_nick(), + author_uid: self.own_uid.clone(), + author_id: self.state.own_client.filter(|_| *route == ChatRoute::Voice), + text: text.to_owned(), + ts_ms: history::now_ms(), + via_relay: *route != ChatRoute::Voice, + }; + ctx.store_live(vec![history::new_message(&ctx.server_uid, &msg, MessageSource::Local)]); + } + + // Gateway + + fn gateway_request(&mut self, request: GatewayRequest) { + let (Some(client), Some(ctx)) = (self.gateway_client.clone(), self.chat_ctx()) else { + self.gateway_update(GatewayUpdate::Failed { + request: request.name().into(), + code: None, + message: "not connected to a gateway".into(), + }); + return; + }; + match request { + // The session keeps the directory. + GatewayRequest::SubscribeStreams { on: true } => self.subscribe_streams(&client), + request => { + tokio::spawn(gateway::execute(ctx, client, request)); + } + } + } + + fn subscribe_streams(&self, client: &GatewayClient) { + let Some((generation, _)) = self.gateway else { return }; + let (client, tx) = (client.clone(), self.sources_tx.clone()); + tokio::spawn(async move { + let result = client.subscribe_streams().await; + let _ = tx.send(SourceEvent::Directory(generation, result)); + }); + } + + /// Subscribe to what the gateway pushes (errors are reported). + fn subscribe_gateway(&self, client: &GatewayClient) { + if client.has(feature::STREAMS) { + self.subscribe_streams(client); + } + let ctx = self.chat_ctx(); + for (feature, request) in [ + (feature::EVENTS, GatewayRequest::SubscribeEvents { on: true }), + (feature::ACTIVITY, GatewayRequest::SubscribeActivity { on: true }), + ] { + if let Some(ctx) = ctx.clone().filter(|_| client.has(feature)) { + tokio::spawn(gateway::execute(ctx, client.clone(), request)); + } + } + } + + /// The registered streams of the directory, for the stream task. + fn feed_directory(&self) { + let Some(streams) = &self.streams else { return }; + let entries = self + .directory + .values() + .filter_map(|e| { + Some(StreamInfo { + id: e.stream_id.clone()?, + streamer: ClientId(e.client_id?), + name: e.title.clone(), + kind: parse_kind(&e.kind), + // Not in the directory; the stream's offer tells. + bitrate: 0, + viewer_limit: 0, + audio: true, + }) + }) + .collect(); + streams.send(StreamInput::Directory(entries)); + } + + fn register_own_stream(&mut self) { + let Some(client) = self.gateway_client.clone().filter(|c| c.has(feature::STREAMS)) else { + return; + }; + let Some(own) = self.own_stream.as_mut().filter(|s| !s.registered) else { return }; + own.registered = true; + let spec = StreamSpec { + stream_id: own.id.clone(), + client_id: self.state.own_client, + channel: self.state.own_channel, + title: own.title.clone(), + kind: kind_name(own.kind), + viewers: None, + }; + let (session, events) = (self.id, self.events.clone()); + tokio::spawn(async move { + let update = match client.register_stream(spec).await { + Ok(stream) => GatewayUpdate::StreamRegistered { stream }, + Err(e) => GatewayUpdate::Failed { + request: "register_stream".into(), + code: e.code(), + message: e.to_string(), + }, + }; + let _ = events.send(Event::Gateway { session, update }); + }); + } + + fn own_stream_ended(&mut self) { + let Some(own) = self.own_stream.take() else { return }; + if let Some(client) = self.gateway_client.clone().filter(|_| own.registered) { + tokio::spawn(async move { + if let Err(e) = client.unregister_stream(own.id).await { + debug!("cannot unregister our stream: {e}"); + } + }); + } + } + + fn own_stream_event(&mut self, e: OwnStreamEvent) { + match e { + OwnStreamEvent::Live { id, title, kind } => { + self.own_stream_ended(); + self.own_stream = Some(OwnStream { id, title, kind, registered: false }); + self.register_own_stream(); + } + OwnStreamEvent::Viewers(n) => { + let registered = self.own_stream.as_ref().filter(|s| s.registered); + if let (Some(own), Some(client)) = (registered, self.gateway_client.clone()) { + let id = own.id.clone(); + tokio::spawn(async move { + if let Err(e) = client.update_stream(id, None, Some(n)).await { + debug!("cannot update our stream's viewers: {e}"); + } + }); + } + } + OwnStreamEvent::Ended { id } => { + if self.own_stream.as_ref().is_some_and(|s| s.id == id) { + self.own_stream_ended(); + } + } + } + } + fn stop_observing(&mut self) { if let Some((_, tx)) = self.gateway.take() { let _ = tx.send(GatewayCmd::Stop); @@ -419,12 +735,28 @@ impl Session { if let Some((_, tx)) = self.query.take() { let _ = tx.send(QueryCmd::Stop); } + self.gateway_gone(None); self.gateway_presence = None; self.query_presence = None; self.state.observe = ObserveState::Off; self.emit_state(); } + /// Forget the logged-in gateway and what came from it. + fn gateway_gone(&mut self, reason: Option) { + if self.gateway_client.take().is_none() { + return; + } + if let Some(own) = &mut self.own_stream { + own.registered = false; + } + if !self.directory.is_empty() { + self.directory.clear(); + self.feed_directory(); + } + self.gateway_update(GatewayUpdate::Disconnected { reason }); + } + fn stop_all(&mut self) { self.stop_streams("session closed"); if let Some((_, tx)) = self.voice.take() { @@ -461,20 +793,53 @@ impl Session { self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending }) } }, + SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => { + self.own_stream_event(e) + } + SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => { + match result { + Ok(streams) => { + self.directory = + streams.iter().map(|e| (e.id.clone(), e.clone())).collect(); + self.feed_directory(); + self.gateway_update(GatewayUpdate::Streams { streams }); + } + Err(e) => self.gateway_update(GatewayUpdate::Failed { + request: "subscribe_streams".into(), + code: e.code(), + message: e.to_string(), + }), + } + } + SourceEvent::KnownServer(uid) => { + // A source may have told the real one meanwhile. + if self.state.server_uid.is_none() { + self.state.server_uid = Some(uid); + self.emit_state(); + self.open_histories(); + } + } _ => debug!("event from a replaced source ignored"), } } fn voice_event(&mut self, e: VoiceEvent) { match e { - VoiceEvent::Connected { name, flavor, own_client } => { + VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => { self.state.voice = VoiceState::Connected; self.state.own_client = Some(own_client); + if own_uid.is_some() { + self.own_uid = own_uid; + } + self.learn_server_uid(server_uid, Source::Voice); self.emit_state(); let capabilities = flavor.capabilities(); if capabilities.streams - && let Some((_, voice)) = &self.voice + && let Some((generation, voice)) = &self.voice { + let generation = *generation; + let (own_tx, own_rx) = mpsc::unbounded_channel(); + self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e)); let streams = StreamHandle::spawn( self.id, own_client, @@ -484,14 +849,17 @@ impl Session { self.frames.clone(), self.audio.clone(), self.settings.clone(), + own_tx, ); if !self.stream_layers.is_empty() { streams.send(StreamInput::Layers(self.stream_layers.clone())); } self.streams = Some(streams); + self.feed_directory(); } self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities }); self.reopen_relayed_chats(); + self.open_histories(); } VoiceEvent::Presence(p) => { // Client ids are reused: forget the volumes of those who left. @@ -530,7 +898,7 @@ impl Session { self.emit_state(); } } - VoiceEvent::Chat(msg) => self.chat(msg), + VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None), VoiceEvent::Audio(packet) => { if let Some(a) = &self.audio { a.send(AudioIn::Packet(packet)); @@ -558,18 +926,34 @@ impl Session { fn gateway_event(&mut self, e: GatewayEvent) { match e { - GatewayEvent::Connected => { + GatewayEvent::Connected(client) => { self.state.observe = ObserveState::Observing; + let info = client.info().clone(); + self.gateway_client = Some(client.clone()); + if self.own_uid.is_none() { + self.own_uid = Some(info.uid.clone()); + } + self.learn_server_uid(info.server_uid.clone(), Source::Gateway); self.emit_state(); + self.gateway_update(GatewayUpdate::Connected { + gateway_id: info.gateway_id, + server_uid: info.server_uid, + server_name: info.server_name, + uid: info.uid, + capabilities: client.capabilities(), + }); + self.subscribe_gateway(&client); + self.register_own_stream(); + self.open_histories(); } GatewayEvent::Presence(p) => { self.gateway_presence = Some(p); self.publish_presence(); } - GatewayEvent::Chat(msg) => self.chat(msg), - GatewayEvent::Error(message) => self.error(format!("gateway: {message}")), + GatewayEvent::Push(push) => self.gateway_push(*push), GatewayEvent::Disconnected(reason) => { self.gateway = None; + self.gateway_gone(reason.clone()); self.gateway_presence = None; self.state.observe = ObserveState::Off; self.emit_state(); @@ -581,6 +965,78 @@ impl Session { } } + fn gateway_push(&mut self, push: Push) { + let ctx = self.chat_ctx(); + match push { + Push::Chat { id, message } => { + let entry = HistoryEntry::new(id, message.clone()); + self.chat(message, MessageSource::Gateway, Some(entry)); + } + Push::Message(entry) => { + self.chat(entry.message.clone(), MessageSource::Gateway, Some(entry)); + } + Push::Pinned { target, pin } => match ctx { + Some(ctx) => ctx.pinned(target, pin), + None => { + let message = HistoryMessage::unstored(&pin.entry); + let pin = gateway::Pin { message, by: pin.by, ts_ms: pin.ts_ms }; + self.gateway_update(GatewayUpdate::Pinned { target, pin }); + } + }, + Push::Unpinned { target, message_id, by } => match ctx { + Some(ctx) => ctx.unpinned(target, message_id, by), + None => self.gateway_update(GatewayUpdate::Unpinned { target, message_id, by }), + }, + Push::Reaction { target, message_id, emoji, user, added, count } => { + let push = ReactionPush { target, message_id, emoji, user, added, count }; + match ctx { + Some(ctx) => ctx.reaction(push, self.own_uid.as_deref()), + None => self.gateway_update(GatewayUpdate::Reaction { + target: push.target, + message_id: push.message_id, + emoji: push.emoji, + user: push.user, + added: push.added, + count: push.count, + }), + } + } + Push::TopicUpdated(topic) => self.gateway_update(GatewayUpdate::Topic { topic }), + Push::EventUpdated(event) => self.gateway_update(GatewayUpdate::Event { event }), + Push::EventDeleted(id) => self.gateway_update(GatewayUpdate::EventDeleted { id }), + Push::EventReminder { event, starts_in_ms } => { + self.gateway_update(GatewayUpdate::EventReminder { event, starts_in_ms }); + } + Push::StreamStarted(stream) => { + self.directory.insert(stream.id.clone(), stream.clone()); + self.feed_directory(); + self.gateway_update(GatewayUpdate::StreamStarted { stream }); + } + Push::StreamUpdated(stream) => { + self.directory.insert(stream.id.clone(), stream.clone()); + self.feed_directory(); + self.gateway_update(GatewayUpdate::StreamUpdated { stream }); + } + Push::StreamEnded { id, reason } => { + if self.directory.remove(&id).is_some() { + self.feed_directory(); + } + self.gateway_update(GatewayUpdate::StreamEnded { id, reason }); + } + Push::ActivityAdded(entry) => { + self.gateway_update(GatewayUpdate::ActivityAdded { entry }) + } + Push::Capabilities(capabilities) => { + self.gateway_update(GatewayUpdate::Capabilities { capabilities }); + } + Push::Error { code, message } => self.error(format!("gateway: {code:?}: {message}")), + Push::PresenceSnapshot(_) + | Push::PresenceDelta(_) + | Push::Other(_) + | Push::Disconnected(_) => {} + } + } + fn query_event(&mut self, e: QueryEvent) { match e { QueryEvent::Presence(p) => { @@ -591,7 +1047,7 @@ impl Session { self.query_presence = Some(p); self.publish_presence(); } - QueryEvent::Chat(msg) => self.chat(msg), + QueryEvent::Chat(msg) => self.chat(msg, MessageSource::Query, None), QueryEvent::Error(message) => self.error(format!("query: {message}")), QueryEvent::Disconnected => { self.query = None; @@ -603,12 +1059,23 @@ impl Session { } } - fn chat(&mut self, msg: ChatMessage) { + /// A live message: reported, and stored (merged with other copies). + fn chat(&mut self, msg: ChatMessage, source: MessageSource, entry: Option) { let wanted = match &msg.target { ChatTarget::Server | ChatTarget::Private(_) => true, target => self.open_chats.contains(target) || !msg.via_relay, }; - if wanted && !self.dedup.is_duplicate(&msg) { + if !wanted { + return; + } + if let Some(ctx) = self.chat_ctx() { + let stored = match &entry { + Some(entry) => history::gateway_message(&ctx.server_uid, entry), + None => history::new_message(&ctx.server_uid, &msg, source), + }; + ctx.store_live(vec![stored]); + } + if !self.dedup.is_duplicate(&msg) { self.emit(Event::Chat { session: self.id, message: msg }); } } diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 04211d7..025d35e 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1061,8 +1061,126 @@ pub static STREAM_PERMISSIONS: Key = Key::new( StreamPermissions::default, ); +/// Keep chat history in the client database. Off: messages seen from now +/// on are kept in memory only (for this run), nothing is read from or +/// written to the database. +pub static CHAT_STORE_HISTORY: Key = + Key::new("chat.store_history", Kind::Bool, "Keep chat history on this device.", || true); + +/// Messages per history page: shown when a chat opens, fetched per step +/// when scrolling back, and per request while syncing with a gateway. +/// 0: everything at once. No maximum. +pub static CHAT_HISTORY_PAGE: Key = Key::new( + "chat.history_page", + Kind::UInt { min: 0 }, + "Messages per chat history page (0: all at once).", + || 100, +); + +/// How far apart (ms) two copies of a message from different sources may +/// be stamped and still count as one message (e.g. live over voice and +/// again from the gateway). No maximum. +pub static CHAT_DEDUPE_TOLERANCE_MS: Key = Key::new( + "chat.dedupe_tolerance_ms", + Kind::UInt { min: 0 }, + "Time difference (ms) within which two copies of a message are one.", + || 5000, +); + +/// Delete stored chat messages older than this many days (pinned ones +/// stay); 0 keeps everything. +pub static CHAT_RETENTION_DAYS: Key = Key::new( + "chat.retention_days", + Kind::UInt { min: 0 }, + "Delete stored chat messages older than this many days (0: keep all).", + || 0, +); + +/// What an audio source of our stream captures, as stored; see +/// [`AudioSourceSetting`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum AudioSourceKindSetting { + /// Everything that plays except Voelin itself (voices, watched streams). + Desktop, + /// One application: by `name` (application name or executable; the + /// package on Android), found again when it restarts, or by `pid` + /// (valid while that process runs). + App { + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pid: Option, + }, + /// The application of the shared window, where the platform tells + /// (X11, Windows). + Window, + /// Our microphone after noise suppression and gain control. + Microphone, + /// A test tone. + Synthetic { + #[serde(default = "default_tone")] + frequency: u32, + }, +} + +fn default_tone() -> u32 { + 440 +} + +fn unity() -> f32 { + 1.0 +} + +/// One audio source mixed into our stream. The serde form: +/// `{"kind": "desktop"}`, `{"kind": "app", "name": "firefox", "gain": 0.5}`, +/// `{"kind": "microphone", "muted": true}`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AudioSourceSetting { + #[serde(flatten)] + pub kind: AudioSourceKindSetting, + /// Linear gain (1: unchanged), any value >= 0. + #[serde(default = "unity")] + pub gain: f32, + #[serde(default)] + pub muted: bool, +} + +impl AudioSourceSetting { + pub fn new(kind: AudioSourceKindSetting) -> Self { + Self { kind, gain: 1.0, muted: false } + } +} + +#[allow(clippy::ptr_arg)] // a validation of `Key>` is `fn(&Vec<_>)` +fn valid_audio_sources(sources: &Vec) -> Result<(), String> { + for (i, source) in sources.iter().enumerate() { + if !(source.gain.is_finite() && source.gain >= 0.0) { + return Err(format!("source {i}: gain must be a number >= 0")); + } + if let AudioSourceKindSetting::App { name, pid } = &source.kind + && name.as_deref().is_none_or(|n| n.trim().is_empty()) + && pid.is_none() + { + return Err(format!("source {i}: an app needs a name or a pid")); + } + } + Ok(()) +} + +/// Audio sources mixed into our stream (read when a stream starts; a +/// running stream follows through `media::Streamer::reconfigure`). Empty: +/// the stream has no audio. +pub static STREAM_AUDIO_SOURCES: Key> = Key::new( + "stream.audio_sources", + Kind::Json, + "Audio sources mixed into our stream (desktop, app, window, microphone).", + || vec![AudioSourceSetting::new(AudioSourceKindSetting::Desktop)], +) +.validated(valid_audio_sources); + /// The keys every [`Settings`] knows from the start. -pub fn builtin_keys() -> [&'static dyn Setting; 11] { +pub fn builtin_keys() -> [&'static dyn Setting; 16] { [ &CRASH_REPORTS, &AUDIO, @@ -1075,6 +1193,11 @@ pub fn builtin_keys() -> [&'static dyn Setting; 11] { &STREAM_SRTP_PROFILES, &STREAM_HARDWARE_ACCELERATION, &STREAM_PERMISSIONS, + &CHAT_STORE_HISTORY, + &CHAT_HISTORY_PAGE, + &CHAT_DEDUPE_TOLERANCE_MS, + &CHAT_RETENTION_DAYS, + &STREAM_AUDIO_SOURCES, ] } @@ -1127,6 +1250,10 @@ mod tests { ); assert!(s.get(&STREAM_HARDWARE_ACCELERATION)); assert_eq!(s.get(&STREAM_ENCODER_BACKEND), "auto"); + assert!(s.get(&CHAT_STORE_HISTORY)); + assert_eq!(s.get(&CHAT_HISTORY_PAGE), 100); + assert_eq!(s.get(&CHAT_DEDUPE_TOLERANCE_MS), 5000); + assert_eq!(s.get(&CHAT_RETENTION_DAYS), 0); assert_eq!(s.source("stream.fps"), Some(Source::Default)); let names: Vec<_> = s.keys().iter().map(|k| k.name()).collect(); assert!(names.contains(&"stream.permissions") && names.contains(&"audio")); @@ -1189,6 +1316,57 @@ mod tests { assert_eq!(s.get(&STREAM_BITRATE_KBPS), u32::MAX); } + #[test] + fn audio_sources() { + let s = Settings::in_memory(); + assert_eq!( + s.get(&STREAM_AUDIO_SOURCES), + [AudioSourceSetting::new(AudioSourceKindSetting::Desktop)] + ); + assert_eq!( + s.get_json("stream.audio_sources"), + Some(json!([{"kind": "desktop", "gain": 1.0, "muted": false}])) + ); + s.set_json( + "stream.audio_sources", + json!([ + {"kind": "desktop", "gain": 0.5}, + {"kind": "app", "name": "firefox"}, + {"kind": "app", "pid": 4242, "muted": true}, + {"kind": "window"}, + {"kind": "microphone", "gain": 2}, + {"kind": "synthetic"} + ]), + ) + .unwrap(); + let sources = s.get(&STREAM_AUDIO_SOURCES); + assert_eq!(sources.len(), 6); + assert_eq!(sources[0].gain, 0.5); + assert_eq!( + sources[1].kind, + AudioSourceKindSetting::App { name: Some("firefox".into()), pid: None } + ); + assert!(sources[2].muted); + assert_eq!( + sources[4], + AudioSourceSetting { + gain: 2.0, + ..AudioSourceSetting::new(AudioSourceKindSetting::Microphone) + } + ); + assert_eq!(sources[5].kind, AudioSourceKindSetting::Synthetic { frequency: 440 }); + let invalid = + |r: Result<(), SettingsError>| matches!(r, Err(SettingsError::Invalid { .. })); + assert!(invalid(s.set_json("stream.audio_sources", json!([{"kind": "app"}])))); + assert!(invalid( + s.set_json("stream.audio_sources", json!([{"kind": "desktop", "gain": -1}])) + )); + assert!(invalid(s.set_json("stream.audio_sources", json!([{"kind": "speakers"}])))); + // No sources: no audio. + s.set_json("stream.audio_sources", json!([])).unwrap(); + assert!(s.get(&STREAM_AUDIO_SOURCES).is_empty()); + } + #[test] fn layers_convert_to_specs() { let s = Settings::in_memory(); diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 8ef8cd9..957eb37 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -3,18 +3,26 @@ //! //! The voice task forwards stream notifications here and sends the resulting //! commands. Only started for TeamSpeak 6 servers. +//! +//! Streams that started before we joined are looked up on the server +//! (`requeststreaminfo`) and in the session's gateway directory: its +//! registered entries (stream id and streamer) are handed to the stream +//! sessions ([`voelin_stream::Streams::discovered`]) for streamers in our +//! channel, and a [`StreamLookup`] answers for the gateway when the server +//! cannot. Our own stream's life (live, viewers, ended) goes back to the +//! session ([`OwnStreamEvent`]), which keeps its directory entry. use std::collections::BTreeMap; use std::fmt; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; use tokio::sync::{broadcast, mpsc}; use tracing::debug; use tsclientlib::ClientId; use voelin_stream::{ - ClientState, LayerFeedback, Output, Request, StreamEvent, StreamNotification, StreamerEvent, - StreamerOptions, Streams, WatchEvent, + ClientState, LayerFeedback, Output, Request, StreamEvent, StreamLookup, StreamNotification, + StreamerEvent, StreamerOptions, Streams, WatchEvent, }; pub use voelin_stream::{ Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, @@ -159,10 +167,72 @@ pub(crate) enum StreamInput { RequestFailed(Request, String), /// Clients on the server: channel and `client_is_streaming`. Clients(BTreeMap), + /// The registered streams of the gateway's directory (full list). + Directory(Vec), /// The voice connection is gone. Shutdown(String), } +/// Our own stream, for the session (the gateway directory). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum OwnStreamEvent { + Live { + id: String, + title: String, + kind: StreamKind, + }, + /// Connected viewers. + Viewers(u32), + Ended { + id: String, + }, +} + +/// The kind of a stream as the gateway directory names it. +pub(crate) fn kind_name(kind: StreamKind) -> String { + match kind { + StreamKind::Camera => "camera".into(), + StreamKind::Screen => "screen".into(), + StreamKind::Window => "window".into(), + StreamKind::Other(v) => format!("other:{v}"), + } +} + +/// [`kind_name`] back; unknown names are screens. +pub(crate) fn parse_kind(name: &str) -> StreamKind { + match name { + "camera" => StreamKind::Camera, + "window" => StreamKind::Window, + other => match other.strip_prefix("other:").and_then(|v| v.parse().ok()) { + Some(v) => StreamKind::from_u8(v), + None => StreamKind::Screen, + }, + } +} + +/// The gateway directory as the stream task sees it. +#[derive(Default)] +struct GatewayStreams { + entries: Vec, + /// Streamers the [`GatewayLookup`] was asked about. + wanted: Vec, +} + +/// Looks unannounced streams up in the gateway's directory (after the +/// server, see [`voelin_stream::discovery`]). +struct GatewayLookup(Arc>); + +impl StreamLookup for GatewayLookup { + fn lookup(&mut self, streamer: ClientId, _out: &mut voelin_stream::session::Outbox) -> bool { + let mut dir = self.0.lock().unwrap_or_else(PoisonError::into_inner); + let known = dir.entries.iter().any(|e| e.streamer == streamer); + if known { + dir.wanted.push(streamer); + } + known + } +} + pub(crate) struct StreamHandle { tx: mpsc::UnboundedSender, } @@ -178,11 +248,15 @@ impl StreamHandle { frames: broadcast::Sender, audio: Option, settings: SharedSettings, + own: mpsc::UnboundedSender, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); + let mut streams = Streams::new(ClientId(own_client), config); + let gateway = Arc::new(Mutex::new(GatewayStreams::default())); + streams.add_lookup(Box::new(GatewayLookup(gateway.clone()))); let task = StreamTask { session, - streams: Streams::new(ClientId(own_client), config), + streams, voice, events, frames, @@ -191,6 +265,12 @@ impl StreamHandle { sink: None, layers: Vec::new(), settings, + own, + setup: None, + live: None, + viewers: 0, + clients: BTreeMap::new(), + gateway, }; tokio::spawn(task.run(rx)); Self { tx } @@ -217,6 +297,17 @@ struct StreamTask { layers: Vec, /// `stream.permissions` decides join requests. settings: SharedSettings, + /// Our stream's life, for the session. + own: mpsc::UnboundedSender, + /// The setup of our stream since `Start`. + setup: Option, + /// Our live stream's id. + live: Option, + /// Connected viewers of our stream, as last told. + viewers: u32, + /// The clients as of the last update. + clients: BTreeMap, + gateway: Arc>, } impl StreamTask { @@ -246,6 +337,7 @@ impl StreamTask { let session = self.session; let result = match input { StreamInput::Start { setup, auto_accept } => { + self.setup = Some(setup.clone()); let layers = self.layers.clone(); let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() }; self.streams.start(options).map(|()| { @@ -297,7 +389,14 @@ impl StreamTask { StreamInput::Clients(clients) => { // Streams of clients that left, stopped streaming or are not // in our channel are gone; unannounced ones are looked up. + self.clients = clients.clone(); self.streams.update_clients(clients); + self.add_directory_streams(); + Ok(()) + } + StreamInput::Directory(entries) => { + self.gateway.lock().unwrap_or_else(PoisonError::into_inner).entries = entries; + self.add_directory_streams(); Ok(()) } StreamInput::Shutdown(_) => Ok(()), @@ -307,6 +406,30 @@ impl StreamTask { } } + /// Streams of the gateway directory we were not told about: streamers in + /// our channel that still stream (the sessions check the channel). + fn add_directory_streams(&mut self) { + let entries = { + let mut dir = self.gateway.lock().unwrap_or_else(PoisonError::into_inner); + dir.wanted.clear(); + dir.entries.clone() + }; + let own = self.streams.own_client(); + for info in entries { + let stopped = + self.clients.get(&info.streamer.0).is_some_and(|c| c.streaming == Some(false)); + if info.streamer != own && !stopped && self.streams.directory().get(&info.id).is_none() + { + debug!(stream = %info.id, streamer = info.streamer.0, "stream from the gateway directory"); + self.streams.discovered(info); + } + } + } + + fn own_stream(&self, event: OwnStreamEvent) { + let _ = self.own.send(event); + } + /// Send the requests on the connection and report the events. fn flush(&mut self) { while let Some(output) = self.streams.poll_output() { @@ -334,6 +457,14 @@ impl StreamTask { feedback, }; self.sink = Some(sink.clone()); + let setup = self.setup.clone().unwrap_or_default(); + self.live = Some(id.clone()); + self.viewers = 0; + self.own_stream(OwnStreamEvent::Live { + id: id.clone(), + title: setup.name, + kind: setup.kind, + }); self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } }); } StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => { @@ -356,6 +487,12 @@ impl StreamTask { } } StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => { + let connected = + viewers.iter().filter(|v| v.state == ViewerState::Connected).count() as u32; + if connected != self.viewers && self.live.is_some() { + self.viewers = connected; + self.own_stream(OwnStreamEvent::Viewers(connected)); + } self.emit(Event::StreamViewers { session, viewers }); } // The sink already has it (layer feedback). @@ -369,6 +506,9 @@ impl StreamTask { if let Some(sink) = self.sink.take() { sink.live.store(false, Ordering::Relaxed); } + if let Some(id) = self.live.take() { + self.own_stream(OwnStreamEvent::Ended { id }); + } self.emit(Event::StreamState { session, state: StreamState::Ended(reason) }); } StreamEvent::Watch { id, event } => { @@ -423,6 +563,9 @@ impl StreamTask { if let Some(sink) = self.sink.take() { sink.live.store(false, Ordering::Relaxed); } + if let Some(id) = self.live.take() { + self.own_stream(OwnStreamEvent::Ended { id }); + } for watched in self.streams.watching() { let stream_id = watched.id().to_owned(); if let Some(audio) = &self.audio { @@ -539,6 +682,25 @@ mod tests { audio: Option, settings: &Settings, ) -> (Handles, broadcast::Receiver, broadcast::Receiver) { + let (handles, rx, frames, _) = pair_full(audio, settings, false); + (handles, rx, frames) + } + + /// [`pair_with`]; with `late`, the server does not tell the viewer + /// (session 2) about streams, as for a client that joined after the + /// stream started, and does not answer lookups. Also returns what the + /// streamer (session 1) reports about its own stream. + fn pair_full( + audio: Option, + settings: &Settings, + late: bool, + ) -> ( + Handles, + broadcast::Receiver, + broadcast::Receiver, + mpsc::UnboundedReceiver, + ) { + let (own_tx, own_rx) = mpsc::unbounded_channel(); let (events, rx) = broadcast::channel(4096); let (frames, frames_rx) = broadcast::channel(4096); let mut voices = Vec::new(); @@ -557,6 +719,7 @@ mod tests { frames.clone(), if session == 2 { audio.take() } else { None }, SharedSettings::new(settings.clone()), + if session == 1 { own_tx.clone() } else { mpsc::unbounded_channel().0 }, )); voices.push(voice_rx); } @@ -568,6 +731,10 @@ mod tests { while let Some(cmd) = voice_rx.recv().await { if let VoiceCmd::Stream(request) = cmd { for (to, n) in relay(CLIENTS[i], request) { + let announcement = matches!(n, StreamNotification::Started { .. }); + if late && to == CLIENTS[1] && announcement { + continue; + } let index = CLIENTS.iter().position(|c| *c == to).unwrap(); handles[index].send(StreamInput::Notification(n)); } @@ -575,7 +742,7 @@ mod tests { } }); } - (handles, rx, frames_rx) + (handles, rx, frames_rx, own_rx) } /// Session 1 streams (auto-accepting), session 2 watches; returns the sink @@ -754,6 +921,92 @@ mod tests { feeder.await.unwrap(); } + /// A viewer that was not told about a running stream, and whose server + /// lookup goes unanswered, finds it in the gateway directory and + /// watches it; the streamer reports its stream's life for the directory. + #[tokio::test(flavor = "multi_thread")] + async fn late_viewer_finds_the_stream_in_the_gateway_directory() { + let (handles, mut rx, _frames, mut own) = pair_full(None, &Settings::in_memory(), true); + let setup = StreamSetup { + name: "directory test".into(), + kind: StreamKind::Window, + ..Default::default() + }; + handles[0].send(StreamInput::Start { setup, auto_accept: true }); + wait(&mut rx, |e| match e { + Event::StreamState { session: 1, state: StreamState::Live { .. } } => Some(()), + _ => None, + }) + .await; + let live = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap(); + assert_eq!( + live, + OwnStreamEvent::Live { + id: "s-1".into(), + title: "directory test".into(), + kind: StreamKind::Window + } + ); + // Both in channel 1, the streamer streaming: the viewer asks the + // server, which does not answer. + let clients = BTreeMap::from([ + (CLIENTS[0], ClientState { channel: 1, streaming: Some(true) }), + (CLIENTS[1], ClientState { channel: 1, streaming: Some(false) }), + ]); + handles[1].send(StreamInput::Clients(clients)); + tokio::time::sleep(Duration::from_millis(200)).await; + // The gateway's directory has it. + let entry = StreamInfo { + id: "s-1".into(), + streamer: ClientId(CLIENTS[0]), + name: "directory test".into(), + kind: parse_kind(&kind_name(StreamKind::Window)), + bitrate: 0, + viewer_limit: 0, + audio: true, + }; + handles[1].send(StreamInput::Directory(vec![entry])); + wait(&mut rx, |e| match e { + Event::StreamsChanged { session: 2, streams } + if streams.iter().any(|s| s.id == "s-1") => + { + Some(()) + } + _ => None, + }) + .await; + handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + wait(&mut rx, |e| match e { + Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()), + _ => None, + }) + .await; + // One connected viewer, then the end. + let viewers = timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap(); + assert_eq!(viewers, OwnStreamEvent::Viewers(1)); + handles[0].send(StreamInput::Stop); + loop { + match timeout(Duration::from_secs(5), own.recv()).await.unwrap().unwrap() { + OwnStreamEvent::Ended { id } => break assert_eq!(id, "s-1"), + OwnStreamEvent::Viewers(_) => {} + other => panic!("{other:?}"), + } + } + for h in handles.iter() { + h.send(StreamInput::Shutdown("done".into())); + } + } + + #[test] + fn kind_names_round_trip() { + for kind in + [StreamKind::Camera, StreamKind::Screen, StreamKind::Window, StreamKind::Other(9)] + { + assert_eq!(parse_kind(&kind_name(kind)), kind); + } + assert_eq!(parse_kind("game"), StreamKind::Screen); + } + /// `stream.permissions` answers join requests unless it is `friends`. #[tokio::test(flavor = "multi_thread")] async fn permissions_answer_join_requests() { diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index c671236..6e9a5f8 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -68,6 +68,11 @@ pub(crate) enum VoiceEvent { name: String, flavor: ServerFlavor, own_client: u16, + /// The server's unique id (from its public key, as the server + /// generation computes it). + server_uid: String, + /// Our unique id as the server knows it. + own_uid: Option, }, Presence(Presence), OwnChannel(ChannelId), @@ -201,11 +206,20 @@ async fn run_inner( { let state = con.get_state()?; let flavor = ServerFlavor::from_version_string(&state.server.version); - info!(server = %state.server.name, ?flavor, "voice connected"); + let ids = voelin_gateway_proto::UniqueIds::from_omega(&state.server.public_key.to_ts()); + let server_uid = ids.for_server(matches!(flavor, ServerFlavor::Ts6(_))).to_owned(); + info!(server = %state.server.name, ?flavor, %server_uid, "voice connected"); + let own_uid = state + .clients + .get(&state.own_client) + .and_then(|c| c.uid.as_ref()) + .map(|u| u.as_ref().to_string()); let _ = events.send(VoiceEvent::Connected { name: state.server.name.clone(), flavor, own_client: state.own_client.0, + server_uid, + own_uid, }); } // Subscribe to all channels to see everyone. @@ -241,6 +255,13 @@ async fn run_inner( MessageTarget::Channel => { ChatTarget::Channel(own_channel.unwrap_or(0)) } + // Our own private message comes back to us: it + // belongs to the chat with its receiver. + MessageTarget::Client(to) + if Some(invoker.id) == own_client(&con) => + { + ChatTarget::Private(client_uid(&con, to).unwrap_or_default()) + } MessageTarget::Client(_) | MessageTarget::Poke(_) => { ChatTarget::Private( invoker @@ -314,6 +335,15 @@ async fn run_inner( Ok(()) } +fn own_client(con: &Connection) -> Option { + con.get_state().ok().map(|state| state.own_client) +} + +fn client_uid(con: &Connection, client: &tsclientlib::ClientId) -> Option { + let state = con.get_state().ok()?; + state.clients.get(client)?.uid.as_ref().map(|u| u.as_ref().to_string()) +} + fn own_channel(con: &Connection) -> Option { let state = con.get_state().ok()?; state.clients.get(&state.own_client).map(|c| c.channel.0) diff --git a/crates/voelin-core/tests/gateway.rs b/crates/voelin-core/tests/gateway.rs new file mode 100644 index 0000000..9fb294f --- /dev/null +++ b/crates/voelin-core/tests/gateway.rs @@ -0,0 +1,707 @@ +//! Chat history and gateway features through the engine, against a fake +//! gateway (a WebSocket server speaking the tsgw protocol from memory). + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use futures::{SinkExt, StreamExt}; +use serde_json::json; +use tokio::net::TcpListener; +use tokio::sync::broadcast::Receiver; +use tokio::sync::mpsc; +use tokio::time::timeout; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::handshake::server::{Request, Response}; +use voelin_core::gateway::{GatewayRequest, GatewayUpdate}; +use voelin_core::history::MessageSource; +use voelin_core::settings::Settings; +use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState}; +use voelin_gateway_proto::{ + ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg, + TopicInfo, UserRef, feature, +}; +use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot}; + +const LOBBY: ChatTarget = ChatTarget::Channel(1); +const ME: &str = "me-uid"; + +/// A connected session: its pushes and open chats. +type Session = (mpsc::UnboundedSender, Arc>>); + +/// The gateway's data. +#[derive(Default)] +struct State { + messages: Vec, + rev: i64, + /// (message, emoji) → who reacted. + reactions: BTreeMap<(i64, String), BTreeSet>, + topics: Vec, + /// Push channels of the connected sessions, with their open chats. + sessions: Vec, + /// Types of the requests received. + requests: Vec, + /// Close connections at once (the gateway is down). + refuse: bool, +} + +impl State { + fn next_rev(&mut self) -> i64 { + self.rev += 1; + self.rev + } + + /// A message as `uid` sees it. + fn view(&self, entry: &HistoryEntry, uid: &str) -> HistoryEntry { + let mut e = entry.clone(); + e.reactions = self + .reactions + .iter() + .filter(|((id, _), users)| *id == entry.id && !users.is_empty()) + .map(|((_, emoji), users)| ReactionCount { + emoji: emoji.clone(), + count: users.len() as u32, + me: users.contains(uid), + }) + .collect(); + e + } + + fn add(&mut self, target: ChatTarget, author: &str, text: &str, ts_ms: i64) -> HistoryEntry { + let rev = self.next_rev(); + let message = ChatMessage { + target, + author_name: author.into(), + author_uid: Some(format!("{author}-uid")), + author_id: None, + text: text.into(), + ts_ms, + via_relay: true, + }; + let entry = + HistoryEntry { rev, ..HistoryEntry::new(self.messages.len() as i64 + 1, message) }; + self.messages.push(entry.clone()); + self.push_open(&entry.message.target, ServerMsg::Message { entry: entry.clone() }); + entry + } + + fn push_open(&self, target: &ChatTarget, msg: ServerMsg) { + for (tx, open) in &self.sessions { + if open.lock().unwrap().contains(target) { + let _ = tx.send(msg.clone()); + } + } + } + + fn page(&self, q: &voelin_gateway_proto::HistoryQuery) -> HistoryPage { + let mut all: Vec<&HistoryEntry> = self + .messages + .iter() + .filter(|e| e.message.target == q.target) + .filter(|e| q.topic.is_none_or(|t| e.topic_id == Some(t))) + .filter(|e| q.before.is_none_or(|b| e.id < b)) + .filter(|e| q.before_ms.is_none_or(|b| e.message.ts_ms < b)) + .filter(|e| q.after.is_none_or(|a| e.id > a)) + .collect(); + let mut has_more = false; + if let Some(limit) = q.limit.map(|l| l as usize) + && all.len() > limit + { + has_more = true; + all = all.split_off(all.len() - limit); + } + HistoryPage { + target: q.target.clone(), + topic: q.topic, + messages: all.into_iter().map(|e| self.view(e, ME)).collect(), + has_more, + } + } +} + +struct FakeGateway { + state: Arc>, + url: String, +} + +impl FakeGateway { + async fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/v1", listener.local_addr().unwrap()); + let state: Arc> = Arc::default(); + let st = state.clone(); + tokio::spawn(async move { + while let Ok((tcp, _)) = listener.accept().await { + tokio::spawn(serve(tcp, st.clone())); + } + }); + Self { state, url } + } + + fn add(&self, target: ChatTarget, author: &str, text: &str, ts_ms: i64) -> HistoryEntry { + self.state.lock().unwrap().add(target, author, text, ts_ms) + } + + fn requests(&self) -> Vec { + self.state.lock().unwrap().requests.clone() + } +} + +fn caps() -> Vec { + [ + feature::PRESENCE, + feature::RELAY, + feature::HISTORY, + feature::PINS, + feature::REACTIONS, + feature::TOPICS, + feature::EVENTS, + ] + .map(String::from) + .to_vec() +} + +async fn serve(tcp: tokio::net::TcpStream, state: Arc>) { + if state.lock().unwrap().refuse { + return; + } + #[allow(clippy::result_large_err)] // tungstenite's callback type + let callback = |_: &Request, mut response: Response| { + response + .headers_mut() + .insert("Sec-WebSocket-Protocol", voelin_gateway_proto::SUBPROTOCOL.parse().unwrap()); + Ok(response) + }; + let ws = tokio_tungstenite::accept_hdr_async(tcp, callback).await.unwrap(); + let (mut sink, mut stream) = ws.split(); + let (tx, mut rx) = mpsc::unbounded_channel::>(); + tokio::spawn(async move { + while let Some(env) = rx.recv().await { + let text = serde_json::to_string(&env).unwrap(); + if sink.send(Message::Text(text.into())).await.is_err() { + break; + } + } + let _ = sink.close().await; + }); + let _ = tx.send(Envelope::new(ServerMsg::Hello { + gateway_id: "fake-gw".into(), + server_uid: "fake-server".into(), + server_name: "Fake".into(), + nonce: "n".into(), + capabilities: caps(), + })); + // Pushes of this session. + let (push_tx, mut push_rx) = mpsc::unbounded_channel(); + let open: Arc>> = Arc::default(); + let forward = tx.clone(); + tokio::spawn(async move { + while let Some(msg) = push_rx.recv().await { + if forward.send(Envelope::new(msg)).is_err() { + break; + } + } + }); + let mut logged_in = false; + while let Some(Ok(frame)) = stream.next().await { + let Message::Text(text) = frame else { continue }; + let env: Envelope = serde_json::from_str(text.as_str()).unwrap(); + let id = env.id.unwrap_or(0); + let reply = { + let mut st = state.lock().unwrap(); + let name = serde_json::to_value(&env.msg).unwrap()["type"].as_str().unwrap().to_owned(); + st.requests.push(name); + answer(&mut st, env.msg, &open, &push_tx, &mut logged_in) + }; + if tx.send(Envelope::with_id(id, reply)).is_err() { + break; + } + } + let mut st = state.lock().unwrap(); + st.sessions.retain(|(t, _)| !t.same_channel(&push_tx)); +} + +fn answer( + st: &mut State, + msg: ClientMsg, + open: &Arc>>, + push: &mpsc::UnboundedSender, + logged_in: &mut bool, +) -> ServerMsg { + match msg { + ClientMsg::Auth { .. } => { + *logged_in = true; + st.sessions.push((push.clone(), open.clone())); + ServerMsg::AuthOk { + uid: ME.into(), + token: "t".into(), + token_expires: i64::MAX, + capabilities: caps(), + } + } + _ if !*logged_in => { + ServerMsg::Error { code: ErrorCode::NotAuthenticated, message: "".into() } + } + ClientMsg::Enable { .. } => ServerMsg::Enabled { features: caps() }, + ClientMsg::SubscribePresence => { + let snapshot = PresenceSnapshot { + server_name: "Fake".into(), + channels: Vec::new(), + clients: Vec::new(), + }; + let _ = push.send(ServerMsg::PresenceSnapshot { seq: 0, snapshot }); + ServerMsg::Ok + } + ClientMsg::OpenChat { target } => { + open.lock().unwrap().insert(target); + ServerMsg::Ok + } + ClientMsg::CloseChat { target } => { + open.lock().unwrap().remove(&target); + ServerMsg::Ok + } + ClientMsg::SendChat { target, text } => { + // Posted as "me" (uid `me-uid`). + st.add(target, "me", &text, now_ms()); + ServerMsg::Ok + } + ClientMsg::Post { target, text, topic } => { + let rev = st.next_rev(); + let message = ChatMessage { + target: target.clone(), + author_name: "me".into(), + author_uid: Some(ME.into()), + author_id: None, + text, + ts_ms: now_ms(), + via_relay: true, + }; + let entry = HistoryEntry { + rev, + topic_id: topic, + ..HistoryEntry::new(st.messages.len() as i64 + 1, message) + }; + st.messages.push(entry.clone()); + st.push_open(&target, ServerMsg::Message { entry: entry.clone() }); + ServerMsg::Posted { entry } + } + ClientMsg::QueryHistory(q) => ServerMsg::HistoryPage(st.page(&q)), + ClientMsg::Sync { target, since_rev, limit } => { + let mut changed: Vec = st + .messages + .iter() + .filter(|e| e.message.target == target && e.rev > since_rev) + .map(|e| st.view(e, ME)) + .collect(); + changed.sort_by_key(|e| e.rev); + let has_more = limit.is_some_and(|l| changed.len() > l as usize); + if let Some(l) = limit { + changed.truncate(l as usize); + } + let rev = changed.last().map_or(since_rev, |e| e.rev); + ServerMsg::SyncPage { target, messages: changed, rev, has_more } + } + ClientMsg::Pin { message_id } => { + let rev = st.next_rev(); + let Some(e) = st.messages.iter_mut().find(|e| e.id == message_id) else { + return ServerMsg::Error { code: ErrorCode::NotFound, message: "".into() }; + }; + e.pinned = true; + e.rev = rev; + let entry = e.clone(); + let pin = PinInfo { entry: st.view(&entry, ME), by: me(), ts_ms: now_ms() }; + st.push_open( + &entry.message.target, + ServerMsg::Pinned { target: entry.message.target.clone(), pin }, + ); + ServerMsg::Ok + } + ClientMsg::ListPins { target } => ServerMsg::Pins { + pins: st + .messages + .iter() + .filter(|e| e.pinned && e.message.target == target) + .map(|e| PinInfo { entry: st.view(e, ME), by: me(), ts_ms: 1 }) + .collect(), + target, + }, + ClientMsg::React { message_id, emoji } => { + let rev = st.next_rev(); + let Some(e) = st.messages.iter_mut().find(|e| e.id == message_id) else { + return ServerMsg::Error { code: ErrorCode::NotFound, message: "".into() }; + }; + e.rev = rev; + let target = e.message.target.clone(); + let users = st.reactions.entry((message_id, emoji.clone())).or_default(); + users.insert(ME.into()); + let count = users.len() as u32; + let push = ServerMsg::Reaction { + target: target.clone(), + message_id, + emoji, + user: me(), + added: true, + count, + }; + st.push_open(&target, push); + ServerMsg::Ok + } + ClientMsg::CreateTopic { target, title, message_id } => { + let topic = TopicInfo { + id: st.topics.len() as i64 + 1, + target, + title, + creator: me(), + created_ms: 1, + root_message_id: message_id, + last_activity_ms: 1, + message_count: 0, + archived: false, + }; + st.topics.push(topic.clone()); + ServerMsg::Topic { topic } + } + ClientMsg::SubscribeEvents | ClientMsg::Ping => ServerMsg::Ok, + _ => ServerMsg::Error { code: ErrorCode::UnknownType, message: "not in the fake".into() }, + } +} + +fn me() -> UserRef { + UserRef { uid: ME.into(), name: "me".into() } +} + +fn now_ms() -> i64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64 +} + +/// The next event matching `f`, within 10 s. +async fn wait(rx: &mut Receiver, what: &str, mut f: impl FnMut(Event) -> Option) -> T { + timeout(Duration::from_secs(10), async { + loop { + match rx.recv().await { + Ok(e) => { + if let Some(t) = f(e) { + return t; + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + Err(e) => panic!("{e}"), + } + } + }) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}")) +} + +type Batch = (Vec, HistorySource, bool); + +async fn batch(rx: &mut Receiver, source: HistorySource) -> Batch { + wait(rx, &format!("{source:?} history"), |e| match e { + Event::ChatHistory { messages, source: s, complete, target, .. } + if s == source && target == LOBBY => + { + Some((messages, s, complete)) + } + _ => None, + }) + .await +} + +fn texts(messages: &[HistoryMessage]) -> Vec<&str> { + messages.iter().map(|m| m.message.text.as_str()).collect() +} + +async fn update( + rx: &mut Receiver, + what: &str, + mut f: impl FnMut(&GatewayUpdate) -> bool, +) -> GatewayUpdate { + wait(rx, what, |e| match e { + Event::Gateway { update, .. } if f(&update) => Some(update), + _ => None, + }) + .await +} + +fn observe(engine: &Engine, session: u64, gw: &FakeGateway) { + let identity = tsclientlib::Identity::create(); + engine.send(Command::ObserveGateway { + session, + url: gw.url.clone(), + identity: Box::new(identity), + }); +} + +fn temp_db(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-core-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir.join("client.db") +} + +/// Opening a chat shows the stored page, then the gateway's; older pages +/// come from the gateway; what was said while we were away arrives on the +/// next connect; the database keeps it all. +#[tokio::test(flavor = "multi_thread")] +async fn history_on_open_paging_and_offline_messages() { + let gw = FakeGateway::start().await; + for i in 1..=5 { + gw.add(LOBBY, "alice", &format!("m{i}"), i * 1000); + } + gw.add(ChatTarget::Server, "alice", "elsewhere", 500); + let path = temp_db("history"); + let settings = Settings::in_memory(); + settings.set_json("chat.history_page", json!(3)).unwrap(); + let engine = Engine::start_with(settings.clone(), History::open(&path).unwrap()); + let mut rx = engine.subscribe(); + + engine.send(Command::OpenChat { session: 1, target: LOBBY }); + observe(&engine, 1, &gw); + // Nothing stored yet; then the gateway's latest page; then in sync. + let (local, _, complete) = batch(&mut rx, HistorySource::Local).await; + assert!(local.is_empty() && !complete); + let (page, _, complete) = batch(&mut rx, HistorySource::Gateway).await; + assert_eq!(texts(&page), ["m3", "m4", "m5"]); + assert!(!complete, "older messages exist"); + assert!(page.iter().all(|m| m.remote_id.is_some() && m.source == MessageSource::Gateway)); + let (synced, _, _) = batch(&mut rx, HistorySource::Gateway).await; + assert!(synced.is_empty(), "nothing new: {synced:?}"); + + // Older: the gateway's page before m3. + engine.send(Command::LoadOlderHistory { session: 1, target: LOBBY, before: Some(page[0].id) }); + let (older, _, complete) = batch(&mut rx, HistorySource::Gateway).await; + assert_eq!(texts(&older), ["m1", "m2"]); + assert!(complete, "the beginning"); + + // Away: two messages and a pin on m2. + engine.send(Command::StopObserving { session: 1 }); + wait(&mut rx, "gateway stopped", |e| match e { + Event::State { state, .. } if state.observe == ObserveState::Off => Some(()), + _ => None, + }) + .await; + gw.add(LOBBY, "bob", "while away 1", 6000); + gw.add(LOBBY, "bob", "while away 2", 7000); + { + let mut st = gw.state.lock().unwrap(); + let rev = st.next_rev(); + let m2 = st.messages.iter_mut().find(|e| e.message.text == "m2").unwrap(); + m2.pinned = true; + m2.rev = rev; + } + // Back: stored page at once, then what we missed. + observe(&engine, 1, &gw); + let (local, _, _) = batch(&mut rx, HistorySource::Local).await; + assert_eq!(texts(&local), ["m3", "m4", "m5"]); + let mut missed = Vec::new(); + while missed.len() < 3 { + missed.extend(batch(&mut rx, HistorySource::Gateway).await.0); + } + missed.sort_by_key(|m| (m.message.ts_ms, m.id)); + assert_eq!(texts(&missed), ["m2", "while away 1", "while away 2"]); + assert!(missed[0].pinned); + assert_eq!(missed[0].id, older[1].id, "the stored row was updated"); + + // It is all in the database, oldest first. + engine.send(Command::CloseSession { session: 1 }); + let history = engine.history(); + let stored = history.page("fake-server", &LOBBY, Default::default(), false).await.unwrap(); + assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]); + history.flush(); + drop((engine, history)); + + // After a restart, with the gateway down: the stored page, found by the + // gateway's URL, which is remembered with the server's id. + gw.state.lock().unwrap().refuse = true; + let engine = Engine::start_with(settings, History::open(&path).unwrap()); + let mut rx = engine.subscribe(); + engine.send(Command::OpenChat { session: 7, target: LOBBY }); + observe(&engine, 7, &gw); + let (local, source) = wait(&mut rx, "history without the gateway", |e| match e { + Event::ChatHistory { session: 7, messages, source, .. } => Some((messages, source)), + _ => None, + }) + .await; + assert_eq!(source, HistorySource::Local); + assert_eq!(texts(&local), ["m5", "while away 1", "while away 2"]); + drop(engine); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); +} + +/// Live messages, our own included, are stored once; pins, reactions, +/// topics and other requests go through Command::Gateway. +#[tokio::test(flavor = "multi_thread")] +async fn live_messages_and_gateway_requests() { + let gw = FakeGateway::start().await; + let engine = Engine::start(); + let mut rx = engine.subscribe(); + engine.send(Command::OpenChat { session: 1, target: LOBBY }); + observe(&engine, 1, &gw); + let connected = + update(&mut rx, "connected", |u| matches!(u, GatewayUpdate::Connected { .. })).await; + let GatewayUpdate::Connected { server_uid, uid, capabilities, .. } = connected else { + unreachable!() + }; + assert_eq!((server_uid.as_str(), uid.as_str()), ("fake-server", ME)); + assert!(capabilities.iter().any(|c| c == feature::PINS)); + // In sync (the chat is empty). + batch(&mut rx, HistorySource::Gateway).await; + + // Our message: stored at once, then merged with the gateway's copy. + engine.send(Command::SendChat { session: 1, target: LOBBY, text: "hello".into() }); + let (sent, _, _) = batch(&mut rx, HistorySource::Live).await; + assert_eq!((sent[0].source, sent[0].remote_id), (MessageSource::Local, None)); + let (merged, _, _) = batch(&mut rx, HistorySource::Live).await; + assert_eq!(merged[0].id, sent[0].id, "one message"); + let remote = merged[0].remote_id.expect("the gateway's id"); + + // A message from someone else arrives live. + gw.add(LOBBY, "bob", "hi me", now_ms()); + let (live, _, _) = batch(&mut rx, HistorySource::Live).await; + assert_eq!(texts(&live), ["hi me"]); + assert_ne!(live[0].id, sent[0].id); + + // Pin: done, pushed, the row is pinned. + engine + .send(Command::Gateway { session: 1, request: GatewayRequest::Pin { message_id: remote } }); + let (mut pinned_row, mut pinned_push, mut done) = (None, None, false); + wait(&mut rx, "pin", |e| { + match e { + Event::ChatHistory { messages, source: HistorySource::Live, .. } + if messages[0].pinned => + { + pinned_row = Some(messages[0].clone()); + } + Event::Gateway { update: GatewayUpdate::Pinned { pin, .. }, .. } => { + pinned_push = Some(pin) + } + Event::Gateway { update: GatewayUpdate::Done { request }, .. } if request == "pin" => { + done = true + } + _ => {} + } + (pinned_row.is_some() && pinned_push.is_some() && done).then_some(()) + }) + .await; + assert_eq!(pinned_row.unwrap().id, sent[0].id); + assert_eq!(pinned_push.unwrap().message.id, sent[0].id); + + // React: the row carries the count and that it was us. + engine.send(Command::Gateway { + session: 1, + request: GatewayRequest::React { message_id: remote, emoji: "👍".into() }, + }); + let row = wait(&mut rx, "reaction", |e| match e { + Event::ChatHistory { messages, source: HistorySource::Live, .. } + if !messages[0].reactions.is_empty() => + { + Some(messages[0].clone()) + } + _ => None, + }) + .await; + assert_eq!(row.reactions, [ReactionCount { emoji: "👍".into(), count: 1, me: true }]); + update(&mut rx, "reaction push", |u| { + matches!(u, GatewayUpdate::Reaction { added: true, count: 1, .. }) + }) + .await; + + // A topic from the message, and a post into it. + engine.send(Command::Gateway { + session: 1, + request: GatewayRequest::CreateTopic { + target: LOBBY, + title: "Plans".into(), + message_id: Some(remote), + }, + }); + let GatewayUpdate::Topic { topic } = + update(&mut rx, "topic", |u| matches!(u, GatewayUpdate::Topic { .. })).await + else { + unreachable!() + }; + assert_eq!((topic.title.as_str(), topic.root_message_id), ("Plans", Some(remote))); + engine.send(Command::Gateway { + session: 1, + request: GatewayRequest::Post { + target: LOBBY, + text: "in topic".into(), + topic: Some(topic.id), + }, + }); + let GatewayUpdate::Posted { message } = + update(&mut rx, "posted", |u| matches!(u, GatewayUpdate::Posted { .. })).await + else { + unreachable!() + }; + assert_eq!((message.topic_id, message.message.text.as_str()), (Some(topic.id), "in topic")); + assert_ne!(message.id, 0, "stored (in memory: negative ids)"); + + // Pins list with local ids. + engine.send(Command::Gateway { session: 1, request: GatewayRequest::Pins { target: LOBBY } }); + let GatewayUpdate::Pins { pins, .. } = + update(&mut rx, "pins", |u| matches!(u, GatewayUpdate::Pins { .. })).await + else { + unreachable!() + }; + assert_eq!(pins.iter().map(|p| p.message.id).collect::>(), [sent[0].id]); + + // Refusals come as Failed, with the gateway's code. + engine.send(Command::Gateway { session: 1, request: GatewayRequest::ConfigList }); + let failed = update(&mut rx, "failed", |u| matches!(u, GatewayUpdate::Failed { .. })).await; + assert!( + matches!(failed, GatewayUpdate::Failed { request, code: Some(ErrorCode::UnknownType), .. } if request == "config_list") + ); + // Without a gateway, too. + engine.send(Command::Gateway { session: 2, request: GatewayRequest::Streams }); + let failed = wait(&mut rx, "no gateway", |e| match e { + Event::Gateway { session: 2, update } => Some(update), + _ => None, + }) + .await; + assert!(matches!(failed, GatewayUpdate::Failed { code: None, .. })); + + // Everything is one row per message in the (in-memory) history. + let stored = engine.history().page("fake-server", &LOBBY, Default::default(), false).await; + assert_eq!(texts(&stored.unwrap()), ["hello", "hi me", "in topic"]); + // The engine enabled the extensions and subscribed to events. + let requests = gw.requests(); + assert!(requests.contains(&"enable".to_owned()), "{requests:?}"); + assert!(requests.contains(&"subscribe_events".to_owned()), "{requests:?}"); + // Requests serialize for tools. + assert_eq!( + serde_json::to_value(GatewayRequest::Pin { message_id: 7 }).unwrap(), + json!({"pin": {"message_id": 7}}) + ); + let parsed: GatewayRequest = + serde_json::from_value(json!({"topics": {"target": {"kind": "channel", "id": 1}}})) + .unwrap(); + assert_eq!(parsed, GatewayRequest::Topics { target: LOBBY, include_archived: false }); +} + +/// With `chat.store_history` off nothing reaches the database; messages +/// are kept in memory with negative ids. +#[tokio::test(flavor = "multi_thread")] +async fn store_history_off_keeps_the_database_empty() { + let gw = FakeGateway::start().await; + gw.add(LOBBY, "alice", "secret", 1000); + let path = temp_db("nostore"); + let settings = Settings::in_memory(); + settings.set_json("chat.store_history", json!(false)).unwrap(); + let engine = Engine::start_with(settings, History::open(&path).unwrap()); + let mut rx = engine.subscribe(); + engine.send(Command::OpenChat { session: 1, target: LOBBY }); + observe(&engine, 1, &gw); + let (page, _, _) = batch(&mut rx, HistorySource::Gateway).await; + assert_eq!(texts(&page), ["secret"]); + assert!(page[0].id < 0, "{}", page[0].id); + let history = engine.history(); + assert!( + history.page("fake-server", &LOBBY, Default::default(), false).await.unwrap().is_empty() + ); + assert_eq!( + history.page("fake-server", &LOBBY, Default::default(), true).await.unwrap().len(), + 1 + ); + drop((engine, history)); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); +} diff --git a/crates/voelin-core/tests/media_live.rs b/crates/voelin-core/tests/media_live.rs index a4519db..3226768 100644 --- a/crates/voelin-core/tests/media_live.rs +++ b/crates/voelin-core/tests/media_live.rs @@ -159,7 +159,11 @@ async fn ts6_test_pattern_decoded() { assert!(widths.iter().all(|w| (120..=136).contains(w)), "{widths:?}"); let stats = viewer.stats(); assert!(stats.error.is_none(), "{stats:?}"); - eprintln!("decoded {stats:?}, sent {:?}", streamer.stats()); + // The mixed test tone went out as 20 ms Opus frames all along. + let sent = streamer.stats(); + eprintln!("decoded {stats:?}, sent {sent:?}"); + assert!(sent.audio_frames >= 50, "{sent:?}"); + assert!(sent.audio_sources.iter().all(|s| s.error.is_none()), "{sent:?}"); engine.send(Command::StopStream { session: 1 }); wait_for(&mut events, "stream ended", |e| match e { diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index fb44818..2d3fde2 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -41,6 +41,8 @@ libloading = { version = "0.8.9", optional = true } libvpx-native-sys = { version = "5.0.17", optional = true } openh264 = { version = "0.9.8", default-features = false, features = ["libloading"], optional = true } reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true } +# Lock-free single-producer rings from capture threads to the stream mixer. +rtrb = "0.4.0" sha2 = { version = "0.10.9", optional = true } str0m = { version = "0.23.1", default-features = false, optional = true } thiserror = "2.0.21" @@ -63,15 +65,23 @@ ndk = { version = "0.9.0", default-features = false, features = ["media", "api-l [target.'cfg(windows)'.dependencies] wasapi = "0.24.0" +# Process names for the list of applications with audio sessions. +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Threading"] } windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +# Logs of integration tests (`RUST_LOG`). +tracing-subscriber = { version = "0.3", features = ["env-filter"] } tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] } [[bench]] name = "convert" harness = false +[[bench]] +name = "mix" +harness = false + [lints] workspace = true diff --git a/crates/voelin-media/benches/mix.rs b/crates/voelin-media/benches/mix.rs new file mode 100644 index 0000000..5328670 --- /dev/null +++ b/crates/voelin-media/benches/mix.rs @@ -0,0 +1,83 @@ +//! The stream mixer: `cargo bench -p voelin-media --bench mix`. +//! +//! One iteration pushes 20 ms into every source and mixes one 20 ms block +//! (960 frames), as the streamer does 50 times a second. +//! +//! - `mix/48k/`: n stereo sources at 48 kHz (copied through) +//! - `mix/44k1/`: n stereo sources at 44.1 kHz (cubic resampling) +//! - `mix/limited/8`: eight loud sources, the limiter working on every frame + +use std::hint::black_box; +use std::time::Duration; + +use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use voelin_media::mix::{MixerConfig, SourceInput, StreamMixer}; + +const BLOCK: usize = 960; + +/// A mixer with `sources` sources at `rate`, each fed a 20 ms stereo block +/// per iteration. +struct Setup { + mixer: StreamMixer, + inputs: Vec, + /// 20 ms of input at the sources' rate. + block: Vec, + out: Vec, +} + +impl Setup { + fn new(sources: usize, rate: u32, amplitude: f32) -> Self { + let mixer = StreamMixer::new(MixerConfig::default()); + let handle = mixer.handle(); + let inputs = (0..sources).map(|i| handle.add_source(format!("s{i}")).input(rate)).collect(); + let frames = rate as usize / 50; + let block = (0..frames) + .flat_map(|i| { + let s = amplitude * (i as f32 * 0.05).sin(); + [s, -s] + }) + .collect(); + let mut setup = Self { mixer, inputs, block, out: vec![0.0; BLOCK * 2] }; + // Every source past its latency and settled. + for _ in 0..100 { + setup.step(); + } + setup + } + + fn step(&mut self) { + for input in &mut self.inputs { + input.push(&self.block, 2); + } + self.mixer.mix(&mut self.out); + } +} + +fn mixing(c: &mut Criterion) { + let mut group = c.benchmark_group("mix"); + group.sample_size(50).measurement_time(Duration::from_secs(3)); + for (name, rate) in [("48k", 48_000), ("44k1", 44_100)] { + for sources in [1, 4, 16, 64] { + let mut setup = Setup::new(sources, rate, 0.5 / sources as f32); + group.throughput(Throughput::Elements((BLOCK * sources) as u64)); + group.bench_function(BenchmarkId::new(name, sources), |b| { + b.iter(|| { + setup.step(); + black_box(&setup.out); + }); + }); + } + } + let mut setup = Setup::new(8, 48_000, 0.6); + group.throughput(Throughput::Elements((BLOCK * 8) as u64)); + group.bench_function(BenchmarkId::new("limited", 8), |b| { + b.iter(|| { + setup.step(); + black_box(&setup.out); + }); + }); + group.finish(); +} + +criterion_group!(benches, mixing); +criterion_main!(benches); diff --git a/crates/voelin-media/src/capture/external.rs b/crates/voelin-media/src/capture/external.rs index be60731..2d72691 100644 --- a/crates/voelin-media/src/capture/external.rs +++ b/crates/voelin-media/src/capture/external.rs @@ -13,12 +13,14 @@ use std::sync::{Arc, Mutex, PoisonError}; -use crate::Result; +use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, forward_audio}; use crate::capture::{ AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, }; -use crate::frame::{AudioBuffer, VideoFrame}; +use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; +use crate::mix::{SourceHandle, SourceInput}; use crate::queue::{FrameReceiver, FrameSender, frame_channel}; +use crate::{Error, Result}; /// Platform code that captures the screen. pub trait ScreenProvider: Send + Sync { @@ -50,6 +52,63 @@ pub trait AudioProvider: Send + Sync { fn start(&self, buffers: FrameSender) -> Result<()>; fn stop(&self); + + /// Start capturing the playback `filter` selects straight into a mixer + /// input; several captures may run at once. Returns an id for + /// [`stop_input`](Self::stop_input). The default supports none (see + /// [`start_playback`] for the fallback). + fn start_input(&self, filter: &PlaybackFilter, input: SourceInput) -> Result { + let _ = (filter, input); + Err(Error::CaptureUnavailable { + backend: self.name(), + reason: "capturing single applications is not supported".into(), + }) + } + + fn stop_input(&self, id: u64) { + let _ = id; + } + + /// Applications whose playback can be captured (Android: the launchable + /// apps, since it cannot tell which play). + fn apps(&self) -> Vec { + Vec::new() + } +} + +/// A capture of [`AudioProvider::start_input`]; stops it when dropped. +struct ProviderCapture { + provider: Arc, + id: u64, +} + +impl SourceCapture for ProviderCapture { + fn backend(&self) -> &'static str { + self.provider.name() + } +} + +impl Drop for ProviderCapture { + fn drop(&mut self) { + self.provider.stop_input(self.id); + } +} + +/// Capture through `provider` into `source`: [`AudioProvider::start_input`], +/// or for everything but our own playback, providers without it run their +/// plain [`AudioProvider::start`] into the source. +pub fn start_playback( + provider: Arc, + filter: &PlaybackFilter, + source: &SourceHandle, +) -> Result> { + match provider.start_input(filter, source.input(AUDIO_SAMPLE_RATE)) { + Ok(id) => Ok(Box::new(ProviderCapture { provider, id })), + Err(_) if *filter == PlaybackFilter::AllButSelf => { + forward_audio(Box::new(ExternalAudioCapture::new(provider)), source) + } + Err(e) => Err(e), + } } type Slot = Mutex>>; @@ -174,7 +233,6 @@ mod tests { use std::time::Duration; use super::*; - use crate::Error; /// Sends one frame per start, or refuses. #[derive(Default)] diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 4bfaf85..f37ee4d 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -33,6 +33,9 @@ pub mod external; #[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod pipewire_audio; #[cfg(all(target_os = "linux", feature = "pipewire"))] +pub mod pipewire_links; +pub mod playback; +#[cfg(all(target_os = "linux", feature = "pipewire"))] pub mod portal; #[cfg(all(target_os = "linux", feature = "pipewire"))] mod pw; diff --git a/crates/voelin-media/src/capture/pipewire_links.rs b/crates/voelin-media/src/capture/pipewire_links.rs new file mode 100644 index 0000000..bd1ecc8 --- /dev/null +++ b/crates/voelin-media/src/capture/pipewire_links.rs @@ -0,0 +1,992 @@ +//! Per-application audio capture on PipeWire, by linking playback streams +//! into capture streams of ours. +//! +//! A [`LinkManager`] keeps one PipeWire connection on a thread of its own +//! and watches the registry: clients (process ids and executables), nodes +//! of class `Stream/Output/Audio` (every application's playback stream, +//! with `application.name`, `media.name`, icon name and state) and their +//! ports. +//! +//! Each capture ([`LinkManager::capture`]) is a PipeWire capture stream +//! with `node.autoconnect = false` (the session manager does not link it), +//! 48 kHz stereo `f32` (`FL`, `FR`), whose process callback pushes into a +//! mixer input. The manager links, through the `link-factory`, the output +//! ports of every playback stream the capture's [`PlaybackFilter`] selects +//! to the capture's input ports (mono and centre channels into both, +//! surround channels to their side, LFE left out), and keeps the links in +//! step as streams come and go: a tab that starts playing is linked within +//! a round trip, a stream that ends takes its links with it, and a +//! restarted application is matched again by name. PipeWire sums all links +//! into an input port, so one capture stream carries any number of +//! applications. The links belong to our connection and vanish with it. +//! +//! This rather than one capture stream per application with +//! `target.object`: whether a capture may follow a playback stream is the +//! session manager's policy, which differs between WirePlumber versions, +//! while links we make ourselves need only a session manager that +//! configures stream ports (WirePlumber and media-session do, whether or +//! not a stream is linked). No extra sink or loopback module is needed, the +//! default sink and all volumes stay as they are, and our own voice +//! playback (cpal → ALSA → pipewire-alsa, a client in this process) never +//! reaches the stream. +//! +//! Our own process tree is recognised by process id: a node's +//! `application.process.id`, else its client's `application.process.id`, +//! else the client's `pipewire.sec.pid`, compared with our pid and walked up +//! the `/proc//stat` parent chain (and, without any pid, by our +//! executable's name). In a sandbox with a pid namespace of its own the +//! daemon sees other pids than we do, so the manager's own connection +//! carries a marker property: native clients with that connection's +//! `pipewire.sec.pid` are ours too. A playback stream is linked only once +//! its node and client details have arrived, so our playback is never +//! linked, not even briefly. The playing sides of loopbacks and filters +//! (`node.link-group`) are never linked: what they replay is captured at +//! the applications that played it. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::Path; +use std::rc::{Rc, Weak as RcWeak}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc as std_mpsc; +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::thread::JoinHandle; +use std::time::Duration; + +use pipewire as pw; +use pw::spa::param::audio::{AudioFormat, AudioInfoRaw}; +use pw::spa::pod::{Object, Value}; +use pw::spa::utils::SpaTypes; +use pw::spa::utils::dict::DictRef; +use pw::types::ObjectType; +use tokio::sync::watch; +use tracing::{debug, warn}; + +use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, parent_pid}; +use crate::capture::pw::{pod, serialize}; +use crate::frame::AUDIO_SAMPLE_RATE; +use crate::mix::{SourceHandle, SourceInput}; +use crate::{Error, Result}; + +const BACKEND: &str = "pipewire"; +/// Prefix of our capture nodes' names. +pub const NODE_PREFIX: &str = "voelin-stream-audio"; +/// Samples converted per push (a PipeWire quantum is at most 8192 frames). +const SCRATCH: usize = 8192 * 2; +const PLAYBACK_CLASS: &str = "Stream/Output/Audio"; +/// Client property that marks the manager's own connection, whose +/// `pipewire.sec.pid` is this process as the daemon sees it (the host pid, +/// also inside a sandbox with a pid namespace). +const MARKER: &str = "voelin.link-manager"; + +/// `EPIPE`, what PipeWire reports when the daemon goes away. +fn libc_epipe() -> i32 { + rustix::io::Errno::PIPE.raw_os_error() +} + +fn unavailable(reason: impl Into) -> Error { + Error::CaptureUnavailable { backend: BACKEND, reason: reason.into() } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +enum Command { + Add { + id: u64, + filter: PlaybackFilter, + name: String, + input: SourceInput, + reply: std_mpsc::Sender>, + }, + Remove(u64), + Quit, +} + +/// Registry watcher and link maker on its own PipeWire connection (see the +/// module docs). One per process is enough: [`LinkManager::shared`]. +pub struct LinkManager { + commands: Mutex>, + apps: watch::Receiver>, + alive: Arc, + next_id: AtomicU64, + thread: Option>, +} + +static SHARED: Mutex>> = Mutex::new(None); + +impl LinkManager { + /// The process's manager, connected to the user's PipeWire daemon; a new + /// one when none is alive (or the last one lost its connection). + pub fn shared() -> Result> { + let mut slot = lock(&SHARED); + if let Some(manager) = slot.as_ref().and_then(Weak::upgrade) + && manager.is_alive() + { + return Ok(manager); + } + let manager = Arc::new(Self::connect(None)?); + *slot = Some(Arc::downgrade(&manager)); + Ok(manager) + } + + /// A manager of its own, connected to the daemon listening on `socket` + /// (the path of its `pipewire-0` socket), or the user's daemon. + pub fn connect(socket: Option<&Path>) -> Result { + let (commands, rx) = pw::channel::channel::(); + let (apps_tx, apps) = watch::channel(Vec::new()); + let alive = Arc::new(AtomicBool::new(true)); + let (init_tx, init_rx) = std_mpsc::channel(); + let remote = socket.map(|s| s.to_string_lossy().into_owned()); + let flag = alive.clone(); + let thread = std::thread::Builder::new() + .name("voelin-pipewire-links".into()) + .spawn(move || run(remote, rx, apps_tx, flag, init_tx))?; + let mut manager = Self { + commands: Mutex::new(commands), + apps, + alive, + next_id: AtomicU64::new(1), + thread: Some(thread), + }; + match init_rx.recv() { + Ok(Ok(())) => Ok(manager), + Ok(Err(e)) => { + manager.stop(); + Err(unavailable(e)) + } + Err(_) => { + manager.stop(); + Err(unavailable("the PipeWire thread ended during setup")) + } + } + } + + /// Whether the connection is still up. + pub fn is_alive(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } + + /// Applications with playback streams (not ours), updated live. + pub fn apps(&self) -> watch::Receiver> { + self.apps.clone() + } + + /// Capture the playback `filter` selects into a new input of `source`, + /// until the returned capture is dropped. + pub fn capture( + self: &Arc, + filter: &PlaybackFilter, + source: &SourceHandle, + ) -> Result> { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let input = source.input(AUDIO_SAMPLE_RATE); + let (reply, answer) = std_mpsc::channel(); + let name = source.name().to_owned(); + self.send(Command::Add { id, filter: filter.clone(), name, input, reply })?; + match answer.recv_timeout(Duration::from_secs(5)) { + Ok(Ok(())) => Ok(Box::new(LinkCapture { manager: self.clone(), id })), + Ok(Err(e)) => Err(unavailable(e)), + Err(_) => Err(unavailable("the PipeWire thread did not answer")), + } + } + + fn send(&self, command: Command) -> Result<()> { + lock(&self.commands) + .send(command) + .map_err(|_| unavailable("the PipeWire connection is gone")) + } + + fn stop(&mut self) { + let _ = self.send(Command::Quit); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for LinkManager { + fn drop(&mut self) { + self.stop(); + } +} + +/// One capture of a [`LinkManager`]; removes its stream and links on drop. +struct LinkCapture { + manager: Arc, + id: u64, +} + +impl SourceCapture for LinkCapture { + fn backend(&self) -> &'static str { + BACKEND + } +} + +impl Drop for LinkCapture { + fn drop(&mut self) { + let _ = self.manager.send(Command::Remove(self.id)); + } +} + +/// The manager's thread: connect, watch, link, until told to quit or the +/// daemon goes away. +fn run( + remote: Option, + rx: pw::channel::Receiver, + apps: watch::Sender>, + alive: Arc, + init: std_mpsc::Sender>, +) { + pw::init(); + static MARKERS: AtomicU64 = AtomicU64::new(1); + let marker = format!("{}-{}", std::process::id(), MARKERS.fetch_add(1, Ordering::Relaxed)); + let setup = (|| { + let mainloop = + pw::main_loop::MainLoopRc::new(None).map_err(|e| format!("PipeWire main loop: {e}"))?; + let context = pw::context::ContextRc::new(&mainloop, None) + .map_err(|e| format!("PipeWire context: {e}"))?; + let mut props = pw::properties::PropertiesBox::new(); + if let Some(remote) = remote { + props.insert(*pw::keys::REMOTE_NAME, remote); + } + props.insert(MARKER, marker.to_string()); + let core = context + .connect_rc(Some(props)) + .map_err(|e| format!("cannot connect to PipeWire: {e}"))?; + let registry = core.get_registry_rc().map_err(|e| format!("PipeWire registry: {e}"))?; + Ok::<_, String>((mainloop, context, core, registry)) + })(); + let (mainloop, _context, core, registry) = match setup { + Ok(parts) => parts, + Err(e) => { + alive.store(false, Ordering::Relaxed); + let _ = init.send(Err(e)); + return; + } + }; + let model = Rc::new(RefCell::new(Model::new(core.clone(), registry.clone(), apps, marker))); + let _registry = registry + .add_listener_local() + .global({ + let model = Rc::downgrade(&model); + move |global| { + if let Some(model) = model.upgrade() { + Model::global(&model, global); + } + } + }) + .global_remove({ + let model = Rc::downgrade(&model); + move |id| { + if let Some(model) = model.upgrade() { + model.borrow_mut().remove(id); + } + } + }) + .register(); + let _core = core + .add_listener_local() + .error({ + let mainloop = mainloop.downgrade(); + let alive = alive.clone(); + move |id, _seq, res, message| { + // Other errors (a link refused, a stale id) are for one + // object; losing the socket ends everything. + if id != pw::core::PW_ID_CORE || res != -libc_epipe() { + debug!(id, res, "PipeWire error: {message}"); + } else { + warn!("PipeWire connection lost: {message}"); + alive.store(false, Ordering::Relaxed); + if let Some(mainloop) = mainloop.upgrade() { + mainloop.quit(); + } + } + } + }) + .register(); + let _commands = rx.attach(mainloop.loop_(), { + let model = Rc::downgrade(&model); + let mainloop = mainloop.downgrade(); + move |command| match command { + Command::Quit => { + if let Some(mainloop) = mainloop.upgrade() { + mainloop.quit(); + } + } + Command::Add { id, filter, name, input, reply } => { + let result = match model.upgrade() { + Some(model) => model.borrow_mut().add_capture(id, filter, &name, input), + None => Err("shutting down".into()), + }; + let _ = reply.send(result); + } + Command::Remove(id) => { + if let Some(model) = model.upgrade() { + model.borrow_mut().remove_capture(id); + } + } + } + }); + let _ = init.send(Ok(())); + mainloop.run(); + alive.store(false, Ordering::Relaxed); + // Links, streams and proxies go before the connection. + model.borrow_mut().clear(); +} + +/// Where a playback port goes in our stereo input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Side { + Left, + Right, + Both, + Skip, +} + +/// The side of a channel position (`audio.channel`): anything with an L is +/// left, a trailing R (or R before C, W, H) right, centres and mono both, +/// LFE nowhere; `AUX` by parity. +fn side(channel: Option<&str>) -> Side { + let Some(channel) = channel.map(str::trim) else { return Side::Both }; + let upper = channel.to_ascii_uppercase(); + let c = upper.as_str(); + if c.starts_with("LFE") { + return Side::Skip; + } + if matches!(c, "MONO" | "FC" | "RC" | "TC" | "TFC" | "TRC" | "BC" | "BLC" | "BRC" | "") { + return Side::Both; + } + if let Some(n) = c.strip_prefix("AUX").and_then(|n| n.parse::().ok()) { + return if n % 2 == 0 { Side::Left } else { Side::Right }; + } + if c.contains('L') { + return Side::Left; + } + let bytes = c.as_bytes(); + let last = bytes[bytes.len() - 1]; + let before = bytes.len().checked_sub(2).map(|i| bytes[i]); + if last == b'R' || (before == Some(b'R') && matches!(last, b'C' | b'W' | b'H')) { + return Side::Right; + } + Side::Both +} + +/// A process id from a property. +fn pid(props: &DictRef, key: &str) -> Option { + props.get(key).and_then(|v| v.trim().parse().ok()).filter(|&p| p > 0) +} + +fn text(props: &DictRef, key: &str) -> Option { + props.get(key).map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned) +} + +struct Client { + /// Kernel-checked pid of the connection (`pipewire.sec.pid`); for + /// pipewire-pulse streams that is pipewire-pulse, not the application. + sec_pid: Option, + pid: Option, + binary: Option, + name: Option, + /// Its details arrived (or never will). + known: bool, + _proxy: Option<(pw::client::ClientListener, pw::client::Client)>, +} + +struct Node { + node_name: String, + client: Option, + app_name: Option, + pid: Option, + binary: Option, + icon: Option, + media: Option, + running: bool, + /// The playing side of a loopback or filter (`node.link-group`): it + /// replays what applications played into a virtual sink, which is + /// captured at those applications already. + internal: bool, + /// Its info arrived (or never will). + known: bool, + _proxy: Option<(pw::node::NodeListener, pw::node::Node)>, +} + +struct Port { + node: u32, + output: bool, + monitor: bool, + channel: Option, +} + +/// One capture stream. +struct Capture { + id: u64, + filter: PlaybackFilter, + node_name: String, + /// Its node, once in the registry. + node: Option, + _listener: pw::stream::StreamListener, + _stream: pw::stream::StreamRc, +} + +/// What a capture stream's callbacks own. +struct CaptureData { + input: SourceInput, + channels: u16, + scratch: Vec, +} + +impl CaptureData { + fn process(&mut self, stream: &pw::stream::Stream) { + let Some(mut buffer) = stream.dequeue_buffer() else { return }; + let Some(data) = buffer.datas_mut().first_mut() else { return }; + let chunk = data.chunk(); + let (offset, size) = (chunk.offset() as usize, chunk.size() as usize); + let Some(bytes) = data.data() else { return }; + let Some(bytes) = bytes.get(offset..offset + size) else { return }; + let channels = usize::from(self.channels.max(1)); + let part = SCRATCH / channels * channels * 4; + for part in bytes.chunks(part) { + self.scratch.clear(); + self.scratch + .extend(part.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))); + self.input.push(&self.scratch, self.channels); + } + } +} + +/// The registry as far as it matters here, our captures and our links. +struct Model { + core: pw::core::CoreRc, + registry: pw::registry::RegistryRc, + own_pid: u32, + /// Our pid as the daemon sees it (see [`MARKER`]). + own_sec_pid: Option, + marker: String, + own_binary: Option, + clients: HashMap, + nodes: HashMap, + ports: HashMap, + captures: Vec, + /// Links we made, by (output port, input port). + links: HashMap<(u32, u32), pw::link::Link>, + /// Parent chains of process ids, cached until a client goes. + chains: RefCell>>, + apps: watch::Sender>, + weak: RcWeak>, +} + +impl Model { + fn new( + core: pw::core::CoreRc, + registry: pw::registry::RegistryRc, + apps: watch::Sender>, + marker: String, + ) -> Self { + let own_binary = std::env::current_exe() + .ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())); + Self { + core, + registry, + own_pid: std::process::id(), + own_sec_pid: None, + marker, + own_binary, + clients: HashMap::new(), + nodes: HashMap::new(), + ports: HashMap::new(), + captures: Vec::new(), + links: HashMap::new(), + chains: RefCell::new(HashMap::new()), + apps, + weak: RcWeak::new(), + } + } + + fn global(model: &Rc>, global: &pw::registry::GlobalObject<&DictRef>) { + let Some(props) = global.props else { return }; + let mut this = model.borrow_mut(); + if this.weak.upgrade().is_none() { + this.weak = Rc::downgrade(model); + } + let id = global.id; + match global.type_ { + ObjectType::Client => { + if props.get(MARKER) == Some(this.marker.as_str()) { + this.own_sec_pid = pid(props, "pipewire.sec.pid"); + } + let proxy = + this.registry.bind::(global).ok().map(|client| { + let model = Rc::downgrade(model); + let listener = client + .add_listener_local() + .info(move |info| { + if let Some(model) = model.upgrade() { + model.borrow_mut().client_info(id, info.props()); + } + }) + .register(); + (listener, client) + }); + let client = Client { + sec_pid: pid(props, "pipewire.sec.pid"), + pid: pid(props, "application.process.id"), + binary: text(props, "application.process.binary"), + name: text(props, "application.name"), + known: proxy.is_none(), + _proxy: proxy, + }; + this.clients.insert(id, client); + } + ObjectType::Node => { + let node_name = props.get("node.name").unwrap_or_default().to_owned(); + if node_name.starts_with(NODE_PREFIX) { + let mut ours = false; + for capture in this.captures.iter_mut().filter(|c| c.node_name == node_name) { + capture.node = Some(id); + ours = true; + } + if ours { + debug!(node = id, %node_name, "capture node ready"); + this.reconcile(); + } + return; + } + if props.get("media.class") != Some(PLAYBACK_CLASS) { + return; + } + let proxy = this.registry.bind::(global).ok().map(|node| { + let model = Rc::downgrade(model); + let listener = node + .add_listener_local() + .info(move |info| { + if let Some(model) = model.upgrade() { + let running = matches!(info.state(), pw::node::NodeState::Running); + model.borrow_mut().node_info(id, running, info.props()); + } + }) + .register(); + (listener, node) + }); + let node = Node { + node_name, + client: pid(props, "client.id"), + app_name: text(props, "application.name"), + pid: pid(props, "application.process.id"), + binary: text(props, "application.process.binary"), + icon: None, + media: text(props, "media.name"), + running: false, + internal: props.get("node.link-group").is_some(), + known: proxy.is_none(), + _proxy: proxy, + }; + this.nodes.insert(id, node); + this.changed(); + } + ObjectType::Port => { + let Some(node) = pid(props, "node.id") else { return }; + let port = Port { + node, + output: props.get("port.direction") == Some("out"), + monitor: props.get("port.monitor") == Some("true"), + channel: text(props, "audio.channel"), + }; + this.ports.insert(id, port); + let relevant = this.nodes.contains_key(&node) + || this.captures.iter().any(|c| c.node == Some(node)); + if relevant { + this.reconcile(); + } + } + _ => {} + } + } + + fn client_info(&mut self, id: u32, props: Option<&DictRef>) { + let Some(client) = self.clients.get_mut(&id) else { return }; + if let Some(props) = props { + client.pid = pid(props, "application.process.id").or(client.pid); + client.sec_pid = pid(props, "pipewire.sec.pid").or(client.sec_pid); + client.binary = text(props, "application.process.binary").or(client.binary.take()); + client.name = text(props, "application.name").or(client.name.take()); + } + client.known = true; + self.changed(); + } + + fn node_info(&mut self, id: u32, running: bool, props: Option<&DictRef>) { + let Some(node) = self.nodes.get_mut(&id) else { return }; + node.running = running; + if let Some(props) = props { + node.app_name = text(props, "application.name").or(node.app_name.take()); + node.pid = pid(props, "application.process.id").or(node.pid); + node.binary = text(props, "application.process.binary").or(node.binary.take()); + node.icon = text(props, "application.icon-name") + .or_else(|| text(props, "application.icon_name")) + .or_else(|| text(props, "media.icon-name")) + .or(node.icon.take()); + node.media = text(props, "media.name").or(node.media.take()); + node.client = pid(props, "client.id").or(node.client); + node.internal |= props.get("node.link-group").is_some(); + } + node.known = true; + self.changed(); + } + + fn remove(&mut self, id: u32) { + if self.clients.remove(&id).is_some() { + // Its process may be gone and its id reused. + self.chains.borrow_mut().clear(); + } + let node = self.nodes.remove(&id).is_some(); + let port = self.ports.remove(&id).is_some(); + let mut capture = false; + for c in self.captures.iter_mut().filter(|c| c.node == Some(id)) { + c.node = None; + capture = true; + } + if port { + self.links.retain(|(out, input), _| *out != id && *input != id); + } + if node || capture { + self.changed(); + } else if port { + self.reconcile(); + } + } + + fn add_capture( + &mut self, + id: u64, + filter: PlaybackFilter, + name: &str, + input: SourceInput, + ) -> std::result::Result<(), String> { + let node_name = format!("{NODE_PREFIX}-{}-{id}", self.own_pid); + let description = format!("Voelin stream audio: {}", name.replace('\0', "")); + let mut props = pw::properties::PropertiesBox::new(); + props.insert(*pw::keys::MEDIA_TYPE, "Audio"); + props.insert(*pw::keys::MEDIA_CATEGORY, "Capture"); + props.insert(*pw::keys::MEDIA_ROLE, "Music"); + props.insert(*pw::keys::NODE_NAME, node_name.as_str()); + props.insert(*pw::keys::NODE_DESCRIPTION, description); + props.insert("node.autoconnect", "false"); + let stream = pw::stream::StreamRc::new(self.core.clone(), &node_name, props) + .map_err(|e| format!("PipeWire stream: {e}"))?; + let data = CaptureData { input, channels: 2, scratch: Vec::with_capacity(SCRATCH) }; + let listener = stream + .add_local_listener_with_user_data(data) + .state_changed(|_, _, _, new| { + if let pw::stream::StreamState::Error(e) = &new { + warn!("application audio stream failed: {e}"); + } + }) + .param_changed(|_, data, id, param| { + let Some(param) = param else { return }; + if id != pw::spa::param::ParamType::Format.as_raw() { + return; + } + let mut info = AudioInfoRaw::new(); + if info.parse(param).is_ok() && info.channels() > 0 { + data.channels = info.channels().min(u32::from(u16::MAX)) as u16; + } + }) + .process(|stream, data| data.process(stream)) + .register() + .map_err(|e| format!("PipeWire listener: {e}"))?; + let mut info = AudioInfoRaw::new(); + info.set_format(AudioFormat::F32LE); + info.set_rate(AUDIO_SAMPLE_RATE); + info.set_channels(2); + let mut position = [0; pw::spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; + position[0] = pw::spa::sys::SPA_AUDIO_CHANNEL_FL; + position[1] = pw::spa::sys::SPA_AUDIO_CHANNEL_FR; + info.set_position(position); + let format = serialize(Value::Object(Object { + type_: SpaTypes::ObjectParamFormat.as_raw(), + id: pw::spa::param::ParamType::EnumFormat.as_raw(), + properties: info.into(), + }))?; + stream + .connect( + pw::spa::utils::Direction::Input, + None, + pw::stream::StreamFlags::MAP_BUFFERS, + &mut [pod(&format)?], + ) + .map_err(|e| format!("cannot connect the application audio stream: {e}"))?; + debug!(id, ?filter, %node_name, "application audio capture"); + self.captures.push(Capture { + id, + filter, + node_name, + node: None, + _listener: listener, + _stream: stream, + }); + Ok(()) + } + + fn remove_capture(&mut self, id: u64) { + self.captures.retain(|c| c.id != id); + self.reconcile(); + } + + fn clear(&mut self) { + self.links.clear(); + self.captures.clear(); + self.nodes.clear(); + self.clients.clear(); + self.ports.clear(); + } + + /// The parent chain of `pid`, itself first. + fn chain(&self, pid: u32) -> Vec { + if let Some(chain) = self.chains.borrow().get(&pid) { + return chain.clone(); + } + let mut chain = vec![pid]; + let mut current = pid; + while chain.len() < 64 { + match parent_pid(current) { + Some(parent) if parent > 0 && parent != current => { + chain.push(parent); + current = parent; + } + _ => break, + } + } + self.chains.borrow_mut().insert(pid, chain.clone()); + chain + } + + /// The process of a node: its own `application.process.id`, else its + /// client's, else the client's socket credentials. + fn node_pid(&self, node: &Node) -> Option { + let client = node.client.and_then(|c| self.clients.get(&c)); + node.pid.or(client.and_then(|c| c.pid)).or(client.and_then(|c| c.sec_pid)) + } + + /// The node's and its client's details are in. + fn resolved(&self, node: &Node) -> bool { + node.known && node.client.and_then(|c| self.clients.get(&c)).is_none_or(|c| c.known) + } + + /// Played by this process or one of its children. + fn is_ours(&self, node: &Node) -> bool { + let client = node.client.and_then(|c| self.clients.get(&c)); + // A native client of ours, as the daemon saw its socket. + if node.pid.is_none() + && self.own_sec_pid.is_some() + && client.and_then(|c| c.sec_pid) == self.own_sec_pid + { + return true; + } + match self.node_pid(node) { + Some(pid) => self.chain(pid).contains(&self.own_pid), + None => { + let binary = node.binary.as_deref().or(client.and_then(|c| c.binary.as_deref())); + binary.is_some() && binary == self.own_binary.as_deref() + } + } + } + + fn matches(&self, filter: &PlaybackFilter, node: &Node) -> bool { + if node.internal || self.is_ours(node) { + return false; + } + match filter { + PlaybackFilter::AllButSelf => true, + PlaybackFilter::App(app @ crate::capture::playback::AppMatch::Name(_)) => { + let client = node.client.and_then(|c| self.clients.get(&c)); + let names = [ + node.app_name.as_deref(), + node.binary.as_deref(), + client.and_then(|c| c.name.as_deref()), + client.and_then(|c| c.binary.as_deref()), + Some(node.node_name.as_str()), + ]; + app.matches_name(names.into_iter().flatten()) + } + PlaybackFilter::App(crate::capture::playback::AppMatch::Pid(wanted)) => { + let client = node.client.and_then(|c| self.clients.get(&c)); + [node.pid, client.and_then(|c| c.pid), client.and_then(|c| c.sec_pid)] + .into_iter() + .flatten() + .any(|pid| self.chain(pid).contains(wanted)) + } + } + } + + /// Nodes or clients changed: links and the app list follow. + fn changed(&mut self) { + self.reconcile(); + self.publish(); + } + + /// Make the links match what every capture selects now. + fn reconcile(&mut self) { + let mut wanted: HashMap<(u32, u32), (u32, u32)> = HashMap::new(); + for capture in &self.captures { + let Some(ours) = capture.node else { continue }; + let mut inputs = (None, None); + for (&id, port) in &self.ports { + if port.node != ours || port.output || port.monitor { + continue; + } + match side(port.channel.as_deref()) { + Side::Left => inputs.0 = Some(id), + Side::Right => inputs.1 = Some(id), + _ => {} + } + } + if inputs == (None, None) { + // Not configured by the session manager yet. + continue; + } + for (&node_id, node) in &self.nodes { + if !self.resolved(node) || !self.matches(&capture.filter, node) { + continue; + } + let outputs: Vec<(u32, &Port)> = self + .ports + .iter() + .filter(|(_, p)| p.node == node_id && p.output && !p.monitor) + .map(|(&id, p)| (id, p)) + .collect(); + let single = outputs.len() == 1; + for (port_id, port) in outputs { + let side = if single { Side::Both } else { side(port.channel.as_deref()) }; + let targets = match side { + Side::Left => [inputs.0, None], + Side::Right => [inputs.1, None], + Side::Both => [inputs.0, inputs.1], + Side::Skip => [None, None], + }; + for input in targets.into_iter().flatten() { + wanted.insert((port_id, input), (node_id, ours)); + } + } + } + } + self.links.retain(|pair, _| wanted.contains_key(pair)); + for (pair, nodes) in wanted { + if self.links.contains_key(&pair) { + continue; + } + let mut props = pw::properties::PropertiesBox::new(); + props.insert("link.output.node", nodes.0.to_string()); + props.insert("link.output.port", pair.0.to_string()); + props.insert("link.input.node", nodes.1.to_string()); + props.insert("link.input.port", pair.1.to_string()); + props.insert("object.linger", "false"); + match self.core.create_object::("link-factory", &props) { + Ok(link) => { + debug!(output = pair.0, input = pair.1, "linked"); + self.links.insert(pair, link); + } + Err(e) => warn!("cannot link port {} to {}: {e}", pair.0, pair.1), + } + } + } + + /// Send the list of playing applications if it changed. + fn publish(&self) { + let mut apps: Vec = Vec::new(); + for node in self.nodes.values() { + if !self.resolved(node) || node.internal || self.is_ours(node) { + continue; + } + let client = node.client.and_then(|c| self.clients.get(&c)); + let pid = self.node_pid(node); + let binary = node.binary.clone().or_else(|| client.and_then(|c| c.binary.clone())); + let name = node + .app_name + .clone() + .or_else(|| client.and_then(|c| c.name.clone())) + .or_else(|| binary.clone()) + .unwrap_or_else(|| node.node_name.clone()); + let existing = apps.iter_mut().find(|a| match pid { + Some(pid) => a.pid == Some(pid), + None => a.pid.is_none() && a.name == name, + }); + match existing { + Some(app) => { + app.streams += 1; + app.playing |= node.running; + if app.media.is_none() || (node.running && !app.playing) { + app.media = node.media.clone(); + } + if app.icon.is_none() { + app.icon = node.icon.clone(); + } + } + None => apps.push(AudioApp { + name, + pid, + binary, + icon: node.icon.clone(), + media: node.media.clone(), + streams: 1, + playing: node.running, + }), + } + } + apps.sort_by(|a, b| { + a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.pid.cmp(&b.pid)) + }); + self.apps.send_if_modified(|current| { + if *current == apps { + false + } else { + *current = apps; + true + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_sides() { + for (channel, expected) in [ + ("FL", Side::Left), + ("FR", Side::Right), + ("MONO", Side::Both), + ("FC", Side::Both), + ("LFE", Side::Skip), + ("RL", Side::Left), + ("RR", Side::Right), + ("SL", Side::Left), + ("SR", Side::Right), + ("FLC", Side::Left), + ("FRC", Side::Right), + ("RC", Side::Both), + ("TFL", Side::Left), + ("TRR", Side::Right), + ("FRW", Side::Right), + ("AUX0", Side::Left), + ("AUX1", Side::Right), + ("UNK", Side::Both), + ] { + assert_eq!(side(Some(channel)), expected, "{channel}"); + } + assert_eq!(side(None), Side::Both); + } + + /// Without a daemon, connecting fails with a clear error instead of + /// hanging. Skipped where a daemon socket exists. + #[test] + fn unavailable_without_daemon() { + let err = LinkManager::connect(Some(Path::new("/nonexistent/voelin/pipewire-0"))) + .err() + .expect("no daemon there"); + assert!(matches!(err, Error::CaptureUnavailable { backend: "pipewire", .. }), "{err}"); + } +} diff --git a/crates/voelin-media/src/capture/playback.rs b/crates/voelin-media/src/capture/playback.rs new file mode 100644 index 0000000..32be577 --- /dev/null +++ b/crates/voelin-media/src/capture/playback.rs @@ -0,0 +1,315 @@ +//! What applications play, captured into stream mixer sources: all of it +//! except our own process tree (so viewers do not hear the TeamSpeak voices +//! we play), or chosen applications only; and the list of applications +//! that play, for a picker. +//! +//! | Platform | All but ours | One application | Playing apps | +//! |---|---|---|---| +//! | Linux (PipeWire) | links from every other playback stream into a capture stream of ours ([`super::pipewire_links`]) | links from that application's streams | playback streams in the registry | +//! | Windows | WASAPI process loopback excluding our process tree | process loopback including the application's process tree | audio sessions of the default device | +//! | Android | `AudioPlaybackCapture` excluding our uid | matching the application's uid | launchable apps (Android cannot tell which play) | +//! +//! [`start_playback`] starts one; the capture feeds the given +//! [`SourceHandle`] (through one or more inputs) until it is dropped. +//! [`forward_audio`] feeds any [`AudioCapture`] into a source instead. + +use std::time::Duration; + +use tokio::sync::watch; + +use crate::capture::{AudioCapture, Worker}; +use crate::mix::SourceHandle; +use crate::{Error, Result}; + +/// Which playback a capture takes. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum PlaybackFilter { + /// Everything that plays except this process and its children (our + /// voices and watched streams). + AllButSelf, + /// One application's playback. + App(AppMatch), +} + +/// How an application is recognised. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum AppMatch { + /// A process and its children (Linux, Windows): the process that owns a + /// window, or an entry of the playing-apps list. Ends with the process. + Pid(u32), + /// By name, ignoring case: the application name or executable (Linux, + /// Windows; `.exe` optional) or the package name (Android). A restarted + /// application is found again. + Name(String), +} + +impl AppMatch { + /// Whether one of `names` is this name. + pub fn matches_name<'a>(&self, names: impl IntoIterator) -> bool { + let AppMatch::Name(wanted) = self else { return false }; + let wanted = wanted.trim(); + let wanted = wanted.strip_suffix(".exe").unwrap_or(wanted).to_lowercase(); + names.into_iter().any(|name| { + let name = name.trim(); + let name = name.strip_suffix(".exe").unwrap_or(name); + !name.is_empty() && name.to_lowercase() == wanted + }) + } +} + +impl std::fmt::Display for AppMatch { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AppMatch::Pid(pid) => write!(f, "process {pid}"), + AppMatch::Name(name) => f.write_str(name), + } + } +} + +/// An application that plays audio (or could, on Android), for a picker. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AudioApp { + /// Name to show. + pub name: String, + /// Its process (Linux, Windows); pick with [`AppMatch::Pid`]. + pub pid: Option, + /// Executable (Linux, Windows) or package name (Android): what + /// [`AppMatch::Name`] matches besides `name`. + pub binary: Option, + /// Icon name (freedesktop icon theme) or icon path, if the application + /// gave one. + pub icon: Option, + /// What it plays, if it says (e.g. a track or tab title). + pub media: Option, + /// Its playback streams now. + pub streams: u32, + /// Audio is flowing now (not paused or idle). + pub playing: bool, +} + +/// A running capture that feeds a mixer source; stops when dropped. +pub trait SourceCapture: Send { + /// Short name for logs (`"pipewire"`, `"wasapi"`, ...). + fn backend(&self) -> &'static str; +} + +/// Capture the playback `filter` selects into `source`, on this platform. +pub fn start_playback( + filter: &PlaybackFilter, + source: &SourceHandle, +) -> Result> { + if let Some(provider) = super::external::audio_provider() { + return super::external::start_playback(provider, filter, source); + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + return super::pipewire_links::LinkManager::shared()?.capture(filter, source); + #[cfg(windows)] + return super::windows::start_playback(filter, source); + #[allow(unreachable_code)] + { + let _ = (filter, source); + Err(Error::CaptureUnavailable { + backend: "audio", + reason: "no application audio capture in this build".into(), + }) + } +} + +/// Applications that play audio now, updated live. Holds the backend's +/// connection (e.g. to PipeWire) while it lives. +pub struct AudioApps { + rx: watch::Receiver>, + _keep: Box, +} + +impl AudioApps { + pub fn new(rx: watch::Receiver>, keep: Box) -> Self { + Self { rx, _keep: keep } + } + + /// The list now (marks it seen). + pub fn current(&mut self) -> Vec { + self.rx.borrow_and_update().clone() + } + + /// Whether the list changed since [`current`](Self::current). + pub fn has_changed(&self) -> bool { + self.rx.has_changed().unwrap_or(false) + } + + /// Wait for a change; `None` once the backend is gone. + pub async fn changed(&mut self) -> Option> { + self.rx.changed().await.ok()?; + Some(self.current()) + } + + /// Wait for a change from a plain thread, up to `timeout`. + pub fn wait_changed(&mut self, timeout: Duration) -> Option> { + let deadline = std::time::Instant::now() + timeout; + while std::time::Instant::now() < deadline { + if self.has_changed() { + return Some(self.current()); + } + std::thread::sleep(Duration::from_millis(20)); + } + None + } +} + +/// The applications that play audio, on this platform. +pub fn audio_apps() -> Result { + if let Some(provider) = super::external::audio_provider() { + let (tx, rx) = watch::channel(provider.apps()); + return Ok(AudioApps::new(rx, Box::new(tx))); + } + #[cfg(all(target_os = "linux", feature = "pipewire"))] + { + let manager = super::pipewire_links::LinkManager::shared()?; + return Ok(AudioApps::new(manager.apps(), Box::new(manager))); + } + #[cfg(windows)] + return super::windows::audio_apps(); + #[allow(unreachable_code)] + Err(Error::CaptureUnavailable { + backend: "audio", + reason: "no application audio listing in this build".into(), + }) +} + +/// The process that owns a captured window, where the platform tells (X11 +/// `_NET_WM_PID`, the owner of a Windows `HWND`). The ScreenCast portal +/// does not say which application a window belongs to. +pub fn window_pid(window: u64) -> Option { + #[cfg(all(target_os = "linux", feature = "x11"))] + return super::x11::window_pid(None, window); + #[cfg(windows)] + return super::windows::window_pid(window); + #[allow(unreachable_code)] + { + let _ = window; + None + } +} + +/// Whether `pid` is `ancestor` or one of its descendants (Linux: the +/// parent chain in `/proc`; elsewhere only `pid == ancestor`). +pub fn descends_from(pid: u32, ancestor: u32) -> bool { + if pid == ancestor { + return true; + } + #[cfg(target_os = "linux")] + { + let mut current = pid; + // A bound on the chain, in case of a cycle while processes are reused. + for _ in 0..64 { + match parent_pid(current) { + Some(parent) if parent == ancestor => return true, + Some(parent) if parent > 1 && parent != current => current = parent, + _ => return false, + } + } + } + false +} + +/// The parent of `pid` from `/proc//stat`. +#[cfg(target_os = "linux")] +pub fn parent_pid(pid: u32) -> Option { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + // `pid (comm) state ppid ...`; the command may contain spaces and ')'. + let rest = &stat[stat.rfind(')')? + 1..]; + rest.split_whitespace().nth(1)?.parse().ok() +} + +/// Feeds an [`AudioCapture`] (48 kHz buffers) into a mixer source from a +/// thread of its own. +struct Forwarded { + backend: &'static str, + worker: Option, + capture: Box, +} + +impl SourceCapture for Forwarded { + fn backend(&self) -> &'static str { + self.backend + } +} + +impl Drop for Forwarded { + fn drop(&mut self) { + self.worker = None; + self.capture.stop(); + } +} + +/// Start `capture` and feed its buffers into `source` until the returned +/// capture is dropped, the source is removed, or the capture ends. +pub fn forward_audio( + mut capture: Box, + source: &SourceHandle, +) -> Result> { + let mut buffers = capture.start()?; + let mut input = source.input(crate::frame::AUDIO_SAMPLE_RATE); + let worker = Worker::spawn("voelin-audio-forward", move |stop| { + while !stop.load(std::sync::atomic::Ordering::Relaxed) && !input.is_closed() { + match buffers.recv_timeout(Duration::from_millis(100)) { + Some(buffer) => { + input.push(&buffer.samples, buffer.channels); + } + None if buffers.is_closed() => break, + None => {} + } + } + })?; + Ok(Box::new(Forwarded { backend: capture.backend(), worker: Some(worker), capture })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::capture::synthetic::SineSource; + use crate::mix::{MixerConfig, StreamMixer}; + + #[test] + fn names_match_loosely() { + let firefox = AppMatch::Name("Firefox".into()); + assert!(firefox.matches_name(["firefox"])); + assert!(firefox.matches_name(["", "FIREFOX.exe"])); + assert!(!firefox.matches_name(["firefox-bin"])); + assert!(AppMatch::Name("spotify.exe".into()).matches_name(["Spotify"])); + assert!(!AppMatch::Pid(1).matches_name(["1"])); + assert_eq!(AppMatch::Pid(7).to_string(), "process 7"); + } + + #[cfg(target_os = "linux")] + #[test] + fn process_tree() { + let me = std::process::id(); + assert!(descends_from(me, me)); + let parent = parent_pid(me).unwrap(); + assert!(descends_from(me, parent)); + assert!(!descends_from(parent, me)); + let mut child = std::process::Command::new("sleep").arg("5").spawn().unwrap(); + assert!(descends_from(child.id(), me)); + assert_eq!(parent_pid(child.id()), Some(me)); + child.kill().unwrap(); + child.wait().unwrap(); + assert!(!descends_from(u32::MAX - 1, me)); + } + + #[test] + fn forwarded_capture_feeds_the_mixer() { + let mut mixer = StreamMixer::new(MixerConfig::default()); + let source = mixer.handle().add_source("tone"); + let capture = forward_audio(Box::new(SineSource::new(1000.0, 0.5)), &source).unwrap(); + assert_eq!(capture.backend(), "synthetic"); + let mut out = vec![0.0; 1920]; + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while source.level().peak < 0.4 && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + mixer.mix(&mut out); + } + assert!(source.level().peak > 0.4, "{:?}", source.level()); + drop(capture); + } +} diff --git a/crates/voelin-media/src/capture/windows.rs b/crates/voelin-media/src/capture/windows.rs index 75fcc9f..2ce053a 100644 --- a/crates/voelin-media/src/capture/windows.rs +++ b/crates/voelin-media/src/capture/windows.rs @@ -4,15 +4,17 @@ //! System audio uses process loopback in exclude mode with our own process //! id, so our own playback (TeamSpeak voices) is not captured (Windows 10 //! 2004 or later). Older systems fall back to plain loopback of the default -//! output device, which includes our playback. +//! output device, which includes our playback. Single applications use +//! process loopback in include mode on their process tree, one capture per +//! process ([`start_playback`]); [`audio_apps`] lists the processes with +//! audio sessions on the playback devices. //! //! Type-checked on Linux (`--target x86_64-pc-windows-gnu`), not run yet. -use std::collections::VecDeque; -use std::sync::atomic::Ordering; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; -use tracing::warn; +use tracing::{debug, warn}; use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler}; use windows_capture::frame::Frame; use windows_capture::graphics_capture_api::InternalCaptureControl; @@ -23,12 +25,14 @@ use windows_capture::settings::{ }; use windows_capture::window::Window; +use crate::capture::playback::{AppMatch, AudioApp, AudioApps, PlaybackFilter, SourceCapture}; use crate::capture::{ AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, - SourceId, Worker, + SourceId, Ticker, Worker, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame}; -use crate::queue::{FrameReceiver, FrameSender, frame_channel}; +use crate::mix::SourceHandle; +use crate::queue::{FrameReceiver, frame_channel}; use crate::{Error, Result}; const BACKEND: &str = "wgc"; @@ -221,34 +225,20 @@ impl WasapiLoopback { impl AudioCapture for WasapiLoopback { fn backend(&self) -> &'static str { - "wasapi" + AUDIO_BACKEND } fn start(&mut self) -> Result> { self.stop(); let (tx, rx) = frame_channel(50); - let (init_tx, init_rx) = std::sync::mpsc::channel(); - self.worker = Some(Worker::spawn("voelin-wasapi-loopback", move |stop| { - if let Err(e) = loopback(&tx, &stop, &init_tx) { - // After a successful start the receiver just sees the end. - let _ = init_tx.send(Err(e.clone())); - warn!("system audio capture ended: {e}"); - } - })?); - match init_rx.recv() { - Ok(Ok(())) => Ok(rx), - Ok(Err(reason)) => { - self.stop(); - Err(Error::CaptureUnavailable { backend: "wasapi", reason }) - } - Err(_) => { - self.stop(); - Err(Error::CaptureUnavailable { - backend: "wasapi", - reason: "capture thread ended".into(), - }) - } - } + let started = Instant::now(); + let worker = + spawn_loopback("voelin-wasapi-loopback", Loopback::AllButSelf, move |samples| { + let samples = samples.to_vec(); + tx.send(AudioBuffer { samples, channels: 2, timestamp: started.elapsed() }) + })?; + self.worker = Some(worker); + Ok(rx) } fn stop(&mut self) { @@ -256,7 +246,53 @@ impl AudioCapture for WasapiLoopback { } } -fn open_client() -> std::result::Result { +const AUDIO_BACKEND: &str = "wasapi"; +/// Bytes of one 48 kHz stereo `f32` frame. +const FRAME_BYTES: usize = 2 * 4; + +/// Which processes a loopback capture hears. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Loopback { + /// Everything except our process tree (plain device loopback where + /// process loopback is missing, which includes our playback). + AllButSelf, + /// One process and its children. + Tree(u32), +} + +/// Start a loopback capture on a thread of its own that hands each packet +/// (48 kHz stereo) to `deliver` until it returns `false` or the worker is +/// dropped. Returns once the capture runs (or failed to start). +fn spawn_loopback( + name: &str, + mode: Loopback, + mut deliver: impl FnMut(&[f32]) -> bool + Send + 'static, +) -> Result { + let (init_tx, init_rx) = std::sync::mpsc::channel(); + let mut worker = Worker::spawn(name, move |stop| { + if let Err(e) = loopback(mode, &stop, &init_tx, &mut deliver) { + // After a successful start the consumer just sees the end. + let _ = init_tx.send(Err(e.clone())); + warn!("audio capture ({mode:?}) ended: {e}"); + } + })?; + match init_rx.recv() { + Ok(Ok(())) => Ok(worker), + Ok(Err(reason)) => { + worker.stop(); + Err(Error::CaptureUnavailable { backend: AUDIO_BACKEND, reason }) + } + Err(_) => { + worker.stop(); + Err(Error::CaptureUnavailable { + backend: AUDIO_BACKEND, + reason: "capture thread ended".into(), + }) + } + } +} + +fn open_client(mode: Loopback) -> std::result::Result { let format = wasapi::WaveFormat::new( 32, 32, @@ -265,15 +301,23 @@ fn open_client() -> std::result::Result { 2, None, ); - let mode = wasapi::StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 200_000 }; - // Everything but our own process tree. - match wasapi::AudioClient::new_application_loopback_client(std::process::id(), false) { - Ok(mut client) => { - match client.initialize_client(&format, &wasapi::Direction::Capture, &mode) { - Ok(()) => return Ok(client), - Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"), - } - } + let stream = + wasapi::StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 200_000 }; + let (pid, include) = match mode { + // Everything but our own process tree. + Loopback::AllButSelf => (std::process::id(), false), + Loopback::Tree(pid) => (pid, true), + }; + let opened = wasapi::AudioClient::new_application_loopback_client(pid, include).and_then( + |mut client| { + client.initialize_client(&format, &wasapi::Direction::Capture, &stream)?; + Ok(client) + }, + ); + match opened { + Ok(client) => return Ok(client), + // No fallback that would capture other applications too. + Err(e) if include => return Err(format!("process loopback of {pid}: {e}")), Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"), } let enumerator = wasapi::DeviceEnumerator::new().map_err(|e| e.to_string())?; @@ -282,42 +326,61 @@ fn open_client() -> std::result::Result { let mut client = device.get_iaudioclient().map_err(|e| e.to_string())?; // Capture on a render device is loopback. client - .initialize_client(&format, &wasapi::Direction::Capture, &mode) + .initialize_client(&format, &wasapi::Direction::Capture, &stream) .map_err(|e| e.to_string())?; Ok(client) } +/// The capture loop: packets as they come, converted into one reused +/// buffer (nothing allocated per packet). fn loopback( - tx: &FrameSender, - stop: &std::sync::atomic::AtomicBool, + mode: Loopback, + stop: &AtomicBool, init: &std::sync::mpsc::Sender>, + deliver: &mut dyn FnMut(&[f32]) -> bool, ) -> std::result::Result<(), String> { // COM for this thread; "already initialised" is fine. let _ = wasapi::initialize_mta(); - let client = open_client()?; + let client = open_client(mode)?; let event = client.set_get_eventhandle().map_err(|e| e.to_string())?; let capture = client.get_audiocaptureclient().map_err(|e| e.to_string())?; client.start_stream().map_err(|e| e.to_string())?; let _ = init.send(Ok(())); - const FRAME_BYTES: usize = 2 * 4; - let chunk = AUDIO_SAMPLE_RATE as usize / 100 * FRAME_BYTES; - let started = Instant::now(); - let mut queue = VecDeque::new(); + // A tenth of a second per packet; grown if a packet is larger. + let mut bytes = vec![0u8; AUDIO_SAMPLE_RATE as usize / 10 * FRAME_BYTES]; + let mut samples: Vec = Vec::with_capacity(bytes.len() / 4); while !stop.load(Ordering::Relaxed) { // No events arrive while nothing plays. if event.wait_for_event(100).is_err() { continue; } - capture.read_from_device_to_deque(&mut queue).map_err(|e| e.to_string())?; - while queue.len() >= chunk { - let bytes: Vec = queue.drain(..chunk).collect(); - let samples = bytes - .chunks_exact(4) - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); - let buffer = AudioBuffer { samples, channels: 2, timestamp: started.elapsed() }; - if !tx.send(buffer) { + loop { + let (frames, info) = match capture.read_from_device(&mut bytes) { + Ok(read) => read, + Err(wasapi::WasapiError::DataLengthTooShort { expected, .. }) => { + // That packet is lost; the next one fits. + bytes.resize(expected * FRAME_BYTES, 0); + samples.reserve(expected * 2); + continue; + } + Err(e) => return Err(e.to_string()), + }; + if frames == 0 { + break; + } + let len = frames as usize * FRAME_BYTES; + samples.clear(); + if info.flags.silent { + samples.resize(len / 4, 0.0); + } else { + samples.extend( + bytes[..len] + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])), + ); + } + if !deliver(&samples) { stop.store(true, Ordering::Relaxed); break; } @@ -325,3 +388,190 @@ fn loopback( } client.stop_stream().map_err(|e| e.to_string()) } + +/// Loopback captures feeding a mixer source. +struct LoopbackCapture { + _worker: Worker, +} + +impl SourceCapture for LoopbackCapture { + fn backend(&self) -> &'static str { + AUDIO_BACKEND + } +} + +fn capture_into(mode: Loopback, source: &SourceHandle) -> Result { + let mut input = source.input(AUDIO_SAMPLE_RATE); + spawn_loopback("voelin-wasapi-source", mode, move |samples| { + input.push(samples, 2); + !input.is_closed() + }) +} + +/// Capture the playback `filter` selects into `source`: process loopback +/// excluding our process tree, or including the chosen process tree (for a +/// name, one capture per matching process, matched again every two +/// seconds). +pub fn start_playback( + filter: &PlaybackFilter, + source: &SourceHandle, +) -> Result> { + let worker = match filter { + PlaybackFilter::AllButSelf => capture_into(Loopback::AllButSelf, source)?, + PlaybackFilter::App(AppMatch::Pid(pid)) => capture_into(Loopback::Tree(*pid), source)?, + PlaybackFilter::App(app) => { + let (app, source) = (app.clone(), source.clone()); + Worker::spawn("voelin-wasapi-apps", move |stop| follow_app(&app, &source, &stop))? + } + }; + Ok(Box::new(LoopbackCapture { _worker: worker })) +} + +/// Keep one include-mode capture per process whose audio sessions match +/// `app`, until stopped or the source is removed. +fn follow_app(app: &AppMatch, source: &SourceHandle, stop: &AtomicBool) { + let _ = wasapi::initialize_mta(); + // Per process: its capture, and the polls it was missing from. + let mut captures: Vec<(u32, Worker, u32)> = Vec::new(); + let mut ticker = Ticker::new(1); + loop { + let pids: Vec = match sessions() { + Ok(apps) => apps + .into_iter() + .filter(|a| app.matches_name([a.name.as_str(), a.binary.as_deref().unwrap_or("")])) + .filter_map(|a| a.pid) + .collect(), + Err(e) => { + debug!("listing audio sessions: {e}"); + Vec::new() + } + }; + for entry in &mut captures { + entry.2 = if pids.contains(&entry.0) { 0 } else { entry.2 + 1 }; + } + // Gone for two polls: the process ended or closed its sessions. + captures.retain(|(_, _, missing)| *missing < 2); + for pid in pids { + if captures.iter().any(|(p, ..)| *p == pid) { + continue; + } + match capture_into(Loopback::Tree(pid), source) { + Ok(worker) => captures.push((pid, worker, 0)), + Err(e) => warn!("capturing process {pid} ({app}): {e}"), + } + } + if source.is_removed() || !ticker.wait(stop) || !ticker.wait(stop) { + break; + } + } +} + +/// The executable file name of `pid`, if we may look. +fn process_name(pid: u32) -> Option { + use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, + QueryFullProcessImageNameW, + }; + let mut path = [0u16; 1024]; + let mut len = path.len() as u32; + // SAFETY: the handle is checked by `OpenProcess` and closed by `Owned`; + // the pointer and length describe `path`, which outlives the call. + #[allow(unsafe_code)] + unsafe { + let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; + let process = windows::core::Owned::new(process); + QueryFullProcessImageNameW( + *process, + PROCESS_NAME_WIN32, + windows::core::PWSTR(path.as_mut_ptr()), + &mut len, + ) + .ok()?; + } + let path = String::from_utf16_lossy(&path[..(len as usize).min(path.len())]); + path.rsplit(['\\', '/']).next().map(str::to_owned).filter(|n| !n.is_empty()) +} + +/// Audio sessions of every active playback device, one entry per process +/// (not ours). +fn sessions() -> std::result::Result, String> { + let own = std::process::id(); + let enumerator = wasapi::DeviceEnumerator::new().map_err(|e| e.to_string())?; + let devices = + enumerator.get_device_collection(&wasapi::Direction::Render).map_err(|e| e.to_string())?; + let mut apps: Vec = Vec::new(); + for device in &devices { + let Ok(device) = device else { continue }; + let Ok(manager) = device.get_iaudiosessionmanager() else { continue }; + let Ok(sessions) = manager.get_audiosessionenumerator() else { continue }; + for i in 0..sessions.get_count().unwrap_or(0) { + let Ok(session) = sessions.get_session(i) else { continue }; + // Process 0 is the system sounds session. + let Ok(pid) = session.get_process_id() else { continue }; + if pid == 0 || pid == own { + continue; + } + let state = session.get_state().ok(); + if matches!(state, Some(wasapi::SessionState::Expired)) { + continue; + } + let playing = matches!(state, Some(wasapi::SessionState::Active)); + if let Some(app) = apps.iter_mut().find(|a| a.pid == Some(pid)) { + app.streams += 1; + app.playing |= playing; + continue; + } + let binary = process_name(pid); + // Names like "@%SystemRoot%\..." are resource references. + let display = session + .get_display_name() + .ok() + .filter(|n| !n.trim().is_empty() && !n.starts_with('@')); + let stem = binary.as_deref().map(|b| b.strip_suffix(".exe").unwrap_or(b).to_owned()); + apps.push(AudioApp { + name: display.or(stem).unwrap_or_else(|| format!("Process {pid}")), + pid: Some(pid), + binary, + icon: session.get_icon_path().ok().filter(|p| !p.trim().is_empty()), + media: None, + streams: 1, + playing, + }); + } + } + apps.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then(a.pid.cmp(&b.pid))); + Ok(apps) +} + +/// Applications with audio sessions, polled every two seconds. +pub fn audio_apps() -> Result { + let _ = wasapi::initialize_mta(); + let first = sessions() + .map_err(|reason| Error::CaptureUnavailable { backend: AUDIO_BACKEND, reason })?; + let (tx, rx) = tokio::sync::watch::channel(first); + let worker = Worker::spawn("voelin-wasapi-sessions", move |stop| { + let _ = wasapi::initialize_mta(); + let mut ticker = Ticker::new(1); + while ticker.wait(&stop) && ticker.wait(&stop) && !tx.is_closed() { + if let Ok(apps) = sessions() { + tx.send_if_modified(|current| { + let changed = *current != apps; + if changed { + *current = apps; + } + changed + }); + } + } + })?; + Ok(AudioApps::new(rx, Box::new(worker))) +} + +/// The process that owns window `hwnd`. +pub fn window_pid(hwnd: u64) -> Option { + let window = Window::from_raw_hwnd(hwnd as usize as *mut std::ffi::c_void); + if !window.is_valid() { + return None; + } + window.process_id().ok() +} diff --git a/crates/voelin-media/src/capture/x11.rs b/crates/voelin-media/src/capture/x11.rs index 8d10406..de06ea9 100644 --- a/crates/voelin-media/src/capture/x11.rs +++ b/crates/voelin-media/src/capture/x11.rs @@ -195,6 +195,21 @@ impl ScreenCapture for X11Capture { } } +/// The process that owns `window` (its `_NET_WM_PID`) on `display` (`None`: +/// `$DISPLAY`), for capturing the window's audio. Clients set it +/// voluntarily; it is the pid on the window's host. +pub fn window_pid(display: Option<&str>, window: u64) -> Option { + let (conn, _) = RustConnection::connect(display).ok()?; + let atom = conn.intern_atom(true, b"_NET_WM_PID").ok()?.reply().ok()?.atom; + if atom == u32::from(AtomEnum::NONE) { + return None; + } + let window = u32::try_from(window).ok()?; + let reply = + conn.get_property(false, window, atom, AtomEnum::CARDINAL, 0, 1).ok()?.reply().ok()?; + reply.value32()?.next().filter(|&pid| pid > 0) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Rect { x: i16, diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 6d57eba..e69b3c9 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -14,6 +14,9 @@ //! test source, X11 (feature `x11`), the Wayland ScreenCast portal and //! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture //! plus WASAPI loopback on Windows +//! - [`mix`]: the stream's audio mixer ([`mix::StreamMixer`]): any number +//! of sources at their own pace and rate into 48 kHz stereo, with gains, +//! mutes, a soft limiter and lock-free meters //! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on //! - the streaming path: [`workers`] (a fork-join pool that allocates //! nothing per job), [`pool`] (recycled I420 frames), [`handoff`] @@ -32,6 +35,7 @@ pub mod convert; pub mod ffmpeg; pub mod frame; pub mod handoff; +pub mod mix; pub mod pool; pub mod queue; pub mod scale; diff --git a/crates/voelin-media/src/mix.rs b/crates/voelin-media/src/mix.rs new file mode 100644 index 0000000..e908a69 --- /dev/null +++ b/crates/voelin-media/src/mix.rs @@ -0,0 +1,1609 @@ +//! The stream's audio mixer: any number of sources into one 48 kHz stereo +//! signal ([`StreamMixer`]). +//! +//! - A source ([`MixerHandle::add_source`]) has a name, a gain and a mute, +//! and any number of inputs ([`SourceHandle::input`]): lock-free +//! single-producer rings that a capture thread fills at its own pace, at +//! any sample rate and channel count. Channels are mapped to stereo as +//! they are pushed; the rate is converted while mixing. +//! - The mixer runs on the caller's clock, one block at a time +//! ([`StreamMixer::mix`], paced by [`BlockClock`]). Each input is held at +//! a small fixed latency ([`MixerConfig::latency`], more for an input that +//! delivers in larger bursts or keeps arriving late): it starts once that +//! much is buffered, and an input that runs dry (its capture stalled, +//! nothing plays, or it ended) fades out and waits to buffer again while +//! every other source goes on. Clock drift between a source and the mixer +//! is absorbed by resampling up to 0.5 % faster or slower while the +//! buffer is off target; the rest of the time a 48 kHz input is copied +//! through bit-exact. +//! - Rate conversion is cubic (Catmull-Rom) interpolation per input. +//! - The sum goes through a master gain and a soft limiter (a peak envelope +//! with 1 ms attack, gain reduction above the threshold, and a soft clip +//! of what the envelope is too slow for), so the output never exceeds +//! full scale; below the threshold it is untouched. +//! - Levels (peak falling back at 20 dB/s, RMS over about 300 ms) of each +//! source (after its gain, before its mute) and of the output are atomics: +//! [`SourceHandle::level`] and [`MixerHandle::level`] read them without +//! locking, from any thread. +//! - Buffers are allocated when a source or an input is created, sized from +//! the [`MixerConfig`]; mixing works in place in them and allocates +//! nothing per block. Sources, inputs, gains and mutes change while +//! mixing: control calls queue changes that the mixer picks up at its next +//! block (with a non-blocking try-lock that only contends with those +//! calls). + +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +use crate::frame::AUDIO_SAMPLE_RATE; + +/// Output rate of the mixer. +pub const MIX_RATE: u32 = AUDIO_SAMPLE_RATE; + +/// One stereo frame: left, right. +pub type Frame = [f32; 2]; + +const SILENCE: Frame = [0.0; 2]; +/// The most the drift correction speeds an input up or slows it down. +const MAX_CORRECTION: f64 = 0.005; +/// Buffer error (seconds) above which the drift correction starts ... +const DRIFT_ENGAGE: f64 = 0.010; +/// ... and below which it winds down again. +const DRIFT_RELEASE: f64 = 0.002; +/// The correction aims to remove the error within this many seconds. +const DRIFT_TIME: f64 = 4.0; +/// Time constant of an input's average buffer level (seconds). +const FILL_TIME: f64 = 1.0; +/// Time constant (seconds) in which an input's largest burst is forgotten. +const BURST_TIME: f64 = 15.0; +/// Headroom beyond the largest burst and a block (seconds). +const BURST_MARGIN: f64 = 0.005; +/// Frames faded in when an input starts, and out when it runs dry. +const FADE: usize = 32; +/// Latency added to an input that ran dry and came back within +/// [`HICCUP`]: it delivers too unevenly for its latency. +const UNDERRUN_STEP: f64 = 0.010; +const HICCUP: f64 = 0.25; +/// Peak meters fall back this fast (dB per second). +const PEAK_FALL: f32 = 20.0; +/// Time constant of the RMS meters (seconds). +const RMS_TIME: f32 = 0.3; +/// Attack of the limiter's envelope (seconds). +const LIMITER_ATTACK: f32 = 0.001; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// How the mixer is set up; buffers are sized from it. +#[derive(Clone, Debug, PartialEq)] +pub struct MixerConfig { + /// Largest block [`StreamMixer::mix`] handles at once, in frames + /// (longer calls are split). Default 960: 20 ms, one Opus frame. + pub max_block: usize, + /// How far behind its capture each input is mixed, to absorb uneven + /// delivery. Inputs that deliver in larger bursts get more. Default + /// 40 ms. + pub latency: Duration, + /// Ring size of each input: how far ahead of the mixer a capture can + /// get before audio is dropped. Default 500 ms. + pub buffer: Duration, + /// Soft-limiter threshold, linear (0 to 1]. Default -1 dBFS. + pub limiter_threshold: f32, + /// How fast the limiter lets go. Default 100 ms. + pub limiter_release: Duration, +} + +impl Default for MixerConfig { + fn default() -> Self { + Self { + max_block: 960, + latency: Duration::from_millis(40), + buffer: Duration::from_millis(500), + limiter_threshold: 0.891, + limiter_release: Duration::from_millis(100), + } + } +} + +/// An `f32` in an `AtomicU32` (relaxed: every value is complete on its own). +struct AtomicF32(AtomicU32); + +impl AtomicF32 { + fn new(value: f32) -> Self { + Self(AtomicU32::new(value.to_bits())) + } + + fn load(&self) -> f32 { + f32::from_bits(self.0.load(Ordering::Relaxed)) + } + + fn store(&self, value: f32) { + self.0.store(value.to_bits(), Ordering::Relaxed); + } +} + +/// A meter reading, linear (1.0 is full scale). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Level { + /// Highest sample, falling back at 20 dB/s. + pub peak: f32, + /// Root mean square over about 300 ms (both channels). + pub rms: f32, +} + +impl Level { + pub fn peak_db(&self) -> f32 { + to_db(self.peak) + } + + pub fn rms_db(&self) -> f32 { + to_db(self.rms) + } +} + +/// dBFS of a linear level; -120 for silence. +pub fn to_db(level: f32) -> f32 { + if level > 1e-6 { 20.0 * level.log10() } else { -120.0 } +} + +/// A level for readers on other threads. +struct Meter { + peak: AtomicF32, + rms: AtomicF32, +} + +impl Meter { + fn new() -> Self { + Self { peak: AtomicF32::new(0.0), rms: AtomicF32::new(0.0) } + } + + fn load(&self) -> Level { + Level { peak: self.peak.load(), rms: self.rms.load() } + } +} + +/// The mixer's side of a meter: fall-back and smoothing. +#[derive(Default)] +struct MeterState { + peak: f32, + mean_square: f32, +} + +/// Fall-back and smoothing factors for one block. +#[derive(Clone, Copy)] +struct Ballistics { + decay: f32, + alpha: f32, +} + +impl Ballistics { + fn new(frames: usize) -> Self { + let dt = frames as f32 / MIX_RATE as f32; + Self { decay: 10f32.powf(-PEAK_FALL / 20.0 * dt), alpha: 1.0 - (-dt / RMS_TIME).exp() } + } +} + +impl MeterState { + /// Take a block's peak and sum of squares (over `samples` samples). + fn update(&mut self, peak: f32, squares: f32, samples: usize, b: Ballistics, meter: &Meter) { + self.peak = peak.max(self.peak * b.decay); + let mean = if samples == 0 { 0.0 } else { squares / samples as f32 }; + self.mean_square += b.alpha * (mean - self.mean_square); + meter.peak.store(self.peak); + meter.rms.store(self.mean_square.max(0.0).sqrt()); + } +} + +/// What a source is doing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SourceState { + /// Nothing buffered to play: no input yet, nothing plays, or the + /// capture stalled. Silent until an input buffers its latency. + #[default] + Idle, + /// At least one input plays. + Playing, + /// Every input ended (their captures stopped). + Ended, +} + +impl SourceState { + fn from_u8(value: u8) -> Self { + match value { + 1 => Self::Playing, + 2 => Self::Ended, + _ => Self::Idle, + } + } +} + +/// Counters of a source ([`SourceHandle::stats`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SourceStats { + pub state: SourceState, + /// Inputs feeding it. + pub inputs: usize, + /// How far behind their captures its playing inputs are mixed (the + /// largest average buffer level). + pub latency: Duration, + /// Times an input ran dry while playing (and came back soon: delivery + /// hiccups, not pauses). + pub underruns: u64, + /// Frames dropped because an input's ring was full (the mixer was held + /// up or stopped). + pub overflows: u64, + /// Frames skipped to bring an input that got far ahead back to its + /// latency. + pub skipped: u64, +} + +/// Burst size of an input, written by its producer. +struct LaneShared { + max_push: AtomicUsize, +} + +struct SourceShared { + id: u64, + name: String, + gain: AtomicF32, + muted: AtomicBool, + removed: AtomicBool, + meter: Meter, + state: AtomicU8, + inputs: AtomicUsize, + latency_us: AtomicU64, + underruns: AtomicU64, + overflows: AtomicU64, + skipped: AtomicU64, + /// Inputs the mixer has not picked up yet. + new_lanes: Mutex>, + has_new_lanes: AtomicBool, +} + +struct MixerShared { + config: MixerConfig, + next_id: AtomicU64, + /// The sources, in the order they were added (for listing). + sources: Mutex>>, + /// Sources the mixer has not picked up yet. + new_sources: Mutex>, + has_new_sources: AtomicBool, + gain: AtomicF32, + meter: Meter, + /// The limiter's current gain (1: not limiting). + limiter: AtomicF32, + /// Frames mixed. + frames: AtomicU64, +} + +/// One input as the mixer sees it: the consuming end of its ring, the +/// resampler window and the latency / drift state. +struct Lane { + ring: rtrb::Consumer, + shared: Arc, + rate: u32, + capacity: usize, + /// Input frames per output frame, without drift correction. + step: f64, + /// Relative speed-up (positive) or slow-down of the drift correction. + correction: f64, + /// The correction is winding down (at 48 kHz: until the phase lines + /// up with a sample again, so the input is copied bit-exact after). + releasing: bool, + /// Frames read from the ring and not passed yet: `window[0]` is the + /// frame before the next output position, which is `pos` in [1, 2). + window: Vec, + pos: f64, + playing: bool, + /// Played before: running dry counts as an underrun. + started: bool, + /// Frames faded in since starting. + faded: usize, + /// Average buffer level before a block is read (input frames). + fill: f64, + /// The level the drift correction keeps: where the input settled in + /// its first second of playing. + setpoint: Option, + settle_sum: f64, + settle_blocks: u32, + /// Largest burst seen lately (input frames). + burst: f64, + /// Latency added after hiccups (input frames). + extra: usize, + /// Blocks since the input ran dry. + dry_blocks: u64, + ended: bool, +} + +impl Lane { + fn new(config: &MixerConfig, rate: u32) -> (Self, rtrb::Producer, Arc) { + let rate = rate.max(1); + let step = f64::from(rate) / f64::from(MIX_RATE); + let window = max_input(config.max_block, step) + 8; + let capacity = + ((config.buffer.as_secs_f64() * f64::from(rate)).ceil() as usize).max(4 * window); + let (producer, ring) = rtrb::RingBuffer::new(capacity); + let shared = Arc::new(LaneShared { max_push: AtomicUsize::new(0) }); + let lane = Self { + ring, + shared: shared.clone(), + rate, + capacity, + step, + correction: 0.0, + releasing: false, + window: Vec::with_capacity(window), + pos: 1.0, + playing: false, + started: false, + faded: 0, + fill: 0.0, + setpoint: None, + settle_sum: 0.0, + settle_blocks: 0, + burst: 0.0, + extra: 0, + dry_blocks: 0, + ended: false, + }; + (lane, producer, shared) + } + + /// Input frames needed for `n` output frames at most. + fn max_input(&self, n: usize) -> usize { + max_input(n, self.step) + } + + /// Frames to buffer before playing. + fn target(&self, n: usize, latency: f64) -> usize { + let rate = f64::from(self.rate); + let base = (latency * rate) as usize; + let burst = self.burst as usize + self.max_input(n) + (BURST_MARGIN * rate) as usize; + (base.max(burst) + self.extra).min(self.capacity * 3 / 4) + } + + fn start(&mut self, avail: usize) { + self.window.clear(); + self.window.push(SILENCE); + self.pos = 1.0; + self.correction = 0.0; + self.releasing = false; + self.faded = 0; + self.playing = true; + self.settle(avail); + // Back soon after running dry: a hiccup, not a pause. + let dry = self.dry_blocks as f64 * 0.02; + if self.started && dry < HICCUP { + self.extra += (UNDERRUN_STEP * f64::from(self.rate)) as usize; + } + self.started = true; + } + + /// Render `out.len()` frames into `out` (overwriting it). Returns + /// `false`, with `out` untouched, while the input is not playing. + fn render(&mut self, out: &mut [Frame], latency: f64, source: &SourceShared) -> bool { + let n = out.len(); + let recent = self.shared.max_push.swap(0, Ordering::Relaxed) as f64; + let dt = n as f64 / f64::from(MIX_RATE); + self.burst = recent.max(self.burst * (-dt / BURST_TIME).exp()); + let mut avail = self.ring.slots(); + let target = self.target(n, latency); + if !self.playing { + let abandoned = self.ring.is_abandoned(); + if avail >= target.max(1) || (abandoned && avail > 0) { + self.start(avail); + } else { + self.ended = abandoned; + self.dry_blocks += 1; + return false; + } + } + // Far ahead (the mixer was held up, or the source runs fast): skip + // back to the target. + if avail > 2 * target + self.max_input(n) { + let skip = avail - target; + if let Ok(chunk) = self.ring.read_chunk(skip) { + chunk.commit_all(); + } + source.skipped.fetch_add(skip as u64, Ordering::Relaxed); + avail = target; + self.settle(avail); + } + self.steer(n, avail); + + // Read what this block needs. + let step = self.step * (1.0 + self.correction); + let reach = if self.releasing { step.max(self.step) } else { step }; + let need = ((self.pos + (n - 1) as f64 * reach) as usize + 3).min(self.window.capacity()); + let take = need.saturating_sub(self.window.len()).min(avail); + if take > 0 + && let Ok(chunk) = self.ring.read_chunk(take) + { + let (a, b) = chunk.as_slices(); + self.window.extend_from_slice(a); + self.window.extend_from_slice(b); + chunk.commit_all(); + } + + let produced = self.interpolate(out); + out[produced..].fill(SILENCE); + // Fade in after starting. + for frame in out[..produced].iter_mut() { + if self.faded >= FADE { + break; + } + self.faded += 1; + let g = self.faded as f32 / (FADE + 1) as f32; + *frame = [frame[0] * g, frame[1] * g]; + } + if produced < n { + // Ran dry: fade out what there was and wait for the latency again. + let m = produced.min(FADE); + for (j, frame) in out[produced - m..produced].iter_mut().enumerate() { + let g = (m - j) as f32 / (m + 1) as f32; + *frame = [frame[0] * g, frame[1] * g]; + } + if !self.ring.is_abandoned() { + source.underruns.fetch_add(1, Ordering::Relaxed); + } + self.playing = false; + self.dry_blocks = 0; + } else { + // Keep one frame of history before the next position. + let drop = (self.pos as usize).saturating_sub(1).min(self.window.len()); + self.window.drain(..drop); + self.pos -= drop as f64; + } + true + } + + /// Measure the level to keep afresh. + fn settle(&mut self, avail: usize) { + self.fill = avail as f64; + self.setpoint = None; + self.settle_sum = 0.0; + self.settle_blocks = 0; + self.correction = 0.0; + self.releasing = false; + } + + /// Drift correction: keep the average buffer level at the setpoint. + /// Starting at a burst's peak or trough is no drift, so the setpoint is + /// the average of the first second rather than the start threshold. + fn steer(&mut self, n: usize, avail: usize) { + let Some(setpoint) = self.setpoint else { + self.settle_sum += avail as f64; + self.settle_blocks += 1; + self.fill = self.settle_sum / f64::from(self.settle_blocks); + if f64::from(self.settle_blocks) * n as f64 >= FILL_TIME * f64::from(MIX_RATE) { + self.setpoint = Some(self.fill); + } + return; + }; + let alpha = 1.0 - (-(n as f64) / (f64::from(MIX_RATE) * FILL_TIME)).exp(); + self.fill += alpha * (avail as f64 - self.fill); + let error = (self.fill - setpoint) / f64::from(self.rate); + let wanted = (error / DRIFT_TIME).clamp(-MAX_CORRECTION, MAX_CORRECTION); + if self.correction == 0.0 { + if error.abs() > DRIFT_ENGAGE { + self.correction = wanted; + self.releasing = false; + } + } else if error.abs() < DRIFT_RELEASE || error.signum() != self.correction.signum() { + self.releasing = true; + } else if !self.releasing { + self.correction = wanted; + } + } + + /// Interpolate from the window into `out`; returns the frames produced + /// (fewer when the window runs out) and advances `pos`. + fn interpolate(&mut self, out: &mut [Frame]) -> usize { + let base = self.step; + if self.releasing && base != 1.0 { + // Changing the step keeps the phase: nothing to line up. + self.correction = 0.0; + self.releasing = false; + } + let len = self.window.len(); + let mut step = base * (1.0 + self.correction); + let mut x = self.pos; + if step == 1.0 && x.fract() == 0.0 { + // 48 kHz in step: a plain copy. + let i = x as usize; + let count = out.len().min(len.saturating_sub(i + 2)); + out[..count].copy_from_slice(&self.window[i..i + count]); + self.pos = x + count as f64; + return count; + } + let snap = (step - base).abs(); + let w = &self.window; + for (k, frame) in out.iter_mut().enumerate() { + let i = x as usize; + if i + 2 >= len { + self.pos = x; + return k; + } + let mut t = x - i as f64; + if self.releasing && t < snap { + // In phase with the input again: stop correcting. + x = i as f64; + t = 0.0; + step = base; + self.correction = 0.0; + self.releasing = false; + } + let t = t as f32; + let (p0, p1, p2, p3) = (w[i - 1], w[i], w[i + 1], w[i + 2]); + *frame = [cubic(p0[0], p1[0], p2[0], p3[0], t), cubic(p0[1], p1[1], p2[1], p3[1], t)]; + x += step; + } + self.pos = x; + out.len() + } +} + +/// Input frames for `n` output frames at `step`, with drift correction and +/// the interpolator's reach. +fn max_input(n: usize, step: f64) -> usize { + (n as f64 * step * (1.0 + MAX_CORRECTION)).ceil() as usize + 4 +} + +/// Catmull-Rom interpolation between `p1` (t = 0, returned exactly) and +/// `p2` (t = 1). +#[inline] +fn cubic(p0: f32, p1: f32, p2: f32, p3: f32, t: f32) -> f32 { + let a = -0.5 * p0 + 1.5 * p1 - 1.5 * p2 + 0.5 * p3; + let b = p0 - 2.5 * p1 + 2.0 * p2 - 0.5 * p3; + let c = 0.5 * (p2 - p0); + ((a * t + b) * t + c) * t + p1 +} + +/// A source as the mixer sees it. +struct MixSource { + shared: Arc, + lanes: Vec, + /// Gain and mute (1 or 0) the last block ended with; the next block + /// ramps from these to the current settings. + gain: f32, + mute: f32, + had_lanes: bool, + meter: MeterState, +} + +/// Envelope-following soft limiter. +struct Limiter { + threshold: f32, + attack: f32, + release: f32, + envelope: f32, + /// Lowest gain of the last block, for [`MixerHandle::limiter_gain`]. + lowest: f32, +} + +impl Limiter { + fn new(config: &MixerConfig) -> Self { + let coeff = |seconds: f32| (-1.0 / (seconds.max(1e-4) * MIX_RATE as f32)).exp(); + Self { + threshold: config.limiter_threshold.clamp(0.01, 1.0), + attack: coeff(LIMITER_ATTACK), + release: coeff(config.limiter_release.as_secs_f32()), + envelope: 0.0, + lowest: 1.0, + } + } + + #[inline] + fn process(&mut self, frame: &mut Frame) { + let peak = frame[0].abs().max(frame[1].abs()); + let coeff = if peak > self.envelope { self.attack } else { self.release }; + self.envelope = peak + coeff * (self.envelope - peak); + if self.envelope > self.threshold { + let gain = self.threshold / self.envelope; + self.lowest = self.lowest.min(gain); + frame[0] *= gain; + frame[1] *= gain; + } + frame[0] = soft_clip(frame[0], self.threshold); + frame[1] = soft_clip(frame[1], self.threshold); + } +} + +/// Unchanged up to `threshold`, then bending smoothly towards 1.0. +#[inline] +fn soft_clip(x: f32, threshold: f32) -> f32 { + let a = x.abs(); + if a <= threshold { + return x; + } + let knee = 1.0 - threshold; + if knee <= 0.0 { + return x.signum(); + } + (threshold + knee * ((a - threshold) / knee).tanh()).copysign(x) +} + +/// Mixes the sources; lives on the thread that paces the audio. Control it +/// from anywhere through [`StreamMixer::handle`]. +pub struct StreamMixer { + shared: Arc, + sources: Vec, + lane_buf: Vec, + source_buf: Vec, + mix_buf: Vec, + limiter: Limiter, + gain: f32, + meter: MeterState, +} + +impl Default for StreamMixer { + fn default() -> Self { + Self::new(MixerConfig::default()) + } +} + +impl StreamMixer { + pub fn new(config: MixerConfig) -> Self { + let config = MixerConfig { max_block: config.max_block.max(1), ..config }; + let block = config.max_block; + let limiter = Limiter::new(&config); + let shared = Arc::new(MixerShared { + config, + next_id: AtomicU64::new(1), + sources: Mutex::new(Vec::new()), + new_sources: Mutex::new(Vec::new()), + has_new_sources: AtomicBool::new(false), + gain: AtomicF32::new(1.0), + meter: Meter::new(), + limiter: AtomicF32::new(1.0), + frames: AtomicU64::new(0), + }); + Self { + shared, + sources: Vec::with_capacity(16), + lane_buf: vec![SILENCE; block], + source_buf: vec![SILENCE; block], + mix_buf: vec![SILENCE; block], + limiter, + gain: 1.0, + meter: MeterState::default(), + } + } + + pub fn handle(&self) -> MixerHandle { + MixerHandle { shared: self.shared.clone() } + } + + pub fn config(&self) -> &MixerConfig { + &self.shared.config + } + + /// Mix `out.len() / 2` frames of interleaved stereo into `out` + /// (overwriting it), on the caller's clock. + pub fn mix(&mut self, out: &mut [f32]) { + let block = self.shared.config.max_block * 2; + let even = out.len() & !1; + let (frames, rest) = out.split_at_mut(even); + for chunk in frames.chunks_mut(block) { + self.mix_block(chunk); + } + rest.fill(0.0); + } + + /// Pick up new sources and inputs, drop removed sources. + fn adopt(&mut self) { + if self.shared.has_new_sources.load(Ordering::Acquire) + && let Ok(mut new) = self.shared.new_sources.try_lock() + { + self.shared.has_new_sources.store(false, Ordering::Relaxed); + for mut source in new.drain(..) { + source.gain = source.shared.gain.load(); + source.mute = if source.shared.muted.load(Ordering::Relaxed) { 0.0 } else { 1.0 }; + self.sources.push(source); + } + } + self.sources.retain(|s| !s.shared.removed.load(Ordering::Relaxed)); + for source in &mut self.sources { + if source.shared.has_new_lanes.load(Ordering::Acquire) + && let Ok(mut new) = source.shared.new_lanes.try_lock() + { + source.shared.has_new_lanes.store(false, Ordering::Relaxed); + source.lanes.append(&mut new); + } + } + } + + fn mix_block(&mut self, out: &mut [f32]) { + let n = out.len() / 2; + self.adopt(); + let latency = self.shared.config.latency.as_secs_f64(); + let ballistics = Ballistics::new(n); + let Self { sources, lane_buf, source_buf, mix_buf, .. } = self; + let mix = &mut mix_buf[..n]; + mix.fill(SILENCE); + for source in sources.iter_mut() { + let sum = &mut source_buf[..n]; + let lane_out = &mut lane_buf[..n]; + let shared = &*source.shared; + let mut any = false; + let mut latency_seconds = 0.0f64; + for lane in &mut source.lanes { + let into = if any { &mut *lane_out } else { &mut *sum }; + if lane.render(into, latency, shared) { + if any { + for (s, l) in sum.iter_mut().zip(lane_out.iter()) { + s[0] += l[0]; + s[1] += l[1]; + } + } + any = true; + } + if lane.playing { + latency_seconds = latency_seconds.max(lane.fill / f64::from(lane.rate)); + } + } + source.lanes.retain(|l| !l.ended); + if !source.lanes.is_empty() { + source.had_lanes = true; + } + let state = if any { + SourceState::Playing + } else if source.lanes.is_empty() && source.had_lanes { + SourceState::Ended + } else { + SourceState::Idle + }; + shared.state.store(state as u8, Ordering::Relaxed); + shared.inputs.store(source.lanes.len(), Ordering::Relaxed); + shared.latency_us.store((latency_seconds * 1e6) as u64, Ordering::Relaxed); + + let gain = shared.gain.load(); + let mute = if shared.muted.load(Ordering::Relaxed) { 0.0 } else { 1.0 }; + if !any { + source.meter.update(0.0, 0.0, 0, ballistics, &shared.meter); + source.gain = gain; + source.mute = mute; + continue; + } + let (peak, squares) = add_source(sum, mix, (source.gain, gain), (source.mute, mute)); + source.meter.update(peak, squares, 2 * n, ballistics, &shared.meter); + source.gain = gain; + source.mute = mute; + } + + // Master gain, limiter, meter, interleave. + let gain = self.shared.gain.load(); + let from = self.gain; + let ramp = (gain - from) / n as f32; + self.limiter.lowest = 1.0; + let (mut peak, mut squares) = (0.0f32, 0.0f32); + for (k, (frame, pair)) in mix.iter_mut().zip(out.chunks_exact_mut(2)).enumerate() { + let g = if ramp == 0.0 { gain } else { from + ramp * (k + 1) as f32 }; + if g != 1.0 { + frame[0] *= g; + frame[1] *= g; + } + self.limiter.process(frame); + peak = peak.max(frame[0].abs()).max(frame[1].abs()); + squares += frame[0] * frame[0] + frame[1] * frame[1]; + pair[0] = frame[0]; + pair[1] = frame[1]; + } + self.gain = gain; + self.meter.update(peak, squares, 2 * n, ballistics, &self.shared.meter); + self.shared.limiter.store(self.limiter.lowest); + self.shared.frames.fetch_add(n as u64, Ordering::Relaxed); + } +} + +/// Add `sum` into `mix` with gain and mute ramped from `.0` to `.1` over +/// the block; returns the peak and sum of squares after the gain (before +/// the mute). +fn add_source(sum: &[Frame], mix: &mut [Frame], gain: (f32, f32), mute: (f32, f32)) -> (f32, f32) { + let (mut peak, mut squares) = (0.0f32, 0.0f32); + let n = sum.len() as f32; + if gain.0 == gain.1 && mute.0 == mute.1 { + let (g, m) = (gain.1, mute.1); + for (s, o) in sum.iter().zip(mix.iter_mut()) { + let (l, r) = (s[0] * g, s[1] * g); + peak = peak.max(l.abs()).max(r.abs()); + squares += l * l + r * r; + o[0] += l * m; + o[1] += r * m; + } + } else { + let dg = (gain.1 - gain.0) / n; + let dm = (mute.1 - mute.0) / n; + for (k, (s, o)) in sum.iter().zip(mix.iter_mut()).enumerate() { + let t = (k + 1) as f32; + let (g, m) = (gain.0 + dg * t, mute.0 + dm * t); + let (l, r) = (s[0] * g, s[1] * g); + peak = peak.max(l.abs()).max(r.abs()); + squares += l * l + r * r; + o[0] += l * m; + o[1] += r * m; + } + } + (peak, squares) +} + +impl Drop for StreamMixer { + fn drop(&mut self) { + // Inputs see the end (`SourceInput::is_closed`). + for source in lock(&self.shared.sources).iter() { + source.removed.store(true, Ordering::Relaxed); + } + for source in lock(&self.shared.new_sources).iter() { + source.shared.removed.store(true, Ordering::Relaxed); + } + } +} + +/// Controls a [`StreamMixer`] from any thread. Cheap to clone. +#[derive(Clone)] +pub struct MixerHandle { + shared: Arc, +} + +impl MixerHandle { + /// A new source (gain 1, not muted) with no inputs yet; the mixer picks + /// it up at its next block. + pub fn add_source(&self, name: impl Into) -> SourceHandle { + let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed); + let shared = Arc::new(SourceShared { + id, + name: name.into(), + gain: AtomicF32::new(1.0), + muted: AtomicBool::new(false), + removed: AtomicBool::new(false), + meter: Meter::new(), + state: AtomicU8::new(SourceState::Idle as u8), + inputs: AtomicUsize::new(0), + latency_us: AtomicU64::new(0), + underruns: AtomicU64::new(0), + overflows: AtomicU64::new(0), + skipped: AtomicU64::new(0), + new_lanes: Mutex::new(Vec::new()), + has_new_lanes: AtomicBool::new(false), + }); + let source = MixSource { + shared: shared.clone(), + lanes: Vec::with_capacity(4), + gain: 1.0, + mute: 1.0, + had_lanes: false, + meter: MeterState::default(), + }; + lock(&self.shared.sources).push(shared.clone()); + lock(&self.shared.new_sources).push(source); + self.shared.has_new_sources.store(true, Ordering::Release); + SourceHandle { mixer: self.shared.clone(), shared } + } + + /// The sources, in the order they were added. + pub fn sources(&self) -> Vec { + lock(&self.shared.sources) + .iter() + .map(|s| SourceHandle { mixer: self.shared.clone(), shared: s.clone() }) + .collect() + } + + pub fn source(&self, id: u64) -> Option { + lock(&self.shared.sources) + .iter() + .find(|s| s.id == id) + .map(|s| SourceHandle { mixer: self.shared.clone(), shared: s.clone() }) + } + + /// Gain after the sum, before the limiter (linear; ramps over a block). + pub fn set_gain(&self, gain: f32) { + self.shared.gain.store(sanitize_gain(gain)); + } + + pub fn gain(&self) -> f32 { + self.shared.gain.load() + } + + /// Output level (after the limiter). Lock-free. + pub fn level(&self) -> Level { + self.shared.meter.load() + } + + /// The limiter's lowest gain in the last block: 1 when it did nothing, + /// 0.5 for 6 dB of reduction. Lock-free. + pub fn limiter_gain(&self) -> f32 { + self.shared.limiter.load() + } + + /// Frames mixed so far. + pub fn frames(&self) -> u64 { + self.shared.frames.load(Ordering::Relaxed) + } + + pub fn config(&self) -> &MixerConfig { + &self.shared.config + } +} + +fn sanitize_gain(gain: f32) -> f32 { + if gain.is_finite() { gain.max(0.0) } else { 1.0 } +} + +/// Controls one source of a [`StreamMixer`]. Cheap to clone; the source +/// stays until [`remove`](Self::remove)d. +#[derive(Clone)] +pub struct SourceHandle { + mixer: Arc, + shared: Arc, +} + +impl std::fmt::Debug for SourceHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SourceHandle") + .field("id", &self.shared.id) + .field("name", &self.shared.name) + .finish() + } +} + +impl SourceHandle { + pub fn id(&self) -> u64 { + self.shared.id + } + + pub fn name(&self) -> &str { + &self.shared.name + } + + /// Linear gain, any value >= 0 (1: unchanged); ramps over one block. + pub fn set_gain(&self, gain: f32) { + self.shared.gain.store(sanitize_gain(gain)); + } + + pub fn gain(&self) -> f32 { + self.shared.gain.load() + } + + /// Mute (ramped over one block). A muted source is still read and + /// metered. + pub fn set_muted(&self, muted: bool) { + self.shared.muted.store(muted, Ordering::Relaxed); + } + + pub fn muted(&self) -> bool { + self.shared.muted.load(Ordering::Relaxed) + } + + /// Level after the gain, before the mute. Lock-free. + pub fn level(&self) -> Level { + self.shared.meter.load() + } + + pub fn state(&self) -> SourceState { + SourceState::from_u8(self.shared.state.load(Ordering::Relaxed)) + } + + pub fn stats(&self) -> SourceStats { + let s = &self.shared; + SourceStats { + state: self.state(), + inputs: s.inputs.load(Ordering::Relaxed), + latency: Duration::from_micros(s.latency_us.load(Ordering::Relaxed)), + underruns: s.underruns.load(Ordering::Relaxed), + overflows: s.overflows.load(Ordering::Relaxed), + skipped: s.skipped.load(Ordering::Relaxed), + } + } + + /// A new input at `rate` Hz for a capture thread to push into. A source + /// can have any number; each ends when its [`SourceInput`] is dropped + /// and what it buffered has played. + pub fn input(&self, rate: u32) -> SourceInput { + let (lane, ring, lane_shared) = Lane::new(&self.mixer.config, rate); + lock(&self.shared.new_lanes).push(lane); + self.shared.has_new_lanes.store(true, Ordering::Release); + SourceInput { + ring, + lane: lane_shared, + source: self.shared.clone(), + rate: rate.max(1), + weights: Vec::new(), + } + } + + /// Take the source out of the mix (from the next block); its inputs see + /// [`SourceInput::is_closed`]. + pub fn remove(&self) { + self.shared.removed.store(true, Ordering::Relaxed); + lock(&self.mixer.sources).retain(|s| s.id != self.shared.id); + lock(&self.shared.new_lanes).clear(); + } + + pub fn is_removed(&self) -> bool { + self.shared.removed.load(Ordering::Relaxed) + } +} + +/// The producing end of a source's input, for one capture thread. Pushing +/// never blocks or allocates (except a new channel count's downmix +/// weights); frames that do not fit in the ring are dropped and counted. +pub struct SourceInput { + ring: rtrb::Producer, + lane: Arc, + source: Arc, + rate: u32, + /// Downmix weights for more than two channels: (left, right) per + /// channel. + weights: Vec, +} + +impl std::fmt::Debug for SourceInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SourceInput") + .field("source", &self.source.id) + .field("rate", &self.rate) + .finish() + } +} + +/// Non-finite samples become silence. +#[inline] +fn clean(x: f32) -> f32 { + if x.is_finite() { x } else { 0.0 } +} + +/// Stereo weights for `channels` > 2 in WAVE order (FL FR FC LFE BL BR +/// FLC FRC ...): front left and right as they are, centre into both at +/// -3 dB, LFE dropped, the rest alternately left and right at -3 dB. Four +/// channels are taken as quad (FL FR BL BR). +fn downmix_weights(channels: usize, weights: &mut Vec) { + const H: f32 = std::f32::consts::FRAC_1_SQRT_2; + weights.clear(); + weights.extend([[1.0, 0.0], [0.0, 1.0]]); + let mut rest = 2; + if channels == 3 || channels >= 5 { + weights.push([H, H]); + rest = 3; + } + if channels >= 6 { + weights.push([0.0, 0.0]); + rest = 4; + } + for i in rest..channels { + weights.push(if (i - rest) % 2 == 0 { [H, 0.0] } else { [0.0, H] }); + } +} + +impl SourceInput { + pub fn rate(&self) -> u32 { + self.rate + } + + /// The source it feeds. + pub fn source_id(&self) -> u64 { + self.source.id + } + + /// The source was removed or the mixer is gone: stop capturing. + pub fn is_closed(&self) -> bool { + self.source.removed.load(Ordering::Relaxed) || self.ring.is_abandoned() + } + + /// Frames that fit now. + pub fn free(&self) -> usize { + self.ring.slots() + } + + /// Push interleaved samples with `channels` channels (mono is played on + /// both sides, more than two are downmixed). Returns the frames taken. + pub fn push(&mut self, samples: &[f32], channels: u16) -> usize { + match channels { + 0 => 0, + 1 => self.push_frames(samples.iter().map(|&s| [clean(s), clean(s)])), + 2 => self.push_frames(samples.chunks_exact(2).map(|f| [clean(f[0]), clean(f[1])])), + n => { + let n = usize::from(n); + if self.weights.len() != n { + downmix_weights(n, &mut self.weights); + } + let weights = std::mem::take(&mut self.weights); + let taken = self.push_frames(samples.chunks_exact(n).map(|f| { + let mut out = SILENCE; + for (s, w) in f.iter().zip(&weights) { + let s = clean(*s); + out[0] += s * w[0]; + out[1] += s * w[1]; + } + out + })); + self.weights = weights; + taken + } + } + } + + /// Push stereo frames. Returns the frames taken (the rest did not fit + /// and is counted as overflow). + pub fn push_frames(&mut self, frames: I) -> usize + where + I: IntoIterator, + I::IntoIter: ExactSizeIterator, + { + let frames = frames.into_iter(); + let len = frames.len(); + if len == 0 { + return 0; + } + self.lane.max_push.fetch_max(len, Ordering::Relaxed); + let n = len.min(self.ring.slots()); + let taken = match self.ring.write_chunk_uninit(n) { + Ok(chunk) => chunk.fill_from_iter(frames), + Err(_) => 0, + }; + if taken < len { + self.source.overflows.fetch_add((len - taken) as u64, Ordering::Relaxed); + } + taken + } + + /// Push `frames` frames of silence (e.g. a muted microphone). + pub fn push_silence(&mut self, frames: usize) -> usize { + self.push_frames(std::iter::repeat_n(SILENCE, frames)) + } +} + +/// Paces mixing on the monotonic clock: which blocks of `frames` frames are +/// due. Block `k` is due `k * frames / 48000` s after the start, computed +/// exactly (no drift). +pub struct BlockClock { + start: Instant, + frames: u64, + blocks: u64, + /// After falling this many blocks behind (a suspended machine), skip + /// ahead instead of mixing a burst. + max_behind: u64, +} + +impl BlockClock { + pub fn new(frames: usize) -> Self { + Self::starting_at(Instant::now(), frames) + } + + pub fn starting_at(start: Instant, frames: usize) -> Self { + Self { start, frames: frames.max(1) as u64, blocks: 0, max_behind: 25 } + } + + fn at(&self, block: u64) -> Instant { + let nanos = + u128::from(block) * u128::from(self.frames) * 1_000_000_000 / u128::from(MIX_RATE); + self.start + Duration::from_nanos(nanos as u64) + } + + /// When the next block is due. + pub fn next(&self) -> Instant { + self.at(self.blocks) + } + + /// The numbers of the blocks due at `now` (empty: wait until + /// [`next`](Self::next)). A block's number is the audio's position in + /// blocks since the start (e.g. its RTP time is `number * frames`). + /// After a long stall only the newest block is due; the numbers jump + /// ahead with the time. + pub fn due(&mut self, now: Instant) -> std::ops::Range { + if now < self.next() { + return self.blocks..self.blocks; + } + let elapsed = now.duration_since(self.start).as_nanos(); + let reached = + (elapsed * u128::from(MIX_RATE) / (u128::from(self.frames) * 1_000_000_000)) as u64 + 1; + let from = if reached - self.blocks > self.max_behind { reached - 1 } else { self.blocks }; + self.blocks = reached; + from..reached + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BLOCK: usize = 960; + + fn config() -> MixerConfig { + MixerConfig { max_block: BLOCK, latency: Duration::from_millis(40), ..Default::default() } + } + + /// Interleaved stereo DC. + fn dc(frames: usize, left: f32, right: f32) -> Vec { + (0..frames).flat_map(|_| [left, right]).collect() + } + + fn sine(frames: usize, start: usize, rate: u32, freq: f64, amplitude: f32) -> Vec { + (start..start + frames) + .flat_map(|i| { + let s = amplitude + * (2.0 * std::f64::consts::PI * freq * i as f64 / f64::from(rate)).sin() as f32; + [s, s] + }) + .collect() + } + + /// Goertzel magnitude of `freq` in the left channel, normalised so a + /// full sine of amplitude `a` gives about `a / 2`. + fn tone(samples: &[f32], freq: f64) -> f64 { + let left: Vec = samples.chunks_exact(2).map(|f| f64::from(f[0])).collect(); + let k = 2.0 * (2.0 * std::f64::consts::PI * freq / f64::from(MIX_RATE)).cos(); + let (mut s1, mut s2) = (0.0, 0.0); + for x in &left { + let s0 = x + k * s1 - s2; + s2 = s1; + s1 = s0; + } + (s1 * s1 + s2 * s2 - k * s1 * s2).max(0.0).sqrt() / left.len() as f64 + } + + /// Run `blocks` blocks: before each, `feed` pushes for that block. + fn run(mixer: &mut StreamMixer, blocks: usize, mut feed: impl FnMut(usize)) -> Vec { + let mut out = Vec::new(); + let mut block = vec![0.0; BLOCK * 2]; + for b in 0..blocks { + feed(b); + mixer.mix(&mut block); + out.extend_from_slice(&block); + } + out + } + + #[test] + fn sums_after_the_latency() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let mut a = handle.add_source("a").input(MIX_RATE); + let mut b = handle.add_source("b").input(MIX_RATE); + let out = run(&mut mixer, 20, |_| { + a.push(&dc(BLOCK, 0.25, 0.125), 2); + b.push(&dc(BLOCK, 0.25, -0.5), 2); + }); + // Silent while buffering (40 ms plus a block of headroom) ... + assert!(out[..2 * BLOCK].iter().all(|&s| s == 0.0)); + // ... then exact sums (past the fade-in). + let tail = &out[out.len() - 4 * BLOCK..]; + for f in tail.chunks_exact(2) { + assert_eq!(f, [0.5, -0.375]); + } + for s in handle.sources() { + assert_eq!(s.state(), SourceState::Playing); + assert_eq!(s.stats().underruns, 0); + assert!(s.stats().latency >= Duration::from_millis(40), "{:?}", s.stats()); + } + } + + #[test] + fn gains_and_mute_ramp_and_meter() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let source = handle.add_source("a"); + source.set_gain(0.5); + let mut input = source.input(MIX_RATE); + let mut feed = |_| { + input.push(&dc(BLOCK, 0.8, 0.8), 2); + }; + let out = run(&mut mixer, 10, &mut feed); + assert_eq!(out[out.len() - 2], 0.4); + let level = source.level(); + // The RMS meter rises over about 300 ms towards 0.4. + assert!((level.peak - 0.4).abs() < 1e-6 && (0.2..=0.4).contains(&level.rms), "{level:?}"); + assert!((handle.level().peak - 0.4).abs() < 1e-6); + + // A gain change ramps over one block, then holds. + source.set_gain(1.0); + let out = run(&mut mixer, 2, &mut feed); + let first: Vec = out[..BLOCK * 2].iter().step_by(2).copied().collect(); + assert!(first.windows(2).all(|w| w[1] >= w[0]), "monotonic ramp"); + assert!((first[0] - 0.4).abs() < 0.01 && (first[BLOCK - 1] - 0.8).abs() < 1e-5); + assert!(out[BLOCK * 2..].iter().all(|&s| s == 0.8)); + + // Muted: silent output, the source meter still reads. + source.set_muted(true); + let out = run(&mut mixer, 3, &mut feed); + assert!(out[BLOCK * 2..].iter().all(|&s| s == 0.0)); + assert!(source.level().peak > 0.79); + assert!(source.muted()); + source.set_muted(false); + let out = run(&mut mixer, 2, &mut feed); + assert_eq!(out[out.len() - 1], 0.8); + } + + #[test] + fn master_gain_and_limiter() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let mut a = handle.add_source("a").input(MIX_RATE); + let mut b = handle.add_source("b").input(MIX_RATE); + // Below the threshold nothing changes. + let out = run(&mut mixer, 8, |b_| { + a.push(&sine(BLOCK, b_ * BLOCK, MIX_RATE, 440.0, 0.4), 2); + b.push(&sine(BLOCK, b_ * BLOCK, MIX_RATE, 440.0, 0.4), 2); + }); + assert!(out.iter().all(|s| s.abs() <= 0.8 + 1e-6)); + assert_eq!(handle.limiter_gain(), 1.0); + // 1.6 peak: limited below full scale, still loud and in tune. + let out = run(&mut mixer, 20, |b_| { + a.push(&sine(BLOCK, (b_ + 8) * BLOCK, MIX_RATE, 440.0, 0.8), 2); + b.push(&sine(BLOCK, (b_ + 8) * BLOCK, MIX_RATE, 440.0, 0.8), 2); + }); + let peak = out.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(peak <= 1.0, "{peak}"); + assert!(peak > 0.85, "{peak}"); + assert!(handle.limiter_gain() < 0.7, "{}", handle.limiter_gain()); + let tail = &out[out.len() - 8 * BLOCK..]; + assert!(tone(tail, 440.0) > 0.3, "{}", tone(tail, 440.0)); + // The master gain applies before the limiter. + handle.set_gain(0.25); + let out = run(&mut mixer, 6, |b_| { + a.push(&dc(BLOCK, 0.4, 0.4), 2); + b.push(&dc(BLOCK, 0.4, 0.4), 2); + let _ = b_; + }); + assert!((out[out.len() - 1] - 0.2).abs() < 1e-6, "{}", out[out.len() - 1]); + assert!(soft_clip(10.0, 0.891) <= 1.0 && soft_clip(-10.0, 0.891) >= -1.0); + assert_eq!(soft_clip(0.5, 0.891), 0.5); + } + + #[test] + fn resamples_and_maps_channels() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + // 44.1 kHz mono 1 kHz tone, 10 ms pushes. + let mut mono = handle.add_source("mono").input(44_100); + let mut n = 0; + let out = run(&mut mixer, 100, |_| { + for _ in 0..2 { + let block: Vec = (n..n + 441) + .map(|i| { + 0.5 * (2.0 * std::f64::consts::PI * 1000.0 * i as f64 / 44_100.0).sin() + as f32 + }) + .collect(); + n += 441; + mono.push(&block, 1); + } + }); + let tail = &out[out.len() - 50 * BLOCK * 2..]; + let at = tone(tail, 1000.0); + assert!(at > 0.2, "{at}"); + assert!(tone(tail, 1100.0) < at / 50.0); + // Both channels. + assert!(tail.chunks_exact(2).all(|f| f[0] == f[1])); + // Output keeps pace with input: nothing ran dry or piled up. + let stats = handle.sources()[0].stats(); + assert_eq!((stats.underruns, stats.skipped, stats.overflows), (0, 0, 0), "{stats:?}"); + + // 5.1 downmix: centre into both sides, LFE dropped. + let mut weights = Vec::new(); + downmix_weights(6, &mut weights); + assert_eq!(weights.len(), 6); + assert_eq!(weights[3], [0.0, 0.0]); + assert!(weights[2][0] > 0.7 && weights[2][1] > 0.7); + assert_eq!((weights[4][1], weights[5][0]), (0.0, 0.0)); + let mut mixer = StreamMixer::new(config()); + let mut six = mixer.handle().add_source("5.1").input(MIX_RATE); + let frame = [0.1, 0.2, 0.0, 1.0, 0.0, 0.0]; + let out = run(&mut mixer, 6, |_| { + let samples: Vec = frame.iter().copied().cycle().take(BLOCK * 6).collect(); + six.push(&samples, 6); + }); + assert_eq!(&out[out.len() - 2..], [0.1, 0.2]); + } + + #[test] + fn a_stalled_or_ended_source_does_not_hold_up_others() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let steady = handle.add_source("steady"); + let flaky = handle.add_source("flaky"); + let mut a = steady.input(MIX_RATE); + let mut b = flaky.input(MIX_RATE); + let mut feed = |block: usize, flaky_on: bool| { + a.push(&dc(BLOCK, 0.25, 0.25), 2); + if flaky_on { + b.push(&dc(BLOCK, 0.5, 0.5), 2); + } + let _ = block; + }; + let out = run(&mut mixer, 10, |b_| feed(b_, true)); + assert_eq!(out[out.len() - 1], 0.75); + // The flaky source stops: the steady one goes on alone. + let out = run(&mut mixer, 10, |b_| feed(b_, false)); + assert_eq!(out[out.len() - 1], 0.25); + assert_eq!(flaky.state(), SourceState::Idle); + assert_eq!(steady.state(), SourceState::Playing); + assert_eq!(steady.stats().underruns, 0); + // It comes back after buffering its latency. + let out = run(&mut mixer, 10, |b_| feed(b_, true)); + assert_eq!(out[out.len() - 1], 0.75); + assert_eq!(flaky.stats().underruns, 1); + // Its capture ends: what was buffered plays out, then it is ended. + drop(b); + let out = run(&mut mixer, 10, |_| { + a.push(&dc(BLOCK, 0.25, 0.25), 2); + }); + assert_eq!(out[out.len() - 1], 0.25); + assert_eq!(flaky.state(), SourceState::Ended); + assert_eq!(flaky.stats().inputs, 0); + assert_eq!(flaky.stats().underruns, 1, "an end is not an underrun"); + } + + #[test] + fn sources_come_and_go_while_mixing() { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let a = handle.add_source("a"); + let mut ia = a.input(MIX_RATE); + let out = run(&mut mixer, 6, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + }); + assert_eq!(out[out.len() - 1], 0.1); + // Any number of sources, added live. + let many: Vec<(SourceHandle, SourceInput)> = (0..40) + .map(|i| { + let s = handle.add_source(format!("s{i}")); + s.set_gain(0.5); + let input = s.input(if i % 2 == 0 { MIX_RATE } else { 44_100 }); + (s, input) + }) + .collect(); + let mut many: Vec<_> = many; + let out = run(&mut mixer, 10, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + for (_, input) in many.iter_mut() { + let frames = if input.rate() == MIX_RATE { BLOCK } else { 882 }; + input.push(&dc(frames, 0.01, 0.01), 2); + } + }); + let expected = 0.1 + 40.0 * 0.005; + assert!((out[out.len() - 1] - expected).abs() < 1e-4, "{}", out[out.len() - 1]); + assert_eq!(handle.sources().len(), 41); + // Removed ones leave at the next block; their inputs see it. + for (s, _) in &many { + s.remove(); + } + assert!(many.iter().all(|(_, input)| input.is_closed())); + let out = run(&mut mixer, 2, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + }); + assert_eq!(out[out.len() - 1], 0.1); + assert_eq!(handle.sources().len(), 1); + // A second input on a live source adds to it. + let mut ib = a.input(MIX_RATE); + let out = run(&mut mixer, 8, |_| { + ia.push(&dc(BLOCK, 0.1, 0.1), 2); + ib.push(&dc(BLOCK, 0.2, 0.2), 2); + }); + assert!((out[out.len() - 1] - 0.3).abs() < 1e-6); + assert_eq!(a.stats().inputs, 2); + assert!(handle.source(a.id()).is_some()); + drop(mixer); + assert!(ia.is_closed()); + } + + #[test] + fn drift_is_absorbed() { + // A source whose clock runs 0.1 % fast and one 0.1 % slow, for five + // simulated minutes: no skips, no underruns, and the latency stays + // where it settled, give or take the correction band. + for ppm in [1000.0, -1000.0] { + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let source = handle.add_source("drift"); + let mut input = source.input(MIX_RATE); + let per_block = BLOCK as f64 * (1.0 + ppm / 1e6); + let (mut owed, mut phase) = (0.0, 0usize); + let mut block = vec![0.0; BLOCK * 2]; + let mut settled = None; + let mut worst = 0.0f64; + for b in 0..15_000 { + owed += per_block; + let frames = owed as usize; + owed -= frames as f64; + input.push(&sine(frames, phase, MIX_RATE, 300.0, 0.3), 2); + phase += frames; + mixer.mix(&mut block); + let latency = source.stats().latency.as_secs_f64(); + if b == 200 { + settled = Some(latency); + } + if let Some(settled) = settled { + worst = worst.max((latency - settled).abs()); + } + } + let stats = source.stats(); + assert_eq!( + (stats.underruns, stats.skipped, stats.overflows), + (0, 0, 0), + "{ppm}: {stats:?}" + ); + // Uncorrected, 0.1 % is 300 ms after five minutes. + assert!(worst < 0.015, "{ppm}: latency moved by {worst} s"); + assert!(tone(&block, 300.0) > 0.1); + } + } + + #[test] + fn bursty_input_gets_more_latency() { + // 8192-frame bursts every 170 ms (a power-saving PipeWire quantum). + let mut mixer = StreamMixer::new(config()); + let handle = mixer.handle(); + let source = handle.add_source("bursty"); + let mut input = source.input(MIX_RATE); + let mut owed = 0usize; + let mut phase = 0; + let mut block = vec![0.0; BLOCK * 2]; + for _ in 0..500 { + owed += BLOCK; + if owed >= 8192 { + input.push(&sine(8192, phase, MIX_RATE, 500.0, 0.3), 2); + phase += 8192; + owed -= 8192; + } + mixer.mix(&mut block); + } + let stats = source.stats(); + assert!(stats.latency > Duration::from_millis(170), "{stats:?}"); + // At most the first burst ran short before the latency adapted. + assert!(stats.underruns <= 1, "{stats:?}"); + assert_eq!(source.state(), SourceState::Playing); + } + + #[test] + fn nan_and_short_calls() { + let mut mixer = StreamMixer::new(config()); + let mut input = mixer.handle().add_source("x").input(MIX_RATE); + let mut samples = dc(BLOCK * 4, 0.5, 0.5); + samples[10] = f32::NAN; + samples[11] = f32::INFINITY; + input.push(&samples, 2); + // Odd lengths and blocks longer than `max_block` are fine. + let mut out = vec![1.0; BLOCK * 3 + 1]; + mixer.mix(&mut out); + assert!(out.iter().all(|s| s.is_finite())); + assert_eq!(out[out.len() - 1], 0.0); + assert_eq!(input.push(&[], 2), 0); + assert_eq!(input.push(&[0.1], 0), 0); + } + + #[test] + fn cubic_is_exact_on_samples_and_lines() { + assert_eq!(cubic(0.3, -0.7, 0.2, 0.9, 0.0), -0.7); + // A straight line is reproduced. + let v = cubic(0.0, 1.0, 2.0, 3.0, 0.25); + assert!((v - 1.25).abs() < 1e-6, "{v}"); + } + + #[test] + fn block_clock_paces_and_skips_ahead() { + let start = Instant::now(); + let mut clock = BlockClock::starting_at(start, 960); + assert_eq!(clock.due(start), 0..1); + assert!(clock.due(start).is_empty()); + assert_eq!(clock.next(), start + Duration::from_millis(20)); + assert_eq!(clock.due(start + Duration::from_millis(59)), 1..3); + assert_eq!(clock.due(start + Duration::from_millis(60)), 3..4); + // Exact over a long run: 441 frames is 9.1875 ms. + let mut clock = BlockClock::starting_at(start, 441); + let mut total = 0; + for ms in 1..=10_000u64 { + let due = clock.due(start + Duration::from_millis(ms)); + total += due.end - due.start; + } + assert_eq!(total, 10_000 * 48 / 441 + 1); + // After a long stall only the newest block is due, numbered by the + // time. + let mut clock = BlockClock::starting_at(start, 960); + clock.due(start); + assert_eq!(clock.due(start + Duration::from_secs(10)), 500..501); + assert_eq!(clock.due(start + Duration::from_millis(10_020)), 501..502); + assert!(to_db(1.0).abs() < 1e-6 && to_db(0.0) == -120.0); + } +} diff --git a/crates/voelin-media/tests/mix_alloc.rs b/crates/voelin-media/tests/mix_alloc.rs new file mode 100644 index 0000000..2f6d314 --- /dev/null +++ b/crates/voelin-media/tests/mix_alloc.rs @@ -0,0 +1,122 @@ +//! The stream mixer allocates nothing per block: pushing into inputs and +//! mixing, with resampling, downmixing, drift correction, gain and mute +//! changes, stalls and restarts, counted with a global allocator that +//! counts only on the thread that asks. +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; + +use voelin_media::mix::{MixerConfig, StreamMixer}; + +thread_local! { + static COUNTING: Cell = const { Cell::new(false) }; + static COUNT: Cell = const { Cell::new(0) }; +} + +fn count() { + // `try_with`: never panics, also while the thread is torn down; const + // thread locals without destructors never allocate. + let _ = COUNTING.try_with(|on| { + if on.get() { + let _ = COUNT.try_with(|n| n.set(n.get() + 1)); + } + }); +} + +struct Counting; + +// SAFETY: every method forwards to `System` with the caller's arguments +// unchanged, so `System`'s guarantees hold; counting touches only +// thread-local cells and never allocates. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged (see above). + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(); + // SAFETY: forwarded unchanged. + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: forwarded unchanged. + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static ALLOCATOR: Counting = Counting; + +/// Allocations `f` makes on this thread. +fn allocations(f: impl FnOnce()) -> u64 { + COUNT.with(|n| n.set(0)); + COUNTING.with(|on| on.set(true)); + f(); + COUNTING.with(|on| on.set(false)); + COUNT.with(Cell::get) +} + +#[test] +fn mixing_allocates_nothing_per_block() { + const BLOCK: usize = 960; + // The counter works. + assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1); + let mut mixer = StreamMixer::new(MixerConfig::default()); + let handle = mixer.handle(); + // 48 kHz stereo, 44.1 kHz mono, 6 channels, and one that stalls. + let stereo = handle.add_source("stereo"); + let mono = handle.add_source("mono"); + let surround = handle.add_source("5.1"); + let flaky = handle.add_source("flaky"); + let mut inputs = [stereo.input(48_000), mono.input(44_100), surround.input(48_000)]; + let mut flaky_input = flaky.input(48_000); + let stereo_block: Vec = (0..BLOCK * 2).map(|i| (i as f32 * 0.01).sin() * 0.3).collect(); + let mono_block: Vec = (0..882).map(|i| (i as f32 * 0.02).sin() * 0.3).collect(); + let six_block: Vec = (0..BLOCK * 6).map(|i| (i as f32 * 0.03).sin() * 0.3).collect(); + let mut out = vec![0.0f32; BLOCK * 2]; + // Slightly fast clock on one input so the drift correction runs. + let mut owed = 0.0f64; + let mut step = |block: usize, out: &mut Vec| { + inputs[0].push(&stereo_block, 2); + inputs[1].push(&mono_block, 1); + owed += BLOCK as f64 * 1.004; + let frames = owed as usize; + owed -= frames as f64; + inputs[2].push(&six_block[..frames.min(BLOCK) * 6], 6); + // On for a second, off for a second. + if (block / 50).is_multiple_of(2) { + flaky_input.push(&stereo_block, 2); + } + match block % 7 { + 0 => stereo.set_gain(0.5 + (block % 3) as f32 * 0.25), + 3 => mono.set_muted(block.is_multiple_of(2)), + 5 => handle.set_gain(0.9), + _ => {} + } + mixer.mix(out); + let _ = (stereo.level(), handle.level(), surround.state(), handle.limiter_gain()); + }; + // Warm up: sources adopted, inputs playing, latencies settled. + for block in 0..300 { + step(block, &mut out); + } + let count = allocations(|| { + for block in 300..1300 { + step(block, &mut out); + } + }); + assert_eq!(count, 0, "allocations in 1000 blocks"); + // The flaky source went idle and came back in the measured part. + assert!(flaky.stats().underruns > 0); + assert!(out.iter().any(|s| *s != 0.0)); +} diff --git a/crates/voelin-media/tests/pipewire_apps.rs b/crates/voelin-media/tests/pipewire_apps.rs new file mode 100644 index 0000000..da12d5a --- /dev/null +++ b/crates/voelin-media/tests/pipewire_apps.rs @@ -0,0 +1,427 @@ +//! Application audio capture against a private PipeWire and WirePlumber: +//! two child processes play tones (1000 Hz as `voelin-tone-a`, 1500 Hz as +//! `voelin-tone-b`) and this process plays 700 Hz, like our voice playback. +//! "Desktop audio without us" must hear both children and not us, a +//! capture of one application only that one, and a child started later +//! is picked up while capturing. +//! +//! Needs `pipewire`, `wireplumber` and `dbus-daemon` (Debian/Ubuntu: +//! `pipewire-bin wireplumber dbus-daemon`); skipped without them. The +//! daemons run in a temporary `XDG_RUNTIME_DIR` and never touch the +//! user's session. +#![cfg(all(target_os = "linux", feature = "pipewire"))] + +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use pipewire as pw; +use voelin_media::capture::pipewire_links::LinkManager; +use voelin_media::capture::playback::{AppMatch, PlaybackFilter, SourceCapture}; +use voelin_media::mix::{BlockClock, MixerConfig, StreamMixer}; + +/// Set in a child: play this frequency until killed. +const TONE_ENV: &str = "VOELIN_TEST_TONE"; +const OURS: f64 = 700.0; +const TONE_A: f64 = 1000.0; +const TONE_B: f64 = 1500.0; +const TONE_C: f64 = 2200.0; + +fn find(binary: &str) -> Option { + std::env::var_os("PATH")? + .to_str()? + .split(':') + .map(|dir| Path::new(dir).join(binary)) + .find(|p| p.is_file()) +} + +/// Play `freq` Hz (0.3, stereo, 48 kHz) as application `name` until `stop`. +fn play(remote: Option, freq: f64, name: String, stop: Arc) { + pw::init(); + let mainloop = pw::main_loop::MainLoopRc::new(None).unwrap(); + let context = pw::context::ContextRc::new(&mainloop, None).unwrap(); + let mut props = pw::properties::PropertiesBox::new(); + if let Some(remote) = remote { + props.insert(*pw::keys::REMOTE_NAME, remote); + } + props.insert(*pw::keys::APP_NAME, name.as_str()); + let core = context.connect_rc(Some(props)).unwrap(); + // End with the daemon. + let _errors = core + .add_listener_local() + .error({ + let mainloop = mainloop.downgrade(); + move |id, _, _, _| { + if id == pw::core::PW_ID_CORE + && let Some(mainloop) = mainloop.upgrade() + { + mainloop.quit(); + } + } + }) + .register(); + let mut props = pw::properties::PropertiesBox::new(); + props.insert(*pw::keys::MEDIA_TYPE, "Audio"); + props.insert(*pw::keys::MEDIA_CATEGORY, "Playback"); + props.insert(*pw::keys::MEDIA_ROLE, "Music"); + props.insert(*pw::keys::APP_NAME, name.as_str()); + props.insert(*pw::keys::NODE_NAME, name.as_str()); + let stream = pw::stream::StreamRc::new(core.clone(), &name, props).unwrap(); + let _listener = stream + .add_local_listener_with_user_data(0.0f64) + .process(move |stream, phase| { + let Some(mut buffer) = stream.dequeue_buffer() else { return }; + let data = &mut buffer.datas_mut()[0]; + let frames = match data.data() { + Some(bytes) => { + let frames = bytes.len() / 8; + for frame in bytes.chunks_exact_mut(8) { + *phase += std::f64::consts::TAU * freq / 48_000.0; + let s = (0.3 * phase.sin()) as f32; + frame[..4].copy_from_slice(&s.to_le_bytes()); + frame[4..].copy_from_slice(&s.to_le_bytes()); + } + frames + } + None => 0, + }; + let chunk = data.chunk_mut(); + *chunk.offset_mut() = 0; + *chunk.stride_mut() = 8; + *chunk.size_mut() = (frames * 8) as u32; + }) + .register() + .unwrap(); + let mut info = pw::spa::param::audio::AudioInfoRaw::new(); + info.set_format(pw::spa::param::audio::AudioFormat::F32LE); + info.set_rate(48_000); + info.set_channels(2); + let mut position = [0; pw::spa::param::audio::MAX_CHANNELS]; + position[0] = pw::spa::sys::SPA_AUDIO_CHANNEL_FL; + position[1] = pw::spa::sys::SPA_AUDIO_CHANNEL_FR; + info.set_position(position); + let format: Vec = pw::spa::pod::serialize::PodSerializer::serialize( + std::io::Cursor::new(Vec::new()), + &pw::spa::pod::Value::Object(pw::spa::pod::Object { + type_: pw::spa::sys::SPA_TYPE_OBJECT_Format, + id: pw::spa::sys::SPA_PARAM_EnumFormat, + properties: info.into(), + }), + ) + .unwrap() + .0 + .into_inner(); + stream + .connect( + pw::spa::utils::Direction::Output, + None, + pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS, + &mut [pw::spa::pod::Pod::from_bytes(&format).unwrap()], + ) + .unwrap(); + let timer = mainloop.loop_().add_timer({ + let mainloop = mainloop.downgrade(); + move |_| { + if stop.load(Ordering::Relaxed) + && let Some(mainloop) = mainloop.upgrade() + { + mainloop.quit(); + } + } + }); + timer + .update_timer(Some(Duration::from_millis(50)), Some(Duration::from_millis(50))) + .into_result() + .unwrap(); + mainloop.run(); +} + +/// The child side: `cargo test` runs this test in the child process, where +/// `VOELIN_TEST_TONE` says what to play. +#[test] +fn tone_child() { + let Ok(spec) = std::env::var(TONE_ENV) else { return }; + let (freq, name) = spec.split_once(':').unwrap(); + play(None, freq.parse().unwrap(), name.to_owned(), Arc::new(AtomicBool::new(false))); +} + +/// Processes killed on drop. +struct Daemons { + children: Vec, + dir: PathBuf, +} + +impl Drop for Daemons { + fn drop(&mut self) { + for child in self.children.iter_mut().rev() { + let _ = child.kill(); + let _ = child.wait(); + } + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +impl Daemons { + fn start() -> Option { + let (pipewire, wireplumber, dbus) = + (find("pipewire")?, find("wireplumber")?, find("dbus-daemon")?); + // Short: the socket path must fit in 108 bytes. + let dir = PathBuf::from(format!("/tmp/voelin-pw-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut daemons = Daemons { children: Vec::new(), dir: dir.clone() }; + let mut bus = Command::new(dbus) + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let mut address = String::new(); + BufReader::new(bus.stdout.take().unwrap()).read_line(&mut address).ok()?; + daemons.children.push(bus); + let env = |command: &mut Command| { + command + .env("XDG_RUNTIME_DIR", &dir) + .env("XDG_CONFIG_HOME", dir.join("config")) + .env("XDG_STATE_HOME", dir.join("state")) + .env("DBUS_SESSION_BUS_ADDRESS", address.trim()) + .env_remove("PIPEWIRE_REMOTE") + .stdout(Stdio::null()) + .stderr(Stdio::null()); + }; + // A sink, as every desktop has one (WirePlumber sets up the ports of + // playback streams once they have somewhere to go). + let conf = dir.join("config/pipewire/pipewire.conf.d"); + std::fs::create_dir_all(&conf).unwrap(); + std::fs::write( + conf.join("voelin-test-sink.conf"), + "context.objects = [ { factory = adapter args = { factory.name = support.null-audio-sink \ + node.name = voelin-test-sink media.class = Audio/Sink audio.position = [ FL FR ] } } ]\n", + ) + .unwrap(); + let mut command = Command::new(pipewire); + env(&mut command); + daemons.children.push(command.spawn().ok()?); + let socket = dir.join("pipewire-0"); + let deadline = Instant::now() + Duration::from_secs(5); + while !socket.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + let mut command = Command::new(wireplumber); + env(&mut command); + daemons.children.push(command.spawn().ok()?); + socket.exists().then_some(daemons) + } + + fn socket(&self) -> PathBuf { + self.dir.join("pipewire-0") + } + + /// Another process playing `freq` as `name`: this test binary, started + /// through a shell that exits right away, so the player is not our + /// descendant (our own process tree is excluded from desktop audio). + fn tone_player(&self, freq: f64, name: &str) -> Player { + let out = Command::new("sh") + .args(["-c", "\"$0\" --exact tone_child --test-threads=1 >/dev/null 2>&1 & echo $!"]) + .arg(std::env::current_exe().unwrap()) + .env(TONE_ENV, format!("{freq}:{name}")) + .env("XDG_RUNTIME_DIR", &self.dir) + .env_remove("PIPEWIRE_REMOTE") + .stderr(Stdio::null()) + .output() + .unwrap(); + let pid = String::from_utf8_lossy(&out.stdout).trim().parse().expect("player pid"); + Player { pid } + } +} + +/// A tone player process; killed on drop. +struct Player { + pid: u32, +} + +impl Player { + fn kill(&mut self) { + if self.pid != 0 { + let _ = Command::new("kill").arg(self.pid.to_string()).status(); + self.pid = 0; + } + } +} + +impl Drop for Player { + fn drop(&mut self) { + self.kill(); + } +} + +/// Print the graph (for a failing test), if the PipeWire tools are there. +fn dump(dir: &Path) { + for (tool, args) in [("pw-link", &["-l"][..]), ("pw-cli", &["ls"][..])] { + if let Some(tool) = find(tool) + && let Ok(out) = Command::new(tool).args(args).env("XDG_RUNTIME_DIR", dir).output() + { + eprintln!("{}", String::from_utf8_lossy(&out.stdout)); + } + } +} + +/// Goertzel magnitude of `freq` in the left channel (about amplitude / 2). +fn tone(samples: &[f32], freq: f64) -> f64 { + let k = 2.0 * (std::f64::consts::TAU * freq / 48_000.0).cos(); + let (mut s1, mut s2) = (0.0, 0.0); + let mut n = 0; + for frame in samples.chunks_exact(2) { + let s0 = f64::from(frame[0]) + k * s1 - s2; + s2 = s1; + s1 = s0; + n += 1; + } + (s1 * s1 + s2 * s2 - k * s1 * s2).max(0.0).sqrt() / f64::from(n.max(1)) +} + +/// A mixer with one capture, mixed in real time on a thread; keeps the last +/// second. +struct Listener { + stop: Arc, + last: Arc>>, + thread: Option>, + _capture: Box, +} + +impl Listener { + fn new(manager: &Arc, filter: PlaybackFilter) -> Self { + let mut mixer = StreamMixer::new(MixerConfig::default()); + let source = mixer.handle().add_source(format!("{filter:?}")); + let capture = manager.capture(&filter, &source).expect("capture"); + let stop = Arc::new(AtomicBool::new(false)); + let last = Arc::new(std::sync::Mutex::new(Vec::new())); + let thread = std::thread::spawn({ + let (stop, last) = (stop.clone(), last.clone()); + move || { + let mut clock = BlockClock::new(960); + let mut block = vec![0.0f32; 1920]; + while !stop.load(Ordering::Relaxed) { + for _ in clock.due(Instant::now()) { + mixer.mix(&mut block); + let mut last = last.lock().unwrap(); + last.extend_from_slice(&block); + let excess = last.len().saturating_sub(96_000); + last.drain(..excess); + } + std::thread::sleep(Duration::from_millis(5)); + } + } + }); + Self { stop, last, thread: Some(thread), _capture: capture } + } + + fn levels(&self, freqs: &[f64]) -> Vec { + let last = self.last.lock().unwrap(); + freqs.iter().map(|&f| tone(&last, f)).collect() + } + + /// Wait until `heard` are all above 0.05 and `silent` below 0.005. + fn expect(&self, heard: &[f64], silent: &[f64], what: &str) { + self.expect_in(heard, silent, what, None); + } + + fn expect_in(&self, heard: &[f64], silent: &[f64], what: &str, dir: Option<&Path>) { + let deadline = Instant::now() + Duration::from_secs(15); + loop { + let loud = self.levels(heard); + let quiet = self.levels(silent); + if loud.iter().all(|&l| l > 0.05) && quiet.iter().all(|&l| l < 0.005) { + return; + } + if Instant::now() >= deadline + && let Some(dir) = dir + { + dump(dir); + } + assert!( + Instant::now() < deadline, + "{what}: {heard:?} at {loud:?} (want > 0.05), {silent:?} at {quiet:?} (want < 0.005)" + ); + std::thread::sleep(Duration::from_millis(200)); + } + } +} + +impl Drop for Listener { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +#[test] +fn desktop_without_self_and_single_apps() { + if std::env::var_os(TONE_ENV).is_some() { + return; + } + let _ = tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .with_test_writer() + .try_init(); + let Some(daemons) = Daemons::start() else { + eprintln!("skipped: needs pipewire, wireplumber and dbus-daemon"); + return; + }; + let remote = daemons.socket().to_string_lossy().into_owned(); + // Our own playback, as the voice audio would be. + let stop_ours = Arc::new(AtomicBool::new(false)); + let ours = std::thread::spawn({ + let (remote, stop) = (remote.clone(), stop_ours.clone()); + move || play(Some(remote), OURS, "voelin-own-voices".into(), stop) + }); + let mut a = daemons.tone_player(TONE_A, "voelin-tone-a"); + let b = daemons.tone_player(TONE_B, "voelin-tone-b"); + + let manager = Arc::new(LinkManager::connect(Some(&daemons.socket())).expect("connect")); + let desktop = Listener::new(&manager, PlaybackFilter::AllButSelf); + let by_name = + Listener::new(&manager, PlaybackFilter::App(AppMatch::Name("VOELIN-TONE-A".into()))); + let by_pid = Listener::new(&manager, PlaybackFilter::App(AppMatch::Pid(b.pid))); + desktop.expect_in(&[TONE_A, TONE_B], &[OURS], "desktop without us", Some(&daemons.dir)); + by_name.expect(&[TONE_A], &[TONE_B, OURS], "app by name"); + by_pid.expect(&[TONE_B], &[TONE_A, OURS], "app by pid"); + + // The picker's list: both children with their pids, not us. + let mut apps = manager.apps(); + let list = apps.borrow_and_update().clone(); + let names: Vec<&str> = list.iter().map(|a| a.name.as_str()).collect(); + assert!(names.contains(&"voelin-tone-a") && names.contains(&"voelin-tone-b"), "{list:?}"); + assert!(!names.contains(&"voelin-own-voices"), "{list:?}"); + let entry = list.iter().find(|a| a.name == "voelin-tone-b").unwrap(); + assert_eq!(entry.pid, Some(b.pid)); + assert!(entry.streams >= 1); + + // A new application is picked up live; one that quits is dropped. + let c = daemons.tone_player(TONE_C, "voelin-tone-c"); + desktop.expect(&[TONE_A, TONE_B, TONE_C], &[OURS], "desktop after a new app"); + by_name.expect(&[TONE_A], &[TONE_C], "app by name after a new app"); + a.kill(); + desktop.expect(&[TONE_B, TONE_C], &[TONE_A, OURS], "desktop after an app quit"); + let deadline = Instant::now() + Duration::from_secs(10); + while apps.borrow_and_update().iter().any(|a| a.name == "voelin-tone-a") { + assert!(Instant::now() < deadline, "voelin-tone-a still listed"); + std::thread::sleep(Duration::from_millis(100)); + } + // Restarted, the application is matched by name again. + let a = daemons.tone_player(TONE_A, "voelin-tone-a"); + by_name.expect(&[TONE_A], &[TONE_B, TONE_C, OURS], "app by name after a restart"); + + drop((desktop, by_name, by_pid)); + drop((a, b, c)); + stop_ours.store(true, Ordering::Relaxed); + let _ = ours.join(); + drop(manager); + drop(daemons); +} diff --git a/crates/voelin-media/tests/x11_capture.rs b/crates/voelin-media/tests/x11_capture.rs index fd01de2..3ba9940 100644 --- a/crates/voelin-media/tests/x11_capture.rs +++ b/crates/voelin-media/tests/x11_capture.rs @@ -8,7 +8,7 @@ use std::time::Duration; -use voelin_media::capture::x11::X11Capture; +use voelin_media::capture::x11::{self, X11Capture}; use voelin_media::{ CaptureOptions, Codec, Codecs, EncoderConfig, FrameReceiver, ScreenCapture, SourceId, VideoFrame, convert, @@ -168,6 +168,23 @@ async fn x11_capture_end_to_end() { assert_eq!(window.id, SourceId::Window(scene.test_window.into())); assert_eq!((window.width, window.height), (u32::from(WW), u32::from(WH))); + // The window's process, for capturing its audio. + let window_id = u64::from(scene.test_window); + assert_eq!(x11::window_pid(Some(&display), window_id), None, "no _NET_WM_PID yet"); + let net_wm_pid = scene.conn.intern_atom(false, b"_NET_WM_PID").unwrap().reply().unwrap().atom; + scene + .conn + .change_property32( + PropMode::REPLACE, + scene.test_window, + net_wm_pid, + AtomEnum::CARDINAL, + &[std::process::id()], + ) + .unwrap(); + scene.conn.sync().unwrap(); + assert_eq!(x11::window_pid(Some(&display), window_id), Some(std::process::id())); + // Same pixels through MIT-SHM and through GetImage. check_monitor(&mut capture, &scene).await; let mut get_image = X11Capture::with_display(display.clone()).use_shm(false); diff --git a/crates/voelin-store/src/chat.rs b/crates/voelin-store/src/chat.rs new file mode 100644 index 0000000..c7e6b01 --- /dev/null +++ b/crates/voelin-store/src/chat.rs @@ -0,0 +1,987 @@ +//! Chat history: the messages this device saw or fetched from a gateway, +//! per server and chat. +//! +//! Every message is one row, whatever delivered it: the voice connection, +//! a gateway (with its stable message id, [`StoredMessage::remote_id`]), a +//! query relay, or this device when it sent the message. The same message +//! often arrives twice (live over voice and again from the gateway); +//! [`Store::write_messages`] merges such copies (see [`WriteOutcome`]): +//! +//! - a gateway copy matches the row with its gateway id, else a row without +//! one of the same message; +//! - otherwise two copies are the same message when they come from different +//! sources, their text is equal once a relay prefix (`[nick] `) is removed, +//! they were stamped at most `tolerance_ms` apart, and they have the same +//! author: the same unique id, or the relay prefix of one names the author +//! of the other, or (without both unique ids) the same nickname. +//! +//! Pages are by time: `(ts_ms, id)` orders a chat ([`PageQuery`]). A +//! [`ChatCursor`] remembers how far a chat is synced with a gateway. + +use rusqlite::{OptionalExtension, Row, Transaction, params}; +use serde::{Deserialize, Serialize}; + +use crate::{Result, Store}; + +/// Where a chat message was posted. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ChatTarget { + Server, + Channel(u64), + /// Private chat with the client of this unique id. + Private(String), +} + +impl ChatTarget { + /// The form stored in the database: `server`, `channel/`, `private/`. + pub fn key(&self) -> String { + match self { + ChatTarget::Server => "server".into(), + ChatTarget::Channel(cid) => format!("channel/{cid}"), + ChatTarget::Private(uid) => format!("private/{uid}"), + } + } + + /// Parse [`Self::key`]; unknown forms are the server chat. + pub fn from_key(key: &str) -> Self { + match key.split_once('/') { + Some(("channel", cid)) => { + cid.parse().map(ChatTarget::Channel).unwrap_or(ChatTarget::Server) + } + Some(("private", uid)) => ChatTarget::Private(uid.to_owned()), + _ => ChatTarget::Server, + } + } +} + +/// What delivered a message first. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MessageSource { + /// Our own voice connection. + Voice, + /// A `tsgw` gateway (live or from its history). + Gateway, + /// A query relay with the user's own credentials. + Query, + /// This device: sent by the user, or stored before sources were recorded. + #[default] + Local, +} + +impl MessageSource { + pub fn as_str(self) -> &'static str { + match self { + MessageSource::Voice => "voice", + MessageSource::Gateway => "gateway", + MessageSource::Query => "query", + MessageSource::Local => "local", + } + } + + pub fn parse(s: &str) -> Self { + match s { + "voice" => MessageSource::Voice, + "gateway" => MessageSource::Gateway, + "query" => MessageSource::Query, + _ => MessageSource::Local, + } + } + + /// Bit in the `seen_by` column. + fn bit(self) -> i64 { + match self { + MessageSource::Voice => 1, + MessageSource::Gateway => 2, + MessageSource::Query => 4, + MessageSource::Local => 8, + } + } +} + +/// Whether a row is known to the gateway. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum SyncState { + /// Only seen by this device (no gateway copy yet). + #[default] + Local, + /// The gateway has it: [`StoredMessage::remote_id`] is set. + Synced, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +/// One emoji on a message, as the gateway counts it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Reaction { + pub emoji: String, + pub count: u32, + /// The user reacted with this emoji. + #[serde(default, skip_serializing_if = "is_false")] + pub me: bool, +} + +/// What a gateway says about a message. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RemoteInfo { + /// The gateway's message id. + pub id: i64, + /// Revision of the last change at the gateway. + pub rev: i64, + pub topic_id: Option, + pub reactions: Vec, + pub pinned: bool, +} + +/// A message to store. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NewMessage { + pub server_uid: String, + pub target: ChatTarget, + /// Unix milliseconds. + pub ts_ms: i64, + pub author_uid: Option, + pub author_name: String, + /// The author's client id on the server, if known. + pub author_id: Option, + /// Carried by a relay rather than our own connection. + pub via_relay: bool, + pub text: String, + pub source: MessageSource, + /// Set for messages from a gateway. + pub remote: Option, +} + +/// A stored message. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredMessage { + /// Assigned by the store; stable on this device. + pub id: i64, + pub server_uid: String, + pub target: ChatTarget, + /// Unix milliseconds. + pub ts_ms: i64, + pub author_uid: Option, + pub author_name: String, + pub author_id: Option, + pub via_relay: bool, + pub text: String, + /// What delivered it first. + pub source: MessageSource, + /// The gateway's message id, once a gateway copy was stored. + pub remote_id: Option, + pub topic_id: Option, + /// Gateway revision of the last change (0 without a gateway copy). + pub rev: i64, + pub reactions: Vec, + pub pinned: bool, + pub sync_state: SyncState, +} + +/// What [`Store::write_messages`] did with one message. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum WriteOutcome { + /// Stored as a new row. + Inserted, + /// Another copy of a stored message (see the [module docs](self)); the + /// row gained what this copy adds, e.g. the gateway id. + Merged, + /// A gateway message stored before, with changes (pin, reactions, topic). + Updated, + /// Nothing new. + Unchanged, +} + +/// A stored message and what the write did. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Written { + pub message: StoredMessage, + pub outcome: WriteOutcome, +} + +/// A window of a chat, by `(ts_ms, id)`. Pages are always oldest first. +/// +/// Without `after`: the newest `limit` messages before `before` (the newest +/// of the chat without it). With `after`: the oldest `limit` messages after +/// it, up to `before` if given. `limit: None` is everything in range. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PageQuery { + pub before: Option<(i64, i64)>, + pub after: Option<(i64, i64)>, + pub limit: Option, +} + +/// How far a chat is synced with a gateway. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChatCursor { + /// The gateway the revision belongs to; another gateway starts over. + pub gateway_id: String, + /// The last gateway revision stored (`sync since_rev`). + pub rev: i64, + /// The gateway has nothing older than the oldest message stored from it. + pub complete: bool, + /// Unix milliseconds of the last sync. + pub updated_ms: i64, +} + +/// Version 2: times in milliseconds, sources, gateway ids and metadata, +/// dedupe keys, sync cursors and server aliases. Old messages keep their +/// data (source `local`, their second times in milliseconds). +pub(crate) fn migrate_2(tx: &Transaction) -> rusqlite::Result<()> { + tx.execute_batch( + "ALTER TABLE messages ADD COLUMN ts_ms INTEGER NOT NULL DEFAULT 0; + UPDATE messages SET ts_ms = ts * 1000; + ALTER TABLE messages ADD COLUMN author_id INTEGER; + ALTER TABLE messages ADD COLUMN source TEXT NOT NULL DEFAULT 'local'; + ALTER TABLE messages ADD COLUMN remote_id INTEGER; + ALTER TABLE messages ADD COLUMN topic_id INTEGER; + ALTER TABLE messages ADD COLUMN rev INTEGER NOT NULL DEFAULT 0; + ALTER TABLE messages ADD COLUMN sync_state INTEGER NOT NULL DEFAULT 0; + ALTER TABLE messages ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0; + ALTER TABLE messages ADD COLUMN reactions TEXT; + -- Sources that delivered the row (MessageSource bits), for dedupe. + ALTER TABLE messages ADD COLUMN seen_by INTEGER NOT NULL DEFAULT 8; + -- FNV-1a of the text without a relay prefix, for dedupe. + ALTER TABLE messages ADD COLUMN text_hash INTEGER NOT NULL DEFAULT 0; + DROP INDEX messages_by_target; + CREATE INDEX messages_by_time ON messages (server_uid, target, ts_ms, id); + CREATE UNIQUE INDEX messages_by_remote ON messages (server_uid, target, remote_id) + WHERE remote_id IS NOT NULL; + CREATE TABLE chat_cursors ( + server_uid TEXT NOT NULL, + target TEXT NOT NULL, + gateway_id TEXT NOT NULL, + rev INTEGER NOT NULL DEFAULT 0, + complete INTEGER NOT NULL DEFAULT 0, + updated_ms INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (server_uid, target) + ) WITHOUT ROWID; + CREATE TABLE server_aliases ( + alias TEXT PRIMARY KEY, + server_uid TEXT NOT NULL, + updated_ms INTEGER NOT NULL DEFAULT 0 + ) WITHOUT ROWID;", + )?; + let rows: Vec<(i64, String)> = tx + .prepare("SELECT id, text FROM messages")? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect::>()?; + let mut update = tx.prepare("UPDATE messages SET text_hash = ?2 WHERE id = ?1")?; + for (id, text) in rows { + update.execute(params![id, text_hash(&text)])?; + } + Ok(()) +} + +/// A relay posts as `[nick] text`: the nick and the text. +fn split_relay(text: &str) -> (Option<&str>, &str) { + if let Some(rest) = text.strip_prefix('[') + && let Some((nick, after)) = rest.split_once("] ") + && !nick.is_empty() + { + return (Some(nick), after); + } + (None, text) +} + +/// FNV-1a (64 bit) of the text without a relay prefix. +fn text_hash(text: &str) -> i64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for byte in split_relay(text).1.bytes() { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x0100_0000_01b3); + } + hash as i64 +} + +/// Whether a stored row and a new copy are the same message (the hash and +/// time already matched). +fn same_message(new: &NewMessage, old: &StoredMessage) -> bool { + let (new_prefix, new_text) = split_relay(&new.text); + let (old_prefix, old_text) = split_relay(&old.text); + if new_text != old_text { + return false; + } + if let (Some(a), Some(b)) = (&new.author_uid, &old.author_uid) + && a == b + { + return true; + } + if new_prefix.is_some_and(|n| n == old.author_name) + || old_prefix.is_some_and(|n| n == new.author_name) + { + return true; + } + (new.author_uid.is_none() || old.author_uid.is_none()) && new.author_name == old.author_name +} + +const COLUMNS: &str = "id, server_uid, target, ts_ms, author_uid, author_name, author_id, \ + via_relay, text, source, remote_id, topic_id, rev, reactions, pinned, sync_state"; + +fn reactions_json(reactions: &[Reaction]) -> Option { + (!reactions.is_empty()).then(|| serde_json::to_string(reactions).unwrap_or_default()) +} + +fn message_from_row(r: &Row) -> rusqlite::Result { + let target: String = r.get(2)?; + let source: String = r.get(9)?; + let reactions: Option = r.get(13)?; + Ok(StoredMessage { + id: r.get(0)?, + server_uid: r.get(1)?, + target: ChatTarget::from_key(&target), + ts_ms: r.get(3)?, + author_uid: r.get(4)?, + author_name: r.get(5)?, + author_id: r.get(6)?, + via_relay: r.get(7)?, + text: r.get(8)?, + source: MessageSource::parse(&source), + remote_id: r.get(10)?, + topic_id: r.get(11)?, + rev: r.get(12)?, + reactions: reactions.and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default(), + pinned: r.get(14)?, + sync_state: if r.get::<_, i64>(15)? == 1 { SyncState::Synced } else { SyncState::Local }, + }) +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default() +} + +/// Upsert one message inside `tx`. +fn write_one(tx: &Transaction, m: &NewMessage, tolerance_ms: i64) -> rusqlite::Result { + let target = m.target.key(); + let by_id = |id: i64| -> rusqlite::Result { + tx.prepare_cached(&format!("SELECT {COLUMNS} FROM messages WHERE id = ?1"))? + .query_row([id], message_from_row) + }; + if let Some(remote) = &m.remote { + // The same gateway message again. + let existing = tx + .prepare_cached(&format!( + "SELECT {COLUMNS} FROM messages + WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3" + ))? + .query_row(params![m.server_uid, target, remote.id], message_from_row) + .optional()?; + if let Some(old) = existing { + let changed = old.rev != remote.rev + || old.topic_id != remote.topic_id + || old.pinned != remote.pinned + || old.reactions != remote.reactions; + if !changed { + return Ok(Written { message: old, outcome: WriteOutcome::Unchanged }); + } + tx.prepare_cached( + "UPDATE messages SET rev = ?2, topic_id = ?3, pinned = ?4, reactions = ?5 WHERE id = ?1", + )? + .execute(params![ + old.id, + remote.rev, + remote.topic_id, + remote.pinned, + reactions_json(&remote.reactions) + ])?; + return Ok(Written { message: by_id(old.id)?, outcome: WriteOutcome::Updated }); + } + } + // Another copy of a message stored from a different source. + let hash = text_hash(&m.text); + let duplicate = { + let mut stmt = tx.prepare_cached(&format!( + "SELECT {COLUMNS} FROM messages + WHERE server_uid = ?1 AND target = ?2 AND ts_ms BETWEEN ?3 AND ?4 + AND text_hash = ?5 AND (seen_by & ?6) = 0 AND (?7 = 0 OR remote_id IS NULL) + ORDER BY ABS(ts_ms - ?8), id" + ))?; + let rows = stmt.query_map( + params![ + m.server_uid, + target, + m.ts_ms.saturating_sub(tolerance_ms), + m.ts_ms.saturating_add(tolerance_ms), + hash, + m.source.bit(), + m.remote.is_some(), + m.ts_ms + ], + message_from_row, + )?; + let mut found = None; + for row in rows { + let row = row?; + if same_message(m, &row) { + found = Some(row); + break; + } + } + found + }; + if let Some(old) = duplicate { + let remote = m.remote.clone().unwrap_or_default(); + tx.prepare_cached( + "UPDATE messages SET seen_by = seen_by | ?2, + author_uid = COALESCE(author_uid, ?3), author_id = COALESCE(author_id, ?4), + remote_id = COALESCE(?5, remote_id), rev = MAX(rev, ?6), + topic_id = COALESCE(?7, topic_id), pinned = CASE WHEN ?5 IS NULL THEN pinned ELSE ?8 END, + reactions = CASE WHEN ?5 IS NULL THEN reactions ELSE ?9 END, + sync_state = CASE WHEN ?5 IS NULL THEN sync_state ELSE 1 END + WHERE id = ?1", + )? + .execute(params![ + old.id, + m.source.bit(), + m.author_uid, + m.author_id, + m.remote.as_ref().map(|r| r.id), + remote.rev, + remote.topic_id, + remote.pinned, + reactions_json(&remote.reactions) + ])?; + let message = by_id(old.id)?; + let outcome = if message == old { WriteOutcome::Unchanged } else { WriteOutcome::Merged }; + return Ok(Written { message, outcome }); + } + let remote = m.remote.clone().unwrap_or_default(); + tx.prepare_cached( + "INSERT INTO messages (server_uid, target, ts, ts_ms, author_uid, author_name, author_id, + via_relay, text, source, remote_id, topic_id, rev, reactions, pinned, sync_state, + seen_by, text_hash) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)", + )? + .execute(params![ + m.server_uid, + target, + m.ts_ms.div_euclid(1000), + m.ts_ms, + m.author_uid, + m.author_name, + m.author_id, + m.via_relay, + m.text, + m.source.as_str(), + m.remote.as_ref().map(|r| r.id), + remote.topic_id, + remote.rev, + reactions_json(&remote.reactions), + remote.pinned, + i64::from(m.remote.is_some()), + m.source.bit(), + hash + ])?; + let id = tx.last_insert_rowid(); + Ok(Written { message: by_id(id)?, outcome: WriteOutcome::Inserted }) +} + +impl Store { + /// Store messages in one transaction, merging copies of the same + /// message (see the [module docs](self)); results in input order. + pub fn write_messages( + &mut self, + messages: &[NewMessage], + tolerance_ms: i64, + ) -> Result> { + let tx = self.db.transaction()?; + let mut out = Vec::with_capacity(messages.len()); + for m in messages { + out.push(write_one(&tx, m, tolerance_ms.max(0))?); + } + tx.commit()?; + Ok(out) + } + + /// A page of a chat, oldest first (see [`PageQuery`]). + pub fn messages( + &self, + server_uid: &str, + target: &ChatTarget, + query: PageQuery, + ) -> Result> { + let (before_ts, before_id) = query.before.unwrap_or((i64::MAX, i64::MAX)); + let (after_ts, after_id) = query.after.unwrap_or((i64::MIN, i64::MIN)); + let ascending = query.after.is_some(); + let sql = format!( + "SELECT {COLUMNS} FROM messages + WHERE server_uid = ?1 AND target = ?2 AND (ts_ms, id) < (?3, ?4) AND (ts_ms, id) > (?5, ?6) + ORDER BY ts_ms {order}, id {order} LIMIT ?7", + order = if ascending { "ASC" } else { "DESC" } + ); + let limit = query.limit.map_or(-1, |l| l as i64); + let mut rows = self + .db + .prepare_cached(&sql)? + .query_map( + params![server_uid, target.key(), before_ts, before_id, after_ts, after_id, limit], + message_from_row, + )? + .collect::>>()?; + if !ascending { + rows.reverse(); + } + Ok(rows) + } + + /// One message by its local id. + pub fn message(&self, id: i64) -> Result> { + Ok(self + .db + .prepare_cached(&format!("SELECT {COLUMNS} FROM messages WHERE id = ?1"))? + .query_row([id], message_from_row) + .optional()?) + } + + /// One message by its gateway id. + pub fn message_by_remote( + &self, + server_uid: &str, + target: &ChatTarget, + remote_id: i64, + ) -> Result> { + Ok(self + .db + .prepare_cached(&format!( + "SELECT {COLUMNS} FROM messages + WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3" + ))? + .query_row(params![server_uid, target.key(), remote_id], message_from_row) + .optional()?) + } + + /// The oldest time of a message stored from the gateway, if any. + pub fn oldest_remote_ts(&self, server_uid: &str, target: &ChatTarget) -> Result> { + Ok(self + .db + .prepare_cached( + "SELECT MIN(ts_ms) FROM messages + WHERE server_uid = ?1 AND target = ?2 AND remote_id IS NOT NULL", + )? + .query_row(params![server_uid, target.key()], |r| r.get(0))?) + } + + /// Mark a gateway message (un)pinned; the updated row, `None` if it is + /// not stored. + pub fn set_pinned( + &mut self, + server_uid: &str, + target: &ChatTarget, + remote_id: i64, + pinned: bool, + ) -> Result> { + self.db + .prepare_cached( + "UPDATE messages SET pinned = ?4 + WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3", + )? + .execute(params![server_uid, target.key(), remote_id, pinned])?; + self.message_by_remote(server_uid, target, remote_id) + } + + /// Set the count of one emoji on a gateway message (0 removes it) and, + /// if given, whether the user reacted with it. The updated row, `None` + /// if the message is not stored. + pub fn set_reaction( + &mut self, + server_uid: &str, + target: &ChatTarget, + remote_id: i64, + emoji: &str, + count: u32, + me: Option, + ) -> Result> { + let tx = self.db.transaction()?; + let current: Option<(i64, Option)> = tx + .prepare_cached( + "SELECT id, reactions FROM messages + WHERE server_uid = ?1 AND target = ?2 AND remote_id = ?3", + )? + .query_row(params![server_uid, target.key(), remote_id], |r| Ok((r.get(0)?, r.get(1)?))) + .optional()?; + let Some((id, json)) = current else { return Ok(None) }; + let mut reactions: Vec = + json.and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default(); + match reactions.iter().position(|r| r.emoji == emoji) { + _ if count == 0 => reactions.retain(|r| r.emoji != emoji), + Some(i) => { + reactions[i].count = count; + if let Some(me) = me { + reactions[i].me = me; + } + } + None => { + reactions.push(Reaction { emoji: emoji.to_owned(), count, me: me.unwrap_or(false) }) + } + } + tx.prepare_cached("UPDATE messages SET reactions = ?2 WHERE id = ?1")? + .execute(params![id, reactions_json(&reactions)])?; + tx.commit()?; + self.message(id) + } + + /// How far a chat is synced with a gateway. + pub fn chat_cursor(&self, server_uid: &str, target: &ChatTarget) -> Result> { + Ok(self + .db + .prepare_cached( + "SELECT gateway_id, rev, complete, updated_ms FROM chat_cursors + WHERE server_uid = ?1 AND target = ?2", + )? + .query_row(params![server_uid, target.key()], |r| { + Ok(ChatCursor { + gateway_id: r.get(0)?, + rev: r.get(1)?, + complete: r.get(2)?, + updated_ms: r.get(3)?, + }) + }) + .optional()?) + } + + pub fn set_chat_cursor( + &self, + server_uid: &str, + target: &ChatTarget, + cursor: &ChatCursor, + ) -> Result<()> { + self.db + .prepare_cached( + "INSERT INTO chat_cursors (server_uid, target, gateway_id, rev, complete, updated_ms) + VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT (server_uid, target) DO UPDATE SET gateway_id = excluded.gateway_id, + rev = excluded.rev, complete = excluded.complete, updated_ms = excluded.updated_ms", + )? + .execute(params![ + server_uid, + target.key(), + cursor.gateway_id, + cursor.rev, + cursor.complete, + cursor.updated_ms + ])?; + Ok(()) + } + + /// Forget the gateway ids of a chat (another gateway numbers its + /// messages differently) and its cursor; the rows stay, as seen by this + /// device, and are matched again with the new gateway's copies. + pub fn forget_remote_ids(&mut self, server_uid: &str, target: &ChatTarget) -> Result { + let tx = self.db.transaction()?; + let n = tx + .prepare_cached( + "UPDATE messages SET remote_id = NULL, rev = 0, sync_state = 0, + seen_by = CASE WHEN seen_by = 2 THEN 8 ELSE seen_by & ~2 END + WHERE server_uid = ?1 AND target = ?2 AND remote_id IS NOT NULL", + )? + .execute(params![server_uid, target.key()])?; + tx.prepare_cached("DELETE FROM chat_cursors WHERE server_uid = ?1 AND target = ?2")? + .execute(params![server_uid, target.key()])?; + tx.commit()?; + Ok(n) + } + + /// The server unique id last seen under another name of the server + /// (e.g. `voice:
`, `gateway:`). + pub fn server_alias(&self, alias: &str) -> Result> { + Ok(self + .db + .prepare_cached("SELECT server_uid FROM server_aliases WHERE alias = ?1")? + .query_row([alias], |r| r.get(0)) + .optional()?) + } + + pub fn set_server_alias(&self, alias: &str, server_uid: &str) -> Result<()> { + self.db + .prepare_cached( + "INSERT INTO server_aliases (alias, server_uid, updated_ms) VALUES (?1, ?2, ?3) + ON CONFLICT (alias) DO UPDATE SET server_uid = excluded.server_uid, + updated_ms = excluded.updated_ms", + )? + .execute(params![alias, server_uid, now_ms()])?; + Ok(()) + } + + /// Delete messages sent before `before_ms` (Unix milliseconds); pinned + /// ones stay. + pub fn prune_messages(&self, before_ms: i64) -> Result { + Ok(self + .db + .prepare_cached( + "DELETE FROM messages WHERE ts_ms < ?1 AND pinned = 0 AND server_uid <> ''", + )? + .execute([before_ms])?) + } + + /// Give new messages ids from `first` on (e.g. negative ones, for a + /// database whose ids must not be confused with another's). SQLite + /// numbers a new row one above the largest id, so this keeps a hidden + /// row (no server) just below `first`. For an empty chat table. + pub fn start_message_ids_at(&self, first: i64) -> Result<()> { + self.db.execute( + "INSERT INTO messages (id, server_uid, target, ts, author_name, text) + VALUES (?1, '', '', 0, '', '')", + [first.saturating_sub(1)], + )?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SRV: &str = "srv"; + + fn msg(source: MessageSource, author: &str, text: &str, ts_ms: i64) -> NewMessage { + NewMessage { + server_uid: SRV.into(), + target: ChatTarget::Channel(1), + ts_ms, + author_uid: Some(format!("uid-{author}")), + author_name: author.into(), + author_id: None, + via_relay: source != MessageSource::Voice, + text: text.into(), + source, + remote: None, + } + } + + fn remote(mut m: NewMessage, id: i64, rev: i64) -> NewMessage { + m.source = MessageSource::Gateway; + m.remote = Some(RemoteInfo { id, rev, ..Default::default() }); + m + } + + fn outcomes(written: &[Written]) -> Vec { + written.iter().map(|w| w.outcome).collect() + } + + fn texts(rows: &[StoredMessage]) -> Vec<&str> { + rows.iter().map(|m| m.text.as_str()).collect() + } + + #[test] + fn batch_insert_and_pages() { + let mut store = Store::open_in_memory().unwrap(); + let target = ChatTarget::Channel(1); + let batch: Vec<_> = (0..10) + .map(|i| msg(MessageSource::Voice, "a", &format!("m{i}"), 1000 + i * 10)) + .collect(); + let written = store.write_messages(&batch, 5000).unwrap(); + assert!(written.iter().all(|w| w.outcome == WriteOutcome::Inserted)); + // Same time, higher id: after. + store.write_messages(&[msg(MessageSource::Voice, "a", "m9b", 1090)], 0).unwrap(); + + let page = |q| store.messages(SRV, &target, q).unwrap(); + let newest = page(PageQuery { limit: Some(3), ..Default::default() }); + assert_eq!(texts(&newest), ["m8", "m9", "m9b"]); + let pos = |m: &StoredMessage| (m.ts_ms, m.id); + let older = + page(PageQuery { before: Some(pos(&newest[0])), limit: Some(3), ..Default::default() }); + assert_eq!(texts(&older), ["m5", "m6", "m7"]); + let after = + page(PageQuery { after: Some(pos(&older[0])), limit: Some(2), ..Default::default() }); + assert_eq!(texts(&after), ["m6", "m7"]); + let range = page(PageQuery { + after: Some(pos(&older[0])), + before: Some(pos(&newest[0])), + limit: None, + }); + assert_eq!(texts(&range), ["m6", "m7"]); + assert_eq!(page(PageQuery::default()).len(), 11, "no limit"); + assert!(store.messages(SRV, &ChatTarget::Server, PageQuery::default()).unwrap().is_empty()); + assert!(store.messages("other", &target, PageQuery::default()).unwrap().is_empty()); + assert_eq!(store.prune_messages(1050).unwrap(), 5); + } + + #[test] + fn copies_from_two_sources_are_one_row() { + let mut store = Store::open_in_memory().unwrap(); + // Live over voice, then from the gateway 1.2 s later (clock skew). + let live = + store.write_messages(&[msg(MessageSource::Voice, "a", "hi", 10_000)], 5000).unwrap(); + let gw = store + .write_messages(&[remote(msg(MessageSource::Gateway, "a", "hi", 11_200), 77, 5)], 5000) + .unwrap(); + assert_eq!(outcomes(&gw), [WriteOutcome::Merged]); + let row = &gw[0].message; + assert_eq!((row.id, row.remote_id, row.rev), (live[0].message.id, Some(77), 5)); + assert_eq!((row.source, row.sync_state), (MessageSource::Voice, SyncState::Synced)); + // The gateway copy again: unchanged; with a pin: updated. + let again = store + .write_messages(&[remote(msg(MessageSource::Gateway, "a", "hi", 11_200), 77, 5)], 5000); + assert_eq!(outcomes(&again.unwrap()), [WriteOutcome::Unchanged]); + let mut pinned = remote(msg(MessageSource::Gateway, "a", "hi", 11_200), 77, 6); + pinned.remote.as_mut().unwrap().pinned = true; + let updated = store.write_messages(&[pinned], 5000).unwrap(); + assert_eq!(outcomes(&updated), [WriteOutcome::Updated]); + assert!(updated[0].message.pinned); + + // A second live copy from the same source is a new message (the + // author said it twice)... + let twice = + store.write_messages(&[msg(MessageSource::Voice, "a", "hi", 10_500)], 5000).unwrap(); + assert_eq!(outcomes(&twice), [WriteOutcome::Inserted]); + // ...and the query relay's copy of it matches it, not the first one. + let relayed = store.write_messages(&[msg(MessageSource::Query, "a", "hi", 10_400)], 5000); + let relayed = relayed.unwrap(); + assert_eq!(relayed[0].message.id, twice[0].message.id); + assert_eq!(relayed[0].outcome, WriteOutcome::Unchanged, "nothing visible changed"); + // Too far apart in time, another author or another text: not the same. + for other in [ + msg(MessageSource::Query, "a", "hi", 30_000), + msg(MessageSource::Query, "b", "hi", 10_000), + msg(MessageSource::Query, "a", "hi!", 10_000), + ] { + assert_eq!( + outcomes(&store.write_messages(&[other], 5000).unwrap()), + [WriteOutcome::Inserted] + ); + } + } + + #[test] + fn relay_posts_match_the_gateway_copy() { + let mut store = Store::open_in_memory().unwrap(); + // We sent "hey" through the gateway: stored at once as our own... + let mut own = msg(MessageSource::Local, "me", "hey", 5_000); + own.via_relay = false; + let own = store.write_messages(&[own], 5000).unwrap(); + // ...the voice connection hears the relay post it as "[me] hey"... + let mut heard = msg(MessageSource::Voice, "tsgw relay", "[me] hey", 5_300); + heard.author_uid = Some("uid-relay".into()); + let heard = store.write_messages(&[heard], 5000).unwrap(); + assert_eq!( + (heard[0].message.id, heard[0].outcome), + (own[0].message.id, WriteOutcome::Unchanged) + ); + // ...and the gateway pushes its copy with our uid. + let gw = store + .write_messages(&[remote(msg(MessageSource::Gateway, "me", "hey", 5_100), 9, 1)], 5000) + .unwrap(); + assert_eq!((gw[0].message.id, gw[0].outcome), (own[0].message.id, WriteOutcome::Merged)); + assert_eq!(gw[0].message.text, "hey"); + // Without uids the nickname decides. + let mut a = msg(MessageSource::Voice, "x", "yo", 1); + a.author_uid = None; + let a = store.write_messages(&[a], 5000).unwrap(); + let b = + store.write_messages(&[remote(msg(MessageSource::Gateway, "x", "yo", 2), 10, 2)], 5000); + assert_eq!(b.unwrap()[0].message.id, a[0].message.id); + } + + #[test] + fn pins_reactions_and_cursors() { + let mut store = Store::open_in_memory().unwrap(); + let target = ChatTarget::Channel(1); + store.write_messages(&[remote(msg(MessageSource::Gateway, "a", "x", 1), 5, 1)], 0).unwrap(); + assert!(store.set_pinned(SRV, &target, 5, true).unwrap().unwrap().pinned); + assert!(store.set_pinned(SRV, &target, 6, true).unwrap().is_none()); + let r = store.set_reaction(SRV, &target, 5, "👍", 2, Some(true)).unwrap().unwrap(); + assert_eq!(r.reactions, [Reaction { emoji: "👍".into(), count: 2, me: true }]); + let r = store.set_reaction(SRV, &target, 5, "👍", 1, Some(false)).unwrap().unwrap(); + assert_eq!(r.reactions, [Reaction { emoji: "👍".into(), count: 1, me: false }]); + assert!( + store + .set_reaction(SRV, &target, 5, "👍", 0, None) + .unwrap() + .unwrap() + .reactions + .is_empty() + ); + // Pinned messages survive pruning. + assert_eq!(store.prune_messages(i64::MAX).unwrap(), 0); + + assert_eq!(store.chat_cursor(SRV, &target).unwrap(), None); + let cursor = ChatCursor { gateway_id: "gw".into(), rev: 42, complete: true, updated_ms: 7 }; + store.set_chat_cursor(SRV, &target, &cursor).unwrap(); + assert_eq!(store.chat_cursor(SRV, &target).unwrap(), Some(cursor)); + assert_eq!(store.oldest_remote_ts(SRV, &target).unwrap(), Some(1)); + // Another gateway: ids and cursor are forgotten, the row stays. + assert_eq!(store.forget_remote_ids(SRV, &target).unwrap(), 1); + assert_eq!(store.chat_cursor(SRV, &target).unwrap(), None); + let row = &store.messages(SRV, &target, PageQuery::default()).unwrap()[0]; + assert_eq!((row.remote_id, row.sync_state), (None, SyncState::Local)); + // The new gateway's copy links to it again. + let again = + store.write_messages(&[remote(msg(MessageSource::Gateway, "a", "x", 1), 900, 1)], 0); + assert_eq!(again.unwrap()[0].message.id, row.id); + + assert_eq!(store.server_alias("voice:host").unwrap(), None); + store.set_server_alias("voice:host", "uid1").unwrap(); + store.set_server_alias("voice:host", "uid2").unwrap(); + assert_eq!(store.server_alias("voice:host").unwrap().as_deref(), Some("uid2")); + } + + /// A database of version 1 with messages is upgraded in place. + #[test] + fn migrates_version_1_with_data() { + let dir = std::env::temp_dir().join(format!("voelin-store-migrate-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("client.db"); + { + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch(crate::store::SCHEMA_1).unwrap(); + db.pragma_update(None, "user_version", 1).unwrap(); + db.execute_batch( + "INSERT INTO settings (key, value) VALUES ('k', '\"v\"'); + INSERT INTO messages (server_uid, target, ts, author_uid, author_name, via_relay, text) + VALUES ('srv', 'channel/1', 100, 'uid-a', 'a', 0, 'old one'), + ('srv', 'channel/1', 200, NULL, 'b', 1, '[c] old two');", + ) + .unwrap(); + } + let mut store = Store::open(&path).unwrap(); + assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION); + assert_eq!(store.setting::("k").unwrap().as_deref(), Some("v")); + let rows = store.messages(SRV, &ChatTarget::Channel(1), PageQuery::default()).unwrap(); + assert_eq!(texts(&rows), ["old one", "[c] old two"]); + assert_eq!((rows[0].ts_ms, rows[0].source), (100_000, MessageSource::Local)); + assert!(rows[1].via_relay); + // The old rows take part in dedupe: the gateway copy of the relay post. + let mut gw = remote(msg(MessageSource::Gateway, "c", "old two", 201_000), 3, 3); + gw.author_uid = Some("uid-c".into()); + let gw = store.write_messages(&[gw], 5000).unwrap(); + assert_eq!((gw[0].message.id, gw[0].outcome), (rows[1].id, WriteOutcome::Merged)); + drop(store); + // Opening again runs nothing. + let store = Store::open(&path).unwrap(); + assert_eq!( + store.messages(SRV, &ChatTarget::Channel(1), PageQuery::default()).unwrap().len(), + 2 + ); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn ids_can_start_elsewhere() { + let mut store = Store::open_in_memory().unwrap(); + store.start_message_ids_at(-1000).unwrap(); + let w = store.write_messages(&[msg(MessageSource::Voice, "a", "x", 1)], 0).unwrap(); + assert_eq!(w[0].message.id, -1000); + let w = store.write_messages(&[msg(MessageSource::Voice, "a", "y", 2)], 0).unwrap(); + assert_eq!(w[0].message.id, -999); + assert_eq!(store.prune_messages(i64::MAX).unwrap(), 2, "the hidden row stays"); + let w = store.write_messages(&[msg(MessageSource::Voice, "a", "z", 3)], 0).unwrap(); + assert_eq!(w[0].message.id, -1000); + } + + #[test] + fn keys_round_trip() { + for t in [ChatTarget::Server, ChatTarget::Channel(12), ChatTarget::Private("a/b=".into())] { + assert_eq!(ChatTarget::from_key(&t.key()), t); + } + assert_eq!(split_relay("[nick] text"), (Some("nick"), "text")); + assert_eq!(split_relay("[] text"), (None, "[] text")); + assert_eq!(text_hash("[nick] text"), text_hash("text")); + } +} diff --git a/crates/voelin-store/src/lib.rs b/crates/voelin-store/src/lib.rs index 65be2ea..fc9a07c 100644 --- a/crates/voelin-store/src/lib.rs +++ b/crates/voelin-store/src/lib.rs @@ -1,18 +1,25 @@ //! Local persistence for the client. //! -//! One SQLite database holds identities, bookmarks, settings and a chat -//! cache. Passwords and query credentials never go into the database; they -//! live in a [`Secrets`] store (the OS keyring with the `keyring` feature). +//! One SQLite database holds identities, bookmarks, settings and the chat +//! history ([`chat`]). Passwords and query credentials never go into the +//! database; they live in a [`Secrets`] store (the OS keyring with the +//! `keyring` feature). +//! +//! The schema is versioned (`PRAGMA user_version`): opening a database runs +//! the migrations it has not seen, each in one transaction, keeping the data. +pub mod chat; mod secrets; mod store; +pub use chat::{ + ChatCursor, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo, + StoredMessage, SyncState, WriteOutcome, Written, +}; #[cfg(feature = "keyring")] pub use secrets::KeyringSecrets; pub use secrets::{MemorySecrets, Secrets}; -pub use store::{ - Bookmark, ChatTarget, IdentityEntry, QueryConfig, QueryTransport, Store, StoredMessage, -}; +pub use store::{Bookmark, IdentityEntry, QueryConfig, QueryTransport, Store}; #[derive(Debug, thiserror::Error)] pub enum Error { diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index ea216ca..5e84339 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -2,15 +2,27 @@ use std::path::Path; -use rusqlite::{Connection, OptionalExtension, params}; +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tsclientlib::Identity; use crate::{Error, Result}; -/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`. -const MIGRATIONS: &[&str] = &[r#" +/// A schema migration: SQL, or code for what SQL alone cannot do. +enum Migration { + Sql(&'static str), + Code(fn(&rusqlite::Transaction) -> rusqlite::Result<()>), +} + +/// Schema migrations; entry `i` upgrades from version `i` to `i + 1` +/// (`PRAGMA user_version`). Add new ones at the end; never change one that +/// shipped. +const MIGRATIONS: &[Migration] = + &[Migration::Sql(SCHEMA_1), Migration::Code(crate::chat::migrate_2)]; + +/// Version 1: identities, bookmarks, settings and a first chat cache. +pub(crate) const SCHEMA_1: &str = r#" CREATE TABLE identities ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, @@ -38,7 +50,7 @@ const MIGRATIONS: &[&str] = &[r#" text TEXT NOT NULL ); CREATE INDEX messages_by_target ON messages (server_uid, target, id); -"#]; +"#; /// A stored identity, without its private key. #[derive(Clone, Debug, PartialEq, Eq)] @@ -104,42 +116,8 @@ impl Bookmark { } } -/// Where a chat message was posted. -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum ChatTarget { - Server, - Channel(u64), - /// Private chat with the client of this unique id. - Private(String), -} - -impl ChatTarget { - fn key(&self) -> String { - match self { - ChatTarget::Server => "server".into(), - ChatTarget::Channel(cid) => format!("channel/{cid}"), - ChatTarget::Private(uid) => format!("private/{uid}"), - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct StoredMessage { - /// Assigned by the store; used for paging. - pub id: i64, - pub server_uid: String, - pub target: ChatTarget, - /// Unix timestamp in seconds. - pub ts: i64, - pub author_uid: Option, - pub author_name: String, - /// Received through a gateway/query relay instead of our own connection. - pub via_relay: bool, - pub text: String, -} - pub struct Store { - db: Connection, + pub(crate) db: Connection, } impl Store { @@ -167,18 +145,35 @@ impl Store { Self::init(Connection::open_in_memory()?) } - fn init(db: Connection) -> Result { + fn init(mut db: Connection) -> Result { // Statements run through `prepare_cached` are parsed once per connection. db.set_prepared_statement_cache_capacity(64); db.pragma_update(None, "foreign_keys", true)?; - let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?; - for (i, migration) in MIGRATIONS.iter().enumerate().skip(version as usize) { - db.execute_batch(migration)?; - db.pragma_update(None, "user_version", i as i64 + 1)?; + // Each migration with its version bump in one write transaction: a + // second connection that opens the file at the same time (the + // settings writer, the chat history) waits, then sees the new version. + loop { + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let version: i64 = tx.pragma_query_value(None, "user_version", |r| r.get(0))?; + let Some(migration) = MIGRATIONS.get(version as usize) else { break }; + match migration { + Migration::Sql(sql) => tx.execute_batch(sql)?, + Migration::Code(migrate) => migrate(&tx)?, + } + tx.pragma_update(None, "user_version", version + 1)?; + tx.commit()?; } Ok(Self { db }) } + /// The schema version (number of migrations applied). + pub fn schema_version(&self) -> Result { + Ok(self.db.pragma_query_value(None, "user_version", |r| r.get(0))?) + } + + /// The number of schema migrations this version knows. + pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64; + // Identities pub fn add_identity(&self, name: &str, identity: &Identity) -> Result { @@ -329,63 +324,6 @@ impl Store { tx.commit()?; Ok(()) } - - // Chat cache - - pub fn add_message(&self, msg: &StoredMessage) -> Result { - self.db.execute( - "INSERT INTO messages (server_uid, target, ts, author_uid, author_name, via_relay, text) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", - params![ - msg.server_uid, - msg.target.key(), - msg.ts, - msg.author_uid, - msg.author_name, - msg.via_relay, - msg.text - ], - )?; - Ok(self.db.last_insert_rowid()) - } - - /// Up to `limit` messages older than `before` (message id), oldest first. - pub fn history( - &self, - server_uid: &str, - target: &ChatTarget, - before: Option, - limit: usize, - ) -> Result> { - let mut stmt = self.db.prepare( - "SELECT id, ts, author_uid, author_name, via_relay, text FROM messages - WHERE server_uid = ?1 AND target = ?2 AND id < ?3 - ORDER BY id DESC LIMIT ?4", - )?; - let rows = stmt.query_map( - params![server_uid, target.key(), before.unwrap_or(i64::MAX), limit as i64], - |r| { - Ok(StoredMessage { - id: r.get(0)?, - server_uid: server_uid.to_string(), - target: target.clone(), - ts: r.get(1)?, - author_uid: r.get(2)?, - author_name: r.get(3)?, - via_relay: r.get(4)?, - text: r.get(5)?, - }) - }, - )?; - let mut messages = rows.collect::>>()?; - messages.reverse(); - Ok(messages) - } - - /// Delete cached messages older than `ts` (Unix seconds). - pub fn prune_messages(&self, ts: i64) -> Result { - Ok(self.db.execute("DELETE FROM messages WHERE ts < ?1", [ts])?) - } } #[cfg(test)] @@ -457,33 +395,6 @@ mod tests { assert!(!store.delete_setting("a").unwrap()); } - #[test] - fn chat_history_pages() { - let store = Store::open_in_memory().unwrap(); - let target = ChatTarget::Channel(5); - for i in 0..10 { - store - .add_message(&StoredMessage { - id: 0, - server_uid: "srv".into(), - target: target.clone(), - ts: 1000 + i, - author_uid: None, - author_name: "a".into(), - via_relay: i % 2 == 0, - text: format!("m{i}"), - }) - .unwrap(); - } - let last = store.history("srv", &target, None, 3).unwrap(); - let texts: Vec<_> = last.iter().map(|m| m.text.as_str()).collect(); - assert_eq!(texts, ["m7", "m8", "m9"]); - let older = store.history("srv", &target, Some(last[0].id), 3).unwrap(); - assert_eq!(older.iter().map(|m| m.text.as_str()).collect::>(), ["m4", "m5", "m6"]); - assert!(store.history("srv", &ChatTarget::Server, None, 3).unwrap().is_empty()); - assert_eq!(store.prune_messages(1005).unwrap(), 5); - } - #[test] fn reopen_keeps_data_and_schema() { let dir = std::env::temp_dir().join(format!("voelin-store-{}", std::process::id())); diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index ffbc6cb..a2fd142 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -4,7 +4,8 @@ use slint::{ComponentHandle, Model}; use tracing::warn; -use voelin_core::settings::{STREAM_BITRATE_KBPS, STREAM_FPS}; +use voelin_core::media::audio_source_specs; +use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS}; use voelin_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState}; use voelin_core::{Command, Event, StreamState, WatchState}; @@ -397,10 +398,13 @@ impl App { audio: form.audio, auto_accept: form.auto_accept, }; + // No sources configured: no audio. + let audio_sources = audio_source_specs(&self.prefs.get(&STREAM_AUDIO_SOURCES)); let request = CaptureRequest { fps, bitrate_kbps: bitrate, - audio: form.audio, + audio: form.audio && !audio_sources.is_empty(), + audio_sources, restore_token: self.settings.portal_restore_token.clone(), }; self.settings.share = defaults; diff --git a/crates/voelin-ui/src/video.rs b/crates/voelin-ui/src/video.rs index cb1debb..df505d8 100644 --- a/crates/voelin-ui/src/video.rs +++ b/crates/voelin-ui/src/video.rs @@ -13,8 +13,8 @@ use tracing::warn; use voelin_core::media::voelin_media::capture::SourceId; use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert}; use voelin_core::media::{ - self, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, - preferred_codec, stream_codec, + self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig, + Viewer, peer_config, preferred_codec, stream_codec, }; use voelin_core::stream::PeerConfig; use voelin_core::{Engine, StreamSink}; @@ -262,6 +262,7 @@ impl Video { codec, encoder: self.encoder.clone(), audio: options.audio, + audio_sources: options.audio_sources, restore_token: options.restore_token, ..StreamerConfig::default() }; @@ -332,6 +333,8 @@ pub(crate) struct CaptureRequest { pub fps: u32, pub bitrate_kbps: u32, pub audio: bool, + /// Mixed into the stream's audio (`stream.audio_sources`). + pub audio_sources: Vec, pub restore_token: Option, } @@ -356,7 +359,7 @@ impl Capture { } pub fn audio_error(&self) -> Option { - self.streamer.audio_error().map(str::to_owned) + self.streamer.audio_error() } /// The portal's token for this choice, to keep. diff --git a/docs/architecture.md b/docs/architecture.md index 0edb158..271c46c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,6 +42,8 @@ the admin grants them to the guest query group. |---|---| | Server chat | Voice connection: `targetmode=3`. Without one: gateway or own query session (`servernotifyregister event=textserver`) | | Channel chat without joining | Relay pool (`voelin-observer`): invisible query sessions sit in channels and relay both ways; posts appear as `[Nick] text` | +| Chat history | Every message a session sees is stored on the device (`voelin-store`); a gateway's stored history fills in what the device missed (sync by revision, paging by time) | +| Pins, reactions, topics, events, stream directory, activity | Gateway features (`tsgw`), driven through `Command::Gateway` / `Event::Gateway` | | Voice | tsproto UDP transport, Opus (`opus2`), echo cancellation / noise suppression (sonora), own jitter buffer, cpal / AAudio | | Invisible presence | Gateway presence stream (snapshot + deltas from query events) or direct query; `channelsubscribeall` when voice-connected | | Screen share with sound | TS6 stream signalling (`voelin-stream`), str0m WebRTC, per-platform capture and codecs (`voelin-media`) | @@ -64,10 +66,10 @@ fuzz/ cargo-fuzz targets | `voelin-query` | ServerQuery codec and transports: raw TCP, SSH (russh), HTTP WebQuery | done | | `voelin-observer` | Presence tracker + chat relay pool over `voelin-query` | done | | `voelin-gateway-proto`, `voelin-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done | -| `voelin-store` | Identities, bookmarks, settings, chat cache, secrets (keyring / Android Keystore) | done | +| `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors), secrets (keyring / Android Keystore); versioned schema | done | | `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) | | `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam | sessions + transport | -| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, audio settings and volumes, streams on TS6; `media` module (capture → encoder → stream, stream → decoder) | done | +| `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6; `media` module (capture → encoder → stream, stream → decoder) | done | | `voelin-ui` | Slint UI and the desktop binary: streams panel, viewer, share dialog, audio / hotkey / codec settings | done (desktop) | | `voelin-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | done (desktop hardware encoders planned; MediaCodec not run on a device yet) | | `voelin-platform` | Global hotkeys, notifications, paths, crash reports, notices | done | @@ -82,6 +84,67 @@ the native command only when voice-connected *and* in that channel, otherwise th gateway, otherwise a local query relay. UI states: `Offline`, `Observing (Gateway|Query)` (invisible), `Connecting`, `Connected`. +## Chat history + +Every chat message a session sees is stored in the client database +(`voelin-store::chat`, table `messages`) under the server's unique id: live +over voice, pushed by the gateway, read by a query relay, or sent by us +(stored at once, as `local`). The unique id comes from the voice connection +(the server's key: base64 SHA-1 on TeamSpeak 3, SHA-256 on 6, the same value +as `virtualserver_unique_identifier`) or the gateway's `hello`; the database +remembers it for the bookmark's address and gateway URL (`server_aliases`), +so a chat shows its stored messages before any source has connected. +Query-only sessions, which learn no id, keep history under the query address. + +Rows carry `ts_ms`, the author, the text, the source that delivered them +first, and, once the gateway's copy is known, its stable id (`remote_id`, +unique per server and chat), revision, topic, pin and reactions. A message +often arrives twice (over voice and from the gateway); the store merges the +copies into one row: by gateway id, else by the text without a relay's +`[nick] ` prefix, the author (unique id, the relay prefix naming the other +copy's author, or the nickname without unique ids) and a time difference of +at most `chat.dedupe_tolerance_ms` (default 5 s), between different sources +only (a person saying the same thing twice stays two messages). + +`voelin-core::history` runs the database on a writer thread: live messages +are queued without waiting, writes that queue up go into one transaction, +statements are cached. When a chat opens (and whenever a source of the +session connects), the engine emits the newest `chat.history_page` stored +messages (`Event::ChatHistory`, source `Local`), then, with a gateway that +keeps history, syncs the chat: the first time the gateway's latest page, +afterwards `sync` from the chat's revision cursor (`chat_cursors`), which +returns new messages and messages whose pin, reactions or topic changed, +page after page until done (`Gateway` batches; the last one may be empty). +`Command::LoadOlderHistory` pages back: the gateway's page before that time +is fetched and merged first, then the stored page is emitted, so gaps (times +this device was offline) fill in as the user scrolls. Live messages and +changes come as `Live` batches. The UI keeps each chat as a list keyed by +the local id and ordered by `(ts_ms, id)`, and upserts every batch. Without +a gateway only `Local` batches come: the UI labels the chat "only messages +seen by this device". + +Settings: `chat.store_history` (off: memory only, negative ids), +`chat.history_page` (0: everything), `chat.dedupe_tolerance_ms`, +`chat.retention_days` (0: keep everything; pinned messages stay). No limit +is built in. + +## Gateway features in the engine + +The session's gateway source runs on the typed client +(`voelin-gateway-proto`, feature `client`): presence and relayed chat as +before, plus the extensions. After login the engine enables the chat +extension pushes and subscribes to events, the stream directory and the +activity feed when the gateway offers them. `Command::Gateway` carries a +`GatewayRequest` (pins, reactions, topics and topic history, events with +RSVP, the stream directory, activity, permissions, runtime configuration and +permission rules); answers and pushes come as `Event::Gateway` with a +`GatewayUpdate` (`Done`/`Failed` for requests without data or refused ones, +`Connected`/`Capabilities`/`Disconnected` for what the gateway offers). +Messages in answers and pushes are stored first, so the UI gets them with +local ids. The contract is in the module docs of `voelin_core::gateway` and +`voelin_core::history`; `voelinctl gateway --engine` drives it from the +command line. + ## Streams `voelin-stream::Streams` holds the stream state of one TS6 connection without @@ -148,7 +211,13 @@ at its start. `voelin-stream::discovery` follows the clients' channels and streaming flags (`Streams::update_clients`), and looks up streams nobody announced to us with `requeststreaminfo clid=` ([research/ts6-late-join.md](research/ts6-late-join.md)). The lookup is a -`StreamLookup` trait, so another directory (a gateway's) can be added. +`StreamLookup` trait. The session's gateway directory is the second one: +its registered entries (stream id, streamer) go to the stream task, which +adds those of streamers in our channel that still stream +(`Streams::discovered`), so a stream is found even when the server's lookup +does not answer. Our own stream registers itself in the directory when it +goes live (title, kind, channel, client), updates its viewer count, and is +removed when it ends. ## Settings @@ -161,7 +230,8 @@ key); writes notify subscribers and go to SQLite on a writer thread. The engine holds one (`Engine::settings`, `Command::AttachSettings`), takes `Command::SetSetting` / `ResetSetting` and reports `Event::SettingChanged`. The UI opens it on its database and registers its own keys (`ui`, -`client_playback`); the stream keys (`stream.*`) are defined in the core. +`client_playback`); the stream keys (`stream.*`) and chat keys (`chat.*`) +are defined in the core, which reads them on every use. ## Milestones diff --git a/docs/gateway-protocol.md b/docs/gateway-protocol.md index d55259b..41f2a85 100644 --- a/docs/gateway-protocol.md +++ b/docs/gateway-protocol.md @@ -3,7 +3,12 @@ How Voelin talks to `tsgw` ([gateway-admin.md](gateway-admin.md)). The types are in `crates/voelin-gateway-proto` (`messages.rs`, `types.rs`); its `client` feature is a typed client (one async method per request, pushes as -`Push`), which the app uses through `voelin_core::gateway`. +`Push`), which the app uses through `voelin_core::gateway`: the engine's +`Command::Gateway` requests and `Event::Gateway` updates map onto the +messages below one to one, and the chat history sync uses `query_history` +and `sync` ([architecture.md](architecture.md#chat-history)). +`voelinctl gateway --engine --request ''` sends any request through +the engine, e.g. `'{"config_get":{"key":"relay.pinned_channels"}}'`. ## Transport diff --git a/docs/media.md b/docs/media.md index 683a4a6..3445db8 100644 --- a/docs/media.md +++ b/docs/media.md @@ -1,7 +1,8 @@ # Media: frames, codecs and capture (`voelin-media`) -`crates/voelin-media` turns screens and system audio into frames, encodes and -decodes video, and converts pixels for rendering. It does no networking: +`crates/voelin-media` turns screens and what applications play into frames, +mixes the stream's audio, encodes and decodes video, and converts pixels for +rendering. It does no networking: `voelin-stream` carries the encoded frames (`Peer::write(MediaKind::Video, MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received `MediaFrame`s go to `VideoDecoder::decode`. @@ -30,6 +31,8 @@ MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received | `FrameReceiver` | bounded queue that drops the oldest item; `recv().await`, `try_recv()`, `recv_timeout()` | | `capture::default_screen_capture()`, `default_audio_capture()` | the backend for this session | | `capture::synthetic::{SyntheticScreen, SineSource}` | test pattern (moving rectangle, frame counter) and sine tone | +| `mix::{StreamMixer, MixerHandle, SourceHandle, SourceInput, BlockClock}` | the stream's audio mixer: any number of sources, each with gain, mute, level meters and any number of inputs (see [Stream audio](#stream-audio)) | +| `capture::playback::{start_playback, audio_apps, window_pid}` | what applications play, captured into a mixer source (`PlaybackFilter::AllButSelf` or `App(AppMatch::Name / Pid)`); the applications that play, updated live (`AudioApps`) | ```rust let codecs = Codecs::new().with_openh264(OpenH264::find_in(&data_dir)?); // H.264 optional @@ -58,7 +61,7 @@ streamer: capture thread ── FrameSink: pace, convert + scale (Pyramid on all ├─ encoder thread, layer 0 ─┐ ├─ encoder thread, layer 1 ─┤ └─ ... ├─ MediaSink: StreamSink / EncodedSource - AudioCapture ─ 20 ms stereo Opus (128 kbit/s) ─┘ + audio sources ─ StreamMixer (thread, every 20 ms) ─ stereo Opus (128 kbit/s) ─┘ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder ─ picture callback ─ Latest stream audio ─ session audio thread (mixer, own volume) ─ speakers ``` @@ -66,10 +69,11 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder - `Streamer::start(&codecs, StreamerConfig)` starts capturing right away (the portal asks the user then), so a cancelled dialog never starts a stream; frames are converted and encoded only after `attach(sink)`, i.e. once the - stream is live. Audio follows the capture clock across gaps. With the test - pattern (`SourceId::Synthetic`, `synthetic_pattern`) the audio is a quiet - sine tone. The portal's restore token is available afterwards - (`restore_token()`) to store. + stream is live. The audio is mixed from `StreamerConfig::audio_sources` + (see [Stream audio](#stream-audio)); without any, it is desktop audio + without Voelin, or a quiet sine tone with the test pattern + (`SourceId::Synthetic`, `synthetic_pattern`). The portal's restore token + is available afterwards (`restore_token()`) to store. - Threads: the capture backend calls the streamer's `FrameSink` on its own thread with the frame still in its capture buffer. Frames over the frame-rate cap (`StreamerConfig::fps`, any value >= 1) are skipped before @@ -90,7 +94,7 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder `max_bitrate`), else its configured bitrate; libvpx changes it in place without a keyframe. - `Streamer::reconfigure(&codecs, StreamerConfigUpdate { fps, bitrate_kbps, - codec, layers })` applies from the next frame without restarting the + codec, layers, audio_sources })` applies from the next frame without restarting the capture: encoders are created first (an error changes nothing), layers keep their encoder when their id stays, new ids get threads, removed ones stop, a new codec swaps every encoder (first frame a keyframe), and the @@ -99,7 +103,9 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder - `stats()`: `StreamerStats` with capture fps, convert time and threads, dropped frames, codec, and per layer (`LayerStats`) size, frames, keyframes, dropped, fps, kbit/s, encode time, target bitrate, threads - and encoder speed. Counters are atomics; rates are computed once a + and encoder speed; the audio mix's level and limiter gain, and per audio + source (`AudioSourceStats`) level, state, latency, underruns and why it + captures nothing, if so. Counters are atomics; rates are computed once a second, and a one-line summary is logged every 5 s at debug level (`RUST_LOG=voelin_core::media=debug`). - `CaptureBackend`: `Auto` (the session default: portal on Wayland, X11, @@ -122,6 +128,70 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder jitter buffer and mixer under a made-up client id, with its own volume. Playback is mono like the rest of the audio path. +## Stream audio + +The audio of our stream is a mix of any number of sources +(`StreamerConfig::audio_sources`: `AudioSourceSpec { kind, gain, muted }`): + +| `AudioSourceKind` | Captures | +|---|---| +| `DesktopWithoutSelf` (default) | everything that plays except Voelin: viewers do not hear the voices or streams we play | +| `App(AppMatch::Name(..))` | one application by name, ignoring case: application name or executable (`.exe` optional), the package on Android; found again when it restarts | +| `App(AppMatch::Pid(..))` | one process and its children (Linux, Windows) | +| `WindowAudio` | the application of the shared window: X11 `_NET_WM_PID`, the owner of a Windows `HWND`. The ScreenCast portal does not say whose window it shares; on Wayland, pick the application | +| `Microphone` | our microphone as the voice connection sends it (after echo cancellation, noise suppression and gain control), through `voelin_audio::tap::microphone()`, while a voice connection runs | +| `Synthetic { hz }` | a quiet sine tone (tests, and the default with the test pattern) | + +- Mixer (`voelin_media::mix::StreamMixer`): each source has inputs, + lock-free single-producer rings that capture threads fill at their own + pace, rate and channel count. Each input is held at a small latency + (40 ms by default, more for an input that delivers in bursts or keeps + arriving late). An input that runs dry fades out and buffers again + while the others go on. Clock drift is absorbed by resampling up to + 0.5 % while a buffer is off target. The sum passes a master gain and a + soft limiter, so it never exceeds full scale. Levels (peak and RMS) of + every source and of the output are atomics. Nothing is allocated per + block (`tests/mix_alloc.rs`; `benches/mix.rs` measures it). +- The streamer's audio thread mixes one 20 ms block whenever + `BlockClock` says it is due (monotonic clock, exact, no drift) and + encodes it with Opus in music mode. The block's number is its RTP time, + so the audio follows real time across silences and stalls; after a + stall of more than 25 blocks it jumps ahead instead of sending a burst. + It also mixes before a sink is attached, so the inputs keep draining. +- `StreamerConfigUpdate::audio_sources` changes the sources live. + Sources whose kind stays keep their capture and take the new gain and + mute; `Some(vec![])` leaves a silent track. A source that cannot + capture (an application that is not running, no PipeWire, a window + whose process is unknown) does not fail the stream: its + `AudioSourceStats::error` and `Streamer::audio_error()` say why. + `Streamer::audio_mixer()` hands out the `MixerHandle` for meters. +- The settings key `stream.audio_sources` stores the sources as JSON, e.g. + `[{"kind": "desktop"}, {"kind": "app", "name": "firefox", "gain": 0.5}, + {"kind": "microphone", "muted": true}]`. Other kinds are `"window"` and + `"synthetic"` (`frequency`), and an app can be given by `"pid"`. The + default is desktop audio; `[]` shares without sound. The desktop app + reads it when sharing starts (`media::audio_source_specs`). + `media::audio_apps()` lists the applications for a picker. + +What applications play is captured by `capture::playback::start_playback`: + +| Platform | All but ours | One application | Application list | +|---|---|---|---| +| Linux (PipeWire) | `pipewire_links::LinkManager`: a capture stream of ours that the session manager leaves unlinked (`node.autoconnect = false`) gets links from the output ports of every other playback stream (`Stream/Output/Audio`); PipeWire sums them. Links follow streams as they come and go | links from that application's streams only | playback streams in the registry, one entry per application, live | +| Windows | WASAPI process loopback excluding our process tree (before Windows 10 2004: plain loopback of the default device, which includes our playback) | process loopback including the process tree; by name, one capture per matching process, matched again every 2 s | processes with audio sessions on any playback device, polled every 2 s | +| Android | `AudioPlaybackCapture` excluding our uid | matching the package's uid | launchable apps (Android cannot tell which play) | + +On Linux, our own streams are recognised by the process id of the node, of +its client, or of the client's socket (`pipewire.sec.pid`, compared with our +own connection's, which also works in a sandbox), walked up the `/proc` +parent chain. The playing sides of loopbacks and filters (`node.link-group`) +are skipped: what they replay is captured at its source. This needs no +session-manager policy and no extra sink, and leaves the user's routing and +volumes alone. On Android, a capture needs the running screen capture and +the microphone permission, and apps can opt out +(`allowAudioPlaybackCapture`, or usages other than media, game and unknown, +e.g. calls). + ## Codecs Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with @@ -205,14 +275,14 @@ found at ..."). ## Capture -| Platform | Screen | System audio | +| Platform | Screen | System audio (`AudioCapture`; streams use [Stream audio](#stream-audio)) | |---|---|---| | any | `SyntheticScreen` | `SineSource` | | Linux X11 (`x11`, default) | `X11Capture`: MIT-SHM 1.2 (memfd passed to the server) or GetImage; RandR 1.5 monitors; windows from `_NET_CLIENT_LIST` (root children without a WM); XFixes cursor blended in | | | Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream (LINEAR DMA-BUF or shared memory) | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) | | Linux wlroots (`wlroots`, default) | `WlrootsCapture`: `ext-image-copy-capture-v1`, else `wlr-screencopy-unstable-v1`, outputs only, shared memory | | | Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback | -| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture`, 48 kHz float) | +| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture` of every app but ours, 48 kHz float) | `default_screen_capture()` picks a registered external provider first (`capture::external::set_screen_provider`, which the Android app calls at @@ -251,12 +321,11 @@ Notes: - X11 reads through the shared-memory segment in place (cursor blended into it); the monitor or window geometry is looked up once a second rather than per frame. x11rb still allocates a small reply buffer per request. -- PipeWire system audio captures everything the default sink plays, including - our own playback (TeamSpeak voices): PipeWire has no "all but this process" - monitor. Excluding our nodes needs a private null sink with links from every - other application's output (via the registry); TODO. Until then, play voices - on another sink or accept that viewers hear them. Without a PipeWire daemon, - `start` returns `Error::CaptureUnavailable`. +- `PipeWireAudioCapture` (the plain `AudioCapture`) captures everything the + default sink plays, including our own playback. Streams do not use it: their + desktop audio links every other application's playback into a capture + stream of ours ([Stream audio](#stream-audio)). Without a PipeWire daemon, + both return `Error::CaptureUnavailable`. - Windows process loopback needs Windows 10 2004 or later. ## Performance and benchmarks @@ -369,6 +438,12 @@ run on Windows yet. | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | | Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `voelin-core` `stream::tests::test_pattern_through_stream_tasks` | tested | | Stream audio (RTP time → jitter buffer ids, volume, end) | `voelin-core` `audio::tests::stream_audio_with_volume`, stream task test | tested | +| Stream mixer (latency, fade on underrun, drift correction, rate conversion, limiter, levels, live source changes), `BlockClock` | `voelin-media` `mix::tests`, `tests/mix_alloc.rs` (no allocation per block) | tested | +| Application audio on PipeWire: desktop without our own stream, by name, by pid, a new player linked live, a quit one dropped, a restarted one matched again, the app list | `voelin-media/tests/pipewire_apps.rs` (private PipeWire, WirePlumber and D-Bus; tones told apart by frequency) | tested with PipeWire 1.0 and WirePlumber 0.4; skipped without them | +| Streamer audio sources (mix levels, gain, mute, live change, microphone tap, window source error, silence) | `voelin-core` `media::tests::audio_sources_change_live`, `audio_sources_from_settings`, `settings::tests::audio_sources` | tested | +| X11 `_NET_WM_PID` of the shared window | `tests/x11_capture.rs` under Xvfb | tested | +| WASAPI per-process loopback, audio sessions, `HWND` owner | – | type-checked for `x86_64-pc-windows-gnu` only | +| Android per-app and all-but-ours playback capture | `cargo ndk -t arm64-v8a clippy`, `gradlew compileDebugKotlin` | compiles only (no device or emulator here) | | The same through the TeamSpeak 6 server | `voelin-core/tests/media_live.rs` (`VOELIN_LIVE=1`), `voelinctl stream start --synthetic` / `watch --expect-frames` | tested against 6.0.0-beta13.1 | | X11 monitor capture → VP8 → server → decoder | `voelinctl stream start --source x11` under Xvfb | tested manually (debug build: about 8 fps at 1400×900) | | Desktop app watching and sharing | Xvfb, `VOELIN_AUTOWATCH` / `VOELIN_AUTOSHARE` against voelinctl, screenshots | tested manually | diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 1b1624d..2441f4a 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -11,12 +11,23 @@ # 6. relay chat: a query relay reads channel chat and posts into the channel # 7. gateway (tsgw): login with a TeamSpeak identity, presence, channel chat # both ways, refusal of an identity the server does not know -# 8. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream -# 9. late stream (TeamSpeak 6 only): a viewer that connects after the stream +# 8. chat history through the engine (voelinctl gateway --engine): an admin +# sets a runtime gateway setting; messages sent while a user is offline +# reach the user's stored history when it connects again +# 9. pins, reactions and topics through the engine: post, pin (allowed by +# a permission rule the admin sets), react, start a topic from the post, +# post into it, read the topic and the pins back +# 10. stream directory (TeamSpeak 6 only): an engine session's stream +# registers itself in the gateway's directory; a viewer that connects +# later finds it there and watches it +# 11. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream +# 12. late stream (TeamSpeak 6 only): a viewer that connects after the stream # started finds it (requeststreaminfo) and watches it # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) -# Env: VOELINCTL=path/to/voelinctl (default: builds target/debug/voelinctl) +# Env: VOELINCTL=path/to/voelinctl, TSGW=path/to/tsgw (default: builds both +# into $CARGO_TARGET_DIR or target) +# TSGW_PORT_TS3, TSGW_PORT_TS6: gateway ports (default 7787, 7788) # COMPOSE_FILE=dev/docker-compose.yml set -euo pipefail @@ -29,16 +40,17 @@ mkdir -p "$STATE_DIR" # Never leave background clients behind. trap 'kill $(jobs -p) 2>/dev/null || true' EXIT +BUILD_DIR="${CARGO_TARGET_DIR:-target}/debug" if [[ -z "${VOELINCTL:-}" ]]; then cargo build --quiet -p voelinctl -p voelin-gateway - VOELINCTL=target/debug/voelinctl + VOELINCTL=$BUILD_DIR/voelinctl fi -TSGW="${TSGW:-target/debug/tsgw}" +TSGW="${TSGW:-$BUILD_DIR/tsgw}" declare -A PORTS=([ts3]=9987 [ts6]=9988) # ServerQuery transport and address per server (dev/docker-compose.yml). declare -A QUERY=([ts3]="raw 127.0.0.1:10011" [ts6]="ssh 127.0.0.1:10022") -declare -A GATEWAY=([ts3]=7787 [ts6]=7788) +declare -A GATEWAY=([ts3]=${TSGW_PORT_TS3:-7787} [ts6]=${TSGW_PORT_TS6:-7788}) QUERY_SECRET=voelin-dev-admin SERVERS=("$@") [[ ${#SERVERS[@]} -eq 0 ]] && SERVERS=(ts3 ts6) @@ -201,7 +213,8 @@ relay_check() { gateway_check() { local svc=$1 addr=$2 port=${GATEWAY[$svc]} out="$STATE_DIR/gateway.log" local url="ws://127.0.0.1:$port/v1" token="gw-$RANDOM$RANDOM" - "$TSGW" --config "dev/tsgw-$svc.toml" >"$STATE_DIR/tsgw-$svc.log" 2>&1 & + "$TSGW" --config "dev/tsgw-$svc.toml" --set "listen.bind=127.0.0.1:$port" \ + --set "history.path=$STATE_DIR/tsgw-$svc.db" >"$STATE_DIR/tsgw-$svc.log" 2>&1 & local gateway=$! for _ in $(seq 1 40); do grep -q "listening" "$STATE_DIR/tsgw-$svc.log" 2>/dev/null && break @@ -236,10 +249,109 @@ gateway_check() { fi grep -E "presence:|to-gateway-$token" "$out" grep "from-gateway-$token" "$STATE_DIR/gateway-heard.log" + + history_check "$svc" "$addr" "$url" "$user" + features_check "$svc" "$url" "$user" + if [[ $svc == ts6 ]]; then + directory_check "$svc" "$addr" "$url" "$user" + fi kill "$gateway" wait "$gateway" 2>/dev/null || true } +# An engine session through the gateway: voelinctl gateway --engine. +engine() { + local url=$1 identity=$2 + shift 2 + "$VOELINCTL" gateway "$url" --identity "$identity" --engine "$@" +} + +# A gateway request as the server's admin; the answer must contain $expect. +admin_request() { + local svc=$1 url=$2 request=$3 expect=$4 out="$STATE_DIR/admin-request.log" + if ! engine "$url" "$STATE_DIR/$svc-admin.json" --request "$request" --expect "$expect" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" + fail "gateway request $request was not answered with $expect" + fi + grep -F "$expect" "$out" | cut -c1-200 +} + +# Messages sent while a user is offline reach the user's stored history +# through the gateway when the user connects again. +history_check() { + local svc=$1 addr=$2 url=$3 user=$4 token="offline-$RANDOM$RANDOM" + local db="$STATE_DIR/$svc-history-$$.db" out="$STATE_DIR/history.log" + rm -f "$db"* + # The gateway reads channel 1 even while nobody has it open (runtime setting). + admin_request "$svc" "$url" '{"config_set":{"key":"relay.pinned_channels","value":[1]}}' \ + '"config_value":{"entry":{"key":"relay.pinned_channels","value":[1]' + # First visit: the chat is synced and stored. + if ! engine "$url" "$user" --db "$db" --chat channel:1 --expect "history gateway channel:1 batch" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" + fail "first chat history sync failed" + fi + # Away: someone talks in the channel. + sleep 2 + "$VOELINCTL" connect "$addr" --nick history-talker chat channel "$token-1" + "$VOELINCTL" connect "$addr" --nick history-talker chat channel "$token-2" + sleep 1 + # Back: the stored history at once, then what was missed, from the gateway. + if ! engine "$url" "$user" --db "$db" --chat channel:1 --expect "$token-2" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" "$STATE_DIR/tsgw-$svc.log" + fail "messages sent while offline did not arrive" + fi + grep -E "^history gateway channel:1 .*$token-1" "$out" || { cat "$out"; fail "$token-1 not from the gateway"; } + grep -E "^history gateway channel:1 .*$token-2" "$out" || { cat "$out"; fail "$token-2 not from the gateway"; } + # And stored: the next visit shows them from the database first. + if ! engine "$url" "$user" --db "$db" --chat channel:1 --expect "history gateway channel:1 batch" \ + --seconds 15 >"$out" 2>&1; then + cat "$out" + fail "third chat history sync failed" + fi + grep -E "^history local channel:1 .*$token-2" "$out" || { cat "$out"; fail "$token-2 was not stored"; } + admin_request "$svc" "$url" '{"config_reset":{"key":"relay.pinned_channels"}}' '"config_value"' >/dev/null + rm -f "$db"* +} + +# Post, pin, react, topic and topic post through the engine as a normal user; +# pinning is allowed by a permission rule the admin sets for the test. +features_check() { + local svc=$1 url=$2 user=$3 out="$STATE_DIR/roundtrip.log" + admin_request "$svc" "$url" '{"perm_set":{"action":"pin","rule":{"everyone":true}}}' '"perm_rules"' >/dev/null + if ! engine "$url" "$user" --roundtrip channel:1 --seconds 20 >"$out" 2>&1; then + cat "$out" + admin_request "$svc" "$url" '{"perm_reset":{"action":"pin"}}' '"perm_rules"' >/dev/null || true + fail "pin/react/topic round trip failed" + fi + admin_request "$svc" "$url" '{"perm_reset":{"action":"pin"}}' '"perm_rules"' >/dev/null + grep -E "^roundtrip|\"pinned\":\{|\"reaction\":\{" "$out" | cut -c1-160 +} + +# TeamSpeak 6: an engine session streams; its stream registers in the +# gateway's directory; a viewer that connects later finds it and watches it. +directory_check() { + local svc=$1 addr=$2 url=$3 user=$4 streamer="dir-$$-$RANDOM" title="directory-$RANDOM" + local out="$STATE_DIR/directory-stream.log" viewer_out="$STATE_DIR/directory-watch.log" + engine "$url" "$STATE_DIR/$svc-admin.json" --voice "$addr" --nick "$streamer" --loopback \ + --stream-seconds 30 --stream-title "$title" --seconds 45 >"$out" 2>&1 & + local streamer_pid=$! + for _ in $(seq 1 80); do grep -q '"stream_registered"' "$out" 2>/dev/null && break; sleep 0.25; done + grep -q '"stream_registered"' "$out" || { cat "$out"; fail "the stream did not register in the directory"; } + if ! engine "$url" "$user" --voice "$addr" --nick "late-dir-$$" --loopback \ + --watch-streamer "$streamer" --expect-frames 30 --seconds 25 >"$viewer_out" 2>&1; then + cat "$viewer_out" "$out" + fail "late viewer did not watch the stream from the directory" + fi + grep -qF "\"title\":\"$title\"" "$viewer_out" || { cat "$viewer_out"; fail "the directory did not list the stream"; } + kill -INT "$streamer_pid" 2>/dev/null || true + wait "$streamer_pid" 2>/dev/null || true + grep -E '"stream_registered"' "$out" | cut -c1-160 + grep -E "^watching|^received" "$viewer_out" +} + for svc in "${SERVERS[@]}"; do port=${PORTS[$svc]:?unknown server $svc} addr="127.0.0.1:$port" diff --git a/tools/voelinctl/src/engine.rs b/tools/voelinctl/src/engine.rs new file mode 100644 index 0000000..2ba88a5 --- /dev/null +++ b/tools/voelinctl/src/engine.rs @@ -0,0 +1,500 @@ +//! `voelinctl gateway --engine`: one engine session (voelin-core) with the +//! gateway (and optionally voice), for chat history, the gateway's features +//! and the stream directory as the app uses them. +//! +//! Prints one line per event: `history ...` per message +//! of a history batch (then `history batch n=.. complete=..`), +//! `update ` per gateway update, `chat ...` for live messages, +//! `state ...`, `streams ...`, `stream ...`, `watch ...`, `error: ...`. +//! `--expect TEXT` succeeds on the first line containing TEXT. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use tokio::sync::broadcast::error::RecvError; +use tokio::time::{Instant as TokioInstant, sleep_until, timeout_at}; +use voelin_core::gateway::{GatewayRequest, GatewayUpdate}; +use voelin_core::history::HistoryMessage; +use voelin_core::settings::Settings; +use voelin_core::stream::{FrameSource, MediaKind, PeerConfig, StreamSetup, SyntheticSource}; +use voelin_core::{ + Command, Engine, Event, History, HistorySource, ObserveState, StreamState, VoiceOptions, + VoiceState, WatchState, +}; +use voelin_model::ChatTarget; + +use crate::gateway::{GatewayArgs, parse_target, target_name}; + +const SESSION: u64 = 1; + +fn message_line(source: HistorySource, target: &ChatTarget, m: &HistoryMessage) -> String { + let reactions: Vec = m + .reactions + .iter() + .map(|r| format!("{}{}{}", r.emoji, r.count, if r.me { "*" } else { "" })) + .collect(); + format!( + "history {} {} id={} remote={} topic={} pinned={} reactions=[{}] {}: {}", + source_name(source), + target_name(target), + m.id, + m.remote_id.map_or("-".into(), |r| r.to_string()), + m.topic_id.map_or("-".into(), |t| t.to_string()), + m.pinned, + reactions.join(","), + m.message.author_name, + m.message.text + ) +} + +fn source_name(source: HistorySource) -> &'static str { + match source { + HistorySource::Local => "local", + HistorySource::Gateway => "gateway", + HistorySource::Live => "live", + } +} + +/// What the run is waiting for. +struct Run { + expect: Option, + /// Lines printed so far that matched. + done: bool, +} + +impl Run { + fn print(&mut self, line: String) { + if self.expect.as_ref().is_some_and(|e| line.contains(e.as_str())) { + self.done = true; + } + println!("{line}"); + } +} + +pub async fn run(args: GatewayArgs) -> Result<()> { + let identity = crate::identity::load(&args.identity)?; + let settings = Settings::in_memory(); + if let Some(e) = settings.apply_overrides(args.set.iter().map(String::as_str)).first() { + bail!("--set: {e}"); + } + let history = match &args.db { + Some(path) => History::open(path).with_context(|| format!("history {}", path.display()))?, + None => History::in_memory(), + }; + let engine = Engine::start_with(settings, history); + let mut events = engine.subscribe(); + let mut frames = engine.subscribe_frames(); + let deadline = TokioInstant::now() + Duration::from_secs(args.seconds); + let mut out = Run { expect: args.expect.clone(), done: false }; + + let chats: Vec = + args.chat.iter().map(|t| parse_target(t)).collect::>()?; + for target in &chats { + engine.send(Command::OpenChat { session: SESSION, target: target.clone() }); + } + let roundtrip = args.roundtrip.as_deref().map(parse_target).transpose()?; + if let Some(target) = &roundtrip { + engine.send(Command::OpenChat { session: SESSION, target: target.clone() }); + } + engine.send(Command::ObserveGateway { + session: SESSION, + url: args.url.clone(), + identity: Box::new(identity.clone()), + }); + if let Some(addr) = &args.voice { + let mut options = VoiceOptions::new(addr, &args.nick); + options.identity = Some(identity); + if args.loopback { + options.stream_peer = PeerConfig::loopback(); + } + engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) }); + } + let requests: Vec = args + .request + .iter() + .map(|r| serde_json::from_str(r).with_context(|| format!("--request {r}"))) + .collect::>()?; + + let mut gateway_up = false; + let mut voice_up = false; + let mut older_left: HashMap = + chats.iter().map(|t| (t.clone(), args.older)).collect(); + // The oldest message shown per chat: (ts_ms, id). + let mut oldest: HashMap = HashMap::new(); + let mut rt = roundtrip.map(Roundtrip::new); + let mut streaming: Option<(Instant, tokio::task::JoinHandle<()>)> = None; + let mut stream_started = false; + let mut watching = false; + let mut nicknames: HashMap = HashMap::new(); + let mut video_frames = 0u64; + + loop { + if out.done && rt.as_ref().is_none_or(|r| r.finished) { + return Ok(()); + } + if let Some(r) = &rt + && let Some(e) = &r.failed + { + bail!("roundtrip failed: {e}"); + } + // Our stream's time is up. + if let Some((until, _)) = &streaming + && Instant::now() >= *until + { + let (_, feeder) = streaming.take().unwrap(); + feeder.abort(); + engine.send(Command::StopStream { session: SESSION }); + } + let wake = streaming + .as_ref() + .map(|(until, _)| TokioInstant::from_std(*until)) + .unwrap_or(deadline) + .min(deadline); + let event = tokio::select! { + e = timeout_at(wake, events.recv()) => match e { + Ok(Ok(e)) => e, + Ok(Err(RecvError::Lagged(_))) => continue, + Ok(Err(RecvError::Closed)) => bail!("engine stopped"), + Err(_) if TokioInstant::now() >= deadline => break, + Err(_) => continue, + }, + f = frames.recv() => { + if let Ok(f) = f && f.frame.kind == MediaKind::Video { + video_frames += 1; + if video_frames == 1 { + out.print(format!("watch {} first video frame", f.stream_id)); + } + if args.expect_frames.is_some_and(|n| video_frames >= n) { + out.print(format!("received {video_frames} video frames")); + return Ok(()); + } + } + continue; + } + }; + match event { + Event::State { session: SESSION, state } => { + out.print(format!( + "state voice={:?} observe={:?} server_uid={}", + state.voice, + state.observe, + state.server_uid.as_deref().unwrap_or("-") + )); + voice_up = state.voice == VoiceState::Connected && state.own_channel.is_some(); + if state.observe == ObserveState::Off && gateway_up { + gateway_up = false; + } + } + Event::Gateway { session: SESSION, update } => { + out.print(format!("update {}", serde_json::to_string(&update)?)); + if let GatewayUpdate::Connected { .. } = &update { + gateway_up = true; + for request in &requests { + engine + .send(Command::Gateway { session: SESSION, request: request.clone() }); + } + } + if let Some(r) = &mut rt { + r.update(&engine, &update); + } + } + Event::ChatHistory { session: SESSION, target, messages, source, complete } => { + for m in &messages { + out.print(message_line(source, &target, m)); + } + out.print(format!( + "history {} {} batch n={} complete={complete}", + source_name(source), + target_name(&target), + messages.len() + )); + if source != HistorySource::Live { + for m in &messages { + let at = (m.message.ts_ms, m.id); + let o = oldest.entry(target.clone()).or_insert(at); + *o = (*o).min(at); + } + } + if let Some(r) = &mut rt { + r.history(&engine, &messages); + } + // Page back after each batch from the gateway. + let left = older_left.get(&target).copied().unwrap_or(0); + if left > 0 && source == HistorySource::Gateway && !complete { + older_left.insert(target.clone(), left - 1); + let before = oldest.get(&target).map(|(_, id)| *id); + engine.send(Command::LoadOlderHistory { session: SESSION, target, before }); + } + } + Event::Chat { session: SESSION, message } => out.print(format!( + "chat {} {}: {}", + target_name(&message.target), + message.author_name, + message.text + )), + Event::Presence { session: SESSION, presence } => { + nicknames = presence.clients.values().map(|c| (c.id, c.nickname.clone())).collect(); + } + Event::ServerInfo { session: SESSION, name, flavor, .. } => { + out.print(format!("server {name:?} {flavor:?}")); + } + Event::StreamsChanged { session: SESSION, streams } => { + for s in &streams { + let nick = nicknames.get(&s.streamer.0).map_or("?", String::as_str); + out.print(format!( + "streams: {} by {nick} ({}) {:?}", + s.id, s.streamer.0, s.name + )); + } + if let Some(wanted) = &args.watch_streamer + && !watching && let Some(s) = streams + .iter() + .find(|s| nicknames.get(&s.streamer.0).is_some_and(|n| n == wanted)) + { + watching = true; + out.print(format!("watching {}", s.id)); + engine.send(Command::WatchStream { session: SESSION, stream_id: s.id.clone() }); + } + } + Event::StreamState { session: SESSION, state } => match state { + StreamState::Starting => out.print("stream starting".into()), + StreamState::Live { id, sink } => { + out.print(format!("stream live {id}")); + let seconds = args.stream_seconds.unwrap_or(0); + let feeder = tokio::spawn(async move { + let mut source = SyntheticSource::new(30, 2000, true); + let mut buf = Vec::new(); + while sink.is_live() { + source.poll_frames(Instant::now(), &mut buf); + for f in buf.drain(..) { + sink.send(f); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }); + streaming = Some((Instant::now() + Duration::from_secs(seconds), feeder)); + } + StreamState::Ended(reason) => { + out.print(format!("stream ended {reason:?}")); + if args.stream_seconds.is_some() && streaming.is_none() { + // Give the directory update a moment to go out. + sleep_until(TokioInstant::now() + Duration::from_millis(500)).await; + return Ok(()); + } + } + }, + Event::WatchState { session: SESSION, stream_id, state } => { + out.print(format!("watch {stream_id} {state:?}")); + if let WatchState::Ended(reason) = state + && args.expect_frames.is_some() + { + bail!("the stream ended before enough frames arrived: {reason:?}"); + } + } + Event::Error { session: SESSION, message } => out.print(format!("error: {message}")), + _ => {} + } + // Stream once voice (and the gateway, if any) are up. + if args.stream_seconds.is_some() && !stream_started && voice_up && gateway_up { + stream_started = true; + let setup = StreamSetup { name: args.stream_title.clone(), ..Default::default() }; + engine.send(Command::StartStream { session: SESSION, setup, auto_accept: true }); + } + } + if let Some(r) = &rt + && !r.finished + { + bail!("roundtrip did not finish (step {:?})", r.step); + } + if args.expect.is_some() && !out.done { + bail!("expected output did not appear"); + } + if args.expect_frames.is_some() { + bail!("received only {video_frames} video frames"); + } + Ok(()) +} + +/// The steps of `--roundtrip`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Step { + Post, + Pin, + React, + Topic, + TopicPost, + TopicHistory, + Pins, + Done, +} + +/// Post, pin, react, start a topic from the message, post into it, read +/// the topic and the pins; each answer is checked. +struct Roundtrip { + target: ChatTarget, + tag: String, + step: Step, + /// Gateway and local id of our post. + remote: i64, + local: i64, + topic: i64, + pinned_row: bool, + pinned_push: bool, + reacted_row: bool, + started: bool, + finished: bool, + failed: Option, +} + +impl Roundtrip { + fn new(target: ChatTarget) -> Self { + let tag = format!("{}", std::process::id() % 100_000); + Self { + target, + tag, + step: Step::Post, + remote: 0, + local: 0, + topic: 0, + pinned_row: false, + pinned_push: false, + reacted_row: false, + started: false, + finished: false, + failed: None, + } + } + + fn send(&self, engine: &Engine, request: GatewayRequest) { + engine.send(Command::Gateway { session: SESSION, request }); + } + + fn next(&mut self, engine: &Engine, step: Step) { + self.step = step; + println!("roundtrip: {step:?}"); + let target = self.target.clone(); + match step { + Step::Post => self.send( + engine, + GatewayRequest::Post { target, text: format!("rt-{}", self.tag), topic: None }, + ), + Step::Pin => self.send(engine, GatewayRequest::Pin { message_id: self.remote }), + Step::React => self.send( + engine, + GatewayRequest::React { message_id: self.remote, emoji: "👍".into() }, + ), + Step::Topic => self.send( + engine, + GatewayRequest::CreateTopic { + target, + title: format!("rt topic {}", self.tag), + message_id: Some(self.remote), + }, + ), + Step::TopicPost => self.send( + engine, + GatewayRequest::Post { + target, + text: format!("rt-in-topic-{}", self.tag), + topic: Some(self.topic), + }, + ), + Step::TopicHistory => self.send( + engine, + GatewayRequest::TopicHistory { + target, + topic: self.topic, + before: None, + limit: None, + }, + ), + Step::Pins => self.send(engine, GatewayRequest::Pins { target }), + Step::Done => { + self.finished = true; + println!("roundtrip ok"); + } + } + } + + fn update(&mut self, engine: &Engine, update: &GatewayUpdate) { + match update { + GatewayUpdate::Connected { .. } if !self.started => { + self.started = true; + self.next(engine, Step::Post); + } + GatewayUpdate::Failed { request, message, .. } => { + self.failed = Some(format!("{request}: {message}")); + } + GatewayUpdate::Posted { message } if self.step == Step::Post => { + self.remote = message.remote_id.unwrap_or_default(); + self.local = message.id; + self.next(engine, Step::Pin); + } + GatewayUpdate::Pinned { pin, .. } if self.step == Step::Pin => { + self.pinned_push = pin.message.id == self.local; + self.after_pin(engine); + } + GatewayUpdate::Reaction { message_id, added: true, .. } + if self.step == Step::React && *message_id == self.remote => + { + if self.reacted_row { + self.next(engine, Step::Topic); + } + } + GatewayUpdate::Topic { topic } if self.step == Step::Topic => { + if topic.root_message_id != Some(self.remote) { + self.failed = Some(format!("topic from another message: {topic:?}")); + return; + } + self.topic = topic.id; + self.next(engine, Step::TopicPost); + } + GatewayUpdate::Posted { message } if self.step == Step::TopicPost => { + if message.topic_id != Some(self.topic) { + self.failed = Some(format!("posted outside the topic: {message:?}")); + return; + } + self.next(engine, Step::TopicHistory); + } + GatewayUpdate::TopicHistory { messages, .. } if self.step == Step::TopicHistory => { + let text = format!("rt-in-topic-{}", self.tag); + if !messages.iter().any(|m| m.message.text == text) { + self.failed = Some(format!("topic history without {text}")); + return; + } + self.next(engine, Step::Pins); + } + GatewayUpdate::Pins { pins, .. } if self.step == Step::Pins => { + if !pins.iter().any(|p| p.message.id == self.local) { + self.failed = Some("our pin is not listed".into()); + return; + } + self.next(engine, Step::Done); + } + _ => {} + } + } + + fn after_pin(&mut self, engine: &Engine) { + if self.pinned_row && self.pinned_push { + self.next(engine, Step::React); + } + } + + fn history(&mut self, engine: &Engine, messages: &[HistoryMessage]) { + let Some(ours) = messages.iter().find(|m| m.id == self.local && self.local != 0) else { + return; + }; + match self.step { + Step::Pin if ours.pinned => { + self.pinned_row = true; + self.after_pin(engine); + } + Step::React if ours.reactions.iter().any(|r| r.emoji == "👍" && r.me) => { + self.reacted_row = true; + } + _ => {} + } + } +} diff --git a/tools/voelinctl/src/gateway.rs b/tools/voelinctl/src/gateway.rs index c23bf6d..41efa06 100644 --- a/tools/voelinctl/src/gateway.rs +++ b/tools/voelinctl/src/gateway.rs @@ -40,17 +40,81 @@ pub struct GatewayArgs { /// Exit successfully when a client with this nickname is present. #[arg(long)] pub expect_client: Option, + + // Through the engine (voelin-core), as the app uses the gateway. + /// Run an engine session instead of a raw connection: chat history, + /// requests, the stream directory. Prints one line per event. + #[arg(long)] + pub engine: bool, + /// Chat history database (engine; default: in memory). + #[arg(long, requires = "engine")] + pub db: Option, + /// Also connect voice to this server address with the same identity (engine). + #[arg(long, requires = "engine")] + pub voice: Option, + /// Voice nickname (engine). + #[arg(long, default_value = "voelinctl", requires = "engine")] + pub nick: String, + /// Stream media over 127.0.0.1 only (engine, both ends on this machine). + #[arg(long, requires = "engine")] + pub loopback: bool, + /// Open a chat and print its history (engine): `server`, `channel:` + /// or `private:`. Repeatable. + #[arg(long = "chat", requires = "engine")] + pub chat: Vec, + /// Page back this many times in each `--chat` (engine). + #[arg(long, default_value_t = 0, requires = "engine")] + pub older: u32, + /// A gateway request as JSON, sent after login (engine), e.g. + /// `{"config_get":{"key":"relay.pinned_channels"}}`, `"config_list"`, + /// `{"perm_set":{"action":"pin","rule":{"everyone":true}}}`. Repeatable. + #[arg(long = "request", requires = "engine")] + pub request: Vec, + /// Post, pin, react, start a topic from the post, post into it and read + /// it back in this chat, checking each step (engine). + #[arg(long, requires = "engine")] + pub roundtrip: Option, + /// With `--voice` (TeamSpeak 6): stream synthetic frames this long; the + /// stream registers itself in the gateway's directory (engine). + #[arg(long, requires = "voice")] + pub stream_seconds: Option, + /// Title of that stream. + #[arg(long, default_value = "voelinctl", requires = "stream_seconds")] + pub stream_title: String, + /// With `--voice`: watch the stream of this client once it is found + /// (from the server or the gateway's directory) (engine). + #[arg(long, requires = "voice")] + pub watch_streamer: Option, + /// Exit successfully once this many video frames of the watched stream arrived. + #[arg(long, requires = "watch_streamer")] + pub expect_frames: Option, + /// An engine setting, e.g. `chat.history_page=20`. Repeatable. + #[arg(long = "set", value_name = "KEY=VALUE", requires = "engine")] + pub set: Vec, } -fn parse_target(s: &str) -> Result { +pub fn parse_target(s: &str) -> Result { match s.split_once(':') { None if s == "server" => Ok(ChatTarget::Server), Some(("channel", cid)) => Ok(ChatTarget::Channel(cid.parse().context("channel id")?)), - _ => bail!("target must be `server` or `channel:`, got {s:?}"), + Some(("private", uid)) => Ok(ChatTarget::Private(uid.to_owned())), + _ => bail!("target must be `server`, `channel:` or `private:`, got {s:?}"), + } +} + +/// [`parse_target`] back. +pub fn target_name(target: &ChatTarget) -> String { + match target { + ChatTarget::Server => "server".into(), + ChatTarget::Channel(cid) => format!("channel:{cid}"), + ChatTarget::Private(uid) => format!("private:{uid}"), } } pub async fn run(args: GatewayArgs) -> Result<()> { + if args.engine { + return crate::engine::run(args).await; + } let identity = crate::identity::load(&args.identity)?; let mut request = args.url.as_str().into_client_request()?; request diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index ec70b44..b631171 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -2,6 +2,7 @@ mod alloc; mod bench; +mod engine; mod gateway; mod identity; mod observe; @@ -51,7 +52,9 @@ enum Command { Observe(observe::ObserveArgs), /// Read and write a channel's chat through an invisible query relay. Relay(observe::RelayArgs), - /// Use a tsgw gateway as a user: presence, chat, history. + /// Use a tsgw gateway as a user: presence, chat, history; with + /// `--engine` through the client engine (chat history sync, pins, + /// reactions, topics, events, stream directory, administration). Gateway(gateway::GatewayArgs), /// TeamSpeak 6: probe how a client that arrives after a stream started /// can learn about it; prints every command both clients exchange. diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 6ecac7e..bf65c55 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -211,7 +211,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { let streamer = Streamer::start(&codecs, config).await.context("capture")?; println!("capturing with {} ({codec})", streamer.backend()); if let Some(e) = streamer.audio_error() { - println!("no system audio: {e}"); + println!("audio: {e}"); } let audio = streamer.has_audio(); (Source::Encoded(EncodedSource::new(streamer)), audio)