AVCapture之4——NSOpenGLView

想要高效的进行界面刷新,OpenGL/硬件加速是必须的。最近我在研究OpenGL的过程中,被OpenGL的API、Shader、GSLS等烧脑得不要不要的。也不怪它,OpenGL本来就是为3D动画设计的,一上来肯定高大上。
网络上有不少OpenGL ES 2.0视频render的开源实现,苹果自家的GLCameraRipple示例也非常棒,但是鲜有OpenGL的实现。OpenGL渲染纹理,CoreImage也可以做得到。

苹果有个Demo中有一个VideoCIView,这个类基本实现了将一个CIImage绘制到NSOpenGLView中。

VideoCIView继承自NSOpenGLView,主要是想利用显示区域变化的事件回调。还有一点要注意,NSOpenGLView不能有subview。

+ (NSOpenGLPixelFormat *)defaultPixelFormat
{
    static NSOpenGLPixelFormat *pf;
    
    if (pf == nil)
    {
        // You must make sure that the pixel format of the context does not
        // have a recovery renderer is important. Otherwise CoreImage may not be able to
        // create contexts that share textures with this context.
        
        static const NSOpenGLPixelFormatAttribute attr[] = {
            NSOpenGLPFAAccelerated,
            NSOpenGLPFANoRecovery,
            NSOpenGLPFAColorSize, 32,
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4
            NSOpenGLPFAAllowOfflineRenderers,
#endif
            0
        };
        
        pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:(void *)&attr];
    }
    
    return pf;
}

NSOpenGLPixelFormat是每个NSOpenGLView初始化所必需的,这种已C数组作为attribute传入到OC中的做法比较少见。attribute分两种类型:1、BOOL;2、带整数。此函数主要是设置OpenGL的一些参数,实现大同小异。

- (void)prepareOpenGL
{
    GLint parm = 1;
    
    //  Set the swap interval to 1 to ensure that buffers swaps occur only during the vertical retrace of the monitor.
    
    [[self openGLContext] setValues:&parm forParameter:NSOpenGLCPSwapInterval];
    
    // To ensure best performance, disbale everything you don't need.
    
    glDisable (GL_ALPHA_TEST);
    glDisable (GL_DEPTH_TEST);
    glDisable (GL_SCISSOR_TEST);
    glDisable (GL_BLEND);
    glDisable (GL_DITHER);
    glDisable (GL_CULL_FACE);
    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glDepthMask (GL_FALSE);
    glStencilMask (0);
    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
    glHint (GL_TRANSFORM_HINT_APPLE, GL_FASTEST);
    _needsReshape = YES;
}

当OpenGL初始化完成当前context,就会调用一次此函数,姑且认为它就是viewDidLoad吧。Apple这里关闭了很多不需要的参数。

// Called when the user scrolls, moves, or resizes the view.
- (void)reshape
{
    // Resets the viewport on the next draw operation.
    _needsReshape = YES;
}

- (void)updateMatrices
{
    NSRect  visibleRect = [self visibleRect];
    NSRect  mappedVisibleRect = NSIntegralRect([self convertRect: visibleRect toView: [self enclosingScrollView]]);
    
    [[self openGLContext] update];
    
    // Install an orthographic projection matrix (no perspective)
    // with the origin in the bottom left and one unit equal to one device pixel.
    
    glViewport (0, 0,mappedVisibleRect.size.width, mappedVisibleRect.size.height);
    
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    glOrtho(visibleRect.origin.x,
            visibleRect.origin.x + visibleRect.size.width,
            visibleRect.origin.y,
            visibleRect.origin.y + visibleRect.size.height,
            -1, 1);
    
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity ();
    _needsReshape = NO;
}

当外部窗口大小发生变化时,会调用此方法(这也是不选NSOpenGLLayer的原因)。窗口大小变化后,没有直接修改glViewport,而是设置_needsReshap = YES!这算是OpenGL的一个通用设计模式吧——所有绘制操作都在render函数里完成,且render函数不重入(我瞎BB的)。OpenGL绘制不需要一定在主线程,至于render函数嘛,一般都是用CADisplayLink驱动,我们这个工程有onCapture回调,所以省了。

- (void)render
{
    NSRect      frame = [self bounds];
    
    [[self openGLContext] makeCurrentContext];
    
    if (_needsReshape)
    {
        [self updateMatrices];
        glClear (GL_COLOR_BUFFER_BIT);
    }
    
    CGRect      imageRect = [_image extent];
    CGRect      destRect = *((CGRect*)&frame);
    
    [[self ciContext] drawImage:_image inRect:destRect fromRect:imageRect];
    
    // Flush the OpenGL command stream. If the view is double-buffered
    // you should  replace  this call with [[self openGLContext]
    
    glFlush ();
    
}

- (CIContext*)ciContext
{
    // Allocate a CoreImage rendering context using the view's OpenGL
    // context as its destination if none already exists.
    // You must do this before sending any queries to the CIContext.
    
    if (_context == nil)
    {
        [[self openGLContext] makeCurrentContext];
        NSOpenGLPixelFormat *pf;
        
        pf = [self pixelFormat];
        if (pf == nil)
            pf = [[self class] defaultPixelFormat];
        
        _context = [[CIContext contextWithCGLContext: CGLGetCurrentContext()
                                         pixelFormat: [pf CGLPixelFormatObj] options: nil] retain];
    }
    return _context;
}

真正的render就干两件事

  1. 可视区域变化?更新viewport和映射关系
  2. 把CIImage绘制到OpenGL中

第2步前需要先得到用于CoreImage绘制的CIContext。绘制函数就一行,drawImage。当然,这个绘制是在GPU完成的,速度非常快。

最后,通过setImage来驱动render

- (void)setImage:(CIImage *)image
{
    if (_image != image)
    {
        [_image release];
        _image = [image retain];
    }
    [self render];
}

最后一步关键点,获得CIImage。通过CMSampleBuffer得到CVImageBuffer,然后再通过CVImageBuffer得到CIImage

    CVImageBufferRef videoFrame = CMSampleBufferGetImageBuffer(sampleBuffer);
    CIImage* image = [CIImage imageWithCVImageBuffer:videoFrame];

+[CIImage imageWithCVImageBuffer:]并不总是能成功,这与采集的图像格式有关。

整个过程NSOpenGLView繁杂了点,iOS上的GLKView用起来要简单许多。
最后测试下来,CIContext的方式CPU占用率约7%,比AVSampleBufferDisplayLayer稍差。原因主要是CVImageBufferRef -> CIImage占用了许多时间,而绘制过程还是相当的高效。

我是比较喜欢这种渲染方式,它既利用到硬件加速,而且CIImage还要好多滤镜可以玩。最重要的,这种实现方案比较简单。


参考链接:
Stupid Video Tricks (CocoaConf DC, March 2014)

你可能感兴趣的:(AVCapture之4——NSOpenGLView)