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, NoGC};
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    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloatfrequencydata>
151    fn GetFloatFrequencyData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Float32Array>) {
152        // Invariant to maintain: No JS code that may touch the array should
153        // run whilst we're writing to it
154        let dest = array.as_mut_slice_safe(no_gc);
155        self.engine
156            .borrow_mut()
157            .fill_frequency_data(dest.unwrap_or(&mut []));
158    }
159
160    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytefrequencydata>
161    fn GetByteFrequencyData(&self, no_gc: &NoGC, 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 = array.as_mut_slice_safe(no_gc);
165        self.engine
166            .borrow_mut()
167            .fill_byte_frequency_data(dest.unwrap_or(&mut []));
168    }
169
170    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloattimedomaindata>
171    fn GetFloatTimeDomainData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Float32Array>) {
172        // Invariant to maintain: No JS code that may touch the array should
173        // run whilst we're writing to it
174        let dest = array.as_mut_slice_safe(no_gc);
175        self.engine
176            .borrow()
177            .fill_time_domain_data(dest.unwrap_or(&mut []));
178    }
179
180    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytetimedomaindata>
181    fn GetByteTimeDomainData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Uint8Array>) {
182        // Invariant to maintain: No JS code that may touch the array should
183        // run whilst we're writing to it
184        let dest = array.as_mut_slice_safe(no_gc);
185        self.engine
186            .borrow()
187            .fill_byte_time_domain_data(dest.unwrap_or(&mut []));
188    }
189
190    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize>
191    fn SetFftSize(&self, value: u32) -> Fallible<()> {
192        if !(32..=32768).contains(&value) || (value & (value - 1) != 0) {
193            return Err(Error::IndexSize(None));
194        }
195        self.engine.borrow_mut().set_fft_size(value as usize);
196        Ok(())
197    }
198
199    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize>
200    fn FftSize(&self) -> u32 {
201        self.engine.borrow().get_fft_size() as u32
202    }
203
204    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-frequencybincount>
205    fn FrequencyBinCount(&self) -> u32 {
206        self.FftSize() / 2
207    }
208
209    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels>
210    fn MinDecibels(&self) -> Finite<f64> {
211        Finite::wrap(self.engine.borrow().get_min_decibels())
212    }
213
214    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels>
215    fn SetMinDecibels(&self, value: Finite<f64>) -> Fallible<()> {
216        if *value >= self.engine.borrow().get_max_decibels() {
217            return Err(Error::IndexSize(None));
218        }
219        self.engine.borrow_mut().set_min_decibels(*value);
220        Ok(())
221    }
222
223    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels>
224    fn MaxDecibels(&self) -> Finite<f64> {
225        Finite::wrap(self.engine.borrow().get_max_decibels())
226    }
227
228    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels>
229    fn SetMaxDecibels(&self, value: Finite<f64>) -> Fallible<()> {
230        if *value <= self.engine.borrow().get_min_decibels() {
231            return Err(Error::IndexSize(None));
232        }
233        self.engine.borrow_mut().set_max_decibels(*value);
234        Ok(())
235    }
236
237    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant>
238    fn SmoothingTimeConstant(&self) -> Finite<f64> {
239        Finite::wrap(self.engine.borrow().get_smoothing_constant())
240    }
241
242    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant>
243    fn SetSmoothingTimeConstant(&self, value: Finite<f64>) -> Fallible<()> {
244        if *value < 0. || *value > 1. {
245            return Err(Error::IndexSize(None));
246        }
247        self.engine.borrow_mut().set_smoothing_constant(*value);
248        Ok(())
249    }
250}