iOS音视频开发一 视频采集

1. 简述

在音视频开发中,我们首先看到的就是视频的采集,在视频采集里,我们也要区分平台,例如android,iOS,PC。在本章的介绍中,我们集中介绍下iOS音视频开发相关能力。


直播全链路流程

从图里,我们可以看到,在整个直播架构体系里面,最开始的就是采集,之后就是编码,封装,推流,转发,拉流,解码,渲染。
我们今天先从第一个,采集开始,为你们系统介绍iOS视频采集相关流程。

2. 视频采集流程

iOS采集器的基本结构图如下:


iOS采集相关架构图

从图里可以看到,我们可以通过AVCapture Device Input创建输入资源,通过Session搭配AVCaptureMovieFileOutput(或者AVCaptureStillImageOutput)来进行资源的输出,也可以通过AVCaptureVideoPreviewLayer来进行预览。本章,我们就简要的介绍下这全流程。

类名字 具体功能
AVCaptureDevice 输入设备,例如摄像头,麦克风。
: AVCaptureInput 输入适配接口层,使用其子类。
AVCaptureOutput 输出适配接口层,使用其子类,这里是用的是AVCaptureVideoDataOutput。
AVCaptureSession 输出输入链接层,用于管理两者的管理者。
AVCaptureVideoPreviewLayer 可用于预览的layer。
  • 创建Session
// 管理输入和输出映射的采集器
AVCaptureSession* session = [[AVCaptureSession alloc] init];
  • 获取系统设备指针
// 获取系统设备信息
AVCaptureDeviceDiscoverySession* deviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:self.config.position];
NSArray* devices = deviceDiscoverySession.devices;
for (AVCaptureDevice* device in devices) {
   if (device.position == self.config.position) {
       self.device = device;
       break;
   }
}

相关函数原型介绍:

@interface AVCaptureDeviceDiscoverySession
/*!
 * @brief 创建相关的采集设备
 * @param deviceTypes 设备的类型,可参考AVCaptureDeviceType相关变量,后续在做详细的解释。
 * @param mediaType 需要采集的视频格式,音频或者视频。
 * @param position 采集摄像头的方位,前置或者后置。
 * @return 成功则返回相关的采集设备。
 */
+ (instancetype)discoverySessionWithDeviceTypes:(NSArray *)deviceTypes mediaType:(nullable AVMediaType)mediaType position:(AVCaptureDevicePosition)position;
@end

到此,可以获取到相关的采集设备指针,该指针可用于创建创建输入。

  • 配置Session

之后,我们需要配置Session,以至于其能够很好的对接从device过来的输入,然后转换为我们需要的输出。

[self.session beginConfiguration];

// 从设备中创建输入,之后需要设置到session
NSError* error = nil;
self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
if (error) {
    NSLog(@"%s:%d init input error!!!", __func__, __LINE__);
    return;
}

// 设置session的输入
if ([self.session canAddInput:self.videoInput]) {
    [self.session addInput:self.videoInput];
}

// 配置session的输出
self.videoOutput = [[AVCaptureVideoDataOutput alloc] init];

// 禁止丢帧
self.videoOutput.alwaysDiscardsLateVideoFrames = NO;

// 设置输出的PixelBuffer的类型,这里可以设置为:
// kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
// kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
// kCVPixelFormatType_32BGRA
[self.videoOutput setVideoSettings:@{(__bridge NSString*)kCVPixelBufferPixelFormatTypeKey:@(self.config.pixelBufferType)}];

// 设置output的数据回调,需要为AVCaptureVideoDataOutputSampleBufferDelegate协议的实现者。
dispatch_queue_t captureQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
[self.videoOutput setSampleBufferDelegate:self queue:captureQueue];
if ([self.session canAddOutput:self.videoOutput]) {
    [self.session addOutput:self.videoOutput];
}

// 设置连接器
AVCaptureConnection* connect = [self.videoOutput connectionWithMediaType:AVMediaTypeVideo];
// 设置图源的显示方位,具体可以参考AVCaptureVideoOrientation枚举。
connect.videoOrientation = self.config.orientation;
if ([connect isVideoStabilizationSupported]) {
    connect.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
}
// 设置图片的缩放程度,实际上的效果不如设置Layer的顶点位置。
connect.videoScaleAndCropFactor = connect.videoMaxScaleAndCropFactor;

[self.session commitConfiguration];
  • 开始采集
- (void)startCapture {
    if (self.session) {
        [self.session startRunning];
    }
}
  • 停止采集
- (void)stopCapture {
    if (self.session) {
        [self.session stopRunning];
    }
}
  • 配置数据回调
#pragma mark AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    if (self.delegate && [self.delegate respondsToSelector:@selector(onVideoWithSampleBuffer:)]) {
        [self.delegate onVideoWithSampleBuffer:sampleBuffer];
    }
}

结果展示图

结果展示图

总结

到此,我们就完成了iOS的端上采集全部流程,当然,这里只是简单的介绍了一下,如何通过AVCaptureSession获取到对应的CMSampleBufferRef,后续,我们需要使用这个来进行相对应的编码。

附加

  1. 关于如何设置采集帧率
    我们需要配置相关的device,以使他能够根据相关时间戳出帧。
// 设置帧率
BOOL frameRateSupport = NO;
NSArray* ranges = [self.device.activeFormat videoSupportedFrameRateRanges];
for (AVFrameRateRange* range in ranges) {
    if (CMTIME_COMPARE_INLINE(self.config.duration, >=, range.minFrameDuration) &&
        CMTIME_COMPARE_INLINE(self.config.duration, <=, range.maxFrameDuration)) {
        frameRateSupport = YES;
    }
}
    
if (frameRateSupport && [self.device lockForConfiguration:&error]) {
    [self.device setActiveVideoMaxFrameDuration:self.config.duration];
    [self.device setActiveVideoMinFrameDuration:self.config.duration];
    [self.device unlockForConfiguration];
}
  1. 如何设置分辨率
    分辨率的设置需要在AVCaptureSession里面进行设置。具体代码如下:
// 设置视频分辨率
if (![self.session canSetSessionPreset:self.config.preset]) {
    if (![self.session canSetSessionPreset:AVCaptureSessionPresetiFrame960x540]) {
        if (![self.session canSetSessionPreset:AVCaptureSessionPreset640x480]) {
            // no support
            NSLog(@"%s:%d capture no support", __func__, __LINE__);
            return;
        } else {
            self.config.preset = AVCaptureSessionPreset640x480;
        }
    } else {
        self.config.preset = AVCaptureSessionPresetiFrame960x540;
    }
}
[self.session setSessionPreset:self.config.preset];

参考文献

iOS - 视频采集详解
官方文档


github

你可能感兴趣的:(iOS音视频开发一 视频采集)