Thursday, December 5, 2019

GAudio/GAudio3D on Mac (Objective-C memory management)

Month: 2, Week: 2

This month I jumped straight into debugging and identifying issues with GAudio and GAudio3D libraries on Linux and Mac (I fixed Windows side last month). My main task for the last couple of days was attempting to port Windows fix directly to other platforms. And this is not as easy as it sounds.


I started with Linux and made some changes, but I could not gain much information due to a steep learning curve on Valgrind (and CMake). I explored both Linux and Mac code bases and decided to focus on Mac first, as I had access to Mac only in the office.


I never worked on Mac before, so XCode, Mac UI and Objective-C were foreign to me but it was not too bad. I implemented my Windows fixes, and while it fixed the issues on C++ side, it did not fix any of the memory leaks that were caused by Objective-C objects. I found a solution but it was a dangerous one. Later that day I came across a very clean and detailed post about Objective-C memory management which made me realize that my solution is very error-prone. I rewrote the cleanup code, refactored some functions and now GAudio/GAudio3D libraries on Mac are not leaking memory and stable.


"So now the question becomes "how long can I safely use the object before the autorelease pool is drained?" In Cocoa, the pool is drained after every NSEvent is sent. For example, if the user clicks the mouse twice then the pool will be drained in between the first and the second click. This is why it is safe to use an object temporarily, but it is not safe to keep an object unless you own it. If you don't retain your ivar and the user moves her mouse, suddenly your ivar is gone and you're probably going to crash very shortly."

Objective-C Memory Management post: https://www.tomdalling.com/blog/cocoa/an-in-depth-look-at-manual-memory-management-in-objective-c/

Now I am moving back to Linux with a better understanding of GAudio, Valgrind and CMake. It should be pretty a straight forward fix, unless I run into multi-threading problems with Pulse audio (Linux), like I did with XAudio2 on Windows.









No comments:

Post a Comment