fix: apply audio volumes, enumerate real devices, remove dead code

- Audio sources were created but never added to the scene, so mic,
  game and app audio never reached the output; all sources are now
  added with their configured volume via obs_source_set_volume
- getAudioDevices enumerates real WASAPI devices again instead of
  returning hardcoded defaults (the crash-isolation bypass)
- Recording module split: encoder selection and output building move
  to their own files; obs_context shrinks from 1556 to 464 lines
- Remove unused IPC (recordings/timeline/export commands), the
  CommandHandler trait, crash marker files, and the stats plumbing
  that was never wired to the frontend
- Deduplicate the LCU reconnect logic into connect_and_listen
This commit is contained in:
vhaudiquet committed 2026-11-13 00:06:16 +01:00
1 parent 4f9f84446d
commit 2e98159083
15 files changed
+457 -2662

No files matched your search

+60 -151
View File
@@ -2,13 +2,12 @@
use std::sync::Arc;
use async_trait::async_trait;
use parking_lot::RwLock;
use tracing::{debug, info};
use super::protocol::{
EncoderInfo, GetEncodersResponse, GetRecordingsResponse, GetSettingsResponse,
GetStatusResponse, IpcCommand, IpcMessage, IpcResponse,
EncoderInfo, GetEncodersResponse, GetSettingsResponse, GetStatusResponse, IpcCommand,
IpcMessage, IpcResponse,
};
use crate::config::Settings;
use crate::error::Result;
@@ -17,39 +16,6 @@ use crate::recording::RecordingEngine;
use crate::state::DaemonStatus;
use crate::timeline::TimelineStore;
/// Write an *unbuffered* marker file that survives native crashes/segfaults.
///
/// The tracing log appender buffers writes in memory, so logs emitted microseconds
/// before a native segfault are lost on disk — that's why the crash diagnostics
/// added so far never appeared. This helper writes to a file with an immediate
/// `sync_all` (fsync) so the bytes hit disk before control returns. After a crash,
/// inspecting the marker directory tells us exactly how far execution got.
#[cfg(target_os = "windows")]
fn write_crash_marker(stage: &str) {
use std::io::Write;
let dir = std::env::temp_dir().join("record-daemon-crash-markers");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join(format!(
"{}_{}.txt",
stage,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
if let Ok(mut f) = std::fs::File::create(&path) {
let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id());
let _ = f.sync_all();
}
}
/// Command handler trait.
#[async_trait]
pub trait CommandHandler: Send + Sync {
/// Handle the command and return a response.
async fn handle(&self, payload: Option<serde_json::Value>) -> Result<serde_json::Value>;
}
/// Collection of IPC command handlers.
pub struct IpcHandlers {
/// Settings reference.
@@ -103,19 +69,8 @@ impl IpcHandlers {
IpcCommand::UpdateAudioSource => self.handle_update_audio_source(message.payload).await,
IpcCommand::StartRecording => self.handle_start_recording().await,
IpcCommand::StopRecording => self.handle_stop_recording().await,
IpcCommand::GetRecordings => self.handle_get_recordings().await,
IpcCommand::GetRecording { id } => self.handle_get_recording(id).await,
IpcCommand::DeleteRecording { id } => self.handle_delete_recording(id).await,
IpcCommand::GetTimeline { recording_id } => {
self.handle_get_timeline(recording_id).await
}
IpcCommand::ExportTimeline {
recording_id,
format,
} => self.handle_export_timeline(recording_id, format).await,
IpcCommand::Shutdown => self.handle_shutdown().await,
};
match result {
Ok(data) => IpcResponse::success(message.id, data),
Err(e) => {
@@ -265,57 +220,6 @@ impl IpcHandlers {
}
}
async fn handle_get_recordings(&self) -> Result<serde_json::Value> {
let recordings = self.timeline.read().get_all_recordings()?;
let response = GetRecordingsResponse { recordings };
Ok(serde_json::to_value(response)?)
}
async fn handle_get_recording(&self, id: uuid::Uuid) -> Result<serde_json::Value> {
let recording = self.timeline.read().get_recording(id)?;
Ok(serde_json::to_value(recording)?)
}
async fn handle_delete_recording(&self, id: uuid::Uuid) -> Result<serde_json::Value> {
self.timeline.write().delete_recording(id)?;
Ok(serde_json::json!({ "success": true }))
}
async fn handle_get_timeline(&self, recording_id: uuid::Uuid) -> Result<serde_json::Value> {
let timeline = self.timeline.read().get_timeline(recording_id)?;
Ok(serde_json::to_value(timeline)?)
}
async fn handle_export_timeline(
&self,
recording_id: uuid::Uuid,
format: super::protocol::ExportFormat,
) -> Result<serde_json::Value> {
let timeline = self.timeline.read().get_timeline(recording_id)?;
let exported = match format {
super::protocol::ExportFormat::Json => serde_json::to_string_pretty(&timeline)?,
super::protocol::ExportFormat::Csv => {
// Convert to CSV format
let mut csv = String::from("timestamp,event_type,description\n");
for event in &timeline.events {
csv.push_str(&format!(
"{},{},{}\n",
event.timestamp.to_rfc3339(),
event.event_type,
event.description,
));
}
csv
}
};
Ok(serde_json::json!({
"data": exported,
"format": format,
}))
}
async fn handle_shutdown(&self) -> Result<serde_json::Value> {
info!("Shutdown requested via IPC");
// Signal shutdown through status
@@ -326,38 +230,13 @@ impl IpcHandlers {
async fn handle_get_audio_devices(&self) -> Result<serde_json::Value> {
use super::protocol::GetAudioDevicesResponse;
info!("[AUDIO_ENUM] handle_get_audio_devices invoked");
// ---- CRASH ISOLATION HOOK ----
// The daemon has been crashing when Settings is opened (which triggers this
// command). The tracing log file is buffered, so logs written microseconds
// before a native segfault are lost on disk — which is why none of the
// diagnostics added so far ever showed up. To definitively determine whether
// the crash happens inside this handler / the WASAPI enumeration, we:
// 1. Write an *unbuffered* marker file (fsync) on entry and on success.
// These survive native crashes and can be inspected afterwards.
// 2. (Temporarily) return hardcoded default devices on Windows WITHOUT
// calling into WASAPI at all. If the daemon still crashes, the WASAPI
// code is NOT the culprit. If it stops crashing, WASAPI is confirmed.
#[cfg(target_os = "windows")]
{
write_crash_marker("audio_devices_enter");
info!("[AUDIO_ENUM] Windows path: returning HARDCODED defaults (WASAPI bypassed for isolation)");
let (input_devices, output_devices) = enumerate_windows_audio_devices()?;
let response = GetAudioDevicesResponse {
input_devices: vec![super::protocol::AudioDeviceInfo {
id: "default".to_string(),
name: "Default Microphone".to_string(),
is_default: true,
}],
output_devices: vec![super::protocol::AudioDeviceInfo {
id: "default".to_string(),
name: "Default Speakers".to_string(),
is_default: true,
}],
input_devices,
output_devices,
};
write_crash_marker("audio_devices_success");
Ok(serde_json::to_value(response)?)
}
@@ -418,10 +297,7 @@ impl IpcHandlers {
{
let mut settings = self.settings.write();
settings
.audio
.capture_apps
.retain(|s| s.id != id);
settings.audio.capture_apps.retain(|s| s.id != id);
crate::config::save_config(&settings)?;
}
@@ -471,8 +347,10 @@ impl IpcHandlers {
/// This runs in a `catch_unwind` so any panic in the unsafe Windows API calls
/// is contained and cannot crash the daemon process.
#[cfg(target_os = "windows")]
fn enumerate_windows_audio_devices(
) -> Result<(Vec<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>)> {
fn enumerate_windows_audio_devices() -> Result<(
Vec<super::protocol::AudioDeviceInfo>,
Vec<super::protocol::AudioDeviceInfo>,
)> {
use super::protocol::AudioDeviceInfo;
use tracing::{error, warn};
@@ -500,7 +378,10 @@ fn enumerate_windows_audio_devices(
match result {
Ok(Ok(devices)) => Ok(devices),
Ok(Err(e)) => {
warn!("WASAPI device enumeration failed, returning defaults: {}", e);
warn!(
"WASAPI device enumeration failed, returning defaults: {}",
e
);
Ok(fallback())
}
Err(panic_info) => {
@@ -512,16 +393,18 @@ fn enumerate_windows_audio_devices(
/// Inner implementation of Windows audio device enumeration using WASAPI.
#[cfg(target_os = "windows")]
fn enumerate_windows_audio_devices_inner(
) -> std::result::Result<
(Vec<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>),
fn enumerate_windows_audio_devices_inner() -> std::result::Result<
(
Vec<super::protocol::AudioDeviceInfo>,
Vec<super::protocol::AudioDeviceInfo>,
),
String,
> {
use super::protocol::AudioDeviceInfo;
use tracing::{info, warn};
use windows::core::PWSTR;
use windows::Win32::Media::Audio::*;
use windows::Win32::System::Com::*;
use windows::core::PWSTR;
use tracing::{info, warn};
fn pwstr_to_string(p: PWSTR) -> String {
if p.is_null() {
@@ -544,7 +427,10 @@ fn enumerate_windows_audio_devices_inner(
let mut input_devices = Vec::new();
let mut output_devices = Vec::new();
info!("[AUDIO_ENUM] inner: starting WASAPI enumeration on this thread (id={:?})", std::thread::current().id());
info!(
"[AUDIO_ENUM] inner: starting WASAPI enumeration on this thread (id={:?})",
std::thread::current().id()
);
let com_initialized;
unsafe {
@@ -562,14 +448,18 @@ fn enumerate_windows_audio_devices_inner(
// RPC_E_CHANGED_MODE would indicate the thread already had COM init in
// a conflicting apartment — this should never happen on a fresh thread,
// but log it loudly so we can diagnose if it ever does.
warn!("[AUDIO_ENUM] inner: CoInitializeEx failed: HRESULT=0x{:08X}", hr.0);
warn!(
"[AUDIO_ENUM] inner: CoInitializeEx failed: HRESULT=0x{:08X}",
hr.0
);
} else {
info!("[AUDIO_ENUM] inner: CoInitializeEx(MTA) succeeded");
}
// Create device enumerator
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)
.map_err(|e| format!("Failed to create MMDeviceEnumerator: {:?}", e))?;
let enumerator: IMMDeviceEnumerator =
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)
.map_err(|e| format!("Failed to create MMDeviceEnumerator: {:?}", e))?;
// Get default input device ID for comparison
let default_input_id: Option<String> = enumerator
@@ -586,7 +476,8 @@ fn enumerate_windows_audio_devices_inner(
.map(pwstr_to_string);
// Enumerate capture (input) devices
if let Ok(capture_collection) = enumerator.EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE) {
if let Ok(capture_collection) = enumerator.EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE)
{
if let Ok(count) = capture_collection.GetCount() {
for i in 0..count {
if let Ok(device) = capture_collection.Item(i) {
@@ -601,8 +492,15 @@ fn enumerate_windows_audio_devices_inner(
let name = get_device_friendly_name(&device)
.unwrap_or_else(|| format!("Input Device {}", i + 1));
debug!("Found input device: {} (id: {}, default: {})", name, id, is_default);
input_devices.push(AudioDeviceInfo { id, name, is_default });
debug!(
"Found input device: {} (id: {}, default: {})",
name, id, is_default
);
input_devices.push(AudioDeviceInfo {
id,
name,
is_default,
});
}
}
}
@@ -624,8 +522,15 @@ fn enumerate_windows_audio_devices_inner(
let name = get_device_friendly_name(&device)
.unwrap_or_else(|| format!("Output Device {}", i + 1));
debug!("Found output device: {} (id: {}, default: {})", name, id, is_default);
output_devices.push(AudioDeviceInfo { id, name, is_default });
debug!(
"Found output device: {} (id: {}, default: {})",
name, id, is_default
);
output_devices.push(AudioDeviceInfo {
id,
name,
is_default,
});
}
}
}
@@ -671,8 +576,8 @@ fn enumerate_windows_audio_devices_inner(
/// `catch_unwind` cannot trap.
#[cfg(target_os = "windows")]
fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) -> Option<String> {
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
use windows::Win32::System::Com::STGM;
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY;
// PKEY_Device_FriendlyName = { a45c254e-df1c-4efd-8020-67d146850500 }, 14
@@ -686,7 +591,9 @@ fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) ->
// Open the property store read-only.
let store: IPropertyStore = device.OpenPropertyStore(STGM(0)).ok()?;
// Read the friendly-name property.
let prop = store.GetValue(&FRIENDLY_NAME_KEY as *const PROPERTYKEY).ok()?;
let prop = store
.GetValue(&FRIENDLY_NAME_KEY as *const PROPERTYKEY)
.ok()?;
// The `windows` crate's `PROPVARIANT` implements `Display` via `to_string()`,
// which safely inspects the variant type and converts the value. For
@@ -706,8 +613,10 @@ fn get_device_friendly_name(device: &windows::Win32::Media::Audio::IMMDevice) ->
/// Enumerate audio devices on Linux using PulseAudio.
#[cfg(target_os = "linux")]
fn enumerate_linux_audio_devices(
) -> Result<(Vec<super::protocol::AudioDeviceInfo>, Vec<super::protocol::AudioDeviceInfo>)> {
fn enumerate_linux_audio_devices() -> Result<(
Vec<super::protocol::AudioDeviceInfo>,
Vec<super::protocol::AudioDeviceInfo>,
)> {
use super::protocol::AudioDeviceInfo;
use tracing::warn;
+1 -1
View File
@@ -7,7 +7,7 @@ mod handlers;
mod protocol;
mod server;
pub use handlers::{CommandHandler, IpcHandlers};
pub use handlers::IpcHandlers;
pub use protocol::{IpcCommand, IpcMessage, IpcNotification, IpcResponse};
pub use server::{IpcServer, IpcServerConfig};
+1 -32
View File
@@ -5,10 +5,9 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::config::{Settings};
use crate::config::Settings;
use crate::recording::RecordingResult;
use crate::state::DaemonStatus;
use crate::timeline::RecordingMetadata;
/// IPC message wrapper.
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -70,37 +69,12 @@ pub enum IpcCommand {
/// Stop recording.
StopRecording,
/// Get list of recordings.
GetRecordings,
/// Get specific recording details.
GetRecording { id: Uuid },
/// Delete a recording.
DeleteRecording { id: Uuid },
// Timeline commands
/// Get timeline for a recording.
GetTimeline { recording_id: Uuid },
/// Export timeline to file.
ExportTimeline {
recording_id: Uuid,
format: ExportFormat,
},
// Daemon control
/// Shutdown the daemon.
Shutdown,
}
/// Export format for timeline.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ExportFormat {
/// JSON format.
Json,
/// CSV format.
Csv,
}
/// IPC response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpcResponse {
/// Original request ID.
@@ -192,11 +166,6 @@ pub struct GetStatusResponse {
pub client_connected: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetRecordingsResponse {
pub recordings: Vec<RecordingMetadata>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetEncodersResponse {
pub available: Vec<EncoderInfo>,
+5 -40
View File
@@ -12,29 +12,6 @@ use super::handlers::IpcHandlers;
use super::protocol::{IpcMessage, IpcNotification, IpcResponse, MessageType};
use crate::error::{IpcError, Result};
/// Write an *unbuffered* marker file that survives native crashes/segfaults.
/// See [`super::handlers`] for the rationale: the tracing log appender buffers
/// writes in memory, so logs emitted microseconds before a native segfault are
/// lost on disk. This helper fsyncs so the bytes hit disk before returning.
#[cfg(target_os = "windows")]
fn write_ipc_crash_marker(stage: &str) {
use std::io::Write;
let dir = std::env::temp_dir().join("record-daemon-crash-markers");
let _ = std::fs::create_dir_all(&dir);
let path = dir.join(format!(
"{}_{}.txt",
stage,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
if let Ok(mut f) = std::fs::File::create(&path) {
let _ = writeln!(f, "{} @ {:?}", stage, std::thread::current().id());
let _ = f.sync_all();
}
}
/// IPC server configuration.
#[derive(Debug, Clone)]
pub struct IpcServerConfig {
@@ -490,13 +467,14 @@ impl IpcServer {
};
info!("[IPC] Received message ({} bytes)", line.len());
#[cfg(target_os = "windows")]
write_ipc_crash_marker("ipc_read_done");
// Parse message
let message = match IpcMessage::from_json(&line) {
Ok(msg) => {
info!("[IPC] Parsed message type={:?} command={:?}", msg.message_type, msg.command);
info!(
"[IPC] Parsed message type={:?} command={:?}",
msg.message_type, msg.command
);
msg
}
Err(e) => {
@@ -514,21 +492,10 @@ impl IpcServer {
continue;
}
};
#[cfg(target_os = "windows")]
write_ipc_crash_marker(&format!("ipc_parsed_{:?}", message.command));
// Handle message
let response = match message.message_type {
MessageType::Request => {
#[cfg(target_os = "windows")]
let cmd_dbg = format!("{:?}", message.command);
#[cfg(target_os = "windows")]
write_ipc_crash_marker(&format!("ipc_dispatch_pre_{}", cmd_dbg));
let r = handlers.handle(message).await;
#[cfg(target_os = "windows")]
write_ipc_crash_marker(&format!("ipc_dispatch_post_{}", cmd_dbg));
r
}
MessageType::Request => handlers.handle(message).await,
MessageType::Notification => {
// Notifications don't get responses
trace!("Received notification: {:?}", message);
@@ -551,8 +518,6 @@ impl IpcServer {
.write_all(b"\n")
.await
.map_err(IpcError::WriteError)?;
#[cfg(target_os = "windows")]
write_ipc_crash_marker("ipc_response_sent");
}
Ok(())