Commit 675d3eb0 authored by Kourser's avatar Kourser
Browse files

Socle projet et boucle de capture locale

Lots L0 et L1 du cahier des charges, sans synchronisation.

EnvorennCore — Swift pur, mode langage 6, aucune API de plateforme :
modele, format du coffre, arborescence, acces disque, recuperation des
captures interrompues. 39 tests executables sans simulateur.

App — SwiftUI, AVFoundation, CryptoKit : capture, bibliotheque groupee
par mois, recherche, lecture, corbeille a 30 jours.

Choix structurants, detailles dans le README :
- capture en PCM/CAF transcodee a l'arret. Seule facon de tenir
  EF-CAP-12 : un M4A tronque par un plantage est irrecuperable, son
  index n'etant ecrit qu'a la fermeture.
- pas d'index SQLite tant qu'il n'y a pas de synchronisation. ENF-06
  n'est pas tenue en l'etat, dette D2 documentee, seuil de revision
  a environ 2000 memos.
- cible application en mode langage Swift 5, paquet coeur en mode 6.
  Deviation temporaire du chapitre 11, dette D1.

Projet Xcode engendre par XcodeGen, non versionne. Aucune dependance
a l'execution.

Non verifie : rien n'a ete compile, Xcode etant absent du poste de
redaction. Points de risque listes dans le README.

Co-Authored-By: Claude (RCA)
parent 9b97f5ad
Loading
Loading
Loading
Loading
+18
Changes for .gitignore: 18 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Projet Xcode généré par XcodeGen — la source de vérité est project.yml
Envorenn.xcodeproj/

# Xcode
xcuserdata/
*.xcworkspace/xcuserdata/
DerivedData/
build/
*.xcuserstate
*.xcscmblueprint

# Swift Package Manager
.build/
.swiftpm/
Packages/*/.build/

# macOS
.DS_Store
+63
Changes for App/Audio/AudioSessionController.swift: 63 added lines, 0 removed lines.
Original line number Diff line number Diff line
import AVFoundation
import Foundation

/// Session audio : autorisation micro, catégorie, interruptions, changements de
/// route.
@MainActor
final class AudioSessionController {

    enum SessionError: LocalizedError {
        case permissionDenied

        var errorDescription: String? {
            switch self {
            case .permissionDenied:
                "Envorenn n'a pas accès au micro. Autorisez-le dans Réglages › Envorenn."
            }
        }
    }

    private let session = AVAudioSession.sharedInstance()

    var hasPermission: Bool {
        AVAudioApplication.shared.recordPermission == .granted
    }

    func requestPermission() async -> Bool {
        if hasPermission { return true }
        return await withCheckedContinuation { continuation in
            AVAudioApplication.requestRecordPermission { granted in
                continuation.resume(returning: granted)
            }
        }
    }

    /// Active la session pour la capture.
    ///
    /// `.playAndRecord` plutôt que `.record` : la même session sert à la
    /// relecture immédiate après enregistrement, et changer de catégorie coupe
    /// brièvement l'audio.
    func activateForRecording() throws {
        try session.setCategory(
            .playAndRecord,
            mode: .default,
            options: [.allowBluetooth, .allowBluetoothA2DP, .defaultToSpeaker]
        )
        try session.setActive(true)
    }

    func activateForPlayback() throws {
        try session.setCategory(.playback, mode: .default)
        try session.setActive(true)
    }

    func deactivate() {
        try? session.setActive(false, options: .notifyOthersOnDeactivation)
    }

    /// Espace disque réellement disponible, en octets (EF-CAP-09).
    static func availableCapacity(at url: URL) -> Int64? {
        let values = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
        return values?.volumeAvailableCapacityForImportantUsage
    }
}
+170
Changes for App/Audio/AudioTranscoder.swift: 170 added lines, 0 removed lines.
Original line number Diff line number Diff line
import AVFoundation
import Foundation
import EnvorennCore

/// Convertit la capture PCM/CAF vers le format final du coffre.
///
/// Pourquoi un couple lecteur/écrivain plutôt qu'`AVAssetExportSession` : les
/// préréglages d'export imposent leurs propres débit, fréquence et nombre de
/// canaux. Le § 7.3 du cahier des charges fixe 96 kb/s mono à 48 kHz, et ces
/// valeurs sont inscrites dans les métadonnées du mémo. Un export dont on ne
/// maîtrise pas les paramètres produirait un fichier dont la description ment.
enum AudioTranscoder {

    enum TranscodeError: LocalizedError {
        case noAudioTrack
        case readerFailed(String)
        case writerFailed(String)

        var errorDescription: String? {
            switch self {
            case .noAudioTrack:
                "Le fichier de capture ne contient aucune piste audio."
            case .readerFailed(let reason):
                "Lecture de la capture impossible : \(reason)"
            case .writerFailed(let reason):
                "Écriture du mémo impossible : \(reason)"
            }
        }
    }

    /// Transcode `source` vers `destination` et renvoie la durée de l'audio.
    @discardableResult
    static func transcode(
        source: URL,
        destination: URL,
        profile: AudioProfile
    ) async throws -> TimeInterval {

        let asset = AVURLAsset(url: source)
        guard try await asset.loadTracks(withMediaType: .audio).first != nil else {
            throw TranscodeError.noAudioTrack
        }
        let duration = try await asset.load(.duration)

        try? FileManager.default.removeItem(at: destination)

        let reader = try AVAssetReader(asset: asset)
        let output = AVAssetReaderAudioMixOutput(
            audioTracks: try await asset.loadTracks(withMediaType: .audio),
            audioSettings: readerSettings(for: profile)
        )
        guard reader.canAdd(output) else {
            throw TranscodeError.readerFailed("sortie audio refusée")
        }
        reader.add(output)

        let writer = try AVAssetWriter(outputURL: destination, fileType: fileType(for: profile))
        let input = AVAssetWriterInput(mediaType: .audio, outputSettings: writerSettings(for: profile))
        input.expectsMediaDataInRealTime = false
        guard writer.canAdd(input) else {
            throw TranscodeError.writerFailed("entrée audio refusée")
        }
        writer.add(input)

        guard reader.startReading() else {
            throw TranscodeError.readerFailed(reader.error?.localizedDescription ?? "démarrage impossible")
        }
        guard writer.startWriting() else {
            throw TranscodeError.writerFailed(writer.error?.localizedDescription ?? "démarrage impossible")
        }
        writer.startSession(atSourceTime: .zero)

        let queue = DispatchQueue(label: "eu.cythin.envorenn.transcode")
        let gate = ResumeGate()

        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
            input.requestMediaDataWhenReady(on: queue) {
                while input.isReadyForMoreMediaData {
                    guard let buffer = output.copyNextSampleBuffer() else {
                        input.markAsFinished()
                        if gate.close() { continuation.resume() }
                        return
                    }
                    if !input.append(buffer) {
                        input.markAsFinished()
                        if gate.close() {
                            continuation.resume(
                                throwing: TranscodeError.writerFailed(
                                    writer.error?.localizedDescription ?? "ajout d'échantillons refusé"
                                )
                            )
                        }
                        return
                    }
                }
            }
        }

        await writer.finishWriting()

        if writer.status == .failed {
            throw TranscodeError.writerFailed(writer.error?.localizedDescription ?? "état d'échec")
        }
        if reader.status == .failed {
            throw TranscodeError.readerFailed(reader.error?.localizedDescription ?? "état d'échec")
        }

        return CMTimeGetSeconds(duration)
    }

    // MARK: - Réglages

    private static func readerSettings(for profile: AudioProfile) -> [String: Any] {
        [
            AVFormatIDKey: Int(kAudioFormatLinearPCM),
            AVSampleRateKey: profile.sampleRate,
            AVNumberOfChannelsKey: profile.channels,
            AVLinearPCMBitDepthKey: profile.captureBitDepth,
            AVLinearPCMIsFloatKey: false,
            AVLinearPCMIsBigEndianKey: false,
            AVLinearPCMIsNonInterleaved: false
        ]
    }

    private static func writerSettings(for profile: AudioProfile) -> [String: Any] {
        switch profile {
        case .voice:
            [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: profile.sampleRate,
                AVNumberOfChannelsKey: profile.channels,
                AVEncoderBitRateKey: profile.bitrateBps ?? 96_000
            ]
        case .archive:
            [
                AVFormatIDKey: Int(kAudioFormatLinearPCM),
                AVSampleRateKey: profile.sampleRate,
                AVNumberOfChannelsKey: profile.channels,
                AVLinearPCMBitDepthKey: profile.captureBitDepth,
                AVLinearPCMIsFloatKey: false,
                AVLinearPCMIsBigEndianKey: false,
                AVLinearPCMIsNonInterleaved: false
            ]
        }
    }

    private static func fileType(for profile: AudioProfile) -> AVFileType {
        switch profile {
        case .voice: .m4a
        case .archive: .wav
        }
    }
}

/// Le bloc passé à `requestMediaDataWhenReady` est rappelé plusieurs fois et
/// depuis une file de travail ; la continuation, elle, ne doit être reprise
/// qu'une seule fois.
private final class ResumeGate: @unchecked Sendable {
    private let lock = NSLock()
    private var closed = false

    /// Renvoie `true` pour le premier appelant seulement.
    func close() -> Bool {
        lock.lock()
        defer { lock.unlock() }
        if closed { return false }
        closed = true
        return true
    }
}
+126
Changes for App/Audio/PlaybackController.swift: 126 added lines, 0 removed lines.
Original line number Diff line number Diff line
import AVFoundation
import Foundation
import Observation
import EnvorennCore

/// Lecture d'un mémo (EF-BIB-02).
@MainActor
@Observable
final class PlaybackController: NSObject, AVAudioPlayerDelegate {

    private(set) var currentID: MemoID?
    private(set) var isPlaying = false
    private(set) var position: TimeInterval = 0
    private(set) var duration: TimeInterval = 0
    private(set) var errorMessage: String?

    var rate: Float = 1 {
        didSet {
            player?.rate = rate
        }
    }

    private var player: AVAudioPlayer?
    private var ticker: Task<Void, Never>?
    private let session: AudioSessionController

    init(session: AudioSessionController) {
        self.session = session
        super.init()
    }

    func toggle(_ memo: Memo) {
        if currentID == memo.id {
            isPlaying ? pause() : resume()
        } else {
            play(memo)
        }
    }

    func play(_ memo: Memo) {
        stop()
        errorMessage = nil

        do {
            try session.activateForPlayback()
            let player = try AVAudioPlayer(contentsOf: memo.audioURL)
            player.delegate = self
            player.enableRate = true
            player.rate = rate
            player.prepareToPlay()
            player.play()

            self.player = player
            currentID = memo.id
            duration = player.duration
            position = 0
            isPlaying = true
            startTicking()
        } catch {
            errorMessage = "Lecture impossible : \(error.localizedDescription)"
        }
    }

    func pause() {
        player?.pause()
        isPlaying = false
        stopTicking()
    }

    func resume() {
        guard let player else { return }
        try? session.activateForPlayback()
        player.play()
        isPlaying = true
        startTicking()
    }

    func stop() {
        stopTicking()
        player?.stop()
        player = nil
        currentID = nil
        isPlaying = false
        position = 0
        duration = 0
    }

    func seek(to time: TimeInterval) {
        guard let player else { return }
        player.currentTime = min(max(0, time), player.duration)
        position = player.currentTime
    }

    func skip(by offset: TimeInterval) {
        guard let player else { return }
        seek(to: player.currentTime + offset)
    }

    /// Le mémo en cours a-t-il changé de fichier sous nos pieds ? Utilisé après
    /// une mise à la corbeille pour éviter de continuer à lire un fichier déplacé.
    func stopIfPlaying(_ id: MemoID) {
        if currentID == id { stop() }
    }

    private func startTicking() {
        stopTicking()
        ticker = Task { [weak self] in
            while !Task.isCancelled {
                try? await Task.sleep(for: .milliseconds(100))
                guard let self else { return }
                self.position = self.player?.currentTime ?? 0
            }
        }
    }

    private func stopTicking() {
        ticker?.cancel()
        ticker = nil
    }

    nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        Task { @MainActor [weak self] in
            self?.stop()
        }
    }
}
+298
Changes for App/Audio/RecordingController.swift: 298 added lines, 0 removed lines.
Original line number Diff line number Diff line
import AVFoundation
import Foundation
import Observation
import EnvorennCore

/// Pilote la capture audio.
///
/// La capture écrit du PCM linéaire dans un conteneur CAF, jamais directement
/// le format final. Un CAF/PCM tronqué par un plantage reste lisible jusqu'à son
/// dernier échantillon ; un M4A tronqué est perdu, son index n'étant écrit qu'à
/// la fermeture. Le transcodage vers le format du coffre a lieu à l'arrêt
/// (voir `RecordingFinalizer`).
@MainActor
@Observable
final class RecordingController {

    enum State: Equatable {
        case idle
        case recording
        case paused
        case finalizing
    }

    enum RecordingError: LocalizedError {
        case notEnoughSpace(minutesAvailable: Int)
        case recorderRefused

        var errorDescription: String? {
            switch self {
            case .notEnoughSpace(let minutes):
                "Espace insuffisant : environ \(minutes) minutes d'enregistrement disponibles."
            case .recorderRefused:
                "Le micro n'a pas pu démarrer."
            }
        }
    }

    /// Seuil d'alerte de EF-CAP-09.
    private static let minimumMinutes = 15
    /// Arrêt propre imposé par EF-CAP-09.
    private static let hardStopBytes: Int64 = 30 * 1024 * 1024

    private(set) var state: State = .idle
    private(set) var elapsed: TimeInterval = 0
    /// Niveau d'entrée normalisé entre 0 et 1 (EF-CAP-04).
    private(set) var level: Float = 0
    private(set) var errorMessage: String?

    private let layout: VaultLayout
    private let scanner: PendingRecordingScanner
    private let session: AudioSessionController
    private let clock: any WallClock

    private var recorder: AVAudioRecorder?
    private var current: PendingRecording?
    private var ticker: Task<Void, Never>?
    private var observers: [NSObjectProtocol] = []

    init(
        layout: VaultLayout,
        scanner: PendingRecordingScanner,
        session: AudioSessionController,
        clock: any WallClock
    ) {
        self.layout = layout
        self.scanner = scanner
        self.session = session
        self.clock = clock
        observeSessionEvents()
    }

    deinit {
        for observer in observers {
            NotificationCenter.default.removeObserver(observer)
        }
    }

    // MARK: - Cycle de vie de la capture

    /// Démarre un enregistrement et renvoie sa description.
    ///
    /// EF-CAP-02 : le micro démarre avant l'écriture du descripteur. Si
    /// l'application meurt entre les deux, le balayage de `.pending/` retrouve
    /// la capture à partir du seul fichier audio.
    @discardableResult
    func start(profile: AudioProfile = .voice) async throws -> PendingRecording {
        errorMessage = nil

        guard await session.requestPermission() else {
            throw AudioSessionController.SessionError.permissionDenied
        }
        try checkFreeSpace(for: profile)
        try session.activateForRecording()

        try FileManager.default.createDirectory(
            at: layout.pendingDirectory,
            withIntermediateDirectories: true
        )

        let startedAt = clock.now
        let id = MemoID(date: startedAt)
        let captureFile = PendingRecording.captureFilename(for: id)
        let captureURL = layout.pendingDirectory.appending(path: captureFile)

        let recorder = try AVAudioRecorder(url: captureURL, settings: captureSettings(for: profile))
        recorder.isMeteringEnabled = true
        guard recorder.prepareToRecord(), recorder.record() else {
            throw RecordingError.recorderRefused
        }

        self.recorder = recorder
        let recording = PendingRecording(
            id: id,
            startedAt: startedAt,
            profile: profile,
            captureFile: captureFile
        )
        self.current = recording

        // Après le démarrage, pas avant.
        try? scanner.write(recording)

        state = .recording
        elapsed = 0
        startTicking()

        return recording
    }

    func pause() {
        guard state == .recording else { return }
        recorder?.pause()
        state = .paused
    }

    func resume() {
        guard state == .paused else { return }
        try? session.activateForRecording()
        recorder?.record()
        state = .recording
    }

    /// Arrête la capture et renvoie sa description, prête à être finalisée.
    func stop() -> PendingRecording? {
        guard let recording = current else { return nil }
        stopTicking()
        recorder?.stop()
        recorder = nil
        current = nil
        session.deactivate()
        state = .finalizing
        return recording
    }

    /// Abandonne la capture en cours et supprime ses fichiers.
    func cancel() {
        guard let recording = current else { return }
        stopTicking()
        recorder?.stop()
        recorder = nil
        current = nil
        session.deactivate()
        scanner.discard(recording)
        state = .idle
        elapsed = 0
        level = 0
    }

    func finishedFinalizing() {
        state = .idle
        elapsed = 0
        level = 0
    }

    // MARK: - Compteur et niveau

    private func startTicking() {
        stopTicking()
        ticker = Task { [weak self] in
            while !Task.isCancelled {
                try? await Task.sleep(for: .milliseconds(100))
                guard let self else { return }
                await self.tick()
            }
        }
    }

    private func stopTicking() {
        ticker?.cancel()
        ticker = nil
    }

    private func tick() {
        guard let recorder, state == .recording else { return }
        recorder.updateMeters()
        elapsed = recorder.currentTime
        level = Self.normalizedLevel(fromDecibels: recorder.averagePower(forChannel: 0))

        if let available = AudioSessionController.availableCapacity(at: layout.root),
           available < Self.hardStopBytes {
            errorMessage = RecordingError.notEnoughSpace(minutesAvailable: 0).localizedDescription
            _ = stop()
        }
    }

    /// Les décibels rendus par AVAudioRecorder vont de -160 à 0 et sont très
    /// tassés vers le bas. -50 dB comme plancher visuel donne un indicateur qui
    /// bouge à hauteur de voix normale.
    static func normalizedLevel(fromDecibels decibels: Float) -> Float {
        let floor: Float = -50
        guard decibels > floor else { return 0 }
        return min(1, (decibels - floor) / -floor)
    }

    // MARK: - Interruptions et routes

    private func observeSessionEvents() {
        let center = NotificationCenter.default

        // EF-CAP-07 : appel entrant, alarme, Siri. L'audio déjà capté est
        // conservé dans tous les cas — le fichier CAF reste sur le disque.
        observers.append(
            center.addObserver(
                forName: AVAudioSession.interruptionNotification,
                object: AVAudioSession.sharedInstance(),
                queue: .main
            ) { [weak self] notification in
                MainActor.assumeIsolated {
                    self?.handleInterruption(notification)
                }
            }
        )

        // EF-CAP-08 : casque débranché, Bluetooth déconnecté.
        observers.append(
            center.addObserver(
                forName: AVAudioSession.routeChangeNotification,
                object: AVAudioSession.sharedInstance(),
                queue: .main
            ) { [weak self] notification in
                MainActor.assumeIsolated {
                    self?.handleRouteChange(notification)
                }
            }
        )
    }

    private func handleInterruption(_ notification: Notification) {
        guard let raw = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
              let type = AVAudioSession.InterruptionType(rawValue: raw)
        else { return }

        switch type {
        case .began:
            pause()
        case .ended:
            let optionsRaw = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0
            if AVAudioSession.InterruptionOptions(rawValue: optionsRaw).contains(.shouldResume) {
                resume()
            }
        @unknown default:
            break
        }
    }

    private func handleRouteChange(_ notification: Notification) {
        guard let raw = notification.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt,
              let reason = AVAudioSession.RouteChangeReason(rawValue: raw)
        else { return }

        // Une entrée qui disparaît en cours de capture bascule sur le micro
        // intégré ; on réactive la session pour que la nouvelle route prenne.
        if reason == .oldDeviceUnavailable, state == .recording {
            try? session.activateForRecording()
        }
    }

    // MARK: - Espace disque

    private func checkFreeSpace(for profile: AudioProfile) throws {
        guard let available = AudioSessionController.availableCapacity(at: layout.root) else { return }
        let minutes = Int(available / Int64(profile.captureBytesPerSecond) / 60)
        if minutes < Self.minimumMinutes {
            throw RecordingError.notEnoughSpace(minutesAvailable: max(0, minutes))
        }
    }

    private func captureSettings(for profile: AudioProfile) -> [String: Any] {
        [
            AVFormatIDKey: Int(kAudioFormatLinearPCM),
            AVSampleRateKey: Double(profile.sampleRate),
            AVNumberOfChannelsKey: profile.channels,
            AVLinearPCMBitDepthKey: profile.captureBitDepth,
            AVLinearPCMIsFloatKey: false,
            AVLinearPCMIsBigEndianKey: false
        ]
    }
}
Loading