open-merou

Open Mérou, a free iOS app for the Oceanic+ underwater iPhone housing
git clone https://git.schurger.org/open-merou.git
Log | Files | Refs | README | LICENSE

CameraSettings.swift (13197B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 // Camera settings and menu: pure logic, driven by the housing buttons.
      3 // The settings are persisted as JSON (UserDefaults key and enum raw values): do not rename them.
      4 import Foundation
      5 
      6 enum CaptureMode: String, Codable, Sendable { case photo, video }
      7 enum PhotoFormat: String, Codable, Sendable, CaseIterable { case heif, rawHeif }
      8 /// Fixed orientation: underwater, the iPhone often points down and cannot rely on gravity.
      9 enum ScreenOrientation: String, Codable, Sendable, CaseIterable {
     10     case landscape, landscapeFlipped, portrait
     11 
     12     /// Rotation angle of the image for the back camera.
     13     var videoAngle: Double {
     14         switch self {
     15         case .landscape: 0
     16         case .landscapeFlipped: 180
     17         case .portrait: 90
     18         }
     19     }
     20 }
     21 
     22 /// Colors: the iPhone's white balance, or gains forced on the sensor to compensate for the water.
     23 enum ColorMode: String, Codable, Sendable, CaseIterable { case system, underwater, calibrated }
     24 
     25 /// Red, green and blue gains applied to the sensor.
     26 struct ColorGains: Codable, Equatable, Sendable {
     27     var red: Double, green: Double, blue: Double
     28 
     29     /// Brings the smallest gain to 1 (the iPhone refuses less), then caps at the device maximum.
     30     /// `saturated`: the wanted correction exceeds what the sensor accepts (too deep, too far).
     31     func fitted(max: Double) -> (gains: ColorGains, saturated: Bool) {
     32         let low = Swift.max(Swift.min(red, green, blue), 0.01)
     33         let wanted = [red / low, green / low, blue / low]
     34         let clamped = wanted.map { Swift.min(Swift.max($0, 1), max) }
     35         // Only red matters: it is what water absorbs (under a warm light, blue is the one that hits the cap).
     36         return (ColorGains(red: clamped[0], green: clamped[1], blue: clamped[2]), wanted[0] > max * 1.001)
     37     }
     38 
     39     /// Wanted red, relative to the smallest gain (for the hysteresis of the indicator).
     40     var relativeRed: Double { red / Swift.max(Swift.min(red, green, blue), 0.01) }
     41 
     42     /// Slides toward `target` smoothly (automatic tracking).
     43     func moved(toward target: ColorGains, by weight: Double) -> ColorGains {
     44         ColorGains(red: red + (target.red - red) * weight, green: green + (target.green - green) * weight,
     45                    blue: blue + (target.blue - blue) * weight)
     46     }
     47 
     48     var label: String {
     49         let r = String(format: "%.2f", red), g = String(format: "%.2f", green), b = String(format: "%.2f", blue)
     50         return String(localized: "R×\(r) G×\(g) B×\(b)")
     51     }
     52 }
     53 
     54 enum Stabilization: String, Codable, Sendable, CaseIterable { case off, standard, cinematic, extended }
     55 
     56 struct VideoQuality: Codable, Equatable, Hashable, Sendable {
     57     let height: Int
     58     let fps: Int
     59 
     60     var width: Int { height == 720 ? 1280 : height == 1080 ? 1920 : 3840 }
     61     var label: String { String(localized: "\(height == 2160 ? "4K" : "\(height)p") · \(String(fps)) fps") }
     62 
     63     /// From the most modest to the most demanding; the app only offers what the iPhone can do.
     64     static let all = [
     65         VideoQuality(height: 720, fps: 30), VideoQuality(height: 1080, fps: 30), VideoQuality(height: 1080, fps: 60),
     66         VideoQuality(height: 2160, fps: 30), VideoQuality(height: 2160, fps: 60), VideoQuality(height: 2160, fps: 120),
     67     ]
     68 }
     69 
     70 struct CameraSettings: Codable, Equatable, Sendable {
     71     var mode = CaptureMode.photo
     72     var photoFormat = PhotoFormat.heif
     73     var exposureBias = 0.0
     74     var stabilization = Stabilization.standard
     75     var videoQuality = VideoQuality(height: 2160, fps: 30)
     76     /// Seconds without a button press before the screen sleeps; 0 = never.
     77     var sleepAfter = 120
     78     var orientation = ScreenOrientation.landscape
     79     var colorMode = ColorMode.underwater
     80     /// Screen brightness in %; 0 = the system's.
     81     var brightness = 0
     82     /// Gains of the last calibration on a light surface.
     83     var calibration: ColorGains?
     84     /// Development mode: CSV log and extra displays.
     85     var developer = false
     86 
     87     static let key = "cameraSettings5"
     88     static func load() -> CameraSettings {
     89         guard let data = UserDefaults.standard.data(forKey: key),
     90               let value = try? JSONDecoder().decode(CameraSettings.self, from: data) else { return CameraSettings() }
     91         return value
     92     }
     93     func save() {
     94         if let data = try? JSONEncoder().encode(self) { UserDefaults.standard.set(data, forKey: Self.key) }
     95     }
     96 }
     97 
     98 /// What this iPhone can do (filled in by the camera at startup).
     99 struct CameraCapabilities: Equatable, Sendable {
    100     var zoomLabels: [String] = []
    101     var proRAW = false
    102     var qualities: [VideoQuality] = []
    103     var stabilizations: [Stabilization] = [.off]
    104     var minBias = -2.0
    105     var maxBias = 2.0
    106 }
    107 
    108 enum CameraSetting: Sendable, CaseIterable {
    109     case color, photoFormat, exposure, stabilization, videoQuality, sleep, orientation, developer, brightness
    110 
    111     /// Settings of the "Settings" list (brightness has its own menu entry).
    112     static let listed = allCases.filter { $0 != .brightness }
    113 
    114     var title: String {
    115         switch self {
    116         case .color: String(localized: "Colors")
    117         case .photoFormat: String(localized: "Photo format")
    118         case .exposure: String(localized: "Exposure")
    119         case .stabilization: String(localized: "Video stabilization")
    120         case .videoQuality: String(localized: "Video quality")
    121         case .sleep: String(localized: "Screen sleep")
    122         case .orientation: String(localized: "Orientation")
    123         case .developer: String(localized: "Development")
    124         case .brightness: String(localized: "Brightness")
    125         }
    126     }
    127 }
    128 
    129 enum SettingValue: Equatable, Sendable {
    130     case color(ColorMode), photoFormat(PhotoFormat), exposure(Double), stabilization(Stabilization), videoQuality(VideoQuality), sleep(Int), orientation(ScreenOrientation), developer(Bool), brightness(Int)
    131 
    132     var label: String {
    133         switch self {
    134         case .color(.system): String(localized: "iPhone (no correction)")
    135         case .color(.underwater): String(localized: "Underwater, automatic")
    136         case .color(.calibrated): String(localized: "Underwater, calibrated")
    137         case .photoFormat(.heif): "HEIF"
    138         case .photoFormat(.rawHeif): "ProRAW + HEIF"
    139         case .exposure(let v): v == 0 ? "0" : String(format: "%+.1f", v)
    140         case .stabilization(.off): String(localized: "Off")
    141         case .stabilization(.standard): String(localized: "Standard")
    142         case .stabilization(.cinematic): String(localized: "Cinematic")
    143         case .stabilization(.extended): String(localized: "Cinematic extended")
    144         case .videoQuality(let q): q.label
    145         case .sleep(0): String(localized: "Never")
    146         case .sleep(let s): s < 60 ? "\(s) s" : "\(s / 60) min"
    147         case .orientation(.landscape): String(localized: "Landscape")
    148         case .orientation(.landscapeFlipped): String(localized: "Landscape flipped")
    149         case .orientation(.portrait): String(localized: "Portrait")
    150         case .developer(let on): on ? String(localized: "Enabled") : String(localized: "Disabled")
    151         case .brightness(0): String(localized: "iPhone setting")
    152         case .brightness(let v): "\(v) %"
    153         }
    154     }
    155 }
    156 
    157 extension CameraSettings {
    158     static let biasSteps = [-2, -1.7, -1.3, -1, -0.7, -0.3, 0, 0.3, 0.7, 1, 1.3, 1.7, 2.0]
    159     static let sleepSteps = [15, 30, 60, 120, 300, 0]
    160 
    161     func options(for setting: CameraSetting, _ caps: CameraCapabilities) -> [SettingValue] {
    162         switch setting {
    163         case .color: ColorMode.allCases.map { .color($0) }
    164         case .photoFormat: (caps.proRAW ? PhotoFormat.allCases : [.heif]).map { .photoFormat($0) }
    165         case .exposure: Self.biasSteps.filter { $0 >= caps.minBias && $0 <= caps.maxBias }.map { .exposure($0) }
    166         case .stabilization: caps.stabilizations.map { .stabilization($0) }
    167         case .videoQuality: caps.qualities.map { .videoQuality($0) }
    168         case .sleep: Self.sleepSteps.map { .sleep($0) }
    169         case .orientation: ScreenOrientation.allCases.map { .orientation($0) }
    170         case .developer: [.developer(false), .developer(true)]
    171         case .brightness: [0, 50, 75, 100].map { .brightness($0) }
    172         }
    173     }
    174 
    175     func current(_ setting: CameraSetting) -> SettingValue {
    176         switch setting {
    177         case .color: .color(colorMode)
    178         case .photoFormat: .photoFormat(photoFormat)
    179         case .exposure: .exposure(exposureBias)
    180         case .stabilization: .stabilization(stabilization)
    181         case .videoQuality: .videoQuality(videoQuality)
    182         case .sleep: .sleep(sleepAfter)
    183         case .orientation: .orientation(orientation)
    184         case .developer: .developer(developer)
    185         case .brightness: .brightness(brightness)
    186         }
    187     }
    188 
    189     mutating func set(_ value: SettingValue) {
    190         switch value {
    191         case .color(let v): colorMode = v
    192         case .photoFormat(let v): photoFormat = v
    193         case .exposure(let v): exposureBias = v
    194         case .stabilization(let v): stabilization = v
    195         case .videoQuality(let v): videoQuality = v
    196         case .sleep(let v): sleepAfter = v
    197         case .orientation(let v): orientation = v
    198         case .developer(let v): developer = v
    199         case .brightness(let v): brightness = v
    200         }
    201     }
    202 }
    203 
    204 /// Menu: right opens and confirms, up and down move, left goes up one level or closes.
    205 struct CameraMenu: Equatable, Sendable {
    206     enum RootItem: Sendable, CaseIterable {
    207         // New entries go at the end: the positions of the others are known to the tests and to `-demoMenu`.
    208         case photo, video, sleep, settings, brightness, info, computer
    209 
    210         var title: String {
    211             switch self {
    212             case .photo: String(localized: "Photo")
    213             case .video: String(localized: "Video")
    214             case .sleep: String(localized: "Sleep")
    215             case .settings: String(localized: "Settings")
    216             case .brightness: String(localized: "Brightness")
    217             case .info: String(localized: "Information")
    218             case .computer: String(localized: "Dive computer")
    219             }
    220         }
    221     }
    222 
    223     enum Level: Equatable, Sendable {
    224         case root(Int)
    225         case settings(Int)
    226         case options(CameraSetting, Int)
    227     }
    228 
    229     enum Action: Equatable, Sendable { case none, close, setMode(CaptureMode), sleepNow, changed, showInfo, showComputer }
    230 
    231     private(set) var level: Level? = nil
    232     var isOpen: Bool { level != nil }
    233 
    234     /// Level we came from to change `setting`.
    235     private func parent(of setting: CameraSetting) -> Level {
    236         if let i = CameraSetting.listed.firstIndex(of: setting) { return .settings(i) }
    237         return .root(RootItem.allCases.firstIndex(of: .brightness)!)
    238     }
    239 
    240     mutating func open() { level = .root(0) }
    241     mutating func close() { level = nil }
    242 
    243     /// Applies a button; changes `settings` when an option is confirmed.
    244     mutating func handle(_ button: HousingButton, settings: inout CameraSettings, caps: CameraCapabilities) -> Action {
    245         guard let level else { return .none }
    246         let step = button == .down ? 1 : button == .up ? -1 : 0
    247         func wrap(_ i: Int, _ n: Int) -> Int { n == 0 ? 0 : (i + step + n) % n }
    248         switch level {
    249         case .root(let i):
    250             switch button {
    251             case .up, .down: self.level = .root(wrap(i, RootItem.allCases.count))
    252             case .left: self.level = nil; return .close
    253             case .right, .shutter:
    254                 switch RootItem.allCases[i] {
    255                 case .photo: self.level = nil; return .setMode(.photo)
    256                 case .video: self.level = nil; return .setMode(.video)
    257                 case .sleep: self.level = nil; return .sleepNow
    258                 case .settings: self.level = .settings(0)
    259                 case .brightness:
    260                     let options = settings.options(for: .brightness, caps)
    261                     self.level = .options(.brightness, options.firstIndex(of: settings.current(.brightness)) ?? 0)
    262                 case .info: self.level = nil; return .showInfo
    263                 case .computer: self.level = nil; return .showComputer
    264                 }
    265             }
    266         case .settings(let i):
    267             switch button {
    268             case .up, .down: self.level = .settings(wrap(i, CameraSetting.listed.count))
    269             case .left: self.level = .root(RootItem.allCases.firstIndex(of: .settings)!)
    270             case .right, .shutter:
    271                 let setting = CameraSetting.listed[i]
    272                 let options = settings.options(for: setting, caps)
    273                 guard !options.isEmpty else { break }
    274                 self.level = .options(setting, options.firstIndex(of: settings.current(setting)) ?? 0)
    275             }
    276         case .options(let setting, let i):
    277             let options = settings.options(for: setting, caps)
    278             switch button {
    279             case .up, .down: self.level = .options(setting, wrap(i, options.count))
    280             case .left: self.level = parent(of: setting)
    281             case .right, .shutter:
    282                 if options.indices.contains(i) { settings.set(options[i]) }
    283                 self.level = parent(of: setting)
    284                 return .changed
    285             }
    286         }
    287         return .none
    288     }
    289 }