I am facing an issue with React Native WebRTC where the first call works as expected, but subsequent calls fail. Additionally, if I explicitly call localPCRef.current.close()
during the cleanup process, the app crashes on the second call attempt.
Even though I have implemented a cleanup function to stop audio devices, release tracks, and reset the PeerConnection
, the resources don’t seem to fully release. Below is my cleanup function:
async function endCall() {
try {
await stopAudioDevices();
setIsCallActive(false);
setCallStatus(null);
if (localStream) {
localStream.getTracks().forEach((track) => {
console.log(`Stopping track kind: ${track.kind}, readyState: ${track.readyState}`);
if (track.readyState === 'live') {
track.stop();
}
});
localStream.ontrack = null;
localStream.onremovetrack = null;
localStream.onicecandidate = null;
localStream.oniceconnectionstatechange = null;
localStream.onsignalingstatechange = null;
localStream?.release();
}
if (remoteStream) {
remoteStream.getTracks().forEach((track) => {
console.log(`Stopping remote track: ${track.kind}`);
track.enabled = false;
track.stop();
});
remoteStream.ontrack = null;
remoteStream.onremovetrack = null;
remoteStream.onicecandidate = null;
remoteStream.oniceconnectionstatechange = null;
remoteStream.onsignalingstatechange = null;
remoteStream?.release();
}
if (localPCRef && localPCRef.current) {
localPCRef.current.getTransceivers().forEach((transceiver) => {
if (transceiver.stop) {
transceiver.stop();
}
});
localPCRef.current.getSenders().forEach((sender) => {
if (sender.track) {
sender.track.stop();
}
localPCRef.current.removeTrack(sender);
});
localPCRef.current.getReceivers().forEach((receiver) => {
if (receiver.track) {
receiver.track.stop();
}
});
try {
localPCRef.current.close(); // Causes crash on subsequent calls
localPCRef.current = null;
} catch (error) {
console.error("Error closing PeerConnection:", error);
}
}
socket.emit("endCall", { callerId: userId, receiverId });
if (settings.soundChatEnd) {
NotificationSounds.getNotifications('notification').then((soundsList) => {
if (soundsList.length > 10) {
const soundUrl = soundsList[10].url;
playSound(soundUrl);
} else {
console.log('No sounds found.');
}
});
}
dispatch(setCallEnded(null));
dispatch(setIncomingCall(null));
setCallStatus('ended');
setIsMuted(false);
if (userId) {
const roomRef = doc(db, "room", userId);
await deleteDoc(roomRef);
}
dispatch(setIsCallingOn(false));
console.log("Call ended and cleaned up successfully");
} catch (error) {
console.error("Error during call cleanup:", error);
}
}
Questions:
- Is there a specific way to safely call
localPCRef.current.close()
in React Native WebRTC without causing a crash? - Are there alternative methods to fully release
PeerConnection
resources after a call? - Is this a known issue with WebRTC on Android, or am I missing a platform-specific cleanup step?