@sdeck/plugin-audio 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/sdeck-audio.exe +0 -0
- package/dist/helper.d.ts +95 -0
- package/dist/helper.d.ts.map +1 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +681 -0
- package/dist/index.js.map +11 -0
- package/native/Cargo.lock +230 -0
- package/native/Cargo.toml +29 -0
- package/native/src/main.rs +28 -0
- package/native/src/policy.rs +41 -0
- package/native/src/protocol.rs +132 -0
- package/native/src/windows_audio.rs +609 -0
- package/package.json +65 -4
- package/src/helper.ts +270 -0
- package/src/index.tsx +541 -0
- package/README.md +0 -3
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
//! Core Audio: devices, per-app sessions, change notifications, and the request loop.
|
|
2
|
+
|
|
3
|
+
#![allow(non_snake_case)]
|
|
4
|
+
|
|
5
|
+
use std::collections::BTreeMap;
|
|
6
|
+
use std::io::{BufRead, Write};
|
|
7
|
+
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
|
8
|
+
use std::time::Duration;
|
|
9
|
+
|
|
10
|
+
use serde_json::{json, Value};
|
|
11
|
+
use windows::core::{implement, Interface, Ref, Result, BOOL, GUID, PCWSTR, PWSTR};
|
|
12
|
+
use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
|
|
13
|
+
use windows::Win32::Foundation::{CloseHandle, E_INVALIDARG, PROPERTYKEY, S_OK};
|
|
14
|
+
use windows::Win32::Media::Audio::Endpoints::{
|
|
15
|
+
IAudioEndpointVolume, IAudioEndpointVolumeCallback, IAudioEndpointVolumeCallback_Impl,
|
|
16
|
+
};
|
|
17
|
+
use windows::Win32::Media::Audio::*;
|
|
18
|
+
use windows::Win32::System::Com::{
|
|
19
|
+
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_MULTITHREADED, STGM_READ,
|
|
20
|
+
};
|
|
21
|
+
use windows::Win32::System::Threading::{
|
|
22
|
+
OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
use crate::policy;
|
|
26
|
+
use crate::protocol::{
|
|
27
|
+
percent, wanted, App, Change, Command, Device, Level, Request, Snapshot, Target,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
enum Message {
|
|
31
|
+
Line(String),
|
|
32
|
+
Closed,
|
|
33
|
+
/// Something audible changed.
|
|
34
|
+
Changed,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// The safety refresh, for changes no notification reports.
|
|
38
|
+
const REFRESH: Duration = Duration::from_secs(2);
|
|
39
|
+
|
|
40
|
+
// -- Notifications -------------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
#[derive(Clone)]
|
|
43
|
+
struct Notify(Sender<Message>);
|
|
44
|
+
|
|
45
|
+
impl Notify {
|
|
46
|
+
fn changed(&self) -> Result<()> {
|
|
47
|
+
// The loop has ended if this fails; there is nobody left to tell.
|
|
48
|
+
let _ = self.0.send(Message::Changed);
|
|
49
|
+
Ok(())
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
#[implement(IMMNotificationClient)]
|
|
54
|
+
struct DeviceEvents(Notify);
|
|
55
|
+
|
|
56
|
+
impl IMMNotificationClient_Impl for DeviceEvents_Impl {
|
|
57
|
+
fn OnDeviceStateChanged(&self, _: &PCWSTR, _: DEVICE_STATE) -> Result<()> {
|
|
58
|
+
self.0.changed()
|
|
59
|
+
}
|
|
60
|
+
fn OnDeviceAdded(&self, _: &PCWSTR) -> Result<()> {
|
|
61
|
+
self.0.changed()
|
|
62
|
+
}
|
|
63
|
+
fn OnDeviceRemoved(&self, _: &PCWSTR) -> Result<()> {
|
|
64
|
+
self.0.changed()
|
|
65
|
+
}
|
|
66
|
+
fn OnDefaultDeviceChanged(&self, _: EDataFlow, _: ERole, _: &PCWSTR) -> Result<()> {
|
|
67
|
+
self.0.changed()
|
|
68
|
+
}
|
|
69
|
+
fn OnPropertyValueChanged(&self, _: &PCWSTR, _: &PROPERTYKEY) -> Result<()> {
|
|
70
|
+
Ok(())
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
#[implement(IAudioEndpointVolumeCallback)]
|
|
75
|
+
struct EndpointEvents(Notify);
|
|
76
|
+
|
|
77
|
+
impl IAudioEndpointVolumeCallback_Impl for EndpointEvents_Impl {
|
|
78
|
+
fn OnNotify(&self, _: *mut AUDIO_VOLUME_NOTIFICATION_DATA) -> Result<()> {
|
|
79
|
+
self.0.changed()
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
#[implement(IAudioSessionNotification)]
|
|
84
|
+
struct NewSessions(Notify);
|
|
85
|
+
|
|
86
|
+
impl IAudioSessionNotification_Impl for NewSessions_Impl {
|
|
87
|
+
fn OnSessionCreated(&self, _: Ref<IAudioSessionControl>) -> Result<()> {
|
|
88
|
+
self.0.changed()
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
#[implement(IAudioSessionEvents)]
|
|
93
|
+
struct SessionEvents(Notify);
|
|
94
|
+
|
|
95
|
+
impl IAudioSessionEvents_Impl for SessionEvents_Impl {
|
|
96
|
+
fn OnDisplayNameChanged(&self, _: &PCWSTR, _: *const GUID) -> Result<()> {
|
|
97
|
+
Ok(())
|
|
98
|
+
}
|
|
99
|
+
fn OnIconPathChanged(&self, _: &PCWSTR, _: *const GUID) -> Result<()> {
|
|
100
|
+
Ok(())
|
|
101
|
+
}
|
|
102
|
+
fn OnSimpleVolumeChanged(&self, _: f32, _: BOOL, _: *const GUID) -> Result<()> {
|
|
103
|
+
self.0.changed()
|
|
104
|
+
}
|
|
105
|
+
fn OnChannelVolumeChanged(&self, _: u32, _: *const f32, _: u32, _: *const GUID) -> Result<()> {
|
|
106
|
+
Ok(())
|
|
107
|
+
}
|
|
108
|
+
fn OnGroupingParamChanged(&self, _: *const GUID, _: *const GUID) -> Result<()> {
|
|
109
|
+
Ok(())
|
|
110
|
+
}
|
|
111
|
+
fn OnStateChanged(&self, _: AudioSessionState) -> Result<()> {
|
|
112
|
+
self.0.changed()
|
|
113
|
+
}
|
|
114
|
+
fn OnSessionDisconnected(&self, _: AudioSessionDisconnectReason) -> Result<()> {
|
|
115
|
+
self.0.changed()
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// Everything registered for notifications; dropping it unregisters.
|
|
120
|
+
#[derive(Default)]
|
|
121
|
+
struct Subscriptions {
|
|
122
|
+
endpoints: Vec<(IAudioEndpointVolume, IAudioEndpointVolumeCallback)>,
|
|
123
|
+
managers: Vec<(IAudioSessionManager2, IAudioSessionNotification)>,
|
|
124
|
+
sessions: Vec<(IAudioSessionControl, IAudioSessionEvents)>,
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
impl Drop for Subscriptions {
|
|
128
|
+
fn drop(&mut self) {
|
|
129
|
+
// SAFETY: each callback is unregistered from the object it was registered with.
|
|
130
|
+
unsafe {
|
|
131
|
+
for (volume, callback) in &self.endpoints {
|
|
132
|
+
let _ = volume.UnregisterControlChangeNotify(callback);
|
|
133
|
+
}
|
|
134
|
+
for (manager, callback) in &self.managers {
|
|
135
|
+
let _ = manager.UnregisterSessionNotification(callback);
|
|
136
|
+
}
|
|
137
|
+
for (session, callback) in &self.sessions {
|
|
138
|
+
let _ = session.UnregisterAudioSessionNotification(callback);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// -- Reading -------------------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
/// Takes ownership of a COM-allocated string.
|
|
147
|
+
unsafe fn take_string(text: PWSTR) -> String {
|
|
148
|
+
let out = text.to_string().unwrap_or_default();
|
|
149
|
+
CoTaskMemFree(Some(text.0 as *const _));
|
|
150
|
+
out
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
unsafe fn devices(enumerator: &IMMDeviceEnumerator, flow: EDataFlow) -> Result<Vec<IMMDevice>> {
|
|
154
|
+
let collection = enumerator.EnumAudioEndpoints(flow, DEVICE_STATE_ACTIVE)?;
|
|
155
|
+
(0..collection.GetCount()?)
|
|
156
|
+
.map(|i| collection.Item(i))
|
|
157
|
+
.collect()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
unsafe fn device_id(device: &IMMDevice) -> Result<String> {
|
|
161
|
+
Ok(take_string(device.GetId()?))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
unsafe fn device_name(device: &IMMDevice) -> String {
|
|
165
|
+
device
|
|
166
|
+
.OpenPropertyStore(STGM_READ)
|
|
167
|
+
.and_then(|store| store.GetValue(&PKEY_Device_FriendlyName))
|
|
168
|
+
.map(|value| value.to_string())
|
|
169
|
+
.unwrap_or_default()
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
unsafe fn endpoint(device: &IMMDevice) -> Result<IAudioEndpointVolume> {
|
|
173
|
+
device.Activate(CLSCTX_ALL, None)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
unsafe fn endpoint_level(volume: &IAudioEndpointVolume) -> Result<Level> {
|
|
177
|
+
Ok(Level {
|
|
178
|
+
volume: percent(volume.GetMasterVolumeLevelScalar()?),
|
|
179
|
+
muted: volume.GetMute()?.as_bool(),
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// The executable name of a process, lowercased; `None` when it cannot be asked.
|
|
184
|
+
unsafe fn process_name(pid: u32) -> Option<String> {
|
|
185
|
+
let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;
|
|
186
|
+
let mut buffer = [0u16; 1024];
|
|
187
|
+
let mut length = buffer.len() as u32;
|
|
188
|
+
let result = QueryFullProcessImageNameW(
|
|
189
|
+
handle,
|
|
190
|
+
PROCESS_NAME_WIN32,
|
|
191
|
+
PWSTR(buffer.as_mut_ptr()),
|
|
192
|
+
&mut length,
|
|
193
|
+
);
|
|
194
|
+
let _ = CloseHandle(handle);
|
|
195
|
+
result.ok()?;
|
|
196
|
+
let path = String::from_utf16_lossy(&buffer[..length as usize]);
|
|
197
|
+
path.rsplit('\\').next().map(str::to_lowercase)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
struct Session {
|
|
201
|
+
app: String,
|
|
202
|
+
active: bool,
|
|
203
|
+
control: IAudioSessionControl,
|
|
204
|
+
volume: ISimpleAudioVolume,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/// Every live audio session on every playback device.
|
|
208
|
+
unsafe fn sessions(enumerator: &IMMDeviceEnumerator) -> Result<Vec<Session>> {
|
|
209
|
+
let mut out = Vec::new();
|
|
210
|
+
for device in devices(enumerator, eRender)? {
|
|
211
|
+
// A device can disappear while it is being read; the next refresh sees the truth.
|
|
212
|
+
let Ok(manager) = device.Activate::<IAudioSessionManager2>(CLSCTX_ALL, None) else {
|
|
213
|
+
continue;
|
|
214
|
+
};
|
|
215
|
+
let Ok(list) = manager.GetSessionEnumerator() else {
|
|
216
|
+
continue;
|
|
217
|
+
};
|
|
218
|
+
for i in 0..list.GetCount()? {
|
|
219
|
+
let Ok(control) = list.GetSession(i) else {
|
|
220
|
+
continue;
|
|
221
|
+
};
|
|
222
|
+
let details: IAudioSessionControl2 = control.cast()?;
|
|
223
|
+
let state = control.GetState()?;
|
|
224
|
+
if state == AudioSessionStateExpired {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
let app = if details.IsSystemSoundsSession() == S_OK {
|
|
228
|
+
"system".to_string()
|
|
229
|
+
} else {
|
|
230
|
+
match details
|
|
231
|
+
.GetProcessId()
|
|
232
|
+
.ok()
|
|
233
|
+
.and_then(|pid| process_name(pid))
|
|
234
|
+
{
|
|
235
|
+
Some(name) => name,
|
|
236
|
+
None => continue,
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
out.push(Session {
|
|
240
|
+
app,
|
|
241
|
+
active: state == AudioSessionStateActive,
|
|
242
|
+
volume: control.cast()?,
|
|
243
|
+
control,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
Ok(out)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
struct Audio {
|
|
251
|
+
enumerator: IMMDeviceEnumerator,
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
impl Audio {
|
|
255
|
+
unsafe fn default_device(&self, flow: EDataFlow) -> Option<IMMDevice> {
|
|
256
|
+
self.enumerator.GetDefaultAudioEndpoint(flow, eConsole).ok()
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
unsafe fn device_list(&self, flow: EDataFlow) -> Result<Vec<Device>> {
|
|
260
|
+
let default = match self.default_device(flow) {
|
|
261
|
+
Some(device) => Some(device_id(&device)?),
|
|
262
|
+
None => None,
|
|
263
|
+
};
|
|
264
|
+
let mut out = Vec::new();
|
|
265
|
+
for device in devices(&self.enumerator, flow)? {
|
|
266
|
+
let (Ok(id), Ok(level)) = (
|
|
267
|
+
device_id(&device),
|
|
268
|
+
endpoint(&device).and_then(|v| endpoint_level(&v)),
|
|
269
|
+
) else {
|
|
270
|
+
continue;
|
|
271
|
+
};
|
|
272
|
+
out.push(Device {
|
|
273
|
+
default: default.as_deref() == Some(id.as_str()),
|
|
274
|
+
name: device_name(&device),
|
|
275
|
+
id,
|
|
276
|
+
level,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
out.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.id.cmp(&b.id)));
|
|
280
|
+
Ok(out)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
unsafe fn snapshot(&self) -> Result<Snapshot> {
|
|
284
|
+
// One entry per executable: its first session's level, muted only if all are.
|
|
285
|
+
let mut apps: BTreeMap<String, App> = BTreeMap::new();
|
|
286
|
+
for session in sessions(&self.enumerator)? {
|
|
287
|
+
let level = Level {
|
|
288
|
+
volume: percent(session.volume.GetMasterVolume()?),
|
|
289
|
+
muted: session.volume.GetMute()?.as_bool(),
|
|
290
|
+
};
|
|
291
|
+
apps.entry(session.app.clone())
|
|
292
|
+
.and_modify(|app| {
|
|
293
|
+
if session.active && !app.active {
|
|
294
|
+
app.level.volume = level.volume;
|
|
295
|
+
}
|
|
296
|
+
app.active |= session.active;
|
|
297
|
+
app.level.muted &= level.muted;
|
|
298
|
+
})
|
|
299
|
+
.or_insert(App {
|
|
300
|
+
name: session.app,
|
|
301
|
+
active: session.active,
|
|
302
|
+
level,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
Ok(Snapshot {
|
|
306
|
+
outputs: self.device_list(eRender)?,
|
|
307
|
+
inputs: self.device_list(eCapture)?,
|
|
308
|
+
apps: apps.into_values().collect(),
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
unsafe fn subscribe(&self, notify: &Notify) -> Result<Subscriptions> {
|
|
313
|
+
let mut subscriptions = Subscriptions::default();
|
|
314
|
+
for flow in [eRender, eCapture] {
|
|
315
|
+
for device in devices(&self.enumerator, flow)? {
|
|
316
|
+
if let Ok(volume) = endpoint(&device) {
|
|
317
|
+
let callback: IAudioEndpointVolumeCallback =
|
|
318
|
+
EndpointEvents(notify.clone()).into();
|
|
319
|
+
if volume.RegisterControlChangeNotify(&callback).is_ok() {
|
|
320
|
+
subscriptions.endpoints.push((volume, callback));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
if flow != eRender {
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
if let Ok(manager) = device.Activate::<IAudioSessionManager2>(CLSCTX_ALL, None) {
|
|
327
|
+
let callback: IAudioSessionNotification = NewSessions(notify.clone()).into();
|
|
328
|
+
// Notifications only start once the sessions have been listed.
|
|
329
|
+
let _ = manager
|
|
330
|
+
.GetSessionEnumerator()
|
|
331
|
+
.and_then(|list| list.GetCount());
|
|
332
|
+
if manager.RegisterSessionNotification(&callback).is_ok() {
|
|
333
|
+
subscriptions.managers.push((manager, callback));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
for session in sessions(&self.enumerator)? {
|
|
339
|
+
let callback: IAudioSessionEvents = SessionEvents(notify.clone()).into();
|
|
340
|
+
if session
|
|
341
|
+
.control
|
|
342
|
+
.RegisterAudioSessionNotification(&callback)
|
|
343
|
+
.is_ok()
|
|
344
|
+
{
|
|
345
|
+
subscriptions.sessions.push((session.control, callback));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
Ok(subscriptions)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/// What decides whether the notification registrations are still complete.
|
|
352
|
+
unsafe fn shape(&self) -> Result<Vec<String>> {
|
|
353
|
+
let mut shape = Vec::new();
|
|
354
|
+
for flow in [eRender, eCapture] {
|
|
355
|
+
for device in devices(&self.enumerator, flow)? {
|
|
356
|
+
shape.push(device_id(&device)?);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
for session in sessions(&self.enumerator)? {
|
|
360
|
+
let details: IAudioSessionControl2 = session.control.cast()?;
|
|
361
|
+
shape.push(take_string(details.GetSessionInstanceIdentifier()?));
|
|
362
|
+
}
|
|
363
|
+
shape.sort();
|
|
364
|
+
Ok(shape)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
unsafe fn target_endpoint(
|
|
368
|
+
&self,
|
|
369
|
+
flow: EDataFlow,
|
|
370
|
+
id: Option<&str>,
|
|
371
|
+
) -> std::result::Result<IAudioEndpointVolume, String> {
|
|
372
|
+
let device = match id {
|
|
373
|
+
Some(id) => {
|
|
374
|
+
let mut found = None;
|
|
375
|
+
for device in devices(&self.enumerator, flow).map_err(text)? {
|
|
376
|
+
if device_id(&device).map_err(text)? == id {
|
|
377
|
+
found = Some(device);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
found.ok_or("that audio device is not connected")?
|
|
381
|
+
}
|
|
382
|
+
None => self
|
|
383
|
+
.default_device(flow)
|
|
384
|
+
.ok_or("there is no default audio device")?,
|
|
385
|
+
};
|
|
386
|
+
endpoint(&device).map_err(text)
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
unsafe fn app_sessions(&self, app: &str) -> std::result::Result<Vec<Session>, String> {
|
|
390
|
+
let wanted = app.to_lowercase();
|
|
391
|
+
let found: Vec<Session> = sessions(&self.enumerator)
|
|
392
|
+
.map_err(text)?
|
|
393
|
+
.into_iter()
|
|
394
|
+
.filter(|s| s.app == wanted || s.app.strip_suffix(".exe") == Some(wanted.as_str()))
|
|
395
|
+
.collect();
|
|
396
|
+
if found.is_empty() {
|
|
397
|
+
return Err(format!("{app} is not playing or recording audio"));
|
|
398
|
+
}
|
|
399
|
+
Ok(found)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/// Applies a volume and/or mute change to a target.
|
|
403
|
+
unsafe fn change(
|
|
404
|
+
&self,
|
|
405
|
+
target: &Target,
|
|
406
|
+
volume: Option<f32>,
|
|
407
|
+
delta: Option<f32>,
|
|
408
|
+
mute: Option<Option<bool>>,
|
|
409
|
+
) -> std::result::Result<Change, String> {
|
|
410
|
+
let none = std::ptr::null();
|
|
411
|
+
match target {
|
|
412
|
+
Target::Output { device } | Target::Input { device } => {
|
|
413
|
+
let flow = if matches!(target, Target::Output { .. }) {
|
|
414
|
+
eRender
|
|
415
|
+
} else {
|
|
416
|
+
eCapture
|
|
417
|
+
};
|
|
418
|
+
let endpoint = self.target_endpoint(flow, device.as_deref())?;
|
|
419
|
+
let before = endpoint_level(&endpoint).map_err(text)?;
|
|
420
|
+
let current = endpoint.GetMasterVolumeLevelScalar().map_err(text)?;
|
|
421
|
+
if let Some(next) = wanted(current, volume, delta) {
|
|
422
|
+
endpoint
|
|
423
|
+
.SetMasterVolumeLevelScalar(next, none)
|
|
424
|
+
.map_err(text)?;
|
|
425
|
+
}
|
|
426
|
+
if let Some(muted) = mute {
|
|
427
|
+
endpoint
|
|
428
|
+
.SetMute(muted.unwrap_or(!before.muted), none)
|
|
429
|
+
.map_err(text)?;
|
|
430
|
+
}
|
|
431
|
+
let after = endpoint_level(&endpoint).map_err(text)?;
|
|
432
|
+
Ok(Change { before, after })
|
|
433
|
+
}
|
|
434
|
+
Target::App { app } => {
|
|
435
|
+
let found = self.app_sessions(app)?;
|
|
436
|
+
let lead = found.iter().find(|s| s.active).unwrap_or(&found[0]);
|
|
437
|
+
let current = lead.volume.GetMasterVolume().map_err(text)?;
|
|
438
|
+
let mut all_muted = true;
|
|
439
|
+
for session in &found {
|
|
440
|
+
all_muted &= session.volume.GetMute().map_err(text)?.as_bool();
|
|
441
|
+
}
|
|
442
|
+
let before = Level {
|
|
443
|
+
volume: percent(current),
|
|
444
|
+
muted: all_muted,
|
|
445
|
+
};
|
|
446
|
+
let next = wanted(current, volume, delta);
|
|
447
|
+
for session in &found {
|
|
448
|
+
if let Some(next) = next {
|
|
449
|
+
session.volume.SetMasterVolume(next, none).map_err(text)?;
|
|
450
|
+
}
|
|
451
|
+
if let Some(muted) = mute {
|
|
452
|
+
session
|
|
453
|
+
.volume
|
|
454
|
+
.SetMute(muted.unwrap_or(!all_muted), none)
|
|
455
|
+
.map_err(text)?;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
let after = Level {
|
|
459
|
+
volume: next.map_or(before.volume, percent),
|
|
460
|
+
muted: mute.map_or(before.muted, |m| m.unwrap_or(!all_muted)),
|
|
461
|
+
};
|
|
462
|
+
Ok(Change { before, after })
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
unsafe fn run(&self, command: Command) -> std::result::Result<Value, String> {
|
|
468
|
+
let value = |v: serde_json::Result<Value>| v.map_err(|e| e.to_string());
|
|
469
|
+
match command {
|
|
470
|
+
Command::Snapshot => value(serde_json::to_value(self.snapshot().map_err(text)?)),
|
|
471
|
+
Command::SetVolume {
|
|
472
|
+
target,
|
|
473
|
+
volume,
|
|
474
|
+
delta,
|
|
475
|
+
} => {
|
|
476
|
+
if volume.is_none() && delta.is_none() {
|
|
477
|
+
return Err("give a volume or a delta".into());
|
|
478
|
+
}
|
|
479
|
+
value(serde_json::to_value(
|
|
480
|
+
self.change(&target, volume, delta, None)?,
|
|
481
|
+
))
|
|
482
|
+
}
|
|
483
|
+
Command::SetMute { target, muted } => value(serde_json::to_value(self.change(
|
|
484
|
+
&target,
|
|
485
|
+
None,
|
|
486
|
+
None,
|
|
487
|
+
Some(muted),
|
|
488
|
+
)?)),
|
|
489
|
+
Command::SetDefault { device } => {
|
|
490
|
+
let mut previous = None;
|
|
491
|
+
let mut known = false;
|
|
492
|
+
for flow in [eRender, eCapture] {
|
|
493
|
+
for candidate in devices(&self.enumerator, flow).map_err(text)? {
|
|
494
|
+
if device_id(&candidate).map_err(text)? == device {
|
|
495
|
+
known = true;
|
|
496
|
+
if let Some(current) = self.default_device(flow) {
|
|
497
|
+
previous = Some(device_id(¤t).map_err(text)?);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if !known {
|
|
503
|
+
return Err(text(windows::core::Error::from(E_INVALIDARG))
|
|
504
|
+
+ ": that audio device is not connected");
|
|
505
|
+
}
|
|
506
|
+
policy::set_default(&device).map_err(text)?;
|
|
507
|
+
Ok(json!({ "previous": previous }))
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
fn text(error: windows::core::Error) -> String {
|
|
514
|
+
error.message()
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
fn send(line: &Value) -> std::io::Result<()> {
|
|
518
|
+
let mut out = std::io::stdout().lock();
|
|
519
|
+
writeln!(out, "{line}")?;
|
|
520
|
+
out.flush()
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
pub fn serve() -> std::result::Result<(), String> {
|
|
524
|
+
let (tx, rx) = mpsc::channel();
|
|
525
|
+
// SAFETY: COM is initialised on this thread before any object is made, and every object stays
|
|
526
|
+
// on it; the callbacks Windows runs elsewhere only send on a channel.
|
|
527
|
+
unsafe {
|
|
528
|
+
CoInitializeEx(None, COINIT_MULTITHREADED)
|
|
529
|
+
.ok()
|
|
530
|
+
.map_err(text)?;
|
|
531
|
+
let audio = Audio {
|
|
532
|
+
enumerator: CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(text)?,
|
|
533
|
+
};
|
|
534
|
+
let notify = Notify(tx.clone());
|
|
535
|
+
let device_events: IMMNotificationClient = DeviceEvents(notify.clone()).into();
|
|
536
|
+
audio
|
|
537
|
+
.enumerator
|
|
538
|
+
.RegisterEndpointNotificationCallback(&device_events)
|
|
539
|
+
.map_err(text)?;
|
|
540
|
+
|
|
541
|
+
std::thread::spawn(move || {
|
|
542
|
+
for line in std::io::stdin().lock().lines() {
|
|
543
|
+
let Ok(line) = line else { break };
|
|
544
|
+
if tx.send(Message::Line(line)).is_err() {
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
let _ = tx.send(Message::Closed);
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
let mut shape = Vec::new();
|
|
552
|
+
let mut subscriptions: Option<Subscriptions> = None;
|
|
553
|
+
let mut last: Option<Snapshot> = None;
|
|
554
|
+
let mut next = Some(Message::Changed);
|
|
555
|
+
loop {
|
|
556
|
+
// Handle everything waiting, then look at the devices once.
|
|
557
|
+
while let Some(message) = next.take() {
|
|
558
|
+
match message {
|
|
559
|
+
Message::Closed => {
|
|
560
|
+
drop(subscriptions);
|
|
561
|
+
let _ = audio
|
|
562
|
+
.enumerator
|
|
563
|
+
.UnregisterEndpointNotificationCallback(&device_events);
|
|
564
|
+
return Ok(());
|
|
565
|
+
}
|
|
566
|
+
Message::Line(line) => {
|
|
567
|
+
let answer = match serde_json::from_str::<Request>(&line) {
|
|
568
|
+
Ok(request) => match audio.run(request.command) {
|
|
569
|
+
Ok(result) => json!({ "id": request.id, "result": result }),
|
|
570
|
+
Err(error) => json!({ "id": request.id, "error": error }),
|
|
571
|
+
},
|
|
572
|
+
Err(error) => {
|
|
573
|
+
let id = serde_json::from_str::<Value>(&line)
|
|
574
|
+
.ok()
|
|
575
|
+
.and_then(|v| v.get("id").cloned());
|
|
576
|
+
json!({ "id": id, "error": format!("bad request: {error}") })
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
send(&answer).map_err(|e| e.to_string())?;
|
|
580
|
+
}
|
|
581
|
+
Message::Changed => {}
|
|
582
|
+
}
|
|
583
|
+
next = rx.try_recv().ok();
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if let Ok(current) = audio.shape() {
|
|
587
|
+
if current != shape || subscriptions.is_none() {
|
|
588
|
+
// The old registrations go first, so nothing is registered twice.
|
|
589
|
+
drop(subscriptions.take());
|
|
590
|
+
subscriptions = audio.subscribe(¬ify).ok();
|
|
591
|
+
shape = current;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if let Ok(snapshot) = audio.snapshot() {
|
|
595
|
+
if last.as_ref() != Some(&snapshot) {
|
|
596
|
+
send(&json!({ "event": "snapshot", "data": &snapshot }))
|
|
597
|
+
.map_err(|e| e.to_string())?;
|
|
598
|
+
last = Some(snapshot);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
next = match rx.recv_timeout(REFRESH) {
|
|
603
|
+
Ok(message) => Some(message),
|
|
604
|
+
Err(RecvTimeoutError::Timeout) => Some(Message::Changed),
|
|
605
|
+
Err(RecvTimeoutError::Disconnected) => Some(Message::Closed),
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdeck/plugin-audio",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Built-in sdeck audio actions: volume and mute for devices and apps, device switching.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"keywords": [
|
|
9
|
+
"sdeck-plugin"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src",
|
|
14
|
+
"native/src",
|
|
15
|
+
"native/Cargo.toml",
|
|
16
|
+
"native/Cargo.lock",
|
|
17
|
+
"bin"
|
|
18
|
+
],
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"bun": "./src/index.tsx",
|
|
25
|
+
"import": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"sdeck": {
|
|
30
|
+
"apiVersion": 2,
|
|
31
|
+
"entry": "./dist/index.js"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "bun ../../scripts/build-package.ts --target=bun",
|
|
35
|
+
"clean": "rm -rf dist",
|
|
36
|
+
"test": "bun test",
|
|
37
|
+
"build:native": "cargo build --release --manifest-path native/Cargo.toml"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@sdeck/plugin": "^0.2.0",
|
|
41
|
+
"@sdeck/schema": "^0.2.0",
|
|
42
|
+
"react": ">=19.3"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"@sdeck/plugin": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@sdeck/schema": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
51
|
+
"react": {
|
|
52
|
+
"optional": true
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@sdeck/plugin": "0.2.0",
|
|
57
|
+
"@sdeck/schema": "0.2.0"
|
|
58
|
+
},
|
|
59
|
+
"repository": {
|
|
60
|
+
"type": "git",
|
|
61
|
+
"url": "git+https://github.com/ivanoliverfabra/sdeck.git",
|
|
62
|
+
"directory": "packages/plugin-audio"
|
|
63
|
+
},
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
}
|
|
67
|
+
}
|