Jan Rüegg
Jan Rüegg

Reputation: 10075

CVMetalTextureGetTexture ownerhsip?

I'm trying to figure out how the ownership works with the function CVMetalTextureGetTexture:

CVMetalTextureRef textureRef;
// ... textureRef is created
id<MTLTexture> texture = CVMetalTextureGetTexture(_textureRef);
CVBufferRelease(textureRef); // Releasing the existing texture
// Is texture still valid here?

Is texture still valid after releasing textureRef? If not, can I somehow transfer ownership from textureRef to texture (ARC), so I don't have to call CVBufferRelease later when texture is released?

The same question for swift:

var texture: MTLTexture
do {
  var textureRef: CVMetalTexture
  // ... textureRef is created
  texture = CVMetalTextureGetTexture(textureRef)!
  // end of scope, textureRef is released
}
// Is texture still valid here?

Upvotes: 8

Views: 679

Answers (2)

Barak Yoresh
Barak Yoresh

Reputation: 299

This is an excellent question since this kind of breaks the Create Rule, but it seems like this method indeed retains the underlying object. I guess this rule doesn't apply for Core Foundation -> ARC methods...

You can see in this Apple Demo that they do release the ref after converting it to an id<MTLTexture>. They do it in the more implicit Swifty version so it's easily missed.

Upvotes: 1

Nh Xu
Nh Xu

Reputation: 121

We have also made another experiment before I see your question:

in a loop, CVMetalTextureRef created from CVPixelBuffer comes from Camera.

static void *texturePtr;  

/** AVCaptureVideoDataOutputSampleBufferDelegate, as a loop */
{
CVMetalTextureRef textureRef;
// ... textureRef is created
id<MTLTexture> texture = CVMetalTextureGetTexture(_textureRef);
CVBufferRelease(textureRef); // Releasing the existing texture

texturePtr= (__bridge_retained void*)texture;

// no releasing the texturePtr
// (__bridge_transfer id<MTLTexture>)texturePtr;
}

I found that I did not release the texturePtr, but still no memory leak occurs. What's more, texturePtr is valid in sometime and before we replace it with the new var.
So I think maybe this is linked to your question.
My reply is more like an argument other than an answer.

Upvotes: 1

Related Questions