twilio / twilio-video-app-react

A collaboration application built with the twilio-video.js SDK and React.js
Apache License 2.0
1.81k stars 728 forks source link

Fix memory leak in AudioLevelIndicator #703

Closed timmydoza closed 2 years ago

timmydoza commented 2 years ago

Contributing to Twilio

All third party contributors acknowledge that any contributions they provide will be made under the same open source license that the open source project is provided under.

Pull Request Details

JIRA link(s):

Description

This PR fixes an issue where the AudioLevelIndicator can cause a memory leak after it is mounted/unmounted many times.

To see the issue, join a room, and run this code in the console which will repeatedly click the "Mute Audio" button:

var intervalId = setInterval(() => document.querySelector('[data-cy-audio-toggle]').click(), 10);

To stop this, just clear the interval id:

clearInterval(intervalId);

As the local audio track is repeatedly muted and unmuted, it will cause the AudioLevelIndicator to turn on and off. While this happens, you should see the memory footprint for the tab start to grow drastically (use Chrome's task manager to see the memory usage):

image

Also, you can see the memory leak if you take a heap snapshot and search for classes with "audio" in their name: image

You'll see that there's a huge number of MediaStreamsAudioSourceNode classes.

This the fix in the PR, you will no longer see 1) the memory footprint grow, or 2) the large amount of MediaStreamsAudioSourceNode classes in the heap.

This memory leak was caused by the fact that all AudioLevelIndicators used to share a single AudioContext. Because of this, all MediaStreamsAudioSourceNodes that were created could not be garbage collected because the single AudioContext instance was never closed.

This this PR, each AudioLevelIndicator now uses their own AudioContext instance, which is then closed when it is no longer needed. As a result, all resources used by the AudioLevelIndicator are now appropriately garbage collected.

Burndown

Before review

Before merge