我有一个正在运行的AVCaptureSession,使用一个AVCaptureVideoPreviewLayer。
我可以看到视频,所以我知道它正在工作。
但是,我想要一个集合视图,在每个单元格中添加一个预览层,以便每个单元格显示视频的预览。
如果我尝试将预览层传递到单元格并将其添加为子层,则会从其他单元格中删除该层,因此它始终只在一个单元格中显示。
是否有另一种(更好的)方法来实现这一点?
我有一个正在运行的AVCaptureSession,使用一个AVCaptureVideoPreviewLayer。
我可以看到视频,所以我知道它正在工作。
但是,我想要一个集合视图,在每个单元格中添加一个预览层,以便每个单元格显示视频的预览。
如果我尝试将预览层传递到单元格并将其添加为子层,则会从其他单元格中删除该层,因此它始终只在一个单元格中显示。
是否有另一种(更好的)方法来实现这一点?
我遇到了需要同时显示多个实时视图的问题。使用UIImage的答案对我所需的速度太慢了。这里有两个解决方案:
第一个选择是使用CAReplicatorLayer自动复制层。如文档所述,它会自动创建“...指定数量的其子层(源层)副本,每个副本可能应用几何、时间和颜色变换。”
如果除了简单的几何或颜色变换(类似照片展示)以外没有与实时预览互动的情况,那么这个功能非常有用。我经常看到CAReplicatorLayer被用来创建“反射”效果。
以下是一些示例代码,用于复制CACaptureVideoPreviewLayer:
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[previewLayer setFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height / 4)];
注意:这将把实时预览层复制四次。
NSUInteger replicatorInstances = 4;
CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
replicatorLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / replicatorInstances);
replicatorLayer.instanceCount = instances;
replicatorLayer.instanceTransform = CATransform3DMakeTranslation(0.0, self.view.bounds.size.height / replicatorInstances, 0.0);
注:根据我的经验,您需要将要复制的图层作为子图层添加到CAReplicatorLayer中。
[replicatorLayer addSublayer:previewLayer];
[self.view.layer addSublayer:replicatorLayer];
使用CAReplicatorLayer的一个缺点是它处理图层复制的所有放置。因此,它将应用于每个实例的任何设置变换,并且所有内容都包含在内。例如:无法在两个单独的单元格中复制AVCaptureVideoPreviewLayer。
虽然这种方法可能有点复杂,但解决了CAReplicatorLayer上面提到的缺点。通过手动呈现实时预览,您可以呈现任意数量的视图。性能可能会受到影响。
注意:可能有其他渲染SampleBuffer的方法,但我选择OpenGL是因为它的性能。代码来源和改编自CIFunHouse。
以下是我的实现方式:
_eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
// Note: must be done after the all your GLKViews are properly set up
_ciContext = [CIContext contextWithEAGLContext:_eaglContext
options:@{kCIContextWorkingColorSpace : [NSNull null]}];
该队列将用于会话和代理。
self.captureSessionQueue = dispatch_queue_create("capture_session_queue", NULL);
注意:为了使内容更易读,我已删除所有设备能力检查。
dispatch_async(self.captureSessionQueue, ^(void) {
NSError *error = nil;
// get the input device and also validate the settings
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *_videoDevice = nil;
if (!_videoDevice) {
_videoDevice = [videoDevices objectAtIndex:0];
}
// obtain device input
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.videoDevice error:&error];
// obtain the preset and validate the preset
NSString *preset = AVCaptureSessionPresetMedium;
// CoreImage wants BGRA pixel format
NSDictionary *outputSettings = @{(id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA)};
// create the capture session
self.captureSession = [[AVCaptureSession alloc] init];
self.captureSession.sessionPreset = preset;
:
注意:以下代码是“神奇代码”,我们在其中创建并添加了一个 DataOutput 到 AVSession,以便通过委托拦截相机帧。这是我需要的突破口,用来解决问题。
:
// create and configure video data output
AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
videoDataOutput.videoSettings = outputSettings;
[videoDataOutput setSampleBufferDelegate:self queue:self.captureSessionQueue];
// begin configure capture session
[self.captureSession beginConfiguration];
// connect the video device input and video data and still image outputs
[self.captureSession addInput:videoDeviceInput];
[self.captureSession addOutput:videoDataOutput];
[self.captureSession commitConfiguration];
// then start everything
[self.captureSession startRunning];
});
我们使用 GLKView 来呈现实时预览。如果您需要 4 个实时预览,则需要 4 个 GLKView。
self.livePreviewView = [[GLKView alloc] initWithFrame:self.bounds context:self.eaglContext];
self.livePreviewView = NO;
因为后置摄像头的本地视频图像是以UIDeviceOrientationLandscapeLeft(即Home键在右侧)的方向显示的,所以我们需要应用一个顺时针90度的变换,以便我们可以将视频预览绘制为类似于横向视图;如果您正在使用前置摄像头,并且希望有一个镜像的预览(让用户看到自己像在镜子里),您需要应用额外的水平翻转(通过将CGAffineTransformMakeScale(-1.0,1.0)连接到旋转变换中)
self.livePreviewView.transform = CGAffineTransformMakeRotation(M_PI_2);
self.livePreviewView.frame = self.bounds;
[self addSubview: self.livePreviewView];
绑定帧缓冲区以获取帧缓冲区的宽度和高度。当在GLKView上绘制时,CIContext使用像素(而不是点)来定义边界,因此需要从帧缓冲区读取宽度和高度。
[self.livePreviewView bindDrawable];
此外,由于我们将在另一个队列(_captureSessionQueue)中访问边界,因此我们希望获取这个信息,以便我们不会从另一个线程/队列访问_videoPreviewView的属性。
_videoPreviewViewBounds = CGRectZero;
_videoPreviewViewBounds.size.width = _videoPreviewView.drawableWidth;
_videoPreviewViewBounds.size.height = _videoPreviewView.drawableHeight;
dispatch_async(dispatch_get_main_queue(), ^(void) {
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2);
// *Horizontally flip here, if using front camera.*
self.livePreviewView.transform = transform;
self.livePreviewView.frame = self.bounds;
});
注意:如果您正在使用前置摄像头,可以按此方式水平翻转实时预览:
transform = CGAffineTransformConcat(transform, CGAffineTransformMakeScale(-1.0, 1.0));
在我们设置好上下文、会话和GLK视图后,我们现在可以从AVCaptureVideoDataOutputSampleBufferDelegate方法captureOutput:didOutputSampleBuffer:fromConnection:中呈现到我们的视图中。
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
CMFormatDescriptionRef formatDesc = CMSampleBufferGetFormatDescription(sampleBuffer);
// update the video dimensions information
self.currentVideoDimensions = CMVideoFormatDescriptionGetDimensions(formatDesc);
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CIImage *sourceImage = [CIImage imageWithCVPixelBuffer:(CVPixelBufferRef)imageBuffer options:nil];
CGRect sourceExtent = sourceImage.extent;
CGFloat sourceAspect = sourceExtent.size.width / sourceExtent.size.height;
你需要引用每个GLKView及其videoPreviewViewBounds。为方便起见,我假设它们都包含在一个UICollectionViewCell中。您需要根据自己的用例进行修改。
for(CustomLivePreviewCell *cell in self.livePreviewCells) {
CGFloat previewAspect = cell.videoPreviewViewBounds.size.width / cell.videoPreviewViewBounds.size.height;
// To maintain the aspect radio of the screen size, we clip the video image
CGRect drawRect = sourceExtent;
if (sourceAspect > previewAspect) {
// use full height of the video image, and center crop the width
drawRect.origin.x += (drawRect.size.width - drawRect.size.height * previewAspect) / 2.0;
drawRect.size.width = drawRect.size.height * previewAspect;
} else {
// use full width of the video image, and center crop the height
drawRect.origin.y += (drawRect.size.height - drawRect.size.width / previewAspect) / 2.0;
drawRect.size.height = drawRect.size.width / previewAspect;
}
[cell.livePreviewView bindDrawable];
if (_eaglContext != [EAGLContext currentContext]) {
[EAGLContext setCurrentContext:_eaglContext];
}
// clear eagl view to grey
glClearColor(0.5, 0.5, 0.5, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
// set the blend mode to "source over" so that CI will use that
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
if (sourceImage) {
[_ciContext drawImage:sourceImage inRect:cell.videoPreviewViewBounds fromRect:drawRect];
}
[cell.livePreviewView display];
}
}
此解决方案使用OpenGL渲染AVCaptureVideoDataOutputSampleBufferDelegate接收的图像缓冲区,让您拥有任意数量的实时预览。
这是一个我用两种解决方案组合而成的Github项目:https://github.com/JohnnySlagle/Multiple-Camera-Feeds
实现AVCaptureSession代理方法,该方法为:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
// Get a CMSampleBuffer's Core Video image buffer for the media data
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, 0);
// Get the number of bytes per row for the pixel buffer
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
// Create a device-dependent RGB color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Create a bitmap graphics context with the sample buffer data
CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
// Create a Quartz image from the pixel data in the bitmap graphics context
CGImageRef quartzImage = CGBitmapContextCreateImage(context);
// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
// Free up the context and color space
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
// Create an image object from the Quartz image
UIImage *image = [UIImage imageWithCGImage:quartzImage scale:1.0 orientation:UIImageOrientationRight];
// Release the Quartz image
CGImageRelease(quartzImage);
return (image);
}
所以你可以在视图中添加多个ImageView,并将这些代码行添加到我之前提到的委托方法中:
UIImage *image = [self imageFromSampleBuffer:sampleBuffer];
imageViewOne.image = image;
imageViewTwo.image = image;
AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init]; [captureOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()]; [_captureSession addOutput:captureOutput];
- Raphael只需将预览层的内容设置为另一个CALayer:
CGImageRef cgImage = (__bridge CGImage)self.previewLayer.contents; self.duplicateLayer.contents = (__bridge id)cgImage;
您可以对任何Metal或OpenGL层的内容执行此操作。在我的端上,内存使用量或CPU负载没有增加。您只是复制了一个微小的指针。这不是其他“解决方案”所具有的特点。
我有一个示例项目可供下载,可以从单个相机源同时显示20个预览层。每个层都应用了不同的效果。
您可以观看该应用程序运行的视频,并下载源代码:
https://demonicactivity.blogspot.com/2017/05/developer-iphone-video-camera-wall.html?m=1
@IBOutlet var testView: UIImageView!
private var extOrientation: UIImage.Orientation = .up
然后我按照以下方式实现了AVCaptureVideoDataOutputSampleBufferDelegate:
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension CameraViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let imageBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
let ciimage : CIImage = CIImage(cvPixelBuffer: imageBuffer)
let image : UIImage = self.convert(cmage: ciimage)
DispatchQueue.main.sync(execute: {() -> Void in
testView.image = image
})
}
// Convert CIImage to CGImage
func convert(cmage:CIImage) -> UIImage
{
let context:CIContext = CIContext.init(options: nil)
let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
let image:UIImage = UIImage.init(cgImage: cgImage, scale: 1.0, orientation: extOrientation)
return image
}
对于我的目的来说,性能很好。我没有注意到新视图中有任何卡顿。
你不能有多个预览。正如苹果AVFundation所说,只能有一个输出流。我尝试了很多方法,但你就是做不到。