script/dom/audio/
analysernode.rs1use dom_struct::dom_struct;
6use ipc_channel::ipc::{self, IpcReceiver};
7use ipc_channel::router::ROUTER;
8use js::context::JSContext;
9use js::rust::{CustomAutoRooterGuard, HandleObject};
10use js::typedarray::{Float32Array, Uint8Array};
11use script_bindings::cell::DomRefCell;
12use script_bindings::reflector::reflect_dom_object_with_proto_and_cx;
13use servo_media::audio::analyser_node::AnalysisEngine;
14use servo_media::audio::block::Block;
15use servo_media::audio::node::AudioNodeInit;
16
17use crate::dom::audio::audionode::{AudioNode, AudioNodeOptionsHelper};
18use crate::dom::audio::baseaudiocontext::BaseAudioContext;
19use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{
20 AnalyserNodeMethods, AnalyserOptions,
21};
22use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
23 ChannelCountMode, ChannelInterpretation,
24};
25use crate::dom::bindings::error::{Error, Fallible};
26use crate::dom::bindings::num::Finite;
27use crate::dom::bindings::refcounted::Trusted;
28use crate::dom::bindings::root::DomRoot;
29use crate::dom::window::Window;
30
31#[dom_struct]
32pub(crate) struct AnalyserNode {
33 node: AudioNode,
34 #[ignore_malloc_size_of = "Defined in servo-media"]
35 #[no_trace]
36 engine: DomRefCell<AnalysisEngine>,
37}
38
39impl AnalyserNode {
40 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
41 pub(crate) fn new_inherited(
42 cx: &mut JSContext,
43 _: &Window,
44 context: &BaseAudioContext,
45 options: &AnalyserOptions,
46 ) -> Fallible<(AnalyserNode, IpcReceiver<Block>)> {
47 let node_options =
48 options
49 .parent
50 .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
51
52 if options.fftSize > 32768 ||
53 options.fftSize < 32 ||
54 (options.fftSize & (options.fftSize - 1) != 0)
55 {
56 return Err(Error::IndexSize(None));
57 }
58
59 if *options.maxDecibels <= *options.minDecibels {
60 return Err(Error::IndexSize(None));
61 }
62
63 if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. {
64 return Err(Error::IndexSize(None));
65 }
66
67 let (send, rcv) = ipc::channel().unwrap();
68 let callback = move |block| {
69 send.send(block).unwrap();
70 };
71
72 let node = AudioNode::new_inherited(
73 cx,
74 AudioNodeInit::AnalyserNode(Box::new(callback)),
75 context,
76 node_options,
77 1, 1, )?;
80
81 let engine = AnalysisEngine::new(
82 options.fftSize as usize,
83 *options.smoothingTimeConstant,
84 *options.minDecibels,
85 *options.maxDecibels,
86 );
87 Ok((
88 AnalyserNode {
89 node,
90 engine: DomRefCell::new(engine),
91 },
92 rcv,
93 ))
94 }
95
96 pub(crate) fn new(
97 cx: &mut JSContext,
98 window: &Window,
99 context: &BaseAudioContext,
100 options: &AnalyserOptions,
101 ) -> Fallible<DomRoot<AnalyserNode>> {
102 Self::new_with_proto(cx, window, None, context, options)
103 }
104
105 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
106 pub(crate) fn new_with_proto(
107 cx: &mut JSContext,
108 window: &Window,
109 proto: Option<HandleObject>,
110 context: &BaseAudioContext,
111 options: &AnalyserOptions,
112 ) -> Fallible<DomRoot<AnalyserNode>> {
113 let (node, recv) = AnalyserNode::new_inherited(cx, window, context, options)?;
114 let object = reflect_dom_object_with_proto_and_cx(Box::new(node), window, proto, cx);
115 let task_source = window
116 .as_global_scope()
117 .task_manager()
118 .dom_manipulation_task_source()
119 .to_sendable();
120 let this = Trusted::new(&*object);
121
122 ROUTER.add_typed_route(
123 recv,
124 Box::new(move |block| {
125 let this = this.clone();
126 task_source.queue(task!(append_analysis_block: move || {
127 let this = this.root();
128 this.push_block(block.unwrap())
129 }));
130 }),
131 );
132 Ok(object)
133 }
134
135 pub(crate) fn push_block(&self, block: Block) {
136 self.engine.borrow_mut().push(block)
137 }
138}
139
140impl AnalyserNodeMethods<crate::DomTypeHolder> for AnalyserNode {
141 fn Constructor(
143 cx: &mut JSContext,
144 window: &Window,
145 proto: Option<HandleObject>,
146 context: &BaseAudioContext,
147 options: &AnalyserOptions,
148 ) -> Fallible<DomRoot<AnalyserNode>> {
149 AnalyserNode::new_with_proto(cx, window, proto, context, options)
150 }
151
152 #[expect(unsafe_code)]
153 fn GetFloatFrequencyData(&self, mut array: CustomAutoRooterGuard<Float32Array>) {
155 let dest = unsafe { array.as_mut_slice() };
158 self.engine.borrow_mut().fill_frequency_data(dest);
159 }
160
161 #[expect(unsafe_code)]
162 fn GetByteFrequencyData(&self, mut array: CustomAutoRooterGuard<Uint8Array>) {
164 let dest = unsafe { array.as_mut_slice() };
167 self.engine.borrow_mut().fill_byte_frequency_data(dest);
168 }
169
170 #[expect(unsafe_code)]
171 fn GetFloatTimeDomainData(&self, mut array: CustomAutoRooterGuard<Float32Array>) {
173 let dest = unsafe { array.as_mut_slice() };
176 self.engine.borrow().fill_time_domain_data(dest);
177 }
178
179 #[expect(unsafe_code)]
180 fn GetByteTimeDomainData(&self, mut array: CustomAutoRooterGuard<Uint8Array>) {
182 let dest = unsafe { array.as_mut_slice() };
185 self.engine.borrow().fill_byte_time_domain_data(dest);
186 }
187
188 fn SetFftSize(&self, value: u32) -> Fallible<()> {
190 if !(32..=32768).contains(&value) || (value & (value - 1) != 0) {
191 return Err(Error::IndexSize(None));
192 }
193 self.engine.borrow_mut().set_fft_size(value as usize);
194 Ok(())
195 }
196
197 fn FftSize(&self) -> u32 {
199 self.engine.borrow().get_fft_size() as u32
200 }
201
202 fn FrequencyBinCount(&self) -> u32 {
204 self.FftSize() / 2
205 }
206
207 fn MinDecibels(&self) -> Finite<f64> {
209 Finite::wrap(self.engine.borrow().get_min_decibels())
210 }
211
212 fn SetMinDecibels(&self, value: Finite<f64>) -> Fallible<()> {
214 if *value >= self.engine.borrow().get_max_decibels() {
215 return Err(Error::IndexSize(None));
216 }
217 self.engine.borrow_mut().set_min_decibels(*value);
218 Ok(())
219 }
220
221 fn MaxDecibels(&self) -> Finite<f64> {
223 Finite::wrap(self.engine.borrow().get_max_decibels())
224 }
225
226 fn SetMaxDecibels(&self, value: Finite<f64>) -> Fallible<()> {
228 if *value <= self.engine.borrow().get_min_decibels() {
229 return Err(Error::IndexSize(None));
230 }
231 self.engine.borrow_mut().set_max_decibels(*value);
232 Ok(())
233 }
234
235 fn SmoothingTimeConstant(&self) -> Finite<f64> {
237 Finite::wrap(self.engine.borrow().get_smoothing_constant())
238 }
239
240 fn SetSmoothingTimeConstant(&self, value: Finite<f64>) -> Fallible<()> {
242 if *value < 0. || *value > 1. {
243 return Err(Error::IndexSize(None));
244 }
245 self.engine.borrow_mut().set_smoothing_constant(*value);
246 Ok(())
247 }
248}