commit 635c034f911e7fc6c9c0e84dcd8ed7d08ea42e84
parent 647a4e002f309065f6d3e096eb2060256dc83d07
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 15:08:12 -0500
0.8: colour correction on the sensor (automatic grey-world tracking, calibration by long press on down)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYGSNhtY1AmBH7DQGNs
Diffstat:
7 files changed, 159 insertions(+), 8 deletions(-)
diff --git a/OpenMerou/App/AppModel.swift b/OpenMerou/App/AppModel.swift
@@ -32,6 +32,15 @@ final class AppModel {
if (state.recordingSince == nil) != (camera.recordingSince == nil) {
DevLog.shared.event(state.recordingSince == nil ? "vidéo : arrêt" : "vidéo : début")
}
+ if let calibration = state.calibration, calibration != camera.calibration {
+ settings.colorMode = .calibrated
+ settings.calibration = calibration
+ settings.save()
+ DevLog.shared.event("calibrage \(calibration.label)")
+ }
+ if state.gainsSaturated != camera.gainsSaturated {
+ DevLog.shared.event(state.gainsSaturated ? "couleurs : rouge au maximum" : "couleurs : dans les limites")
+ }
camera = state
}
engine.start(settings)
@@ -87,7 +96,11 @@ final class AppModel {
}
return
}
- guard !event.isLong else { return }
+ if event.isLong {
+ // Appui long en bas : calibrer les couleurs sur ce que l'on vise.
+ if event.button == .down { engine.calibrate() }
+ return
+ }
switch event.button {
case .shutter:
if settings.mode == .photo { DevLog.shared.event("photo demandée") }
diff --git a/OpenMerou/Camera/CameraEngine.swift b/OpenMerou/Camera/CameraEngine.swift
@@ -13,6 +13,11 @@ struct CameraState: Equatable, Sendable {
var recordingSince: Date?
var shots = 0
var message: String?
+ /// Gains de couleur appliqués au capteur (nil : balance des blancs de l'iPhone).
+ var gains: ColorGains?
+ var gainsSaturated = false
+ /// Dernier calibrage fait à la demande, à enregistrer dans les réglages.
+ var calibration: ColorGains?
}
final class CameraEngine: NSObject, @unchecked Sendable {
@@ -29,6 +34,7 @@ final class CameraEngine: NSObject, @unchecked Sendable {
private var settings = CameraSettings()
private var state = CameraState()
private var photoDelegates: [Int64: PhotoDelegate] = [:]
+ private var colorTimer: DispatchSourceTimer?
override init() {
previewLayer = AVCaptureVideoPreviewLayer(session: session)
@@ -114,11 +120,13 @@ final class CameraEngine: NSObject, @unchecked Sendable {
func apply(_ settings: CameraSettings) {
queue.async { [self] in
+ let colorChanged = settings.colorMode != self.settings.colorMode
let modeChanged = settings.mode != self.settings.mode || settings.videoQuality != self.settings.videoQuality
|| settings.photoFormat != self.settings.photoFormat
self.settings = settings
guard device != nil, !movieOutput.isRecording else { return }
if modeChanged { applyMode() } else { applyLight() }
+ if colorChanged && !modeChanged { applyColor() }
publish()
}
}
@@ -155,6 +163,7 @@ final class CameraEngine: NSObject, @unchecked Sendable {
let modes: [(Stabilization, AVCaptureVideoStabilizationMode)] = [(.off, .off), (.standard, .standard), (.cinematic, .cinematic), (.extended, .cinematicExtended)]
state.capabilities.stabilizations = modes.filter { $0.1 == .off || device.activeFormat.isVideoStabilizationModeSupported($0.1) }.map(\.0)
applyLight()
+ applyColor()
}
private func rotate(_ connection: AVCaptureConnection?) {
@@ -186,6 +195,77 @@ final class CameraEngine: NSObject, @unchecked Sendable {
}
}
+ // MARK: Couleurs
+
+ /// Gains « gris moyen » mesurés par l'iPhone sur la scène, ajustés à ce que le capteur accepte.
+ private func measuredGains() -> (gains: ColorGains, saturated: Bool)? {
+ guard let device, device.isLockingWhiteBalanceWithCustomDeviceGainsSupported else { return nil }
+ let g = device.grayWorldDeviceWhiteBalanceGains
+ guard g.redGain > 0, g.greenGain > 0, g.blueGain > 0 else { return nil }
+ return ColorGains(red: Double(g.redGain), green: Double(g.greenGain), blue: Double(g.blueGain))
+ .fitted(max: Double(device.maxWhiteBalanceGain))
+ }
+
+ private func lock(_ gains: ColorGains, saturated: Bool) {
+ guard let device, device.isLockingWhiteBalanceWithCustomDeviceGainsSupported else { return }
+ let fitted = gains.fitted(max: Double(device.maxWhiteBalanceGain)).gains // jamais hors bornes
+ guard (try? device.lockForConfiguration()) != nil else { return }
+ device.setWhiteBalanceModeLocked(with: .init(redGain: Float(fitted.red), greenGain: Float(fitted.green), blueGain: Float(fitted.blue)))
+ device.unlockForConfiguration()
+ state.gains = fitted
+ state.gainsSaturated = saturated
+ }
+
+ private func applyColor() {
+ guard let device else { return }
+ colorTimer?.cancel()
+ colorTimer = nil
+ guard settings.colorMode != .system, device.isLockingWhiteBalanceWithCustomDeviceGainsSupported else {
+ if settings.colorMode != .system { state.message = "Couleurs : réglage manuel indisponible sur cet appareil" }
+ if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance), (try? device.lockForConfiguration()) != nil {
+ device.whiteBalanceMode = .continuousAutoWhiteBalance
+ device.unlockForConfiguration()
+ }
+ state.gains = nil
+ state.gainsSaturated = false
+ return
+ }
+ switch settings.colorMode {
+ case .calibrated:
+ if let saved = settings.calibration { lock(saved, saturated: false) } else { calibrateNow() }
+ default:
+ // Suivi automatique : deux mesures par seconde, lissées pour éviter le pompage des couleurs.
+ let timer = DispatchSource.makeTimerSource(queue: queue)
+ timer.schedule(deadline: .now() + 0.5, repeating: 0.5)
+ timer.setEventHandler { [weak self] in
+ guard let self, let measured = self.measuredGains() else { return }
+ let next = self.state.gains?.moved(toward: measured.gains, by: 0.25) ?? measured.gains
+ let before = self.state
+ self.lock(next, saturated: measured.saturated)
+ if self.state != before { self.publish() }
+ }
+ timer.resume()
+ colorTimer = timer
+ }
+ }
+
+ private func calibrateNow() {
+ guard let measured = measuredGains() else { say("Calibrage impossible"); return }
+ lock(measured.gains, saturated: measured.saturated)
+ state.calibration = measured.gains
+ say(measured.saturated ? "Couleurs calibrées (rouge au maximum)" : "Couleurs calibrées")
+ }
+
+ /// Calibrage à la demande : viser une surface claire (sable, ardoise) et appuyer.
+ func calibrate() {
+ queue.async { [self] in
+ colorTimer?.cancel()
+ colorTimer = nil
+ settings.colorMode = .calibrated
+ calibrateNow()
+ }
+ }
+
private func addMicrophone() {
guard audioInput == nil, AVCaptureDevice.authorizationStatus(for: .audio) != .denied,
let mic = AVCaptureDevice.default(for: .audio), let input = try? AVCaptureDeviceInput(device: mic),
diff --git a/OpenMerou/Camera/CameraSettings.swift b/OpenMerou/Camera/CameraSettings.swift
@@ -17,6 +17,31 @@ enum ScreenOrientation: String, Codable, Sendable, CaseIterable {
}
}
+/// Couleurs : balance des blancs de l'iPhone, ou gains imposés au capteur pour compenser l'eau.
+enum ColorMode: String, Codable, Sendable, CaseIterable { case system, underwater, calibrated }
+
+/// Gains rouge, vert, bleu appliqués au capteur.
+struct ColorGains: Codable, Equatable, Sendable {
+ var red: Double, green: Double, blue: Double
+
+ /// Ramène le plus petit gain à 1 (l'iPhone refuse moins), puis plafonne au maximum de l'appareil.
+ /// `saturated` : la correction voulue dépasse ce que le capteur accepte (trop profond, trop loin).
+ func fitted(max: Double) -> (gains: ColorGains, saturated: Bool) {
+ let low = Swift.max(Swift.min(red, green, blue), 0.01)
+ let wanted = [red / low, green / low, blue / low]
+ let clamped = wanted.map { Swift.min(Swift.max($0, 1), max) }
+ return (ColorGains(red: clamped[0], green: clamped[1], blue: clamped[2]), wanted.contains { $0 > max * 1.001 })
+ }
+
+ /// Glisse vers `target` sans à-coups (suivi automatique).
+ func moved(toward target: ColorGains, by weight: Double) -> ColorGains {
+ ColorGains(red: red + (target.red - red) * weight, green: green + (target.green - green) * weight,
+ blue: blue + (target.blue - blue) * weight)
+ }
+
+ var label: String { String(format: "R×%.2f V×%.2f B×%.2f", red, green, blue) }
+}
+
enum Stabilization: String, Codable, Sendable, CaseIterable { case off, standard, cinematic, extended }
struct VideoQuality: Codable, Equatable, Hashable, Sendable {
@@ -42,10 +67,13 @@ struct CameraSettings: Codable, Equatable, Sendable {
/// Secondes sans bouton avant la veille de l'écran ; 0 = jamais.
var sleepAfter = 120
var orientation = ScreenOrientation.landscape
+ var colorMode = ColorMode.underwater
+ /// Gains du dernier calibrage sur une surface claire.
+ var calibration: ColorGains?
/// Mode développement : journal CSV et affichages supplémentaires.
var developer = false
- static let key = "cameraSettings3"
+ static let key = "cameraSettings4"
static func load() -> CameraSettings {
guard let data = UserDefaults.standard.data(forKey: key),
let value = try? JSONDecoder().decode(CameraSettings.self, from: data) else { return CameraSettings() }
@@ -67,10 +95,11 @@ struct CameraCapabilities: Equatable, Sendable {
}
enum CameraSetting: Sendable, CaseIterable {
- case photoFormat, exposure, stabilization, videoQuality, sleep, orientation, developer
+ case color, photoFormat, exposure, stabilization, videoQuality, sleep, orientation, developer
var title: String {
switch self {
+ case .color: "Couleurs"
case .photoFormat: "Format photo"
case .exposure: "Exposition"
case .stabilization: "Stabilisation vidéo"
@@ -83,10 +112,13 @@ enum CameraSetting: Sendable, CaseIterable {
}
enum SettingValue: Equatable, Sendable {
- case photoFormat(PhotoFormat), exposure(Double), stabilization(Stabilization), videoQuality(VideoQuality), sleep(Int), orientation(ScreenOrientation), developer(Bool)
+ case color(ColorMode), photoFormat(PhotoFormat), exposure(Double), stabilization(Stabilization), videoQuality(VideoQuality), sleep(Int), orientation(ScreenOrientation), developer(Bool)
var label: String {
switch self {
+ case .color(.system): "iPhone (sans correction)"
+ case .color(.underwater): "Sous l'eau, automatique"
+ case .color(.calibrated): "Sous l'eau, calibrées"
case .photoFormat(.heif): "HEIF"
case .photoFormat(.rawHeif): "ProRAW + HEIF"
case .exposure(let v): v == 0 ? "0" : String(format: "%+.1f", v)
@@ -111,6 +143,7 @@ extension CameraSettings {
func options(for setting: CameraSetting, _ caps: CameraCapabilities) -> [SettingValue] {
switch setting {
+ case .color: ColorMode.allCases.map { .color($0) }
case .photoFormat: (caps.proRAW ? PhotoFormat.allCases : [.heif]).map { .photoFormat($0) }
case .exposure: Self.biasSteps.filter { $0 >= caps.minBias && $0 <= caps.maxBias }.map { .exposure($0) }
case .stabilization: caps.stabilizations.map { .stabilization($0) }
@@ -123,6 +156,7 @@ extension CameraSettings {
func current(_ setting: CameraSetting) -> SettingValue {
switch setting {
+ case .color: .color(colorMode)
case .photoFormat: .photoFormat(photoFormat)
case .exposure: .exposure(exposureBias)
case .stabilization: .stabilization(stabilization)
@@ -135,6 +169,7 @@ extension CameraSettings {
mutating func set(_ value: SettingValue) {
switch value {
+ case .color(let v): colorMode = v
case .photoFormat(let v): photoFormat = v
case .exposure(let v): exposureBias = v
case .stabilization(let v): stabilization = v
diff --git a/OpenMerou/UI/CameraScreen.swift b/OpenMerou/UI/CameraScreen.swift
@@ -128,6 +128,7 @@ struct CameraScreen: View {
"P ext? \(n(r.externalPressurePa, "%.0f")) Pa T \(n(r.temperatureC, "%.2f")) °C",
"pompe \(r.pumpState.map { "\($0)" } ?? "—") 1628 \(r.alarmRaw.map { String(format: "%02X", $0) } ?? "—") batt \(r.batteryPercent.map(String.init) ?? "—") %",
"étape \(String(describing: v.step).prefix { $0 != "(" }) iPhone thermique \(ProcessInfo.processInfo.thermalState.rawValue)",
+ "couleurs \(model.camera.gains?.label ?? "iPhone")\(model.camera.gainsSaturated ? " MAX" : "")",
"journal \(DevLog.shared.url?.lastPathComponent ?? "—")",
]
return HStack {
@@ -168,6 +169,12 @@ struct CameraScreen: View {
Text(model.settings.mode == .photo ? "PHOTO" : "VIDÉO")
if model.settings.mode == .video { Text(model.settings.videoQuality.label) }
if model.settings.mode == .photo, model.settings.photoFormat == .rawHeif { Text("RAW") }
+ switch model.settings.colorMode {
+ case .system: EmptyView()
+ case .underwater: Label("AUTO", systemImage: "drop.fill")
+ case .calibrated: Label("CAL.", systemImage: "drop.fill")
+ }
+ if model.camera.gainsSaturated { Label("ROUGE MAX", systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) }
if model.settings.exposureBias != 0 { Text(String(format: "%+.1f EV", model.settings.exposureBias)) }
Spacer()
let labels = model.camera.capabilities.zoomLabels
diff --git a/OpenMerouTests/CameraMenuTests.swift b/OpenMerouTests/CameraMenuTests.swift
@@ -20,7 +20,7 @@ struct CameraMenuTests {
menu.open()
_ = menu.handle(.up, settings: &settings, caps: caps) // boucle vers Réglages
_ = menu.handle(.right, settings: &settings, caps: caps)
- for _ in 0..<3 { _ = menu.handle(.down, settings: &settings, caps: caps) } // Qualité vidéo
+ for _ in 0..<4 { _ = menu.handle(.down, settings: &settings, caps: caps) } // Qualité vidéo
_ = menu.handle(.right, settings: &settings, caps: caps)
#expect(menu.level == .options(.videoQuality, 0))
_ = menu.handle(.down, settings: &settings, caps: caps)
@@ -35,12 +35,28 @@ struct CameraMenuTests {
menu.open()
_ = menu.handle(.up, settings: &settings, caps: caps)
_ = menu.handle(.right, settings: &settings, caps: caps)
+ _ = menu.handle(.down, settings: &settings, caps: caps)
_ = menu.handle(.right, settings: &settings, caps: caps) // Format photo
_ = menu.handle(.down, settings: &settings, caps: caps)
_ = menu.handle(.left, settings: &settings, caps: caps)
#expect(settings.photoFormat == .heif)
}
+ @Test func gainsAreFittedToTheSensor() {
+ // Eau bleue : il faudrait ×6 de rouge, le capteur plafonne à ×4.
+ let deep = ColorGains(red: 3.0, green: 0.6, blue: 0.5).fitted(max: 4)
+ #expect(deep.gains == ColorGains(red: 4, green: 1.2, blue: 1))
+ #expect(deep.saturated)
+ let shallow = ColorGains(red: 2.4, green: 1.0, blue: 1.6).fitted(max: 4)
+ #expect(shallow.gains == ColorGains(red: 2.4, green: 1, blue: 1.6))
+ #expect(!shallow.saturated)
+ }
+
+ @Test func gainsMoveSmoothly() {
+ let moved = ColorGains(red: 1, green: 1, blue: 1).moved(toward: ColorGains(red: 3, green: 1, blue: 2), by: 0.25)
+ #expect(moved == ColorGains(red: 1.5, green: 1, blue: 1.25))
+ }
+
@Test func rawOnlyWhenSupported() {
var noRaw = caps
noRaw.proRAW = false
diff --git a/fastlane/Fastfile b/fastlane/Fastfile
@@ -122,9 +122,9 @@ platform :ios do
end
texts = {
"fr-CA" => ["App libre et gratuite pour boîtier de plongée compatible : boutons, pompe à vide, capteurs, caméra.",
- "0.7 : boîtier simulé (bouton « Simuler un boîtier » au premier écran, boutons à l'écran) pour les démonstrations ; mode développement (Menu → Réglages → Développement) : valeurs brutes à l'écran et journal CSV des mesures et des événements, à récupérer par le bouton ⓘ ou dans l'app Fichiers. À faire dans l'eau : activer le mode, plonger le boîtier, noter la profondeur réelle."],
+ "0.8 : correction des couleurs par le capteur. Réglages → Couleurs : iPhone, sous l'eau automatique (par défaut), ou calibrées. Appui long sur le bouton bas : calibrer sur ce que l'on vise (sable, ardoise blanche). Témoin « ROUGE MAX » quand le capteur est au bout de sa correction. À essayer dans l'eau avec le mode développement."],
"en-CA" => ["Free, open-source app for compatible dive housings: buttons, vacuum pump, sensors, camera.",
- "0.7: simulated housing (Simulate a housing on the first screen, on-screen buttons) for demos; developer mode (Menu → Settings → Development): raw values on screen and a CSV log of measurements and events, shared from the ⓘ button or the Files app. In water: turn it on, submerge the housing, note the real depth."],
+ "0.8: on-sensor color correction. Settings → Colors: iPhone, underwater automatic (default), or calibrated. Long press on the down button: calibrate on what you aim at (sand, white slate). RED MAX indicator when the sensor reaches its limit. Please try in water with developer mode on."],
}
_, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations")
texts.each do |locale, (description, _)|
diff --git a/project.yml b/project.yml
@@ -9,7 +9,7 @@ settings:
base:
DEVELOPMENT_TEAM: CM5RQKJH56
CODE_SIGN_STYLE: Automatic
- MARKETING_VERSION: "0.7"
+ MARKETING_VERSION: "0.8"
CURRENT_PROJECT_VERSION: "1"
SWIFT_VERSION: "6.0"
targets: