本系列將帶來最簡單的 iOS 推流代碼,涵蓋視頻捕獲、軟編碼(faac、x264)、硬編碼(aac、h264)、美顏、flv 編碼、rtmp 協議等內容,並會陸續更新代碼解析。想入門直播技術的同學千萬別錯過。
源代碼地址:https://github.com/hardman/AWLive
通過系統相機錄制視頻來獲取音視頻數據,是推流的第一步。源碼中提供了兩種獲取數據的方法:一是使用系統自帶接口,二是使用 GPUImage。本篇先介紹第一種。
網上關於獲取視頻數據的代碼不少,但為了方便閱讀,這裡做簡要說明。
[注意] 請仔細閱讀代碼註釋。
整套推流代碼的入口是 AWAVCaptureManager,它是一個工廠類,根據參數創建上述兩種數據獲取方法。通過設置 captureType 就能決定使用哪種方式。
typedef enum : NSUInteger {
AWAVCaptureTypeNone,
AWAVCaptureTypeSystem,
AWAVCaptureTypeGPUImage,
} AWAVCaptureType;
@interface AWAVCaptureManager : NSObject
// 視頻捕獲類型
@property (nonatomic, unsafe_unretained) AWAVCaptureType captureType;
@property (nonatomic, weak) AWAVCapture *avCapture;
// 省略其他代碼
@end
設置好 captureType 後,就能通過 avCapture 拿到正確的捕獲對象。
AWAVCapture 是一個虛基類(C++ 中的說法,指不會直接產生對象、只用來被繼承的類,在 Java 中稱為抽象類),它的兩個子類分別是 AWSystemAVCapture 和 AWGPUImageAVCapture,這裡用到了多態。
如果 captureType 設為 AWAVCaptureTypeSystem,avCapture 拿到的真實對象就是 AWSystemAVCapture 類型;如果設為 AWAVCaptureTypeGPUImage,拿到的就是 AWGPUImageAVCapture 類型。
AWSystemAVCapture 類的功能只有一個:調用系統相機,獲取音視頻數據。
分為三個步驟:
1. 初始化輸入輸出設備。
2. 創建 AVCaptureSession,用來管理視頻與數據的捕獲。
3. 創建預覽 UI。
此外還包括一些其他功能:切換攝像頭、更改 fps。
對應到代碼中就是 AWSystemAVCapture 的 onInit 方法,只要初始化就會被調用。
【注意】請仔細閱讀下文代碼中的註釋。
-(void) createCaptureDevice {
// 初始化前後攝像頭
// 執行後系統會彈框提示:應用想要訪問您的相機,請點擊同意
// iOS10 還需在 info.plist 中添加 NSCameraUsageDescription,否則會閃退
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
self.frontCamera = [AVCaptureDeviceInput deviceInputWithDevice:videoDevices.firstObject error:nil];
self.backCamera = [AVCaptureDeviceInput deviceInputWithDevice:videoDevices.lastObject error:nil];
// 初始化麥克風
// 執行後系統會彈框提示:應用想要訪問您的麥克風,請點擊同意
// iOS10 還需在 info.plist 中添加 NSMicrophoneUsageDescription,否則會閃退
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
self.audioInputDevice = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
// 省略其他代碼
}
-(void) createOutput {
// 創建數據獲取線程
dispatch_queue_t captureQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 視頻數據輸出
self.videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
// 設置代理,需實現 AVCaptureVideoDataOutputSampleBufferDelegate 協議
[self.videoDataOutput setSampleBufferDelegate:self queue:captureQueue];
// 拋棄過期幀,保證實時性
[self.videoDataOutput setAlwaysDiscardsLateVideoFrames:YES];
// 設置輸出格式為 yuv420
[self.videoDataOutput setVideoSettings:@{ (__bridge NSString *)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange) }];
// 音頻數據輸出
self.audioDataOutput = [[AVCaptureAudioDataOutput alloc] init];
// 設置代理,需實現 AVCaptureAudioDataOutputSampleBufferDelegate 協議
[self.audioDataOutput setSampleBufferDelegate:self queue:captureQueue];
// 視頻與音頻的 SampleBuffer 回調方法名相同:
// captureOutput:didOutputSampleBuffer:fromConnection:
// 最終音視頻數據都可在此方法中獲取
}
// AVCaptureSession 的邏輯很簡單,它像一個中介者,從音視頻輸入設備獲取數據,處理後傳遞給輸出設備(數據代理 / 預覽 layer)
-(void) createCaptureSession {
self.captureSession = [AVCaptureSession new];
[self.captureSession beginConfiguration];
// 加入視頻輸入設備
if ([self.captureSession canAddInput:self.videoInputDevice]) {
[self.captureSession addInput:self.videoInputDevice];
}
// 加入音頻輸入設備
if ([self.captureSession canAddInput:self.audioInputDevice]) {
[self.captureSession addInput:self.audioInputDevice];
}
// 加入視頻輸出
if ([self.captureSession canAddOutput:self.videoDataOutput]) {
[self.captureSession addOutput:self.videoDataOutput];
[self setVideoOutConfig];
}
// 加入音頻輸出
if ([self.captureSession canAddOutput:self.audioDataOutput]) {
[self.captureSession addOutput:self.audioDataOutput];
}
// 設置預覽分辨率
// 注意:不同設備對分辨率的支持不同,例如 iPhone4 前置只支持 480*640,
// 後置不支持 540*960 但支持 720*1280,因此需要寫代碼管理分辨率。
// 目前處理方式:對不支持的分辨率拋出異常;更好的方案是按設備提供不同分辨率,
// 或在必須使用時對數據和預覽進行裁剪、縮放。
if (![self.captureSession canSetSessionPreset:self.captureSessionPreset]) {
@throw [NSException exceptionWithName:@"Not supported captureSessionPreset" reason:[NSString stringWithFormat:@"captureSessionPreset is [%@]", self.captureSessionPreset] userInfo:nil];
}
self.captureSession.sessionPreset = self.captureSessionPreset;
[self.captureSession commitConfiguration];
// 開始運行,此時 CaptureSession 會從輸入設備獲取數據,處理後傳給輸出設備
[self.captureSession startRunning];
}
// 其實只有一句代碼:用 AVCaptureVideoPreviewLayer 綁定 session
// 它本質上是 AVCaptureSession 的一種輸出方式,
// CaptureSession 會把從 input 得到的數據處理後顯示到此 layer 上,
// 我們可以把這個 layer 變換後加入任意 UIView
-(void) createPreviewLayer {
self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
self.previewLayer.frame = self.preview.bounds;
[self.preview.layer addSublayer:self.previewLayer];
}
-(void)setVideoInputDevice:(AVCaptureDeviceInput *)videoInputDevice {
if ([videoInputDevice isEqual:_videoInputDevice]) {
return;
}
[self.captureSession beginConfiguration];
// 移除當前輸入設備
if (_videoInputDevice) {
[self.captureSession removeInput:_videoInputDevice];
}
// 加入新的輸入設備
if (videoInputDevice) {
[self.captureSession addInput:videoInputDevice];
}
// 提交配置,至此前後攝像頭切換完成
[self.captureSession commitConfiguration];
_videoInputDevice = videoInputDevice;
}
-(void) updateFps:(NSInteger) fps {
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
// 遍歷所有設備(前後攝像頭)
for (AVCaptureDevice *vDevice in videoDevices) {
float maxRate = [(AVFrameRateRange *)[vDevice.activeFormat.videoSupportedFrameRateRanges objectAtIndex:0] maxFrameRate];
// 若要設置的 fps 小於或等於最大 fps,就進行修改
if (maxRate >= fps) {
if ([vDevice lockForConfiguration:NULL]) {
vDevice.activeVideoMinFrameDuration = CMTimeMake(10, (int)(fps * 10));
vDevice.activeVideoMaxFrameDuration = vDevice.activeVideoMinFrameDuration;
[vDevice unlockForConfiguration];
}
}
}
}
至此,我們達成了所有目標:能夠錄制視頻、預覽畫面、獲取音視頻數據、切換前後攝像頭,以及修改捕獲視頻的 fps。