import AVFoundation import Photos import UIKit /// Il reel finito: 1080×1920, 30 fps. La sessione registra in 16:9 ruotato, cioè già 9:16: niente tagli. enum ReelCanvas { static let w: CGFloat = 1080 static let h: CGFloat = 1920 } /// Un ingresso audio di iOS (microfono dell'iPhone, Bluetooth, USB, cuffie col filo). struct MicInput: Identifiable, Hashable { let id: String // portUID let name: String let type: AVAudioSession.Port var icon: String { switch type { case .bluetoothHFP: return "dot.radiowaves.left.and.right" case .usbAudio: return "cable.connector" case .headsetMic: return "headphones" case .builtInMic: return "iphone" default: return "mic" } } var kind: String { switch type { case .bluetoothHFP: return "Bluetooth" case .usbAudio: return "USB" case .headsetMic: return "col filo" case .builtInMic: return "integrato" default: return type.rawValue } } } final class Camera: NSObject, ObservableObject { let session = AVCaptureSession() private let queue = DispatchQueue(label: "camera.session") private let movieOutput = AVCaptureMovieFileOutput() /// Fotogrammi per l'anteprima sull'Apple Watch (da iOS 16 convive con la registrazione su file). private let frameOutput = AVCaptureVideoDataOutput() private let frameQueue = DispatchQueue(label: "camera.frames") private(set) var device: AVCaptureDevice? private var videoInput: AVCaptureDeviceInput? private var zoomObs: NSKeyValueObservation? private var constituentObs: NSKeyValueObservation? /// Il preview layer, per rimettere rotazione e specchiatura quando si cambia fotocamera. weak var previewLayer: AVCaptureVideoPreviewLayer? /// Rotazione per avere il verticale. La posteriore vuole 90; la frontale dell'iPhone 17 (sensore quadrato) no: /// con 90 compariva girata di lato. Per la frontale l'angolo lo dice il RotationCoordinator di Apple. private(set) var captureAngle: CGFloat = 90 private(set) var previewAngle: CGFloat = 90 /// Con la frontale l'anteprima è a specchio, come la Fotocamera di Apple (più facile muoversi); il file mai. private(set) var previewMirrored = false private var rotationCoordinator: AVCaptureDevice.RotationCoordinator? /// Ingrandimento della lente più larga rispetto alla 1× (0,5 se c'è l'ultra-grandangolo). private var base: CGFloat = 1 private var configured = false @Published var position: AVCaptureDevice.Position = .back @Published var displayZoom: CGFloat = 1 @Published var presets: [CGFloat] = [1] @Published var lensName = "" @Published var macroAvailable = false @Published var macroEnabled = false // per i reel la lente la sceglie lo zoom, non la distanza (24/11) @Published var macroActive = false @Published var torchAvailable = false @Published var torchOn = false @Published var aeafLocked = false @Published var exposureBias: Float = 0 @Published var use4K = true @Published var recording = false @Published var elapsed: TimeInterval = 0 /// Livello del microfono in dB (da −60 a 0), media e picco. @Published var audioLevel: Float = -60 @Published var audioPeak: Float = -60 @Published var micName = "" /// Gli ingressi audio disponibili adesso, e quello scelto nelle impostazioni ("" = lascia fare a iOS). @Published var inputs: [MicInput] = [] @Published var micUID: String = UserDefaults.standard.string(forKey: "micUID") ?? "" @Published var lastThumb: UIImage? @Published var message: String? @Published var authorized = true @Published var saving = false /// Come la Fotocamera di Apple: all'avvio della ripresa il bilanciamento del bianco si blocca e resta quello /// per tutto il video (si inquadra un foglio bianco, si parte, si toglie il foglio). Si sblocca alla fine. @Published var lockWBWhileRecording = UserDefaults.standard.object(forKey: "bloccaBianco") as? Bool ?? true { didSet { UserDefaults.standard.set(lockWBWhileRecording, forKey: "bloccaBianco") } } @Published var wbLocked = false private var startDate: Date? private var meterTimer: Timer? func start() { WatchLink.shared.activate(self) AVCaptureDevice.requestAccess(for: .video) { okV in AVCaptureDevice.requestAccess(for: .audio) { okA in DispatchQueue.main.async { self.authorized = okV if !okA { self.message = "Senza microfono il video non ha audio" } } guard okV else { return } self.queue.async { self.configure() } } } NotificationCenter.default.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] _ in guard let self else { return } // un microfono Bluetooth acceso dopo l'app: se è quello scelto, lo si riprende if !self.recording, !self.micUID.isEmpty, AVAudioSession.sharedInstance().currentRoute.inputs.first?.uid != self.micUID { self.applyPreferredInput() } self.refreshInputs() self.updateMicName() } } private func configure() { guard !configured else { return } configured = true // La sessione audio la configura l'app, non AVCaptureSession: serve per poter registrare da un microfono // Bluetooth (profilo HFP) o USB invece che da quello dell'iPhone. session.automaticallyConfiguresApplicationAudioSession = false configureAudioSession() session.beginConfiguration() if let mic = AVCaptureDevice.default(for: .audio), let ai = try? AVCaptureDeviceInput(device: mic), session.canAddInput(ai) { session.addInput(ai) } if session.canAddOutput(movieOutput) { session.addOutput(movieOutput) } frameOutput.alwaysDiscardsLateVideoFrames = true frameOutput.setSampleBufferDelegate(self, queue: frameQueue) if session.canAddOutput(frameOutput) { session.addOutput(frameOutput) } session.commitConfiguration() setupVideo(.back) session.startRunning() DispatchQueue.main.async { self.updateMicName() self.startMeter() } } // MARK: fotocamera private func pickDevice(_ pos: AVCaptureDevice.Position) -> AVCaptureDevice? { if pos == .front { return AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) } // Come l'app Fotocamera: un solo ingresso, la tripla virtuale (0,5× ultra-grandangolo, 1× principale, 4× tele). let types: [AVCaptureDevice.DeviceType] = [.builtInTripleCamera, .builtInDualWideCamera, .builtInWideAngleCamera] let disc = AVCaptureDevice.DiscoverySession(deviceTypes: types, mediaType: .video, position: .back) return types.compactMap { t in disc.devices.first { $0.deviceType == t } }.first } private func setupVideo(_ pos: AVCaptureDevice.Position) { guard let dev = pickDevice(pos), let newInput = try? AVCaptureDeviceInput(device: dev) else { DispatchQueue.main.async { self.message = "Fotocamera non disponibile" } return } session.beginConfiguration() if let old = videoInput { session.removeInput(old) } if session.canAddInput(newInput) { session.addInput(newInput) videoInput = newInput } else if let old = videoInput { session.addInput(old) session.commitConfiguration() return } applyPreset() session.commitConfiguration() device = dev let sw = dev.virtualDeviceSwitchOverVideoZoomFactors.map { CGFloat(truncating: $0) } base = dev.isVirtualDevice ? 1 / (sw.first ?? 2) : 1 var p: [CGFloat] = [] if base < 1 { p.append(0.5) } p.append(1) // 2× anche con la frontale (zoom digitale), se la fotocamera ci arriva. if pos == .back || dev.maxAvailableVideoZoomFactor >= 2 / base { p.append(2) } if sw.count > 1 { p.append((sw[1] * base).rounded()) } do { try dev.lockForConfiguration() if dev.isFocusModeSupported(.continuousAutoFocus) { dev.focusMode = .continuousAutoFocus } if dev.isExposureModeSupported(.continuousAutoExposure) { dev.exposureMode = .continuousAutoExposure } dev.setExposureTargetBias(0) dev.videoZoomFactor = max(dev.minAvailableVideoZoomFactor, 1 / base) dev.unlockForConfiguration() } catch {} applyFrameRate() applyMacro() previewMirrored = pos == .front if pos == .back { captureAngle = 90; previewAngle = 90 fixConnections() } else { DispatchQueue.main.async { let rc = AVCaptureDevice.RotationCoordinator(device: dev, previewLayer: self.previewLayer) self.rotationCoordinator = rc let snap: (CGFloat) -> CGFloat = { (($0 / 90).rounded() * 90).truncatingRemainder(dividingBy: 360) } let cap = snap(rc.videoRotationAngleForHorizonLevelCapture) let prev = snap(rc.videoRotationAngleForHorizonLevelPreview) self.queue.async { self.captureAngle = cap; self.previewAngle = prev self.fixConnections() } } } zoomObs = dev.observe(\.videoZoomFactor, options: [.initial, .new]) { [weak self] d, _ in guard let self else { return } let z = d.videoZoomFactor * self.base DispatchQueue.main.async { self.displayZoom = z } self.updateLensName() } constituentObs = dev.isVirtualDevice ? dev.observe(\.activePrimaryConstituent, options: [.initial, .new]) { [weak self] _, _ in self?.updateLensName() } : nil updateLensName() DispatchQueue.main.async { self.position = pos WatchLink.shared.sendState() self.presets = p self.macroAvailable = dev.isVirtualDevice self.torchAvailable = dev.hasTorch self.torchOn = false self.aeafLocked = false self.exposureBias = 0 } } /// 4K o 1080p, sempre 16:9 (che ruotato diventa il 9:16 del reel). private func applyPreset() { let want: AVCaptureSession.Preset = use4K ? .hd4K3840x2160 : .hd1920x1080 if session.canSetSessionPreset(want) { session.sessionPreset = want } else if session.canSetSessionPreset(.hd1920x1080) { session.sessionPreset = .hd1920x1080 DispatchQueue.main.async { self.use4K = false } } } /// 30 fps fissi, come le registrazioni dei reel di classifica. private func applyFrameRate() { guard let dev = device else { return } let ok = dev.activeFormat.videoSupportedFrameRateRanges.contains { $0.minFrameRate <= 30 && $0.maxFrameRate >= 30 } guard ok else { return } do { try dev.lockForConfiguration() dev.activeVideoMinFrameDuration = CMTime(value: 1, timescale: 30) dev.activeVideoMaxFrameDuration = CMTime(value: 1, timescale: 30) dev.unlockForConfiguration() } catch {} } /// Verticale, mai specchiato (né in anteprima né nel file: quello che si vede è il reel), stabilizzazione spenta /// perché si registra sul treppiede e la stabilizzazione taglia i bordi che l'anteprima mostra. /// Dopo un cambio di fotocamera la sessione ricrea le connessioni in modo asincrono: la rotazione messa subito /// può andare persa (la frontale compariva ruotata di 90°). Si rimette subito e poi ancora a 0,2, 0,5 e 1 secondo. private func fixConnections() { applyConnections() for t in [0.2, 0.5, 1.0] { queue.asyncAfter(deadline: .now() + t) { [weak self] in self?.applyConnections() } } } private func applyConnections() { if let c = movieOutput.connection(with: .video), !movieOutput.isRecording { if c.isVideoRotationAngleSupported(captureAngle) { c.videoRotationAngle = captureAngle } if c.isVideoMirroringSupported { c.automaticallyAdjustsVideoMirroring = false; c.isVideoMirrored = false } if c.isVideoStabilizationSupported { c.preferredVideoStabilizationMode = .off } if movieOutput.availableVideoCodecTypes.contains(.hevc) { movieOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: c) } } if let c = frameOutput.connection(with: .video) { if c.isVideoRotationAngleSupported(captureAngle) { c.videoRotationAngle = captureAngle } if c.isVideoMirroringSupported { c.automaticallyAdjustsVideoMirroring = false; c.isVideoMirrored = false } } let pa = previewAngle let pm = previewMirrored DispatchQueue.main.async { guard let c = self.previewLayer?.connection else { return } if c.isVideoRotationAngleSupported(pa), c.videoRotationAngle != pa { c.videoRotationAngle = pa } if c.isVideoMirroringSupported { c.automaticallyAdjustsVideoMirroring = false; c.isVideoMirrored = pm } } } func flip() { guard !recording else { return } let next: AVCaptureDevice.Position = position == .back ? .front : .back queue.async { self.setupVideo(next) } } func setUse4K(_ on: Bool) { guard !recording else { return } use4K = on queue.async { self.session.beginConfiguration() self.applyPreset() self.session.commitConfiguration() self.applyFrameRate() self.fixConnections() } } private func updateLensName() { guard let d = device else { return } let z = d.videoZoomFactor * base let pc = d.isVirtualDevice ? d.activePrimaryConstituent : d let uw = pc?.deviceType == .builtInUltraWideCamera let m = d.isVirtualDevice && uw && z >= 0.99 var name: String if d.position == .front { name = "fotocamera frontale" } else { switch pc?.deviceType { case .builtInUltraWideCamera?: name = "ultra-grandangolo" case .builtInTelephotoCamera?: name = "teleobiettivo" default: name = "principale" } } DispatchQueue.main.async { self.macroActive = m; self.lensName = name } } private func applyMacro() { guard let dev = device, dev.isVirtualDevice else { return } do { try dev.lockForConfiguration() if macroEnabled { dev.setPrimaryConstituentDeviceSwitchingBehavior(.auto, restrictedSwitchingBehaviorConditions: []) } else { dev.setPrimaryConstituentDeviceSwitchingBehavior(.restricted, restrictedSwitchingBehaviorConditions: [.videoZoomChanged]) } dev.unlockForConfiguration() } catch {} } func toggleMacro() { macroEnabled.toggle() queue.async { self.applyMacro(); self.updateLensName() } } func toggleTorch() { guard let dev = device, dev.hasTorch else { return } let on = !torchOn torchOn = on queue.async { do { try dev.lockForConfiguration() dev.torchMode = on ? .on : .off dev.unlockForConfiguration() } catch {} } } // MARK: zoom var currentDisplayZoom: CGFloat { (device?.videoZoomFactor ?? 1) * base } func setZoom(_ display: CGFloat) { guard let dev = device else { return } let f = max(dev.minAvailableVideoZoomFactor, min(display / base, dev.maxAvailableVideoZoomFactor, 20)) queue.async { do { try dev.lockForConfiguration() // durante la ripresa lo zoom scorre, non salta if self.recording { dev.ramp(toVideoZoomFactor: f, withRate: 4) } else { dev.videoZoomFactor = f } dev.unlockForConfiguration() } catch {} } } // MARK: messa a fuoco ed esposizione func focus(at p: CGPoint, lock: Bool) { guard let dev = device else { return } queue.async { do { try dev.lockForConfiguration() if dev.isFocusPointOfInterestSupported { dev.focusPointOfInterest = p } let fm: AVCaptureDevice.FocusMode = lock ? .autoFocus : .continuousAutoFocus if dev.isFocusModeSupported(fm) { dev.focusMode = fm } if dev.isExposurePointOfInterestSupported { dev.exposurePointOfInterest = p } let em: AVCaptureDevice.ExposureMode = lock ? .autoExpose : .continuousAutoExposure if dev.isExposureModeSupported(em) { dev.exposureMode = em } dev.setExposureTargetBias(0) dev.isSubjectAreaChangeMonitoringEnabled = !lock dev.unlockForConfiguration() } catch {} if lock { DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { self.lockAEAF() } } DispatchQueue.main.async { self.aeafLocked = false; self.exposureBias = 0 } } } private func lockAEAF() { guard let dev = device else { return } queue.async { do { try dev.lockForConfiguration() if dev.isFocusModeSupported(.locked) { dev.focusMode = .locked } if dev.isExposureModeSupported(.locked) { dev.exposureMode = .locked } dev.unlockForConfiguration() } catch {} DispatchQueue.main.async { self.aeafLocked = true } } } func resetFocus() { guard let dev = device else { return } queue.async { do { try dev.lockForConfiguration() if dev.isFocusModeSupported(.continuousAutoFocus) { dev.focusMode = .continuousAutoFocus } if dev.isExposureModeSupported(.continuousAutoExposure) { dev.exposureMode = .continuousAutoExposure } dev.setExposureTargetBias(0) dev.unlockForConfiguration() } catch {} DispatchQueue.main.async { self.aeafLocked = false; self.exposureBias = 0 } } } func setBias(_ b: Float) { guard let dev = device else { return } let v = max(dev.minExposureTargetBias, min(b, dev.maxExposureTargetBias, 2), -2) exposureBias = v queue.async { do { try dev.lockForConfiguration(); dev.setExposureTargetBias(v); dev.unlockForConfiguration() } catch {} } } // MARK: microfono private func configureAudioSession() { let a = AVAudioSession.sharedInstance() do { if #available(iOS 26.0, *) { // audio Bluetooth a banda piena dove il microfono lo supporta (vale solo col modo default), // altrimenti si ripiega sull'HFP, in qualità telefonica try a.setCategory(.playAndRecord, mode: .default, options: [.allowBluetoothHFP, .bluetoothHighQualityRecording, .defaultToSpeaker]) try? a.setPrefersNoInterruptionsFromSystemAlerts(true) } else { try a.setCategory(.playAndRecord, mode: .videoRecording, options: [.allowBluetoothHFP, .defaultToSpeaker]) } try a.setActive(true) } catch { DispatchQueue.main.async { self.message = "Audio: \(error.localizedDescription)" } } applyPreferredInput() } /// Mette il microfono scelto nelle impostazioni, se è collegato; altrimenti lascia scegliere a iOS. func applyPreferredInput() { let a = AVAudioSession.sharedInstance() let uid = UserDefaults.standard.string(forKey: "micUID") ?? "" let port = a.availableInputs?.first { $0.uid == uid } try? a.setPreferredInput(uid.isEmpty ? nil : port) DispatchQueue.main.async { self.refreshInputs() self.updateMicName() if !uid.isEmpty && port == nil { self.message = "Il microfono scelto non è collegato" } } } func chooseMic(_ uid: String) { guard !recording else { return } UserDefaults.standard.set(uid, forKey: "micUID") micUID = uid queue.async { self.applyPreferredInput() } } func refreshInputs() { inputs = (AVAudioSession.sharedInstance().availableInputs ?? []).map { MicInput(id: $0.uid, name: $0.portName, type: $0.portType) } } private func updateMicName() { let r = AVAudioSession.sharedInstance().currentRoute micName = r.inputs.first?.portName ?? "microfono" } private func startMeter() { meterTimer?.invalidate() meterTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in guard let self else { return } let ch = self.movieOutput.connection(with: .audio)?.audioChannels ?? [] if let avg = ch.map({ $0.averagePowerLevel }).max(), let pk = ch.map({ $0.peakHoldLevel }).max() { self.audioLevel = max(-60, min(0, avg)) self.audioPeak = max(-60, min(0, pk)) } if self.recording, let s = self.startDate { self.elapsed = Date().timeIntervalSince(s) } } } // MARK: registrazione func toggleRecord() { if recording { queue.async { self.movieOutput.stopRecording() } return } guard !saving, device != nil else { return } let lockWB = lockWBWhileRecording queue.async { self.applyConnections() if lockWB { self.setWBLocked(true) } let f = DateFormatter() f.dateFormat = "yyyy-MM-dd HHmmss" let url = FileManager.default.temporaryDirectory.appendingPathComponent("Reel \(f.string(from: Date())).mov") self.movieOutput.startRecording(to: url, recordingDelegate: self) } } /// Blocca il bilanciamento del bianco sui valori di adesso, o torna all'automatico. private func setWBLocked(_ on: Bool) { guard let dev = device else { return } let mode: AVCaptureDevice.WhiteBalanceMode = on ? .locked : .continuousAutoWhiteBalance guard dev.isWhiteBalanceModeSupported(mode) else { return } do { try dev.lockForConfiguration() dev.whiteBalanceMode = mode dev.unlockForConfiguration() DispatchQueue.main.async { self.wbLocked = on } } catch {} } private func save(_ url: URL) { DispatchQueue.main.async { self.saving = true } PHPhotoLibrary.requestAuthorization(for: .addOnly) { st in guard st == .authorized || st == .limited else { DispatchQueue.main.async { self.message = "Serve il permesso per salvare nel Rullino"; self.saving = false } return } PHPhotoLibrary.shared().performChanges({ let r = PHAssetCreationRequest.forAsset() let o = PHAssetResourceCreationOptions() o.originalFilename = url.lastPathComponent o.shouldMoveFile = true r.addResource(with: .video, fileURL: url, options: o) }) { ok, _ in Task { @MainActor in self.saving = false self.message = ok ? "Salvato nel Rullino · \(self.use4K ? "4K" : "HD") · \(Self.mmss(self.elapsed))" : "Salvataggio non riuscito" WatchLink.shared.sendState() } } } } static func mmss(_ t: TimeInterval) -> String { let s = Int(t) return String(format: "%d:%02d", s / 60, s % 60) } private func thumbnail(_ url: URL) { let gen = AVAssetImageGenerator(asset: AVURLAsset(url: url)) gen.appliesPreferredTrackTransform = true gen.maximumSize = CGSize(width: 200, height: 356) if let cg = try? gen.copyCGImage(at: CMTime(seconds: 0.5, preferredTimescale: 600), actualTime: nil) { let img = UIImage(cgImage: cg) DispatchQueue.main.async { self.lastThumb = img } } } } extension Camera: AVCaptureFileOutputRecordingDelegate { func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { DispatchQueue.main.async { self.startDate = Date() self.elapsed = 0 self.recording = true UIImpactFeedbackGenerator(style: .medium).impactOccurred() WatchLink.shared.sendState() } } func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo url: URL, from connections: [AVCaptureConnection], error: Error?) { DispatchQueue.main.async { self.recording = false UIImpactFeedbackGenerator(style: .light).impactOccurred() if self.wbLocked { self.queue.async { self.setWBLocked(false) } } WatchLink.shared.sendState() } var ok = error == nil if let e = error as NSError?, let fine = e.userInfo[AVErrorRecordingSuccessfullyFinishedKey] as? Bool { ok = fine } guard ok else { DispatchQueue.main.async { self.message = "Registrazione non riuscita" } return } thumbnail(url) save(url) } } extension Camera: AVCaptureVideoDataOutputSampleBufferDelegate { func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { WatchLink.shared.offer(sampleBuffer) } }