web-audio-api-rs icon indicating copy to clipboard operation
web-audio-api-rs copied to clipboard

AudioContext.destination and listener should probably not return owned values

Open orottier opened this issue 2 years ago • 1 comments

The spec contains some cyclic references that are quite hard for us to model in rust. For example:

  1. BaseAudioContext has a destination property that should return a AudioDestinationNode
  2. AudioDestinationNode implements the AudioNode interface
  3. The context property of an AudioNode should return the associated BaseAudioContext

Same (but differently) goes for the AudioListener.

This is currently solved by only storing the raw pieces of the destination and the listener, and by reconstructing them on the fly when the properties are accessed. This however means we return owned values: fn destination(&self) -> node::AudioDestinationNode { Where you would expect to have a reference returned with its lifetime bound to the audio context fn destination(&'context self) -> &'context node::AudioDestinationNode {

This is definitely possible to implement because the BaseAudioContext is wrapping an Arc, and these allow for cyclic dependencies.

For example with tricks like this we could make temporary empty contexts to bootstrap the cyclic deps:

 pub struct ConcreteBaseAudioContext {
-    inner: Arc<ConcreteBaseAudioContextInner>,
+    inner: Option<Arc<ConcreteBaseAudioContextInner>>,
 }

This would allow to store the Destination and the Listener inside the ConcreteBaseAudioContextInner so we can hand out references

orottier avatar Mar 29 '22 17:03 orottier

Removing the milestone goal. It would be nice to have, but this can probably go into v2 along with other breaking changes such as variable render quantum size.

orottier avatar Apr 04 '22 06:04 orottier

Revisiting this, I think it would be a mistake to tie the lifetime of the Destination and the Listener to the AudioContext. Other nodes are allowed to outlive the context, and this is nice because the context can go out of scope while still allowing to continue playback and change settings of the node.

orottier avatar Jun 02 '23 18:06 orottier