Metal入門教程(三)攝像頭采集渲染

前言

Metal入門教程(一)圖片繪制
Metal入門教程(二)三維變換

前面的教程介紹了如何繪制一張圖片和如何把圖片顯示到3D物體上并進行三維變換,這次介紹如何用Metal渲染攝像頭采集到的圖像。

Metal系列教程的代碼地址
OpenGL ES系列教程在這里

你的star和fork是我的源動力,你的意見能讓我走得更遠。

正文

核心思路

AVFoundation采集攝像頭數據得到CMSampleBufferRef,用CoreVideo提供的方法將圖像數據轉為Metal的紋理,再用MetalPerformanceShaders的高斯模糊濾鏡對圖像進行處理,結果展示到屏幕上。

效果展示

123.gif

具體步驟

1、Metal相關設置
- (void)setupMetal {
    self.mtkView = [[MTKView alloc] initWithFrame:self.view.bounds];
    self.mtkView.device = MTLCreateSystemDefaultDevice();
    [self.view insertSubview:self.mtkView atIndex:0];
    self.mtkView.delegate = self;
    self.mtkView.framebufferOnly = NO;
    self.commandQueue = [self.mtkView.device newCommandQueue];
    CVMetalTextureCacheCreate(NULL, NULL, self.mtkView.device, NULL, &_textureCache);
}

除了正常創建和初始化MTKView之外,這里還多兩行代碼:

  • 設置MTKView的dramwable紋理是可讀寫的;(默認是只讀)
  • 創建CVMetalTextureCacheRef _textureCache,這是Core Video的Metal紋理緩存;
2、攝像頭采集設置
- (void)setupCaptureSession {
    self.mCaptureSession = [[AVCaptureSession alloc] init];
    self.mCaptureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
    self.mProcessQueue = dispatch_queue_create("mProcessQueue", DISPATCH_QUEUE_SERIAL); // 串行隊列
    AVCaptureDevice *inputCamera = nil;
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == AVCaptureDevicePositionBack) {
            inputCamera = device;
        }
    }
    self.mCaptureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:inputCamera error:nil];
    if ([self.mCaptureSession canAddInput:self.mCaptureDeviceInput]) {
        [self.mCaptureSession addInput:self.mCaptureDeviceInput];
    }
    self.mCaptureDeviceOutput = [[AVCaptureVideoDataOutput alloc] init];
    [self.mCaptureDeviceOutput setAlwaysDiscardsLateVideoFrames:NO];
    // 這里設置格式為BGRA,而不用YUV的顏色空間,避免使用Shader轉換
    [self.mCaptureDeviceOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
    [self.mCaptureDeviceOutput setSampleBufferDelegate:self queue:self.mProcessQueue];
    if ([self.mCaptureSession canAddOutput:self.mCaptureDeviceOutput]) {
        [self.mCaptureSession addOutput:self.mCaptureDeviceOutput];
    }
    AVCaptureConnection *connection = [self.mCaptureDeviceOutput connectionWithMediaType:AVMediaTypeVideo];
    [connection setVideoOrientation:AVCaptureVideoOrientationPortrait]; // 設置方向
    [self.mCaptureSession startRunning];
}

創建AVCaptureSession、AVCaptureDeviceInputAVCaptureVideoDataOutput,注意在創建AVCaptureVideoDataOutput時,需要指定內容格式,這里使用的是BGRA的格式;
同時需要設定采集的方向,否則圖像會出現旋轉;

3、攝像頭采集回調
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    size_t width = CVPixelBufferGetWidth(pixelBuffer);
    size_t height = CVPixelBufferGetHeight(pixelBuffer);
    
    CVMetalTextureRef tmpTexture = NULL;
    // 如果MTLPixelFormatBGRA8Unorm和攝像頭采集時設置的顏色格式不一致,則會出現圖像異常的情況;
    CVReturn status = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, self.textureCache, pixelBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &tmpTexture);
    if(status == kCVReturnSuccess)
    {
        self.mtkView.drawableSize = CGSizeMake(width, height);
        self.texture = CVMetalTextureGetTexture(tmpTexture);
        CFRelease(tmpTexture);
    }
}

這是demo的核心內容,攝像頭回傳CMSampleBufferRef數據,找到CVPixelBufferRef,用CVMetalTextureCacheCreateTextureFromImage創建CoreVideo的Metal紋理緩存CVMetalTextureRef,最后通過CVMetalTextureGetTexture得到Metal的紋理;
這個過程與Metal入門教程(一)圖片繪制使用device newTextureWithDescriptor創建紋理,再通過texture replaceRegion的方式上傳紋理數據類似,但是性能上有提升。

4、渲染處理
- (void)drawInMTKView:(MTKView *)view {
    if (self.texture) {
        id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer]; // 創建指令緩沖
        id<MTLTexture> drawingTexture = view.currentDrawable.texture; // 把MKTView作為目標紋理
        
        MPSImageGaussianBlur *filter = [[MPSImageGaussianBlur alloc] initWithDevice:self.mtkView.device sigma:1]; // 這里的sigma值可以修改,sigma值越高圖像越模糊
        [filter encodeToCommandBuffer:commandBuffer sourceTexture:self.texture destinationTexture:drawingTexture]; // 把攝像頭返回圖像數據的原始數據
        
        [commandBuffer presentDrawable:view.currentDrawable]; // 展示數據
        [commandBuffer commit];
        
        self.texture = NULL;
    }
}

這也是demo的核心內容,MetalPerformanceShaders是Metal的一個集成庫,有一些濾鏡處理的Metal實現,demo選用其中的高斯模糊處理MPSImageGaussianBlur;
MPSImageGaussianBlur以一個Metal紋理作為輸入,以一個Metal紋理作為輸出;
這里的輸入是從攝像頭采集的圖像,也即是第三步創建的紋理;輸出的紋理是MTKViewcurrentDrawable.texture;
在繪制完之后調用presentDrawable:展示渲染結果。

注意事項

1、運行后Crash,提示frameBufferOnly texture not supported for compute
這是因為MTKViewdrawable紋理默認是只用來展示渲染結果,只允許作為framebuffer attachments,需要設置framebufferOnly為NO;

self.mtkView.framebufferOnly = NO;

2、圖像顯示異常,偏綠or偏藍
如果MTLPixelFormatBGRA8Unorm和攝像頭采集時設置的顏色格式不一致,則會出現圖像異常的情況,以下兩行代碼需要設置同樣的格式:

    [self.mCaptureDeviceOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];

    CVReturn status = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, self.textureCache, pixelBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &tmpTexture);

3、圖像顯示異常,倒置or旋轉
如果出現圖像朝向異常的情況,可以通過下面的兩種方式進行修改:

  • 修改AVCaptureConnection的朝向:
    [connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
  • 或者給MTKView增加旋轉變換:
    self.mtkView.transform = CGAffineTransformMakeRotation(M_PI / 2);

總結

本文有兩個核心點:CVPixelBufferRef創建Metal紋理以及MetalPerformanceShaders的使用和理解,這兩個點也引入后續Metal更復雜的能力,分別是視頻渲染和自定義Shader計算。
同時從這個demo可以看到相對OpenGL,Metal對圖像的處理更為方便,代碼也更為精簡。
代碼的地址在這里,歡迎交流。

好玩的Metal
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容