webrtc-sdk / webrtc

BSD 3-Clause "New" or "Revised" License
248 stars 97 forks source link

webrtc::FrameCryptorTransformer Memory leak #146

Open abdd14 opened 1 month ago

abdd14 commented 1 month ago

The FrameCryptorTransformer instance keep increasing every time someone create a track.

image Screenshot 2024-09-20 at 5 50 26 PM

This will keep the CPU threads busy.

    2328 Thread_1315129: FrameCryptorTransformer 0x0x7faffa7d8570
    + 2328 thread_start  (in libsystem_pthread.dylib) + 15  [0x114311bff]
    +   2328 _pthread_start  (in libsystem_pthread.dylib) + 99  [0x114309783]
    +     2328 rtc::Thread::PreRun(void*)  (in WebRTC) + 110  [0x11218372e]
    +       2328 rtc::Thread::ProcessMessages(int)  (in WebRTC) + 134  [0x112181dc6]
    +         2328 rtc::Thread::Get(int)  (in WebRTC) + 521  [0x112182c49]
    +           2328 rtc::NullSocketServer::Wait(webrtc::TimeDelta, bool)  (in WebRTC) + 23  [0x112187387]
    +             2328 ???  (in WebRTC)  load address 0x111d8c000 + 0x3fafbb  [0x112186fbb]
    +               2328 _pthread_cond_wait  (in libsystem_pthread.dylib) + 1211  [0x11430cc44]
    +                 2328 __psynch_cvwait  (in libsystem_kernel.dylib) + 10  [0x7ff80e202f7a]
    +                   2328 ???  (in <unknown binary>)  [0x7ff89e4e2a78]
cloudwebrtc commented 1 month ago

The thread should stop when the FrameCryptorTransformer is destroyed

https://github.com/webrtc-sdk/webrtc/blob/m125_release/api/crypto/frame_crypto_transformer.cc#L335

abdd14 commented 1 month ago

@cloudwebrtc Hi, How to stop it? I'm using webrtc from flutter SDK

cloudwebrtc commented 1 month ago

you can use await frameCryptor.dispose(); to release instance. https://github.com/flutter-webrtc/flutter-webrtc/blob/main/lib/src/native/frame_cryptor_impl.dart#L325

abdd14 commented 1 month ago

I'm calling that, and It's being removed from the frameCryptors dictionary. But even with that I was looking at the memory graph and The FrameCrypto was still there

image

I discovered that I should set stream handler to nil and after that RTCFrameCrypto was getting removed but not FrameCryptorTransformer.

FlutterEventChannel* eventChannel = self.frameCryptorsChannels[frameCryptorId];
[eventChannel setStreamHandler:nil];
frameCryptor.eventSink = nil;
frameCryptor.delegate = nil;
abdd14 commented 1 month ago

I found out that I have older version which dealloc is like that:

- (void)dealloc {
  frame_crypto_transformer_->UnRegisterFrameCryptorTransformerObserver();
}

while in the current branch I can see

- (void)dealloc {
  os_unfair_lock_lock(&_lock);
  if (_frame_crypto_transformer != nullptr) {
    _frame_crypto_transformer->UnRegisterFrameCryptorTransformerObserver();
    _frame_crypto_transformer = nullptr;
  }
  _observer = nullptr;
  os_unfair_lock_unlock(&_lock);
}

Maybe this is the issue.