use core::ffi::c_void;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use firewheel::cpal::cpal::DeviceId;
use firewheel::cpal::CpalEnumerator;
use super::events;
use super::util::*;
use crate::glue;
pub const DEFAULT_SINK: &str = "default";
const POLL_INTERVAL: Duration = Duration::from_millis(2000);
const SETTLE: Duration = Duration::from_millis(150);
const LISTEN_CHECK: Duration = Duration::from_millis(250);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Flow {
Output,
Input,
}
static HOST_NOTIFIES: AtomicBool = AtomicBool::new(false);
static CHANGES: AtomicU64 = AtomicU64::new(0);
static DEFAULT_OUTPUT: AtomicU64 = AtomicU64::new(0);
static DEFAULT_INPUT: AtomicU64 = AtomicU64::new(0);
pub fn set_host_notifications() {
HOST_NOTIFIES.store(true, Ordering::Release);
}
pub fn notify_devices_changed() {
CHANGES.fetch_add(1, Ordering::AcqRel);
crate::web::notify_embedder();
}
pub fn notify_default_changed(flow: Flow) {
match flow {
Flow::Output => DEFAULT_OUTPUT.fetch_add(1, Ordering::AcqRel),
Flow::Input => DEFAULT_INPUT.fetch_add(1, Ordering::AcqRel),
};
notify_devices_changed();
}
pub fn default_generation(flow: Flow) -> u64 {
match flow {
Flow::Output => DEFAULT_OUTPUT.load(Ordering::Acquire),
Flow::Input => DEFAULT_INPUT.load(Ordering::Acquire),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioDevice {
pub id: String,
pub label: String,
pub is_default: bool,
}
pub fn input_devices() -> Vec<AudioDevice> {
CpalEnumerator
.default_host()
.input_devices()
.into_iter()
.map(|d| AudioDevice {
id: format!("{}", d.id),
label: d.name.unwrap_or_else(|| String::from("Unknown input device")),
is_default: d.is_default,
})
.collect()
}
fn fake_inputs() -> Vec<AudioDevice> {
use super::mediastream::fake::{DEVICE_ID, LABEL};
vec![AudioDevice { id: DEVICE_ID.to_string(), label: LABEL.to_string(), is_default: true }]
}
pub fn output_devices() -> Vec<AudioDevice> {
let enumerator = CpalEnumerator;
let host = enumerator.default_host();
host.output_devices()
.into_iter()
.map(|d| AudioDevice {
id: format!("{}", d.id),
label: d.name.unwrap_or_else(|| String::from("Unknown output device")),
is_default: d.is_default,
})
.collect()
}
pub fn resolve_output(sink_id: &str) -> Result<Option<DeviceId>, ()> {
if sink_id.is_empty() || sink_id == DEFAULT_SINK {
return Ok(None);
}
if !output_devices().iter().any(|d| d.id == sink_id) {
return Err(());
}
DeviceId::from_str(sink_id).map(Some).map_err(|_| ())
}
fn devices_changed(prev: &[(String, bool)], next: &[(String, bool)]) -> bool {
prev != next
}
fn snapshot_of(devices: &[AudioDevice]) -> Vec<(String, bool)> {
devices.iter().map(|d| (d.id.clone(), d.is_default)).collect()
}
fn snapshot_now() -> Vec<(String, bool)> {
let mut s = snapshot_of(&output_devices());
let inputs = if super::mediastream::fake_capture() { fake_inputs() } else { input_devices() };
s.extend(inputs.into_iter().map(|d| (format!("in:{}", d.id), d.is_default)));
s
}
struct MdClasses {
info: Class,
input: Class,
s_md: *mut c_void,
}
unsafe impl Send for MdClasses {}
unsafe impl Sync for MdClasses {}
fn classes_reg() -> &'static Mutex<HashMap<usize, &'static MdClasses>> {
static R: OnceLock<Mutex<HashMap<usize, &'static MdClasses>>> = OnceLock::new();
R.get_or_init(|| Mutex::new(HashMap::new()))
}
fn classes(g: *mut c_void) -> &'static MdClasses {
classes_reg().lock().unwrap().get(&(g as usize)).copied().expect("webapi::mediadevices not installed")
}
struct PollState {
obj: u64,
snapshot: Vec<(String, bool)>,
armed: bool,
last_poll: Instant,
seen: u64,
moved_at: Option<Instant>,
}
impl PollState {
fn new(obj: u64) -> PollState {
PollState {
obj,
snapshot: Vec::new(),
armed: false,
last_poll: Instant::now(),
seen: CHANGES.load(Ordering::Acquire),
moved_at: None,
}
}
fn step(
&mut self,
now: Instant,
host: bool,
changes: u64,
listening: impl FnOnce() -> bool,
read: impl FnOnce() -> Vec<(String, bool)>,
) -> bool {
if !host {
if now.duration_since(self.last_poll) < POLL_INTERVAL {
return false;
}
self.last_poll = now;
if !listening() {
self.armed = false;
self.snapshot.clear();
return false;
}
let next = read();
let fire = self.armed && devices_changed(&self.snapshot, &next);
self.snapshot = next;
self.armed = true;
return fire;
}
if changes != self.seen {
self.seen = changes;
self.moved_at = Some(now);
}
if let Some(at) = self.moved_at {
if now.duration_since(at) >= SETTLE {
self.moved_at = None;
if self.armed {
let next = read();
let fire = devices_changed(&self.snapshot, &next);
self.snapshot = next;
return fire;
}
}
}
if now.duration_since(self.last_poll) >= LISTEN_CHECK {
self.last_poll = now;
match (listening(), self.armed) {
(true, false) => {
self.snapshot = read();
self.armed = true;
}
(false, true) => {
self.armed = false;
self.snapshot.clear();
}
_ => {}
}
}
false
}
fn next_due(&self, host: bool) -> Option<Instant> {
if host {
return self.moved_at.map(|at| at + SETTLE);
}
self.armed.then(|| self.last_poll + POLL_INTERVAL)
}
}
pub(crate) fn next_poll_ms(g: *mut c_void) -> Option<f64> {
let host = HOST_NOTIFIES.load(Ordering::Acquire);
let due = polls().lock().unwrap().get(&(g as usize))?.next_due(host)?;
let now = Instant::now();
Some(crate::web::now_ms() + due.saturating_duration_since(now).as_secs_f64() * 1000.0)
}
fn polls() -> &'static Mutex<HashMap<usize, PollState>> {
static P: OnceLock<Mutex<HashMap<usize, PollState>>> = OnceLock::new();
P.get_or_init(|| Mutex::new(HashMap::new()))
}
pub(crate) fn forget(gone: crate::context::Gone) {
classes_reg().lock().unwrap().remove(&gone.key);
polls().lock().unwrap().remove(&gone.key);
}
unsafe fn info_slots(g: *mut c_void, obj: u64) -> u64 {
get_a(g, obj, classes(g).s_md)
}
unsafe fn new_device_info(g: *mut c_void, kind: &str, device_id: &str, label: &str) -> u64 {
let c = classes(g);
let proto = if kind == "audioinput" || kind == "videoinput" { c.input.proto } else { c.info.proto };
let obj = new_object(g, proto);
let slots = new_object(g, UNDEF);
define(g, slots, "deviceId", js_string(g, device_id), 0);
define(g, slots, "kind", js_string(g, kind), 0);
define(g, slots, "label", js_string(g, label), 0);
define(g, slots, "groupId", js_string(g, ""), 0);
glue::rjs_define(g, obj, c.s_md, slots, 0);
obj
}
macro_rules! info_getter {
($fn_name:ident, $slot:literal) => {
#[crate::host_fn]
unsafe fn $fn_name(g: *mut c_void, cf: *mut c_void) -> u64 {
let slots = info_slots(g, cf_this(cf));
if !is_cell(slots) {
return throw_type_error(g, concat!("MediaDeviceInfo.", $slot, " on wrong this"));
}
get(g, slots, $slot)
}
};
}
info_getter!(info_get_device_id, "deviceId");
info_getter!(info_get_kind, "kind");
info_getter!(info_get_label, "label");
info_getter!(info_get_group_id, "groupId");
#[crate::host_fn]
unsafe fn info_to_json(g: *mut c_void, cf: *mut c_void) -> u64 {
let slots = info_slots(g, cf_this(cf));
if !is_cell(slots) {
return throw_type_error(g, "MediaDeviceInfo.toJSON on wrong this");
}
let out = new_object(g, UNDEF);
for key in ["deviceId", "kind", "label", "groupId"] {
define(g, out, key, get(g, slots, key), 0);
}
out
}
#[crate::host_fn]
unsafe fn input_get_capabilities(g: *mut c_void, cf: *mut c_void) -> u64 {
let this = cf_this(cf);
let slots = info_slots(g, this);
if !is_cell(slots) || !proto_chain_has(g, this, classes(g).input.proto) {
return throw_type_error(g, "InputDeviceInfo.getCapabilities on wrong this");
}
let out = new_object(g, UNDEF);
let id = read_string(g, get(g, slots, "deviceId")).unwrap_or_default();
if id.is_empty() {
return out;
}
define(g, out, "deviceId", js_string(g, &id), 0);
define(g, out, "groupId", get(g, slots, "groupId"), 0);
let Some((rate, channels)) = super::mediastream::input_format(g as usize, &id) else {
return out;
};
let range = |name: &str, min: f64, max: f64| {
let r = new_object(g, UNDEF);
define(g, r, "min", enc_f64(min), 0);
define(g, r, "max", enc_f64(max), 0);
define(g, out, name, r, 0);
};
range("sampleRate", rate as f64, rate as f64);
range("sampleSize", 16.0, 16.0);
range("channelCount", 1.0, channels as f64);
range("latency", 0.01, 0.01);
let can = super::mediastream::capture_processing_available();
for name in ["echoCancellation", "noiseSuppression", "autoGainControl"] {
let a = new_array(g);
if can {
set_i(g, a, 0, TRUE);
set_i(g, a, 1, FALSE);
} else {
set_i(g, a, 0, FALSE);
}
define(g, out, name, a, 0);
}
out
}
unsafe fn push_kind(g: *mut c_void, arr: u64, i: &mut u32, kind: &str, devices: &[AudioDevice]) {
let default_label = devices
.iter()
.find(|d| d.is_default)
.map(|d| format!("Default - {}", d.label))
.unwrap_or_else(|| String::from("Default"));
set_i(g, arr, *i, new_device_info(g, kind, DEFAULT_SINK, &default_label));
*i += 1;
for d in devices {
if d.id == DEFAULT_SINK {
continue;
}
set_i(g, arr, *i, new_device_info(g, kind, &d.id, &d.label));
*i += 1;
}
}
#[crate::host_fn]
unsafe fn md_enumerate_devices(g: *mut c_void, _cf: *mut c_void) -> u64 {
let arr = new_array(g);
let mut i = 0u32;
let inputs = if super::mediastream::fake::enabled(g as usize) {
fake_inputs()
} else {
input_devices()
};
if !inputs.is_empty() {
if super::mediastream::inputs_visible(g as usize) {
push_kind(g, arr, &mut i, "audioinput", &inputs);
} else {
set_i(g, arr, i, new_device_info(g, "audioinput", "", ""));
i += 1;
}
}
push_kind(g, arr, &mut i, "audiooutput", &output_devices());
resolved_promise(g, arr)
}
#[crate::host_fn]
unsafe fn md_get_user_media(g: *mut c_void, _cf: *mut c_void) -> u64 {
super::domexception::rejected(
g,
"NotSupportedError",
"navigator.mediaDevices.getUserMedia is unavailable: the MediaStream surface \
(redjs/mediastream.js) failed to install. See the log for its error.",
)
}
unsafe fn has_device_change_listener(g: *mut c_void, obj: u64) -> bool {
let st = state(g);
let list = get_a(g, obj, st.s_listeners);
if is_cell(list) {
let n = array_len(g, list);
for i in 0..n {
let e = get_i(g, list, i);
if read_string(g, get_a(g, e, st.a_type)).as_deref() == Some("devicechange") {
return true;
}
}
}
let handler = get(g, obj, "ondevicechange");
is_cell(handler) && glue::rjs_kind(g, handler) == 9
}
pub unsafe fn pump(g: *mut c_void) {
let host = HOST_NOTIFIES.load(Ordering::Acquire);
let changes = CHANGES.load(Ordering::Acquire);
let Some(mut p) = polls().lock().unwrap().remove(&(g as usize)) else {
return;
};
let obj = p.obj;
let fire = p.step(Instant::now(), host, changes, || has_device_change_listener(g, obj), snapshot_now);
polls().lock().unwrap().insert(g as usize, p);
if fire {
let ev = events::new_trusted_event(g, "devicechange");
events::dispatch(g, obj, ev);
}
}
pub unsafe fn install(g: *mut c_void, event_target_proto: u64) {
let s_md = atom_priv(g, "redjs#mediaDevices");
let info = define_class(g, &ClassSpec {
name: "MediaDeviceInfo",
arity: 0,
construct: None,
parent_proto: 0,
methods: &[("toJSON", 0, info_to_json)],
getters: &[
("deviceId", info_get_device_id),
("kind", info_get_kind),
("label", info_get_label),
("groupId", info_get_group_id),
],
accessors: &[],
});
let input = define_class(g, &ClassSpec {
name: "InputDeviceInfo",
arity: 0,
construct: None,
parent_proto: info.proto,
methods: &[("getCapabilities", 0, input_get_capabilities)],
getters: &[],
accessors: &[],
});
crate::capi::JSObjectSetPrototype(g, input.ctor as usize as crate::capi::JSObjectRef, info.ctor as usize as crate::capi::JSValueRef);
let md_class = define_class(g, &ClassSpec {
name: "MediaDevices",
arity: 0,
construct: None,
parent_proto: event_target_proto,
methods: &[
("enumerateDevices", 0, md_enumerate_devices),
("getUserMedia", 1, md_get_user_media),
],
getters: &[],
accessors: &[],
});
let boxed: &'static MdClasses = Box::leak(Box::new(MdClasses { info, input, s_md }));
classes_reg().lock().unwrap().insert(g as usize, boxed);
let md = new_object(g, md_class.proto);
crate::ffi::redjs_protect(g, md);
let global = glue::rjs_global(g);
let existing = get(g, global, "navigator");
let navigator = if is_cell(existing) {
existing
} else {
let n = new_object(g, UNDEF);
define(g, global, "navigator", n, 2 );
n
};
define(g, navigator, "mediaDevices", md, 2);
polls().lock().unwrap().insert(g as usize, PollState::new(md));
}
#[cfg(test)]
pub(crate) const FAKE_CAPABILITIES: &str = concat!(
r#"{"deviceId":"default","groupId":"","sampleRate":{"min":48000,"max":48000},"#,
r#""sampleSize":{"min":16,"max":16},"channelCount":{"min":1,"max":1},"latency":{"min":0.01,"max":0.01},"#,
r#""echoCancellation":[false],"noiseSuppression":[false],"autoGainControl":[false]}"#
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_sentinels_resolve_to_the_system_default() {
assert_eq!(resolve_output(""), Ok(None));
assert_eq!(resolve_output(DEFAULT_SINK), Ok(None));
}
#[test]
fn an_unknown_id_is_refused_rather_than_silently_defaulted() {
assert_eq!(resolve_output("not-a-device"), Err(()));
assert_eq!(resolve_output("wasapi:{00000000-0000-0000-0000-000000000000}"), Err(()));
}
#[test]
fn every_enumerated_id_can_be_selected_again() {
for d in output_devices() {
assert!(!d.id.is_empty(), "an enumerated device has an empty id: {d:?}");
assert!(
matches!(resolve_output(&d.id), Ok(Some(_))),
"enumerated id does not resolve back: {d:?}",
);
}
}
#[test]
fn enumerated_ids_are_unique() {
let devices = output_devices();
let mut ids: Vec<&str> = devices.iter().map(|d| d.id.as_str()).collect();
ids.sort_unstable();
let before = ids.len();
ids.dedup();
assert_eq!(before, ids.len(), "duplicate device ids in {devices:?}");
}
#[test]
fn the_change_detector_sees_adds_removals_and_a_new_default() {
let a = vec![("a".to_string(), true), ("b".to_string(), false)];
assert!(!devices_changed(&a, &a.clone()), "an unchanged list must not fire");
let added = vec![("a".to_string(), true), ("b".to_string(), false), ("c".to_string(), false)];
assert!(devices_changed(&a, &added), "a plugged-in device must fire");
let removed = vec![("a".to_string(), true)];
assert!(devices_changed(&a, &removed), "an unplugged device must fire");
let redefaulted = vec![("a".to_string(), false), ("b".to_string(), true)];
assert!(devices_changed(&a, &redefaulted), "a new system default must fire");
}
fn list(ids: &[(&str, bool)]) -> Vec<(String, bool)> {
ids.iter().map(|(id, d)| (id.to_string(), *d)).collect()
}
struct Rig {
p: PollState,
t: Instant,
host: bool,
changes: u64,
listening: bool,
devices: Vec<(String, bool)>,
reads: usize,
}
impl Rig {
fn new(host: bool) -> Rig {
let t = Instant::now();
let mut p = PollState::new(0);
p.seen = 0;
p.last_poll = t;
Rig { p, t, host, changes: 0, listening: true, devices: list(&[("a", true)]), reads: 0 }
}
fn at(&mut self, ms: u64) -> bool {
self.t += Duration::from_millis(ms);
let reads = &mut self.reads;
let devices = self.devices.clone();
let listening = self.listening;
self.p.step(self.t, self.host, self.changes, || listening, || {
*reads += 1;
devices
})
}
fn run(&mut self, ms: u64) -> usize {
(0..ms / 16).filter(|_| self.at(16)).count()
}
}
#[test]
fn with_host_notifications_the_devices_are_read_only_after_a_change() {
let mut r = Rig::new(true);
assert_eq!(r.run(300), 0);
assert_eq!(r.reads, 1, "the baseline");
assert_eq!(r.run(10_000), 0);
assert_eq!(r.reads, 1, "no change, no read");
r.devices = list(&[("a", false), ("h", true)]);
for _ in 0..5 {
r.changes += 1;
assert!(!r.at(20));
}
assert_eq!(r.reads, 1, "nothing is read while the burst goes on");
assert_eq!(r.run(300), 1);
assert_eq!(r.reads, 2);
}
#[test]
fn a_notified_change_that_leaves_the_list_as_it_was_fires_nothing() {
let mut r = Rig::new(true);
r.run(300);
r.changes += 1;
assert_eq!(r.run(300), 0);
assert_eq!(r.reads, 2, "read once, and found the same list");
}
#[test]
fn without_a_listener_a_change_is_not_read() {
let mut r = Rig::new(true);
r.listening = false;
r.changes += 3;
r.devices = list(&[("b", true)]);
assert_eq!(r.run(1_000), 0);
assert_eq!(r.reads, 0);
r.listening = true;
assert_eq!(r.run(300), 0);
assert_eq!(r.reads, 1);
}
#[test]
fn without_host_notifications_the_poll_runs_every_two_seconds() {
let mut r = Rig::new(false);
assert_eq!(r.run(1_900), 0);
assert_eq!(r.reads, 0);
assert_eq!(r.run(200), 0);
assert_eq!(r.reads, 1, "the first poll is the baseline");
r.devices = list(&[("a", true), ("b", false)]);
assert_eq!(r.run(2_100), 1);
assert_eq!(r.reads, 2);
}
#[test]
fn a_default_change_moves_its_flows_generation_and_counts_as_a_change() {
let (out0, in0, ch0) =
(default_generation(Flow::Output), default_generation(Flow::Input), CHANGES.load(Ordering::Acquire));
notify_default_changed(Flow::Input);
assert_eq!(default_generation(Flow::Input), in0 + 1);
assert_eq!(default_generation(Flow::Output), out0, "only the input moved");
assert!(CHANGES.load(Ordering::Acquire) > ch0, "devicechange fires for it too");
}
}
#[cfg(test)]
mod jsc_tests {
use crate::api::Context;
use crate::webapi::testing::*;
fn run(c: &Context, body: &str) -> String {
s(
c,
&format!(
"globalThis.__out = '<pending>'; (async () => {{ {body} }})().then(\
v => {{ globalThis.__out = String(v); }}, \
e => {{ globalThis.__out = 'ERROR: ' + \
(e instanceof DOMException ? 'DOMException ' + e.name + ': ' : '') + \
((e && e.message) || e); }}); 'started'"
),
);
for _ in 0..64 {
c.drain_microtasks();
}
s(c, "globalThis.__out")
}
#[test]
fn media_devices_is_a_singleton_event_target() {
let c = ctx();
ok(&c, "navigator.mediaDevices === navigator.mediaDevices");
ok(&c, "navigator.mediaDevices instanceof MediaDevices");
ok(&c, "typeof navigator.mediaDevices.addEventListener === 'function'");
ok(&c, "typeof navigator.mediaDevices.removeEventListener === 'function'");
}
#[test]
fn both_listener_shapes_receive_a_device_change() {
let c = ctx();
ok(
&c,
"let n = 0;
navigator.mediaDevices.addEventListener('devicechange', () => { n++; });
navigator.mediaDevices.ondevicechange = () => { n += 10; };
navigator.mediaDevices.dispatchEvent(new Event('devicechange'));
n === 11",
);
}
#[test]
fn the_outputs_are_listed_with_a_default_first() {
let c = ctx();
assert_eq!(
run(
&c,
"const ds = (await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'audiooutput');
if (ds.length < 1) return 'empty list';
if (ds[0].deviceId !== 'default') return 'first is ' + ds[0].deviceId;
const ids = new Set();
for (const d of ds) {
if (!(d instanceof MediaDeviceInfo)) return 'not a MediaDeviceInfo';
if (typeof d.deviceId !== 'string' || !d.deviceId) return 'bad deviceId';
if (typeof d.label !== 'string' || !d.label) return 'bad label';
if (typeof d.groupId !== 'string') return 'bad groupId';
if (d.toJSON().deviceId !== d.deviceId) return 'toJSON mismatch';
if (ids.has(d.deviceId)) return 'duplicate id ' + d.deviceId;
ids.add(d.deviceId);
}
return 'ok';"
),
"ok"
);
}
#[test]
fn the_input_boundary_is_pinned() {
let c = ctx();
assert_eq!(
run(
&c,
"const ds = await navigator.mediaDevices.enumerateDevices();
const kinds = new Set(ds.map(d => d.kind));
for (const k of kinds) if (k !== 'audioinput' && k !== 'audiooutput') return 'kind ' + k;
const ins = ds.filter(d => d.kind === 'audioinput');
if (ins.length > 1) return 'named inputs while closed: ' + ins.length;
if (ins.length && (ins[0].deviceId !== '' || ins[0].label !== '')) return 'an input is named';
if (ins.length && ds.indexOf(ins[0]) !== 0) return 'inputs are not first';
return 'ok';"
),
"ok"
);
let got = run(&c, "await navigator.mediaDevices.getUserMedia({ audio: true }); return 'resolved';");
assert!(got.contains("DOMException NotAllowedError"), "{got}");
assert!(got.contains("has not enabled microphone capture"), "getUserMedia must say why: {got}");
}
#[test]
fn every_enumerated_input_id_is_unique_and_non_empty() {
let devices = super::input_devices();
let mut ids: Vec<&str> = devices.iter().map(|d| d.id.as_str()).collect();
assert!(ids.iter().all(|i| !i.is_empty()), "{devices:?}");
ids.sort_unstable();
let before = ids.len();
ids.dedup();
assert_eq!(before, ids.len(), "duplicate input ids in {devices:?}");
}
#[test]
fn an_input_entry_is_an_input_device_info_with_capabilities() {
let c = ctx();
ok(&c, "Object.getPrototypeOf(InputDeviceInfo) === MediaDeviceInfo && InputDeviceInfo.prototype instanceof MediaDeviceInfo");
ok(&c, "Object.prototype.toString.call(InputDeviceInfo.prototype) === '[object InputDeviceInfo]'");
assert!(throws(&c, "new InputDeviceInfo()").contains("Illegal constructor"));
unsafe {
let g = c.raw();
crate::glue::rjs_lock(g);
for (name, kind, id) in [("anon", "audioinput", ""), ("mic", "audioinput", "default"), ("spk", "audiooutput", "default")] {
let d = super::new_device_info(g, kind, id, id);
crate::webapi::util::define(g, crate::glue::rjs_global(g), name, d, 0);
}
crate::glue::rjs_unlock(g);
}
ok(&c, "anon instanceof InputDeviceInfo && mic instanceof InputDeviceInfo && !(spk instanceof InputDeviceInfo) && spk instanceof MediaDeviceInfo");
ok(&c, "Object.prototype.toString.call(mic) === '[object InputDeviceInfo]' && Object.prototype.toString.call(spk) === '[object MediaDeviceInfo]'");
ok(&c, "mic.kind === 'audioinput' && mic.toJSON().deviceId === 'default'");
assert_eq!(s(&c, "JSON.stringify(anon.getCapabilities())"), "{}");
assert_eq!(s(&c, "JSON.stringify(mic.getCapabilities())"), r#"{"deviceId":"default","groupId":""}"#);
assert!(throws(&c, "InputDeviceInfo.prototype.getCapabilities.call(spk)").contains("wrong this"));
assert!(throws(&c, "InputDeviceInfo.prototype.getCapabilities.call({})").contains("wrong this"));
crate::webapi::mediastream::fake::enable(c.raw());
assert_eq!(s(&c, "JSON.stringify(mic.getCapabilities())"), super::FAKE_CAPABILITIES);
}
#[test]
fn media_device_info_is_not_constructible() {
let c = ctx();
let msg = throws(&c, "new MediaDeviceInfo()");
assert!(msg.contains("Illegal constructor"), "{msg}");
let msg = throws(&c, "new MediaDevices()");
assert!(msg.contains("Illegal constructor"), "{msg}");
}
#[test]
fn the_getters_refuse_a_foreign_this() {
let c = ctx();
let msg = throws(
&c,
"Object.getOwnPropertyDescriptor(MediaDeviceInfo.prototype, 'deviceId').get.call({})",
);
assert!(msg.contains("wrong this"), "{msg}");
}
}