Skip to main content

script/dom/audio/
analysernode.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::sync::{Arc, OnceLock};
6
7use dom_struct::dom_struct;
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_base::generic_channel::GenericCallback;
14use servo_media::audio::analyser_node::AnalysisEngine;
15use servo_media::audio::block::Block;
16use servo_media::audio::node::AudioNodeInit;
17
18use crate::dom::audio::audionode::{AudioNode, AudioNodeOptionsHelper};
19use crate::dom::audio::baseaudiocontext::BaseAudioContext;
20use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{
21    AnalyserNodeMethods, AnalyserOptions,
22};
23use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
24    ChannelCountMode, ChannelInterpretation,
25};
26use crate::dom::bindings::error::{Error, Fallible};
27use crate::dom::bindings::num::Finite;
28use crate::dom::bindings::refcounted::Trusted;
29use crate::dom::bindings::root::DomRoot;
30use crate::dom::window::Window;
31
32#[dom_struct]
33pub(crate) struct AnalyserNode {
34    node: AudioNode,
35    #[ignore_malloc_size_of = "Defined in servo-media"]
36    #[no_trace]
37    engine: DomRefCell<AnalysisEngine>,
38}
39
40impl AnalyserNode {
41    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
42    pub(crate) fn new_inherited(
43        cx: &mut JSContext,
44        _: &Window,
45        context: &BaseAudioContext,
46        options: &AnalyserOptions,
47        callback: Arc<OnceLock<GenericCallback<Block>>>,
48    ) -> Fallible<AnalyserNode> {
49        let node_options =
50            options
51                .parent
52                .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
53
54        if options.fftSize > 32768 ||
55            options.fftSize < 32 ||
56            (options.fftSize & (options.fftSize - 1) != 0)
57        {
58            return Err(Error::IndexSize(None));
59        }
60
61        if *options.maxDecibels <= *options.minDecibels {
62            return Err(Error::IndexSize(None));
63        }
64
65        if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. {
66            return Err(Error::IndexSize(None));
67        }
68
69        let node = AudioNode::new_inherited(
70            cx,
71            AudioNodeInit::AnalyserNode(callback),
72            context,
73            node_options,
74            1, // inputs
75            1, // outputs
76        )?;
77
78        let engine = AnalysisEngine::new(
79            options.fftSize as usize,
80            *options.smoothingTimeConstant,
81            *options.minDecibels,
82            *options.maxDecibels,
83        );
84        Ok(AnalyserNode {
85            node,
86            engine: DomRefCell::new(engine),
87        })
88    }
89
90    pub(crate) fn new(
91        cx: &mut JSContext,
92        window: &Window,
93        context: &BaseAudioContext,
94        options: &AnalyserOptions,
95    ) -> Fallible<DomRoot<AnalyserNode>> {
96        Self::new_with_proto(cx, window, None, context, options)
97    }
98
99    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
100    pub(crate) fn new_with_proto(
101        cx: &mut JSContext,
102        window: &Window,
103        proto: Option<HandleObject>,
104        context: &BaseAudioContext,
105        options: &AnalyserOptions,
106    ) -> Fallible<DomRoot<AnalyserNode>> {
107        let callback_oncelock = Arc::new(OnceLock::new());
108        let node =
109            AnalyserNode::new_inherited(cx, window, context, options, callback_oncelock.clone())?;
110        let object = reflect_dom_object_with_proto_and_cx(Box::new(node), window, proto, cx);
111        let task_source = window
112            .as_global_scope()
113            .task_manager()
114            .dom_manipulation_task_source()
115            .to_sendable();
116        let this = Trusted::new(&*object);
117
118        let callback = GenericCallback::new(move |block| {
119            let this = this.clone();
120            task_source.queue(task!(append_analysis_block: move || {
121                let this = this.root();
122                this.push_block(block.unwrap())
123            }));
124        })
125        .unwrap();
126        if callback_oncelock.set(callback).is_err() {
127            log::error!("AnalyzerNode callback is already set. Not setting it again");
128        }
129
130        Ok(object)
131    }
132
133    pub(crate) fn push_block(&self, block: Block) {
134        self.engine.borrow_mut().push(block)
135    }
136}
137
138impl AnalyserNodeMethods<crate::DomTypeHolder> for AnalyserNode {
139    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-analysernode>
140    fn Constructor(
141        cx: &mut JSContext,
142        window: &Window,
143        proto: Option<HandleObject>,
144        context: &BaseAudioContext,
145        options: &AnalyserOptions,
146    ) -> Fallible<DomRoot<AnalyserNode>> {
147        AnalyserNode::new_with_proto(cx, window, proto, context, options)
148    }
149
150    #[expect(unsafe_code)]
151    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloatfrequencydata>
152    fn GetFloatFrequencyData(&self, mut array: CustomAutoRooterGuard<Float32Array>) {
153        // Invariant to maintain: No JS code that may touch the array should
154        // run whilst we're writing to it
155        let dest = unsafe { array.as_mut_slice() };
156        self.engine.borrow_mut().fill_frequency_data(dest);
157    }
158
159    #[expect(unsafe_code)]
160    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytefrequencydata>
161    fn GetByteFrequencyData(&self, mut array: CustomAutoRooterGuard<Uint8Array>) {
162        // Invariant to maintain: No JS code that may touch the array should
163        // run whilst we're writing to it
164        let dest = unsafe { array.as_mut_slice() };
165        self.engine.borrow_mut().fill_byte_frequency_data(dest);
166    }
167
168    #[expect(unsafe_code)]
169    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloattimedomaindata>
170    fn GetFloatTimeDomainData(&self, mut array: CustomAutoRooterGuard<Float32Array>) {
171        // Invariant to maintain: No JS code that may touch the array should
172        // run whilst we're writing to it
173        let dest = unsafe { array.as_mut_slice() };
174        self.engine.borrow().fill_time_domain_data(dest);
175    }
176
177    #[expect(unsafe_code)]
178    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytetimedomaindata>
179    fn GetByteTimeDomainData(&self, mut array: CustomAutoRooterGuard<Uint8Array>) {
180        // Invariant to maintain: No JS code that may touch the array should
181        // run whilst we're writing to it
182        let dest = unsafe { array.as_mut_slice() };
183        self.engine.borrow().fill_byte_time_domain_data(dest);
184    }
185
186    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize>
187    fn SetFftSize(&self, value: u32) -> Fallible<()> {
188        if !(32..=32768).contains(&value) || (value & (value - 1) != 0) {
189            return Err(Error::IndexSize(None));
190        }
191        self.engine.borrow_mut().set_fft_size(value as usize);
192        Ok(())
193    }
194
195    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize>
196    fn FftSize(&self) -> u32 {
197        self.engine.borrow().get_fft_size() as u32
198    }
199
200    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-frequencybincount>
201    fn FrequencyBinCount(&self) -> u32 {
202        self.FftSize() / 2
203    }
204
205    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels>
206    fn MinDecibels(&self) -> Finite<f64> {
207        Finite::wrap(self.engine.borrow().get_min_decibels())
208    }
209
210    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels>
211    fn SetMinDecibels(&self, value: Finite<f64>) -> Fallible<()> {
212        if *value >= self.engine.borrow().get_max_decibels() {
213            return Err(Error::IndexSize(None));
214        }
215        self.engine.borrow_mut().set_min_decibels(*value);
216        Ok(())
217    }
218
219    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels>
220    fn MaxDecibels(&self) -> Finite<f64> {
221        Finite::wrap(self.engine.borrow().get_max_decibels())
222    }
223
224    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels>
225    fn SetMaxDecibels(&self, value: Finite<f64>) -> Fallible<()> {
226        if *value <= self.engine.borrow().get_min_decibels() {
227            return Err(Error::IndexSize(None));
228        }
229        self.engine.borrow_mut().set_max_decibels(*value);
230        Ok(())
231    }
232
233    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant>
234    fn SmoothingTimeConstant(&self) -> Finite<f64> {
235        Finite::wrap(self.engine.borrow().get_smoothing_constant())
236    }
237
238    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant>
239    fn SetSmoothingTimeConstant(&self, value: Finite<f64>) -> Fallible<()> {
240        if *value < 0. || *value > 1. {
241            return Err(Error::IndexSize(None));
242        }
243        self.engine.borrow_mut().set_smoothing_constant(*value);
244        Ok(())
245    }
246}