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 dom_struct::dom_struct;
6use ipc_channel::ipc::{self, IpcReceiver};
7use ipc_channel::router::ROUTER;
8use js::rust::{CustomAutoRooterGuard, HandleObject};
9use js::typedarray::{Float32Array, Uint8Array};
10use servo_media::audio::analyser_node::AnalysisEngine;
11use servo_media::audio::block::Block;
12use servo_media::audio::node::AudioNodeInit;
13
14use crate::dom::audio::audionode::{AudioNode, AudioNodeOptionsHelper};
15use crate::dom::audio::baseaudiocontext::BaseAudioContext;
16use crate::dom::bindings::cell::DomRefCell;
17use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{
18    AnalyserNodeMethods, AnalyserOptions,
19};
20use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
21    ChannelCountMode, ChannelInterpretation,
22};
23use crate::dom::bindings::error::{Error, Fallible};
24use crate::dom::bindings::num::Finite;
25use crate::dom::bindings::refcounted::Trusted;
26use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
27use crate::dom::bindings::root::DomRoot;
28use crate::dom::window::Window;
29use crate::script_runtime::CanGc;
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, allow(crown::unrooted_must_root))]
41    pub(crate) fn new_inherited(
42        _: &Window,
43        context: &BaseAudioContext,
44        options: &AnalyserOptions,
45    ) -> Fallible<(AnalyserNode, IpcReceiver<Block>)> {
46        let node_options =
47            options
48                .parent
49                .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
50
51        if options.fftSize > 32768 ||
52            options.fftSize < 32 ||
53            (options.fftSize & (options.fftSize - 1) != 0)
54        {
55            return Err(Error::IndexSize);
56        }
57
58        if *options.maxDecibels <= *options.minDecibels {
59            return Err(Error::IndexSize);
60        }
61
62        if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. {
63            return Err(Error::IndexSize);
64        }
65
66        let (send, rcv) = ipc::channel().unwrap();
67        let callback = move |block| {
68            send.send(block).unwrap();
69        };
70
71        let node = AudioNode::new_inherited(
72            AudioNodeInit::AnalyserNode(Box::new(callback)),
73            context,
74            node_options,
75            1, // inputs
76            1, // outputs
77        )?;
78
79        let engine = AnalysisEngine::new(
80            options.fftSize as usize,
81            *options.smoothingTimeConstant,
82            *options.minDecibels,
83            *options.maxDecibels,
84        );
85        Ok((
86            AnalyserNode {
87                node,
88                engine: DomRefCell::new(engine),
89            },
90            rcv,
91        ))
92    }
93
94    pub(crate) fn new(
95        window: &Window,
96        context: &BaseAudioContext,
97        options: &AnalyserOptions,
98        can_gc: CanGc,
99    ) -> Fallible<DomRoot<AnalyserNode>> {
100        Self::new_with_proto(window, None, context, options, can_gc)
101    }
102
103    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
104    pub(crate) fn new_with_proto(
105        window: &Window,
106        proto: Option<HandleObject>,
107        context: &BaseAudioContext,
108        options: &AnalyserOptions,
109        can_gc: CanGc,
110    ) -> Fallible<DomRoot<AnalyserNode>> {
111        let (node, recv) = AnalyserNode::new_inherited(window, context, options)?;
112        let object = reflect_dom_object_with_proto(Box::new(node), window, proto, can_gc);
113        let task_source = window
114            .as_global_scope()
115            .task_manager()
116            .dom_manipulation_task_source()
117            .to_sendable();
118        let this = Trusted::new(&*object);
119
120        ROUTER.add_typed_route(
121            recv,
122            Box::new(move |block| {
123                let this = this.clone();
124                task_source.queue(task!(append_analysis_block: move || {
125                    let this = this.root();
126                    this.push_block(block.unwrap())
127                }));
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        window: &Window,
142        proto: Option<HandleObject>,
143        can_gc: CanGc,
144        context: &BaseAudioContext,
145        options: &AnalyserOptions,
146    ) -> Fallible<DomRoot<AnalyserNode>> {
147        AnalyserNode::new_with_proto(window, proto, context, options, can_gc)
148    }
149
150    #[allow(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    #[allow(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    #[allow(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    #[allow(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);
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);
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);
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);
242        }
243        self.engine.borrow_mut().set_smoothing_constant(*value);
244        Ok(())
245    }
246}