Search Unity

Question Possible memory leak when streaming video to texture?

Discussion in 'Scripting' started by pringmylifeup, Nov 23, 2022.

  1. pringmylifeup

    pringmylifeup

    Joined:
    Mar 20, 2019
    Posts:
    4
    Howdy -

    Cross-posting this with `General Graphics` as I don't know a good home for my question..

    I'm trying to livestream video to a texture, and, it works, but after some time Unity hung and I got a low disk warning (atm I have 15GB free). After I killed Unity, the disk freed back up. This leads me to believe there is a memory leak somewhere in my code or pipeline, which led to a disk swap catastrophe.

    My pipeline is as follows: sending a 480p/30fps jpg-compressed camera stream through ROS (ROS-TCP connector). This callback runs on every frame coming in:
    Code (CSharp):
    1.     public void c_img_cb(CompressedImageMsg img) {
    2.         //Debug.Log(img);
    3.         Texture2D texRos = new Texture2D(640, 480, TextureFormat.RGB24, false);
    4.         texRos.LoadImage(img.data);
    5.         obj.GetComponent<Renderer>().material.mainTexture = texRos;      
    6.     }
    Any help would be much appreciated!
     
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Are you running this code every frame?
    Asset types like Texture2D are unmanaged, you need to Destroy() them when no longer used.
    As I read your code now you are creating a new texture every frame that never gets unloaded.
    You should really only need one and reuse it.
     
  3. pringmylifeup

    pringmylifeup

    Joined:
    Mar 20, 2019
    Posts:
    4
    Awesome - thank you!!

    Just curious - Are there managed assets in Unity? Why doesn't texRos fall out of scope after the function runs (and thus get picked up by the garbage collector)?
     
  4. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Not as far as I know.
    I'm sure it's explained in the manual somewhere, I just can't seem to find where right now.
    The assets, like materials, meshes and textures, live on the C++ side of the engine and the C# objects just point to them. So the C# objects might go out of scope, but the C++ side does not.
    I'm surely missing details here but this is how I understand it to work.
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    No matter the reason, please don't cross-post.