Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(mobile): add cap-screen-recorder native module

Richie McIlroy40a2236acf2b
diff --git a/apps/mobile/modules/cap-screen-recorder/app.plugin.js b/apps/mobile/modules/cap-screen-recorder/app.plugin.js
new file mode 100644
index 000000000..47260b9a8
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/app.plugin.js
@@ -0,0 +1 @@
+module.exports = require("./plugin/withCapScreenRecorder");
diff --git a/apps/mobile/modules/cap-screen-recorder/expo-module.config.json b/apps/mobile/modules/cap-screen-recorder/expo-module.config.json
new file mode 100644
index 000000000..9279f7bc8
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/expo-module.config.json
@@ -0,0 +1,6 @@
+{
+ "platforms": ["apple"],
+ "apple": {
+ "modules": ["CapScreenRecorderModule"]
+ }
+}
diff --git a/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/CapScreenBroadcast.entitlements b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/CapScreenBroadcast.entitlements
new file mode 100644
index 000000000..7bbaa984d
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/CapScreenBroadcast.entitlements
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>__APP_GROUP__</string>
+ </array>
+</dict>
+</plist>
diff --git a/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/Info.plist b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/Info.plist
new file mode 100644
index 000000000..f9998da92
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/Info.plist
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CapScreenRecordingAppGroup</key>
+ <string>__APP_GROUP__</string>
+ <key>CFBundleDisplayName</key>
+ <string>Cap Screen Recording</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>XPC!</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.broadcast-services-upload</string>
+ <key>NSExtensionPrincipalClass</key>
+ <string>$(PRODUCT_MODULE_NAME).SampleHandler</string>
+ <key>RPBroadcastProcessMode</key>
+ <string>RPBroadcastProcessModeSampleBuffer</string>
+ </dict>
+</dict>
+</plist>
diff --git a/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/SampleHandler.swift b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/SampleHandler.swift
new file mode 100644
index 000000000..5fa4f28b8
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/SampleHandler.swift
@@ -0,0 +1,186 @@
+import CoreMedia
+import Foundation
+import ImageIO
+import ReplayKit
+
+final class SampleHandler: RPBroadcastSampleHandler {
+ private static let finishWaitInterval: TimeInterval = 4
+
+ private let stateLock = NSLock()
+ private var writer: SegmentedScreenWriter?
+ private var isFinishing = false
+
+ override func broadcastStarted(withSetupInfo _: [String: NSObject]?) {
+ do {
+ let (configuration, recordingsRoot) = try loadRecordingContext()
+ let writer = try SegmentedScreenWriter(
+ configuration: configuration,
+ recordingsRoot: recordingsRoot
+ ) { [weak self] in
+ self?.finishAtDurationLimit()
+ } onError: { [weak self] error in
+ self?.finishWithWriterError(error)
+ }
+ self.writer = writer
+ try writer.markRecordingStarted()
+ } catch {
+ markPreparedRecordingFailed(error)
+ finishBroadcastWithError(error)
+ }
+ }
+
+ override func broadcastFinished() {
+ guard let writer, beginFinishing() else {
+ return
+ }
+ let completion = DispatchSemaphore(value: 0)
+ writer.finish { _ in
+ completion.signal()
+ }
+ _ = completion.wait(timeout: .now() + Self.finishWaitInterval)
+ }
+
+ override func processSampleBuffer(
+ _ sampleBuffer: CMSampleBuffer,
+ with sampleBufferType: RPSampleBufferType
+ ) {
+ guard !finishing else {
+ return
+ }
+ switch sampleBufferType {
+ case .video:
+ writer?.appendVideo(
+ sampleBuffer,
+ orientation: videoOrientation(sampleBuffer)
+ )
+ case .audioMic:
+ writer?.appendMicrophoneAudio(sampleBuffer)
+ case .audioApp:
+ break
+ @unknown default:
+ break
+ }
+ }
+
+ private func finishAtDurationLimit() {
+ guard let writer, beginFinishing() else {
+ return
+ }
+ writer.finish { [weak self] result in
+ guard let self else {
+ return
+ }
+ switch result {
+ case .success:
+ self.finishBroadcastWithError(
+ NSError(
+ domain: "so.cap.mobile.screen-recorder",
+ code: 2,
+ userInfo: [
+ NSLocalizedDescriptionKey:
+ "Your screen recording reached the Free plan limit and was saved."
+ ]
+ )
+ )
+ case let .failure(error):
+ self.finishBroadcastWithError(error)
+ }
+ }
+ }
+
+ private func finishWithWriterError(_ error: Error) {
+ guard beginFinishing() else {
+ return
+ }
+ finishBroadcastWithError(error)
+ }
+
+ private var finishing: Bool {
+ stateLock.lock()
+ defer {
+ stateLock.unlock()
+ }
+ return isFinishing
+ }
+
+ private func beginFinishing() -> Bool {
+ stateLock.lock()
+ defer {
+ stateLock.unlock()
+ }
+ guard !isFinishing else {
+ return false
+ }
+ isFinishing = true
+ return true
+ }
+
+ private func loadRecordingContext() throws
+ -> (ScreenRecordingConfiguration, URL)
+ {
+ guard let appGroup = Bundle.main.object(
+ forInfoDictionaryKey: "CapScreenRecordingAppGroup"
+ ) as? String,
+ let container = FileManager.default.containerURL(
+ forSecurityApplicationGroupIdentifier: appGroup
+ )
+ else {
+ throw NSError(
+ domain: "so.cap.mobile.screen-recorder",
+ code: 1,
+ userInfo: [
+ NSLocalizedDescriptionKey: "Cap could not access the screen recording."
+ ]
+ )
+ }
+ let recordingsRoot = container.appendingPathComponent(
+ "CapScreenRecordings",
+ isDirectory: true
+ )
+ let configuration = try ScreenRecordingStore.decode(
+ ScreenRecordingConfiguration.self,
+ from: ScreenRecordingStore.activeConfigurationURL(
+ recordingsRoot: recordingsRoot
+ )
+ )
+ return (configuration, recordingsRoot)
+ }
+
+ private func markPreparedRecordingFailed(_ error: Error) {
+ guard let (configuration, recordingsRoot) = try? loadRecordingContext()
+ else {
+ return
+ }
+ let manifestURL = ScreenRecordingStore.manifestURL(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ guard var manifest = try? ScreenRecordingStore.decode(
+ ScreenRecordingManifest.self,
+ from: manifestURL
+ ) else {
+ return
+ }
+ manifest.status = "failed"
+ manifest.error = error.localizedDescription
+ manifest.uploadStartedAt = nil
+ try? ScreenRecordingStore.encode(manifest, to: manifestURL)
+ ScreenRecordingStore.removeActiveConfiguration(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ }
+
+ private func videoOrientation(
+ _ sampleBuffer: CMSampleBuffer
+ ) -> CGImagePropertyOrientation {
+ guard let rawValue = CMGetAttachment(
+ sampleBuffer,
+ key: RPVideoSampleOrientationKey as CFString,
+ attachmentModeOut: nil
+ ) as? NSNumber else {
+ return .up
+ }
+ return CGImagePropertyOrientation(rawValue: rawValue.uint32Value) ?? .up
+ }
+}
diff --git a/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/SegmentedScreenWriter.swift b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/SegmentedScreenWriter.swift
new file mode 100644
index 000000000..4bb575605
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/extension/CapScreenBroadcast/SegmentedScreenWriter.swift
@@ -0,0 +1,780 @@
+@preconcurrency import AVFoundation
+@preconcurrency import CoreMedia
+import CoreImage
+import ImageIO
+import UniformTypeIdentifiers
+
+struct ScreenRecordingConfiguration: Codable, Sendable {
+ let recordingId: String
+ let width: Int
+ let height: Int
+ let videoBitrate: Int
+ let segmentDurationSeconds: Double
+ let maximumDurationSeconds: Double?
+ let createdAt: Date
+}
+
+struct ScreenRecordingResult: Sendable {
+ let durationSeconds: Double
+ let totalBytes: Int
+}
+
+struct ScreenRecordingUploadSegment: Codable, Sendable {
+ let track: String
+ let type: String
+ let index: Int
+ let uri: String
+ let durationSeconds: Double
+ let byteLength: Int
+}
+
+struct ScreenRecordingManifest: Codable, Sendable {
+ let recordingId: String
+ var status: String
+ var segments: [ScreenRecordingUploadSegment]
+ var durationSeconds: Double?
+ var totalBytes: Int
+ var error: String?
+ var uploadStartedAt: Date?
+}
+
+enum ScreenRecordingStore {
+ static func manifestURL(
+ recordingsRoot: URL,
+ recordingId: String
+ ) -> URL {
+ recordingsRoot
+ .appendingPathComponent(recordingId, isDirectory: true)
+ .appendingPathComponent("manifest.json")
+ }
+
+ static func activeConfigurationURL(recordingsRoot: URL) -> URL {
+ recordingsRoot.appendingPathComponent("active-screen-recording.json")
+ }
+
+ static func encode<T: Encodable>(_ value: T, to url: URL) throws {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ try encoder.encode(value).write(to: url, options: .atomic)
+ }
+
+ static func decode<T: Decodable>(_ type: T.Type, from url: URL) throws -> T {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return try decoder.decode(type, from: Data(contentsOf: url))
+ }
+
+ static func removeActiveConfiguration(
+ recordingsRoot: URL,
+ recordingId: String
+ ) {
+ let url = activeConfigurationURL(recordingsRoot: recordingsRoot)
+ guard let configuration = try? decode(
+ ScreenRecordingConfiguration.self,
+ from: url
+ ), configuration.recordingId == recordingId else {
+ return
+ }
+ try? FileManager.default.removeItem(at: url)
+ }
+}
+
+private final class ScreenWriterUnavailableError: LocalizedError {
+ var errorDescription: String? {
+ "Cap could not encode the screen recording."
+ }
+}
+
+private struct UncheckedTransfer<Value>: @unchecked Sendable {
+ let value: Value
+}
+
+final class SegmentedScreenWriter:
+ NSObject,
+ AVAssetWriterDelegate,
+ @unchecked Sendable
+{
+ private let configuration: ScreenRecordingConfiguration
+ private let recordingDirectory: URL
+ private let recordingsRoot: URL
+ private let videoQueue = DispatchQueue(
+ label: "so.cap.mobile.screen-recorder.video",
+ qos: .userInitiated,
+ autoreleaseFrequency: .workItem
+ )
+ private let audioQueue = DispatchQueue(
+ label: "so.cap.mobile.screen-recorder.audio",
+ qos: .userInitiated,
+ autoreleaseFrequency: .workItem
+ )
+ private let finishQueue = DispatchQueue(
+ label: "so.cap.mobile.screen-recorder.finish",
+ qos: .userInitiated,
+ autoreleaseFrequency: .workItem
+ )
+ private let segmentQueue = DispatchQueue(
+ label: "so.cap.mobile.screen-recorder.segments",
+ qos: .utility,
+ autoreleaseFrequency: .workItem
+ )
+ private let stateLock = NSLock()
+ private let videoSlots = DispatchSemaphore(value: 2)
+ private let audioSlots = DispatchSemaphore(value: 8)
+ private let pendingSamples = DispatchGroup()
+ private let pendingSegmentWrites = DispatchGroup()
+ private let ciContext = CIContext(options: [.cacheIntermediates: false])
+ private let colorSpace = CGColorSpaceCreateDeviceRGB()
+ private let onMaximumDurationReached: @Sendable () -> Void
+ private let onError: @Sendable (Error) -> Void
+
+ private var manifest: ScreenRecordingManifest
+ private var videoWriter: AVAssetWriter?
+ private var audioWriter: AVAssetWriter?
+ private var videoInput: AVAssetWriterInput?
+ private var audioInput: AVAssetWriterInput?
+ private var pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor?
+ private var recordingStartTime: CMTime?
+ private var recordingStartedAt: Date?
+ private var latestVideoTime: CMTime?
+ private var lastAppendedVideoTime: CMTime?
+ private var lastVideoPixelBuffer: CVPixelBuffer?
+ private var videoSegmentIndex = 0
+ private var audioSegmentIndex = 0
+ private var acceptingSamples = true
+ private var isFinishing = false
+ private var maximumDurationSignalled = false
+ private var failureSignalled = false
+
+ init(
+ configuration: ScreenRecordingConfiguration,
+ recordingsRoot: URL,
+ onMaximumDurationReached: @escaping @Sendable () -> Void,
+ onError: @escaping @Sendable (Error) -> Void
+ ) throws {
+ self.configuration = configuration
+ self.recordingsRoot = recordingsRoot
+ recordingDirectory = recordingsRoot.appendingPathComponent(
+ configuration.recordingId,
+ isDirectory: true
+ )
+ self.onMaximumDurationReached = onMaximumDurationReached
+ self.onError = onError
+ manifest = try ScreenRecordingStore.decode(
+ ScreenRecordingManifest.self,
+ from: ScreenRecordingStore.manifestURL(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ )
+ super.init()
+ }
+
+ func markRecordingStarted() throws {
+ try segmentQueue.sync {
+ manifest.status = "recording"
+ manifest.error = nil
+ manifest.uploadStartedAt = nil
+ try writeManifest()
+ }
+ }
+
+ func appendVideo(
+ _ sampleBuffer: CMSampleBuffer,
+ orientation: CGImagePropertyOrientation
+ ) {
+ guard reserveSampleSlot(videoSlots) else {
+ return
+ }
+ var copiedSampleBuffer: CMSampleBuffer?
+ guard CMSampleBufferCreateCopy(
+ allocator: kCFAllocatorDefault,
+ sampleBuffer: sampleBuffer,
+ sampleBufferOut: &copiedSampleBuffer
+ ) == noErr,
+ let copiedSampleBuffer
+ else {
+ videoSlots.signal()
+ pendingSamples.leave()
+ return
+ }
+
+ let transferredSampleBuffer = UncheckedTransfer(value: copiedSampleBuffer)
+ let pendingSamples = pendingSamples
+ let videoSlots = videoSlots
+ videoQueue.async { [weak self] in
+ defer {
+ videoSlots.signal()
+ pendingSamples.leave()
+ }
+ let sampleBuffer = transferredSampleBuffer.value
+ guard let self,
+ CMSampleBufferDataIsReady(sampleBuffer),
+ let sourcePixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
+ else {
+ return
+ }
+
+ do {
+ let presentationTime = CMSampleBufferGetPresentationTimeStamp(
+ sampleBuffer
+ )
+ if let lastAppendedVideoTime = self.lastAppendedVideoTime {
+ let delta = CMTimeSubtract(
+ presentationTime,
+ lastAppendedVideoTime
+ )
+ if CMTimeCompare(delta, CMTime(value: 1, timescale: 30)) < 0 {
+ return
+ }
+ }
+ if self.videoWriter == nil {
+ try self.prepareVideoWriter(startTime: presentationTime)
+ }
+ guard self.videoWriter?.status == .writing,
+ self.videoInput?.isReadyForMoreMediaData == true,
+ let adaptor = self.pixelBufferAdaptor,
+ let pool = adaptor.pixelBufferPool
+ else {
+ return
+ }
+
+ var targetPixelBuffer: CVPixelBuffer?
+ guard CVPixelBufferPoolCreatePixelBuffer(
+ nil,
+ pool,
+ &targetPixelBuffer
+ ) == kCVReturnSuccess,
+ let targetPixelBuffer
+ else {
+ throw ScreenWriterUnavailableError()
+ }
+ try self.render(
+ sourcePixelBuffer,
+ orientation: orientation,
+ into: targetPixelBuffer
+ )
+ guard adaptor.append(
+ targetPixelBuffer,
+ withPresentationTime: presentationTime
+ ) else {
+ throw self.videoWriter?.error ?? ScreenWriterUnavailableError()
+ }
+
+ self.lastAppendedVideoTime = presentationTime
+ self.lastVideoPixelBuffer = targetPixelBuffer
+ let duration = CMSampleBufferGetDuration(sampleBuffer)
+ self.latestVideoTime = CMTimeAdd(
+ presentationTime,
+ duration.isValid && duration.isNumeric
+ ? duration
+ : CMTime(value: 1, timescale: 30)
+ )
+ self.signalMaximumDurationIfNeeded()
+ } catch {
+ self.fail(error)
+ }
+ }
+ }
+
+ func appendMicrophoneAudio(_ sampleBuffer: CMSampleBuffer) {
+ guard reserveSampleSlot(audioSlots) else {
+ return
+ }
+ var copiedSampleBuffer: CMSampleBuffer?
+ guard CMSampleBufferCreateCopy(
+ allocator: kCFAllocatorDefault,
+ sampleBuffer: sampleBuffer,
+ sampleBufferOut: &copiedSampleBuffer
+ ) == noErr,
+ let copiedSampleBuffer
+ else {
+ audioSlots.signal()
+ pendingSamples.leave()
+ return
+ }
+
+ let transferredSampleBuffer = UncheckedTransfer(value: copiedSampleBuffer)
+ let audioSlots = audioSlots
+ let pendingSamples = pendingSamples
+ audioQueue.async { [weak self] in
+ defer {
+ audioSlots.signal()
+ pendingSamples.leave()
+ }
+ let sampleBuffer = transferredSampleBuffer.value
+ guard let self,
+ CMSampleBufferDataIsReady(sampleBuffer),
+ let recordingStartTime = self.currentRecordingStartTime()
+ else {
+ return
+ }
+
+ let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
+ guard CMTimeCompare(presentationTime, recordingStartTime) >= 0 else {
+ return
+ }
+
+ do {
+ if self.audioWriter == nil {
+ try self.prepareAudioWriter(
+ startTime: recordingStartTime,
+ sourceFormatHint: CMSampleBufferGetFormatDescription(sampleBuffer)
+ )
+ }
+ guard self.audioWriter?.status == .writing,
+ self.audioInput?.isReadyForMoreMediaData == true
+ else {
+ return
+ }
+ guard self.audioInput?.append(sampleBuffer) == true else {
+ throw self.audioWriter?.error ?? ScreenWriterUnavailableError()
+ }
+ } catch {
+ self.fail(error)
+ }
+ }
+ }
+
+ func finish(
+ completion: @escaping @Sendable (
+ Result<ScreenRecordingResult, Error>
+ ) -> Void
+ ) {
+ guard stopAcceptingSamples() else {
+ return
+ }
+ pendingSamples.notify(queue: finishQueue) { [weak self] in
+ guard let self else {
+ completion(.failure(ScreenWriterUnavailableError()))
+ return
+ }
+ guard !self.isFinishing else {
+ return
+ }
+ self.isFinishing = true
+
+ guard let videoWriter = self.videoWriter,
+ videoWriter.status == .writing
+ else {
+ self.completeFailure(
+ self.videoWriter?.error ?? ScreenWriterUnavailableError(),
+ completion: completion
+ )
+ return
+ }
+
+ self.extendStaticVideoFrame()
+ self.videoInput?.markAsFinished()
+ self.audioInput?.markAsFinished()
+ let finishGroup = DispatchGroup()
+ finishGroup.enter()
+ videoWriter.finishWriting {
+ finishGroup.leave()
+ }
+ if let audioWriter = self.audioWriter, audioWriter.status == .writing {
+ finishGroup.enter()
+ audioWriter.finishWriting {
+ finishGroup.leave()
+ }
+ }
+ finishGroup.notify(queue: self.finishQueue) {
+ self.pendingSegmentWrites.notify(queue: self.segmentQueue) {
+ let audioFailed =
+ self.audioWriter != nil && self.audioWriter?.status != .completed
+ guard videoWriter.status == .completed, !audioFailed else {
+ self.completeFailure(
+ videoWriter.error ??
+ self.audioWriter?.error ??
+ ScreenWriterUnavailableError(),
+ completion: completion
+ )
+ return
+ }
+
+ let duration = self.recordingDuration()
+ self.manifest.status = "finished"
+ self.manifest.durationSeconds = duration
+ self.manifest.error = nil
+ self.manifest.uploadStartedAt = nil
+ do {
+ try self.writeManifest()
+ ScreenRecordingStore.removeActiveConfiguration(
+ recordingsRoot: self.recordingsRoot,
+ recordingId: self.configuration.recordingId
+ )
+ completion(
+ .success(
+ ScreenRecordingResult(
+ durationSeconds: duration,
+ totalBytes: self.manifest.totalBytes
+ )
+ )
+ )
+ } catch {
+ self.completeFailure(error, completion: completion)
+ }
+ }
+ }
+ }
+ }
+
+ func assetWriter(
+ _ writer: AVAssetWriter,
+ didOutputSegmentData segmentData: Data,
+ segmentType: AVAssetSegmentType,
+ segmentReport: AVAssetSegmentReport?
+ ) {
+ let track: String
+ let mediaType: AVMediaType
+ if writer === videoWriter {
+ track = "video"
+ mediaType = .video
+ } else if writer === audioWriter {
+ track = "audio"
+ mediaType = .audio
+ } else {
+ return
+ }
+
+ let pendingSegmentWrites = pendingSegmentWrites
+ pendingSegmentWrites.enter()
+ segmentQueue.async { [weak self] in
+ defer {
+ pendingSegmentWrites.leave()
+ }
+ guard let self else {
+ return
+ }
+
+ let isInitialization = segmentType == .initialization
+ let index: Int
+ let fileName: String
+ if isInitialization {
+ index = 0
+ fileName = "\(track)_init.mp4"
+ } else if track == "video" {
+ self.videoSegmentIndex += 1
+ index = self.videoSegmentIndex
+ fileName = String(format: "video_segment_%03d.m4s", index)
+ } else {
+ self.audioSegmentIndex += 1
+ index = self.audioSegmentIndex
+ fileName = String(format: "audio_segment_%03d.m4s", index)
+ }
+
+ let fileURL = self.recordingDirectory.appendingPathComponent(fileName)
+ do {
+ try segmentData.write(to: fileURL, options: .atomic)
+ let reportedDuration = segmentReport?.trackReports
+ .first(where: { $0.mediaType == mediaType })?
+ .duration.seconds
+ let duration = if isInitialization {
+ 0.0
+ } else if let reportedDuration,
+ reportedDuration.isFinite,
+ reportedDuration > 0
+ {
+ reportedDuration
+ } else {
+ self.configuration.segmentDurationSeconds
+ }
+ let segment = ScreenRecordingUploadSegment(
+ track: track,
+ type: isInitialization ? "initialization" : "media",
+ index: index,
+ uri: fileURL.absoluteString,
+ durationSeconds: duration,
+ byteLength: segmentData.count
+ )
+ self.manifest.segments.append(segment)
+ self.manifest.totalBytes += segmentData.count
+ try self.writeManifest()
+ } catch {
+ self.fail(error)
+ }
+ }
+ }
+
+ private func prepareVideoWriter(startTime: CMTime) throws {
+ let writer = AVAssetWriter(contentType: .mpeg4Movie)
+ let outputSettings: [String: Any] = [
+ AVVideoCodecKey: AVVideoCodecType.h264,
+ AVVideoWidthKey: configuration.width,
+ AVVideoHeightKey: configuration.height,
+ AVVideoCompressionPropertiesKey: [
+ AVVideoAverageBitRateKey: configuration.videoBitrate,
+ AVVideoExpectedSourceFrameRateKey: 30,
+ AVVideoMaxKeyFrameIntervalKey: 60,
+ AVVideoAllowFrameReorderingKey: false,
+ AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel
+ ]
+ ]
+ let input = AVAssetWriterInput(
+ mediaType: .video,
+ outputSettings: outputSettings
+ )
+ input.expectsMediaDataInRealTime = true
+ guard writer.canAdd(input) else {
+ throw ScreenWriterUnavailableError()
+ }
+ writer.add(input)
+ let adaptor = AVAssetWriterInputPixelBufferAdaptor(
+ assetWriterInput: input,
+ sourcePixelBufferAttributes: [
+ kCVPixelBufferPixelFormatTypeKey as String:
+ kCVPixelFormatType_32BGRA,
+ kCVPixelBufferWidthKey as String: configuration.width,
+ kCVPixelBufferHeightKey as String: configuration.height,
+ kCVPixelBufferIOSurfacePropertiesKey as String: [:]
+ ]
+ )
+ configureSegmentedWriter(writer, startTime: startTime)
+ guard writer.startWriting() else {
+ throw writer.error ?? ScreenWriterUnavailableError()
+ }
+ writer.startSession(atSourceTime: startTime)
+ videoWriter = writer
+ videoInput = input
+ pixelBufferAdaptor = adaptor
+ stateLock.lock()
+ recordingStartTime = startTime
+ recordingStartedAt = Date()
+ stateLock.unlock()
+ }
+
+ private func prepareAudioWriter(
+ startTime: CMTime,
+ sourceFormatHint: CMFormatDescription?
+ ) throws {
+ let writer = AVAssetWriter(contentType: .mpeg4Movie)
+ let outputSettings: [String: Any] = [
+ AVFormatIDKey: kAudioFormatMPEG4AAC,
+ AVSampleRateKey: 48_000,
+ AVNumberOfChannelsKey: 1,
+ AVEncoderBitRateKey: 96_000
+ ]
+ let input = AVAssetWriterInput(
+ mediaType: .audio,
+ outputSettings: outputSettings,
+ sourceFormatHint: sourceFormatHint
+ )
+ input.expectsMediaDataInRealTime = true
+ guard writer.canAdd(input) else {
+ throw ScreenWriterUnavailableError()
+ }
+ writer.add(input)
+ configureSegmentedWriter(writer, startTime: startTime)
+ guard writer.startWriting() else {
+ throw writer.error ?? ScreenWriterUnavailableError()
+ }
+ writer.startSession(atSourceTime: startTime)
+ audioWriter = writer
+ audioInput = input
+ }
+
+ private func configureSegmentedWriter(
+ _ writer: AVAssetWriter,
+ startTime: CMTime
+ ) {
+ writer.outputFileTypeProfile = .mpeg4CMAFCompliant
+ writer.preferredOutputSegmentInterval = CMTime(
+ seconds: configuration.segmentDurationSeconds,
+ preferredTimescale: 600
+ )
+ writer.initialSegmentStartTime = startTime
+ writer.shouldOptimizeForNetworkUse = true
+ writer.delegate = self
+ }
+
+ private func extendStaticVideoFrame() {
+ guard videoInput?.isReadyForMoreMediaData == true,
+ let adaptor = pixelBufferAdaptor,
+ let pixelBuffer = lastVideoPixelBuffer,
+ let startTime = recordingStartTime,
+ let startedAt = recordingStartedAt
+ else {
+ return
+ }
+
+ let frameDuration = CMTime(value: 1, timescale: 30)
+ let elapsed = max(frameDuration.seconds, Date().timeIntervalSince(startedAt))
+ let endTime = CMTimeAdd(
+ startTime,
+ CMTime(seconds: elapsed, preferredTimescale: 600)
+ )
+ let presentationTime = CMTimeSubtract(endTime, frameDuration)
+ guard let latestVideoTime,
+ CMTimeCompare(presentationTime, latestVideoTime) > 0
+ else {
+ return
+ }
+
+ guard adaptor.append(
+ pixelBuffer,
+ withPresentationTime: presentationTime
+ ) else {
+ return
+ }
+ self.latestVideoTime = endTime
+ }
+
+ private func render(
+ _ sourcePixelBuffer: CVPixelBuffer,
+ orientation: CGImagePropertyOrientation,
+ into targetPixelBuffer: CVPixelBuffer
+ ) throws {
+ let orientedImage = CIImage(cvPixelBuffer: sourcePixelBuffer)
+ .oriented(orientation)
+ let extent = orientedImage.extent
+ guard extent.width > 0, extent.height > 0 else {
+ throw ScreenWriterUnavailableError()
+ }
+ let targetBounds = CGRect(
+ x: 0,
+ y: 0,
+ width: configuration.width,
+ height: configuration.height
+ )
+ let scale = min(
+ targetBounds.width / extent.width,
+ targetBounds.height / extent.height
+ )
+ let normalized = orientedImage.transformed(
+ by: CGAffineTransform(
+ translationX: -extent.minX,
+ y: -extent.minY
+ )
+ )
+ let scaled = normalized.transformed(
+ by: CGAffineTransform(scaleX: scale, y: scale)
+ )
+ let centered = scaled.transformed(
+ by: CGAffineTransform(
+ translationX: (targetBounds.width - scaled.extent.width) / 2,
+ y: (targetBounds.height - scaled.extent.height) / 2
+ )
+ )
+ let background = CIImage(color: .black).cropped(to: targetBounds)
+ ciContext.render(
+ centered.composited(over: background),
+ to: targetPixelBuffer,
+ bounds: targetBounds,
+ colorSpace: colorSpace
+ )
+ }
+
+ private func reserveSampleSlot(_ slots: DispatchSemaphore) -> Bool {
+ stateLock.lock()
+ let canAccept = acceptingSamples
+ stateLock.unlock()
+ guard canAccept, slots.wait(timeout: .now()) == .success else {
+ return false
+ }
+ stateLock.lock()
+ let stillAccepting = acceptingSamples
+ if stillAccepting {
+ pendingSamples.enter()
+ }
+ stateLock.unlock()
+ if !stillAccepting {
+ slots.signal()
+ }
+ return stillAccepting
+ }
+
+ private func stopAcceptingSamples() -> Bool {
+ stateLock.lock()
+ defer {
+ stateLock.unlock()
+ }
+ guard acceptingSamples else {
+ return false
+ }
+ acceptingSamples = false
+ return true
+ }
+
+ private func currentRecordingStartTime() -> CMTime? {
+ stateLock.lock()
+ defer {
+ stateLock.unlock()
+ }
+ return recordingStartTime
+ }
+
+ private func signalMaximumDurationIfNeeded() {
+ guard !maximumDurationSignalled,
+ let maximumDurationSeconds = configuration.maximumDurationSeconds,
+ recordingDuration() >= maximumDurationSeconds
+ else {
+ return
+ }
+ maximumDurationSignalled = true
+ onMaximumDurationReached()
+ }
+
+ private func recordingDuration() -> Double {
+ if let recordingStartedAt {
+ return max(0.1, Date().timeIntervalSince(recordingStartedAt))
+ }
+ guard let start = recordingStartTime, let end = latestVideoTime else {
+ return 0.1
+ }
+ return max(0.1, CMTimeSubtract(end, start).seconds)
+ }
+
+ private func fail(_ error: Error) {
+ guard stopAcceptingSamples() else {
+ return
+ }
+ pendingSamples.notify(queue: finishQueue) { [weak self] in
+ guard let self, !self.failureSignalled else {
+ return
+ }
+ self.failureSignalled = true
+ self.isFinishing = true
+ self.videoWriter?.cancelWriting()
+ self.audioWriter?.cancelWriting()
+ self.segmentQueue.async {
+ self.manifest.status = "failed"
+ self.manifest.durationSeconds = self.recordingDuration()
+ self.manifest.error = error.localizedDescription
+ self.manifest.uploadStartedAt = nil
+ try? self.writeManifest()
+ ScreenRecordingStore.removeActiveConfiguration(
+ recordingsRoot: self.recordingsRoot,
+ recordingId: self.configuration.recordingId
+ )
+ self.onError(error)
+ }
+ }
+ }
+
+ private func completeFailure(
+ _ error: Error,
+ completion: @escaping @Sendable (
+ Result<ScreenRecordingResult, Error>
+ ) -> Void
+ ) {
+ manifest.status = "failed"
+ manifest.durationSeconds = recordingDuration()
+ manifest.error = error.localizedDescription
+ manifest.uploadStartedAt = nil
+ try? writeManifest()
+ ScreenRecordingStore.removeActiveConfiguration(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ completion(.failure(error))
+ }
+
+ private func writeManifest() throws {
+ try ScreenRecordingStore.encode(
+ manifest,
+ to: ScreenRecordingStore.manifestURL(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ )
+ }
+}
diff --git a/apps/mobile/modules/cap-screen-recorder/index.ts b/apps/mobile/modules/cap-screen-recorder/index.ts
new file mode 100644
index 000000000..09a343b61
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/index.ts
@@ -0,0 +1,15 @@
+export type {
+ CapScreenRecorderAvailability,
+ CapScreenRecorderSegment,
+ CapScreenRecorderStatus,
+ CapScreenRecorderUpdates,
+ CapScreenRecorderViewProps,
+ PrepareScreenRecordingOptions,
+} from "./src/CapScreenRecorder.types";
+export {
+ cancelScreenRecording,
+ getScreenRecordingAvailability,
+ getScreenRecordingUpdates,
+ prepareScreenRecording,
+} from "./src/CapScreenRecorderModule";
+export { default as CapScreenRecorderView } from "./src/CapScreenRecorderView";
diff --git a/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorder.podspec b/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorder.podspec
new file mode 100644
index 000000000..075426370
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorder.podspec
@@ -0,0 +1,15 @@
+Pod::Spec.new do |s|
+ s.name = 'CapScreenRecorder'
+ s.version = '0.1.0'
+ s.summary = 'Native iOS screen recording for Cap'
+ s.description = 'Native ReplayKit broadcast picker and shared recording bridge for Cap'
+ s.license = { :type => 'AGPL-3.0' }
+ s.author = 'Cap'
+ s.homepage = 'https://cap.so'
+ s.platforms = { :ios => '15.1' }
+ s.source = { :git => 'https://github.com/CapSoftware/Cap.git' }
+ s.static_framework = true
+ s.dependency 'ExpoModulesCore'
+ s.frameworks = 'ReplayKit'
+ s.source_files = '**/*.{h,m,mm,swift}'
+end
diff --git a/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorderModule.swift b/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorderModule.swift
new file mode 100644
index 000000000..87dbd9892
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorderModule.swift
@@ -0,0 +1,480 @@
+import ExpoModulesCore
+import ReplayKit
+
+private func bridgeValue<T>(_ value: T?) -> Any {
+ if let value {
+ return value
+ }
+ return NSNull()
+}
+
+private final class ScreenRecorderException:
+ Exception,
+ @unchecked Sendable
+{
+ private let message: String
+
+ init(_ message: String) {
+ self.message = message
+ super.init()
+ }
+
+ override var reason: String {
+ message
+ }
+}
+
+private struct PrepareScreenRecordingOptions: Record {
+ @Field var recordingId = ""
+ @Field var width = 720
+ @Field var height = 1280
+ @Field var videoBitrate = 1_800_000
+ @Field var segmentDurationSeconds = 2.0
+ @Field var maximumDurationSeconds: Double?
+}
+
+private struct ScreenRecordingConfiguration: Codable {
+ let recordingId: String
+ let width: Int
+ let height: Int
+ let videoBitrate: Int
+ let segmentDurationSeconds: Double
+ let maximumDurationSeconds: Double?
+ let createdAt: Date
+}
+
+private struct ScreenRecordingSegment: Codable {
+ let track: String
+ let type: String
+ let index: Int
+ let uri: String
+ let durationSeconds: Double
+ let byteLength: Int
+}
+
+private struct ScreenRecordingManifest: Codable {
+ let recordingId: String
+ var status: String
+ var segments: [ScreenRecordingSegment]
+ var durationSeconds: Double?
+ var totalBytes: Int
+ var error: String?
+ var uploadStartedAt: Date?
+}
+
+public final class CapScreenRecorderModule: Module {
+ private static let staleRecordingInterval: TimeInterval = 15
+ private static let stalePreparedInterval: TimeInterval = 10 * 60
+ private static let staleUploadInterval: TimeInterval = 30
+
+ public func definition() -> ModuleDefinition {
+ Name("CapScreenRecorder")
+
+ View(CapScreenRecorderView.self) {
+ Prop("enabled") { (view, enabled: Bool?) in
+ view.enabled = enabled ?? true
+ }
+ }
+
+ AsyncFunction("getAvailability") {
+ #if targetEnvironment(simulator)
+ return [
+ "available": false,
+ "minimumSystemVersion": "15.1",
+ "reason": "Screen recording requires a physical iPhone."
+ ]
+ #else
+ let available = RPScreenRecorder.shared().isAvailable
+ let reason: String? = available
+ ? nil
+ : "Screen recording is currently unavailable on this iPhone."
+ return [
+ "available": available,
+ "minimumSystemVersion": "15.1",
+ "reason": bridgeValue(reason)
+ ]
+ #endif
+ }
+
+ AsyncFunction("prepareRecording") {
+ (options: PrepareScreenRecordingOptions) in
+ try self.prepareRecording(options)
+ }
+
+ AsyncFunction("getRecordingUpdates") { (recordingId: String) in
+ try self.getRecordingUpdates(recordingId)
+ }
+
+ AsyncFunction("cancelRecording") { (recordingId: String) in
+ try self.cancelRecording(recordingId)
+ }
+ }
+
+ private func prepareRecording(
+ _ options: PrepareScreenRecordingOptions
+ ) throws {
+ try validateRecordingId(options.recordingId)
+ #if targetEnvironment(simulator)
+ throw ScreenRecorderException(
+ "Screen recording requires a physical iPhone."
+ )
+ #else
+ guard RPScreenRecorder.shared().isAvailable else {
+ throw ScreenRecorderException(
+ "Screen recording is currently unavailable on this iPhone."
+ )
+ }
+ #endif
+
+ let maximumDurationIsValid =
+ options.maximumDurationSeconds == nil ||
+ (
+ options.maximumDurationSeconds?.isFinite == true &&
+ (options.maximumDurationSeconds ?? 0) > 0
+ )
+ guard options.width >= 320,
+ options.width <= 1920,
+ options.height >= 320,
+ options.height <= 1920,
+ options.videoBitrate >= 800_000,
+ options.videoBitrate <= 4_000_000,
+ options.segmentDurationSeconds >= 1,
+ options.segmentDurationSeconds <= 6,
+ maximumDurationIsValid
+ else {
+ throw ScreenRecorderException(
+ "Cap received an invalid screen recording configuration."
+ )
+ }
+
+ let root = try recordingsRoot()
+ try recoverExistingConfiguration(recordingsRoot: root)
+ let recordingDirectory = root.appendingPathComponent(
+ options.recordingId,
+ isDirectory: true
+ )
+ if FileManager.default.fileExists(atPath: recordingDirectory.path) {
+ try FileManager.default.removeItem(at: recordingDirectory)
+ }
+ try FileManager.default.createDirectory(
+ at: recordingDirectory,
+ withIntermediateDirectories: true
+ )
+ try excludeFromBackup(recordingDirectory)
+
+ let configuration = ScreenRecordingConfiguration(
+ recordingId: options.recordingId,
+ width: options.width,
+ height: options.height,
+ videoBitrate: options.videoBitrate,
+ segmentDurationSeconds: options.segmentDurationSeconds,
+ maximumDurationSeconds: options.maximumDurationSeconds,
+ createdAt: Date()
+ )
+ let manifest = ScreenRecordingManifest(
+ recordingId: options.recordingId,
+ status: "prepared",
+ segments: [],
+ durationSeconds: nil,
+ totalBytes: 0,
+ error: nil,
+ uploadStartedAt: nil
+ )
+ try encode(
+ manifest,
+ to: manifestURL(
+ recordingsRoot: root,
+ recordingId: options.recordingId
+ )
+ )
+ try encode(configuration, to: activeConfigurationURL(root))
+ }
+
+ private func getRecordingUpdates(
+ _ recordingId: String
+ ) throws -> [String: Any] {
+ try validateRecordingId(recordingId)
+ let root = try recordingsRoot()
+ let url = manifestURL(
+ recordingsRoot: root,
+ recordingId: recordingId
+ )
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ return [
+ "status": "missing",
+ "segments": [],
+ "durationSeconds": NSNull(),
+ "totalBytes": 0,
+ "error": NSNull()
+ ]
+ }
+
+ var manifest = try decode(ScreenRecordingManifest.self, from: url)
+ try recoverStalledPreparedRecording(
+ &manifest,
+ at: url,
+ recordingsRoot: root
+ )
+ try recoverStalledRecording(
+ &manifest,
+ at: url,
+ recordingsRoot: root
+ )
+ try recoverStalledUpload(&manifest, at: url)
+ let segments: [[String: Any]] = manifest.segments.map { segment in
+ [
+ "track": segment.track,
+ "type": segment.type,
+ "index": segment.index,
+ "uri": segment.uri,
+ "durationSeconds": segment.durationSeconds,
+ "byteLength": segment.byteLength
+ ]
+ }
+ return [
+ "status": manifest.status,
+ "segments": segments,
+ "durationSeconds": bridgeValue(manifest.durationSeconds),
+ "totalBytes": manifest.totalBytes,
+ "error": bridgeValue(manifest.error)
+ ]
+ }
+
+ private func cancelRecording(_ recordingId: String) throws {
+ try validateRecordingId(recordingId)
+ let root = try recordingsRoot()
+ let recordingDirectory = root.appendingPathComponent(
+ recordingId,
+ isDirectory: true
+ )
+ let url = manifestURL(
+ recordingsRoot: root,
+ recordingId: recordingId
+ )
+ if var manifest = try? decode(ScreenRecordingManifest.self, from: url) {
+ try recoverStalledRecording(
+ &manifest,
+ at: url,
+ recordingsRoot: root
+ )
+ if ["recording", "uploading"].contains(manifest.status) {
+ throw ScreenRecorderException(
+ "Stop the screen recording before discarding it."
+ )
+ }
+ }
+ removeActiveConfiguration(
+ recordingsRoot: root,
+ recordingId: recordingId
+ )
+ if FileManager.default.fileExists(atPath: recordingDirectory.path) {
+ try FileManager.default.removeItem(at: recordingDirectory)
+ }
+ }
+
+ private func recoverExistingConfiguration(
+ recordingsRoot: URL
+ ) throws {
+ let configurationURL = activeConfigurationURL(recordingsRoot)
+ guard let configuration = try? decode(
+ ScreenRecordingConfiguration.self,
+ from: configurationURL
+ ) else {
+ return
+ }
+ let url = manifestURL(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ guard var manifest = try? decode(
+ ScreenRecordingManifest.self,
+ from: url
+ ) else {
+ try? FileManager.default.removeItem(at: configurationURL)
+ return
+ }
+ try recoverStalledRecording(
+ &manifest,
+ at: url,
+ recordingsRoot: recordingsRoot
+ )
+ if manifest.status == "recording" {
+ throw ScreenRecorderException(
+ "Another screen recording is already active."
+ )
+ }
+ if manifest.status == "prepared" {
+ manifest.status = "cancelled"
+ manifest.error = nil
+ try encode(manifest, to: url)
+ }
+ removeActiveConfiguration(
+ recordingsRoot: recordingsRoot,
+ recordingId: configuration.recordingId
+ )
+ }
+
+ private func recoverStalledPreparedRecording(
+ _ manifest: inout ScreenRecordingManifest,
+ at url: URL,
+ recordingsRoot: URL
+ ) throws {
+ guard manifest.status == "prepared",
+ age(of: url) >= Self.stalePreparedInterval
+ else {
+ return
+ }
+ manifest.status = "cancelled"
+ manifest.error = nil
+ try encode(manifest, to: url)
+ removeActiveConfiguration(
+ recordingsRoot: recordingsRoot,
+ recordingId: manifest.recordingId
+ )
+ }
+
+ private func recoverStalledRecording(
+ _ manifest: inout ScreenRecordingManifest,
+ at url: URL,
+ recordingsRoot: URL
+ ) throws {
+ guard manifest.status == "recording",
+ age(of: url) >= Self.staleRecordingInterval
+ else {
+ return
+ }
+ let videoSegments = manifest.segments.filter {
+ $0.track == "video" && $0.type == "media"
+ }
+ if videoSegments.isEmpty {
+ manifest.status = "failed"
+ manifest.error = "The screen recording stopped before video was captured."
+ } else {
+ manifest.status = "finished"
+ manifest.durationSeconds = max(
+ 0.1,
+ videoSegments.reduce(0) { $0 + $1.durationSeconds }
+ )
+ manifest.error = nil
+ }
+ manifest.uploadStartedAt = nil
+ try encode(manifest, to: url)
+ removeActiveConfiguration(
+ recordingsRoot: recordingsRoot,
+ recordingId: manifest.recordingId
+ )
+ }
+
+ private func recoverStalledUpload(
+ _ manifest: inout ScreenRecordingManifest,
+ at url: URL
+ ) throws {
+ guard manifest.status == "uploading",
+ let uploadStartedAt = manifest.uploadStartedAt,
+ Date().timeIntervalSince(uploadStartedAt) >=
+ Self.staleUploadInterval
+ else {
+ return
+ }
+ manifest.status = "finished"
+ manifest.error = nil
+ manifest.uploadStartedAt = nil
+ try encode(manifest, to: url)
+ }
+
+ private func recordingsRoot() throws -> URL {
+ guard let appGroup = Bundle.main.object(
+ forInfoDictionaryKey: "CapScreenRecordingAppGroup"
+ ) as? String,
+ let container = FileManager.default.containerURL(
+ forSecurityApplicationGroupIdentifier: appGroup
+ )
+ else {
+ throw ScreenRecorderException(
+ "Cap could not access screen recording storage."
+ )
+ }
+ let root = container.appendingPathComponent(
+ "CapScreenRecordings",
+ isDirectory: true
+ )
+ try FileManager.default.createDirectory(
+ at: root,
+ withIntermediateDirectories: true
+ )
+ try excludeFromBackup(root)
+ return root
+ }
+
+ private func activeConfigurationURL(_ recordingsRoot: URL) -> URL {
+ recordingsRoot.appendingPathComponent("active-screen-recording.json")
+ }
+
+ private func manifestURL(
+ recordingsRoot: URL,
+ recordingId: String
+ ) -> URL {
+ recordingsRoot
+ .appendingPathComponent(recordingId, isDirectory: true)
+ .appendingPathComponent("manifest.json")
+ }
+
+ private func removeActiveConfiguration(
+ recordingsRoot: URL,
+ recordingId: String
+ ) {
+ let url = activeConfigurationURL(recordingsRoot)
+ guard let configuration = try? decode(
+ ScreenRecordingConfiguration.self,
+ from: url
+ ), configuration.recordingId == recordingId else {
+ return
+ }
+ try? FileManager.default.removeItem(at: url)
+ }
+
+ private func age(of url: URL) -> TimeInterval {
+ let values = try? url.resourceValues(
+ forKeys: [.contentModificationDateKey]
+ )
+ guard let date = values?.contentModificationDate else {
+ return 0
+ }
+ return Date().timeIntervalSince(date)
+ }
+
+ private func validateRecordingId(_ recordingId: String) throws {
+ guard !recordingId.isEmpty,
+ recordingId.range(
+ of: "^[A-Za-z0-9_-]+$",
+ options: .regularExpression
+ ) != nil
+ else {
+ throw ScreenRecorderException(
+ "Cap received an invalid screen recording identifier."
+ )
+ }
+ }
+
+ private func encode<T: Encodable>(_ value: T, to url: URL) throws {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ try encoder.encode(value).write(to: url, options: .atomic)
+ }
+
+ private func decode<T: Decodable>(
+ _ type: T.Type,
+ from url: URL
+ ) throws -> T {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return try decoder.decode(type, from: Data(contentsOf: url))
+ }
+
+ private func excludeFromBackup(_ url: URL) throws {
+ var values = URLResourceValues()
+ values.isExcludedFromBackup = true
+ var mutableURL = url
+ try mutableURL.setResourceValues(values)
+ }
+}
diff --git a/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorderView.swift b/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorderView.swift
new file mode 100644
index 000000000..0dceba1b7
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/ios/CapScreenRecorderView.swift
@@ -0,0 +1,35 @@
+import ExpoModulesCore
+import ReplayKit
+
+public final class CapScreenRecorderView: ExpoView {
+ private let picker = RPSystemBroadcastPickerView(
+ frame: CGRect(x: 0, y: 0, width: 82, height: 82)
+ )
+
+ var enabled = true {
+ didSet {
+ picker.isUserInteractionEnabled = enabled
+ picker.alpha = enabled ? 1 : 0.42
+ }
+ }
+
+ public required init(appContext: AppContext? = nil) {
+ super.init(appContext: appContext)
+ backgroundColor = .clear
+ picker.backgroundColor = .clear
+ picker.showsMicrophoneButton = true
+ picker.tintColor = .clear
+ picker.preferredExtension = Bundle.main.object(
+ forInfoDictionaryKey: "CapScreenBroadcastExtensionBundleIdentifier"
+ ) as? String
+ picker.translatesAutoresizingMaskIntoConstraints = false
+ picker.accessibilityLabel = "Start screen broadcast"
+ addSubview(picker)
+ NSLayoutConstraint.activate([
+ picker.leadingAnchor.constraint(equalTo: leadingAnchor),
+ picker.trailingAnchor.constraint(equalTo: trailingAnchor),
+ picker.topAnchor.constraint(equalTo: topAnchor),
+ picker.bottomAnchor.constraint(equalTo: bottomAnchor)
+ ])
+ }
+}
diff --git a/apps/mobile/modules/cap-screen-recorder/plugin/withCapScreenRecorder.js b/apps/mobile/modules/cap-screen-recorder/plugin/withCapScreenRecorder.js
new file mode 100644
index 000000000..3c5345f05
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/plugin/withCapScreenRecorder.js
@@ -0,0 +1,312 @@
+const fs = require("node:fs");
+const path = require("node:path");
+const {
+ withDangerousMod,
+ withEntitlementsPlist,
+ withInfoPlist,
+ withXcodeProject,
+} = require("expo/config-plugins");
+
+const targetName = "CapScreenBroadcast";
+const defaultAppGroup = "group.so.cap.mobile.screen-recording";
+const defaultExtensionBundleIdentifier = "so.cap.mobile.screen-broadcast";
+
+const unquote = (value) =>
+ typeof value === "string" ? value.replace(/^"|"$/g, "") : value;
+
+const findTarget = (project) =>
+ Object.entries(project.pbxNativeTargetSection()).find(
+ ([key, value]) =>
+ !key.endsWith("_comment") && unquote(value.name) === targetName,
+ );
+
+const extensionBuildConfigurations = (project, target) => {
+ const configurationList =
+ project.pbxXCConfigurationList()[
+ target.pbxNativeTarget.buildConfigurationList
+ ];
+ const configurations = project.pbxXCBuildConfigurationSection();
+ return configurationList.buildConfigurations.map(
+ ({ value }) => configurations[value],
+ );
+};
+
+const removeSourceFromTarget = (project, targetUuid, fileName) => {
+ const sources = project.pbxSourcesBuildPhaseObj(targetUuid);
+ if (!sources) return;
+ const removedBuildFileUuids = new Set(
+ sources.files
+ .filter((file) => file.comment === `${fileName} in Sources`)
+ .map((file) => file.value),
+ );
+ sources.files = sources.files.filter(
+ (file) => !removedBuildFileUuids.has(file.value),
+ );
+ const buildFiles = project.pbxBuildFileSection();
+ for (const uuid of removedBuildFileUuids) {
+ delete buildFiles[uuid];
+ delete buildFiles[`${uuid}_comment`];
+ }
+};
+
+const configureTargetAttributes = (
+ project,
+ targetUuid,
+ developmentTeam,
+ capabilityNames,
+) => {
+ const projectObject = Object.entries(project.pbxProjectSection()).find(
+ ([key]) => !key.endsWith("_comment"),
+ )?.[1];
+ if (!projectObject) {
+ throw new Error("Cap screen recording could not find the iOS project.");
+ }
+ projectObject.attributes ??= {};
+ projectObject.attributes.TargetAttributes ??= {};
+ const targetAttributes =
+ projectObject.attributes.TargetAttributes[targetUuid] ?? {};
+ targetAttributes.ProvisioningStyle = "Automatic";
+ if (developmentTeam) {
+ targetAttributes.DevelopmentTeam = developmentTeam;
+ }
+ targetAttributes.SystemCapabilities = {
+ ...targetAttributes.SystemCapabilities,
+ ...Object.fromEntries(
+ capabilityNames.map((name) => [name, { enabled: 1 }]),
+ ),
+ };
+ projectObject.attributes.TargetAttributes[targetUuid] = targetAttributes;
+};
+
+const addExtensionTarget = (
+ project,
+ extensionBundleIdentifier,
+ deploymentTarget,
+ marketingVersion,
+ usesAppleSignIn,
+) => {
+ const applicationTargetEntry = Object.entries(
+ project.pbxNativeTargetSection(),
+ ).find(
+ ([key, value]) =>
+ !key.endsWith("_comment") &&
+ unquote(value.productType) === "com.apple.product-type.application",
+ );
+ const applicationTarget = applicationTargetEntry?.[1];
+ const applicationConfigurations = applicationTarget
+ ? extensionBuildConfigurations(project, {
+ pbxNativeTarget: applicationTarget,
+ })
+ : [];
+ const existingTarget = findTarget(project);
+ const target = existingTarget
+ ? { uuid: existingTarget[0], pbxNativeTarget: existingTarget[1] }
+ : project.addTarget(
+ targetName,
+ "app_extension",
+ targetName,
+ extensionBundleIdentifier,
+ );
+ if (existingTarget) {
+ removeSourceFromTarget(
+ project,
+ target.uuid,
+ "ScreenUploadCoordinator.swift",
+ );
+ }
+
+ for (const configuration of applicationConfigurations) {
+ configuration.buildSettings.CODE_SIGN_STYLE = "Automatic";
+ }
+ if (!existingTarget) {
+ project.addBuildPhase(
+ [
+ `${targetName}/SampleHandler.swift`,
+ `${targetName}/SegmentedScreenWriter.swift`,
+ ],
+ "PBXSourcesBuildPhase",
+ "Sources",
+ target.uuid,
+ );
+ project.addBuildPhase(
+ [
+ "AVFoundation.framework",
+ "CoreImage.framework",
+ "ImageIO.framework",
+ "ReplayKit.framework",
+ "UniformTypeIdentifiers.framework",
+ ],
+ "PBXFrameworksBuildPhase",
+ "Frameworks",
+ target.uuid,
+ );
+ }
+
+ for (const configuration of extensionBuildConfigurations(project, target)) {
+ const applicationConfiguration = applicationConfigurations.find(
+ (candidate) => candidate.name === configuration.name,
+ );
+ configuration.buildSettings.APPLICATION_EXTENSION_API_ONLY = "YES";
+ configuration.buildSettings.CODE_SIGN_ENTITLEMENTS = `"${targetName}/${targetName}.entitlements"`;
+ configuration.buildSettings.CODE_SIGN_STYLE = "Automatic";
+ configuration.buildSettings.CURRENT_PROJECT_VERSION =
+ applicationConfiguration?.buildSettings.CURRENT_PROJECT_VERSION ?? "1";
+ configuration.buildSettings.DEFINES_MODULE = "YES";
+ if (applicationConfiguration?.buildSettings.DEVELOPMENT_TEAM) {
+ configuration.buildSettings.DEVELOPMENT_TEAM =
+ applicationConfiguration.buildSettings.DEVELOPMENT_TEAM;
+ }
+ configuration.buildSettings.GENERATE_INFOPLIST_FILE = "NO";
+ configuration.buildSettings.INFOPLIST_FILE = `"${targetName}/Info.plist"`;
+ configuration.buildSettings.IPHONEOS_DEPLOYMENT_TARGET = deploymentTarget;
+ configuration.buildSettings.MARKETING_VERSION =
+ marketingVersion ??
+ applicationConfiguration?.buildSettings.MARKETING_VERSION ??
+ "1.0";
+ configuration.buildSettings.PRODUCT_BUNDLE_IDENTIFIER = `"${extensionBundleIdentifier}"`;
+ configuration.buildSettings.SDKROOT = "iphoneos";
+ configuration.buildSettings.SKIP_INSTALL = "YES";
+ configuration.buildSettings.SWIFT_VERSION = "5.0";
+ configuration.buildSettings.TARGETED_DEVICE_FAMILY = '"1"';
+ }
+
+ const developmentTeam = applicationConfigurations.find(
+ (configuration) => configuration.buildSettings.DEVELOPMENT_TEAM,
+ )?.buildSettings.DEVELOPMENT_TEAM;
+ if (applicationTargetEntry) {
+ configureTargetAttributes(
+ project,
+ applicationTargetEntry[0],
+ developmentTeam,
+ [
+ "com.apple.ApplicationGroups.iOS",
+ ...(usesAppleSignIn ? ["com.apple.SignInWithApple"] : []),
+ ],
+ );
+ }
+ configureTargetAttributes(project, target.uuid, developmentTeam, [
+ "com.apple.ApplicationGroups.iOS",
+ ]);
+};
+
+const copyExtensionSources = (
+ projectRoot,
+ appGroup,
+ extensionBundleIdentifier,
+) => {
+ const sourceDirectory = path.join(__dirname, "..", "extension", targetName);
+ const destinationDirectory = path.join(projectRoot, "ios", targetName);
+ fs.rmSync(destinationDirectory, { force: true, recursive: true });
+ fs.mkdirSync(destinationDirectory, { recursive: true });
+ for (const fileName of [
+ "SampleHandler.swift",
+ "SegmentedScreenWriter.swift",
+ ]) {
+ fs.copyFileSync(
+ path.join(sourceDirectory, fileName),
+ path.join(destinationDirectory, fileName),
+ );
+ }
+ for (const fileName of ["Info.plist", `${targetName}.entitlements`]) {
+ const contents = fs
+ .readFileSync(path.join(sourceDirectory, fileName), "utf8")
+ .replaceAll("__APP_GROUP__", appGroup)
+ .replaceAll("__EXTENSION_BUNDLE_IDENTIFIER__", extensionBundleIdentifier);
+ fs.writeFileSync(path.join(destinationDirectory, fileName), contents);
+ }
+};
+
+const addEasExtension = (config, extensionBundleIdentifier, appGroup) => {
+ const extensions =
+ config.extra?.eas?.build?.experimental?.ios?.appExtensions ?? [];
+ const nextExtension = {
+ targetName,
+ bundleIdentifier: extensionBundleIdentifier,
+ entitlements: {
+ "com.apple.security.application-groups": [appGroup],
+ },
+ };
+ const appExtensions = [
+ ...extensions.filter((extension) => extension.targetName !== targetName),
+ nextExtension,
+ ];
+ config.extra = {
+ ...config.extra,
+ eas: {
+ ...config.extra?.eas,
+ build: {
+ ...config.extra?.eas?.build,
+ experimental: {
+ ...config.extra?.eas?.build?.experimental,
+ ios: {
+ ...config.extra?.eas?.build?.experimental?.ios,
+ appExtensions,
+ },
+ },
+ },
+ },
+ };
+ return config;
+};
+
+module.exports = (
+ config,
+ {
+ appGroup = defaultAppGroup,
+ extensionBundleIdentifier = defaultExtensionBundleIdentifier,
+ } = {},
+) => {
+ addEasExtension(config, extensionBundleIdentifier, appGroup);
+ config = withEntitlementsPlist(config, (entitlementsConfig) => {
+ const groups = new Set(
+ entitlementsConfig.modResults["com.apple.security.application-groups"] ??
+ [],
+ );
+ groups.add(appGroup);
+ entitlementsConfig.modResults["com.apple.security.application-groups"] = [
+ ...groups,
+ ];
+ delete entitlementsConfig.modResults[
+ "com.apple.developer.screen-recording"
+ ];
+ return entitlementsConfig;
+ });
+ config = withInfoPlist(config, (infoConfig) => {
+ const backgroundModes = (
+ infoConfig.modResults.UIBackgroundModes ?? []
+ ).filter((mode) => mode !== "audio" && mode !== "screen-capture");
+ if (backgroundModes.length > 0) {
+ infoConfig.modResults.UIBackgroundModes = backgroundModes;
+ } else {
+ delete infoConfig.modResults.UIBackgroundModes;
+ }
+ infoConfig.modResults.CapScreenRecordingAppGroup = appGroup;
+ infoConfig.modResults.CapScreenBroadcastExtensionBundleIdentifier =
+ extensionBundleIdentifier;
+ infoConfig.modResults.NSScreenCaptureUsageDescription =
+ "Cap records your screen after you confirm Start Broadcast.";
+ return infoConfig;
+ });
+ config = withDangerousMod(config, [
+ "ios",
+ async (dangerousConfig) => {
+ copyExtensionSources(
+ dangerousConfig.modRequest.projectRoot,
+ appGroup,
+ extensionBundleIdentifier,
+ );
+ return dangerousConfig;
+ },
+ ]);
+ config = withXcodeProject(config, (xcodeConfig) => {
+ addExtensionTarget(
+ xcodeConfig.modResults,
+ extensionBundleIdentifier,
+ xcodeConfig.ios?.deploymentTarget ?? "15.1",
+ config.version,
+ config.ios?.usesAppleSignIn === true,
+ );
+ return xcodeConfig;
+ });
+ return config;
+};
diff --git a/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorder.types.ts b/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorder.types.ts
new file mode 100644
index 000000000..88b8d01cd
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorder.types.ts
@@ -0,0 +1,47 @@
+import type { ViewProps } from "react-native";
+
+export type CapScreenRecorderStatus =
+ | "missing"
+ | "prepared"
+ | "recording"
+ | "uploading"
+ | "finished"
+ | "uploaded"
+ | "cancelled"
+ | "failed";
+
+export type CapScreenRecorderAvailability = {
+ available: boolean;
+ minimumSystemVersion: string;
+ reason: string | null;
+};
+
+export type CapScreenRecorderSegment = {
+ track: "video" | "audio";
+ type: "initialization" | "media";
+ index: number;
+ uri: string;
+ durationSeconds: number;
+ byteLength: number;
+};
+
+export type CapScreenRecorderUpdates = {
+ status: CapScreenRecorderStatus;
+ segments: CapScreenRecorderSegment[];
+ durationSeconds: number | null;
+ totalBytes: number;
+ error: string | null;
+};
+
+export type PrepareScreenRecordingOptions = {
+ recordingId: string;
+ width: number;
+ height: number;
+ videoBitrate: number;
+ segmentDurationSeconds: number;
+ maximumDurationSeconds: number | null;
+};
+
+export type CapScreenRecorderViewProps = ViewProps & {
+ enabled?: boolean;
+};
diff --git a/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorderModule.ts b/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorderModule.ts
new file mode 100644
index 000000000..3c364771f
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorderModule.ts
@@ -0,0 +1,49 @@
+import { NativeModule, requireOptionalNativeModule } from "expo";
+import type {
+ CapScreenRecorderAvailability,
+ CapScreenRecorderUpdates,
+ PrepareScreenRecordingOptions,
+} from "./CapScreenRecorder.types";
+
+declare class CapScreenRecorderNativeModule extends NativeModule {
+ getAvailability(): Promise<CapScreenRecorderAvailability>;
+ prepareRecording(options: PrepareScreenRecordingOptions): Promise<void>;
+ getRecordingUpdates(recordingId: string): Promise<CapScreenRecorderUpdates>;
+ cancelRecording(recordingId: string): Promise<void>;
+}
+
+const getNativeModule = () => {
+ const nativeModule =
+ requireOptionalNativeModule<CapScreenRecorderNativeModule>(
+ "CapScreenRecorder",
+ );
+ if (!nativeModule) {
+ throw new Error("Screen recording is unavailable in this build.");
+ }
+ return nativeModule;
+};
+
+export const getScreenRecordingAvailability = async () => {
+ const nativeModule =
+ requireOptionalNativeModule<CapScreenRecorderNativeModule>(
+ "CapScreenRecorder",
+ );
+ if (!nativeModule) {
+ return {
+ available: false,
+ minimumSystemVersion: "15.1",
+ reason: "Screen recording is unavailable in this build.",
+ };
+ }
+ return nativeModule.getAvailability();
+};
+
+export const prepareScreenRecording = (
+ options: PrepareScreenRecordingOptions,
+) => getNativeModule().prepareRecording(options);
+
+export const getScreenRecordingUpdates = (recordingId: string) =>
+ getNativeModule().getRecordingUpdates(recordingId);
+
+export const cancelScreenRecording = (recordingId: string) =>
+ getNativeModule().cancelRecording(recordingId);
diff --git a/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorderView.tsx b/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorderView.tsx
new file mode 100644
index 000000000..c153e57df
--- /dev/null
+++ b/apps/mobile/modules/cap-screen-recorder/src/CapScreenRecorderView.tsx
@@ -0,0 +1,8 @@
+import { requireNativeView } from "expo";
+import type { ComponentType } from "react";
+import type { CapScreenRecorderViewProps } from "./CapScreenRecorder.types";
+
+const CapScreenRecorderView: ComponentType<CapScreenRecorderViewProps> =
+ requireNativeView("CapScreenRecorder");
+
+export default CapScreenRecorderView;