Swift-AVCapture视频采集

import UIKit
import AVFoundation

protocol CaptureManagerDelegate: AnyObject {
    func processSampleBuffer(sampleBuffer: CMSampleBuffer, type: AVMediaType)
}

class ZGCapture: NSObject {
    
    weak var delegate: CaptureManagerDelegate?
    
    /// 最小感光度ISO
    var minISO: Float {
        return currentDevice?.activeFormat.minISO ?? 0
    }

    /// 最大感光度ISO
    var maxISO: Float {
        return currentDevice?.activeFormat.maxISO ?? 0
    }

    /// 最小快门速度S
    var minExposureDuration: CMTime {
        return currentDevice?.activeFormat.minExposureDuration ?? .zero
    }

    /// 最大快门速度S
    var maxExposureDuration: CMTime {
        return currentDevice?.activeFormat.maxExposureDuration ?? .zero
    }
    
    var minExposureTargetBias: Float {
        return currentDevice?.minExposureTargetBias ?? .zero
    }

    var maxExposureTargetBias: Float {
        return currentDevice?.maxExposureTargetBias ?? .zero
    }
    
    /// 当前缩放
    var zoom: CGFloat {
        return currentDevice?.videoZoomFactor ?? 1
    }
    
    /// 最大缩放
    var maxZoom: CGFloat {
        return currentDevice?.maxAvailableVideoZoomFactor ?? 1
    }

    /// 最小缩放
    var minZoom: CGFloat {
        return currentDevice?.minAvailableVideoZoomFactor ?? 1
    }
    
    // MARK: - 曝光补偿
    var exposureTargetBias: Float {
        return currentDevice?.exposureTargetBias ?? .zero
    }
    
    private var autoExposureDuration: CMTime = .zero
    
    private(set) var videoDevices = [AVCaptureDevice]()
    private(set) var currentDevice: AVCaptureDevice?
    private var captureSession = AVCaptureSession()
    private var captureConnection: AVCaptureConnection?
    private var currentVideoInput: AVCaptureDeviceInput?
    private var videoQueue = DispatchQueue(label: "videoQueue")
    private var previewLayer: AVCaptureVideoPreviewLayer?
    private var currentBackDeviceIndex = 0
    
    override init() {
        super.init()
        getVideoDevices()
        initCapture(deviceIndex: 0)
    }
    
    func setPreview(preview: UIView) {
        previewLayer?.removeFromSuperlayer()
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer?.frame = preview.bounds
        previewLayer?.videoGravity = .resizeAspectFill
        preview.layer.insertSublayer(previewLayer!, at: 0)
    }
    
    func startRecordVideo() {
        startCapture()
    }
    
    func stopRecordVideo(){
        stopCapture()
    }
    
    private func startCapture() {
        if captureSession.isRunning {
            captureSession.stopRunning()
        }
        videoQueue.async {
            self.captureSession.startRunning()
        }
    }

    // 结束采集
    private func stopCapture() {
        if captureSession.isRunning {
            captureSession.stopRunning()
        }
    }

    private func getVideoDevices(){
        //广角、长焦
        var deviceTypes:[AVCaptureDevice.DeviceType] = [.builtInWideAngleCamera, .builtInTelephotoCamera]
        if #available(iOS 10.2, *) {
            //双摄广角
            deviceTypes.append(.builtInDualCamera)
        }
        if #available(iOS 11.1, *) {
            //组合
            deviceTypes.append(.builtInTrueDepthCamera)
        }
        if #available(iOS 13.0, *) {
            //超广角、超广角+广角、超广角+广角+长焦
            deviceTypes += [.builtInUltraWideCamera, .builtInDualWideCamera, .builtInTripleCamera]
        }
        let deviceSession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes, mediaType: .video, position: .back)
        videoDevices = deviceSession.devices
    }
    
    ///选择或切换后置镜头
    func initCapture(deviceIndex: Int){
        guard deviceIndex < videoDevices.count else {
            return
        }
        let videoDevice = videoDevices[deviceIndex]
        currentBackDeviceIndex = deviceIndex
        DispatchQueue.global().async {
            self.initDevice(device: videoDevice)
        }
    }
    
    ///切换前后置摄像头
    func switchPosition(position: AVCaptureDevice.Position){
        if position == .front,
           let device = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .front).devices.first  {
            setTorchMode(mode: .off)
            initDevice(device: device)
        }
        else{
            initCapture(deviceIndex: currentBackDeviceIndex)
        }
    }
    

    private func initDevice(device: AVCaptureDevice){
        let isRestoration = captureSession.isRunning
        stopCapture()
        // 设置输入源
        guard let videoInput = try? AVCaptureDeviceInput(device: device) else {
            return
        }
        // 记录当前采集设备
        currentDevice = device
        autoExposureDuration = device.exposureDuration
        
        // 设置输出源
        let videoOutput = AVCaptureVideoDataOutput()
        videoOutput.setSampleBufferDelegate(self, queue: videoQueue)
        // 抛弃过期帧
        videoOutput.alwaysDiscardsLateVideoFrames = true
        // 设置输出格式
        videoOutput.videoSettings = [
            kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange),
        ]
        
        captureSession.beginConfiguration()
        //移除旧源
        if let currentVideoDeviceInput = captureSession.inputs.first as? AVCaptureDeviceInput {
            captureSession.removeInput(currentVideoDeviceInput)
        }
        if let currentVideoOutput = captureSession.outputs.first {
            captureSession.removeOutput(currentVideoOutput)
        }
        //添加源
        if captureSession.canAddInput(videoInput) {
            captureSession.addInput(videoInput)
            currentVideoInput = videoInput
        }
        if captureSession.canAddOutput(videoOutput) {
            captureSession.addOutput(videoOutput)
        }
        captureSession.commitConfiguration()

        captureConnection = videoOutput.connection(with: AVMediaType.video)
        // 视频录制方向
        setupVideoOrientation(orientation: .portrait)
        
        if isRestoration {
            startCapture()
        }
    }
    
    private func setupVideoOrientation(deviceOrientation: UIDeviceOrientation) {
        // 设置视频方向
        var videoOrientation: AVCaptureVideoOrientation = .portrait
        switch deviceOrientation {
            case .portrait:
                videoOrientation = .portrait
            case .portraitUpsideDown:
                videoOrientation = .portraitUpsideDown
            case .landscapeLeft:
                videoOrientation = .landscapeLeft
            case .landscapeRight:
                videoOrientation = .landscapeRight
            default:
                break
        }
        self.setupVideoOrientation(orientation: videoOrientation)
    }

    /// 设置视频方向
    private func setupVideoOrientation(orientation: AVCaptureVideoOrientation) {
        if (self.captureConnection?.isVideoOrientationSupported ?? false) {
            captureConnection?.videoOrientation = orientation
        }
    }
    
//设置分辨率和帧率,因为耗时,在未设置完又beginConfiguration会出错,所以加个Queue用于取消
    private let setResolutionAndFpsQueue = DispatchQueue(label: "serialQueue")
    private var workItem: DispatchWorkItem?
    func setResolutionAndFps(width: Int, height: Int, frameRate: Float64) {
        workItem?.cancel()
        workItem = DispatchWorkItem { [self] in
            guard let captureDevice = currentDevice else { return }
            let size = CGSize(width: width, height: height)
            for vFormat in captureDevice.formats {
                let maxRate = vFormat.videoSupportedFrameRateRanges.first?.maxFrameRate ?? 30
                guard maxRate >= frameRate else { continue }
                let description = vFormat.formatDescription
                let dims = CMVideoFormatDescriptionGetDimensions(description)
                //分辨率
                if dims.width == Int32(size.width) && dims.height == Int32(size.height) {
                    //帧率
                    captureSession.beginConfiguration()
                    do {
                        try captureDevice.lockForConfiguration()
                        captureDevice.activeFormat = vFormat
                        captureDevice.activeVideoMinFrameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate))
                        captureDevice.activeVideoMaxFrameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate))
                        captureDevice.unlockForConfiguration()
                        captureSession.commitConfiguration()
                        break
                    } catch {
                        captureSession.commitConfiguration()
                    }
                }
            }
            print("设置分辨率:\(size) 帧率:\(frameRate)")
        }
        setResolutionAndFpsQueue.async(execute: workItem!)
    }
    
    /// 设置ISO/快门自动
    func setAutoMode() {
        guard let currentDevice = currentDevice,
              currentDevice.isExposureModeSupported(.autoExpose)
        else { return }

        try? currentDevice.lockForConfiguration()
        currentDevice.setExposureModeCustom(duration: autoExposureDuration, iso: currentDevice.iso) { [weak currentDevice] _ in
            currentDevice?.exposureMode = .autoExpose
            currentDevice?.unlockForConfiguration()
        }
    }
    /// 感光度 ISO
    func setISO(value: Float) {
        guard let currentDevice = currentDevice else {
            return
        }
        try? currentDevice.lockForConfiguration()
        let clampedISO = min(max(value, minISO), maxISO) // 确保ISO值在范围内
        currentDevice.setExposureModeCustom(duration: AVCaptureDevice.currentExposureDuration, iso: clampedISO, completionHandler: nil)
        currentDevice.unlockForConfiguration()
    }
    /// 快门速度
    func setShutterSpeed(value: Float) {
        guard let currentDevice = currentDevice else {
            return
        }
        let maxValue = maxExposureDuration.seconds
        let minValue = minExposureDuration.seconds
        let value = Double(value)

        var duration: CMTime
        if value < minValue {
            duration = minExposureDuration
        } else if value > maxValue {
            duration = maxExposureDuration
        } else {
            let scale: Int32 = 10000
            let v = max(Int64(value * Double(scale)), 1)
            duration = CMTimeMake(value: v, timescale: scale)
        }

        try? currentDevice.lockForConfiguration()
        currentDevice.setExposureModeCustom(duration: duration, iso: currentDevice.iso) { [weak currentDevice] _ in
            currentDevice?.exposureMode = .custom
            currentDevice?.unlockForConfiguration()
        }
    }
    
    // 对焦模式
    func setFocus(mode: AVCaptureDevice.FocusMode, point: CGPoint? = nil) {
        guard let currentDevice = currentDevice,
              currentDevice.isFocusModeSupported(mode)
        else { return }
        try? currentDevice.lockForConfiguration()
        if currentDevice.isFocusPointOfInterestSupported,
           let point = point,
           let castPoint = previewLayer?.captureDevicePointConverted(fromLayerPoint: point) {
            currentDevice.focusPointOfInterest = castPoint
        }
        currentDevice.focusMode = mode
        currentDevice.unlockForConfiguration()
    }
    
    func setFocus(lensPosition: Float) {
        guard let currentDevice = currentDevice,
              currentDevice.isLockingFocusWithCustomLensPositionSupported
        else { return }
        try? currentDevice.lockForConfiguration()
        currentDevice.setFocusModeLocked(lensPosition: lensPosition)
        currentDevice.unlockForConfiguration()
    }
    
    // 设置曝光量 EV (-8 -- 8)
    func setExposure(value: Float) {
        guard let currentDevice = currentDevice,
              currentDevice.isExposureModeSupported(.locked)
        else { return }
        try? currentDevice.lockForConfiguration()
        currentDevice.setExposureTargetBias(value)
        currentDevice.unlockForConfiguration()
    }
    
    /// 设置白平衡模式 WB
    func setWhiteBalance(mode: AVCaptureDevice.WhiteBalanceMode) {
        guard let currentDevice = currentDevice,
              currentDevice.isWhiteBalanceModeSupported(mode)
        else { return }
        try? currentDevice.lockForConfiguration()
        currentDevice.whiteBalanceMode = mode
        currentDevice.unlockForConfiguration()
    }

    /// 设置白平衡量 WB
    func setWhiteBalance(temperature: Float) {
        guard let currentDevice = currentDevice,
              currentDevice.isWhiteBalanceModeSupported(.locked)
        else { return }
        
        let temperatureAndTintValues = AVCaptureDevice.WhiteBalanceTemperatureAndTintValues(temperature: temperature, tint: 0)
        let whiteBalanceGains = currentDevice.deviceWhiteBalanceGains(for: temperatureAndTintValues)

        let maxWhiteBalanceGain = currentDevice.maxWhiteBalanceGain
        var fixWhiteBalanceGains = whiteBalanceGains
        fixWhiteBalanceGains.redGain = max(1.0, min(maxWhiteBalanceGain, whiteBalanceGains.redGain))
        fixWhiteBalanceGains.greenGain = max(1.0, min(maxWhiteBalanceGain, whiteBalanceGains.greenGain))
        fixWhiteBalanceGains.blueGain = max(1.0, min(maxWhiteBalanceGain, whiteBalanceGains.blueGain))
        
        try? currentDevice.lockForConfiguration()
        currentDevice.setWhiteBalanceModeLocked(with: fixWhiteBalanceGains)
        currentDevice.unlockForConfiguration()
    }
    ///缩放
    func setZoom(factor: CGFloat){
        guard let currentDevice = currentDevice else { return }

        let minZoom = currentDevice.minAvailableVideoZoomFactor
        let maxZoom = currentDevice.maxAvailableVideoZoomFactor
        let zoom = min(maxZoom, max(factor, minZoom))
        try? currentDevice.lockForConfiguration()
        currentDevice.ramp(toVideoZoomFactor: zoom, withRate: 4.0)
        currentDevice.unlockForConfiguration()
    }
    
    ///闪光灯
    func setTorchMode(mode: AVCaptureDevice.TorchMode){
        guard let currentDevice = currentDevice else { return }
        try? currentDevice.lockForConfiguration()
        currentDevice.torchMode = mode
        currentDevice.unlockForConfiguration()
    }
    
}

extension ZGCapture: AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate {
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        
        if connection == captureConnection {
            // sampleBuffer 就是我们拿到的画面,美颜等操作都是对 sampleBuffer 进行的
//            print("已经采集视频—-video")
            
            delegate?.processSampleBuffer(sampleBuffer: sampleBuffer, type: .video)
            
        } else {
            print("已经采集音频--audio")
        }
        
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容