我正在寻找一种方法来等待 CIContext 渲染完成而不阻塞。为简单起见,这里是一个示例,其中我使用 CIImage
和 CIContext
将一个 CVPixelBufferRef
渲染到另一个 CVPixelBufferRef
。显然我的实际管道会做更多的事情,但这是最简单的情况。
CIContext *context = [CIContext new];
// sourceBuffer provided from something like a camera
CIImage *image = [CIImage imageWithCVPixelBuffer:sourceBuffer];
CVPixelBufferRef output;
// pool was allocated elsewhere
CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, bufferPool, &output)
[context render:image toCVPixelBuffer:output];
代码会一直阻塞,直到渲染完成,因为 [CIContext render:toCVPixelBuffer:]
正在阻塞。
您可以使用[CIContext startTaskToRender:toDestination:error:]
以非阻塞方式启动渲染任务,如下所示
CIContext *context = [CIContext new];
// sourceBuffer provided from something like a camera
CIImage *image = [CIImage imageWithCVPixelBuffer:sourceBuffer];
CVPixelBufferRef output;
// pool was allocated elsewhere
CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, bufferPool, &output)
CIRenderDestination *destination = [[CIRenderDestination alloc] initWithPixelBuffer:output];
[context startTaskToRender:image toDestination:destination error:nil];
这已经完成一半了,调用不会阻塞,但我不知道渲染任务何时完成。该 API 返回 CIRenderTask ,但它只有一个实例方法,当然是 waitUntilCompletedAndReturnError
,它将阻塞直到任务完成。
说实话,除了提供错误回调的媒介之外,我不太明白这个 API 的意义。除非您的管道不需要知道任务何时完成,否则您仍然需要阻止才能获取结果。
所以,我的问题:是否可以在不阻塞的情况下获取 CIContext
渲染的结果?
最佳答案
第一个 render
调用实际上不应该是阻塞调用。正如 this answer 中提到的,
"Core Image defers the rendering until the client requests the access to the frame buffer, i.e.
CVPixelBufferLockBaseAddress
".
但是,您也可以使用 CIRenderDestiantion
API 并自行使其异步,如下所示:
CIRenderTask *task = [context startTaskToRender:image toDestination:destination error:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[task waitUntilCompletedAndReturnError: NULL];
// do async stuff here, e.g. call a callback block
});
关于ios - 以非阻塞方式等待 CIContext 渲染任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66344111/