前言
Metal入門教程(一)圖片繪制
Metal入門教程(二)三維變換
前面的教程介紹了如何繪制一張圖片和如何把圖片顯示到3D物體上并進行三維變換,這次介紹如何用Metal渲染攝像頭采集到的圖像。
Metal系列教程的代碼地址;
OpenGL ES系列教程在這里;
你的star和fork是我的源動力,你的意見能讓我走得更遠。
正文
核心思路
用AVFoundation
采集攝像頭數據得到CMSampleBufferRef
,用CoreVideo
提供的方法將圖像數據轉為Metal的紋理,再用MetalPerformanceShaders
的高斯模糊濾鏡對圖像進行處理,結果展示到屏幕上。
效果展示
具體步驟
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
、AVCaptureDeviceInput
和AVCaptureVideoDataOutput
,注意在創建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紋理作為輸出;
這里的輸入是從攝像頭采集的圖像,也即是第三步創建的紋理;輸出的紋理是MTKView
的currentDrawable.texture
;
在繪制完之后調用presentDrawable:
展示渲染結果。
注意事項
1、運行后Crash,提示frameBufferOnly texture not supported for compute
這是因為MTKView
的drawable
紋理默認是只用來展示渲染結果,只允許作為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對圖像的處理更為方便,代碼也更為精簡。
代碼的地址在這里,歡迎交流。