servo-script 0.5.0

A component of the servo web-engine.
Documentation
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::sync::{Arc, OnceLock};

use dom_struct::dom_struct;
use js::context::{JSContext, NoGC};
use js::rust::{CustomAutoRooterGuard, HandleObject};
use js::typedarray::{Float32Array, Uint8Array};
use script_bindings::cell::DomRefCell;
use script_bindings::reflector::reflect_dom_object_with_proto_and_cx;
use servo_base::generic_channel::GenericCallback;
use servo_media::audio::analyser_node::AnalysisEngine;
use servo_media::audio::audio_node::AudioNodeInit;
use servo_media::audio::block::Block;

use crate::dom::audio::audionode::{AudioNode, AudioNodeOptionsHelper};
use crate::dom::audio::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{
    AnalyserNodeMethods, AnalyserOptions,
};
use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
    ChannelCountMode, ChannelInterpretation,
};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::root::DomRoot;
use crate::dom::window::Window;

#[dom_struct]
pub(crate) struct AnalyserNode {
    node: AudioNode,
    #[ignore_malloc_size_of = "Defined in servo-media"]
    #[no_trace]
    engine: DomRefCell<AnalysisEngine>,
}

impl AnalyserNode {
    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
    pub(crate) fn new_inherited(
        cx: &mut JSContext,
        _: &Window,
        context: &BaseAudioContext,
        options: &AnalyserOptions,
        callback: Arc<OnceLock<GenericCallback<Block>>>,
    ) -> Fallible<AnalyserNode> {
        let node_options =
            options
                .parent
                .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);

        if options.fftSize > 32768 ||
            options.fftSize < 32 ||
            (options.fftSize & (options.fftSize - 1) != 0)
        {
            return Err(Error::IndexSize(None));
        }

        if *options.maxDecibels <= *options.minDecibels {
            return Err(Error::IndexSize(None));
        }

        if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. {
            return Err(Error::IndexSize(None));
        }

        let node = AudioNode::new_inherited(
            cx,
            AudioNodeInit::AnalyserNode(callback),
            context,
            node_options,
            1, // inputs
            1, // outputs
        )?;

        let engine = AnalysisEngine::new(
            options.fftSize as usize,
            *options.smoothingTimeConstant,
            *options.minDecibels,
            *options.maxDecibels,
        );
        Ok(AnalyserNode {
            node,
            engine: DomRefCell::new(engine),
        })
    }

    pub(crate) fn new(
        cx: &mut JSContext,
        window: &Window,
        context: &BaseAudioContext,
        options: &AnalyserOptions,
    ) -> Fallible<DomRoot<AnalyserNode>> {
        Self::new_with_proto(cx, window, None, context, options)
    }

    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
    pub(crate) fn new_with_proto(
        cx: &mut JSContext,
        window: &Window,
        proto: Option<HandleObject>,
        context: &BaseAudioContext,
        options: &AnalyserOptions,
    ) -> Fallible<DomRoot<AnalyserNode>> {
        let callback_oncelock = Arc::new(OnceLock::new());
        let node =
            AnalyserNode::new_inherited(cx, window, context, options, callback_oncelock.clone())?;
        let object = reflect_dom_object_with_proto_and_cx(Box::new(node), window, proto, cx);
        let task_source = window
            .as_global_scope()
            .task_manager()
            .dom_manipulation_task_source()
            .to_sendable();
        let this = Trusted::new(&*object);

        let callback = GenericCallback::new(move |block| {
            let this = this.clone();
            task_source.queue(task!(append_analysis_block: move || {
                let this = this.root();
                this.push_block(block.unwrap())
            }));
        })
        .unwrap();
        if callback_oncelock.set(callback).is_err() {
            log::error!("AnalyzerNode callback is already set. Not setting it again");
        }

        Ok(object)
    }

    pub(crate) fn push_block(&self, block: Block) {
        self.engine.borrow_mut().push(block)
    }
}

impl AnalyserNodeMethods<crate::DomTypeHolder> for AnalyserNode {
    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-analysernode>
    fn Constructor(
        cx: &mut JSContext,
        window: &Window,
        proto: Option<HandleObject>,
        context: &BaseAudioContext,
        options: &AnalyserOptions,
    ) -> Fallible<DomRoot<AnalyserNode>> {
        AnalyserNode::new_with_proto(cx, window, proto, context, options)
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloatfrequencydata>
    fn GetFloatFrequencyData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Float32Array>) {
        // Invariant to maintain: No JS code that may touch the array should
        // run whilst we're writing to it
        let dest = array.as_mut_slice_safe(no_gc);
        self.engine
            .borrow_mut()
            .fill_frequency_data(dest.unwrap_or(&mut []));
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytefrequencydata>
    fn GetByteFrequencyData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Uint8Array>) {
        // Invariant to maintain: No JS code that may touch the array should
        // run whilst we're writing to it
        let dest = array.as_mut_slice_safe(no_gc);
        self.engine
            .borrow_mut()
            .fill_byte_frequency_data(dest.unwrap_or(&mut []));
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloattimedomaindata>
    fn GetFloatTimeDomainData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Float32Array>) {
        // Invariant to maintain: No JS code that may touch the array should
        // run whilst we're writing to it
        let dest = array.as_mut_slice_safe(no_gc);
        self.engine
            .borrow()
            .fill_time_domain_data(dest.unwrap_or(&mut []));
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytetimedomaindata>
    fn GetByteTimeDomainData(&self, no_gc: &NoGC, mut array: CustomAutoRooterGuard<Uint8Array>) {
        // Invariant to maintain: No JS code that may touch the array should
        // run whilst we're writing to it
        let dest = array.as_mut_slice_safe(no_gc);
        self.engine
            .borrow()
            .fill_byte_time_domain_data(dest.unwrap_or(&mut []));
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize>
    fn SetFftSize(&self, value: u32) -> Fallible<()> {
        if !(32..=32768).contains(&value) || (value & (value - 1) != 0) {
            return Err(Error::IndexSize(None));
        }
        self.engine.borrow_mut().set_fft_size(value as usize);
        Ok(())
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize>
    fn FftSize(&self) -> u32 {
        self.engine.borrow().get_fft_size() as u32
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-frequencybincount>
    fn FrequencyBinCount(&self) -> u32 {
        self.FftSize() / 2
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels>
    fn MinDecibels(&self) -> Finite<f64> {
        Finite::wrap(self.engine.borrow().get_min_decibels())
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels>
    fn SetMinDecibels(&self, value: Finite<f64>) -> Fallible<()> {
        if *value >= self.engine.borrow().get_max_decibels() {
            return Err(Error::IndexSize(None));
        }
        self.engine.borrow_mut().set_min_decibels(*value);
        Ok(())
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels>
    fn MaxDecibels(&self) -> Finite<f64> {
        Finite::wrap(self.engine.borrow().get_max_decibels())
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels>
    fn SetMaxDecibels(&self, value: Finite<f64>) -> Fallible<()> {
        if *value <= self.engine.borrow().get_min_decibels() {
            return Err(Error::IndexSize(None));
        }
        self.engine.borrow_mut().set_max_decibels(*value);
        Ok(())
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant>
    fn SmoothingTimeConstant(&self) -> Finite<f64> {
        Finite::wrap(self.engine.borrow().get_smoothing_constant())
    }

    /// <https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant>
    fn SetSmoothingTimeConstant(&self, value: Finite<f64>) -> Fallible<()> {
        if *value < 0. || *value > 1. {
            return Err(Error::IndexSize(None));
        }
        self.engine.borrow_mut().set_smoothing_constant(*value);
        Ok(())
    }
}