livekit / client-sdk-swift

LiveKit Swift Client SDK. Easily build live audio or video experiences on iOS, macOS, tvOS, and visionOS.
https://livekit.io
Apache License 2.0
211 stars 100 forks source link

Memory leaks when Room.connect(url: String, token: String, connectOptions: ConnectOptions? = nil, roomOptions: RoomOptions? = nil) #435

Open henry-castalk opened 3 months ago

henry-castalk commented 3 months ago

Steps to Reproduce

Here is how I connect and disconnect a room

  1. Declare the liveKitRoom: Room variable, a method connectToLiveKitRoom() to connect and a method teardownLiveKitRoom() to cleanup after disconnect.
  2. After got the liveStreamUrl?.absoluteString and liveKitRoomToken, I processed the connectToLiveKitRoom() method, and surely call teardownLiveKitRoom() after leaving the screen.
  3. The leaks show in the Instrument screen. According to the stacktrace, the leaks cause at this block of code
    static func createPeerConnection(_ configuration: LKRTCConfiguration,
                                     constraints: LKRTCMediaConstraints) -> LKRTCPeerConnection?
    {
        DispatchQueue.liveKitWebRTC.sync { peerConnectionFactory.peerConnection(with: configuration,
                                                                                constraints: constraints,
                                                                                delegate: nil) }
    }
image

Here is my code

private let liveKitRoom: Room = {
    let adaptiveStream = true
    let roomOptions = RoomOptions(adaptiveStream: adaptiveStream)
    let room = Room(roomOptions: roomOptions)
    return room
}()

private func connectToLiveKitRoom() {
    Task { [weak self] in
        guard let self else { return }
        try await liveKitRoom.connect(
            url: liveStreamUrl?.absoluteString ?? "",
            token: liveKitRoomToken ?? ""
        )
    }
}

private func teardownLiveKitRoom() {
    liveKitRoom.remove(delegate: self)
    Task { [liveKitRoom] in
        await Self.mute(liveKitRoom: liveKitRoom)
        await liveKitRoom.disconnect()
    }
}

SDK Version 2.0.5 I tried to upgrade the library from 2.0.5 to 2.0.6, 2.0.7, 2.0.8, 2.0.9, 2.0.10 but the leaks still happen.

iOS/macOS Version 17.5.1

Xcode Version

Expected behavior Leaks doesn't happen

hiroshihorie commented 3 months ago

Thanks for the detailed report. That block of code doesn't seem to retain code, it could be leaking at WebRTC level.

henry-castalk commented 3 months ago

@hiroshihorie Thanks man. Do you have any suggestion about what I should do to resolve this case?