iOS音視頻開發(fā)一 視頻采集

1. 簡述

在音視頻開發(fā)中,我們首先看到的就是視頻的采集,在視頻采集里,我們也要區(qū)分平臺,例如android,iOS,PC。在本章的介紹中,我們集中介紹下iOS音視頻開發(fā)相關(guān)能力。


直播全鏈路流程

從圖里,我們可以看到,在整個直播架構(gòu)體系里面,最開始的就是采集,之后就是編碼,封裝,推流,轉(zhuǎn)發(fā),拉流,解碼,渲染。
我們今天先從第一個,采集開始,為你們系統(tǒng)介紹iOS視頻采集相關(guān)流程。

2. 視頻采集流程

iOS采集器的基本結(jié)構(gòu)圖如下:


iOS采集相關(guān)架構(gòu)圖

從圖里可以看到,我們可以通過AVCapture Device Input創(chuàng)建輸入資源,通過Session搭配AVCaptureMovieFileOutput(或者AVCaptureStillImageOutput)來進(jìn)行資源的輸出,也可以通過AVCaptureVideoPreviewLayer來進(jìn)行預(yù)覽。本章,我們就簡要的介紹下這全流程。

類名字 具體功能
AVCaptureDevice 輸入設(shè)備,例如攝像頭,麥克風(fēng)。
: AVCaptureInput 輸入適配接口層,使用其子類。
AVCaptureOutput 輸出適配接口層,使用其子類,這里是用的是AVCaptureVideoDataOutput。
AVCaptureSession 輸出輸入鏈接層,用于管理兩者的管理者。
AVCaptureVideoPreviewLayer 可用于預(yù)覽的layer。
  • 創(chuàng)建Session
// 管理輸入和輸出映射的采集器
AVCaptureSession* session = [[AVCaptureSession alloc] init];
  • 獲取系統(tǒng)設(shè)備指針
// 獲取系統(tǒng)設(shè)備信息
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;
   }
}

相關(guān)函數(shù)原型介紹:

@interface AVCaptureDeviceDiscoverySession
/*!
 * @brief 創(chuàng)建相關(guān)的采集設(shè)備
 * @param deviceTypes 設(shè)備的類型,可參考AVCaptureDeviceType相關(guān)變量,后續(xù)在做詳細(xì)的解釋。
 * @param mediaType 需要采集的視頻格式,音頻或者視頻。
 * @param position 采集攝像頭的方位,前置或者后置。
 * @return 成功則返回相關(guān)的采集設(shè)備。
 */
+ (instancetype)discoverySessionWithDeviceTypes:(NSArray<AVCaptureDeviceType> *)deviceTypes mediaType:(nullable AVMediaType)mediaType position:(AVCaptureDevicePosition)position;
@end

到此,可以獲取到相關(guān)的采集設(shè)備指針,該指針可用于創(chuàng)建創(chuàng)建輸入。

  • 配置Session

之后,我們需要配置Session,以至于其能夠很好的對接從device過來的輸入,然后轉(zhuǎn)換為我們需要的輸出。

[self.session beginConfiguration];

// 從設(shè)備中創(chuàng)建輸入,之后需要設(shè)置到session
NSError* error = nil;
self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
if (error) {
    NSLog(@"%s:%d init input error!!!", __func__, __LINE__);
    return;
}

// 設(shè)置session的輸入
if ([self.session canAddInput:self.videoInput]) {
    [self.session addInput:self.videoInput];
}

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

// 禁止丟幀
self.videoOutput.alwaysDiscardsLateVideoFrames = NO;

// 設(shè)置輸出的PixelBuffer的類型,這里可以設(shè)置為:
// kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
// kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
// kCVPixelFormatType_32BGRA
[self.videoOutput setVideoSettings:@{(__bridge NSString*)kCVPixelBufferPixelFormatTypeKey:@(self.config.pixelBufferType)}];

// 設(shè)置output的數(shù)據(jù)回調(diào),需要為AVCaptureVideoDataOutputSampleBufferDelegate協(xié)議的實(shí)現(xiàn)者。
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];
}

// 設(shè)置連接器
AVCaptureConnection* connect = [self.videoOutput connectionWithMediaType:AVMediaTypeVideo];
// 設(shè)置圖源的顯示方位,具體可以參考AVCaptureVideoOrientation枚舉。
connect.videoOrientation = self.config.orientation;
if ([connect isVideoStabilizationSupported]) {
    connect.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
}
// 設(shè)置圖片的縮放程度,實(shí)際上的效果不如設(shè)置Layer的頂點(diǎn)位置。
connect.videoScaleAndCropFactor = connect.videoMaxScaleAndCropFactor;

[self.session commitConfiguration];
  • 開始采集
- (void)startCapture {
    if (self.session) {
        [self.session startRunning];
    }
}
  • 停止采集
- (void)stopCapture {
    if (self.session) {
        [self.session stopRunning];
    }
}
  • 配置數(shù)據(jù)回調(diào)
#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];
    }
}

結(jié)果展示圖

結(jié)果展示圖

總結(jié)

到此,我們就完成了iOS的端上采集全部流程,當(dāng)然,這里只是簡單的介紹了一下,如何通過AVCaptureSession獲取到對應(yīng)的CMSampleBufferRef,后續(xù),我們需要使用這個來進(jìn)行相對應(yīng)的編碼。

附加

  1. 關(guān)于如何設(shè)置采集幀率
    我們需要配置相關(guān)的device,以使他能夠根據(jù)相關(guān)時間戳出幀。
// 設(shè)置幀率
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. 如何設(shè)置分辨率
    分辨率的設(shè)置需要在AVCaptureSession里面進(jìn)行設(shè)置。具體代碼如下:
// 設(shè)置視頻分辨率
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];

參考文獻(xiàn)

iOS - 視頻采集詳解
官方文檔


github

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容