-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudioViewController.swift
More file actions
3571 lines (3282 loc) · 161 KB
/
StudioViewController.swift
File metadata and controls
3571 lines (3282 loc) · 161 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Example demo screen — exercises the full Prism API surface in a single VC, so the
// file and class are larger than a production screen would be. Length-based lint rules
// don't add signal here.
// swiftlint:disable file_length type_body_length
@preconcurrency import AVFoundation
import ImageIO
import Photos
import PrismCore
import PrismUI
import SnapKit
import UIKit
// MARK: - StudioViewController
/// A DSLR-style camera app: live preview, focal-length lens picker, telemetry strip,
/// photo / live / portrait / pano / video / slow-mo / night modes, tap-to-focus,
/// pinch-to-zoom, drag-to-bias-exposure, hardware capture controls, full settings drawer.
///
/// Exercises the full PrismCore + PrismUI surface in one screen.
@MainActor
final class StudioViewController: UIViewController {
// MARK: - Camera
private let camera = PRMCamera()
private let pipeline = PRMFilterPipeline()
/// `PRMRenderContext()` only fails when the device has no Metal support, which is
/// terminal for a Metal-backed preview — no graceful fallback is possible.
private let renderContext: PRMRenderContext = {
guard let context = PRMRenderContext() else {
fatalError("Metal is unavailable on this device — Prism preview requires Metal.")
}
return context
}()
private lazy var previewView = PRMPreviewView(context: renderContext)
private var photoCapture: PRMPhotoCapture?
private var videoRecorder: PRMVideoRecorder?
private var nightCapture: PRMNightModeCapture?
// MARK: - UI
private let topBar = UIStackView()
private let telemetryLabel = PaddedLabel()
private let lensStrip = UIStackView()
private let modePicker = ModePicker()
private let shutter = PRMShutterButton()
private let switchCameraButton = UIButton(type: .system)
private let gridOverlay = PRMGridView()
private let aspectMask = PRMAspectRatioMaskView()
private let levelIndicator = PRMLevelIndicatorView()
private let focusIndicator = PRMFocusIndicatorView()
private let recordingTimerLabel = PaddedLabel()
private let countdownLabel = UILabel()
private let flashButton = ToolbarChip(symbol: "bolt.badge.a.fill")
private let gridButton = ToolbarChip(symbol: "grid")
private let aspectButton = ToolbarChip(symbol: "aspectratio")
private let timerButton = ToolbarChip(symbol: "timer")
private let settingsButton = ToolbarChip(symbol: "slider.horizontal.3")
private let liveIndicator = LiveCaptureIndicator()
private let nightIndicator = NightCaptureIndicator()
private let drawer = PRMSettingsDrawerView(title: "Camera Settings")
// MARK: - State
private enum Mode: Equatable {
case photo, live, portrait, video, slowMo, night
var label: String {
switch self {
case .photo: "PHOTO"
case .live: "LIVE"
case .portrait: "PORTRAIT"
case .video: "VIDEO"
case .slowMo: "SLO-MO"
case .night: "NIGHT"
}
}
}
private var mode: Mode = .photo {
didSet { applyModeChange(from: oldValue) }
}
private var aspectIndex = 0
private let aspectCycle: [PRMAspectRatioMaskView.AspectRatio] = [.unconstrained, .ratio4x3, .ratio16x9, .ratio1x1]
private var gridIndex = 0
private let gridCycle: [PRMGridView.GridType?] = [nil, .ruleOfThirds]
private enum FlashSetting {
case auto, on, off
var next: Self {
switch self {
case .auto: .on
case .on: .off
case .off: .auto
}
}
var symbol: String {
switch self {
case .auto: "bolt.badge.a.fill"
case .on: "bolt.fill"
case .off: "bolt.slash.fill"
}
}
var avMode: AVCaptureDevice.FlashMode {
switch self {
case .auto: .auto
case .on: .on
case .off: .off
}
}
}
private enum TimerSetting: Int, CaseIterable {
case off = 0, three = 3, ten = 10
var next: Self {
switch self {
case .off: .three
case .three: .ten
case .ten: .off
}
}
var symbol: String {
switch self {
case .off: "timer"
case .three: "3.circle.fill"
case .ten: "10.circle.fill"
}
}
}
/// Night mode capture duration. `.auto` lets the controller pick from current ISO and
/// shutter telemetry (Apple Camera's behavior); the explicit values let the user
/// override the auto pick the same way Apple's slide-shutter does.
private enum NightDuration: Equatable {
case auto
case oneSecond
case threeSeconds
case fiveSeconds
var label: String {
switch self {
case .auto: "AUTO"
case .oneSecond: "1s"
case .threeSeconds: "3s"
case .fiveSeconds: "5s"
}
}
/// (frameCount, perFrameDuration, iso) for `PRMNightModeCapture.capture`.
var capture: (frames: Int, perFrame: Double, iso: Float) {
switch self {
case .auto, .oneSecond: (frames: 4, perFrame: 0.25, iso: 800)
case .threeSeconds: (frames: 6, perFrame: 0.5, iso: 1600)
case .fiveSeconds: (frames: 10, perFrame: 0.5, iso: 1600)
}
}
var next: Self {
switch self {
case .auto: .oneSecond
case .oneSecond: .threeSeconds
case .threeSeconds: .fiveSeconds
case .fiveSeconds: .auto
}
}
}
/// Cinematic-style frame-rate variants under VIDEO. 24 fps gives a film cadence, 30
/// matches the iOS Camera default. 60 fps was intentionally dropped from the picker:
/// the camera's `.photo` session preset uses a 4:3 sensor format whose frame-rate
/// range tops out at 30 fps, so 60 fps forces a switch to a 16:9 video format with
/// narrower FoV — the preview visibly resizes, and the Metal pipeline adds latency
/// during the format renegotiation. Higher temporal resolutions are still available
/// via the SLO-MO variant (120/240 fps, expected to look different to users).
private enum VideoFPS: Equatable {
case fps24, fps30
var value: Float64 {
switch self {
case .fps24: 24
case .fps30: 30
}
}
var label: String {
switch self {
case .fps24: "24"
case .fps30: "30"
}
}
}
private var flashSetting: FlashSetting = .auto
private var timerSetting: TimerSetting = .off
private var burstEnabled = false
private var nightDuration: NightDuration = .auto
private var videoFPS: VideoFPS = .fps30
private var initialPinchZoom: CGFloat = 1.0
/// Latest zoom target the pinch handler wants. A single drain task picks up whichever
/// value is most recent, skipping intermediate values the finger has already pinched
/// past. Without coalescing, UIPinchGestureRecognizer fires `.changed` at ~60Hz and
/// each event enqueued its own actor hop — the actor processed them in order, so a
/// fast pinch produced visible stepping as stale targets fired before the newest
/// one. With coalescing, queue depth stays at 1.
private var pendingZoomTarget: CGFloat?
private var zoomDrainTask: Task<Void, Never>?
private var recordingStartedAt: Date?
private var recordingTimer: Timer?
private var lastDevice: PRMCameraDevice?
// MARK: - Drawer row handles
//
// Kept so sliders / segmented controls can be cross-synced from `updateTelemetry` and
// from each other — e.g. dragging ISO promotes the exposure-mode segmented to "Custom",
// picking the Day/Indoor/Night preset updates the ISO + shutter sliders, the state-
// stream tick keeps every widget aligned with AVFoundation's actual mode after
// auto-mode drift.
private var exposureModeSegmented: UISegmentedControl?
private var evRow: PRMSettingsRow?
private var evSlider: UISlider?
private var isoRow: PRMSettingsRow?
private var isoSlider: UISlider?
private var shutterRow: PRMSettingsRow?
private var shutterSlider: UISlider?
/// User-facing stops, in seconds. Filled in by `makeShutterRow` to match the active
/// format's supported range so the slider can't land on a value the device will
/// silently clamp out from under us.
private var shutterStops: [Double] = []
private var customExposureSegmented: UISegmentedControl?
private var wbModeSegmented: UISegmentedControl?
private var wbRow: PRMSettingsRow?
private var wbKelvinSlider: UISlider?
private var focusModeSegmented: UISegmentedControl?
private var focusRow: PRMSettingsRow?
private var lensSlider: UISlider?
/// Max Dimensions row + its toggle. Tracked so `syncMaxDimensionsRow(from:)` can
/// flip the disabled state when the active device's largest supported photo
/// dimensions don't exceed 12MP (virtual devices like `.builtInTripleCamera`).
private var maxDimensionsRow: PRMSettingsRow?
private var maxDimensionsToggle: UISwitch?
/// Set while a programmatic slider / segmented update is in flight so the
/// `.valueChanged` action doesn't re-fire the underlying camera setter. Prevents a
/// feedback loop when the state-stream sync writes back into the same control that
/// originated the change.
private var isApplyingExternalUpdate = false
/// Drives `PRMCamera.rampZoom` / `.cancelZoomRamp` — smooth 1.0×→2.0× ramp at rate 1.0.
fileprivate var isZoomRamping = false
/// Set when the user taps a lens chip — pins the highlight to that pill until
/// AVFoundation's `activePrimaryConstituent` catches up. `videoZoomFactor` updates
/// instantly but the constituent-device resolution lags by a few frames, so without
/// this pin the state-stream tick can briefly revert the highlight to the *previous*
/// lens (the stale active constituent) before settling on the correct one.
private var pinnedActivePill: LensPill?
/// Wall-clock deadline for the pin. Once `Date() >= this`, the pin is dropped and
/// `refreshActiveLens` resumes following live AVFoundation state.
private var pinnedActivePillUntil: Date?
private var rotationStreamTask: Task<Void, Never>?
// Error + interruption observers (toasts surfaced via showToast).
private var errorStreamTask: Task<Void, Never>?
private var interruptionStreamTask: Task<Void, Never>?
private var stateStreamTask: Task<Void, Never>?
/// Polls `camera.refreshState()` at 2Hz so the telemetry label reflects auto-driven
/// changes (ISO drift under auto-exposure, white-balance temperature drift, lens
/// position) that AVFoundation mutates continuously without going through a setter.
/// Without this tick the label would only update when the user pinches, taps a lens,
/// or otherwise calls a `PRMCamera` mutator that triggers `refreshState` itself.
private var telemetryTickTask: Task<Void, Never>?
/// Hardware shutter (Camera Control button on iPhone 16+, volume buttons elsewhere).
private let captureEventHelper = PRMCaptureEventHelper()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Example app: turn on Prism's verbose SDK traces so the Console.app log shows
// every configure / start / switchCamera / setter / format-swap / capture entry.
// SDK callers ship with this off — flipping it on here keeps the example useful
// as a "what's actually happening under the hood?" debugging surface without
// making release builds chatty.
PRMLogger.isVerboseTracingEnabled = true
view.backgroundColor = .black
overrideUserInterfaceStyle = .dark
navigationController?.setNavigationBarHidden(true, animated: false)
modalPresentationCapturesStatusBarAppearance = true
setupLayout()
wireGestures()
previewView.addInteraction(captureEventHelper.makeInteraction())
captureEventHelper.onPrimaryAction = { [weak self] in self?.handleShutterTap() }
captureEventHelper.onSecondaryAction = { [weak self] in self?.flipCameraSync() }
PRMLogger.session.notice("Studio viewDidLoad — verbose tracing enabled")
Task { await bootCamera() }
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
rotationStreamTask?.cancel()
errorStreamTask?.cancel()
interruptionStreamTask?.cancel()
stateStreamTask?.cancel()
telemetryTickTask?.cancel()
rotationStreamTask = nil
errorStreamTask = nil
interruptionStreamTask = nil
stateStreamTask = nil
telemetryTickTask = nil
Task { await camera.stop() }
navigationController?.setNavigationBarHidden(false, animated: animated)
}
private func flipCameraSync() {
Task { await flipCamera() }
}
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
// MARK: - Layout
private func setupLayout() {
// Preview is bounded *above* the mode picker so the bottom UI strip (lens row,
// mode picker, shutter, telemetry) sits on a black bar instead of overlapping the
// preview frame. The bottom constraint is wired after `modePicker` is added below
// (in this same method) via SnapKit closures.
view.addSubview(previewView)
// Preview frames arrive pre-rotated via the data-output connection's
// `videoRotationAngle`, set from `PRMRotationCoordinator` in `bootCamera()`.
// MTKView itself renders identity.
// Letterbox the full sensor frame instead of cropping to the view aspect.
previewView.contentFit = .fit
// Aspect mask + grid overlay match the preview frame, not the whole view, so
// crop guides and rule-of-thirds align with the actual visible image.
view.addSubview(aspectMask)
view.addSubview(gridOverlay)
gridOverlay.isGridVisible = false
levelIndicator.lineColor = UIColor.white.withAlphaComponent(0.7)
levelIndicator.leveledColor = .systemYellow
levelIndicator.lineWidth = 1.5
view.addSubview(levelIndicator)
levelIndicator.lineLengthRatio = 0.6
levelIndicator.snp.makeConstraints {
// Centered within the preview frame, not the whole view, so the line stays
// visually anchored to the image as the preview shrinks above the mode picker.
$0.center.equalTo(previewView)
$0.width.equalTo(220)
$0.height.equalTo(220)
}
levelIndicator.isActive = true
topBar.axis = .horizontal
topBar.spacing = 12
topBar.alignment = .center
view.addSubview(topBar)
topBar.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).offset(12)
$0.leading.equalToSuperview().offset(16)
$0.trailing.equalToSuperview().offset(-16)
$0.height.equalTo(40)
}
flashButton.onTap = { [weak self] in self?.cycleFlash() }
gridButton.onTap = { [weak self] in self?.cycleGrid() }
aspectButton.onTap = { [weak self] in self?.cycleAspect() }
timerButton.onTap = { [weak self] in self?.cycleTimer() }
settingsButton.onTap = { [weak self] in self?.toggleDrawer() }
topBar.addArrangedSubview(flashButton)
topBar.addArrangedSubview(gridButton)
topBar.addArrangedSubview(aspectButton)
topBar.addArrangedSubview(timerButton)
let topBarSpacer = UIView()
topBarSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
topBar.addArrangedSubview(topBarSpacer)
topBar.addArrangedSubview(settingsButton)
recordingTimerLabel.isHidden = true
recordingTimerLabel.textColor = .white
recordingTimerLabel.font = .monospacedSystemFont(ofSize: 13, weight: .semibold)
recordingTimerLabel.backgroundColor = UIColor.systemRed.withAlphaComponent(0.85)
view.addSubview(recordingTimerLabel)
// Anchored well below the top bar to clear the chip row visually.
// `recordingTimerLabel`, `liveIndicator`, and `nightIndicator` are mutually
// exclusive (video uses one, Live Photo a second, Night the third) and share the
// same centerX + centerY so they swap in place.
recordingTimerLabel.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.top.equalTo(topBar.snp.bottom).offset(48)
$0.height.equalTo(28)
}
view.addSubview(liveIndicator)
liveIndicator.snp.makeConstraints {
$0.centerX.equalTo(recordingTimerLabel)
$0.centerY.equalTo(recordingTimerLabel)
$0.height.equalTo(28)
}
view.addSubview(nightIndicator)
nightIndicator.snp.makeConstraints {
$0.centerX.equalTo(recordingTimerLabel)
$0.centerY.equalTo(recordingTimerLabel)
$0.height.equalTo(28)
}
countdownLabel.isHidden = true
countdownLabel.textColor = .systemYellow
countdownLabel.font = .systemFont(ofSize: 96, weight: .bold)
countdownLabel.textAlignment = .center
view.addSubview(countdownLabel)
countdownLabel.snp.makeConstraints { $0.center.equalToSuperview() }
telemetryLabel.font = .monospacedSystemFont(ofSize: 11, weight: .medium)
telemetryLabel.textColor = UIColor.white.withAlphaComponent(0.9)
telemetryLabel.backgroundColor = UIColor.black.withAlphaComponent(0.35)
telemetryLabel.textAlignment = .center
telemetryLabel.text = "Initializing…"
view.addSubview(telemetryLabel)
lensStrip.axis = .horizontal
lensStrip.spacing = 10
lensStrip.alignment = .center
lensStrip.distribution = .equalSpacing
view.addSubview(lensStrip)
view.addSubview(modePicker)
modePicker.onChange = { [weak self] primary, variant in
self?.applyModeChange(primary: primary, variant: variant)
}
modePicker.onDisabledVariantTap = { [weak self] message in
self?.showToast(message)
}
view.addSubview(shutter)
view.addSubview(switchCameraButton)
let flipSymbol = UIImage(
systemName: "arrow.triangle.2.circlepath.camera",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular)
)
switchCameraButton.setImage(flipSymbol, for: .normal)
switchCameraButton.tintColor = .white
switchCameraButton.imageView?.contentMode = .scaleAspectFit
switchCameraButton.addAction(UIAction { [weak self] _ in
Task { await self?.flipCamera() }
}, for: .touchUpInside)
shutter.onTap = { [weak self] in self?.handleShutterTap() }
shutter.onLongPressBegan = { [weak self] in self?.handleShutterLongPressBegan() }
shutter.onLongPressEnded = { [weak self] in self?.handleShutterLongPressEnded() }
shutter.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-16)
$0.size.equalTo(CGSize(width: 76, height: 76))
}
switchCameraButton.snp.makeConstraints {
$0.trailing.equalToSuperview().offset(-30)
$0.centerY.equalTo(shutter)
$0.size.equalTo(CGSize(width: 32, height: 32))
}
modePicker.snp.makeConstraints {
$0.leading.equalToSuperview().offset(16)
$0.trailing.equalToSuperview().offset(-16)
$0.bottom.equalTo(shutter.snp.top).offset(-14)
}
// Preview is centered vertically in the screen with a fixed 4:3 portrait aspect
// ratio (matches the iPhone sensor's native crop). A small upward `centerY.offset`
// lifts it above the geometric middle so the heavier bottom chrome (lens strip +
// mode picker + shutter) feels visually balanced. It floats independent of the
// top bar and mode picker — both can grow/shrink without dragging the preview
// off-center. The .lessThanOrEqualTo guards keep it inside the available space
// if the screen is short enough that the centered frame would overlap chrome.
// The lens strip (xx mm chips) and telemetry label paint on top of the preview
// (added to the view hierarchy after `previewView`), matching Apple's layout.
previewView.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview().offset(-40)
$0.leading.trailing.equalToSuperview()
$0.height.equalTo(previewView.snp.width).multipliedBy(4.0 / 3.0)
$0.top.greaterThanOrEqualTo(topBar.snp.bottom).offset(8)
$0.bottom.lessThanOrEqualTo(modePicker.snp.top).offset(-8)
}
aspectMask.snp.makeConstraints { $0.edges.equalTo(previewView) }
gridOverlay.snp.makeConstraints { $0.edges.equalTo(previewView) }
lensStrip.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.bottom.equalTo(modePicker.snp.top).offset(-12)
$0.height.equalTo(36)
}
telemetryLabel.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.bottom.equalTo(lensStrip.snp.top).offset(-12)
$0.height.equalTo(26)
}
view.addSubview(focusIndicator)
view.addSubview(drawer)
drawer.snp.makeConstraints { $0.edges.equalToSuperview() }
drawer.isUserInteractionEnabled = false // pass through when closed
}
private func wireGestures() {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
previewView.addGestureRecognizer(tap)
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
previewView.addGestureRecognizer(pinch)
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
previewView.addGestureRecognizer(pan)
}
// MARK: - Boot
private func bootCamera() async {
if PRMPermissions.cameraStatus() == .notDetermined {
_ = await PRMPermissions.requestCameraAccess()
}
if PRMPermissions.microphoneStatus() == .notDetermined {
_ = await PRMPermissions.requestMicrophoneAccess()
}
do {
var config = PRMCameraConfiguration()
// **`enableLivePhoto` MUST be true at configure time** if Live Photo is ever
// going to be tapped at runtime. Per Apple's docs
// (developer.apple.com/documentation/avfoundation/avcapturephotooutput/
// islivephotocapturesupported): "Live Photo capture requires a lengthy
// reconfiguration of the capture render pipeline, so if you intend to do any
// Live Photo captures at all, you should set livePhotoCaptureEnabled to YES
// *before calling -[AVCaptureSession startRunning]*." The pipeline's secondary
// movie-capture path is decided at build time; no runtime format swap can
// retroactively add it — `isLivePhotoCaptureSupported` stays false forever
// for sessions that started without it (verified empirically: iterating all
// 12 formats on Triple camera, every single one reports
// isLivePhotoCaptureSupported=false when the pipeline was built with
// enableLivePhoto=false).
//
// The per-frame runtime knob `setLivePhotoCaptureEnabled(_:)` is still needed
// for manual-exposure modes — Live Photo *enabled* (not supported) at the
// photo output silently reverts `device.exposureMode = .custom` and WB lock
// back to continuous-auto within a frame or two (the photo output requires
// the sensor in auto pipeline to bracket the Live Photo movie). So Studio's
// `applyModeChange()` flips `setLivePhotoCaptureEnabled(true)` in Live mode
// and `false` everywhere else. That toggle is cheap when the pipeline already
// has the support wired; what we cannot do is *add* support at runtime.
config.includesMovieFileOutput = false
config.enableLivePhoto = true
config.enableDepthDataDelivery = true
config.enablePortraitEffectsMatteDelivery = true
// Auto-deferred photo delivery conflicts with depth/matte on iPhone Pro
// models: AVFoundation routes the depth XPC stream through the deferred
// proxy and the proxy callback's `depthData` arrives with an internally
// null `depthDataMap`. Visible as the FigXPCUtilities -17281 / "buffer is
// nil" errors on iPhone 15 Pro Max in Portrait mode. Disable deferred
// delivery in this example so portrait actually produces depth — apps
// that don't need depth can opt back in via `PRMCameraConfiguration`.
config.enableAutoDeferredPhotoDelivery = false
// Responsive Capture and Zero Shutter Lag both fight manual
// exposure on iPhone 14 Pro+: ZSL maintains a ring buffer of
// pre-shutter frames that AVFoundation pre-stabilizes via Smart
// HDR / Deep Fusion (so the photo at shutter time draws from a
// fused, multi-exposure pre-capture), and Responsive Capture
// overlaps frame processing so the in-flight frame at shutter time
// may belong to a *prior* auto-exposure pipeline state even after
// the user committed manual. Per WWDC23 session 10105, ZSL is
// documented to auto-disable for manual exposure — but the auto-
// disable only kicks in once `device.exposureMode == .custom` has
// committed on the *device*, which has a ~3 s lag (dev-forum
// 751112). For a Studio-style app the user pays nothing for going
// without ZSL / Responsive (the manual-shutter cadence is the
// bottleneck, not pipeline latency) and gets reliably-honored
// manual exposure in return. AVCamManual disables both for the
// same reason.
config.enableResponsiveCapture = false
config.enableZeroShutterLag = false
// Don't pre-promote to the 48MP format at configure time — that format is
// mutually exclusive with Live Photo. Studio toggles Max Dimensions per user
// action via `camera.setHighResolutionPhotoFormat(_:)`, which flips formats
// on demand. Configure leaves us in the default `.photo` preset format,
// which supports Live Photo + burst + depth.
try await camera.configure(config)
} catch {
PRMLogger.session.error("Camera configure failed: \(String(describing: error), privacy: .public)")
showAlert(title: "Cannot start camera", message: error.localizedDescription)
return
}
// Portrait baseline. `PRMRotationCoordinator` only updates this on real devices —
// the simulator has no gyroscope (CoreMotion is unavailable), so
// `videoRotationAngleForHorizonLevelPreview` would stay at 0 (raw sensor
// landscape) and the preview would look 90° CCW rotated in portrait. Seeding 90°
// here pre-rotates every CVPixelBuffer to gravity-aligned portrait so MTKView
// can render identity; on real hardware the coordinator stream overrides this
// as the device tilts.
await applyConnectionRotation(90)
pipeline.isEnabled = true
await camera.session.setVideoDataOutputDelegate(pipeline)
pipeline.onFrame = { [weak self] frame in
self?.previewView.update(frame.pixelBuffer)
}
// Use the session-based inits so both wrappers transparently survive
// reconfigure-driven output replacements: `PRMPhotoCapture` re-resolves
// `session.photoOutput` at every capture entry point (covers Live-Photo
// recovery on virtual devices), and `PRMVideoRecorder` re-resolves
// `session.movieFileOutput` at every `start()` (covers slo-mo format
// swaps). Neither wrapper needs to be rebuilt after a `swapInput` /
// `setFrameRate` / `setLivePhotoCaptureEnabled` mutation.
let capture = PRMPhotoCapture(session: camera.session)
let context = renderContext
photoCapture = capture
nightCapture = PRMNightModeCapture(capture: capture, context: context)
videoRecorder = PRMVideoRecorder(session: camera.session)
// Seed the `maxPhotoDimensions` cache that `makePhotoSettings(...)`
// reads when the user opts into the Max Dimensions cap. Subsequent
// device swaps / photo-output re-attaches refresh it via
// `refreshOutputCeilings()` at their call sites.
await refreshOutputCeilings()
rebuildLensStrip()
populateModeStrip()
populateDrawer()
// PRMCamera state stream — drives the telemetry strip.
stateStreamTask = Task { [weak self] in
guard let self else { return }
for await state in camera.stateStream() {
guard !Task.isCancelled else { break }
updateTelemetry(from: state)
}
}
// PRMCamera error stream — surface AVFoundation runtime errors as a toast.
errorStreamTask = Task { [weak self] in
guard let self else { return }
for await error in camera.errorStream() {
guard !Task.isCancelled else { break }
reportError(error, context: "Runtime")
}
}
// PRMCamera interruption stream — phone calls, Control Center pip, etc.
interruptionStreamTask = Task { [weak self] in
guard let self else { return }
for await interrupted in camera.interruptionStream() {
guard !Task.isCancelled else { break }
showToast(interrupted ? "Session interrupted" : "Session resumed")
}
}
// 2Hz telemetry refresh tick. AVFoundation continuously updates `iso`,
// `exposureDuration`, `whiteBalanceGains`, etc. under auto modes — but
// `PRMCamera.refreshState` only fires when a setter is called. Without this
// tick the telemetry label freezes on whatever values were captured at the
// most recent user action (so on first open ISO is stuck at the cold-start
// value even as the device adjusts to the actual scene).
telemetryTickTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(500))
guard !Task.isCancelled, let self else { break }
await camera.refreshState()
}
}
await rebindRotationCoordinator()
await camera.start()
await applyDefaultFocalLength()
}
/// Holds the current rotation coordinator so it can be torn down + replaced on
/// camera switch. Reassigning to a new coordinator (in `rebindRotationCoordinator`)
/// drops the previous one — its KVO observations stop, its continuations finish, and
/// the old rotation stream task exits.
private var rotationCoordinator: PRMRotationCoordinator?
/// Tears down the previous coordinator + stream task and binds a fresh
/// `PRMRotationCoordinator` to the *current* `camera.session.videoDevice`. Each
/// emitted angle gets applied to the data-output connection's `videoRotationAngle`
/// — AVFoundation then pre-rotates every CVPixelBuffer so MTKView can render
/// identity. Same path `AVCaptureVideoPreviewLayer` takes internally. Call after
/// the device changes (initial boot, `flipCamera`).
///
/// On the simulator the coordinator emits 0 (no gyroscope), so the explicit
/// `applyConnectionRotation(90)` baseline at boot keeps the preview upright.
private func rebindRotationCoordinator() async {
rotationStreamTask?.cancel()
rotationStreamTask = nil
rotationCoordinator = nil
guard let device = await camera.session.videoDevice else { return }
let coordinator = PRMRotationCoordinator(device: device, previewLayer: nil)
rotationCoordinator = coordinator
rotationStreamTask = Task { [weak self] in
for await angle in coordinator.previewRotationAngles() {
guard !Task.isCancelled, let self else { break }
// Coordinator returns 0 on the simulator (no CoreMotion). Don't let it
// overwrite the 90° portrait baseline seeded at configure time.
guard angle != 0 else { continue }
await applyConnectionRotation(angle)
}
}
}
/// Sets `videoRotationAngle` on the video-data-output connection inside a
/// `beginConfiguration`/`commitConfiguration` block (the Apple-recommended pattern).
/// Hop through `PRMCameraActor` since `AVCaptureSession` mutations must serialize there.
private func applyConnectionRotation(_ angle: CGFloat) async {
let session = camera.session
await PRMCameraActor.shared.run {
guard let connection = await session.videoDataOutput?.connection(with: .video) else { return }
guard connection.isVideoRotationAngleSupported(angle) else { return }
session.session.beginConfiguration()
connection.videoRotationAngle = angle
session.session.commitConfiguration()
}
}
// MARK: - Lens strip
private func rebuildLensStrip() {
lensStrip.arrangedSubviews.forEach { $0.removeFromSuperview() }
let lenses = camera.device?.lenses ?? []
for lens in lenses {
let snappedFocal = lens.snapping().focalLength35mm
let button = LensPill(
title: "\(Int(snappedFocal))mm",
zoomFactor: lens.zoomFactor,
displayZoomFactor: lens.displayZoomFactor,
deviceType: lens.deviceType,
kind: lens.kind
)
button.onTap = { [weak self, weak button] in
guard let self, let button else { return }
selectLens(button: button, zoomFactor: lens.zoomFactor)
}
lensStrip.addArrangedSubview(button)
}
refreshActiveLens(from: camera.state)
}
/// Pin the highlight to `button` and dispatch the underlying `setZoom`. Used by
/// both the tap handler and the `applyDefaultFocalLength` startup path so the
/// default 24mm chip lights up on first boot too.
///
/// The pin protects the highlight from being clobbered by the state-stream tick that
/// fires immediately after `setZoom`: `videoZoomFactor` updates synchronously, but
/// AVFoundation's `activePrimaryConstituent` lags by a few frames. Without the pin
/// the tick reads a stale constituent and the highlight reverts to the previous lens.
///
/// When the new pill represents a different physical lens than the current one, also
/// shows `lensSwitchOverlay` briefly to mask the visible "previous lens does digital
/// zoom" artifact during the constituent switch. Same-lens taps skip the overlay.
private func selectLens(button: LensPill, zoomFactor: CGFloat) {
let previouslyActive = (lensStrip.arrangedSubviews.compactMap { $0 as? LensPill })
.first(where: \.isActive)
// Skip the overlay when either pill is a sensor crop — the physical lens isn't
// changing, so the "previous lens does digital zoom" artifact the overlay masks
// doesn't exist. Crossing a deviceType boundary only matters between physical
// lenses (e.g. wide → telephoto).
let crossesLens = previouslyActive?.deviceType != button.deviceType
&& previouslyActive?.kind == .physical
&& button.kind == .physical
pinnedActivePill = button
pinnedActivePillUntil = Date().addingTimeInterval(1.0)
let pills = lensStrip.arrangedSubviews.compactMap { $0 as? LensPill }
for pill in pills {
pill.setActive(pill === button)
}
if crossesLens {
showLensSwitchOverlay()
}
Task { await camera.setZoom(zoomFactor) }
}
/// Brief blur overlay over the preview that masks the ~200-300ms constituent-switch
/// transition. AVFoundation updates `videoZoomFactor` synchronously, but in-flight
/// frames from the *previous* constituent show as digital zoom on that lens before
/// the actual lens switch lands. Covering the preview during the transition is what
/// makes the change look instant — matches the cross-fade Apple Camera uses.
private func showLensSwitchOverlay() {
let overlay = UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterialDark))
overlay.alpha = 0.95
previewView.addSubview(overlay)
overlay.snp.makeConstraints { $0.edges.equalToSuperview() }
UIView.animate(
withDuration: 0.25,
delay: 0.2,
options: [.curveEaseOut],
animations: { overlay.alpha = 0 },
completion: { _ in overlay.removeFromSuperview() }
)
}
/// Highlights the lens pill that is *physically* feeding the preview right now.
///
/// Preferred path (iOS 16+ on virtual devices): match by
/// `state.activePrimaryDeviceType` — AVFoundation reports which constituent lens it
/// has selected, including runtime fallbacks (low light, close subject, etc.) where
/// it sticks with wide even though the user picked telephoto.
///
/// Fallback (single-lens devices, simulator, or pre-resolve): use the switchover
/// bucket — `PRMLens` entries are sorted by raw `zoomFactor`, and AVFoundation
/// hands frames from the highest-zoom lens whose `zoomFactor ≤ currentZoom`.
private func refreshActiveLens(from state: PRMCameraState) {
let pills = lensStrip.arrangedSubviews.compactMap { $0 as? LensPill }
guard !pills.isEmpty else { return }
// Honor the most recent tap for a short window while AVFoundation's
// `activePrimaryConstituent` catches up to the new `videoZoomFactor`. Without
// this, the state-stream tick that fires immediately after `setZoom` would see
// the *stale* constituent device and revert the highlight to the previous lens
// until a later tick. The pin times itself out so pinch / hardware zoom paths
// still flow through to the live AVFoundation match.
if let pinnedPill = pinnedActivePill,
let until = pinnedActivePillUntil,
Date() < until {
for pill in pills {
pill.setActive(pill === pinnedPill)
}
return
}
// Pin expired — drop the reference so we stop comparing against it.
pinnedActivePill = nil
pinnedActivePillUntil = nil
// Resolve via the zoom-factor bucket first — this is the only way virtual
// sensor-crop chips (deviceType == nil, zoomFactor above the wide they crop
// from) can light up at 2× and beyond, since AVFoundation's
// `activePrimaryDeviceType` reports the underlying physical lens (wide) for
// both 1× and 2× on those devices. The sorted-bucket approach finds the
// highest-`zoomFactor` chip whose factor is ≤ current zoom.
//
// Then, on Pro devices with multiple physical lenses and a low-light fallback
// (user picks 5× telephoto, AVFoundation refuses and silently stays on wide
// with digital zoom), prefer the `activePrimaryDeviceType` match so the wide
// pill lights up instead of the telephoto — gives the user a visible signal
// that the requested switch didn't happen. The override only applies between
// *physical* chips; crops have no constituent device so they always win the
// zoom-bucket bid for their factor band.
let sorted = pills.sorted { $0.zoomFactor < $1.zoomFactor }
var active = sorted.last { $0.zoomFactor <= state.zoomFactor + 0.001 } ?? sorted.first
if let bucket = active, bucket.kind == .physical, let activeType = state.activePrimaryDeviceType,
activeType != bucket.deviceType,
let constituentMatch = pills.first(where: { $0.kind == .physical && $0.deviceType == activeType }) {
active = constituentMatch
}
for pill in pills {
pill.setActive(pill === active)
}
}
/// 35mm-equivalent focal length for an arbitrary raw zoom factor, interpolated
/// between the snapped focal lengths of the device's lens stops. Used for the
/// telemetry readout so the displayed value tracks pinch zoom smoothly while still
/// snapping to canonical numbers (13 / 24 / 120 mm etc.) at the lens stops.
private func focalLength35mm(forZoom zoom: CGFloat) -> Double {
guard let lenses = camera.device?.lenses else { return 0 }
let sorted = lenses.sorted { $0.zoomFactor < $1.zoomFactor }
guard let first = sorted.first, let last = sorted.last else { return 0 }
if zoom <= first.zoomFactor { return first.snapping().focalLength35mm }
if zoom >= last.zoomFactor {
// Beyond the last physical lens stop, scale the last lens's focal length
// linearly with extra digital zoom — matches what the sensor effectively
// sees (focal length × zoom factor).
let lastSnapped = last.snapping().focalLength35mm
return lastSnapped * Double(zoom / last.zoomFactor)
}
for index in 0 ..< (sorted.count - 1) {
let low = sorted[index]
let high = sorted[index + 1]
if zoom >= low.zoomFactor, zoom <= high.zoomFactor {
let t = Double((zoom - low.zoomFactor) / (high.zoomFactor - low.zoomFactor))
let lowFocal = low.snapping().focalLength35mm
let highFocal = high.snapping().focalLength35mm
return lowFocal + t * (highFocal - lowFocal)
}
}
return first.snapping().focalLength35mm
}
/// Seeds zoom to the lens whose snapped 35mm-equivalent focal length is closest to 24mm.
/// iPhone wide lenses usually report 24-26mm, so this picks the main camera on every
/// device that has one and falls back to the closest lens on devices that don't.
/// Routes through `selectLens` so the matching chip lights up immediately on first
/// boot (without it, the highlight stays on whichever lens AVFoundation cold-started
/// at — usually ultrawide / 13mm).
private func applyDefaultFocalLength() async {
let target: Double = 24
guard let lenses = camera.device?.lenses, !lenses.isEmpty else { return }
let pick = lenses.min { lhs, rhs in
abs(lhs.snapping().focalLength35mm - target) < abs(rhs.snapping().focalLength35mm - target)
}
guard let pick else { return }
let pills = lensStrip.arrangedSubviews.compactMap { $0 as? LensPill }
guard let pill = pills.first(where: { abs($0.zoomFactor - pick.zoomFactor) < 0.001 }) else {
await camera.setZoom(pick.zoomFactor)
return
}
selectLens(button: pill, zoomFactor: pick.zoomFactor)
}
// MARK: - Mode picker
private func populateModeStrip() {
// Gate against the broader device discovery, not just the active one. On Pro
// iPhones the virtual `.builtInTripleCamera`'s `formats` caps at 60 fps, but the
// separately-discoverable `.builtInWideAngleCamera` supports 120/240. Slo-mo
// entry hops to the wide camera (see `applyModeChange`); exit restores the
// pre-slo-mo device type.
let supportsSlowMo = PRMCameraDevice.anyDeviceSupportsSlowMotion(at: .back)
modePicker.supportsSlowMotion = supportsSlowMo
if !supportsSlowMo {
logInfo("Slo-mo variant hidden: no back-facing device reports a ≥120 fps format")
}
modePicker.select(primary: .photo, variant: .standard)
applyModeChange(primary: .photo, variant: .standard)
}
/// Translates a picker (primary, variant) selection into the `Mode` enum the rest of the
/// controller already understands. Burst folds into `.photo` via `burstEnabled`; the
/// Night variants fold into `.night` via `nightDuration`.
private func applyModeChange(primary: ModePicker.Primary, variant: ModePicker.Variant) {
PRMLogger.session.notice(
"Studio applyModeChange: primary=\(String(describing: primary), privacy: .public), variant=\(String(describing: variant), privacy: .public)"
)
// Re-apply variant-disable state — `rebuildVariants` swapped the strip contents
// when the primary changed, dropping any per-variant disable we set previously.
syncModePickerAvailability()
burstEnabled = (primary == .photo && variant == .burst)
if primary == .night {
switch variant {
case .nightAuto: nightDuration = .auto
case .night1s: nightDuration = .oneSecond
case .night3s: nightDuration = .threeSeconds
case .night5s: nightDuration = .fiveSeconds
default: nightDuration = .auto
}
}
switch primary {
case .photo:
switch variant {
case .live: mode = .live
case .portrait: mode = .portrait
// Video / Night variants are not exposed as Photo variants by
// `ModePicker.variants(for:)`, but the enum is shared so the switch needs
// to be exhaustive.
case .standard, .burst, .slowMo, .video24, .video30,
.nightAuto, .night1s, .night3s, .night5s:
mode = .photo
}
case .video:
switch variant {
case .video24: videoFPS = .fps24
case .video30: videoFPS = .fps30
default: break
}
let newMode: Mode = variant == .slowMo ? .slowMo : .video
// If we're already in `.video` and just changing fps, the `mode` didSet
// won't fire — apply the new fps directly so the picker stays in sync.
if mode == newMode, newMode == .video {
Task { await camera.setFrameRate(videoFPS.value) }
} else {
mode = newMode
}
case .night:
mode = .night
}
}
private func applyModeChange(from oldMode: Mode) {
PRMLogger.session.notice(
"Studio mode change: \(oldMode.label, privacy: .public) → \(self.mode.label, privacy: .public)"
)
Task {