VideoService.swift 15.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/*
 *  Copyright (C) 2018 Savoir-faire Linux Inc.
 *
 *  Author: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */

import Foundation
import SwiftyBeaver
import RxSwift
import UIKit
import AVFoundation

typealias DeviceInfo = [String: String]

enum VideoError: Error {
    case getPermissionFailed
    case needPermission
    case selectDeviceFailed
    case setupInputDeviceFailed
    case setupOutputDeviceFailed
    case getConnectionFailed
    case unsupportedParameter
    case startCaptureFailed
    case switchCameraFailed
}

protocol FrameExtractorDelegate: class {
    func captured(image: UIImage)
}

class FrameExtractor: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {

47 48 49 50
    let nameLandscape = "frontCameraLanscape"
    let namePortrait = "frontCameraPortrait"
    let nameCamera = "camera://"

51 52 53
    private let log = SwiftyBeaver.self

    private let quality = AVCaptureSession.Preset.medium
54
    private var orientation = AVCaptureVideoOrientation.portrait
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

    var permissionGranted = Variable<Bool>(false)

    lazy var permissionGrantedObservable: Observable<Bool> = {
        return self.permissionGranted.asObservable()
    }()

    private let sessionQueue = DispatchQueue(label: "session queue")
    private let captureSession = AVCaptureSession()
    private let context = CIContext()

    weak var delegate: FrameExtractorDelegate?

    override init() {
        super.init()
    }

72
    func getDeviceInfo(forPosition position: AVCaptureDevice.Position, orientation: UIDeviceOrientation) throws -> DeviceInfo {
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        guard self.permissionGranted.value else {
            throw VideoError.needPermission
        }
        self.captureSession.sessionPreset = self.quality
        guard let captureDevice = self.selectCaptureDevice(withPosition: position) else {
            throw VideoError.selectDeviceFailed
        }
        let formatDescription = captureDevice.activeFormat.formatDescription
        let dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription)
        var bestRate = 30.0
        for vFormat in captureDevice.formats {
            var ranges = vFormat.videoSupportedFrameRateRanges as [AVFrameRateRange]
            let frameRates = ranges[0]
            if frameRates.maxFrameRate > bestRate {
                bestRate = frameRates.maxFrameRate
            }
        }
90 91 92 93 94 95 96 97 98 99 100 101 102
        if orientation == .portrait || orientation == .portraitUpsideDown {
            let devInfo: DeviceInfo = ["format": "BGRA",
                                       "width": String(dimensions.height),
                                       "height": String(dimensions.width),
                                       "rate": String(bestRate)]
            return devInfo
        } else {
            let devInfo: DeviceInfo = ["format": "BGRA",
                                       "width": String(dimensions.width),
                                       "height": String(dimensions.height),
                                       "rate": String(bestRate)]
            return devInfo
        }
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    }

    func startCapturing() {
        sessionQueue.async { [unowned self] in
            self.captureSession.startRunning()
        }
    }

    func stopCapturing() {
        sessionQueue.async { [unowned self] in
            self.captureSession.stopRunning()
        }
    }

    func checkPermission() {
        switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) {
        case .authorized:
            self.permissionGranted.value = true
        case .notDetermined:
            requestPermission()
        default:
            self.permissionGranted.value = false
        }
    }

    private func requestPermission() {
        sessionQueue.suspend()
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { [unowned self] granted in
            self.permissionGranted.value = granted
            self.sessionQueue.resume()
        }
    }

136 137
    func configureSession(withPosition position: AVCaptureDevice.Position,
                          withOrientation orientation: AVCaptureVideoOrientation) throws {
138 139 140 141 142 143 144 145 146 147 148 149 150 151
        captureSession.beginConfiguration()
        guard self.permissionGranted.value else {
            throw VideoError.needPermission
        }
        captureSession.sessionPreset = quality
        guard let captureDevice = selectCaptureDevice(withPosition: position) else {
            throw VideoError.selectDeviceFailed
        }
        let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
        guard captureSession.canAddInput(captureDeviceInput) else {
            throw VideoError.setupInputDeviceFailed
        }
        captureSession.addInput(captureDeviceInput)
        let videoOutput = AVCaptureVideoDataOutput()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
152
        videoOutput.setSampleBufferDelegate(self, queue: sessionQueue)
153 154 155 156 157 158 159 160 161 162 163 164 165
        guard captureSession.canAddOutput(videoOutput) else {
            throw VideoError.setupOutputDeviceFailed
        }
        captureSession.addOutput(videoOutput)
        guard let connection = videoOutput.connection(with: AVFoundation.AVMediaType.video) else {
            throw VideoError.getConnectionFailed
        }
        guard connection.isVideoOrientationSupported else {
            throw VideoError.unsupportedParameter
        }
        guard connection.isVideoMirroringSupported else {
            throw VideoError.unsupportedParameter
        }
166
        connection.videoOrientation = orientation
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        connection.isVideoMirrored = position == .front
        captureSession.commitConfiguration()
    }

    func selectCaptureDevice(withPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let devices = AVCaptureDevice.devices(for: AVMediaType.video)
        for device in devices where device.position == position {
            return device
        }
        return nil
    }

    func switchCamera() -> Completable {
        return Completable.create { [unowned self] completable in
            self.captureSession.beginConfiguration()
            guard let currentCameraInput: AVCaptureInput = self.captureSession.inputs.first else {
                completable(.error(VideoError.switchCameraFailed))
                return Disposables.create {}
            }
            self.captureSession.removeInput(currentCameraInput)
            var newCamera: AVCaptureDevice! = nil
            if let input = currentCameraInput as? AVCaptureDeviceInput {
                if input.device.position == .back {
                    newCamera = self.selectCaptureDevice(withPosition: .front)
                } else {
                    newCamera = self.selectCaptureDevice(withPosition: .back)
                }
            }
            var newVideoInput: AVCaptureDeviceInput!
            do {
                newVideoInput = try AVCaptureDeviceInput(device: newCamera)
            } catch {
                completable(.error(VideoError.switchCameraFailed))
                return Disposables.create { }
            }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
            if self.captureSession.canAddInput(newVideoInput) {
                self.captureSession.addInput(newVideoInput)
                guard let currentCameraOutput: AVCaptureOutput = self.captureSession.outputs.first else {
                    completable(.error(VideoError.switchCameraFailed))
                    return Disposables.create {}
                }
                guard let connection = currentCameraOutput.connection(with: AVFoundation.AVMediaType.video) else {
                    completable(.error(VideoError.switchCameraFailed))
                    return Disposables.create {}
                }
                guard connection.isVideoOrientationSupported else {
                    completable(.error(VideoError.switchCameraFailed))
                    return Disposables.create {}
                }
                guard connection.isVideoMirroringSupported else {
                    completable(.error(VideoError.switchCameraFailed))
                    return Disposables.create {}
                }
220
                connection.videoOrientation = self.orientation
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
221 222 223 224 225
                self.captureSession.commitConfiguration()
                completable(.completed)
            } else {
                completable(.error(VideoError.switchCameraFailed))
            }
226 227 228 229
            return Disposables.create { }
        }
    }

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    func rotateCamera(orientation: AVCaptureVideoOrientation) -> Completable {
        return Completable.create { [unowned self] completable in
            guard self.permissionGranted.value else {
                completable(.error(VideoError.needPermission))
                return Disposables.create {}
            }
            self.captureSession.beginConfiguration()
            let videoOutput = self.captureSession.outputs[0]
            guard let connection = videoOutput.connection(with: AVFoundation.AVMediaType.video) else {
                completable(.error(VideoError.getConnectionFailed))
                return Disposables.create {}
            }
            guard connection.isVideoOrientationSupported else {
                completable(.error(VideoError.unsupportedParameter))
                return Disposables.create {}
            }
            self.orientation = orientation
            connection.videoOrientation = orientation
            self.captureSession.commitConfiguration()
            completable(.completed)
            return Disposables.create { }
        }
    }

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    // MARK: Sample buffer to UIImage conversion
    private func imageFromSampleBuffer(sampleBuffer: CMSampleBuffer) -> UIImage? {
        guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
        let ciImage = CIImage(cvPixelBuffer: imageBuffer)
        guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
        return UIImage(cgImage: cgImage)
    }

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        guard let uiImage = imageFromSampleBuffer(sampleBuffer: sampleBuffer) else { return }
        DispatchQueue.main.async { [unowned self] in
            self.delegate?.captured(image: uiImage)
        }
    }
}

class VideoService: FrameExtractorDelegate {

    fileprivate let videoAdapter: VideoAdapter
    fileprivate let camera = FrameExtractor()

    var cameraPosition = AVCaptureDevice.Position.front
    let incomingVideoFrame = PublishSubject<UIImage?>()
    let capturedVideoFrame = PublishSubject<UIImage?>()

    private let log = SwiftyBeaver.self
280
    private var blockOutgoingFrame = true
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    fileprivate let disposeBag = DisposeBag()

    init(withVideoAdapter videoAdapter: VideoAdapter) {
        self.videoAdapter = videoAdapter
        VideoAdapter.delegate = self
        camera.delegate = self
    }

    func setupInputs() {
        self.camera.permissionGrantedObservable
            .subscribe(onNext: { granted in
                if granted {
                    self.enumerateVideoInputDevices()
                }
            })
            .disposed(by: self.disposeBag)
        // Will trigger enumerateVideoInputDevices once permission is granted
        camera.checkPermission()
    }

    private func enumerateVideoInputDevices() {
        do {
304
            try camera.configureSession(withPosition: AVCaptureDevice.Position.front, withOrientation: AVCaptureVideoOrientation.portrait)
305
            self.log.debug("Camera successfully configured")
306 307 308 309 310
            let frontLandscapeCameraDevInfo: [String: String] = try camera.getDeviceInfo(forPosition: AVCaptureDevice.Position.front, orientation: .landscapeLeft)
            let frontPortraitCameraDevInfo: [String: String] = try camera.getDeviceInfo(forPosition: AVCaptureDevice.Position.front, orientation: .portrait)
            videoAdapter.addVideoDevice(withName: camera.nameLandscape, withDevInfo: frontLandscapeCameraDevInfo)
            videoAdapter.addVideoDevice(withName: camera.namePortrait, withDevInfo: frontPortraitCameraDevInfo)

311 312 313 314 315 316
        } catch let e as VideoError {
            self.log.error("Error during capture device enumeration: \(e)")
        } catch {
            self.log.error("Unkonwn error configuring capture device")
        }
    }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
317 318 319 320 321

    func switchCamera() {
        self.camera.switchCamera()
            .subscribe(onCompleted: {
            print ("camera switched")
322
        }) { error in
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
323 324 325
            print(error)
        }.disposed(by: self.disposeBag)
    }
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    func setCameraOrientation(orientation: UIDeviceOrientation) {
        self.blockOutgoingFrame = true
        let deviceName: String =
            (orientation == .landscapeLeft || orientation == .landscapeRight) ?
                self.camera.nameLandscape : self.camera.namePortrait
        self.switchInput(toDevice: self.camera.nameCamera + deviceName)
        var newOrientation: AVCaptureVideoOrientation
        switch orientation {
        case .portrait:
            newOrientation = AVCaptureVideoOrientation.portrait
        case .portraitUpsideDown:
            newOrientation = AVCaptureVideoOrientation.portraitUpsideDown
        case .landscapeLeft:
            newOrientation = AVCaptureVideoOrientation.landscapeRight
        case .landscapeRight:
            newOrientation = AVCaptureVideoOrientation.landscapeLeft
        default:
            newOrientation = AVCaptureVideoOrientation.portrait
        }
        self.camera.rotateCamera(orientation: newOrientation)
            .subscribe(onCompleted: { [unowned self] in
                self.log.debug("new camera orientation: \(orientation)")
            }, onError: { error in
                self.log.debug("camera re-orientation error: \(error)")
            }).disposed(by: self.disposeBag)
    }
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
}

extension VideoService: VideoAdapterDelegate {
    func switchInput(toDevice device: String) {
        videoAdapter.switchInput(device)
    }

    func setDecodingAccelerated(withState state: Bool) {
        videoAdapter.setDecodingAccelerated(false)
    }

    func decodingStarted(withRendererId rendererId: String, withWidth width: Int, withHeight height: Int) {
        self.log.debug("Decoding started...")
        videoAdapter.registerSinkTarget(withSinkId: rendererId, withWidth: width, withHeight: height)
    }

    func decodingStopped(withRendererId rendererId: String) {
        self.log.debug("Decoding stopped...")
        videoAdapter.removeSinkTarget(withSinkId: rendererId)
    }

    func startCapture(withDevice device: String) {
        self.log.debug("Capture started...")
        self.camera.startCapturing()
377
        self.blockOutgoingFrame = false
378 379 380 381 382 383 384 385 386 387 388 389 390
    }

    func stopCapture() {
        self.log.debug("Capture stopped...")
        self.camera.stopCapturing()
    }

    func writeFrame(withImage image: UIImage?) {
        self.incomingVideoFrame.onNext(image)
    }

    func captured(image: UIImage) {
        self.capturedVideoFrame.onNext(image)
391 392 393 394
        if self.blockOutgoingFrame {
            return
        }
        videoAdapter.writeOutgoingFrame(with: image)
395 396
    }
}