Skip to content

Open source CapCut alternative.

TypeScript
8.6 KB
Raw Blame
import Foundation

/// Commands the camera model sends to whatever owns the capture session.
/// The app target's CameraController conforms; the model never imports
/// AVFoundation.
public protocol CameraControlling: AnyObject {
    func activate()
    func deactivate()
    func setFacing(_ facing: CameraFacing)
    func setZoom(display: Double)
    func setTorch(_ on: Bool)
    func apply(_ settings: CameraSettings)
    func startRecording()
    func stopRecording()
    /// Starts or stops the stream of microphone levels that feeds
    /// `CameraModel.audioLevel`.
    func setAudioMetering(_ on: Bool)
}

nonisolated public enum CameraAvailability: Equatable, Sendable {
    case idle
    case starting
    case running
    case unavailable(reason: String)
}

@Observable
public final class CameraModel {
    public internal(set) var availability: CameraAvailability = .idle
    /// The camera and capture settings persist across launches: pick 4K on
    /// the back camera once and every later session opens that way.
    public private(set) var facing: CameraFacing = .front {
        didSet {
            if facing != oldValue { defaults.set(facing.rawValue, forKey: Self.facingKey) }
        }
    }
    public private(set) var settings = CameraSettings() {
        didSet {
            if settings != oldValue { persistSettings() }
        }
    }
    /// What the device could honor for the current request, shown in the badge.
    public private(set) var effectiveSettings = CameraSettings()
    public internal(set) var zoomMapping = ZoomMapping(wideBase: 1, minDisplay: 1, maxDisplay: 1)
    public private(set) var zoom: Double = 1
    public private(set) var isTorchOn = false
    public internal(set) var hasTorch = false
    public internal(set) var recordingStartedAt: Date?
    /// Teleprompter settings persist across sessions: set the pace once and
    /// every later recording starts with it.
    public var teleprompter = TeleprompterState() {
        didSet {
            if teleprompter.settings != oldValue.settings { persistTeleprompterSettings() }
        }
    }

    /// Whether the short-form guide shades the picture. Kept across
    /// sessions: a person who posts vertical video frames for it every time.
    public private(set) var showsSafeZones = false {
        didSet {
            if showsSafeZones != oldValue {
                defaults.set(showsSafeZones, forKey: Self.safeZonesKey)
            }
        }
    }

    /// Whether the microphone meter sits on the picture. On by default, so a
    /// silent take shows itself before the shutter is pressed; a person who
    /// hides it stays without it across sessions.
    public private(set) var showsAudioMeter = true {
        didSet {
            if showsAudioMeter != oldValue {
                defaults.set(showsAudioMeter, forKey: Self.audioMeterKey)
            }
        }
    }
    /// How loud the microphone is right now, 0 for silence up to 1 for full
    /// scale, read from the connection the movie file is written from. Nil
    /// while the meter is off, and while the session has no microphone at
    /// all, which is the case the meter exists to expose.
    public internal(set) var audioLevel: Double?

    public var isRecording: Bool { recordingStartedAt != nil }

    public var controller: (any CameraControlling)?

    private let defaults: UserDefaults
    private static let teleprompterKey = "teleprompterSettings"
    private static let safeZonesKey = "showsSafeZones"
    private static let audioMeterKey = "showsAudioMeter"
    private static let settingsKey = "cameraSettings"
    private static let facingKey = "cameraFacing"

    public init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        if let data = defaults.data(forKey: Self.teleprompterKey),
           let settings = try? JSONDecoder().decode(TeleprompterSettings.self, from: data) {
            teleprompter.settings = settings
        }
        showsSafeZones = defaults.bool(forKey: Self.safeZonesKey)
        showsAudioMeter = defaults.object(forKey: Self.audioMeterKey) as? Bool ?? true
        if let data = defaults.data(forKey: Self.settingsKey),
           let settings = try? JSONDecoder().decode(CameraSettings.self, from: data) {
            self.settings = settings
        }
        if let raw = defaults.string(forKey: Self.facingKey), let facing = CameraFacing(rawValue: raw) {
            self.facing = facing
        }
    }

    public func toggleSafeZones() {
        showsSafeZones.toggle()
    }

    public func toggleAudioMeter() {
        showsAudioMeter.toggle()
        if !showsAudioMeter { audioLevel = nil }
        controller?.setAudioMetering(showsAudioMeter)
    }

    private func persistSettings() {
        guard let data = try? JSONEncoder().encode(settings) else { return }
        defaults.set(data, forKey: Self.settingsKey)
    }

    private func persistTeleprompterSettings() {
        guard let data = try? JSONEncoder().encode(teleprompter.settings) else { return }
        defaults.set(data, forKey: Self.teleprompterKey)
    }

    // MARK: Intents

    public func appeared() {
        availability = .starting
        controller?.activate()
    }

    public func disappeared() {
        controller?.deactivate()
        availability = .idle
    }

    public func flip() {
        facing = facing.flipped
        zoom = 1
        isTorchOn = false
        controller?.setFacing(facing)
    }

    public func select(zoom display: Double) {
        zoom = display
        controller?.setZoom(display: display)
    }

    /// True when the flash button does anything: the hardware torch, or the
    /// screen fill light on cameras without one.
    public var flashAvailable: Bool { hasTorch || facing == .front }

    /// The screen stands in for a torch the current camera lacks.
    public var isFillLightOn: Bool { isTorchOn && !hasTorch }

    public func toggleTorch() {
        isTorchOn.toggle()
        if hasTorch {
            controller?.setTorch(isTorchOn)
        }
    }

    public func update(_ transform: (inout CameraSettings) -> Void) {
        transform(&settings)
        controller?.apply(settings)
    }

    public func toggleRecording() {
        if isRecording {
            controller?.stopRecording()
        } else {
            controller?.startRecording()
        }
    }

    /// Loads a note into the teleprompter and shows the card.
    public func loadTeleprompter(script: String) {
        teleprompter.script = script
        teleprompter.isCardShown = true
    }

    /// Clears the card and runs the script from the top at the set pace.
    public func startTeleprompter() {
        guard teleprompter.hasScript else { return }
        teleprompter.isCardShown = false
        teleprompter.isRunning = true
        teleprompter.runStartedAt = .now
        // A fresh run puts the script back where the pacing wants it.
        teleprompter.nudge = 0
    }

    /// Moves the running script by `points`: down for positive, the way a
    /// drag down moves it.
    public func nudgeTeleprompter(by points: Double) {
        guard teleprompter.isRunning else { return }
        teleprompter.nudge += points
    }

    /// Takes the prompter off the picture: the card and the running script
    /// both go.
    public func dismissTeleprompter() {
        teleprompter.isCardShown = false
        teleprompter.isRunning = false
        teleprompter.runStartedAt = nil
    }

    // MARK: Controller events

    public func sessionDidStart(zoomMapping: ZoomMapping, hasTorch: Bool, effective: CameraSettings) {
        self.zoomMapping = zoomMapping
        self.hasTorch = hasTorch
        effectiveSettings = effective
        availability = .running
    }

    public func sessionFailed(reason: String) {
        availability = .unavailable(reason: reason)
    }

    public func audioLevelDidChange(_ level: Double?) {
        guard showsAudioMeter else { return }
        audioLevel = level
    }

    public func recordingDidStart() {
        recordingStartedAt = .now
        // A take starts the script from the top. The card is off screen while
        // recording, so an open card hands its script to the prompter; a
        // dismissed prompter stays dismissed.
        if teleprompter.isRunning || (teleprompter.isCardShown && teleprompter.hasScript) {
            startTeleprompter()
        }
    }

    public func recordingDidFinish() {
        recordingStartedAt = nil
    }
}

/// Formats a duration as m:ss for the recording timer and duration badges.
nonisolated public func formattedDuration(_ seconds: TimeInterval) -> String {
    let whole = max(0, Int(seconds.rounded(.down)))
    return "\(whole / 60):" + String(format: "%02d", whole % 60)
}