2021-05-06 06:11:55 -06:00
|
|
|
//
|
|
|
|
// RecordingSession.swift
|
|
|
|
// VisionCamera
|
|
|
|
//
|
|
|
|
// Created by Marc Rousavy on 01.05.21.
|
2021-06-01 05:07:57 -06:00
|
|
|
// Copyright © 2021 mrousavy. All rights reserved.
|
2021-05-06 06:11:55 -06:00
|
|
|
//
|
|
|
|
|
|
|
|
import AVFoundation
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
// MARK: - BufferType
|
|
|
|
|
2021-06-07 05:08:40 -06:00
|
|
|
enum BufferType {
|
2021-05-06 06:11:55 -06:00
|
|
|
case audio
|
|
|
|
case video
|
|
|
|
}
|
|
|
|
|
2021-06-09 06:56:56 -06:00
|
|
|
// MARK: - RecordingSessionError
|
|
|
|
|
|
|
|
enum RecordingSessionError: Error {
|
|
|
|
case failedToStartSession
|
|
|
|
}
|
|
|
|
|
2021-05-06 06:11:55 -06:00
|
|
|
// MARK: - RecordingSession
|
|
|
|
|
|
|
|
class RecordingSession {
|
|
|
|
private let assetWriter: AVAssetWriter
|
2021-06-03 06:16:02 -06:00
|
|
|
private var audioWriter: AVAssetWriterInput?
|
|
|
|
private var bufferAdaptor: AVAssetWriterInputPixelBufferAdaptor?
|
2021-05-06 06:11:55 -06:00
|
|
|
private let completionHandler: (AVAssetWriter.Status, Error?) -> Void
|
|
|
|
|
2021-06-03 06:16:02 -06:00
|
|
|
private var initialTimestamp: CMTime?
|
2021-05-06 06:11:55 -06:00
|
|
|
private var latestTimestamp: CMTime?
|
|
|
|
private var hasWrittenFirstVideoFrame = false
|
|
|
|
|
|
|
|
var url: URL {
|
|
|
|
return assetWriter.outputURL
|
|
|
|
}
|
|
|
|
|
|
|
|
var duration: Double {
|
2021-06-03 06:16:02 -06:00
|
|
|
guard let latestTimestamp = latestTimestamp,
|
|
|
|
let initialTimestamp = initialTimestamp else {
|
2021-05-06 06:11:55 -06:00
|
|
|
return 0.0
|
|
|
|
}
|
|
|
|
return (latestTimestamp - initialTimestamp).seconds
|
|
|
|
}
|
|
|
|
|
|
|
|
init(url: URL,
|
|
|
|
fileType: AVFileType,
|
|
|
|
completion: @escaping (AVAssetWriter.Status, Error?) -> Void) throws {
|
2021-06-03 06:16:02 -06:00
|
|
|
completionHandler = completion
|
|
|
|
|
2021-05-06 06:11:55 -06:00
|
|
|
do {
|
|
|
|
assetWriter = try AVAssetWriter(outputURL: url, fileType: fileType)
|
|
|
|
} catch let error as NSError {
|
|
|
|
throw CameraError.capture(.createRecorderError(message: error.description))
|
|
|
|
}
|
2021-06-03 06:16:02 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
|
|
|
if assetWriter.status == .writing {
|
|
|
|
ReactLogger.log(level: .info, message: "Cancelling AssetWriter...", alsoLogToJS: true)
|
|
|
|
assetWriter.cancelWriting()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-09 06:56:56 -06:00
|
|
|
/**
|
|
|
|
Initializes an AssetWriter for video frames (CMSampleBuffers).
|
|
|
|
*/
|
2021-06-03 06:16:02 -06:00
|
|
|
func initializeVideoWriter(withSettings settings: [String: Any], isVideoMirrored: Bool) {
|
|
|
|
guard !settings.isEmpty else {
|
|
|
|
ReactLogger.log(level: .error, message: "Tried to initialize Video Writer with empty settings!", alsoLogToJS: true)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
guard bufferAdaptor == nil else {
|
|
|
|
ReactLogger.log(level: .error, message: "Tried to add Video Writer twice!", alsoLogToJS: true)
|
|
|
|
return
|
|
|
|
}
|
2021-05-06 06:11:55 -06:00
|
|
|
|
2021-06-03 06:16:02 -06:00
|
|
|
let videoWriter = AVAssetWriterInput(mediaType: .video, outputSettings: settings)
|
2021-05-06 06:11:55 -06:00
|
|
|
videoWriter.expectsMediaDataInRealTime = true
|
2021-06-03 06:16:02 -06:00
|
|
|
|
2021-05-06 06:11:55 -06:00
|
|
|
if isVideoMirrored {
|
|
|
|
videoWriter.transform = CGAffineTransform(rotationAngle: -(.pi / 2))
|
|
|
|
} else {
|
|
|
|
videoWriter.transform = CGAffineTransform(rotationAngle: .pi / 2)
|
|
|
|
}
|
|
|
|
|
|
|
|
assetWriter.add(videoWriter)
|
2021-06-03 06:16:02 -06:00
|
|
|
bufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriter, withVideoSettings: settings)
|
|
|
|
ReactLogger.log(level: .info, message: "Initialized Video AssetWriter.")
|
2021-05-06 06:11:55 -06:00
|
|
|
}
|
|
|
|
|
2021-06-09 06:56:56 -06:00
|
|
|
/**
|
|
|
|
Initializes an AssetWriter for audio frames (CMSampleBuffers).
|
|
|
|
*/
|
2021-06-03 06:16:02 -06:00
|
|
|
func initializeAudioWriter(withSettings settings: [String: Any]) {
|
|
|
|
guard !settings.isEmpty else {
|
|
|
|
ReactLogger.log(level: .error, message: "Tried to initialize Audio Writer with empty settings!", alsoLogToJS: true)
|
|
|
|
return
|
2021-05-06 06:11:55 -06:00
|
|
|
}
|
2021-06-03 06:16:02 -06:00
|
|
|
guard audioWriter == nil else {
|
|
|
|
ReactLogger.log(level: .error, message: "Tried to add Audio Writer twice!", alsoLogToJS: true)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
audioWriter = AVAssetWriterInput(mediaType: .audio, outputSettings: settings)
|
|
|
|
audioWriter!.expectsMediaDataInRealTime = true
|
|
|
|
assetWriter.add(audioWriter!)
|
|
|
|
ReactLogger.log(level: .info, message: "Initialized Audio AssetWriter.")
|
|
|
|
}
|
|
|
|
|
2021-06-09 06:56:56 -06:00
|
|
|
/**
|
|
|
|
Start the Asset Writer(s). If the AssetWriter failed to start, an error will be thrown.
|
|
|
|
*/
|
|
|
|
func start() throws {
|
|
|
|
ReactLogger.log(level: .info, message: "Starting Asset Writer(s)...")
|
|
|
|
|
|
|
|
let success = assetWriter.startWriting()
|
|
|
|
if !success {
|
|
|
|
ReactLogger.log(level: .error, message: "Failed to start Asset Writer(s)!")
|
|
|
|
throw RecordingSessionError.failedToStartSession
|
|
|
|
}
|
|
|
|
|
2021-06-03 06:16:02 -06:00
|
|
|
initialTimestamp = CMTime(seconds: CACurrentMediaTime(), preferredTimescale: 1_000_000_000)
|
|
|
|
assetWriter.startSession(atSourceTime: initialTimestamp!)
|
|
|
|
ReactLogger.log(level: .info, message: "Started RecordingSession at \(initialTimestamp!.seconds) seconds.")
|
2021-05-06 06:11:55 -06:00
|
|
|
}
|
|
|
|
|
2021-06-09 06:56:56 -06:00
|
|
|
/**
|
|
|
|
Appends a new CMSampleBuffer to the Asset Writer. Use bufferType to specify if this is a video or audio frame.
|
|
|
|
The timestamp parameter represents the presentation timestamp of the buffer, which should be synchronized across video and audio frames.
|
|
|
|
*/
|
2021-06-03 06:50:08 -06:00
|
|
|
func appendBuffer(_ buffer: CMSampleBuffer, type bufferType: BufferType, timestamp: CMTime) {
|
2021-06-09 06:56:56 -06:00
|
|
|
guard assetWriter.status == .writing else {
|
|
|
|
ReactLogger.log(level: .error, message: "Frame arrived, but AssetWriter status is \(assetWriter.status.descriptor)!")
|
|
|
|
return
|
|
|
|
}
|
2021-05-06 06:11:55 -06:00
|
|
|
if !CMSampleBufferDataIsReady(buffer) {
|
2021-06-09 06:56:56 -06:00
|
|
|
ReactLogger.log(level: .error, message: "Frame arrived, but sample buffer is not ready!")
|
2021-05-06 06:11:55 -06:00
|
|
|
return
|
|
|
|
}
|
2021-06-03 06:16:02 -06:00
|
|
|
guard let initialTimestamp = initialTimestamp else {
|
|
|
|
ReactLogger.log(level: .error,
|
2021-06-07 05:08:40 -06:00
|
|
|
message: "A frame arrived, but initialTimestamp was nil. Is this RecordingSession running?",
|
2021-06-03 06:16:02 -06:00
|
|
|
alsoLogToJS: true)
|
|
|
|
return
|
|
|
|
}
|
2021-05-06 06:11:55 -06:00
|
|
|
|
|
|
|
latestTimestamp = timestamp
|
|
|
|
|
|
|
|
switch bufferType {
|
|
|
|
case .video:
|
2021-06-03 06:16:02 -06:00
|
|
|
guard let bufferAdaptor = bufferAdaptor else {
|
|
|
|
ReactLogger.log(level: .error, message: "Video Frame arrived but VideoWriter was nil!", alsoLogToJS: true)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !bufferAdaptor.assetWriterInput.isReadyForMoreMediaData {
|
|
|
|
ReactLogger.log(level: .warning,
|
|
|
|
message: "The Video AVAssetWriterInput was not ready for more data! Is your frame rate too high?",
|
|
|
|
alsoLogToJS: true)
|
2021-05-06 06:11:55 -06:00
|
|
|
return
|
|
|
|
}
|
|
|
|
guard let imageBuffer = CMSampleBufferGetImageBuffer(buffer) else {
|
2021-06-03 06:16:02 -06:00
|
|
|
ReactLogger.log(level: .error, message: "Failed to get the CVImageBuffer!", alsoLogToJS: true)
|
2021-05-06 06:11:55 -06:00
|
|
|
return
|
|
|
|
}
|
|
|
|
bufferAdaptor.append(imageBuffer, withPresentationTime: timestamp)
|
|
|
|
if !hasWrittenFirstVideoFrame {
|
|
|
|
hasWrittenFirstVideoFrame = true
|
2021-06-09 06:56:56 -06:00
|
|
|
ReactLogger.log(level: .warning, message: "VideoWriter: First frame arrived \((initialTimestamp - timestamp).seconds) seconds late.")
|
2021-05-06 06:11:55 -06:00
|
|
|
}
|
|
|
|
case .audio:
|
2021-06-03 06:16:02 -06:00
|
|
|
guard let audioWriter = audioWriter else {
|
|
|
|
ReactLogger.log(level: .error, message: "Audio Frame arrived but AudioWriter was nil!", alsoLogToJS: true)
|
|
|
|
return
|
|
|
|
}
|
2021-05-06 06:11:55 -06:00
|
|
|
if !audioWriter.isReadyForMoreMediaData {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !hasWrittenFirstVideoFrame {
|
|
|
|
// first video frame has not been written yet, so skip this audio frame.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
audioWriter.append(buffer)
|
|
|
|
}
|
|
|
|
|
|
|
|
if assetWriter.status == .failed {
|
2021-06-03 06:16:02 -06:00
|
|
|
ReactLogger.log(level: .error,
|
|
|
|
message: "AssetWriter failed to write buffer! Error: \(assetWriter.error?.localizedDescription ?? "none")",
|
|
|
|
alsoLogToJS: true)
|
2021-06-09 06:56:56 -06:00
|
|
|
finish()
|
2021-05-06 06:11:55 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-09 06:56:56 -06:00
|
|
|
/**
|
|
|
|
Marks the AssetWriters as finished and stops writing frames. The callback will be invoked either with an error or the status "success".
|
|
|
|
*/
|
2021-05-06 06:11:55 -06:00
|
|
|
func finish() {
|
|
|
|
ReactLogger.log(level: .info, message: "Finishing Recording with AssetWriter status \"\(assetWriter.status.descriptor)\"...")
|
2021-06-09 06:56:56 -06:00
|
|
|
|
|
|
|
if !hasWrittenFirstVideoFrame {
|
|
|
|
let error = NSError(domain: "capture/aborted",
|
|
|
|
code: 1,
|
|
|
|
userInfo: [NSLocalizedDescriptionKey: "Stopped Recording Session too early, no frames have been recorded!"])
|
|
|
|
completionHandler(.failed, error)
|
|
|
|
} else if assetWriter.status == .writing {
|
2021-06-03 06:16:02 -06:00
|
|
|
bufferAdaptor?.assetWriterInput.markAsFinished()
|
|
|
|
audioWriter?.markAsFinished()
|
2021-05-06 06:11:55 -06:00
|
|
|
assetWriter.finishWriting {
|
|
|
|
self.completionHandler(self.assetWriter.status, self.assetWriter.error)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
completionHandler(assetWriter.status, assetWriter.error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|