前言
Metal入門教程(一)圖片繪制
Metal入門教程(二)三維變換
前面的教程介紹了如何繪制一張圖片和如何把圖片顯示到3D物體上并進(jìn)行三維變換,這次介紹如何用Metal渲染攝像頭采集到的圖像。
Metal系列教程的代碼地址;
OpenGL ES系列教程在這里;
你的star和fork是我的源動(dòng)力,你的意見(jiàn)能讓我走得更遠(yuǎn)。
正文
核心思路
用AVFoundation
采集攝像頭數(shù)據(jù)得到CMSampleBufferRef
,用CoreVideo
提供的方法將圖像數(shù)據(jù)轉(zhuǎn)為Metal的紋理,再用MetalPerformanceShaders
的高斯模糊濾鏡對(duì)圖像進(jìn)行處理,結(jié)果展示到屏幕上。
效果展示
具體步驟
1、Metal相關(guān)設(shè)置
- (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);
}
除了正常創(chuàng)建和初始化MTKView
之外,這里還多兩行代碼:
- 設(shè)置
MTKView
的dramwable紋理是可讀寫的;(默認(rèn)是只讀) - 創(chuàng)建
CVMetalTextureCacheRef _textureCache
,這是Core Video的Metal紋理緩存;
2、攝像頭采集設(shè)置
- (void)setupCaptureSession {
self.mCaptureSession = [[AVCaptureSession alloc] init];
self.mCaptureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
self.mProcessQueue = dispatch_queue_create("mProcessQueue", DISPATCH_QUEUE_SERIAL); // 串行隊(duì)列
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];
// 這里設(shè)置格式為BGRA,而不用YUV的顏色空間,避免使用Shader轉(zhuǎn)換
[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]; // 設(shè)置方向
[self.mCaptureSession startRunning];
}
創(chuàng)建AVCaptureSession
、AVCaptureDeviceInput
和AVCaptureVideoDataOutput
,注意在創(chuàng)建AVCaptureVideoDataOutput
時(shí),需要指定內(nèi)容格式,這里使用的是BGRA的格式;
同時(shí)需要設(shè)定采集的方向,否則圖像會(huì)出現(xiàn)旋轉(zhuǎn);
3、攝像頭采集回調(diào)
- (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和攝像頭采集時(shí)設(shè)置的顏色格式不一致,則會(huì)出現(xiàn)圖像異常的情況;
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的核心內(nèi)容,攝像頭回傳CMSampleBufferRef
數(shù)據(jù),找到CVPixelBufferRef
,用CVMetalTextureCacheCreateTextureFromImage
創(chuàng)建CoreVideo的Metal紋理緩存CVMetalTextureRef
,最后通過(guò)CVMetalTextureGetTexture
得到Metal的紋理;
這個(gè)過(guò)程與Metal入門教程(一)圖片繪制使用device newTextureWithDescriptor
創(chuàng)建紋理,再通過(guò)texture replaceRegion
的方式上傳紋理數(shù)據(jù)類似,但是性能上有提升。
4、渲染處理
- (void)drawInMTKView:(MTKView *)view {
if (self.texture) {
id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer]; // 創(chuàng)建指令緩沖
id<MTLTexture> drawingTexture = view.currentDrawable.texture; // 把MKTView作為目標(biāo)紋理
MPSImageGaussianBlur *filter = [[MPSImageGaussianBlur alloc] initWithDevice:self.mtkView.device sigma:1]; // 這里的sigma值可以修改,sigma值越高圖像越模糊
[filter encodeToCommandBuffer:commandBuffer sourceTexture:self.texture destinationTexture:drawingTexture]; // 把攝像頭返回圖像數(shù)據(jù)的原始數(shù)據(jù)
[commandBuffer presentDrawable:view.currentDrawable]; // 展示數(shù)據(jù)
[commandBuffer commit];
self.texture = NULL;
}
}
這也是demo的核心內(nèi)容,MetalPerformanceShaders
是Metal的一個(gè)集成庫(kù),有一些濾鏡處理的Metal實(shí)現(xiàn),demo選用其中的高斯模糊處理MPSImageGaussianBlur
;
MPSImageGaussianBlur
以一個(gè)Metal紋理作為輸入,以一個(gè)Metal紋理作為輸出;
這里的輸入是從攝像頭采集的圖像,也即是第三步創(chuàng)建的紋理;輸出的紋理是MTKView
的currentDrawable.texture
;
在繪制完之后調(diào)用presentDrawable:
展示渲染結(jié)果。
注意事項(xiàng)
1、運(yùn)行后Crash,提示frameBufferOnly texture not supported for compute
這是因?yàn)?code>MTKView的drawable
紋理默認(rèn)是只用來(lái)展示渲染結(jié)果,只允許作為framebuffer attachments
,需要設(shè)置framebufferOnly
為NO;
self.mtkView.framebufferOnly = NO;
2、圖像顯示異常,偏綠or偏藍(lán)
如果MTLPixelFormatBGRA8Unorm和攝像頭采集時(shí)設(shè)置的顏色格式不一致,則會(huì)出現(xiàn)圖像異常的情況,以下兩行代碼需要設(shè)置同樣的格式:
[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旋轉(zhuǎn)
如果出現(xiàn)圖像朝向異常的情況,可以通過(guò)下面的兩種方式進(jìn)行修改:
- 修改
AVCaptureConnection
的朝向:
[connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
- 或者給MTKView增加旋轉(zhuǎn)變換:
self.mtkView.transform = CGAffineTransformMakeRotation(M_PI / 2);
總結(jié)
本文有兩個(gè)核心點(diǎn):從CVPixelBufferRef
創(chuàng)建Metal紋理以及MetalPerformanceShaders
的使用和理解,這兩個(gè)點(diǎn)也引入后續(xù)Metal更復(fù)雜的能力,分別是視頻渲染和自定義Shader計(jì)算。
同時(shí)從這個(gè)demo可以看到相對(duì)OpenGL,Metal對(duì)圖像的處理更為方便,代碼也更為精簡(jiǎn)。
代碼的地址在這里,歡迎交流。