feat(calling): call end-to-end test with the real account
- teams.exe --join <link> / --hang-up, forwarded to the running app over the single-instance pipe - --join uses the own engine once, calls.teams_web stays untouched - audio_probe: play a wav into a render device, record one process's playback - scripts/call-e2e.mjs: Teams web with a speech mic joins a Meet now, the app joins with VB-CABLE as mic, both directions checked for speech with pauses - scripts/default-audio.ps1: switch and restore the Windows default mic - live-matrix CDP helpers moved to scripts/teams-web-cdp.mjs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1,7 +1,9 @@
1
use std::sync::Mutex;
1
2
use std::sync::atomic::{AtomicBool, Ordering};
2
3
use std::time::{Duration, Instant};
3
4
4
5
static ACTIVATION: AtomicBool = AtomicBool::new(false);
6
static COMMANDS: Mutex<Vec<String>> = Mutex::new(Vec::new());
5
7
6
8
const RETRY_INTERVAL: Duration = Duration::from_millis(200);
7
9
const RETRY_TIMEOUT: Duration = Duration::from_secs(15);
@@ -16,14 +18,31 @@ pub fn take_activation() -> bool {
16
18
ACTIVATION.swap(false, Ordering::AcqRel)
17
19
}
18
20
19
pub fn claim(name: &str, wait_for_previous: bool) -> Claim {
21
pub fn queue_command(command: &str) {
22
if !command.is_empty() {
23
COMMANDS.lock().unwrap().push(command.to_owned());
24
}
25
}
26
27
pub fn take_commands() -> Vec<String> {
28
std::mem::take(&mut *COMMANDS.lock().unwrap())
29
}
30
31
fn received(message: &[u8]) {
32
queue_command(String::from_utf8_lossy(message).trim());
33
ACTIVATION.store(true, Ordering::Release);
34
}
35
36
/// `command` travels to the running instance, which queues it for `take_commands`.
37
pub fn claim(name: &str, wait_for_previous: bool, command: &str) -> Claim {
20
38
let started = Instant::now();
21
39
loop {
22
40
if platform::try_become_primary(name) {
41
queue_command(command);
23
42
return Claim::Primary;
24
43
}
25
44
if !wait_for_previous {
26
platform::notify_primary(name);
45
platform::notify_primary(name, command);
27
46
return Claim::Forwarded;
28
47
}
29
48
if started.elapsed() >= RETRY_TIMEOUT {
@@ -41,15 +60,19 @@ fn user_name() -> String {
41
60
42
61
#[cfg(windows)]
43
62
mod platform {
44
use std::fs::OpenOptions;
45
use std::sync::atomic::Ordering;
63
use std::fs::{File, OpenOptions};
64
use std::io::{Read, Write};
65
use std::mem::ManuallyDrop;
66
use std::os::windows::io::{AsRawHandle, FromRawHandle};
46
67
use std::time::Duration;
47
68
48
69
use windows::Win32::Foundation::{
49
70
ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError,
50
INVALID_HANDLE_VALUE,
71
HANDLE, INVALID_HANDLE_VALUE,
72
};
73
use windows::Win32::Storage::FileSystem::{
74
FILE_FLAG_FIRST_PIPE_INSTANCE, FlushFileBuffers, PIPE_ACCESS_INBOUND,
51
75
};
52
use windows::Win32::Storage::FileSystem::{FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_INBOUND};
53
76
use windows::Win32::System::Pipes::{
54
77
ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
55
78
PIPE_TYPE_BYTE, PIPE_WAIT,
@@ -57,7 +80,7 @@ mod platform {
57
80
use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow};
58
81
use windows::core::PCWSTR;
59
82
60
use super::{ACTIVATION, user_name};
83
use super::{received, user_name};
61
84
62
85
const CONNECT_ATTEMPTS: u32 = 20;
63
86
const CONNECT_INTERVAL: Duration = Duration::from_millis(100);
@@ -89,7 +112,7 @@ mod platform {
89
112
}
90
113
let raw_handle = handle.0 as usize;
91
114
std::thread::spawn(move || {
92
let handle = windows::Win32::Foundation::HANDLE(raw_handle as *mut _);
115
let handle = HANDLE(raw_handle as *mut _);
93
116
loop {
94
117
let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok()
95
118
|| matches!(
@@ -97,7 +120,10 @@ mod platform {
97
120
ERROR_PIPE_CONNECTED | ERROR_NO_DATA
98
121
);
99
122
if connected {
100
ACTIVATION.store(true, Ordering::Release);
123
let mut pipe = ManuallyDrop::new(unsafe { File::from_raw_handle(handle.0) });
124
let mut message = Vec::new();
125
let _ = pipe.read_to_end(&mut message);
126
received(&message);
101
127
} else {
102
128
std::thread::sleep(CONNECT_INTERVAL);
103
129
}
@@ -107,11 +133,13 @@ mod platform {
107
133
true
108
134
}
109
135
110
pub fn notify_primary(name: &str) {
136
pub fn notify_primary(name: &str, command: &str) {
111
137
let path = pipe_path(name);
112
138
let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) };
113
139
for _ in 0..CONNECT_ATTEMPTS {
114
if OpenOptions::new().write(true).open(&path).is_ok() {
140
if let Ok(mut pipe) = OpenOptions::new().write(true).open(&path) {
141
let _ = pipe.write_all(command.as_bytes());
142
let _ = unsafe { FlushFileBuffers(HANDLE(pipe.as_raw_handle())) };
115
143
return;
116
144
}
117
145
std::thread::sleep(CONNECT_INTERVAL);
@@ -121,12 +149,14 @@ mod platform {
121
149
122
150
#[cfg(unix)]
123
151
mod platform {
124
use std::io::ErrorKind;
152
use std::io::{ErrorKind, Read, Write};
125
153
use std::os::unix::net::{UnixListener, UnixStream};
126
154
use std::path::PathBuf;
127
use std::sync::atomic::Ordering;
155
use std::time::Duration;
156
157
use super::{received, user_name};
128
158
129
use super::{ACTIVATION, user_name};
159
const READ_TIMEOUT: Duration = Duration::from_secs(1);
130
160
131
161
pub(super) fn socket_path(name: &str) -> PathBuf {
132
162
let directory = std::env::var_os("XDG_RUNTIME_DIR")
@@ -162,17 +192,20 @@ mod platform {
162
192
Bound::Unavailable => return true,
163
193
};
164
194
std::thread::spawn(move || {
165
for connection in listener.incoming() {
166
if connection.is_ok() {
167
ACTIVATION.store(true, Ordering::Release);
168
}
195
for mut connection in listener.incoming().flatten() {
196
let _ = connection.set_read_timeout(Some(READ_TIMEOUT));
197
let mut message = Vec::new();
198
let _ = connection.read_to_end(&mut message);
199
received(&message);
169
200
}
170
201
});
171
202
true
172
203
}
173
204
174
pub fn notify_primary(name: &str) {
175
let _ = UnixStream::connect(socket_path(name));
205
pub fn notify_primary(name: &str, command: &str) {
206
if let Ok(mut stream) = UnixStream::connect(socket_path(name)) {
207
let _ = stream.write_all(command.as_bytes());
208
}
176
209
}
177
210
}
178
211
@@ -183,14 +216,21 @@ mod tests {
183
216
#[test]
184
217
fn second_claim_forwards_and_stale_socket_is_reclaimed() {
185
218
let name = format!("rusty-teams-test-{}", std::process::id());
186
assert_eq!(claim(&name, false), Claim::Primary);
187
assert_eq!(claim(&name, false), Claim::Forwarded);
219
assert_eq!(
220
claim(&name, false, "join https://example/meet"),
221
Claim::Primary
222
);
223
assert_eq!(take_commands(), ["join https://example/meet"]);
224
assert_eq!(claim(&name, false, "hang-up"), Claim::Forwarded);
188
225
let started = Instant::now();
189
while !take_activation() {
226
let mut commands = Vec::new();
227
while commands.is_empty() {
190
228
assert!(started.elapsed() < Duration::from_secs(1));
191
229
std::thread::sleep(Duration::from_millis(10));
230
commands = take_commands();
192
231
}
193
assert!(!take_activation());
232
assert_eq!(commands, ["hang-up"]);
233
assert!(take_activation());
194
234
195
235
let stale_name = format!("{name}-stale");
196
236
#[cfg(unix)]
@@ -199,11 +239,12 @@ mod tests {
199
239
drop(std::os::unix::net::UnixListener::bind(&path).unwrap());
200
240
assert!(path.exists());
201
241
}
202
assert_eq!(claim(&stale_name, false), Claim::Primary);
242
assert_eq!(claim(&stale_name, false, ""), Claim::Primary);
203
243
assert_eq!(
204
claim("missing-directory/rusty-teams", false),
244
claim("missing-directory/rusty-teams", false, ""),
205
245
Claim::Primary
206
246
);
247
assert!(take_commands().is_empty());
207
248
208
249
#[cfg(unix)]
209
250
for leftover in [&name, &stale_name] {
@@ -1,7 +1,9 @@1
use std::sync::Mutex;1
use std::sync::atomic::{AtomicBool, Ordering};2
use std::sync::atomic::{AtomicBool, Ordering};2
use std::time::{Duration, Instant};3
use std::time::{Duration, Instant};3
4
4
static ACTIVATION: AtomicBool = AtomicBool::new(false);5
static ACTIVATION: AtomicBool = AtomicBool::new(false);6
static COMMANDS: Mutex<Vec<String>> = Mutex::new(Vec::new());5
7
6
const RETRY_INTERVAL: Duration = Duration::from_millis(200);8
const RETRY_INTERVAL: Duration = Duration::from_millis(200);7
const RETRY_TIMEOUT: Duration = Duration::from_secs(15);9
const RETRY_TIMEOUT: Duration = Duration::from_secs(15);@@ -16,14 +18,31 @@ pub fn take_activation() -> bool {16
ACTIVATION.swap(false, Ordering::AcqRel)18
ACTIVATION.swap(false, Ordering::AcqRel)17
}19
}18
20
19
pub fn claim(name: &str, wait_for_previous: bool) -> Claim {21
pub fn queue_command(command: &str) {22
if !command.is_empty() {23
COMMANDS.lock().unwrap().push(command.to_owned());24
}25
}26
27
pub fn take_commands() -> Vec<String> {28
std::mem::take(&mut *COMMANDS.lock().unwrap())29
}30
31
fn received(message: &[u8]) {32
queue_command(String::from_utf8_lossy(message).trim());33
ACTIVATION.store(true, Ordering::Release);34
}35
36
/// `command` travels to the running instance, which queues it for `take_commands`.37
pub fn claim(name: &str, wait_for_previous: bool, command: &str) -> Claim {20
let started = Instant::now();38
let started = Instant::now();21
loop {39
loop {22
if platform::try_become_primary(name) {40
if platform::try_become_primary(name) {41
queue_command(command);23
return Claim::Primary;42
return Claim::Primary;24
}43
}25
if !wait_for_previous {44
if !wait_for_previous {26
platform::notify_primary(name);45
platform::notify_primary(name, command);27
return Claim::Forwarded;46
return Claim::Forwarded;28
}47
}29
if started.elapsed() >= RETRY_TIMEOUT {48
if started.elapsed() >= RETRY_TIMEOUT {@@ -41,15 +60,19 @@ fn user_name() -> String {41
60
42
#[cfg(windows)]61
#[cfg(windows)]43
mod platform {62
mod platform {44
use std::fs::OpenOptions;63
use std::fs::{File, OpenOptions};45
use std::sync::atomic::Ordering;64
use std::io::{Read, Write};65
use std::mem::ManuallyDrop;66
use std::os::windows::io::{AsRawHandle, FromRawHandle};46
use std::time::Duration;67
use std::time::Duration;47
68
48
use windows::Win32::Foundation::{69
use windows::Win32::Foundation::{49
ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError,70
ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError,50
INVALID_HANDLE_VALUE,71
HANDLE, INVALID_HANDLE_VALUE,72
};73
use windows::Win32::Storage::FileSystem::{74
FILE_FLAG_FIRST_PIPE_INSTANCE, FlushFileBuffers, PIPE_ACCESS_INBOUND,51
};75
};52
use windows::Win32::Storage::FileSystem::{FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_INBOUND};53
use windows::Win32::System::Pipes::{76
use windows::Win32::System::Pipes::{54
ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,77
ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,55
PIPE_TYPE_BYTE, PIPE_WAIT,78
PIPE_TYPE_BYTE, PIPE_WAIT,@@ -57,7 +80,7 @@ mod platform {57
use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow};80
use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow};58
use windows::core::PCWSTR;81
use windows::core::PCWSTR;59
82
60
use super::{ACTIVATION, user_name};83
use super::{received, user_name};61
84
62
const CONNECT_ATTEMPTS: u32 = 20;85
const CONNECT_ATTEMPTS: u32 = 20;63
const CONNECT_INTERVAL: Duration = Duration::from_millis(100);86
const CONNECT_INTERVAL: Duration = Duration::from_millis(100);@@ -89,7 +112,7 @@ mod platform {89
}112
}90
let raw_handle = handle.0 as usize;113
let raw_handle = handle.0 as usize;91
std::thread::spawn(move || {114
std::thread::spawn(move || {92
let handle = windows::Win32::Foundation::HANDLE(raw_handle as *mut _);115
let handle = HANDLE(raw_handle as *mut _);93
loop {116
loop {94
let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok()117
let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok()95
|| matches!(118
|| matches!(@@ -97,7 +120,10 @@ mod platform {97
ERROR_PIPE_CONNECTED | ERROR_NO_DATA120
ERROR_PIPE_CONNECTED | ERROR_NO_DATA98
);121
);99
if connected {122
if connected {100
ACTIVATION.store(true, Ordering::Release);123
let mut pipe = ManuallyDrop::new(unsafe { File::from_raw_handle(handle.0) });124
let mut message = Vec::new();125
let _ = pipe.read_to_end(&mut message);126
received(&message);101
} else {127
} else {102
std::thread::sleep(CONNECT_INTERVAL);128
std::thread::sleep(CONNECT_INTERVAL);103
}129
}@@ -107,11 +133,13 @@ mod platform {107
true133
true108
}134
}109
135
110
pub fn notify_primary(name: &str) {136
pub fn notify_primary(name: &str, command: &str) {111
let path = pipe_path(name);137
let path = pipe_path(name);112
let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) };138
let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) };113
for _ in 0..CONNECT_ATTEMPTS {139
for _ in 0..CONNECT_ATTEMPTS {114
if OpenOptions::new().write(true).open(&path).is_ok() {140
if let Ok(mut pipe) = OpenOptions::new().write(true).open(&path) {141
let _ = pipe.write_all(command.as_bytes());142
let _ = unsafe { FlushFileBuffers(HANDLE(pipe.as_raw_handle())) };115
return;143
return;116
}144
}117
std::thread::sleep(CONNECT_INTERVAL);145
std::thread::sleep(CONNECT_INTERVAL);@@ -121,12 +149,14 @@ mod platform {121
149
122
#[cfg(unix)]150
#[cfg(unix)]123
mod platform {151
mod platform {124
use std::io::ErrorKind;152
use std::io::{ErrorKind, Read, Write};125
use std::os::unix::net::{UnixListener, UnixStream};153
use std::os::unix::net::{UnixListener, UnixStream};126
use std::path::PathBuf;154
use std::path::PathBuf;127
use std::sync::atomic::Ordering;155
use std::time::Duration;156
157
use super::{received, user_name};128
158
129
use super::{ACTIVATION, user_name};159
const READ_TIMEOUT: Duration = Duration::from_secs(1);130
160
131
pub(super) fn socket_path(name: &str) -> PathBuf {161
pub(super) fn socket_path(name: &str) -> PathBuf {132
let directory = std::env::var_os("XDG_RUNTIME_DIR")162
let directory = std::env::var_os("XDG_RUNTIME_DIR")@@ -162,17 +192,20 @@ mod platform {162
Bound::Unavailable => return true,192
Bound::Unavailable => return true,163
};193
};164
std::thread::spawn(move || {194
std::thread::spawn(move || {165
for connection in listener.incoming() {195
for mut connection in listener.incoming().flatten() {166
if connection.is_ok() {196
let _ = connection.set_read_timeout(Some(READ_TIMEOUT));167
ACTIVATION.store(true, Ordering::Release);197
let mut message = Vec::new();168
}198
let _ = connection.read_to_end(&mut message);199
received(&message);169
}200
}170
});201
});171
true202
true172
}203
}173
204
174
pub fn notify_primary(name: &str) {205
pub fn notify_primary(name: &str, command: &str) {175
let _ = UnixStream::connect(socket_path(name));206
if let Ok(mut stream) = UnixStream::connect(socket_path(name)) {207
let _ = stream.write_all(command.as_bytes());208
}176
}209
}177
}210
}178
211
@@ -183,14 +216,21 @@ mod tests {183
#[test]216
#[test]184
fn second_claim_forwards_and_stale_socket_is_reclaimed() {217
fn second_claim_forwards_and_stale_socket_is_reclaimed() {185
let name = format!("rusty-teams-test-{}", std::process::id());218
let name = format!("rusty-teams-test-{}", std::process::id());186
assert_eq!(claim(&name, false), Claim::Primary);219
assert_eq!(187
assert_eq!(claim(&name, false), Claim::Forwarded);220
claim(&name, false, "join https://example/meet"),221
Claim::Primary222
);223
assert_eq!(take_commands(), ["join https://example/meet"]);224
assert_eq!(claim(&name, false, "hang-up"), Claim::Forwarded);188
let started = Instant::now();225
let started = Instant::now();189
while !take_activation() {226
let mut commands = Vec::new();227
while commands.is_empty() {190
assert!(started.elapsed() < Duration::from_secs(1));228
assert!(started.elapsed() < Duration::from_secs(1));191
std::thread::sleep(Duration::from_millis(10));229
std::thread::sleep(Duration::from_millis(10));230
commands = take_commands();192
}231
}193
assert!(!take_activation());232
assert_eq!(commands, ["hang-up"]);233
assert!(take_activation());194
234
195
let stale_name = format!("{name}-stale");235
let stale_name = format!("{name}-stale");196
#[cfg(unix)]236
#[cfg(unix)]@@ -199,11 +239,12 @@ mod tests {199
drop(std::os::unix::net::UnixListener::bind(&path).unwrap());239
drop(std::os::unix::net::UnixListener::bind(&path).unwrap());200
assert!(path.exists());240
assert!(path.exists());201
}241
}202
assert_eq!(claim(&stale_name, false), Claim::Primary);242
assert_eq!(claim(&stale_name, false, ""), Claim::Primary);203
assert_eq!(243
assert_eq!(204
claim("missing-directory/rusty-teams", false),244
claim("missing-directory/rusty-teams", false, ""),205
Claim::Primary245
Claim::Primary206
);246
);247
assert!(take_commands().is_empty());207
248
208
#[cfg(unix)]249
#[cfg(unix)]209
for leftover in [&name, &stale_name] {250
for leftover in [&name, &stale_name] {@@ -158,6 +158,7 @@ pub struct AppState {
158
158
pub markdown_mode: bool,
159
159
pub actions_on_right_click: bool,
160
160
pub web_calls: bool,
161
pub own_engine_next_call: bool,
161
162
pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
162
163
pub own_tenant: Option<String>,
163
164
pub call_share_motion: bool,
@@ -327,6 +328,7 @@ impl AppState {
327
328
markdown_mode,
328
329
actions_on_right_click,
329
330
web_calls,
331
own_engine_next_call: false,
330
332
demo_chat_desktop: HashMap::new(),
331
333
own_tenant: None,
332
334
call_share_motion: false,
@@ -158,6 +158,7 @@ pub struct AppState {158
pub markdown_mode: bool,158
pub markdown_mode: bool,159
pub actions_on_right_click: bool,159
pub actions_on_right_click: bool,160
pub web_calls: bool,160
pub web_calls: bool,161
pub own_engine_next_call: bool,161
pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,162
pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,162
pub own_tenant: Option<String>,163
pub own_tenant: Option<String>,163
pub call_share_motion: bool,164
pub call_share_motion: bool,@@ -327,6 +328,7 @@ impl AppState {327
markdown_mode,328
markdown_mode,328
actions_on_right_click,329
actions_on_right_click,329
web_calls,330
web_calls,331
own_engine_next_call: false,330
demo_chat_desktop: HashMap::new(),332
demo_chat_desktop: HashMap::new(),331
own_tenant: None,333
own_tenant: None,332
call_share_motion: false,334
call_share_motion: false,@@ -30,7 +30,7 @@ pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
30
30
}
31
31
32
32
#[derive(Clone, Copy, PartialEq, Eq)]
33
enum JoinMode {
33
pub(crate) enum JoinMode {
34
34
Prejoin,
35
35
Direct,
36
36
}
@@ -111,7 +111,7 @@ impl AppState {
111
111
self.join_link(text, JoinMode::Prejoin, cx);
112
112
}
113
113
114
fn join_link(&mut self, text: &str, mode: JoinMode, cx: &mut Context<Self>) {
114
pub(crate) fn join_link(&mut self, text: &str, mode: JoinMode, cx: &mut Context<Self>) {
115
115
match parse_meeting_link(text) {
116
116
Some(MeetingLink::Thread(meeting)) => {
117
117
self.join_resolved_meeting(meeting_target(&meeting), mode, cx)
@@ -30,7 +30,7 @@ pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {30
}30
}31
31
32
#[derive(Clone, Copy, PartialEq, Eq)]32
#[derive(Clone, Copy, PartialEq, Eq)]33
enum JoinMode {33
pub(crate) enum JoinMode {34
Prejoin,34
Prejoin,35
Direct,35
Direct,36
}36
}@@ -111,7 +111,7 @@ impl AppState {111
self.join_link(text, JoinMode::Prejoin, cx);111
self.join_link(text, JoinMode::Prejoin, cx);112
}112
}113
113
114
fn join_link(&mut self, text: &str, mode: JoinMode, cx: &mut Context<Self>) {114
pub(crate) fn join_link(&mut self, text: &str, mode: JoinMode, cx: &mut Context<Self>) {115
match parse_meeting_link(text) {115
match parse_meeting_link(text) {116
Some(MeetingLink::Thread(meeting)) => {116
Some(MeetingLink::Thread(meeting)) => {117
self.join_resolved_meeting(meeting_target(&meeting), mode, cx)117
self.join_resolved_meeting(meeting_target(&meeting), mode, cx)@@ -12,6 +12,7 @@ pub mod overlay_layout;
12
12
pub mod people_actions;
13
13
pub mod prejoin;
14
14
pub mod record_load;
15
pub mod remote_command;
15
16
pub mod reminder;
16
17
pub mod share_actions;
17
18
pub mod share_overlay;
@@ -12,6 +12,7 @@ pub mod overlay_layout;12
pub mod people_actions;12
pub mod people_actions;13
pub mod prejoin;13
pub mod prejoin;14
pub mod record_load;14
pub mod record_load;15
pub mod remote_command;15
pub mod reminder;16
pub mod reminder;16
pub mod share_actions;17
pub mod share_actions;17
pub mod share_overlay;18
pub mod share_overlay;@@ -0,0 +1,64 @@
1
use gpui_kit::*;
2
3
use super::join::JoinMode;
4
use crate::app_state::AppState;
5
6
pub const JOIN_FLAG: &str = "--join";
7
pub const HANG_UP_FLAG: &str = "--hang-up";
8
const JOIN_COMMAND: &str = "join ";
9
const HANG_UP_COMMAND: &str = "hang-up";
10
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
pub enum RemoteCommand {
13
Join(String),
14
HangUp,
15
}
16
17
impl RemoteCommand {
18
pub fn encode(&self) -> String {
19
match self {
20
RemoteCommand::Join(link) => format!("{JOIN_COMMAND}{link}"),
21
RemoteCommand::HangUp => HANG_UP_COMMAND.to_owned(),
22
}
23
}
24
25
pub fn decode(text: &str) -> Option<RemoteCommand> {
26
if text == HANG_UP_COMMAND {
27
return Some(RemoteCommand::HangUp);
28
}
29
let link = text.strip_prefix(JOIN_COMMAND)?.trim();
30
(!link.is_empty()).then(|| RemoteCommand::Join(link.to_owned()))
31
}
32
}
33
34
impl AppState {
35
/// Commands a second `teams` process forwards, used by the call end-to-end test.
36
pub fn run_remote_command(&mut self, text: &str, cx: &mut Context<Self>) {
37
match RemoteCommand::decode(text) {
38
Some(RemoteCommand::Join(link)) => {
39
self.own_engine_next_call = true;
40
self.join_link(&link, JoinMode::Direct, cx);
41
self.own_engine_next_call = false;
42
}
43
Some(RemoteCommand::HangUp) => self.leave_call(cx),
44
None => {}
45
}
46
}
47
}
48
49
#[cfg(test)]
50
mod tests {
51
use super::RemoteCommand;
52
53
#[test]
54
fn commands_survive_the_trip_through_the_pipe() {
55
for command in [
56
RemoteCommand::Join("https://teams.microsoft.com/l/meetup-join/x".to_owned()),
57
RemoteCommand::HangUp,
58
] {
59
assert_eq!(RemoteCommand::decode(&command.encode()), Some(command));
60
}
61
assert_eq!(RemoteCommand::decode("join "), None);
62
assert_eq!(RemoteCommand::decode("reboot"), None);
63
}
64
}
@@ -0,0 +1,64 @@1
use gpui_kit::*;2
3
use super::join::JoinMode;4
use crate::app_state::AppState;5
6
pub const JOIN_FLAG: &str = "--join";7
pub const HANG_UP_FLAG: &str = "--hang-up";8
const JOIN_COMMAND: &str = "join ";9
const HANG_UP_COMMAND: &str = "hang-up";10
11
#[derive(Debug, Clone, PartialEq, Eq)]12
pub enum RemoteCommand {13
Join(String),14
HangUp,15
}16
17
impl RemoteCommand {18
pub fn encode(&self) -> String {19
match self {20
RemoteCommand::Join(link) => format!("{JOIN_COMMAND}{link}"),21
RemoteCommand::HangUp => HANG_UP_COMMAND.to_owned(),22
}23
}24
25
pub fn decode(text: &str) -> Option<RemoteCommand> {26
if text == HANG_UP_COMMAND {27
return Some(RemoteCommand::HangUp);28
}29
let link = text.strip_prefix(JOIN_COMMAND)?.trim();30
(!link.is_empty()).then(|| RemoteCommand::Join(link.to_owned()))31
}32
}33
34
impl AppState {35
/// Commands a second `teams` process forwards, used by the call end-to-end test.36
pub fn run_remote_command(&mut self, text: &str, cx: &mut Context<Self>) {37
match RemoteCommand::decode(text) {38
Some(RemoteCommand::Join(link)) => {39
self.own_engine_next_call = true;40
self.join_link(&link, JoinMode::Direct, cx);41
self.own_engine_next_call = false;42
}43
Some(RemoteCommand::HangUp) => self.leave_call(cx),44
None => {}45
}46
}47
}48
49
#[cfg(test)]50
mod tests {51
use super::RemoteCommand;52
53
#[test]54
fn commands_survive_the_trip_through_the_pipe() {55
for command in [56
RemoteCommand::Join("https://teams.microsoft.com/l/meetup-join/x".to_owned()),57
RemoteCommand::HangUp,58
] {59
assert_eq!(RemoteCommand::decode(&command.encode()), Some(command));60
}61
assert_eq!(RemoteCommand::decode("join "), None);62
assert_eq!(RemoteCommand::decode("reboot"), None);63
}64
}@@ -49,7 +49,7 @@ impl AppState {
49
49
50
50
/// Opens the call in Teams on the web when that setting is on; false leaves it to the own engine.
51
51
pub(super) fn try_web_call(&mut self, url: String, cx: &mut Context<Self>) -> bool {
52
if !self.web_calls || self.mode.demo {
52
if self.own_engine_next_call || !self.web_calls || self.mode.demo {
53
53
return false;
54
54
}
55
55
open_web_call(url, cx)
@@ -49,7 +49,7 @@ impl AppState {49
49
50
/// Opens the call in Teams on the web when that setting is on; false leaves it to the own engine.50
/// Opens the call in Teams on the web when that setting is on; false leaves it to the own engine.51
pub(super) fn try_web_call(&mut self, url: String, cx: &mut Context<Self>) -> bool {51
pub(super) fn try_web_call(&mut self, url: String, cx: &mut Context<Self>) -> bool {52
if !self.web_calls || self.mode.demo {52
if self.own_engine_next_call || !self.web_calls || self.mode.demo {53
return false;53
return false;54
}54
}55
open_web_call(url, cx)55
open_web_call(url, cx)@@ -25,6 +25,7 @@ use gpui_kit::*;
25
25
use store::Store;
26
26
27
27
use crate::app_state::{AppState, Mode};
28
use crate::call::remote_command::{HANG_UP_FLAG, JOIN_FLAG, RemoteCommand};
28
29
use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
29
30
30
31
const LINUX_APP_ID: &str = "rusty-teams";
@@ -55,6 +56,7 @@ struct Arguments {
55
56
channels_tab: bool,
56
57
autostart: bool,
57
58
demo_sync: Option<Duration>,
59
remote_command: Option<RemoteCommand>,
58
60
}
59
61
60
62
fn parse_arguments() -> Arguments {
@@ -78,6 +80,8 @@ fn parse_arguments() -> Arguments {
78
80
.and_then(|value| value.parse().ok())
79
81
.map(Duration::from_secs_f32)
80
82
}
83
JOIN_FLAG => arguments.remote_command = input.next().map(RemoteCommand::Join),
84
HANG_UP_FLAG => arguments.remote_command = Some(RemoteCommand::HangUp),
81
85
"--database" => arguments.database = input.next().map(PathBuf::from),
82
86
"--endpoint" => arguments.endpoint = input.next(),
83
87
"--open" => {
@@ -162,7 +166,12 @@ fn main() {
162
166
updater::wait_for_previous_exit(value);
163
167
}
164
168
let relaunched = relaunch_value.is_some();
165
if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched)
169
let command = arguments
170
.remote_command
171
.as_ref()
172
.map(RemoteCommand::encode)
173
.unwrap_or_default();
174
if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched, &command)
166
175
== single_instance::Claim::Forwarded
167
176
{
168
177
return;
@@ -25,6 +25,7 @@ use gpui_kit::*;25
use store::Store;25
use store::Store;26
26
27
use crate::app_state::{AppState, Mode};27
use crate::app_state::{AppState, Mode};28
use crate::call::remote_command::{HANG_UP_FLAG, JOIN_FLAG, RemoteCommand};28
use views::shell::{AppShell, OpenTarget, Startup, bind_keys};29
use views::shell::{AppShell, OpenTarget, Startup, bind_keys};29
30
30
const LINUX_APP_ID: &str = "rusty-teams";31
const LINUX_APP_ID: &str = "rusty-teams";@@ -55,6 +56,7 @@ struct Arguments {55
channels_tab: bool,56
channels_tab: bool,56
autostart: bool,57
autostart: bool,57
demo_sync: Option<Duration>,58
demo_sync: Option<Duration>,59
remote_command: Option<RemoteCommand>,58
}60
}59
61
60
fn parse_arguments() -> Arguments {62
fn parse_arguments() -> Arguments {@@ -78,6 +80,8 @@ fn parse_arguments() -> Arguments {78
.and_then(|value| value.parse().ok())80
.and_then(|value| value.parse().ok())79
.map(Duration::from_secs_f32)81
.map(Duration::from_secs_f32)80
}82
}83
JOIN_FLAG => arguments.remote_command = input.next().map(RemoteCommand::Join),84
HANG_UP_FLAG => arguments.remote_command = Some(RemoteCommand::HangUp),81
"--database" => arguments.database = input.next().map(PathBuf::from),85
"--database" => arguments.database = input.next().map(PathBuf::from),82
"--endpoint" => arguments.endpoint = input.next(),86
"--endpoint" => arguments.endpoint = input.next(),83
"--open" => {87
"--open" => {@@ -162,7 +166,12 @@ fn main() {162
updater::wait_for_previous_exit(value);166
updater::wait_for_previous_exit(value);163
}167
}164
let relaunched = relaunch_value.is_some();168
let relaunched = relaunch_value.is_some();165
if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched)169
let command = arguments170
.remote_command171
.as_ref()172
.map(RemoteCommand::encode)173
.unwrap_or_default();174
if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched, &command)166
== single_instance::Claim::Forwarded175
== single_instance::Claim::Forwarded167
{176
{168
return;177
return;@@ -1076,6 +1076,10 @@ impl NotificationCenter {
1076
1076
if single_instance::take_activation() {
1077
1077
self.raise_main_window(cx);
1078
1078
}
1079
for command in single_instance::take_commands() {
1080
self.app
1081
.update(cx, |state, cx| state.run_remote_command(&command, cx));
1082
}
1079
1083
}
1080
1084
1081
1085
fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
@@ -1076,6 +1076,10 @@ impl NotificationCenter {1076
if single_instance::take_activation() {1076
if single_instance::take_activation() {1077
self.raise_main_window(cx);1077
self.raise_main_window(cx);1078
}1078
}1079
for command in single_instance::take_commands() {1080
self.app1081
.update(cx, |state, cx| state.run_remote_command(&command, cx));1082
}1079
}1083
}1080
1084
1081
fn repeat_urgent(&mut self, cx: &mut Context<Self>) {1085
fn repeat_urgent(&mut self, cx: &mut Context<Self>) {@@ -0,0 +1,174 @@
1
//! Windows tool for the call end-to-end test.
2
//! `audio_probe play <render device name part> <mono 16-bit 48 kHz wav> <seconds>` loops the file into that endpoint.
3
//! `audio_probe record-process <pid> <seconds> <out.wav>` records only what that process plays and prints loudness per 250 ms as JSON.
4
5
#[cfg(windows)]
6
fn main() {
7
let arguments: Vec<String> = std::env::args().skip(1).collect();
8
let arguments: Vec<&str> = arguments.iter().map(String::as_str).collect();
9
let outcome = match arguments.as_slice() {
10
["play", device, wav, seconds] => probe::play(device, wav, seconds.parse().expect("seconds")),
11
["record-process", process_id, seconds, out] => probe::record_process(
12
process_id.parse().expect("pid"),
13
seconds.parse().expect("seconds"),
14
out,
15
),
16
_ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav".to_owned()),
17
};
18
if let Err(error) = outcome {
19
eprintln!("{error}");
20
std::process::exit(1);
21
}
22
}
23
24
#[cfg(not(windows))]
25
fn main() {
26
eprintln!("audio_probe runs on Windows only");
27
}
28
29
#[cfg(windows)]
30
mod probe {
31
use std::time::{Duration, Instant};
32
33
use calling::audio::{FRAME_SAMPLES, SAMPLE_RATE};
34
use calling::pcm::SampleQueue;
35
use calling::wav_dump::WavDump;
36
use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
37
use windows::Win32::Media::Audio::{
38
AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
39
DEVICE_STATE_ACTIVE, IAudioClient, IAudioRenderClient, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX,
40
eRender,
41
};
42
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, STGM_READ};
43
44
const CHANNELS: u16 = 2;
45
const BITS: u16 = 16;
46
const PCM_TAG: u16 = 1;
47
const BUFFER_HNS: i64 = 1_000_000;
48
const TICK: Duration = Duration::from_millis(10);
49
const WINDOW_MS: usize = 250;
50
const WAV_HEADER: usize = 44;
51
52
fn failed(what: &str, error: impl std::fmt::Display) -> String {
53
format!("{what}: {error}")
54
}
55
56
fn render_device(name_part: &str) -> Result<IMMDevice, String> {
57
unsafe {
58
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
59
let enumerator: IMMDeviceEnumerator =
60
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| failed("enumerator", error))?;
61
let devices = enumerator
62
.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE)
63
.map_err(|error| failed("endpoints", error))?;
64
let mut names = Vec::new();
65
for index in 0..devices.GetCount().map_err(|error| failed("count", error))? {
66
let device = devices.Item(index).map_err(|error| failed("item", error))?;
67
let store = device.OpenPropertyStore(STGM_READ).map_err(|error| failed("properties", error))?;
68
let value = store.GetValue(&PKEY_Device_FriendlyName).map_err(|error| failed("name", error))?;
69
let name = value.Anonymous.Anonymous.Anonymous.pwszVal.to_string().unwrap_or_default();
70
if name.contains(name_part) {
71
return Ok(device);
72
}
73
names.push(name);
74
}
75
Err(format!("no render device with \"{name_part}\" in {names:?}"))
76
}
77
}
78
79
fn read_mono_wav(path: &str) -> Result<Vec<i16>, String> {
80
let bytes = std::fs::read(path).map_err(|error| failed("read wav", error))?;
81
let header = bytes.get(..WAV_HEADER).ok_or("wav too short")?;
82
let channels = u16::from_le_bytes([header[22], header[23]]);
83
let rate = u32::from_le_bytes([header[24], header[25], header[26], header[27]]);
84
let bits = u16::from_le_bytes([header[34], header[35]]);
85
if channels != 1 || rate != SAMPLE_RATE || bits != BITS {
86
return Err(format!("need mono 16-bit {SAMPLE_RATE} Hz, got {channels} ch {bits} bit {rate} Hz"));
87
}
88
let data = bytes.windows(4).position(|tag| tag == b"data").ok_or("wav without data chunk")? + 8;
89
Ok(bytes[data..].chunks_exact(2).map(|pair| i16::from_le_bytes([pair[0], pair[1]])).collect())
90
}
91
92
pub fn play(name_part: &str, wav: &str, seconds: u64) -> Result<(), String> {
93
let samples = read_mono_wav(wav)?;
94
if samples.is_empty() {
95
return Err("wav without samples".to_owned());
96
}
97
let device = render_device(name_part)?;
98
let block_align = CHANNELS * BITS / 8;
99
let format = WAVEFORMATEX {
100
wFormatTag: PCM_TAG,
101
nChannels: CHANNELS,
102
nSamplesPerSec: SAMPLE_RATE,
103
nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),
104
nBlockAlign: block_align,
105
wBitsPerSample: BITS,
106
cbSize: 0,
107
};
108
unsafe {
109
let client: IAudioClient = device.Activate(CLSCTX_ALL, None).map_err(|error| failed("activate", error))?;
110
client
111
.Initialize(
112
AUDCLNT_SHAREMODE_SHARED,
113
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
114
BUFFER_HNS,
115
0,
116
&raw const format,
117
None,
118
)
119
.map_err(|error| failed("initialize", error))?;
120
let buffer_frames = client.GetBufferSize().map_err(|error| failed("buffer size", error))?;
121
let render: IAudioRenderClient = client.GetService().map_err(|error| failed("render service", error))?;
122
client.Start().map_err(|error| failed("start", error))?;
123
let started = Instant::now();
124
let mut position = 0usize;
125
println!("{{\"playing\":true}}");
126
while started.elapsed() < Duration::from_secs(seconds) {
127
let padding = client.GetCurrentPadding().map_err(|error| failed("padding", error))?;
128
let frames = buffer_frames - padding;
129
if frames > 0 {
130
let data = render.GetBuffer(frames).map_err(|error| failed("buffer", error))?;
131
let output = std::slice::from_raw_parts_mut(data.cast::<i16>(), frames as usize * usize::from(CHANNELS));
132
for pair in output.chunks_exact_mut(usize::from(CHANNELS)) {
133
let sample = samples[position % samples.len()];
134
pair.fill(sample);
135
position += 1;
136
}
137
render.ReleaseBuffer(frames, 0).map_err(|error| failed("release", error))?;
138
}
139
std::thread::sleep(TICK);
140
}
141
let _ = client.Stop();
142
}
143
Ok(())
144
}
145
146
fn rms(samples: &[i16]) -> f64 {
147
let sum: f64 = samples.iter().map(|sample| f64::from(*sample).powi(2)).sum();
148
(sum / samples.len().max(1) as f64).sqrt()
149
}
150
151
pub fn record_process(process_id: u32, seconds: u64, out: &str) -> Result<(), String> {
152
let queue = SampleQueue::default();
153
let _capture = calling::start_process_capture(queue.clone(), process_id).map_err(|error| failed("capture", error))?;
154
let mut dump = WavDump::create(std::path::Path::new(out)).map_err(|error| failed("wav", error))?;
155
let frames_per_window = WINDOW_MS * SAMPLE_RATE as usize / 1000 / FRAME_SAMPLES;
156
let mut window = Vec::new();
157
let mut loudness = Vec::new();
158
let started = Instant::now();
159
let mut next = Instant::now();
160
while started.elapsed() < Duration::from_secs(seconds) {
161
let (frame, _) = queue.next_frame();
162
dump.write(&frame);
163
window.extend_from_slice(&frame);
164
if window.len() >= frames_per_window * FRAME_SAMPLES {
165
loudness.push(rms(&window).round());
166
window.clear();
167
}
168
next += TICK;
169
std::thread::sleep(next.saturating_duration_since(Instant::now()));
170
}
171
println!("{{\"window_ms\":{WINDOW_MS},\"rms\":{loudness:?}}}");
172
Ok(())
173
}
174
}
@@ -0,0 +1,174 @@1
//! Windows tool for the call end-to-end test.2
//! `audio_probe play <render device name part> <mono 16-bit 48 kHz wav> <seconds>` loops the file into that endpoint.3
//! `audio_probe record-process <pid> <seconds> <out.wav>` records only what that process plays and prints loudness per 250 ms as JSON.4
5
#[cfg(windows)]6
fn main() {7
let arguments: Vec<String> = std::env::args().skip(1).collect();8
let arguments: Vec<&str> = arguments.iter().map(String::as_str).collect();9
let outcome = match arguments.as_slice() {10
["play", device, wav, seconds] => probe::play(device, wav, seconds.parse().expect("seconds")),11
["record-process", process_id, seconds, out] => probe::record_process(12
process_id.parse().expect("pid"),13
seconds.parse().expect("seconds"),14
out,15
),16
_ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav".to_owned()),17
};18
if let Err(error) = outcome {19
eprintln!("{error}");20
std::process::exit(1);21
}22
}23
24
#[cfg(not(windows))]25
fn main() {26
eprintln!("audio_probe runs on Windows only");27
}28
29
#[cfg(windows)]30
mod probe {31
use std::time::{Duration, Instant};32
33
use calling::audio::{FRAME_SAMPLES, SAMPLE_RATE};34
use calling::pcm::SampleQueue;35
use calling::wav_dump::WavDump;36
use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;37
use windows::Win32::Media::Audio::{38
AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,39
DEVICE_STATE_ACTIVE, IAudioClient, IAudioRenderClient, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX,40
eRender,41
};42
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, STGM_READ};43
44
const CHANNELS: u16 = 2;45
const BITS: u16 = 16;46
const PCM_TAG: u16 = 1;47
const BUFFER_HNS: i64 = 1_000_000;48
const TICK: Duration = Duration::from_millis(10);49
const WINDOW_MS: usize = 250;50
const WAV_HEADER: usize = 44;51
52
fn failed(what: &str, error: impl std::fmt::Display) -> String {53
format!("{what}: {error}")54
}55
56
fn render_device(name_part: &str) -> Result<IMMDevice, String> {57
unsafe {58
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);59
let enumerator: IMMDeviceEnumerator =60
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|error| failed("enumerator", error))?;61
let devices = enumerator62
.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE)63
.map_err(|error| failed("endpoints", error))?;64
let mut names = Vec::new();65
for index in 0..devices.GetCount().map_err(|error| failed("count", error))? {66
let device = devices.Item(index).map_err(|error| failed("item", error))?;67
let store = device.OpenPropertyStore(STGM_READ).map_err(|error| failed("properties", error))?;68
let value = store.GetValue(&PKEY_Device_FriendlyName).map_err(|error| failed("name", error))?;69
let name = value.Anonymous.Anonymous.Anonymous.pwszVal.to_string().unwrap_or_default();70
if name.contains(name_part) {71
return Ok(device);72
}73
names.push(name);74
}75
Err(format!("no render device with \"{name_part}\" in {names:?}"))76
}77
}78
79
fn read_mono_wav(path: &str) -> Result<Vec<i16>, String> {80
let bytes = std::fs::read(path).map_err(|error| failed("read wav", error))?;81
let header = bytes.get(..WAV_HEADER).ok_or("wav too short")?;82
let channels = u16::from_le_bytes([header[22], header[23]]);83
let rate = u32::from_le_bytes([header[24], header[25], header[26], header[27]]);84
let bits = u16::from_le_bytes([header[34], header[35]]);85
if channels != 1 || rate != SAMPLE_RATE || bits != BITS {86
return Err(format!("need mono 16-bit {SAMPLE_RATE} Hz, got {channels} ch {bits} bit {rate} Hz"));87
}88
let data = bytes.windows(4).position(|tag| tag == b"data").ok_or("wav without data chunk")? + 8;89
Ok(bytes[data..].chunks_exact(2).map(|pair| i16::from_le_bytes([pair[0], pair[1]])).collect())90
}91
92
pub fn play(name_part: &str, wav: &str, seconds: u64) -> Result<(), String> {93
let samples = read_mono_wav(wav)?;94
if samples.is_empty() {95
return Err("wav without samples".to_owned());96
}97
let device = render_device(name_part)?;98
let block_align = CHANNELS * BITS / 8;99
let format = WAVEFORMATEX {100
wFormatTag: PCM_TAG,101
nChannels: CHANNELS,102
nSamplesPerSec: SAMPLE_RATE,103
nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),104
nBlockAlign: block_align,105
wBitsPerSample: BITS,106
cbSize: 0,107
};108
unsafe {109
let client: IAudioClient = device.Activate(CLSCTX_ALL, None).map_err(|error| failed("activate", error))?;110
client111
.Initialize(112
AUDCLNT_SHAREMODE_SHARED,113
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,114
BUFFER_HNS,115
0,116
&raw const format,117
None,118
)119
.map_err(|error| failed("initialize", error))?;120
let buffer_frames = client.GetBufferSize().map_err(|error| failed("buffer size", error))?;121
let render: IAudioRenderClient = client.GetService().map_err(|error| failed("render service", error))?;122
client.Start().map_err(|error| failed("start", error))?;123
let started = Instant::now();124
let mut position = 0usize;125
println!("{{\"playing\":true}}");126
while started.elapsed() < Duration::from_secs(seconds) {127
let padding = client.GetCurrentPadding().map_err(|error| failed("padding", error))?;128
let frames = buffer_frames - padding;129
if frames > 0 {130
let data = render.GetBuffer(frames).map_err(|error| failed("buffer", error))?;131
let output = std::slice::from_raw_parts_mut(data.cast::<i16>(), frames as usize * usize::from(CHANNELS));132
for pair in output.chunks_exact_mut(usize::from(CHANNELS)) {133
let sample = samples[position % samples.len()];134
pair.fill(sample);135
position += 1;136
}137
render.ReleaseBuffer(frames, 0).map_err(|error| failed("release", error))?;138
}139
std::thread::sleep(TICK);140
}141
let _ = client.Stop();142
}143
Ok(())144
}145
146
fn rms(samples: &[i16]) -> f64 {147
let sum: f64 = samples.iter().map(|sample| f64::from(*sample).powi(2)).sum();148
(sum / samples.len().max(1) as f64).sqrt()149
}150
151
pub fn record_process(process_id: u32, seconds: u64, out: &str) -> Result<(), String> {152
let queue = SampleQueue::default();153
let _capture = calling::start_process_capture(queue.clone(), process_id).map_err(|error| failed("capture", error))?;154
let mut dump = WavDump::create(std::path::Path::new(out)).map_err(|error| failed("wav", error))?;155
let frames_per_window = WINDOW_MS * SAMPLE_RATE as usize / 1000 / FRAME_SAMPLES;156
let mut window = Vec::new();157
let mut loudness = Vec::new();158
let started = Instant::now();159
let mut next = Instant::now();160
while started.elapsed() < Duration::from_secs(seconds) {161
let (frame, _) = queue.next_frame();162
dump.write(&frame);163
window.extend_from_slice(&frame);164
if window.len() >= frames_per_window * FRAME_SAMPLES {165
loudness.push(rms(&window).round());166
window.clear();167
}168
next += TICK;169
std::thread::sleep(next.saturating_duration_since(Instant::now()));170
}171
println!("{{\"window_ms\":{WINDOW_MS},\"rms\":{loudness:?}}}");172
Ok(())173
}174
}@@ -0,0 +1,41 @@
1
//! Creates a "Native client test" Meet now meeting and prints its join link (call end-to-end test).
2
use serde_json::{Value, json};
3
use session::{DEFAULT_ENDPOINT, Method, SPACES, Scope, Session};
4
5
const CREATE_URL: &str =
6
"https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
7
const SUBJECT: &str = "Native client test";
8
const LINK_KEYS: [&str; 4] = ["meetingUrl", "joinUrl", "meetingJoinUrl", "joinWebUrl"];
9
10
fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
11
match value {
12
Value::Object(map) => map.iter().find_map(|(key, inner)| {
13
let direct = keys
14
.iter()
15
.any(|wanted| key.eq_ignore_ascii_case(wanted))
16
.then(|| inner.as_str().filter(|text| !text.is_empty()))
17
.flatten();
18
direct.or_else(|| find_text(inner, keys))
19
}),
20
Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
21
_ => None,
22
}
23
}
24
25
#[tokio::main]
26
async fn main() {
27
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
28
let session = Session::connect(&endpoint).await.expect("browser");
29
let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
30
let created = session
31
.request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
32
.await
33
.expect("create meeting");
34
match find_text(&created.body, &LINK_KEYS) {
35
Some(link) => println!("{link}"),
36
None => {
37
eprintln!("HTTP {} without a join link: {:#}", created.status, created.body);
38
std::process::exit(1);
39
}
40
}
41
}
@@ -0,0 +1,41 @@1
//! Creates a "Native client test" Meet now meeting and prints its join link (call end-to-end test).2
use serde_json::{Value, json};3
use session::{DEFAULT_ENDPOINT, Method, SPACES, Scope, Session};4
5
const CREATE_URL: &str =6
"https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";7
const SUBJECT: &str = "Native client test";8
const LINK_KEYS: [&str; 4] = ["meetingUrl", "joinUrl", "meetingJoinUrl", "joinWebUrl"];9
10
fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {11
match value {12
Value::Object(map) => map.iter().find_map(|(key, inner)| {13
let direct = keys14
.iter()15
.any(|wanted| key.eq_ignore_ascii_case(wanted))16
.then(|| inner.as_str().filter(|text| !text.is_empty()))17
.flatten();18
direct.or_else(|| find_text(inner, keys))19
}),20
Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),21
_ => None,22
}23
}24
25
#[tokio::main]26
async fn main() {27
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());28
let session = Session::connect(&endpoint).await.expect("browser");29
let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});30
let created = session31
.request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))32
.await33
.expect("create meeting");34
match find_text(&created.body, &LINK_KEYS) {35
Some(link) => println!("{link}"),36
None => {37
eprintln!("HTTP {} without a join link: {:#}", created.status, created.body);38
std::process::exit(1);39
}40
}41
}@@ -34,6 +34,8 @@ mod loopback_windows;
34
34
#[cfg(windows)]
35
35
mod mic_windows;
36
36
#[cfg(windows)]
37
pub use loopback_windows::start_process_capture;
38
#[cfg(windows)]
37
39
pub use mic_windows::probe_effects;
38
40
pub mod meeting;
39
41
pub mod meeting_options;
@@ -34,6 +34,8 @@ mod loopback_windows;34
#[cfg(windows)]34
#[cfg(windows)]35
mod mic_windows;35
mod mic_windows;36
#[cfg(windows)]36
#[cfg(windows)]37
pub use loopback_windows::start_process_capture;38
#[cfg(windows)]37
pub use mic_windows::probe_effects;39
pub use mic_windows::probe_effects;38
pub mod meeting;40
pub mod meeting;39
pub mod meeting_options;41
pub mod meeting_options;@@ -8,7 +8,8 @@ use windows::Win32::Media::Audio::{
8
8
AUDCLNT_STREAMFLAGS_LOOPBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,
9
9
AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
10
10
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,
11
IActivateAudioInterfaceCompletionHandler_Impl, IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
11
IActivateAudioInterfaceCompletionHandler_Impl, IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
12
PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
12
13
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVEFORMATEX,
13
14
};
14
15
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
@@ -60,13 +61,13 @@ fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
60
61
Error::Audio(format!("{what}: {error}"))
61
62
}
62
63
63
fn activate_excluding(process_id: u32) -> Result<IAudioClient> {
64
fn activate(process_id: u32, mode: PROCESS_LOOPBACK_MODE) -> Result<IAudioClient> {
64
65
let mut parameters = AUDIOCLIENT_ACTIVATION_PARAMS {
65
66
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
66
67
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
67
68
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
68
69
TargetProcessId: process_id,
69
ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,
70
ProcessLoopbackMode: mode,
70
71
},
71
72
},
72
73
};
@@ -140,12 +141,21 @@ fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::R
140
141
}
141
142
142
143
pub fn start_process_loopback(queue: SampleQueue, own_process_id: u32) -> Result<Capture> {
144
start(queue, own_process_id, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE)
145
}
146
147
/// Only the audio of `process_id` and its children, for checking what an app plays out.
148
pub fn start_process_capture(queue: SampleQueue, process_id: u32) -> Result<Capture> {
149
start(queue, process_id, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE)
150
}
151
152
fn start(queue: SampleQueue, process_id: u32, mode: PROCESS_LOOPBACK_MODE) -> Result<Capture> {
143
153
let (ready_sender, ready) = mpsc::channel::<Result<()>>();
144
154
let capture = Capture::spawn_thread("process-loopback", move |stop| {
145
155
unsafe {
146
156
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
147
157
}
148
let started = activate_excluding(own_process_id).and_then(|client| initialise(&client).map(|(capture, event)| (client, capture, event)));
158
let started = activate(process_id, mode).and_then(|client| initialise(&client).map(|(capture, event)| (client, capture, event)));
149
159
match started {
150
160
Ok((client, capture, event)) => {
151
161
let _ = ready_sender.send(Ok(()));
@@ -8,7 +8,8 @@ use windows::Win32::Media::Audio::{8
AUDCLNT_STREAMFLAGS_LOOPBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,8
AUDCLNT_STREAMFLAGS_LOOPBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,9
AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,9
AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,10
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,10
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,11
IActivateAudioInterfaceCompletionHandler_Impl, IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,11
IActivateAudioInterfaceCompletionHandler_Impl, IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,12
PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,12
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVEFORMATEX,13
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVEFORMATEX,13
};14
};14
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;15
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;@@ -60,13 +61,13 @@ fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {60
Error::Audio(format!("{what}: {error}"))61
Error::Audio(format!("{what}: {error}"))61
}62
}62
63
63
fn activate_excluding(process_id: u32) -> Result<IAudioClient> {64
fn activate(process_id: u32, mode: PROCESS_LOOPBACK_MODE) -> Result<IAudioClient> {64
let mut parameters = AUDIOCLIENT_ACTIVATION_PARAMS {65
let mut parameters = AUDIOCLIENT_ACTIVATION_PARAMS {65
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,66
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,66
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {67
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {67
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {68
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {68
TargetProcessId: process_id,69
TargetProcessId: process_id,69
ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,70
ProcessLoopbackMode: mode,70
},71
},71
},72
},72
};73
};@@ -140,12 +141,21 @@ fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::R140
}141
}141
142
142
pub fn start_process_loopback(queue: SampleQueue, own_process_id: u32) -> Result<Capture> {143
pub fn start_process_loopback(queue: SampleQueue, own_process_id: u32) -> Result<Capture> {144
start(queue, own_process_id, PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE)145
}146
147
/// Only the audio of `process_id` and its children, for checking what an app plays out.148
pub fn start_process_capture(queue: SampleQueue, process_id: u32) -> Result<Capture> {149
start(queue, process_id, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE)150
}151
152
fn start(queue: SampleQueue, process_id: u32, mode: PROCESS_LOOPBACK_MODE) -> Result<Capture> {143
let (ready_sender, ready) = mpsc::channel::<Result<()>>();153
let (ready_sender, ready) = mpsc::channel::<Result<()>>();144
let capture = Capture::spawn_thread("process-loopback", move |stop| {154
let capture = Capture::spawn_thread("process-loopback", move |stop| {145
unsafe {155
unsafe {146
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);156
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);147
}157
}148
let started = activate_excluding(own_process_id).and_then(|client| initialise(&client).map(|(capture, event)| (client, capture, event)));158
let started = activate(process_id, mode).and_then(|client| initialise(&client).map(|(capture, event)| (client, capture, event)));149
match started {159
match started {150
Ok((client, capture, event)) => {160
Ok((client, capture, event)) => {151
let _ = ready_sender.send(Ok(()));161
let _ = ready_sender.send(Ok(()));@@ -13,6 +13,27 @@ async fn main() {
13
13
let arguments: Vec<String> = std::env::args().skip(1).collect();
14
14
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
15
15
let session = Session::connect(&endpoint).await.expect("browser");
16
if let ["lib-create", team_thread_id, group_id, name, privacy, object_id, tenant_id] =
17
arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice()
18
{
19
let channel = chatsvc::NewChannel {
20
team_thread_id,
21
group_id,
22
name,
23
description: "",
24
privacy: if *privacy == "private" {
25
chatsvc::ChannelPrivacy::Private
26
} else {
27
chatsvc::ChannelPrivacy::Standard
28
},
29
};
30
let mailbox = chatsvc::Mailbox { object_id, tenant_id };
31
let outcome = chatsvc::TeamAdmin::new(&session)
32
.create_channel(&channel, mailbox)
33
.await;
34
println!("{outcome:?}");
35
return;
36
}
16
37
let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
17
38
["create-team", name] => (
18
39
Method::Post,
@@ -13,6 +13,27 @@ async fn main() {13
let arguments: Vec<String> = std::env::args().skip(1).collect();13
let arguments: Vec<String> = std::env::args().skip(1).collect();14
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());14
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());15
let session = Session::connect(&endpoint).await.expect("browser");15
let session = Session::connect(&endpoint).await.expect("browser");16
if let ["lib-create", team_thread_id, group_id, name, privacy, object_id, tenant_id] =17
arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice()18
{19
let channel = chatsvc::NewChannel {20
team_thread_id,21
group_id,22
name,23
description: "",24
privacy: if *privacy == "private" {25
chatsvc::ChannelPrivacy::Private26
} else {27
chatsvc::ChannelPrivacy::Standard28
},29
};30
let mailbox = chatsvc::Mailbox { object_id, tenant_id };31
let outcome = chatsvc::TeamAdmin::new(&session)32
.create_channel(&channel, mailbox)33
.await;34
println!("{outcome:?}");35
return;36
}16
let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {37
let (method, path, body) = match arguments.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {17
["create-team", name] => (38
["create-team", name] => (18
Method::Post,39
Method::Post,@@ -0,0 +1,212 @@
1
// Call end-to-end test with Daniel's real account and the deployed Windows app, no second person needed.
2
// Teams web (own Chrome, CDP 9222) joins a fresh Meet now with a looped speech file as its mic.
3
// The Windows app joins through `teams.exe --join`; its mic is VB-CABLE fed with a second speech file,
4
// and process loopback records what the app plays. Both directions must show speech with pauses.
5
// Usage: node scripts/call-e2e.mjs <work dir> [meeting link]
6
import { spawn, execFileSync } from 'node:child_process';
7
import { createServer } from 'node:http';
8
import { readFileSync, writeFileSync } from 'node:fs';
9
import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';
10
11
const [workDir, givenLink] = process.argv.slice(2);
12
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';
13
const PORT = Number(process.env.E2E_PORT ?? 9475);
14
const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';
15
const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';
16
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
17
const TASKLIST = '/mnt/c/Windows/System32/tasklist.exe';
18
const SCRIPT_DIR = new URL('.', import.meta.url).pathname;
19
const REPO_DIR = new URL('..', import.meta.url).pathname;
20
const APP_START_WAIT_MS = 40_000;
21
const WEB_JOIN_TIMEOUT_MS = 90_000;
22
const APP_JOIN_WAIT_MS = 25_000;
23
const MEASURE_SECONDS = 30;
24
const WINDOW_MS = 250;
25
const WEB_JOIN_STEPS = ['Continue on this browser', 'Join now'];
26
const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };
27
const APP_THRESHOLD = { speech: 200, floor: 20 };
28
const SPEECH_TO_PAUSE = 4;
29
30
const windowsPath = (path) => execFileSync('wslpath', ['-w', path]).toString().trim();
31
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
const log = (message) => console.error(`[${new Date().toISOString().slice(11, 19)}] ${message}`);
33
34
function defaultAudio(...args) {
35
const script = windowsPath(SCRIPT_DIR + 'default-audio.ps1');
36
return execFileSync(POWERSHELL, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, ...args]).toString().trim();
37
}
38
39
function createMeeting() {
40
return execFileSync('cargo', ['run', '-q', '-p', 'calling', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })
41
.toString()
42
.trim();
43
}
44
45
function teamsProcessId() {
46
const rows = execFileSync(TASKLIST, ['/FI', 'IMAGENAME eq teams.exe', '/FO', 'CSV', '/NH']).toString().trim().split(/\r?\n/);
47
const processes = rows
48
.map((row) => row.split('","').map((cell) => cell.replace(/"/g, '')))
49
.filter((cells) => cells[0]?.toLowerCase() === 'teams.exe')
50
.map((cells) => ({ id: Number(cells[1]), memory: Number(cells[4].replace(/\D/g, '')) }));
51
processes.sort((left, right) => right.memory - left.memory);
52
return processes[0]?.id;
53
}
54
55
function runTeams(...args) {
56
spawn(TEAMS_EXE, args, { detached: true, stdio: 'ignore' }).unref();
57
}
58
59
function runProbe(...args) {
60
return new Promise((resolve, reject) => {
61
const child = spawn(PROBE_DIR + '/audio_probe.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
62
let output = '';
63
let errors = '';
64
child.stdout.on('data', (chunk) => (output += chunk));
65
child.stderr.on('data', (chunk) => (errors += chunk));
66
child.on('exit', (code) => (code === 0 ? resolve(output) : reject(new Error(`audio_probe ${args[0]}: ${errors.trim()}`))));
67
});
68
}
69
70
function serveSpeech() {
71
const speech = readFileSync(PROBE_DIR + '/web.wav');
72
const server = createServer((_, response) => {
73
response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(speech);
74
});
75
server.listen(PORT, '127.0.0.1');
76
return server;
77
}
78
79
const INBOUND_AUDIO = `(async () => {
80
let energy = 0, duration = 0, packets = 0;
81
for (const peer of window.__pcs || []) {
82
if (peer.connectionState === 'closed') continue;
83
(await peer.getStats()).forEach((entry) => {
84
if (entry.type !== 'inbound-rtp' || entry.kind !== 'audio') return;
85
energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; packets += entry.packetsReceived || 0;
86
});
87
}
88
return { energy, duration, packets };
89
})()`;
90
91
class WebTab {
92
constructor(browser) { this.browser = browser; }
93
async open(link) {
94
const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank' });
95
this.targetId = targetId;
96
const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });
97
this.sessionId = sessionId;
98
await this.browser.send('Page.enable', {}, sessionId);
99
await this.browser.send('Runtime.enable', {}, sessionId);
100
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);
101
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/speech.wav`) }, sessionId);
102
await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin: 'https://teams.cloud.microsoft' }).catch(() => {});
103
await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});
104
await this.browser.send('Page.navigate', { url: link }, sessionId);
105
}
106
async evaluate(expression) {
107
const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);
108
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');
109
return result.result.value;
110
}
111
async join() {
112
const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;
113
while (Date.now() < deadline) {
114
const audio = await this.evaluate(INBOUND_AUDIO).catch(() => null);
115
if (audio && audio.packets > 0) return true;
116
for (const step of WEB_JOIN_STEPS) {
117
const click = await this.evaluate(CLICK(step)).catch(() => null);
118
if (click?.clicked) log(`web: clicked "${step}"`);
119
}
120
await delay(2000);
121
}
122
return false;
123
}
124
async shot(path) {
125
const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);
126
writeFileSync(path, Buffer.from(data, 'base64'));
127
}
128
async close() {
129
if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});
130
}
131
}
132
133
async function sampleWeb(tab, seconds) {
134
const levels = [];
135
let previous = await tab.evaluate(INBOUND_AUDIO);
136
const end = Date.now() + seconds * 1000;
137
while (Date.now() < end) {
138
await delay(WINDOW_MS);
139
const current = await tab.evaluate(INBOUND_AUDIO);
140
const duration = current.duration - previous.duration;
141
levels.push(duration > 0 ? Math.sqrt(Math.max(0, current.energy - previous.energy) / duration) : 0);
142
previous = current;
143
}
144
return levels;
145
}
146
147
function judge(levels, threshold) {
148
const sorted = [...levels].sort((left, right) => left - right);
149
const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;
150
const [p10, p90] = [percentile(0.1), percentile(0.9)];
151
const speech = p90 >= threshold.speech;
152
const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);
153
return { pass: speech && pauses, p10, p90, windows: levels.length };
154
}
155
156
const report = { started: new Date().toISOString() };
157
const savedCapture = defaultAudio('get', 'capture');
158
const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);
159
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });
160
const server = serveSpeech();
161
const browser = await new Browser(OWN_ENDPOINT).connect();
162
const tab = new WebTab(browser);
163
try {
164
if (!teamsProcessId()) {
165
log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);
166
runTeams();
167
await delay(APP_START_WAIT_MS);
168
}
169
const link = givenLink ?? createMeeting();
170
report.link = link;
171
log('meeting ready');
172
await tab.open(link);
173
report.webJoined = await tab.join();
174
log(`web joined: ${report.webJoined}`);
175
if (!report.webJoined) {
176
await tab.shot(workDir + '/web-join.png');
177
throw new Error('Teams web did not join, see web-join.png');
178
}
179
defaultAudio('set', 'capture', 'CABLE Output');
180
log('default mic: CABLE Output');
181
const playSeconds = Math.ceil(APP_JOIN_WAIT_MS / 1000) + MEASURE_SECONDS + 10;
182
const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));
183
runTeams('--join', link);
184
log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);
185
await delay(APP_JOIN_WAIT_MS);
186
const processId = teamsProcessId();
187
if (!processId) throw new Error('teams.exe is not running');
188
log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);
189
const [recorded, webLevels] = await Promise.all([
190
runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),
191
sampleWeb(tab, MEASURE_SECONDS),
192
]);
193
report.appToWeb = judge(webLevels, WEB_THRESHOLD);
194
report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);
195
report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));
196
report.appLevels = JSON.parse(recorded).rms;
197
await tab.shot(workDir + '/web-in-call.png');
198
await playing.catch((error) => (report.playError = error.message));
199
} catch (error) {
200
report.error = error.message;
201
} finally {
202
if (teamsProcessId()) runTeams('--hang-up');
203
await tab.close();
204
restoreCapture();
205
log('default mic restored');
206
server.close();
207
browser.socket.close();
208
}
209
report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);
210
writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));
211
console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, error: report.error }));
212
process.exit(report.pass ? 0 : 1);
@@ -0,0 +1,212 @@1
// Call end-to-end test with Daniel's real account and the deployed Windows app, no second person needed.2
// Teams web (own Chrome, CDP 9222) joins a fresh Meet now with a looped speech file as its mic.3
// The Windows app joins through `teams.exe --join`; its mic is VB-CABLE fed with a second speech file,4
// and process loopback records what the app plays. Both directions must show speech with pauses.5
// Usage: node scripts/call-e2e.mjs <work dir> [meeting link]6
import { spawn, execFileSync } from 'node:child_process';7
import { createServer } from 'node:http';8
import { readFileSync, writeFileSync } from 'node:fs';9
import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK } from './teams-web-cdp.mjs';10
11
const [workDir, givenLink] = process.argv.slice(2);12
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';13
const PORT = Number(process.env.E2E_PORT ?? 9475);14
const PROBE_DIR = process.env.PROBE_DIR ?? '/mnt/c/Users/dd/AppData/Local/Temp/call-e2e';15
const TEAMS_EXE = process.env.TEAMS_EXE ?? '/mnt/c/Users/dd/AppData/Local/Programs/ms-teams-linux/teams.exe';16
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';17
const TASKLIST = '/mnt/c/Windows/System32/tasklist.exe';18
const SCRIPT_DIR = new URL('.', import.meta.url).pathname;19
const REPO_DIR = new URL('..', import.meta.url).pathname;20
const APP_START_WAIT_MS = 40_000;21
const WEB_JOIN_TIMEOUT_MS = 90_000;22
const APP_JOIN_WAIT_MS = 25_000;23
const MEASURE_SECONDS = 30;24
const WINDOW_MS = 250;25
const WEB_JOIN_STEPS = ['Continue on this browser', 'Join now'];26
const WEB_THRESHOLD = { speech: 0.005, floor: 0.0005 };27
const APP_THRESHOLD = { speech: 200, floor: 20 };28
const SPEECH_TO_PAUSE = 4;29
30
const windowsPath = (path) => execFileSync('wslpath', ['-w', path]).toString().trim();31
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));32
const log = (message) => console.error(`[${new Date().toISOString().slice(11, 19)}] ${message}`);33
34
function defaultAudio(...args) {35
const script = windowsPath(SCRIPT_DIR + 'default-audio.ps1');36
return execFileSync(POWERSHELL, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, ...args]).toString().trim();37
}38
39
function createMeeting() {40
return execFileSync('cargo', ['run', '-q', '-p', 'calling', '--example', 'create_test_meeting'], { cwd: REPO_DIR, stdio: ['ignore', 'pipe', 'inherit'] })41
.toString()42
.trim();43
}44
45
function teamsProcessId() {46
const rows = execFileSync(TASKLIST, ['/FI', 'IMAGENAME eq teams.exe', '/FO', 'CSV', '/NH']).toString().trim().split(/\r?\n/);47
const processes = rows48
.map((row) => row.split('","').map((cell) => cell.replace(/"/g, '')))49
.filter((cells) => cells[0]?.toLowerCase() === 'teams.exe')50
.map((cells) => ({ id: Number(cells[1]), memory: Number(cells[4].replace(/\D/g, '')) }));51
processes.sort((left, right) => right.memory - left.memory);52
return processes[0]?.id;53
}54
55
function runTeams(...args) {56
spawn(TEAMS_EXE, args, { detached: true, stdio: 'ignore' }).unref();57
}58
59
function runProbe(...args) {60
return new Promise((resolve, reject) => {61
const child = spawn(PROBE_DIR + '/audio_probe.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] });62
let output = '';63
let errors = '';64
child.stdout.on('data', (chunk) => (output += chunk));65
child.stderr.on('data', (chunk) => (errors += chunk));66
child.on('exit', (code) => (code === 0 ? resolve(output) : reject(new Error(`audio_probe ${args[0]}: ${errors.trim()}`))));67
});68
}69
70
function serveSpeech() {71
const speech = readFileSync(PROBE_DIR + '/web.wav');72
const server = createServer((_, response) => {73
response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(speech);74
});75
server.listen(PORT, '127.0.0.1');76
return server;77
}78
79
const INBOUND_AUDIO = `(async () => {80
let energy = 0, duration = 0, packets = 0;81
for (const peer of window.__pcs || []) {82
if (peer.connectionState === 'closed') continue;83
(await peer.getStats()).forEach((entry) => {84
if (entry.type !== 'inbound-rtp' || entry.kind !== 'audio') return;85
energy += entry.totalAudioEnergy || 0; duration += entry.totalSamplesDuration || 0; packets += entry.packetsReceived || 0;86
});87
}88
return { energy, duration, packets };89
})()`;90
91
class WebTab {92
constructor(browser) { this.browser = browser; }93
async open(link) {94
const { targetId } = await this.browser.send('Target.createTarget', { url: 'about:blank' });95
this.targetId = targetId;96
const { sessionId } = await this.browser.send('Target.attachToTarget', { targetId, flatten: true });97
this.sessionId = sessionId;98
await this.browser.send('Page.enable', {}, sessionId);99
await this.browser.send('Runtime.enable', {}, sessionId);100
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId);101
await this.browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/speech.wav`) }, sessionId);102
await this.browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture'], origin: 'https://teams.cloud.microsoft' }).catch(() => {});103
await this.browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {});104
await this.browser.send('Page.navigate', { url: link }, sessionId);105
}106
async evaluate(expression) {107
const result = await this.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, this.sessionId);108
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed');109
return result.result.value;110
}111
async join() {112
const deadline = Date.now() + WEB_JOIN_TIMEOUT_MS;113
while (Date.now() < deadline) {114
const audio = await this.evaluate(INBOUND_AUDIO).catch(() => null);115
if (audio && audio.packets > 0) return true;116
for (const step of WEB_JOIN_STEPS) {117
const click = await this.evaluate(CLICK(step)).catch(() => null);118
if (click?.clicked) log(`web: clicked "${step}"`);119
}120
await delay(2000);121
}122
return false;123
}124
async shot(path) {125
const { data } = await this.browser.send('Page.captureScreenshot', { format: 'png' }, this.sessionId);126
writeFileSync(path, Buffer.from(data, 'base64'));127
}128
async close() {129
if (this.targetId) await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {});130
}131
}132
133
async function sampleWeb(tab, seconds) {134
const levels = [];135
let previous = await tab.evaluate(INBOUND_AUDIO);136
const end = Date.now() + seconds * 1000;137
while (Date.now() < end) {138
await delay(WINDOW_MS);139
const current = await tab.evaluate(INBOUND_AUDIO);140
const duration = current.duration - previous.duration;141
levels.push(duration > 0 ? Math.sqrt(Math.max(0, current.energy - previous.energy) / duration) : 0);142
previous = current;143
}144
return levels;145
}146
147
function judge(levels, threshold) {148
const sorted = [...levels].sort((left, right) => left - right);149
const percentile = (share) => sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))] ?? 0;150
const [p10, p90] = [percentile(0.1), percentile(0.9)];151
const speech = p90 >= threshold.speech;152
const pauses = p90 >= SPEECH_TO_PAUSE * Math.max(p10, threshold.floor);153
return { pass: speech && pauses, p10, p90, windows: levels.length };154
}155
156
const report = { started: new Date().toISOString() };157
const savedCapture = defaultAudio('get', 'capture');158
const restoreCapture = () => defaultAudio('set', 'capture', savedCapture);159
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { restoreCapture(); process.exit(130); });160
const server = serveSpeech();161
const browser = await new Browser(OWN_ENDPOINT).connect();162
const tab = new WebTab(browser);163
try {164
if (!teamsProcessId()) {165
log(`starting the app, waiting ${APP_START_WAIT_MS / 1000}s`);166
runTeams();167
await delay(APP_START_WAIT_MS);168
}169
const link = givenLink ?? createMeeting();170
report.link = link;171
log('meeting ready');172
await tab.open(link);173
report.webJoined = await tab.join();174
log(`web joined: ${report.webJoined}`);175
if (!report.webJoined) {176
await tab.shot(workDir + '/web-join.png');177
throw new Error('Teams web did not join, see web-join.png');178
}179
defaultAudio('set', 'capture', 'CABLE Output');180
log('default mic: CABLE Output');181
const playSeconds = Math.ceil(APP_JOIN_WAIT_MS / 1000) + MEASURE_SECONDS + 10;182
const playing = runProbe('play', 'CABLE Input', windowsPath(PROBE_DIR + '/app.wav'), String(playSeconds));183
runTeams('--join', link);184
log(`app joining, waiting ${APP_JOIN_WAIT_MS / 1000}s`);185
await delay(APP_JOIN_WAIT_MS);186
const processId = teamsProcessId();187
if (!processId) throw new Error('teams.exe is not running');188
log(`measuring ${MEASURE_SECONDS}s (teams.exe pid ${processId})`);189
const [recorded, webLevels] = await Promise.all([190
runProbe('record-process', String(processId), String(MEASURE_SECONDS), windowsPath(workDir + '/app-heard.wav')),191
sampleWeb(tab, MEASURE_SECONDS),192
]);193
report.appToWeb = judge(webLevels, WEB_THRESHOLD);194
report.webToApp = judge(JSON.parse(recorded).rms, APP_THRESHOLD);195
report.webLevels = webLevels.map((level) => Number(level.toFixed(4)));196
report.appLevels = JSON.parse(recorded).rms;197
await tab.shot(workDir + '/web-in-call.png');198
await playing.catch((error) => (report.playError = error.message));199
} catch (error) {200
report.error = error.message;201
} finally {202
if (teamsProcessId()) runTeams('--hang-up');203
await tab.close();204
restoreCapture();205
log('default mic restored');206
server.close();207
browser.socket.close();208
}209
report.pass = Boolean(report.appToWeb?.pass && report.webToApp?.pass);210
writeFileSync(workDir + '/report.json', JSON.stringify(report, null, 2));211
console.log(JSON.stringify({ pass: report.pass, appToWeb: report.appToWeb, webToApp: report.webToApp, error: report.error }));212
process.exit(report.pass ? 0 : 1);@@ -0,0 +1,65 @@
1
# Read or set the Windows default audio endpoints (console and communications role) for the call end-to-end test.
2
# get <render|capture> prints "<console id>|<communications id>"
3
# set <render|capture> <name part or id>|<communications id> sets both roles
4
param([string]$Action, [string]$Flow, [string]$Target)
5
Add-Type -TypeDefinition @"
6
using System; using System.Runtime.InteropServices;
7
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
8
interface IMMDeviceEnumerator { int EnumAudioEndpoints(int dataFlow, int state, out IMMDeviceCollection devices); int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device); }
9
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
10
interface IMMDeviceCollection { int GetCount(out int count); int Item(int index, out IMMDevice device); }
11
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
12
interface IMMDevice { int Activate(); int OpenPropertyStore(int access, out IPropertyStore store); int GetId([MarshalAs(UnmanagedType.LPWStr)] out string id); }
13
[Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
14
interface IPropertyStore { int GetCount(out int count); int GetAt(int index, out PropertyKey key); int GetValue(ref PropertyKey key, out PropVariant value); }
15
[Guid("f8679f50-850a-41cf-9c72-430f290290c8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
16
interface IPolicyConfig { int A(); int B(); int C(); int D(); int E(); int F(); int G(); int H(); int I(); int J();
17
int SetDefaultEndpoint([MarshalAs(UnmanagedType.LPWStr)] string id, int role); }
18
[StructLayout(LayoutKind.Sequential)] public struct PropertyKey { public Guid fmtid; public int pid; }
19
[StructLayout(LayoutKind.Explicit)] public struct PropVariant { [FieldOffset(0)] public short vt; [FieldOffset(8)] public IntPtr pointer; }
20
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumerator {}
21
[ComImport, Guid("870af99c-171d-4f9e-af0d-e63df40c2bc9")] class PolicyConfigClient {}
22
public static class DefaultAudio {
23
const int Console = 0, Communications = 2, Active = 1;
24
static IMMDeviceEnumerator Enumerator() { return (IMMDeviceEnumerator)new MMDeviceEnumerator(); }
25
static string Id(IMMDevice device) { string id; device.GetId(out id); return id; }
26
static string Name(IMMDevice device) {
27
IPropertyStore store; device.OpenPropertyStore(0, out store);
28
var key = new PropertyKey { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 14 }; PropVariant value; store.GetValue(ref key, out value);
29
return Marshal.PtrToStringUni(value.pointer);
30
}
31
public static string Get(int flow) {
32
IMMDevice console, communications;
33
Enumerator().GetDefaultAudioEndpoint(flow, Console, out console);
34
Enumerator().GetDefaultAudioEndpoint(flow, Communications, out communications);
35
return Id(console) + "|" + Id(communications);
36
}
37
public static string Resolve(int flow, string target) {
38
if (target.StartsWith("{")) return target;
39
IMMDeviceCollection devices; Enumerator().EnumAudioEndpoints(flow, Active, out devices);
40
int count; devices.GetCount(out count);
41
for (int index = 0; index < count; index++) {
42
IMMDevice device; devices.Item(index, out device);
43
if (Name(device).Contains(target)) return Id(device);
44
}
45
throw new Exception("no active endpoint named " + target);
46
}
47
public static void Set(int flow, string consoleTarget, string communicationsTarget) {
48
var policy = (IPolicyConfig)new PolicyConfigClient();
49
policy.SetDefaultEndpoint(Resolve(flow, consoleTarget), Console);
50
policy.SetDefaultEndpoint(Resolve(flow, communicationsTarget), Communications);
51
}
52
}
53
"@
54
$dataFlow = if ($Flow -eq 'capture') { 1 } else { 0 }
55
if ($Action -eq 'get') {
56
[DefaultAudio]::Get($dataFlow)
57
} elseif ($Action -eq 'set') {
58
$parts = $Target.Split('|')
59
$communications = if ($parts.Length -gt 1) { $parts[1] } else { $parts[0] }
60
[DefaultAudio]::Set($dataFlow, $parts[0], $communications)
61
[DefaultAudio]::Get($dataFlow)
62
} else {
63
Write-Error 'usage: default-audio.ps1 get|set render|capture [target]'
64
exit 1
65
}
@@ -0,0 +1,65 @@1
# Read or set the Windows default audio endpoints (console and communications role) for the call end-to-end test.2
# get <render|capture> prints "<console id>|<communications id>"3
# set <render|capture> <name part or id>|<communications id> sets both roles4
param([string]$Action, [string]$Flow, [string]$Target)5
Add-Type -TypeDefinition @"6
using System; using System.Runtime.InteropServices;7
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]8
interface IMMDeviceEnumerator { int EnumAudioEndpoints(int dataFlow, int state, out IMMDeviceCollection devices); int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device); }9
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]10
interface IMMDeviceCollection { int GetCount(out int count); int Item(int index, out IMMDevice device); }11
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]12
interface IMMDevice { int Activate(); int OpenPropertyStore(int access, out IPropertyStore store); int GetId([MarshalAs(UnmanagedType.LPWStr)] out string id); }13
[Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]14
interface IPropertyStore { int GetCount(out int count); int GetAt(int index, out PropertyKey key); int GetValue(ref PropertyKey key, out PropVariant value); }15
[Guid("f8679f50-850a-41cf-9c72-430f290290c8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]16
interface IPolicyConfig { int A(); int B(); int C(); int D(); int E(); int F(); int G(); int H(); int I(); int J();17
int SetDefaultEndpoint([MarshalAs(UnmanagedType.LPWStr)] string id, int role); }18
[StructLayout(LayoutKind.Sequential)] public struct PropertyKey { public Guid fmtid; public int pid; }19
[StructLayout(LayoutKind.Explicit)] public struct PropVariant { [FieldOffset(0)] public short vt; [FieldOffset(8)] public IntPtr pointer; }20
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumerator {}21
[ComImport, Guid("870af99c-171d-4f9e-af0d-e63df40c2bc9")] class PolicyConfigClient {}22
public static class DefaultAudio {23
const int Console = 0, Communications = 2, Active = 1;24
static IMMDeviceEnumerator Enumerator() { return (IMMDeviceEnumerator)new MMDeviceEnumerator(); }25
static string Id(IMMDevice device) { string id; device.GetId(out id); return id; }26
static string Name(IMMDevice device) {27
IPropertyStore store; device.OpenPropertyStore(0, out store);28
var key = new PropertyKey { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 14 }; PropVariant value; store.GetValue(ref key, out value);29
return Marshal.PtrToStringUni(value.pointer);30
}31
public static string Get(int flow) {32
IMMDevice console, communications;33
Enumerator().GetDefaultAudioEndpoint(flow, Console, out console);34
Enumerator().GetDefaultAudioEndpoint(flow, Communications, out communications);35
return Id(console) + "|" + Id(communications);36
}37
public static string Resolve(int flow, string target) {38
if (target.StartsWith("{")) return target;39
IMMDeviceCollection devices; Enumerator().EnumAudioEndpoints(flow, Active, out devices);40
int count; devices.GetCount(out count);41
for (int index = 0; index < count; index++) {42
IMMDevice device; devices.Item(index, out device);43
if (Name(device).Contains(target)) return Id(device);44
}45
throw new Exception("no active endpoint named " + target);46
}47
public static void Set(int flow, string consoleTarget, string communicationsTarget) {48
var policy = (IPolicyConfig)new PolicyConfigClient();49
policy.SetDefaultEndpoint(Resolve(flow, consoleTarget), Console);50
policy.SetDefaultEndpoint(Resolve(flow, communicationsTarget), Communications);51
}52
}53
"@54
$dataFlow = if ($Flow -eq 'capture') { 1 } else { 0 }55
if ($Action -eq 'get') {56
[DefaultAudio]::Get($dataFlow)57
} elseif ($Action -eq 'set') {58
$parts = $Target.Split('|')59
$communications = if ($parts.Length -gt 1) { $parts[1] } else { $parts[0] }60
[DefaultAudio]::Set($dataFlow, $parts[0], $communications)61
[DefaultAudio]::Get($dataFlow)62
} else {63
Write-Error 'usage: default-audio.ps1 get|set render|capture [target]'64
exit 165
}@@ -3,98 +3,13 @@
3
3
import { spawn } from 'node:child_process';
4
4
import { createServer } from 'node:http';
5
5
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
6
import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK, PEER_STATS } from './teams-web-cdp.mjs';
6
7
7
8
const [binary, workDir] = process.argv.slice(2);
8
9
const GUEST_ENDPOINT = process.env.GUEST_CDP ?? 'http://127.0.0.1:9471';
9
10
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';
10
11
const PORT = Number(process.env.MATRIX_PORT ?? 9472);
11
12
12
const PEER_HOOK = `(() => {
13
const Original = window.RTCPeerConnection;
14
if (!Original || Original.__matrix) return;
15
window.__pcs = [];
16
const Wrapped = function (...args) { const peer = new Original(...args); window.__pcs.push(peer); return peer; };
17
Wrapped.prototype = Original.prototype;
18
Object.setPrototypeOf(Wrapped, Original);
19
Wrapped.__matrix = true;
20
window.RTCPeerConnection = Wrapped;
21
})();`;
22
23
// Signed-in Chrome has no fake devices: camera = moving canvas, mic = looped speech file, screen = canvas.
24
const FAKE_MEDIA = (speechUrl) => `(() => {
25
if (!navigator.mediaDevices || navigator.mediaDevices.__matrix) return;
26
const canvasTrack = (label, width, height) => {
27
const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height;
28
const context = canvas.getContext('2d'); let frame = 0;
29
setInterval(() => { frame++; context.fillStyle = 'hsl(' + (frame * 3 % 360) + ',70%,40%)'; context.fillRect(0, 0, width, height);
30
context.fillStyle = '#fff'; context.font = '48px sans-serif'; context.fillText(label + ' ' + frame, 40, height / 2); }, 66);
31
return canvas.captureStream(15).getVideoTracks()[0];
32
};
33
let audioContext;
34
const speechTrack = async () => {
35
audioContext = audioContext || new AudioContext();
36
const destination = audioContext.createMediaStreamDestination();
37
try {
38
const data = await (await fetch('${speechUrl}')).arrayBuffer();
39
const buffer = await audioContext.decodeAudioData(data);
40
const source = audioContext.createBufferSource(); source.buffer = buffer; source.loop = true; source.connect(destination); source.start();
41
} catch (error) {
42
const oscillator = audioContext.createOscillator(); oscillator.frequency.value = 440; oscillator.connect(destination); oscillator.start();
43
}
44
return destination.stream.getAudioTracks()[0];
45
};
46
const devices = [
47
{ deviceId: 'matrix-mic', kind: 'audioinput', label: 'Matrix mic', groupId: 'matrix' },
48
{ deviceId: 'matrix-cam', kind: 'videoinput', label: 'Matrix camera', groupId: 'matrix' },
49
{ deviceId: 'matrix-speaker', kind: 'audiooutput', label: 'Matrix speaker', groupId: 'matrix' },
50
].map((device) => ({ ...device, toJSON() { return device; } }));
51
navigator.mediaDevices.enumerateDevices = async () => devices;
52
navigator.mediaDevices.getUserMedia = async (constraints) => {
53
const tracks = [];
54
if (constraints && constraints.audio) tracks.push(await speechTrack());
55
if (constraints && constraints.video) tracks.push(canvasTrack('camera', 640, 360));
56
return new MediaStream(tracks);
57
};
58
navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);
59
navigator.mediaDevices.__matrix = true;
60
})();`;
61
62
const PEER_STATS = `(async () => {
63
const report = { peers: 0, audioIn: [], videoIn: [], audioOut: [], videoOut: [] };
64
for (const peer of window.__pcs || []) {
65
if (peer.connectionState === 'closed') continue;
66
report.peers++;
67
(await peer.getStats()).forEach((entry) => {
68
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });
69
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });
70
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });
71
});
72
}
73
return report;
74
})()`;
75
76
class Browser {
77
constructor(endpoint) { this.endpoint = endpoint; this.nextId = 1; this.pending = new Map(); this.listeners = []; }
78
async connect() {
79
const version = await (await fetch(this.endpoint + '/json/version')).json();
80
this.socket = new WebSocket(version.webSocketDebuggerUrl);
81
await new Promise((resolve, reject) => { this.socket.onopen = resolve; this.socket.onerror = reject; });
82
this.socket.onmessage = (message) => {
83
const data = JSON.parse(message.data);
84
if (data.id && this.pending.has(data.id)) {
85
const { resolve, reject } = this.pending.get(data.id); this.pending.delete(data.id);
86
data.error ? reject(new Error(data.error.message)) : resolve(data.result);
87
} else if (data.method) this.listeners.forEach((listener) => listener(data));
88
};
89
return this;
90
}
91
send(method, params = {}, sessionId) {
92
const id = this.nextId++;
93
this.socket.send(JSON.stringify({ id, method, params, sessionId }));
94
return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); setTimeout(() => { if (this.pending.delete(id)) reject(new Error(method + ' timed out')); }, 60000); });
95
}
96
}
97
98
13
const guests = new Map();
99
14
const events = [];
100
15
let child;
@@ -154,18 +69,6 @@ async function evaluate(guest, expression) {
154
69
return result.result.value;
155
70
}
156
71
157
const CLICK = (text) => `(() => {
158
const wanted = ${JSON.stringify(text)}.toLowerCase();
159
const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=tab], a, [role=option]')];
160
const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();
161
const visible = nodes.filter((node) => node.offsetParent !== null || node.getClientRects().length);
162
const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);
163
const target = exact || visible.find((node) => label(node).includes(wanted));
164
if (!target) return { clicked: false, candidates: visible.map(label).filter(Boolean).slice(0, 60) };
165
target.scrollIntoView({ block: 'center' }); target.click();
166
return { clicked: true, label: label(target).slice(0, 80) };
167
})()`;
168
169
72
async function openGuest({ name, own = false, url }) {
170
73
const browser = own ? ownBrowser : guestBrowser;
171
74
let browserContextId;
@@ -3,98 +3,13 @@3
import { spawn } from 'node:child_process';3
import { spawn } from 'node:child_process';4
import { createServer } from 'node:http';4
import { createServer } from 'node:http';5
import { readFileSync, writeFileSync, existsSync } from 'node:fs';5
import { readFileSync, writeFileSync, existsSync } from 'node:fs';6
import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK, PEER_STATS } from './teams-web-cdp.mjs';6
7
7
const [binary, workDir] = process.argv.slice(2);8
const [binary, workDir] = process.argv.slice(2);8
const GUEST_ENDPOINT = process.env.GUEST_CDP ?? 'http://127.0.0.1:9471';9
const GUEST_ENDPOINT = process.env.GUEST_CDP ?? 'http://127.0.0.1:9471';9
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';10
const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';10
const PORT = Number(process.env.MATRIX_PORT ?? 9472);11
const PORT = Number(process.env.MATRIX_PORT ?? 9472);11
12
12
const PEER_HOOK = `(() => {13
const Original = window.RTCPeerConnection;14
if (!Original || Original.__matrix) return;15
window.__pcs = [];16
const Wrapped = function (...args) { const peer = new Original(...args); window.__pcs.push(peer); return peer; };17
Wrapped.prototype = Original.prototype;18
Object.setPrototypeOf(Wrapped, Original);19
Wrapped.__matrix = true;20
window.RTCPeerConnection = Wrapped;21
})();`;22
23
// Signed-in Chrome has no fake devices: camera = moving canvas, mic = looped speech file, screen = canvas.24
const FAKE_MEDIA = (speechUrl) => `(() => {25
if (!navigator.mediaDevices || navigator.mediaDevices.__matrix) return;26
const canvasTrack = (label, width, height) => {27
const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height;28
const context = canvas.getContext('2d'); let frame = 0;29
setInterval(() => { frame++; context.fillStyle = 'hsl(' + (frame * 3 % 360) + ',70%,40%)'; context.fillRect(0, 0, width, height);30
context.fillStyle = '#fff'; context.font = '48px sans-serif'; context.fillText(label + ' ' + frame, 40, height / 2); }, 66);31
return canvas.captureStream(15).getVideoTracks()[0];32
};33
let audioContext;34
const speechTrack = async () => {35
audioContext = audioContext || new AudioContext();36
const destination = audioContext.createMediaStreamDestination();37
try {38
const data = await (await fetch('${speechUrl}')).arrayBuffer();39
const buffer = await audioContext.decodeAudioData(data);40
const source = audioContext.createBufferSource(); source.buffer = buffer; source.loop = true; source.connect(destination); source.start();41
} catch (error) {42
const oscillator = audioContext.createOscillator(); oscillator.frequency.value = 440; oscillator.connect(destination); oscillator.start();43
}44
return destination.stream.getAudioTracks()[0];45
};46
const devices = [47
{ deviceId: 'matrix-mic', kind: 'audioinput', label: 'Matrix mic', groupId: 'matrix' },48
{ deviceId: 'matrix-cam', kind: 'videoinput', label: 'Matrix camera', groupId: 'matrix' },49
{ deviceId: 'matrix-speaker', kind: 'audiooutput', label: 'Matrix speaker', groupId: 'matrix' },50
].map((device) => ({ ...device, toJSON() { return device; } }));51
navigator.mediaDevices.enumerateDevices = async () => devices;52
navigator.mediaDevices.getUserMedia = async (constraints) => {53
const tracks = [];54
if (constraints && constraints.audio) tracks.push(await speechTrack());55
if (constraints && constraints.video) tracks.push(canvasTrack('camera', 640, 360));56
return new MediaStream(tracks);57
};58
navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);59
navigator.mediaDevices.__matrix = true;60
})();`;61
62
const PEER_STATS = `(async () => {63
const report = { peers: 0, audioIn: [], videoIn: [], audioOut: [], videoOut: [] };64
for (const peer of window.__pcs || []) {65
if (peer.connectionState === 'closed') continue;66
report.peers++;67
(await peer.getStats()).forEach((entry) => {68
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });69
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });70
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });71
});72
}73
return report;74
})()`;75
76
class Browser {77
constructor(endpoint) { this.endpoint = endpoint; this.nextId = 1; this.pending = new Map(); this.listeners = []; }78
async connect() {79
const version = await (await fetch(this.endpoint + '/json/version')).json();80
this.socket = new WebSocket(version.webSocketDebuggerUrl);81
await new Promise((resolve, reject) => { this.socket.onopen = resolve; this.socket.onerror = reject; });82
this.socket.onmessage = (message) => {83
const data = JSON.parse(message.data);84
if (data.id && this.pending.has(data.id)) {85
const { resolve, reject } = this.pending.get(data.id); this.pending.delete(data.id);86
data.error ? reject(new Error(data.error.message)) : resolve(data.result);87
} else if (data.method) this.listeners.forEach((listener) => listener(data));88
};89
return this;90
}91
send(method, params = {}, sessionId) {92
const id = this.nextId++;93
this.socket.send(JSON.stringify({ id, method, params, sessionId }));94
return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); setTimeout(() => { if (this.pending.delete(id)) reject(new Error(method + ' timed out')); }, 60000); });95
}96
}97
98
const guests = new Map();13
const guests = new Map();99
const events = [];14
const events = [];100
let child;15
let child;@@ -154,18 +69,6 @@ async function evaluate(guest, expression) {154
return result.result.value;69
return result.result.value;155
}70
}156
71
157
const CLICK = (text) => `(() => {158
const wanted = ${JSON.stringify(text)}.toLowerCase();159
const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=tab], a, [role=option]')];160
const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();161
const visible = nodes.filter((node) => node.offsetParent !== null || node.getClientRects().length);162
const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);163
const target = exact || visible.find((node) => label(node).includes(wanted));164
if (!target) return { clicked: false, candidates: visible.map(label).filter(Boolean).slice(0, 60) };165
target.scrollIntoView({ block: 'center' }); target.click();166
return { clicked: true, label: label(target).slice(0, 80) };167
})()`;168
169
async function openGuest({ name, own = false, url }) {72
async function openGuest({ name, own = false, url }) {170
const browser = own ? ownBrowser : guestBrowser;73
const browser = own ? ownBrowser : guestBrowser;171
let browserContextId;74
let browserContextId;@@ -0,0 +1,99 @@
1
// Teams web over the Chrome DevTools Protocol: peer connection hook, fake media, stats and click helpers.
2
3
export const PEER_HOOK = `(() => {
4
const Original = window.RTCPeerConnection;
5
if (!Original || Original.__matrix) return;
6
window.__pcs = [];
7
const Wrapped = function (...args) { const peer = new Original(...args); window.__pcs.push(peer); return peer; };
8
Wrapped.prototype = Original.prototype;
9
Object.setPrototypeOf(Wrapped, Original);
10
Wrapped.__matrix = true;
11
window.RTCPeerConnection = Wrapped;
12
})();`;
13
14
// Signed-in Chrome has no fake devices: camera = moving canvas, mic = looped speech file, screen = canvas.
15
export const FAKE_MEDIA = (speechUrl) => `(() => {
16
if (!navigator.mediaDevices || navigator.mediaDevices.__matrix) return;
17
const canvasTrack = (label, width, height) => {
18
const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height;
19
const context = canvas.getContext('2d'); let frame = 0;
20
setInterval(() => { frame++; context.fillStyle = 'hsl(' + (frame * 3 % 360) + ',70%,40%)'; context.fillRect(0, 0, width, height);
21
context.fillStyle = '#fff'; context.font = '48px sans-serif'; context.fillText(label + ' ' + frame, 40, height / 2); }, 66);
22
return canvas.captureStream(15).getVideoTracks()[0];
23
};
24
let audioContext;
25
const speechTrack = async () => {
26
audioContext = audioContext || new AudioContext();
27
const destination = audioContext.createMediaStreamDestination();
28
try {
29
const data = await (await fetch('${speechUrl}')).arrayBuffer();
30
const buffer = await audioContext.decodeAudioData(data);
31
const source = audioContext.createBufferSource(); source.buffer = buffer; source.loop = true; source.connect(destination); source.start();
32
} catch (error) {
33
const oscillator = audioContext.createOscillator(); oscillator.frequency.value = 440; oscillator.connect(destination); oscillator.start();
34
}
35
return destination.stream.getAudioTracks()[0];
36
};
37
const devices = [
38
{ deviceId: 'matrix-mic', kind: 'audioinput', label: 'Matrix mic', groupId: 'matrix' },
39
{ deviceId: 'matrix-cam', kind: 'videoinput', label: 'Matrix camera', groupId: 'matrix' },
40
{ deviceId: 'matrix-speaker', kind: 'audiooutput', label: 'Matrix speaker', groupId: 'matrix' },
41
].map((device) => ({ ...device, toJSON() { return device; } }));
42
navigator.mediaDevices.enumerateDevices = async () => devices;
43
navigator.mediaDevices.getUserMedia = async (constraints) => {
44
const tracks = [];
45
if (constraints && constraints.audio) tracks.push(await speechTrack());
46
if (constraints && constraints.video) tracks.push(canvasTrack('camera', 640, 360));
47
return new MediaStream(tracks);
48
};
49
navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);
50
navigator.mediaDevices.__matrix = true;
51
})();`;
52
53
export const PEER_STATS = `(async () => {
54
const report = { peers: 0, audioIn: [], videoIn: [], audioOut: [], videoOut: [] };
55
for (const peer of window.__pcs || []) {
56
if (peer.connectionState === 'closed') continue;
57
report.peers++;
58
(await peer.getStats()).forEach((entry) => {
59
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });
60
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });
61
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });
62
});
63
}
64
return report;
65
})()`;
66
67
export const CLICK = (text) => `(() => {
68
const wanted = ${JSON.stringify(text)}.toLowerCase();
69
const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=tab], a, [role=option]')];
70
const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();
71
const visible = nodes.filter((node) => node.offsetParent !== null || node.getClientRects().length);
72
const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);
73
const target = exact || visible.find((node) => label(node).includes(wanted));
74
if (!target) return { clicked: false, candidates: visible.map(label).filter(Boolean).slice(0, 60) };
75
target.scrollIntoView({ block: 'center' }); target.click();
76
return { clicked: true, label: label(target).slice(0, 80) };
77
})()`;
78
79
export class Browser {
80
constructor(endpoint) { this.endpoint = endpoint; this.nextId = 1; this.pending = new Map(); this.listeners = []; }
81
async connect() {
82
const version = await (await fetch(this.endpoint + '/json/version')).json();
83
this.socket = new WebSocket(version.webSocketDebuggerUrl);
84
await new Promise((resolve, reject) => { this.socket.onopen = resolve; this.socket.onerror = reject; });
85
this.socket.onmessage = (message) => {
86
const data = JSON.parse(message.data);
87
if (data.id && this.pending.has(data.id)) {
88
const { resolve, reject } = this.pending.get(data.id); this.pending.delete(data.id);
89
data.error ? reject(new Error(data.error.message)) : resolve(data.result);
90
} else if (data.method) this.listeners.forEach((listener) => listener(data));
91
};
92
return this;
93
}
94
send(method, params = {}, sessionId) {
95
const id = this.nextId++;
96
this.socket.send(JSON.stringify({ id, method, params, sessionId }));
97
return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); setTimeout(() => { if (this.pending.delete(id)) reject(new Error(method + ' timed out')); }, 60000); });
98
}
99
}
@@ -0,0 +1,99 @@1
// Teams web over the Chrome DevTools Protocol: peer connection hook, fake media, stats and click helpers.2
3
export const PEER_HOOK = `(() => {4
const Original = window.RTCPeerConnection;5
if (!Original || Original.__matrix) return;6
window.__pcs = [];7
const Wrapped = function (...args) { const peer = new Original(...args); window.__pcs.push(peer); return peer; };8
Wrapped.prototype = Original.prototype;9
Object.setPrototypeOf(Wrapped, Original);10
Wrapped.__matrix = true;11
window.RTCPeerConnection = Wrapped;12
})();`;13
14
// Signed-in Chrome has no fake devices: camera = moving canvas, mic = looped speech file, screen = canvas.15
export const FAKE_MEDIA = (speechUrl) => `(() => {16
if (!navigator.mediaDevices || navigator.mediaDevices.__matrix) return;17
const canvasTrack = (label, width, height) => {18
const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height;19
const context = canvas.getContext('2d'); let frame = 0;20
setInterval(() => { frame++; context.fillStyle = 'hsl(' + (frame * 3 % 360) + ',70%,40%)'; context.fillRect(0, 0, width, height);21
context.fillStyle = '#fff'; context.font = '48px sans-serif'; context.fillText(label + ' ' + frame, 40, height / 2); }, 66);22
return canvas.captureStream(15).getVideoTracks()[0];23
};24
let audioContext;25
const speechTrack = async () => {26
audioContext = audioContext || new AudioContext();27
const destination = audioContext.createMediaStreamDestination();28
try {29
const data = await (await fetch('${speechUrl}')).arrayBuffer();30
const buffer = await audioContext.decodeAudioData(data);31
const source = audioContext.createBufferSource(); source.buffer = buffer; source.loop = true; source.connect(destination); source.start();32
} catch (error) {33
const oscillator = audioContext.createOscillator(); oscillator.frequency.value = 440; oscillator.connect(destination); oscillator.start();34
}35
return destination.stream.getAudioTracks()[0];36
};37
const devices = [38
{ deviceId: 'matrix-mic', kind: 'audioinput', label: 'Matrix mic', groupId: 'matrix' },39
{ deviceId: 'matrix-cam', kind: 'videoinput', label: 'Matrix camera', groupId: 'matrix' },40
{ deviceId: 'matrix-speaker', kind: 'audiooutput', label: 'Matrix speaker', groupId: 'matrix' },41
].map((device) => ({ ...device, toJSON() { return device; } }));42
navigator.mediaDevices.enumerateDevices = async () => devices;43
navigator.mediaDevices.getUserMedia = async (constraints) => {44
const tracks = [];45
if (constraints && constraints.audio) tracks.push(await speechTrack());46
if (constraints && constraints.video) tracks.push(canvasTrack('camera', 640, 360));47
return new MediaStream(tracks);48
};49
navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);50
navigator.mediaDevices.__matrix = true;51
})();`;52
53
export const PEER_STATS = `(async () => {54
const report = { peers: 0, audioIn: [], videoIn: [], audioOut: [], videoOut: [] };55
for (const peer of window.__pcs || []) {56
if (peer.connectionState === 'closed') continue;57
report.peers++;58
(await peer.getStats()).forEach((entry) => {59
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });60
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });61
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });62
});63
}64
return report;65
})()`;66
67
export const CLICK = (text) => `(() => {68
const wanted = ${JSON.stringify(text)}.toLowerCase();69
const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=tab], a, [role=option]')];70
const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();71
const visible = nodes.filter((node) => node.offsetParent !== null || node.getClientRects().length);72
const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);73
const target = exact || visible.find((node) => label(node).includes(wanted));74
if (!target) return { clicked: false, candidates: visible.map(label).filter(Boolean).slice(0, 60) };75
target.scrollIntoView({ block: 'center' }); target.click();76
return { clicked: true, label: label(target).slice(0, 80) };77
})()`;78
79
export class Browser {80
constructor(endpoint) { this.endpoint = endpoint; this.nextId = 1; this.pending = new Map(); this.listeners = []; }81
async connect() {82
const version = await (await fetch(this.endpoint + '/json/version')).json();83
this.socket = new WebSocket(version.webSocketDebuggerUrl);84
await new Promise((resolve, reject) => { this.socket.onopen = resolve; this.socket.onerror = reject; });85
this.socket.onmessage = (message) => {86
const data = JSON.parse(message.data);87
if (data.id && this.pending.has(data.id)) {88
const { resolve, reject } = this.pending.get(data.id); this.pending.delete(data.id);89
data.error ? reject(new Error(data.error.message)) : resolve(data.result);90
} else if (data.method) this.listeners.forEach((listener) => listener(data));91
};92
return this;93
}94
send(method, params = {}, sessionId) {95
const id = this.nextId++;96
this.socket.send(JSON.stringify({ id, method, params, sessionId }));97
return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); setTimeout(() => { if (this.pending.delete(id)) reject(new Error(method + ' timed out')); }, 60000); });98
}99
}